xref: /openbmc/linux/mm/swapfile.c (revision 6e84f31522f931027bf695752087ece278c10d3f)
11da177e4SLinus Torvalds /*
21da177e4SLinus Torvalds  *  linux/mm/swapfile.c
31da177e4SLinus Torvalds  *
41da177e4SLinus Torvalds  *  Copyright (C) 1991, 1992, 1993, 1994  Linus Torvalds
51da177e4SLinus Torvalds  *  Swap reorganised 29.12.95, Stephen Tweedie
61da177e4SLinus Torvalds  */
71da177e4SLinus Torvalds 
81da177e4SLinus Torvalds #include <linux/mm.h>
9*6e84f315SIngo Molnar #include <linux/sched/mm.h>
101da177e4SLinus Torvalds #include <linux/hugetlb.h>
111da177e4SLinus Torvalds #include <linux/mman.h>
121da177e4SLinus Torvalds #include <linux/slab.h>
131da177e4SLinus Torvalds #include <linux/kernel_stat.h>
141da177e4SLinus Torvalds #include <linux/swap.h>
151da177e4SLinus Torvalds #include <linux/vmalloc.h>
161da177e4SLinus Torvalds #include <linux/pagemap.h>
171da177e4SLinus Torvalds #include <linux/namei.h>
18072441e2SHugh Dickins #include <linux/shmem_fs.h>
191da177e4SLinus Torvalds #include <linux/blkdev.h>
2020137a49SHugh Dickins #include <linux/random.h>
211da177e4SLinus Torvalds #include <linux/writeback.h>
221da177e4SLinus Torvalds #include <linux/proc_fs.h>
231da177e4SLinus Torvalds #include <linux/seq_file.h>
241da177e4SLinus Torvalds #include <linux/init.h>
255ad64688SHugh Dickins #include <linux/ksm.h>
261da177e4SLinus Torvalds #include <linux/rmap.h>
271da177e4SLinus Torvalds #include <linux/security.h>
281da177e4SLinus Torvalds #include <linux/backing-dev.h>
29fc0abb14SIngo Molnar #include <linux/mutex.h>
30c59ede7bSRandy.Dunlap #include <linux/capability.h>
311da177e4SLinus Torvalds #include <linux/syscalls.h>
328a9f3ccdSBalbir Singh #include <linux/memcontrol.h>
3366d7dd51SKay Sievers #include <linux/poll.h>
3472788c38SDavid Rientjes #include <linux/oom.h>
3538b5faf4SDan Magenheimer #include <linux/frontswap.h>
3638b5faf4SDan Magenheimer #include <linux/swapfile.h>
37f981c595SMel Gorman #include <linux/export.h>
3867afa38eSTim Chen #include <linux/swap_slots.h>
391da177e4SLinus Torvalds 
401da177e4SLinus Torvalds #include <asm/pgtable.h>
411da177e4SLinus Torvalds #include <asm/tlbflush.h>
421da177e4SLinus Torvalds #include <linux/swapops.h>
435d1ea48bSJohannes Weiner #include <linux/swap_cgroup.h>
441da177e4SLinus Torvalds 
45570a335bSHugh Dickins static bool swap_count_continued(struct swap_info_struct *, pgoff_t,
46570a335bSHugh Dickins 				 unsigned char);
47570a335bSHugh Dickins static void free_swap_count_continuations(struct swap_info_struct *);
48d4906e1aSLee Schermerhorn static sector_t map_swap_entry(swp_entry_t, struct block_device**);
49570a335bSHugh Dickins 
5038b5faf4SDan Magenheimer DEFINE_SPINLOCK(swap_lock);
517c363b8cSAdrian Bunk static unsigned int nr_swapfiles;
52ec8acf20SShaohua Li atomic_long_t nr_swap_pages;
53fb0fec50SChris Wilson /*
54fb0fec50SChris Wilson  * Some modules use swappable objects and may try to swap them out under
55fb0fec50SChris Wilson  * memory pressure (via the shrinker). Before doing so, they may wish to
56fb0fec50SChris Wilson  * check to see if any swap space is available.
57fb0fec50SChris Wilson  */
58fb0fec50SChris Wilson EXPORT_SYMBOL_GPL(nr_swap_pages);
59ec8acf20SShaohua Li /* protected with swap_lock. reading in vm_swap_full() doesn't need lock */
601da177e4SLinus Torvalds long total_swap_pages;
6178ecba08SHugh Dickins static int least_priority;
621da177e4SLinus Torvalds 
631da177e4SLinus Torvalds static const char Bad_file[] = "Bad swap file entry ";
641da177e4SLinus Torvalds static const char Unused_file[] = "Unused swap file entry ";
651da177e4SLinus Torvalds static const char Bad_offset[] = "Bad swap offset entry ";
661da177e4SLinus Torvalds static const char Unused_offset[] = "Unused swap offset entry ";
671da177e4SLinus Torvalds 
68adfab836SDan Streetman /*
69adfab836SDan Streetman  * all active swap_info_structs
70adfab836SDan Streetman  * protected with swap_lock, and ordered by priority.
71adfab836SDan Streetman  */
7218ab4d4cSDan Streetman PLIST_HEAD(swap_active_head);
7318ab4d4cSDan Streetman 
7418ab4d4cSDan Streetman /*
7518ab4d4cSDan Streetman  * all available (active, not full) swap_info_structs
7618ab4d4cSDan Streetman  * protected with swap_avail_lock, ordered by priority.
7718ab4d4cSDan Streetman  * This is used by get_swap_page() instead of swap_active_head
7818ab4d4cSDan Streetman  * because swap_active_head includes all swap_info_structs,
7918ab4d4cSDan Streetman  * but get_swap_page() doesn't need to look at full ones.
8018ab4d4cSDan Streetman  * This uses its own lock instead of swap_lock because when a
8118ab4d4cSDan Streetman  * swap_info_struct changes between not-full/full, it needs to
8218ab4d4cSDan Streetman  * add/remove itself to/from this list, but the swap_info_struct->lock
8318ab4d4cSDan Streetman  * is held and the locking order requires swap_lock to be taken
8418ab4d4cSDan Streetman  * before any swap_info_struct->lock.
8518ab4d4cSDan Streetman  */
8618ab4d4cSDan Streetman static PLIST_HEAD(swap_avail_head);
8718ab4d4cSDan Streetman static DEFINE_SPINLOCK(swap_avail_lock);
881da177e4SLinus Torvalds 
8938b5faf4SDan Magenheimer struct swap_info_struct *swap_info[MAX_SWAPFILES];
901da177e4SLinus Torvalds 
91fc0abb14SIngo Molnar static DEFINE_MUTEX(swapon_mutex);
921da177e4SLinus Torvalds 
9366d7dd51SKay Sievers static DECLARE_WAIT_QUEUE_HEAD(proc_poll_wait);
9466d7dd51SKay Sievers /* Activity counter to indicate that a swapon or swapoff has occurred */
9566d7dd51SKay Sievers static atomic_t proc_poll_event = ATOMIC_INIT(0);
9666d7dd51SKay Sievers 
978d69aaeeSHugh Dickins static inline unsigned char swap_count(unsigned char ent)
98355cfa73SKAMEZAWA Hiroyuki {
99570a335bSHugh Dickins 	return ent & ~SWAP_HAS_CACHE;	/* may include SWAP_HAS_CONT flag */
100355cfa73SKAMEZAWA Hiroyuki }
101355cfa73SKAMEZAWA Hiroyuki 
102efa90a98SHugh Dickins /* returns 1 if swap entry is freed */
103c9e44410SKAMEZAWA Hiroyuki static int
104c9e44410SKAMEZAWA Hiroyuki __try_to_reclaim_swap(struct swap_info_struct *si, unsigned long offset)
105c9e44410SKAMEZAWA Hiroyuki {
106efa90a98SHugh Dickins 	swp_entry_t entry = swp_entry(si->type, offset);
107c9e44410SKAMEZAWA Hiroyuki 	struct page *page;
108c9e44410SKAMEZAWA Hiroyuki 	int ret = 0;
109c9e44410SKAMEZAWA Hiroyuki 
110f6ab1f7fSHuang Ying 	page = find_get_page(swap_address_space(entry), swp_offset(entry));
111c9e44410SKAMEZAWA Hiroyuki 	if (!page)
112c9e44410SKAMEZAWA Hiroyuki 		return 0;
113c9e44410SKAMEZAWA Hiroyuki 	/*
114c9e44410SKAMEZAWA Hiroyuki 	 * This function is called from scan_swap_map() and it's called
115c9e44410SKAMEZAWA Hiroyuki 	 * by vmscan.c at reclaiming pages. So, we hold a lock on a page, here.
116c9e44410SKAMEZAWA Hiroyuki 	 * We have to use trylock for avoiding deadlock. This is a special
117c9e44410SKAMEZAWA Hiroyuki 	 * case and you should use try_to_free_swap() with explicit lock_page()
118c9e44410SKAMEZAWA Hiroyuki 	 * in usual operations.
119c9e44410SKAMEZAWA Hiroyuki 	 */
120c9e44410SKAMEZAWA Hiroyuki 	if (trylock_page(page)) {
121c9e44410SKAMEZAWA Hiroyuki 		ret = try_to_free_swap(page);
122c9e44410SKAMEZAWA Hiroyuki 		unlock_page(page);
123c9e44410SKAMEZAWA Hiroyuki 	}
12409cbfeafSKirill A. Shutemov 	put_page(page);
125c9e44410SKAMEZAWA Hiroyuki 	return ret;
126c9e44410SKAMEZAWA Hiroyuki }
127355cfa73SKAMEZAWA Hiroyuki 
1281da177e4SLinus Torvalds /*
1296a6ba831SHugh Dickins  * swapon tell device that all the old swap contents can be discarded,
1306a6ba831SHugh Dickins  * to allow the swap device to optimize its wear-levelling.
1316a6ba831SHugh Dickins  */
1326a6ba831SHugh Dickins static int discard_swap(struct swap_info_struct *si)
1336a6ba831SHugh Dickins {
1346a6ba831SHugh Dickins 	struct swap_extent *se;
1359625a5f2SHugh Dickins 	sector_t start_block;
1369625a5f2SHugh Dickins 	sector_t nr_blocks;
1376a6ba831SHugh Dickins 	int err = 0;
1386a6ba831SHugh Dickins 
1396a6ba831SHugh Dickins 	/* Do not discard the swap header page! */
1409625a5f2SHugh Dickins 	se = &si->first_swap_extent;
1419625a5f2SHugh Dickins 	start_block = (se->start_block + 1) << (PAGE_SHIFT - 9);
1429625a5f2SHugh Dickins 	nr_blocks = ((sector_t)se->nr_pages - 1) << (PAGE_SHIFT - 9);
1439625a5f2SHugh Dickins 	if (nr_blocks) {
1449625a5f2SHugh Dickins 		err = blkdev_issue_discard(si->bdev, start_block,
145dd3932edSChristoph Hellwig 				nr_blocks, GFP_KERNEL, 0);
1469625a5f2SHugh Dickins 		if (err)
1479625a5f2SHugh Dickins 			return err;
1489625a5f2SHugh Dickins 		cond_resched();
1496a6ba831SHugh Dickins 	}
1506a6ba831SHugh Dickins 
1519625a5f2SHugh Dickins 	list_for_each_entry(se, &si->first_swap_extent.list, list) {
1529625a5f2SHugh Dickins 		start_block = se->start_block << (PAGE_SHIFT - 9);
1539625a5f2SHugh Dickins 		nr_blocks = (sector_t)se->nr_pages << (PAGE_SHIFT - 9);
1549625a5f2SHugh Dickins 
1556a6ba831SHugh Dickins 		err = blkdev_issue_discard(si->bdev, start_block,
156dd3932edSChristoph Hellwig 				nr_blocks, GFP_KERNEL, 0);
1576a6ba831SHugh Dickins 		if (err)
1586a6ba831SHugh Dickins 			break;
1596a6ba831SHugh Dickins 
1606a6ba831SHugh Dickins 		cond_resched();
1616a6ba831SHugh Dickins 	}
1626a6ba831SHugh Dickins 	return err;		/* That will often be -EOPNOTSUPP */
1636a6ba831SHugh Dickins }
1646a6ba831SHugh Dickins 
1657992fde7SHugh Dickins /*
1667992fde7SHugh Dickins  * swap allocation tell device that a cluster of swap can now be discarded,
1677992fde7SHugh Dickins  * to allow the swap device to optimize its wear-levelling.
1687992fde7SHugh Dickins  */
1697992fde7SHugh Dickins static void discard_swap_cluster(struct swap_info_struct *si,
1707992fde7SHugh Dickins 				 pgoff_t start_page, pgoff_t nr_pages)
1717992fde7SHugh Dickins {
1727992fde7SHugh Dickins 	struct swap_extent *se = si->curr_swap_extent;
1737992fde7SHugh Dickins 	int found_extent = 0;
1747992fde7SHugh Dickins 
1757992fde7SHugh Dickins 	while (nr_pages) {
1767992fde7SHugh Dickins 		if (se->start_page <= start_page &&
1777992fde7SHugh Dickins 		    start_page < se->start_page + se->nr_pages) {
1787992fde7SHugh Dickins 			pgoff_t offset = start_page - se->start_page;
1797992fde7SHugh Dickins 			sector_t start_block = se->start_block + offset;
180858a2990SHugh Dickins 			sector_t nr_blocks = se->nr_pages - offset;
1817992fde7SHugh Dickins 
1827992fde7SHugh Dickins 			if (nr_blocks > nr_pages)
1837992fde7SHugh Dickins 				nr_blocks = nr_pages;
1847992fde7SHugh Dickins 			start_page += nr_blocks;
1857992fde7SHugh Dickins 			nr_pages -= nr_blocks;
1867992fde7SHugh Dickins 
1877992fde7SHugh Dickins 			if (!found_extent++)
1887992fde7SHugh Dickins 				si->curr_swap_extent = se;
1897992fde7SHugh Dickins 
1907992fde7SHugh Dickins 			start_block <<= PAGE_SHIFT - 9;
1917992fde7SHugh Dickins 			nr_blocks <<= PAGE_SHIFT - 9;
1927992fde7SHugh Dickins 			if (blkdev_issue_discard(si->bdev, start_block,
193dd3932edSChristoph Hellwig 				    nr_blocks, GFP_NOIO, 0))
1947992fde7SHugh Dickins 				break;
1957992fde7SHugh Dickins 		}
1967992fde7SHugh Dickins 
197a8ae4991SGeliang Tang 		se = list_next_entry(se, list);
1987992fde7SHugh Dickins 	}
1997992fde7SHugh Dickins }
2007992fde7SHugh Dickins 
201048c27fdSHugh Dickins #define SWAPFILE_CLUSTER	256
202048c27fdSHugh Dickins #define LATENCY_LIMIT		256
203048c27fdSHugh Dickins 
2042a8f9449SShaohua Li static inline void cluster_set_flag(struct swap_cluster_info *info,
2052a8f9449SShaohua Li 	unsigned int flag)
2062a8f9449SShaohua Li {
2072a8f9449SShaohua Li 	info->flags = flag;
2082a8f9449SShaohua Li }
2092a8f9449SShaohua Li 
2102a8f9449SShaohua Li static inline unsigned int cluster_count(struct swap_cluster_info *info)
2112a8f9449SShaohua Li {
2122a8f9449SShaohua Li 	return info->data;
2132a8f9449SShaohua Li }
2142a8f9449SShaohua Li 
2152a8f9449SShaohua Li static inline void cluster_set_count(struct swap_cluster_info *info,
2162a8f9449SShaohua Li 				     unsigned int c)
2172a8f9449SShaohua Li {
2182a8f9449SShaohua Li 	info->data = c;
2192a8f9449SShaohua Li }
2202a8f9449SShaohua Li 
2212a8f9449SShaohua Li static inline void cluster_set_count_flag(struct swap_cluster_info *info,
2222a8f9449SShaohua Li 					 unsigned int c, unsigned int f)
2232a8f9449SShaohua Li {
2242a8f9449SShaohua Li 	info->flags = f;
2252a8f9449SShaohua Li 	info->data = c;
2262a8f9449SShaohua Li }
2272a8f9449SShaohua Li 
2282a8f9449SShaohua Li static inline unsigned int cluster_next(struct swap_cluster_info *info)
2292a8f9449SShaohua Li {
2302a8f9449SShaohua Li 	return info->data;
2312a8f9449SShaohua Li }
2322a8f9449SShaohua Li 
2332a8f9449SShaohua Li static inline void cluster_set_next(struct swap_cluster_info *info,
2342a8f9449SShaohua Li 				    unsigned int n)
2352a8f9449SShaohua Li {
2362a8f9449SShaohua Li 	info->data = n;
2372a8f9449SShaohua Li }
2382a8f9449SShaohua Li 
2392a8f9449SShaohua Li static inline void cluster_set_next_flag(struct swap_cluster_info *info,
2402a8f9449SShaohua Li 					 unsigned int n, unsigned int f)
2412a8f9449SShaohua Li {
2422a8f9449SShaohua Li 	info->flags = f;
2432a8f9449SShaohua Li 	info->data = n;
2442a8f9449SShaohua Li }
2452a8f9449SShaohua Li 
2462a8f9449SShaohua Li static inline bool cluster_is_free(struct swap_cluster_info *info)
2472a8f9449SShaohua Li {
2482a8f9449SShaohua Li 	return info->flags & CLUSTER_FLAG_FREE;
2492a8f9449SShaohua Li }
2502a8f9449SShaohua Li 
2512a8f9449SShaohua Li static inline bool cluster_is_null(struct swap_cluster_info *info)
2522a8f9449SShaohua Li {
2532a8f9449SShaohua Li 	return info->flags & CLUSTER_FLAG_NEXT_NULL;
2542a8f9449SShaohua Li }
2552a8f9449SShaohua Li 
2562a8f9449SShaohua Li static inline void cluster_set_null(struct swap_cluster_info *info)
2572a8f9449SShaohua Li {
2582a8f9449SShaohua Li 	info->flags = CLUSTER_FLAG_NEXT_NULL;
2592a8f9449SShaohua Li 	info->data = 0;
2602a8f9449SShaohua Li }
2612a8f9449SShaohua Li 
262235b6217SHuang, Ying static inline struct swap_cluster_info *lock_cluster(struct swap_info_struct *si,
263235b6217SHuang, Ying 						     unsigned long offset)
264235b6217SHuang, Ying {
265235b6217SHuang, Ying 	struct swap_cluster_info *ci;
266235b6217SHuang, Ying 
267235b6217SHuang, Ying 	ci = si->cluster_info;
268235b6217SHuang, Ying 	if (ci) {
269235b6217SHuang, Ying 		ci += offset / SWAPFILE_CLUSTER;
270235b6217SHuang, Ying 		spin_lock(&ci->lock);
271235b6217SHuang, Ying 	}
272235b6217SHuang, Ying 	return ci;
273235b6217SHuang, Ying }
274235b6217SHuang, Ying 
275235b6217SHuang, Ying static inline void unlock_cluster(struct swap_cluster_info *ci)
276235b6217SHuang, Ying {
277235b6217SHuang, Ying 	if (ci)
278235b6217SHuang, Ying 		spin_unlock(&ci->lock);
279235b6217SHuang, Ying }
280235b6217SHuang, Ying 
281235b6217SHuang, Ying static inline struct swap_cluster_info *lock_cluster_or_swap_info(
282235b6217SHuang, Ying 	struct swap_info_struct *si,
283235b6217SHuang, Ying 	unsigned long offset)
284235b6217SHuang, Ying {
285235b6217SHuang, Ying 	struct swap_cluster_info *ci;
286235b6217SHuang, Ying 
287235b6217SHuang, Ying 	ci = lock_cluster(si, offset);
288235b6217SHuang, Ying 	if (!ci)
289235b6217SHuang, Ying 		spin_lock(&si->lock);
290235b6217SHuang, Ying 
291235b6217SHuang, Ying 	return ci;
292235b6217SHuang, Ying }
293235b6217SHuang, Ying 
294235b6217SHuang, Ying static inline void unlock_cluster_or_swap_info(struct swap_info_struct *si,
295235b6217SHuang, Ying 					       struct swap_cluster_info *ci)
296235b6217SHuang, Ying {
297235b6217SHuang, Ying 	if (ci)
298235b6217SHuang, Ying 		unlock_cluster(ci);
299235b6217SHuang, Ying 	else
300235b6217SHuang, Ying 		spin_unlock(&si->lock);
301235b6217SHuang, Ying }
302235b6217SHuang, Ying 
3036b534915SHuang Ying static inline bool cluster_list_empty(struct swap_cluster_list *list)
3046b534915SHuang Ying {
3056b534915SHuang Ying 	return cluster_is_null(&list->head);
3066b534915SHuang Ying }
3076b534915SHuang Ying 
3086b534915SHuang Ying static inline unsigned int cluster_list_first(struct swap_cluster_list *list)
3096b534915SHuang Ying {
3106b534915SHuang Ying 	return cluster_next(&list->head);
3116b534915SHuang Ying }
3126b534915SHuang Ying 
3136b534915SHuang Ying static void cluster_list_init(struct swap_cluster_list *list)
3146b534915SHuang Ying {
3156b534915SHuang Ying 	cluster_set_null(&list->head);
3166b534915SHuang Ying 	cluster_set_null(&list->tail);
3176b534915SHuang Ying }
3186b534915SHuang Ying 
3196b534915SHuang Ying static void cluster_list_add_tail(struct swap_cluster_list *list,
3206b534915SHuang Ying 				  struct swap_cluster_info *ci,
3216b534915SHuang Ying 				  unsigned int idx)
3226b534915SHuang Ying {
3236b534915SHuang Ying 	if (cluster_list_empty(list)) {
3246b534915SHuang Ying 		cluster_set_next_flag(&list->head, idx, 0);
3256b534915SHuang Ying 		cluster_set_next_flag(&list->tail, idx, 0);
3266b534915SHuang Ying 	} else {
327235b6217SHuang, Ying 		struct swap_cluster_info *ci_tail;
3286b534915SHuang Ying 		unsigned int tail = cluster_next(&list->tail);
3296b534915SHuang Ying 
330235b6217SHuang, Ying 		/*
331235b6217SHuang, Ying 		 * Nested cluster lock, but both cluster locks are
332235b6217SHuang, Ying 		 * only acquired when we held swap_info_struct->lock
333235b6217SHuang, Ying 		 */
334235b6217SHuang, Ying 		ci_tail = ci + tail;
335235b6217SHuang, Ying 		spin_lock_nested(&ci_tail->lock, SINGLE_DEPTH_NESTING);
336235b6217SHuang, Ying 		cluster_set_next(ci_tail, idx);
337235b6217SHuang, Ying 		unlock_cluster(ci_tail);
3386b534915SHuang Ying 		cluster_set_next_flag(&list->tail, idx, 0);
3396b534915SHuang Ying 	}
3406b534915SHuang Ying }
3416b534915SHuang Ying 
3426b534915SHuang Ying static unsigned int cluster_list_del_first(struct swap_cluster_list *list,
3436b534915SHuang Ying 					   struct swap_cluster_info *ci)
3446b534915SHuang Ying {
3456b534915SHuang Ying 	unsigned int idx;
3466b534915SHuang Ying 
3476b534915SHuang Ying 	idx = cluster_next(&list->head);
3486b534915SHuang Ying 	if (cluster_next(&list->tail) == idx) {
3496b534915SHuang Ying 		cluster_set_null(&list->head);
3506b534915SHuang Ying 		cluster_set_null(&list->tail);
3516b534915SHuang Ying 	} else
3526b534915SHuang Ying 		cluster_set_next_flag(&list->head,
3536b534915SHuang Ying 				      cluster_next(&ci[idx]), 0);
3546b534915SHuang Ying 
3556b534915SHuang Ying 	return idx;
3566b534915SHuang Ying }
3576b534915SHuang Ying 
358815c2c54SShaohua Li /* Add a cluster to discard list and schedule it to do discard */
359815c2c54SShaohua Li static void swap_cluster_schedule_discard(struct swap_info_struct *si,
360815c2c54SShaohua Li 		unsigned int idx)
361815c2c54SShaohua Li {
362815c2c54SShaohua Li 	/*
363815c2c54SShaohua Li 	 * If scan_swap_map() can't find a free cluster, it will check
364815c2c54SShaohua Li 	 * si->swap_map directly. To make sure the discarding cluster isn't
365815c2c54SShaohua Li 	 * taken by scan_swap_map(), mark the swap entries bad (occupied). It
366815c2c54SShaohua Li 	 * will be cleared after discard
367815c2c54SShaohua Li 	 */
368815c2c54SShaohua Li 	memset(si->swap_map + idx * SWAPFILE_CLUSTER,
369815c2c54SShaohua Li 			SWAP_MAP_BAD, SWAPFILE_CLUSTER);
370815c2c54SShaohua Li 
3716b534915SHuang Ying 	cluster_list_add_tail(&si->discard_clusters, si->cluster_info, idx);
372815c2c54SShaohua Li 
373815c2c54SShaohua Li 	schedule_work(&si->discard_work);
374815c2c54SShaohua Li }
375815c2c54SShaohua Li 
376815c2c54SShaohua Li /*
377815c2c54SShaohua Li  * Doing discard actually. After a cluster discard is finished, the cluster
378815c2c54SShaohua Li  * will be added to free cluster list. caller should hold si->lock.
379815c2c54SShaohua Li */
380815c2c54SShaohua Li static void swap_do_scheduled_discard(struct swap_info_struct *si)
381815c2c54SShaohua Li {
382235b6217SHuang, Ying 	struct swap_cluster_info *info, *ci;
383815c2c54SShaohua Li 	unsigned int idx;
384815c2c54SShaohua Li 
385815c2c54SShaohua Li 	info = si->cluster_info;
386815c2c54SShaohua Li 
3876b534915SHuang Ying 	while (!cluster_list_empty(&si->discard_clusters)) {
3886b534915SHuang Ying 		idx = cluster_list_del_first(&si->discard_clusters, info);
389815c2c54SShaohua Li 		spin_unlock(&si->lock);
390815c2c54SShaohua Li 
391815c2c54SShaohua Li 		discard_swap_cluster(si, idx * SWAPFILE_CLUSTER,
392815c2c54SShaohua Li 				SWAPFILE_CLUSTER);
393815c2c54SShaohua Li 
394815c2c54SShaohua Li 		spin_lock(&si->lock);
395235b6217SHuang, Ying 		ci = lock_cluster(si, idx * SWAPFILE_CLUSTER);
396235b6217SHuang, Ying 		cluster_set_flag(ci, CLUSTER_FLAG_FREE);
397235b6217SHuang, Ying 		unlock_cluster(ci);
3986b534915SHuang Ying 		cluster_list_add_tail(&si->free_clusters, info, idx);
399235b6217SHuang, Ying 		ci = lock_cluster(si, idx * SWAPFILE_CLUSTER);
400815c2c54SShaohua Li 		memset(si->swap_map + idx * SWAPFILE_CLUSTER,
401815c2c54SShaohua Li 				0, SWAPFILE_CLUSTER);
402235b6217SHuang, Ying 		unlock_cluster(ci);
403815c2c54SShaohua Li 	}
404815c2c54SShaohua Li }
405815c2c54SShaohua Li 
406815c2c54SShaohua Li static void swap_discard_work(struct work_struct *work)
407815c2c54SShaohua Li {
408815c2c54SShaohua Li 	struct swap_info_struct *si;
409815c2c54SShaohua Li 
410815c2c54SShaohua Li 	si = container_of(work, struct swap_info_struct, discard_work);
411815c2c54SShaohua Li 
412815c2c54SShaohua Li 	spin_lock(&si->lock);
413815c2c54SShaohua Li 	swap_do_scheduled_discard(si);
414815c2c54SShaohua Li 	spin_unlock(&si->lock);
415815c2c54SShaohua Li }
416815c2c54SShaohua Li 
4172a8f9449SShaohua Li /*
4182a8f9449SShaohua Li  * The cluster corresponding to page_nr will be used. The cluster will be
4192a8f9449SShaohua Li  * removed from free cluster list and its usage counter will be increased.
4202a8f9449SShaohua Li  */
4212a8f9449SShaohua Li static void inc_cluster_info_page(struct swap_info_struct *p,
4222a8f9449SShaohua Li 	struct swap_cluster_info *cluster_info, unsigned long page_nr)
4232a8f9449SShaohua Li {
4242a8f9449SShaohua Li 	unsigned long idx = page_nr / SWAPFILE_CLUSTER;
4252a8f9449SShaohua Li 
4262a8f9449SShaohua Li 	if (!cluster_info)
4272a8f9449SShaohua Li 		return;
4282a8f9449SShaohua Li 	if (cluster_is_free(&cluster_info[idx])) {
4296b534915SHuang Ying 		VM_BUG_ON(cluster_list_first(&p->free_clusters) != idx);
4306b534915SHuang Ying 		cluster_list_del_first(&p->free_clusters, cluster_info);
4312a8f9449SShaohua Li 		cluster_set_count_flag(&cluster_info[idx], 0, 0);
4322a8f9449SShaohua Li 	}
4332a8f9449SShaohua Li 
4342a8f9449SShaohua Li 	VM_BUG_ON(cluster_count(&cluster_info[idx]) >= SWAPFILE_CLUSTER);
4352a8f9449SShaohua Li 	cluster_set_count(&cluster_info[idx],
4362a8f9449SShaohua Li 		cluster_count(&cluster_info[idx]) + 1);
4372a8f9449SShaohua Li }
4382a8f9449SShaohua Li 
4392a8f9449SShaohua Li /*
4402a8f9449SShaohua Li  * The cluster corresponding to page_nr decreases one usage. If the usage
4412a8f9449SShaohua Li  * counter becomes 0, which means no page in the cluster is in using, we can
4422a8f9449SShaohua Li  * optionally discard the cluster and add it to free cluster list.
4432a8f9449SShaohua Li  */
4442a8f9449SShaohua Li static void dec_cluster_info_page(struct swap_info_struct *p,
4452a8f9449SShaohua Li 	struct swap_cluster_info *cluster_info, unsigned long page_nr)
4462a8f9449SShaohua Li {
4472a8f9449SShaohua Li 	unsigned long idx = page_nr / SWAPFILE_CLUSTER;
4482a8f9449SShaohua Li 
4492a8f9449SShaohua Li 	if (!cluster_info)
4502a8f9449SShaohua Li 		return;
4512a8f9449SShaohua Li 
4522a8f9449SShaohua Li 	VM_BUG_ON(cluster_count(&cluster_info[idx]) == 0);
4532a8f9449SShaohua Li 	cluster_set_count(&cluster_info[idx],
4542a8f9449SShaohua Li 		cluster_count(&cluster_info[idx]) - 1);
4552a8f9449SShaohua Li 
4562a8f9449SShaohua Li 	if (cluster_count(&cluster_info[idx]) == 0) {
457815c2c54SShaohua Li 		/*
458815c2c54SShaohua Li 		 * If the swap is discardable, prepare discard the cluster
459815c2c54SShaohua Li 		 * instead of free it immediately. The cluster will be freed
460815c2c54SShaohua Li 		 * after discard.
461815c2c54SShaohua Li 		 */
462edfe23daSShaohua Li 		if ((p->flags & (SWP_WRITEOK | SWP_PAGE_DISCARD)) ==
463edfe23daSShaohua Li 				 (SWP_WRITEOK | SWP_PAGE_DISCARD)) {
464815c2c54SShaohua Li 			swap_cluster_schedule_discard(p, idx);
465815c2c54SShaohua Li 			return;
466815c2c54SShaohua Li 		}
467815c2c54SShaohua Li 
4682a8f9449SShaohua Li 		cluster_set_flag(&cluster_info[idx], CLUSTER_FLAG_FREE);
4696b534915SHuang Ying 		cluster_list_add_tail(&p->free_clusters, cluster_info, idx);
4702a8f9449SShaohua Li 	}
4712a8f9449SShaohua Li }
4722a8f9449SShaohua Li 
4732a8f9449SShaohua Li /*
4742a8f9449SShaohua Li  * It's possible scan_swap_map() uses a free cluster in the middle of free
4752a8f9449SShaohua Li  * cluster list. Avoiding such abuse to avoid list corruption.
4762a8f9449SShaohua Li  */
477ebc2a1a6SShaohua Li static bool
478ebc2a1a6SShaohua Li scan_swap_map_ssd_cluster_conflict(struct swap_info_struct *si,
4792a8f9449SShaohua Li 	unsigned long offset)
4802a8f9449SShaohua Li {
481ebc2a1a6SShaohua Li 	struct percpu_cluster *percpu_cluster;
482ebc2a1a6SShaohua Li 	bool conflict;
483ebc2a1a6SShaohua Li 
4842a8f9449SShaohua Li 	offset /= SWAPFILE_CLUSTER;
4856b534915SHuang Ying 	conflict = !cluster_list_empty(&si->free_clusters) &&
4866b534915SHuang Ying 		offset != cluster_list_first(&si->free_clusters) &&
4872a8f9449SShaohua Li 		cluster_is_free(&si->cluster_info[offset]);
488ebc2a1a6SShaohua Li 
489ebc2a1a6SShaohua Li 	if (!conflict)
490ebc2a1a6SShaohua Li 		return false;
491ebc2a1a6SShaohua Li 
492ebc2a1a6SShaohua Li 	percpu_cluster = this_cpu_ptr(si->percpu_cluster);
493ebc2a1a6SShaohua Li 	cluster_set_null(&percpu_cluster->index);
494ebc2a1a6SShaohua Li 	return true;
495ebc2a1a6SShaohua Li }
496ebc2a1a6SShaohua Li 
497ebc2a1a6SShaohua Li /*
498ebc2a1a6SShaohua Li  * Try to get a swap entry from current cpu's swap entry pool (a cluster). This
499ebc2a1a6SShaohua Li  * might involve allocating a new cluster for current CPU too.
500ebc2a1a6SShaohua Li  */
50136005baeSTim Chen static bool scan_swap_map_try_ssd_cluster(struct swap_info_struct *si,
502ebc2a1a6SShaohua Li 	unsigned long *offset, unsigned long *scan_base)
503ebc2a1a6SShaohua Li {
504ebc2a1a6SShaohua Li 	struct percpu_cluster *cluster;
505235b6217SHuang, Ying 	struct swap_cluster_info *ci;
506ebc2a1a6SShaohua Li 	bool found_free;
507235b6217SHuang, Ying 	unsigned long tmp, max;
508ebc2a1a6SShaohua Li 
509ebc2a1a6SShaohua Li new_cluster:
510ebc2a1a6SShaohua Li 	cluster = this_cpu_ptr(si->percpu_cluster);
511ebc2a1a6SShaohua Li 	if (cluster_is_null(&cluster->index)) {
5126b534915SHuang Ying 		if (!cluster_list_empty(&si->free_clusters)) {
5136b534915SHuang Ying 			cluster->index = si->free_clusters.head;
514ebc2a1a6SShaohua Li 			cluster->next = cluster_next(&cluster->index) *
515ebc2a1a6SShaohua Li 					SWAPFILE_CLUSTER;
5166b534915SHuang Ying 		} else if (!cluster_list_empty(&si->discard_clusters)) {
517ebc2a1a6SShaohua Li 			/*
518ebc2a1a6SShaohua Li 			 * we don't have free cluster but have some clusters in
519ebc2a1a6SShaohua Li 			 * discarding, do discard now and reclaim them
520ebc2a1a6SShaohua Li 			 */
521ebc2a1a6SShaohua Li 			swap_do_scheduled_discard(si);
522ebc2a1a6SShaohua Li 			*scan_base = *offset = si->cluster_next;
523ebc2a1a6SShaohua Li 			goto new_cluster;
524ebc2a1a6SShaohua Li 		} else
52536005baeSTim Chen 			return false;
526ebc2a1a6SShaohua Li 	}
527ebc2a1a6SShaohua Li 
528ebc2a1a6SShaohua Li 	found_free = false;
529ebc2a1a6SShaohua Li 
530ebc2a1a6SShaohua Li 	/*
531ebc2a1a6SShaohua Li 	 * Other CPUs can use our cluster if they can't find a free cluster,
532ebc2a1a6SShaohua Li 	 * check if there is still free entry in the cluster
533ebc2a1a6SShaohua Li 	 */
534ebc2a1a6SShaohua Li 	tmp = cluster->next;
535235b6217SHuang, Ying 	max = min_t(unsigned long, si->max,
536235b6217SHuang, Ying 		    (cluster_next(&cluster->index) + 1) * SWAPFILE_CLUSTER);
537235b6217SHuang, Ying 	if (tmp >= max) {
538235b6217SHuang, Ying 		cluster_set_null(&cluster->index);
539235b6217SHuang, Ying 		goto new_cluster;
540235b6217SHuang, Ying 	}
541235b6217SHuang, Ying 	ci = lock_cluster(si, tmp);
542235b6217SHuang, Ying 	while (tmp < max) {
543ebc2a1a6SShaohua Li 		if (!si->swap_map[tmp]) {
544ebc2a1a6SShaohua Li 			found_free = true;
545ebc2a1a6SShaohua Li 			break;
546ebc2a1a6SShaohua Li 		}
547ebc2a1a6SShaohua Li 		tmp++;
548ebc2a1a6SShaohua Li 	}
549235b6217SHuang, Ying 	unlock_cluster(ci);
550ebc2a1a6SShaohua Li 	if (!found_free) {
551ebc2a1a6SShaohua Li 		cluster_set_null(&cluster->index);
552ebc2a1a6SShaohua Li 		goto new_cluster;
553ebc2a1a6SShaohua Li 	}
554ebc2a1a6SShaohua Li 	cluster->next = tmp + 1;
555ebc2a1a6SShaohua Li 	*offset = tmp;
556ebc2a1a6SShaohua Li 	*scan_base = tmp;
55736005baeSTim Chen 	return found_free;
5582a8f9449SShaohua Li }
5592a8f9449SShaohua Li 
56036005baeSTim Chen static int scan_swap_map_slots(struct swap_info_struct *si,
56136005baeSTim Chen 			       unsigned char usage, int nr,
56236005baeSTim Chen 			       swp_entry_t slots[])
5631da177e4SLinus Torvalds {
564235b6217SHuang, Ying 	struct swap_cluster_info *ci;
565ebebbbe9SHugh Dickins 	unsigned long offset;
566c60aa176SHugh Dickins 	unsigned long scan_base;
5677992fde7SHugh Dickins 	unsigned long last_in_cluster = 0;
568048c27fdSHugh Dickins 	int latency_ration = LATENCY_LIMIT;
56936005baeSTim Chen 	int n_ret = 0;
57036005baeSTim Chen 
57136005baeSTim Chen 	if (nr > SWAP_BATCH)
57236005baeSTim Chen 		nr = SWAP_BATCH;
5731da177e4SLinus Torvalds 
5747dfad418SHugh Dickins 	/*
5757dfad418SHugh Dickins 	 * We try to cluster swap pages by allocating them sequentially
5767dfad418SHugh Dickins 	 * in swap.  Once we've allocated SWAPFILE_CLUSTER pages this
5777dfad418SHugh Dickins 	 * way, however, we resort to first-free allocation, starting
5787dfad418SHugh Dickins 	 * a new cluster.  This prevents us from scattering swap pages
5797dfad418SHugh Dickins 	 * all over the entire swap partition, so that we reduce
5807dfad418SHugh Dickins 	 * overall disk seek times between swap pages.  -- sct
5817dfad418SHugh Dickins 	 * But we do now try to find an empty cluster.  -Andrea
582c60aa176SHugh Dickins 	 * And we let swap pages go all over an SSD partition.  Hugh
5831da177e4SLinus Torvalds 	 */
5847dfad418SHugh Dickins 
58552b7efdbSHugh Dickins 	si->flags += SWP_SCANNING;
586c60aa176SHugh Dickins 	scan_base = offset = si->cluster_next;
587ebebbbe9SHugh Dickins 
588ebc2a1a6SShaohua Li 	/* SSD algorithm */
589ebc2a1a6SShaohua Li 	if (si->cluster_info) {
59036005baeSTim Chen 		if (scan_swap_map_try_ssd_cluster(si, &offset, &scan_base))
591815c2c54SShaohua Li 			goto checks;
59236005baeSTim Chen 		else
59336005baeSTim Chen 			goto scan;
594815c2c54SShaohua Li 	}
595815c2c54SShaohua Li 
596ebc2a1a6SShaohua Li 	if (unlikely(!si->cluster_nr--)) {
597ebc2a1a6SShaohua Li 		if (si->pages - si->inuse_pages < SWAPFILE_CLUSTER) {
598ebc2a1a6SShaohua Li 			si->cluster_nr = SWAPFILE_CLUSTER - 1;
5992a8f9449SShaohua Li 			goto checks;
6002a8f9449SShaohua Li 		}
6012a8f9449SShaohua Li 
602ec8acf20SShaohua Li 		spin_unlock(&si->lock);
6037dfad418SHugh Dickins 
604c60aa176SHugh Dickins 		/*
605c60aa176SHugh Dickins 		 * If seek is expensive, start searching for new cluster from
606c60aa176SHugh Dickins 		 * start of partition, to minimize the span of allocated swap.
60750088c44SChen Yucong 		 * If seek is cheap, that is the SWP_SOLIDSTATE si->cluster_info
60850088c44SChen Yucong 		 * case, just handled by scan_swap_map_try_ssd_cluster() above.
609c60aa176SHugh Dickins 		 */
610c60aa176SHugh Dickins 		scan_base = offset = si->lowest_bit;
6117dfad418SHugh Dickins 		last_in_cluster = offset + SWAPFILE_CLUSTER - 1;
6127dfad418SHugh Dickins 
6137dfad418SHugh Dickins 		/* Locate the first empty (unaligned) cluster */
6147dfad418SHugh Dickins 		for (; last_in_cluster <= si->highest_bit; offset++) {
6151da177e4SLinus Torvalds 			if (si->swap_map[offset])
6167dfad418SHugh Dickins 				last_in_cluster = offset + SWAPFILE_CLUSTER;
6177dfad418SHugh Dickins 			else if (offset == last_in_cluster) {
618ec8acf20SShaohua Li 				spin_lock(&si->lock);
619ebebbbe9SHugh Dickins 				offset -= SWAPFILE_CLUSTER - 1;
620ebebbbe9SHugh Dickins 				si->cluster_next = offset;
621ebebbbe9SHugh Dickins 				si->cluster_nr = SWAPFILE_CLUSTER - 1;
622ebebbbe9SHugh Dickins 				goto checks;
6237dfad418SHugh Dickins 			}
624048c27fdSHugh Dickins 			if (unlikely(--latency_ration < 0)) {
625048c27fdSHugh Dickins 				cond_resched();
626048c27fdSHugh Dickins 				latency_ration = LATENCY_LIMIT;
627048c27fdSHugh Dickins 			}
6287dfad418SHugh Dickins 		}
629ebebbbe9SHugh Dickins 
630c60aa176SHugh Dickins 		offset = scan_base;
631ec8acf20SShaohua Li 		spin_lock(&si->lock);
632ebebbbe9SHugh Dickins 		si->cluster_nr = SWAPFILE_CLUSTER - 1;
6337dfad418SHugh Dickins 	}
6347dfad418SHugh Dickins 
635ebebbbe9SHugh Dickins checks:
636ebc2a1a6SShaohua Li 	if (si->cluster_info) {
63736005baeSTim Chen 		while (scan_swap_map_ssd_cluster_conflict(si, offset)) {
63836005baeSTim Chen 		/* take a break if we already got some slots */
63936005baeSTim Chen 			if (n_ret)
64036005baeSTim Chen 				goto done;
64136005baeSTim Chen 			if (!scan_swap_map_try_ssd_cluster(si, &offset,
64236005baeSTim Chen 							&scan_base))
64336005baeSTim Chen 				goto scan;
64436005baeSTim Chen 		}
645ebc2a1a6SShaohua Li 	}
646ebebbbe9SHugh Dickins 	if (!(si->flags & SWP_WRITEOK))
64752b7efdbSHugh Dickins 		goto no_page;
6487dfad418SHugh Dickins 	if (!si->highest_bit)
6497dfad418SHugh Dickins 		goto no_page;
650ebebbbe9SHugh Dickins 	if (offset > si->highest_bit)
651c60aa176SHugh Dickins 		scan_base = offset = si->lowest_bit;
652c9e44410SKAMEZAWA Hiroyuki 
653235b6217SHuang, Ying 	ci = lock_cluster(si, offset);
654b73d7fceSHugh Dickins 	/* reuse swap entry of cache-only swap if not busy. */
655b73d7fceSHugh Dickins 	if (vm_swap_full() && si->swap_map[offset] == SWAP_HAS_CACHE) {
656c9e44410SKAMEZAWA Hiroyuki 		int swap_was_freed;
657235b6217SHuang, Ying 		unlock_cluster(ci);
658ec8acf20SShaohua Li 		spin_unlock(&si->lock);
659c9e44410SKAMEZAWA Hiroyuki 		swap_was_freed = __try_to_reclaim_swap(si, offset);
660ec8acf20SShaohua Li 		spin_lock(&si->lock);
661c9e44410SKAMEZAWA Hiroyuki 		/* entry was freed successfully, try to use this again */
662c9e44410SKAMEZAWA Hiroyuki 		if (swap_was_freed)
663c9e44410SKAMEZAWA Hiroyuki 			goto checks;
664c9e44410SKAMEZAWA Hiroyuki 		goto scan; /* check next one */
665c9e44410SKAMEZAWA Hiroyuki 	}
666c9e44410SKAMEZAWA Hiroyuki 
667235b6217SHuang, Ying 	if (si->swap_map[offset]) {
668235b6217SHuang, Ying 		unlock_cluster(ci);
66936005baeSTim Chen 		if (!n_ret)
670ebebbbe9SHugh Dickins 			goto scan;
67136005baeSTim Chen 		else
67236005baeSTim Chen 			goto done;
673235b6217SHuang, Ying 	}
674ebebbbe9SHugh Dickins 
67552b7efdbSHugh Dickins 	if (offset == si->lowest_bit)
6761da177e4SLinus Torvalds 		si->lowest_bit++;
6771da177e4SLinus Torvalds 	if (offset == si->highest_bit)
6781da177e4SLinus Torvalds 		si->highest_bit--;
6797dfad418SHugh Dickins 	si->inuse_pages++;
6807dfad418SHugh Dickins 	if (si->inuse_pages == si->pages) {
6811da177e4SLinus Torvalds 		si->lowest_bit = si->max;
6821da177e4SLinus Torvalds 		si->highest_bit = 0;
68318ab4d4cSDan Streetman 		spin_lock(&swap_avail_lock);
68418ab4d4cSDan Streetman 		plist_del(&si->avail_list, &swap_avail_head);
68518ab4d4cSDan Streetman 		spin_unlock(&swap_avail_lock);
6861da177e4SLinus Torvalds 	}
687253d553bSHugh Dickins 	si->swap_map[offset] = usage;
6882a8f9449SShaohua Li 	inc_cluster_info_page(si, si->cluster_info, offset);
689235b6217SHuang, Ying 	unlock_cluster(ci);
6901da177e4SLinus Torvalds 	si->cluster_next = offset + 1;
69136005baeSTim Chen 	slots[n_ret++] = swp_entry(si->type, offset);
6927992fde7SHugh Dickins 
69336005baeSTim Chen 	/* got enough slots or reach max slots? */
69436005baeSTim Chen 	if ((n_ret == nr) || (offset >= si->highest_bit))
69536005baeSTim Chen 		goto done;
69636005baeSTim Chen 
69736005baeSTim Chen 	/* search for next available slot */
69836005baeSTim Chen 
69936005baeSTim Chen 	/* time to take a break? */
70036005baeSTim Chen 	if (unlikely(--latency_ration < 0)) {
70136005baeSTim Chen 		if (n_ret)
70236005baeSTim Chen 			goto done;
70336005baeSTim Chen 		spin_unlock(&si->lock);
70436005baeSTim Chen 		cond_resched();
70536005baeSTim Chen 		spin_lock(&si->lock);
70636005baeSTim Chen 		latency_ration = LATENCY_LIMIT;
70736005baeSTim Chen 	}
70836005baeSTim Chen 
70936005baeSTim Chen 	/* try to get more slots in cluster */
71036005baeSTim Chen 	if (si->cluster_info) {
71136005baeSTim Chen 		if (scan_swap_map_try_ssd_cluster(si, &offset, &scan_base))
71236005baeSTim Chen 			goto checks;
71336005baeSTim Chen 		else
71436005baeSTim Chen 			goto done;
71536005baeSTim Chen 	}
71636005baeSTim Chen 	/* non-ssd case */
71736005baeSTim Chen 	++offset;
71836005baeSTim Chen 
71936005baeSTim Chen 	/* non-ssd case, still more slots in cluster? */
72036005baeSTim Chen 	if (si->cluster_nr && !si->swap_map[offset]) {
72136005baeSTim Chen 		--si->cluster_nr;
72236005baeSTim Chen 		goto checks;
72336005baeSTim Chen 	}
72436005baeSTim Chen 
72536005baeSTim Chen done:
72636005baeSTim Chen 	si->flags -= SWP_SCANNING;
72736005baeSTim Chen 	return n_ret;
7287dfad418SHugh Dickins 
729ebebbbe9SHugh Dickins scan:
730ec8acf20SShaohua Li 	spin_unlock(&si->lock);
7317dfad418SHugh Dickins 	while (++offset <= si->highest_bit) {
73252b7efdbSHugh Dickins 		if (!si->swap_map[offset]) {
733ec8acf20SShaohua Li 			spin_lock(&si->lock);
73452b7efdbSHugh Dickins 			goto checks;
7357dfad418SHugh Dickins 		}
736c9e44410SKAMEZAWA Hiroyuki 		if (vm_swap_full() && si->swap_map[offset] == SWAP_HAS_CACHE) {
737ec8acf20SShaohua Li 			spin_lock(&si->lock);
738c9e44410SKAMEZAWA Hiroyuki 			goto checks;
739c9e44410SKAMEZAWA Hiroyuki 		}
740048c27fdSHugh Dickins 		if (unlikely(--latency_ration < 0)) {
741048c27fdSHugh Dickins 			cond_resched();
742048c27fdSHugh Dickins 			latency_ration = LATENCY_LIMIT;
743048c27fdSHugh Dickins 		}
74452b7efdbSHugh Dickins 	}
745c60aa176SHugh Dickins 	offset = si->lowest_bit;
746a5998061SJamie Liu 	while (offset < scan_base) {
747c60aa176SHugh Dickins 		if (!si->swap_map[offset]) {
748ec8acf20SShaohua Li 			spin_lock(&si->lock);
749ebebbbe9SHugh Dickins 			goto checks;
750c60aa176SHugh Dickins 		}
751c9e44410SKAMEZAWA Hiroyuki 		if (vm_swap_full() && si->swap_map[offset] == SWAP_HAS_CACHE) {
752ec8acf20SShaohua Li 			spin_lock(&si->lock);
753c9e44410SKAMEZAWA Hiroyuki 			goto checks;
754c9e44410SKAMEZAWA Hiroyuki 		}
755c60aa176SHugh Dickins 		if (unlikely(--latency_ration < 0)) {
756c60aa176SHugh Dickins 			cond_resched();
757c60aa176SHugh Dickins 			latency_ration = LATENCY_LIMIT;
758c60aa176SHugh Dickins 		}
759a5998061SJamie Liu 		offset++;
760c60aa176SHugh Dickins 	}
761ec8acf20SShaohua Li 	spin_lock(&si->lock);
7627dfad418SHugh Dickins 
7637dfad418SHugh Dickins no_page:
76452b7efdbSHugh Dickins 	si->flags -= SWP_SCANNING;
76536005baeSTim Chen 	return n_ret;
7661da177e4SLinus Torvalds }
7671da177e4SLinus Torvalds 
76836005baeSTim Chen static unsigned long scan_swap_map(struct swap_info_struct *si,
76936005baeSTim Chen 				   unsigned char usage)
77036005baeSTim Chen {
77136005baeSTim Chen 	swp_entry_t entry;
77236005baeSTim Chen 	int n_ret;
77336005baeSTim Chen 
77436005baeSTim Chen 	n_ret = scan_swap_map_slots(si, usage, 1, &entry);
77536005baeSTim Chen 
77636005baeSTim Chen 	if (n_ret)
77736005baeSTim Chen 		return swp_offset(entry);
77836005baeSTim Chen 	else
77936005baeSTim Chen 		return 0;
78036005baeSTim Chen 
78136005baeSTim Chen }
78236005baeSTim Chen 
78336005baeSTim Chen int get_swap_pages(int n_goal, swp_entry_t swp_entries[])
7841da177e4SLinus Torvalds {
785adfab836SDan Streetman 	struct swap_info_struct *si, *next;
78636005baeSTim Chen 	long avail_pgs;
78736005baeSTim Chen 	int n_ret = 0;
7881da177e4SLinus Torvalds 
78936005baeSTim Chen 	avail_pgs = atomic_long_read(&nr_swap_pages);
79036005baeSTim Chen 	if (avail_pgs <= 0)
791fb4f88dcSHugh Dickins 		goto noswap;
79236005baeSTim Chen 
79336005baeSTim Chen 	if (n_goal > SWAP_BATCH)
79436005baeSTim Chen 		n_goal = SWAP_BATCH;
79536005baeSTim Chen 
79636005baeSTim Chen 	if (n_goal > avail_pgs)
79736005baeSTim Chen 		n_goal = avail_pgs;
79836005baeSTim Chen 
79936005baeSTim Chen 	atomic_long_sub(n_goal, &nr_swap_pages);
8001da177e4SLinus Torvalds 
80118ab4d4cSDan Streetman 	spin_lock(&swap_avail_lock);
80218ab4d4cSDan Streetman 
80318ab4d4cSDan Streetman start_over:
80418ab4d4cSDan Streetman 	plist_for_each_entry_safe(si, next, &swap_avail_head, avail_list) {
80518ab4d4cSDan Streetman 		/* requeue si to after same-priority siblings */
80618ab4d4cSDan Streetman 		plist_requeue(&si->avail_list, &swap_avail_head);
80718ab4d4cSDan Streetman 		spin_unlock(&swap_avail_lock);
808ec8acf20SShaohua Li 		spin_lock(&si->lock);
809adfab836SDan Streetman 		if (!si->highest_bit || !(si->flags & SWP_WRITEOK)) {
81018ab4d4cSDan Streetman 			spin_lock(&swap_avail_lock);
81118ab4d4cSDan Streetman 			if (plist_node_empty(&si->avail_list)) {
812ec8acf20SShaohua Li 				spin_unlock(&si->lock);
81318ab4d4cSDan Streetman 				goto nextsi;
81418ab4d4cSDan Streetman 			}
81518ab4d4cSDan Streetman 			WARN(!si->highest_bit,
81618ab4d4cSDan Streetman 			     "swap_info %d in list but !highest_bit\n",
81718ab4d4cSDan Streetman 			     si->type);
81818ab4d4cSDan Streetman 			WARN(!(si->flags & SWP_WRITEOK),
81918ab4d4cSDan Streetman 			     "swap_info %d in list but !SWP_WRITEOK\n",
82018ab4d4cSDan Streetman 			     si->type);
82118ab4d4cSDan Streetman 			plist_del(&si->avail_list, &swap_avail_head);
82218ab4d4cSDan Streetman 			spin_unlock(&si->lock);
82318ab4d4cSDan Streetman 			goto nextsi;
824ec8acf20SShaohua Li 		}
82536005baeSTim Chen 		n_ret = scan_swap_map_slots(si, SWAP_HAS_CACHE,
82636005baeSTim Chen 					    n_goal, swp_entries);
827ec8acf20SShaohua Li 		spin_unlock(&si->lock);
82836005baeSTim Chen 		if (n_ret)
82936005baeSTim Chen 			goto check_out;
83018ab4d4cSDan Streetman 		pr_debug("scan_swap_map of si %d failed to find offset\n",
83118ab4d4cSDan Streetman 			si->type);
83236005baeSTim Chen 
83318ab4d4cSDan Streetman 		spin_lock(&swap_avail_lock);
83418ab4d4cSDan Streetman nextsi:
835adfab836SDan Streetman 		/*
836adfab836SDan Streetman 		 * if we got here, it's likely that si was almost full before,
837adfab836SDan Streetman 		 * and since scan_swap_map() can drop the si->lock, multiple
838adfab836SDan Streetman 		 * callers probably all tried to get a page from the same si
83918ab4d4cSDan Streetman 		 * and it filled up before we could get one; or, the si filled
84018ab4d4cSDan Streetman 		 * up between us dropping swap_avail_lock and taking si->lock.
84118ab4d4cSDan Streetman 		 * Since we dropped the swap_avail_lock, the swap_avail_head
84218ab4d4cSDan Streetman 		 * list may have been modified; so if next is still in the
84336005baeSTim Chen 		 * swap_avail_head list then try it, otherwise start over
84436005baeSTim Chen 		 * if we have not gotten any slots.
845adfab836SDan Streetman 		 */
84618ab4d4cSDan Streetman 		if (plist_node_empty(&next->avail_list))
84718ab4d4cSDan Streetman 			goto start_over;
848fb4f88dcSHugh Dickins 	}
849fb4f88dcSHugh Dickins 
85018ab4d4cSDan Streetman 	spin_unlock(&swap_avail_lock);
85118ab4d4cSDan Streetman 
85236005baeSTim Chen check_out:
85336005baeSTim Chen 	if (n_ret < n_goal)
85436005baeSTim Chen 		atomic_long_add((long) (n_goal-n_ret), &nr_swap_pages);
855fb4f88dcSHugh Dickins noswap:
85636005baeSTim Chen 	return n_ret;
85736005baeSTim Chen }
85836005baeSTim Chen 
8592de1a7e4SSeth Jennings /* The only caller of this function is now suspend routine */
860910321eaSHugh Dickins swp_entry_t get_swap_page_of_type(int type)
861910321eaSHugh Dickins {
862910321eaSHugh Dickins 	struct swap_info_struct *si;
863910321eaSHugh Dickins 	pgoff_t offset;
864910321eaSHugh Dickins 
865910321eaSHugh Dickins 	si = swap_info[type];
866ec8acf20SShaohua Li 	spin_lock(&si->lock);
867910321eaSHugh Dickins 	if (si && (si->flags & SWP_WRITEOK)) {
868ec8acf20SShaohua Li 		atomic_long_dec(&nr_swap_pages);
869910321eaSHugh Dickins 		/* This is called for allocating swap entry, not cache */
870910321eaSHugh Dickins 		offset = scan_swap_map(si, 1);
871910321eaSHugh Dickins 		if (offset) {
872ec8acf20SShaohua Li 			spin_unlock(&si->lock);
873910321eaSHugh Dickins 			return swp_entry(type, offset);
874910321eaSHugh Dickins 		}
875ec8acf20SShaohua Li 		atomic_long_inc(&nr_swap_pages);
876910321eaSHugh Dickins 	}
877ec8acf20SShaohua Li 	spin_unlock(&si->lock);
878910321eaSHugh Dickins 	return (swp_entry_t) {0};
879910321eaSHugh Dickins }
880910321eaSHugh Dickins 
881e8c26ab6STim Chen static struct swap_info_struct *__swap_info_get(swp_entry_t entry)
8821da177e4SLinus Torvalds {
8831da177e4SLinus Torvalds 	struct swap_info_struct *p;
8841da177e4SLinus Torvalds 	unsigned long offset, type;
8851da177e4SLinus Torvalds 
8861da177e4SLinus Torvalds 	if (!entry.val)
8871da177e4SLinus Torvalds 		goto out;
8881da177e4SLinus Torvalds 	type = swp_type(entry);
8891da177e4SLinus Torvalds 	if (type >= nr_swapfiles)
8901da177e4SLinus Torvalds 		goto bad_nofile;
891efa90a98SHugh Dickins 	p = swap_info[type];
8921da177e4SLinus Torvalds 	if (!(p->flags & SWP_USED))
8931da177e4SLinus Torvalds 		goto bad_device;
8941da177e4SLinus Torvalds 	offset = swp_offset(entry);
8951da177e4SLinus Torvalds 	if (offset >= p->max)
8961da177e4SLinus Torvalds 		goto bad_offset;
8971da177e4SLinus Torvalds 	return p;
8981da177e4SLinus Torvalds 
8991da177e4SLinus Torvalds bad_offset:
9006a991fc7SHuang, Ying 	pr_err("swap_info_get: %s%08lx\n", Bad_offset, entry.val);
9011da177e4SLinus Torvalds 	goto out;
9021da177e4SLinus Torvalds bad_device:
9036a991fc7SHuang, Ying 	pr_err("swap_info_get: %s%08lx\n", Unused_file, entry.val);
9041da177e4SLinus Torvalds 	goto out;
9051da177e4SLinus Torvalds bad_nofile:
9066a991fc7SHuang, Ying 	pr_err("swap_info_get: %s%08lx\n", Bad_file, entry.val);
9071da177e4SLinus Torvalds out:
9081da177e4SLinus Torvalds 	return NULL;
9091da177e4SLinus Torvalds }
9101da177e4SLinus Torvalds 
911e8c26ab6STim Chen static struct swap_info_struct *_swap_info_get(swp_entry_t entry)
912e8c26ab6STim Chen {
913e8c26ab6STim Chen 	struct swap_info_struct *p;
914e8c26ab6STim Chen 
915e8c26ab6STim Chen 	p = __swap_info_get(entry);
916e8c26ab6STim Chen 	if (!p)
917e8c26ab6STim Chen 		goto out;
918e8c26ab6STim Chen 	if (!p->swap_map[swp_offset(entry)])
919e8c26ab6STim Chen 		goto bad_free;
920e8c26ab6STim Chen 	return p;
921e8c26ab6STim Chen 
922e8c26ab6STim Chen bad_free:
923e8c26ab6STim Chen 	pr_err("swap_info_get: %s%08lx\n", Unused_offset, entry.val);
924e8c26ab6STim Chen 	goto out;
925e8c26ab6STim Chen out:
926e8c26ab6STim Chen 	return NULL;
927e8c26ab6STim Chen }
928e8c26ab6STim Chen 
929235b6217SHuang, Ying static struct swap_info_struct *swap_info_get(swp_entry_t entry)
9301da177e4SLinus Torvalds {
931235b6217SHuang, Ying 	struct swap_info_struct *p;
932235b6217SHuang, Ying 
933235b6217SHuang, Ying 	p = _swap_info_get(entry);
934235b6217SHuang, Ying 	if (p)
935235b6217SHuang, Ying 		spin_lock(&p->lock);
936235b6217SHuang, Ying 	return p;
937235b6217SHuang, Ying }
938235b6217SHuang, Ying 
9397c00bafeSTim Chen static struct swap_info_struct *swap_info_get_cont(swp_entry_t entry,
9407c00bafeSTim Chen 					struct swap_info_struct *q)
9417c00bafeSTim Chen {
9427c00bafeSTim Chen 	struct swap_info_struct *p;
9437c00bafeSTim Chen 
9447c00bafeSTim Chen 	p = _swap_info_get(entry);
9457c00bafeSTim Chen 
9467c00bafeSTim Chen 	if (p != q) {
9477c00bafeSTim Chen 		if (q != NULL)
9487c00bafeSTim Chen 			spin_unlock(&q->lock);
9497c00bafeSTim Chen 		if (p != NULL)
9507c00bafeSTim Chen 			spin_lock(&p->lock);
9517c00bafeSTim Chen 	}
9527c00bafeSTim Chen 	return p;
9537c00bafeSTim Chen }
9547c00bafeSTim Chen 
9557c00bafeSTim Chen static unsigned char __swap_entry_free(struct swap_info_struct *p,
9567c00bafeSTim Chen 				       swp_entry_t entry, unsigned char usage)
957235b6217SHuang, Ying {
958235b6217SHuang, Ying 	struct swap_cluster_info *ci;
959253d553bSHugh Dickins 	unsigned long offset = swp_offset(entry);
9608d69aaeeSHugh Dickins 	unsigned char count;
9618d69aaeeSHugh Dickins 	unsigned char has_cache;
962235b6217SHuang, Ying 
9637c00bafeSTim Chen 	ci = lock_cluster_or_swap_info(p, offset);
9641da177e4SLinus Torvalds 
965355cfa73SKAMEZAWA Hiroyuki 	count = p->swap_map[offset];
966235b6217SHuang, Ying 
967253d553bSHugh Dickins 	has_cache = count & SWAP_HAS_CACHE;
968253d553bSHugh Dickins 	count &= ~SWAP_HAS_CACHE;
969253d553bSHugh Dickins 
970253d553bSHugh Dickins 	if (usage == SWAP_HAS_CACHE) {
971253d553bSHugh Dickins 		VM_BUG_ON(!has_cache);
972253d553bSHugh Dickins 		has_cache = 0;
973aaa46865SHugh Dickins 	} else if (count == SWAP_MAP_SHMEM) {
974aaa46865SHugh Dickins 		/*
975aaa46865SHugh Dickins 		 * Or we could insist on shmem.c using a special
976aaa46865SHugh Dickins 		 * swap_shmem_free() and free_shmem_swap_and_cache()...
977aaa46865SHugh Dickins 		 */
978aaa46865SHugh Dickins 		count = 0;
979570a335bSHugh Dickins 	} else if ((count & ~COUNT_CONTINUED) <= SWAP_MAP_MAX) {
980570a335bSHugh Dickins 		if (count == COUNT_CONTINUED) {
981570a335bSHugh Dickins 			if (swap_count_continued(p, offset, count))
982570a335bSHugh Dickins 				count = SWAP_MAP_MAX | COUNT_CONTINUED;
983570a335bSHugh Dickins 			else
984570a335bSHugh Dickins 				count = SWAP_MAP_MAX;
985570a335bSHugh Dickins 		} else
986253d553bSHugh Dickins 			count--;
987570a335bSHugh Dickins 	}
988253d553bSHugh Dickins 
989253d553bSHugh Dickins 	usage = count | has_cache;
9907c00bafeSTim Chen 	p->swap_map[offset] = usage ? : SWAP_HAS_CACHE;
991253d553bSHugh Dickins 
9927c00bafeSTim Chen 	unlock_cluster_or_swap_info(p, ci);
993235b6217SHuang, Ying 
9947c00bafeSTim Chen 	return usage;
9957c00bafeSTim Chen }
9967c00bafeSTim Chen 
9977c00bafeSTim Chen static void swap_entry_free(struct swap_info_struct *p, swp_entry_t entry)
9987c00bafeSTim Chen {
9997c00bafeSTim Chen 	struct swap_cluster_info *ci;
10007c00bafeSTim Chen 	unsigned long offset = swp_offset(entry);
10017c00bafeSTim Chen 	unsigned char count;
10027c00bafeSTim Chen 
1003235b6217SHuang, Ying 	ci = lock_cluster(p, offset);
10047c00bafeSTim Chen 	count = p->swap_map[offset];
10057c00bafeSTim Chen 	VM_BUG_ON(count != SWAP_HAS_CACHE);
10067c00bafeSTim Chen 	p->swap_map[offset] = 0;
10072a8f9449SShaohua Li 	dec_cluster_info_page(p, p->cluster_info, offset);
1008235b6217SHuang, Ying 	unlock_cluster(ci);
10097c00bafeSTim Chen 
10107c00bafeSTim Chen 	mem_cgroup_uncharge_swap(entry);
10111da177e4SLinus Torvalds 	if (offset < p->lowest_bit)
10121da177e4SLinus Torvalds 		p->lowest_bit = offset;
101318ab4d4cSDan Streetman 	if (offset > p->highest_bit) {
101418ab4d4cSDan Streetman 		bool was_full = !p->highest_bit;
10157c00bafeSTim Chen 
10161da177e4SLinus Torvalds 		p->highest_bit = offset;
101718ab4d4cSDan Streetman 		if (was_full && (p->flags & SWP_WRITEOK)) {
101818ab4d4cSDan Streetman 			spin_lock(&swap_avail_lock);
101918ab4d4cSDan Streetman 			WARN_ON(!plist_node_empty(&p->avail_list));
102018ab4d4cSDan Streetman 			if (plist_node_empty(&p->avail_list))
102118ab4d4cSDan Streetman 				plist_add(&p->avail_list,
102218ab4d4cSDan Streetman 					  &swap_avail_head);
102318ab4d4cSDan Streetman 			spin_unlock(&swap_avail_lock);
102418ab4d4cSDan Streetman 		}
102518ab4d4cSDan Streetman 	}
1026ec8acf20SShaohua Li 	atomic_long_inc(&nr_swap_pages);
10271da177e4SLinus Torvalds 	p->inuse_pages--;
102838b5faf4SDan Magenheimer 	frontswap_invalidate_page(p->type, offset);
102973744923SMel Gorman 	if (p->flags & SWP_BLKDEV) {
103073744923SMel Gorman 		struct gendisk *disk = p->bdev->bd_disk;
10317c00bafeSTim Chen 
103273744923SMel Gorman 		if (disk->fops->swap_slot_free_notify)
103373744923SMel Gorman 			disk->fops->swap_slot_free_notify(p->bdev,
103473744923SMel Gorman 							  offset);
103573744923SMel Gorman 	}
10361da177e4SLinus Torvalds }
1037253d553bSHugh Dickins 
10381da177e4SLinus Torvalds /*
10391da177e4SLinus Torvalds  * Caller has made sure that the swap device corresponding to entry
10401da177e4SLinus Torvalds  * is still around or has not been recycled.
10411da177e4SLinus Torvalds  */
10421da177e4SLinus Torvalds void swap_free(swp_entry_t entry)
10431da177e4SLinus Torvalds {
10441da177e4SLinus Torvalds 	struct swap_info_struct *p;
10451da177e4SLinus Torvalds 
1046235b6217SHuang, Ying 	p = _swap_info_get(entry);
10477c00bafeSTim Chen 	if (p) {
10487c00bafeSTim Chen 		if (!__swap_entry_free(p, entry, 1))
104967afa38eSTim Chen 			free_swap_slot(entry);
10507c00bafeSTim Chen 	}
10511da177e4SLinus Torvalds }
10521da177e4SLinus Torvalds 
10531da177e4SLinus Torvalds /*
1054cb4b86baSKAMEZAWA Hiroyuki  * Called after dropping swapcache to decrease refcnt to swap entries.
1055cb4b86baSKAMEZAWA Hiroyuki  */
10560a31bc97SJohannes Weiner void swapcache_free(swp_entry_t entry)
1057cb4b86baSKAMEZAWA Hiroyuki {
1058355cfa73SKAMEZAWA Hiroyuki 	struct swap_info_struct *p;
1059355cfa73SKAMEZAWA Hiroyuki 
1060235b6217SHuang, Ying 	p = _swap_info_get(entry);
10617c00bafeSTim Chen 	if (p) {
10627c00bafeSTim Chen 		if (!__swap_entry_free(p, entry, SWAP_HAS_CACHE))
106367afa38eSTim Chen 			free_swap_slot(entry);
10647c00bafeSTim Chen 	}
10657c00bafeSTim Chen }
10667c00bafeSTim Chen 
10677c00bafeSTim Chen void swapcache_free_entries(swp_entry_t *entries, int n)
10687c00bafeSTim Chen {
10697c00bafeSTim Chen 	struct swap_info_struct *p, *prev;
10707c00bafeSTim Chen 	int i;
10717c00bafeSTim Chen 
10727c00bafeSTim Chen 	if (n <= 0)
10737c00bafeSTim Chen 		return;
10747c00bafeSTim Chen 
10757c00bafeSTim Chen 	prev = NULL;
10767c00bafeSTim Chen 	p = NULL;
10777c00bafeSTim Chen 	for (i = 0; i < n; ++i) {
10787c00bafeSTim Chen 		p = swap_info_get_cont(entries[i], prev);
1079235b6217SHuang, Ying 		if (p)
10807c00bafeSTim Chen 			swap_entry_free(p, entries[i]);
10817c00bafeSTim Chen 		else
10827c00bafeSTim Chen 			break;
10837c00bafeSTim Chen 		prev = p;
10847c00bafeSTim Chen 	}
10857c00bafeSTim Chen 	if (p)
10867c00bafeSTim Chen 		spin_unlock(&p->lock);
1087cb4b86baSKAMEZAWA Hiroyuki }
1088cb4b86baSKAMEZAWA Hiroyuki 
1089cb4b86baSKAMEZAWA Hiroyuki /*
1090c475a8abSHugh Dickins  * How many references to page are currently swapped out?
1091570a335bSHugh Dickins  * This does not give an exact answer when swap count is continued,
1092570a335bSHugh Dickins  * but does include the high COUNT_CONTINUED flag to allow for that.
10931da177e4SLinus Torvalds  */
1094bde05d1cSHugh Dickins int page_swapcount(struct page *page)
10951da177e4SLinus Torvalds {
1096c475a8abSHugh Dickins 	int count = 0;
10971da177e4SLinus Torvalds 	struct swap_info_struct *p;
1098235b6217SHuang, Ying 	struct swap_cluster_info *ci;
10991da177e4SLinus Torvalds 	swp_entry_t entry;
1100235b6217SHuang, Ying 	unsigned long offset;
11011da177e4SLinus Torvalds 
11024c21e2f2SHugh Dickins 	entry.val = page_private(page);
1103235b6217SHuang, Ying 	p = _swap_info_get(entry);
11041da177e4SLinus Torvalds 	if (p) {
1105235b6217SHuang, Ying 		offset = swp_offset(entry);
1106235b6217SHuang, Ying 		ci = lock_cluster_or_swap_info(p, offset);
1107235b6217SHuang, Ying 		count = swap_count(p->swap_map[offset]);
1108235b6217SHuang, Ying 		unlock_cluster_or_swap_info(p, ci);
11091da177e4SLinus Torvalds 	}
1110c475a8abSHugh Dickins 	return count;
11111da177e4SLinus Torvalds }
11121da177e4SLinus Torvalds 
11131da177e4SLinus Torvalds /*
11148334b962SMinchan Kim  * How many references to @entry are currently swapped out?
1115e8c26ab6STim Chen  * This does not give an exact answer when swap count is continued,
1116e8c26ab6STim Chen  * but does include the high COUNT_CONTINUED flag to allow for that.
1117e8c26ab6STim Chen  */
1118e8c26ab6STim Chen int __swp_swapcount(swp_entry_t entry)
1119e8c26ab6STim Chen {
1120e8c26ab6STim Chen 	int count = 0;
1121e8c26ab6STim Chen 	pgoff_t offset;
1122e8c26ab6STim Chen 	struct swap_info_struct *si;
1123e8c26ab6STim Chen 	struct swap_cluster_info *ci;
1124e8c26ab6STim Chen 
1125e8c26ab6STim Chen 	si = __swap_info_get(entry);
1126e8c26ab6STim Chen 	if (si) {
1127e8c26ab6STim Chen 		offset = swp_offset(entry);
1128e8c26ab6STim Chen 		ci = lock_cluster_or_swap_info(si, offset);
1129e8c26ab6STim Chen 		count = swap_count(si->swap_map[offset]);
1130e8c26ab6STim Chen 		unlock_cluster_or_swap_info(si, ci);
1131e8c26ab6STim Chen 	}
1132e8c26ab6STim Chen 	return count;
1133e8c26ab6STim Chen }
1134e8c26ab6STim Chen 
1135e8c26ab6STim Chen /*
1136e8c26ab6STim Chen  * How many references to @entry are currently swapped out?
11378334b962SMinchan Kim  * This considers COUNT_CONTINUED so it returns exact answer.
11388334b962SMinchan Kim  */
11398334b962SMinchan Kim int swp_swapcount(swp_entry_t entry)
11408334b962SMinchan Kim {
11418334b962SMinchan Kim 	int count, tmp_count, n;
11428334b962SMinchan Kim 	struct swap_info_struct *p;
1143235b6217SHuang, Ying 	struct swap_cluster_info *ci;
11448334b962SMinchan Kim 	struct page *page;
11458334b962SMinchan Kim 	pgoff_t offset;
11468334b962SMinchan Kim 	unsigned char *map;
11478334b962SMinchan Kim 
1148235b6217SHuang, Ying 	p = _swap_info_get(entry);
11498334b962SMinchan Kim 	if (!p)
11508334b962SMinchan Kim 		return 0;
11518334b962SMinchan Kim 
1152235b6217SHuang, Ying 	offset = swp_offset(entry);
1153235b6217SHuang, Ying 
1154235b6217SHuang, Ying 	ci = lock_cluster_or_swap_info(p, offset);
1155235b6217SHuang, Ying 
1156235b6217SHuang, Ying 	count = swap_count(p->swap_map[offset]);
11578334b962SMinchan Kim 	if (!(count & COUNT_CONTINUED))
11588334b962SMinchan Kim 		goto out;
11598334b962SMinchan Kim 
11608334b962SMinchan Kim 	count &= ~COUNT_CONTINUED;
11618334b962SMinchan Kim 	n = SWAP_MAP_MAX + 1;
11628334b962SMinchan Kim 
11638334b962SMinchan Kim 	page = vmalloc_to_page(p->swap_map + offset);
11648334b962SMinchan Kim 	offset &= ~PAGE_MASK;
11658334b962SMinchan Kim 	VM_BUG_ON(page_private(page) != SWP_CONTINUED);
11668334b962SMinchan Kim 
11678334b962SMinchan Kim 	do {
1168a8ae4991SGeliang Tang 		page = list_next_entry(page, lru);
11698334b962SMinchan Kim 		map = kmap_atomic(page);
11708334b962SMinchan Kim 		tmp_count = map[offset];
11718334b962SMinchan Kim 		kunmap_atomic(map);
11728334b962SMinchan Kim 
11738334b962SMinchan Kim 		count += (tmp_count & ~COUNT_CONTINUED) * n;
11748334b962SMinchan Kim 		n *= (SWAP_CONT_MAX + 1);
11758334b962SMinchan Kim 	} while (tmp_count & COUNT_CONTINUED);
11768334b962SMinchan Kim out:
1177235b6217SHuang, Ying 	unlock_cluster_or_swap_info(p, ci);
11788334b962SMinchan Kim 	return count;
11798334b962SMinchan Kim }
11808334b962SMinchan Kim 
11818334b962SMinchan Kim /*
11827b1fe597SHugh Dickins  * We can write to an anon page without COW if there are no other references
11837b1fe597SHugh Dickins  * to it.  And as a side-effect, free up its swap: because the old content
11847b1fe597SHugh Dickins  * on disk will never be read, and seeking back there to write new content
11857b1fe597SHugh Dickins  * later would only waste time away from clustering.
11866d0a07edSAndrea Arcangeli  *
11876d0a07edSAndrea Arcangeli  * NOTE: total_mapcount should not be relied upon by the caller if
11886d0a07edSAndrea Arcangeli  * reuse_swap_page() returns false, but it may be always overwritten
11896d0a07edSAndrea Arcangeli  * (see the other implementation for CONFIG_SWAP=n).
11901da177e4SLinus Torvalds  */
11916d0a07edSAndrea Arcangeli bool reuse_swap_page(struct page *page, int *total_mapcount)
11921da177e4SLinus Torvalds {
1193c475a8abSHugh Dickins 	int count;
11941da177e4SLinus Torvalds 
1195309381feSSasha Levin 	VM_BUG_ON_PAGE(!PageLocked(page), page);
11965ad64688SHugh Dickins 	if (unlikely(PageKsm(page)))
11976d0a07edSAndrea Arcangeli 		return false;
11986d0a07edSAndrea Arcangeli 	count = page_trans_huge_mapcount(page, total_mapcount);
11997b1fe597SHugh Dickins 	if (count <= 1 && PageSwapCache(page)) {
1200c475a8abSHugh Dickins 		count += page_swapcount(page);
1201f0571429SMinchan Kim 		if (count != 1)
1202f0571429SMinchan Kim 			goto out;
1203f0571429SMinchan Kim 		if (!PageWriteback(page)) {
12047b1fe597SHugh Dickins 			delete_from_swap_cache(page);
12057b1fe597SHugh Dickins 			SetPageDirty(page);
1206f0571429SMinchan Kim 		} else {
1207f0571429SMinchan Kim 			swp_entry_t entry;
1208f0571429SMinchan Kim 			struct swap_info_struct *p;
1209f0571429SMinchan Kim 
1210f0571429SMinchan Kim 			entry.val = page_private(page);
1211f0571429SMinchan Kim 			p = swap_info_get(entry);
1212f0571429SMinchan Kim 			if (p->flags & SWP_STABLE_WRITES) {
1213f0571429SMinchan Kim 				spin_unlock(&p->lock);
1214f0571429SMinchan Kim 				return false;
1215f0571429SMinchan Kim 			}
1216f0571429SMinchan Kim 			spin_unlock(&p->lock);
12177b1fe597SHugh Dickins 		}
12187b1fe597SHugh Dickins 	}
1219f0571429SMinchan Kim out:
12205ad64688SHugh Dickins 	return count <= 1;
12211da177e4SLinus Torvalds }
12221da177e4SLinus Torvalds 
12231da177e4SLinus Torvalds /*
1224a2c43eedSHugh Dickins  * If swap is getting full, or if there are no more mappings of this page,
1225a2c43eedSHugh Dickins  * then try_to_free_swap is called to free its swap space.
12261da177e4SLinus Torvalds  */
1227a2c43eedSHugh Dickins int try_to_free_swap(struct page *page)
12281da177e4SLinus Torvalds {
1229309381feSSasha Levin 	VM_BUG_ON_PAGE(!PageLocked(page), page);
12301da177e4SLinus Torvalds 
12311da177e4SLinus Torvalds 	if (!PageSwapCache(page))
12321da177e4SLinus Torvalds 		return 0;
12331da177e4SLinus Torvalds 	if (PageWriteback(page))
12341da177e4SLinus Torvalds 		return 0;
1235a2c43eedSHugh Dickins 	if (page_swapcount(page))
12361da177e4SLinus Torvalds 		return 0;
12371da177e4SLinus Torvalds 
1238b73d7fceSHugh Dickins 	/*
1239b73d7fceSHugh Dickins 	 * Once hibernation has begun to create its image of memory,
1240b73d7fceSHugh Dickins 	 * there's a danger that one of the calls to try_to_free_swap()
1241b73d7fceSHugh Dickins 	 * - most probably a call from __try_to_reclaim_swap() while
1242b73d7fceSHugh Dickins 	 * hibernation is allocating its own swap pages for the image,
1243b73d7fceSHugh Dickins 	 * but conceivably even a call from memory reclaim - will free
1244b73d7fceSHugh Dickins 	 * the swap from a page which has already been recorded in the
1245b73d7fceSHugh Dickins 	 * image as a clean swapcache page, and then reuse its swap for
1246b73d7fceSHugh Dickins 	 * another page of the image.  On waking from hibernation, the
1247b73d7fceSHugh Dickins 	 * original page might be freed under memory pressure, then
1248b73d7fceSHugh Dickins 	 * later read back in from swap, now with the wrong data.
1249b73d7fceSHugh Dickins 	 *
12502de1a7e4SSeth Jennings 	 * Hibernation suspends storage while it is writing the image
1251f90ac398SMel Gorman 	 * to disk so check that here.
1252b73d7fceSHugh Dickins 	 */
1253f90ac398SMel Gorman 	if (pm_suspended_storage())
1254b73d7fceSHugh Dickins 		return 0;
1255b73d7fceSHugh Dickins 
1256a2c43eedSHugh Dickins 	delete_from_swap_cache(page);
12571da177e4SLinus Torvalds 	SetPageDirty(page);
1258a2c43eedSHugh Dickins 	return 1;
125968a22394SRik van Riel }
126068a22394SRik van Riel 
126168a22394SRik van Riel /*
12621da177e4SLinus Torvalds  * Free the swap entry like above, but also try to
12631da177e4SLinus Torvalds  * free the page cache entry if it is the last user.
12641da177e4SLinus Torvalds  */
12652509ef26SHugh Dickins int free_swap_and_cache(swp_entry_t entry)
12661da177e4SLinus Torvalds {
12671da177e4SLinus Torvalds 	struct swap_info_struct *p;
12681da177e4SLinus Torvalds 	struct page *page = NULL;
12697c00bafeSTim Chen 	unsigned char count;
12701da177e4SLinus Torvalds 
1271a7420aa5SAndi Kleen 	if (non_swap_entry(entry))
12722509ef26SHugh Dickins 		return 1;
12730697212aSChristoph Lameter 
12747c00bafeSTim Chen 	p = _swap_info_get(entry);
12751da177e4SLinus Torvalds 	if (p) {
12767c00bafeSTim Chen 		count = __swap_entry_free(p, entry, 1);
12777c00bafeSTim Chen 		if (count == SWAP_HAS_CACHE) {
127833806f06SShaohua Li 			page = find_get_page(swap_address_space(entry),
1279f6ab1f7fSHuang Ying 					     swp_offset(entry));
12808413ac9dSNick Piggin 			if (page && !trylock_page(page)) {
128109cbfeafSKirill A. Shutemov 				put_page(page);
128293fac704SNick Piggin 				page = NULL;
128393fac704SNick Piggin 			}
12847c00bafeSTim Chen 		} else if (!count)
128567afa38eSTim Chen 			free_swap_slot(entry);
12861da177e4SLinus Torvalds 	}
12871da177e4SLinus Torvalds 	if (page) {
1288a2c43eedSHugh Dickins 		/*
1289a2c43eedSHugh Dickins 		 * Not mapped elsewhere, or swap space full? Free it!
1290a2c43eedSHugh Dickins 		 * Also recheck PageSwapCache now page is locked (above).
1291a2c43eedSHugh Dickins 		 */
129293fac704SNick Piggin 		if (PageSwapCache(page) && !PageWriteback(page) &&
12935ccc5abaSVladimir Davydov 		    (!page_mapped(page) || mem_cgroup_swap_full(page))) {
12941da177e4SLinus Torvalds 			delete_from_swap_cache(page);
12951da177e4SLinus Torvalds 			SetPageDirty(page);
12961da177e4SLinus Torvalds 		}
12971da177e4SLinus Torvalds 		unlock_page(page);
129809cbfeafSKirill A. Shutemov 		put_page(page);
12991da177e4SLinus Torvalds 	}
13002509ef26SHugh Dickins 	return p != NULL;
13011da177e4SLinus Torvalds }
13021da177e4SLinus Torvalds 
1303b0cb1a19SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
1304f577eb30SRafael J. Wysocki /*
1305915bae9eSRafael J. Wysocki  * Find the swap type that corresponds to given device (if any).
1306f577eb30SRafael J. Wysocki  *
1307915bae9eSRafael J. Wysocki  * @offset - number of the PAGE_SIZE-sized block of the device, starting
1308915bae9eSRafael J. Wysocki  * from 0, in which the swap header is expected to be located.
1309915bae9eSRafael J. Wysocki  *
1310915bae9eSRafael J. Wysocki  * This is needed for the suspend to disk (aka swsusp).
1311f577eb30SRafael J. Wysocki  */
13127bf23687SRafael J. Wysocki int swap_type_of(dev_t device, sector_t offset, struct block_device **bdev_p)
1313f577eb30SRafael J. Wysocki {
1314915bae9eSRafael J. Wysocki 	struct block_device *bdev = NULL;
1315efa90a98SHugh Dickins 	int type;
1316f577eb30SRafael J. Wysocki 
1317915bae9eSRafael J. Wysocki 	if (device)
1318915bae9eSRafael J. Wysocki 		bdev = bdget(device);
1319915bae9eSRafael J. Wysocki 
1320f577eb30SRafael J. Wysocki 	spin_lock(&swap_lock);
1321efa90a98SHugh Dickins 	for (type = 0; type < nr_swapfiles; type++) {
1322efa90a98SHugh Dickins 		struct swap_info_struct *sis = swap_info[type];
1323f577eb30SRafael J. Wysocki 
1324915bae9eSRafael J. Wysocki 		if (!(sis->flags & SWP_WRITEOK))
1325f577eb30SRafael J. Wysocki 			continue;
1326b6b5bce3SRafael J. Wysocki 
1327915bae9eSRafael J. Wysocki 		if (!bdev) {
13287bf23687SRafael J. Wysocki 			if (bdev_p)
1329dddac6a7SAlan Jenkins 				*bdev_p = bdgrab(sis->bdev);
13307bf23687SRafael J. Wysocki 
13316e1819d6SRafael J. Wysocki 			spin_unlock(&swap_lock);
1332efa90a98SHugh Dickins 			return type;
13336e1819d6SRafael J. Wysocki 		}
1334915bae9eSRafael J. Wysocki 		if (bdev == sis->bdev) {
13359625a5f2SHugh Dickins 			struct swap_extent *se = &sis->first_swap_extent;
1336915bae9eSRafael J. Wysocki 
1337915bae9eSRafael J. Wysocki 			if (se->start_block == offset) {
13387bf23687SRafael J. Wysocki 				if (bdev_p)
1339dddac6a7SAlan Jenkins 					*bdev_p = bdgrab(sis->bdev);
13407bf23687SRafael J. Wysocki 
1341f577eb30SRafael J. Wysocki 				spin_unlock(&swap_lock);
1342915bae9eSRafael J. Wysocki 				bdput(bdev);
1343efa90a98SHugh Dickins 				return type;
1344f577eb30SRafael J. Wysocki 			}
1345f577eb30SRafael J. Wysocki 		}
1346915bae9eSRafael J. Wysocki 	}
1347f577eb30SRafael J. Wysocki 	spin_unlock(&swap_lock);
1348915bae9eSRafael J. Wysocki 	if (bdev)
1349915bae9eSRafael J. Wysocki 		bdput(bdev);
1350915bae9eSRafael J. Wysocki 
1351f577eb30SRafael J. Wysocki 	return -ENODEV;
1352f577eb30SRafael J. Wysocki }
1353f577eb30SRafael J. Wysocki 
1354f577eb30SRafael J. Wysocki /*
135573c34b6aSHugh Dickins  * Get the (PAGE_SIZE) block corresponding to given offset on the swapdev
135673c34b6aSHugh Dickins  * corresponding to given index in swap_info (swap type).
135773c34b6aSHugh Dickins  */
135873c34b6aSHugh Dickins sector_t swapdev_block(int type, pgoff_t offset)
135973c34b6aSHugh Dickins {
136073c34b6aSHugh Dickins 	struct block_device *bdev;
136173c34b6aSHugh Dickins 
136273c34b6aSHugh Dickins 	if ((unsigned int)type >= nr_swapfiles)
136373c34b6aSHugh Dickins 		return 0;
136473c34b6aSHugh Dickins 	if (!(swap_info[type]->flags & SWP_WRITEOK))
136573c34b6aSHugh Dickins 		return 0;
1366d4906e1aSLee Schermerhorn 	return map_swap_entry(swp_entry(type, offset), &bdev);
136773c34b6aSHugh Dickins }
136873c34b6aSHugh Dickins 
136973c34b6aSHugh Dickins /*
1370f577eb30SRafael J. Wysocki  * Return either the total number of swap pages of given type, or the number
1371f577eb30SRafael J. Wysocki  * of free pages of that type (depending on @free)
1372f577eb30SRafael J. Wysocki  *
1373f577eb30SRafael J. Wysocki  * This is needed for software suspend
1374f577eb30SRafael J. Wysocki  */
1375f577eb30SRafael J. Wysocki unsigned int count_swap_pages(int type, int free)
1376f577eb30SRafael J. Wysocki {
1377f577eb30SRafael J. Wysocki 	unsigned int n = 0;
1378f577eb30SRafael J. Wysocki 
1379f577eb30SRafael J. Wysocki 	spin_lock(&swap_lock);
1380efa90a98SHugh Dickins 	if ((unsigned int)type < nr_swapfiles) {
1381efa90a98SHugh Dickins 		struct swap_info_struct *sis = swap_info[type];
1382efa90a98SHugh Dickins 
1383ec8acf20SShaohua Li 		spin_lock(&sis->lock);
1384efa90a98SHugh Dickins 		if (sis->flags & SWP_WRITEOK) {
1385efa90a98SHugh Dickins 			n = sis->pages;
1386f577eb30SRafael J. Wysocki 			if (free)
1387efa90a98SHugh Dickins 				n -= sis->inuse_pages;
1388efa90a98SHugh Dickins 		}
1389ec8acf20SShaohua Li 		spin_unlock(&sis->lock);
1390f577eb30SRafael J. Wysocki 	}
1391f577eb30SRafael J. Wysocki 	spin_unlock(&swap_lock);
1392f577eb30SRafael J. Wysocki 	return n;
1393f577eb30SRafael J. Wysocki }
139473c34b6aSHugh Dickins #endif /* CONFIG_HIBERNATION */
1395f577eb30SRafael J. Wysocki 
13969f8bdb3fSHugh Dickins static inline int pte_same_as_swp(pte_t pte, pte_t swp_pte)
1397179ef71cSCyrill Gorcunov {
13989f8bdb3fSHugh Dickins 	return pte_same(pte_swp_clear_soft_dirty(pte), swp_pte);
1399179ef71cSCyrill Gorcunov }
1400179ef71cSCyrill Gorcunov 
14011da177e4SLinus Torvalds /*
140272866f6fSHugh Dickins  * No need to decide whether this PTE shares the swap entry with others,
140372866f6fSHugh Dickins  * just let do_wp_page work it out if a write is requested later - to
140472866f6fSHugh Dickins  * force COW, vm_page_prot omits write permission from any private vma.
14051da177e4SLinus Torvalds  */
1406044d66c1SHugh Dickins static int unuse_pte(struct vm_area_struct *vma, pmd_t *pmd,
14071da177e4SLinus Torvalds 		unsigned long addr, swp_entry_t entry, struct page *page)
14081da177e4SLinus Torvalds {
14099e16b7fbSHugh Dickins 	struct page *swapcache;
141072835c86SJohannes Weiner 	struct mem_cgroup *memcg;
1411044d66c1SHugh Dickins 	spinlock_t *ptl;
1412044d66c1SHugh Dickins 	pte_t *pte;
1413044d66c1SHugh Dickins 	int ret = 1;
1414044d66c1SHugh Dickins 
14159e16b7fbSHugh Dickins 	swapcache = page;
14169e16b7fbSHugh Dickins 	page = ksm_might_need_to_copy(page, vma, addr);
14179e16b7fbSHugh Dickins 	if (unlikely(!page))
14189e16b7fbSHugh Dickins 		return -ENOMEM;
14199e16b7fbSHugh Dickins 
1420f627c2f5SKirill A. Shutemov 	if (mem_cgroup_try_charge(page, vma->vm_mm, GFP_KERNEL,
1421f627c2f5SKirill A. Shutemov 				&memcg, false)) {
1422044d66c1SHugh Dickins 		ret = -ENOMEM;
142385d9fc89SKAMEZAWA Hiroyuki 		goto out_nolock;
142485d9fc89SKAMEZAWA Hiroyuki 	}
1425044d66c1SHugh Dickins 
1426044d66c1SHugh Dickins 	pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
14279f8bdb3fSHugh Dickins 	if (unlikely(!pte_same_as_swp(*pte, swp_entry_to_pte(entry)))) {
1428f627c2f5SKirill A. Shutemov 		mem_cgroup_cancel_charge(page, memcg, false);
1429044d66c1SHugh Dickins 		ret = 0;
1430044d66c1SHugh Dickins 		goto out;
1431044d66c1SHugh Dickins 	}
14328a9f3ccdSBalbir Singh 
1433b084d435SKAMEZAWA Hiroyuki 	dec_mm_counter(vma->vm_mm, MM_SWAPENTS);
1434d559db08SKAMEZAWA Hiroyuki 	inc_mm_counter(vma->vm_mm, MM_ANONPAGES);
14351da177e4SLinus Torvalds 	get_page(page);
14361da177e4SLinus Torvalds 	set_pte_at(vma->vm_mm, addr, pte,
14371da177e4SLinus Torvalds 		   pte_mkold(mk_pte(page, vma->vm_page_prot)));
143800501b53SJohannes Weiner 	if (page == swapcache) {
1439d281ee61SKirill A. Shutemov 		page_add_anon_rmap(page, vma, addr, false);
1440f627c2f5SKirill A. Shutemov 		mem_cgroup_commit_charge(page, memcg, true, false);
144100501b53SJohannes Weiner 	} else { /* ksm created a completely new copy */
1442d281ee61SKirill A. Shutemov 		page_add_new_anon_rmap(page, vma, addr, false);
1443f627c2f5SKirill A. Shutemov 		mem_cgroup_commit_charge(page, memcg, false, false);
144400501b53SJohannes Weiner 		lru_cache_add_active_or_unevictable(page, vma);
144500501b53SJohannes Weiner 	}
14461da177e4SLinus Torvalds 	swap_free(entry);
14471da177e4SLinus Torvalds 	/*
14481da177e4SLinus Torvalds 	 * Move the page to the active list so it is not
14491da177e4SLinus Torvalds 	 * immediately swapped out again after swapon.
14501da177e4SLinus Torvalds 	 */
14511da177e4SLinus Torvalds 	activate_page(page);
1452044d66c1SHugh Dickins out:
1453044d66c1SHugh Dickins 	pte_unmap_unlock(pte, ptl);
145485d9fc89SKAMEZAWA Hiroyuki out_nolock:
14559e16b7fbSHugh Dickins 	if (page != swapcache) {
14569e16b7fbSHugh Dickins 		unlock_page(page);
14579e16b7fbSHugh Dickins 		put_page(page);
14589e16b7fbSHugh Dickins 	}
1459044d66c1SHugh Dickins 	return ret;
14601da177e4SLinus Torvalds }
14611da177e4SLinus Torvalds 
14621da177e4SLinus Torvalds static int unuse_pte_range(struct vm_area_struct *vma, pmd_t *pmd,
14631da177e4SLinus Torvalds 				unsigned long addr, unsigned long end,
14641da177e4SLinus Torvalds 				swp_entry_t entry, struct page *page)
14651da177e4SLinus Torvalds {
14661da177e4SLinus Torvalds 	pte_t swp_pte = swp_entry_to_pte(entry);
1467705e87c0SHugh Dickins 	pte_t *pte;
14688a9f3ccdSBalbir Singh 	int ret = 0;
14691da177e4SLinus Torvalds 
1470044d66c1SHugh Dickins 	/*
1471044d66c1SHugh Dickins 	 * We don't actually need pte lock while scanning for swp_pte: since
1472044d66c1SHugh Dickins 	 * we hold page lock and mmap_sem, swp_pte cannot be inserted into the
1473044d66c1SHugh Dickins 	 * page table while we're scanning; though it could get zapped, and on
1474044d66c1SHugh Dickins 	 * some architectures (e.g. x86_32 with PAE) we might catch a glimpse
1475044d66c1SHugh Dickins 	 * of unmatched parts which look like swp_pte, so unuse_pte must
1476044d66c1SHugh Dickins 	 * recheck under pte lock.  Scanning without pte lock lets it be
14772de1a7e4SSeth Jennings 	 * preemptable whenever CONFIG_PREEMPT but not CONFIG_HIGHPTE.
1478044d66c1SHugh Dickins 	 */
1479044d66c1SHugh Dickins 	pte = pte_offset_map(pmd, addr);
14801da177e4SLinus Torvalds 	do {
14811da177e4SLinus Torvalds 		/*
14821da177e4SLinus Torvalds 		 * swapoff spends a _lot_ of time in this loop!
14831da177e4SLinus Torvalds 		 * Test inline before going to call unuse_pte.
14841da177e4SLinus Torvalds 		 */
14859f8bdb3fSHugh Dickins 		if (unlikely(pte_same_as_swp(*pte, swp_pte))) {
1486044d66c1SHugh Dickins 			pte_unmap(pte);
1487044d66c1SHugh Dickins 			ret = unuse_pte(vma, pmd, addr, entry, page);
1488044d66c1SHugh Dickins 			if (ret)
1489044d66c1SHugh Dickins 				goto out;
1490044d66c1SHugh Dickins 			pte = pte_offset_map(pmd, addr);
14911da177e4SLinus Torvalds 		}
14921da177e4SLinus Torvalds 	} while (pte++, addr += PAGE_SIZE, addr != end);
1493044d66c1SHugh Dickins 	pte_unmap(pte - 1);
1494044d66c1SHugh Dickins out:
14958a9f3ccdSBalbir Singh 	return ret;
14961da177e4SLinus Torvalds }
14971da177e4SLinus Torvalds 
14981da177e4SLinus Torvalds static inline int unuse_pmd_range(struct vm_area_struct *vma, pud_t *pud,
14991da177e4SLinus Torvalds 				unsigned long addr, unsigned long end,
15001da177e4SLinus Torvalds 				swp_entry_t entry, struct page *page)
15011da177e4SLinus Torvalds {
15021da177e4SLinus Torvalds 	pmd_t *pmd;
15031da177e4SLinus Torvalds 	unsigned long next;
15048a9f3ccdSBalbir Singh 	int ret;
15051da177e4SLinus Torvalds 
15061da177e4SLinus Torvalds 	pmd = pmd_offset(pud, addr);
15071da177e4SLinus Torvalds 	do {
1508dc644a07SHugh Dickins 		cond_resched();
15091da177e4SLinus Torvalds 		next = pmd_addr_end(addr, end);
15101a5a9906SAndrea Arcangeli 		if (pmd_none_or_trans_huge_or_clear_bad(pmd))
15111da177e4SLinus Torvalds 			continue;
15128a9f3ccdSBalbir Singh 		ret = unuse_pte_range(vma, pmd, addr, next, entry, page);
15138a9f3ccdSBalbir Singh 		if (ret)
15148a9f3ccdSBalbir Singh 			return ret;
15151da177e4SLinus Torvalds 	} while (pmd++, addr = next, addr != end);
15161da177e4SLinus Torvalds 	return 0;
15171da177e4SLinus Torvalds }
15181da177e4SLinus Torvalds 
15191da177e4SLinus Torvalds static inline int unuse_pud_range(struct vm_area_struct *vma, pgd_t *pgd,
15201da177e4SLinus Torvalds 				unsigned long addr, unsigned long end,
15211da177e4SLinus Torvalds 				swp_entry_t entry, struct page *page)
15221da177e4SLinus Torvalds {
15231da177e4SLinus Torvalds 	pud_t *pud;
15241da177e4SLinus Torvalds 	unsigned long next;
15258a9f3ccdSBalbir Singh 	int ret;
15261da177e4SLinus Torvalds 
15271da177e4SLinus Torvalds 	pud = pud_offset(pgd, addr);
15281da177e4SLinus Torvalds 	do {
15291da177e4SLinus Torvalds 		next = pud_addr_end(addr, end);
15301da177e4SLinus Torvalds 		if (pud_none_or_clear_bad(pud))
15311da177e4SLinus Torvalds 			continue;
15328a9f3ccdSBalbir Singh 		ret = unuse_pmd_range(vma, pud, addr, next, entry, page);
15338a9f3ccdSBalbir Singh 		if (ret)
15348a9f3ccdSBalbir Singh 			return ret;
15351da177e4SLinus Torvalds 	} while (pud++, addr = next, addr != end);
15361da177e4SLinus Torvalds 	return 0;
15371da177e4SLinus Torvalds }
15381da177e4SLinus Torvalds 
15391da177e4SLinus Torvalds static int unuse_vma(struct vm_area_struct *vma,
15401da177e4SLinus Torvalds 				swp_entry_t entry, struct page *page)
15411da177e4SLinus Torvalds {
15421da177e4SLinus Torvalds 	pgd_t *pgd;
15431da177e4SLinus Torvalds 	unsigned long addr, end, next;
15448a9f3ccdSBalbir Singh 	int ret;
15451da177e4SLinus Torvalds 
15463ca7b3c5SHugh Dickins 	if (page_anon_vma(page)) {
15471da177e4SLinus Torvalds 		addr = page_address_in_vma(page, vma);
15481da177e4SLinus Torvalds 		if (addr == -EFAULT)
15491da177e4SLinus Torvalds 			return 0;
15501da177e4SLinus Torvalds 		else
15511da177e4SLinus Torvalds 			end = addr + PAGE_SIZE;
15521da177e4SLinus Torvalds 	} else {
15531da177e4SLinus Torvalds 		addr = vma->vm_start;
15541da177e4SLinus Torvalds 		end = vma->vm_end;
15551da177e4SLinus Torvalds 	}
15561da177e4SLinus Torvalds 
15571da177e4SLinus Torvalds 	pgd = pgd_offset(vma->vm_mm, addr);
15581da177e4SLinus Torvalds 	do {
15591da177e4SLinus Torvalds 		next = pgd_addr_end(addr, end);
15601da177e4SLinus Torvalds 		if (pgd_none_or_clear_bad(pgd))
15611da177e4SLinus Torvalds 			continue;
15628a9f3ccdSBalbir Singh 		ret = unuse_pud_range(vma, pgd, addr, next, entry, page);
15638a9f3ccdSBalbir Singh 		if (ret)
15648a9f3ccdSBalbir Singh 			return ret;
15651da177e4SLinus Torvalds 	} while (pgd++, addr = next, addr != end);
15661da177e4SLinus Torvalds 	return 0;
15671da177e4SLinus Torvalds }
15681da177e4SLinus Torvalds 
15691da177e4SLinus Torvalds static int unuse_mm(struct mm_struct *mm,
15701da177e4SLinus Torvalds 				swp_entry_t entry, struct page *page)
15711da177e4SLinus Torvalds {
15721da177e4SLinus Torvalds 	struct vm_area_struct *vma;
15738a9f3ccdSBalbir Singh 	int ret = 0;
15741da177e4SLinus Torvalds 
15751da177e4SLinus Torvalds 	if (!down_read_trylock(&mm->mmap_sem)) {
15761da177e4SLinus Torvalds 		/*
15777d03431cSFernando Luis Vazquez Cao 		 * Activate page so shrink_inactive_list is unlikely to unmap
15787d03431cSFernando Luis Vazquez Cao 		 * its ptes while lock is dropped, so swapoff can make progress.
15791da177e4SLinus Torvalds 		 */
1580c475a8abSHugh Dickins 		activate_page(page);
15811da177e4SLinus Torvalds 		unlock_page(page);
15821da177e4SLinus Torvalds 		down_read(&mm->mmap_sem);
15831da177e4SLinus Torvalds 		lock_page(page);
15841da177e4SLinus Torvalds 	}
15851da177e4SLinus Torvalds 	for (vma = mm->mmap; vma; vma = vma->vm_next) {
15868a9f3ccdSBalbir Singh 		if (vma->anon_vma && (ret = unuse_vma(vma, entry, page)))
15871da177e4SLinus Torvalds 			break;
1588dc644a07SHugh Dickins 		cond_resched();
15891da177e4SLinus Torvalds 	}
15901da177e4SLinus Torvalds 	up_read(&mm->mmap_sem);
15918a9f3ccdSBalbir Singh 	return (ret < 0)? ret: 0;
15921da177e4SLinus Torvalds }
15931da177e4SLinus Torvalds 
15941da177e4SLinus Torvalds /*
159538b5faf4SDan Magenheimer  * Scan swap_map (or frontswap_map if frontswap parameter is true)
159638b5faf4SDan Magenheimer  * from current position to next entry still in use.
15971da177e4SLinus Torvalds  * Recycle to start on reaching the end, returning 0 when empty.
15981da177e4SLinus Torvalds  */
15996eb396dcSHugh Dickins static unsigned int find_next_to_unuse(struct swap_info_struct *si,
160038b5faf4SDan Magenheimer 					unsigned int prev, bool frontswap)
16011da177e4SLinus Torvalds {
16026eb396dcSHugh Dickins 	unsigned int max = si->max;
16036eb396dcSHugh Dickins 	unsigned int i = prev;
16048d69aaeeSHugh Dickins 	unsigned char count;
16051da177e4SLinus Torvalds 
16061da177e4SLinus Torvalds 	/*
16075d337b91SHugh Dickins 	 * No need for swap_lock here: we're just looking
16081da177e4SLinus Torvalds 	 * for whether an entry is in use, not modifying it; false
16091da177e4SLinus Torvalds 	 * hits are okay, and sys_swapoff() has already prevented new
16105d337b91SHugh Dickins 	 * allocations from this area (while holding swap_lock).
16111da177e4SLinus Torvalds 	 */
16121da177e4SLinus Torvalds 	for (;;) {
16131da177e4SLinus Torvalds 		if (++i >= max) {
16141da177e4SLinus Torvalds 			if (!prev) {
16151da177e4SLinus Torvalds 				i = 0;
16161da177e4SLinus Torvalds 				break;
16171da177e4SLinus Torvalds 			}
16181da177e4SLinus Torvalds 			/*
16191da177e4SLinus Torvalds 			 * No entries in use at top of swap_map,
16201da177e4SLinus Torvalds 			 * loop back to start and recheck there.
16211da177e4SLinus Torvalds 			 */
16221da177e4SLinus Torvalds 			max = prev + 1;
16231da177e4SLinus Torvalds 			prev = 0;
16241da177e4SLinus Torvalds 			i = 1;
16251da177e4SLinus Torvalds 		}
16264db0c3c2SJason Low 		count = READ_ONCE(si->swap_map[i]);
1627355cfa73SKAMEZAWA Hiroyuki 		if (count && swap_count(count) != SWAP_MAP_BAD)
1628dc644a07SHugh Dickins 			if (!frontswap || frontswap_test(si, i))
16291da177e4SLinus Torvalds 				break;
1630dc644a07SHugh Dickins 		if ((i % LATENCY_LIMIT) == 0)
1631dc644a07SHugh Dickins 			cond_resched();
16321da177e4SLinus Torvalds 	}
16331da177e4SLinus Torvalds 	return i;
16341da177e4SLinus Torvalds }
16351da177e4SLinus Torvalds 
16361da177e4SLinus Torvalds /*
16371da177e4SLinus Torvalds  * We completely avoid races by reading each swap page in advance,
16381da177e4SLinus Torvalds  * and then search for the process using it.  All the necessary
16391da177e4SLinus Torvalds  * page table adjustments can then be made atomically.
164038b5faf4SDan Magenheimer  *
164138b5faf4SDan Magenheimer  * if the boolean frontswap is true, only unuse pages_to_unuse pages;
164238b5faf4SDan Magenheimer  * pages_to_unuse==0 means all pages; ignored if frontswap is false
16431da177e4SLinus Torvalds  */
164438b5faf4SDan Magenheimer int try_to_unuse(unsigned int type, bool frontswap,
164538b5faf4SDan Magenheimer 		 unsigned long pages_to_unuse)
16461da177e4SLinus Torvalds {
1647efa90a98SHugh Dickins 	struct swap_info_struct *si = swap_info[type];
16481da177e4SLinus Torvalds 	struct mm_struct *start_mm;
1649edfe23daSShaohua Li 	volatile unsigned char *swap_map; /* swap_map is accessed without
1650edfe23daSShaohua Li 					   * locking. Mark it as volatile
1651edfe23daSShaohua Li 					   * to prevent compiler doing
1652edfe23daSShaohua Li 					   * something odd.
1653edfe23daSShaohua Li 					   */
16548d69aaeeSHugh Dickins 	unsigned char swcount;
16551da177e4SLinus Torvalds 	struct page *page;
16561da177e4SLinus Torvalds 	swp_entry_t entry;
16576eb396dcSHugh Dickins 	unsigned int i = 0;
16581da177e4SLinus Torvalds 	int retval = 0;
16591da177e4SLinus Torvalds 
16601da177e4SLinus Torvalds 	/*
16611da177e4SLinus Torvalds 	 * When searching mms for an entry, a good strategy is to
16621da177e4SLinus Torvalds 	 * start at the first mm we freed the previous entry from
16631da177e4SLinus Torvalds 	 * (though actually we don't notice whether we or coincidence
16641da177e4SLinus Torvalds 	 * freed the entry).  Initialize this start_mm with a hold.
16651da177e4SLinus Torvalds 	 *
16661da177e4SLinus Torvalds 	 * A simpler strategy would be to start at the last mm we
16671da177e4SLinus Torvalds 	 * freed the previous entry from; but that would take less
16681da177e4SLinus Torvalds 	 * advantage of mmlist ordering, which clusters forked mms
16691da177e4SLinus Torvalds 	 * together, child after parent.  If we race with dup_mmap(), we
16701da177e4SLinus Torvalds 	 * prefer to resolve parent before child, lest we miss entries
16711da177e4SLinus Torvalds 	 * duplicated after we scanned child: using last mm would invert
1672570a335bSHugh Dickins 	 * that.
16731da177e4SLinus Torvalds 	 */
16741da177e4SLinus Torvalds 	start_mm = &init_mm;
16753fce371bSVegard Nossum 	mmget(&init_mm);
16761da177e4SLinus Torvalds 
16771da177e4SLinus Torvalds 	/*
16781da177e4SLinus Torvalds 	 * Keep on scanning until all entries have gone.  Usually,
16791da177e4SLinus Torvalds 	 * one pass through swap_map is enough, but not necessarily:
16801da177e4SLinus Torvalds 	 * there are races when an instance of an entry might be missed.
16811da177e4SLinus Torvalds 	 */
168238b5faf4SDan Magenheimer 	while ((i = find_next_to_unuse(si, i, frontswap)) != 0) {
16831da177e4SLinus Torvalds 		if (signal_pending(current)) {
16841da177e4SLinus Torvalds 			retval = -EINTR;
16851da177e4SLinus Torvalds 			break;
16861da177e4SLinus Torvalds 		}
16871da177e4SLinus Torvalds 
16881da177e4SLinus Torvalds 		/*
16891da177e4SLinus Torvalds 		 * Get a page for the entry, using the existing swap
16901da177e4SLinus Torvalds 		 * cache page if there is one.  Otherwise, get a clean
16911da177e4SLinus Torvalds 		 * page and read the swap into it.
16921da177e4SLinus Torvalds 		 */
16931da177e4SLinus Torvalds 		swap_map = &si->swap_map[i];
16941da177e4SLinus Torvalds 		entry = swp_entry(type, i);
169502098feaSHugh Dickins 		page = read_swap_cache_async(entry,
169602098feaSHugh Dickins 					GFP_HIGHUSER_MOVABLE, NULL, 0);
16971da177e4SLinus Torvalds 		if (!page) {
16981da177e4SLinus Torvalds 			/*
16991da177e4SLinus Torvalds 			 * Either swap_duplicate() failed because entry
17001da177e4SLinus Torvalds 			 * has been freed independently, and will not be
17011da177e4SLinus Torvalds 			 * reused since sys_swapoff() already disabled
17021da177e4SLinus Torvalds 			 * allocation from here, or alloc_page() failed.
17031da177e4SLinus Torvalds 			 */
1704edfe23daSShaohua Li 			swcount = *swap_map;
1705edfe23daSShaohua Li 			/*
1706edfe23daSShaohua Li 			 * We don't hold lock here, so the swap entry could be
1707edfe23daSShaohua Li 			 * SWAP_MAP_BAD (when the cluster is discarding).
1708edfe23daSShaohua Li 			 * Instead of fail out, We can just skip the swap
1709edfe23daSShaohua Li 			 * entry because swapoff will wait for discarding
1710edfe23daSShaohua Li 			 * finish anyway.
1711edfe23daSShaohua Li 			 */
1712edfe23daSShaohua Li 			if (!swcount || swcount == SWAP_MAP_BAD)
17131da177e4SLinus Torvalds 				continue;
17141da177e4SLinus Torvalds 			retval = -ENOMEM;
17151da177e4SLinus Torvalds 			break;
17161da177e4SLinus Torvalds 		}
17171da177e4SLinus Torvalds 
17181da177e4SLinus Torvalds 		/*
17191da177e4SLinus Torvalds 		 * Don't hold on to start_mm if it looks like exiting.
17201da177e4SLinus Torvalds 		 */
17211da177e4SLinus Torvalds 		if (atomic_read(&start_mm->mm_users) == 1) {
17221da177e4SLinus Torvalds 			mmput(start_mm);
17231da177e4SLinus Torvalds 			start_mm = &init_mm;
17243fce371bSVegard Nossum 			mmget(&init_mm);
17251da177e4SLinus Torvalds 		}
17261da177e4SLinus Torvalds 
17271da177e4SLinus Torvalds 		/*
17281da177e4SLinus Torvalds 		 * Wait for and lock page.  When do_swap_page races with
17291da177e4SLinus Torvalds 		 * try_to_unuse, do_swap_page can handle the fault much
17301da177e4SLinus Torvalds 		 * faster than try_to_unuse can locate the entry.  This
17311da177e4SLinus Torvalds 		 * apparently redundant "wait_on_page_locked" lets try_to_unuse
17321da177e4SLinus Torvalds 		 * defer to do_swap_page in such a case - in some tests,
17331da177e4SLinus Torvalds 		 * do_swap_page and try_to_unuse repeatedly compete.
17341da177e4SLinus Torvalds 		 */
17351da177e4SLinus Torvalds 		wait_on_page_locked(page);
17361da177e4SLinus Torvalds 		wait_on_page_writeback(page);
17371da177e4SLinus Torvalds 		lock_page(page);
17381da177e4SLinus Torvalds 		wait_on_page_writeback(page);
17391da177e4SLinus Torvalds 
17401da177e4SLinus Torvalds 		/*
17411da177e4SLinus Torvalds 		 * Remove all references to entry.
17421da177e4SLinus Torvalds 		 */
17431da177e4SLinus Torvalds 		swcount = *swap_map;
1744aaa46865SHugh Dickins 		if (swap_count(swcount) == SWAP_MAP_SHMEM) {
1745aaa46865SHugh Dickins 			retval = shmem_unuse(entry, page);
1746aaa46865SHugh Dickins 			/* page has already been unlocked and released */
1747aaa46865SHugh Dickins 			if (retval < 0)
1748aaa46865SHugh Dickins 				break;
1749aaa46865SHugh Dickins 			continue;
17501da177e4SLinus Torvalds 		}
1751aaa46865SHugh Dickins 		if (swap_count(swcount) && start_mm != &init_mm)
1752aaa46865SHugh Dickins 			retval = unuse_mm(start_mm, entry, page);
1753aaa46865SHugh Dickins 
1754355cfa73SKAMEZAWA Hiroyuki 		if (swap_count(*swap_map)) {
17551da177e4SLinus Torvalds 			int set_start_mm = (*swap_map >= swcount);
17561da177e4SLinus Torvalds 			struct list_head *p = &start_mm->mmlist;
17571da177e4SLinus Torvalds 			struct mm_struct *new_start_mm = start_mm;
17581da177e4SLinus Torvalds 			struct mm_struct *prev_mm = start_mm;
17591da177e4SLinus Torvalds 			struct mm_struct *mm;
17601da177e4SLinus Torvalds 
17613fce371bSVegard Nossum 			mmget(new_start_mm);
17623fce371bSVegard Nossum 			mmget(prev_mm);
17631da177e4SLinus Torvalds 			spin_lock(&mmlist_lock);
1764aaa46865SHugh Dickins 			while (swap_count(*swap_map) && !retval &&
17651da177e4SLinus Torvalds 					(p = p->next) != &start_mm->mmlist) {
17661da177e4SLinus Torvalds 				mm = list_entry(p, struct mm_struct, mmlist);
1767388f7934SVegard Nossum 				if (!mmget_not_zero(mm))
17681da177e4SLinus Torvalds 					continue;
17691da177e4SLinus Torvalds 				spin_unlock(&mmlist_lock);
17701da177e4SLinus Torvalds 				mmput(prev_mm);
17711da177e4SLinus Torvalds 				prev_mm = mm;
17721da177e4SLinus Torvalds 
17731da177e4SLinus Torvalds 				cond_resched();
17741da177e4SLinus Torvalds 
17751da177e4SLinus Torvalds 				swcount = *swap_map;
1776355cfa73SKAMEZAWA Hiroyuki 				if (!swap_count(swcount)) /* any usage ? */
17771da177e4SLinus Torvalds 					;
1778aaa46865SHugh Dickins 				else if (mm == &init_mm)
17791da177e4SLinus Torvalds 					set_start_mm = 1;
1780aaa46865SHugh Dickins 				else
17811da177e4SLinus Torvalds 					retval = unuse_mm(mm, entry, page);
1782355cfa73SKAMEZAWA Hiroyuki 
178332c5fc10SBo Liu 				if (set_start_mm && *swap_map < swcount) {
17841da177e4SLinus Torvalds 					mmput(new_start_mm);
17853fce371bSVegard Nossum 					mmget(mm);
17861da177e4SLinus Torvalds 					new_start_mm = mm;
17871da177e4SLinus Torvalds 					set_start_mm = 0;
17881da177e4SLinus Torvalds 				}
17891da177e4SLinus Torvalds 				spin_lock(&mmlist_lock);
17901da177e4SLinus Torvalds 			}
17911da177e4SLinus Torvalds 			spin_unlock(&mmlist_lock);
17921da177e4SLinus Torvalds 			mmput(prev_mm);
17931da177e4SLinus Torvalds 			mmput(start_mm);
17941da177e4SLinus Torvalds 			start_mm = new_start_mm;
17951da177e4SLinus Torvalds 		}
17961da177e4SLinus Torvalds 		if (retval) {
17971da177e4SLinus Torvalds 			unlock_page(page);
179809cbfeafSKirill A. Shutemov 			put_page(page);
17991da177e4SLinus Torvalds 			break;
18001da177e4SLinus Torvalds 		}
18011da177e4SLinus Torvalds 
18021da177e4SLinus Torvalds 		/*
18031da177e4SLinus Torvalds 		 * If a reference remains (rare), we would like to leave
18041da177e4SLinus Torvalds 		 * the page in the swap cache; but try_to_unmap could
18051da177e4SLinus Torvalds 		 * then re-duplicate the entry once we drop page lock,
18061da177e4SLinus Torvalds 		 * so we might loop indefinitely; also, that page could
18071da177e4SLinus Torvalds 		 * not be swapped out to other storage meanwhile.  So:
18081da177e4SLinus Torvalds 		 * delete from cache even if there's another reference,
18091da177e4SLinus Torvalds 		 * after ensuring that the data has been saved to disk -
18101da177e4SLinus Torvalds 		 * since if the reference remains (rarer), it will be
18111da177e4SLinus Torvalds 		 * read from disk into another page.  Splitting into two
18121da177e4SLinus Torvalds 		 * pages would be incorrect if swap supported "shared
18131da177e4SLinus Torvalds 		 * private" pages, but they are handled by tmpfs files.
18145ad64688SHugh Dickins 		 *
18155ad64688SHugh Dickins 		 * Given how unuse_vma() targets one particular offset
18165ad64688SHugh Dickins 		 * in an anon_vma, once the anon_vma has been determined,
18175ad64688SHugh Dickins 		 * this splitting happens to be just what is needed to
18185ad64688SHugh Dickins 		 * handle where KSM pages have been swapped out: re-reading
18195ad64688SHugh Dickins 		 * is unnecessarily slow, but we can fix that later on.
18201da177e4SLinus Torvalds 		 */
1821355cfa73SKAMEZAWA Hiroyuki 		if (swap_count(*swap_map) &&
1822355cfa73SKAMEZAWA Hiroyuki 		     PageDirty(page) && PageSwapCache(page)) {
18231da177e4SLinus Torvalds 			struct writeback_control wbc = {
18241da177e4SLinus Torvalds 				.sync_mode = WB_SYNC_NONE,
18251da177e4SLinus Torvalds 			};
18261da177e4SLinus Torvalds 
18271da177e4SLinus Torvalds 			swap_writepage(page, &wbc);
18281da177e4SLinus Torvalds 			lock_page(page);
18291da177e4SLinus Torvalds 			wait_on_page_writeback(page);
18301da177e4SLinus Torvalds 		}
183168bdc8d6SHugh Dickins 
183268bdc8d6SHugh Dickins 		/*
183368bdc8d6SHugh Dickins 		 * It is conceivable that a racing task removed this page from
183468bdc8d6SHugh Dickins 		 * swap cache just before we acquired the page lock at the top,
183568bdc8d6SHugh Dickins 		 * or while we dropped it in unuse_mm().  The page might even
183668bdc8d6SHugh Dickins 		 * be back in swap cache on another swap area: that we must not
183768bdc8d6SHugh Dickins 		 * delete, since it may not have been written out to swap yet.
183868bdc8d6SHugh Dickins 		 */
183968bdc8d6SHugh Dickins 		if (PageSwapCache(page) &&
184068bdc8d6SHugh Dickins 		    likely(page_private(page) == entry.val))
18411da177e4SLinus Torvalds 			delete_from_swap_cache(page);
18421da177e4SLinus Torvalds 
18431da177e4SLinus Torvalds 		/*
18441da177e4SLinus Torvalds 		 * So we could skip searching mms once swap count went
18451da177e4SLinus Torvalds 		 * to 1, we did not mark any present ptes as dirty: must
18462706a1b8SAnderson Briglia 		 * mark page dirty so shrink_page_list will preserve it.
18471da177e4SLinus Torvalds 		 */
18481da177e4SLinus Torvalds 		SetPageDirty(page);
18491da177e4SLinus Torvalds 		unlock_page(page);
185009cbfeafSKirill A. Shutemov 		put_page(page);
18511da177e4SLinus Torvalds 
18521da177e4SLinus Torvalds 		/*
18531da177e4SLinus Torvalds 		 * Make sure that we aren't completely killing
18541da177e4SLinus Torvalds 		 * interactive performance.
18551da177e4SLinus Torvalds 		 */
18561da177e4SLinus Torvalds 		cond_resched();
185738b5faf4SDan Magenheimer 		if (frontswap && pages_to_unuse > 0) {
185838b5faf4SDan Magenheimer 			if (!--pages_to_unuse)
185938b5faf4SDan Magenheimer 				break;
186038b5faf4SDan Magenheimer 		}
18611da177e4SLinus Torvalds 	}
18621da177e4SLinus Torvalds 
18631da177e4SLinus Torvalds 	mmput(start_mm);
18641da177e4SLinus Torvalds 	return retval;
18651da177e4SLinus Torvalds }
18661da177e4SLinus Torvalds 
18671da177e4SLinus Torvalds /*
18685d337b91SHugh Dickins  * After a successful try_to_unuse, if no swap is now in use, we know
18695d337b91SHugh Dickins  * we can empty the mmlist.  swap_lock must be held on entry and exit.
18705d337b91SHugh Dickins  * Note that mmlist_lock nests inside swap_lock, and an mm must be
18711da177e4SLinus Torvalds  * added to the mmlist just after page_duplicate - before would be racy.
18721da177e4SLinus Torvalds  */
18731da177e4SLinus Torvalds static void drain_mmlist(void)
18741da177e4SLinus Torvalds {
18751da177e4SLinus Torvalds 	struct list_head *p, *next;
1876efa90a98SHugh Dickins 	unsigned int type;
18771da177e4SLinus Torvalds 
1878efa90a98SHugh Dickins 	for (type = 0; type < nr_swapfiles; type++)
1879efa90a98SHugh Dickins 		if (swap_info[type]->inuse_pages)
18801da177e4SLinus Torvalds 			return;
18811da177e4SLinus Torvalds 	spin_lock(&mmlist_lock);
18821da177e4SLinus Torvalds 	list_for_each_safe(p, next, &init_mm.mmlist)
18831da177e4SLinus Torvalds 		list_del_init(p);
18841da177e4SLinus Torvalds 	spin_unlock(&mmlist_lock);
18851da177e4SLinus Torvalds }
18861da177e4SLinus Torvalds 
18871da177e4SLinus Torvalds /*
18881da177e4SLinus Torvalds  * Use this swapdev's extent info to locate the (PAGE_SIZE) block which
1889d4906e1aSLee Schermerhorn  * corresponds to page offset for the specified swap entry.
1890d4906e1aSLee Schermerhorn  * Note that the type of this function is sector_t, but it returns page offset
1891d4906e1aSLee Schermerhorn  * into the bdev, not sector offset.
18921da177e4SLinus Torvalds  */
1893d4906e1aSLee Schermerhorn static sector_t map_swap_entry(swp_entry_t entry, struct block_device **bdev)
18941da177e4SLinus Torvalds {
1895f29ad6a9SHugh Dickins 	struct swap_info_struct *sis;
1896f29ad6a9SHugh Dickins 	struct swap_extent *start_se;
1897f29ad6a9SHugh Dickins 	struct swap_extent *se;
1898f29ad6a9SHugh Dickins 	pgoff_t offset;
1899f29ad6a9SHugh Dickins 
1900efa90a98SHugh Dickins 	sis = swap_info[swp_type(entry)];
1901f29ad6a9SHugh Dickins 	*bdev = sis->bdev;
1902f29ad6a9SHugh Dickins 
1903f29ad6a9SHugh Dickins 	offset = swp_offset(entry);
1904f29ad6a9SHugh Dickins 	start_se = sis->curr_swap_extent;
1905f29ad6a9SHugh Dickins 	se = start_se;
19061da177e4SLinus Torvalds 
19071da177e4SLinus Torvalds 	for ( ; ; ) {
19081da177e4SLinus Torvalds 		if (se->start_page <= offset &&
19091da177e4SLinus Torvalds 				offset < (se->start_page + se->nr_pages)) {
19101da177e4SLinus Torvalds 			return se->start_block + (offset - se->start_page);
19111da177e4SLinus Torvalds 		}
1912a8ae4991SGeliang Tang 		se = list_next_entry(se, list);
19131da177e4SLinus Torvalds 		sis->curr_swap_extent = se;
19141da177e4SLinus Torvalds 		BUG_ON(se == start_se);		/* It *must* be present */
19151da177e4SLinus Torvalds 	}
19161da177e4SLinus Torvalds }
19171da177e4SLinus Torvalds 
19181da177e4SLinus Torvalds /*
1919d4906e1aSLee Schermerhorn  * Returns the page offset into bdev for the specified page's swap entry.
1920d4906e1aSLee Schermerhorn  */
1921d4906e1aSLee Schermerhorn sector_t map_swap_page(struct page *page, struct block_device **bdev)
1922d4906e1aSLee Schermerhorn {
1923d4906e1aSLee Schermerhorn 	swp_entry_t entry;
1924d4906e1aSLee Schermerhorn 	entry.val = page_private(page);
1925d4906e1aSLee Schermerhorn 	return map_swap_entry(entry, bdev);
1926d4906e1aSLee Schermerhorn }
1927d4906e1aSLee Schermerhorn 
1928d4906e1aSLee Schermerhorn /*
19291da177e4SLinus Torvalds  * Free all of a swapdev's extent information
19301da177e4SLinus Torvalds  */
19311da177e4SLinus Torvalds static void destroy_swap_extents(struct swap_info_struct *sis)
19321da177e4SLinus Torvalds {
19339625a5f2SHugh Dickins 	while (!list_empty(&sis->first_swap_extent.list)) {
19341da177e4SLinus Torvalds 		struct swap_extent *se;
19351da177e4SLinus Torvalds 
1936a8ae4991SGeliang Tang 		se = list_first_entry(&sis->first_swap_extent.list,
19371da177e4SLinus Torvalds 				struct swap_extent, list);
19381da177e4SLinus Torvalds 		list_del(&se->list);
19391da177e4SLinus Torvalds 		kfree(se);
19401da177e4SLinus Torvalds 	}
194162c230bcSMel Gorman 
194262c230bcSMel Gorman 	if (sis->flags & SWP_FILE) {
194362c230bcSMel Gorman 		struct file *swap_file = sis->swap_file;
194462c230bcSMel Gorman 		struct address_space *mapping = swap_file->f_mapping;
194562c230bcSMel Gorman 
194662c230bcSMel Gorman 		sis->flags &= ~SWP_FILE;
194762c230bcSMel Gorman 		mapping->a_ops->swap_deactivate(swap_file);
194862c230bcSMel Gorman 	}
19491da177e4SLinus Torvalds }
19501da177e4SLinus Torvalds 
19511da177e4SLinus Torvalds /*
19521da177e4SLinus Torvalds  * Add a block range (and the corresponding page range) into this swapdev's
195311d31886SHugh Dickins  * extent list.  The extent list is kept sorted in page order.
19541da177e4SLinus Torvalds  *
195511d31886SHugh Dickins  * This function rather assumes that it is called in ascending page order.
19561da177e4SLinus Torvalds  */
1957a509bc1aSMel Gorman int
19581da177e4SLinus Torvalds add_swap_extent(struct swap_info_struct *sis, unsigned long start_page,
19591da177e4SLinus Torvalds 		unsigned long nr_pages, sector_t start_block)
19601da177e4SLinus Torvalds {
19611da177e4SLinus Torvalds 	struct swap_extent *se;
19621da177e4SLinus Torvalds 	struct swap_extent *new_se;
19631da177e4SLinus Torvalds 	struct list_head *lh;
19641da177e4SLinus Torvalds 
19659625a5f2SHugh Dickins 	if (start_page == 0) {
19669625a5f2SHugh Dickins 		se = &sis->first_swap_extent;
19679625a5f2SHugh Dickins 		sis->curr_swap_extent = se;
19689625a5f2SHugh Dickins 		se->start_page = 0;
19699625a5f2SHugh Dickins 		se->nr_pages = nr_pages;
19709625a5f2SHugh Dickins 		se->start_block = start_block;
19719625a5f2SHugh Dickins 		return 1;
19729625a5f2SHugh Dickins 	} else {
19739625a5f2SHugh Dickins 		lh = sis->first_swap_extent.list.prev;	/* Highest extent */
19741da177e4SLinus Torvalds 		se = list_entry(lh, struct swap_extent, list);
197511d31886SHugh Dickins 		BUG_ON(se->start_page + se->nr_pages != start_page);
197611d31886SHugh Dickins 		if (se->start_block + se->nr_pages == start_block) {
19771da177e4SLinus Torvalds 			/* Merge it */
19781da177e4SLinus Torvalds 			se->nr_pages += nr_pages;
19791da177e4SLinus Torvalds 			return 0;
19801da177e4SLinus Torvalds 		}
19811da177e4SLinus Torvalds 	}
19821da177e4SLinus Torvalds 
19831da177e4SLinus Torvalds 	/*
19841da177e4SLinus Torvalds 	 * No merge.  Insert a new extent, preserving ordering.
19851da177e4SLinus Torvalds 	 */
19861da177e4SLinus Torvalds 	new_se = kmalloc(sizeof(*se), GFP_KERNEL);
19871da177e4SLinus Torvalds 	if (new_se == NULL)
19881da177e4SLinus Torvalds 		return -ENOMEM;
19891da177e4SLinus Torvalds 	new_se->start_page = start_page;
19901da177e4SLinus Torvalds 	new_se->nr_pages = nr_pages;
19911da177e4SLinus Torvalds 	new_se->start_block = start_block;
19921da177e4SLinus Torvalds 
19939625a5f2SHugh Dickins 	list_add_tail(&new_se->list, &sis->first_swap_extent.list);
199453092a74SHugh Dickins 	return 1;
19951da177e4SLinus Torvalds }
19961da177e4SLinus Torvalds 
19971da177e4SLinus Torvalds /*
19981da177e4SLinus Torvalds  * A `swap extent' is a simple thing which maps a contiguous range of pages
19991da177e4SLinus Torvalds  * onto a contiguous range of disk blocks.  An ordered list of swap extents
20001da177e4SLinus Torvalds  * is built at swapon time and is then used at swap_writepage/swap_readpage
20011da177e4SLinus Torvalds  * time for locating where on disk a page belongs.
20021da177e4SLinus Torvalds  *
20031da177e4SLinus Torvalds  * If the swapfile is an S_ISBLK block device, a single extent is installed.
20041da177e4SLinus Torvalds  * This is done so that the main operating code can treat S_ISBLK and S_ISREG
20051da177e4SLinus Torvalds  * swap files identically.
20061da177e4SLinus Torvalds  *
20071da177e4SLinus Torvalds  * Whether the swapdev is an S_ISREG file or an S_ISBLK blockdev, the swap
20081da177e4SLinus Torvalds  * extent list operates in PAGE_SIZE disk blocks.  Both S_ISREG and S_ISBLK
20091da177e4SLinus Torvalds  * swapfiles are handled *identically* after swapon time.
20101da177e4SLinus Torvalds  *
20111da177e4SLinus Torvalds  * For S_ISREG swapfiles, setup_swap_extents() will walk all the file's blocks
20121da177e4SLinus Torvalds  * and will parse them into an ordered extent list, in PAGE_SIZE chunks.  If
20131da177e4SLinus Torvalds  * some stray blocks are found which do not fall within the PAGE_SIZE alignment
20141da177e4SLinus Torvalds  * requirements, they are simply tossed out - we will never use those blocks
20151da177e4SLinus Torvalds  * for swapping.
20161da177e4SLinus Torvalds  *
2017b0d9bcd4SHugh Dickins  * For S_ISREG swapfiles we set S_SWAPFILE across the life of the swapon.  This
20181da177e4SLinus Torvalds  * prevents root from shooting her foot off by ftruncating an in-use swapfile,
20191da177e4SLinus Torvalds  * which will scribble on the fs.
20201da177e4SLinus Torvalds  *
20211da177e4SLinus Torvalds  * The amount of disk space which a single swap extent represents varies.
20221da177e4SLinus Torvalds  * Typically it is in the 1-4 megabyte range.  So we can have hundreds of
20231da177e4SLinus Torvalds  * extents in the list.  To avoid much list walking, we cache the previous
20241da177e4SLinus Torvalds  * search location in `curr_swap_extent', and start new searches from there.
20251da177e4SLinus Torvalds  * This is extremely effective.  The average number of iterations in
20261da177e4SLinus Torvalds  * map_swap_page() has been measured at about 0.3 per page.  - akpm.
20271da177e4SLinus Torvalds  */
202853092a74SHugh Dickins static int setup_swap_extents(struct swap_info_struct *sis, sector_t *span)
20291da177e4SLinus Torvalds {
203062c230bcSMel Gorman 	struct file *swap_file = sis->swap_file;
203162c230bcSMel Gorman 	struct address_space *mapping = swap_file->f_mapping;
203262c230bcSMel Gorman 	struct inode *inode = mapping->host;
20331da177e4SLinus Torvalds 	int ret;
20341da177e4SLinus Torvalds 
20351da177e4SLinus Torvalds 	if (S_ISBLK(inode->i_mode)) {
20361da177e4SLinus Torvalds 		ret = add_swap_extent(sis, 0, sis->max, 0);
203753092a74SHugh Dickins 		*span = sis->pages;
2038a509bc1aSMel Gorman 		return ret;
20391da177e4SLinus Torvalds 	}
20401da177e4SLinus Torvalds 
204162c230bcSMel Gorman 	if (mapping->a_ops->swap_activate) {
2042a509bc1aSMel Gorman 		ret = mapping->a_ops->swap_activate(sis, swap_file, span);
204362c230bcSMel Gorman 		if (!ret) {
204462c230bcSMel Gorman 			sis->flags |= SWP_FILE;
204562c230bcSMel Gorman 			ret = add_swap_extent(sis, 0, sis->max, 0);
204662c230bcSMel Gorman 			*span = sis->pages;
204762c230bcSMel Gorman 		}
20489625a5f2SHugh Dickins 		return ret;
2049a509bc1aSMel Gorman 	}
2050a509bc1aSMel Gorman 
2051a509bc1aSMel Gorman 	return generic_swapfile_activate(sis, swap_file, span);
20521da177e4SLinus Torvalds }
20531da177e4SLinus Torvalds 
2054cf0cac0aSCesar Eduardo Barros static void _enable_swap_info(struct swap_info_struct *p, int prio,
20552a8f9449SShaohua Li 				unsigned char *swap_map,
20562a8f9449SShaohua Li 				struct swap_cluster_info *cluster_info)
205740531542SCesar Eduardo Barros {
205840531542SCesar Eduardo Barros 	if (prio >= 0)
205940531542SCesar Eduardo Barros 		p->prio = prio;
206040531542SCesar Eduardo Barros 	else
206140531542SCesar Eduardo Barros 		p->prio = --least_priority;
206218ab4d4cSDan Streetman 	/*
206318ab4d4cSDan Streetman 	 * the plist prio is negated because plist ordering is
206418ab4d4cSDan Streetman 	 * low-to-high, while swap ordering is high-to-low
206518ab4d4cSDan Streetman 	 */
206618ab4d4cSDan Streetman 	p->list.prio = -p->prio;
206718ab4d4cSDan Streetman 	p->avail_list.prio = -p->prio;
206840531542SCesar Eduardo Barros 	p->swap_map = swap_map;
20692a8f9449SShaohua Li 	p->cluster_info = cluster_info;
207040531542SCesar Eduardo Barros 	p->flags |= SWP_WRITEOK;
2071ec8acf20SShaohua Li 	atomic_long_add(p->pages, &nr_swap_pages);
207240531542SCesar Eduardo Barros 	total_swap_pages += p->pages;
207340531542SCesar Eduardo Barros 
2074adfab836SDan Streetman 	assert_spin_locked(&swap_lock);
2075adfab836SDan Streetman 	/*
207618ab4d4cSDan Streetman 	 * both lists are plists, and thus priority ordered.
207718ab4d4cSDan Streetman 	 * swap_active_head needs to be priority ordered for swapoff(),
207818ab4d4cSDan Streetman 	 * which on removal of any swap_info_struct with an auto-assigned
207918ab4d4cSDan Streetman 	 * (i.e. negative) priority increments the auto-assigned priority
208018ab4d4cSDan Streetman 	 * of any lower-priority swap_info_structs.
208118ab4d4cSDan Streetman 	 * swap_avail_head needs to be priority ordered for get_swap_page(),
208218ab4d4cSDan Streetman 	 * which allocates swap pages from the highest available priority
208318ab4d4cSDan Streetman 	 * swap_info_struct.
2084adfab836SDan Streetman 	 */
208518ab4d4cSDan Streetman 	plist_add(&p->list, &swap_active_head);
208618ab4d4cSDan Streetman 	spin_lock(&swap_avail_lock);
208718ab4d4cSDan Streetman 	plist_add(&p->avail_list, &swap_avail_head);
208818ab4d4cSDan Streetman 	spin_unlock(&swap_avail_lock);
2089cf0cac0aSCesar Eduardo Barros }
2090cf0cac0aSCesar Eduardo Barros 
2091cf0cac0aSCesar Eduardo Barros static void enable_swap_info(struct swap_info_struct *p, int prio,
2092cf0cac0aSCesar Eduardo Barros 				unsigned char *swap_map,
20932a8f9449SShaohua Li 				struct swap_cluster_info *cluster_info,
2094cf0cac0aSCesar Eduardo Barros 				unsigned long *frontswap_map)
2095cf0cac0aSCesar Eduardo Barros {
20964f89849dSMinchan Kim 	frontswap_init(p->type, frontswap_map);
2097cf0cac0aSCesar Eduardo Barros 	spin_lock(&swap_lock);
2098ec8acf20SShaohua Li 	spin_lock(&p->lock);
20992a8f9449SShaohua Li 	 _enable_swap_info(p, prio, swap_map, cluster_info);
2100ec8acf20SShaohua Li 	spin_unlock(&p->lock);
2101cf0cac0aSCesar Eduardo Barros 	spin_unlock(&swap_lock);
2102cf0cac0aSCesar Eduardo Barros }
2103cf0cac0aSCesar Eduardo Barros 
2104cf0cac0aSCesar Eduardo Barros static void reinsert_swap_info(struct swap_info_struct *p)
2105cf0cac0aSCesar Eduardo Barros {
2106cf0cac0aSCesar Eduardo Barros 	spin_lock(&swap_lock);
2107ec8acf20SShaohua Li 	spin_lock(&p->lock);
21082a8f9449SShaohua Li 	_enable_swap_info(p, p->prio, p->swap_map, p->cluster_info);
2109ec8acf20SShaohua Li 	spin_unlock(&p->lock);
211040531542SCesar Eduardo Barros 	spin_unlock(&swap_lock);
211140531542SCesar Eduardo Barros }
211240531542SCesar Eduardo Barros 
211367afa38eSTim Chen bool has_usable_swap(void)
211467afa38eSTim Chen {
211567afa38eSTim Chen 	bool ret = true;
211667afa38eSTim Chen 
211767afa38eSTim Chen 	spin_lock(&swap_lock);
211867afa38eSTim Chen 	if (plist_head_empty(&swap_active_head))
211967afa38eSTim Chen 		ret = false;
212067afa38eSTim Chen 	spin_unlock(&swap_lock);
212167afa38eSTim Chen 	return ret;
212267afa38eSTim Chen }
212367afa38eSTim Chen 
2124c4ea37c2SHeiko Carstens SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
21251da177e4SLinus Torvalds {
21261da177e4SLinus Torvalds 	struct swap_info_struct *p = NULL;
21278d69aaeeSHugh Dickins 	unsigned char *swap_map;
21282a8f9449SShaohua Li 	struct swap_cluster_info *cluster_info;
21294f89849dSMinchan Kim 	unsigned long *frontswap_map;
21301da177e4SLinus Torvalds 	struct file *swap_file, *victim;
21311da177e4SLinus Torvalds 	struct address_space *mapping;
21321da177e4SLinus Torvalds 	struct inode *inode;
213391a27b2aSJeff Layton 	struct filename *pathname;
2134adfab836SDan Streetman 	int err, found = 0;
21355b808a23SKrzysztof Kozlowski 	unsigned int old_block_size;
21361da177e4SLinus Torvalds 
21371da177e4SLinus Torvalds 	if (!capable(CAP_SYS_ADMIN))
21381da177e4SLinus Torvalds 		return -EPERM;
21391da177e4SLinus Torvalds 
2140191c5424SAl Viro 	BUG_ON(!current->mm);
2141191c5424SAl Viro 
21421da177e4SLinus Torvalds 	pathname = getname(specialfile);
21431da177e4SLinus Torvalds 	if (IS_ERR(pathname))
2144f58b59c1SXiaotian Feng 		return PTR_ERR(pathname);
21451da177e4SLinus Torvalds 
2146669abf4eSJeff Layton 	victim = file_open_name(pathname, O_RDWR|O_LARGEFILE, 0);
21471da177e4SLinus Torvalds 	err = PTR_ERR(victim);
21481da177e4SLinus Torvalds 	if (IS_ERR(victim))
21491da177e4SLinus Torvalds 		goto out;
21501da177e4SLinus Torvalds 
21511da177e4SLinus Torvalds 	mapping = victim->f_mapping;
21525d337b91SHugh Dickins 	spin_lock(&swap_lock);
215318ab4d4cSDan Streetman 	plist_for_each_entry(p, &swap_active_head, list) {
215422c6f8fdSHugh Dickins 		if (p->flags & SWP_WRITEOK) {
2155adfab836SDan Streetman 			if (p->swap_file->f_mapping == mapping) {
2156adfab836SDan Streetman 				found = 1;
21571da177e4SLinus Torvalds 				break;
21581da177e4SLinus Torvalds 			}
21591da177e4SLinus Torvalds 		}
2160adfab836SDan Streetman 	}
2161adfab836SDan Streetman 	if (!found) {
21621da177e4SLinus Torvalds 		err = -EINVAL;
21635d337b91SHugh Dickins 		spin_unlock(&swap_lock);
21641da177e4SLinus Torvalds 		goto out_dput;
21651da177e4SLinus Torvalds 	}
2166191c5424SAl Viro 	if (!security_vm_enough_memory_mm(current->mm, p->pages))
21671da177e4SLinus Torvalds 		vm_unacct_memory(p->pages);
21681da177e4SLinus Torvalds 	else {
21691da177e4SLinus Torvalds 		err = -ENOMEM;
21705d337b91SHugh Dickins 		spin_unlock(&swap_lock);
21711da177e4SLinus Torvalds 		goto out_dput;
21721da177e4SLinus Torvalds 	}
217318ab4d4cSDan Streetman 	spin_lock(&swap_avail_lock);
217418ab4d4cSDan Streetman 	plist_del(&p->avail_list, &swap_avail_head);
217518ab4d4cSDan Streetman 	spin_unlock(&swap_avail_lock);
2176ec8acf20SShaohua Li 	spin_lock(&p->lock);
217778ecba08SHugh Dickins 	if (p->prio < 0) {
2178adfab836SDan Streetman 		struct swap_info_struct *si = p;
2179adfab836SDan Streetman 
218018ab4d4cSDan Streetman 		plist_for_each_entry_continue(si, &swap_active_head, list) {
2181adfab836SDan Streetman 			si->prio++;
218218ab4d4cSDan Streetman 			si->list.prio--;
218318ab4d4cSDan Streetman 			si->avail_list.prio--;
2184adfab836SDan Streetman 		}
218578ecba08SHugh Dickins 		least_priority++;
218678ecba08SHugh Dickins 	}
218718ab4d4cSDan Streetman 	plist_del(&p->list, &swap_active_head);
2188ec8acf20SShaohua Li 	atomic_long_sub(p->pages, &nr_swap_pages);
21891da177e4SLinus Torvalds 	total_swap_pages -= p->pages;
21901da177e4SLinus Torvalds 	p->flags &= ~SWP_WRITEOK;
2191ec8acf20SShaohua Li 	spin_unlock(&p->lock);
21925d337b91SHugh Dickins 	spin_unlock(&swap_lock);
2193fb4f88dcSHugh Dickins 
2194039939a6STim Chen 	disable_swap_slots_cache_lock();
2195039939a6STim Chen 
2196e1e12d2fSDavid Rientjes 	set_current_oom_origin();
2197adfab836SDan Streetman 	err = try_to_unuse(p->type, false, 0); /* force unuse all pages */
2198e1e12d2fSDavid Rientjes 	clear_current_oom_origin();
21991da177e4SLinus Torvalds 
22001da177e4SLinus Torvalds 	if (err) {
22011da177e4SLinus Torvalds 		/* re-insert swap space back into swap_list */
2202cf0cac0aSCesar Eduardo Barros 		reinsert_swap_info(p);
2203039939a6STim Chen 		reenable_swap_slots_cache_unlock();
22041da177e4SLinus Torvalds 		goto out_dput;
22051da177e4SLinus Torvalds 	}
220652b7efdbSHugh Dickins 
2207039939a6STim Chen 	reenable_swap_slots_cache_unlock();
2208039939a6STim Chen 
2209815c2c54SShaohua Li 	flush_work(&p->discard_work);
2210815c2c54SShaohua Li 
22114cd3bb10SHugh Dickins 	destroy_swap_extents(p);
2212570a335bSHugh Dickins 	if (p->flags & SWP_CONTINUED)
2213570a335bSHugh Dickins 		free_swap_count_continuations(p);
2214570a335bSHugh Dickins 
2215fc0abb14SIngo Molnar 	mutex_lock(&swapon_mutex);
22165d337b91SHugh Dickins 	spin_lock(&swap_lock);
2217ec8acf20SShaohua Li 	spin_lock(&p->lock);
22181da177e4SLinus Torvalds 	drain_mmlist();
22195d337b91SHugh Dickins 
22205d337b91SHugh Dickins 	/* wait for anyone still in scan_swap_map */
22215d337b91SHugh Dickins 	p->highest_bit = 0;		/* cuts scans short */
22225d337b91SHugh Dickins 	while (p->flags >= SWP_SCANNING) {
2223ec8acf20SShaohua Li 		spin_unlock(&p->lock);
22245d337b91SHugh Dickins 		spin_unlock(&swap_lock);
222513e4b57fSNishanth Aravamudan 		schedule_timeout_uninterruptible(1);
22265d337b91SHugh Dickins 		spin_lock(&swap_lock);
2227ec8acf20SShaohua Li 		spin_lock(&p->lock);
22285d337b91SHugh Dickins 	}
22295d337b91SHugh Dickins 
22301da177e4SLinus Torvalds 	swap_file = p->swap_file;
22315b808a23SKrzysztof Kozlowski 	old_block_size = p->old_block_size;
22321da177e4SLinus Torvalds 	p->swap_file = NULL;
22331da177e4SLinus Torvalds 	p->max = 0;
22341da177e4SLinus Torvalds 	swap_map = p->swap_map;
22351da177e4SLinus Torvalds 	p->swap_map = NULL;
22362a8f9449SShaohua Li 	cluster_info = p->cluster_info;
22372a8f9449SShaohua Li 	p->cluster_info = NULL;
22384f89849dSMinchan Kim 	frontswap_map = frontswap_map_get(p);
2239ec8acf20SShaohua Li 	spin_unlock(&p->lock);
22405d337b91SHugh Dickins 	spin_unlock(&swap_lock);
2241adfab836SDan Streetman 	frontswap_invalidate_area(p->type);
224258e97ba6SKrzysztof Kozlowski 	frontswap_map_set(p, NULL);
2243fc0abb14SIngo Molnar 	mutex_unlock(&swapon_mutex);
2244ebc2a1a6SShaohua Li 	free_percpu(p->percpu_cluster);
2245ebc2a1a6SShaohua Li 	p->percpu_cluster = NULL;
22461da177e4SLinus Torvalds 	vfree(swap_map);
22472a8f9449SShaohua Li 	vfree(cluster_info);
22484f89849dSMinchan Kim 	vfree(frontswap_map);
22492de1a7e4SSeth Jennings 	/* Destroy swap account information */
2250adfab836SDan Streetman 	swap_cgroup_swapoff(p->type);
22514b3ef9daSHuang, Ying 	exit_swap_address_space(p->type);
225227a7faa0SKAMEZAWA Hiroyuki 
22531da177e4SLinus Torvalds 	inode = mapping->host;
22541da177e4SLinus Torvalds 	if (S_ISBLK(inode->i_mode)) {
22551da177e4SLinus Torvalds 		struct block_device *bdev = I_BDEV(inode);
22565b808a23SKrzysztof Kozlowski 		set_blocksize(bdev, old_block_size);
2257e525fd89STejun Heo 		blkdev_put(bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL);
22581da177e4SLinus Torvalds 	} else {
22595955102cSAl Viro 		inode_lock(inode);
22601da177e4SLinus Torvalds 		inode->i_flags &= ~S_SWAPFILE;
22615955102cSAl Viro 		inode_unlock(inode);
22621da177e4SLinus Torvalds 	}
22631da177e4SLinus Torvalds 	filp_close(swap_file, NULL);
2264f893ab41SWeijie Yang 
2265f893ab41SWeijie Yang 	/*
2266f893ab41SWeijie Yang 	 * Clear the SWP_USED flag after all resources are freed so that swapon
2267f893ab41SWeijie Yang 	 * can reuse this swap_info in alloc_swap_info() safely.  It is ok to
2268f893ab41SWeijie Yang 	 * not hold p->lock after we cleared its SWP_WRITEOK.
2269f893ab41SWeijie Yang 	 */
2270f893ab41SWeijie Yang 	spin_lock(&swap_lock);
2271f893ab41SWeijie Yang 	p->flags = 0;
2272f893ab41SWeijie Yang 	spin_unlock(&swap_lock);
2273f893ab41SWeijie Yang 
22741da177e4SLinus Torvalds 	err = 0;
227566d7dd51SKay Sievers 	atomic_inc(&proc_poll_event);
227666d7dd51SKay Sievers 	wake_up_interruptible(&proc_poll_wait);
22771da177e4SLinus Torvalds 
22781da177e4SLinus Torvalds out_dput:
22791da177e4SLinus Torvalds 	filp_close(victim, NULL);
22801da177e4SLinus Torvalds out:
2281f58b59c1SXiaotian Feng 	putname(pathname);
22821da177e4SLinus Torvalds 	return err;
22831da177e4SLinus Torvalds }
22841da177e4SLinus Torvalds 
22851da177e4SLinus Torvalds #ifdef CONFIG_PROC_FS
228666d7dd51SKay Sievers static unsigned swaps_poll(struct file *file, poll_table *wait)
228766d7dd51SKay Sievers {
2288f1514638SKay Sievers 	struct seq_file *seq = file->private_data;
228966d7dd51SKay Sievers 
229066d7dd51SKay Sievers 	poll_wait(file, &proc_poll_wait, wait);
229166d7dd51SKay Sievers 
2292f1514638SKay Sievers 	if (seq->poll_event != atomic_read(&proc_poll_event)) {
2293f1514638SKay Sievers 		seq->poll_event = atomic_read(&proc_poll_event);
229466d7dd51SKay Sievers 		return POLLIN | POLLRDNORM | POLLERR | POLLPRI;
229566d7dd51SKay Sievers 	}
229666d7dd51SKay Sievers 
229766d7dd51SKay Sievers 	return POLLIN | POLLRDNORM;
229866d7dd51SKay Sievers }
229966d7dd51SKay Sievers 
23001da177e4SLinus Torvalds /* iterator */
23011da177e4SLinus Torvalds static void *swap_start(struct seq_file *swap, loff_t *pos)
23021da177e4SLinus Torvalds {
2303efa90a98SHugh Dickins 	struct swap_info_struct *si;
2304efa90a98SHugh Dickins 	int type;
23051da177e4SLinus Torvalds 	loff_t l = *pos;
23061da177e4SLinus Torvalds 
2307fc0abb14SIngo Molnar 	mutex_lock(&swapon_mutex);
23081da177e4SLinus Torvalds 
2309881e4aabSSuleiman Souhlal 	if (!l)
2310881e4aabSSuleiman Souhlal 		return SEQ_START_TOKEN;
2311881e4aabSSuleiman Souhlal 
2312efa90a98SHugh Dickins 	for (type = 0; type < nr_swapfiles; type++) {
2313efa90a98SHugh Dickins 		smp_rmb();	/* read nr_swapfiles before swap_info[type] */
2314efa90a98SHugh Dickins 		si = swap_info[type];
2315efa90a98SHugh Dickins 		if (!(si->flags & SWP_USED) || !si->swap_map)
23161da177e4SLinus Torvalds 			continue;
2317881e4aabSSuleiman Souhlal 		if (!--l)
2318efa90a98SHugh Dickins 			return si;
23191da177e4SLinus Torvalds 	}
23201da177e4SLinus Torvalds 
23211da177e4SLinus Torvalds 	return NULL;
23221da177e4SLinus Torvalds }
23231da177e4SLinus Torvalds 
23241da177e4SLinus Torvalds static void *swap_next(struct seq_file *swap, void *v, loff_t *pos)
23251da177e4SLinus Torvalds {
2326efa90a98SHugh Dickins 	struct swap_info_struct *si = v;
2327efa90a98SHugh Dickins 	int type;
23281da177e4SLinus Torvalds 
2329881e4aabSSuleiman Souhlal 	if (v == SEQ_START_TOKEN)
2330efa90a98SHugh Dickins 		type = 0;
2331efa90a98SHugh Dickins 	else
2332efa90a98SHugh Dickins 		type = si->type + 1;
2333881e4aabSSuleiman Souhlal 
2334efa90a98SHugh Dickins 	for (; type < nr_swapfiles; type++) {
2335efa90a98SHugh Dickins 		smp_rmb();	/* read nr_swapfiles before swap_info[type] */
2336efa90a98SHugh Dickins 		si = swap_info[type];
2337efa90a98SHugh Dickins 		if (!(si->flags & SWP_USED) || !si->swap_map)
23381da177e4SLinus Torvalds 			continue;
23391da177e4SLinus Torvalds 		++*pos;
2340efa90a98SHugh Dickins 		return si;
23411da177e4SLinus Torvalds 	}
23421da177e4SLinus Torvalds 
23431da177e4SLinus Torvalds 	return NULL;
23441da177e4SLinus Torvalds }
23451da177e4SLinus Torvalds 
23461da177e4SLinus Torvalds static void swap_stop(struct seq_file *swap, void *v)
23471da177e4SLinus Torvalds {
2348fc0abb14SIngo Molnar 	mutex_unlock(&swapon_mutex);
23491da177e4SLinus Torvalds }
23501da177e4SLinus Torvalds 
23511da177e4SLinus Torvalds static int swap_show(struct seq_file *swap, void *v)
23521da177e4SLinus Torvalds {
2353efa90a98SHugh Dickins 	struct swap_info_struct *si = v;
23541da177e4SLinus Torvalds 	struct file *file;
23551da177e4SLinus Torvalds 	int len;
23561da177e4SLinus Torvalds 
2357efa90a98SHugh Dickins 	if (si == SEQ_START_TOKEN) {
23581da177e4SLinus Torvalds 		seq_puts(swap,"Filename\t\t\t\tType\t\tSize\tUsed\tPriority\n");
2359881e4aabSSuleiman Souhlal 		return 0;
2360881e4aabSSuleiman Souhlal 	}
23611da177e4SLinus Torvalds 
2362efa90a98SHugh Dickins 	file = si->swap_file;
23632726d566SMiklos Szeredi 	len = seq_file_path(swap, file, " \t\n\\");
23646eb396dcSHugh Dickins 	seq_printf(swap, "%*s%s\t%u\t%u\t%d\n",
23651da177e4SLinus Torvalds 			len < 40 ? 40 - len : 1, " ",
2366496ad9aaSAl Viro 			S_ISBLK(file_inode(file)->i_mode) ?
23671da177e4SLinus Torvalds 				"partition" : "file\t",
2368efa90a98SHugh Dickins 			si->pages << (PAGE_SHIFT - 10),
2369efa90a98SHugh Dickins 			si->inuse_pages << (PAGE_SHIFT - 10),
2370efa90a98SHugh Dickins 			si->prio);
23711da177e4SLinus Torvalds 	return 0;
23721da177e4SLinus Torvalds }
23731da177e4SLinus Torvalds 
237415ad7cdcSHelge Deller static const struct seq_operations swaps_op = {
23751da177e4SLinus Torvalds 	.start =	swap_start,
23761da177e4SLinus Torvalds 	.next =		swap_next,
23771da177e4SLinus Torvalds 	.stop =		swap_stop,
23781da177e4SLinus Torvalds 	.show =		swap_show
23791da177e4SLinus Torvalds };
23801da177e4SLinus Torvalds 
23811da177e4SLinus Torvalds static int swaps_open(struct inode *inode, struct file *file)
23821da177e4SLinus Torvalds {
2383f1514638SKay Sievers 	struct seq_file *seq;
238466d7dd51SKay Sievers 	int ret;
238566d7dd51SKay Sievers 
238666d7dd51SKay Sievers 	ret = seq_open(file, &swaps_op);
2387f1514638SKay Sievers 	if (ret)
238866d7dd51SKay Sievers 		return ret;
238966d7dd51SKay Sievers 
2390f1514638SKay Sievers 	seq = file->private_data;
2391f1514638SKay Sievers 	seq->poll_event = atomic_read(&proc_poll_event);
2392f1514638SKay Sievers 	return 0;
23931da177e4SLinus Torvalds }
23941da177e4SLinus Torvalds 
239515ad7cdcSHelge Deller static const struct file_operations proc_swaps_operations = {
23961da177e4SLinus Torvalds 	.open		= swaps_open,
23971da177e4SLinus Torvalds 	.read		= seq_read,
23981da177e4SLinus Torvalds 	.llseek		= seq_lseek,
23991da177e4SLinus Torvalds 	.release	= seq_release,
240066d7dd51SKay Sievers 	.poll		= swaps_poll,
24011da177e4SLinus Torvalds };
24021da177e4SLinus Torvalds 
24031da177e4SLinus Torvalds static int __init procswaps_init(void)
24041da177e4SLinus Torvalds {
24053d71f86fSDenis V. Lunev 	proc_create("swaps", 0, NULL, &proc_swaps_operations);
24061da177e4SLinus Torvalds 	return 0;
24071da177e4SLinus Torvalds }
24081da177e4SLinus Torvalds __initcall(procswaps_init);
24091da177e4SLinus Torvalds #endif /* CONFIG_PROC_FS */
24101da177e4SLinus Torvalds 
24111796316aSJan Beulich #ifdef MAX_SWAPFILES_CHECK
24121796316aSJan Beulich static int __init max_swapfiles_check(void)
24131796316aSJan Beulich {
24141796316aSJan Beulich 	MAX_SWAPFILES_CHECK();
24151796316aSJan Beulich 	return 0;
24161796316aSJan Beulich }
24171796316aSJan Beulich late_initcall(max_swapfiles_check);
24181796316aSJan Beulich #endif
24191796316aSJan Beulich 
242053cbb243SCesar Eduardo Barros static struct swap_info_struct *alloc_swap_info(void)
24211da177e4SLinus Torvalds {
24221da177e4SLinus Torvalds 	struct swap_info_struct *p;
24231da177e4SLinus Torvalds 	unsigned int type;
2424efa90a98SHugh Dickins 
2425efa90a98SHugh Dickins 	p = kzalloc(sizeof(*p), GFP_KERNEL);
2426efa90a98SHugh Dickins 	if (!p)
242753cbb243SCesar Eduardo Barros 		return ERR_PTR(-ENOMEM);
2428efa90a98SHugh Dickins 
24295d337b91SHugh Dickins 	spin_lock(&swap_lock);
2430efa90a98SHugh Dickins 	for (type = 0; type < nr_swapfiles; type++) {
2431efa90a98SHugh Dickins 		if (!(swap_info[type]->flags & SWP_USED))
24321da177e4SLinus Torvalds 			break;
2433efa90a98SHugh Dickins 	}
24340697212aSChristoph Lameter 	if (type >= MAX_SWAPFILES) {
24355d337b91SHugh Dickins 		spin_unlock(&swap_lock);
2436efa90a98SHugh Dickins 		kfree(p);
2437730c0581SCesar Eduardo Barros 		return ERR_PTR(-EPERM);
24381da177e4SLinus Torvalds 	}
2439efa90a98SHugh Dickins 	if (type >= nr_swapfiles) {
2440efa90a98SHugh Dickins 		p->type = type;
2441efa90a98SHugh Dickins 		swap_info[type] = p;
2442efa90a98SHugh Dickins 		/*
2443efa90a98SHugh Dickins 		 * Write swap_info[type] before nr_swapfiles, in case a
2444efa90a98SHugh Dickins 		 * racing procfs swap_start() or swap_next() is reading them.
2445efa90a98SHugh Dickins 		 * (We never shrink nr_swapfiles, we never free this entry.)
2446efa90a98SHugh Dickins 		 */
2447efa90a98SHugh Dickins 		smp_wmb();
2448efa90a98SHugh Dickins 		nr_swapfiles++;
2449efa90a98SHugh Dickins 	} else {
2450efa90a98SHugh Dickins 		kfree(p);
2451efa90a98SHugh Dickins 		p = swap_info[type];
2452efa90a98SHugh Dickins 		/*
2453efa90a98SHugh Dickins 		 * Do not memset this entry: a racing procfs swap_next()
2454efa90a98SHugh Dickins 		 * would be relying on p->type to remain valid.
2455efa90a98SHugh Dickins 		 */
2456efa90a98SHugh Dickins 	}
24579625a5f2SHugh Dickins 	INIT_LIST_HEAD(&p->first_swap_extent.list);
245818ab4d4cSDan Streetman 	plist_node_init(&p->list, 0);
245918ab4d4cSDan Streetman 	plist_node_init(&p->avail_list, 0);
24601da177e4SLinus Torvalds 	p->flags = SWP_USED;
24615d337b91SHugh Dickins 	spin_unlock(&swap_lock);
2462ec8acf20SShaohua Li 	spin_lock_init(&p->lock);
2463efa90a98SHugh Dickins 
246453cbb243SCesar Eduardo Barros 	return p;
246553cbb243SCesar Eduardo Barros }
246653cbb243SCesar Eduardo Barros 
24674d0e1e10SCesar Eduardo Barros static int claim_swapfile(struct swap_info_struct *p, struct inode *inode)
24684d0e1e10SCesar Eduardo Barros {
24694d0e1e10SCesar Eduardo Barros 	int error;
24704d0e1e10SCesar Eduardo Barros 
24714d0e1e10SCesar Eduardo Barros 	if (S_ISBLK(inode->i_mode)) {
24724d0e1e10SCesar Eduardo Barros 		p->bdev = bdgrab(I_BDEV(inode));
24734d0e1e10SCesar Eduardo Barros 		error = blkdev_get(p->bdev,
24746f179af8SHugh Dickins 				   FMODE_READ | FMODE_WRITE | FMODE_EXCL, p);
24754d0e1e10SCesar Eduardo Barros 		if (error < 0) {
24764d0e1e10SCesar Eduardo Barros 			p->bdev = NULL;
24776f179af8SHugh Dickins 			return error;
24784d0e1e10SCesar Eduardo Barros 		}
24794d0e1e10SCesar Eduardo Barros 		p->old_block_size = block_size(p->bdev);
24804d0e1e10SCesar Eduardo Barros 		error = set_blocksize(p->bdev, PAGE_SIZE);
24814d0e1e10SCesar Eduardo Barros 		if (error < 0)
248287ade72aSCesar Eduardo Barros 			return error;
24834d0e1e10SCesar Eduardo Barros 		p->flags |= SWP_BLKDEV;
24844d0e1e10SCesar Eduardo Barros 	} else if (S_ISREG(inode->i_mode)) {
24854d0e1e10SCesar Eduardo Barros 		p->bdev = inode->i_sb->s_bdev;
24865955102cSAl Viro 		inode_lock(inode);
248787ade72aSCesar Eduardo Barros 		if (IS_SWAPFILE(inode))
248887ade72aSCesar Eduardo Barros 			return -EBUSY;
248987ade72aSCesar Eduardo Barros 	} else
249087ade72aSCesar Eduardo Barros 		return -EINVAL;
24914d0e1e10SCesar Eduardo Barros 
24924d0e1e10SCesar Eduardo Barros 	return 0;
24934d0e1e10SCesar Eduardo Barros }
24944d0e1e10SCesar Eduardo Barros 
2495ca8bd38bSCesar Eduardo Barros static unsigned long read_swap_header(struct swap_info_struct *p,
2496ca8bd38bSCesar Eduardo Barros 					union swap_header *swap_header,
2497ca8bd38bSCesar Eduardo Barros 					struct inode *inode)
2498ca8bd38bSCesar Eduardo Barros {
2499ca8bd38bSCesar Eduardo Barros 	int i;
2500ca8bd38bSCesar Eduardo Barros 	unsigned long maxpages;
2501ca8bd38bSCesar Eduardo Barros 	unsigned long swapfilepages;
2502d6bbbd29SRaymond Jennings 	unsigned long last_page;
2503ca8bd38bSCesar Eduardo Barros 
2504ca8bd38bSCesar Eduardo Barros 	if (memcmp("SWAPSPACE2", swap_header->magic.magic, 10)) {
2505465c47fdSAndrew Morton 		pr_err("Unable to find swap-space signature\n");
250638719025SCesar Eduardo Barros 		return 0;
2507ca8bd38bSCesar Eduardo Barros 	}
2508ca8bd38bSCesar Eduardo Barros 
2509ca8bd38bSCesar Eduardo Barros 	/* swap partition endianess hack... */
2510ca8bd38bSCesar Eduardo Barros 	if (swab32(swap_header->info.version) == 1) {
2511ca8bd38bSCesar Eduardo Barros 		swab32s(&swap_header->info.version);
2512ca8bd38bSCesar Eduardo Barros 		swab32s(&swap_header->info.last_page);
2513ca8bd38bSCesar Eduardo Barros 		swab32s(&swap_header->info.nr_badpages);
2514dd111be6SJann Horn 		if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES)
2515dd111be6SJann Horn 			return 0;
2516ca8bd38bSCesar Eduardo Barros 		for (i = 0; i < swap_header->info.nr_badpages; i++)
2517ca8bd38bSCesar Eduardo Barros 			swab32s(&swap_header->info.badpages[i]);
2518ca8bd38bSCesar Eduardo Barros 	}
2519ca8bd38bSCesar Eduardo Barros 	/* Check the swap header's sub-version */
2520ca8bd38bSCesar Eduardo Barros 	if (swap_header->info.version != 1) {
2521465c47fdSAndrew Morton 		pr_warn("Unable to handle swap header version %d\n",
2522ca8bd38bSCesar Eduardo Barros 			swap_header->info.version);
252338719025SCesar Eduardo Barros 		return 0;
2524ca8bd38bSCesar Eduardo Barros 	}
2525ca8bd38bSCesar Eduardo Barros 
2526ca8bd38bSCesar Eduardo Barros 	p->lowest_bit  = 1;
2527ca8bd38bSCesar Eduardo Barros 	p->cluster_next = 1;
2528ca8bd38bSCesar Eduardo Barros 	p->cluster_nr = 0;
2529ca8bd38bSCesar Eduardo Barros 
2530ca8bd38bSCesar Eduardo Barros 	/*
2531ca8bd38bSCesar Eduardo Barros 	 * Find out how many pages are allowed for a single swap
25329b15b817SHugh Dickins 	 * device. There are two limiting factors: 1) the number
2533a2c16d6cSHugh Dickins 	 * of bits for the swap offset in the swp_entry_t type, and
2534a2c16d6cSHugh Dickins 	 * 2) the number of bits in the swap pte as defined by the
25359b15b817SHugh Dickins 	 * different architectures. In order to find the
2536a2c16d6cSHugh Dickins 	 * largest possible bit mask, a swap entry with swap type 0
2537ca8bd38bSCesar Eduardo Barros 	 * and swap offset ~0UL is created, encoded to a swap pte,
2538a2c16d6cSHugh Dickins 	 * decoded to a swp_entry_t again, and finally the swap
2539ca8bd38bSCesar Eduardo Barros 	 * offset is extracted. This will mask all the bits from
2540ca8bd38bSCesar Eduardo Barros 	 * the initial ~0UL mask that can't be encoded in either
2541ca8bd38bSCesar Eduardo Barros 	 * the swp_entry_t or the architecture definition of a
25429b15b817SHugh Dickins 	 * swap pte.
2543ca8bd38bSCesar Eduardo Barros 	 */
2544ca8bd38bSCesar Eduardo Barros 	maxpages = swp_offset(pte_to_swp_entry(
25459b15b817SHugh Dickins 			swp_entry_to_pte(swp_entry(0, ~0UL)))) + 1;
2546d6bbbd29SRaymond Jennings 	last_page = swap_header->info.last_page;
2547d6bbbd29SRaymond Jennings 	if (last_page > maxpages) {
2548465c47fdSAndrew Morton 		pr_warn("Truncating oversized swap area, only using %luk out of %luk\n",
2549d6bbbd29SRaymond Jennings 			maxpages << (PAGE_SHIFT - 10),
2550d6bbbd29SRaymond Jennings 			last_page << (PAGE_SHIFT - 10));
2551d6bbbd29SRaymond Jennings 	}
2552d6bbbd29SRaymond Jennings 	if (maxpages > last_page) {
2553d6bbbd29SRaymond Jennings 		maxpages = last_page + 1;
2554ca8bd38bSCesar Eduardo Barros 		/* p->max is an unsigned int: don't overflow it */
2555ca8bd38bSCesar Eduardo Barros 		if ((unsigned int)maxpages == 0)
2556ca8bd38bSCesar Eduardo Barros 			maxpages = UINT_MAX;
2557ca8bd38bSCesar Eduardo Barros 	}
2558ca8bd38bSCesar Eduardo Barros 	p->highest_bit = maxpages - 1;
2559ca8bd38bSCesar Eduardo Barros 
2560ca8bd38bSCesar Eduardo Barros 	if (!maxpages)
256138719025SCesar Eduardo Barros 		return 0;
2562ca8bd38bSCesar Eduardo Barros 	swapfilepages = i_size_read(inode) >> PAGE_SHIFT;
2563ca8bd38bSCesar Eduardo Barros 	if (swapfilepages && maxpages > swapfilepages) {
2564465c47fdSAndrew Morton 		pr_warn("Swap area shorter than signature indicates\n");
256538719025SCesar Eduardo Barros 		return 0;
2566ca8bd38bSCesar Eduardo Barros 	}
2567ca8bd38bSCesar Eduardo Barros 	if (swap_header->info.nr_badpages && S_ISREG(inode->i_mode))
256838719025SCesar Eduardo Barros 		return 0;
2569ca8bd38bSCesar Eduardo Barros 	if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES)
257038719025SCesar Eduardo Barros 		return 0;
2571ca8bd38bSCesar Eduardo Barros 
2572ca8bd38bSCesar Eduardo Barros 	return maxpages;
2573ca8bd38bSCesar Eduardo Barros }
2574ca8bd38bSCesar Eduardo Barros 
25754b3ef9daSHuang, Ying #define SWAP_CLUSTER_INFO_COLS						\
2576235b6217SHuang, Ying 	DIV_ROUND_UP(L1_CACHE_BYTES, sizeof(struct swap_cluster_info))
25774b3ef9daSHuang, Ying #define SWAP_CLUSTER_SPACE_COLS						\
25784b3ef9daSHuang, Ying 	DIV_ROUND_UP(SWAP_ADDRESS_SPACE_PAGES, SWAPFILE_CLUSTER)
25794b3ef9daSHuang, Ying #define SWAP_CLUSTER_COLS						\
25804b3ef9daSHuang, Ying 	max_t(unsigned int, SWAP_CLUSTER_INFO_COLS, SWAP_CLUSTER_SPACE_COLS)
2581235b6217SHuang, Ying 
2582915d4d7bSCesar Eduardo Barros static int setup_swap_map_and_extents(struct swap_info_struct *p,
2583915d4d7bSCesar Eduardo Barros 					union swap_header *swap_header,
2584915d4d7bSCesar Eduardo Barros 					unsigned char *swap_map,
25852a8f9449SShaohua Li 					struct swap_cluster_info *cluster_info,
2586915d4d7bSCesar Eduardo Barros 					unsigned long maxpages,
2587915d4d7bSCesar Eduardo Barros 					sector_t *span)
2588915d4d7bSCesar Eduardo Barros {
2589235b6217SHuang, Ying 	unsigned int j, k;
2590915d4d7bSCesar Eduardo Barros 	unsigned int nr_good_pages;
2591915d4d7bSCesar Eduardo Barros 	int nr_extents;
25922a8f9449SShaohua Li 	unsigned long nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
2593235b6217SHuang, Ying 	unsigned long col = p->cluster_next / SWAPFILE_CLUSTER % SWAP_CLUSTER_COLS;
2594235b6217SHuang, Ying 	unsigned long i, idx;
2595915d4d7bSCesar Eduardo Barros 
2596915d4d7bSCesar Eduardo Barros 	nr_good_pages = maxpages - 1;	/* omit header page */
2597915d4d7bSCesar Eduardo Barros 
25986b534915SHuang Ying 	cluster_list_init(&p->free_clusters);
25996b534915SHuang Ying 	cluster_list_init(&p->discard_clusters);
26002a8f9449SShaohua Li 
2601915d4d7bSCesar Eduardo Barros 	for (i = 0; i < swap_header->info.nr_badpages; i++) {
2602915d4d7bSCesar Eduardo Barros 		unsigned int page_nr = swap_header->info.badpages[i];
2603bdb8e3f6SCesar Eduardo Barros 		if (page_nr == 0 || page_nr > swap_header->info.last_page)
2604bdb8e3f6SCesar Eduardo Barros 			return -EINVAL;
2605915d4d7bSCesar Eduardo Barros 		if (page_nr < maxpages) {
2606915d4d7bSCesar Eduardo Barros 			swap_map[page_nr] = SWAP_MAP_BAD;
2607915d4d7bSCesar Eduardo Barros 			nr_good_pages--;
26082a8f9449SShaohua Li 			/*
26092a8f9449SShaohua Li 			 * Haven't marked the cluster free yet, no list
26102a8f9449SShaohua Li 			 * operation involved
26112a8f9449SShaohua Li 			 */
26122a8f9449SShaohua Li 			inc_cluster_info_page(p, cluster_info, page_nr);
2613915d4d7bSCesar Eduardo Barros 		}
2614915d4d7bSCesar Eduardo Barros 	}
2615915d4d7bSCesar Eduardo Barros 
26162a8f9449SShaohua Li 	/* Haven't marked the cluster free yet, no list operation involved */
26172a8f9449SShaohua Li 	for (i = maxpages; i < round_up(maxpages, SWAPFILE_CLUSTER); i++)
26182a8f9449SShaohua Li 		inc_cluster_info_page(p, cluster_info, i);
26192a8f9449SShaohua Li 
2620915d4d7bSCesar Eduardo Barros 	if (nr_good_pages) {
2621915d4d7bSCesar Eduardo Barros 		swap_map[0] = SWAP_MAP_BAD;
26222a8f9449SShaohua Li 		/*
26232a8f9449SShaohua Li 		 * Not mark the cluster free yet, no list
26242a8f9449SShaohua Li 		 * operation involved
26252a8f9449SShaohua Li 		 */
26262a8f9449SShaohua Li 		inc_cluster_info_page(p, cluster_info, 0);
2627915d4d7bSCesar Eduardo Barros 		p->max = maxpages;
2628915d4d7bSCesar Eduardo Barros 		p->pages = nr_good_pages;
2629915d4d7bSCesar Eduardo Barros 		nr_extents = setup_swap_extents(p, span);
2630bdb8e3f6SCesar Eduardo Barros 		if (nr_extents < 0)
2631bdb8e3f6SCesar Eduardo Barros 			return nr_extents;
2632915d4d7bSCesar Eduardo Barros 		nr_good_pages = p->pages;
2633915d4d7bSCesar Eduardo Barros 	}
2634915d4d7bSCesar Eduardo Barros 	if (!nr_good_pages) {
2635465c47fdSAndrew Morton 		pr_warn("Empty swap-file\n");
2636bdb8e3f6SCesar Eduardo Barros 		return -EINVAL;
2637915d4d7bSCesar Eduardo Barros 	}
2638915d4d7bSCesar Eduardo Barros 
26392a8f9449SShaohua Li 	if (!cluster_info)
26402a8f9449SShaohua Li 		return nr_extents;
26412a8f9449SShaohua Li 
2642235b6217SHuang, Ying 
26434b3ef9daSHuang, Ying 	/*
26444b3ef9daSHuang, Ying 	 * Reduce false cache line sharing between cluster_info and
26454b3ef9daSHuang, Ying 	 * sharing same address space.
26464b3ef9daSHuang, Ying 	 */
2647235b6217SHuang, Ying 	for (k = 0; k < SWAP_CLUSTER_COLS; k++) {
2648235b6217SHuang, Ying 		j = (k + col) % SWAP_CLUSTER_COLS;
2649235b6217SHuang, Ying 		for (i = 0; i < DIV_ROUND_UP(nr_clusters, SWAP_CLUSTER_COLS); i++) {
2650235b6217SHuang, Ying 			idx = i * SWAP_CLUSTER_COLS + j;
2651235b6217SHuang, Ying 			if (idx >= nr_clusters)
2652235b6217SHuang, Ying 				continue;
2653235b6217SHuang, Ying 			if (cluster_count(&cluster_info[idx]))
2654235b6217SHuang, Ying 				continue;
26552a8f9449SShaohua Li 			cluster_set_flag(&cluster_info[idx], CLUSTER_FLAG_FREE);
26566b534915SHuang Ying 			cluster_list_add_tail(&p->free_clusters, cluster_info,
26576b534915SHuang Ying 					      idx);
26582a8f9449SShaohua Li 		}
26592a8f9449SShaohua Li 	}
2660915d4d7bSCesar Eduardo Barros 	return nr_extents;
2661915d4d7bSCesar Eduardo Barros }
2662915d4d7bSCesar Eduardo Barros 
2663dcf6b7ddSRafael Aquini /*
2664dcf6b7ddSRafael Aquini  * Helper to sys_swapon determining if a given swap
2665dcf6b7ddSRafael Aquini  * backing device queue supports DISCARD operations.
2666dcf6b7ddSRafael Aquini  */
2667dcf6b7ddSRafael Aquini static bool swap_discardable(struct swap_info_struct *si)
2668dcf6b7ddSRafael Aquini {
2669dcf6b7ddSRafael Aquini 	struct request_queue *q = bdev_get_queue(si->bdev);
2670dcf6b7ddSRafael Aquini 
2671dcf6b7ddSRafael Aquini 	if (!q || !blk_queue_discard(q))
2672dcf6b7ddSRafael Aquini 		return false;
2673dcf6b7ddSRafael Aquini 
2674dcf6b7ddSRafael Aquini 	return true;
2675dcf6b7ddSRafael Aquini }
2676dcf6b7ddSRafael Aquini 
267753cbb243SCesar Eduardo Barros SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
267853cbb243SCesar Eduardo Barros {
267953cbb243SCesar Eduardo Barros 	struct swap_info_struct *p;
268091a27b2aSJeff Layton 	struct filename *name;
268153cbb243SCesar Eduardo Barros 	struct file *swap_file = NULL;
268253cbb243SCesar Eduardo Barros 	struct address_space *mapping;
268340531542SCesar Eduardo Barros 	int prio;
268453cbb243SCesar Eduardo Barros 	int error;
268553cbb243SCesar Eduardo Barros 	union swap_header *swap_header;
2686915d4d7bSCesar Eduardo Barros 	int nr_extents;
268753cbb243SCesar Eduardo Barros 	sector_t span;
268853cbb243SCesar Eduardo Barros 	unsigned long maxpages;
268953cbb243SCesar Eduardo Barros 	unsigned char *swap_map = NULL;
26902a8f9449SShaohua Li 	struct swap_cluster_info *cluster_info = NULL;
269138b5faf4SDan Magenheimer 	unsigned long *frontswap_map = NULL;
269253cbb243SCesar Eduardo Barros 	struct page *page = NULL;
269353cbb243SCesar Eduardo Barros 	struct inode *inode = NULL;
269453cbb243SCesar Eduardo Barros 
2695d15cab97SHugh Dickins 	if (swap_flags & ~SWAP_FLAGS_VALID)
2696d15cab97SHugh Dickins 		return -EINVAL;
2697d15cab97SHugh Dickins 
269853cbb243SCesar Eduardo Barros 	if (!capable(CAP_SYS_ADMIN))
269953cbb243SCesar Eduardo Barros 		return -EPERM;
270053cbb243SCesar Eduardo Barros 
270153cbb243SCesar Eduardo Barros 	p = alloc_swap_info();
27022542e513SCesar Eduardo Barros 	if (IS_ERR(p))
27032542e513SCesar Eduardo Barros 		return PTR_ERR(p);
270453cbb243SCesar Eduardo Barros 
2705815c2c54SShaohua Li 	INIT_WORK(&p->discard_work, swap_discard_work);
2706815c2c54SShaohua Li 
27071da177e4SLinus Torvalds 	name = getname(specialfile);
27081da177e4SLinus Torvalds 	if (IS_ERR(name)) {
27097de7fb6bSCesar Eduardo Barros 		error = PTR_ERR(name);
27101da177e4SLinus Torvalds 		name = NULL;
2711bd69010bSCesar Eduardo Barros 		goto bad_swap;
27121da177e4SLinus Torvalds 	}
2713669abf4eSJeff Layton 	swap_file = file_open_name(name, O_RDWR|O_LARGEFILE, 0);
27141da177e4SLinus Torvalds 	if (IS_ERR(swap_file)) {
27157de7fb6bSCesar Eduardo Barros 		error = PTR_ERR(swap_file);
27161da177e4SLinus Torvalds 		swap_file = NULL;
2717bd69010bSCesar Eduardo Barros 		goto bad_swap;
27181da177e4SLinus Torvalds 	}
27191da177e4SLinus Torvalds 
27201da177e4SLinus Torvalds 	p->swap_file = swap_file;
27211da177e4SLinus Torvalds 	mapping = swap_file->f_mapping;
27222130781eSCesar Eduardo Barros 	inode = mapping->host;
27236f179af8SHugh Dickins 
27245955102cSAl Viro 	/* If S_ISREG(inode->i_mode) will do inode_lock(inode); */
27254d0e1e10SCesar Eduardo Barros 	error = claim_swapfile(p, inode);
27264d0e1e10SCesar Eduardo Barros 	if (unlikely(error))
27271da177e4SLinus Torvalds 		goto bad_swap;
27281da177e4SLinus Torvalds 
27291da177e4SLinus Torvalds 	/*
27301da177e4SLinus Torvalds 	 * Read the swap header.
27311da177e4SLinus Torvalds 	 */
27321da177e4SLinus Torvalds 	if (!mapping->a_ops->readpage) {
27331da177e4SLinus Torvalds 		error = -EINVAL;
27341da177e4SLinus Torvalds 		goto bad_swap;
27351da177e4SLinus Torvalds 	}
2736090d2b18SPekka Enberg 	page = read_mapping_page(mapping, 0, swap_file);
27371da177e4SLinus Torvalds 	if (IS_ERR(page)) {
27381da177e4SLinus Torvalds 		error = PTR_ERR(page);
27391da177e4SLinus Torvalds 		goto bad_swap;
27401da177e4SLinus Torvalds 	}
274181e33971SHugh Dickins 	swap_header = kmap(page);
27421da177e4SLinus Torvalds 
2743ca8bd38bSCesar Eduardo Barros 	maxpages = read_swap_header(p, swap_header, inode);
2744ca8bd38bSCesar Eduardo Barros 	if (unlikely(!maxpages)) {
27451da177e4SLinus Torvalds 		error = -EINVAL;
27461da177e4SLinus Torvalds 		goto bad_swap;
27471da177e4SLinus Torvalds 	}
27481da177e4SLinus Torvalds 
27491da177e4SLinus Torvalds 	/* OK, set up the swap map and apply the bad block list */
2750803d0c83SCesar Eduardo Barros 	swap_map = vzalloc(maxpages);
275178ecba08SHugh Dickins 	if (!swap_map) {
27521da177e4SLinus Torvalds 		error = -ENOMEM;
27531da177e4SLinus Torvalds 		goto bad_swap;
27541da177e4SLinus Torvalds 	}
2755f0571429SMinchan Kim 
2756f0571429SMinchan Kim 	if (bdi_cap_stable_pages_required(inode_to_bdi(inode)))
2757f0571429SMinchan Kim 		p->flags |= SWP_STABLE_WRITES;
2758f0571429SMinchan Kim 
27592a8f9449SShaohua Li 	if (p->bdev && blk_queue_nonrot(bdev_get_queue(p->bdev))) {
27606f179af8SHugh Dickins 		int cpu;
2761235b6217SHuang, Ying 		unsigned long ci, nr_cluster;
27626f179af8SHugh Dickins 
27632a8f9449SShaohua Li 		p->flags |= SWP_SOLIDSTATE;
27642a8f9449SShaohua Li 		/*
27652a8f9449SShaohua Li 		 * select a random position to start with to help wear leveling
27662a8f9449SShaohua Li 		 * SSD
27672a8f9449SShaohua Li 		 */
27682a8f9449SShaohua Li 		p->cluster_next = 1 + (prandom_u32() % p->highest_bit);
2769235b6217SHuang, Ying 		nr_cluster = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
27702a8f9449SShaohua Li 
2771235b6217SHuang, Ying 		cluster_info = vzalloc(nr_cluster * sizeof(*cluster_info));
27722a8f9449SShaohua Li 		if (!cluster_info) {
27732a8f9449SShaohua Li 			error = -ENOMEM;
27742a8f9449SShaohua Li 			goto bad_swap;
27752a8f9449SShaohua Li 		}
2776235b6217SHuang, Ying 
2777235b6217SHuang, Ying 		for (ci = 0; ci < nr_cluster; ci++)
2778235b6217SHuang, Ying 			spin_lock_init(&((cluster_info + ci)->lock));
2779235b6217SHuang, Ying 
2780ebc2a1a6SShaohua Li 		p->percpu_cluster = alloc_percpu(struct percpu_cluster);
2781ebc2a1a6SShaohua Li 		if (!p->percpu_cluster) {
2782ebc2a1a6SShaohua Li 			error = -ENOMEM;
2783ebc2a1a6SShaohua Li 			goto bad_swap;
2784ebc2a1a6SShaohua Li 		}
27856f179af8SHugh Dickins 		for_each_possible_cpu(cpu) {
2786ebc2a1a6SShaohua Li 			struct percpu_cluster *cluster;
27876f179af8SHugh Dickins 			cluster = per_cpu_ptr(p->percpu_cluster, cpu);
2788ebc2a1a6SShaohua Li 			cluster_set_null(&cluster->index);
2789ebc2a1a6SShaohua Li 		}
27902a8f9449SShaohua Li 	}
27911da177e4SLinus Torvalds 
27921421ef3cSCesar Eduardo Barros 	error = swap_cgroup_swapon(p->type, maxpages);
27931421ef3cSCesar Eduardo Barros 	if (error)
27941421ef3cSCesar Eduardo Barros 		goto bad_swap;
27951421ef3cSCesar Eduardo Barros 
2796915d4d7bSCesar Eduardo Barros 	nr_extents = setup_swap_map_and_extents(p, swap_header, swap_map,
27972a8f9449SShaohua Li 		cluster_info, maxpages, &span);
2798915d4d7bSCesar Eduardo Barros 	if (unlikely(nr_extents < 0)) {
279953092a74SHugh Dickins 		error = nr_extents;
2800e2244ec2SHugh Dickins 		goto bad_swap;
280153092a74SHugh Dickins 	}
280238b5faf4SDan Magenheimer 	/* frontswap enabled? set up bit-per-page map for frontswap */
28038ea1d2a1SVlastimil Babka 	if (IS_ENABLED(CONFIG_FRONTSWAP))
28047b57976dSAkinobu Mita 		frontswap_map = vzalloc(BITS_TO_LONGS(maxpages) * sizeof(long));
28051da177e4SLinus Torvalds 
28062a8f9449SShaohua Li 	if (p->bdev &&(swap_flags & SWAP_FLAG_DISCARD) && swap_discardable(p)) {
2807dcf6b7ddSRafael Aquini 		/*
2808dcf6b7ddSRafael Aquini 		 * When discard is enabled for swap with no particular
2809dcf6b7ddSRafael Aquini 		 * policy flagged, we set all swap discard flags here in
2810dcf6b7ddSRafael Aquini 		 * order to sustain backward compatibility with older
2811dcf6b7ddSRafael Aquini 		 * swapon(8) releases.
2812dcf6b7ddSRafael Aquini 		 */
2813dcf6b7ddSRafael Aquini 		p->flags |= (SWP_DISCARDABLE | SWP_AREA_DISCARD |
2814dcf6b7ddSRafael Aquini 			     SWP_PAGE_DISCARD);
2815dcf6b7ddSRafael Aquini 
2816dcf6b7ddSRafael Aquini 		/*
2817dcf6b7ddSRafael Aquini 		 * By flagging sys_swapon, a sysadmin can tell us to
2818dcf6b7ddSRafael Aquini 		 * either do single-time area discards only, or to just
2819dcf6b7ddSRafael Aquini 		 * perform discards for released swap page-clusters.
2820dcf6b7ddSRafael Aquini 		 * Now it's time to adjust the p->flags accordingly.
2821dcf6b7ddSRafael Aquini 		 */
2822dcf6b7ddSRafael Aquini 		if (swap_flags & SWAP_FLAG_DISCARD_ONCE)
2823dcf6b7ddSRafael Aquini 			p->flags &= ~SWP_PAGE_DISCARD;
2824dcf6b7ddSRafael Aquini 		else if (swap_flags & SWAP_FLAG_DISCARD_PAGES)
2825dcf6b7ddSRafael Aquini 			p->flags &= ~SWP_AREA_DISCARD;
2826dcf6b7ddSRafael Aquini 
2827dcf6b7ddSRafael Aquini 		/* issue a swapon-time discard if it's still required */
2828dcf6b7ddSRafael Aquini 		if (p->flags & SWP_AREA_DISCARD) {
2829dcf6b7ddSRafael Aquini 			int err = discard_swap(p);
2830dcf6b7ddSRafael Aquini 			if (unlikely(err))
2831465c47fdSAndrew Morton 				pr_err("swapon: discard_swap(%p): %d\n",
2832dcf6b7ddSRafael Aquini 					p, err);
2833dcf6b7ddSRafael Aquini 		}
2834dcf6b7ddSRafael Aquini 	}
28356a6ba831SHugh Dickins 
28364b3ef9daSHuang, Ying 	error = init_swap_address_space(p->type, maxpages);
28374b3ef9daSHuang, Ying 	if (error)
28384b3ef9daSHuang, Ying 		goto bad_swap;
28394b3ef9daSHuang, Ying 
2840fc0abb14SIngo Molnar 	mutex_lock(&swapon_mutex);
284140531542SCesar Eduardo Barros 	prio = -1;
284278ecba08SHugh Dickins 	if (swap_flags & SWAP_FLAG_PREFER)
284340531542SCesar Eduardo Barros 		prio =
284478ecba08SHugh Dickins 		  (swap_flags & SWAP_FLAG_PRIO_MASK) >> SWAP_FLAG_PRIO_SHIFT;
28452a8f9449SShaohua Li 	enable_swap_info(p, prio, swap_map, cluster_info, frontswap_map);
2846c69dbfb8SCesar Eduardo Barros 
2847756a025fSJoe Perches 	pr_info("Adding %uk swap on %s.  Priority:%d extents:%d across:%lluk %s%s%s%s%s\n",
284891a27b2aSJeff Layton 		p->pages<<(PAGE_SHIFT-10), name->name, p->prio,
2849c69dbfb8SCesar Eduardo Barros 		nr_extents, (unsigned long long)span<<(PAGE_SHIFT-10),
2850c69dbfb8SCesar Eduardo Barros 		(p->flags & SWP_SOLIDSTATE) ? "SS" : "",
285138b5faf4SDan Magenheimer 		(p->flags & SWP_DISCARDABLE) ? "D" : "",
2852dcf6b7ddSRafael Aquini 		(p->flags & SWP_AREA_DISCARD) ? "s" : "",
2853dcf6b7ddSRafael Aquini 		(p->flags & SWP_PAGE_DISCARD) ? "c" : "",
285438b5faf4SDan Magenheimer 		(frontswap_map) ? "FS" : "");
2855c69dbfb8SCesar Eduardo Barros 
2856fc0abb14SIngo Molnar 	mutex_unlock(&swapon_mutex);
285766d7dd51SKay Sievers 	atomic_inc(&proc_poll_event);
285866d7dd51SKay Sievers 	wake_up_interruptible(&proc_poll_wait);
285966d7dd51SKay Sievers 
28609b01c350SCesar Eduardo Barros 	if (S_ISREG(inode->i_mode))
28619b01c350SCesar Eduardo Barros 		inode->i_flags |= S_SWAPFILE;
28621da177e4SLinus Torvalds 	error = 0;
28631da177e4SLinus Torvalds 	goto out;
28641da177e4SLinus Torvalds bad_swap:
2865ebc2a1a6SShaohua Li 	free_percpu(p->percpu_cluster);
2866ebc2a1a6SShaohua Li 	p->percpu_cluster = NULL;
2867bd69010bSCesar Eduardo Barros 	if (inode && S_ISBLK(inode->i_mode) && p->bdev) {
2868f2090d2dSCesar Eduardo Barros 		set_blocksize(p->bdev, p->old_block_size);
2869f2090d2dSCesar Eduardo Barros 		blkdev_put(p->bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL);
28701da177e4SLinus Torvalds 	}
28714cd3bb10SHugh Dickins 	destroy_swap_extents(p);
2872e8e6c2ecSCesar Eduardo Barros 	swap_cgroup_swapoff(p->type);
28735d337b91SHugh Dickins 	spin_lock(&swap_lock);
28741da177e4SLinus Torvalds 	p->swap_file = NULL;
28751da177e4SLinus Torvalds 	p->flags = 0;
28765d337b91SHugh Dickins 	spin_unlock(&swap_lock);
28771da177e4SLinus Torvalds 	vfree(swap_map);
28782a8f9449SShaohua Li 	vfree(cluster_info);
287952c50567SMel Gorman 	if (swap_file) {
28802130781eSCesar Eduardo Barros 		if (inode && S_ISREG(inode->i_mode)) {
28815955102cSAl Viro 			inode_unlock(inode);
28822130781eSCesar Eduardo Barros 			inode = NULL;
28832130781eSCesar Eduardo Barros 		}
28841da177e4SLinus Torvalds 		filp_close(swap_file, NULL);
288552c50567SMel Gorman 	}
28861da177e4SLinus Torvalds out:
28871da177e4SLinus Torvalds 	if (page && !IS_ERR(page)) {
28881da177e4SLinus Torvalds 		kunmap(page);
288909cbfeafSKirill A. Shutemov 		put_page(page);
28901da177e4SLinus Torvalds 	}
28911da177e4SLinus Torvalds 	if (name)
28921da177e4SLinus Torvalds 		putname(name);
28939b01c350SCesar Eduardo Barros 	if (inode && S_ISREG(inode->i_mode))
28945955102cSAl Viro 		inode_unlock(inode);
2895039939a6STim Chen 	if (!error)
2896039939a6STim Chen 		enable_swap_slots_cache();
28971da177e4SLinus Torvalds 	return error;
28981da177e4SLinus Torvalds }
28991da177e4SLinus Torvalds 
29001da177e4SLinus Torvalds void si_swapinfo(struct sysinfo *val)
29011da177e4SLinus Torvalds {
2902efa90a98SHugh Dickins 	unsigned int type;
29031da177e4SLinus Torvalds 	unsigned long nr_to_be_unused = 0;
29041da177e4SLinus Torvalds 
29055d337b91SHugh Dickins 	spin_lock(&swap_lock);
2906efa90a98SHugh Dickins 	for (type = 0; type < nr_swapfiles; type++) {
2907efa90a98SHugh Dickins 		struct swap_info_struct *si = swap_info[type];
2908efa90a98SHugh Dickins 
2909efa90a98SHugh Dickins 		if ((si->flags & SWP_USED) && !(si->flags & SWP_WRITEOK))
2910efa90a98SHugh Dickins 			nr_to_be_unused += si->inuse_pages;
29111da177e4SLinus Torvalds 	}
2912ec8acf20SShaohua Li 	val->freeswap = atomic_long_read(&nr_swap_pages) + nr_to_be_unused;
29131da177e4SLinus Torvalds 	val->totalswap = total_swap_pages + nr_to_be_unused;
29145d337b91SHugh Dickins 	spin_unlock(&swap_lock);
29151da177e4SLinus Torvalds }
29161da177e4SLinus Torvalds 
29171da177e4SLinus Torvalds /*
29181da177e4SLinus Torvalds  * Verify that a swap entry is valid and increment its swap map count.
29191da177e4SLinus Torvalds  *
2920355cfa73SKAMEZAWA Hiroyuki  * Returns error code in following case.
2921355cfa73SKAMEZAWA Hiroyuki  * - success -> 0
2922355cfa73SKAMEZAWA Hiroyuki  * - swp_entry is invalid -> EINVAL
2923355cfa73SKAMEZAWA Hiroyuki  * - swp_entry is migration entry -> EINVAL
2924355cfa73SKAMEZAWA Hiroyuki  * - swap-cache reference is requested but there is already one. -> EEXIST
2925355cfa73SKAMEZAWA Hiroyuki  * - swap-cache reference is requested but the entry is not used. -> ENOENT
2926570a335bSHugh Dickins  * - swap-mapped reference requested but needs continued swap count. -> ENOMEM
29271da177e4SLinus Torvalds  */
29288d69aaeeSHugh Dickins static int __swap_duplicate(swp_entry_t entry, unsigned char usage)
29291da177e4SLinus Torvalds {
29301da177e4SLinus Torvalds 	struct swap_info_struct *p;
2931235b6217SHuang, Ying 	struct swap_cluster_info *ci;
29321da177e4SLinus Torvalds 	unsigned long offset, type;
29338d69aaeeSHugh Dickins 	unsigned char count;
29348d69aaeeSHugh Dickins 	unsigned char has_cache;
2935253d553bSHugh Dickins 	int err = -EINVAL;
29361da177e4SLinus Torvalds 
2937a7420aa5SAndi Kleen 	if (non_swap_entry(entry))
2938253d553bSHugh Dickins 		goto out;
29390697212aSChristoph Lameter 
29401da177e4SLinus Torvalds 	type = swp_type(entry);
29411da177e4SLinus Torvalds 	if (type >= nr_swapfiles)
29421da177e4SLinus Torvalds 		goto bad_file;
2943efa90a98SHugh Dickins 	p = swap_info[type];
29441da177e4SLinus Torvalds 	offset = swp_offset(entry);
2945355cfa73SKAMEZAWA Hiroyuki 	if (unlikely(offset >= p->max))
2946235b6217SHuang, Ying 		goto out;
2947235b6217SHuang, Ying 
2948235b6217SHuang, Ying 	ci = lock_cluster_or_swap_info(p, offset);
2949355cfa73SKAMEZAWA Hiroyuki 
2950253d553bSHugh Dickins 	count = p->swap_map[offset];
2951edfe23daSShaohua Li 
2952edfe23daSShaohua Li 	/*
2953edfe23daSShaohua Li 	 * swapin_readahead() doesn't check if a swap entry is valid, so the
2954edfe23daSShaohua Li 	 * swap entry could be SWAP_MAP_BAD. Check here with lock held.
2955edfe23daSShaohua Li 	 */
2956edfe23daSShaohua Li 	if (unlikely(swap_count(count) == SWAP_MAP_BAD)) {
2957edfe23daSShaohua Li 		err = -ENOENT;
2958edfe23daSShaohua Li 		goto unlock_out;
2959edfe23daSShaohua Li 	}
2960edfe23daSShaohua Li 
2961253d553bSHugh Dickins 	has_cache = count & SWAP_HAS_CACHE;
2962253d553bSHugh Dickins 	count &= ~SWAP_HAS_CACHE;
2963253d553bSHugh Dickins 	err = 0;
2964355cfa73SKAMEZAWA Hiroyuki 
2965253d553bSHugh Dickins 	if (usage == SWAP_HAS_CACHE) {
2966355cfa73SKAMEZAWA Hiroyuki 
2967355cfa73SKAMEZAWA Hiroyuki 		/* set SWAP_HAS_CACHE if there is no cache and entry is used */
2968253d553bSHugh Dickins 		if (!has_cache && count)
2969253d553bSHugh Dickins 			has_cache = SWAP_HAS_CACHE;
2970253d553bSHugh Dickins 		else if (has_cache)		/* someone else added cache */
2971253d553bSHugh Dickins 			err = -EEXIST;
2972253d553bSHugh Dickins 		else				/* no users remaining */
2973253d553bSHugh Dickins 			err = -ENOENT;
2974355cfa73SKAMEZAWA Hiroyuki 
2975355cfa73SKAMEZAWA Hiroyuki 	} else if (count || has_cache) {
2976253d553bSHugh Dickins 
2977570a335bSHugh Dickins 		if ((count & ~COUNT_CONTINUED) < SWAP_MAP_MAX)
2978570a335bSHugh Dickins 			count += usage;
2979570a335bSHugh Dickins 		else if ((count & ~COUNT_CONTINUED) > SWAP_MAP_MAX)
2980253d553bSHugh Dickins 			err = -EINVAL;
2981570a335bSHugh Dickins 		else if (swap_count_continued(p, offset, count))
2982570a335bSHugh Dickins 			count = COUNT_CONTINUED;
2983570a335bSHugh Dickins 		else
2984570a335bSHugh Dickins 			err = -ENOMEM;
2985253d553bSHugh Dickins 	} else
2986253d553bSHugh Dickins 		err = -ENOENT;			/* unused swap entry */
2987253d553bSHugh Dickins 
2988253d553bSHugh Dickins 	p->swap_map[offset] = count | has_cache;
2989253d553bSHugh Dickins 
2990355cfa73SKAMEZAWA Hiroyuki unlock_out:
2991235b6217SHuang, Ying 	unlock_cluster_or_swap_info(p, ci);
29921da177e4SLinus Torvalds out:
2993253d553bSHugh Dickins 	return err;
29941da177e4SLinus Torvalds 
29951da177e4SLinus Torvalds bad_file:
2996465c47fdSAndrew Morton 	pr_err("swap_dup: %s%08lx\n", Bad_file, entry.val);
29971da177e4SLinus Torvalds 	goto out;
29981da177e4SLinus Torvalds }
2999253d553bSHugh Dickins 
3000355cfa73SKAMEZAWA Hiroyuki /*
3001aaa46865SHugh Dickins  * Help swapoff by noting that swap entry belongs to shmem/tmpfs
3002aaa46865SHugh Dickins  * (in which case its reference count is never incremented).
3003aaa46865SHugh Dickins  */
3004aaa46865SHugh Dickins void swap_shmem_alloc(swp_entry_t entry)
3005aaa46865SHugh Dickins {
3006aaa46865SHugh Dickins 	__swap_duplicate(entry, SWAP_MAP_SHMEM);
3007aaa46865SHugh Dickins }
3008aaa46865SHugh Dickins 
3009aaa46865SHugh Dickins /*
301008259d58SHugh Dickins  * Increase reference count of swap entry by 1.
301108259d58SHugh Dickins  * Returns 0 for success, or -ENOMEM if a swap_count_continuation is required
301208259d58SHugh Dickins  * but could not be atomically allocated.  Returns 0, just as if it succeeded,
301308259d58SHugh Dickins  * if __swap_duplicate() fails for another reason (-EINVAL or -ENOENT), which
301408259d58SHugh Dickins  * might occur if a page table entry has got corrupted.
3015355cfa73SKAMEZAWA Hiroyuki  */
3016570a335bSHugh Dickins int swap_duplicate(swp_entry_t entry)
3017355cfa73SKAMEZAWA Hiroyuki {
3018570a335bSHugh Dickins 	int err = 0;
3019570a335bSHugh Dickins 
3020570a335bSHugh Dickins 	while (!err && __swap_duplicate(entry, 1) == -ENOMEM)
3021570a335bSHugh Dickins 		err = add_swap_count_continuation(entry, GFP_ATOMIC);
3022570a335bSHugh Dickins 	return err;
3023355cfa73SKAMEZAWA Hiroyuki }
30241da177e4SLinus Torvalds 
3025cb4b86baSKAMEZAWA Hiroyuki /*
3026355cfa73SKAMEZAWA Hiroyuki  * @entry: swap entry for which we allocate swap cache.
3027355cfa73SKAMEZAWA Hiroyuki  *
302873c34b6aSHugh Dickins  * Called when allocating swap cache for existing swap entry,
3029355cfa73SKAMEZAWA Hiroyuki  * This can return error codes. Returns 0 at success.
3030355cfa73SKAMEZAWA Hiroyuki  * -EBUSY means there is a swap cache.
3031355cfa73SKAMEZAWA Hiroyuki  * Note: return code is different from swap_duplicate().
3032cb4b86baSKAMEZAWA Hiroyuki  */
3033cb4b86baSKAMEZAWA Hiroyuki int swapcache_prepare(swp_entry_t entry)
3034cb4b86baSKAMEZAWA Hiroyuki {
3035253d553bSHugh Dickins 	return __swap_duplicate(entry, SWAP_HAS_CACHE);
3036cb4b86baSKAMEZAWA Hiroyuki }
3037cb4b86baSKAMEZAWA Hiroyuki 
3038f981c595SMel Gorman struct swap_info_struct *page_swap_info(struct page *page)
3039f981c595SMel Gorman {
3040f981c595SMel Gorman 	swp_entry_t swap = { .val = page_private(page) };
3041f981c595SMel Gorman 	return swap_info[swp_type(swap)];
3042f981c595SMel Gorman }
3043f981c595SMel Gorman 
3044f981c595SMel Gorman /*
3045f981c595SMel Gorman  * out-of-line __page_file_ methods to avoid include hell.
3046f981c595SMel Gorman  */
3047f981c595SMel Gorman struct address_space *__page_file_mapping(struct page *page)
3048f981c595SMel Gorman {
3049309381feSSasha Levin 	VM_BUG_ON_PAGE(!PageSwapCache(page), page);
3050f981c595SMel Gorman 	return page_swap_info(page)->swap_file->f_mapping;
3051f981c595SMel Gorman }
3052f981c595SMel Gorman EXPORT_SYMBOL_GPL(__page_file_mapping);
3053f981c595SMel Gorman 
3054f981c595SMel Gorman pgoff_t __page_file_index(struct page *page)
3055f981c595SMel Gorman {
3056f981c595SMel Gorman 	swp_entry_t swap = { .val = page_private(page) };
3057309381feSSasha Levin 	VM_BUG_ON_PAGE(!PageSwapCache(page), page);
3058f981c595SMel Gorman 	return swp_offset(swap);
3059f981c595SMel Gorman }
3060f981c595SMel Gorman EXPORT_SYMBOL_GPL(__page_file_index);
3061f981c595SMel Gorman 
30621da177e4SLinus Torvalds /*
3063570a335bSHugh Dickins  * add_swap_count_continuation - called when a swap count is duplicated
3064570a335bSHugh Dickins  * beyond SWAP_MAP_MAX, it allocates a new page and links that to the entry's
3065570a335bSHugh Dickins  * page of the original vmalloc'ed swap_map, to hold the continuation count
3066570a335bSHugh Dickins  * (for that entry and for its neighbouring PAGE_SIZE swap entries).  Called
3067570a335bSHugh Dickins  * again when count is duplicated beyond SWAP_MAP_MAX * SWAP_CONT_MAX, etc.
3068570a335bSHugh Dickins  *
3069570a335bSHugh Dickins  * These continuation pages are seldom referenced: the common paths all work
3070570a335bSHugh Dickins  * on the original swap_map, only referring to a continuation page when the
3071570a335bSHugh Dickins  * low "digit" of a count is incremented or decremented through SWAP_MAP_MAX.
3072570a335bSHugh Dickins  *
3073570a335bSHugh Dickins  * add_swap_count_continuation(, GFP_ATOMIC) can be called while holding
3074570a335bSHugh Dickins  * page table locks; if it fails, add_swap_count_continuation(, GFP_KERNEL)
3075570a335bSHugh Dickins  * can be called after dropping locks.
3076570a335bSHugh Dickins  */
3077570a335bSHugh Dickins int add_swap_count_continuation(swp_entry_t entry, gfp_t gfp_mask)
3078570a335bSHugh Dickins {
3079570a335bSHugh Dickins 	struct swap_info_struct *si;
3080235b6217SHuang, Ying 	struct swap_cluster_info *ci;
3081570a335bSHugh Dickins 	struct page *head;
3082570a335bSHugh Dickins 	struct page *page;
3083570a335bSHugh Dickins 	struct page *list_page;
3084570a335bSHugh Dickins 	pgoff_t offset;
3085570a335bSHugh Dickins 	unsigned char count;
3086570a335bSHugh Dickins 
3087570a335bSHugh Dickins 	/*
3088570a335bSHugh Dickins 	 * When debugging, it's easier to use __GFP_ZERO here; but it's better
3089570a335bSHugh Dickins 	 * for latency not to zero a page while GFP_ATOMIC and holding locks.
3090570a335bSHugh Dickins 	 */
3091570a335bSHugh Dickins 	page = alloc_page(gfp_mask | __GFP_HIGHMEM);
3092570a335bSHugh Dickins 
3093570a335bSHugh Dickins 	si = swap_info_get(entry);
3094570a335bSHugh Dickins 	if (!si) {
3095570a335bSHugh Dickins 		/*
3096570a335bSHugh Dickins 		 * An acceptable race has occurred since the failing
3097570a335bSHugh Dickins 		 * __swap_duplicate(): the swap entry has been freed,
3098570a335bSHugh Dickins 		 * perhaps even the whole swap_map cleared for swapoff.
3099570a335bSHugh Dickins 		 */
3100570a335bSHugh Dickins 		goto outer;
3101570a335bSHugh Dickins 	}
3102570a335bSHugh Dickins 
3103570a335bSHugh Dickins 	offset = swp_offset(entry);
3104235b6217SHuang, Ying 
3105235b6217SHuang, Ying 	ci = lock_cluster(si, offset);
3106235b6217SHuang, Ying 
3107570a335bSHugh Dickins 	count = si->swap_map[offset] & ~SWAP_HAS_CACHE;
3108570a335bSHugh Dickins 
3109570a335bSHugh Dickins 	if ((count & ~COUNT_CONTINUED) != SWAP_MAP_MAX) {
3110570a335bSHugh Dickins 		/*
3111570a335bSHugh Dickins 		 * The higher the swap count, the more likely it is that tasks
3112570a335bSHugh Dickins 		 * will race to add swap count continuation: we need to avoid
3113570a335bSHugh Dickins 		 * over-provisioning.
3114570a335bSHugh Dickins 		 */
3115570a335bSHugh Dickins 		goto out;
3116570a335bSHugh Dickins 	}
3117570a335bSHugh Dickins 
3118570a335bSHugh Dickins 	if (!page) {
3119235b6217SHuang, Ying 		unlock_cluster(ci);
3120ec8acf20SShaohua Li 		spin_unlock(&si->lock);
3121570a335bSHugh Dickins 		return -ENOMEM;
3122570a335bSHugh Dickins 	}
3123570a335bSHugh Dickins 
3124570a335bSHugh Dickins 	/*
3125570a335bSHugh Dickins 	 * We are fortunate that although vmalloc_to_page uses pte_offset_map,
3126570a335bSHugh Dickins 	 * no architecture is using highmem pages for kernel page tables: so it
3127570a335bSHugh Dickins 	 * will not corrupt the GFP_ATOMIC caller's atomic page table kmaps.
3128570a335bSHugh Dickins 	 */
3129570a335bSHugh Dickins 	head = vmalloc_to_page(si->swap_map + offset);
3130570a335bSHugh Dickins 	offset &= ~PAGE_MASK;
3131570a335bSHugh Dickins 
3132570a335bSHugh Dickins 	/*
3133570a335bSHugh Dickins 	 * Page allocation does not initialize the page's lru field,
3134570a335bSHugh Dickins 	 * but it does always reset its private field.
3135570a335bSHugh Dickins 	 */
3136570a335bSHugh Dickins 	if (!page_private(head)) {
3137570a335bSHugh Dickins 		BUG_ON(count & COUNT_CONTINUED);
3138570a335bSHugh Dickins 		INIT_LIST_HEAD(&head->lru);
3139570a335bSHugh Dickins 		set_page_private(head, SWP_CONTINUED);
3140570a335bSHugh Dickins 		si->flags |= SWP_CONTINUED;
3141570a335bSHugh Dickins 	}
3142570a335bSHugh Dickins 
3143570a335bSHugh Dickins 	list_for_each_entry(list_page, &head->lru, lru) {
3144570a335bSHugh Dickins 		unsigned char *map;
3145570a335bSHugh Dickins 
3146570a335bSHugh Dickins 		/*
3147570a335bSHugh Dickins 		 * If the previous map said no continuation, but we've found
3148570a335bSHugh Dickins 		 * a continuation page, free our allocation and use this one.
3149570a335bSHugh Dickins 		 */
3150570a335bSHugh Dickins 		if (!(count & COUNT_CONTINUED))
3151570a335bSHugh Dickins 			goto out;
3152570a335bSHugh Dickins 
31539b04c5feSCong Wang 		map = kmap_atomic(list_page) + offset;
3154570a335bSHugh Dickins 		count = *map;
31559b04c5feSCong Wang 		kunmap_atomic(map);
3156570a335bSHugh Dickins 
3157570a335bSHugh Dickins 		/*
3158570a335bSHugh Dickins 		 * If this continuation count now has some space in it,
3159570a335bSHugh Dickins 		 * free our allocation and use this one.
3160570a335bSHugh Dickins 		 */
3161570a335bSHugh Dickins 		if ((count & ~COUNT_CONTINUED) != SWAP_CONT_MAX)
3162570a335bSHugh Dickins 			goto out;
3163570a335bSHugh Dickins 	}
3164570a335bSHugh Dickins 
3165570a335bSHugh Dickins 	list_add_tail(&page->lru, &head->lru);
3166570a335bSHugh Dickins 	page = NULL;			/* now it's attached, don't free it */
3167570a335bSHugh Dickins out:
3168235b6217SHuang, Ying 	unlock_cluster(ci);
3169ec8acf20SShaohua Li 	spin_unlock(&si->lock);
3170570a335bSHugh Dickins outer:
3171570a335bSHugh Dickins 	if (page)
3172570a335bSHugh Dickins 		__free_page(page);
3173570a335bSHugh Dickins 	return 0;
3174570a335bSHugh Dickins }
3175570a335bSHugh Dickins 
3176570a335bSHugh Dickins /*
3177570a335bSHugh Dickins  * swap_count_continued - when the original swap_map count is incremented
3178570a335bSHugh Dickins  * from SWAP_MAP_MAX, check if there is already a continuation page to carry
3179570a335bSHugh Dickins  * into, carry if so, or else fail until a new continuation page is allocated;
3180570a335bSHugh Dickins  * when the original swap_map count is decremented from 0 with continuation,
3181570a335bSHugh Dickins  * borrow from the continuation and report whether it still holds more.
3182235b6217SHuang, Ying  * Called while __swap_duplicate() or swap_entry_free() holds swap or cluster
3183235b6217SHuang, Ying  * lock.
3184570a335bSHugh Dickins  */
3185570a335bSHugh Dickins static bool swap_count_continued(struct swap_info_struct *si,
3186570a335bSHugh Dickins 				 pgoff_t offset, unsigned char count)
3187570a335bSHugh Dickins {
3188570a335bSHugh Dickins 	struct page *head;
3189570a335bSHugh Dickins 	struct page *page;
3190570a335bSHugh Dickins 	unsigned char *map;
3191570a335bSHugh Dickins 
3192570a335bSHugh Dickins 	head = vmalloc_to_page(si->swap_map + offset);
3193570a335bSHugh Dickins 	if (page_private(head) != SWP_CONTINUED) {
3194570a335bSHugh Dickins 		BUG_ON(count & COUNT_CONTINUED);
3195570a335bSHugh Dickins 		return false;		/* need to add count continuation */
3196570a335bSHugh Dickins 	}
3197570a335bSHugh Dickins 
3198570a335bSHugh Dickins 	offset &= ~PAGE_MASK;
3199570a335bSHugh Dickins 	page = list_entry(head->lru.next, struct page, lru);
32009b04c5feSCong Wang 	map = kmap_atomic(page) + offset;
3201570a335bSHugh Dickins 
3202570a335bSHugh Dickins 	if (count == SWAP_MAP_MAX)	/* initial increment from swap_map */
3203570a335bSHugh Dickins 		goto init_map;		/* jump over SWAP_CONT_MAX checks */
3204570a335bSHugh Dickins 
3205570a335bSHugh Dickins 	if (count == (SWAP_MAP_MAX | COUNT_CONTINUED)) { /* incrementing */
3206570a335bSHugh Dickins 		/*
3207570a335bSHugh Dickins 		 * Think of how you add 1 to 999
3208570a335bSHugh Dickins 		 */
3209570a335bSHugh Dickins 		while (*map == (SWAP_CONT_MAX | COUNT_CONTINUED)) {
32109b04c5feSCong Wang 			kunmap_atomic(map);
3211570a335bSHugh Dickins 			page = list_entry(page->lru.next, struct page, lru);
3212570a335bSHugh Dickins 			BUG_ON(page == head);
32139b04c5feSCong Wang 			map = kmap_atomic(page) + offset;
3214570a335bSHugh Dickins 		}
3215570a335bSHugh Dickins 		if (*map == SWAP_CONT_MAX) {
32169b04c5feSCong Wang 			kunmap_atomic(map);
3217570a335bSHugh Dickins 			page = list_entry(page->lru.next, struct page, lru);
3218570a335bSHugh Dickins 			if (page == head)
3219570a335bSHugh Dickins 				return false;	/* add count continuation */
32209b04c5feSCong Wang 			map = kmap_atomic(page) + offset;
3221570a335bSHugh Dickins init_map:		*map = 0;		/* we didn't zero the page */
3222570a335bSHugh Dickins 		}
3223570a335bSHugh Dickins 		*map += 1;
32249b04c5feSCong Wang 		kunmap_atomic(map);
3225570a335bSHugh Dickins 		page = list_entry(page->lru.prev, struct page, lru);
3226570a335bSHugh Dickins 		while (page != head) {
32279b04c5feSCong Wang 			map = kmap_atomic(page) + offset;
3228570a335bSHugh Dickins 			*map = COUNT_CONTINUED;
32299b04c5feSCong Wang 			kunmap_atomic(map);
3230570a335bSHugh Dickins 			page = list_entry(page->lru.prev, struct page, lru);
3231570a335bSHugh Dickins 		}
3232570a335bSHugh Dickins 		return true;			/* incremented */
3233570a335bSHugh Dickins 
3234570a335bSHugh Dickins 	} else {				/* decrementing */
3235570a335bSHugh Dickins 		/*
3236570a335bSHugh Dickins 		 * Think of how you subtract 1 from 1000
3237570a335bSHugh Dickins 		 */
3238570a335bSHugh Dickins 		BUG_ON(count != COUNT_CONTINUED);
3239570a335bSHugh Dickins 		while (*map == COUNT_CONTINUED) {
32409b04c5feSCong Wang 			kunmap_atomic(map);
3241570a335bSHugh Dickins 			page = list_entry(page->lru.next, struct page, lru);
3242570a335bSHugh Dickins 			BUG_ON(page == head);
32439b04c5feSCong Wang 			map = kmap_atomic(page) + offset;
3244570a335bSHugh Dickins 		}
3245570a335bSHugh Dickins 		BUG_ON(*map == 0);
3246570a335bSHugh Dickins 		*map -= 1;
3247570a335bSHugh Dickins 		if (*map == 0)
3248570a335bSHugh Dickins 			count = 0;
32499b04c5feSCong Wang 		kunmap_atomic(map);
3250570a335bSHugh Dickins 		page = list_entry(page->lru.prev, struct page, lru);
3251570a335bSHugh Dickins 		while (page != head) {
32529b04c5feSCong Wang 			map = kmap_atomic(page) + offset;
3253570a335bSHugh Dickins 			*map = SWAP_CONT_MAX | count;
3254570a335bSHugh Dickins 			count = COUNT_CONTINUED;
32559b04c5feSCong Wang 			kunmap_atomic(map);
3256570a335bSHugh Dickins 			page = list_entry(page->lru.prev, struct page, lru);
3257570a335bSHugh Dickins 		}
3258570a335bSHugh Dickins 		return count == COUNT_CONTINUED;
3259570a335bSHugh Dickins 	}
3260570a335bSHugh Dickins }
3261570a335bSHugh Dickins 
3262570a335bSHugh Dickins /*
3263570a335bSHugh Dickins  * free_swap_count_continuations - swapoff free all the continuation pages
3264570a335bSHugh Dickins  * appended to the swap_map, after swap_map is quiesced, before vfree'ing it.
3265570a335bSHugh Dickins  */
3266570a335bSHugh Dickins static void free_swap_count_continuations(struct swap_info_struct *si)
3267570a335bSHugh Dickins {
3268570a335bSHugh Dickins 	pgoff_t offset;
3269570a335bSHugh Dickins 
3270570a335bSHugh Dickins 	for (offset = 0; offset < si->max; offset += PAGE_SIZE) {
3271570a335bSHugh Dickins 		struct page *head;
3272570a335bSHugh Dickins 		head = vmalloc_to_page(si->swap_map + offset);
3273570a335bSHugh Dickins 		if (page_private(head)) {
32740d576d20SGeliang Tang 			struct page *page, *next;
32750d576d20SGeliang Tang 
32760d576d20SGeliang Tang 			list_for_each_entry_safe(page, next, &head->lru, lru) {
32770d576d20SGeliang Tang 				list_del(&page->lru);
3278570a335bSHugh Dickins 				__free_page(page);
3279570a335bSHugh Dickins 			}
3280570a335bSHugh Dickins 		}
3281570a335bSHugh Dickins 	}
3282570a335bSHugh Dickins }
3283