xref: /openbmc/linux/mm/swapfile.c (revision 960087445cd263c30ecc32b9e218887a349597ce)
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>
96e84f315SIngo Molnar #include <linux/sched/mm.h>
1029930025SIngo Molnar #include <linux/sched/task.h>
111da177e4SLinus Torvalds #include <linux/hugetlb.h>
121da177e4SLinus Torvalds #include <linux/mman.h>
131da177e4SLinus Torvalds #include <linux/slab.h>
141da177e4SLinus Torvalds #include <linux/kernel_stat.h>
151da177e4SLinus Torvalds #include <linux/swap.h>
161da177e4SLinus Torvalds #include <linux/vmalloc.h>
171da177e4SLinus Torvalds #include <linux/pagemap.h>
181da177e4SLinus Torvalds #include <linux/namei.h>
19072441e2SHugh Dickins #include <linux/shmem_fs.h>
201da177e4SLinus Torvalds #include <linux/blkdev.h>
2120137a49SHugh Dickins #include <linux/random.h>
221da177e4SLinus Torvalds #include <linux/writeback.h>
231da177e4SLinus Torvalds #include <linux/proc_fs.h>
241da177e4SLinus Torvalds #include <linux/seq_file.h>
251da177e4SLinus Torvalds #include <linux/init.h>
265ad64688SHugh Dickins #include <linux/ksm.h>
271da177e4SLinus Torvalds #include <linux/rmap.h>
281da177e4SLinus Torvalds #include <linux/security.h>
291da177e4SLinus Torvalds #include <linux/backing-dev.h>
30fc0abb14SIngo Molnar #include <linux/mutex.h>
31c59ede7bSRandy.Dunlap #include <linux/capability.h>
321da177e4SLinus Torvalds #include <linux/syscalls.h>
338a9f3ccdSBalbir Singh #include <linux/memcontrol.h>
3466d7dd51SKay Sievers #include <linux/poll.h>
3572788c38SDavid Rientjes #include <linux/oom.h>
3638b5faf4SDan Magenheimer #include <linux/frontswap.h>
3738b5faf4SDan Magenheimer #include <linux/swapfile.h>
38f981c595SMel Gorman #include <linux/export.h>
3967afa38eSTim Chen #include <linux/swap_slots.h>
40155b5f88SHuang Ying #include <linux/sort.h>
411da177e4SLinus Torvalds 
421da177e4SLinus Torvalds #include <asm/pgtable.h>
431da177e4SLinus Torvalds #include <asm/tlbflush.h>
441da177e4SLinus Torvalds #include <linux/swapops.h>
455d1ea48bSJohannes Weiner #include <linux/swap_cgroup.h>
461da177e4SLinus Torvalds 
47570a335bSHugh Dickins static bool swap_count_continued(struct swap_info_struct *, pgoff_t,
48570a335bSHugh Dickins 				 unsigned char);
49570a335bSHugh Dickins static void free_swap_count_continuations(struct swap_info_struct *);
50d4906e1aSLee Schermerhorn static sector_t map_swap_entry(swp_entry_t, struct block_device**);
51570a335bSHugh Dickins 
5238b5faf4SDan Magenheimer DEFINE_SPINLOCK(swap_lock);
537c363b8cSAdrian Bunk static unsigned int nr_swapfiles;
54ec8acf20SShaohua Li atomic_long_t nr_swap_pages;
55fb0fec50SChris Wilson /*
56fb0fec50SChris Wilson  * Some modules use swappable objects and may try to swap them out under
57fb0fec50SChris Wilson  * memory pressure (via the shrinker). Before doing so, they may wish to
58fb0fec50SChris Wilson  * check to see if any swap space is available.
59fb0fec50SChris Wilson  */
60fb0fec50SChris Wilson EXPORT_SYMBOL_GPL(nr_swap_pages);
61ec8acf20SShaohua Li /* protected with swap_lock. reading in vm_swap_full() doesn't need lock */
621da177e4SLinus Torvalds long total_swap_pages;
63a2468cc9SAaron Lu static int least_priority = -1;
641da177e4SLinus Torvalds 
651da177e4SLinus Torvalds static const char Bad_file[] = "Bad swap file entry ";
661da177e4SLinus Torvalds static const char Unused_file[] = "Unused swap file entry ";
671da177e4SLinus Torvalds static const char Bad_offset[] = "Bad swap offset entry ";
681da177e4SLinus Torvalds static const char Unused_offset[] = "Unused swap offset entry ";
691da177e4SLinus Torvalds 
70adfab836SDan Streetman /*
71adfab836SDan Streetman  * all active swap_info_structs
72adfab836SDan Streetman  * protected with swap_lock, and ordered by priority.
73adfab836SDan Streetman  */
7418ab4d4cSDan Streetman PLIST_HEAD(swap_active_head);
7518ab4d4cSDan Streetman 
7618ab4d4cSDan Streetman /*
7718ab4d4cSDan Streetman  * all available (active, not full) swap_info_structs
7818ab4d4cSDan Streetman  * protected with swap_avail_lock, ordered by priority.
7918ab4d4cSDan Streetman  * This is used by get_swap_page() instead of swap_active_head
8018ab4d4cSDan Streetman  * because swap_active_head includes all swap_info_structs,
8118ab4d4cSDan Streetman  * but get_swap_page() doesn't need to look at full ones.
8218ab4d4cSDan Streetman  * This uses its own lock instead of swap_lock because when a
8318ab4d4cSDan Streetman  * swap_info_struct changes between not-full/full, it needs to
8418ab4d4cSDan Streetman  * add/remove itself to/from this list, but the swap_info_struct->lock
8518ab4d4cSDan Streetman  * is held and the locking order requires swap_lock to be taken
8618ab4d4cSDan Streetman  * before any swap_info_struct->lock.
8718ab4d4cSDan Streetman  */
88bfc6b1caSColin Ian King static struct plist_head *swap_avail_heads;
8918ab4d4cSDan Streetman static DEFINE_SPINLOCK(swap_avail_lock);
901da177e4SLinus Torvalds 
9138b5faf4SDan Magenheimer struct swap_info_struct *swap_info[MAX_SWAPFILES];
921da177e4SLinus Torvalds 
93fc0abb14SIngo Molnar static DEFINE_MUTEX(swapon_mutex);
941da177e4SLinus Torvalds 
9566d7dd51SKay Sievers static DECLARE_WAIT_QUEUE_HEAD(proc_poll_wait);
9666d7dd51SKay Sievers /* Activity counter to indicate that a swapon or swapoff has occurred */
9766d7dd51SKay Sievers static atomic_t proc_poll_event = ATOMIC_INIT(0);
9866d7dd51SKay Sievers 
9981a0298bSHuang Ying atomic_t nr_rotate_swap = ATOMIC_INIT(0);
10081a0298bSHuang Ying 
101c10d38ccSDaniel Jordan static struct swap_info_struct *swap_type_to_swap_info(int type)
102c10d38ccSDaniel Jordan {
103c10d38ccSDaniel Jordan 	if (type >= READ_ONCE(nr_swapfiles))
104c10d38ccSDaniel Jordan 		return NULL;
105c10d38ccSDaniel Jordan 
106c10d38ccSDaniel Jordan 	smp_rmb();	/* Pairs with smp_wmb in alloc_swap_info. */
107c10d38ccSDaniel Jordan 	return READ_ONCE(swap_info[type]);
108c10d38ccSDaniel Jordan }
109c10d38ccSDaniel Jordan 
1108d69aaeeSHugh Dickins static inline unsigned char swap_count(unsigned char ent)
111355cfa73SKAMEZAWA Hiroyuki {
112955c97f0SDaniel Jordan 	return ent & ~SWAP_HAS_CACHE;	/* may include COUNT_CONTINUED flag */
113355cfa73SKAMEZAWA Hiroyuki }
114355cfa73SKAMEZAWA Hiroyuki 
115bcd49e86SHuang Ying /* Reclaim the swap entry anyway if possible */
116bcd49e86SHuang Ying #define TTRS_ANYWAY		0x1
117bcd49e86SHuang Ying /*
118bcd49e86SHuang Ying  * Reclaim the swap entry if there are no more mappings of the
119bcd49e86SHuang Ying  * corresponding page
120bcd49e86SHuang Ying  */
121bcd49e86SHuang Ying #define TTRS_UNMAPPED		0x2
122bcd49e86SHuang Ying /* Reclaim the swap entry if swap is getting full*/
123bcd49e86SHuang Ying #define TTRS_FULL		0x4
124bcd49e86SHuang Ying 
125efa90a98SHugh Dickins /* returns 1 if swap entry is freed */
126bcd49e86SHuang Ying static int __try_to_reclaim_swap(struct swap_info_struct *si,
127bcd49e86SHuang Ying 				 unsigned long offset, unsigned long flags)
128c9e44410SKAMEZAWA Hiroyuki {
129efa90a98SHugh Dickins 	swp_entry_t entry = swp_entry(si->type, offset);
130c9e44410SKAMEZAWA Hiroyuki 	struct page *page;
131c9e44410SKAMEZAWA Hiroyuki 	int ret = 0;
132c9e44410SKAMEZAWA Hiroyuki 
133bcd49e86SHuang Ying 	page = find_get_page(swap_address_space(entry), offset);
134c9e44410SKAMEZAWA Hiroyuki 	if (!page)
135c9e44410SKAMEZAWA Hiroyuki 		return 0;
136c9e44410SKAMEZAWA Hiroyuki 	/*
137bcd49e86SHuang Ying 	 * When this function is called from scan_swap_map_slots() and it's
138bcd49e86SHuang Ying 	 * called by vmscan.c at reclaiming pages. So, we hold a lock on a page,
139bcd49e86SHuang Ying 	 * here. We have to use trylock for avoiding deadlock. This is a special
140c9e44410SKAMEZAWA Hiroyuki 	 * case and you should use try_to_free_swap() with explicit lock_page()
141c9e44410SKAMEZAWA Hiroyuki 	 * in usual operations.
142c9e44410SKAMEZAWA Hiroyuki 	 */
143c9e44410SKAMEZAWA Hiroyuki 	if (trylock_page(page)) {
144bcd49e86SHuang Ying 		if ((flags & TTRS_ANYWAY) ||
145bcd49e86SHuang Ying 		    ((flags & TTRS_UNMAPPED) && !page_mapped(page)) ||
146bcd49e86SHuang Ying 		    ((flags & TTRS_FULL) && mem_cgroup_swap_full(page)))
147c9e44410SKAMEZAWA Hiroyuki 			ret = try_to_free_swap(page);
148c9e44410SKAMEZAWA Hiroyuki 		unlock_page(page);
149c9e44410SKAMEZAWA Hiroyuki 	}
15009cbfeafSKirill A. Shutemov 	put_page(page);
151c9e44410SKAMEZAWA Hiroyuki 	return ret;
152c9e44410SKAMEZAWA Hiroyuki }
153355cfa73SKAMEZAWA Hiroyuki 
1541da177e4SLinus Torvalds /*
1556a6ba831SHugh Dickins  * swapon tell device that all the old swap contents can be discarded,
1566a6ba831SHugh Dickins  * to allow the swap device to optimize its wear-levelling.
1576a6ba831SHugh Dickins  */
1586a6ba831SHugh Dickins static int discard_swap(struct swap_info_struct *si)
1596a6ba831SHugh Dickins {
1606a6ba831SHugh Dickins 	struct swap_extent *se;
1619625a5f2SHugh Dickins 	sector_t start_block;
1629625a5f2SHugh Dickins 	sector_t nr_blocks;
1636a6ba831SHugh Dickins 	int err = 0;
1646a6ba831SHugh Dickins 
1656a6ba831SHugh Dickins 	/* Do not discard the swap header page! */
1669625a5f2SHugh Dickins 	se = &si->first_swap_extent;
1679625a5f2SHugh Dickins 	start_block = (se->start_block + 1) << (PAGE_SHIFT - 9);
1689625a5f2SHugh Dickins 	nr_blocks = ((sector_t)se->nr_pages - 1) << (PAGE_SHIFT - 9);
1699625a5f2SHugh Dickins 	if (nr_blocks) {
1709625a5f2SHugh Dickins 		err = blkdev_issue_discard(si->bdev, start_block,
171dd3932edSChristoph Hellwig 				nr_blocks, GFP_KERNEL, 0);
1729625a5f2SHugh Dickins 		if (err)
1739625a5f2SHugh Dickins 			return err;
1749625a5f2SHugh Dickins 		cond_resched();
1756a6ba831SHugh Dickins 	}
1766a6ba831SHugh Dickins 
1779625a5f2SHugh Dickins 	list_for_each_entry(se, &si->first_swap_extent.list, list) {
1789625a5f2SHugh Dickins 		start_block = se->start_block << (PAGE_SHIFT - 9);
1799625a5f2SHugh Dickins 		nr_blocks = (sector_t)se->nr_pages << (PAGE_SHIFT - 9);
1809625a5f2SHugh Dickins 
1816a6ba831SHugh Dickins 		err = blkdev_issue_discard(si->bdev, start_block,
182dd3932edSChristoph Hellwig 				nr_blocks, GFP_KERNEL, 0);
1836a6ba831SHugh Dickins 		if (err)
1846a6ba831SHugh Dickins 			break;
1856a6ba831SHugh Dickins 
1866a6ba831SHugh Dickins 		cond_resched();
1876a6ba831SHugh Dickins 	}
1886a6ba831SHugh Dickins 	return err;		/* That will often be -EOPNOTSUPP */
1896a6ba831SHugh Dickins }
1906a6ba831SHugh Dickins 
1917992fde7SHugh Dickins /*
1927992fde7SHugh Dickins  * swap allocation tell device that a cluster of swap can now be discarded,
1937992fde7SHugh Dickins  * to allow the swap device to optimize its wear-levelling.
1947992fde7SHugh Dickins  */
1957992fde7SHugh Dickins static void discard_swap_cluster(struct swap_info_struct *si,
1967992fde7SHugh Dickins 				 pgoff_t start_page, pgoff_t nr_pages)
1977992fde7SHugh Dickins {
1987992fde7SHugh Dickins 	struct swap_extent *se = si->curr_swap_extent;
1997992fde7SHugh Dickins 	int found_extent = 0;
2007992fde7SHugh Dickins 
2017992fde7SHugh Dickins 	while (nr_pages) {
2027992fde7SHugh Dickins 		if (se->start_page <= start_page &&
2037992fde7SHugh Dickins 		    start_page < se->start_page + se->nr_pages) {
2047992fde7SHugh Dickins 			pgoff_t offset = start_page - se->start_page;
2057992fde7SHugh Dickins 			sector_t start_block = se->start_block + offset;
206858a2990SHugh Dickins 			sector_t nr_blocks = se->nr_pages - offset;
2077992fde7SHugh Dickins 
2087992fde7SHugh Dickins 			if (nr_blocks > nr_pages)
2097992fde7SHugh Dickins 				nr_blocks = nr_pages;
2107992fde7SHugh Dickins 			start_page += nr_blocks;
2117992fde7SHugh Dickins 			nr_pages -= nr_blocks;
2127992fde7SHugh Dickins 
2137992fde7SHugh Dickins 			if (!found_extent++)
2147992fde7SHugh Dickins 				si->curr_swap_extent = se;
2157992fde7SHugh Dickins 
2167992fde7SHugh Dickins 			start_block <<= PAGE_SHIFT - 9;
2177992fde7SHugh Dickins 			nr_blocks <<= PAGE_SHIFT - 9;
2187992fde7SHugh Dickins 			if (blkdev_issue_discard(si->bdev, start_block,
219dd3932edSChristoph Hellwig 				    nr_blocks, GFP_NOIO, 0))
2207992fde7SHugh Dickins 				break;
2217992fde7SHugh Dickins 		}
2227992fde7SHugh Dickins 
223a8ae4991SGeliang Tang 		se = list_next_entry(se, list);
2247992fde7SHugh Dickins 	}
2257992fde7SHugh Dickins }
2267992fde7SHugh Dickins 
22738d8b4e6SHuang Ying #ifdef CONFIG_THP_SWAP
22838d8b4e6SHuang Ying #define SWAPFILE_CLUSTER	HPAGE_PMD_NR
229a448f2d0SHuang Ying 
230a448f2d0SHuang Ying #define swap_entry_size(size)	(size)
23138d8b4e6SHuang Ying #else
232048c27fdSHugh Dickins #define SWAPFILE_CLUSTER	256
233a448f2d0SHuang Ying 
234a448f2d0SHuang Ying /*
235a448f2d0SHuang Ying  * Define swap_entry_size() as constant to let compiler to optimize
236a448f2d0SHuang Ying  * out some code if !CONFIG_THP_SWAP
237a448f2d0SHuang Ying  */
238a448f2d0SHuang Ying #define swap_entry_size(size)	1
23938d8b4e6SHuang Ying #endif
240048c27fdSHugh Dickins #define LATENCY_LIMIT		256
241048c27fdSHugh Dickins 
2422a8f9449SShaohua Li static inline void cluster_set_flag(struct swap_cluster_info *info,
2432a8f9449SShaohua Li 	unsigned int flag)
2442a8f9449SShaohua Li {
2452a8f9449SShaohua Li 	info->flags = flag;
2462a8f9449SShaohua Li }
2472a8f9449SShaohua Li 
2482a8f9449SShaohua Li static inline unsigned int cluster_count(struct swap_cluster_info *info)
2492a8f9449SShaohua Li {
2502a8f9449SShaohua Li 	return info->data;
2512a8f9449SShaohua Li }
2522a8f9449SShaohua Li 
2532a8f9449SShaohua Li static inline void cluster_set_count(struct swap_cluster_info *info,
2542a8f9449SShaohua Li 				     unsigned int c)
2552a8f9449SShaohua Li {
2562a8f9449SShaohua Li 	info->data = c;
2572a8f9449SShaohua Li }
2582a8f9449SShaohua Li 
2592a8f9449SShaohua Li static inline void cluster_set_count_flag(struct swap_cluster_info *info,
2602a8f9449SShaohua Li 					 unsigned int c, unsigned int f)
2612a8f9449SShaohua Li {
2622a8f9449SShaohua Li 	info->flags = f;
2632a8f9449SShaohua Li 	info->data = c;
2642a8f9449SShaohua Li }
2652a8f9449SShaohua Li 
2662a8f9449SShaohua Li static inline unsigned int cluster_next(struct swap_cluster_info *info)
2672a8f9449SShaohua Li {
2682a8f9449SShaohua Li 	return info->data;
2692a8f9449SShaohua Li }
2702a8f9449SShaohua Li 
2712a8f9449SShaohua Li static inline void cluster_set_next(struct swap_cluster_info *info,
2722a8f9449SShaohua Li 				    unsigned int n)
2732a8f9449SShaohua Li {
2742a8f9449SShaohua Li 	info->data = n;
2752a8f9449SShaohua Li }
2762a8f9449SShaohua Li 
2772a8f9449SShaohua Li static inline void cluster_set_next_flag(struct swap_cluster_info *info,
2782a8f9449SShaohua Li 					 unsigned int n, unsigned int f)
2792a8f9449SShaohua Li {
2802a8f9449SShaohua Li 	info->flags = f;
2812a8f9449SShaohua Li 	info->data = n;
2822a8f9449SShaohua Li }
2832a8f9449SShaohua Li 
2842a8f9449SShaohua Li static inline bool cluster_is_free(struct swap_cluster_info *info)
2852a8f9449SShaohua Li {
2862a8f9449SShaohua Li 	return info->flags & CLUSTER_FLAG_FREE;
2872a8f9449SShaohua Li }
2882a8f9449SShaohua Li 
2892a8f9449SShaohua Li static inline bool cluster_is_null(struct swap_cluster_info *info)
2902a8f9449SShaohua Li {
2912a8f9449SShaohua Li 	return info->flags & CLUSTER_FLAG_NEXT_NULL;
2922a8f9449SShaohua Li }
2932a8f9449SShaohua Li 
2942a8f9449SShaohua Li static inline void cluster_set_null(struct swap_cluster_info *info)
2952a8f9449SShaohua Li {
2962a8f9449SShaohua Li 	info->flags = CLUSTER_FLAG_NEXT_NULL;
2972a8f9449SShaohua Li 	info->data = 0;
2982a8f9449SShaohua Li }
2992a8f9449SShaohua Li 
300e0709829SHuang Ying static inline bool cluster_is_huge(struct swap_cluster_info *info)
301e0709829SHuang Ying {
30233ee011eSHuang Ying 	if (IS_ENABLED(CONFIG_THP_SWAP))
303e0709829SHuang Ying 		return info->flags & CLUSTER_FLAG_HUGE;
30433ee011eSHuang Ying 	return false;
305e0709829SHuang Ying }
306e0709829SHuang Ying 
307e0709829SHuang Ying static inline void cluster_clear_huge(struct swap_cluster_info *info)
308e0709829SHuang Ying {
309e0709829SHuang Ying 	info->flags &= ~CLUSTER_FLAG_HUGE;
310e0709829SHuang Ying }
311e0709829SHuang Ying 
312235b6217SHuang, Ying static inline struct swap_cluster_info *lock_cluster(struct swap_info_struct *si,
313235b6217SHuang, Ying 						     unsigned long offset)
314235b6217SHuang, Ying {
315235b6217SHuang, Ying 	struct swap_cluster_info *ci;
316235b6217SHuang, Ying 
317235b6217SHuang, Ying 	ci = si->cluster_info;
318235b6217SHuang, Ying 	if (ci) {
319235b6217SHuang, Ying 		ci += offset / SWAPFILE_CLUSTER;
320235b6217SHuang, Ying 		spin_lock(&ci->lock);
321235b6217SHuang, Ying 	}
322235b6217SHuang, Ying 	return ci;
323235b6217SHuang, Ying }
324235b6217SHuang, Ying 
325235b6217SHuang, Ying static inline void unlock_cluster(struct swap_cluster_info *ci)
326235b6217SHuang, Ying {
327235b6217SHuang, Ying 	if (ci)
328235b6217SHuang, Ying 		spin_unlock(&ci->lock);
329235b6217SHuang, Ying }
330235b6217SHuang, Ying 
33159d98bf3SHuang Ying /*
33259d98bf3SHuang Ying  * Determine the locking method in use for this device.  Return
33359d98bf3SHuang Ying  * swap_cluster_info if SSD-style cluster-based locking is in place.
33459d98bf3SHuang Ying  */
335235b6217SHuang, Ying static inline struct swap_cluster_info *lock_cluster_or_swap_info(
33659d98bf3SHuang Ying 		struct swap_info_struct *si, unsigned long offset)
337235b6217SHuang, Ying {
338235b6217SHuang, Ying 	struct swap_cluster_info *ci;
339235b6217SHuang, Ying 
34059d98bf3SHuang Ying 	/* Try to use fine-grained SSD-style locking if available: */
341235b6217SHuang, Ying 	ci = lock_cluster(si, offset);
34259d98bf3SHuang Ying 	/* Otherwise, fall back to traditional, coarse locking: */
343235b6217SHuang, Ying 	if (!ci)
344235b6217SHuang, Ying 		spin_lock(&si->lock);
345235b6217SHuang, Ying 
346235b6217SHuang, Ying 	return ci;
347235b6217SHuang, Ying }
348235b6217SHuang, Ying 
349235b6217SHuang, Ying static inline void unlock_cluster_or_swap_info(struct swap_info_struct *si,
350235b6217SHuang, Ying 					       struct swap_cluster_info *ci)
351235b6217SHuang, Ying {
352235b6217SHuang, Ying 	if (ci)
353235b6217SHuang, Ying 		unlock_cluster(ci);
354235b6217SHuang, Ying 	else
355235b6217SHuang, Ying 		spin_unlock(&si->lock);
356235b6217SHuang, Ying }
357235b6217SHuang, Ying 
3586b534915SHuang Ying static inline bool cluster_list_empty(struct swap_cluster_list *list)
3596b534915SHuang Ying {
3606b534915SHuang Ying 	return cluster_is_null(&list->head);
3616b534915SHuang Ying }
3626b534915SHuang Ying 
3636b534915SHuang Ying static inline unsigned int cluster_list_first(struct swap_cluster_list *list)
3646b534915SHuang Ying {
3656b534915SHuang Ying 	return cluster_next(&list->head);
3666b534915SHuang Ying }
3676b534915SHuang Ying 
3686b534915SHuang Ying static void cluster_list_init(struct swap_cluster_list *list)
3696b534915SHuang Ying {
3706b534915SHuang Ying 	cluster_set_null(&list->head);
3716b534915SHuang Ying 	cluster_set_null(&list->tail);
3726b534915SHuang Ying }
3736b534915SHuang Ying 
3746b534915SHuang Ying static void cluster_list_add_tail(struct swap_cluster_list *list,
3756b534915SHuang Ying 				  struct swap_cluster_info *ci,
3766b534915SHuang Ying 				  unsigned int idx)
3776b534915SHuang Ying {
3786b534915SHuang Ying 	if (cluster_list_empty(list)) {
3796b534915SHuang Ying 		cluster_set_next_flag(&list->head, idx, 0);
3806b534915SHuang Ying 		cluster_set_next_flag(&list->tail, idx, 0);
3816b534915SHuang Ying 	} else {
382235b6217SHuang, Ying 		struct swap_cluster_info *ci_tail;
3836b534915SHuang Ying 		unsigned int tail = cluster_next(&list->tail);
3846b534915SHuang Ying 
385235b6217SHuang, Ying 		/*
386235b6217SHuang, Ying 		 * Nested cluster lock, but both cluster locks are
387235b6217SHuang, Ying 		 * only acquired when we held swap_info_struct->lock
388235b6217SHuang, Ying 		 */
389235b6217SHuang, Ying 		ci_tail = ci + tail;
390235b6217SHuang, Ying 		spin_lock_nested(&ci_tail->lock, SINGLE_DEPTH_NESTING);
391235b6217SHuang, Ying 		cluster_set_next(ci_tail, idx);
3920ef017d1SHuang Ying 		spin_unlock(&ci_tail->lock);
3936b534915SHuang Ying 		cluster_set_next_flag(&list->tail, idx, 0);
3946b534915SHuang Ying 	}
3956b534915SHuang Ying }
3966b534915SHuang Ying 
3976b534915SHuang Ying static unsigned int cluster_list_del_first(struct swap_cluster_list *list,
3986b534915SHuang Ying 					   struct swap_cluster_info *ci)
3996b534915SHuang Ying {
4006b534915SHuang Ying 	unsigned int idx;
4016b534915SHuang Ying 
4026b534915SHuang Ying 	idx = cluster_next(&list->head);
4036b534915SHuang Ying 	if (cluster_next(&list->tail) == idx) {
4046b534915SHuang Ying 		cluster_set_null(&list->head);
4056b534915SHuang Ying 		cluster_set_null(&list->tail);
4066b534915SHuang Ying 	} else
4076b534915SHuang Ying 		cluster_set_next_flag(&list->head,
4086b534915SHuang Ying 				      cluster_next(&ci[idx]), 0);
4096b534915SHuang Ying 
4106b534915SHuang Ying 	return idx;
4116b534915SHuang Ying }
4126b534915SHuang Ying 
413815c2c54SShaohua Li /* Add a cluster to discard list and schedule it to do discard */
414815c2c54SShaohua Li static void swap_cluster_schedule_discard(struct swap_info_struct *si,
415815c2c54SShaohua Li 		unsigned int idx)
416815c2c54SShaohua Li {
417815c2c54SShaohua Li 	/*
418815c2c54SShaohua Li 	 * If scan_swap_map() can't find a free cluster, it will check
419815c2c54SShaohua Li 	 * si->swap_map directly. To make sure the discarding cluster isn't
420815c2c54SShaohua Li 	 * taken by scan_swap_map(), mark the swap entries bad (occupied). It
421815c2c54SShaohua Li 	 * will be cleared after discard
422815c2c54SShaohua Li 	 */
423815c2c54SShaohua Li 	memset(si->swap_map + idx * SWAPFILE_CLUSTER,
424815c2c54SShaohua Li 			SWAP_MAP_BAD, SWAPFILE_CLUSTER);
425815c2c54SShaohua Li 
4266b534915SHuang Ying 	cluster_list_add_tail(&si->discard_clusters, si->cluster_info, idx);
427815c2c54SShaohua Li 
428815c2c54SShaohua Li 	schedule_work(&si->discard_work);
429815c2c54SShaohua Li }
430815c2c54SShaohua Li 
43138d8b4e6SHuang Ying static void __free_cluster(struct swap_info_struct *si, unsigned long idx)
43238d8b4e6SHuang Ying {
43338d8b4e6SHuang Ying 	struct swap_cluster_info *ci = si->cluster_info;
43438d8b4e6SHuang Ying 
43538d8b4e6SHuang Ying 	cluster_set_flag(ci + idx, CLUSTER_FLAG_FREE);
43638d8b4e6SHuang Ying 	cluster_list_add_tail(&si->free_clusters, ci, idx);
43738d8b4e6SHuang Ying }
43838d8b4e6SHuang Ying 
439815c2c54SShaohua Li /*
440815c2c54SShaohua Li  * Doing discard actually. After a cluster discard is finished, the cluster
441815c2c54SShaohua Li  * will be added to free cluster list. caller should hold si->lock.
442815c2c54SShaohua Li */
443815c2c54SShaohua Li static void swap_do_scheduled_discard(struct swap_info_struct *si)
444815c2c54SShaohua Li {
445235b6217SHuang, Ying 	struct swap_cluster_info *info, *ci;
446815c2c54SShaohua Li 	unsigned int idx;
447815c2c54SShaohua Li 
448815c2c54SShaohua Li 	info = si->cluster_info;
449815c2c54SShaohua Li 
4506b534915SHuang Ying 	while (!cluster_list_empty(&si->discard_clusters)) {
4516b534915SHuang Ying 		idx = cluster_list_del_first(&si->discard_clusters, info);
452815c2c54SShaohua Li 		spin_unlock(&si->lock);
453815c2c54SShaohua Li 
454815c2c54SShaohua Li 		discard_swap_cluster(si, idx * SWAPFILE_CLUSTER,
455815c2c54SShaohua Li 				SWAPFILE_CLUSTER);
456815c2c54SShaohua Li 
457815c2c54SShaohua Li 		spin_lock(&si->lock);
458235b6217SHuang, Ying 		ci = lock_cluster(si, idx * SWAPFILE_CLUSTER);
45938d8b4e6SHuang Ying 		__free_cluster(si, idx);
460815c2c54SShaohua Li 		memset(si->swap_map + idx * SWAPFILE_CLUSTER,
461815c2c54SShaohua Li 				0, SWAPFILE_CLUSTER);
462235b6217SHuang, Ying 		unlock_cluster(ci);
463815c2c54SShaohua Li 	}
464815c2c54SShaohua Li }
465815c2c54SShaohua Li 
466815c2c54SShaohua Li static void swap_discard_work(struct work_struct *work)
467815c2c54SShaohua Li {
468815c2c54SShaohua Li 	struct swap_info_struct *si;
469815c2c54SShaohua Li 
470815c2c54SShaohua Li 	si = container_of(work, struct swap_info_struct, discard_work);
471815c2c54SShaohua Li 
472815c2c54SShaohua Li 	spin_lock(&si->lock);
473815c2c54SShaohua Li 	swap_do_scheduled_discard(si);
474815c2c54SShaohua Li 	spin_unlock(&si->lock);
475815c2c54SShaohua Li }
476815c2c54SShaohua Li 
47738d8b4e6SHuang Ying static void alloc_cluster(struct swap_info_struct *si, unsigned long idx)
47838d8b4e6SHuang Ying {
47938d8b4e6SHuang Ying 	struct swap_cluster_info *ci = si->cluster_info;
48038d8b4e6SHuang Ying 
48138d8b4e6SHuang Ying 	VM_BUG_ON(cluster_list_first(&si->free_clusters) != idx);
48238d8b4e6SHuang Ying 	cluster_list_del_first(&si->free_clusters, ci);
48338d8b4e6SHuang Ying 	cluster_set_count_flag(ci + idx, 0, 0);
48438d8b4e6SHuang Ying }
48538d8b4e6SHuang Ying 
48638d8b4e6SHuang Ying static void free_cluster(struct swap_info_struct *si, unsigned long idx)
48738d8b4e6SHuang Ying {
48838d8b4e6SHuang Ying 	struct swap_cluster_info *ci = si->cluster_info + idx;
48938d8b4e6SHuang Ying 
49038d8b4e6SHuang Ying 	VM_BUG_ON(cluster_count(ci) != 0);
49138d8b4e6SHuang Ying 	/*
49238d8b4e6SHuang Ying 	 * If the swap is discardable, prepare discard the cluster
49338d8b4e6SHuang Ying 	 * instead of free it immediately. The cluster will be freed
49438d8b4e6SHuang Ying 	 * after discard.
49538d8b4e6SHuang Ying 	 */
49638d8b4e6SHuang Ying 	if ((si->flags & (SWP_WRITEOK | SWP_PAGE_DISCARD)) ==
49738d8b4e6SHuang Ying 	    (SWP_WRITEOK | SWP_PAGE_DISCARD)) {
49838d8b4e6SHuang Ying 		swap_cluster_schedule_discard(si, idx);
49938d8b4e6SHuang Ying 		return;
50038d8b4e6SHuang Ying 	}
50138d8b4e6SHuang Ying 
50238d8b4e6SHuang Ying 	__free_cluster(si, idx);
50338d8b4e6SHuang Ying }
50438d8b4e6SHuang Ying 
5052a8f9449SShaohua Li /*
5062a8f9449SShaohua Li  * The cluster corresponding to page_nr will be used. The cluster will be
5072a8f9449SShaohua Li  * removed from free cluster list and its usage counter will be increased.
5082a8f9449SShaohua Li  */
5092a8f9449SShaohua Li static void inc_cluster_info_page(struct swap_info_struct *p,
5102a8f9449SShaohua Li 	struct swap_cluster_info *cluster_info, unsigned long page_nr)
5112a8f9449SShaohua Li {
5122a8f9449SShaohua Li 	unsigned long idx = page_nr / SWAPFILE_CLUSTER;
5132a8f9449SShaohua Li 
5142a8f9449SShaohua Li 	if (!cluster_info)
5152a8f9449SShaohua Li 		return;
51638d8b4e6SHuang Ying 	if (cluster_is_free(&cluster_info[idx]))
51738d8b4e6SHuang Ying 		alloc_cluster(p, idx);
5182a8f9449SShaohua Li 
5192a8f9449SShaohua Li 	VM_BUG_ON(cluster_count(&cluster_info[idx]) >= SWAPFILE_CLUSTER);
5202a8f9449SShaohua Li 	cluster_set_count(&cluster_info[idx],
5212a8f9449SShaohua Li 		cluster_count(&cluster_info[idx]) + 1);
5222a8f9449SShaohua Li }
5232a8f9449SShaohua Li 
5242a8f9449SShaohua Li /*
5252a8f9449SShaohua Li  * The cluster corresponding to page_nr decreases one usage. If the usage
5262a8f9449SShaohua Li  * counter becomes 0, which means no page in the cluster is in using, we can
5272a8f9449SShaohua Li  * optionally discard the cluster and add it to free cluster list.
5282a8f9449SShaohua Li  */
5292a8f9449SShaohua Li static void dec_cluster_info_page(struct swap_info_struct *p,
5302a8f9449SShaohua Li 	struct swap_cluster_info *cluster_info, unsigned long page_nr)
5312a8f9449SShaohua Li {
5322a8f9449SShaohua Li 	unsigned long idx = page_nr / SWAPFILE_CLUSTER;
5332a8f9449SShaohua Li 
5342a8f9449SShaohua Li 	if (!cluster_info)
5352a8f9449SShaohua Li 		return;
5362a8f9449SShaohua Li 
5372a8f9449SShaohua Li 	VM_BUG_ON(cluster_count(&cluster_info[idx]) == 0);
5382a8f9449SShaohua Li 	cluster_set_count(&cluster_info[idx],
5392a8f9449SShaohua Li 		cluster_count(&cluster_info[idx]) - 1);
5402a8f9449SShaohua Li 
54138d8b4e6SHuang Ying 	if (cluster_count(&cluster_info[idx]) == 0)
54238d8b4e6SHuang Ying 		free_cluster(p, idx);
5432a8f9449SShaohua Li }
5442a8f9449SShaohua Li 
5452a8f9449SShaohua Li /*
5462a8f9449SShaohua Li  * It's possible scan_swap_map() uses a free cluster in the middle of free
5472a8f9449SShaohua Li  * cluster list. Avoiding such abuse to avoid list corruption.
5482a8f9449SShaohua Li  */
549ebc2a1a6SShaohua Li static bool
550ebc2a1a6SShaohua Li scan_swap_map_ssd_cluster_conflict(struct swap_info_struct *si,
5512a8f9449SShaohua Li 	unsigned long offset)
5522a8f9449SShaohua Li {
553ebc2a1a6SShaohua Li 	struct percpu_cluster *percpu_cluster;
554ebc2a1a6SShaohua Li 	bool conflict;
555ebc2a1a6SShaohua Li 
5562a8f9449SShaohua Li 	offset /= SWAPFILE_CLUSTER;
5576b534915SHuang Ying 	conflict = !cluster_list_empty(&si->free_clusters) &&
5586b534915SHuang Ying 		offset != cluster_list_first(&si->free_clusters) &&
5592a8f9449SShaohua Li 		cluster_is_free(&si->cluster_info[offset]);
560ebc2a1a6SShaohua Li 
561ebc2a1a6SShaohua Li 	if (!conflict)
562ebc2a1a6SShaohua Li 		return false;
563ebc2a1a6SShaohua Li 
564ebc2a1a6SShaohua Li 	percpu_cluster = this_cpu_ptr(si->percpu_cluster);
565ebc2a1a6SShaohua Li 	cluster_set_null(&percpu_cluster->index);
566ebc2a1a6SShaohua Li 	return true;
567ebc2a1a6SShaohua Li }
568ebc2a1a6SShaohua Li 
569ebc2a1a6SShaohua Li /*
570ebc2a1a6SShaohua Li  * Try to get a swap entry from current cpu's swap entry pool (a cluster). This
571ebc2a1a6SShaohua Li  * might involve allocating a new cluster for current CPU too.
572ebc2a1a6SShaohua Li  */
57336005baeSTim Chen static bool scan_swap_map_try_ssd_cluster(struct swap_info_struct *si,
574ebc2a1a6SShaohua Li 	unsigned long *offset, unsigned long *scan_base)
575ebc2a1a6SShaohua Li {
576ebc2a1a6SShaohua Li 	struct percpu_cluster *cluster;
577235b6217SHuang, Ying 	struct swap_cluster_info *ci;
578ebc2a1a6SShaohua Li 	bool found_free;
579235b6217SHuang, Ying 	unsigned long tmp, max;
580ebc2a1a6SShaohua Li 
581ebc2a1a6SShaohua Li new_cluster:
582ebc2a1a6SShaohua Li 	cluster = this_cpu_ptr(si->percpu_cluster);
583ebc2a1a6SShaohua Li 	if (cluster_is_null(&cluster->index)) {
5846b534915SHuang Ying 		if (!cluster_list_empty(&si->free_clusters)) {
5856b534915SHuang Ying 			cluster->index = si->free_clusters.head;
586ebc2a1a6SShaohua Li 			cluster->next = cluster_next(&cluster->index) *
587ebc2a1a6SShaohua Li 					SWAPFILE_CLUSTER;
5886b534915SHuang Ying 		} else if (!cluster_list_empty(&si->discard_clusters)) {
589ebc2a1a6SShaohua Li 			/*
590ebc2a1a6SShaohua Li 			 * we don't have free cluster but have some clusters in
591ebc2a1a6SShaohua Li 			 * discarding, do discard now and reclaim them
592ebc2a1a6SShaohua Li 			 */
593ebc2a1a6SShaohua Li 			swap_do_scheduled_discard(si);
594ebc2a1a6SShaohua Li 			*scan_base = *offset = si->cluster_next;
595ebc2a1a6SShaohua Li 			goto new_cluster;
596ebc2a1a6SShaohua Li 		} else
59736005baeSTim Chen 			return false;
598ebc2a1a6SShaohua Li 	}
599ebc2a1a6SShaohua Li 
600ebc2a1a6SShaohua Li 	found_free = false;
601ebc2a1a6SShaohua Li 
602ebc2a1a6SShaohua Li 	/*
603ebc2a1a6SShaohua Li 	 * Other CPUs can use our cluster if they can't find a free cluster,
604ebc2a1a6SShaohua Li 	 * check if there is still free entry in the cluster
605ebc2a1a6SShaohua Li 	 */
606ebc2a1a6SShaohua Li 	tmp = cluster->next;
607235b6217SHuang, Ying 	max = min_t(unsigned long, si->max,
608235b6217SHuang, Ying 		    (cluster_next(&cluster->index) + 1) * SWAPFILE_CLUSTER);
609235b6217SHuang, Ying 	if (tmp >= max) {
610235b6217SHuang, Ying 		cluster_set_null(&cluster->index);
611235b6217SHuang, Ying 		goto new_cluster;
612235b6217SHuang, Ying 	}
613235b6217SHuang, Ying 	ci = lock_cluster(si, tmp);
614235b6217SHuang, Ying 	while (tmp < max) {
615ebc2a1a6SShaohua Li 		if (!si->swap_map[tmp]) {
616ebc2a1a6SShaohua Li 			found_free = true;
617ebc2a1a6SShaohua Li 			break;
618ebc2a1a6SShaohua Li 		}
619ebc2a1a6SShaohua Li 		tmp++;
620ebc2a1a6SShaohua Li 	}
621235b6217SHuang, Ying 	unlock_cluster(ci);
622ebc2a1a6SShaohua Li 	if (!found_free) {
623ebc2a1a6SShaohua Li 		cluster_set_null(&cluster->index);
624ebc2a1a6SShaohua Li 		goto new_cluster;
625ebc2a1a6SShaohua Li 	}
626ebc2a1a6SShaohua Li 	cluster->next = tmp + 1;
627ebc2a1a6SShaohua Li 	*offset = tmp;
628ebc2a1a6SShaohua Li 	*scan_base = tmp;
62936005baeSTim Chen 	return found_free;
6302a8f9449SShaohua Li }
6312a8f9449SShaohua Li 
632a2468cc9SAaron Lu static void __del_from_avail_list(struct swap_info_struct *p)
633a2468cc9SAaron Lu {
634a2468cc9SAaron Lu 	int nid;
635a2468cc9SAaron Lu 
636a2468cc9SAaron Lu 	for_each_node(nid)
637a2468cc9SAaron Lu 		plist_del(&p->avail_lists[nid], &swap_avail_heads[nid]);
638a2468cc9SAaron Lu }
639a2468cc9SAaron Lu 
640a2468cc9SAaron Lu static void del_from_avail_list(struct swap_info_struct *p)
641a2468cc9SAaron Lu {
642a2468cc9SAaron Lu 	spin_lock(&swap_avail_lock);
643a2468cc9SAaron Lu 	__del_from_avail_list(p);
644a2468cc9SAaron Lu 	spin_unlock(&swap_avail_lock);
645a2468cc9SAaron Lu }
646a2468cc9SAaron Lu 
64738d8b4e6SHuang Ying static void swap_range_alloc(struct swap_info_struct *si, unsigned long offset,
64838d8b4e6SHuang Ying 			     unsigned int nr_entries)
64938d8b4e6SHuang Ying {
65038d8b4e6SHuang Ying 	unsigned int end = offset + nr_entries - 1;
65138d8b4e6SHuang Ying 
65238d8b4e6SHuang Ying 	if (offset == si->lowest_bit)
65338d8b4e6SHuang Ying 		si->lowest_bit += nr_entries;
65438d8b4e6SHuang Ying 	if (end == si->highest_bit)
65538d8b4e6SHuang Ying 		si->highest_bit -= nr_entries;
65638d8b4e6SHuang Ying 	si->inuse_pages += nr_entries;
65738d8b4e6SHuang Ying 	if (si->inuse_pages == si->pages) {
65838d8b4e6SHuang Ying 		si->lowest_bit = si->max;
65938d8b4e6SHuang Ying 		si->highest_bit = 0;
660a2468cc9SAaron Lu 		del_from_avail_list(si);
66138d8b4e6SHuang Ying 	}
66238d8b4e6SHuang Ying }
66338d8b4e6SHuang Ying 
664a2468cc9SAaron Lu static void add_to_avail_list(struct swap_info_struct *p)
665a2468cc9SAaron Lu {
666a2468cc9SAaron Lu 	int nid;
667a2468cc9SAaron Lu 
668a2468cc9SAaron Lu 	spin_lock(&swap_avail_lock);
669a2468cc9SAaron Lu 	for_each_node(nid) {
670a2468cc9SAaron Lu 		WARN_ON(!plist_node_empty(&p->avail_lists[nid]));
671a2468cc9SAaron Lu 		plist_add(&p->avail_lists[nid], &swap_avail_heads[nid]);
672a2468cc9SAaron Lu 	}
673a2468cc9SAaron Lu 	spin_unlock(&swap_avail_lock);
674a2468cc9SAaron Lu }
675a2468cc9SAaron Lu 
67638d8b4e6SHuang Ying static void swap_range_free(struct swap_info_struct *si, unsigned long offset,
67738d8b4e6SHuang Ying 			    unsigned int nr_entries)
67838d8b4e6SHuang Ying {
67938d8b4e6SHuang Ying 	unsigned long end = offset + nr_entries - 1;
68038d8b4e6SHuang Ying 	void (*swap_slot_free_notify)(struct block_device *, unsigned long);
68138d8b4e6SHuang Ying 
68238d8b4e6SHuang Ying 	if (offset < si->lowest_bit)
68338d8b4e6SHuang Ying 		si->lowest_bit = offset;
68438d8b4e6SHuang Ying 	if (end > si->highest_bit) {
68538d8b4e6SHuang Ying 		bool was_full = !si->highest_bit;
68638d8b4e6SHuang Ying 
68738d8b4e6SHuang Ying 		si->highest_bit = end;
688a2468cc9SAaron Lu 		if (was_full && (si->flags & SWP_WRITEOK))
689a2468cc9SAaron Lu 			add_to_avail_list(si);
69038d8b4e6SHuang Ying 	}
69138d8b4e6SHuang Ying 	atomic_long_add(nr_entries, &nr_swap_pages);
69238d8b4e6SHuang Ying 	si->inuse_pages -= nr_entries;
69338d8b4e6SHuang Ying 	if (si->flags & SWP_BLKDEV)
69438d8b4e6SHuang Ying 		swap_slot_free_notify =
69538d8b4e6SHuang Ying 			si->bdev->bd_disk->fops->swap_slot_free_notify;
69638d8b4e6SHuang Ying 	else
69738d8b4e6SHuang Ying 		swap_slot_free_notify = NULL;
69838d8b4e6SHuang Ying 	while (offset <= end) {
69938d8b4e6SHuang Ying 		frontswap_invalidate_page(si->type, offset);
70038d8b4e6SHuang Ying 		if (swap_slot_free_notify)
70138d8b4e6SHuang Ying 			swap_slot_free_notify(si->bdev, offset);
70238d8b4e6SHuang Ying 		offset++;
70338d8b4e6SHuang Ying 	}
70438d8b4e6SHuang Ying }
70538d8b4e6SHuang Ying 
70636005baeSTim Chen static int scan_swap_map_slots(struct swap_info_struct *si,
70736005baeSTim Chen 			       unsigned char usage, int nr,
70836005baeSTim Chen 			       swp_entry_t slots[])
7091da177e4SLinus Torvalds {
710235b6217SHuang, Ying 	struct swap_cluster_info *ci;
711ebebbbe9SHugh Dickins 	unsigned long offset;
712c60aa176SHugh Dickins 	unsigned long scan_base;
7137992fde7SHugh Dickins 	unsigned long last_in_cluster = 0;
714048c27fdSHugh Dickins 	int latency_ration = LATENCY_LIMIT;
71536005baeSTim Chen 	int n_ret = 0;
71636005baeSTim Chen 
71736005baeSTim Chen 	if (nr > SWAP_BATCH)
71836005baeSTim Chen 		nr = SWAP_BATCH;
7191da177e4SLinus Torvalds 
7207dfad418SHugh Dickins 	/*
7217dfad418SHugh Dickins 	 * We try to cluster swap pages by allocating them sequentially
7227dfad418SHugh Dickins 	 * in swap.  Once we've allocated SWAPFILE_CLUSTER pages this
7237dfad418SHugh Dickins 	 * way, however, we resort to first-free allocation, starting
7247dfad418SHugh Dickins 	 * a new cluster.  This prevents us from scattering swap pages
7257dfad418SHugh Dickins 	 * all over the entire swap partition, so that we reduce
7267dfad418SHugh Dickins 	 * overall disk seek times between swap pages.  -- sct
7277dfad418SHugh Dickins 	 * But we do now try to find an empty cluster.  -Andrea
728c60aa176SHugh Dickins 	 * And we let swap pages go all over an SSD partition.  Hugh
7291da177e4SLinus Torvalds 	 */
7307dfad418SHugh Dickins 
73152b7efdbSHugh Dickins 	si->flags += SWP_SCANNING;
732c60aa176SHugh Dickins 	scan_base = offset = si->cluster_next;
733ebebbbe9SHugh Dickins 
734ebc2a1a6SShaohua Li 	/* SSD algorithm */
735ebc2a1a6SShaohua Li 	if (si->cluster_info) {
73636005baeSTim Chen 		if (scan_swap_map_try_ssd_cluster(si, &offset, &scan_base))
737815c2c54SShaohua Li 			goto checks;
73836005baeSTim Chen 		else
73936005baeSTim Chen 			goto scan;
740815c2c54SShaohua Li 	}
741815c2c54SShaohua Li 
742ebc2a1a6SShaohua Li 	if (unlikely(!si->cluster_nr--)) {
743ebc2a1a6SShaohua Li 		if (si->pages - si->inuse_pages < SWAPFILE_CLUSTER) {
744ebc2a1a6SShaohua Li 			si->cluster_nr = SWAPFILE_CLUSTER - 1;
7452a8f9449SShaohua Li 			goto checks;
7462a8f9449SShaohua Li 		}
7472a8f9449SShaohua Li 
748ec8acf20SShaohua Li 		spin_unlock(&si->lock);
7497dfad418SHugh Dickins 
750c60aa176SHugh Dickins 		/*
751c60aa176SHugh Dickins 		 * If seek is expensive, start searching for new cluster from
752c60aa176SHugh Dickins 		 * start of partition, to minimize the span of allocated swap.
75350088c44SChen Yucong 		 * If seek is cheap, that is the SWP_SOLIDSTATE si->cluster_info
75450088c44SChen Yucong 		 * case, just handled by scan_swap_map_try_ssd_cluster() above.
755c60aa176SHugh Dickins 		 */
756c60aa176SHugh Dickins 		scan_base = offset = si->lowest_bit;
7577dfad418SHugh Dickins 		last_in_cluster = offset + SWAPFILE_CLUSTER - 1;
7587dfad418SHugh Dickins 
7597dfad418SHugh Dickins 		/* Locate the first empty (unaligned) cluster */
7607dfad418SHugh Dickins 		for (; last_in_cluster <= si->highest_bit; offset++) {
7611da177e4SLinus Torvalds 			if (si->swap_map[offset])
7627dfad418SHugh Dickins 				last_in_cluster = offset + SWAPFILE_CLUSTER;
7637dfad418SHugh Dickins 			else if (offset == last_in_cluster) {
764ec8acf20SShaohua Li 				spin_lock(&si->lock);
765ebebbbe9SHugh Dickins 				offset -= SWAPFILE_CLUSTER - 1;
766ebebbbe9SHugh Dickins 				si->cluster_next = offset;
767ebebbbe9SHugh Dickins 				si->cluster_nr = SWAPFILE_CLUSTER - 1;
768ebebbbe9SHugh Dickins 				goto checks;
7697dfad418SHugh Dickins 			}
770048c27fdSHugh Dickins 			if (unlikely(--latency_ration < 0)) {
771048c27fdSHugh Dickins 				cond_resched();
772048c27fdSHugh Dickins 				latency_ration = LATENCY_LIMIT;
773048c27fdSHugh Dickins 			}
7747dfad418SHugh Dickins 		}
775ebebbbe9SHugh Dickins 
776c60aa176SHugh Dickins 		offset = scan_base;
777ec8acf20SShaohua Li 		spin_lock(&si->lock);
778ebebbbe9SHugh Dickins 		si->cluster_nr = SWAPFILE_CLUSTER - 1;
7797dfad418SHugh Dickins 	}
7807dfad418SHugh Dickins 
781ebebbbe9SHugh Dickins checks:
782ebc2a1a6SShaohua Li 	if (si->cluster_info) {
78336005baeSTim Chen 		while (scan_swap_map_ssd_cluster_conflict(si, offset)) {
78436005baeSTim Chen 		/* take a break if we already got some slots */
78536005baeSTim Chen 			if (n_ret)
78636005baeSTim Chen 				goto done;
78736005baeSTim Chen 			if (!scan_swap_map_try_ssd_cluster(si, &offset,
78836005baeSTim Chen 							&scan_base))
78936005baeSTim Chen 				goto scan;
79036005baeSTim Chen 		}
791ebc2a1a6SShaohua Li 	}
792ebebbbe9SHugh Dickins 	if (!(si->flags & SWP_WRITEOK))
79352b7efdbSHugh Dickins 		goto no_page;
7947dfad418SHugh Dickins 	if (!si->highest_bit)
7957dfad418SHugh Dickins 		goto no_page;
796ebebbbe9SHugh Dickins 	if (offset > si->highest_bit)
797c60aa176SHugh Dickins 		scan_base = offset = si->lowest_bit;
798c9e44410SKAMEZAWA Hiroyuki 
799235b6217SHuang, Ying 	ci = lock_cluster(si, offset);
800b73d7fceSHugh Dickins 	/* reuse swap entry of cache-only swap if not busy. */
801b73d7fceSHugh Dickins 	if (vm_swap_full() && si->swap_map[offset] == SWAP_HAS_CACHE) {
802c9e44410SKAMEZAWA Hiroyuki 		int swap_was_freed;
803235b6217SHuang, Ying 		unlock_cluster(ci);
804ec8acf20SShaohua Li 		spin_unlock(&si->lock);
805bcd49e86SHuang Ying 		swap_was_freed = __try_to_reclaim_swap(si, offset, TTRS_ANYWAY);
806ec8acf20SShaohua Li 		spin_lock(&si->lock);
807c9e44410SKAMEZAWA Hiroyuki 		/* entry was freed successfully, try to use this again */
808c9e44410SKAMEZAWA Hiroyuki 		if (swap_was_freed)
809c9e44410SKAMEZAWA Hiroyuki 			goto checks;
810c9e44410SKAMEZAWA Hiroyuki 		goto scan; /* check next one */
811c9e44410SKAMEZAWA Hiroyuki 	}
812c9e44410SKAMEZAWA Hiroyuki 
813235b6217SHuang, Ying 	if (si->swap_map[offset]) {
814235b6217SHuang, Ying 		unlock_cluster(ci);
81536005baeSTim Chen 		if (!n_ret)
816ebebbbe9SHugh Dickins 			goto scan;
81736005baeSTim Chen 		else
81836005baeSTim Chen 			goto done;
819235b6217SHuang, Ying 	}
8202872bb2dSHuang Ying 	si->swap_map[offset] = usage;
8212872bb2dSHuang Ying 	inc_cluster_info_page(si, si->cluster_info, offset);
8222872bb2dSHuang Ying 	unlock_cluster(ci);
823ebebbbe9SHugh Dickins 
82438d8b4e6SHuang Ying 	swap_range_alloc(si, offset, 1);
8251da177e4SLinus Torvalds 	si->cluster_next = offset + 1;
82636005baeSTim Chen 	slots[n_ret++] = swp_entry(si->type, offset);
8277992fde7SHugh Dickins 
82836005baeSTim Chen 	/* got enough slots or reach max slots? */
82936005baeSTim Chen 	if ((n_ret == nr) || (offset >= si->highest_bit))
83036005baeSTim Chen 		goto done;
83136005baeSTim Chen 
83236005baeSTim Chen 	/* search for next available slot */
83336005baeSTim Chen 
83436005baeSTim Chen 	/* time to take a break? */
83536005baeSTim Chen 	if (unlikely(--latency_ration < 0)) {
83636005baeSTim Chen 		if (n_ret)
83736005baeSTim Chen 			goto done;
83836005baeSTim Chen 		spin_unlock(&si->lock);
83936005baeSTim Chen 		cond_resched();
84036005baeSTim Chen 		spin_lock(&si->lock);
84136005baeSTim Chen 		latency_ration = LATENCY_LIMIT;
84236005baeSTim Chen 	}
84336005baeSTim Chen 
84436005baeSTim Chen 	/* try to get more slots in cluster */
84536005baeSTim Chen 	if (si->cluster_info) {
84636005baeSTim Chen 		if (scan_swap_map_try_ssd_cluster(si, &offset, &scan_base))
84736005baeSTim Chen 			goto checks;
84836005baeSTim Chen 		else
84936005baeSTim Chen 			goto done;
85036005baeSTim Chen 	}
85136005baeSTim Chen 	/* non-ssd case */
85236005baeSTim Chen 	++offset;
85336005baeSTim Chen 
85436005baeSTim Chen 	/* non-ssd case, still more slots in cluster? */
85536005baeSTim Chen 	if (si->cluster_nr && !si->swap_map[offset]) {
85636005baeSTim Chen 		--si->cluster_nr;
85736005baeSTim Chen 		goto checks;
85836005baeSTim Chen 	}
85936005baeSTim Chen 
86036005baeSTim Chen done:
86136005baeSTim Chen 	si->flags -= SWP_SCANNING;
86236005baeSTim Chen 	return n_ret;
8637dfad418SHugh Dickins 
864ebebbbe9SHugh Dickins scan:
865ec8acf20SShaohua Li 	spin_unlock(&si->lock);
8667dfad418SHugh Dickins 	while (++offset <= si->highest_bit) {
86752b7efdbSHugh Dickins 		if (!si->swap_map[offset]) {
868ec8acf20SShaohua Li 			spin_lock(&si->lock);
86952b7efdbSHugh Dickins 			goto checks;
8707dfad418SHugh Dickins 		}
871c9e44410SKAMEZAWA Hiroyuki 		if (vm_swap_full() && si->swap_map[offset] == SWAP_HAS_CACHE) {
872ec8acf20SShaohua Li 			spin_lock(&si->lock);
873c9e44410SKAMEZAWA Hiroyuki 			goto checks;
874c9e44410SKAMEZAWA Hiroyuki 		}
875048c27fdSHugh Dickins 		if (unlikely(--latency_ration < 0)) {
876048c27fdSHugh Dickins 			cond_resched();
877048c27fdSHugh Dickins 			latency_ration = LATENCY_LIMIT;
878048c27fdSHugh Dickins 		}
87952b7efdbSHugh Dickins 	}
880c60aa176SHugh Dickins 	offset = si->lowest_bit;
881a5998061SJamie Liu 	while (offset < scan_base) {
882c60aa176SHugh Dickins 		if (!si->swap_map[offset]) {
883ec8acf20SShaohua Li 			spin_lock(&si->lock);
884ebebbbe9SHugh Dickins 			goto checks;
885c60aa176SHugh Dickins 		}
886c9e44410SKAMEZAWA Hiroyuki 		if (vm_swap_full() && si->swap_map[offset] == SWAP_HAS_CACHE) {
887ec8acf20SShaohua Li 			spin_lock(&si->lock);
888c9e44410SKAMEZAWA Hiroyuki 			goto checks;
889c9e44410SKAMEZAWA Hiroyuki 		}
890c60aa176SHugh Dickins 		if (unlikely(--latency_ration < 0)) {
891c60aa176SHugh Dickins 			cond_resched();
892c60aa176SHugh Dickins 			latency_ration = LATENCY_LIMIT;
893c60aa176SHugh Dickins 		}
894a5998061SJamie Liu 		offset++;
895c60aa176SHugh Dickins 	}
896ec8acf20SShaohua Li 	spin_lock(&si->lock);
8977dfad418SHugh Dickins 
8987dfad418SHugh Dickins no_page:
89952b7efdbSHugh Dickins 	si->flags -= SWP_SCANNING;
90036005baeSTim Chen 	return n_ret;
9011da177e4SLinus Torvalds }
9021da177e4SLinus Torvalds 
90338d8b4e6SHuang Ying static int swap_alloc_cluster(struct swap_info_struct *si, swp_entry_t *slot)
90438d8b4e6SHuang Ying {
90538d8b4e6SHuang Ying 	unsigned long idx;
90638d8b4e6SHuang Ying 	struct swap_cluster_info *ci;
90738d8b4e6SHuang Ying 	unsigned long offset, i;
90838d8b4e6SHuang Ying 	unsigned char *map;
90938d8b4e6SHuang Ying 
910fe5266d5SHuang Ying 	/*
911fe5266d5SHuang Ying 	 * Should not even be attempting cluster allocations when huge
912fe5266d5SHuang Ying 	 * page swap is disabled.  Warn and fail the allocation.
913fe5266d5SHuang Ying 	 */
914fe5266d5SHuang Ying 	if (!IS_ENABLED(CONFIG_THP_SWAP)) {
915fe5266d5SHuang Ying 		VM_WARN_ON_ONCE(1);
916fe5266d5SHuang Ying 		return 0;
917fe5266d5SHuang Ying 	}
918fe5266d5SHuang Ying 
91938d8b4e6SHuang Ying 	if (cluster_list_empty(&si->free_clusters))
92038d8b4e6SHuang Ying 		return 0;
92138d8b4e6SHuang Ying 
92238d8b4e6SHuang Ying 	idx = cluster_list_first(&si->free_clusters);
92338d8b4e6SHuang Ying 	offset = idx * SWAPFILE_CLUSTER;
92438d8b4e6SHuang Ying 	ci = lock_cluster(si, offset);
92538d8b4e6SHuang Ying 	alloc_cluster(si, idx);
926e0709829SHuang Ying 	cluster_set_count_flag(ci, SWAPFILE_CLUSTER, CLUSTER_FLAG_HUGE);
92738d8b4e6SHuang Ying 
92838d8b4e6SHuang Ying 	map = si->swap_map + offset;
92938d8b4e6SHuang Ying 	for (i = 0; i < SWAPFILE_CLUSTER; i++)
93038d8b4e6SHuang Ying 		map[i] = SWAP_HAS_CACHE;
93138d8b4e6SHuang Ying 	unlock_cluster(ci);
93238d8b4e6SHuang Ying 	swap_range_alloc(si, offset, SWAPFILE_CLUSTER);
93338d8b4e6SHuang Ying 	*slot = swp_entry(si->type, offset);
93438d8b4e6SHuang Ying 
93538d8b4e6SHuang Ying 	return 1;
93638d8b4e6SHuang Ying }
93738d8b4e6SHuang Ying 
93838d8b4e6SHuang Ying static void swap_free_cluster(struct swap_info_struct *si, unsigned long idx)
93938d8b4e6SHuang Ying {
94038d8b4e6SHuang Ying 	unsigned long offset = idx * SWAPFILE_CLUSTER;
94138d8b4e6SHuang Ying 	struct swap_cluster_info *ci;
94238d8b4e6SHuang Ying 
94338d8b4e6SHuang Ying 	ci = lock_cluster(si, offset);
944979aafa5SHuang Ying 	memset(si->swap_map + offset, 0, SWAPFILE_CLUSTER);
94538d8b4e6SHuang Ying 	cluster_set_count_flag(ci, 0, 0);
94638d8b4e6SHuang Ying 	free_cluster(si, idx);
94738d8b4e6SHuang Ying 	unlock_cluster(ci);
94838d8b4e6SHuang Ying 	swap_range_free(si, offset, SWAPFILE_CLUSTER);
94938d8b4e6SHuang Ying }
95038d8b4e6SHuang Ying 
95136005baeSTim Chen static unsigned long scan_swap_map(struct swap_info_struct *si,
95236005baeSTim Chen 				   unsigned char usage)
95336005baeSTim Chen {
95436005baeSTim Chen 	swp_entry_t entry;
95536005baeSTim Chen 	int n_ret;
95636005baeSTim Chen 
95736005baeSTim Chen 	n_ret = scan_swap_map_slots(si, usage, 1, &entry);
95836005baeSTim Chen 
95936005baeSTim Chen 	if (n_ret)
96036005baeSTim Chen 		return swp_offset(entry);
96136005baeSTim Chen 	else
96236005baeSTim Chen 		return 0;
96336005baeSTim Chen 
96436005baeSTim Chen }
96536005baeSTim Chen 
9665d5e8f19SHuang Ying int get_swap_pages(int n_goal, swp_entry_t swp_entries[], int entry_size)
9671da177e4SLinus Torvalds {
9685d5e8f19SHuang Ying 	unsigned long size = swap_entry_size(entry_size);
969adfab836SDan Streetman 	struct swap_info_struct *si, *next;
97036005baeSTim Chen 	long avail_pgs;
97136005baeSTim Chen 	int n_ret = 0;
972a2468cc9SAaron Lu 	int node;
9731da177e4SLinus Torvalds 
97438d8b4e6SHuang Ying 	/* Only single cluster request supported */
9755d5e8f19SHuang Ying 	WARN_ON_ONCE(n_goal > 1 && size == SWAPFILE_CLUSTER);
97638d8b4e6SHuang Ying 
9775d5e8f19SHuang Ying 	avail_pgs = atomic_long_read(&nr_swap_pages) / size;
97836005baeSTim Chen 	if (avail_pgs <= 0)
979fb4f88dcSHugh Dickins 		goto noswap;
98036005baeSTim Chen 
98136005baeSTim Chen 	if (n_goal > SWAP_BATCH)
98236005baeSTim Chen 		n_goal = SWAP_BATCH;
98336005baeSTim Chen 
98436005baeSTim Chen 	if (n_goal > avail_pgs)
98536005baeSTim Chen 		n_goal = avail_pgs;
98636005baeSTim Chen 
9875d5e8f19SHuang Ying 	atomic_long_sub(n_goal * size, &nr_swap_pages);
9881da177e4SLinus Torvalds 
98918ab4d4cSDan Streetman 	spin_lock(&swap_avail_lock);
99018ab4d4cSDan Streetman 
99118ab4d4cSDan Streetman start_over:
992a2468cc9SAaron Lu 	node = numa_node_id();
993a2468cc9SAaron Lu 	plist_for_each_entry_safe(si, next, &swap_avail_heads[node], avail_lists[node]) {
99418ab4d4cSDan Streetman 		/* requeue si to after same-priority siblings */
995a2468cc9SAaron Lu 		plist_requeue(&si->avail_lists[node], &swap_avail_heads[node]);
99618ab4d4cSDan Streetman 		spin_unlock(&swap_avail_lock);
997ec8acf20SShaohua Li 		spin_lock(&si->lock);
998adfab836SDan Streetman 		if (!si->highest_bit || !(si->flags & SWP_WRITEOK)) {
99918ab4d4cSDan Streetman 			spin_lock(&swap_avail_lock);
1000a2468cc9SAaron Lu 			if (plist_node_empty(&si->avail_lists[node])) {
1001ec8acf20SShaohua Li 				spin_unlock(&si->lock);
100218ab4d4cSDan Streetman 				goto nextsi;
100318ab4d4cSDan Streetman 			}
100418ab4d4cSDan Streetman 			WARN(!si->highest_bit,
100518ab4d4cSDan Streetman 			     "swap_info %d in list but !highest_bit\n",
100618ab4d4cSDan Streetman 			     si->type);
100718ab4d4cSDan Streetman 			WARN(!(si->flags & SWP_WRITEOK),
100818ab4d4cSDan Streetman 			     "swap_info %d in list but !SWP_WRITEOK\n",
100918ab4d4cSDan Streetman 			     si->type);
1010a2468cc9SAaron Lu 			__del_from_avail_list(si);
101118ab4d4cSDan Streetman 			spin_unlock(&si->lock);
101218ab4d4cSDan Streetman 			goto nextsi;
1013ec8acf20SShaohua Li 		}
10145d5e8f19SHuang Ying 		if (size == SWAPFILE_CLUSTER) {
1015bc4ae27dSOmar Sandoval 			if (!(si->flags & SWP_FS))
101638d8b4e6SHuang Ying 				n_ret = swap_alloc_cluster(si, swp_entries);
1017f0eea189SHuang Ying 		} else
101836005baeSTim Chen 			n_ret = scan_swap_map_slots(si, SWAP_HAS_CACHE,
101936005baeSTim Chen 						    n_goal, swp_entries);
1020ec8acf20SShaohua Li 		spin_unlock(&si->lock);
10215d5e8f19SHuang Ying 		if (n_ret || size == SWAPFILE_CLUSTER)
102236005baeSTim Chen 			goto check_out;
102318ab4d4cSDan Streetman 		pr_debug("scan_swap_map of si %d failed to find offset\n",
102418ab4d4cSDan Streetman 			si->type);
102536005baeSTim Chen 
102618ab4d4cSDan Streetman 		spin_lock(&swap_avail_lock);
102718ab4d4cSDan Streetman nextsi:
1028adfab836SDan Streetman 		/*
1029adfab836SDan Streetman 		 * if we got here, it's likely that si was almost full before,
1030adfab836SDan Streetman 		 * and since scan_swap_map() can drop the si->lock, multiple
1031adfab836SDan Streetman 		 * callers probably all tried to get a page from the same si
103218ab4d4cSDan Streetman 		 * and it filled up before we could get one; or, the si filled
103318ab4d4cSDan Streetman 		 * up between us dropping swap_avail_lock and taking si->lock.
103418ab4d4cSDan Streetman 		 * Since we dropped the swap_avail_lock, the swap_avail_head
103518ab4d4cSDan Streetman 		 * list may have been modified; so if next is still in the
103636005baeSTim Chen 		 * swap_avail_head list then try it, otherwise start over
103736005baeSTim Chen 		 * if we have not gotten any slots.
1038adfab836SDan Streetman 		 */
1039a2468cc9SAaron Lu 		if (plist_node_empty(&next->avail_lists[node]))
104018ab4d4cSDan Streetman 			goto start_over;
1041fb4f88dcSHugh Dickins 	}
1042fb4f88dcSHugh Dickins 
104318ab4d4cSDan Streetman 	spin_unlock(&swap_avail_lock);
104418ab4d4cSDan Streetman 
104536005baeSTim Chen check_out:
104636005baeSTim Chen 	if (n_ret < n_goal)
10475d5e8f19SHuang Ying 		atomic_long_add((long)(n_goal - n_ret) * size,
104838d8b4e6SHuang Ying 				&nr_swap_pages);
1049fb4f88dcSHugh Dickins noswap:
105036005baeSTim Chen 	return n_ret;
105136005baeSTim Chen }
105236005baeSTim Chen 
10532de1a7e4SSeth Jennings /* The only caller of this function is now suspend routine */
1054910321eaSHugh Dickins swp_entry_t get_swap_page_of_type(int type)
1055910321eaSHugh Dickins {
1056c10d38ccSDaniel Jordan 	struct swap_info_struct *si = swap_type_to_swap_info(type);
1057910321eaSHugh Dickins 	pgoff_t offset;
1058910321eaSHugh Dickins 
1059c10d38ccSDaniel Jordan 	if (!si)
1060c10d38ccSDaniel Jordan 		goto fail;
1061c10d38ccSDaniel Jordan 
1062ec8acf20SShaohua Li 	spin_lock(&si->lock);
1063c10d38ccSDaniel Jordan 	if (si->flags & SWP_WRITEOK) {
1064ec8acf20SShaohua Li 		atomic_long_dec(&nr_swap_pages);
1065910321eaSHugh Dickins 		/* This is called for allocating swap entry, not cache */
1066910321eaSHugh Dickins 		offset = scan_swap_map(si, 1);
1067910321eaSHugh Dickins 		if (offset) {
1068ec8acf20SShaohua Li 			spin_unlock(&si->lock);
1069910321eaSHugh Dickins 			return swp_entry(type, offset);
1070910321eaSHugh Dickins 		}
1071ec8acf20SShaohua Li 		atomic_long_inc(&nr_swap_pages);
1072910321eaSHugh Dickins 	}
1073ec8acf20SShaohua Li 	spin_unlock(&si->lock);
1074c10d38ccSDaniel Jordan fail:
1075910321eaSHugh Dickins 	return (swp_entry_t) {0};
1076910321eaSHugh Dickins }
1077910321eaSHugh Dickins 
1078e8c26ab6STim Chen static struct swap_info_struct *__swap_info_get(swp_entry_t entry)
10791da177e4SLinus Torvalds {
10801da177e4SLinus Torvalds 	struct swap_info_struct *p;
10811da177e4SLinus Torvalds 	unsigned long offset, type;
10821da177e4SLinus Torvalds 
10831da177e4SLinus Torvalds 	if (!entry.val)
10841da177e4SLinus Torvalds 		goto out;
10851da177e4SLinus Torvalds 	type = swp_type(entry);
1086c10d38ccSDaniel Jordan 	p = swap_type_to_swap_info(type);
1087c10d38ccSDaniel Jordan 	if (!p)
10881da177e4SLinus Torvalds 		goto bad_nofile;
10891da177e4SLinus Torvalds 	if (!(p->flags & SWP_USED))
10901da177e4SLinus Torvalds 		goto bad_device;
10911da177e4SLinus Torvalds 	offset = swp_offset(entry);
10921da177e4SLinus Torvalds 	if (offset >= p->max)
10931da177e4SLinus Torvalds 		goto bad_offset;
10941da177e4SLinus Torvalds 	return p;
10951da177e4SLinus Torvalds 
10961da177e4SLinus Torvalds bad_offset:
10976a991fc7SHuang, Ying 	pr_err("swap_info_get: %s%08lx\n", Bad_offset, entry.val);
10981da177e4SLinus Torvalds 	goto out;
10991da177e4SLinus Torvalds bad_device:
11006a991fc7SHuang, Ying 	pr_err("swap_info_get: %s%08lx\n", Unused_file, entry.val);
11011da177e4SLinus Torvalds 	goto out;
11021da177e4SLinus Torvalds bad_nofile:
11036a991fc7SHuang, Ying 	pr_err("swap_info_get: %s%08lx\n", Bad_file, entry.val);
11041da177e4SLinus Torvalds out:
11051da177e4SLinus Torvalds 	return NULL;
11061da177e4SLinus Torvalds }
11071da177e4SLinus Torvalds 
1108e8c26ab6STim Chen static struct swap_info_struct *_swap_info_get(swp_entry_t entry)
1109e8c26ab6STim Chen {
1110e8c26ab6STim Chen 	struct swap_info_struct *p;
1111e8c26ab6STim Chen 
1112e8c26ab6STim Chen 	p = __swap_info_get(entry);
1113e8c26ab6STim Chen 	if (!p)
1114e8c26ab6STim Chen 		goto out;
1115e8c26ab6STim Chen 	if (!p->swap_map[swp_offset(entry)])
1116e8c26ab6STim Chen 		goto bad_free;
1117e8c26ab6STim Chen 	return p;
1118e8c26ab6STim Chen 
1119e8c26ab6STim Chen bad_free:
1120e8c26ab6STim Chen 	pr_err("swap_info_get: %s%08lx\n", Unused_offset, entry.val);
1121e8c26ab6STim Chen 	goto out;
1122e8c26ab6STim Chen out:
1123e8c26ab6STim Chen 	return NULL;
1124e8c26ab6STim Chen }
1125e8c26ab6STim Chen 
1126235b6217SHuang, Ying static struct swap_info_struct *swap_info_get(swp_entry_t entry)
11271da177e4SLinus Torvalds {
1128235b6217SHuang, Ying 	struct swap_info_struct *p;
1129235b6217SHuang, Ying 
1130235b6217SHuang, Ying 	p = _swap_info_get(entry);
1131235b6217SHuang, Ying 	if (p)
1132235b6217SHuang, Ying 		spin_lock(&p->lock);
1133235b6217SHuang, Ying 	return p;
1134235b6217SHuang, Ying }
1135235b6217SHuang, Ying 
11367c00bafeSTim Chen static struct swap_info_struct *swap_info_get_cont(swp_entry_t entry,
11377c00bafeSTim Chen 					struct swap_info_struct *q)
11387c00bafeSTim Chen {
11397c00bafeSTim Chen 	struct swap_info_struct *p;
11407c00bafeSTim Chen 
11417c00bafeSTim Chen 	p = _swap_info_get(entry);
11427c00bafeSTim Chen 
11437c00bafeSTim Chen 	if (p != q) {
11447c00bafeSTim Chen 		if (q != NULL)
11457c00bafeSTim Chen 			spin_unlock(&q->lock);
11467c00bafeSTim Chen 		if (p != NULL)
11477c00bafeSTim Chen 			spin_lock(&p->lock);
11487c00bafeSTim Chen 	}
11497c00bafeSTim Chen 	return p;
11507c00bafeSTim Chen }
11517c00bafeSTim Chen 
1152b32d5f32SHuang Ying static unsigned char __swap_entry_free_locked(struct swap_info_struct *p,
1153b32d5f32SHuang Ying 					      unsigned long offset,
1154b32d5f32SHuang Ying 					      unsigned char usage)
1155235b6217SHuang, Ying {
11568d69aaeeSHugh Dickins 	unsigned char count;
11578d69aaeeSHugh Dickins 	unsigned char has_cache;
1158235b6217SHuang, Ying 
1159355cfa73SKAMEZAWA Hiroyuki 	count = p->swap_map[offset];
1160235b6217SHuang, Ying 
1161253d553bSHugh Dickins 	has_cache = count & SWAP_HAS_CACHE;
1162253d553bSHugh Dickins 	count &= ~SWAP_HAS_CACHE;
1163253d553bSHugh Dickins 
1164253d553bSHugh Dickins 	if (usage == SWAP_HAS_CACHE) {
1165253d553bSHugh Dickins 		VM_BUG_ON(!has_cache);
1166253d553bSHugh Dickins 		has_cache = 0;
1167aaa46865SHugh Dickins 	} else if (count == SWAP_MAP_SHMEM) {
1168aaa46865SHugh Dickins 		/*
1169aaa46865SHugh Dickins 		 * Or we could insist on shmem.c using a special
1170aaa46865SHugh Dickins 		 * swap_shmem_free() and free_shmem_swap_and_cache()...
1171aaa46865SHugh Dickins 		 */
1172aaa46865SHugh Dickins 		count = 0;
1173570a335bSHugh Dickins 	} else if ((count & ~COUNT_CONTINUED) <= SWAP_MAP_MAX) {
1174570a335bSHugh Dickins 		if (count == COUNT_CONTINUED) {
1175570a335bSHugh Dickins 			if (swap_count_continued(p, offset, count))
1176570a335bSHugh Dickins 				count = SWAP_MAP_MAX | COUNT_CONTINUED;
1177570a335bSHugh Dickins 			else
1178570a335bSHugh Dickins 				count = SWAP_MAP_MAX;
1179570a335bSHugh Dickins 		} else
1180253d553bSHugh Dickins 			count--;
1181570a335bSHugh Dickins 	}
1182253d553bSHugh Dickins 
1183253d553bSHugh Dickins 	usage = count | has_cache;
11847c00bafeSTim Chen 	p->swap_map[offset] = usage ? : SWAP_HAS_CACHE;
1185253d553bSHugh Dickins 
1186b32d5f32SHuang Ying 	return usage;
1187b32d5f32SHuang Ying }
1188b32d5f32SHuang Ying 
1189b32d5f32SHuang Ying static unsigned char __swap_entry_free(struct swap_info_struct *p,
1190b32d5f32SHuang Ying 				       swp_entry_t entry, unsigned char usage)
1191b32d5f32SHuang Ying {
1192b32d5f32SHuang Ying 	struct swap_cluster_info *ci;
1193b32d5f32SHuang Ying 	unsigned long offset = swp_offset(entry);
1194b32d5f32SHuang Ying 
1195b32d5f32SHuang Ying 	ci = lock_cluster_or_swap_info(p, offset);
1196b32d5f32SHuang Ying 	usage = __swap_entry_free_locked(p, offset, usage);
11977c00bafeSTim Chen 	unlock_cluster_or_swap_info(p, ci);
119810e364daSHuang Ying 	if (!usage)
119910e364daSHuang Ying 		free_swap_slot(entry);
1200235b6217SHuang, Ying 
12017c00bafeSTim Chen 	return usage;
12027c00bafeSTim Chen }
12037c00bafeSTim Chen 
12047c00bafeSTim Chen static void swap_entry_free(struct swap_info_struct *p, swp_entry_t entry)
12057c00bafeSTim Chen {
12067c00bafeSTim Chen 	struct swap_cluster_info *ci;
12077c00bafeSTim Chen 	unsigned long offset = swp_offset(entry);
12087c00bafeSTim Chen 	unsigned char count;
12097c00bafeSTim Chen 
1210235b6217SHuang, Ying 	ci = lock_cluster(p, offset);
12117c00bafeSTim Chen 	count = p->swap_map[offset];
12127c00bafeSTim Chen 	VM_BUG_ON(count != SWAP_HAS_CACHE);
12137c00bafeSTim Chen 	p->swap_map[offset] = 0;
12142a8f9449SShaohua Li 	dec_cluster_info_page(p, p->cluster_info, offset);
1215235b6217SHuang, Ying 	unlock_cluster(ci);
12167c00bafeSTim Chen 
121738d8b4e6SHuang Ying 	mem_cgroup_uncharge_swap(entry, 1);
121838d8b4e6SHuang Ying 	swap_range_free(p, offset, 1);
12191da177e4SLinus Torvalds }
1220253d553bSHugh Dickins 
12211da177e4SLinus Torvalds /*
12221da177e4SLinus Torvalds  * Caller has made sure that the swap device corresponding to entry
12231da177e4SLinus Torvalds  * is still around or has not been recycled.
12241da177e4SLinus Torvalds  */
12251da177e4SLinus Torvalds void swap_free(swp_entry_t entry)
12261da177e4SLinus Torvalds {
12271da177e4SLinus Torvalds 	struct swap_info_struct *p;
12281da177e4SLinus Torvalds 
1229235b6217SHuang, Ying 	p = _swap_info_get(entry);
123010e364daSHuang Ying 	if (p)
123110e364daSHuang Ying 		__swap_entry_free(p, entry, 1);
12321da177e4SLinus Torvalds }
12331da177e4SLinus Torvalds 
12341da177e4SLinus Torvalds /*
1235cb4b86baSKAMEZAWA Hiroyuki  * Called after dropping swapcache to decrease refcnt to swap entries.
1236cb4b86baSKAMEZAWA Hiroyuki  */
1237a448f2d0SHuang Ying void put_swap_page(struct page *page, swp_entry_t entry)
123838d8b4e6SHuang Ying {
123938d8b4e6SHuang Ying 	unsigned long offset = swp_offset(entry);
124038d8b4e6SHuang Ying 	unsigned long idx = offset / SWAPFILE_CLUSTER;
124138d8b4e6SHuang Ying 	struct swap_cluster_info *ci;
124238d8b4e6SHuang Ying 	struct swap_info_struct *si;
124338d8b4e6SHuang Ying 	unsigned char *map;
1244a3aea839SHuang Ying 	unsigned int i, free_entries = 0;
1245a3aea839SHuang Ying 	unsigned char val;
1246a448f2d0SHuang Ying 	int size = swap_entry_size(hpage_nr_pages(page));
1247fe5266d5SHuang Ying 
1248a3aea839SHuang Ying 	si = _swap_info_get(entry);
124938d8b4e6SHuang Ying 	if (!si)
125038d8b4e6SHuang Ying 		return;
125138d8b4e6SHuang Ying 
1252c2343d27SHuang Ying 	ci = lock_cluster_or_swap_info(si, offset);
1253a448f2d0SHuang Ying 	if (size == SWAPFILE_CLUSTER) {
1254e0709829SHuang Ying 		VM_BUG_ON(!cluster_is_huge(ci));
125538d8b4e6SHuang Ying 		map = si->swap_map + offset;
125638d8b4e6SHuang Ying 		for (i = 0; i < SWAPFILE_CLUSTER; i++) {
1257a3aea839SHuang Ying 			val = map[i];
1258a3aea839SHuang Ying 			VM_BUG_ON(!(val & SWAP_HAS_CACHE));
1259a3aea839SHuang Ying 			if (val == SWAP_HAS_CACHE)
1260a3aea839SHuang Ying 				free_entries++;
126138d8b4e6SHuang Ying 		}
1262e0709829SHuang Ying 		cluster_clear_huge(ci);
1263a3aea839SHuang Ying 		if (free_entries == SWAPFILE_CLUSTER) {
1264c2343d27SHuang Ying 			unlock_cluster_or_swap_info(si, ci);
1265a3aea839SHuang Ying 			spin_lock(&si->lock);
126638d8b4e6SHuang Ying 			mem_cgroup_uncharge_swap(entry, SWAPFILE_CLUSTER);
126738d8b4e6SHuang Ying 			swap_free_cluster(si, idx);
126838d8b4e6SHuang Ying 			spin_unlock(&si->lock);
1269a448f2d0SHuang Ying 			return;
1270a448f2d0SHuang Ying 		}
1271a448f2d0SHuang Ying 	}
1272a448f2d0SHuang Ying 	for (i = 0; i < size; i++, entry.val++) {
1273c2343d27SHuang Ying 		if (!__swap_entry_free_locked(si, offset + i, SWAP_HAS_CACHE)) {
1274c2343d27SHuang Ying 			unlock_cluster_or_swap_info(si, ci);
1275a3aea839SHuang Ying 			free_swap_slot(entry);
1276c2343d27SHuang Ying 			if (i == size - 1)
1277c2343d27SHuang Ying 				return;
1278c2343d27SHuang Ying 			lock_cluster_or_swap_info(si, offset);
1279a3aea839SHuang Ying 		}
1280a3aea839SHuang Ying 	}
1281c2343d27SHuang Ying 	unlock_cluster_or_swap_info(si, ci);
128238d8b4e6SHuang Ying }
128359807685SHuang Ying 
1284fe5266d5SHuang Ying #ifdef CONFIG_THP_SWAP
128559807685SHuang Ying int split_swap_cluster(swp_entry_t entry)
128659807685SHuang Ying {
128759807685SHuang Ying 	struct swap_info_struct *si;
128859807685SHuang Ying 	struct swap_cluster_info *ci;
128959807685SHuang Ying 	unsigned long offset = swp_offset(entry);
129059807685SHuang Ying 
129159807685SHuang Ying 	si = _swap_info_get(entry);
129259807685SHuang Ying 	if (!si)
129359807685SHuang Ying 		return -EBUSY;
129459807685SHuang Ying 	ci = lock_cluster(si, offset);
129559807685SHuang Ying 	cluster_clear_huge(ci);
129659807685SHuang Ying 	unlock_cluster(ci);
129759807685SHuang Ying 	return 0;
129859807685SHuang Ying }
1299fe5266d5SHuang Ying #endif
130038d8b4e6SHuang Ying 
1301155b5f88SHuang Ying static int swp_entry_cmp(const void *ent1, const void *ent2)
1302155b5f88SHuang Ying {
1303155b5f88SHuang Ying 	const swp_entry_t *e1 = ent1, *e2 = ent2;
1304155b5f88SHuang Ying 
1305155b5f88SHuang Ying 	return (int)swp_type(*e1) - (int)swp_type(*e2);
1306155b5f88SHuang Ying }
1307155b5f88SHuang Ying 
13087c00bafeSTim Chen void swapcache_free_entries(swp_entry_t *entries, int n)
13097c00bafeSTim Chen {
13107c00bafeSTim Chen 	struct swap_info_struct *p, *prev;
13117c00bafeSTim Chen 	int i;
13127c00bafeSTim Chen 
13137c00bafeSTim Chen 	if (n <= 0)
13147c00bafeSTim Chen 		return;
13157c00bafeSTim Chen 
13167c00bafeSTim Chen 	prev = NULL;
13177c00bafeSTim Chen 	p = NULL;
1318155b5f88SHuang Ying 
1319155b5f88SHuang Ying 	/*
1320155b5f88SHuang Ying 	 * Sort swap entries by swap device, so each lock is only taken once.
1321155b5f88SHuang Ying 	 * nr_swapfiles isn't absolutely correct, but the overhead of sort() is
1322155b5f88SHuang Ying 	 * so low that it isn't necessary to optimize further.
1323155b5f88SHuang Ying 	 */
1324155b5f88SHuang Ying 	if (nr_swapfiles > 1)
1325155b5f88SHuang Ying 		sort(entries, n, sizeof(entries[0]), swp_entry_cmp, NULL);
13267c00bafeSTim Chen 	for (i = 0; i < n; ++i) {
13277c00bafeSTim Chen 		p = swap_info_get_cont(entries[i], prev);
1328235b6217SHuang, Ying 		if (p)
13297c00bafeSTim Chen 			swap_entry_free(p, entries[i]);
13307c00bafeSTim Chen 		prev = p;
13317c00bafeSTim Chen 	}
13327c00bafeSTim Chen 	if (p)
13337c00bafeSTim Chen 		spin_unlock(&p->lock);
1334cb4b86baSKAMEZAWA Hiroyuki }
1335cb4b86baSKAMEZAWA Hiroyuki 
1336cb4b86baSKAMEZAWA Hiroyuki /*
1337c475a8abSHugh Dickins  * How many references to page are currently swapped out?
1338570a335bSHugh Dickins  * This does not give an exact answer when swap count is continued,
1339570a335bSHugh Dickins  * but does include the high COUNT_CONTINUED flag to allow for that.
13401da177e4SLinus Torvalds  */
1341bde05d1cSHugh Dickins int page_swapcount(struct page *page)
13421da177e4SLinus Torvalds {
1343c475a8abSHugh Dickins 	int count = 0;
13441da177e4SLinus Torvalds 	struct swap_info_struct *p;
1345235b6217SHuang, Ying 	struct swap_cluster_info *ci;
13461da177e4SLinus Torvalds 	swp_entry_t entry;
1347235b6217SHuang, Ying 	unsigned long offset;
13481da177e4SLinus Torvalds 
13494c21e2f2SHugh Dickins 	entry.val = page_private(page);
1350235b6217SHuang, Ying 	p = _swap_info_get(entry);
13511da177e4SLinus Torvalds 	if (p) {
1352235b6217SHuang, Ying 		offset = swp_offset(entry);
1353235b6217SHuang, Ying 		ci = lock_cluster_or_swap_info(p, offset);
1354235b6217SHuang, Ying 		count = swap_count(p->swap_map[offset]);
1355235b6217SHuang, Ying 		unlock_cluster_or_swap_info(p, ci);
13561da177e4SLinus Torvalds 	}
1357c475a8abSHugh Dickins 	return count;
13581da177e4SLinus Torvalds }
13591da177e4SLinus Torvalds 
1360aa8d22a1SMinchan Kim int __swap_count(struct swap_info_struct *si, swp_entry_t entry)
1361aa8d22a1SMinchan Kim {
1362aa8d22a1SMinchan Kim 	pgoff_t offset = swp_offset(entry);
1363aa8d22a1SMinchan Kim 
1364aa8d22a1SMinchan Kim 	return swap_count(si->swap_map[offset]);
1365aa8d22a1SMinchan Kim }
1366aa8d22a1SMinchan Kim 
1367322b8afeSHuang Ying static int swap_swapcount(struct swap_info_struct *si, swp_entry_t entry)
1368322b8afeSHuang Ying {
1369322b8afeSHuang Ying 	int count = 0;
1370322b8afeSHuang Ying 	pgoff_t offset = swp_offset(entry);
1371322b8afeSHuang Ying 	struct swap_cluster_info *ci;
1372322b8afeSHuang Ying 
1373322b8afeSHuang Ying 	ci = lock_cluster_or_swap_info(si, offset);
1374322b8afeSHuang Ying 	count = swap_count(si->swap_map[offset]);
1375322b8afeSHuang Ying 	unlock_cluster_or_swap_info(si, ci);
1376322b8afeSHuang Ying 	return count;
1377322b8afeSHuang Ying }
1378322b8afeSHuang Ying 
13791da177e4SLinus Torvalds /*
13808334b962SMinchan Kim  * How many references to @entry are currently swapped out?
1381e8c26ab6STim Chen  * This does not give an exact answer when swap count is continued,
1382e8c26ab6STim Chen  * but does include the high COUNT_CONTINUED flag to allow for that.
1383e8c26ab6STim Chen  */
1384e8c26ab6STim Chen int __swp_swapcount(swp_entry_t entry)
1385e8c26ab6STim Chen {
1386e8c26ab6STim Chen 	int count = 0;
1387e8c26ab6STim Chen 	struct swap_info_struct *si;
1388e8c26ab6STim Chen 
1389e8c26ab6STim Chen 	si = __swap_info_get(entry);
1390322b8afeSHuang Ying 	if (si)
1391322b8afeSHuang Ying 		count = swap_swapcount(si, entry);
1392e8c26ab6STim Chen 	return count;
1393e8c26ab6STim Chen }
1394e8c26ab6STim Chen 
1395e8c26ab6STim Chen /*
1396e8c26ab6STim Chen  * How many references to @entry are currently swapped out?
13978334b962SMinchan Kim  * This considers COUNT_CONTINUED so it returns exact answer.
13988334b962SMinchan Kim  */
13998334b962SMinchan Kim int swp_swapcount(swp_entry_t entry)
14008334b962SMinchan Kim {
14018334b962SMinchan Kim 	int count, tmp_count, n;
14028334b962SMinchan Kim 	struct swap_info_struct *p;
1403235b6217SHuang, Ying 	struct swap_cluster_info *ci;
14048334b962SMinchan Kim 	struct page *page;
14058334b962SMinchan Kim 	pgoff_t offset;
14068334b962SMinchan Kim 	unsigned char *map;
14078334b962SMinchan Kim 
1408235b6217SHuang, Ying 	p = _swap_info_get(entry);
14098334b962SMinchan Kim 	if (!p)
14108334b962SMinchan Kim 		return 0;
14118334b962SMinchan Kim 
1412235b6217SHuang, Ying 	offset = swp_offset(entry);
1413235b6217SHuang, Ying 
1414235b6217SHuang, Ying 	ci = lock_cluster_or_swap_info(p, offset);
1415235b6217SHuang, Ying 
1416235b6217SHuang, Ying 	count = swap_count(p->swap_map[offset]);
14178334b962SMinchan Kim 	if (!(count & COUNT_CONTINUED))
14188334b962SMinchan Kim 		goto out;
14198334b962SMinchan Kim 
14208334b962SMinchan Kim 	count &= ~COUNT_CONTINUED;
14218334b962SMinchan Kim 	n = SWAP_MAP_MAX + 1;
14228334b962SMinchan Kim 
14238334b962SMinchan Kim 	page = vmalloc_to_page(p->swap_map + offset);
14248334b962SMinchan Kim 	offset &= ~PAGE_MASK;
14258334b962SMinchan Kim 	VM_BUG_ON(page_private(page) != SWP_CONTINUED);
14268334b962SMinchan Kim 
14278334b962SMinchan Kim 	do {
1428a8ae4991SGeliang Tang 		page = list_next_entry(page, lru);
14298334b962SMinchan Kim 		map = kmap_atomic(page);
14308334b962SMinchan Kim 		tmp_count = map[offset];
14318334b962SMinchan Kim 		kunmap_atomic(map);
14328334b962SMinchan Kim 
14338334b962SMinchan Kim 		count += (tmp_count & ~COUNT_CONTINUED) * n;
14348334b962SMinchan Kim 		n *= (SWAP_CONT_MAX + 1);
14358334b962SMinchan Kim 	} while (tmp_count & COUNT_CONTINUED);
14368334b962SMinchan Kim out:
1437235b6217SHuang, Ying 	unlock_cluster_or_swap_info(p, ci);
14388334b962SMinchan Kim 	return count;
14398334b962SMinchan Kim }
14408334b962SMinchan Kim 
1441e0709829SHuang Ying static bool swap_page_trans_huge_swapped(struct swap_info_struct *si,
1442e0709829SHuang Ying 					 swp_entry_t entry)
1443e0709829SHuang Ying {
1444e0709829SHuang Ying 	struct swap_cluster_info *ci;
1445e0709829SHuang Ying 	unsigned char *map = si->swap_map;
1446e0709829SHuang Ying 	unsigned long roffset = swp_offset(entry);
1447e0709829SHuang Ying 	unsigned long offset = round_down(roffset, SWAPFILE_CLUSTER);
1448e0709829SHuang Ying 	int i;
1449e0709829SHuang Ying 	bool ret = false;
1450e0709829SHuang Ying 
1451e0709829SHuang Ying 	ci = lock_cluster_or_swap_info(si, offset);
1452e0709829SHuang Ying 	if (!ci || !cluster_is_huge(ci)) {
1453afa4711eSHuang Ying 		if (swap_count(map[roffset]))
1454e0709829SHuang Ying 			ret = true;
1455e0709829SHuang Ying 		goto unlock_out;
1456e0709829SHuang Ying 	}
1457e0709829SHuang Ying 	for (i = 0; i < SWAPFILE_CLUSTER; i++) {
1458afa4711eSHuang Ying 		if (swap_count(map[offset + i])) {
1459e0709829SHuang Ying 			ret = true;
1460e0709829SHuang Ying 			break;
1461e0709829SHuang Ying 		}
1462e0709829SHuang Ying 	}
1463e0709829SHuang Ying unlock_out:
1464e0709829SHuang Ying 	unlock_cluster_or_swap_info(si, ci);
1465e0709829SHuang Ying 	return ret;
1466e0709829SHuang Ying }
1467e0709829SHuang Ying 
1468e0709829SHuang Ying static bool page_swapped(struct page *page)
1469e0709829SHuang Ying {
1470e0709829SHuang Ying 	swp_entry_t entry;
1471e0709829SHuang Ying 	struct swap_info_struct *si;
1472e0709829SHuang Ying 
1473fe5266d5SHuang Ying 	if (!IS_ENABLED(CONFIG_THP_SWAP) || likely(!PageTransCompound(page)))
1474e0709829SHuang Ying 		return page_swapcount(page) != 0;
1475e0709829SHuang Ying 
1476e0709829SHuang Ying 	page = compound_head(page);
1477e0709829SHuang Ying 	entry.val = page_private(page);
1478e0709829SHuang Ying 	si = _swap_info_get(entry);
1479e0709829SHuang Ying 	if (si)
1480e0709829SHuang Ying 		return swap_page_trans_huge_swapped(si, entry);
1481e0709829SHuang Ying 	return false;
1482e0709829SHuang Ying }
1483ba3c4ce6SHuang Ying 
1484ba3c4ce6SHuang Ying static int page_trans_huge_map_swapcount(struct page *page, int *total_mapcount,
1485ba3c4ce6SHuang Ying 					 int *total_swapcount)
1486ba3c4ce6SHuang Ying {
1487ba3c4ce6SHuang Ying 	int i, map_swapcount, _total_mapcount, _total_swapcount;
1488ba3c4ce6SHuang Ying 	unsigned long offset = 0;
1489ba3c4ce6SHuang Ying 	struct swap_info_struct *si;
1490ba3c4ce6SHuang Ying 	struct swap_cluster_info *ci = NULL;
1491ba3c4ce6SHuang Ying 	unsigned char *map = NULL;
1492ba3c4ce6SHuang Ying 	int mapcount, swapcount = 0;
1493ba3c4ce6SHuang Ying 
1494ba3c4ce6SHuang Ying 	/* hugetlbfs shouldn't call it */
1495ba3c4ce6SHuang Ying 	VM_BUG_ON_PAGE(PageHuge(page), page);
1496ba3c4ce6SHuang Ying 
1497fe5266d5SHuang Ying 	if (!IS_ENABLED(CONFIG_THP_SWAP) || likely(!PageTransCompound(page))) {
1498fe5266d5SHuang Ying 		mapcount = page_trans_huge_mapcount(page, total_mapcount);
1499ba3c4ce6SHuang Ying 		if (PageSwapCache(page))
1500ba3c4ce6SHuang Ying 			swapcount = page_swapcount(page);
1501ba3c4ce6SHuang Ying 		if (total_swapcount)
1502ba3c4ce6SHuang Ying 			*total_swapcount = swapcount;
1503ba3c4ce6SHuang Ying 		return mapcount + swapcount;
1504ba3c4ce6SHuang Ying 	}
1505ba3c4ce6SHuang Ying 
1506ba3c4ce6SHuang Ying 	page = compound_head(page);
1507ba3c4ce6SHuang Ying 
1508ba3c4ce6SHuang Ying 	_total_mapcount = _total_swapcount = map_swapcount = 0;
1509ba3c4ce6SHuang Ying 	if (PageSwapCache(page)) {
1510ba3c4ce6SHuang Ying 		swp_entry_t entry;
1511ba3c4ce6SHuang Ying 
1512ba3c4ce6SHuang Ying 		entry.val = page_private(page);
1513ba3c4ce6SHuang Ying 		si = _swap_info_get(entry);
1514ba3c4ce6SHuang Ying 		if (si) {
1515ba3c4ce6SHuang Ying 			map = si->swap_map;
1516ba3c4ce6SHuang Ying 			offset = swp_offset(entry);
1517ba3c4ce6SHuang Ying 		}
1518ba3c4ce6SHuang Ying 	}
1519ba3c4ce6SHuang Ying 	if (map)
1520ba3c4ce6SHuang Ying 		ci = lock_cluster(si, offset);
1521ba3c4ce6SHuang Ying 	for (i = 0; i < HPAGE_PMD_NR; i++) {
1522ba3c4ce6SHuang Ying 		mapcount = atomic_read(&page[i]._mapcount) + 1;
1523ba3c4ce6SHuang Ying 		_total_mapcount += mapcount;
1524ba3c4ce6SHuang Ying 		if (map) {
1525ba3c4ce6SHuang Ying 			swapcount = swap_count(map[offset + i]);
1526ba3c4ce6SHuang Ying 			_total_swapcount += swapcount;
1527ba3c4ce6SHuang Ying 		}
1528ba3c4ce6SHuang Ying 		map_swapcount = max(map_swapcount, mapcount + swapcount);
1529ba3c4ce6SHuang Ying 	}
1530ba3c4ce6SHuang Ying 	unlock_cluster(ci);
1531ba3c4ce6SHuang Ying 	if (PageDoubleMap(page)) {
1532ba3c4ce6SHuang Ying 		map_swapcount -= 1;
1533ba3c4ce6SHuang Ying 		_total_mapcount -= HPAGE_PMD_NR;
1534ba3c4ce6SHuang Ying 	}
1535ba3c4ce6SHuang Ying 	mapcount = compound_mapcount(page);
1536ba3c4ce6SHuang Ying 	map_swapcount += mapcount;
1537ba3c4ce6SHuang Ying 	_total_mapcount += mapcount;
1538ba3c4ce6SHuang Ying 	if (total_mapcount)
1539ba3c4ce6SHuang Ying 		*total_mapcount = _total_mapcount;
1540ba3c4ce6SHuang Ying 	if (total_swapcount)
1541ba3c4ce6SHuang Ying 		*total_swapcount = _total_swapcount;
1542ba3c4ce6SHuang Ying 
1543ba3c4ce6SHuang Ying 	return map_swapcount;
1544ba3c4ce6SHuang Ying }
1545e0709829SHuang Ying 
15468334b962SMinchan Kim /*
15477b1fe597SHugh Dickins  * We can write to an anon page without COW if there are no other references
15487b1fe597SHugh Dickins  * to it.  And as a side-effect, free up its swap: because the old content
15497b1fe597SHugh Dickins  * on disk will never be read, and seeking back there to write new content
15507b1fe597SHugh Dickins  * later would only waste time away from clustering.
15516d0a07edSAndrea Arcangeli  *
1552ba3c4ce6SHuang Ying  * NOTE: total_map_swapcount should not be relied upon by the caller if
15536d0a07edSAndrea Arcangeli  * reuse_swap_page() returns false, but it may be always overwritten
15546d0a07edSAndrea Arcangeli  * (see the other implementation for CONFIG_SWAP=n).
15551da177e4SLinus Torvalds  */
1556ba3c4ce6SHuang Ying bool reuse_swap_page(struct page *page, int *total_map_swapcount)
15571da177e4SLinus Torvalds {
1558ba3c4ce6SHuang Ying 	int count, total_mapcount, total_swapcount;
15591da177e4SLinus Torvalds 
1560309381feSSasha Levin 	VM_BUG_ON_PAGE(!PageLocked(page), page);
15615ad64688SHugh Dickins 	if (unlikely(PageKsm(page)))
15626d0a07edSAndrea Arcangeli 		return false;
1563ba3c4ce6SHuang Ying 	count = page_trans_huge_map_swapcount(page, &total_mapcount,
1564ba3c4ce6SHuang Ying 					      &total_swapcount);
1565ba3c4ce6SHuang Ying 	if (total_map_swapcount)
1566ba3c4ce6SHuang Ying 		*total_map_swapcount = total_mapcount + total_swapcount;
1567ba3c4ce6SHuang Ying 	if (count == 1 && PageSwapCache(page) &&
1568ba3c4ce6SHuang Ying 	    (likely(!PageTransCompound(page)) ||
1569ba3c4ce6SHuang Ying 	     /* The remaining swap count will be freed soon */
1570ba3c4ce6SHuang Ying 	     total_swapcount == page_swapcount(page))) {
1571f0571429SMinchan Kim 		if (!PageWriteback(page)) {
1572ba3c4ce6SHuang Ying 			page = compound_head(page);
15737b1fe597SHugh Dickins 			delete_from_swap_cache(page);
15747b1fe597SHugh Dickins 			SetPageDirty(page);
1575f0571429SMinchan Kim 		} else {
1576f0571429SMinchan Kim 			swp_entry_t entry;
1577f0571429SMinchan Kim 			struct swap_info_struct *p;
1578f0571429SMinchan Kim 
1579f0571429SMinchan Kim 			entry.val = page_private(page);
1580f0571429SMinchan Kim 			p = swap_info_get(entry);
1581f0571429SMinchan Kim 			if (p->flags & SWP_STABLE_WRITES) {
1582f0571429SMinchan Kim 				spin_unlock(&p->lock);
1583f0571429SMinchan Kim 				return false;
1584f0571429SMinchan Kim 			}
1585f0571429SMinchan Kim 			spin_unlock(&p->lock);
15867b1fe597SHugh Dickins 		}
15877b1fe597SHugh Dickins 	}
1588ba3c4ce6SHuang Ying 
15895ad64688SHugh Dickins 	return count <= 1;
15901da177e4SLinus Torvalds }
15911da177e4SLinus Torvalds 
15921da177e4SLinus Torvalds /*
1593a2c43eedSHugh Dickins  * If swap is getting full, or if there are no more mappings of this page,
1594a2c43eedSHugh Dickins  * then try_to_free_swap is called to free its swap space.
15951da177e4SLinus Torvalds  */
1596a2c43eedSHugh Dickins int try_to_free_swap(struct page *page)
15971da177e4SLinus Torvalds {
1598309381feSSasha Levin 	VM_BUG_ON_PAGE(!PageLocked(page), page);
15991da177e4SLinus Torvalds 
16001da177e4SLinus Torvalds 	if (!PageSwapCache(page))
16011da177e4SLinus Torvalds 		return 0;
16021da177e4SLinus Torvalds 	if (PageWriteback(page))
16031da177e4SLinus Torvalds 		return 0;
1604e0709829SHuang Ying 	if (page_swapped(page))
16051da177e4SLinus Torvalds 		return 0;
16061da177e4SLinus Torvalds 
1607b73d7fceSHugh Dickins 	/*
1608b73d7fceSHugh Dickins 	 * Once hibernation has begun to create its image of memory,
1609b73d7fceSHugh Dickins 	 * there's a danger that one of the calls to try_to_free_swap()
1610b73d7fceSHugh Dickins 	 * - most probably a call from __try_to_reclaim_swap() while
1611b73d7fceSHugh Dickins 	 * hibernation is allocating its own swap pages for the image,
1612b73d7fceSHugh Dickins 	 * but conceivably even a call from memory reclaim - will free
1613b73d7fceSHugh Dickins 	 * the swap from a page which has already been recorded in the
1614b73d7fceSHugh Dickins 	 * image as a clean swapcache page, and then reuse its swap for
1615b73d7fceSHugh Dickins 	 * another page of the image.  On waking from hibernation, the
1616b73d7fceSHugh Dickins 	 * original page might be freed under memory pressure, then
1617b73d7fceSHugh Dickins 	 * later read back in from swap, now with the wrong data.
1618b73d7fceSHugh Dickins 	 *
16192de1a7e4SSeth Jennings 	 * Hibernation suspends storage while it is writing the image
1620f90ac398SMel Gorman 	 * to disk so check that here.
1621b73d7fceSHugh Dickins 	 */
1622f90ac398SMel Gorman 	if (pm_suspended_storage())
1623b73d7fceSHugh Dickins 		return 0;
1624b73d7fceSHugh Dickins 
1625e0709829SHuang Ying 	page = compound_head(page);
1626a2c43eedSHugh Dickins 	delete_from_swap_cache(page);
16271da177e4SLinus Torvalds 	SetPageDirty(page);
1628a2c43eedSHugh Dickins 	return 1;
162968a22394SRik van Riel }
163068a22394SRik van Riel 
163168a22394SRik van Riel /*
16321da177e4SLinus Torvalds  * Free the swap entry like above, but also try to
16331da177e4SLinus Torvalds  * free the page cache entry if it is the last user.
16341da177e4SLinus Torvalds  */
16352509ef26SHugh Dickins int free_swap_and_cache(swp_entry_t entry)
16361da177e4SLinus Torvalds {
16371da177e4SLinus Torvalds 	struct swap_info_struct *p;
16387c00bafeSTim Chen 	unsigned char count;
16391da177e4SLinus Torvalds 
1640a7420aa5SAndi Kleen 	if (non_swap_entry(entry))
16412509ef26SHugh Dickins 		return 1;
16420697212aSChristoph Lameter 
16437c00bafeSTim Chen 	p = _swap_info_get(entry);
16441da177e4SLinus Torvalds 	if (p) {
16457c00bafeSTim Chen 		count = __swap_entry_free(p, entry, 1);
1646e0709829SHuang Ying 		if (count == SWAP_HAS_CACHE &&
1647bcd49e86SHuang Ying 		    !swap_page_trans_huge_swapped(p, entry))
1648bcd49e86SHuang Ying 			__try_to_reclaim_swap(p, swp_offset(entry),
1649bcd49e86SHuang Ying 					      TTRS_UNMAPPED | TTRS_FULL);
16501da177e4SLinus Torvalds 	}
16512509ef26SHugh Dickins 	return p != NULL;
16521da177e4SLinus Torvalds }
16531da177e4SLinus Torvalds 
1654b0cb1a19SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
1655f577eb30SRafael J. Wysocki /*
1656915bae9eSRafael J. Wysocki  * Find the swap type that corresponds to given device (if any).
1657f577eb30SRafael J. Wysocki  *
1658915bae9eSRafael J. Wysocki  * @offset - number of the PAGE_SIZE-sized block of the device, starting
1659915bae9eSRafael J. Wysocki  * from 0, in which the swap header is expected to be located.
1660915bae9eSRafael J. Wysocki  *
1661915bae9eSRafael J. Wysocki  * This is needed for the suspend to disk (aka swsusp).
1662f577eb30SRafael J. Wysocki  */
16637bf23687SRafael J. Wysocki int swap_type_of(dev_t device, sector_t offset, struct block_device **bdev_p)
1664f577eb30SRafael J. Wysocki {
1665915bae9eSRafael J. Wysocki 	struct block_device *bdev = NULL;
1666efa90a98SHugh Dickins 	int type;
1667f577eb30SRafael J. Wysocki 
1668915bae9eSRafael J. Wysocki 	if (device)
1669915bae9eSRafael J. Wysocki 		bdev = bdget(device);
1670915bae9eSRafael J. Wysocki 
1671f577eb30SRafael J. Wysocki 	spin_lock(&swap_lock);
1672efa90a98SHugh Dickins 	for (type = 0; type < nr_swapfiles; type++) {
1673efa90a98SHugh Dickins 		struct swap_info_struct *sis = swap_info[type];
1674f577eb30SRafael J. Wysocki 
1675915bae9eSRafael J. Wysocki 		if (!(sis->flags & SWP_WRITEOK))
1676f577eb30SRafael J. Wysocki 			continue;
1677b6b5bce3SRafael J. Wysocki 
1678915bae9eSRafael J. Wysocki 		if (!bdev) {
16797bf23687SRafael J. Wysocki 			if (bdev_p)
1680dddac6a7SAlan Jenkins 				*bdev_p = bdgrab(sis->bdev);
16817bf23687SRafael J. Wysocki 
16826e1819d6SRafael J. Wysocki 			spin_unlock(&swap_lock);
1683efa90a98SHugh Dickins 			return type;
16846e1819d6SRafael J. Wysocki 		}
1685915bae9eSRafael J. Wysocki 		if (bdev == sis->bdev) {
16869625a5f2SHugh Dickins 			struct swap_extent *se = &sis->first_swap_extent;
1687915bae9eSRafael J. Wysocki 
1688915bae9eSRafael J. Wysocki 			if (se->start_block == offset) {
16897bf23687SRafael J. Wysocki 				if (bdev_p)
1690dddac6a7SAlan Jenkins 					*bdev_p = bdgrab(sis->bdev);
16917bf23687SRafael J. Wysocki 
1692f577eb30SRafael J. Wysocki 				spin_unlock(&swap_lock);
1693915bae9eSRafael J. Wysocki 				bdput(bdev);
1694efa90a98SHugh Dickins 				return type;
1695f577eb30SRafael J. Wysocki 			}
1696f577eb30SRafael J. Wysocki 		}
1697915bae9eSRafael J. Wysocki 	}
1698f577eb30SRafael J. Wysocki 	spin_unlock(&swap_lock);
1699915bae9eSRafael J. Wysocki 	if (bdev)
1700915bae9eSRafael J. Wysocki 		bdput(bdev);
1701915bae9eSRafael J. Wysocki 
1702f577eb30SRafael J. Wysocki 	return -ENODEV;
1703f577eb30SRafael J. Wysocki }
1704f577eb30SRafael J. Wysocki 
1705f577eb30SRafael J. Wysocki /*
170673c34b6aSHugh Dickins  * Get the (PAGE_SIZE) block corresponding to given offset on the swapdev
170773c34b6aSHugh Dickins  * corresponding to given index in swap_info (swap type).
170873c34b6aSHugh Dickins  */
170973c34b6aSHugh Dickins sector_t swapdev_block(int type, pgoff_t offset)
171073c34b6aSHugh Dickins {
171173c34b6aSHugh Dickins 	struct block_device *bdev;
1712c10d38ccSDaniel Jordan 	struct swap_info_struct *si = swap_type_to_swap_info(type);
171373c34b6aSHugh Dickins 
1714c10d38ccSDaniel Jordan 	if (!si || !(si->flags & SWP_WRITEOK))
171573c34b6aSHugh Dickins 		return 0;
1716d4906e1aSLee Schermerhorn 	return map_swap_entry(swp_entry(type, offset), &bdev);
171773c34b6aSHugh Dickins }
171873c34b6aSHugh Dickins 
171973c34b6aSHugh Dickins /*
1720f577eb30SRafael J. Wysocki  * Return either the total number of swap pages of given type, or the number
1721f577eb30SRafael J. Wysocki  * of free pages of that type (depending on @free)
1722f577eb30SRafael J. Wysocki  *
1723f577eb30SRafael J. Wysocki  * This is needed for software suspend
1724f577eb30SRafael J. Wysocki  */
1725f577eb30SRafael J. Wysocki unsigned int count_swap_pages(int type, int free)
1726f577eb30SRafael J. Wysocki {
1727f577eb30SRafael J. Wysocki 	unsigned int n = 0;
1728f577eb30SRafael J. Wysocki 
1729f577eb30SRafael J. Wysocki 	spin_lock(&swap_lock);
1730efa90a98SHugh Dickins 	if ((unsigned int)type < nr_swapfiles) {
1731efa90a98SHugh Dickins 		struct swap_info_struct *sis = swap_info[type];
1732efa90a98SHugh Dickins 
1733ec8acf20SShaohua Li 		spin_lock(&sis->lock);
1734efa90a98SHugh Dickins 		if (sis->flags & SWP_WRITEOK) {
1735efa90a98SHugh Dickins 			n = sis->pages;
1736f577eb30SRafael J. Wysocki 			if (free)
1737efa90a98SHugh Dickins 				n -= sis->inuse_pages;
1738efa90a98SHugh Dickins 		}
1739ec8acf20SShaohua Li 		spin_unlock(&sis->lock);
1740f577eb30SRafael J. Wysocki 	}
1741f577eb30SRafael J. Wysocki 	spin_unlock(&swap_lock);
1742f577eb30SRafael J. Wysocki 	return n;
1743f577eb30SRafael J. Wysocki }
174473c34b6aSHugh Dickins #endif /* CONFIG_HIBERNATION */
1745f577eb30SRafael J. Wysocki 
17469f8bdb3fSHugh Dickins static inline int pte_same_as_swp(pte_t pte, pte_t swp_pte)
1747179ef71cSCyrill Gorcunov {
17489f8bdb3fSHugh Dickins 	return pte_same(pte_swp_clear_soft_dirty(pte), swp_pte);
1749179ef71cSCyrill Gorcunov }
1750179ef71cSCyrill Gorcunov 
17511da177e4SLinus Torvalds /*
175272866f6fSHugh Dickins  * No need to decide whether this PTE shares the swap entry with others,
175372866f6fSHugh Dickins  * just let do_wp_page work it out if a write is requested later - to
175472866f6fSHugh Dickins  * force COW, vm_page_prot omits write permission from any private vma.
17551da177e4SLinus Torvalds  */
1756044d66c1SHugh Dickins static int unuse_pte(struct vm_area_struct *vma, pmd_t *pmd,
17571da177e4SLinus Torvalds 		unsigned long addr, swp_entry_t entry, struct page *page)
17581da177e4SLinus Torvalds {
17599e16b7fbSHugh Dickins 	struct page *swapcache;
176072835c86SJohannes Weiner 	struct mem_cgroup *memcg;
1761044d66c1SHugh Dickins 	spinlock_t *ptl;
1762044d66c1SHugh Dickins 	pte_t *pte;
1763044d66c1SHugh Dickins 	int ret = 1;
1764044d66c1SHugh Dickins 
17659e16b7fbSHugh Dickins 	swapcache = page;
17669e16b7fbSHugh Dickins 	page = ksm_might_need_to_copy(page, vma, addr);
17679e16b7fbSHugh Dickins 	if (unlikely(!page))
17689e16b7fbSHugh Dickins 		return -ENOMEM;
17699e16b7fbSHugh Dickins 
1770f627c2f5SKirill A. Shutemov 	if (mem_cgroup_try_charge(page, vma->vm_mm, GFP_KERNEL,
1771f627c2f5SKirill A. Shutemov 				&memcg, false)) {
1772044d66c1SHugh Dickins 		ret = -ENOMEM;
177385d9fc89SKAMEZAWA Hiroyuki 		goto out_nolock;
177485d9fc89SKAMEZAWA Hiroyuki 	}
1775044d66c1SHugh Dickins 
1776044d66c1SHugh Dickins 	pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
17779f8bdb3fSHugh Dickins 	if (unlikely(!pte_same_as_swp(*pte, swp_entry_to_pte(entry)))) {
1778f627c2f5SKirill A. Shutemov 		mem_cgroup_cancel_charge(page, memcg, false);
1779044d66c1SHugh Dickins 		ret = 0;
1780044d66c1SHugh Dickins 		goto out;
1781044d66c1SHugh Dickins 	}
17828a9f3ccdSBalbir Singh 
1783b084d435SKAMEZAWA Hiroyuki 	dec_mm_counter(vma->vm_mm, MM_SWAPENTS);
1784d559db08SKAMEZAWA Hiroyuki 	inc_mm_counter(vma->vm_mm, MM_ANONPAGES);
17851da177e4SLinus Torvalds 	get_page(page);
17861da177e4SLinus Torvalds 	set_pte_at(vma->vm_mm, addr, pte,
17871da177e4SLinus Torvalds 		   pte_mkold(mk_pte(page, vma->vm_page_prot)));
178800501b53SJohannes Weiner 	if (page == swapcache) {
1789d281ee61SKirill A. Shutemov 		page_add_anon_rmap(page, vma, addr, false);
1790f627c2f5SKirill A. Shutemov 		mem_cgroup_commit_charge(page, memcg, true, false);
179100501b53SJohannes Weiner 	} else { /* ksm created a completely new copy */
1792d281ee61SKirill A. Shutemov 		page_add_new_anon_rmap(page, vma, addr, false);
1793f627c2f5SKirill A. Shutemov 		mem_cgroup_commit_charge(page, memcg, false, false);
179400501b53SJohannes Weiner 		lru_cache_add_active_or_unevictable(page, vma);
179500501b53SJohannes Weiner 	}
17961da177e4SLinus Torvalds 	swap_free(entry);
17971da177e4SLinus Torvalds 	/*
17981da177e4SLinus Torvalds 	 * Move the page to the active list so it is not
17991da177e4SLinus Torvalds 	 * immediately swapped out again after swapon.
18001da177e4SLinus Torvalds 	 */
18011da177e4SLinus Torvalds 	activate_page(page);
1802044d66c1SHugh Dickins out:
1803044d66c1SHugh Dickins 	pte_unmap_unlock(pte, ptl);
180485d9fc89SKAMEZAWA Hiroyuki out_nolock:
18059e16b7fbSHugh Dickins 	if (page != swapcache) {
18069e16b7fbSHugh Dickins 		unlock_page(page);
18079e16b7fbSHugh Dickins 		put_page(page);
18089e16b7fbSHugh Dickins 	}
1809044d66c1SHugh Dickins 	return ret;
18101da177e4SLinus Torvalds }
18111da177e4SLinus Torvalds 
18121da177e4SLinus Torvalds static int unuse_pte_range(struct vm_area_struct *vma, pmd_t *pmd,
18131da177e4SLinus Torvalds 			unsigned long addr, unsigned long end,
1814b56a2d8aSVineeth Remanan Pillai 			unsigned int type, bool frontswap,
1815b56a2d8aSVineeth Remanan Pillai 			unsigned long *fs_pages_to_unuse)
18161da177e4SLinus Torvalds {
1817b56a2d8aSVineeth Remanan Pillai 	struct page *page;
1818b56a2d8aSVineeth Remanan Pillai 	swp_entry_t entry;
1819705e87c0SHugh Dickins 	pte_t *pte;
1820b56a2d8aSVineeth Remanan Pillai 	struct swap_info_struct *si;
1821b56a2d8aSVineeth Remanan Pillai 	unsigned long offset;
18228a9f3ccdSBalbir Singh 	int ret = 0;
1823b56a2d8aSVineeth Remanan Pillai 	volatile unsigned char *swap_map;
18241da177e4SLinus Torvalds 
1825b56a2d8aSVineeth Remanan Pillai 	si = swap_info[type];
1826044d66c1SHugh Dickins 	pte = pte_offset_map(pmd, addr);
18271da177e4SLinus Torvalds 	do {
1828b56a2d8aSVineeth Remanan Pillai 		struct vm_fault vmf;
1829b56a2d8aSVineeth Remanan Pillai 
1830b56a2d8aSVineeth Remanan Pillai 		if (!is_swap_pte(*pte))
1831b56a2d8aSVineeth Remanan Pillai 			continue;
1832b56a2d8aSVineeth Remanan Pillai 
1833b56a2d8aSVineeth Remanan Pillai 		entry = pte_to_swp_entry(*pte);
1834b56a2d8aSVineeth Remanan Pillai 		if (swp_type(entry) != type)
1835b56a2d8aSVineeth Remanan Pillai 			continue;
1836b56a2d8aSVineeth Remanan Pillai 
1837b56a2d8aSVineeth Remanan Pillai 		offset = swp_offset(entry);
1838b56a2d8aSVineeth Remanan Pillai 		if (frontswap && !frontswap_test(si, offset))
1839b56a2d8aSVineeth Remanan Pillai 			continue;
1840b56a2d8aSVineeth Remanan Pillai 
1841044d66c1SHugh Dickins 		pte_unmap(pte);
1842b56a2d8aSVineeth Remanan Pillai 		swap_map = &si->swap_map[offset];
1843b56a2d8aSVineeth Remanan Pillai 		vmf.vma = vma;
1844b56a2d8aSVineeth Remanan Pillai 		vmf.address = addr;
1845b56a2d8aSVineeth Remanan Pillai 		vmf.pmd = pmd;
1846b56a2d8aSVineeth Remanan Pillai 		page = swapin_readahead(entry, GFP_HIGHUSER_MOVABLE, &vmf);
1847b56a2d8aSVineeth Remanan Pillai 		if (!page) {
1848b56a2d8aSVineeth Remanan Pillai 			if (*swap_map == 0 || *swap_map == SWAP_MAP_BAD)
1849b56a2d8aSVineeth Remanan Pillai 				goto try_next;
1850b56a2d8aSVineeth Remanan Pillai 			return -ENOMEM;
18511da177e4SLinus Torvalds 		}
1852b56a2d8aSVineeth Remanan Pillai 
1853b56a2d8aSVineeth Remanan Pillai 		lock_page(page);
1854b56a2d8aSVineeth Remanan Pillai 		wait_on_page_writeback(page);
1855b56a2d8aSVineeth Remanan Pillai 		ret = unuse_pte(vma, pmd, addr, entry, page);
1856b56a2d8aSVineeth Remanan Pillai 		if (ret < 0) {
1857b56a2d8aSVineeth Remanan Pillai 			unlock_page(page);
1858b56a2d8aSVineeth Remanan Pillai 			put_page(page);
1859b56a2d8aSVineeth Remanan Pillai 			goto out;
1860b56a2d8aSVineeth Remanan Pillai 		}
1861b56a2d8aSVineeth Remanan Pillai 
1862b56a2d8aSVineeth Remanan Pillai 		try_to_free_swap(page);
1863b56a2d8aSVineeth Remanan Pillai 		unlock_page(page);
1864b56a2d8aSVineeth Remanan Pillai 		put_page(page);
1865b56a2d8aSVineeth Remanan Pillai 
1866b56a2d8aSVineeth Remanan Pillai 		if (*fs_pages_to_unuse && !--(*fs_pages_to_unuse)) {
1867b56a2d8aSVineeth Remanan Pillai 			ret = FRONTSWAP_PAGES_UNUSED;
1868b56a2d8aSVineeth Remanan Pillai 			goto out;
1869b56a2d8aSVineeth Remanan Pillai 		}
1870b56a2d8aSVineeth Remanan Pillai try_next:
1871b56a2d8aSVineeth Remanan Pillai 		pte = pte_offset_map(pmd, addr);
18721da177e4SLinus Torvalds 	} while (pte++, addr += PAGE_SIZE, addr != end);
1873044d66c1SHugh Dickins 	pte_unmap(pte - 1);
1874b56a2d8aSVineeth Remanan Pillai 
1875b56a2d8aSVineeth Remanan Pillai 	ret = 0;
1876044d66c1SHugh Dickins out:
18778a9f3ccdSBalbir Singh 	return ret;
18781da177e4SLinus Torvalds }
18791da177e4SLinus Torvalds 
18801da177e4SLinus Torvalds static inline int unuse_pmd_range(struct vm_area_struct *vma, pud_t *pud,
18811da177e4SLinus Torvalds 				unsigned long addr, unsigned long end,
1882b56a2d8aSVineeth Remanan Pillai 				unsigned int type, bool frontswap,
1883b56a2d8aSVineeth Remanan Pillai 				unsigned long *fs_pages_to_unuse)
18841da177e4SLinus Torvalds {
18851da177e4SLinus Torvalds 	pmd_t *pmd;
18861da177e4SLinus Torvalds 	unsigned long next;
18878a9f3ccdSBalbir Singh 	int ret;
18881da177e4SLinus Torvalds 
18891da177e4SLinus Torvalds 	pmd = pmd_offset(pud, addr);
18901da177e4SLinus Torvalds 	do {
1891dc644a07SHugh Dickins 		cond_resched();
18921da177e4SLinus Torvalds 		next = pmd_addr_end(addr, end);
18931a5a9906SAndrea Arcangeli 		if (pmd_none_or_trans_huge_or_clear_bad(pmd))
18941da177e4SLinus Torvalds 			continue;
1895b56a2d8aSVineeth Remanan Pillai 		ret = unuse_pte_range(vma, pmd, addr, next, type,
1896b56a2d8aSVineeth Remanan Pillai 				      frontswap, fs_pages_to_unuse);
18978a9f3ccdSBalbir Singh 		if (ret)
18988a9f3ccdSBalbir Singh 			return ret;
18991da177e4SLinus Torvalds 	} while (pmd++, addr = next, addr != end);
19001da177e4SLinus Torvalds 	return 0;
19011da177e4SLinus Torvalds }
19021da177e4SLinus Torvalds 
1903c2febafcSKirill A. Shutemov static inline int unuse_pud_range(struct vm_area_struct *vma, p4d_t *p4d,
19041da177e4SLinus Torvalds 				unsigned long addr, unsigned long end,
1905b56a2d8aSVineeth Remanan Pillai 				unsigned int type, bool frontswap,
1906b56a2d8aSVineeth Remanan Pillai 				unsigned long *fs_pages_to_unuse)
19071da177e4SLinus Torvalds {
19081da177e4SLinus Torvalds 	pud_t *pud;
19091da177e4SLinus Torvalds 	unsigned long next;
19108a9f3ccdSBalbir Singh 	int ret;
19111da177e4SLinus Torvalds 
1912c2febafcSKirill A. Shutemov 	pud = pud_offset(p4d, addr);
19131da177e4SLinus Torvalds 	do {
19141da177e4SLinus Torvalds 		next = pud_addr_end(addr, end);
19151da177e4SLinus Torvalds 		if (pud_none_or_clear_bad(pud))
19161da177e4SLinus Torvalds 			continue;
1917b56a2d8aSVineeth Remanan Pillai 		ret = unuse_pmd_range(vma, pud, addr, next, type,
1918b56a2d8aSVineeth Remanan Pillai 				      frontswap, fs_pages_to_unuse);
19198a9f3ccdSBalbir Singh 		if (ret)
19208a9f3ccdSBalbir Singh 			return ret;
19211da177e4SLinus Torvalds 	} while (pud++, addr = next, addr != end);
19221da177e4SLinus Torvalds 	return 0;
19231da177e4SLinus Torvalds }
19241da177e4SLinus Torvalds 
1925c2febafcSKirill A. Shutemov static inline int unuse_p4d_range(struct vm_area_struct *vma, pgd_t *pgd,
1926c2febafcSKirill A. Shutemov 				unsigned long addr, unsigned long end,
1927b56a2d8aSVineeth Remanan Pillai 				unsigned int type, bool frontswap,
1928b56a2d8aSVineeth Remanan Pillai 				unsigned long *fs_pages_to_unuse)
1929c2febafcSKirill A. Shutemov {
1930c2febafcSKirill A. Shutemov 	p4d_t *p4d;
1931c2febafcSKirill A. Shutemov 	unsigned long next;
1932c2febafcSKirill A. Shutemov 	int ret;
1933c2febafcSKirill A. Shutemov 
1934c2febafcSKirill A. Shutemov 	p4d = p4d_offset(pgd, addr);
1935c2febafcSKirill A. Shutemov 	do {
1936c2febafcSKirill A. Shutemov 		next = p4d_addr_end(addr, end);
1937c2febafcSKirill A. Shutemov 		if (p4d_none_or_clear_bad(p4d))
1938c2febafcSKirill A. Shutemov 			continue;
1939b56a2d8aSVineeth Remanan Pillai 		ret = unuse_pud_range(vma, p4d, addr, next, type,
1940b56a2d8aSVineeth Remanan Pillai 				      frontswap, fs_pages_to_unuse);
1941c2febafcSKirill A. Shutemov 		if (ret)
1942c2febafcSKirill A. Shutemov 			return ret;
1943c2febafcSKirill A. Shutemov 	} while (p4d++, addr = next, addr != end);
1944c2febafcSKirill A. Shutemov 	return 0;
1945c2febafcSKirill A. Shutemov }
1946c2febafcSKirill A. Shutemov 
1947b56a2d8aSVineeth Remanan Pillai static int unuse_vma(struct vm_area_struct *vma, unsigned int type,
1948b56a2d8aSVineeth Remanan Pillai 		     bool frontswap, unsigned long *fs_pages_to_unuse)
19491da177e4SLinus Torvalds {
19501da177e4SLinus Torvalds 	pgd_t *pgd;
19511da177e4SLinus Torvalds 	unsigned long addr, end, next;
19528a9f3ccdSBalbir Singh 	int ret;
19531da177e4SLinus Torvalds 
19541da177e4SLinus Torvalds 	addr = vma->vm_start;
19551da177e4SLinus Torvalds 	end = vma->vm_end;
19561da177e4SLinus Torvalds 
19571da177e4SLinus Torvalds 	pgd = pgd_offset(vma->vm_mm, addr);
19581da177e4SLinus Torvalds 	do {
19591da177e4SLinus Torvalds 		next = pgd_addr_end(addr, end);
19601da177e4SLinus Torvalds 		if (pgd_none_or_clear_bad(pgd))
19611da177e4SLinus Torvalds 			continue;
1962b56a2d8aSVineeth Remanan Pillai 		ret = unuse_p4d_range(vma, pgd, addr, next, type,
1963b56a2d8aSVineeth Remanan Pillai 				      frontswap, fs_pages_to_unuse);
19648a9f3ccdSBalbir Singh 		if (ret)
19658a9f3ccdSBalbir Singh 			return ret;
19661da177e4SLinus Torvalds 	} while (pgd++, addr = next, addr != end);
19671da177e4SLinus Torvalds 	return 0;
19681da177e4SLinus Torvalds }
19691da177e4SLinus Torvalds 
1970b56a2d8aSVineeth Remanan Pillai static int unuse_mm(struct mm_struct *mm, unsigned int type,
1971b56a2d8aSVineeth Remanan Pillai 		    bool frontswap, unsigned long *fs_pages_to_unuse)
19721da177e4SLinus Torvalds {
19731da177e4SLinus Torvalds 	struct vm_area_struct *vma;
19748a9f3ccdSBalbir Singh 	int ret = 0;
19751da177e4SLinus Torvalds 
19761da177e4SLinus Torvalds 	down_read(&mm->mmap_sem);
19771da177e4SLinus Torvalds 	for (vma = mm->mmap; vma; vma = vma->vm_next) {
1978b56a2d8aSVineeth Remanan Pillai 		if (vma->anon_vma) {
1979b56a2d8aSVineeth Remanan Pillai 			ret = unuse_vma(vma, type, frontswap,
1980b56a2d8aSVineeth Remanan Pillai 					fs_pages_to_unuse);
1981b56a2d8aSVineeth Remanan Pillai 			if (ret)
19821da177e4SLinus Torvalds 				break;
1983b56a2d8aSVineeth Remanan Pillai 		}
1984dc644a07SHugh Dickins 		cond_resched();
19851da177e4SLinus Torvalds 	}
19861da177e4SLinus Torvalds 	up_read(&mm->mmap_sem);
1987b56a2d8aSVineeth Remanan Pillai 	return ret;
19881da177e4SLinus Torvalds }
19891da177e4SLinus Torvalds 
19901da177e4SLinus Torvalds /*
199138b5faf4SDan Magenheimer  * Scan swap_map (or frontswap_map if frontswap parameter is true)
1992b56a2d8aSVineeth Remanan Pillai  * from current position to next entry still in use. Return 0
1993b56a2d8aSVineeth Remanan Pillai  * if there are no inuse entries after prev till end of the map.
19941da177e4SLinus Torvalds  */
19956eb396dcSHugh Dickins static unsigned int find_next_to_unuse(struct swap_info_struct *si,
199638b5faf4SDan Magenheimer 					unsigned int prev, bool frontswap)
19971da177e4SLinus Torvalds {
1998b56a2d8aSVineeth Remanan Pillai 	unsigned int i;
19998d69aaeeSHugh Dickins 	unsigned char count;
20001da177e4SLinus Torvalds 
20011da177e4SLinus Torvalds 	/*
20025d337b91SHugh Dickins 	 * No need for swap_lock here: we're just looking
20031da177e4SLinus Torvalds 	 * for whether an entry is in use, not modifying it; false
20041da177e4SLinus Torvalds 	 * hits are okay, and sys_swapoff() has already prevented new
20055d337b91SHugh Dickins 	 * allocations from this area (while holding swap_lock).
20061da177e4SLinus Torvalds 	 */
2007b56a2d8aSVineeth Remanan Pillai 	for (i = prev + 1; i < si->max; i++) {
20084db0c3c2SJason Low 		count = READ_ONCE(si->swap_map[i]);
2009355cfa73SKAMEZAWA Hiroyuki 		if (count && swap_count(count) != SWAP_MAP_BAD)
2010dc644a07SHugh Dickins 			if (!frontswap || frontswap_test(si, i))
20111da177e4SLinus Torvalds 				break;
2012dc644a07SHugh Dickins 		if ((i % LATENCY_LIMIT) == 0)
2013dc644a07SHugh Dickins 			cond_resched();
20141da177e4SLinus Torvalds 	}
2015b56a2d8aSVineeth Remanan Pillai 
2016b56a2d8aSVineeth Remanan Pillai 	if (i == si->max)
2017b56a2d8aSVineeth Remanan Pillai 		i = 0;
2018b56a2d8aSVineeth Remanan Pillai 
20191da177e4SLinus Torvalds 	return i;
20201da177e4SLinus Torvalds }
20211da177e4SLinus Torvalds 
20221da177e4SLinus Torvalds /*
2023b56a2d8aSVineeth Remanan Pillai  * If the boolean frontswap is true, only unuse pages_to_unuse pages;
202438b5faf4SDan Magenheimer  * pages_to_unuse==0 means all pages; ignored if frontswap is false
20251da177e4SLinus Torvalds  */
2026b56a2d8aSVineeth Remanan Pillai #define SWAP_UNUSE_MAX_TRIES 3
202738b5faf4SDan Magenheimer int try_to_unuse(unsigned int type, bool frontswap,
202838b5faf4SDan Magenheimer 		 unsigned long pages_to_unuse)
20291da177e4SLinus Torvalds {
2030b56a2d8aSVineeth Remanan Pillai 	struct mm_struct *prev_mm;
2031b56a2d8aSVineeth Remanan Pillai 	struct mm_struct *mm;
2032b56a2d8aSVineeth Remanan Pillai 	struct list_head *p;
2033b56a2d8aSVineeth Remanan Pillai 	int retval = 0;
2034efa90a98SHugh Dickins 	struct swap_info_struct *si = swap_info[type];
20351da177e4SLinus Torvalds 	struct page *page;
20361da177e4SLinus Torvalds 	swp_entry_t entry;
2037b56a2d8aSVineeth Remanan Pillai 	unsigned int i;
2038b56a2d8aSVineeth Remanan Pillai 	int retries = 0;
20391da177e4SLinus Torvalds 
2040b56a2d8aSVineeth Remanan Pillai 	if (!si->inuse_pages)
2041b56a2d8aSVineeth Remanan Pillai 		return 0;
20421da177e4SLinus Torvalds 
2043b56a2d8aSVineeth Remanan Pillai 	if (!frontswap)
2044b56a2d8aSVineeth Remanan Pillai 		pages_to_unuse = 0;
2045b56a2d8aSVineeth Remanan Pillai 
2046b56a2d8aSVineeth Remanan Pillai retry:
2047b56a2d8aSVineeth Remanan Pillai 	retval = shmem_unuse(type, frontswap, &pages_to_unuse);
2048b56a2d8aSVineeth Remanan Pillai 	if (retval)
2049b56a2d8aSVineeth Remanan Pillai 		goto out;
2050b56a2d8aSVineeth Remanan Pillai 
2051b56a2d8aSVineeth Remanan Pillai 	prev_mm = &init_mm;
2052b56a2d8aSVineeth Remanan Pillai 	mmget(prev_mm);
2053b56a2d8aSVineeth Remanan Pillai 
2054b56a2d8aSVineeth Remanan Pillai 	spin_lock(&mmlist_lock);
2055b56a2d8aSVineeth Remanan Pillai 	p = &init_mm.mmlist;
2056b56a2d8aSVineeth Remanan Pillai 	while ((p = p->next) != &init_mm.mmlist) {
20571da177e4SLinus Torvalds 		if (signal_pending(current)) {
20581da177e4SLinus Torvalds 			retval = -EINTR;
20591da177e4SLinus Torvalds 			break;
20601da177e4SLinus Torvalds 		}
20611da177e4SLinus Torvalds 
20621da177e4SLinus Torvalds 		mm = list_entry(p, struct mm_struct, mmlist);
2063388f7934SVegard Nossum 		if (!mmget_not_zero(mm))
20641da177e4SLinus Torvalds 			continue;
20651da177e4SLinus Torvalds 		spin_unlock(&mmlist_lock);
20661da177e4SLinus Torvalds 		mmput(prev_mm);
20671da177e4SLinus Torvalds 		prev_mm = mm;
2068b56a2d8aSVineeth Remanan Pillai 		retval = unuse_mm(mm, type, frontswap, &pages_to_unuse);
20691da177e4SLinus Torvalds 
20701da177e4SLinus Torvalds 		if (retval) {
2071b56a2d8aSVineeth Remanan Pillai 			mmput(prev_mm);
2072b56a2d8aSVineeth Remanan Pillai 			goto out;
20731da177e4SLinus Torvalds 		}
20741da177e4SLinus Torvalds 
20751da177e4SLinus Torvalds 		/*
20761da177e4SLinus Torvalds 		 * Make sure that we aren't completely killing
20771da177e4SLinus Torvalds 		 * interactive performance.
20781da177e4SLinus Torvalds 		 */
20791da177e4SLinus Torvalds 		cond_resched();
2080b56a2d8aSVineeth Remanan Pillai 		spin_lock(&mmlist_lock);
208138b5faf4SDan Magenheimer 	}
2082b56a2d8aSVineeth Remanan Pillai 	spin_unlock(&mmlist_lock);
2083b56a2d8aSVineeth Remanan Pillai 
2084b56a2d8aSVineeth Remanan Pillai 	mmput(prev_mm);
2085b56a2d8aSVineeth Remanan Pillai 
2086b56a2d8aSVineeth Remanan Pillai 	i = 0;
2087b56a2d8aSVineeth Remanan Pillai 	while ((i = find_next_to_unuse(si, i, frontswap)) != 0) {
2088b56a2d8aSVineeth Remanan Pillai 
2089b56a2d8aSVineeth Remanan Pillai 		entry = swp_entry(type, i);
2090b56a2d8aSVineeth Remanan Pillai 		page = find_get_page(swap_address_space(entry), i);
2091b56a2d8aSVineeth Remanan Pillai 		if (!page)
2092b56a2d8aSVineeth Remanan Pillai 			continue;
2093b56a2d8aSVineeth Remanan Pillai 
2094b56a2d8aSVineeth Remanan Pillai 		/*
2095b56a2d8aSVineeth Remanan Pillai 		 * It is conceivable that a racing task removed this page from
2096b56a2d8aSVineeth Remanan Pillai 		 * swap cache just before we acquired the page lock. The page
2097b56a2d8aSVineeth Remanan Pillai 		 * might even be back in swap cache on another swap area. But
2098b56a2d8aSVineeth Remanan Pillai 		 * that is okay, try_to_free_swap() only removes stale pages.
2099b56a2d8aSVineeth Remanan Pillai 		 */
2100b56a2d8aSVineeth Remanan Pillai 		lock_page(page);
2101b56a2d8aSVineeth Remanan Pillai 		wait_on_page_writeback(page);
2102b56a2d8aSVineeth Remanan Pillai 		try_to_free_swap(page);
2103b56a2d8aSVineeth Remanan Pillai 		unlock_page(page);
2104b56a2d8aSVineeth Remanan Pillai 		put_page(page);
2105b56a2d8aSVineeth Remanan Pillai 
2106b56a2d8aSVineeth Remanan Pillai 		/*
2107b56a2d8aSVineeth Remanan Pillai 		 * For frontswap, we just need to unuse pages_to_unuse, if
2108b56a2d8aSVineeth Remanan Pillai 		 * it was specified. Need not check frontswap again here as
2109b56a2d8aSVineeth Remanan Pillai 		 * we already zeroed out pages_to_unuse if not frontswap.
2110b56a2d8aSVineeth Remanan Pillai 		 */
2111b56a2d8aSVineeth Remanan Pillai 		if (pages_to_unuse && --pages_to_unuse == 0)
2112b56a2d8aSVineeth Remanan Pillai 			goto out;
21131da177e4SLinus Torvalds 	}
21141da177e4SLinus Torvalds 
2115b56a2d8aSVineeth Remanan Pillai 	/*
2116b56a2d8aSVineeth Remanan Pillai 	 * Lets check again to see if there are still swap entries in the map.
2117b56a2d8aSVineeth Remanan Pillai 	 * If yes, we would need to do retry the unuse logic again.
2118b56a2d8aSVineeth Remanan Pillai 	 * Under global memory pressure, swap entries can be reinserted back
2119b56a2d8aSVineeth Remanan Pillai 	 * into process space after the mmlist loop above passes over them.
2120b56a2d8aSVineeth Remanan Pillai 	 * Its not worth continuosuly retrying to unuse the swap in this case.
2121b56a2d8aSVineeth Remanan Pillai 	 * So we try SWAP_UNUSE_MAX_TRIES times.
2122b56a2d8aSVineeth Remanan Pillai 	 */
2123b56a2d8aSVineeth Remanan Pillai 	if (++retries >= SWAP_UNUSE_MAX_TRIES)
2124b56a2d8aSVineeth Remanan Pillai 		retval = -EBUSY;
2125b56a2d8aSVineeth Remanan Pillai 	else if (si->inuse_pages)
2126b56a2d8aSVineeth Remanan Pillai 		goto retry;
2127b56a2d8aSVineeth Remanan Pillai 
2128b56a2d8aSVineeth Remanan Pillai out:
2129b56a2d8aSVineeth Remanan Pillai 	return (retval == FRONTSWAP_PAGES_UNUSED) ? 0 : retval;
21301da177e4SLinus Torvalds }
21311da177e4SLinus Torvalds 
21321da177e4SLinus Torvalds /*
21335d337b91SHugh Dickins  * After a successful try_to_unuse, if no swap is now in use, we know
21345d337b91SHugh Dickins  * we can empty the mmlist.  swap_lock must be held on entry and exit.
21355d337b91SHugh Dickins  * Note that mmlist_lock nests inside swap_lock, and an mm must be
21361da177e4SLinus Torvalds  * added to the mmlist just after page_duplicate - before would be racy.
21371da177e4SLinus Torvalds  */
21381da177e4SLinus Torvalds static void drain_mmlist(void)
21391da177e4SLinus Torvalds {
21401da177e4SLinus Torvalds 	struct list_head *p, *next;
2141efa90a98SHugh Dickins 	unsigned int type;
21421da177e4SLinus Torvalds 
2143efa90a98SHugh Dickins 	for (type = 0; type < nr_swapfiles; type++)
2144efa90a98SHugh Dickins 		if (swap_info[type]->inuse_pages)
21451da177e4SLinus Torvalds 			return;
21461da177e4SLinus Torvalds 	spin_lock(&mmlist_lock);
21471da177e4SLinus Torvalds 	list_for_each_safe(p, next, &init_mm.mmlist)
21481da177e4SLinus Torvalds 		list_del_init(p);
21491da177e4SLinus Torvalds 	spin_unlock(&mmlist_lock);
21501da177e4SLinus Torvalds }
21511da177e4SLinus Torvalds 
21521da177e4SLinus Torvalds /*
21531da177e4SLinus Torvalds  * Use this swapdev's extent info to locate the (PAGE_SIZE) block which
2154d4906e1aSLee Schermerhorn  * corresponds to page offset for the specified swap entry.
2155d4906e1aSLee Schermerhorn  * Note that the type of this function is sector_t, but it returns page offset
2156d4906e1aSLee Schermerhorn  * into the bdev, not sector offset.
21571da177e4SLinus Torvalds  */
2158d4906e1aSLee Schermerhorn static sector_t map_swap_entry(swp_entry_t entry, struct block_device **bdev)
21591da177e4SLinus Torvalds {
2160f29ad6a9SHugh Dickins 	struct swap_info_struct *sis;
2161f29ad6a9SHugh Dickins 	struct swap_extent *start_se;
2162f29ad6a9SHugh Dickins 	struct swap_extent *se;
2163f29ad6a9SHugh Dickins 	pgoff_t offset;
2164f29ad6a9SHugh Dickins 
2165c10d38ccSDaniel Jordan 	sis = swp_swap_info(entry);
2166f29ad6a9SHugh Dickins 	*bdev = sis->bdev;
2167f29ad6a9SHugh Dickins 
2168f29ad6a9SHugh Dickins 	offset = swp_offset(entry);
2169f29ad6a9SHugh Dickins 	start_se = sis->curr_swap_extent;
2170f29ad6a9SHugh Dickins 	se = start_se;
21711da177e4SLinus Torvalds 
21721da177e4SLinus Torvalds 	for ( ; ; ) {
21731da177e4SLinus Torvalds 		if (se->start_page <= offset &&
21741da177e4SLinus Torvalds 				offset < (se->start_page + se->nr_pages)) {
21751da177e4SLinus Torvalds 			return se->start_block + (offset - se->start_page);
21761da177e4SLinus Torvalds 		}
2177a8ae4991SGeliang Tang 		se = list_next_entry(se, list);
21781da177e4SLinus Torvalds 		sis->curr_swap_extent = se;
21791da177e4SLinus Torvalds 		BUG_ON(se == start_se);		/* It *must* be present */
21801da177e4SLinus Torvalds 	}
21811da177e4SLinus Torvalds }
21821da177e4SLinus Torvalds 
21831da177e4SLinus Torvalds /*
2184d4906e1aSLee Schermerhorn  * Returns the page offset into bdev for the specified page's swap entry.
2185d4906e1aSLee Schermerhorn  */
2186d4906e1aSLee Schermerhorn sector_t map_swap_page(struct page *page, struct block_device **bdev)
2187d4906e1aSLee Schermerhorn {
2188d4906e1aSLee Schermerhorn 	swp_entry_t entry;
2189d4906e1aSLee Schermerhorn 	entry.val = page_private(page);
2190d4906e1aSLee Schermerhorn 	return map_swap_entry(entry, bdev);
2191d4906e1aSLee Schermerhorn }
2192d4906e1aSLee Schermerhorn 
2193d4906e1aSLee Schermerhorn /*
21941da177e4SLinus Torvalds  * Free all of a swapdev's extent information
21951da177e4SLinus Torvalds  */
21961da177e4SLinus Torvalds static void destroy_swap_extents(struct swap_info_struct *sis)
21971da177e4SLinus Torvalds {
21989625a5f2SHugh Dickins 	while (!list_empty(&sis->first_swap_extent.list)) {
21991da177e4SLinus Torvalds 		struct swap_extent *se;
22001da177e4SLinus Torvalds 
2201a8ae4991SGeliang Tang 		se = list_first_entry(&sis->first_swap_extent.list,
22021da177e4SLinus Torvalds 				struct swap_extent, list);
22031da177e4SLinus Torvalds 		list_del(&se->list);
22041da177e4SLinus Torvalds 		kfree(se);
22051da177e4SLinus Torvalds 	}
220662c230bcSMel Gorman 
2207bc4ae27dSOmar Sandoval 	if (sis->flags & SWP_ACTIVATED) {
220862c230bcSMel Gorman 		struct file *swap_file = sis->swap_file;
220962c230bcSMel Gorman 		struct address_space *mapping = swap_file->f_mapping;
221062c230bcSMel Gorman 
2211bc4ae27dSOmar Sandoval 		sis->flags &= ~SWP_ACTIVATED;
2212bc4ae27dSOmar Sandoval 		if (mapping->a_ops->swap_deactivate)
221362c230bcSMel Gorman 			mapping->a_ops->swap_deactivate(swap_file);
221462c230bcSMel Gorman 	}
22151da177e4SLinus Torvalds }
22161da177e4SLinus Torvalds 
22171da177e4SLinus Torvalds /*
22181da177e4SLinus Torvalds  * Add a block range (and the corresponding page range) into this swapdev's
221911d31886SHugh Dickins  * extent list.  The extent list is kept sorted in page order.
22201da177e4SLinus Torvalds  *
222111d31886SHugh Dickins  * This function rather assumes that it is called in ascending page order.
22221da177e4SLinus Torvalds  */
2223a509bc1aSMel Gorman int
22241da177e4SLinus Torvalds add_swap_extent(struct swap_info_struct *sis, unsigned long start_page,
22251da177e4SLinus Torvalds 		unsigned long nr_pages, sector_t start_block)
22261da177e4SLinus Torvalds {
22271da177e4SLinus Torvalds 	struct swap_extent *se;
22281da177e4SLinus Torvalds 	struct swap_extent *new_se;
22291da177e4SLinus Torvalds 	struct list_head *lh;
22301da177e4SLinus Torvalds 
22319625a5f2SHugh Dickins 	if (start_page == 0) {
22329625a5f2SHugh Dickins 		se = &sis->first_swap_extent;
22339625a5f2SHugh Dickins 		sis->curr_swap_extent = se;
22349625a5f2SHugh Dickins 		se->start_page = 0;
22359625a5f2SHugh Dickins 		se->nr_pages = nr_pages;
22369625a5f2SHugh Dickins 		se->start_block = start_block;
22379625a5f2SHugh Dickins 		return 1;
22389625a5f2SHugh Dickins 	} else {
22399625a5f2SHugh Dickins 		lh = sis->first_swap_extent.list.prev;	/* Highest extent */
22401da177e4SLinus Torvalds 		se = list_entry(lh, struct swap_extent, list);
224111d31886SHugh Dickins 		BUG_ON(se->start_page + se->nr_pages != start_page);
224211d31886SHugh Dickins 		if (se->start_block + se->nr_pages == start_block) {
22431da177e4SLinus Torvalds 			/* Merge it */
22441da177e4SLinus Torvalds 			se->nr_pages += nr_pages;
22451da177e4SLinus Torvalds 			return 0;
22461da177e4SLinus Torvalds 		}
22471da177e4SLinus Torvalds 	}
22481da177e4SLinus Torvalds 
22491da177e4SLinus Torvalds 	/*
22501da177e4SLinus Torvalds 	 * No merge.  Insert a new extent, preserving ordering.
22511da177e4SLinus Torvalds 	 */
22521da177e4SLinus Torvalds 	new_se = kmalloc(sizeof(*se), GFP_KERNEL);
22531da177e4SLinus Torvalds 	if (new_se == NULL)
22541da177e4SLinus Torvalds 		return -ENOMEM;
22551da177e4SLinus Torvalds 	new_se->start_page = start_page;
22561da177e4SLinus Torvalds 	new_se->nr_pages = nr_pages;
22571da177e4SLinus Torvalds 	new_se->start_block = start_block;
22581da177e4SLinus Torvalds 
22599625a5f2SHugh Dickins 	list_add_tail(&new_se->list, &sis->first_swap_extent.list);
226053092a74SHugh Dickins 	return 1;
22611da177e4SLinus Torvalds }
2262aa8aa8a3SOmar Sandoval EXPORT_SYMBOL_GPL(add_swap_extent);
22631da177e4SLinus Torvalds 
22641da177e4SLinus Torvalds /*
22651da177e4SLinus Torvalds  * A `swap extent' is a simple thing which maps a contiguous range of pages
22661da177e4SLinus Torvalds  * onto a contiguous range of disk blocks.  An ordered list of swap extents
22671da177e4SLinus Torvalds  * is built at swapon time and is then used at swap_writepage/swap_readpage
22681da177e4SLinus Torvalds  * time for locating where on disk a page belongs.
22691da177e4SLinus Torvalds  *
22701da177e4SLinus Torvalds  * If the swapfile is an S_ISBLK block device, a single extent is installed.
22711da177e4SLinus Torvalds  * This is done so that the main operating code can treat S_ISBLK and S_ISREG
22721da177e4SLinus Torvalds  * swap files identically.
22731da177e4SLinus Torvalds  *
22741da177e4SLinus Torvalds  * Whether the swapdev is an S_ISREG file or an S_ISBLK blockdev, the swap
22751da177e4SLinus Torvalds  * extent list operates in PAGE_SIZE disk blocks.  Both S_ISREG and S_ISBLK
22761da177e4SLinus Torvalds  * swapfiles are handled *identically* after swapon time.
22771da177e4SLinus Torvalds  *
22781da177e4SLinus Torvalds  * For S_ISREG swapfiles, setup_swap_extents() will walk all the file's blocks
22791da177e4SLinus Torvalds  * and will parse them into an ordered extent list, in PAGE_SIZE chunks.  If
22801da177e4SLinus Torvalds  * some stray blocks are found which do not fall within the PAGE_SIZE alignment
22811da177e4SLinus Torvalds  * requirements, they are simply tossed out - we will never use those blocks
22821da177e4SLinus Torvalds  * for swapping.
22831da177e4SLinus Torvalds  *
2284b0d9bcd4SHugh Dickins  * For S_ISREG swapfiles we set S_SWAPFILE across the life of the swapon.  This
22851da177e4SLinus Torvalds  * prevents root from shooting her foot off by ftruncating an in-use swapfile,
22861da177e4SLinus Torvalds  * which will scribble on the fs.
22871da177e4SLinus Torvalds  *
22881da177e4SLinus Torvalds  * The amount of disk space which a single swap extent represents varies.
22891da177e4SLinus Torvalds  * Typically it is in the 1-4 megabyte range.  So we can have hundreds of
22901da177e4SLinus Torvalds  * extents in the list.  To avoid much list walking, we cache the previous
22911da177e4SLinus Torvalds  * search location in `curr_swap_extent', and start new searches from there.
22921da177e4SLinus Torvalds  * This is extremely effective.  The average number of iterations in
22931da177e4SLinus Torvalds  * map_swap_page() has been measured at about 0.3 per page.  - akpm.
22941da177e4SLinus Torvalds  */
229553092a74SHugh Dickins static int setup_swap_extents(struct swap_info_struct *sis, sector_t *span)
22961da177e4SLinus Torvalds {
229762c230bcSMel Gorman 	struct file *swap_file = sis->swap_file;
229862c230bcSMel Gorman 	struct address_space *mapping = swap_file->f_mapping;
229962c230bcSMel Gorman 	struct inode *inode = mapping->host;
23001da177e4SLinus Torvalds 	int ret;
23011da177e4SLinus Torvalds 
23021da177e4SLinus Torvalds 	if (S_ISBLK(inode->i_mode)) {
23031da177e4SLinus Torvalds 		ret = add_swap_extent(sis, 0, sis->max, 0);
230453092a74SHugh Dickins 		*span = sis->pages;
2305a509bc1aSMel Gorman 		return ret;
23061da177e4SLinus Torvalds 	}
23071da177e4SLinus Torvalds 
230862c230bcSMel Gorman 	if (mapping->a_ops->swap_activate) {
2309a509bc1aSMel Gorman 		ret = mapping->a_ops->swap_activate(sis, swap_file, span);
2310bc4ae27dSOmar Sandoval 		if (ret >= 0)
2311bc4ae27dSOmar Sandoval 			sis->flags |= SWP_ACTIVATED;
231262c230bcSMel Gorman 		if (!ret) {
2313bc4ae27dSOmar Sandoval 			sis->flags |= SWP_FS;
231462c230bcSMel Gorman 			ret = add_swap_extent(sis, 0, sis->max, 0);
231562c230bcSMel Gorman 			*span = sis->pages;
231662c230bcSMel Gorman 		}
23179625a5f2SHugh Dickins 		return ret;
2318a509bc1aSMel Gorman 	}
2319a509bc1aSMel Gorman 
2320a509bc1aSMel Gorman 	return generic_swapfile_activate(sis, swap_file, span);
23211da177e4SLinus Torvalds }
23221da177e4SLinus Torvalds 
2323a2468cc9SAaron Lu static int swap_node(struct swap_info_struct *p)
2324a2468cc9SAaron Lu {
2325a2468cc9SAaron Lu 	struct block_device *bdev;
2326a2468cc9SAaron Lu 
2327a2468cc9SAaron Lu 	if (p->bdev)
2328a2468cc9SAaron Lu 		bdev = p->bdev;
2329a2468cc9SAaron Lu 	else
2330a2468cc9SAaron Lu 		bdev = p->swap_file->f_inode->i_sb->s_bdev;
2331a2468cc9SAaron Lu 
2332a2468cc9SAaron Lu 	return bdev ? bdev->bd_disk->node_id : NUMA_NO_NODE;
2333a2468cc9SAaron Lu }
2334a2468cc9SAaron Lu 
2335cf0cac0aSCesar Eduardo Barros static void _enable_swap_info(struct swap_info_struct *p, int prio,
23362a8f9449SShaohua Li 				unsigned char *swap_map,
23372a8f9449SShaohua Li 				struct swap_cluster_info *cluster_info)
233840531542SCesar Eduardo Barros {
2339a2468cc9SAaron Lu 	int i;
2340a2468cc9SAaron Lu 
234140531542SCesar Eduardo Barros 	if (prio >= 0)
234240531542SCesar Eduardo Barros 		p->prio = prio;
234340531542SCesar Eduardo Barros 	else
234440531542SCesar Eduardo Barros 		p->prio = --least_priority;
234518ab4d4cSDan Streetman 	/*
234618ab4d4cSDan Streetman 	 * the plist prio is negated because plist ordering is
234718ab4d4cSDan Streetman 	 * low-to-high, while swap ordering is high-to-low
234818ab4d4cSDan Streetman 	 */
234918ab4d4cSDan Streetman 	p->list.prio = -p->prio;
2350a2468cc9SAaron Lu 	for_each_node(i) {
2351a2468cc9SAaron Lu 		if (p->prio >= 0)
2352a2468cc9SAaron Lu 			p->avail_lists[i].prio = -p->prio;
2353a2468cc9SAaron Lu 		else {
2354a2468cc9SAaron Lu 			if (swap_node(p) == i)
2355a2468cc9SAaron Lu 				p->avail_lists[i].prio = 1;
2356a2468cc9SAaron Lu 			else
2357a2468cc9SAaron Lu 				p->avail_lists[i].prio = -p->prio;
2358a2468cc9SAaron Lu 		}
2359a2468cc9SAaron Lu 	}
236040531542SCesar Eduardo Barros 	p->swap_map = swap_map;
23612a8f9449SShaohua Li 	p->cluster_info = cluster_info;
236240531542SCesar Eduardo Barros 	p->flags |= SWP_WRITEOK;
2363ec8acf20SShaohua Li 	atomic_long_add(p->pages, &nr_swap_pages);
236440531542SCesar Eduardo Barros 	total_swap_pages += p->pages;
236540531542SCesar Eduardo Barros 
2366adfab836SDan Streetman 	assert_spin_locked(&swap_lock);
2367adfab836SDan Streetman 	/*
236818ab4d4cSDan Streetman 	 * both lists are plists, and thus priority ordered.
236918ab4d4cSDan Streetman 	 * swap_active_head needs to be priority ordered for swapoff(),
237018ab4d4cSDan Streetman 	 * which on removal of any swap_info_struct with an auto-assigned
237118ab4d4cSDan Streetman 	 * (i.e. negative) priority increments the auto-assigned priority
237218ab4d4cSDan Streetman 	 * of any lower-priority swap_info_structs.
237318ab4d4cSDan Streetman 	 * swap_avail_head needs to be priority ordered for get_swap_page(),
237418ab4d4cSDan Streetman 	 * which allocates swap pages from the highest available priority
237518ab4d4cSDan Streetman 	 * swap_info_struct.
2376adfab836SDan Streetman 	 */
237718ab4d4cSDan Streetman 	plist_add(&p->list, &swap_active_head);
2378a2468cc9SAaron Lu 	add_to_avail_list(p);
2379cf0cac0aSCesar Eduardo Barros }
2380cf0cac0aSCesar Eduardo Barros 
2381cf0cac0aSCesar Eduardo Barros static void enable_swap_info(struct swap_info_struct *p, int prio,
2382cf0cac0aSCesar Eduardo Barros 				unsigned char *swap_map,
23832a8f9449SShaohua Li 				struct swap_cluster_info *cluster_info,
2384cf0cac0aSCesar Eduardo Barros 				unsigned long *frontswap_map)
2385cf0cac0aSCesar Eduardo Barros {
23864f89849dSMinchan Kim 	frontswap_init(p->type, frontswap_map);
2387cf0cac0aSCesar Eduardo Barros 	spin_lock(&swap_lock);
2388ec8acf20SShaohua Li 	spin_lock(&p->lock);
23892a8f9449SShaohua Li 	 _enable_swap_info(p, prio, swap_map, cluster_info);
2390ec8acf20SShaohua Li 	spin_unlock(&p->lock);
2391cf0cac0aSCesar Eduardo Barros 	spin_unlock(&swap_lock);
2392cf0cac0aSCesar Eduardo Barros }
2393cf0cac0aSCesar Eduardo Barros 
2394cf0cac0aSCesar Eduardo Barros static void reinsert_swap_info(struct swap_info_struct *p)
2395cf0cac0aSCesar Eduardo Barros {
2396cf0cac0aSCesar Eduardo Barros 	spin_lock(&swap_lock);
2397ec8acf20SShaohua Li 	spin_lock(&p->lock);
23982a8f9449SShaohua Li 	_enable_swap_info(p, p->prio, p->swap_map, p->cluster_info);
2399ec8acf20SShaohua Li 	spin_unlock(&p->lock);
240040531542SCesar Eduardo Barros 	spin_unlock(&swap_lock);
240140531542SCesar Eduardo Barros }
240240531542SCesar Eduardo Barros 
240367afa38eSTim Chen bool has_usable_swap(void)
240467afa38eSTim Chen {
240567afa38eSTim Chen 	bool ret = true;
240667afa38eSTim Chen 
240767afa38eSTim Chen 	spin_lock(&swap_lock);
240867afa38eSTim Chen 	if (plist_head_empty(&swap_active_head))
240967afa38eSTim Chen 		ret = false;
241067afa38eSTim Chen 	spin_unlock(&swap_lock);
241167afa38eSTim Chen 	return ret;
241267afa38eSTim Chen }
241367afa38eSTim Chen 
2414c4ea37c2SHeiko Carstens SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
24151da177e4SLinus Torvalds {
24161da177e4SLinus Torvalds 	struct swap_info_struct *p = NULL;
24178d69aaeeSHugh Dickins 	unsigned char *swap_map;
24182a8f9449SShaohua Li 	struct swap_cluster_info *cluster_info;
24194f89849dSMinchan Kim 	unsigned long *frontswap_map;
24201da177e4SLinus Torvalds 	struct file *swap_file, *victim;
24211da177e4SLinus Torvalds 	struct address_space *mapping;
24221da177e4SLinus Torvalds 	struct inode *inode;
242391a27b2aSJeff Layton 	struct filename *pathname;
2424adfab836SDan Streetman 	int err, found = 0;
24255b808a23SKrzysztof Kozlowski 	unsigned int old_block_size;
24261da177e4SLinus Torvalds 
24271da177e4SLinus Torvalds 	if (!capable(CAP_SYS_ADMIN))
24281da177e4SLinus Torvalds 		return -EPERM;
24291da177e4SLinus Torvalds 
2430191c5424SAl Viro 	BUG_ON(!current->mm);
2431191c5424SAl Viro 
24321da177e4SLinus Torvalds 	pathname = getname(specialfile);
24331da177e4SLinus Torvalds 	if (IS_ERR(pathname))
2434f58b59c1SXiaotian Feng 		return PTR_ERR(pathname);
24351da177e4SLinus Torvalds 
2436669abf4eSJeff Layton 	victim = file_open_name(pathname, O_RDWR|O_LARGEFILE, 0);
24371da177e4SLinus Torvalds 	err = PTR_ERR(victim);
24381da177e4SLinus Torvalds 	if (IS_ERR(victim))
24391da177e4SLinus Torvalds 		goto out;
24401da177e4SLinus Torvalds 
24411da177e4SLinus Torvalds 	mapping = victim->f_mapping;
24425d337b91SHugh Dickins 	spin_lock(&swap_lock);
244318ab4d4cSDan Streetman 	plist_for_each_entry(p, &swap_active_head, list) {
244422c6f8fdSHugh Dickins 		if (p->flags & SWP_WRITEOK) {
2445adfab836SDan Streetman 			if (p->swap_file->f_mapping == mapping) {
2446adfab836SDan Streetman 				found = 1;
24471da177e4SLinus Torvalds 				break;
24481da177e4SLinus Torvalds 			}
24491da177e4SLinus Torvalds 		}
2450adfab836SDan Streetman 	}
2451adfab836SDan Streetman 	if (!found) {
24521da177e4SLinus Torvalds 		err = -EINVAL;
24535d337b91SHugh Dickins 		spin_unlock(&swap_lock);
24541da177e4SLinus Torvalds 		goto out_dput;
24551da177e4SLinus Torvalds 	}
2456191c5424SAl Viro 	if (!security_vm_enough_memory_mm(current->mm, p->pages))
24571da177e4SLinus Torvalds 		vm_unacct_memory(p->pages);
24581da177e4SLinus Torvalds 	else {
24591da177e4SLinus Torvalds 		err = -ENOMEM;
24605d337b91SHugh Dickins 		spin_unlock(&swap_lock);
24611da177e4SLinus Torvalds 		goto out_dput;
24621da177e4SLinus Torvalds 	}
2463a2468cc9SAaron Lu 	del_from_avail_list(p);
2464ec8acf20SShaohua Li 	spin_lock(&p->lock);
246578ecba08SHugh Dickins 	if (p->prio < 0) {
2466adfab836SDan Streetman 		struct swap_info_struct *si = p;
2467a2468cc9SAaron Lu 		int nid;
2468adfab836SDan Streetman 
246918ab4d4cSDan Streetman 		plist_for_each_entry_continue(si, &swap_active_head, list) {
2470adfab836SDan Streetman 			si->prio++;
247118ab4d4cSDan Streetman 			si->list.prio--;
2472a2468cc9SAaron Lu 			for_each_node(nid) {
2473a2468cc9SAaron Lu 				if (si->avail_lists[nid].prio != 1)
2474a2468cc9SAaron Lu 					si->avail_lists[nid].prio--;
2475a2468cc9SAaron Lu 			}
2476adfab836SDan Streetman 		}
247778ecba08SHugh Dickins 		least_priority++;
247878ecba08SHugh Dickins 	}
247918ab4d4cSDan Streetman 	plist_del(&p->list, &swap_active_head);
2480ec8acf20SShaohua Li 	atomic_long_sub(p->pages, &nr_swap_pages);
24811da177e4SLinus Torvalds 	total_swap_pages -= p->pages;
24821da177e4SLinus Torvalds 	p->flags &= ~SWP_WRITEOK;
2483ec8acf20SShaohua Li 	spin_unlock(&p->lock);
24845d337b91SHugh Dickins 	spin_unlock(&swap_lock);
2485fb4f88dcSHugh Dickins 
2486039939a6STim Chen 	disable_swap_slots_cache_lock();
2487039939a6STim Chen 
2488e1e12d2fSDavid Rientjes 	set_current_oom_origin();
2489adfab836SDan Streetman 	err = try_to_unuse(p->type, false, 0); /* force unuse all pages */
2490e1e12d2fSDavid Rientjes 	clear_current_oom_origin();
24911da177e4SLinus Torvalds 
24921da177e4SLinus Torvalds 	if (err) {
24931da177e4SLinus Torvalds 		/* re-insert swap space back into swap_list */
2494cf0cac0aSCesar Eduardo Barros 		reinsert_swap_info(p);
2495039939a6STim Chen 		reenable_swap_slots_cache_unlock();
24961da177e4SLinus Torvalds 		goto out_dput;
24971da177e4SLinus Torvalds 	}
249852b7efdbSHugh Dickins 
2499039939a6STim Chen 	reenable_swap_slots_cache_unlock();
2500039939a6STim Chen 
2501815c2c54SShaohua Li 	flush_work(&p->discard_work);
2502815c2c54SShaohua Li 
25034cd3bb10SHugh Dickins 	destroy_swap_extents(p);
2504570a335bSHugh Dickins 	if (p->flags & SWP_CONTINUED)
2505570a335bSHugh Dickins 		free_swap_count_continuations(p);
2506570a335bSHugh Dickins 
250781a0298bSHuang Ying 	if (!p->bdev || !blk_queue_nonrot(bdev_get_queue(p->bdev)))
250881a0298bSHuang Ying 		atomic_dec(&nr_rotate_swap);
250981a0298bSHuang Ying 
2510fc0abb14SIngo Molnar 	mutex_lock(&swapon_mutex);
25115d337b91SHugh Dickins 	spin_lock(&swap_lock);
2512ec8acf20SShaohua Li 	spin_lock(&p->lock);
25131da177e4SLinus Torvalds 	drain_mmlist();
25145d337b91SHugh Dickins 
25155d337b91SHugh Dickins 	/* wait for anyone still in scan_swap_map */
25165d337b91SHugh Dickins 	p->highest_bit = 0;		/* cuts scans short */
25175d337b91SHugh Dickins 	while (p->flags >= SWP_SCANNING) {
2518ec8acf20SShaohua Li 		spin_unlock(&p->lock);
25195d337b91SHugh Dickins 		spin_unlock(&swap_lock);
252013e4b57fSNishanth Aravamudan 		schedule_timeout_uninterruptible(1);
25215d337b91SHugh Dickins 		spin_lock(&swap_lock);
2522ec8acf20SShaohua Li 		spin_lock(&p->lock);
25235d337b91SHugh Dickins 	}
25245d337b91SHugh Dickins 
25251da177e4SLinus Torvalds 	swap_file = p->swap_file;
25265b808a23SKrzysztof Kozlowski 	old_block_size = p->old_block_size;
25271da177e4SLinus Torvalds 	p->swap_file = NULL;
25281da177e4SLinus Torvalds 	p->max = 0;
25291da177e4SLinus Torvalds 	swap_map = p->swap_map;
25301da177e4SLinus Torvalds 	p->swap_map = NULL;
25312a8f9449SShaohua Li 	cluster_info = p->cluster_info;
25322a8f9449SShaohua Li 	p->cluster_info = NULL;
25334f89849dSMinchan Kim 	frontswap_map = frontswap_map_get(p);
2534ec8acf20SShaohua Li 	spin_unlock(&p->lock);
25355d337b91SHugh Dickins 	spin_unlock(&swap_lock);
2536adfab836SDan Streetman 	frontswap_invalidate_area(p->type);
253758e97ba6SKrzysztof Kozlowski 	frontswap_map_set(p, NULL);
2538fc0abb14SIngo Molnar 	mutex_unlock(&swapon_mutex);
2539ebc2a1a6SShaohua Li 	free_percpu(p->percpu_cluster);
2540ebc2a1a6SShaohua Li 	p->percpu_cluster = NULL;
25411da177e4SLinus Torvalds 	vfree(swap_map);
254254f180d3SHuang Ying 	kvfree(cluster_info);
254354f180d3SHuang Ying 	kvfree(frontswap_map);
25442de1a7e4SSeth Jennings 	/* Destroy swap account information */
2545adfab836SDan Streetman 	swap_cgroup_swapoff(p->type);
25464b3ef9daSHuang, Ying 	exit_swap_address_space(p->type);
254727a7faa0SKAMEZAWA Hiroyuki 
25481da177e4SLinus Torvalds 	inode = mapping->host;
25491da177e4SLinus Torvalds 	if (S_ISBLK(inode->i_mode)) {
25501da177e4SLinus Torvalds 		struct block_device *bdev = I_BDEV(inode);
25515b808a23SKrzysztof Kozlowski 		set_blocksize(bdev, old_block_size);
2552e525fd89STejun Heo 		blkdev_put(bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL);
25531da177e4SLinus Torvalds 	} else {
25545955102cSAl Viro 		inode_lock(inode);
25551da177e4SLinus Torvalds 		inode->i_flags &= ~S_SWAPFILE;
25565955102cSAl Viro 		inode_unlock(inode);
25571da177e4SLinus Torvalds 	}
25581da177e4SLinus Torvalds 	filp_close(swap_file, NULL);
2559f893ab41SWeijie Yang 
2560f893ab41SWeijie Yang 	/*
2561f893ab41SWeijie Yang 	 * Clear the SWP_USED flag after all resources are freed so that swapon
2562f893ab41SWeijie Yang 	 * can reuse this swap_info in alloc_swap_info() safely.  It is ok to
2563f893ab41SWeijie Yang 	 * not hold p->lock after we cleared its SWP_WRITEOK.
2564f893ab41SWeijie Yang 	 */
2565f893ab41SWeijie Yang 	spin_lock(&swap_lock);
2566f893ab41SWeijie Yang 	p->flags = 0;
2567f893ab41SWeijie Yang 	spin_unlock(&swap_lock);
2568f893ab41SWeijie Yang 
25691da177e4SLinus Torvalds 	err = 0;
257066d7dd51SKay Sievers 	atomic_inc(&proc_poll_event);
257166d7dd51SKay Sievers 	wake_up_interruptible(&proc_poll_wait);
25721da177e4SLinus Torvalds 
25731da177e4SLinus Torvalds out_dput:
25741da177e4SLinus Torvalds 	filp_close(victim, NULL);
25751da177e4SLinus Torvalds out:
2576f58b59c1SXiaotian Feng 	putname(pathname);
25771da177e4SLinus Torvalds 	return err;
25781da177e4SLinus Torvalds }
25791da177e4SLinus Torvalds 
25801da177e4SLinus Torvalds #ifdef CONFIG_PROC_FS
25819dd95748SAl Viro static __poll_t swaps_poll(struct file *file, poll_table *wait)
258266d7dd51SKay Sievers {
2583f1514638SKay Sievers 	struct seq_file *seq = file->private_data;
258466d7dd51SKay Sievers 
258566d7dd51SKay Sievers 	poll_wait(file, &proc_poll_wait, wait);
258666d7dd51SKay Sievers 
2587f1514638SKay Sievers 	if (seq->poll_event != atomic_read(&proc_poll_event)) {
2588f1514638SKay Sievers 		seq->poll_event = atomic_read(&proc_poll_event);
2589a9a08845SLinus Torvalds 		return EPOLLIN | EPOLLRDNORM | EPOLLERR | EPOLLPRI;
259066d7dd51SKay Sievers 	}
259166d7dd51SKay Sievers 
2592a9a08845SLinus Torvalds 	return EPOLLIN | EPOLLRDNORM;
259366d7dd51SKay Sievers }
259466d7dd51SKay Sievers 
25951da177e4SLinus Torvalds /* iterator */
25961da177e4SLinus Torvalds static void *swap_start(struct seq_file *swap, loff_t *pos)
25971da177e4SLinus Torvalds {
2598efa90a98SHugh Dickins 	struct swap_info_struct *si;
2599efa90a98SHugh Dickins 	int type;
26001da177e4SLinus Torvalds 	loff_t l = *pos;
26011da177e4SLinus Torvalds 
2602fc0abb14SIngo Molnar 	mutex_lock(&swapon_mutex);
26031da177e4SLinus Torvalds 
2604881e4aabSSuleiman Souhlal 	if (!l)
2605881e4aabSSuleiman Souhlal 		return SEQ_START_TOKEN;
2606881e4aabSSuleiman Souhlal 
2607c10d38ccSDaniel Jordan 	for (type = 0; (si = swap_type_to_swap_info(type)); type++) {
2608efa90a98SHugh Dickins 		if (!(si->flags & SWP_USED) || !si->swap_map)
26091da177e4SLinus Torvalds 			continue;
2610881e4aabSSuleiman Souhlal 		if (!--l)
2611efa90a98SHugh Dickins 			return si;
26121da177e4SLinus Torvalds 	}
26131da177e4SLinus Torvalds 
26141da177e4SLinus Torvalds 	return NULL;
26151da177e4SLinus Torvalds }
26161da177e4SLinus Torvalds 
26171da177e4SLinus Torvalds static void *swap_next(struct seq_file *swap, void *v, loff_t *pos)
26181da177e4SLinus Torvalds {
2619efa90a98SHugh Dickins 	struct swap_info_struct *si = v;
2620efa90a98SHugh Dickins 	int type;
26211da177e4SLinus Torvalds 
2622881e4aabSSuleiman Souhlal 	if (v == SEQ_START_TOKEN)
2623efa90a98SHugh Dickins 		type = 0;
2624efa90a98SHugh Dickins 	else
2625efa90a98SHugh Dickins 		type = si->type + 1;
2626881e4aabSSuleiman Souhlal 
2627c10d38ccSDaniel Jordan 	for (; (si = swap_type_to_swap_info(type)); type++) {
2628efa90a98SHugh Dickins 		if (!(si->flags & SWP_USED) || !si->swap_map)
26291da177e4SLinus Torvalds 			continue;
26301da177e4SLinus Torvalds 		++*pos;
2631efa90a98SHugh Dickins 		return si;
26321da177e4SLinus Torvalds 	}
26331da177e4SLinus Torvalds 
26341da177e4SLinus Torvalds 	return NULL;
26351da177e4SLinus Torvalds }
26361da177e4SLinus Torvalds 
26371da177e4SLinus Torvalds static void swap_stop(struct seq_file *swap, void *v)
26381da177e4SLinus Torvalds {
2639fc0abb14SIngo Molnar 	mutex_unlock(&swapon_mutex);
26401da177e4SLinus Torvalds }
26411da177e4SLinus Torvalds 
26421da177e4SLinus Torvalds static int swap_show(struct seq_file *swap, void *v)
26431da177e4SLinus Torvalds {
2644efa90a98SHugh Dickins 	struct swap_info_struct *si = v;
26451da177e4SLinus Torvalds 	struct file *file;
26461da177e4SLinus Torvalds 	int len;
26471da177e4SLinus Torvalds 
2648efa90a98SHugh Dickins 	if (si == SEQ_START_TOKEN) {
26491da177e4SLinus Torvalds 		seq_puts(swap,"Filename\t\t\t\tType\t\tSize\tUsed\tPriority\n");
2650881e4aabSSuleiman Souhlal 		return 0;
2651881e4aabSSuleiman Souhlal 	}
26521da177e4SLinus Torvalds 
2653efa90a98SHugh Dickins 	file = si->swap_file;
26542726d566SMiklos Szeredi 	len = seq_file_path(swap, file, " \t\n\\");
26556eb396dcSHugh Dickins 	seq_printf(swap, "%*s%s\t%u\t%u\t%d\n",
26561da177e4SLinus Torvalds 			len < 40 ? 40 - len : 1, " ",
2657496ad9aaSAl Viro 			S_ISBLK(file_inode(file)->i_mode) ?
26581da177e4SLinus Torvalds 				"partition" : "file\t",
2659efa90a98SHugh Dickins 			si->pages << (PAGE_SHIFT - 10),
2660efa90a98SHugh Dickins 			si->inuse_pages << (PAGE_SHIFT - 10),
2661efa90a98SHugh Dickins 			si->prio);
26621da177e4SLinus Torvalds 	return 0;
26631da177e4SLinus Torvalds }
26641da177e4SLinus Torvalds 
266515ad7cdcSHelge Deller static const struct seq_operations swaps_op = {
26661da177e4SLinus Torvalds 	.start =	swap_start,
26671da177e4SLinus Torvalds 	.next =		swap_next,
26681da177e4SLinus Torvalds 	.stop =		swap_stop,
26691da177e4SLinus Torvalds 	.show =		swap_show
26701da177e4SLinus Torvalds };
26711da177e4SLinus Torvalds 
26721da177e4SLinus Torvalds static int swaps_open(struct inode *inode, struct file *file)
26731da177e4SLinus Torvalds {
2674f1514638SKay Sievers 	struct seq_file *seq;
267566d7dd51SKay Sievers 	int ret;
267666d7dd51SKay Sievers 
267766d7dd51SKay Sievers 	ret = seq_open(file, &swaps_op);
2678f1514638SKay Sievers 	if (ret)
267966d7dd51SKay Sievers 		return ret;
268066d7dd51SKay Sievers 
2681f1514638SKay Sievers 	seq = file->private_data;
2682f1514638SKay Sievers 	seq->poll_event = atomic_read(&proc_poll_event);
2683f1514638SKay Sievers 	return 0;
26841da177e4SLinus Torvalds }
26851da177e4SLinus Torvalds 
268615ad7cdcSHelge Deller static const struct file_operations proc_swaps_operations = {
26871da177e4SLinus Torvalds 	.open		= swaps_open,
26881da177e4SLinus Torvalds 	.read		= seq_read,
26891da177e4SLinus Torvalds 	.llseek		= seq_lseek,
26901da177e4SLinus Torvalds 	.release	= seq_release,
269166d7dd51SKay Sievers 	.poll		= swaps_poll,
26921da177e4SLinus Torvalds };
26931da177e4SLinus Torvalds 
26941da177e4SLinus Torvalds static int __init procswaps_init(void)
26951da177e4SLinus Torvalds {
26963d71f86fSDenis V. Lunev 	proc_create("swaps", 0, NULL, &proc_swaps_operations);
26971da177e4SLinus Torvalds 	return 0;
26981da177e4SLinus Torvalds }
26991da177e4SLinus Torvalds __initcall(procswaps_init);
27001da177e4SLinus Torvalds #endif /* CONFIG_PROC_FS */
27011da177e4SLinus Torvalds 
27021796316aSJan Beulich #ifdef MAX_SWAPFILES_CHECK
27031796316aSJan Beulich static int __init max_swapfiles_check(void)
27041796316aSJan Beulich {
27051796316aSJan Beulich 	MAX_SWAPFILES_CHECK();
27061796316aSJan Beulich 	return 0;
27071796316aSJan Beulich }
27081796316aSJan Beulich late_initcall(max_swapfiles_check);
27091796316aSJan Beulich #endif
27101796316aSJan Beulich 
271153cbb243SCesar Eduardo Barros static struct swap_info_struct *alloc_swap_info(void)
27121da177e4SLinus Torvalds {
27131da177e4SLinus Torvalds 	struct swap_info_struct *p;
27141da177e4SLinus Torvalds 	unsigned int type;
2715a2468cc9SAaron Lu 	int i;
2716efa90a98SHugh Dickins 
2717*96008744SGustavo A. R. Silva 	p = kvzalloc(struct_size(p, avail_lists, nr_node_ids), GFP_KERNEL);
2718efa90a98SHugh Dickins 	if (!p)
271953cbb243SCesar Eduardo Barros 		return ERR_PTR(-ENOMEM);
2720efa90a98SHugh Dickins 
27215d337b91SHugh Dickins 	spin_lock(&swap_lock);
2722efa90a98SHugh Dickins 	for (type = 0; type < nr_swapfiles; type++) {
2723efa90a98SHugh Dickins 		if (!(swap_info[type]->flags & SWP_USED))
27241da177e4SLinus Torvalds 			break;
2725efa90a98SHugh Dickins 	}
27260697212aSChristoph Lameter 	if (type >= MAX_SWAPFILES) {
27275d337b91SHugh Dickins 		spin_unlock(&swap_lock);
2728873d7bcfSVasily Averin 		kvfree(p);
2729730c0581SCesar Eduardo Barros 		return ERR_PTR(-EPERM);
27301da177e4SLinus Torvalds 	}
2731efa90a98SHugh Dickins 	if (type >= nr_swapfiles) {
2732efa90a98SHugh Dickins 		p->type = type;
2733c10d38ccSDaniel Jordan 		WRITE_ONCE(swap_info[type], p);
2734efa90a98SHugh Dickins 		/*
2735efa90a98SHugh Dickins 		 * Write swap_info[type] before nr_swapfiles, in case a
2736efa90a98SHugh Dickins 		 * racing procfs swap_start() or swap_next() is reading them.
2737efa90a98SHugh Dickins 		 * (We never shrink nr_swapfiles, we never free this entry.)
2738efa90a98SHugh Dickins 		 */
2739efa90a98SHugh Dickins 		smp_wmb();
2740c10d38ccSDaniel Jordan 		WRITE_ONCE(nr_swapfiles, nr_swapfiles + 1);
2741efa90a98SHugh Dickins 	} else {
2742873d7bcfSVasily Averin 		kvfree(p);
2743efa90a98SHugh Dickins 		p = swap_info[type];
2744efa90a98SHugh Dickins 		/*
2745efa90a98SHugh Dickins 		 * Do not memset this entry: a racing procfs swap_next()
2746efa90a98SHugh Dickins 		 * would be relying on p->type to remain valid.
2747efa90a98SHugh Dickins 		 */
2748efa90a98SHugh Dickins 	}
27499625a5f2SHugh Dickins 	INIT_LIST_HEAD(&p->first_swap_extent.list);
275018ab4d4cSDan Streetman 	plist_node_init(&p->list, 0);
2751a2468cc9SAaron Lu 	for_each_node(i)
2752a2468cc9SAaron Lu 		plist_node_init(&p->avail_lists[i], 0);
27531da177e4SLinus Torvalds 	p->flags = SWP_USED;
27545d337b91SHugh Dickins 	spin_unlock(&swap_lock);
2755ec8acf20SShaohua Li 	spin_lock_init(&p->lock);
27562628bd6fSHuang Ying 	spin_lock_init(&p->cont_lock);
2757efa90a98SHugh Dickins 
275853cbb243SCesar Eduardo Barros 	return p;
275953cbb243SCesar Eduardo Barros }
276053cbb243SCesar Eduardo Barros 
27614d0e1e10SCesar Eduardo Barros static int claim_swapfile(struct swap_info_struct *p, struct inode *inode)
27624d0e1e10SCesar Eduardo Barros {
27634d0e1e10SCesar Eduardo Barros 	int error;
27644d0e1e10SCesar Eduardo Barros 
27654d0e1e10SCesar Eduardo Barros 	if (S_ISBLK(inode->i_mode)) {
27664d0e1e10SCesar Eduardo Barros 		p->bdev = bdgrab(I_BDEV(inode));
27674d0e1e10SCesar Eduardo Barros 		error = blkdev_get(p->bdev,
27686f179af8SHugh Dickins 				   FMODE_READ | FMODE_WRITE | FMODE_EXCL, p);
27694d0e1e10SCesar Eduardo Barros 		if (error < 0) {
27704d0e1e10SCesar Eduardo Barros 			p->bdev = NULL;
27716f179af8SHugh Dickins 			return error;
27724d0e1e10SCesar Eduardo Barros 		}
27734d0e1e10SCesar Eduardo Barros 		p->old_block_size = block_size(p->bdev);
27744d0e1e10SCesar Eduardo Barros 		error = set_blocksize(p->bdev, PAGE_SIZE);
27754d0e1e10SCesar Eduardo Barros 		if (error < 0)
277687ade72aSCesar Eduardo Barros 			return error;
27774d0e1e10SCesar Eduardo Barros 		p->flags |= SWP_BLKDEV;
27784d0e1e10SCesar Eduardo Barros 	} else if (S_ISREG(inode->i_mode)) {
27794d0e1e10SCesar Eduardo Barros 		p->bdev = inode->i_sb->s_bdev;
27805955102cSAl Viro 		inode_lock(inode);
278187ade72aSCesar Eduardo Barros 		if (IS_SWAPFILE(inode))
278287ade72aSCesar Eduardo Barros 			return -EBUSY;
278387ade72aSCesar Eduardo Barros 	} else
278487ade72aSCesar Eduardo Barros 		return -EINVAL;
27854d0e1e10SCesar Eduardo Barros 
27864d0e1e10SCesar Eduardo Barros 	return 0;
27874d0e1e10SCesar Eduardo Barros }
27884d0e1e10SCesar Eduardo Barros 
2789377eeaa8SAndi Kleen 
2790377eeaa8SAndi Kleen /*
2791377eeaa8SAndi Kleen  * Find out how many pages are allowed for a single swap device. There
2792377eeaa8SAndi Kleen  * are two limiting factors:
2793377eeaa8SAndi Kleen  * 1) the number of bits for the swap offset in the swp_entry_t type, and
2794377eeaa8SAndi Kleen  * 2) the number of bits in the swap pte, as defined by the different
2795377eeaa8SAndi Kleen  * architectures.
2796377eeaa8SAndi Kleen  *
2797377eeaa8SAndi Kleen  * In order to find the largest possible bit mask, a swap entry with
2798377eeaa8SAndi Kleen  * swap type 0 and swap offset ~0UL is created, encoded to a swap pte,
2799377eeaa8SAndi Kleen  * decoded to a swp_entry_t again, and finally the swap offset is
2800377eeaa8SAndi Kleen  * extracted.
2801377eeaa8SAndi Kleen  *
2802377eeaa8SAndi Kleen  * This will mask all the bits from the initial ~0UL mask that can't
2803377eeaa8SAndi Kleen  * be encoded in either the swp_entry_t or the architecture definition
2804377eeaa8SAndi Kleen  * of a swap pte.
2805377eeaa8SAndi Kleen  */
2806377eeaa8SAndi Kleen unsigned long generic_max_swapfile_size(void)
2807377eeaa8SAndi Kleen {
2808377eeaa8SAndi Kleen 	return swp_offset(pte_to_swp_entry(
2809377eeaa8SAndi Kleen 			swp_entry_to_pte(swp_entry(0, ~0UL)))) + 1;
2810377eeaa8SAndi Kleen }
2811377eeaa8SAndi Kleen 
2812377eeaa8SAndi Kleen /* Can be overridden by an architecture for additional checks. */
2813377eeaa8SAndi Kleen __weak unsigned long max_swapfile_size(void)
2814377eeaa8SAndi Kleen {
2815377eeaa8SAndi Kleen 	return generic_max_swapfile_size();
2816377eeaa8SAndi Kleen }
2817377eeaa8SAndi Kleen 
2818ca8bd38bSCesar Eduardo Barros static unsigned long read_swap_header(struct swap_info_struct *p,
2819ca8bd38bSCesar Eduardo Barros 					union swap_header *swap_header,
2820ca8bd38bSCesar Eduardo Barros 					struct inode *inode)
2821ca8bd38bSCesar Eduardo Barros {
2822ca8bd38bSCesar Eduardo Barros 	int i;
2823ca8bd38bSCesar Eduardo Barros 	unsigned long maxpages;
2824ca8bd38bSCesar Eduardo Barros 	unsigned long swapfilepages;
2825d6bbbd29SRaymond Jennings 	unsigned long last_page;
2826ca8bd38bSCesar Eduardo Barros 
2827ca8bd38bSCesar Eduardo Barros 	if (memcmp("SWAPSPACE2", swap_header->magic.magic, 10)) {
2828465c47fdSAndrew Morton 		pr_err("Unable to find swap-space signature\n");
282938719025SCesar Eduardo Barros 		return 0;
2830ca8bd38bSCesar Eduardo Barros 	}
2831ca8bd38bSCesar Eduardo Barros 
2832ca8bd38bSCesar Eduardo Barros 	/* swap partition endianess hack... */
2833ca8bd38bSCesar Eduardo Barros 	if (swab32(swap_header->info.version) == 1) {
2834ca8bd38bSCesar Eduardo Barros 		swab32s(&swap_header->info.version);
2835ca8bd38bSCesar Eduardo Barros 		swab32s(&swap_header->info.last_page);
2836ca8bd38bSCesar Eduardo Barros 		swab32s(&swap_header->info.nr_badpages);
2837dd111be6SJann Horn 		if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES)
2838dd111be6SJann Horn 			return 0;
2839ca8bd38bSCesar Eduardo Barros 		for (i = 0; i < swap_header->info.nr_badpages; i++)
2840ca8bd38bSCesar Eduardo Barros 			swab32s(&swap_header->info.badpages[i]);
2841ca8bd38bSCesar Eduardo Barros 	}
2842ca8bd38bSCesar Eduardo Barros 	/* Check the swap header's sub-version */
2843ca8bd38bSCesar Eduardo Barros 	if (swap_header->info.version != 1) {
2844465c47fdSAndrew Morton 		pr_warn("Unable to handle swap header version %d\n",
2845ca8bd38bSCesar Eduardo Barros 			swap_header->info.version);
284638719025SCesar Eduardo Barros 		return 0;
2847ca8bd38bSCesar Eduardo Barros 	}
2848ca8bd38bSCesar Eduardo Barros 
2849ca8bd38bSCesar Eduardo Barros 	p->lowest_bit  = 1;
2850ca8bd38bSCesar Eduardo Barros 	p->cluster_next = 1;
2851ca8bd38bSCesar Eduardo Barros 	p->cluster_nr = 0;
2852ca8bd38bSCesar Eduardo Barros 
2853377eeaa8SAndi Kleen 	maxpages = max_swapfile_size();
2854d6bbbd29SRaymond Jennings 	last_page = swap_header->info.last_page;
2855a06ad633STom Abraham 	if (!last_page) {
2856a06ad633STom Abraham 		pr_warn("Empty swap-file\n");
2857a06ad633STom Abraham 		return 0;
2858a06ad633STom Abraham 	}
2859d6bbbd29SRaymond Jennings 	if (last_page > maxpages) {
2860465c47fdSAndrew Morton 		pr_warn("Truncating oversized swap area, only using %luk out of %luk\n",
2861d6bbbd29SRaymond Jennings 			maxpages << (PAGE_SHIFT - 10),
2862d6bbbd29SRaymond Jennings 			last_page << (PAGE_SHIFT - 10));
2863d6bbbd29SRaymond Jennings 	}
2864d6bbbd29SRaymond Jennings 	if (maxpages > last_page) {
2865d6bbbd29SRaymond Jennings 		maxpages = last_page + 1;
2866ca8bd38bSCesar Eduardo Barros 		/* p->max is an unsigned int: don't overflow it */
2867ca8bd38bSCesar Eduardo Barros 		if ((unsigned int)maxpages == 0)
2868ca8bd38bSCesar Eduardo Barros 			maxpages = UINT_MAX;
2869ca8bd38bSCesar Eduardo Barros 	}
2870ca8bd38bSCesar Eduardo Barros 	p->highest_bit = maxpages - 1;
2871ca8bd38bSCesar Eduardo Barros 
2872ca8bd38bSCesar Eduardo Barros 	if (!maxpages)
287338719025SCesar Eduardo Barros 		return 0;
2874ca8bd38bSCesar Eduardo Barros 	swapfilepages = i_size_read(inode) >> PAGE_SHIFT;
2875ca8bd38bSCesar Eduardo Barros 	if (swapfilepages && maxpages > swapfilepages) {
2876465c47fdSAndrew Morton 		pr_warn("Swap area shorter than signature indicates\n");
287738719025SCesar Eduardo Barros 		return 0;
2878ca8bd38bSCesar Eduardo Barros 	}
2879ca8bd38bSCesar Eduardo Barros 	if (swap_header->info.nr_badpages && S_ISREG(inode->i_mode))
288038719025SCesar Eduardo Barros 		return 0;
2881ca8bd38bSCesar Eduardo Barros 	if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES)
288238719025SCesar Eduardo Barros 		return 0;
2883ca8bd38bSCesar Eduardo Barros 
2884ca8bd38bSCesar Eduardo Barros 	return maxpages;
2885ca8bd38bSCesar Eduardo Barros }
2886ca8bd38bSCesar Eduardo Barros 
28874b3ef9daSHuang, Ying #define SWAP_CLUSTER_INFO_COLS						\
2888235b6217SHuang, Ying 	DIV_ROUND_UP(L1_CACHE_BYTES, sizeof(struct swap_cluster_info))
28894b3ef9daSHuang, Ying #define SWAP_CLUSTER_SPACE_COLS						\
28904b3ef9daSHuang, Ying 	DIV_ROUND_UP(SWAP_ADDRESS_SPACE_PAGES, SWAPFILE_CLUSTER)
28914b3ef9daSHuang, Ying #define SWAP_CLUSTER_COLS						\
28924b3ef9daSHuang, Ying 	max_t(unsigned int, SWAP_CLUSTER_INFO_COLS, SWAP_CLUSTER_SPACE_COLS)
2893235b6217SHuang, Ying 
2894915d4d7bSCesar Eduardo Barros static int setup_swap_map_and_extents(struct swap_info_struct *p,
2895915d4d7bSCesar Eduardo Barros 					union swap_header *swap_header,
2896915d4d7bSCesar Eduardo Barros 					unsigned char *swap_map,
28972a8f9449SShaohua Li 					struct swap_cluster_info *cluster_info,
2898915d4d7bSCesar Eduardo Barros 					unsigned long maxpages,
2899915d4d7bSCesar Eduardo Barros 					sector_t *span)
2900915d4d7bSCesar Eduardo Barros {
2901235b6217SHuang, Ying 	unsigned int j, k;
2902915d4d7bSCesar Eduardo Barros 	unsigned int nr_good_pages;
2903915d4d7bSCesar Eduardo Barros 	int nr_extents;
29042a8f9449SShaohua Li 	unsigned long nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
2905235b6217SHuang, Ying 	unsigned long col = p->cluster_next / SWAPFILE_CLUSTER % SWAP_CLUSTER_COLS;
2906235b6217SHuang, Ying 	unsigned long i, idx;
2907915d4d7bSCesar Eduardo Barros 
2908915d4d7bSCesar Eduardo Barros 	nr_good_pages = maxpages - 1;	/* omit header page */
2909915d4d7bSCesar Eduardo Barros 
29106b534915SHuang Ying 	cluster_list_init(&p->free_clusters);
29116b534915SHuang Ying 	cluster_list_init(&p->discard_clusters);
29122a8f9449SShaohua Li 
2913915d4d7bSCesar Eduardo Barros 	for (i = 0; i < swap_header->info.nr_badpages; i++) {
2914915d4d7bSCesar Eduardo Barros 		unsigned int page_nr = swap_header->info.badpages[i];
2915bdb8e3f6SCesar Eduardo Barros 		if (page_nr == 0 || page_nr > swap_header->info.last_page)
2916bdb8e3f6SCesar Eduardo Barros 			return -EINVAL;
2917915d4d7bSCesar Eduardo Barros 		if (page_nr < maxpages) {
2918915d4d7bSCesar Eduardo Barros 			swap_map[page_nr] = SWAP_MAP_BAD;
2919915d4d7bSCesar Eduardo Barros 			nr_good_pages--;
29202a8f9449SShaohua Li 			/*
29212a8f9449SShaohua Li 			 * Haven't marked the cluster free yet, no list
29222a8f9449SShaohua Li 			 * operation involved
29232a8f9449SShaohua Li 			 */
29242a8f9449SShaohua Li 			inc_cluster_info_page(p, cluster_info, page_nr);
2925915d4d7bSCesar Eduardo Barros 		}
2926915d4d7bSCesar Eduardo Barros 	}
2927915d4d7bSCesar Eduardo Barros 
29282a8f9449SShaohua Li 	/* Haven't marked the cluster free yet, no list operation involved */
29292a8f9449SShaohua Li 	for (i = maxpages; i < round_up(maxpages, SWAPFILE_CLUSTER); i++)
29302a8f9449SShaohua Li 		inc_cluster_info_page(p, cluster_info, i);
29312a8f9449SShaohua Li 
2932915d4d7bSCesar Eduardo Barros 	if (nr_good_pages) {
2933915d4d7bSCesar Eduardo Barros 		swap_map[0] = SWAP_MAP_BAD;
29342a8f9449SShaohua Li 		/*
29352a8f9449SShaohua Li 		 * Not mark the cluster free yet, no list
29362a8f9449SShaohua Li 		 * operation involved
29372a8f9449SShaohua Li 		 */
29382a8f9449SShaohua Li 		inc_cluster_info_page(p, cluster_info, 0);
2939915d4d7bSCesar Eduardo Barros 		p->max = maxpages;
2940915d4d7bSCesar Eduardo Barros 		p->pages = nr_good_pages;
2941915d4d7bSCesar Eduardo Barros 		nr_extents = setup_swap_extents(p, span);
2942bdb8e3f6SCesar Eduardo Barros 		if (nr_extents < 0)
2943bdb8e3f6SCesar Eduardo Barros 			return nr_extents;
2944915d4d7bSCesar Eduardo Barros 		nr_good_pages = p->pages;
2945915d4d7bSCesar Eduardo Barros 	}
2946915d4d7bSCesar Eduardo Barros 	if (!nr_good_pages) {
2947465c47fdSAndrew Morton 		pr_warn("Empty swap-file\n");
2948bdb8e3f6SCesar Eduardo Barros 		return -EINVAL;
2949915d4d7bSCesar Eduardo Barros 	}
2950915d4d7bSCesar Eduardo Barros 
29512a8f9449SShaohua Li 	if (!cluster_info)
29522a8f9449SShaohua Li 		return nr_extents;
29532a8f9449SShaohua Li 
2954235b6217SHuang, Ying 
29554b3ef9daSHuang, Ying 	/*
29564b3ef9daSHuang, Ying 	 * Reduce false cache line sharing between cluster_info and
29574b3ef9daSHuang, Ying 	 * sharing same address space.
29584b3ef9daSHuang, Ying 	 */
2959235b6217SHuang, Ying 	for (k = 0; k < SWAP_CLUSTER_COLS; k++) {
2960235b6217SHuang, Ying 		j = (k + col) % SWAP_CLUSTER_COLS;
2961235b6217SHuang, Ying 		for (i = 0; i < DIV_ROUND_UP(nr_clusters, SWAP_CLUSTER_COLS); i++) {
2962235b6217SHuang, Ying 			idx = i * SWAP_CLUSTER_COLS + j;
2963235b6217SHuang, Ying 			if (idx >= nr_clusters)
2964235b6217SHuang, Ying 				continue;
2965235b6217SHuang, Ying 			if (cluster_count(&cluster_info[idx]))
2966235b6217SHuang, Ying 				continue;
29672a8f9449SShaohua Li 			cluster_set_flag(&cluster_info[idx], CLUSTER_FLAG_FREE);
29686b534915SHuang Ying 			cluster_list_add_tail(&p->free_clusters, cluster_info,
29696b534915SHuang Ying 					      idx);
29702a8f9449SShaohua Li 		}
29712a8f9449SShaohua Li 	}
2972915d4d7bSCesar Eduardo Barros 	return nr_extents;
2973915d4d7bSCesar Eduardo Barros }
2974915d4d7bSCesar Eduardo Barros 
2975dcf6b7ddSRafael Aquini /*
2976dcf6b7ddSRafael Aquini  * Helper to sys_swapon determining if a given swap
2977dcf6b7ddSRafael Aquini  * backing device queue supports DISCARD operations.
2978dcf6b7ddSRafael Aquini  */
2979dcf6b7ddSRafael Aquini static bool swap_discardable(struct swap_info_struct *si)
2980dcf6b7ddSRafael Aquini {
2981dcf6b7ddSRafael Aquini 	struct request_queue *q = bdev_get_queue(si->bdev);
2982dcf6b7ddSRafael Aquini 
2983dcf6b7ddSRafael Aquini 	if (!q || !blk_queue_discard(q))
2984dcf6b7ddSRafael Aquini 		return false;
2985dcf6b7ddSRafael Aquini 
2986dcf6b7ddSRafael Aquini 	return true;
2987dcf6b7ddSRafael Aquini }
2988dcf6b7ddSRafael Aquini 
298953cbb243SCesar Eduardo Barros SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
299053cbb243SCesar Eduardo Barros {
299153cbb243SCesar Eduardo Barros 	struct swap_info_struct *p;
299291a27b2aSJeff Layton 	struct filename *name;
299353cbb243SCesar Eduardo Barros 	struct file *swap_file = NULL;
299453cbb243SCesar Eduardo Barros 	struct address_space *mapping;
299540531542SCesar Eduardo Barros 	int prio;
299653cbb243SCesar Eduardo Barros 	int error;
299753cbb243SCesar Eduardo Barros 	union swap_header *swap_header;
2998915d4d7bSCesar Eduardo Barros 	int nr_extents;
299953cbb243SCesar Eduardo Barros 	sector_t span;
300053cbb243SCesar Eduardo Barros 	unsigned long maxpages;
300153cbb243SCesar Eduardo Barros 	unsigned char *swap_map = NULL;
30022a8f9449SShaohua Li 	struct swap_cluster_info *cluster_info = NULL;
300338b5faf4SDan Magenheimer 	unsigned long *frontswap_map = NULL;
300453cbb243SCesar Eduardo Barros 	struct page *page = NULL;
300553cbb243SCesar Eduardo Barros 	struct inode *inode = NULL;
30067cbf3192SOmar Sandoval 	bool inced_nr_rotate_swap = false;
300753cbb243SCesar Eduardo Barros 
3008d15cab97SHugh Dickins 	if (swap_flags & ~SWAP_FLAGS_VALID)
3009d15cab97SHugh Dickins 		return -EINVAL;
3010d15cab97SHugh Dickins 
301153cbb243SCesar Eduardo Barros 	if (!capable(CAP_SYS_ADMIN))
301253cbb243SCesar Eduardo Barros 		return -EPERM;
301353cbb243SCesar Eduardo Barros 
3014a2468cc9SAaron Lu 	if (!swap_avail_heads)
3015a2468cc9SAaron Lu 		return -ENOMEM;
3016a2468cc9SAaron Lu 
301753cbb243SCesar Eduardo Barros 	p = alloc_swap_info();
30182542e513SCesar Eduardo Barros 	if (IS_ERR(p))
30192542e513SCesar Eduardo Barros 		return PTR_ERR(p);
302053cbb243SCesar Eduardo Barros 
3021815c2c54SShaohua Li 	INIT_WORK(&p->discard_work, swap_discard_work);
3022815c2c54SShaohua Li 
30231da177e4SLinus Torvalds 	name = getname(specialfile);
30241da177e4SLinus Torvalds 	if (IS_ERR(name)) {
30257de7fb6bSCesar Eduardo Barros 		error = PTR_ERR(name);
30261da177e4SLinus Torvalds 		name = NULL;
3027bd69010bSCesar Eduardo Barros 		goto bad_swap;
30281da177e4SLinus Torvalds 	}
3029669abf4eSJeff Layton 	swap_file = file_open_name(name, O_RDWR|O_LARGEFILE, 0);
30301da177e4SLinus Torvalds 	if (IS_ERR(swap_file)) {
30317de7fb6bSCesar Eduardo Barros 		error = PTR_ERR(swap_file);
30321da177e4SLinus Torvalds 		swap_file = NULL;
3033bd69010bSCesar Eduardo Barros 		goto bad_swap;
30341da177e4SLinus Torvalds 	}
30351da177e4SLinus Torvalds 
30361da177e4SLinus Torvalds 	p->swap_file = swap_file;
30371da177e4SLinus Torvalds 	mapping = swap_file->f_mapping;
30382130781eSCesar Eduardo Barros 	inode = mapping->host;
30396f179af8SHugh Dickins 
30405955102cSAl Viro 	/* If S_ISREG(inode->i_mode) will do inode_lock(inode); */
30414d0e1e10SCesar Eduardo Barros 	error = claim_swapfile(p, inode);
30424d0e1e10SCesar Eduardo Barros 	if (unlikely(error))
30431da177e4SLinus Torvalds 		goto bad_swap;
30441da177e4SLinus Torvalds 
30451da177e4SLinus Torvalds 	/*
30461da177e4SLinus Torvalds 	 * Read the swap header.
30471da177e4SLinus Torvalds 	 */
30481da177e4SLinus Torvalds 	if (!mapping->a_ops->readpage) {
30491da177e4SLinus Torvalds 		error = -EINVAL;
30501da177e4SLinus Torvalds 		goto bad_swap;
30511da177e4SLinus Torvalds 	}
3052090d2b18SPekka Enberg 	page = read_mapping_page(mapping, 0, swap_file);
30531da177e4SLinus Torvalds 	if (IS_ERR(page)) {
30541da177e4SLinus Torvalds 		error = PTR_ERR(page);
30551da177e4SLinus Torvalds 		goto bad_swap;
30561da177e4SLinus Torvalds 	}
305781e33971SHugh Dickins 	swap_header = kmap(page);
30581da177e4SLinus Torvalds 
3059ca8bd38bSCesar Eduardo Barros 	maxpages = read_swap_header(p, swap_header, inode);
3060ca8bd38bSCesar Eduardo Barros 	if (unlikely(!maxpages)) {
30611da177e4SLinus Torvalds 		error = -EINVAL;
30621da177e4SLinus Torvalds 		goto bad_swap;
30631da177e4SLinus Torvalds 	}
30641da177e4SLinus Torvalds 
30651da177e4SLinus Torvalds 	/* OK, set up the swap map and apply the bad block list */
3066803d0c83SCesar Eduardo Barros 	swap_map = vzalloc(maxpages);
306778ecba08SHugh Dickins 	if (!swap_map) {
30681da177e4SLinus Torvalds 		error = -ENOMEM;
30691da177e4SLinus Torvalds 		goto bad_swap;
30701da177e4SLinus Torvalds 	}
3071f0571429SMinchan Kim 
3072f0571429SMinchan Kim 	if (bdi_cap_stable_pages_required(inode_to_bdi(inode)))
3073f0571429SMinchan Kim 		p->flags |= SWP_STABLE_WRITES;
3074f0571429SMinchan Kim 
3075539a6feaSMinchan Kim 	if (bdi_cap_synchronous_io(inode_to_bdi(inode)))
3076539a6feaSMinchan Kim 		p->flags |= SWP_SYNCHRONOUS_IO;
3077539a6feaSMinchan Kim 
30782a8f9449SShaohua Li 	if (p->bdev && blk_queue_nonrot(bdev_get_queue(p->bdev))) {
30796f179af8SHugh Dickins 		int cpu;
3080235b6217SHuang, Ying 		unsigned long ci, nr_cluster;
30816f179af8SHugh Dickins 
30822a8f9449SShaohua Li 		p->flags |= SWP_SOLIDSTATE;
30832a8f9449SShaohua Li 		/*
30842a8f9449SShaohua Li 		 * select a random position to start with to help wear leveling
30852a8f9449SShaohua Li 		 * SSD
30862a8f9449SShaohua Li 		 */
30872a8f9449SShaohua Li 		p->cluster_next = 1 + (prandom_u32() % p->highest_bit);
3088235b6217SHuang, Ying 		nr_cluster = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
30892a8f9449SShaohua Li 
3090778e1cddSKees Cook 		cluster_info = kvcalloc(nr_cluster, sizeof(*cluster_info),
309154f180d3SHuang Ying 					GFP_KERNEL);
30922a8f9449SShaohua Li 		if (!cluster_info) {
30932a8f9449SShaohua Li 			error = -ENOMEM;
30942a8f9449SShaohua Li 			goto bad_swap;
30952a8f9449SShaohua Li 		}
3096235b6217SHuang, Ying 
3097235b6217SHuang, Ying 		for (ci = 0; ci < nr_cluster; ci++)
3098235b6217SHuang, Ying 			spin_lock_init(&((cluster_info + ci)->lock));
3099235b6217SHuang, Ying 
3100ebc2a1a6SShaohua Li 		p->percpu_cluster = alloc_percpu(struct percpu_cluster);
3101ebc2a1a6SShaohua Li 		if (!p->percpu_cluster) {
3102ebc2a1a6SShaohua Li 			error = -ENOMEM;
3103ebc2a1a6SShaohua Li 			goto bad_swap;
3104ebc2a1a6SShaohua Li 		}
31056f179af8SHugh Dickins 		for_each_possible_cpu(cpu) {
3106ebc2a1a6SShaohua Li 			struct percpu_cluster *cluster;
31076f179af8SHugh Dickins 			cluster = per_cpu_ptr(p->percpu_cluster, cpu);
3108ebc2a1a6SShaohua Li 			cluster_set_null(&cluster->index);
3109ebc2a1a6SShaohua Li 		}
31107cbf3192SOmar Sandoval 	} else {
311181a0298bSHuang Ying 		atomic_inc(&nr_rotate_swap);
31127cbf3192SOmar Sandoval 		inced_nr_rotate_swap = true;
31137cbf3192SOmar Sandoval 	}
31141da177e4SLinus Torvalds 
31151421ef3cSCesar Eduardo Barros 	error = swap_cgroup_swapon(p->type, maxpages);
31161421ef3cSCesar Eduardo Barros 	if (error)
31171421ef3cSCesar Eduardo Barros 		goto bad_swap;
31181421ef3cSCesar Eduardo Barros 
3119915d4d7bSCesar Eduardo Barros 	nr_extents = setup_swap_map_and_extents(p, swap_header, swap_map,
31202a8f9449SShaohua Li 		cluster_info, maxpages, &span);
3121915d4d7bSCesar Eduardo Barros 	if (unlikely(nr_extents < 0)) {
312253092a74SHugh Dickins 		error = nr_extents;
3123e2244ec2SHugh Dickins 		goto bad_swap;
312453092a74SHugh Dickins 	}
312538b5faf4SDan Magenheimer 	/* frontswap enabled? set up bit-per-page map for frontswap */
31268ea1d2a1SVlastimil Babka 	if (IS_ENABLED(CONFIG_FRONTSWAP))
3127778e1cddSKees Cook 		frontswap_map = kvcalloc(BITS_TO_LONGS(maxpages),
3128778e1cddSKees Cook 					 sizeof(long),
312954f180d3SHuang Ying 					 GFP_KERNEL);
31301da177e4SLinus Torvalds 
31312a8f9449SShaohua Li 	if (p->bdev &&(swap_flags & SWAP_FLAG_DISCARD) && swap_discardable(p)) {
3132dcf6b7ddSRafael Aquini 		/*
3133dcf6b7ddSRafael Aquini 		 * When discard is enabled for swap with no particular
3134dcf6b7ddSRafael Aquini 		 * policy flagged, we set all swap discard flags here in
3135dcf6b7ddSRafael Aquini 		 * order to sustain backward compatibility with older
3136dcf6b7ddSRafael Aquini 		 * swapon(8) releases.
3137dcf6b7ddSRafael Aquini 		 */
3138dcf6b7ddSRafael Aquini 		p->flags |= (SWP_DISCARDABLE | SWP_AREA_DISCARD |
3139dcf6b7ddSRafael Aquini 			     SWP_PAGE_DISCARD);
3140dcf6b7ddSRafael Aquini 
3141dcf6b7ddSRafael Aquini 		/*
3142dcf6b7ddSRafael Aquini 		 * By flagging sys_swapon, a sysadmin can tell us to
3143dcf6b7ddSRafael Aquini 		 * either do single-time area discards only, or to just
3144dcf6b7ddSRafael Aquini 		 * perform discards for released swap page-clusters.
3145dcf6b7ddSRafael Aquini 		 * Now it's time to adjust the p->flags accordingly.
3146dcf6b7ddSRafael Aquini 		 */
3147dcf6b7ddSRafael Aquini 		if (swap_flags & SWAP_FLAG_DISCARD_ONCE)
3148dcf6b7ddSRafael Aquini 			p->flags &= ~SWP_PAGE_DISCARD;
3149dcf6b7ddSRafael Aquini 		else if (swap_flags & SWAP_FLAG_DISCARD_PAGES)
3150dcf6b7ddSRafael Aquini 			p->flags &= ~SWP_AREA_DISCARD;
3151dcf6b7ddSRafael Aquini 
3152dcf6b7ddSRafael Aquini 		/* issue a swapon-time discard if it's still required */
3153dcf6b7ddSRafael Aquini 		if (p->flags & SWP_AREA_DISCARD) {
3154dcf6b7ddSRafael Aquini 			int err = discard_swap(p);
3155dcf6b7ddSRafael Aquini 			if (unlikely(err))
3156465c47fdSAndrew Morton 				pr_err("swapon: discard_swap(%p): %d\n",
3157dcf6b7ddSRafael Aquini 					p, err);
3158dcf6b7ddSRafael Aquini 		}
3159dcf6b7ddSRafael Aquini 	}
31606a6ba831SHugh Dickins 
31614b3ef9daSHuang, Ying 	error = init_swap_address_space(p->type, maxpages);
31624b3ef9daSHuang, Ying 	if (error)
31634b3ef9daSHuang, Ying 		goto bad_swap;
31644b3ef9daSHuang, Ying 
3165fc0abb14SIngo Molnar 	mutex_lock(&swapon_mutex);
316640531542SCesar Eduardo Barros 	prio = -1;
316778ecba08SHugh Dickins 	if (swap_flags & SWAP_FLAG_PREFER)
316840531542SCesar Eduardo Barros 		prio =
316978ecba08SHugh Dickins 		  (swap_flags & SWAP_FLAG_PRIO_MASK) >> SWAP_FLAG_PRIO_SHIFT;
31702a8f9449SShaohua Li 	enable_swap_info(p, prio, swap_map, cluster_info, frontswap_map);
3171c69dbfb8SCesar Eduardo Barros 
3172756a025fSJoe Perches 	pr_info("Adding %uk swap on %s.  Priority:%d extents:%d across:%lluk %s%s%s%s%s\n",
317391a27b2aSJeff Layton 		p->pages<<(PAGE_SHIFT-10), name->name, p->prio,
3174c69dbfb8SCesar Eduardo Barros 		nr_extents, (unsigned long long)span<<(PAGE_SHIFT-10),
3175c69dbfb8SCesar Eduardo Barros 		(p->flags & SWP_SOLIDSTATE) ? "SS" : "",
317638b5faf4SDan Magenheimer 		(p->flags & SWP_DISCARDABLE) ? "D" : "",
3177dcf6b7ddSRafael Aquini 		(p->flags & SWP_AREA_DISCARD) ? "s" : "",
3178dcf6b7ddSRafael Aquini 		(p->flags & SWP_PAGE_DISCARD) ? "c" : "",
317938b5faf4SDan Magenheimer 		(frontswap_map) ? "FS" : "");
3180c69dbfb8SCesar Eduardo Barros 
3181fc0abb14SIngo Molnar 	mutex_unlock(&swapon_mutex);
318266d7dd51SKay Sievers 	atomic_inc(&proc_poll_event);
318366d7dd51SKay Sievers 	wake_up_interruptible(&proc_poll_wait);
318466d7dd51SKay Sievers 
31859b01c350SCesar Eduardo Barros 	if (S_ISREG(inode->i_mode))
31869b01c350SCesar Eduardo Barros 		inode->i_flags |= S_SWAPFILE;
31871da177e4SLinus Torvalds 	error = 0;
31881da177e4SLinus Torvalds 	goto out;
31891da177e4SLinus Torvalds bad_swap:
3190ebc2a1a6SShaohua Li 	free_percpu(p->percpu_cluster);
3191ebc2a1a6SShaohua Li 	p->percpu_cluster = NULL;
3192bd69010bSCesar Eduardo Barros 	if (inode && S_ISBLK(inode->i_mode) && p->bdev) {
3193f2090d2dSCesar Eduardo Barros 		set_blocksize(p->bdev, p->old_block_size);
3194f2090d2dSCesar Eduardo Barros 		blkdev_put(p->bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL);
31951da177e4SLinus Torvalds 	}
31964cd3bb10SHugh Dickins 	destroy_swap_extents(p);
3197e8e6c2ecSCesar Eduardo Barros 	swap_cgroup_swapoff(p->type);
31985d337b91SHugh Dickins 	spin_lock(&swap_lock);
31991da177e4SLinus Torvalds 	p->swap_file = NULL;
32001da177e4SLinus Torvalds 	p->flags = 0;
32015d337b91SHugh Dickins 	spin_unlock(&swap_lock);
32021da177e4SLinus Torvalds 	vfree(swap_map);
32038606a1a9SDarrick J. Wong 	kvfree(cluster_info);
3204b6b1fd2aSDavid Rientjes 	kvfree(frontswap_map);
32057cbf3192SOmar Sandoval 	if (inced_nr_rotate_swap)
32067cbf3192SOmar Sandoval 		atomic_dec(&nr_rotate_swap);
320752c50567SMel Gorman 	if (swap_file) {
32082130781eSCesar Eduardo Barros 		if (inode && S_ISREG(inode->i_mode)) {
32095955102cSAl Viro 			inode_unlock(inode);
32102130781eSCesar Eduardo Barros 			inode = NULL;
32112130781eSCesar Eduardo Barros 		}
32121da177e4SLinus Torvalds 		filp_close(swap_file, NULL);
321352c50567SMel Gorman 	}
32141da177e4SLinus Torvalds out:
32151da177e4SLinus Torvalds 	if (page && !IS_ERR(page)) {
32161da177e4SLinus Torvalds 		kunmap(page);
321709cbfeafSKirill A. Shutemov 		put_page(page);
32181da177e4SLinus Torvalds 	}
32191da177e4SLinus Torvalds 	if (name)
32201da177e4SLinus Torvalds 		putname(name);
32219b01c350SCesar Eduardo Barros 	if (inode && S_ISREG(inode->i_mode))
32225955102cSAl Viro 		inode_unlock(inode);
3223039939a6STim Chen 	if (!error)
3224039939a6STim Chen 		enable_swap_slots_cache();
32251da177e4SLinus Torvalds 	return error;
32261da177e4SLinus Torvalds }
32271da177e4SLinus Torvalds 
32281da177e4SLinus Torvalds void si_swapinfo(struct sysinfo *val)
32291da177e4SLinus Torvalds {
3230efa90a98SHugh Dickins 	unsigned int type;
32311da177e4SLinus Torvalds 	unsigned long nr_to_be_unused = 0;
32321da177e4SLinus Torvalds 
32335d337b91SHugh Dickins 	spin_lock(&swap_lock);
3234efa90a98SHugh Dickins 	for (type = 0; type < nr_swapfiles; type++) {
3235efa90a98SHugh Dickins 		struct swap_info_struct *si = swap_info[type];
3236efa90a98SHugh Dickins 
3237efa90a98SHugh Dickins 		if ((si->flags & SWP_USED) && !(si->flags & SWP_WRITEOK))
3238efa90a98SHugh Dickins 			nr_to_be_unused += si->inuse_pages;
32391da177e4SLinus Torvalds 	}
3240ec8acf20SShaohua Li 	val->freeswap = atomic_long_read(&nr_swap_pages) + nr_to_be_unused;
32411da177e4SLinus Torvalds 	val->totalswap = total_swap_pages + nr_to_be_unused;
32425d337b91SHugh Dickins 	spin_unlock(&swap_lock);
32431da177e4SLinus Torvalds }
32441da177e4SLinus Torvalds 
32451da177e4SLinus Torvalds /*
32461da177e4SLinus Torvalds  * Verify that a swap entry is valid and increment its swap map count.
32471da177e4SLinus Torvalds  *
3248355cfa73SKAMEZAWA Hiroyuki  * Returns error code in following case.
3249355cfa73SKAMEZAWA Hiroyuki  * - success -> 0
3250355cfa73SKAMEZAWA Hiroyuki  * - swp_entry is invalid -> EINVAL
3251355cfa73SKAMEZAWA Hiroyuki  * - swp_entry is migration entry -> EINVAL
3252355cfa73SKAMEZAWA Hiroyuki  * - swap-cache reference is requested but there is already one. -> EEXIST
3253355cfa73SKAMEZAWA Hiroyuki  * - swap-cache reference is requested but the entry is not used. -> ENOENT
3254570a335bSHugh Dickins  * - swap-mapped reference requested but needs continued swap count. -> ENOMEM
32551da177e4SLinus Torvalds  */
32568d69aaeeSHugh Dickins static int __swap_duplicate(swp_entry_t entry, unsigned char usage)
32571da177e4SLinus Torvalds {
32581da177e4SLinus Torvalds 	struct swap_info_struct *p;
3259235b6217SHuang, Ying 	struct swap_cluster_info *ci;
3260c10d38ccSDaniel Jordan 	unsigned long offset;
32618d69aaeeSHugh Dickins 	unsigned char count;
32628d69aaeeSHugh Dickins 	unsigned char has_cache;
3263253d553bSHugh Dickins 	int err = -EINVAL;
32641da177e4SLinus Torvalds 
3265a7420aa5SAndi Kleen 	if (non_swap_entry(entry))
3266253d553bSHugh Dickins 		goto out;
32670697212aSChristoph Lameter 
3268c10d38ccSDaniel Jordan 	p = swp_swap_info(entry);
3269c10d38ccSDaniel Jordan 	if (!p)
32701da177e4SLinus Torvalds 		goto bad_file;
3271c10d38ccSDaniel Jordan 
32721da177e4SLinus Torvalds 	offset = swp_offset(entry);
3273355cfa73SKAMEZAWA Hiroyuki 	if (unlikely(offset >= p->max))
3274235b6217SHuang, Ying 		goto out;
3275235b6217SHuang, Ying 
3276235b6217SHuang, Ying 	ci = lock_cluster_or_swap_info(p, offset);
3277355cfa73SKAMEZAWA Hiroyuki 
3278253d553bSHugh Dickins 	count = p->swap_map[offset];
3279edfe23daSShaohua Li 
3280edfe23daSShaohua Li 	/*
3281edfe23daSShaohua Li 	 * swapin_readahead() doesn't check if a swap entry is valid, so the
3282edfe23daSShaohua Li 	 * swap entry could be SWAP_MAP_BAD. Check here with lock held.
3283edfe23daSShaohua Li 	 */
3284edfe23daSShaohua Li 	if (unlikely(swap_count(count) == SWAP_MAP_BAD)) {
3285edfe23daSShaohua Li 		err = -ENOENT;
3286edfe23daSShaohua Li 		goto unlock_out;
3287edfe23daSShaohua Li 	}
3288edfe23daSShaohua Li 
3289253d553bSHugh Dickins 	has_cache = count & SWAP_HAS_CACHE;
3290253d553bSHugh Dickins 	count &= ~SWAP_HAS_CACHE;
3291253d553bSHugh Dickins 	err = 0;
3292355cfa73SKAMEZAWA Hiroyuki 
3293253d553bSHugh Dickins 	if (usage == SWAP_HAS_CACHE) {
3294355cfa73SKAMEZAWA Hiroyuki 
3295355cfa73SKAMEZAWA Hiroyuki 		/* set SWAP_HAS_CACHE if there is no cache and entry is used */
3296253d553bSHugh Dickins 		if (!has_cache && count)
3297253d553bSHugh Dickins 			has_cache = SWAP_HAS_CACHE;
3298253d553bSHugh Dickins 		else if (has_cache)		/* someone else added cache */
3299253d553bSHugh Dickins 			err = -EEXIST;
3300253d553bSHugh Dickins 		else				/* no users remaining */
3301253d553bSHugh Dickins 			err = -ENOENT;
3302355cfa73SKAMEZAWA Hiroyuki 
3303355cfa73SKAMEZAWA Hiroyuki 	} else if (count || has_cache) {
3304253d553bSHugh Dickins 
3305570a335bSHugh Dickins 		if ((count & ~COUNT_CONTINUED) < SWAP_MAP_MAX)
3306570a335bSHugh Dickins 			count += usage;
3307570a335bSHugh Dickins 		else if ((count & ~COUNT_CONTINUED) > SWAP_MAP_MAX)
3308253d553bSHugh Dickins 			err = -EINVAL;
3309570a335bSHugh Dickins 		else if (swap_count_continued(p, offset, count))
3310570a335bSHugh Dickins 			count = COUNT_CONTINUED;
3311570a335bSHugh Dickins 		else
3312570a335bSHugh Dickins 			err = -ENOMEM;
3313253d553bSHugh Dickins 	} else
3314253d553bSHugh Dickins 		err = -ENOENT;			/* unused swap entry */
3315253d553bSHugh Dickins 
3316253d553bSHugh Dickins 	p->swap_map[offset] = count | has_cache;
3317253d553bSHugh Dickins 
3318355cfa73SKAMEZAWA Hiroyuki unlock_out:
3319235b6217SHuang, Ying 	unlock_cluster_or_swap_info(p, ci);
33201da177e4SLinus Torvalds out:
3321253d553bSHugh Dickins 	return err;
33221da177e4SLinus Torvalds 
33231da177e4SLinus Torvalds bad_file:
3324465c47fdSAndrew Morton 	pr_err("swap_dup: %s%08lx\n", Bad_file, entry.val);
33251da177e4SLinus Torvalds 	goto out;
33261da177e4SLinus Torvalds }
3327253d553bSHugh Dickins 
3328355cfa73SKAMEZAWA Hiroyuki /*
3329aaa46865SHugh Dickins  * Help swapoff by noting that swap entry belongs to shmem/tmpfs
3330aaa46865SHugh Dickins  * (in which case its reference count is never incremented).
3331aaa46865SHugh Dickins  */
3332aaa46865SHugh Dickins void swap_shmem_alloc(swp_entry_t entry)
3333aaa46865SHugh Dickins {
3334aaa46865SHugh Dickins 	__swap_duplicate(entry, SWAP_MAP_SHMEM);
3335aaa46865SHugh Dickins }
3336aaa46865SHugh Dickins 
3337aaa46865SHugh Dickins /*
333808259d58SHugh Dickins  * Increase reference count of swap entry by 1.
333908259d58SHugh Dickins  * Returns 0 for success, or -ENOMEM if a swap_count_continuation is required
334008259d58SHugh Dickins  * but could not be atomically allocated.  Returns 0, just as if it succeeded,
334108259d58SHugh Dickins  * if __swap_duplicate() fails for another reason (-EINVAL or -ENOENT), which
334208259d58SHugh Dickins  * might occur if a page table entry has got corrupted.
3343355cfa73SKAMEZAWA Hiroyuki  */
3344570a335bSHugh Dickins int swap_duplicate(swp_entry_t entry)
3345355cfa73SKAMEZAWA Hiroyuki {
3346570a335bSHugh Dickins 	int err = 0;
3347570a335bSHugh Dickins 
3348570a335bSHugh Dickins 	while (!err && __swap_duplicate(entry, 1) == -ENOMEM)
3349570a335bSHugh Dickins 		err = add_swap_count_continuation(entry, GFP_ATOMIC);
3350570a335bSHugh Dickins 	return err;
3351355cfa73SKAMEZAWA Hiroyuki }
33521da177e4SLinus Torvalds 
3353cb4b86baSKAMEZAWA Hiroyuki /*
3354355cfa73SKAMEZAWA Hiroyuki  * @entry: swap entry for which we allocate swap cache.
3355355cfa73SKAMEZAWA Hiroyuki  *
335673c34b6aSHugh Dickins  * Called when allocating swap cache for existing swap entry,
3357355cfa73SKAMEZAWA Hiroyuki  * This can return error codes. Returns 0 at success.
3358355cfa73SKAMEZAWA Hiroyuki  * -EBUSY means there is a swap cache.
3359355cfa73SKAMEZAWA Hiroyuki  * Note: return code is different from swap_duplicate().
3360cb4b86baSKAMEZAWA Hiroyuki  */
3361cb4b86baSKAMEZAWA Hiroyuki int swapcache_prepare(swp_entry_t entry)
3362cb4b86baSKAMEZAWA Hiroyuki {
3363253d553bSHugh Dickins 	return __swap_duplicate(entry, SWAP_HAS_CACHE);
3364cb4b86baSKAMEZAWA Hiroyuki }
3365cb4b86baSKAMEZAWA Hiroyuki 
33660bcac06fSMinchan Kim struct swap_info_struct *swp_swap_info(swp_entry_t entry)
33670bcac06fSMinchan Kim {
3368c10d38ccSDaniel Jordan 	return swap_type_to_swap_info(swp_type(entry));
33690bcac06fSMinchan Kim }
33700bcac06fSMinchan Kim 
3371f981c595SMel Gorman struct swap_info_struct *page_swap_info(struct page *page)
3372f981c595SMel Gorman {
33730bcac06fSMinchan Kim 	swp_entry_t entry = { .val = page_private(page) };
33740bcac06fSMinchan Kim 	return swp_swap_info(entry);
3375f981c595SMel Gorman }
3376f981c595SMel Gorman 
3377f981c595SMel Gorman /*
3378f981c595SMel Gorman  * out-of-line __page_file_ methods to avoid include hell.
3379f981c595SMel Gorman  */
3380f981c595SMel Gorman struct address_space *__page_file_mapping(struct page *page)
3381f981c595SMel Gorman {
3382f981c595SMel Gorman 	return page_swap_info(page)->swap_file->f_mapping;
3383f981c595SMel Gorman }
3384f981c595SMel Gorman EXPORT_SYMBOL_GPL(__page_file_mapping);
3385f981c595SMel Gorman 
3386f981c595SMel Gorman pgoff_t __page_file_index(struct page *page)
3387f981c595SMel Gorman {
3388f981c595SMel Gorman 	swp_entry_t swap = { .val = page_private(page) };
3389f981c595SMel Gorman 	return swp_offset(swap);
3390f981c595SMel Gorman }
3391f981c595SMel Gorman EXPORT_SYMBOL_GPL(__page_file_index);
3392f981c595SMel Gorman 
33931da177e4SLinus Torvalds /*
3394570a335bSHugh Dickins  * add_swap_count_continuation - called when a swap count is duplicated
3395570a335bSHugh Dickins  * beyond SWAP_MAP_MAX, it allocates a new page and links that to the entry's
3396570a335bSHugh Dickins  * page of the original vmalloc'ed swap_map, to hold the continuation count
3397570a335bSHugh Dickins  * (for that entry and for its neighbouring PAGE_SIZE swap entries).  Called
3398570a335bSHugh Dickins  * again when count is duplicated beyond SWAP_MAP_MAX * SWAP_CONT_MAX, etc.
3399570a335bSHugh Dickins  *
3400570a335bSHugh Dickins  * These continuation pages are seldom referenced: the common paths all work
3401570a335bSHugh Dickins  * on the original swap_map, only referring to a continuation page when the
3402570a335bSHugh Dickins  * low "digit" of a count is incremented or decremented through SWAP_MAP_MAX.
3403570a335bSHugh Dickins  *
3404570a335bSHugh Dickins  * add_swap_count_continuation(, GFP_ATOMIC) can be called while holding
3405570a335bSHugh Dickins  * page table locks; if it fails, add_swap_count_continuation(, GFP_KERNEL)
3406570a335bSHugh Dickins  * can be called after dropping locks.
3407570a335bSHugh Dickins  */
3408570a335bSHugh Dickins int add_swap_count_continuation(swp_entry_t entry, gfp_t gfp_mask)
3409570a335bSHugh Dickins {
3410570a335bSHugh Dickins 	struct swap_info_struct *si;
3411235b6217SHuang, Ying 	struct swap_cluster_info *ci;
3412570a335bSHugh Dickins 	struct page *head;
3413570a335bSHugh Dickins 	struct page *page;
3414570a335bSHugh Dickins 	struct page *list_page;
3415570a335bSHugh Dickins 	pgoff_t offset;
3416570a335bSHugh Dickins 	unsigned char count;
3417570a335bSHugh Dickins 
3418570a335bSHugh Dickins 	/*
3419570a335bSHugh Dickins 	 * When debugging, it's easier to use __GFP_ZERO here; but it's better
3420570a335bSHugh Dickins 	 * for latency not to zero a page while GFP_ATOMIC and holding locks.
3421570a335bSHugh Dickins 	 */
3422570a335bSHugh Dickins 	page = alloc_page(gfp_mask | __GFP_HIGHMEM);
3423570a335bSHugh Dickins 
3424570a335bSHugh Dickins 	si = swap_info_get(entry);
3425570a335bSHugh Dickins 	if (!si) {
3426570a335bSHugh Dickins 		/*
3427570a335bSHugh Dickins 		 * An acceptable race has occurred since the failing
3428570a335bSHugh Dickins 		 * __swap_duplicate(): the swap entry has been freed,
3429570a335bSHugh Dickins 		 * perhaps even the whole swap_map cleared for swapoff.
3430570a335bSHugh Dickins 		 */
3431570a335bSHugh Dickins 		goto outer;
3432570a335bSHugh Dickins 	}
3433570a335bSHugh Dickins 
3434570a335bSHugh Dickins 	offset = swp_offset(entry);
3435235b6217SHuang, Ying 
3436235b6217SHuang, Ying 	ci = lock_cluster(si, offset);
3437235b6217SHuang, Ying 
3438570a335bSHugh Dickins 	count = si->swap_map[offset] & ~SWAP_HAS_CACHE;
3439570a335bSHugh Dickins 
3440570a335bSHugh Dickins 	if ((count & ~COUNT_CONTINUED) != SWAP_MAP_MAX) {
3441570a335bSHugh Dickins 		/*
3442570a335bSHugh Dickins 		 * The higher the swap count, the more likely it is that tasks
3443570a335bSHugh Dickins 		 * will race to add swap count continuation: we need to avoid
3444570a335bSHugh Dickins 		 * over-provisioning.
3445570a335bSHugh Dickins 		 */
3446570a335bSHugh Dickins 		goto out;
3447570a335bSHugh Dickins 	}
3448570a335bSHugh Dickins 
3449570a335bSHugh Dickins 	if (!page) {
3450235b6217SHuang, Ying 		unlock_cluster(ci);
3451ec8acf20SShaohua Li 		spin_unlock(&si->lock);
3452570a335bSHugh Dickins 		return -ENOMEM;
3453570a335bSHugh Dickins 	}
3454570a335bSHugh Dickins 
3455570a335bSHugh Dickins 	/*
3456570a335bSHugh Dickins 	 * We are fortunate that although vmalloc_to_page uses pte_offset_map,
3457570a335bSHugh Dickins 	 * no architecture is using highmem pages for kernel page tables: so it
3458570a335bSHugh Dickins 	 * will not corrupt the GFP_ATOMIC caller's atomic page table kmaps.
3459570a335bSHugh Dickins 	 */
3460570a335bSHugh Dickins 	head = vmalloc_to_page(si->swap_map + offset);
3461570a335bSHugh Dickins 	offset &= ~PAGE_MASK;
3462570a335bSHugh Dickins 
34632628bd6fSHuang Ying 	spin_lock(&si->cont_lock);
3464570a335bSHugh Dickins 	/*
3465570a335bSHugh Dickins 	 * Page allocation does not initialize the page's lru field,
3466570a335bSHugh Dickins 	 * but it does always reset its private field.
3467570a335bSHugh Dickins 	 */
3468570a335bSHugh Dickins 	if (!page_private(head)) {
3469570a335bSHugh Dickins 		BUG_ON(count & COUNT_CONTINUED);
3470570a335bSHugh Dickins 		INIT_LIST_HEAD(&head->lru);
3471570a335bSHugh Dickins 		set_page_private(head, SWP_CONTINUED);
3472570a335bSHugh Dickins 		si->flags |= SWP_CONTINUED;
3473570a335bSHugh Dickins 	}
3474570a335bSHugh Dickins 
3475570a335bSHugh Dickins 	list_for_each_entry(list_page, &head->lru, lru) {
3476570a335bSHugh Dickins 		unsigned char *map;
3477570a335bSHugh Dickins 
3478570a335bSHugh Dickins 		/*
3479570a335bSHugh Dickins 		 * If the previous map said no continuation, but we've found
3480570a335bSHugh Dickins 		 * a continuation page, free our allocation and use this one.
3481570a335bSHugh Dickins 		 */
3482570a335bSHugh Dickins 		if (!(count & COUNT_CONTINUED))
34832628bd6fSHuang Ying 			goto out_unlock_cont;
3484570a335bSHugh Dickins 
34859b04c5feSCong Wang 		map = kmap_atomic(list_page) + offset;
3486570a335bSHugh Dickins 		count = *map;
34879b04c5feSCong Wang 		kunmap_atomic(map);
3488570a335bSHugh Dickins 
3489570a335bSHugh Dickins 		/*
3490570a335bSHugh Dickins 		 * If this continuation count now has some space in it,
3491570a335bSHugh Dickins 		 * free our allocation and use this one.
3492570a335bSHugh Dickins 		 */
3493570a335bSHugh Dickins 		if ((count & ~COUNT_CONTINUED) != SWAP_CONT_MAX)
34942628bd6fSHuang Ying 			goto out_unlock_cont;
3495570a335bSHugh Dickins 	}
3496570a335bSHugh Dickins 
3497570a335bSHugh Dickins 	list_add_tail(&page->lru, &head->lru);
3498570a335bSHugh Dickins 	page = NULL;			/* now it's attached, don't free it */
34992628bd6fSHuang Ying out_unlock_cont:
35002628bd6fSHuang Ying 	spin_unlock(&si->cont_lock);
3501570a335bSHugh Dickins out:
3502235b6217SHuang, Ying 	unlock_cluster(ci);
3503ec8acf20SShaohua Li 	spin_unlock(&si->lock);
3504570a335bSHugh Dickins outer:
3505570a335bSHugh Dickins 	if (page)
3506570a335bSHugh Dickins 		__free_page(page);
3507570a335bSHugh Dickins 	return 0;
3508570a335bSHugh Dickins }
3509570a335bSHugh Dickins 
3510570a335bSHugh Dickins /*
3511570a335bSHugh Dickins  * swap_count_continued - when the original swap_map count is incremented
3512570a335bSHugh Dickins  * from SWAP_MAP_MAX, check if there is already a continuation page to carry
3513570a335bSHugh Dickins  * into, carry if so, or else fail until a new continuation page is allocated;
3514570a335bSHugh Dickins  * when the original swap_map count is decremented from 0 with continuation,
3515570a335bSHugh Dickins  * borrow from the continuation and report whether it still holds more.
3516235b6217SHuang, Ying  * Called while __swap_duplicate() or swap_entry_free() holds swap or cluster
3517235b6217SHuang, Ying  * lock.
3518570a335bSHugh Dickins  */
3519570a335bSHugh Dickins static bool swap_count_continued(struct swap_info_struct *si,
3520570a335bSHugh Dickins 				 pgoff_t offset, unsigned char count)
3521570a335bSHugh Dickins {
3522570a335bSHugh Dickins 	struct page *head;
3523570a335bSHugh Dickins 	struct page *page;
3524570a335bSHugh Dickins 	unsigned char *map;
35252628bd6fSHuang Ying 	bool ret;
3526570a335bSHugh Dickins 
3527570a335bSHugh Dickins 	head = vmalloc_to_page(si->swap_map + offset);
3528570a335bSHugh Dickins 	if (page_private(head) != SWP_CONTINUED) {
3529570a335bSHugh Dickins 		BUG_ON(count & COUNT_CONTINUED);
3530570a335bSHugh Dickins 		return false;		/* need to add count continuation */
3531570a335bSHugh Dickins 	}
3532570a335bSHugh Dickins 
35332628bd6fSHuang Ying 	spin_lock(&si->cont_lock);
3534570a335bSHugh Dickins 	offset &= ~PAGE_MASK;
3535570a335bSHugh Dickins 	page = list_entry(head->lru.next, struct page, lru);
35369b04c5feSCong Wang 	map = kmap_atomic(page) + offset;
3537570a335bSHugh Dickins 
3538570a335bSHugh Dickins 	if (count == SWAP_MAP_MAX)	/* initial increment from swap_map */
3539570a335bSHugh Dickins 		goto init_map;		/* jump over SWAP_CONT_MAX checks */
3540570a335bSHugh Dickins 
3541570a335bSHugh Dickins 	if (count == (SWAP_MAP_MAX | COUNT_CONTINUED)) { /* incrementing */
3542570a335bSHugh Dickins 		/*
3543570a335bSHugh Dickins 		 * Think of how you add 1 to 999
3544570a335bSHugh Dickins 		 */
3545570a335bSHugh Dickins 		while (*map == (SWAP_CONT_MAX | COUNT_CONTINUED)) {
35469b04c5feSCong Wang 			kunmap_atomic(map);
3547570a335bSHugh Dickins 			page = list_entry(page->lru.next, struct page, lru);
3548570a335bSHugh Dickins 			BUG_ON(page == head);
35499b04c5feSCong Wang 			map = kmap_atomic(page) + offset;
3550570a335bSHugh Dickins 		}
3551570a335bSHugh Dickins 		if (*map == SWAP_CONT_MAX) {
35529b04c5feSCong Wang 			kunmap_atomic(map);
3553570a335bSHugh Dickins 			page = list_entry(page->lru.next, struct page, lru);
35542628bd6fSHuang Ying 			if (page == head) {
35552628bd6fSHuang Ying 				ret = false;	/* add count continuation */
35562628bd6fSHuang Ying 				goto out;
35572628bd6fSHuang Ying 			}
35589b04c5feSCong Wang 			map = kmap_atomic(page) + offset;
3559570a335bSHugh Dickins init_map:		*map = 0;		/* we didn't zero the page */
3560570a335bSHugh Dickins 		}
3561570a335bSHugh Dickins 		*map += 1;
35629b04c5feSCong Wang 		kunmap_atomic(map);
3563570a335bSHugh Dickins 		page = list_entry(page->lru.prev, struct page, lru);
3564570a335bSHugh Dickins 		while (page != head) {
35659b04c5feSCong Wang 			map = kmap_atomic(page) + offset;
3566570a335bSHugh Dickins 			*map = COUNT_CONTINUED;
35679b04c5feSCong Wang 			kunmap_atomic(map);
3568570a335bSHugh Dickins 			page = list_entry(page->lru.prev, struct page, lru);
3569570a335bSHugh Dickins 		}
35702628bd6fSHuang Ying 		ret = true;			/* incremented */
3571570a335bSHugh Dickins 
3572570a335bSHugh Dickins 	} else {				/* decrementing */
3573570a335bSHugh Dickins 		/*
3574570a335bSHugh Dickins 		 * Think of how you subtract 1 from 1000
3575570a335bSHugh Dickins 		 */
3576570a335bSHugh Dickins 		BUG_ON(count != COUNT_CONTINUED);
3577570a335bSHugh Dickins 		while (*map == COUNT_CONTINUED) {
35789b04c5feSCong Wang 			kunmap_atomic(map);
3579570a335bSHugh Dickins 			page = list_entry(page->lru.next, struct page, lru);
3580570a335bSHugh Dickins 			BUG_ON(page == head);
35819b04c5feSCong Wang 			map = kmap_atomic(page) + offset;
3582570a335bSHugh Dickins 		}
3583570a335bSHugh Dickins 		BUG_ON(*map == 0);
3584570a335bSHugh Dickins 		*map -= 1;
3585570a335bSHugh Dickins 		if (*map == 0)
3586570a335bSHugh Dickins 			count = 0;
35879b04c5feSCong Wang 		kunmap_atomic(map);
3588570a335bSHugh Dickins 		page = list_entry(page->lru.prev, struct page, lru);
3589570a335bSHugh Dickins 		while (page != head) {
35909b04c5feSCong Wang 			map = kmap_atomic(page) + offset;
3591570a335bSHugh Dickins 			*map = SWAP_CONT_MAX | count;
3592570a335bSHugh Dickins 			count = COUNT_CONTINUED;
35939b04c5feSCong Wang 			kunmap_atomic(map);
3594570a335bSHugh Dickins 			page = list_entry(page->lru.prev, struct page, lru);
3595570a335bSHugh Dickins 		}
35962628bd6fSHuang Ying 		ret = count == COUNT_CONTINUED;
3597570a335bSHugh Dickins 	}
35982628bd6fSHuang Ying out:
35992628bd6fSHuang Ying 	spin_unlock(&si->cont_lock);
36002628bd6fSHuang Ying 	return ret;
3601570a335bSHugh Dickins }
3602570a335bSHugh Dickins 
3603570a335bSHugh Dickins /*
3604570a335bSHugh Dickins  * free_swap_count_continuations - swapoff free all the continuation pages
3605570a335bSHugh Dickins  * appended to the swap_map, after swap_map is quiesced, before vfree'ing it.
3606570a335bSHugh Dickins  */
3607570a335bSHugh Dickins static void free_swap_count_continuations(struct swap_info_struct *si)
3608570a335bSHugh Dickins {
3609570a335bSHugh Dickins 	pgoff_t offset;
3610570a335bSHugh Dickins 
3611570a335bSHugh Dickins 	for (offset = 0; offset < si->max; offset += PAGE_SIZE) {
3612570a335bSHugh Dickins 		struct page *head;
3613570a335bSHugh Dickins 		head = vmalloc_to_page(si->swap_map + offset);
3614570a335bSHugh Dickins 		if (page_private(head)) {
36150d576d20SGeliang Tang 			struct page *page, *next;
36160d576d20SGeliang Tang 
36170d576d20SGeliang Tang 			list_for_each_entry_safe(page, next, &head->lru, lru) {
36180d576d20SGeliang Tang 				list_del(&page->lru);
3619570a335bSHugh Dickins 				__free_page(page);
3620570a335bSHugh Dickins 			}
3621570a335bSHugh Dickins 		}
3622570a335bSHugh Dickins 	}
3623570a335bSHugh Dickins }
3624a2468cc9SAaron Lu 
36252cf85583STejun Heo #if defined(CONFIG_MEMCG) && defined(CONFIG_BLK_CGROUP)
36262cf85583STejun Heo void mem_cgroup_throttle_swaprate(struct mem_cgroup *memcg, int node,
36272cf85583STejun Heo 				  gfp_t gfp_mask)
36282cf85583STejun Heo {
36292cf85583STejun Heo 	struct swap_info_struct *si, *next;
36302cf85583STejun Heo 	if (!(gfp_mask & __GFP_IO) || !memcg)
36312cf85583STejun Heo 		return;
36322cf85583STejun Heo 
36332cf85583STejun Heo 	if (!blk_cgroup_congested())
36342cf85583STejun Heo 		return;
36352cf85583STejun Heo 
36362cf85583STejun Heo 	/*
36372cf85583STejun Heo 	 * We've already scheduled a throttle, avoid taking the global swap
36382cf85583STejun Heo 	 * lock.
36392cf85583STejun Heo 	 */
36402cf85583STejun Heo 	if (current->throttle_queue)
36412cf85583STejun Heo 		return;
36422cf85583STejun Heo 
36432cf85583STejun Heo 	spin_lock(&swap_avail_lock);
36442cf85583STejun Heo 	plist_for_each_entry_safe(si, next, &swap_avail_heads[node],
36452cf85583STejun Heo 				  avail_lists[node]) {
36462cf85583STejun Heo 		if (si->bdev) {
36472cf85583STejun Heo 			blkcg_schedule_throttle(bdev_get_queue(si->bdev),
36482cf85583STejun Heo 						true);
36492cf85583STejun Heo 			break;
36502cf85583STejun Heo 		}
36512cf85583STejun Heo 	}
36522cf85583STejun Heo 	spin_unlock(&swap_avail_lock);
36532cf85583STejun Heo }
36542cf85583STejun Heo #endif
36552cf85583STejun Heo 
3656a2468cc9SAaron Lu static int __init swapfile_init(void)
3657a2468cc9SAaron Lu {
3658a2468cc9SAaron Lu 	int nid;
3659a2468cc9SAaron Lu 
3660a2468cc9SAaron Lu 	swap_avail_heads = kmalloc_array(nr_node_ids, sizeof(struct plist_head),
3661a2468cc9SAaron Lu 					 GFP_KERNEL);
3662a2468cc9SAaron Lu 	if (!swap_avail_heads) {
3663a2468cc9SAaron Lu 		pr_emerg("Not enough memory for swap heads, swap is disabled\n");
3664a2468cc9SAaron Lu 		return -ENOMEM;
3665a2468cc9SAaron Lu 	}
3666a2468cc9SAaron Lu 
3667a2468cc9SAaron Lu 	for_each_node(nid)
3668a2468cc9SAaron Lu 		plist_head_init(&swap_avail_heads[nid]);
3669a2468cc9SAaron Lu 
3670a2468cc9SAaron Lu 	return 0;
3671a2468cc9SAaron Lu }
3672a2468cc9SAaron Lu subsys_initcall(swapfile_init);
3673