xref: /openbmc/linux/mm/swapfile.c (revision d8ed45c5dcd455fc5848d47f86883a1b872ac0d0)
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>
211da177e4SLinus Torvalds #include <linux/blkdev.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>
421da177e4SLinus Torvalds 
431da177e4SLinus Torvalds #include <asm/tlbflush.h>
441da177e4SLinus Torvalds #include <linux/swapops.h>
455d1ea48bSJohannes Weiner #include <linux/swap_cgroup.h>
461da177e4SLinus Torvalds 
47570a335bSHugh Dickins static bool swap_count_continued(struct swap_info_struct *, pgoff_t,
48570a335bSHugh Dickins 				 unsigned char);
49570a335bSHugh Dickins static void free_swap_count_continuations(struct swap_info_struct *);
50d4906e1aSLee Schermerhorn static sector_t map_swap_entry(swp_entry_t, struct block_device**);
51570a335bSHugh Dickins 
5238b5faf4SDan Magenheimer DEFINE_SPINLOCK(swap_lock);
537c363b8cSAdrian Bunk static unsigned int nr_swapfiles;
54ec8acf20SShaohua Li atomic_long_t nr_swap_pages;
55fb0fec50SChris Wilson /*
56fb0fec50SChris Wilson  * Some modules use swappable objects and may try to swap them out under
57fb0fec50SChris Wilson  * memory pressure (via the shrinker). Before doing so, they may wish to
58fb0fec50SChris Wilson  * check to see if any swap space is available.
59fb0fec50SChris Wilson  */
60fb0fec50SChris Wilson EXPORT_SYMBOL_GPL(nr_swap_pages);
61ec8acf20SShaohua Li /* protected with swap_lock. reading in vm_swap_full() doesn't need lock */
621da177e4SLinus Torvalds long total_swap_pages;
63a2468cc9SAaron Lu static int least_priority = -1;
641da177e4SLinus Torvalds 
651da177e4SLinus Torvalds static const char Bad_file[] = "Bad swap file entry ";
661da177e4SLinus Torvalds static const char Unused_file[] = "Unused swap file entry ";
671da177e4SLinus Torvalds static const char Bad_offset[] = "Bad swap offset entry ";
681da177e4SLinus Torvalds static const char Unused_offset[] = "Unused swap offset entry ";
691da177e4SLinus Torvalds 
70adfab836SDan Streetman /*
71adfab836SDan Streetman  * all active swap_info_structs
72adfab836SDan Streetman  * protected with swap_lock, and ordered by priority.
73adfab836SDan Streetman  */
7418ab4d4cSDan Streetman PLIST_HEAD(swap_active_head);
7518ab4d4cSDan Streetman 
7618ab4d4cSDan Streetman /*
7718ab4d4cSDan Streetman  * all available (active, not full) swap_info_structs
7818ab4d4cSDan Streetman  * protected with swap_avail_lock, ordered by priority.
7918ab4d4cSDan Streetman  * This is used by get_swap_page() instead of swap_active_head
8018ab4d4cSDan Streetman  * because swap_active_head includes all swap_info_structs,
8118ab4d4cSDan Streetman  * but get_swap_page() doesn't need to look at full ones.
8218ab4d4cSDan Streetman  * This uses its own lock instead of swap_lock because when a
8318ab4d4cSDan Streetman  * swap_info_struct changes between not-full/full, it needs to
8418ab4d4cSDan Streetman  * add/remove itself to/from this list, but the swap_info_struct->lock
8518ab4d4cSDan Streetman  * is held and the locking order requires swap_lock to be taken
8618ab4d4cSDan Streetman  * before any swap_info_struct->lock.
8718ab4d4cSDan Streetman  */
88bfc6b1caSColin Ian King static struct plist_head *swap_avail_heads;
8918ab4d4cSDan Streetman static DEFINE_SPINLOCK(swap_avail_lock);
901da177e4SLinus Torvalds 
9138b5faf4SDan Magenheimer struct swap_info_struct *swap_info[MAX_SWAPFILES];
921da177e4SLinus Torvalds 
93fc0abb14SIngo Molnar static DEFINE_MUTEX(swapon_mutex);
941da177e4SLinus Torvalds 
9566d7dd51SKay Sievers static DECLARE_WAIT_QUEUE_HEAD(proc_poll_wait);
9666d7dd51SKay Sievers /* Activity counter to indicate that a swapon or swapoff has occurred */
9766d7dd51SKay Sievers static atomic_t proc_poll_event = ATOMIC_INIT(0);
9866d7dd51SKay Sievers 
9981a0298bSHuang Ying atomic_t nr_rotate_swap = ATOMIC_INIT(0);
10081a0298bSHuang Ying 
101c10d38ccSDaniel Jordan static struct swap_info_struct *swap_type_to_swap_info(int type)
102c10d38ccSDaniel Jordan {
103c10d38ccSDaniel Jordan 	if (type >= READ_ONCE(nr_swapfiles))
104c10d38ccSDaniel Jordan 		return NULL;
105c10d38ccSDaniel Jordan 
106c10d38ccSDaniel Jordan 	smp_rmb();	/* Pairs with smp_wmb in alloc_swap_info. */
107c10d38ccSDaniel Jordan 	return READ_ONCE(swap_info[type]);
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 
2237992fde7SHugh Dickins /*
2247992fde7SHugh Dickins  * swap allocation tell device that a cluster of swap can now be discarded,
2257992fde7SHugh Dickins  * to allow the swap device to optimize its wear-levelling.
2267992fde7SHugh Dickins  */
2277992fde7SHugh Dickins static void discard_swap_cluster(struct swap_info_struct *si,
2287992fde7SHugh Dickins 				 pgoff_t start_page, pgoff_t nr_pages)
2297992fde7SHugh Dickins {
2304efaceb1SAaron Lu 	struct swap_extent *se = offset_to_swap_extent(si, start_page);
2317992fde7SHugh Dickins 
2327992fde7SHugh Dickins 	while (nr_pages) {
2337992fde7SHugh Dickins 		pgoff_t offset = start_page - se->start_page;
2347992fde7SHugh Dickins 		sector_t start_block = se->start_block + offset;
235858a2990SHugh Dickins 		sector_t nr_blocks = se->nr_pages - offset;
2367992fde7SHugh Dickins 
2377992fde7SHugh Dickins 		if (nr_blocks > nr_pages)
2387992fde7SHugh Dickins 			nr_blocks = nr_pages;
2397992fde7SHugh Dickins 		start_page += nr_blocks;
2407992fde7SHugh Dickins 		nr_pages -= nr_blocks;
2417992fde7SHugh Dickins 
2427992fde7SHugh Dickins 		start_block <<= PAGE_SHIFT - 9;
2437992fde7SHugh Dickins 		nr_blocks <<= PAGE_SHIFT - 9;
2447992fde7SHugh Dickins 		if (blkdev_issue_discard(si->bdev, start_block,
245dd3932edSChristoph Hellwig 					nr_blocks, GFP_NOIO, 0))
2467992fde7SHugh Dickins 			break;
2477992fde7SHugh Dickins 
2484efaceb1SAaron Lu 		se = next_se(se);
2497992fde7SHugh Dickins 	}
2507992fde7SHugh Dickins }
2517992fde7SHugh Dickins 
25238d8b4e6SHuang Ying #ifdef CONFIG_THP_SWAP
25338d8b4e6SHuang Ying #define SWAPFILE_CLUSTER	HPAGE_PMD_NR
254a448f2d0SHuang Ying 
255a448f2d0SHuang Ying #define swap_entry_size(size)	(size)
25638d8b4e6SHuang Ying #else
257048c27fdSHugh Dickins #define SWAPFILE_CLUSTER	256
258a448f2d0SHuang Ying 
259a448f2d0SHuang Ying /*
260a448f2d0SHuang Ying  * Define swap_entry_size() as constant to let compiler to optimize
261a448f2d0SHuang Ying  * out some code if !CONFIG_THP_SWAP
262a448f2d0SHuang Ying  */
263a448f2d0SHuang Ying #define swap_entry_size(size)	1
26438d8b4e6SHuang Ying #endif
265048c27fdSHugh Dickins #define LATENCY_LIMIT		256
266048c27fdSHugh Dickins 
2672a8f9449SShaohua Li static inline void cluster_set_flag(struct swap_cluster_info *info,
2682a8f9449SShaohua Li 	unsigned int flag)
2692a8f9449SShaohua Li {
2702a8f9449SShaohua Li 	info->flags = flag;
2712a8f9449SShaohua Li }
2722a8f9449SShaohua Li 
2732a8f9449SShaohua Li static inline unsigned int cluster_count(struct swap_cluster_info *info)
2742a8f9449SShaohua Li {
2752a8f9449SShaohua Li 	return info->data;
2762a8f9449SShaohua Li }
2772a8f9449SShaohua Li 
2782a8f9449SShaohua Li static inline void cluster_set_count(struct swap_cluster_info *info,
2792a8f9449SShaohua Li 				     unsigned int c)
2802a8f9449SShaohua Li {
2812a8f9449SShaohua Li 	info->data = c;
2822a8f9449SShaohua Li }
2832a8f9449SShaohua Li 
2842a8f9449SShaohua Li static inline void cluster_set_count_flag(struct swap_cluster_info *info,
2852a8f9449SShaohua Li 					 unsigned int c, unsigned int f)
2862a8f9449SShaohua Li {
2872a8f9449SShaohua Li 	info->flags = f;
2882a8f9449SShaohua Li 	info->data = c;
2892a8f9449SShaohua Li }
2902a8f9449SShaohua Li 
2912a8f9449SShaohua Li static inline unsigned int cluster_next(struct swap_cluster_info *info)
2922a8f9449SShaohua Li {
2932a8f9449SShaohua Li 	return info->data;
2942a8f9449SShaohua Li }
2952a8f9449SShaohua Li 
2962a8f9449SShaohua Li static inline void cluster_set_next(struct swap_cluster_info *info,
2972a8f9449SShaohua Li 				    unsigned int n)
2982a8f9449SShaohua Li {
2992a8f9449SShaohua Li 	info->data = n;
3002a8f9449SShaohua Li }
3012a8f9449SShaohua Li 
3022a8f9449SShaohua Li static inline void cluster_set_next_flag(struct swap_cluster_info *info,
3032a8f9449SShaohua Li 					 unsigned int n, unsigned int f)
3042a8f9449SShaohua Li {
3052a8f9449SShaohua Li 	info->flags = f;
3062a8f9449SShaohua Li 	info->data = n;
3072a8f9449SShaohua Li }
3082a8f9449SShaohua Li 
3092a8f9449SShaohua Li static inline bool cluster_is_free(struct swap_cluster_info *info)
3102a8f9449SShaohua Li {
3112a8f9449SShaohua Li 	return info->flags & CLUSTER_FLAG_FREE;
3122a8f9449SShaohua Li }
3132a8f9449SShaohua Li 
3142a8f9449SShaohua Li static inline bool cluster_is_null(struct swap_cluster_info *info)
3152a8f9449SShaohua Li {
3162a8f9449SShaohua Li 	return info->flags & CLUSTER_FLAG_NEXT_NULL;
3172a8f9449SShaohua Li }
3182a8f9449SShaohua Li 
3192a8f9449SShaohua Li static inline void cluster_set_null(struct swap_cluster_info *info)
3202a8f9449SShaohua Li {
3212a8f9449SShaohua Li 	info->flags = CLUSTER_FLAG_NEXT_NULL;
3222a8f9449SShaohua Li 	info->data = 0;
3232a8f9449SShaohua Li }
3242a8f9449SShaohua Li 
325e0709829SHuang Ying static inline bool cluster_is_huge(struct swap_cluster_info *info)
326e0709829SHuang Ying {
32733ee011eSHuang Ying 	if (IS_ENABLED(CONFIG_THP_SWAP))
328e0709829SHuang Ying 		return info->flags & CLUSTER_FLAG_HUGE;
32933ee011eSHuang Ying 	return false;
330e0709829SHuang Ying }
331e0709829SHuang Ying 
332e0709829SHuang Ying static inline void cluster_clear_huge(struct swap_cluster_info *info)
333e0709829SHuang Ying {
334e0709829SHuang Ying 	info->flags &= ~CLUSTER_FLAG_HUGE;
335e0709829SHuang Ying }
336e0709829SHuang Ying 
337235b6217SHuang, Ying static inline struct swap_cluster_info *lock_cluster(struct swap_info_struct *si,
338235b6217SHuang, Ying 						     unsigned long offset)
339235b6217SHuang, Ying {
340235b6217SHuang, Ying 	struct swap_cluster_info *ci;
341235b6217SHuang, Ying 
342235b6217SHuang, Ying 	ci = si->cluster_info;
343235b6217SHuang, Ying 	if (ci) {
344235b6217SHuang, Ying 		ci += offset / SWAPFILE_CLUSTER;
345235b6217SHuang, Ying 		spin_lock(&ci->lock);
346235b6217SHuang, Ying 	}
347235b6217SHuang, Ying 	return ci;
348235b6217SHuang, Ying }
349235b6217SHuang, Ying 
350235b6217SHuang, Ying static inline void unlock_cluster(struct swap_cluster_info *ci)
351235b6217SHuang, Ying {
352235b6217SHuang, Ying 	if (ci)
353235b6217SHuang, Ying 		spin_unlock(&ci->lock);
354235b6217SHuang, Ying }
355235b6217SHuang, Ying 
35659d98bf3SHuang Ying /*
35759d98bf3SHuang Ying  * Determine the locking method in use for this device.  Return
35859d98bf3SHuang Ying  * swap_cluster_info if SSD-style cluster-based locking is in place.
35959d98bf3SHuang Ying  */
360235b6217SHuang, Ying static inline struct swap_cluster_info *lock_cluster_or_swap_info(
36159d98bf3SHuang Ying 		struct swap_info_struct *si, unsigned long offset)
362235b6217SHuang, Ying {
363235b6217SHuang, Ying 	struct swap_cluster_info *ci;
364235b6217SHuang, Ying 
36559d98bf3SHuang Ying 	/* Try to use fine-grained SSD-style locking if available: */
366235b6217SHuang, Ying 	ci = lock_cluster(si, offset);
36759d98bf3SHuang Ying 	/* Otherwise, fall back to traditional, coarse locking: */
368235b6217SHuang, Ying 	if (!ci)
369235b6217SHuang, Ying 		spin_lock(&si->lock);
370235b6217SHuang, Ying 
371235b6217SHuang, Ying 	return ci;
372235b6217SHuang, Ying }
373235b6217SHuang, Ying 
374235b6217SHuang, Ying static inline void unlock_cluster_or_swap_info(struct swap_info_struct *si,
375235b6217SHuang, Ying 					       struct swap_cluster_info *ci)
376235b6217SHuang, Ying {
377235b6217SHuang, Ying 	if (ci)
378235b6217SHuang, Ying 		unlock_cluster(ci);
379235b6217SHuang, Ying 	else
380235b6217SHuang, Ying 		spin_unlock(&si->lock);
381235b6217SHuang, Ying }
382235b6217SHuang, Ying 
3836b534915SHuang Ying static inline bool cluster_list_empty(struct swap_cluster_list *list)
3846b534915SHuang Ying {
3856b534915SHuang Ying 	return cluster_is_null(&list->head);
3866b534915SHuang Ying }
3876b534915SHuang Ying 
3886b534915SHuang Ying static inline unsigned int cluster_list_first(struct swap_cluster_list *list)
3896b534915SHuang Ying {
3906b534915SHuang Ying 	return cluster_next(&list->head);
3916b534915SHuang Ying }
3926b534915SHuang Ying 
3936b534915SHuang Ying static void cluster_list_init(struct swap_cluster_list *list)
3946b534915SHuang Ying {
3956b534915SHuang Ying 	cluster_set_null(&list->head);
3966b534915SHuang Ying 	cluster_set_null(&list->tail);
3976b534915SHuang Ying }
3986b534915SHuang Ying 
3996b534915SHuang Ying static void cluster_list_add_tail(struct swap_cluster_list *list,
4006b534915SHuang Ying 				  struct swap_cluster_info *ci,
4016b534915SHuang Ying 				  unsigned int idx)
4026b534915SHuang Ying {
4036b534915SHuang Ying 	if (cluster_list_empty(list)) {
4046b534915SHuang Ying 		cluster_set_next_flag(&list->head, idx, 0);
4056b534915SHuang Ying 		cluster_set_next_flag(&list->tail, idx, 0);
4066b534915SHuang Ying 	} else {
407235b6217SHuang, Ying 		struct swap_cluster_info *ci_tail;
4086b534915SHuang Ying 		unsigned int tail = cluster_next(&list->tail);
4096b534915SHuang Ying 
410235b6217SHuang, Ying 		/*
411235b6217SHuang, Ying 		 * Nested cluster lock, but both cluster locks are
412235b6217SHuang, Ying 		 * only acquired when we held swap_info_struct->lock
413235b6217SHuang, Ying 		 */
414235b6217SHuang, Ying 		ci_tail = ci + tail;
415235b6217SHuang, Ying 		spin_lock_nested(&ci_tail->lock, SINGLE_DEPTH_NESTING);
416235b6217SHuang, Ying 		cluster_set_next(ci_tail, idx);
4170ef017d1SHuang Ying 		spin_unlock(&ci_tail->lock);
4186b534915SHuang Ying 		cluster_set_next_flag(&list->tail, idx, 0);
4196b534915SHuang Ying 	}
4206b534915SHuang Ying }
4216b534915SHuang Ying 
4226b534915SHuang Ying static unsigned int cluster_list_del_first(struct swap_cluster_list *list,
4236b534915SHuang Ying 					   struct swap_cluster_info *ci)
4246b534915SHuang Ying {
4256b534915SHuang Ying 	unsigned int idx;
4266b534915SHuang Ying 
4276b534915SHuang Ying 	idx = cluster_next(&list->head);
4286b534915SHuang Ying 	if (cluster_next(&list->tail) == idx) {
4296b534915SHuang Ying 		cluster_set_null(&list->head);
4306b534915SHuang Ying 		cluster_set_null(&list->tail);
4316b534915SHuang Ying 	} else
4326b534915SHuang Ying 		cluster_set_next_flag(&list->head,
4336b534915SHuang Ying 				      cluster_next(&ci[idx]), 0);
4346b534915SHuang Ying 
4356b534915SHuang Ying 	return idx;
4366b534915SHuang Ying }
4376b534915SHuang Ying 
438815c2c54SShaohua Li /* Add a cluster to discard list and schedule it to do discard */
439815c2c54SShaohua Li static void swap_cluster_schedule_discard(struct swap_info_struct *si,
440815c2c54SShaohua Li 		unsigned int idx)
441815c2c54SShaohua Li {
442815c2c54SShaohua Li 	/*
443815c2c54SShaohua Li 	 * If scan_swap_map() can't find a free cluster, it will check
444815c2c54SShaohua Li 	 * si->swap_map directly. To make sure the discarding cluster isn't
445815c2c54SShaohua Li 	 * taken by scan_swap_map(), mark the swap entries bad (occupied). It
446815c2c54SShaohua Li 	 * will be cleared after discard
447815c2c54SShaohua Li 	 */
448815c2c54SShaohua Li 	memset(si->swap_map + idx * SWAPFILE_CLUSTER,
449815c2c54SShaohua Li 			SWAP_MAP_BAD, SWAPFILE_CLUSTER);
450815c2c54SShaohua Li 
4516b534915SHuang Ying 	cluster_list_add_tail(&si->discard_clusters, si->cluster_info, idx);
452815c2c54SShaohua Li 
453815c2c54SShaohua Li 	schedule_work(&si->discard_work);
454815c2c54SShaohua Li }
455815c2c54SShaohua Li 
45638d8b4e6SHuang Ying static void __free_cluster(struct swap_info_struct *si, unsigned long idx)
45738d8b4e6SHuang Ying {
45838d8b4e6SHuang Ying 	struct swap_cluster_info *ci = si->cluster_info;
45938d8b4e6SHuang Ying 
46038d8b4e6SHuang Ying 	cluster_set_flag(ci + idx, CLUSTER_FLAG_FREE);
46138d8b4e6SHuang Ying 	cluster_list_add_tail(&si->free_clusters, ci, idx);
46238d8b4e6SHuang Ying }
46338d8b4e6SHuang Ying 
464815c2c54SShaohua Li /*
465815c2c54SShaohua Li  * Doing discard actually. After a cluster discard is finished, the cluster
466815c2c54SShaohua Li  * will be added to free cluster list. caller should hold si->lock.
467815c2c54SShaohua Li */
468815c2c54SShaohua Li static void swap_do_scheduled_discard(struct swap_info_struct *si)
469815c2c54SShaohua Li {
470235b6217SHuang, Ying 	struct swap_cluster_info *info, *ci;
471815c2c54SShaohua Li 	unsigned int idx;
472815c2c54SShaohua Li 
473815c2c54SShaohua Li 	info = si->cluster_info;
474815c2c54SShaohua Li 
4756b534915SHuang Ying 	while (!cluster_list_empty(&si->discard_clusters)) {
4766b534915SHuang Ying 		idx = cluster_list_del_first(&si->discard_clusters, info);
477815c2c54SShaohua Li 		spin_unlock(&si->lock);
478815c2c54SShaohua Li 
479815c2c54SShaohua Li 		discard_swap_cluster(si, idx * SWAPFILE_CLUSTER,
480815c2c54SShaohua Li 				SWAPFILE_CLUSTER);
481815c2c54SShaohua Li 
482815c2c54SShaohua Li 		spin_lock(&si->lock);
483235b6217SHuang, Ying 		ci = lock_cluster(si, idx * SWAPFILE_CLUSTER);
48438d8b4e6SHuang Ying 		__free_cluster(si, idx);
485815c2c54SShaohua Li 		memset(si->swap_map + idx * SWAPFILE_CLUSTER,
486815c2c54SShaohua Li 				0, SWAPFILE_CLUSTER);
487235b6217SHuang, Ying 		unlock_cluster(ci);
488815c2c54SShaohua Li 	}
489815c2c54SShaohua Li }
490815c2c54SShaohua Li 
491815c2c54SShaohua Li static void swap_discard_work(struct work_struct *work)
492815c2c54SShaohua Li {
493815c2c54SShaohua Li 	struct swap_info_struct *si;
494815c2c54SShaohua Li 
495815c2c54SShaohua Li 	si = container_of(work, struct swap_info_struct, discard_work);
496815c2c54SShaohua Li 
497815c2c54SShaohua Li 	spin_lock(&si->lock);
498815c2c54SShaohua Li 	swap_do_scheduled_discard(si);
499815c2c54SShaohua Li 	spin_unlock(&si->lock);
500815c2c54SShaohua Li }
501815c2c54SShaohua Li 
50238d8b4e6SHuang Ying static void alloc_cluster(struct swap_info_struct *si, unsigned long idx)
50338d8b4e6SHuang Ying {
50438d8b4e6SHuang Ying 	struct swap_cluster_info *ci = si->cluster_info;
50538d8b4e6SHuang Ying 
50638d8b4e6SHuang Ying 	VM_BUG_ON(cluster_list_first(&si->free_clusters) != idx);
50738d8b4e6SHuang Ying 	cluster_list_del_first(&si->free_clusters, ci);
50838d8b4e6SHuang Ying 	cluster_set_count_flag(ci + idx, 0, 0);
50938d8b4e6SHuang Ying }
51038d8b4e6SHuang Ying 
51138d8b4e6SHuang Ying static void free_cluster(struct swap_info_struct *si, unsigned long idx)
51238d8b4e6SHuang Ying {
51338d8b4e6SHuang Ying 	struct swap_cluster_info *ci = si->cluster_info + idx;
51438d8b4e6SHuang Ying 
51538d8b4e6SHuang Ying 	VM_BUG_ON(cluster_count(ci) != 0);
51638d8b4e6SHuang Ying 	/*
51738d8b4e6SHuang Ying 	 * If the swap is discardable, prepare discard the cluster
51838d8b4e6SHuang Ying 	 * instead of free it immediately. The cluster will be freed
51938d8b4e6SHuang Ying 	 * after discard.
52038d8b4e6SHuang Ying 	 */
52138d8b4e6SHuang Ying 	if ((si->flags & (SWP_WRITEOK | SWP_PAGE_DISCARD)) ==
52238d8b4e6SHuang Ying 	    (SWP_WRITEOK | SWP_PAGE_DISCARD)) {
52338d8b4e6SHuang Ying 		swap_cluster_schedule_discard(si, idx);
52438d8b4e6SHuang Ying 		return;
52538d8b4e6SHuang Ying 	}
52638d8b4e6SHuang Ying 
52738d8b4e6SHuang Ying 	__free_cluster(si, idx);
52838d8b4e6SHuang Ying }
52938d8b4e6SHuang Ying 
5302a8f9449SShaohua Li /*
5312a8f9449SShaohua Li  * The cluster corresponding to page_nr will be used. The cluster will be
5322a8f9449SShaohua Li  * removed from free cluster list and its usage counter will be increased.
5332a8f9449SShaohua Li  */
5342a8f9449SShaohua Li static void inc_cluster_info_page(struct swap_info_struct *p,
5352a8f9449SShaohua Li 	struct swap_cluster_info *cluster_info, unsigned long page_nr)
5362a8f9449SShaohua Li {
5372a8f9449SShaohua Li 	unsigned long idx = page_nr / SWAPFILE_CLUSTER;
5382a8f9449SShaohua Li 
5392a8f9449SShaohua Li 	if (!cluster_info)
5402a8f9449SShaohua Li 		return;
54138d8b4e6SHuang Ying 	if (cluster_is_free(&cluster_info[idx]))
54238d8b4e6SHuang Ying 		alloc_cluster(p, idx);
5432a8f9449SShaohua Li 
5442a8f9449SShaohua Li 	VM_BUG_ON(cluster_count(&cluster_info[idx]) >= SWAPFILE_CLUSTER);
5452a8f9449SShaohua Li 	cluster_set_count(&cluster_info[idx],
5462a8f9449SShaohua Li 		cluster_count(&cluster_info[idx]) + 1);
5472a8f9449SShaohua Li }
5482a8f9449SShaohua Li 
5492a8f9449SShaohua Li /*
5502a8f9449SShaohua Li  * The cluster corresponding to page_nr decreases one usage. If the usage
5512a8f9449SShaohua Li  * counter becomes 0, which means no page in the cluster is in using, we can
5522a8f9449SShaohua Li  * optionally discard the cluster and add it to free cluster list.
5532a8f9449SShaohua Li  */
5542a8f9449SShaohua Li static void dec_cluster_info_page(struct swap_info_struct *p,
5552a8f9449SShaohua Li 	struct swap_cluster_info *cluster_info, unsigned long page_nr)
5562a8f9449SShaohua Li {
5572a8f9449SShaohua Li 	unsigned long idx = page_nr / SWAPFILE_CLUSTER;
5582a8f9449SShaohua Li 
5592a8f9449SShaohua Li 	if (!cluster_info)
5602a8f9449SShaohua Li 		return;
5612a8f9449SShaohua Li 
5622a8f9449SShaohua Li 	VM_BUG_ON(cluster_count(&cluster_info[idx]) == 0);
5632a8f9449SShaohua Li 	cluster_set_count(&cluster_info[idx],
5642a8f9449SShaohua Li 		cluster_count(&cluster_info[idx]) - 1);
5652a8f9449SShaohua Li 
56638d8b4e6SHuang Ying 	if (cluster_count(&cluster_info[idx]) == 0)
56738d8b4e6SHuang Ying 		free_cluster(p, idx);
5682a8f9449SShaohua Li }
5692a8f9449SShaohua Li 
5702a8f9449SShaohua Li /*
5712a8f9449SShaohua Li  * It's possible scan_swap_map() uses a free cluster in the middle of free
5722a8f9449SShaohua Li  * cluster list. Avoiding such abuse to avoid list corruption.
5732a8f9449SShaohua Li  */
574ebc2a1a6SShaohua Li static bool
575ebc2a1a6SShaohua Li scan_swap_map_ssd_cluster_conflict(struct swap_info_struct *si,
5762a8f9449SShaohua Li 	unsigned long offset)
5772a8f9449SShaohua Li {
578ebc2a1a6SShaohua Li 	struct percpu_cluster *percpu_cluster;
579ebc2a1a6SShaohua Li 	bool conflict;
580ebc2a1a6SShaohua Li 
5812a8f9449SShaohua Li 	offset /= SWAPFILE_CLUSTER;
5826b534915SHuang Ying 	conflict = !cluster_list_empty(&si->free_clusters) &&
5836b534915SHuang Ying 		offset != cluster_list_first(&si->free_clusters) &&
5842a8f9449SShaohua Li 		cluster_is_free(&si->cluster_info[offset]);
585ebc2a1a6SShaohua Li 
586ebc2a1a6SShaohua Li 	if (!conflict)
587ebc2a1a6SShaohua Li 		return false;
588ebc2a1a6SShaohua Li 
589ebc2a1a6SShaohua Li 	percpu_cluster = this_cpu_ptr(si->percpu_cluster);
590ebc2a1a6SShaohua Li 	cluster_set_null(&percpu_cluster->index);
591ebc2a1a6SShaohua Li 	return true;
592ebc2a1a6SShaohua Li }
593ebc2a1a6SShaohua Li 
594ebc2a1a6SShaohua Li /*
595ebc2a1a6SShaohua Li  * Try to get a swap entry from current cpu's swap entry pool (a cluster). This
596ebc2a1a6SShaohua Li  * might involve allocating a new cluster for current CPU too.
597ebc2a1a6SShaohua Li  */
59836005baeSTim Chen static bool scan_swap_map_try_ssd_cluster(struct swap_info_struct *si,
599ebc2a1a6SShaohua Li 	unsigned long *offset, unsigned long *scan_base)
600ebc2a1a6SShaohua Li {
601ebc2a1a6SShaohua Li 	struct percpu_cluster *cluster;
602235b6217SHuang, Ying 	struct swap_cluster_info *ci;
603235b6217SHuang, Ying 	unsigned long tmp, max;
604ebc2a1a6SShaohua Li 
605ebc2a1a6SShaohua Li new_cluster:
606ebc2a1a6SShaohua Li 	cluster = this_cpu_ptr(si->percpu_cluster);
607ebc2a1a6SShaohua Li 	if (cluster_is_null(&cluster->index)) {
6086b534915SHuang Ying 		if (!cluster_list_empty(&si->free_clusters)) {
6096b534915SHuang Ying 			cluster->index = si->free_clusters.head;
610ebc2a1a6SShaohua Li 			cluster->next = cluster_next(&cluster->index) *
611ebc2a1a6SShaohua Li 					SWAPFILE_CLUSTER;
6126b534915SHuang Ying 		} else if (!cluster_list_empty(&si->discard_clusters)) {
613ebc2a1a6SShaohua Li 			/*
614ebc2a1a6SShaohua Li 			 * we don't have free cluster but have some clusters in
61549070588SHuang Ying 			 * discarding, do discard now and reclaim them, then
61649070588SHuang Ying 			 * reread cluster_next_cpu since we dropped si->lock
617ebc2a1a6SShaohua Li 			 */
618ebc2a1a6SShaohua Li 			swap_do_scheduled_discard(si);
61949070588SHuang Ying 			*scan_base = this_cpu_read(*si->cluster_next_cpu);
62049070588SHuang Ying 			*offset = *scan_base;
621ebc2a1a6SShaohua Li 			goto new_cluster;
622ebc2a1a6SShaohua Li 		} else
62336005baeSTim Chen 			return false;
624ebc2a1a6SShaohua Li 	}
625ebc2a1a6SShaohua Li 
626ebc2a1a6SShaohua Li 	/*
627ebc2a1a6SShaohua Li 	 * Other CPUs can use our cluster if they can't find a free cluster,
628ebc2a1a6SShaohua Li 	 * check if there is still free entry in the cluster
629ebc2a1a6SShaohua Li 	 */
630ebc2a1a6SShaohua Li 	tmp = cluster->next;
631235b6217SHuang, Ying 	max = min_t(unsigned long, si->max,
632235b6217SHuang, Ying 		    (cluster_next(&cluster->index) + 1) * SWAPFILE_CLUSTER);
6337b9e2de1SWei Yang 	if (tmp < max) {
634235b6217SHuang, Ying 		ci = lock_cluster(si, tmp);
635235b6217SHuang, Ying 		while (tmp < max) {
6360fd0e19eSWei Yang 			if (!si->swap_map[tmp])
637ebc2a1a6SShaohua Li 				break;
638ebc2a1a6SShaohua Li 			tmp++;
639ebc2a1a6SShaohua Li 		}
640235b6217SHuang, Ying 		unlock_cluster(ci);
6417b9e2de1SWei Yang 	}
6420fd0e19eSWei Yang 	if (tmp >= max) {
643ebc2a1a6SShaohua Li 		cluster_set_null(&cluster->index);
644ebc2a1a6SShaohua Li 		goto new_cluster;
645ebc2a1a6SShaohua Li 	}
646ebc2a1a6SShaohua Li 	cluster->next = tmp + 1;
647ebc2a1a6SShaohua Li 	*offset = tmp;
648ebc2a1a6SShaohua Li 	*scan_base = tmp;
649fdff1debSWei Yang 	return true;
6502a8f9449SShaohua Li }
6512a8f9449SShaohua Li 
652a2468cc9SAaron Lu static void __del_from_avail_list(struct swap_info_struct *p)
653a2468cc9SAaron Lu {
654a2468cc9SAaron Lu 	int nid;
655a2468cc9SAaron Lu 
656a2468cc9SAaron Lu 	for_each_node(nid)
657a2468cc9SAaron Lu 		plist_del(&p->avail_lists[nid], &swap_avail_heads[nid]);
658a2468cc9SAaron Lu }
659a2468cc9SAaron Lu 
660a2468cc9SAaron Lu static void del_from_avail_list(struct swap_info_struct *p)
661a2468cc9SAaron Lu {
662a2468cc9SAaron Lu 	spin_lock(&swap_avail_lock);
663a2468cc9SAaron Lu 	__del_from_avail_list(p);
664a2468cc9SAaron Lu 	spin_unlock(&swap_avail_lock);
665a2468cc9SAaron Lu }
666a2468cc9SAaron Lu 
66738d8b4e6SHuang Ying static void swap_range_alloc(struct swap_info_struct *si, unsigned long offset,
66838d8b4e6SHuang Ying 			     unsigned int nr_entries)
66938d8b4e6SHuang Ying {
67038d8b4e6SHuang Ying 	unsigned int end = offset + nr_entries - 1;
67138d8b4e6SHuang Ying 
67238d8b4e6SHuang Ying 	if (offset == si->lowest_bit)
67338d8b4e6SHuang Ying 		si->lowest_bit += nr_entries;
67438d8b4e6SHuang Ying 	if (end == si->highest_bit)
67538d8b4e6SHuang Ying 		si->highest_bit -= nr_entries;
67638d8b4e6SHuang Ying 	si->inuse_pages += nr_entries;
67738d8b4e6SHuang Ying 	if (si->inuse_pages == si->pages) {
67838d8b4e6SHuang Ying 		si->lowest_bit = si->max;
67938d8b4e6SHuang Ying 		si->highest_bit = 0;
680a2468cc9SAaron Lu 		del_from_avail_list(si);
68138d8b4e6SHuang Ying 	}
68238d8b4e6SHuang Ying }
68338d8b4e6SHuang Ying 
684a2468cc9SAaron Lu static void add_to_avail_list(struct swap_info_struct *p)
685a2468cc9SAaron Lu {
686a2468cc9SAaron Lu 	int nid;
687a2468cc9SAaron Lu 
688a2468cc9SAaron Lu 	spin_lock(&swap_avail_lock);
689a2468cc9SAaron Lu 	for_each_node(nid) {
690a2468cc9SAaron Lu 		WARN_ON(!plist_node_empty(&p->avail_lists[nid]));
691a2468cc9SAaron Lu 		plist_add(&p->avail_lists[nid], &swap_avail_heads[nid]);
692a2468cc9SAaron Lu 	}
693a2468cc9SAaron Lu 	spin_unlock(&swap_avail_lock);
694a2468cc9SAaron Lu }
695a2468cc9SAaron Lu 
69638d8b4e6SHuang Ying static void swap_range_free(struct swap_info_struct *si, unsigned long offset,
69738d8b4e6SHuang Ying 			    unsigned int nr_entries)
69838d8b4e6SHuang Ying {
69938d8b4e6SHuang Ying 	unsigned long end = offset + nr_entries - 1;
70038d8b4e6SHuang Ying 	void (*swap_slot_free_notify)(struct block_device *, unsigned long);
70138d8b4e6SHuang Ying 
70238d8b4e6SHuang Ying 	if (offset < si->lowest_bit)
70338d8b4e6SHuang Ying 		si->lowest_bit = offset;
70438d8b4e6SHuang Ying 	if (end > si->highest_bit) {
70538d8b4e6SHuang Ying 		bool was_full = !si->highest_bit;
70638d8b4e6SHuang Ying 
70738d8b4e6SHuang Ying 		si->highest_bit = end;
708a2468cc9SAaron Lu 		if (was_full && (si->flags & SWP_WRITEOK))
709a2468cc9SAaron Lu 			add_to_avail_list(si);
71038d8b4e6SHuang Ying 	}
71138d8b4e6SHuang Ying 	atomic_long_add(nr_entries, &nr_swap_pages);
71238d8b4e6SHuang Ying 	si->inuse_pages -= nr_entries;
71338d8b4e6SHuang Ying 	if (si->flags & SWP_BLKDEV)
71438d8b4e6SHuang Ying 		swap_slot_free_notify =
71538d8b4e6SHuang Ying 			si->bdev->bd_disk->fops->swap_slot_free_notify;
71638d8b4e6SHuang Ying 	else
71738d8b4e6SHuang Ying 		swap_slot_free_notify = NULL;
71838d8b4e6SHuang Ying 	while (offset <= end) {
71938d8b4e6SHuang Ying 		frontswap_invalidate_page(si->type, offset);
72038d8b4e6SHuang Ying 		if (swap_slot_free_notify)
72138d8b4e6SHuang Ying 			swap_slot_free_notify(si->bdev, offset);
72238d8b4e6SHuang Ying 		offset++;
72338d8b4e6SHuang Ying 	}
72438d8b4e6SHuang Ying }
72538d8b4e6SHuang Ying 
72649070588SHuang Ying static void set_cluster_next(struct swap_info_struct *si, unsigned long next)
72749070588SHuang Ying {
72849070588SHuang Ying 	unsigned long prev;
72949070588SHuang Ying 
73049070588SHuang Ying 	if (!(si->flags & SWP_SOLIDSTATE)) {
73149070588SHuang Ying 		si->cluster_next = next;
73249070588SHuang Ying 		return;
73349070588SHuang Ying 	}
73449070588SHuang Ying 
73549070588SHuang Ying 	prev = this_cpu_read(*si->cluster_next_cpu);
73649070588SHuang Ying 	/*
73749070588SHuang Ying 	 * Cross the swap address space size aligned trunk, choose
73849070588SHuang Ying 	 * another trunk randomly to avoid lock contention on swap
73949070588SHuang Ying 	 * address space if possible.
74049070588SHuang Ying 	 */
74149070588SHuang Ying 	if ((prev >> SWAP_ADDRESS_SPACE_SHIFT) !=
74249070588SHuang Ying 	    (next >> SWAP_ADDRESS_SPACE_SHIFT)) {
74349070588SHuang Ying 		/* No free swap slots available */
74449070588SHuang Ying 		if (si->highest_bit <= si->lowest_bit)
74549070588SHuang Ying 			return;
74649070588SHuang Ying 		next = si->lowest_bit +
74749070588SHuang Ying 			prandom_u32_max(si->highest_bit - si->lowest_bit + 1);
74849070588SHuang Ying 		next = ALIGN_DOWN(next, SWAP_ADDRESS_SPACE_PAGES);
74949070588SHuang Ying 		next = max_t(unsigned int, next, si->lowest_bit);
75049070588SHuang Ying 	}
75149070588SHuang Ying 	this_cpu_write(*si->cluster_next_cpu, next);
75249070588SHuang Ying }
75349070588SHuang Ying 
75436005baeSTim Chen static int scan_swap_map_slots(struct swap_info_struct *si,
75536005baeSTim Chen 			       unsigned char usage, int nr,
75636005baeSTim Chen 			       swp_entry_t slots[])
7571da177e4SLinus Torvalds {
758235b6217SHuang, Ying 	struct swap_cluster_info *ci;
759ebebbbe9SHugh Dickins 	unsigned long offset;
760c60aa176SHugh Dickins 	unsigned long scan_base;
7617992fde7SHugh Dickins 	unsigned long last_in_cluster = 0;
762048c27fdSHugh Dickins 	int latency_ration = LATENCY_LIMIT;
76336005baeSTim Chen 	int n_ret = 0;
764ed43af10SHuang Ying 	bool scanned_many = false;
76536005baeSTim Chen 
7667dfad418SHugh Dickins 	/*
7677dfad418SHugh Dickins 	 * We try to cluster swap pages by allocating them sequentially
7687dfad418SHugh Dickins 	 * in swap.  Once we've allocated SWAPFILE_CLUSTER pages this
7697dfad418SHugh Dickins 	 * way, however, we resort to first-free allocation, starting
7707dfad418SHugh Dickins 	 * a new cluster.  This prevents us from scattering swap pages
7717dfad418SHugh Dickins 	 * all over the entire swap partition, so that we reduce
7727dfad418SHugh Dickins 	 * overall disk seek times between swap pages.  -- sct
7737dfad418SHugh Dickins 	 * But we do now try to find an empty cluster.  -Andrea
774c60aa176SHugh Dickins 	 * And we let swap pages go all over an SSD partition.  Hugh
7751da177e4SLinus Torvalds 	 */
7767dfad418SHugh Dickins 
77752b7efdbSHugh Dickins 	si->flags += SWP_SCANNING;
77849070588SHuang Ying 	/*
77949070588SHuang Ying 	 * Use percpu scan base for SSD to reduce lock contention on
78049070588SHuang Ying 	 * cluster and swap cache.  For HDD, sequential access is more
78149070588SHuang Ying 	 * important.
78249070588SHuang Ying 	 */
78349070588SHuang Ying 	if (si->flags & SWP_SOLIDSTATE)
78449070588SHuang Ying 		scan_base = this_cpu_read(*si->cluster_next_cpu);
78549070588SHuang Ying 	else
78649070588SHuang Ying 		scan_base = si->cluster_next;
78749070588SHuang Ying 	offset = scan_base;
788ebebbbe9SHugh Dickins 
789ebc2a1a6SShaohua Li 	/* SSD algorithm */
790ebc2a1a6SShaohua Li 	if (si->cluster_info) {
791bd2d18daSWei Yang 		if (!scan_swap_map_try_ssd_cluster(si, &offset, &scan_base))
79236005baeSTim Chen 			goto scan;
793f4eaf51aSWei Yang 	} else if (unlikely(!si->cluster_nr--)) {
794ebc2a1a6SShaohua Li 		if (si->pages - si->inuse_pages < SWAPFILE_CLUSTER) {
795ebc2a1a6SShaohua Li 			si->cluster_nr = SWAPFILE_CLUSTER - 1;
7962a8f9449SShaohua Li 			goto checks;
7972a8f9449SShaohua Li 		}
7982a8f9449SShaohua Li 
799ec8acf20SShaohua Li 		spin_unlock(&si->lock);
8007dfad418SHugh Dickins 
801c60aa176SHugh Dickins 		/*
802c60aa176SHugh Dickins 		 * If seek is expensive, start searching for new cluster from
803c60aa176SHugh Dickins 		 * start of partition, to minimize the span of allocated swap.
80450088c44SChen Yucong 		 * If seek is cheap, that is the SWP_SOLIDSTATE si->cluster_info
80550088c44SChen Yucong 		 * case, just handled by scan_swap_map_try_ssd_cluster() above.
806c60aa176SHugh Dickins 		 */
807c60aa176SHugh Dickins 		scan_base = offset = si->lowest_bit;
8087dfad418SHugh Dickins 		last_in_cluster = offset + SWAPFILE_CLUSTER - 1;
8097dfad418SHugh Dickins 
8107dfad418SHugh Dickins 		/* Locate the first empty (unaligned) cluster */
8117dfad418SHugh Dickins 		for (; last_in_cluster <= si->highest_bit; offset++) {
8121da177e4SLinus Torvalds 			if (si->swap_map[offset])
8137dfad418SHugh Dickins 				last_in_cluster = offset + SWAPFILE_CLUSTER;
8147dfad418SHugh Dickins 			else if (offset == last_in_cluster) {
815ec8acf20SShaohua Li 				spin_lock(&si->lock);
816ebebbbe9SHugh Dickins 				offset -= SWAPFILE_CLUSTER - 1;
817ebebbbe9SHugh Dickins 				si->cluster_next = offset;
818ebebbbe9SHugh Dickins 				si->cluster_nr = SWAPFILE_CLUSTER - 1;
819ebebbbe9SHugh Dickins 				goto checks;
8207dfad418SHugh Dickins 			}
821048c27fdSHugh Dickins 			if (unlikely(--latency_ration < 0)) {
822048c27fdSHugh Dickins 				cond_resched();
823048c27fdSHugh Dickins 				latency_ration = LATENCY_LIMIT;
824048c27fdSHugh Dickins 			}
8257dfad418SHugh Dickins 		}
826ebebbbe9SHugh Dickins 
827c60aa176SHugh Dickins 		offset = scan_base;
828ec8acf20SShaohua Li 		spin_lock(&si->lock);
829ebebbbe9SHugh Dickins 		si->cluster_nr = SWAPFILE_CLUSTER - 1;
8307dfad418SHugh Dickins 	}
8317dfad418SHugh Dickins 
832ebebbbe9SHugh Dickins checks:
833ebc2a1a6SShaohua Li 	if (si->cluster_info) {
83436005baeSTim Chen 		while (scan_swap_map_ssd_cluster_conflict(si, offset)) {
83536005baeSTim Chen 		/* take a break if we already got some slots */
83636005baeSTim Chen 			if (n_ret)
83736005baeSTim Chen 				goto done;
83836005baeSTim Chen 			if (!scan_swap_map_try_ssd_cluster(si, &offset,
83936005baeSTim Chen 							&scan_base))
84036005baeSTim Chen 				goto scan;
84136005baeSTim Chen 		}
842ebc2a1a6SShaohua Li 	}
843ebebbbe9SHugh Dickins 	if (!(si->flags & SWP_WRITEOK))
84452b7efdbSHugh Dickins 		goto no_page;
8457dfad418SHugh Dickins 	if (!si->highest_bit)
8467dfad418SHugh Dickins 		goto no_page;
847ebebbbe9SHugh Dickins 	if (offset > si->highest_bit)
848c60aa176SHugh Dickins 		scan_base = offset = si->lowest_bit;
849c9e44410SKAMEZAWA Hiroyuki 
850235b6217SHuang, Ying 	ci = lock_cluster(si, offset);
851b73d7fceSHugh Dickins 	/* reuse swap entry of cache-only swap if not busy. */
852b73d7fceSHugh Dickins 	if (vm_swap_full() && si->swap_map[offset] == SWAP_HAS_CACHE) {
853c9e44410SKAMEZAWA Hiroyuki 		int swap_was_freed;
854235b6217SHuang, Ying 		unlock_cluster(ci);
855ec8acf20SShaohua Li 		spin_unlock(&si->lock);
856bcd49e86SHuang Ying 		swap_was_freed = __try_to_reclaim_swap(si, offset, TTRS_ANYWAY);
857ec8acf20SShaohua Li 		spin_lock(&si->lock);
858c9e44410SKAMEZAWA Hiroyuki 		/* entry was freed successfully, try to use this again */
859c9e44410SKAMEZAWA Hiroyuki 		if (swap_was_freed)
860c9e44410SKAMEZAWA Hiroyuki 			goto checks;
861c9e44410SKAMEZAWA Hiroyuki 		goto scan; /* check next one */
862c9e44410SKAMEZAWA Hiroyuki 	}
863c9e44410SKAMEZAWA Hiroyuki 
864235b6217SHuang, Ying 	if (si->swap_map[offset]) {
865235b6217SHuang, Ying 		unlock_cluster(ci);
86636005baeSTim Chen 		if (!n_ret)
867ebebbbe9SHugh Dickins 			goto scan;
86836005baeSTim Chen 		else
86936005baeSTim Chen 			goto done;
870235b6217SHuang, Ying 	}
8712872bb2dSHuang Ying 	si->swap_map[offset] = usage;
8722872bb2dSHuang Ying 	inc_cluster_info_page(si, si->cluster_info, offset);
8732872bb2dSHuang Ying 	unlock_cluster(ci);
874ebebbbe9SHugh Dickins 
87538d8b4e6SHuang Ying 	swap_range_alloc(si, offset, 1);
87636005baeSTim Chen 	slots[n_ret++] = swp_entry(si->type, offset);
8777992fde7SHugh Dickins 
87836005baeSTim Chen 	/* got enough slots or reach max slots? */
87936005baeSTim Chen 	if ((n_ret == nr) || (offset >= si->highest_bit))
88036005baeSTim Chen 		goto done;
88136005baeSTim Chen 
88236005baeSTim Chen 	/* search for next available slot */
88336005baeSTim Chen 
88436005baeSTim Chen 	/* time to take a break? */
88536005baeSTim Chen 	if (unlikely(--latency_ration < 0)) {
88636005baeSTim Chen 		if (n_ret)
88736005baeSTim Chen 			goto done;
88836005baeSTim Chen 		spin_unlock(&si->lock);
88936005baeSTim Chen 		cond_resched();
89036005baeSTim Chen 		spin_lock(&si->lock);
89136005baeSTim Chen 		latency_ration = LATENCY_LIMIT;
89236005baeSTim Chen 	}
89336005baeSTim Chen 
89436005baeSTim Chen 	/* try to get more slots in cluster */
89536005baeSTim Chen 	if (si->cluster_info) {
89636005baeSTim Chen 		if (scan_swap_map_try_ssd_cluster(si, &offset, &scan_base))
89736005baeSTim Chen 			goto checks;
898f4eaf51aSWei Yang 	} else if (si->cluster_nr && !si->swap_map[++offset]) {
89936005baeSTim Chen 		/* non-ssd case, still more slots in cluster? */
90036005baeSTim Chen 		--si->cluster_nr;
90136005baeSTim Chen 		goto checks;
90236005baeSTim Chen 	}
90336005baeSTim Chen 
904ed43af10SHuang Ying 	/*
905ed43af10SHuang Ying 	 * Even if there's no free clusters available (fragmented),
906ed43af10SHuang Ying 	 * try to scan a little more quickly with lock held unless we
907ed43af10SHuang Ying 	 * have scanned too many slots already.
908ed43af10SHuang Ying 	 */
909ed43af10SHuang Ying 	if (!scanned_many) {
910ed43af10SHuang Ying 		unsigned long scan_limit;
911ed43af10SHuang Ying 
912ed43af10SHuang Ying 		if (offset < scan_base)
913ed43af10SHuang Ying 			scan_limit = scan_base;
914ed43af10SHuang Ying 		else
915ed43af10SHuang Ying 			scan_limit = si->highest_bit;
916ed43af10SHuang Ying 		for (; offset <= scan_limit && --latency_ration > 0;
917ed43af10SHuang Ying 		     offset++) {
918ed43af10SHuang Ying 			if (!si->swap_map[offset])
919ed43af10SHuang Ying 				goto checks;
920ed43af10SHuang Ying 		}
921ed43af10SHuang Ying 	}
922ed43af10SHuang Ying 
92336005baeSTim Chen done:
92449070588SHuang Ying 	set_cluster_next(si, offset + 1);
92536005baeSTim Chen 	si->flags -= SWP_SCANNING;
92636005baeSTim Chen 	return n_ret;
9277dfad418SHugh Dickins 
928ebebbbe9SHugh Dickins scan:
929ec8acf20SShaohua Li 	spin_unlock(&si->lock);
9307dfad418SHugh Dickins 	while (++offset <= si->highest_bit) {
93152b7efdbSHugh Dickins 		if (!si->swap_map[offset]) {
932ec8acf20SShaohua Li 			spin_lock(&si->lock);
93352b7efdbSHugh Dickins 			goto checks;
9347dfad418SHugh Dickins 		}
935c9e44410SKAMEZAWA Hiroyuki 		if (vm_swap_full() && si->swap_map[offset] == SWAP_HAS_CACHE) {
936ec8acf20SShaohua Li 			spin_lock(&si->lock);
937c9e44410SKAMEZAWA Hiroyuki 			goto checks;
938c9e44410SKAMEZAWA Hiroyuki 		}
939048c27fdSHugh Dickins 		if (unlikely(--latency_ration < 0)) {
940048c27fdSHugh Dickins 			cond_resched();
941048c27fdSHugh Dickins 			latency_ration = LATENCY_LIMIT;
942ed43af10SHuang Ying 			scanned_many = true;
943048c27fdSHugh Dickins 		}
94452b7efdbSHugh Dickins 	}
945c60aa176SHugh Dickins 	offset = si->lowest_bit;
946a5998061SJamie Liu 	while (offset < scan_base) {
947c60aa176SHugh Dickins 		if (!si->swap_map[offset]) {
948ec8acf20SShaohua Li 			spin_lock(&si->lock);
949ebebbbe9SHugh Dickins 			goto checks;
950c60aa176SHugh Dickins 		}
951c9e44410SKAMEZAWA Hiroyuki 		if (vm_swap_full() && si->swap_map[offset] == SWAP_HAS_CACHE) {
952ec8acf20SShaohua Li 			spin_lock(&si->lock);
953c9e44410SKAMEZAWA Hiroyuki 			goto checks;
954c9e44410SKAMEZAWA Hiroyuki 		}
955c60aa176SHugh Dickins 		if (unlikely(--latency_ration < 0)) {
956c60aa176SHugh Dickins 			cond_resched();
957c60aa176SHugh Dickins 			latency_ration = LATENCY_LIMIT;
958ed43af10SHuang Ying 			scanned_many = true;
959c60aa176SHugh Dickins 		}
960a5998061SJamie Liu 		offset++;
961c60aa176SHugh Dickins 	}
962ec8acf20SShaohua Li 	spin_lock(&si->lock);
9637dfad418SHugh Dickins 
9647dfad418SHugh Dickins no_page:
96552b7efdbSHugh Dickins 	si->flags -= SWP_SCANNING;
96636005baeSTim Chen 	return n_ret;
9671da177e4SLinus Torvalds }
9681da177e4SLinus Torvalds 
96938d8b4e6SHuang Ying static int swap_alloc_cluster(struct swap_info_struct *si, swp_entry_t *slot)
97038d8b4e6SHuang Ying {
97138d8b4e6SHuang Ying 	unsigned long idx;
97238d8b4e6SHuang Ying 	struct swap_cluster_info *ci;
97338d8b4e6SHuang Ying 	unsigned long offset, i;
97438d8b4e6SHuang Ying 	unsigned char *map;
97538d8b4e6SHuang Ying 
976fe5266d5SHuang Ying 	/*
977fe5266d5SHuang Ying 	 * Should not even be attempting cluster allocations when huge
978fe5266d5SHuang Ying 	 * page swap is disabled.  Warn and fail the allocation.
979fe5266d5SHuang Ying 	 */
980fe5266d5SHuang Ying 	if (!IS_ENABLED(CONFIG_THP_SWAP)) {
981fe5266d5SHuang Ying 		VM_WARN_ON_ONCE(1);
982fe5266d5SHuang Ying 		return 0;
983fe5266d5SHuang Ying 	}
984fe5266d5SHuang Ying 
98538d8b4e6SHuang Ying 	if (cluster_list_empty(&si->free_clusters))
98638d8b4e6SHuang Ying 		return 0;
98738d8b4e6SHuang Ying 
98838d8b4e6SHuang Ying 	idx = cluster_list_first(&si->free_clusters);
98938d8b4e6SHuang Ying 	offset = idx * SWAPFILE_CLUSTER;
99038d8b4e6SHuang Ying 	ci = lock_cluster(si, offset);
99138d8b4e6SHuang Ying 	alloc_cluster(si, idx);
992e0709829SHuang Ying 	cluster_set_count_flag(ci, SWAPFILE_CLUSTER, CLUSTER_FLAG_HUGE);
99338d8b4e6SHuang Ying 
99438d8b4e6SHuang Ying 	map = si->swap_map + offset;
99538d8b4e6SHuang Ying 	for (i = 0; i < SWAPFILE_CLUSTER; i++)
99638d8b4e6SHuang Ying 		map[i] = SWAP_HAS_CACHE;
99738d8b4e6SHuang Ying 	unlock_cluster(ci);
99838d8b4e6SHuang Ying 	swap_range_alloc(si, offset, SWAPFILE_CLUSTER);
99938d8b4e6SHuang Ying 	*slot = swp_entry(si->type, offset);
100038d8b4e6SHuang Ying 
100138d8b4e6SHuang Ying 	return 1;
100238d8b4e6SHuang Ying }
100338d8b4e6SHuang Ying 
100438d8b4e6SHuang Ying static void swap_free_cluster(struct swap_info_struct *si, unsigned long idx)
100538d8b4e6SHuang Ying {
100638d8b4e6SHuang Ying 	unsigned long offset = idx * SWAPFILE_CLUSTER;
100738d8b4e6SHuang Ying 	struct swap_cluster_info *ci;
100838d8b4e6SHuang Ying 
100938d8b4e6SHuang Ying 	ci = lock_cluster(si, offset);
1010979aafa5SHuang Ying 	memset(si->swap_map + offset, 0, SWAPFILE_CLUSTER);
101138d8b4e6SHuang Ying 	cluster_set_count_flag(ci, 0, 0);
101238d8b4e6SHuang Ying 	free_cluster(si, idx);
101338d8b4e6SHuang Ying 	unlock_cluster(ci);
101438d8b4e6SHuang Ying 	swap_range_free(si, offset, SWAPFILE_CLUSTER);
101538d8b4e6SHuang Ying }
101638d8b4e6SHuang Ying 
101736005baeSTim Chen static unsigned long scan_swap_map(struct swap_info_struct *si,
101836005baeSTim Chen 				   unsigned char usage)
101936005baeSTim Chen {
102036005baeSTim Chen 	swp_entry_t entry;
102136005baeSTim Chen 	int n_ret;
102236005baeSTim Chen 
102336005baeSTim Chen 	n_ret = scan_swap_map_slots(si, usage, 1, &entry);
102436005baeSTim Chen 
102536005baeSTim Chen 	if (n_ret)
102636005baeSTim Chen 		return swp_offset(entry);
102736005baeSTim Chen 	else
102836005baeSTim Chen 		return 0;
102936005baeSTim Chen 
103036005baeSTim Chen }
103136005baeSTim Chen 
10325d5e8f19SHuang Ying int get_swap_pages(int n_goal, swp_entry_t swp_entries[], int entry_size)
10331da177e4SLinus Torvalds {
10345d5e8f19SHuang Ying 	unsigned long size = swap_entry_size(entry_size);
1035adfab836SDan Streetman 	struct swap_info_struct *si, *next;
103636005baeSTim Chen 	long avail_pgs;
103736005baeSTim Chen 	int n_ret = 0;
1038a2468cc9SAaron Lu 	int node;
10391da177e4SLinus Torvalds 
104038d8b4e6SHuang Ying 	/* Only single cluster request supported */
10415d5e8f19SHuang Ying 	WARN_ON_ONCE(n_goal > 1 && size == SWAPFILE_CLUSTER);
104238d8b4e6SHuang Ying 
10435d5e8f19SHuang Ying 	avail_pgs = atomic_long_read(&nr_swap_pages) / size;
104436005baeSTim Chen 	if (avail_pgs <= 0)
1045fb4f88dcSHugh Dickins 		goto noswap;
104636005baeSTim Chen 
104708d3090fSWei Yang 	n_goal = min3((long)n_goal, (long)SWAP_BATCH, avail_pgs);
104836005baeSTim Chen 
10495d5e8f19SHuang Ying 	atomic_long_sub(n_goal * size, &nr_swap_pages);
10501da177e4SLinus Torvalds 
105118ab4d4cSDan Streetman 	spin_lock(&swap_avail_lock);
105218ab4d4cSDan Streetman 
105318ab4d4cSDan Streetman start_over:
1054a2468cc9SAaron Lu 	node = numa_node_id();
1055a2468cc9SAaron Lu 	plist_for_each_entry_safe(si, next, &swap_avail_heads[node], avail_lists[node]) {
105618ab4d4cSDan Streetman 		/* requeue si to after same-priority siblings */
1057a2468cc9SAaron Lu 		plist_requeue(&si->avail_lists[node], &swap_avail_heads[node]);
105818ab4d4cSDan Streetman 		spin_unlock(&swap_avail_lock);
1059ec8acf20SShaohua Li 		spin_lock(&si->lock);
1060adfab836SDan Streetman 		if (!si->highest_bit || !(si->flags & SWP_WRITEOK)) {
106118ab4d4cSDan Streetman 			spin_lock(&swap_avail_lock);
1062a2468cc9SAaron Lu 			if (plist_node_empty(&si->avail_lists[node])) {
1063ec8acf20SShaohua Li 				spin_unlock(&si->lock);
106418ab4d4cSDan Streetman 				goto nextsi;
106518ab4d4cSDan Streetman 			}
106618ab4d4cSDan Streetman 			WARN(!si->highest_bit,
106718ab4d4cSDan Streetman 			     "swap_info %d in list but !highest_bit\n",
106818ab4d4cSDan Streetman 			     si->type);
106918ab4d4cSDan Streetman 			WARN(!(si->flags & SWP_WRITEOK),
107018ab4d4cSDan Streetman 			     "swap_info %d in list but !SWP_WRITEOK\n",
107118ab4d4cSDan Streetman 			     si->type);
1072a2468cc9SAaron Lu 			__del_from_avail_list(si);
107318ab4d4cSDan Streetman 			spin_unlock(&si->lock);
107418ab4d4cSDan Streetman 			goto nextsi;
1075ec8acf20SShaohua Li 		}
10765d5e8f19SHuang Ying 		if (size == SWAPFILE_CLUSTER) {
1077bc4ae27dSOmar Sandoval 			if (!(si->flags & SWP_FS))
107838d8b4e6SHuang Ying 				n_ret = swap_alloc_cluster(si, swp_entries);
1079f0eea189SHuang Ying 		} else
108036005baeSTim Chen 			n_ret = scan_swap_map_slots(si, SWAP_HAS_CACHE,
108136005baeSTim Chen 						    n_goal, swp_entries);
1082ec8acf20SShaohua Li 		spin_unlock(&si->lock);
10835d5e8f19SHuang Ying 		if (n_ret || size == SWAPFILE_CLUSTER)
108436005baeSTim Chen 			goto check_out;
108518ab4d4cSDan Streetman 		pr_debug("scan_swap_map of si %d failed to find offset\n",
108618ab4d4cSDan Streetman 			si->type);
108736005baeSTim Chen 
108818ab4d4cSDan Streetman 		spin_lock(&swap_avail_lock);
108918ab4d4cSDan Streetman nextsi:
1090adfab836SDan Streetman 		/*
1091adfab836SDan Streetman 		 * if we got here, it's likely that si was almost full before,
1092adfab836SDan Streetman 		 * and since scan_swap_map() can drop the si->lock, multiple
1093adfab836SDan Streetman 		 * callers probably all tried to get a page from the same si
109418ab4d4cSDan Streetman 		 * and it filled up before we could get one; or, the si filled
109518ab4d4cSDan Streetman 		 * up between us dropping swap_avail_lock and taking si->lock.
109618ab4d4cSDan Streetman 		 * Since we dropped the swap_avail_lock, the swap_avail_head
109718ab4d4cSDan Streetman 		 * list may have been modified; so if next is still in the
109836005baeSTim Chen 		 * swap_avail_head list then try it, otherwise start over
109936005baeSTim Chen 		 * if we have not gotten any slots.
1100adfab836SDan Streetman 		 */
1101a2468cc9SAaron Lu 		if (plist_node_empty(&next->avail_lists[node]))
110218ab4d4cSDan Streetman 			goto start_over;
1103fb4f88dcSHugh Dickins 	}
1104fb4f88dcSHugh Dickins 
110518ab4d4cSDan Streetman 	spin_unlock(&swap_avail_lock);
110618ab4d4cSDan Streetman 
110736005baeSTim Chen check_out:
110836005baeSTim Chen 	if (n_ret < n_goal)
11095d5e8f19SHuang Ying 		atomic_long_add((long)(n_goal - n_ret) * size,
111038d8b4e6SHuang Ying 				&nr_swap_pages);
1111fb4f88dcSHugh Dickins noswap:
111236005baeSTim Chen 	return n_ret;
111336005baeSTim Chen }
111436005baeSTim Chen 
11152de1a7e4SSeth Jennings /* The only caller of this function is now suspend routine */
1116910321eaSHugh Dickins swp_entry_t get_swap_page_of_type(int type)
1117910321eaSHugh Dickins {
1118c10d38ccSDaniel Jordan 	struct swap_info_struct *si = swap_type_to_swap_info(type);
1119910321eaSHugh Dickins 	pgoff_t offset;
1120910321eaSHugh Dickins 
1121c10d38ccSDaniel Jordan 	if (!si)
1122c10d38ccSDaniel Jordan 		goto fail;
1123c10d38ccSDaniel Jordan 
1124ec8acf20SShaohua Li 	spin_lock(&si->lock);
1125c10d38ccSDaniel Jordan 	if (si->flags & SWP_WRITEOK) {
1126ec8acf20SShaohua Li 		atomic_long_dec(&nr_swap_pages);
1127910321eaSHugh Dickins 		/* This is called for allocating swap entry, not cache */
1128910321eaSHugh Dickins 		offset = scan_swap_map(si, 1);
1129910321eaSHugh Dickins 		if (offset) {
1130ec8acf20SShaohua Li 			spin_unlock(&si->lock);
1131910321eaSHugh Dickins 			return swp_entry(type, offset);
1132910321eaSHugh Dickins 		}
1133ec8acf20SShaohua Li 		atomic_long_inc(&nr_swap_pages);
1134910321eaSHugh Dickins 	}
1135ec8acf20SShaohua Li 	spin_unlock(&si->lock);
1136c10d38ccSDaniel Jordan fail:
1137910321eaSHugh Dickins 	return (swp_entry_t) {0};
1138910321eaSHugh Dickins }
1139910321eaSHugh Dickins 
1140e8c26ab6STim Chen static struct swap_info_struct *__swap_info_get(swp_entry_t entry)
11411da177e4SLinus Torvalds {
11421da177e4SLinus Torvalds 	struct swap_info_struct *p;
1143eb085574SHuang Ying 	unsigned long offset;
11441da177e4SLinus Torvalds 
11451da177e4SLinus Torvalds 	if (!entry.val)
11461da177e4SLinus Torvalds 		goto out;
1147eb085574SHuang Ying 	p = swp_swap_info(entry);
1148c10d38ccSDaniel Jordan 	if (!p)
11491da177e4SLinus Torvalds 		goto bad_nofile;
11501da177e4SLinus Torvalds 	if (!(p->flags & SWP_USED))
11511da177e4SLinus Torvalds 		goto bad_device;
11521da177e4SLinus Torvalds 	offset = swp_offset(entry);
11531da177e4SLinus Torvalds 	if (offset >= p->max)
11541da177e4SLinus Torvalds 		goto bad_offset;
11551da177e4SLinus Torvalds 	return p;
11561da177e4SLinus Torvalds 
11571da177e4SLinus Torvalds bad_offset:
11586a991fc7SHuang, Ying 	pr_err("swap_info_get: %s%08lx\n", Bad_offset, entry.val);
11591da177e4SLinus Torvalds 	goto out;
11601da177e4SLinus Torvalds bad_device:
11616a991fc7SHuang, Ying 	pr_err("swap_info_get: %s%08lx\n", Unused_file, entry.val);
11621da177e4SLinus Torvalds 	goto out;
11631da177e4SLinus Torvalds bad_nofile:
11646a991fc7SHuang, Ying 	pr_err("swap_info_get: %s%08lx\n", Bad_file, entry.val);
11651da177e4SLinus Torvalds out:
11661da177e4SLinus Torvalds 	return NULL;
11671da177e4SLinus Torvalds }
11681da177e4SLinus Torvalds 
1169e8c26ab6STim Chen static struct swap_info_struct *_swap_info_get(swp_entry_t entry)
1170e8c26ab6STim Chen {
1171e8c26ab6STim Chen 	struct swap_info_struct *p;
1172e8c26ab6STim Chen 
1173e8c26ab6STim Chen 	p = __swap_info_get(entry);
1174e8c26ab6STim Chen 	if (!p)
1175e8c26ab6STim Chen 		goto out;
1176e8c26ab6STim Chen 	if (!p->swap_map[swp_offset(entry)])
1177e8c26ab6STim Chen 		goto bad_free;
1178e8c26ab6STim Chen 	return p;
1179e8c26ab6STim Chen 
1180e8c26ab6STim Chen bad_free:
1181e8c26ab6STim Chen 	pr_err("swap_info_get: %s%08lx\n", Unused_offset, entry.val);
1182e8c26ab6STim Chen 	goto out;
1183e8c26ab6STim Chen out:
1184e8c26ab6STim Chen 	return NULL;
1185e8c26ab6STim Chen }
1186e8c26ab6STim Chen 
1187235b6217SHuang, Ying static struct swap_info_struct *swap_info_get(swp_entry_t entry)
11881da177e4SLinus Torvalds {
1189235b6217SHuang, Ying 	struct swap_info_struct *p;
1190235b6217SHuang, Ying 
1191235b6217SHuang, Ying 	p = _swap_info_get(entry);
1192235b6217SHuang, Ying 	if (p)
1193235b6217SHuang, Ying 		spin_lock(&p->lock);
1194235b6217SHuang, Ying 	return p;
1195235b6217SHuang, Ying }
1196235b6217SHuang, Ying 
11977c00bafeSTim Chen static struct swap_info_struct *swap_info_get_cont(swp_entry_t entry,
11987c00bafeSTim Chen 					struct swap_info_struct *q)
11997c00bafeSTim Chen {
12007c00bafeSTim Chen 	struct swap_info_struct *p;
12017c00bafeSTim Chen 
12027c00bafeSTim Chen 	p = _swap_info_get(entry);
12037c00bafeSTim Chen 
12047c00bafeSTim Chen 	if (p != q) {
12057c00bafeSTim Chen 		if (q != NULL)
12067c00bafeSTim Chen 			spin_unlock(&q->lock);
12077c00bafeSTim Chen 		if (p != NULL)
12087c00bafeSTim Chen 			spin_lock(&p->lock);
12097c00bafeSTim Chen 	}
12107c00bafeSTim Chen 	return p;
12117c00bafeSTim Chen }
12127c00bafeSTim Chen 
1213b32d5f32SHuang Ying static unsigned char __swap_entry_free_locked(struct swap_info_struct *p,
1214b32d5f32SHuang Ying 					      unsigned long offset,
1215b32d5f32SHuang Ying 					      unsigned char usage)
1216235b6217SHuang, Ying {
12178d69aaeeSHugh Dickins 	unsigned char count;
12188d69aaeeSHugh Dickins 	unsigned char has_cache;
1219235b6217SHuang, Ying 
1220355cfa73SKAMEZAWA Hiroyuki 	count = p->swap_map[offset];
1221235b6217SHuang, Ying 
1222253d553bSHugh Dickins 	has_cache = count & SWAP_HAS_CACHE;
1223253d553bSHugh Dickins 	count &= ~SWAP_HAS_CACHE;
1224253d553bSHugh Dickins 
1225253d553bSHugh Dickins 	if (usage == SWAP_HAS_CACHE) {
1226253d553bSHugh Dickins 		VM_BUG_ON(!has_cache);
1227253d553bSHugh Dickins 		has_cache = 0;
1228aaa46865SHugh Dickins 	} else if (count == SWAP_MAP_SHMEM) {
1229aaa46865SHugh Dickins 		/*
1230aaa46865SHugh Dickins 		 * Or we could insist on shmem.c using a special
1231aaa46865SHugh Dickins 		 * swap_shmem_free() and free_shmem_swap_and_cache()...
1232aaa46865SHugh Dickins 		 */
1233aaa46865SHugh Dickins 		count = 0;
1234570a335bSHugh Dickins 	} else if ((count & ~COUNT_CONTINUED) <= SWAP_MAP_MAX) {
1235570a335bSHugh Dickins 		if (count == COUNT_CONTINUED) {
1236570a335bSHugh Dickins 			if (swap_count_continued(p, offset, count))
1237570a335bSHugh Dickins 				count = SWAP_MAP_MAX | COUNT_CONTINUED;
1238570a335bSHugh Dickins 			else
1239570a335bSHugh Dickins 				count = SWAP_MAP_MAX;
1240570a335bSHugh Dickins 		} else
1241253d553bSHugh Dickins 			count--;
1242570a335bSHugh Dickins 	}
1243253d553bSHugh Dickins 
1244253d553bSHugh Dickins 	usage = count | has_cache;
12457c00bafeSTim Chen 	p->swap_map[offset] = usage ? : SWAP_HAS_CACHE;
1246253d553bSHugh Dickins 
1247b32d5f32SHuang Ying 	return usage;
1248b32d5f32SHuang Ying }
1249b32d5f32SHuang Ying 
1250eb085574SHuang Ying /*
1251eb085574SHuang Ying  * Check whether swap entry is valid in the swap device.  If so,
1252eb085574SHuang Ying  * return pointer to swap_info_struct, and keep the swap entry valid
1253eb085574SHuang Ying  * via preventing the swap device from being swapoff, until
1254eb085574SHuang Ying  * put_swap_device() is called.  Otherwise return NULL.
1255eb085574SHuang Ying  *
1256eb085574SHuang Ying  * The entirety of the RCU read critical section must come before the
1257eb085574SHuang Ying  * return from or after the call to synchronize_rcu() in
1258eb085574SHuang Ying  * enable_swap_info() or swapoff().  So if "si->flags & SWP_VALID" is
1259eb085574SHuang Ying  * true, the si->map, si->cluster_info, etc. must be valid in the
1260eb085574SHuang Ying  * critical section.
1261eb085574SHuang Ying  *
1262eb085574SHuang Ying  * Notice that swapoff or swapoff+swapon can still happen before the
1263eb085574SHuang Ying  * rcu_read_lock() in get_swap_device() or after the rcu_read_unlock()
1264eb085574SHuang Ying  * in put_swap_device() if there isn't any other way to prevent
1265eb085574SHuang Ying  * swapoff, such as page lock, page table lock, etc.  The caller must
1266eb085574SHuang Ying  * be prepared for that.  For example, the following situation is
1267eb085574SHuang Ying  * possible.
1268eb085574SHuang Ying  *
1269eb085574SHuang Ying  *   CPU1				CPU2
1270eb085574SHuang Ying  *   do_swap_page()
1271eb085574SHuang Ying  *     ...				swapoff+swapon
1272eb085574SHuang Ying  *     __read_swap_cache_async()
1273eb085574SHuang Ying  *       swapcache_prepare()
1274eb085574SHuang Ying  *         __swap_duplicate()
1275eb085574SHuang Ying  *           // check swap_map
1276eb085574SHuang Ying  *     // verify PTE not changed
1277eb085574SHuang Ying  *
1278eb085574SHuang Ying  * In __swap_duplicate(), the swap_map need to be checked before
1279eb085574SHuang Ying  * changing partly because the specified swap entry may be for another
1280eb085574SHuang Ying  * swap device which has been swapoff.  And in do_swap_page(), after
1281eb085574SHuang Ying  * the page is read from the swap device, the PTE is verified not
1282eb085574SHuang Ying  * changed with the page table locked to check whether the swap device
1283eb085574SHuang Ying  * has been swapoff or swapoff+swapon.
1284eb085574SHuang Ying  */
1285eb085574SHuang Ying struct swap_info_struct *get_swap_device(swp_entry_t entry)
1286eb085574SHuang Ying {
1287eb085574SHuang Ying 	struct swap_info_struct *si;
1288eb085574SHuang Ying 	unsigned long offset;
1289eb085574SHuang Ying 
1290eb085574SHuang Ying 	if (!entry.val)
1291eb085574SHuang Ying 		goto out;
1292eb085574SHuang Ying 	si = swp_swap_info(entry);
1293eb085574SHuang Ying 	if (!si)
1294eb085574SHuang Ying 		goto bad_nofile;
1295eb085574SHuang Ying 
1296eb085574SHuang Ying 	rcu_read_lock();
1297eb085574SHuang Ying 	if (!(si->flags & SWP_VALID))
1298eb085574SHuang Ying 		goto unlock_out;
1299eb085574SHuang Ying 	offset = swp_offset(entry);
1300eb085574SHuang Ying 	if (offset >= si->max)
1301eb085574SHuang Ying 		goto unlock_out;
1302eb085574SHuang Ying 
1303eb085574SHuang Ying 	return si;
1304eb085574SHuang Ying bad_nofile:
1305eb085574SHuang Ying 	pr_err("%s: %s%08lx\n", __func__, Bad_file, entry.val);
1306eb085574SHuang Ying out:
1307eb085574SHuang Ying 	return NULL;
1308eb085574SHuang Ying unlock_out:
1309eb085574SHuang Ying 	rcu_read_unlock();
1310eb085574SHuang Ying 	return NULL;
1311eb085574SHuang Ying }
1312eb085574SHuang Ying 
1313b32d5f32SHuang Ying static unsigned char __swap_entry_free(struct swap_info_struct *p,
131433e16272SWei Yang 				       swp_entry_t entry)
1315b32d5f32SHuang Ying {
1316b32d5f32SHuang Ying 	struct swap_cluster_info *ci;
1317b32d5f32SHuang Ying 	unsigned long offset = swp_offset(entry);
131833e16272SWei Yang 	unsigned char usage;
1319b32d5f32SHuang Ying 
1320b32d5f32SHuang Ying 	ci = lock_cluster_or_swap_info(p, offset);
132133e16272SWei Yang 	usage = __swap_entry_free_locked(p, offset, 1);
13227c00bafeSTim Chen 	unlock_cluster_or_swap_info(p, ci);
132310e364daSHuang Ying 	if (!usage)
132410e364daSHuang Ying 		free_swap_slot(entry);
1325235b6217SHuang, Ying 
13267c00bafeSTim Chen 	return usage;
13277c00bafeSTim Chen }
13287c00bafeSTim Chen 
13297c00bafeSTim Chen static void swap_entry_free(struct swap_info_struct *p, swp_entry_t entry)
13307c00bafeSTim Chen {
13317c00bafeSTim Chen 	struct swap_cluster_info *ci;
13327c00bafeSTim Chen 	unsigned long offset = swp_offset(entry);
13337c00bafeSTim Chen 	unsigned char count;
13347c00bafeSTim Chen 
1335235b6217SHuang, Ying 	ci = lock_cluster(p, offset);
13367c00bafeSTim Chen 	count = p->swap_map[offset];
13377c00bafeSTim Chen 	VM_BUG_ON(count != SWAP_HAS_CACHE);
13387c00bafeSTim Chen 	p->swap_map[offset] = 0;
13392a8f9449SShaohua Li 	dec_cluster_info_page(p, p->cluster_info, offset);
1340235b6217SHuang, Ying 	unlock_cluster(ci);
13417c00bafeSTim Chen 
134238d8b4e6SHuang Ying 	mem_cgroup_uncharge_swap(entry, 1);
134338d8b4e6SHuang Ying 	swap_range_free(p, offset, 1);
13441da177e4SLinus Torvalds }
1345253d553bSHugh Dickins 
13461da177e4SLinus Torvalds /*
13471da177e4SLinus Torvalds  * Caller has made sure that the swap device corresponding to entry
13481da177e4SLinus Torvalds  * is still around or has not been recycled.
13491da177e4SLinus Torvalds  */
13501da177e4SLinus Torvalds void swap_free(swp_entry_t entry)
13511da177e4SLinus Torvalds {
13521da177e4SLinus Torvalds 	struct swap_info_struct *p;
13531da177e4SLinus Torvalds 
1354235b6217SHuang, Ying 	p = _swap_info_get(entry);
135510e364daSHuang Ying 	if (p)
135633e16272SWei Yang 		__swap_entry_free(p, entry);
13571da177e4SLinus Torvalds }
13581da177e4SLinus Torvalds 
13591da177e4SLinus Torvalds /*
1360cb4b86baSKAMEZAWA Hiroyuki  * Called after dropping swapcache to decrease refcnt to swap entries.
1361cb4b86baSKAMEZAWA Hiroyuki  */
1362a448f2d0SHuang Ying void put_swap_page(struct page *page, swp_entry_t entry)
136338d8b4e6SHuang Ying {
136438d8b4e6SHuang Ying 	unsigned long offset = swp_offset(entry);
136538d8b4e6SHuang Ying 	unsigned long idx = offset / SWAPFILE_CLUSTER;
136638d8b4e6SHuang Ying 	struct swap_cluster_info *ci;
136738d8b4e6SHuang Ying 	struct swap_info_struct *si;
136838d8b4e6SHuang Ying 	unsigned char *map;
1369a3aea839SHuang Ying 	unsigned int i, free_entries = 0;
1370a3aea839SHuang Ying 	unsigned char val;
1371a448f2d0SHuang Ying 	int size = swap_entry_size(hpage_nr_pages(page));
1372fe5266d5SHuang Ying 
1373a3aea839SHuang Ying 	si = _swap_info_get(entry);
137438d8b4e6SHuang Ying 	if (!si)
137538d8b4e6SHuang Ying 		return;
137638d8b4e6SHuang Ying 
1377c2343d27SHuang Ying 	ci = lock_cluster_or_swap_info(si, offset);
1378a448f2d0SHuang Ying 	if (size == SWAPFILE_CLUSTER) {
1379e0709829SHuang Ying 		VM_BUG_ON(!cluster_is_huge(ci));
138038d8b4e6SHuang Ying 		map = si->swap_map + offset;
138138d8b4e6SHuang Ying 		for (i = 0; i < SWAPFILE_CLUSTER; i++) {
1382a3aea839SHuang Ying 			val = map[i];
1383a3aea839SHuang Ying 			VM_BUG_ON(!(val & SWAP_HAS_CACHE));
1384a3aea839SHuang Ying 			if (val == SWAP_HAS_CACHE)
1385a3aea839SHuang Ying 				free_entries++;
138638d8b4e6SHuang Ying 		}
1387e0709829SHuang Ying 		cluster_clear_huge(ci);
1388a3aea839SHuang Ying 		if (free_entries == SWAPFILE_CLUSTER) {
1389c2343d27SHuang Ying 			unlock_cluster_or_swap_info(si, ci);
1390a3aea839SHuang Ying 			spin_lock(&si->lock);
139138d8b4e6SHuang Ying 			mem_cgroup_uncharge_swap(entry, SWAPFILE_CLUSTER);
139238d8b4e6SHuang Ying 			swap_free_cluster(si, idx);
139338d8b4e6SHuang Ying 			spin_unlock(&si->lock);
1394a448f2d0SHuang Ying 			return;
1395a448f2d0SHuang Ying 		}
1396a448f2d0SHuang Ying 	}
1397a448f2d0SHuang Ying 	for (i = 0; i < size; i++, entry.val++) {
1398c2343d27SHuang Ying 		if (!__swap_entry_free_locked(si, offset + i, SWAP_HAS_CACHE)) {
1399c2343d27SHuang Ying 			unlock_cluster_or_swap_info(si, ci);
1400a3aea839SHuang Ying 			free_swap_slot(entry);
1401c2343d27SHuang Ying 			if (i == size - 1)
1402c2343d27SHuang Ying 				return;
1403c2343d27SHuang Ying 			lock_cluster_or_swap_info(si, offset);
1404a3aea839SHuang Ying 		}
1405a3aea839SHuang Ying 	}
1406c2343d27SHuang Ying 	unlock_cluster_or_swap_info(si, ci);
140738d8b4e6SHuang Ying }
140859807685SHuang Ying 
1409fe5266d5SHuang Ying #ifdef CONFIG_THP_SWAP
141059807685SHuang Ying int split_swap_cluster(swp_entry_t entry)
141159807685SHuang Ying {
141259807685SHuang Ying 	struct swap_info_struct *si;
141359807685SHuang Ying 	struct swap_cluster_info *ci;
141459807685SHuang Ying 	unsigned long offset = swp_offset(entry);
141559807685SHuang Ying 
141659807685SHuang Ying 	si = _swap_info_get(entry);
141759807685SHuang Ying 	if (!si)
141859807685SHuang Ying 		return -EBUSY;
141959807685SHuang Ying 	ci = lock_cluster(si, offset);
142059807685SHuang Ying 	cluster_clear_huge(ci);
142159807685SHuang Ying 	unlock_cluster(ci);
142259807685SHuang Ying 	return 0;
142359807685SHuang Ying }
1424fe5266d5SHuang Ying #endif
142538d8b4e6SHuang Ying 
1426155b5f88SHuang Ying static int swp_entry_cmp(const void *ent1, const void *ent2)
1427155b5f88SHuang Ying {
1428155b5f88SHuang Ying 	const swp_entry_t *e1 = ent1, *e2 = ent2;
1429155b5f88SHuang Ying 
1430155b5f88SHuang Ying 	return (int)swp_type(*e1) - (int)swp_type(*e2);
1431155b5f88SHuang Ying }
1432155b5f88SHuang Ying 
14337c00bafeSTim Chen void swapcache_free_entries(swp_entry_t *entries, int n)
14347c00bafeSTim Chen {
14357c00bafeSTim Chen 	struct swap_info_struct *p, *prev;
14367c00bafeSTim Chen 	int i;
14377c00bafeSTim Chen 
14387c00bafeSTim Chen 	if (n <= 0)
14397c00bafeSTim Chen 		return;
14407c00bafeSTim Chen 
14417c00bafeSTim Chen 	prev = NULL;
14427c00bafeSTim Chen 	p = NULL;
1443155b5f88SHuang Ying 
1444155b5f88SHuang Ying 	/*
1445155b5f88SHuang Ying 	 * Sort swap entries by swap device, so each lock is only taken once.
1446155b5f88SHuang Ying 	 * nr_swapfiles isn't absolutely correct, but the overhead of sort() is
1447155b5f88SHuang Ying 	 * so low that it isn't necessary to optimize further.
1448155b5f88SHuang Ying 	 */
1449155b5f88SHuang Ying 	if (nr_swapfiles > 1)
1450155b5f88SHuang Ying 		sort(entries, n, sizeof(entries[0]), swp_entry_cmp, NULL);
14517c00bafeSTim Chen 	for (i = 0; i < n; ++i) {
14527c00bafeSTim Chen 		p = swap_info_get_cont(entries[i], prev);
1453235b6217SHuang, Ying 		if (p)
14547c00bafeSTim Chen 			swap_entry_free(p, entries[i]);
14557c00bafeSTim Chen 		prev = p;
14567c00bafeSTim Chen 	}
14577c00bafeSTim Chen 	if (p)
14587c00bafeSTim Chen 		spin_unlock(&p->lock);
1459cb4b86baSKAMEZAWA Hiroyuki }
1460cb4b86baSKAMEZAWA Hiroyuki 
1461cb4b86baSKAMEZAWA Hiroyuki /*
1462c475a8abSHugh Dickins  * How many references to page are currently swapped out?
1463570a335bSHugh Dickins  * This does not give an exact answer when swap count is continued,
1464570a335bSHugh Dickins  * but does include the high COUNT_CONTINUED flag to allow for that.
14651da177e4SLinus Torvalds  */
1466bde05d1cSHugh Dickins int page_swapcount(struct page *page)
14671da177e4SLinus Torvalds {
1468c475a8abSHugh Dickins 	int count = 0;
14691da177e4SLinus Torvalds 	struct swap_info_struct *p;
1470235b6217SHuang, Ying 	struct swap_cluster_info *ci;
14711da177e4SLinus Torvalds 	swp_entry_t entry;
1472235b6217SHuang, Ying 	unsigned long offset;
14731da177e4SLinus Torvalds 
14744c21e2f2SHugh Dickins 	entry.val = page_private(page);
1475235b6217SHuang, Ying 	p = _swap_info_get(entry);
14761da177e4SLinus Torvalds 	if (p) {
1477235b6217SHuang, Ying 		offset = swp_offset(entry);
1478235b6217SHuang, Ying 		ci = lock_cluster_or_swap_info(p, offset);
1479235b6217SHuang, Ying 		count = swap_count(p->swap_map[offset]);
1480235b6217SHuang, Ying 		unlock_cluster_or_swap_info(p, ci);
14811da177e4SLinus Torvalds 	}
1482c475a8abSHugh Dickins 	return count;
14831da177e4SLinus Torvalds }
14841da177e4SLinus Torvalds 
1485eb085574SHuang Ying int __swap_count(swp_entry_t entry)
1486aa8d22a1SMinchan Kim {
1487eb085574SHuang Ying 	struct swap_info_struct *si;
1488aa8d22a1SMinchan Kim 	pgoff_t offset = swp_offset(entry);
1489eb085574SHuang Ying 	int count = 0;
1490aa8d22a1SMinchan Kim 
1491eb085574SHuang Ying 	si = get_swap_device(entry);
1492eb085574SHuang Ying 	if (si) {
1493eb085574SHuang Ying 		count = swap_count(si->swap_map[offset]);
1494eb085574SHuang Ying 		put_swap_device(si);
1495eb085574SHuang Ying 	}
1496eb085574SHuang Ying 	return count;
1497aa8d22a1SMinchan Kim }
1498aa8d22a1SMinchan Kim 
1499322b8afeSHuang Ying static int swap_swapcount(struct swap_info_struct *si, swp_entry_t entry)
1500322b8afeSHuang Ying {
1501322b8afeSHuang Ying 	int count = 0;
1502322b8afeSHuang Ying 	pgoff_t offset = swp_offset(entry);
1503322b8afeSHuang Ying 	struct swap_cluster_info *ci;
1504322b8afeSHuang Ying 
1505322b8afeSHuang Ying 	ci = lock_cluster_or_swap_info(si, offset);
1506322b8afeSHuang Ying 	count = swap_count(si->swap_map[offset]);
1507322b8afeSHuang Ying 	unlock_cluster_or_swap_info(si, ci);
1508322b8afeSHuang Ying 	return count;
1509322b8afeSHuang Ying }
1510322b8afeSHuang Ying 
15111da177e4SLinus Torvalds /*
15128334b962SMinchan Kim  * How many references to @entry are currently swapped out?
1513e8c26ab6STim Chen  * This does not give an exact answer when swap count is continued,
1514e8c26ab6STim Chen  * but does include the high COUNT_CONTINUED flag to allow for that.
1515e8c26ab6STim Chen  */
1516e8c26ab6STim Chen int __swp_swapcount(swp_entry_t entry)
1517e8c26ab6STim Chen {
1518e8c26ab6STim Chen 	int count = 0;
1519e8c26ab6STim Chen 	struct swap_info_struct *si;
1520e8c26ab6STim Chen 
1521eb085574SHuang Ying 	si = get_swap_device(entry);
1522eb085574SHuang Ying 	if (si) {
1523322b8afeSHuang Ying 		count = swap_swapcount(si, entry);
1524eb085574SHuang Ying 		put_swap_device(si);
1525eb085574SHuang Ying 	}
1526e8c26ab6STim Chen 	return count;
1527e8c26ab6STim Chen }
1528e8c26ab6STim Chen 
1529e8c26ab6STim Chen /*
1530e8c26ab6STim Chen  * How many references to @entry are currently swapped out?
15318334b962SMinchan Kim  * This considers COUNT_CONTINUED so it returns exact answer.
15328334b962SMinchan Kim  */
15338334b962SMinchan Kim int swp_swapcount(swp_entry_t entry)
15348334b962SMinchan Kim {
15358334b962SMinchan Kim 	int count, tmp_count, n;
15368334b962SMinchan Kim 	struct swap_info_struct *p;
1537235b6217SHuang, Ying 	struct swap_cluster_info *ci;
15388334b962SMinchan Kim 	struct page *page;
15398334b962SMinchan Kim 	pgoff_t offset;
15408334b962SMinchan Kim 	unsigned char *map;
15418334b962SMinchan Kim 
1542235b6217SHuang, Ying 	p = _swap_info_get(entry);
15438334b962SMinchan Kim 	if (!p)
15448334b962SMinchan Kim 		return 0;
15458334b962SMinchan Kim 
1546235b6217SHuang, Ying 	offset = swp_offset(entry);
1547235b6217SHuang, Ying 
1548235b6217SHuang, Ying 	ci = lock_cluster_or_swap_info(p, offset);
1549235b6217SHuang, Ying 
1550235b6217SHuang, Ying 	count = swap_count(p->swap_map[offset]);
15518334b962SMinchan Kim 	if (!(count & COUNT_CONTINUED))
15528334b962SMinchan Kim 		goto out;
15538334b962SMinchan Kim 
15548334b962SMinchan Kim 	count &= ~COUNT_CONTINUED;
15558334b962SMinchan Kim 	n = SWAP_MAP_MAX + 1;
15568334b962SMinchan Kim 
15578334b962SMinchan Kim 	page = vmalloc_to_page(p->swap_map + offset);
15588334b962SMinchan Kim 	offset &= ~PAGE_MASK;
15598334b962SMinchan Kim 	VM_BUG_ON(page_private(page) != SWP_CONTINUED);
15608334b962SMinchan Kim 
15618334b962SMinchan Kim 	do {
1562a8ae4991SGeliang Tang 		page = list_next_entry(page, lru);
15638334b962SMinchan Kim 		map = kmap_atomic(page);
15648334b962SMinchan Kim 		tmp_count = map[offset];
15658334b962SMinchan Kim 		kunmap_atomic(map);
15668334b962SMinchan Kim 
15678334b962SMinchan Kim 		count += (tmp_count & ~COUNT_CONTINUED) * n;
15688334b962SMinchan Kim 		n *= (SWAP_CONT_MAX + 1);
15698334b962SMinchan Kim 	} while (tmp_count & COUNT_CONTINUED);
15708334b962SMinchan Kim out:
1571235b6217SHuang, Ying 	unlock_cluster_or_swap_info(p, ci);
15728334b962SMinchan Kim 	return count;
15738334b962SMinchan Kim }
15748334b962SMinchan Kim 
1575e0709829SHuang Ying static bool swap_page_trans_huge_swapped(struct swap_info_struct *si,
1576e0709829SHuang Ying 					 swp_entry_t entry)
1577e0709829SHuang Ying {
1578e0709829SHuang Ying 	struct swap_cluster_info *ci;
1579e0709829SHuang Ying 	unsigned char *map = si->swap_map;
1580e0709829SHuang Ying 	unsigned long roffset = swp_offset(entry);
1581e0709829SHuang Ying 	unsigned long offset = round_down(roffset, SWAPFILE_CLUSTER);
1582e0709829SHuang Ying 	int i;
1583e0709829SHuang Ying 	bool ret = false;
1584e0709829SHuang Ying 
1585e0709829SHuang Ying 	ci = lock_cluster_or_swap_info(si, offset);
1586e0709829SHuang Ying 	if (!ci || !cluster_is_huge(ci)) {
1587afa4711eSHuang Ying 		if (swap_count(map[roffset]))
1588e0709829SHuang Ying 			ret = true;
1589e0709829SHuang Ying 		goto unlock_out;
1590e0709829SHuang Ying 	}
1591e0709829SHuang Ying 	for (i = 0; i < SWAPFILE_CLUSTER; i++) {
1592afa4711eSHuang Ying 		if (swap_count(map[offset + i])) {
1593e0709829SHuang Ying 			ret = true;
1594e0709829SHuang Ying 			break;
1595e0709829SHuang Ying 		}
1596e0709829SHuang Ying 	}
1597e0709829SHuang Ying unlock_out:
1598e0709829SHuang Ying 	unlock_cluster_or_swap_info(si, ci);
1599e0709829SHuang Ying 	return ret;
1600e0709829SHuang Ying }
1601e0709829SHuang Ying 
1602e0709829SHuang Ying static bool page_swapped(struct page *page)
1603e0709829SHuang Ying {
1604e0709829SHuang Ying 	swp_entry_t entry;
1605e0709829SHuang Ying 	struct swap_info_struct *si;
1606e0709829SHuang Ying 
1607fe5266d5SHuang Ying 	if (!IS_ENABLED(CONFIG_THP_SWAP) || likely(!PageTransCompound(page)))
1608e0709829SHuang Ying 		return page_swapcount(page) != 0;
1609e0709829SHuang Ying 
1610e0709829SHuang Ying 	page = compound_head(page);
1611e0709829SHuang Ying 	entry.val = page_private(page);
1612e0709829SHuang Ying 	si = _swap_info_get(entry);
1613e0709829SHuang Ying 	if (si)
1614e0709829SHuang Ying 		return swap_page_trans_huge_swapped(si, entry);
1615e0709829SHuang Ying 	return false;
1616e0709829SHuang Ying }
1617ba3c4ce6SHuang Ying 
1618ba3c4ce6SHuang Ying static int page_trans_huge_map_swapcount(struct page *page, int *total_mapcount,
1619ba3c4ce6SHuang Ying 					 int *total_swapcount)
1620ba3c4ce6SHuang Ying {
1621ba3c4ce6SHuang Ying 	int i, map_swapcount, _total_mapcount, _total_swapcount;
1622ba3c4ce6SHuang Ying 	unsigned long offset = 0;
1623ba3c4ce6SHuang Ying 	struct swap_info_struct *si;
1624ba3c4ce6SHuang Ying 	struct swap_cluster_info *ci = NULL;
1625ba3c4ce6SHuang Ying 	unsigned char *map = NULL;
1626ba3c4ce6SHuang Ying 	int mapcount, swapcount = 0;
1627ba3c4ce6SHuang Ying 
1628ba3c4ce6SHuang Ying 	/* hugetlbfs shouldn't call it */
1629ba3c4ce6SHuang Ying 	VM_BUG_ON_PAGE(PageHuge(page), page);
1630ba3c4ce6SHuang Ying 
1631fe5266d5SHuang Ying 	if (!IS_ENABLED(CONFIG_THP_SWAP) || likely(!PageTransCompound(page))) {
1632fe5266d5SHuang Ying 		mapcount = page_trans_huge_mapcount(page, total_mapcount);
1633ba3c4ce6SHuang Ying 		if (PageSwapCache(page))
1634ba3c4ce6SHuang Ying 			swapcount = page_swapcount(page);
1635ba3c4ce6SHuang Ying 		if (total_swapcount)
1636ba3c4ce6SHuang Ying 			*total_swapcount = swapcount;
1637ba3c4ce6SHuang Ying 		return mapcount + swapcount;
1638ba3c4ce6SHuang Ying 	}
1639ba3c4ce6SHuang Ying 
1640ba3c4ce6SHuang Ying 	page = compound_head(page);
1641ba3c4ce6SHuang Ying 
1642ba3c4ce6SHuang Ying 	_total_mapcount = _total_swapcount = map_swapcount = 0;
1643ba3c4ce6SHuang Ying 	if (PageSwapCache(page)) {
1644ba3c4ce6SHuang Ying 		swp_entry_t entry;
1645ba3c4ce6SHuang Ying 
1646ba3c4ce6SHuang Ying 		entry.val = page_private(page);
1647ba3c4ce6SHuang Ying 		si = _swap_info_get(entry);
1648ba3c4ce6SHuang Ying 		if (si) {
1649ba3c4ce6SHuang Ying 			map = si->swap_map;
1650ba3c4ce6SHuang Ying 			offset = swp_offset(entry);
1651ba3c4ce6SHuang Ying 		}
1652ba3c4ce6SHuang Ying 	}
1653ba3c4ce6SHuang Ying 	if (map)
1654ba3c4ce6SHuang Ying 		ci = lock_cluster(si, offset);
1655ba3c4ce6SHuang Ying 	for (i = 0; i < HPAGE_PMD_NR; i++) {
1656ba3c4ce6SHuang Ying 		mapcount = atomic_read(&page[i]._mapcount) + 1;
1657ba3c4ce6SHuang Ying 		_total_mapcount += mapcount;
1658ba3c4ce6SHuang Ying 		if (map) {
1659ba3c4ce6SHuang Ying 			swapcount = swap_count(map[offset + i]);
1660ba3c4ce6SHuang Ying 			_total_swapcount += swapcount;
1661ba3c4ce6SHuang Ying 		}
1662ba3c4ce6SHuang Ying 		map_swapcount = max(map_swapcount, mapcount + swapcount);
1663ba3c4ce6SHuang Ying 	}
1664ba3c4ce6SHuang Ying 	unlock_cluster(ci);
1665ba3c4ce6SHuang Ying 	if (PageDoubleMap(page)) {
1666ba3c4ce6SHuang Ying 		map_swapcount -= 1;
1667ba3c4ce6SHuang Ying 		_total_mapcount -= HPAGE_PMD_NR;
1668ba3c4ce6SHuang Ying 	}
1669ba3c4ce6SHuang Ying 	mapcount = compound_mapcount(page);
1670ba3c4ce6SHuang Ying 	map_swapcount += mapcount;
1671ba3c4ce6SHuang Ying 	_total_mapcount += mapcount;
1672ba3c4ce6SHuang Ying 	if (total_mapcount)
1673ba3c4ce6SHuang Ying 		*total_mapcount = _total_mapcount;
1674ba3c4ce6SHuang Ying 	if (total_swapcount)
1675ba3c4ce6SHuang Ying 		*total_swapcount = _total_swapcount;
1676ba3c4ce6SHuang Ying 
1677ba3c4ce6SHuang Ying 	return map_swapcount;
1678ba3c4ce6SHuang Ying }
1679e0709829SHuang Ying 
16808334b962SMinchan Kim /*
16817b1fe597SHugh Dickins  * We can write to an anon page without COW if there are no other references
16827b1fe597SHugh Dickins  * to it.  And as a side-effect, free up its swap: because the old content
16837b1fe597SHugh Dickins  * on disk will never be read, and seeking back there to write new content
16847b1fe597SHugh Dickins  * later would only waste time away from clustering.
16856d0a07edSAndrea Arcangeli  *
1686ba3c4ce6SHuang Ying  * NOTE: total_map_swapcount should not be relied upon by the caller if
16876d0a07edSAndrea Arcangeli  * reuse_swap_page() returns false, but it may be always overwritten
16886d0a07edSAndrea Arcangeli  * (see the other implementation for CONFIG_SWAP=n).
16891da177e4SLinus Torvalds  */
1690ba3c4ce6SHuang Ying bool reuse_swap_page(struct page *page, int *total_map_swapcount)
16911da177e4SLinus Torvalds {
1692ba3c4ce6SHuang Ying 	int count, total_mapcount, total_swapcount;
16931da177e4SLinus Torvalds 
1694309381feSSasha Levin 	VM_BUG_ON_PAGE(!PageLocked(page), page);
16955ad64688SHugh Dickins 	if (unlikely(PageKsm(page)))
16966d0a07edSAndrea Arcangeli 		return false;
1697ba3c4ce6SHuang Ying 	count = page_trans_huge_map_swapcount(page, &total_mapcount,
1698ba3c4ce6SHuang Ying 					      &total_swapcount);
1699ba3c4ce6SHuang Ying 	if (total_map_swapcount)
1700ba3c4ce6SHuang Ying 		*total_map_swapcount = total_mapcount + total_swapcount;
1701ba3c4ce6SHuang Ying 	if (count == 1 && PageSwapCache(page) &&
1702ba3c4ce6SHuang Ying 	    (likely(!PageTransCompound(page)) ||
1703ba3c4ce6SHuang Ying 	     /* The remaining swap count will be freed soon */
1704ba3c4ce6SHuang Ying 	     total_swapcount == page_swapcount(page))) {
1705f0571429SMinchan Kim 		if (!PageWriteback(page)) {
1706ba3c4ce6SHuang Ying 			page = compound_head(page);
17077b1fe597SHugh Dickins 			delete_from_swap_cache(page);
17087b1fe597SHugh Dickins 			SetPageDirty(page);
1709f0571429SMinchan Kim 		} else {
1710f0571429SMinchan Kim 			swp_entry_t entry;
1711f0571429SMinchan Kim 			struct swap_info_struct *p;
1712f0571429SMinchan Kim 
1713f0571429SMinchan Kim 			entry.val = page_private(page);
1714f0571429SMinchan Kim 			p = swap_info_get(entry);
1715f0571429SMinchan Kim 			if (p->flags & SWP_STABLE_WRITES) {
1716f0571429SMinchan Kim 				spin_unlock(&p->lock);
1717f0571429SMinchan Kim 				return false;
1718f0571429SMinchan Kim 			}
1719f0571429SMinchan Kim 			spin_unlock(&p->lock);
17207b1fe597SHugh Dickins 		}
17217b1fe597SHugh Dickins 	}
1722ba3c4ce6SHuang Ying 
17235ad64688SHugh Dickins 	return count <= 1;
17241da177e4SLinus Torvalds }
17251da177e4SLinus Torvalds 
17261da177e4SLinus Torvalds /*
1727a2c43eedSHugh Dickins  * If swap is getting full, or if there are no more mappings of this page,
1728a2c43eedSHugh Dickins  * then try_to_free_swap is called to free its swap space.
17291da177e4SLinus Torvalds  */
1730a2c43eedSHugh Dickins int try_to_free_swap(struct page *page)
17311da177e4SLinus Torvalds {
1732309381feSSasha Levin 	VM_BUG_ON_PAGE(!PageLocked(page), page);
17331da177e4SLinus Torvalds 
17341da177e4SLinus Torvalds 	if (!PageSwapCache(page))
17351da177e4SLinus Torvalds 		return 0;
17361da177e4SLinus Torvalds 	if (PageWriteback(page))
17371da177e4SLinus Torvalds 		return 0;
1738e0709829SHuang Ying 	if (page_swapped(page))
17391da177e4SLinus Torvalds 		return 0;
17401da177e4SLinus Torvalds 
1741b73d7fceSHugh Dickins 	/*
1742b73d7fceSHugh Dickins 	 * Once hibernation has begun to create its image of memory,
1743b73d7fceSHugh Dickins 	 * there's a danger that one of the calls to try_to_free_swap()
1744b73d7fceSHugh Dickins 	 * - most probably a call from __try_to_reclaim_swap() while
1745b73d7fceSHugh Dickins 	 * hibernation is allocating its own swap pages for the image,
1746b73d7fceSHugh Dickins 	 * but conceivably even a call from memory reclaim - will free
1747b73d7fceSHugh Dickins 	 * the swap from a page which has already been recorded in the
1748b73d7fceSHugh Dickins 	 * image as a clean swapcache page, and then reuse its swap for
1749b73d7fceSHugh Dickins 	 * another page of the image.  On waking from hibernation, the
1750b73d7fceSHugh Dickins 	 * original page might be freed under memory pressure, then
1751b73d7fceSHugh Dickins 	 * later read back in from swap, now with the wrong data.
1752b73d7fceSHugh Dickins 	 *
17532de1a7e4SSeth Jennings 	 * Hibernation suspends storage while it is writing the image
1754f90ac398SMel Gorman 	 * to disk so check that here.
1755b73d7fceSHugh Dickins 	 */
1756f90ac398SMel Gorman 	if (pm_suspended_storage())
1757b73d7fceSHugh Dickins 		return 0;
1758b73d7fceSHugh Dickins 
1759e0709829SHuang Ying 	page = compound_head(page);
1760a2c43eedSHugh Dickins 	delete_from_swap_cache(page);
17611da177e4SLinus Torvalds 	SetPageDirty(page);
1762a2c43eedSHugh Dickins 	return 1;
176368a22394SRik van Riel }
176468a22394SRik van Riel 
176568a22394SRik van Riel /*
17661da177e4SLinus Torvalds  * Free the swap entry like above, but also try to
17671da177e4SLinus Torvalds  * free the page cache entry if it is the last user.
17681da177e4SLinus Torvalds  */
17692509ef26SHugh Dickins int free_swap_and_cache(swp_entry_t entry)
17701da177e4SLinus Torvalds {
17711da177e4SLinus Torvalds 	struct swap_info_struct *p;
17727c00bafeSTim Chen 	unsigned char count;
17731da177e4SLinus Torvalds 
1774a7420aa5SAndi Kleen 	if (non_swap_entry(entry))
17752509ef26SHugh Dickins 		return 1;
17760697212aSChristoph Lameter 
17777c00bafeSTim Chen 	p = _swap_info_get(entry);
17781da177e4SLinus Torvalds 	if (p) {
177933e16272SWei Yang 		count = __swap_entry_free(p, entry);
1780e0709829SHuang Ying 		if (count == SWAP_HAS_CACHE &&
1781bcd49e86SHuang Ying 		    !swap_page_trans_huge_swapped(p, entry))
1782bcd49e86SHuang Ying 			__try_to_reclaim_swap(p, swp_offset(entry),
1783bcd49e86SHuang Ying 					      TTRS_UNMAPPED | TTRS_FULL);
17841da177e4SLinus Torvalds 	}
17852509ef26SHugh Dickins 	return p != NULL;
17861da177e4SLinus Torvalds }
17871da177e4SLinus Torvalds 
1788b0cb1a19SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
1789f577eb30SRafael J. Wysocki /*
1790915bae9eSRafael J. Wysocki  * Find the swap type that corresponds to given device (if any).
1791f577eb30SRafael J. Wysocki  *
1792915bae9eSRafael J. Wysocki  * @offset - number of the PAGE_SIZE-sized block of the device, starting
1793915bae9eSRafael J. Wysocki  * from 0, in which the swap header is expected to be located.
1794915bae9eSRafael J. Wysocki  *
1795915bae9eSRafael J. Wysocki  * This is needed for the suspend to disk (aka swsusp).
1796f577eb30SRafael J. Wysocki  */
17977bf23687SRafael J. Wysocki int swap_type_of(dev_t device, sector_t offset, struct block_device **bdev_p)
1798f577eb30SRafael J. Wysocki {
1799915bae9eSRafael J. Wysocki 	struct block_device *bdev = NULL;
1800efa90a98SHugh Dickins 	int type;
1801f577eb30SRafael J. Wysocki 
1802915bae9eSRafael J. Wysocki 	if (device)
1803915bae9eSRafael J. Wysocki 		bdev = bdget(device);
1804915bae9eSRafael J. Wysocki 
1805f577eb30SRafael J. Wysocki 	spin_lock(&swap_lock);
1806efa90a98SHugh Dickins 	for (type = 0; type < nr_swapfiles; type++) {
1807efa90a98SHugh Dickins 		struct swap_info_struct *sis = swap_info[type];
1808f577eb30SRafael J. Wysocki 
1809915bae9eSRafael J. Wysocki 		if (!(sis->flags & SWP_WRITEOK))
1810f577eb30SRafael J. Wysocki 			continue;
1811b6b5bce3SRafael J. Wysocki 
1812915bae9eSRafael J. Wysocki 		if (!bdev) {
18137bf23687SRafael J. Wysocki 			if (bdev_p)
1814dddac6a7SAlan Jenkins 				*bdev_p = bdgrab(sis->bdev);
18157bf23687SRafael J. Wysocki 
18166e1819d6SRafael J. Wysocki 			spin_unlock(&swap_lock);
1817efa90a98SHugh Dickins 			return type;
18186e1819d6SRafael J. Wysocki 		}
1819915bae9eSRafael J. Wysocki 		if (bdev == sis->bdev) {
18204efaceb1SAaron Lu 			struct swap_extent *se = first_se(sis);
1821915bae9eSRafael J. Wysocki 
1822915bae9eSRafael J. Wysocki 			if (se->start_block == offset) {
18237bf23687SRafael J. Wysocki 				if (bdev_p)
1824dddac6a7SAlan Jenkins 					*bdev_p = bdgrab(sis->bdev);
18257bf23687SRafael J. Wysocki 
1826f577eb30SRafael J. Wysocki 				spin_unlock(&swap_lock);
1827915bae9eSRafael J. Wysocki 				bdput(bdev);
1828efa90a98SHugh Dickins 				return type;
1829f577eb30SRafael J. Wysocki 			}
1830f577eb30SRafael J. Wysocki 		}
1831915bae9eSRafael J. Wysocki 	}
1832f577eb30SRafael J. Wysocki 	spin_unlock(&swap_lock);
1833915bae9eSRafael J. Wysocki 	if (bdev)
1834915bae9eSRafael J. Wysocki 		bdput(bdev);
1835915bae9eSRafael J. Wysocki 
1836f577eb30SRafael J. Wysocki 	return -ENODEV;
1837f577eb30SRafael J. Wysocki }
1838f577eb30SRafael J. Wysocki 
1839f577eb30SRafael J. Wysocki /*
184073c34b6aSHugh Dickins  * Get the (PAGE_SIZE) block corresponding to given offset on the swapdev
184173c34b6aSHugh Dickins  * corresponding to given index in swap_info (swap type).
184273c34b6aSHugh Dickins  */
184373c34b6aSHugh Dickins sector_t swapdev_block(int type, pgoff_t offset)
184473c34b6aSHugh Dickins {
184573c34b6aSHugh Dickins 	struct block_device *bdev;
1846c10d38ccSDaniel Jordan 	struct swap_info_struct *si = swap_type_to_swap_info(type);
184773c34b6aSHugh Dickins 
1848c10d38ccSDaniel Jordan 	if (!si || !(si->flags & SWP_WRITEOK))
184973c34b6aSHugh Dickins 		return 0;
1850d4906e1aSLee Schermerhorn 	return map_swap_entry(swp_entry(type, offset), &bdev);
185173c34b6aSHugh Dickins }
185273c34b6aSHugh Dickins 
185373c34b6aSHugh Dickins /*
1854f577eb30SRafael J. Wysocki  * Return either the total number of swap pages of given type, or the number
1855f577eb30SRafael J. Wysocki  * of free pages of that type (depending on @free)
1856f577eb30SRafael J. Wysocki  *
1857f577eb30SRafael J. Wysocki  * This is needed for software suspend
1858f577eb30SRafael J. Wysocki  */
1859f577eb30SRafael J. Wysocki unsigned int count_swap_pages(int type, int free)
1860f577eb30SRafael J. Wysocki {
1861f577eb30SRafael J. Wysocki 	unsigned int n = 0;
1862f577eb30SRafael J. Wysocki 
1863f577eb30SRafael J. Wysocki 	spin_lock(&swap_lock);
1864efa90a98SHugh Dickins 	if ((unsigned int)type < nr_swapfiles) {
1865efa90a98SHugh Dickins 		struct swap_info_struct *sis = swap_info[type];
1866efa90a98SHugh Dickins 
1867ec8acf20SShaohua Li 		spin_lock(&sis->lock);
1868efa90a98SHugh Dickins 		if (sis->flags & SWP_WRITEOK) {
1869efa90a98SHugh Dickins 			n = sis->pages;
1870f577eb30SRafael J. Wysocki 			if (free)
1871efa90a98SHugh Dickins 				n -= sis->inuse_pages;
1872efa90a98SHugh Dickins 		}
1873ec8acf20SShaohua Li 		spin_unlock(&sis->lock);
1874f577eb30SRafael J. Wysocki 	}
1875f577eb30SRafael J. Wysocki 	spin_unlock(&swap_lock);
1876f577eb30SRafael J. Wysocki 	return n;
1877f577eb30SRafael J. Wysocki }
187873c34b6aSHugh Dickins #endif /* CONFIG_HIBERNATION */
1879f577eb30SRafael J. Wysocki 
18809f8bdb3fSHugh Dickins static inline int pte_same_as_swp(pte_t pte, pte_t swp_pte)
1881179ef71cSCyrill Gorcunov {
18829f8bdb3fSHugh Dickins 	return pte_same(pte_swp_clear_soft_dirty(pte), swp_pte);
1883179ef71cSCyrill Gorcunov }
1884179ef71cSCyrill Gorcunov 
18851da177e4SLinus Torvalds /*
188672866f6fSHugh Dickins  * No need to decide whether this PTE shares the swap entry with others,
188772866f6fSHugh Dickins  * just let do_wp_page work it out if a write is requested later - to
188872866f6fSHugh Dickins  * force COW, vm_page_prot omits write permission from any private vma.
18891da177e4SLinus Torvalds  */
1890044d66c1SHugh Dickins static int unuse_pte(struct vm_area_struct *vma, pmd_t *pmd,
18911da177e4SLinus Torvalds 		unsigned long addr, swp_entry_t entry, struct page *page)
18921da177e4SLinus Torvalds {
18939e16b7fbSHugh Dickins 	struct page *swapcache;
1894044d66c1SHugh Dickins 	spinlock_t *ptl;
1895044d66c1SHugh Dickins 	pte_t *pte;
1896044d66c1SHugh Dickins 	int ret = 1;
1897044d66c1SHugh Dickins 
18989e16b7fbSHugh Dickins 	swapcache = page;
18999e16b7fbSHugh Dickins 	page = ksm_might_need_to_copy(page, vma, addr);
19009e16b7fbSHugh Dickins 	if (unlikely(!page))
19019e16b7fbSHugh Dickins 		return -ENOMEM;
19029e16b7fbSHugh Dickins 
1903044d66c1SHugh Dickins 	pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
19049f8bdb3fSHugh Dickins 	if (unlikely(!pte_same_as_swp(*pte, swp_entry_to_pte(entry)))) {
1905044d66c1SHugh Dickins 		ret = 0;
1906044d66c1SHugh Dickins 		goto out;
1907044d66c1SHugh Dickins 	}
19088a9f3ccdSBalbir Singh 
1909b084d435SKAMEZAWA Hiroyuki 	dec_mm_counter(vma->vm_mm, MM_SWAPENTS);
1910d559db08SKAMEZAWA Hiroyuki 	inc_mm_counter(vma->vm_mm, MM_ANONPAGES);
19111da177e4SLinus Torvalds 	get_page(page);
19121da177e4SLinus Torvalds 	set_pte_at(vma->vm_mm, addr, pte,
19131da177e4SLinus Torvalds 		   pte_mkold(mk_pte(page, vma->vm_page_prot)));
191400501b53SJohannes Weiner 	if (page == swapcache) {
1915be5d0a74SJohannes Weiner 		page_add_anon_rmap(page, vma, addr, false);
191600501b53SJohannes Weiner 	} else { /* ksm created a completely new copy */
1917be5d0a74SJohannes Weiner 		page_add_new_anon_rmap(page, vma, addr, false);
191800501b53SJohannes Weiner 		lru_cache_add_active_or_unevictable(page, vma);
191900501b53SJohannes Weiner 	}
19201da177e4SLinus Torvalds 	swap_free(entry);
19211da177e4SLinus Torvalds 	/*
19221da177e4SLinus Torvalds 	 * Move the page to the active list so it is not
19231da177e4SLinus Torvalds 	 * immediately swapped out again after swapon.
19241da177e4SLinus Torvalds 	 */
19251da177e4SLinus Torvalds 	activate_page(page);
1926044d66c1SHugh Dickins out:
1927044d66c1SHugh Dickins 	pte_unmap_unlock(pte, ptl);
19289e16b7fbSHugh Dickins 	if (page != swapcache) {
19299e16b7fbSHugh Dickins 		unlock_page(page);
19309e16b7fbSHugh Dickins 		put_page(page);
19319e16b7fbSHugh Dickins 	}
1932044d66c1SHugh Dickins 	return ret;
19331da177e4SLinus Torvalds }
19341da177e4SLinus Torvalds 
19351da177e4SLinus Torvalds static int unuse_pte_range(struct vm_area_struct *vma, pmd_t *pmd,
19361da177e4SLinus Torvalds 			unsigned long addr, unsigned long end,
1937b56a2d8aSVineeth Remanan Pillai 			unsigned int type, bool frontswap,
1938b56a2d8aSVineeth Remanan Pillai 			unsigned long *fs_pages_to_unuse)
19391da177e4SLinus Torvalds {
1940b56a2d8aSVineeth Remanan Pillai 	struct page *page;
1941b56a2d8aSVineeth Remanan Pillai 	swp_entry_t entry;
1942705e87c0SHugh Dickins 	pte_t *pte;
1943b56a2d8aSVineeth Remanan Pillai 	struct swap_info_struct *si;
1944b56a2d8aSVineeth Remanan Pillai 	unsigned long offset;
19458a9f3ccdSBalbir Singh 	int ret = 0;
1946b56a2d8aSVineeth Remanan Pillai 	volatile unsigned char *swap_map;
19471da177e4SLinus Torvalds 
1948b56a2d8aSVineeth Remanan Pillai 	si = swap_info[type];
1949044d66c1SHugh Dickins 	pte = pte_offset_map(pmd, addr);
19501da177e4SLinus Torvalds 	do {
1951b56a2d8aSVineeth Remanan Pillai 		struct vm_fault vmf;
1952b56a2d8aSVineeth Remanan Pillai 
1953b56a2d8aSVineeth Remanan Pillai 		if (!is_swap_pte(*pte))
1954b56a2d8aSVineeth Remanan Pillai 			continue;
1955b56a2d8aSVineeth Remanan Pillai 
1956b56a2d8aSVineeth Remanan Pillai 		entry = pte_to_swp_entry(*pte);
1957b56a2d8aSVineeth Remanan Pillai 		if (swp_type(entry) != type)
1958b56a2d8aSVineeth Remanan Pillai 			continue;
1959b56a2d8aSVineeth Remanan Pillai 
1960b56a2d8aSVineeth Remanan Pillai 		offset = swp_offset(entry);
1961b56a2d8aSVineeth Remanan Pillai 		if (frontswap && !frontswap_test(si, offset))
1962b56a2d8aSVineeth Remanan Pillai 			continue;
1963b56a2d8aSVineeth Remanan Pillai 
1964044d66c1SHugh Dickins 		pte_unmap(pte);
1965b56a2d8aSVineeth Remanan Pillai 		swap_map = &si->swap_map[offset];
1966ebc5951eSAndrea Righi 		page = lookup_swap_cache(entry, vma, addr);
1967ebc5951eSAndrea Righi 		if (!page) {
1968b56a2d8aSVineeth Remanan Pillai 			vmf.vma = vma;
1969b56a2d8aSVineeth Remanan Pillai 			vmf.address = addr;
1970b56a2d8aSVineeth Remanan Pillai 			vmf.pmd = pmd;
1971ebc5951eSAndrea Righi 			page = swapin_readahead(entry, GFP_HIGHUSER_MOVABLE,
1972ebc5951eSAndrea Righi 						&vmf);
1973ebc5951eSAndrea Righi 		}
1974b56a2d8aSVineeth Remanan Pillai 		if (!page) {
1975b56a2d8aSVineeth Remanan Pillai 			if (*swap_map == 0 || *swap_map == SWAP_MAP_BAD)
1976b56a2d8aSVineeth Remanan Pillai 				goto try_next;
1977b56a2d8aSVineeth Remanan Pillai 			return -ENOMEM;
19781da177e4SLinus Torvalds 		}
1979b56a2d8aSVineeth Remanan Pillai 
1980b56a2d8aSVineeth Remanan Pillai 		lock_page(page);
1981b56a2d8aSVineeth Remanan Pillai 		wait_on_page_writeback(page);
1982b56a2d8aSVineeth Remanan Pillai 		ret = unuse_pte(vma, pmd, addr, entry, page);
1983b56a2d8aSVineeth Remanan Pillai 		if (ret < 0) {
1984b56a2d8aSVineeth Remanan Pillai 			unlock_page(page);
1985b56a2d8aSVineeth Remanan Pillai 			put_page(page);
1986b56a2d8aSVineeth Remanan Pillai 			goto out;
1987b56a2d8aSVineeth Remanan Pillai 		}
1988b56a2d8aSVineeth Remanan Pillai 
1989b56a2d8aSVineeth Remanan Pillai 		try_to_free_swap(page);
1990b56a2d8aSVineeth Remanan Pillai 		unlock_page(page);
1991b56a2d8aSVineeth Remanan Pillai 		put_page(page);
1992b56a2d8aSVineeth Remanan Pillai 
1993b56a2d8aSVineeth Remanan Pillai 		if (*fs_pages_to_unuse && !--(*fs_pages_to_unuse)) {
1994b56a2d8aSVineeth Remanan Pillai 			ret = FRONTSWAP_PAGES_UNUSED;
1995b56a2d8aSVineeth Remanan Pillai 			goto out;
1996b56a2d8aSVineeth Remanan Pillai 		}
1997b56a2d8aSVineeth Remanan Pillai try_next:
1998b56a2d8aSVineeth Remanan Pillai 		pte = pte_offset_map(pmd, addr);
19991da177e4SLinus Torvalds 	} while (pte++, addr += PAGE_SIZE, addr != end);
2000044d66c1SHugh Dickins 	pte_unmap(pte - 1);
2001b56a2d8aSVineeth Remanan Pillai 
2002b56a2d8aSVineeth Remanan Pillai 	ret = 0;
2003044d66c1SHugh Dickins out:
20048a9f3ccdSBalbir Singh 	return ret;
20051da177e4SLinus Torvalds }
20061da177e4SLinus Torvalds 
20071da177e4SLinus Torvalds static inline int unuse_pmd_range(struct vm_area_struct *vma, pud_t *pud,
20081da177e4SLinus Torvalds 				unsigned long addr, unsigned long end,
2009b56a2d8aSVineeth Remanan Pillai 				unsigned int type, bool frontswap,
2010b56a2d8aSVineeth Remanan Pillai 				unsigned long *fs_pages_to_unuse)
20111da177e4SLinus Torvalds {
20121da177e4SLinus Torvalds 	pmd_t *pmd;
20131da177e4SLinus Torvalds 	unsigned long next;
20148a9f3ccdSBalbir Singh 	int ret;
20151da177e4SLinus Torvalds 
20161da177e4SLinus Torvalds 	pmd = pmd_offset(pud, addr);
20171da177e4SLinus Torvalds 	do {
2018dc644a07SHugh Dickins 		cond_resched();
20191da177e4SLinus Torvalds 		next = pmd_addr_end(addr, end);
20201a5a9906SAndrea Arcangeli 		if (pmd_none_or_trans_huge_or_clear_bad(pmd))
20211da177e4SLinus Torvalds 			continue;
2022b56a2d8aSVineeth Remanan Pillai 		ret = unuse_pte_range(vma, pmd, addr, next, type,
2023b56a2d8aSVineeth Remanan Pillai 				      frontswap, fs_pages_to_unuse);
20248a9f3ccdSBalbir Singh 		if (ret)
20258a9f3ccdSBalbir Singh 			return ret;
20261da177e4SLinus Torvalds 	} while (pmd++, addr = next, addr != end);
20271da177e4SLinus Torvalds 	return 0;
20281da177e4SLinus Torvalds }
20291da177e4SLinus Torvalds 
2030c2febafcSKirill A. Shutemov static inline int unuse_pud_range(struct vm_area_struct *vma, p4d_t *p4d,
20311da177e4SLinus Torvalds 				unsigned long addr, unsigned long end,
2032b56a2d8aSVineeth Remanan Pillai 				unsigned int type, bool frontswap,
2033b56a2d8aSVineeth Remanan Pillai 				unsigned long *fs_pages_to_unuse)
20341da177e4SLinus Torvalds {
20351da177e4SLinus Torvalds 	pud_t *pud;
20361da177e4SLinus Torvalds 	unsigned long next;
20378a9f3ccdSBalbir Singh 	int ret;
20381da177e4SLinus Torvalds 
2039c2febafcSKirill A. Shutemov 	pud = pud_offset(p4d, addr);
20401da177e4SLinus Torvalds 	do {
20411da177e4SLinus Torvalds 		next = pud_addr_end(addr, end);
20421da177e4SLinus Torvalds 		if (pud_none_or_clear_bad(pud))
20431da177e4SLinus Torvalds 			continue;
2044b56a2d8aSVineeth Remanan Pillai 		ret = unuse_pmd_range(vma, pud, addr, next, type,
2045b56a2d8aSVineeth Remanan Pillai 				      frontswap, fs_pages_to_unuse);
20468a9f3ccdSBalbir Singh 		if (ret)
20478a9f3ccdSBalbir Singh 			return ret;
20481da177e4SLinus Torvalds 	} while (pud++, addr = next, addr != end);
20491da177e4SLinus Torvalds 	return 0;
20501da177e4SLinus Torvalds }
20511da177e4SLinus Torvalds 
2052c2febafcSKirill A. Shutemov static inline int unuse_p4d_range(struct vm_area_struct *vma, pgd_t *pgd,
2053c2febafcSKirill A. Shutemov 				unsigned long addr, unsigned long end,
2054b56a2d8aSVineeth Remanan Pillai 				unsigned int type, bool frontswap,
2055b56a2d8aSVineeth Remanan Pillai 				unsigned long *fs_pages_to_unuse)
2056c2febafcSKirill A. Shutemov {
2057c2febafcSKirill A. Shutemov 	p4d_t *p4d;
2058c2febafcSKirill A. Shutemov 	unsigned long next;
2059c2febafcSKirill A. Shutemov 	int ret;
2060c2febafcSKirill A. Shutemov 
2061c2febafcSKirill A. Shutemov 	p4d = p4d_offset(pgd, addr);
2062c2febafcSKirill A. Shutemov 	do {
2063c2febafcSKirill A. Shutemov 		next = p4d_addr_end(addr, end);
2064c2febafcSKirill A. Shutemov 		if (p4d_none_or_clear_bad(p4d))
2065c2febafcSKirill A. Shutemov 			continue;
2066b56a2d8aSVineeth Remanan Pillai 		ret = unuse_pud_range(vma, p4d, addr, next, type,
2067b56a2d8aSVineeth Remanan Pillai 				      frontswap, fs_pages_to_unuse);
2068c2febafcSKirill A. Shutemov 		if (ret)
2069c2febafcSKirill A. Shutemov 			return ret;
2070c2febafcSKirill A. Shutemov 	} while (p4d++, addr = next, addr != end);
2071c2febafcSKirill A. Shutemov 	return 0;
2072c2febafcSKirill A. Shutemov }
2073c2febafcSKirill A. Shutemov 
2074b56a2d8aSVineeth Remanan Pillai static int unuse_vma(struct vm_area_struct *vma, unsigned int type,
2075b56a2d8aSVineeth Remanan Pillai 		     bool frontswap, unsigned long *fs_pages_to_unuse)
20761da177e4SLinus Torvalds {
20771da177e4SLinus Torvalds 	pgd_t *pgd;
20781da177e4SLinus Torvalds 	unsigned long addr, end, next;
20798a9f3ccdSBalbir Singh 	int ret;
20801da177e4SLinus Torvalds 
20811da177e4SLinus Torvalds 	addr = vma->vm_start;
20821da177e4SLinus Torvalds 	end = vma->vm_end;
20831da177e4SLinus Torvalds 
20841da177e4SLinus Torvalds 	pgd = pgd_offset(vma->vm_mm, addr);
20851da177e4SLinus Torvalds 	do {
20861da177e4SLinus Torvalds 		next = pgd_addr_end(addr, end);
20871da177e4SLinus Torvalds 		if (pgd_none_or_clear_bad(pgd))
20881da177e4SLinus Torvalds 			continue;
2089b56a2d8aSVineeth Remanan Pillai 		ret = unuse_p4d_range(vma, pgd, addr, next, type,
2090b56a2d8aSVineeth Remanan Pillai 				      frontswap, fs_pages_to_unuse);
20918a9f3ccdSBalbir Singh 		if (ret)
20928a9f3ccdSBalbir Singh 			return ret;
20931da177e4SLinus Torvalds 	} while (pgd++, addr = next, addr != end);
20941da177e4SLinus Torvalds 	return 0;
20951da177e4SLinus Torvalds }
20961da177e4SLinus Torvalds 
2097b56a2d8aSVineeth Remanan Pillai static int unuse_mm(struct mm_struct *mm, unsigned int type,
2098b56a2d8aSVineeth Remanan Pillai 		    bool frontswap, unsigned long *fs_pages_to_unuse)
20991da177e4SLinus Torvalds {
21001da177e4SLinus Torvalds 	struct vm_area_struct *vma;
21018a9f3ccdSBalbir Singh 	int ret = 0;
21021da177e4SLinus Torvalds 
2103*d8ed45c5SMichel Lespinasse 	mmap_read_lock(mm);
21041da177e4SLinus Torvalds 	for (vma = mm->mmap; vma; vma = vma->vm_next) {
2105b56a2d8aSVineeth Remanan Pillai 		if (vma->anon_vma) {
2106b56a2d8aSVineeth Remanan Pillai 			ret = unuse_vma(vma, type, frontswap,
2107b56a2d8aSVineeth Remanan Pillai 					fs_pages_to_unuse);
2108b56a2d8aSVineeth Remanan Pillai 			if (ret)
21091da177e4SLinus Torvalds 				break;
2110b56a2d8aSVineeth Remanan Pillai 		}
2111dc644a07SHugh Dickins 		cond_resched();
21121da177e4SLinus Torvalds 	}
2113*d8ed45c5SMichel Lespinasse 	mmap_read_unlock(mm);
2114b56a2d8aSVineeth Remanan Pillai 	return ret;
21151da177e4SLinus Torvalds }
21161da177e4SLinus Torvalds 
21171da177e4SLinus Torvalds /*
211838b5faf4SDan Magenheimer  * Scan swap_map (or frontswap_map if frontswap parameter is true)
2119b56a2d8aSVineeth Remanan Pillai  * from current position to next entry still in use. Return 0
2120b56a2d8aSVineeth Remanan Pillai  * if there are no inuse entries after prev till end of the map.
21211da177e4SLinus Torvalds  */
21226eb396dcSHugh Dickins static unsigned int find_next_to_unuse(struct swap_info_struct *si,
212338b5faf4SDan Magenheimer 					unsigned int prev, bool frontswap)
21241da177e4SLinus Torvalds {
2125b56a2d8aSVineeth Remanan Pillai 	unsigned int i;
21268d69aaeeSHugh Dickins 	unsigned char count;
21271da177e4SLinus Torvalds 
21281da177e4SLinus Torvalds 	/*
21295d337b91SHugh Dickins 	 * No need for swap_lock here: we're just looking
21301da177e4SLinus Torvalds 	 * for whether an entry is in use, not modifying it; false
21311da177e4SLinus Torvalds 	 * hits are okay, and sys_swapoff() has already prevented new
21325d337b91SHugh Dickins 	 * allocations from this area (while holding swap_lock).
21331da177e4SLinus Torvalds 	 */
2134b56a2d8aSVineeth Remanan Pillai 	for (i = prev + 1; i < si->max; i++) {
21354db0c3c2SJason Low 		count = READ_ONCE(si->swap_map[i]);
2136355cfa73SKAMEZAWA Hiroyuki 		if (count && swap_count(count) != SWAP_MAP_BAD)
2137dc644a07SHugh Dickins 			if (!frontswap || frontswap_test(si, i))
21381da177e4SLinus Torvalds 				break;
2139dc644a07SHugh Dickins 		if ((i % LATENCY_LIMIT) == 0)
2140dc644a07SHugh Dickins 			cond_resched();
21411da177e4SLinus Torvalds 	}
2142b56a2d8aSVineeth Remanan Pillai 
2143b56a2d8aSVineeth Remanan Pillai 	if (i == si->max)
2144b56a2d8aSVineeth Remanan Pillai 		i = 0;
2145b56a2d8aSVineeth Remanan Pillai 
21461da177e4SLinus Torvalds 	return i;
21471da177e4SLinus Torvalds }
21481da177e4SLinus Torvalds 
21491da177e4SLinus Torvalds /*
2150b56a2d8aSVineeth Remanan Pillai  * If the boolean frontswap is true, only unuse pages_to_unuse pages;
215138b5faf4SDan Magenheimer  * pages_to_unuse==0 means all pages; ignored if frontswap is false
21521da177e4SLinus Torvalds  */
215338b5faf4SDan Magenheimer int try_to_unuse(unsigned int type, bool frontswap,
215438b5faf4SDan Magenheimer 		 unsigned long pages_to_unuse)
21551da177e4SLinus Torvalds {
2156b56a2d8aSVineeth Remanan Pillai 	struct mm_struct *prev_mm;
2157b56a2d8aSVineeth Remanan Pillai 	struct mm_struct *mm;
2158b56a2d8aSVineeth Remanan Pillai 	struct list_head *p;
2159b56a2d8aSVineeth Remanan Pillai 	int retval = 0;
2160efa90a98SHugh Dickins 	struct swap_info_struct *si = swap_info[type];
21611da177e4SLinus Torvalds 	struct page *page;
21621da177e4SLinus Torvalds 	swp_entry_t entry;
2163b56a2d8aSVineeth Remanan Pillai 	unsigned int i;
21641da177e4SLinus Torvalds 
216521820948SQian Cai 	if (!READ_ONCE(si->inuse_pages))
2166b56a2d8aSVineeth Remanan Pillai 		return 0;
21671da177e4SLinus Torvalds 
2168b56a2d8aSVineeth Remanan Pillai 	if (!frontswap)
2169b56a2d8aSVineeth Remanan Pillai 		pages_to_unuse = 0;
2170b56a2d8aSVineeth Remanan Pillai 
2171b56a2d8aSVineeth Remanan Pillai retry:
2172b56a2d8aSVineeth Remanan Pillai 	retval = shmem_unuse(type, frontswap, &pages_to_unuse);
2173b56a2d8aSVineeth Remanan Pillai 	if (retval)
2174b56a2d8aSVineeth Remanan Pillai 		goto out;
2175b56a2d8aSVineeth Remanan Pillai 
2176b56a2d8aSVineeth Remanan Pillai 	prev_mm = &init_mm;
2177b56a2d8aSVineeth Remanan Pillai 	mmget(prev_mm);
2178b56a2d8aSVineeth Remanan Pillai 
2179b56a2d8aSVineeth Remanan Pillai 	spin_lock(&mmlist_lock);
2180b56a2d8aSVineeth Remanan Pillai 	p = &init_mm.mmlist;
218121820948SQian Cai 	while (READ_ONCE(si->inuse_pages) &&
218264165b1aSHugh Dickins 	       !signal_pending(current) &&
218364165b1aSHugh Dickins 	       (p = p->next) != &init_mm.mmlist) {
21841da177e4SLinus Torvalds 
21851da177e4SLinus Torvalds 		mm = list_entry(p, struct mm_struct, mmlist);
2186388f7934SVegard Nossum 		if (!mmget_not_zero(mm))
21871da177e4SLinus Torvalds 			continue;
21881da177e4SLinus Torvalds 		spin_unlock(&mmlist_lock);
21891da177e4SLinus Torvalds 		mmput(prev_mm);
21901da177e4SLinus Torvalds 		prev_mm = mm;
2191b56a2d8aSVineeth Remanan Pillai 		retval = unuse_mm(mm, type, frontswap, &pages_to_unuse);
21921da177e4SLinus Torvalds 
21931da177e4SLinus Torvalds 		if (retval) {
2194b56a2d8aSVineeth Remanan Pillai 			mmput(prev_mm);
2195b56a2d8aSVineeth Remanan Pillai 			goto out;
21961da177e4SLinus Torvalds 		}
21971da177e4SLinus Torvalds 
21981da177e4SLinus Torvalds 		/*
21991da177e4SLinus Torvalds 		 * Make sure that we aren't completely killing
22001da177e4SLinus Torvalds 		 * interactive performance.
22011da177e4SLinus Torvalds 		 */
22021da177e4SLinus Torvalds 		cond_resched();
2203b56a2d8aSVineeth Remanan Pillai 		spin_lock(&mmlist_lock);
220438b5faf4SDan Magenheimer 	}
2205b56a2d8aSVineeth Remanan Pillai 	spin_unlock(&mmlist_lock);
2206b56a2d8aSVineeth Remanan Pillai 
2207b56a2d8aSVineeth Remanan Pillai 	mmput(prev_mm);
2208b56a2d8aSVineeth Remanan Pillai 
2209b56a2d8aSVineeth Remanan Pillai 	i = 0;
221021820948SQian Cai 	while (READ_ONCE(si->inuse_pages) &&
221164165b1aSHugh Dickins 	       !signal_pending(current) &&
221264165b1aSHugh Dickins 	       (i = find_next_to_unuse(si, i, frontswap)) != 0) {
2213b56a2d8aSVineeth Remanan Pillai 
2214b56a2d8aSVineeth Remanan Pillai 		entry = swp_entry(type, i);
2215b56a2d8aSVineeth Remanan Pillai 		page = find_get_page(swap_address_space(entry), i);
2216b56a2d8aSVineeth Remanan Pillai 		if (!page)
2217b56a2d8aSVineeth Remanan Pillai 			continue;
2218b56a2d8aSVineeth Remanan Pillai 
2219b56a2d8aSVineeth Remanan Pillai 		/*
2220b56a2d8aSVineeth Remanan Pillai 		 * It is conceivable that a racing task removed this page from
2221b56a2d8aSVineeth Remanan Pillai 		 * swap cache just before we acquired the page lock. The page
2222b56a2d8aSVineeth Remanan Pillai 		 * might even be back in swap cache on another swap area. But
2223b56a2d8aSVineeth Remanan Pillai 		 * that is okay, try_to_free_swap() only removes stale pages.
2224b56a2d8aSVineeth Remanan Pillai 		 */
2225b56a2d8aSVineeth Remanan Pillai 		lock_page(page);
2226b56a2d8aSVineeth Remanan Pillai 		wait_on_page_writeback(page);
2227b56a2d8aSVineeth Remanan Pillai 		try_to_free_swap(page);
2228b56a2d8aSVineeth Remanan Pillai 		unlock_page(page);
2229b56a2d8aSVineeth Remanan Pillai 		put_page(page);
2230b56a2d8aSVineeth Remanan Pillai 
2231b56a2d8aSVineeth Remanan Pillai 		/*
2232b56a2d8aSVineeth Remanan Pillai 		 * For frontswap, we just need to unuse pages_to_unuse, if
2233b56a2d8aSVineeth Remanan Pillai 		 * it was specified. Need not check frontswap again here as
2234b56a2d8aSVineeth Remanan Pillai 		 * we already zeroed out pages_to_unuse if not frontswap.
2235b56a2d8aSVineeth Remanan Pillai 		 */
2236b56a2d8aSVineeth Remanan Pillai 		if (pages_to_unuse && --pages_to_unuse == 0)
2237b56a2d8aSVineeth Remanan Pillai 			goto out;
22381da177e4SLinus Torvalds 	}
22391da177e4SLinus Torvalds 
2240b56a2d8aSVineeth Remanan Pillai 	/*
2241b56a2d8aSVineeth Remanan Pillai 	 * Lets check again to see if there are still swap entries in the map.
2242b56a2d8aSVineeth Remanan Pillai 	 * If yes, we would need to do retry the unuse logic again.
2243b56a2d8aSVineeth Remanan Pillai 	 * Under global memory pressure, swap entries can be reinserted back
2244b56a2d8aSVineeth Remanan Pillai 	 * into process space after the mmlist loop above passes over them.
2245dd862debSHugh Dickins 	 *
2246af53d3e9SHugh Dickins 	 * Limit the number of retries? No: when mmget_not_zero() above fails,
2247af53d3e9SHugh Dickins 	 * that mm is likely to be freeing swap from exit_mmap(), which proceeds
2248af53d3e9SHugh Dickins 	 * at its own independent pace; and even shmem_writepage() could have
2249af53d3e9SHugh Dickins 	 * been preempted after get_swap_page(), temporarily hiding that swap.
2250af53d3e9SHugh Dickins 	 * It's easy and robust (though cpu-intensive) just to keep retrying.
2251b56a2d8aSVineeth Remanan Pillai 	 */
225221820948SQian Cai 	if (READ_ONCE(si->inuse_pages)) {
225364165b1aSHugh Dickins 		if (!signal_pending(current))
2254b56a2d8aSVineeth Remanan Pillai 			goto retry;
225564165b1aSHugh Dickins 		retval = -EINTR;
225664165b1aSHugh Dickins 	}
2257b56a2d8aSVineeth Remanan Pillai out:
2258b56a2d8aSVineeth Remanan Pillai 	return (retval == FRONTSWAP_PAGES_UNUSED) ? 0 : retval;
22591da177e4SLinus Torvalds }
22601da177e4SLinus Torvalds 
22611da177e4SLinus Torvalds /*
22625d337b91SHugh Dickins  * After a successful try_to_unuse, if no swap is now in use, we know
22635d337b91SHugh Dickins  * we can empty the mmlist.  swap_lock must be held on entry and exit.
22645d337b91SHugh Dickins  * Note that mmlist_lock nests inside swap_lock, and an mm must be
22651da177e4SLinus Torvalds  * added to the mmlist just after page_duplicate - before would be racy.
22661da177e4SLinus Torvalds  */
22671da177e4SLinus Torvalds static void drain_mmlist(void)
22681da177e4SLinus Torvalds {
22691da177e4SLinus Torvalds 	struct list_head *p, *next;
2270efa90a98SHugh Dickins 	unsigned int type;
22711da177e4SLinus Torvalds 
2272efa90a98SHugh Dickins 	for (type = 0; type < nr_swapfiles; type++)
2273efa90a98SHugh Dickins 		if (swap_info[type]->inuse_pages)
22741da177e4SLinus Torvalds 			return;
22751da177e4SLinus Torvalds 	spin_lock(&mmlist_lock);
22761da177e4SLinus Torvalds 	list_for_each_safe(p, next, &init_mm.mmlist)
22771da177e4SLinus Torvalds 		list_del_init(p);
22781da177e4SLinus Torvalds 	spin_unlock(&mmlist_lock);
22791da177e4SLinus Torvalds }
22801da177e4SLinus Torvalds 
22811da177e4SLinus Torvalds /*
22821da177e4SLinus Torvalds  * Use this swapdev's extent info to locate the (PAGE_SIZE) block which
2283d4906e1aSLee Schermerhorn  * corresponds to page offset for the specified swap entry.
2284d4906e1aSLee Schermerhorn  * Note that the type of this function is sector_t, but it returns page offset
2285d4906e1aSLee Schermerhorn  * into the bdev, not sector offset.
22861da177e4SLinus Torvalds  */
2287d4906e1aSLee Schermerhorn static sector_t map_swap_entry(swp_entry_t entry, struct block_device **bdev)
22881da177e4SLinus Torvalds {
2289f29ad6a9SHugh Dickins 	struct swap_info_struct *sis;
2290f29ad6a9SHugh Dickins 	struct swap_extent *se;
2291f29ad6a9SHugh Dickins 	pgoff_t offset;
2292f29ad6a9SHugh Dickins 
2293c10d38ccSDaniel Jordan 	sis = swp_swap_info(entry);
2294f29ad6a9SHugh Dickins 	*bdev = sis->bdev;
2295f29ad6a9SHugh Dickins 
2296f29ad6a9SHugh Dickins 	offset = swp_offset(entry);
22974efaceb1SAaron Lu 	se = offset_to_swap_extent(sis, offset);
22981da177e4SLinus Torvalds 	return se->start_block + (offset - se->start_page);
22991da177e4SLinus Torvalds }
23001da177e4SLinus Torvalds 
23011da177e4SLinus Torvalds /*
2302d4906e1aSLee Schermerhorn  * Returns the page offset into bdev for the specified page's swap entry.
2303d4906e1aSLee Schermerhorn  */
2304d4906e1aSLee Schermerhorn sector_t map_swap_page(struct page *page, struct block_device **bdev)
2305d4906e1aSLee Schermerhorn {
2306d4906e1aSLee Schermerhorn 	swp_entry_t entry;
2307d4906e1aSLee Schermerhorn 	entry.val = page_private(page);
2308d4906e1aSLee Schermerhorn 	return map_swap_entry(entry, bdev);
2309d4906e1aSLee Schermerhorn }
2310d4906e1aSLee Schermerhorn 
2311d4906e1aSLee Schermerhorn /*
23121da177e4SLinus Torvalds  * Free all of a swapdev's extent information
23131da177e4SLinus Torvalds  */
23141da177e4SLinus Torvalds static void destroy_swap_extents(struct swap_info_struct *sis)
23151da177e4SLinus Torvalds {
23164efaceb1SAaron Lu 	while (!RB_EMPTY_ROOT(&sis->swap_extent_root)) {
23174efaceb1SAaron Lu 		struct rb_node *rb = sis->swap_extent_root.rb_node;
23184efaceb1SAaron Lu 		struct swap_extent *se = rb_entry(rb, struct swap_extent, rb_node);
23191da177e4SLinus Torvalds 
23204efaceb1SAaron Lu 		rb_erase(rb, &sis->swap_extent_root);
23211da177e4SLinus Torvalds 		kfree(se);
23221da177e4SLinus Torvalds 	}
232362c230bcSMel Gorman 
2324bc4ae27dSOmar Sandoval 	if (sis->flags & SWP_ACTIVATED) {
232562c230bcSMel Gorman 		struct file *swap_file = sis->swap_file;
232662c230bcSMel Gorman 		struct address_space *mapping = swap_file->f_mapping;
232762c230bcSMel Gorman 
2328bc4ae27dSOmar Sandoval 		sis->flags &= ~SWP_ACTIVATED;
2329bc4ae27dSOmar Sandoval 		if (mapping->a_ops->swap_deactivate)
233062c230bcSMel Gorman 			mapping->a_ops->swap_deactivate(swap_file);
233162c230bcSMel Gorman 	}
23321da177e4SLinus Torvalds }
23331da177e4SLinus Torvalds 
23341da177e4SLinus Torvalds /*
23351da177e4SLinus Torvalds  * Add a block range (and the corresponding page range) into this swapdev's
23364efaceb1SAaron Lu  * extent tree.
23371da177e4SLinus Torvalds  *
233811d31886SHugh Dickins  * This function rather assumes that it is called in ascending page order.
23391da177e4SLinus Torvalds  */
2340a509bc1aSMel Gorman int
23411da177e4SLinus Torvalds add_swap_extent(struct swap_info_struct *sis, unsigned long start_page,
23421da177e4SLinus Torvalds 		unsigned long nr_pages, sector_t start_block)
23431da177e4SLinus Torvalds {
23444efaceb1SAaron Lu 	struct rb_node **link = &sis->swap_extent_root.rb_node, *parent = NULL;
23451da177e4SLinus Torvalds 	struct swap_extent *se;
23461da177e4SLinus Torvalds 	struct swap_extent *new_se;
23471da177e4SLinus Torvalds 
23484efaceb1SAaron Lu 	/*
23494efaceb1SAaron Lu 	 * place the new node at the right most since the
23504efaceb1SAaron Lu 	 * function is called in ascending page order.
23514efaceb1SAaron Lu 	 */
23524efaceb1SAaron Lu 	while (*link) {
23534efaceb1SAaron Lu 		parent = *link;
23544efaceb1SAaron Lu 		link = &parent->rb_right;
23554efaceb1SAaron Lu 	}
23564efaceb1SAaron Lu 
23574efaceb1SAaron Lu 	if (parent) {
23584efaceb1SAaron Lu 		se = rb_entry(parent, struct swap_extent, rb_node);
235911d31886SHugh Dickins 		BUG_ON(se->start_page + se->nr_pages != start_page);
236011d31886SHugh Dickins 		if (se->start_block + se->nr_pages == start_block) {
23611da177e4SLinus Torvalds 			/* Merge it */
23621da177e4SLinus Torvalds 			se->nr_pages += nr_pages;
23631da177e4SLinus Torvalds 			return 0;
23641da177e4SLinus Torvalds 		}
23651da177e4SLinus Torvalds 	}
23661da177e4SLinus Torvalds 
23674efaceb1SAaron Lu 	/* No merge, insert a new extent. */
23681da177e4SLinus Torvalds 	new_se = kmalloc(sizeof(*se), GFP_KERNEL);
23691da177e4SLinus Torvalds 	if (new_se == NULL)
23701da177e4SLinus Torvalds 		return -ENOMEM;
23711da177e4SLinus Torvalds 	new_se->start_page = start_page;
23721da177e4SLinus Torvalds 	new_se->nr_pages = nr_pages;
23731da177e4SLinus Torvalds 	new_se->start_block = start_block;
23741da177e4SLinus Torvalds 
23754efaceb1SAaron Lu 	rb_link_node(&new_se->rb_node, parent, link);
23764efaceb1SAaron Lu 	rb_insert_color(&new_se->rb_node, &sis->swap_extent_root);
237753092a74SHugh Dickins 	return 1;
23781da177e4SLinus Torvalds }
2379aa8aa8a3SOmar Sandoval EXPORT_SYMBOL_GPL(add_swap_extent);
23801da177e4SLinus Torvalds 
23811da177e4SLinus Torvalds /*
23821da177e4SLinus Torvalds  * A `swap extent' is a simple thing which maps a contiguous range of pages
23831da177e4SLinus Torvalds  * onto a contiguous range of disk blocks.  An ordered list of swap extents
23841da177e4SLinus Torvalds  * is built at swapon time and is then used at swap_writepage/swap_readpage
23851da177e4SLinus Torvalds  * time for locating where on disk a page belongs.
23861da177e4SLinus Torvalds  *
23871da177e4SLinus Torvalds  * If the swapfile is an S_ISBLK block device, a single extent is installed.
23881da177e4SLinus Torvalds  * This is done so that the main operating code can treat S_ISBLK and S_ISREG
23891da177e4SLinus Torvalds  * swap files identically.
23901da177e4SLinus Torvalds  *
23911da177e4SLinus Torvalds  * Whether the swapdev is an S_ISREG file or an S_ISBLK blockdev, the swap
23921da177e4SLinus Torvalds  * extent list operates in PAGE_SIZE disk blocks.  Both S_ISREG and S_ISBLK
23931da177e4SLinus Torvalds  * swapfiles are handled *identically* after swapon time.
23941da177e4SLinus Torvalds  *
23951da177e4SLinus Torvalds  * For S_ISREG swapfiles, setup_swap_extents() will walk all the file's blocks
23961da177e4SLinus Torvalds  * and will parse them into an ordered extent list, in PAGE_SIZE chunks.  If
23971da177e4SLinus Torvalds  * some stray blocks are found which do not fall within the PAGE_SIZE alignment
23981da177e4SLinus Torvalds  * requirements, they are simply tossed out - we will never use those blocks
23991da177e4SLinus Torvalds  * for swapping.
24001da177e4SLinus Torvalds  *
24011638045cSDarrick J. Wong  * For all swap devices we set S_SWAPFILE across the life of the swapon.  This
24021638045cSDarrick J. Wong  * prevents users from writing to the swap device, which will corrupt memory.
24031da177e4SLinus Torvalds  *
24041da177e4SLinus Torvalds  * The amount of disk space which a single swap extent represents varies.
24051da177e4SLinus Torvalds  * Typically it is in the 1-4 megabyte range.  So we can have hundreds of
24061da177e4SLinus Torvalds  * extents in the list.  To avoid much list walking, we cache the previous
24071da177e4SLinus Torvalds  * search location in `curr_swap_extent', and start new searches from there.
24081da177e4SLinus Torvalds  * This is extremely effective.  The average number of iterations in
24091da177e4SLinus Torvalds  * map_swap_page() has been measured at about 0.3 per page.  - akpm.
24101da177e4SLinus Torvalds  */
241153092a74SHugh Dickins static int setup_swap_extents(struct swap_info_struct *sis, sector_t *span)
24121da177e4SLinus Torvalds {
241362c230bcSMel Gorman 	struct file *swap_file = sis->swap_file;
241462c230bcSMel Gorman 	struct address_space *mapping = swap_file->f_mapping;
241562c230bcSMel Gorman 	struct inode *inode = mapping->host;
24161da177e4SLinus Torvalds 	int ret;
24171da177e4SLinus Torvalds 
24181da177e4SLinus Torvalds 	if (S_ISBLK(inode->i_mode)) {
24191da177e4SLinus Torvalds 		ret = add_swap_extent(sis, 0, sis->max, 0);
242053092a74SHugh Dickins 		*span = sis->pages;
2421a509bc1aSMel Gorman 		return ret;
24221da177e4SLinus Torvalds 	}
24231da177e4SLinus Torvalds 
242462c230bcSMel Gorman 	if (mapping->a_ops->swap_activate) {
2425a509bc1aSMel Gorman 		ret = mapping->a_ops->swap_activate(sis, swap_file, span);
2426bc4ae27dSOmar Sandoval 		if (ret >= 0)
2427bc4ae27dSOmar Sandoval 			sis->flags |= SWP_ACTIVATED;
242862c230bcSMel Gorman 		if (!ret) {
2429bc4ae27dSOmar Sandoval 			sis->flags |= SWP_FS;
243062c230bcSMel Gorman 			ret = add_swap_extent(sis, 0, sis->max, 0);
243162c230bcSMel Gorman 			*span = sis->pages;
243262c230bcSMel Gorman 		}
24339625a5f2SHugh Dickins 		return ret;
2434a509bc1aSMel Gorman 	}
2435a509bc1aSMel Gorman 
2436a509bc1aSMel Gorman 	return generic_swapfile_activate(sis, swap_file, span);
24371da177e4SLinus Torvalds }
24381da177e4SLinus Torvalds 
2439a2468cc9SAaron Lu static int swap_node(struct swap_info_struct *p)
2440a2468cc9SAaron Lu {
2441a2468cc9SAaron Lu 	struct block_device *bdev;
2442a2468cc9SAaron Lu 
2443a2468cc9SAaron Lu 	if (p->bdev)
2444a2468cc9SAaron Lu 		bdev = p->bdev;
2445a2468cc9SAaron Lu 	else
2446a2468cc9SAaron Lu 		bdev = p->swap_file->f_inode->i_sb->s_bdev;
2447a2468cc9SAaron Lu 
2448a2468cc9SAaron Lu 	return bdev ? bdev->bd_disk->node_id : NUMA_NO_NODE;
2449a2468cc9SAaron Lu }
2450a2468cc9SAaron Lu 
2451eb085574SHuang Ying static void setup_swap_info(struct swap_info_struct *p, int prio,
24522a8f9449SShaohua Li 			    unsigned char *swap_map,
24532a8f9449SShaohua Li 			    struct swap_cluster_info *cluster_info)
245440531542SCesar Eduardo Barros {
2455a2468cc9SAaron Lu 	int i;
2456a2468cc9SAaron Lu 
245740531542SCesar Eduardo Barros 	if (prio >= 0)
245840531542SCesar Eduardo Barros 		p->prio = prio;
245940531542SCesar Eduardo Barros 	else
246040531542SCesar Eduardo Barros 		p->prio = --least_priority;
246118ab4d4cSDan Streetman 	/*
246218ab4d4cSDan Streetman 	 * the plist prio is negated because plist ordering is
246318ab4d4cSDan Streetman 	 * low-to-high, while swap ordering is high-to-low
246418ab4d4cSDan Streetman 	 */
246518ab4d4cSDan Streetman 	p->list.prio = -p->prio;
2466a2468cc9SAaron Lu 	for_each_node(i) {
2467a2468cc9SAaron Lu 		if (p->prio >= 0)
2468a2468cc9SAaron Lu 			p->avail_lists[i].prio = -p->prio;
2469a2468cc9SAaron Lu 		else {
2470a2468cc9SAaron Lu 			if (swap_node(p) == i)
2471a2468cc9SAaron Lu 				p->avail_lists[i].prio = 1;
2472a2468cc9SAaron Lu 			else
2473a2468cc9SAaron Lu 				p->avail_lists[i].prio = -p->prio;
2474a2468cc9SAaron Lu 		}
2475a2468cc9SAaron Lu 	}
247640531542SCesar Eduardo Barros 	p->swap_map = swap_map;
24772a8f9449SShaohua Li 	p->cluster_info = cluster_info;
2478eb085574SHuang Ying }
2479eb085574SHuang Ying 
2480eb085574SHuang Ying static void _enable_swap_info(struct swap_info_struct *p)
2481eb085574SHuang Ying {
2482eb085574SHuang Ying 	p->flags |= SWP_WRITEOK | SWP_VALID;
2483ec8acf20SShaohua Li 	atomic_long_add(p->pages, &nr_swap_pages);
248440531542SCesar Eduardo Barros 	total_swap_pages += p->pages;
248540531542SCesar Eduardo Barros 
2486adfab836SDan Streetman 	assert_spin_locked(&swap_lock);
2487adfab836SDan Streetman 	/*
248818ab4d4cSDan Streetman 	 * both lists are plists, and thus priority ordered.
248918ab4d4cSDan Streetman 	 * swap_active_head needs to be priority ordered for swapoff(),
249018ab4d4cSDan Streetman 	 * which on removal of any swap_info_struct with an auto-assigned
249118ab4d4cSDan Streetman 	 * (i.e. negative) priority increments the auto-assigned priority
249218ab4d4cSDan Streetman 	 * of any lower-priority swap_info_structs.
249318ab4d4cSDan Streetman 	 * swap_avail_head needs to be priority ordered for get_swap_page(),
249418ab4d4cSDan Streetman 	 * which allocates swap pages from the highest available priority
249518ab4d4cSDan Streetman 	 * swap_info_struct.
2496adfab836SDan Streetman 	 */
249718ab4d4cSDan Streetman 	plist_add(&p->list, &swap_active_head);
2498a2468cc9SAaron Lu 	add_to_avail_list(p);
2499cf0cac0aSCesar Eduardo Barros }
2500cf0cac0aSCesar Eduardo Barros 
2501cf0cac0aSCesar Eduardo Barros static void enable_swap_info(struct swap_info_struct *p, int prio,
2502cf0cac0aSCesar Eduardo Barros 				unsigned char *swap_map,
25032a8f9449SShaohua Li 				struct swap_cluster_info *cluster_info,
2504cf0cac0aSCesar Eduardo Barros 				unsigned long *frontswap_map)
2505cf0cac0aSCesar Eduardo Barros {
25064f89849dSMinchan Kim 	frontswap_init(p->type, frontswap_map);
2507cf0cac0aSCesar Eduardo Barros 	spin_lock(&swap_lock);
2508ec8acf20SShaohua Li 	spin_lock(&p->lock);
2509eb085574SHuang Ying 	setup_swap_info(p, prio, swap_map, cluster_info);
2510eb085574SHuang Ying 	spin_unlock(&p->lock);
2511eb085574SHuang Ying 	spin_unlock(&swap_lock);
2512eb085574SHuang Ying 	/*
2513eb085574SHuang Ying 	 * Guarantee swap_map, cluster_info, etc. fields are valid
2514eb085574SHuang Ying 	 * between get/put_swap_device() if SWP_VALID bit is set
2515eb085574SHuang Ying 	 */
2516eb085574SHuang Ying 	synchronize_rcu();
2517eb085574SHuang Ying 	spin_lock(&swap_lock);
2518eb085574SHuang Ying 	spin_lock(&p->lock);
2519eb085574SHuang Ying 	_enable_swap_info(p);
2520ec8acf20SShaohua Li 	spin_unlock(&p->lock);
2521cf0cac0aSCesar Eduardo Barros 	spin_unlock(&swap_lock);
2522cf0cac0aSCesar Eduardo Barros }
2523cf0cac0aSCesar Eduardo Barros 
2524cf0cac0aSCesar Eduardo Barros static void reinsert_swap_info(struct swap_info_struct *p)
2525cf0cac0aSCesar Eduardo Barros {
2526cf0cac0aSCesar Eduardo Barros 	spin_lock(&swap_lock);
2527ec8acf20SShaohua Li 	spin_lock(&p->lock);
2528eb085574SHuang Ying 	setup_swap_info(p, p->prio, p->swap_map, p->cluster_info);
2529eb085574SHuang Ying 	_enable_swap_info(p);
2530ec8acf20SShaohua Li 	spin_unlock(&p->lock);
253140531542SCesar Eduardo Barros 	spin_unlock(&swap_lock);
253240531542SCesar Eduardo Barros }
253340531542SCesar Eduardo Barros 
253467afa38eSTim Chen bool has_usable_swap(void)
253567afa38eSTim Chen {
253667afa38eSTim Chen 	bool ret = true;
253767afa38eSTim Chen 
253867afa38eSTim Chen 	spin_lock(&swap_lock);
253967afa38eSTim Chen 	if (plist_head_empty(&swap_active_head))
254067afa38eSTim Chen 		ret = false;
254167afa38eSTim Chen 	spin_unlock(&swap_lock);
254267afa38eSTim Chen 	return ret;
254367afa38eSTim Chen }
254467afa38eSTim Chen 
2545c4ea37c2SHeiko Carstens SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
25461da177e4SLinus Torvalds {
25471da177e4SLinus Torvalds 	struct swap_info_struct *p = NULL;
25488d69aaeeSHugh Dickins 	unsigned char *swap_map;
25492a8f9449SShaohua Li 	struct swap_cluster_info *cluster_info;
25504f89849dSMinchan Kim 	unsigned long *frontswap_map;
25511da177e4SLinus Torvalds 	struct file *swap_file, *victim;
25521da177e4SLinus Torvalds 	struct address_space *mapping;
25531da177e4SLinus Torvalds 	struct inode *inode;
255491a27b2aSJeff Layton 	struct filename *pathname;
2555adfab836SDan Streetman 	int err, found = 0;
25565b808a23SKrzysztof Kozlowski 	unsigned int old_block_size;
25571da177e4SLinus Torvalds 
25581da177e4SLinus Torvalds 	if (!capable(CAP_SYS_ADMIN))
25591da177e4SLinus Torvalds 		return -EPERM;
25601da177e4SLinus Torvalds 
2561191c5424SAl Viro 	BUG_ON(!current->mm);
2562191c5424SAl Viro 
25631da177e4SLinus Torvalds 	pathname = getname(specialfile);
25641da177e4SLinus Torvalds 	if (IS_ERR(pathname))
2565f58b59c1SXiaotian Feng 		return PTR_ERR(pathname);
25661da177e4SLinus Torvalds 
2567669abf4eSJeff Layton 	victim = file_open_name(pathname, O_RDWR|O_LARGEFILE, 0);
25681da177e4SLinus Torvalds 	err = PTR_ERR(victim);
25691da177e4SLinus Torvalds 	if (IS_ERR(victim))
25701da177e4SLinus Torvalds 		goto out;
25711da177e4SLinus Torvalds 
25721da177e4SLinus Torvalds 	mapping = victim->f_mapping;
25735d337b91SHugh Dickins 	spin_lock(&swap_lock);
257418ab4d4cSDan Streetman 	plist_for_each_entry(p, &swap_active_head, list) {
257522c6f8fdSHugh Dickins 		if (p->flags & SWP_WRITEOK) {
2576adfab836SDan Streetman 			if (p->swap_file->f_mapping == mapping) {
2577adfab836SDan Streetman 				found = 1;
25781da177e4SLinus Torvalds 				break;
25791da177e4SLinus Torvalds 			}
25801da177e4SLinus Torvalds 		}
2581adfab836SDan Streetman 	}
2582adfab836SDan Streetman 	if (!found) {
25831da177e4SLinus Torvalds 		err = -EINVAL;
25845d337b91SHugh Dickins 		spin_unlock(&swap_lock);
25851da177e4SLinus Torvalds 		goto out_dput;
25861da177e4SLinus Torvalds 	}
2587191c5424SAl Viro 	if (!security_vm_enough_memory_mm(current->mm, p->pages))
25881da177e4SLinus Torvalds 		vm_unacct_memory(p->pages);
25891da177e4SLinus Torvalds 	else {
25901da177e4SLinus Torvalds 		err = -ENOMEM;
25915d337b91SHugh Dickins 		spin_unlock(&swap_lock);
25921da177e4SLinus Torvalds 		goto out_dput;
25931da177e4SLinus Torvalds 	}
2594a2468cc9SAaron Lu 	del_from_avail_list(p);
2595ec8acf20SShaohua Li 	spin_lock(&p->lock);
259678ecba08SHugh Dickins 	if (p->prio < 0) {
2597adfab836SDan Streetman 		struct swap_info_struct *si = p;
2598a2468cc9SAaron Lu 		int nid;
2599adfab836SDan Streetman 
260018ab4d4cSDan Streetman 		plist_for_each_entry_continue(si, &swap_active_head, list) {
2601adfab836SDan Streetman 			si->prio++;
260218ab4d4cSDan Streetman 			si->list.prio--;
2603a2468cc9SAaron Lu 			for_each_node(nid) {
2604a2468cc9SAaron Lu 				if (si->avail_lists[nid].prio != 1)
2605a2468cc9SAaron Lu 					si->avail_lists[nid].prio--;
2606a2468cc9SAaron Lu 			}
2607adfab836SDan Streetman 		}
260878ecba08SHugh Dickins 		least_priority++;
260978ecba08SHugh Dickins 	}
261018ab4d4cSDan Streetman 	plist_del(&p->list, &swap_active_head);
2611ec8acf20SShaohua Li 	atomic_long_sub(p->pages, &nr_swap_pages);
26121da177e4SLinus Torvalds 	total_swap_pages -= p->pages;
26131da177e4SLinus Torvalds 	p->flags &= ~SWP_WRITEOK;
2614ec8acf20SShaohua Li 	spin_unlock(&p->lock);
26155d337b91SHugh Dickins 	spin_unlock(&swap_lock);
2616fb4f88dcSHugh Dickins 
2617039939a6STim Chen 	disable_swap_slots_cache_lock();
2618039939a6STim Chen 
2619e1e12d2fSDavid Rientjes 	set_current_oom_origin();
2620adfab836SDan Streetman 	err = try_to_unuse(p->type, false, 0); /* force unuse all pages */
2621e1e12d2fSDavid Rientjes 	clear_current_oom_origin();
26221da177e4SLinus Torvalds 
26231da177e4SLinus Torvalds 	if (err) {
26241da177e4SLinus Torvalds 		/* re-insert swap space back into swap_list */
2625cf0cac0aSCesar Eduardo Barros 		reinsert_swap_info(p);
2626039939a6STim Chen 		reenable_swap_slots_cache_unlock();
26271da177e4SLinus Torvalds 		goto out_dput;
26281da177e4SLinus Torvalds 	}
262952b7efdbSHugh Dickins 
2630039939a6STim Chen 	reenable_swap_slots_cache_unlock();
2631039939a6STim Chen 
2632eb085574SHuang Ying 	spin_lock(&swap_lock);
2633eb085574SHuang Ying 	spin_lock(&p->lock);
2634eb085574SHuang Ying 	p->flags &= ~SWP_VALID;		/* mark swap device as invalid */
2635eb085574SHuang Ying 	spin_unlock(&p->lock);
2636eb085574SHuang Ying 	spin_unlock(&swap_lock);
2637eb085574SHuang Ying 	/*
2638eb085574SHuang Ying 	 * wait for swap operations protected by get/put_swap_device()
2639eb085574SHuang Ying 	 * to complete
2640eb085574SHuang Ying 	 */
2641eb085574SHuang Ying 	synchronize_rcu();
2642eb085574SHuang Ying 
2643815c2c54SShaohua Li 	flush_work(&p->discard_work);
2644815c2c54SShaohua Li 
26454cd3bb10SHugh Dickins 	destroy_swap_extents(p);
2646570a335bSHugh Dickins 	if (p->flags & SWP_CONTINUED)
2647570a335bSHugh Dickins 		free_swap_count_continuations(p);
2648570a335bSHugh Dickins 
264981a0298bSHuang Ying 	if (!p->bdev || !blk_queue_nonrot(bdev_get_queue(p->bdev)))
265081a0298bSHuang Ying 		atomic_dec(&nr_rotate_swap);
265181a0298bSHuang Ying 
2652fc0abb14SIngo Molnar 	mutex_lock(&swapon_mutex);
26535d337b91SHugh Dickins 	spin_lock(&swap_lock);
2654ec8acf20SShaohua Li 	spin_lock(&p->lock);
26551da177e4SLinus Torvalds 	drain_mmlist();
26565d337b91SHugh Dickins 
26575d337b91SHugh Dickins 	/* wait for anyone still in scan_swap_map */
26585d337b91SHugh Dickins 	p->highest_bit = 0;		/* cuts scans short */
26595d337b91SHugh Dickins 	while (p->flags >= SWP_SCANNING) {
2660ec8acf20SShaohua Li 		spin_unlock(&p->lock);
26615d337b91SHugh Dickins 		spin_unlock(&swap_lock);
266213e4b57fSNishanth Aravamudan 		schedule_timeout_uninterruptible(1);
26635d337b91SHugh Dickins 		spin_lock(&swap_lock);
2664ec8acf20SShaohua Li 		spin_lock(&p->lock);
26655d337b91SHugh Dickins 	}
26665d337b91SHugh Dickins 
26671da177e4SLinus Torvalds 	swap_file = p->swap_file;
26685b808a23SKrzysztof Kozlowski 	old_block_size = p->old_block_size;
26691da177e4SLinus Torvalds 	p->swap_file = NULL;
26701da177e4SLinus Torvalds 	p->max = 0;
26711da177e4SLinus Torvalds 	swap_map = p->swap_map;
26721da177e4SLinus Torvalds 	p->swap_map = NULL;
26732a8f9449SShaohua Li 	cluster_info = p->cluster_info;
26742a8f9449SShaohua Li 	p->cluster_info = NULL;
26754f89849dSMinchan Kim 	frontswap_map = frontswap_map_get(p);
2676ec8acf20SShaohua Li 	spin_unlock(&p->lock);
26775d337b91SHugh Dickins 	spin_unlock(&swap_lock);
2678adfab836SDan Streetman 	frontswap_invalidate_area(p->type);
267958e97ba6SKrzysztof Kozlowski 	frontswap_map_set(p, NULL);
2680fc0abb14SIngo Molnar 	mutex_unlock(&swapon_mutex);
2681ebc2a1a6SShaohua Li 	free_percpu(p->percpu_cluster);
2682ebc2a1a6SShaohua Li 	p->percpu_cluster = NULL;
268349070588SHuang Ying 	free_percpu(p->cluster_next_cpu);
268449070588SHuang Ying 	p->cluster_next_cpu = NULL;
26851da177e4SLinus Torvalds 	vfree(swap_map);
268654f180d3SHuang Ying 	kvfree(cluster_info);
268754f180d3SHuang Ying 	kvfree(frontswap_map);
26882de1a7e4SSeth Jennings 	/* Destroy swap account information */
2689adfab836SDan Streetman 	swap_cgroup_swapoff(p->type);
26904b3ef9daSHuang, Ying 	exit_swap_address_space(p->type);
269127a7faa0SKAMEZAWA Hiroyuki 
26921da177e4SLinus Torvalds 	inode = mapping->host;
26931da177e4SLinus Torvalds 	if (S_ISBLK(inode->i_mode)) {
26941da177e4SLinus Torvalds 		struct block_device *bdev = I_BDEV(inode);
26951638045cSDarrick J. Wong 
26965b808a23SKrzysztof Kozlowski 		set_blocksize(bdev, old_block_size);
2697e525fd89STejun Heo 		blkdev_put(bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL);
26981638045cSDarrick J. Wong 	}
26991638045cSDarrick J. Wong 
27005955102cSAl Viro 	inode_lock(inode);
27011da177e4SLinus Torvalds 	inode->i_flags &= ~S_SWAPFILE;
27025955102cSAl Viro 	inode_unlock(inode);
27031da177e4SLinus Torvalds 	filp_close(swap_file, NULL);
2704f893ab41SWeijie Yang 
2705f893ab41SWeijie Yang 	/*
2706f893ab41SWeijie Yang 	 * Clear the SWP_USED flag after all resources are freed so that swapon
2707f893ab41SWeijie Yang 	 * can reuse this swap_info in alloc_swap_info() safely.  It is ok to
2708f893ab41SWeijie Yang 	 * not hold p->lock after we cleared its SWP_WRITEOK.
2709f893ab41SWeijie Yang 	 */
2710f893ab41SWeijie Yang 	spin_lock(&swap_lock);
2711f893ab41SWeijie Yang 	p->flags = 0;
2712f893ab41SWeijie Yang 	spin_unlock(&swap_lock);
2713f893ab41SWeijie Yang 
27141da177e4SLinus Torvalds 	err = 0;
271566d7dd51SKay Sievers 	atomic_inc(&proc_poll_event);
271666d7dd51SKay Sievers 	wake_up_interruptible(&proc_poll_wait);
27171da177e4SLinus Torvalds 
27181da177e4SLinus Torvalds out_dput:
27191da177e4SLinus Torvalds 	filp_close(victim, NULL);
27201da177e4SLinus Torvalds out:
2721f58b59c1SXiaotian Feng 	putname(pathname);
27221da177e4SLinus Torvalds 	return err;
27231da177e4SLinus Torvalds }
27241da177e4SLinus Torvalds 
27251da177e4SLinus Torvalds #ifdef CONFIG_PROC_FS
27269dd95748SAl Viro static __poll_t swaps_poll(struct file *file, poll_table *wait)
272766d7dd51SKay Sievers {
2728f1514638SKay Sievers 	struct seq_file *seq = file->private_data;
272966d7dd51SKay Sievers 
273066d7dd51SKay Sievers 	poll_wait(file, &proc_poll_wait, wait);
273166d7dd51SKay Sievers 
2732f1514638SKay Sievers 	if (seq->poll_event != atomic_read(&proc_poll_event)) {
2733f1514638SKay Sievers 		seq->poll_event = atomic_read(&proc_poll_event);
2734a9a08845SLinus Torvalds 		return EPOLLIN | EPOLLRDNORM | EPOLLERR | EPOLLPRI;
273566d7dd51SKay Sievers 	}
273666d7dd51SKay Sievers 
2737a9a08845SLinus Torvalds 	return EPOLLIN | EPOLLRDNORM;
273866d7dd51SKay Sievers }
273966d7dd51SKay Sievers 
27401da177e4SLinus Torvalds /* iterator */
27411da177e4SLinus Torvalds static void *swap_start(struct seq_file *swap, loff_t *pos)
27421da177e4SLinus Torvalds {
2743efa90a98SHugh Dickins 	struct swap_info_struct *si;
2744efa90a98SHugh Dickins 	int type;
27451da177e4SLinus Torvalds 	loff_t l = *pos;
27461da177e4SLinus Torvalds 
2747fc0abb14SIngo Molnar 	mutex_lock(&swapon_mutex);
27481da177e4SLinus Torvalds 
2749881e4aabSSuleiman Souhlal 	if (!l)
2750881e4aabSSuleiman Souhlal 		return SEQ_START_TOKEN;
2751881e4aabSSuleiman Souhlal 
2752c10d38ccSDaniel Jordan 	for (type = 0; (si = swap_type_to_swap_info(type)); type++) {
2753efa90a98SHugh Dickins 		if (!(si->flags & SWP_USED) || !si->swap_map)
27541da177e4SLinus Torvalds 			continue;
2755881e4aabSSuleiman Souhlal 		if (!--l)
2756efa90a98SHugh Dickins 			return si;
27571da177e4SLinus Torvalds 	}
27581da177e4SLinus Torvalds 
27591da177e4SLinus Torvalds 	return NULL;
27601da177e4SLinus Torvalds }
27611da177e4SLinus Torvalds 
27621da177e4SLinus Torvalds static void *swap_next(struct seq_file *swap, void *v, loff_t *pos)
27631da177e4SLinus Torvalds {
2764efa90a98SHugh Dickins 	struct swap_info_struct *si = v;
2765efa90a98SHugh Dickins 	int type;
27661da177e4SLinus Torvalds 
2767881e4aabSSuleiman Souhlal 	if (v == SEQ_START_TOKEN)
2768efa90a98SHugh Dickins 		type = 0;
2769efa90a98SHugh Dickins 	else
2770efa90a98SHugh Dickins 		type = si->type + 1;
2771881e4aabSSuleiman Souhlal 
277210c8d69fSVasily Averin 	++(*pos);
2773c10d38ccSDaniel Jordan 	for (; (si = swap_type_to_swap_info(type)); type++) {
2774efa90a98SHugh Dickins 		if (!(si->flags & SWP_USED) || !si->swap_map)
27751da177e4SLinus Torvalds 			continue;
2776efa90a98SHugh Dickins 		return si;
27771da177e4SLinus Torvalds 	}
27781da177e4SLinus Torvalds 
27791da177e4SLinus Torvalds 	return NULL;
27801da177e4SLinus Torvalds }
27811da177e4SLinus Torvalds 
27821da177e4SLinus Torvalds static void swap_stop(struct seq_file *swap, void *v)
27831da177e4SLinus Torvalds {
2784fc0abb14SIngo Molnar 	mutex_unlock(&swapon_mutex);
27851da177e4SLinus Torvalds }
27861da177e4SLinus Torvalds 
27871da177e4SLinus Torvalds static int swap_show(struct seq_file *swap, void *v)
27881da177e4SLinus Torvalds {
2789efa90a98SHugh Dickins 	struct swap_info_struct *si = v;
27901da177e4SLinus Torvalds 	struct file *file;
27911da177e4SLinus Torvalds 	int len;
27926f793940SRandy Dunlap 	unsigned int bytes, inuse;
27931da177e4SLinus Torvalds 
2794efa90a98SHugh Dickins 	if (si == SEQ_START_TOKEN) {
27956f793940SRandy Dunlap 		seq_puts(swap,"Filename\t\t\t\tType\t\tSize\t\tUsed\t\tPriority\n");
2796881e4aabSSuleiman Souhlal 		return 0;
2797881e4aabSSuleiman Souhlal 	}
27981da177e4SLinus Torvalds 
27996f793940SRandy Dunlap 	bytes = si->pages << (PAGE_SHIFT - 10);
28006f793940SRandy Dunlap 	inuse = si->inuse_pages << (PAGE_SHIFT - 10);
28016f793940SRandy Dunlap 
2802efa90a98SHugh Dickins 	file = si->swap_file;
28032726d566SMiklos Szeredi 	len = seq_file_path(swap, file, " \t\n\\");
28046f793940SRandy Dunlap 	seq_printf(swap, "%*s%s\t%u\t%s%u\t%s%d\n",
28051da177e4SLinus Torvalds 			len < 40 ? 40 - len : 1, " ",
2806496ad9aaSAl Viro 			S_ISBLK(file_inode(file)->i_mode) ?
28071da177e4SLinus Torvalds 				"partition" : "file\t",
28086f793940SRandy Dunlap 			bytes, bytes < 10000000 ? "\t" : "",
28096f793940SRandy Dunlap 			inuse, inuse < 10000000 ? "\t" : "",
2810efa90a98SHugh Dickins 			si->prio);
28111da177e4SLinus Torvalds 	return 0;
28121da177e4SLinus Torvalds }
28131da177e4SLinus Torvalds 
281415ad7cdcSHelge Deller static const struct seq_operations swaps_op = {
28151da177e4SLinus Torvalds 	.start =	swap_start,
28161da177e4SLinus Torvalds 	.next =		swap_next,
28171da177e4SLinus Torvalds 	.stop =		swap_stop,
28181da177e4SLinus Torvalds 	.show =		swap_show
28191da177e4SLinus Torvalds };
28201da177e4SLinus Torvalds 
28211da177e4SLinus Torvalds static int swaps_open(struct inode *inode, struct file *file)
28221da177e4SLinus Torvalds {
2823f1514638SKay Sievers 	struct seq_file *seq;
282466d7dd51SKay Sievers 	int ret;
282566d7dd51SKay Sievers 
282666d7dd51SKay Sievers 	ret = seq_open(file, &swaps_op);
2827f1514638SKay Sievers 	if (ret)
282866d7dd51SKay Sievers 		return ret;
282966d7dd51SKay Sievers 
2830f1514638SKay Sievers 	seq = file->private_data;
2831f1514638SKay Sievers 	seq->poll_event = atomic_read(&proc_poll_event);
2832f1514638SKay Sievers 	return 0;
28331da177e4SLinus Torvalds }
28341da177e4SLinus Torvalds 
283597a32539SAlexey Dobriyan static const struct proc_ops swaps_proc_ops = {
2836d919b33dSAlexey Dobriyan 	.proc_flags	= PROC_ENTRY_PERMANENT,
283797a32539SAlexey Dobriyan 	.proc_open	= swaps_open,
283897a32539SAlexey Dobriyan 	.proc_read	= seq_read,
283997a32539SAlexey Dobriyan 	.proc_lseek	= seq_lseek,
284097a32539SAlexey Dobriyan 	.proc_release	= seq_release,
284197a32539SAlexey Dobriyan 	.proc_poll	= swaps_poll,
28421da177e4SLinus Torvalds };
28431da177e4SLinus Torvalds 
28441da177e4SLinus Torvalds static int __init procswaps_init(void)
28451da177e4SLinus Torvalds {
284697a32539SAlexey Dobriyan 	proc_create("swaps", 0, NULL, &swaps_proc_ops);
28471da177e4SLinus Torvalds 	return 0;
28481da177e4SLinus Torvalds }
28491da177e4SLinus Torvalds __initcall(procswaps_init);
28501da177e4SLinus Torvalds #endif /* CONFIG_PROC_FS */
28511da177e4SLinus Torvalds 
28521796316aSJan Beulich #ifdef MAX_SWAPFILES_CHECK
28531796316aSJan Beulich static int __init max_swapfiles_check(void)
28541796316aSJan Beulich {
28551796316aSJan Beulich 	MAX_SWAPFILES_CHECK();
28561796316aSJan Beulich 	return 0;
28571796316aSJan Beulich }
28581796316aSJan Beulich late_initcall(max_swapfiles_check);
28591796316aSJan Beulich #endif
28601796316aSJan Beulich 
286153cbb243SCesar Eduardo Barros static struct swap_info_struct *alloc_swap_info(void)
28621da177e4SLinus Torvalds {
28631da177e4SLinus Torvalds 	struct swap_info_struct *p;
28641da177e4SLinus Torvalds 	unsigned int type;
2865a2468cc9SAaron Lu 	int i;
2866efa90a98SHugh Dickins 
286796008744SGustavo A. R. Silva 	p = kvzalloc(struct_size(p, avail_lists, nr_node_ids), GFP_KERNEL);
2868efa90a98SHugh Dickins 	if (!p)
286953cbb243SCesar Eduardo Barros 		return ERR_PTR(-ENOMEM);
2870efa90a98SHugh Dickins 
28715d337b91SHugh Dickins 	spin_lock(&swap_lock);
2872efa90a98SHugh Dickins 	for (type = 0; type < nr_swapfiles; type++) {
2873efa90a98SHugh Dickins 		if (!(swap_info[type]->flags & SWP_USED))
28741da177e4SLinus Torvalds 			break;
2875efa90a98SHugh Dickins 	}
28760697212aSChristoph Lameter 	if (type >= MAX_SWAPFILES) {
28775d337b91SHugh Dickins 		spin_unlock(&swap_lock);
2878873d7bcfSVasily Averin 		kvfree(p);
2879730c0581SCesar Eduardo Barros 		return ERR_PTR(-EPERM);
28801da177e4SLinus Torvalds 	}
2881efa90a98SHugh Dickins 	if (type >= nr_swapfiles) {
2882efa90a98SHugh Dickins 		p->type = type;
2883c10d38ccSDaniel Jordan 		WRITE_ONCE(swap_info[type], p);
2884efa90a98SHugh Dickins 		/*
2885efa90a98SHugh Dickins 		 * Write swap_info[type] before nr_swapfiles, in case a
2886efa90a98SHugh Dickins 		 * racing procfs swap_start() or swap_next() is reading them.
2887efa90a98SHugh Dickins 		 * (We never shrink nr_swapfiles, we never free this entry.)
2888efa90a98SHugh Dickins 		 */
2889efa90a98SHugh Dickins 		smp_wmb();
2890c10d38ccSDaniel Jordan 		WRITE_ONCE(nr_swapfiles, nr_swapfiles + 1);
2891efa90a98SHugh Dickins 	} else {
2892873d7bcfSVasily Averin 		kvfree(p);
2893efa90a98SHugh Dickins 		p = swap_info[type];
2894efa90a98SHugh Dickins 		/*
2895efa90a98SHugh Dickins 		 * Do not memset this entry: a racing procfs swap_next()
2896efa90a98SHugh Dickins 		 * would be relying on p->type to remain valid.
2897efa90a98SHugh Dickins 		 */
2898efa90a98SHugh Dickins 	}
28994efaceb1SAaron Lu 	p->swap_extent_root = RB_ROOT;
290018ab4d4cSDan Streetman 	plist_node_init(&p->list, 0);
2901a2468cc9SAaron Lu 	for_each_node(i)
2902a2468cc9SAaron Lu 		plist_node_init(&p->avail_lists[i], 0);
29031da177e4SLinus Torvalds 	p->flags = SWP_USED;
29045d337b91SHugh Dickins 	spin_unlock(&swap_lock);
2905ec8acf20SShaohua Li 	spin_lock_init(&p->lock);
29062628bd6fSHuang Ying 	spin_lock_init(&p->cont_lock);
2907efa90a98SHugh Dickins 
290853cbb243SCesar Eduardo Barros 	return p;
290953cbb243SCesar Eduardo Barros }
291053cbb243SCesar Eduardo Barros 
29114d0e1e10SCesar Eduardo Barros static int claim_swapfile(struct swap_info_struct *p, struct inode *inode)
29124d0e1e10SCesar Eduardo Barros {
29134d0e1e10SCesar Eduardo Barros 	int error;
29144d0e1e10SCesar Eduardo Barros 
29154d0e1e10SCesar Eduardo Barros 	if (S_ISBLK(inode->i_mode)) {
29164d0e1e10SCesar Eduardo Barros 		p->bdev = bdgrab(I_BDEV(inode));
29174d0e1e10SCesar Eduardo Barros 		error = blkdev_get(p->bdev,
29186f179af8SHugh Dickins 				   FMODE_READ | FMODE_WRITE | FMODE_EXCL, p);
29194d0e1e10SCesar Eduardo Barros 		if (error < 0) {
29204d0e1e10SCesar Eduardo Barros 			p->bdev = NULL;
29216f179af8SHugh Dickins 			return error;
29224d0e1e10SCesar Eduardo Barros 		}
29234d0e1e10SCesar Eduardo Barros 		p->old_block_size = block_size(p->bdev);
29244d0e1e10SCesar Eduardo Barros 		error = set_blocksize(p->bdev, PAGE_SIZE);
29254d0e1e10SCesar Eduardo Barros 		if (error < 0)
292687ade72aSCesar Eduardo Barros 			return error;
292712d2966dSNaohiro Aota 		/*
292812d2966dSNaohiro Aota 		 * Zoned block devices contain zones that have a sequential
292912d2966dSNaohiro Aota 		 * write only restriction.  Hence zoned block devices are not
293012d2966dSNaohiro Aota 		 * suitable for swapping.  Disallow them here.
293112d2966dSNaohiro Aota 		 */
293212d2966dSNaohiro Aota 		if (blk_queue_is_zoned(p->bdev->bd_queue))
293312d2966dSNaohiro Aota 			return -EINVAL;
29344d0e1e10SCesar Eduardo Barros 		p->flags |= SWP_BLKDEV;
29354d0e1e10SCesar Eduardo Barros 	} else if (S_ISREG(inode->i_mode)) {
29364d0e1e10SCesar Eduardo Barros 		p->bdev = inode->i_sb->s_bdev;
29371638045cSDarrick J. Wong 	}
29381638045cSDarrick J. Wong 
29394d0e1e10SCesar Eduardo Barros 	return 0;
29404d0e1e10SCesar Eduardo Barros }
29414d0e1e10SCesar Eduardo Barros 
2942377eeaa8SAndi Kleen 
2943377eeaa8SAndi Kleen /*
2944377eeaa8SAndi Kleen  * Find out how many pages are allowed for a single swap device. There
2945377eeaa8SAndi Kleen  * are two limiting factors:
2946377eeaa8SAndi Kleen  * 1) the number of bits for the swap offset in the swp_entry_t type, and
2947377eeaa8SAndi Kleen  * 2) the number of bits in the swap pte, as defined by the different
2948377eeaa8SAndi Kleen  * architectures.
2949377eeaa8SAndi Kleen  *
2950377eeaa8SAndi Kleen  * In order to find the largest possible bit mask, a swap entry with
2951377eeaa8SAndi Kleen  * swap type 0 and swap offset ~0UL is created, encoded to a swap pte,
2952377eeaa8SAndi Kleen  * decoded to a swp_entry_t again, and finally the swap offset is
2953377eeaa8SAndi Kleen  * extracted.
2954377eeaa8SAndi Kleen  *
2955377eeaa8SAndi Kleen  * This will mask all the bits from the initial ~0UL mask that can't
2956377eeaa8SAndi Kleen  * be encoded in either the swp_entry_t or the architecture definition
2957377eeaa8SAndi Kleen  * of a swap pte.
2958377eeaa8SAndi Kleen  */
2959377eeaa8SAndi Kleen unsigned long generic_max_swapfile_size(void)
2960377eeaa8SAndi Kleen {
2961377eeaa8SAndi Kleen 	return swp_offset(pte_to_swp_entry(
2962377eeaa8SAndi Kleen 			swp_entry_to_pte(swp_entry(0, ~0UL)))) + 1;
2963377eeaa8SAndi Kleen }
2964377eeaa8SAndi Kleen 
2965377eeaa8SAndi Kleen /* Can be overridden by an architecture for additional checks. */
2966377eeaa8SAndi Kleen __weak unsigned long max_swapfile_size(void)
2967377eeaa8SAndi Kleen {
2968377eeaa8SAndi Kleen 	return generic_max_swapfile_size();
2969377eeaa8SAndi Kleen }
2970377eeaa8SAndi Kleen 
2971ca8bd38bSCesar Eduardo Barros static unsigned long read_swap_header(struct swap_info_struct *p,
2972ca8bd38bSCesar Eduardo Barros 					union swap_header *swap_header,
2973ca8bd38bSCesar Eduardo Barros 					struct inode *inode)
2974ca8bd38bSCesar Eduardo Barros {
2975ca8bd38bSCesar Eduardo Barros 	int i;
2976ca8bd38bSCesar Eduardo Barros 	unsigned long maxpages;
2977ca8bd38bSCesar Eduardo Barros 	unsigned long swapfilepages;
2978d6bbbd29SRaymond Jennings 	unsigned long last_page;
2979ca8bd38bSCesar Eduardo Barros 
2980ca8bd38bSCesar Eduardo Barros 	if (memcmp("SWAPSPACE2", swap_header->magic.magic, 10)) {
2981465c47fdSAndrew Morton 		pr_err("Unable to find swap-space signature\n");
298238719025SCesar Eduardo Barros 		return 0;
2983ca8bd38bSCesar Eduardo Barros 	}
2984ca8bd38bSCesar Eduardo Barros 
2985ca8bd38bSCesar Eduardo Barros 	/* swap partition endianess hack... */
2986ca8bd38bSCesar Eduardo Barros 	if (swab32(swap_header->info.version) == 1) {
2987ca8bd38bSCesar Eduardo Barros 		swab32s(&swap_header->info.version);
2988ca8bd38bSCesar Eduardo Barros 		swab32s(&swap_header->info.last_page);
2989ca8bd38bSCesar Eduardo Barros 		swab32s(&swap_header->info.nr_badpages);
2990dd111be6SJann Horn 		if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES)
2991dd111be6SJann Horn 			return 0;
2992ca8bd38bSCesar Eduardo Barros 		for (i = 0; i < swap_header->info.nr_badpages; i++)
2993ca8bd38bSCesar Eduardo Barros 			swab32s(&swap_header->info.badpages[i]);
2994ca8bd38bSCesar Eduardo Barros 	}
2995ca8bd38bSCesar Eduardo Barros 	/* Check the swap header's sub-version */
2996ca8bd38bSCesar Eduardo Barros 	if (swap_header->info.version != 1) {
2997465c47fdSAndrew Morton 		pr_warn("Unable to handle swap header version %d\n",
2998ca8bd38bSCesar Eduardo Barros 			swap_header->info.version);
299938719025SCesar Eduardo Barros 		return 0;
3000ca8bd38bSCesar Eduardo Barros 	}
3001ca8bd38bSCesar Eduardo Barros 
3002ca8bd38bSCesar Eduardo Barros 	p->lowest_bit  = 1;
3003ca8bd38bSCesar Eduardo Barros 	p->cluster_next = 1;
3004ca8bd38bSCesar Eduardo Barros 	p->cluster_nr = 0;
3005ca8bd38bSCesar Eduardo Barros 
3006377eeaa8SAndi Kleen 	maxpages = max_swapfile_size();
3007d6bbbd29SRaymond Jennings 	last_page = swap_header->info.last_page;
3008a06ad633STom Abraham 	if (!last_page) {
3009a06ad633STom Abraham 		pr_warn("Empty swap-file\n");
3010a06ad633STom Abraham 		return 0;
3011a06ad633STom Abraham 	}
3012d6bbbd29SRaymond Jennings 	if (last_page > maxpages) {
3013465c47fdSAndrew Morton 		pr_warn("Truncating oversized swap area, only using %luk out of %luk\n",
3014d6bbbd29SRaymond Jennings 			maxpages << (PAGE_SHIFT - 10),
3015d6bbbd29SRaymond Jennings 			last_page << (PAGE_SHIFT - 10));
3016d6bbbd29SRaymond Jennings 	}
3017d6bbbd29SRaymond Jennings 	if (maxpages > last_page) {
3018d6bbbd29SRaymond Jennings 		maxpages = last_page + 1;
3019ca8bd38bSCesar Eduardo Barros 		/* p->max is an unsigned int: don't overflow it */
3020ca8bd38bSCesar Eduardo Barros 		if ((unsigned int)maxpages == 0)
3021ca8bd38bSCesar Eduardo Barros 			maxpages = UINT_MAX;
3022ca8bd38bSCesar Eduardo Barros 	}
3023ca8bd38bSCesar Eduardo Barros 	p->highest_bit = maxpages - 1;
3024ca8bd38bSCesar Eduardo Barros 
3025ca8bd38bSCesar Eduardo Barros 	if (!maxpages)
302638719025SCesar Eduardo Barros 		return 0;
3027ca8bd38bSCesar Eduardo Barros 	swapfilepages = i_size_read(inode) >> PAGE_SHIFT;
3028ca8bd38bSCesar Eduardo Barros 	if (swapfilepages && maxpages > swapfilepages) {
3029465c47fdSAndrew Morton 		pr_warn("Swap area shorter than signature indicates\n");
303038719025SCesar Eduardo Barros 		return 0;
3031ca8bd38bSCesar Eduardo Barros 	}
3032ca8bd38bSCesar Eduardo Barros 	if (swap_header->info.nr_badpages && S_ISREG(inode->i_mode))
303338719025SCesar Eduardo Barros 		return 0;
3034ca8bd38bSCesar Eduardo Barros 	if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES)
303538719025SCesar Eduardo Barros 		return 0;
3036ca8bd38bSCesar Eduardo Barros 
3037ca8bd38bSCesar Eduardo Barros 	return maxpages;
3038ca8bd38bSCesar Eduardo Barros }
3039ca8bd38bSCesar Eduardo Barros 
30404b3ef9daSHuang, Ying #define SWAP_CLUSTER_INFO_COLS						\
3041235b6217SHuang, Ying 	DIV_ROUND_UP(L1_CACHE_BYTES, sizeof(struct swap_cluster_info))
30424b3ef9daSHuang, Ying #define SWAP_CLUSTER_SPACE_COLS						\
30434b3ef9daSHuang, Ying 	DIV_ROUND_UP(SWAP_ADDRESS_SPACE_PAGES, SWAPFILE_CLUSTER)
30444b3ef9daSHuang, Ying #define SWAP_CLUSTER_COLS						\
30454b3ef9daSHuang, Ying 	max_t(unsigned int, SWAP_CLUSTER_INFO_COLS, SWAP_CLUSTER_SPACE_COLS)
3046235b6217SHuang, Ying 
3047915d4d7bSCesar Eduardo Barros static int setup_swap_map_and_extents(struct swap_info_struct *p,
3048915d4d7bSCesar Eduardo Barros 					union swap_header *swap_header,
3049915d4d7bSCesar Eduardo Barros 					unsigned char *swap_map,
30502a8f9449SShaohua Li 					struct swap_cluster_info *cluster_info,
3051915d4d7bSCesar Eduardo Barros 					unsigned long maxpages,
3052915d4d7bSCesar Eduardo Barros 					sector_t *span)
3053915d4d7bSCesar Eduardo Barros {
3054235b6217SHuang, Ying 	unsigned int j, k;
3055915d4d7bSCesar Eduardo Barros 	unsigned int nr_good_pages;
3056915d4d7bSCesar Eduardo Barros 	int nr_extents;
30572a8f9449SShaohua Li 	unsigned long nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
3058235b6217SHuang, Ying 	unsigned long col = p->cluster_next / SWAPFILE_CLUSTER % SWAP_CLUSTER_COLS;
3059235b6217SHuang, Ying 	unsigned long i, idx;
3060915d4d7bSCesar Eduardo Barros 
3061915d4d7bSCesar Eduardo Barros 	nr_good_pages = maxpages - 1;	/* omit header page */
3062915d4d7bSCesar Eduardo Barros 
30636b534915SHuang Ying 	cluster_list_init(&p->free_clusters);
30646b534915SHuang Ying 	cluster_list_init(&p->discard_clusters);
30652a8f9449SShaohua Li 
3066915d4d7bSCesar Eduardo Barros 	for (i = 0; i < swap_header->info.nr_badpages; i++) {
3067915d4d7bSCesar Eduardo Barros 		unsigned int page_nr = swap_header->info.badpages[i];
3068bdb8e3f6SCesar Eduardo Barros 		if (page_nr == 0 || page_nr > swap_header->info.last_page)
3069bdb8e3f6SCesar Eduardo Barros 			return -EINVAL;
3070915d4d7bSCesar Eduardo Barros 		if (page_nr < maxpages) {
3071915d4d7bSCesar Eduardo Barros 			swap_map[page_nr] = SWAP_MAP_BAD;
3072915d4d7bSCesar Eduardo Barros 			nr_good_pages--;
30732a8f9449SShaohua Li 			/*
30742a8f9449SShaohua Li 			 * Haven't marked the cluster free yet, no list
30752a8f9449SShaohua Li 			 * operation involved
30762a8f9449SShaohua Li 			 */
30772a8f9449SShaohua Li 			inc_cluster_info_page(p, cluster_info, page_nr);
3078915d4d7bSCesar Eduardo Barros 		}
3079915d4d7bSCesar Eduardo Barros 	}
3080915d4d7bSCesar Eduardo Barros 
30812a8f9449SShaohua Li 	/* Haven't marked the cluster free yet, no list operation involved */
30822a8f9449SShaohua Li 	for (i = maxpages; i < round_up(maxpages, SWAPFILE_CLUSTER); i++)
30832a8f9449SShaohua Li 		inc_cluster_info_page(p, cluster_info, i);
30842a8f9449SShaohua Li 
3085915d4d7bSCesar Eduardo Barros 	if (nr_good_pages) {
3086915d4d7bSCesar Eduardo Barros 		swap_map[0] = SWAP_MAP_BAD;
30872a8f9449SShaohua Li 		/*
30882a8f9449SShaohua Li 		 * Not mark the cluster free yet, no list
30892a8f9449SShaohua Li 		 * operation involved
30902a8f9449SShaohua Li 		 */
30912a8f9449SShaohua Li 		inc_cluster_info_page(p, cluster_info, 0);
3092915d4d7bSCesar Eduardo Barros 		p->max = maxpages;
3093915d4d7bSCesar Eduardo Barros 		p->pages = nr_good_pages;
3094915d4d7bSCesar Eduardo Barros 		nr_extents = setup_swap_extents(p, span);
3095bdb8e3f6SCesar Eduardo Barros 		if (nr_extents < 0)
3096bdb8e3f6SCesar Eduardo Barros 			return nr_extents;
3097915d4d7bSCesar Eduardo Barros 		nr_good_pages = p->pages;
3098915d4d7bSCesar Eduardo Barros 	}
3099915d4d7bSCesar Eduardo Barros 	if (!nr_good_pages) {
3100465c47fdSAndrew Morton 		pr_warn("Empty swap-file\n");
3101bdb8e3f6SCesar Eduardo Barros 		return -EINVAL;
3102915d4d7bSCesar Eduardo Barros 	}
3103915d4d7bSCesar Eduardo Barros 
31042a8f9449SShaohua Li 	if (!cluster_info)
31052a8f9449SShaohua Li 		return nr_extents;
31062a8f9449SShaohua Li 
3107235b6217SHuang, Ying 
31084b3ef9daSHuang, Ying 	/*
31094b3ef9daSHuang, Ying 	 * Reduce false cache line sharing between cluster_info and
31104b3ef9daSHuang, Ying 	 * sharing same address space.
31114b3ef9daSHuang, Ying 	 */
3112235b6217SHuang, Ying 	for (k = 0; k < SWAP_CLUSTER_COLS; k++) {
3113235b6217SHuang, Ying 		j = (k + col) % SWAP_CLUSTER_COLS;
3114235b6217SHuang, Ying 		for (i = 0; i < DIV_ROUND_UP(nr_clusters, SWAP_CLUSTER_COLS); i++) {
3115235b6217SHuang, Ying 			idx = i * SWAP_CLUSTER_COLS + j;
3116235b6217SHuang, Ying 			if (idx >= nr_clusters)
3117235b6217SHuang, Ying 				continue;
3118235b6217SHuang, Ying 			if (cluster_count(&cluster_info[idx]))
3119235b6217SHuang, Ying 				continue;
31202a8f9449SShaohua Li 			cluster_set_flag(&cluster_info[idx], CLUSTER_FLAG_FREE);
31216b534915SHuang Ying 			cluster_list_add_tail(&p->free_clusters, cluster_info,
31226b534915SHuang Ying 					      idx);
31232a8f9449SShaohua Li 		}
31242a8f9449SShaohua Li 	}
3125915d4d7bSCesar Eduardo Barros 	return nr_extents;
3126915d4d7bSCesar Eduardo Barros }
3127915d4d7bSCesar Eduardo Barros 
3128dcf6b7ddSRafael Aquini /*
3129dcf6b7ddSRafael Aquini  * Helper to sys_swapon determining if a given swap
3130dcf6b7ddSRafael Aquini  * backing device queue supports DISCARD operations.
3131dcf6b7ddSRafael Aquini  */
3132dcf6b7ddSRafael Aquini static bool swap_discardable(struct swap_info_struct *si)
3133dcf6b7ddSRafael Aquini {
3134dcf6b7ddSRafael Aquini 	struct request_queue *q = bdev_get_queue(si->bdev);
3135dcf6b7ddSRafael Aquini 
3136dcf6b7ddSRafael Aquini 	if (!q || !blk_queue_discard(q))
3137dcf6b7ddSRafael Aquini 		return false;
3138dcf6b7ddSRafael Aquini 
3139dcf6b7ddSRafael Aquini 	return true;
3140dcf6b7ddSRafael Aquini }
3141dcf6b7ddSRafael Aquini 
314253cbb243SCesar Eduardo Barros SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
314353cbb243SCesar Eduardo Barros {
314453cbb243SCesar Eduardo Barros 	struct swap_info_struct *p;
314591a27b2aSJeff Layton 	struct filename *name;
314653cbb243SCesar Eduardo Barros 	struct file *swap_file = NULL;
314753cbb243SCesar Eduardo Barros 	struct address_space *mapping;
314840531542SCesar Eduardo Barros 	int prio;
314953cbb243SCesar Eduardo Barros 	int error;
315053cbb243SCesar Eduardo Barros 	union swap_header *swap_header;
3151915d4d7bSCesar Eduardo Barros 	int nr_extents;
315253cbb243SCesar Eduardo Barros 	sector_t span;
315353cbb243SCesar Eduardo Barros 	unsigned long maxpages;
315453cbb243SCesar Eduardo Barros 	unsigned char *swap_map = NULL;
31552a8f9449SShaohua Li 	struct swap_cluster_info *cluster_info = NULL;
315638b5faf4SDan Magenheimer 	unsigned long *frontswap_map = NULL;
315753cbb243SCesar Eduardo Barros 	struct page *page = NULL;
315853cbb243SCesar Eduardo Barros 	struct inode *inode = NULL;
31597cbf3192SOmar Sandoval 	bool inced_nr_rotate_swap = false;
316053cbb243SCesar Eduardo Barros 
3161d15cab97SHugh Dickins 	if (swap_flags & ~SWAP_FLAGS_VALID)
3162d15cab97SHugh Dickins 		return -EINVAL;
3163d15cab97SHugh Dickins 
316453cbb243SCesar Eduardo Barros 	if (!capable(CAP_SYS_ADMIN))
316553cbb243SCesar Eduardo Barros 		return -EPERM;
316653cbb243SCesar Eduardo Barros 
3167a2468cc9SAaron Lu 	if (!swap_avail_heads)
3168a2468cc9SAaron Lu 		return -ENOMEM;
3169a2468cc9SAaron Lu 
317053cbb243SCesar Eduardo Barros 	p = alloc_swap_info();
31712542e513SCesar Eduardo Barros 	if (IS_ERR(p))
31722542e513SCesar Eduardo Barros 		return PTR_ERR(p);
317353cbb243SCesar Eduardo Barros 
3174815c2c54SShaohua Li 	INIT_WORK(&p->discard_work, swap_discard_work);
3175815c2c54SShaohua Li 
31761da177e4SLinus Torvalds 	name = getname(specialfile);
31771da177e4SLinus Torvalds 	if (IS_ERR(name)) {
31787de7fb6bSCesar Eduardo Barros 		error = PTR_ERR(name);
31791da177e4SLinus Torvalds 		name = NULL;
3180bd69010bSCesar Eduardo Barros 		goto bad_swap;
31811da177e4SLinus Torvalds 	}
3182669abf4eSJeff Layton 	swap_file = file_open_name(name, O_RDWR|O_LARGEFILE, 0);
31831da177e4SLinus Torvalds 	if (IS_ERR(swap_file)) {
31847de7fb6bSCesar Eduardo Barros 		error = PTR_ERR(swap_file);
31851da177e4SLinus Torvalds 		swap_file = NULL;
3186bd69010bSCesar Eduardo Barros 		goto bad_swap;
31871da177e4SLinus Torvalds 	}
31881da177e4SLinus Torvalds 
31891da177e4SLinus Torvalds 	p->swap_file = swap_file;
31901da177e4SLinus Torvalds 	mapping = swap_file->f_mapping;
31912130781eSCesar Eduardo Barros 	inode = mapping->host;
31926f179af8SHugh Dickins 
31934d0e1e10SCesar Eduardo Barros 	error = claim_swapfile(p, inode);
31944d0e1e10SCesar Eduardo Barros 	if (unlikely(error))
31951da177e4SLinus Torvalds 		goto bad_swap;
31961da177e4SLinus Torvalds 
3197d795a90eSNaohiro Aota 	inode_lock(inode);
3198d795a90eSNaohiro Aota 	if (IS_SWAPFILE(inode)) {
3199d795a90eSNaohiro Aota 		error = -EBUSY;
3200d795a90eSNaohiro Aota 		goto bad_swap_unlock_inode;
3201d795a90eSNaohiro Aota 	}
3202d795a90eSNaohiro Aota 
32031da177e4SLinus Torvalds 	/*
32041da177e4SLinus Torvalds 	 * Read the swap header.
32051da177e4SLinus Torvalds 	 */
32061da177e4SLinus Torvalds 	if (!mapping->a_ops->readpage) {
32071da177e4SLinus Torvalds 		error = -EINVAL;
3208d795a90eSNaohiro Aota 		goto bad_swap_unlock_inode;
32091da177e4SLinus Torvalds 	}
3210090d2b18SPekka Enberg 	page = read_mapping_page(mapping, 0, swap_file);
32111da177e4SLinus Torvalds 	if (IS_ERR(page)) {
32121da177e4SLinus Torvalds 		error = PTR_ERR(page);
3213d795a90eSNaohiro Aota 		goto bad_swap_unlock_inode;
32141da177e4SLinus Torvalds 	}
321581e33971SHugh Dickins 	swap_header = kmap(page);
32161da177e4SLinus Torvalds 
3217ca8bd38bSCesar Eduardo Barros 	maxpages = read_swap_header(p, swap_header, inode);
3218ca8bd38bSCesar Eduardo Barros 	if (unlikely(!maxpages)) {
32191da177e4SLinus Torvalds 		error = -EINVAL;
3220d795a90eSNaohiro Aota 		goto bad_swap_unlock_inode;
32211da177e4SLinus Torvalds 	}
32221da177e4SLinus Torvalds 
32231da177e4SLinus Torvalds 	/* OK, set up the swap map and apply the bad block list */
3224803d0c83SCesar Eduardo Barros 	swap_map = vzalloc(maxpages);
322578ecba08SHugh Dickins 	if (!swap_map) {
32261da177e4SLinus Torvalds 		error = -ENOMEM;
3227d795a90eSNaohiro Aota 		goto bad_swap_unlock_inode;
32281da177e4SLinus Torvalds 	}
3229f0571429SMinchan Kim 
3230f0571429SMinchan Kim 	if (bdi_cap_stable_pages_required(inode_to_bdi(inode)))
3231f0571429SMinchan Kim 		p->flags |= SWP_STABLE_WRITES;
3232f0571429SMinchan Kim 
3233539a6feaSMinchan Kim 	if (bdi_cap_synchronous_io(inode_to_bdi(inode)))
3234539a6feaSMinchan Kim 		p->flags |= SWP_SYNCHRONOUS_IO;
3235539a6feaSMinchan Kim 
32362a8f9449SShaohua Li 	if (p->bdev && blk_queue_nonrot(bdev_get_queue(p->bdev))) {
32376f179af8SHugh Dickins 		int cpu;
3238235b6217SHuang, Ying 		unsigned long ci, nr_cluster;
32396f179af8SHugh Dickins 
32402a8f9449SShaohua Li 		p->flags |= SWP_SOLIDSTATE;
324149070588SHuang Ying 		p->cluster_next_cpu = alloc_percpu(unsigned int);
324249070588SHuang Ying 		if (!p->cluster_next_cpu) {
324349070588SHuang Ying 			error = -ENOMEM;
324449070588SHuang Ying 			goto bad_swap_unlock_inode;
324549070588SHuang Ying 		}
32462a8f9449SShaohua Li 		/*
32472a8f9449SShaohua Li 		 * select a random position to start with to help wear leveling
32482a8f9449SShaohua Li 		 * SSD
32492a8f9449SShaohua Li 		 */
325049070588SHuang Ying 		for_each_possible_cpu(cpu) {
325149070588SHuang Ying 			per_cpu(*p->cluster_next_cpu, cpu) =
325249070588SHuang Ying 				1 + prandom_u32_max(p->highest_bit);
325349070588SHuang Ying 		}
3254235b6217SHuang, Ying 		nr_cluster = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
32552a8f9449SShaohua Li 
3256778e1cddSKees Cook 		cluster_info = kvcalloc(nr_cluster, sizeof(*cluster_info),
325754f180d3SHuang Ying 					GFP_KERNEL);
32582a8f9449SShaohua Li 		if (!cluster_info) {
32592a8f9449SShaohua Li 			error = -ENOMEM;
3260d795a90eSNaohiro Aota 			goto bad_swap_unlock_inode;
32612a8f9449SShaohua Li 		}
3262235b6217SHuang, Ying 
3263235b6217SHuang, Ying 		for (ci = 0; ci < nr_cluster; ci++)
3264235b6217SHuang, Ying 			spin_lock_init(&((cluster_info + ci)->lock));
3265235b6217SHuang, Ying 
3266ebc2a1a6SShaohua Li 		p->percpu_cluster = alloc_percpu(struct percpu_cluster);
3267ebc2a1a6SShaohua Li 		if (!p->percpu_cluster) {
3268ebc2a1a6SShaohua Li 			error = -ENOMEM;
3269d795a90eSNaohiro Aota 			goto bad_swap_unlock_inode;
3270ebc2a1a6SShaohua Li 		}
32716f179af8SHugh Dickins 		for_each_possible_cpu(cpu) {
3272ebc2a1a6SShaohua Li 			struct percpu_cluster *cluster;
32736f179af8SHugh Dickins 			cluster = per_cpu_ptr(p->percpu_cluster, cpu);
3274ebc2a1a6SShaohua Li 			cluster_set_null(&cluster->index);
3275ebc2a1a6SShaohua Li 		}
32767cbf3192SOmar Sandoval 	} else {
327781a0298bSHuang Ying 		atomic_inc(&nr_rotate_swap);
32787cbf3192SOmar Sandoval 		inced_nr_rotate_swap = true;
32797cbf3192SOmar Sandoval 	}
32801da177e4SLinus Torvalds 
32811421ef3cSCesar Eduardo Barros 	error = swap_cgroup_swapon(p->type, maxpages);
32821421ef3cSCesar Eduardo Barros 	if (error)
3283d795a90eSNaohiro Aota 		goto bad_swap_unlock_inode;
32841421ef3cSCesar Eduardo Barros 
3285915d4d7bSCesar Eduardo Barros 	nr_extents = setup_swap_map_and_extents(p, swap_header, swap_map,
32862a8f9449SShaohua Li 		cluster_info, maxpages, &span);
3287915d4d7bSCesar Eduardo Barros 	if (unlikely(nr_extents < 0)) {
328853092a74SHugh Dickins 		error = nr_extents;
3289d795a90eSNaohiro Aota 		goto bad_swap_unlock_inode;
329053092a74SHugh Dickins 	}
329138b5faf4SDan Magenheimer 	/* frontswap enabled? set up bit-per-page map for frontswap */
32928ea1d2a1SVlastimil Babka 	if (IS_ENABLED(CONFIG_FRONTSWAP))
3293778e1cddSKees Cook 		frontswap_map = kvcalloc(BITS_TO_LONGS(maxpages),
3294778e1cddSKees Cook 					 sizeof(long),
329554f180d3SHuang Ying 					 GFP_KERNEL);
32961da177e4SLinus Torvalds 
32972a8f9449SShaohua Li 	if (p->bdev &&(swap_flags & SWAP_FLAG_DISCARD) && swap_discardable(p)) {
3298dcf6b7ddSRafael Aquini 		/*
3299dcf6b7ddSRafael Aquini 		 * When discard is enabled for swap with no particular
3300dcf6b7ddSRafael Aquini 		 * policy flagged, we set all swap discard flags here in
3301dcf6b7ddSRafael Aquini 		 * order to sustain backward compatibility with older
3302dcf6b7ddSRafael Aquini 		 * swapon(8) releases.
3303dcf6b7ddSRafael Aquini 		 */
3304dcf6b7ddSRafael Aquini 		p->flags |= (SWP_DISCARDABLE | SWP_AREA_DISCARD |
3305dcf6b7ddSRafael Aquini 			     SWP_PAGE_DISCARD);
3306dcf6b7ddSRafael Aquini 
3307dcf6b7ddSRafael Aquini 		/*
3308dcf6b7ddSRafael Aquini 		 * By flagging sys_swapon, a sysadmin can tell us to
3309dcf6b7ddSRafael Aquini 		 * either do single-time area discards only, or to just
3310dcf6b7ddSRafael Aquini 		 * perform discards for released swap page-clusters.
3311dcf6b7ddSRafael Aquini 		 * Now it's time to adjust the p->flags accordingly.
3312dcf6b7ddSRafael Aquini 		 */
3313dcf6b7ddSRafael Aquini 		if (swap_flags & SWAP_FLAG_DISCARD_ONCE)
3314dcf6b7ddSRafael Aquini 			p->flags &= ~SWP_PAGE_DISCARD;
3315dcf6b7ddSRafael Aquini 		else if (swap_flags & SWAP_FLAG_DISCARD_PAGES)
3316dcf6b7ddSRafael Aquini 			p->flags &= ~SWP_AREA_DISCARD;
3317dcf6b7ddSRafael Aquini 
3318dcf6b7ddSRafael Aquini 		/* issue a swapon-time discard if it's still required */
3319dcf6b7ddSRafael Aquini 		if (p->flags & SWP_AREA_DISCARD) {
3320dcf6b7ddSRafael Aquini 			int err = discard_swap(p);
3321dcf6b7ddSRafael Aquini 			if (unlikely(err))
3322465c47fdSAndrew Morton 				pr_err("swapon: discard_swap(%p): %d\n",
3323dcf6b7ddSRafael Aquini 					p, err);
3324dcf6b7ddSRafael Aquini 		}
3325dcf6b7ddSRafael Aquini 	}
33266a6ba831SHugh Dickins 
33274b3ef9daSHuang, Ying 	error = init_swap_address_space(p->type, maxpages);
33284b3ef9daSHuang, Ying 	if (error)
3329d795a90eSNaohiro Aota 		goto bad_swap_unlock_inode;
33304b3ef9daSHuang, Ying 
3331dc617f29SDarrick J. Wong 	/*
3332dc617f29SDarrick J. Wong 	 * Flush any pending IO and dirty mappings before we start using this
3333dc617f29SDarrick J. Wong 	 * swap device.
3334dc617f29SDarrick J. Wong 	 */
3335dc617f29SDarrick J. Wong 	inode->i_flags |= S_SWAPFILE;
3336dc617f29SDarrick J. Wong 	error = inode_drain_writes(inode);
3337dc617f29SDarrick J. Wong 	if (error) {
3338dc617f29SDarrick J. Wong 		inode->i_flags &= ~S_SWAPFILE;
3339d795a90eSNaohiro Aota 		goto bad_swap_unlock_inode;
3340dc617f29SDarrick J. Wong 	}
3341dc617f29SDarrick J. Wong 
3342fc0abb14SIngo Molnar 	mutex_lock(&swapon_mutex);
334340531542SCesar Eduardo Barros 	prio = -1;
334478ecba08SHugh Dickins 	if (swap_flags & SWAP_FLAG_PREFER)
334540531542SCesar Eduardo Barros 		prio =
334678ecba08SHugh Dickins 		  (swap_flags & SWAP_FLAG_PRIO_MASK) >> SWAP_FLAG_PRIO_SHIFT;
33472a8f9449SShaohua Li 	enable_swap_info(p, prio, swap_map, cluster_info, frontswap_map);
3348c69dbfb8SCesar Eduardo Barros 
3349756a025fSJoe Perches 	pr_info("Adding %uk swap on %s.  Priority:%d extents:%d across:%lluk %s%s%s%s%s\n",
335091a27b2aSJeff Layton 		p->pages<<(PAGE_SHIFT-10), name->name, p->prio,
3351c69dbfb8SCesar Eduardo Barros 		nr_extents, (unsigned long long)span<<(PAGE_SHIFT-10),
3352c69dbfb8SCesar Eduardo Barros 		(p->flags & SWP_SOLIDSTATE) ? "SS" : "",
335338b5faf4SDan Magenheimer 		(p->flags & SWP_DISCARDABLE) ? "D" : "",
3354dcf6b7ddSRafael Aquini 		(p->flags & SWP_AREA_DISCARD) ? "s" : "",
3355dcf6b7ddSRafael Aquini 		(p->flags & SWP_PAGE_DISCARD) ? "c" : "",
335638b5faf4SDan Magenheimer 		(frontswap_map) ? "FS" : "");
3357c69dbfb8SCesar Eduardo Barros 
3358fc0abb14SIngo Molnar 	mutex_unlock(&swapon_mutex);
335966d7dd51SKay Sievers 	atomic_inc(&proc_poll_event);
336066d7dd51SKay Sievers 	wake_up_interruptible(&proc_poll_wait);
336166d7dd51SKay Sievers 
33621da177e4SLinus Torvalds 	error = 0;
33631da177e4SLinus Torvalds 	goto out;
3364d795a90eSNaohiro Aota bad_swap_unlock_inode:
3365d795a90eSNaohiro Aota 	inode_unlock(inode);
33661da177e4SLinus Torvalds bad_swap:
3367ebc2a1a6SShaohua Li 	free_percpu(p->percpu_cluster);
3368ebc2a1a6SShaohua Li 	p->percpu_cluster = NULL;
336949070588SHuang Ying 	free_percpu(p->cluster_next_cpu);
337049070588SHuang Ying 	p->cluster_next_cpu = NULL;
3371bd69010bSCesar Eduardo Barros 	if (inode && S_ISBLK(inode->i_mode) && p->bdev) {
3372f2090d2dSCesar Eduardo Barros 		set_blocksize(p->bdev, p->old_block_size);
3373f2090d2dSCesar Eduardo Barros 		blkdev_put(p->bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL);
33741da177e4SLinus Torvalds 	}
3375d795a90eSNaohiro Aota 	inode = NULL;
33764cd3bb10SHugh Dickins 	destroy_swap_extents(p);
3377e8e6c2ecSCesar Eduardo Barros 	swap_cgroup_swapoff(p->type);
33785d337b91SHugh Dickins 	spin_lock(&swap_lock);
33791da177e4SLinus Torvalds 	p->swap_file = NULL;
33801da177e4SLinus Torvalds 	p->flags = 0;
33815d337b91SHugh Dickins 	spin_unlock(&swap_lock);
33821da177e4SLinus Torvalds 	vfree(swap_map);
33838606a1a9SDarrick J. Wong 	kvfree(cluster_info);
3384b6b1fd2aSDavid Rientjes 	kvfree(frontswap_map);
33857cbf3192SOmar Sandoval 	if (inced_nr_rotate_swap)
33867cbf3192SOmar Sandoval 		atomic_dec(&nr_rotate_swap);
3387d795a90eSNaohiro Aota 	if (swap_file)
33881da177e4SLinus Torvalds 		filp_close(swap_file, NULL);
33891da177e4SLinus Torvalds out:
33901da177e4SLinus Torvalds 	if (page && !IS_ERR(page)) {
33911da177e4SLinus Torvalds 		kunmap(page);
339209cbfeafSKirill A. Shutemov 		put_page(page);
33931da177e4SLinus Torvalds 	}
33941da177e4SLinus Torvalds 	if (name)
33951da177e4SLinus Torvalds 		putname(name);
33961638045cSDarrick J. Wong 	if (inode)
33975955102cSAl Viro 		inode_unlock(inode);
3398039939a6STim Chen 	if (!error)
3399039939a6STim Chen 		enable_swap_slots_cache();
34001da177e4SLinus Torvalds 	return error;
34011da177e4SLinus Torvalds }
34021da177e4SLinus Torvalds 
34031da177e4SLinus Torvalds void si_swapinfo(struct sysinfo *val)
34041da177e4SLinus Torvalds {
3405efa90a98SHugh Dickins 	unsigned int type;
34061da177e4SLinus Torvalds 	unsigned long nr_to_be_unused = 0;
34071da177e4SLinus Torvalds 
34085d337b91SHugh Dickins 	spin_lock(&swap_lock);
3409efa90a98SHugh Dickins 	for (type = 0; type < nr_swapfiles; type++) {
3410efa90a98SHugh Dickins 		struct swap_info_struct *si = swap_info[type];
3411efa90a98SHugh Dickins 
3412efa90a98SHugh Dickins 		if ((si->flags & SWP_USED) && !(si->flags & SWP_WRITEOK))
3413efa90a98SHugh Dickins 			nr_to_be_unused += si->inuse_pages;
34141da177e4SLinus Torvalds 	}
3415ec8acf20SShaohua Li 	val->freeswap = atomic_long_read(&nr_swap_pages) + nr_to_be_unused;
34161da177e4SLinus Torvalds 	val->totalswap = total_swap_pages + nr_to_be_unused;
34175d337b91SHugh Dickins 	spin_unlock(&swap_lock);
34181da177e4SLinus Torvalds }
34191da177e4SLinus Torvalds 
34201da177e4SLinus Torvalds /*
34211da177e4SLinus Torvalds  * Verify that a swap entry is valid and increment its swap map count.
34221da177e4SLinus Torvalds  *
3423355cfa73SKAMEZAWA Hiroyuki  * Returns error code in following case.
3424355cfa73SKAMEZAWA Hiroyuki  * - success -> 0
3425355cfa73SKAMEZAWA Hiroyuki  * - swp_entry is invalid -> EINVAL
3426355cfa73SKAMEZAWA Hiroyuki  * - swp_entry is migration entry -> EINVAL
3427355cfa73SKAMEZAWA Hiroyuki  * - swap-cache reference is requested but there is already one. -> EEXIST
3428355cfa73SKAMEZAWA Hiroyuki  * - swap-cache reference is requested but the entry is not used. -> ENOENT
3429570a335bSHugh Dickins  * - swap-mapped reference requested but needs continued swap count. -> ENOMEM
34301da177e4SLinus Torvalds  */
34318d69aaeeSHugh Dickins static int __swap_duplicate(swp_entry_t entry, unsigned char usage)
34321da177e4SLinus Torvalds {
34331da177e4SLinus Torvalds 	struct swap_info_struct *p;
3434235b6217SHuang, Ying 	struct swap_cluster_info *ci;
3435c10d38ccSDaniel Jordan 	unsigned long offset;
34368d69aaeeSHugh Dickins 	unsigned char count;
34378d69aaeeSHugh Dickins 	unsigned char has_cache;
3438253d553bSHugh Dickins 	int err = -EINVAL;
34391da177e4SLinus Torvalds 
3440eb085574SHuang Ying 	p = get_swap_device(entry);
3441c10d38ccSDaniel Jordan 	if (!p)
3442eb085574SHuang Ying 		goto out;
3443c10d38ccSDaniel Jordan 
34441da177e4SLinus Torvalds 	offset = swp_offset(entry);
3445235b6217SHuang, Ying 	ci = lock_cluster_or_swap_info(p, offset);
3446355cfa73SKAMEZAWA Hiroyuki 
3447253d553bSHugh Dickins 	count = p->swap_map[offset];
3448edfe23daSShaohua Li 
3449edfe23daSShaohua Li 	/*
3450edfe23daSShaohua Li 	 * swapin_readahead() doesn't check if a swap entry is valid, so the
3451edfe23daSShaohua Li 	 * swap entry could be SWAP_MAP_BAD. Check here with lock held.
3452edfe23daSShaohua Li 	 */
3453edfe23daSShaohua Li 	if (unlikely(swap_count(count) == SWAP_MAP_BAD)) {
3454edfe23daSShaohua Li 		err = -ENOENT;
3455edfe23daSShaohua Li 		goto unlock_out;
3456edfe23daSShaohua Li 	}
3457edfe23daSShaohua Li 
3458253d553bSHugh Dickins 	has_cache = count & SWAP_HAS_CACHE;
3459253d553bSHugh Dickins 	count &= ~SWAP_HAS_CACHE;
3460253d553bSHugh Dickins 	err = 0;
3461355cfa73SKAMEZAWA Hiroyuki 
3462253d553bSHugh Dickins 	if (usage == SWAP_HAS_CACHE) {
3463355cfa73SKAMEZAWA Hiroyuki 
3464355cfa73SKAMEZAWA Hiroyuki 		/* set SWAP_HAS_CACHE if there is no cache and entry is used */
3465253d553bSHugh Dickins 		if (!has_cache && count)
3466253d553bSHugh Dickins 			has_cache = SWAP_HAS_CACHE;
3467253d553bSHugh Dickins 		else if (has_cache)		/* someone else added cache */
3468253d553bSHugh Dickins 			err = -EEXIST;
3469253d553bSHugh Dickins 		else				/* no users remaining */
3470253d553bSHugh Dickins 			err = -ENOENT;
3471355cfa73SKAMEZAWA Hiroyuki 
3472355cfa73SKAMEZAWA Hiroyuki 	} else if (count || has_cache) {
3473253d553bSHugh Dickins 
3474570a335bSHugh Dickins 		if ((count & ~COUNT_CONTINUED) < SWAP_MAP_MAX)
3475570a335bSHugh Dickins 			count += usage;
3476570a335bSHugh Dickins 		else if ((count & ~COUNT_CONTINUED) > SWAP_MAP_MAX)
3477253d553bSHugh Dickins 			err = -EINVAL;
3478570a335bSHugh Dickins 		else if (swap_count_continued(p, offset, count))
3479570a335bSHugh Dickins 			count = COUNT_CONTINUED;
3480570a335bSHugh Dickins 		else
3481570a335bSHugh Dickins 			err = -ENOMEM;
3482253d553bSHugh Dickins 	} else
3483253d553bSHugh Dickins 		err = -ENOENT;			/* unused swap entry */
3484253d553bSHugh Dickins 
3485253d553bSHugh Dickins 	p->swap_map[offset] = count | has_cache;
3486253d553bSHugh Dickins 
3487355cfa73SKAMEZAWA Hiroyuki unlock_out:
3488235b6217SHuang, Ying 	unlock_cluster_or_swap_info(p, ci);
34891da177e4SLinus Torvalds out:
3490eb085574SHuang Ying 	if (p)
3491eb085574SHuang Ying 		put_swap_device(p);
3492253d553bSHugh Dickins 	return err;
34931da177e4SLinus Torvalds }
3494253d553bSHugh Dickins 
3495355cfa73SKAMEZAWA Hiroyuki /*
3496aaa46865SHugh Dickins  * Help swapoff by noting that swap entry belongs to shmem/tmpfs
3497aaa46865SHugh Dickins  * (in which case its reference count is never incremented).
3498aaa46865SHugh Dickins  */
3499aaa46865SHugh Dickins void swap_shmem_alloc(swp_entry_t entry)
3500aaa46865SHugh Dickins {
3501aaa46865SHugh Dickins 	__swap_duplicate(entry, SWAP_MAP_SHMEM);
3502aaa46865SHugh Dickins }
3503aaa46865SHugh Dickins 
3504aaa46865SHugh Dickins /*
350508259d58SHugh Dickins  * Increase reference count of swap entry by 1.
350608259d58SHugh Dickins  * Returns 0 for success, or -ENOMEM if a swap_count_continuation is required
350708259d58SHugh Dickins  * but could not be atomically allocated.  Returns 0, just as if it succeeded,
350808259d58SHugh Dickins  * if __swap_duplicate() fails for another reason (-EINVAL or -ENOENT), which
350908259d58SHugh Dickins  * might occur if a page table entry has got corrupted.
3510355cfa73SKAMEZAWA Hiroyuki  */
3511570a335bSHugh Dickins int swap_duplicate(swp_entry_t entry)
3512355cfa73SKAMEZAWA Hiroyuki {
3513570a335bSHugh Dickins 	int err = 0;
3514570a335bSHugh Dickins 
3515570a335bSHugh Dickins 	while (!err && __swap_duplicate(entry, 1) == -ENOMEM)
3516570a335bSHugh Dickins 		err = add_swap_count_continuation(entry, GFP_ATOMIC);
3517570a335bSHugh Dickins 	return err;
3518355cfa73SKAMEZAWA Hiroyuki }
35191da177e4SLinus Torvalds 
3520cb4b86baSKAMEZAWA Hiroyuki /*
3521355cfa73SKAMEZAWA Hiroyuki  * @entry: swap entry for which we allocate swap cache.
3522355cfa73SKAMEZAWA Hiroyuki  *
352373c34b6aSHugh Dickins  * Called when allocating swap cache for existing swap entry,
3524355cfa73SKAMEZAWA Hiroyuki  * This can return error codes. Returns 0 at success.
35253eeba135SChen Wandun  * -EEXIST means there is a swap cache.
3526355cfa73SKAMEZAWA Hiroyuki  * Note: return code is different from swap_duplicate().
3527cb4b86baSKAMEZAWA Hiroyuki  */
3528cb4b86baSKAMEZAWA Hiroyuki int swapcache_prepare(swp_entry_t entry)
3529cb4b86baSKAMEZAWA Hiroyuki {
3530253d553bSHugh Dickins 	return __swap_duplicate(entry, SWAP_HAS_CACHE);
3531cb4b86baSKAMEZAWA Hiroyuki }
3532cb4b86baSKAMEZAWA Hiroyuki 
35330bcac06fSMinchan Kim struct swap_info_struct *swp_swap_info(swp_entry_t entry)
35340bcac06fSMinchan Kim {
3535c10d38ccSDaniel Jordan 	return swap_type_to_swap_info(swp_type(entry));
35360bcac06fSMinchan Kim }
35370bcac06fSMinchan Kim 
3538f981c595SMel Gorman struct swap_info_struct *page_swap_info(struct page *page)
3539f981c595SMel Gorman {
35400bcac06fSMinchan Kim 	swp_entry_t entry = { .val = page_private(page) };
35410bcac06fSMinchan Kim 	return swp_swap_info(entry);
3542f981c595SMel Gorman }
3543f981c595SMel Gorman 
3544f981c595SMel Gorman /*
3545f981c595SMel Gorman  * out-of-line __page_file_ methods to avoid include hell.
3546f981c595SMel Gorman  */
3547f981c595SMel Gorman struct address_space *__page_file_mapping(struct page *page)
3548f981c595SMel Gorman {
3549f981c595SMel Gorman 	return page_swap_info(page)->swap_file->f_mapping;
3550f981c595SMel Gorman }
3551f981c595SMel Gorman EXPORT_SYMBOL_GPL(__page_file_mapping);
3552f981c595SMel Gorman 
3553f981c595SMel Gorman pgoff_t __page_file_index(struct page *page)
3554f981c595SMel Gorman {
3555f981c595SMel Gorman 	swp_entry_t swap = { .val = page_private(page) };
3556f981c595SMel Gorman 	return swp_offset(swap);
3557f981c595SMel Gorman }
3558f981c595SMel Gorman EXPORT_SYMBOL_GPL(__page_file_index);
3559f981c595SMel Gorman 
35601da177e4SLinus Torvalds /*
3561570a335bSHugh Dickins  * add_swap_count_continuation - called when a swap count is duplicated
3562570a335bSHugh Dickins  * beyond SWAP_MAP_MAX, it allocates a new page and links that to the entry's
3563570a335bSHugh Dickins  * page of the original vmalloc'ed swap_map, to hold the continuation count
3564570a335bSHugh Dickins  * (for that entry and for its neighbouring PAGE_SIZE swap entries).  Called
3565570a335bSHugh Dickins  * again when count is duplicated beyond SWAP_MAP_MAX * SWAP_CONT_MAX, etc.
3566570a335bSHugh Dickins  *
3567570a335bSHugh Dickins  * These continuation pages are seldom referenced: the common paths all work
3568570a335bSHugh Dickins  * on the original swap_map, only referring to a continuation page when the
3569570a335bSHugh Dickins  * low "digit" of a count is incremented or decremented through SWAP_MAP_MAX.
3570570a335bSHugh Dickins  *
3571570a335bSHugh Dickins  * add_swap_count_continuation(, GFP_ATOMIC) can be called while holding
3572570a335bSHugh Dickins  * page table locks; if it fails, add_swap_count_continuation(, GFP_KERNEL)
3573570a335bSHugh Dickins  * can be called after dropping locks.
3574570a335bSHugh Dickins  */
3575570a335bSHugh Dickins int add_swap_count_continuation(swp_entry_t entry, gfp_t gfp_mask)
3576570a335bSHugh Dickins {
3577570a335bSHugh Dickins 	struct swap_info_struct *si;
3578235b6217SHuang, Ying 	struct swap_cluster_info *ci;
3579570a335bSHugh Dickins 	struct page *head;
3580570a335bSHugh Dickins 	struct page *page;
3581570a335bSHugh Dickins 	struct page *list_page;
3582570a335bSHugh Dickins 	pgoff_t offset;
3583570a335bSHugh Dickins 	unsigned char count;
3584eb085574SHuang Ying 	int ret = 0;
3585570a335bSHugh Dickins 
3586570a335bSHugh Dickins 	/*
3587570a335bSHugh Dickins 	 * When debugging, it's easier to use __GFP_ZERO here; but it's better
3588570a335bSHugh Dickins 	 * for latency not to zero a page while GFP_ATOMIC and holding locks.
3589570a335bSHugh Dickins 	 */
3590570a335bSHugh Dickins 	page = alloc_page(gfp_mask | __GFP_HIGHMEM);
3591570a335bSHugh Dickins 
3592eb085574SHuang Ying 	si = get_swap_device(entry);
3593570a335bSHugh Dickins 	if (!si) {
3594570a335bSHugh Dickins 		/*
3595570a335bSHugh Dickins 		 * An acceptable race has occurred since the failing
3596eb085574SHuang Ying 		 * __swap_duplicate(): the swap device may be swapoff
3597570a335bSHugh Dickins 		 */
3598570a335bSHugh Dickins 		goto outer;
3599570a335bSHugh Dickins 	}
3600eb085574SHuang Ying 	spin_lock(&si->lock);
3601570a335bSHugh Dickins 
3602570a335bSHugh Dickins 	offset = swp_offset(entry);
3603235b6217SHuang, Ying 
3604235b6217SHuang, Ying 	ci = lock_cluster(si, offset);
3605235b6217SHuang, Ying 
3606570a335bSHugh Dickins 	count = si->swap_map[offset] & ~SWAP_HAS_CACHE;
3607570a335bSHugh Dickins 
3608570a335bSHugh Dickins 	if ((count & ~COUNT_CONTINUED) != SWAP_MAP_MAX) {
3609570a335bSHugh Dickins 		/*
3610570a335bSHugh Dickins 		 * The higher the swap count, the more likely it is that tasks
3611570a335bSHugh Dickins 		 * will race to add swap count continuation: we need to avoid
3612570a335bSHugh Dickins 		 * over-provisioning.
3613570a335bSHugh Dickins 		 */
3614570a335bSHugh Dickins 		goto out;
3615570a335bSHugh Dickins 	}
3616570a335bSHugh Dickins 
3617570a335bSHugh Dickins 	if (!page) {
3618eb085574SHuang Ying 		ret = -ENOMEM;
3619eb085574SHuang Ying 		goto out;
3620570a335bSHugh Dickins 	}
3621570a335bSHugh Dickins 
3622570a335bSHugh Dickins 	/*
3623570a335bSHugh Dickins 	 * We are fortunate that although vmalloc_to_page uses pte_offset_map,
3624570a335bSHugh Dickins 	 * no architecture is using highmem pages for kernel page tables: so it
3625570a335bSHugh Dickins 	 * will not corrupt the GFP_ATOMIC caller's atomic page table kmaps.
3626570a335bSHugh Dickins 	 */
3627570a335bSHugh Dickins 	head = vmalloc_to_page(si->swap_map + offset);
3628570a335bSHugh Dickins 	offset &= ~PAGE_MASK;
3629570a335bSHugh Dickins 
36302628bd6fSHuang Ying 	spin_lock(&si->cont_lock);
3631570a335bSHugh Dickins 	/*
3632570a335bSHugh Dickins 	 * Page allocation does not initialize the page's lru field,
3633570a335bSHugh Dickins 	 * but it does always reset its private field.
3634570a335bSHugh Dickins 	 */
3635570a335bSHugh Dickins 	if (!page_private(head)) {
3636570a335bSHugh Dickins 		BUG_ON(count & COUNT_CONTINUED);
3637570a335bSHugh Dickins 		INIT_LIST_HEAD(&head->lru);
3638570a335bSHugh Dickins 		set_page_private(head, SWP_CONTINUED);
3639570a335bSHugh Dickins 		si->flags |= SWP_CONTINUED;
3640570a335bSHugh Dickins 	}
3641570a335bSHugh Dickins 
3642570a335bSHugh Dickins 	list_for_each_entry(list_page, &head->lru, lru) {
3643570a335bSHugh Dickins 		unsigned char *map;
3644570a335bSHugh Dickins 
3645570a335bSHugh Dickins 		/*
3646570a335bSHugh Dickins 		 * If the previous map said no continuation, but we've found
3647570a335bSHugh Dickins 		 * a continuation page, free our allocation and use this one.
3648570a335bSHugh Dickins 		 */
3649570a335bSHugh Dickins 		if (!(count & COUNT_CONTINUED))
36502628bd6fSHuang Ying 			goto out_unlock_cont;
3651570a335bSHugh Dickins 
36529b04c5feSCong Wang 		map = kmap_atomic(list_page) + offset;
3653570a335bSHugh Dickins 		count = *map;
36549b04c5feSCong Wang 		kunmap_atomic(map);
3655570a335bSHugh Dickins 
3656570a335bSHugh Dickins 		/*
3657570a335bSHugh Dickins 		 * If this continuation count now has some space in it,
3658570a335bSHugh Dickins 		 * free our allocation and use this one.
3659570a335bSHugh Dickins 		 */
3660570a335bSHugh Dickins 		if ((count & ~COUNT_CONTINUED) != SWAP_CONT_MAX)
36612628bd6fSHuang Ying 			goto out_unlock_cont;
3662570a335bSHugh Dickins 	}
3663570a335bSHugh Dickins 
3664570a335bSHugh Dickins 	list_add_tail(&page->lru, &head->lru);
3665570a335bSHugh Dickins 	page = NULL;			/* now it's attached, don't free it */
36662628bd6fSHuang Ying out_unlock_cont:
36672628bd6fSHuang Ying 	spin_unlock(&si->cont_lock);
3668570a335bSHugh Dickins out:
3669235b6217SHuang, Ying 	unlock_cluster(ci);
3670ec8acf20SShaohua Li 	spin_unlock(&si->lock);
3671eb085574SHuang Ying 	put_swap_device(si);
3672570a335bSHugh Dickins outer:
3673570a335bSHugh Dickins 	if (page)
3674570a335bSHugh Dickins 		__free_page(page);
3675eb085574SHuang Ying 	return ret;
3676570a335bSHugh Dickins }
3677570a335bSHugh Dickins 
3678570a335bSHugh Dickins /*
3679570a335bSHugh Dickins  * swap_count_continued - when the original swap_map count is incremented
3680570a335bSHugh Dickins  * from SWAP_MAP_MAX, check if there is already a continuation page to carry
3681570a335bSHugh Dickins  * into, carry if so, or else fail until a new continuation page is allocated;
3682570a335bSHugh Dickins  * when the original swap_map count is decremented from 0 with continuation,
3683570a335bSHugh Dickins  * borrow from the continuation and report whether it still holds more.
3684235b6217SHuang, Ying  * Called while __swap_duplicate() or swap_entry_free() holds swap or cluster
3685235b6217SHuang, Ying  * lock.
3686570a335bSHugh Dickins  */
3687570a335bSHugh Dickins static bool swap_count_continued(struct swap_info_struct *si,
3688570a335bSHugh Dickins 				 pgoff_t offset, unsigned char count)
3689570a335bSHugh Dickins {
3690570a335bSHugh Dickins 	struct page *head;
3691570a335bSHugh Dickins 	struct page *page;
3692570a335bSHugh Dickins 	unsigned char *map;
36932628bd6fSHuang Ying 	bool ret;
3694570a335bSHugh Dickins 
3695570a335bSHugh Dickins 	head = vmalloc_to_page(si->swap_map + offset);
3696570a335bSHugh Dickins 	if (page_private(head) != SWP_CONTINUED) {
3697570a335bSHugh Dickins 		BUG_ON(count & COUNT_CONTINUED);
3698570a335bSHugh Dickins 		return false;		/* need to add count continuation */
3699570a335bSHugh Dickins 	}
3700570a335bSHugh Dickins 
37012628bd6fSHuang Ying 	spin_lock(&si->cont_lock);
3702570a335bSHugh Dickins 	offset &= ~PAGE_MASK;
3703213516acSchenqiwu 	page = list_next_entry(head, lru);
37049b04c5feSCong Wang 	map = kmap_atomic(page) + offset;
3705570a335bSHugh Dickins 
3706570a335bSHugh Dickins 	if (count == SWAP_MAP_MAX)	/* initial increment from swap_map */
3707570a335bSHugh Dickins 		goto init_map;		/* jump over SWAP_CONT_MAX checks */
3708570a335bSHugh Dickins 
3709570a335bSHugh Dickins 	if (count == (SWAP_MAP_MAX | COUNT_CONTINUED)) { /* incrementing */
3710570a335bSHugh Dickins 		/*
3711570a335bSHugh Dickins 		 * Think of how you add 1 to 999
3712570a335bSHugh Dickins 		 */
3713570a335bSHugh Dickins 		while (*map == (SWAP_CONT_MAX | COUNT_CONTINUED)) {
37149b04c5feSCong Wang 			kunmap_atomic(map);
3715213516acSchenqiwu 			page = list_next_entry(page, lru);
3716570a335bSHugh Dickins 			BUG_ON(page == head);
37179b04c5feSCong Wang 			map = kmap_atomic(page) + offset;
3718570a335bSHugh Dickins 		}
3719570a335bSHugh Dickins 		if (*map == SWAP_CONT_MAX) {
37209b04c5feSCong Wang 			kunmap_atomic(map);
3721213516acSchenqiwu 			page = list_next_entry(page, lru);
37222628bd6fSHuang Ying 			if (page == head) {
37232628bd6fSHuang Ying 				ret = false;	/* add count continuation */
37242628bd6fSHuang Ying 				goto out;
37252628bd6fSHuang Ying 			}
37269b04c5feSCong Wang 			map = kmap_atomic(page) + offset;
3727570a335bSHugh Dickins init_map:		*map = 0;		/* we didn't zero the page */
3728570a335bSHugh Dickins 		}
3729570a335bSHugh Dickins 		*map += 1;
37309b04c5feSCong Wang 		kunmap_atomic(map);
3731213516acSchenqiwu 		while ((page = list_prev_entry(page, lru)) != head) {
37329b04c5feSCong Wang 			map = kmap_atomic(page) + offset;
3733570a335bSHugh Dickins 			*map = COUNT_CONTINUED;
37349b04c5feSCong Wang 			kunmap_atomic(map);
3735570a335bSHugh Dickins 		}
37362628bd6fSHuang Ying 		ret = true;			/* incremented */
3737570a335bSHugh Dickins 
3738570a335bSHugh Dickins 	} else {				/* decrementing */
3739570a335bSHugh Dickins 		/*
3740570a335bSHugh Dickins 		 * Think of how you subtract 1 from 1000
3741570a335bSHugh Dickins 		 */
3742570a335bSHugh Dickins 		BUG_ON(count != COUNT_CONTINUED);
3743570a335bSHugh Dickins 		while (*map == COUNT_CONTINUED) {
37449b04c5feSCong Wang 			kunmap_atomic(map);
3745213516acSchenqiwu 			page = list_next_entry(page, lru);
3746570a335bSHugh Dickins 			BUG_ON(page == head);
37479b04c5feSCong Wang 			map = kmap_atomic(page) + offset;
3748570a335bSHugh Dickins 		}
3749570a335bSHugh Dickins 		BUG_ON(*map == 0);
3750570a335bSHugh Dickins 		*map -= 1;
3751570a335bSHugh Dickins 		if (*map == 0)
3752570a335bSHugh Dickins 			count = 0;
37539b04c5feSCong Wang 		kunmap_atomic(map);
3754213516acSchenqiwu 		while ((page = list_prev_entry(page, lru)) != head) {
37559b04c5feSCong Wang 			map = kmap_atomic(page) + offset;
3756570a335bSHugh Dickins 			*map = SWAP_CONT_MAX | count;
3757570a335bSHugh Dickins 			count = COUNT_CONTINUED;
37589b04c5feSCong Wang 			kunmap_atomic(map);
3759570a335bSHugh Dickins 		}
37602628bd6fSHuang Ying 		ret = count == COUNT_CONTINUED;
3761570a335bSHugh Dickins 	}
37622628bd6fSHuang Ying out:
37632628bd6fSHuang Ying 	spin_unlock(&si->cont_lock);
37642628bd6fSHuang Ying 	return ret;
3765570a335bSHugh Dickins }
3766570a335bSHugh Dickins 
3767570a335bSHugh Dickins /*
3768570a335bSHugh Dickins  * free_swap_count_continuations - swapoff free all the continuation pages
3769570a335bSHugh Dickins  * appended to the swap_map, after swap_map is quiesced, before vfree'ing it.
3770570a335bSHugh Dickins  */
3771570a335bSHugh Dickins static void free_swap_count_continuations(struct swap_info_struct *si)
3772570a335bSHugh Dickins {
3773570a335bSHugh Dickins 	pgoff_t offset;
3774570a335bSHugh Dickins 
3775570a335bSHugh Dickins 	for (offset = 0; offset < si->max; offset += PAGE_SIZE) {
3776570a335bSHugh Dickins 		struct page *head;
3777570a335bSHugh Dickins 		head = vmalloc_to_page(si->swap_map + offset);
3778570a335bSHugh Dickins 		if (page_private(head)) {
37790d576d20SGeliang Tang 			struct page *page, *next;
37800d576d20SGeliang Tang 
37810d576d20SGeliang Tang 			list_for_each_entry_safe(page, next, &head->lru, lru) {
37820d576d20SGeliang Tang 				list_del(&page->lru);
3783570a335bSHugh Dickins 				__free_page(page);
3784570a335bSHugh Dickins 			}
3785570a335bSHugh Dickins 		}
3786570a335bSHugh Dickins 	}
3787570a335bSHugh Dickins }
3788a2468cc9SAaron Lu 
37892cf85583STejun Heo #if defined(CONFIG_MEMCG) && defined(CONFIG_BLK_CGROUP)
37906caa6a07SJohannes Weiner void cgroup_throttle_swaprate(struct page *page, gfp_t gfp_mask)
37912cf85583STejun Heo {
37922cf85583STejun Heo 	struct swap_info_struct *si, *next;
37936caa6a07SJohannes Weiner 	int nid = page_to_nid(page);
37946caa6a07SJohannes Weiner 
37956caa6a07SJohannes Weiner 	if (!(gfp_mask & __GFP_IO))
37962cf85583STejun Heo 		return;
37972cf85583STejun Heo 
37982cf85583STejun Heo 	if (!blk_cgroup_congested())
37992cf85583STejun Heo 		return;
38002cf85583STejun Heo 
38012cf85583STejun Heo 	/*
38022cf85583STejun Heo 	 * We've already scheduled a throttle, avoid taking the global swap
38032cf85583STejun Heo 	 * lock.
38042cf85583STejun Heo 	 */
38052cf85583STejun Heo 	if (current->throttle_queue)
38062cf85583STejun Heo 		return;
38072cf85583STejun Heo 
38082cf85583STejun Heo 	spin_lock(&swap_avail_lock);
38096caa6a07SJohannes Weiner 	plist_for_each_entry_safe(si, next, &swap_avail_heads[nid],
38106caa6a07SJohannes Weiner 				  avail_lists[nid]) {
38112cf85583STejun Heo 		if (si->bdev) {
38126caa6a07SJohannes Weiner 			blkcg_schedule_throttle(bdev_get_queue(si->bdev), true);
38132cf85583STejun Heo 			break;
38142cf85583STejun Heo 		}
38152cf85583STejun Heo 	}
38162cf85583STejun Heo 	spin_unlock(&swap_avail_lock);
38172cf85583STejun Heo }
38182cf85583STejun Heo #endif
38192cf85583STejun Heo 
3820a2468cc9SAaron Lu static int __init swapfile_init(void)
3821a2468cc9SAaron Lu {
3822a2468cc9SAaron Lu 	int nid;
3823a2468cc9SAaron Lu 
3824a2468cc9SAaron Lu 	swap_avail_heads = kmalloc_array(nr_node_ids, sizeof(struct plist_head),
3825a2468cc9SAaron Lu 					 GFP_KERNEL);
3826a2468cc9SAaron Lu 	if (!swap_avail_heads) {
3827a2468cc9SAaron Lu 		pr_emerg("Not enough memory for swap heads, swap is disabled\n");
3828a2468cc9SAaron Lu 		return -ENOMEM;
3829a2468cc9SAaron Lu 	}
3830a2468cc9SAaron Lu 
3831a2468cc9SAaron Lu 	for_each_node(nid)
3832a2468cc9SAaron Lu 		plist_head_init(&swap_avail_heads[nid]);
3833a2468cc9SAaron Lu 
3834a2468cc9SAaron Lu 	return 0;
3835a2468cc9SAaron Lu }
3836a2468cc9SAaron Lu subsys_initcall(swapfile_init);
3837