xref: /linux/mm/swap_state.c (revision 0fc8f6200d2313278fbf4539bbab74677c685531)
1b2441318SGreg Kroah-Hartman // SPDX-License-Identifier: GPL-2.0
21da177e4SLinus Torvalds /*
31da177e4SLinus Torvalds  *  linux/mm/swap_state.c
41da177e4SLinus Torvalds  *
51da177e4SLinus Torvalds  *  Copyright (C) 1991, 1992, 1993, 1994  Linus Torvalds
61da177e4SLinus Torvalds  *  Swap reorganised 29.12.95, Stephen Tweedie
71da177e4SLinus Torvalds  *
81da177e4SLinus Torvalds  *  Rewritten to use page cache, (C) 1998 Stephen Tweedie
91da177e4SLinus Torvalds  */
101da177e4SLinus Torvalds #include <linux/mm.h>
115a0e3ad6STejun Heo #include <linux/gfp.h>
121da177e4SLinus Torvalds #include <linux/kernel_stat.h>
13ddc1a5cbSHugh Dickins #include <linux/mempolicy.h>
141da177e4SLinus Torvalds #include <linux/swap.h>
1506fb6146SLorenzo Stoakes #include <linux/leafops.h>
161da177e4SLinus Torvalds #include <linux/init.h>
171da177e4SLinus Torvalds #include <linux/pagemap.h>
184e1d77a8STal Zussman #include <linux/folio_batch.h>
191da177e4SLinus Torvalds #include <linux/backing-dev.h>
203fb5c298SChristian Ehrhardt #include <linux/blkdev.h>
21b20a3503SChristoph Lameter #include <linux/migrate.h>
224b3ef9daSHuang, Ying #include <linux/vmalloc.h>
2338d8b4e6SHuang Ying #include <linux/huge_mm.h>
2461ef1865SMatthew Wilcox (Oracle) #include <linux/shmem_fs.h>
25243bce09SHugh Dickins #include "internal.h"
268578e0c0SKairui Song #include "swap_table.h"
27014bb1deSNeilBrown #include "swap.h"
281da177e4SLinus Torvalds 
291da177e4SLinus Torvalds /*
301da177e4SLinus Torvalds  * swapper_space is a fiction, retained to simplify the path through
310ba5e806SIllia Ostapyshyn  * vmscan's shrink_folio_list.
321da177e4SLinus Torvalds  */
33f5e54d6eSChristoph Hellwig static const struct address_space_operations swap_aops = {
344c4a7634SNeilBrown 	.dirty_folio	= noop_dirty_folio,
351c93923cSAndrew Morton #ifdef CONFIG_MIGRATION
3654184650SMatthew Wilcox (Oracle) 	.migrate_folio	= migrate_folio,
371c93923cSAndrew Morton #endif
381da177e4SLinus Torvalds };
391da177e4SLinus Torvalds 
40a0f3c084Srobin.kuo struct address_space swap_space __read_mostly = {
418578e0c0SKairui Song 	.a_ops = &swap_aops,
428578e0c0SKairui Song };
438578e0c0SKairui Song 
44f5c754d6SColin Ian King static bool enable_vma_readahead __read_mostly = true;
45ec560175SHuang Ying 
46dce08dd2SHuang Ying #define SWAP_RA_ORDER_CEILING	5
47dce08dd2SHuang Ying 
48ec560175SHuang Ying #define SWAP_RA_WIN_SHIFT	(PAGE_SHIFT / 2)
49ec560175SHuang Ying #define SWAP_RA_HITS_MASK	((1UL << SWAP_RA_WIN_SHIFT) - 1)
50ec560175SHuang Ying #define SWAP_RA_HITS_MAX	SWAP_RA_HITS_MASK
51ec560175SHuang Ying #define SWAP_RA_WIN_MASK	(~PAGE_MASK & ~SWAP_RA_HITS_MASK)
52ec560175SHuang Ying 
53ec560175SHuang Ying #define SWAP_RA_HITS(v)		((v) & SWAP_RA_HITS_MASK)
54ec560175SHuang Ying #define SWAP_RA_WIN(v)		(((v) & SWAP_RA_WIN_MASK) >> SWAP_RA_WIN_SHIFT)
55ec560175SHuang Ying #define SWAP_RA_ADDR(v)		((v) & PAGE_MASK)
56ec560175SHuang Ying 
57ec560175SHuang Ying #define SWAP_RA_VAL(addr, win, hits)				\
58ec560175SHuang Ying 	(((addr) & PAGE_MASK) |					\
59ec560175SHuang Ying 	 (((win) << SWAP_RA_WIN_SHIFT) & SWAP_RA_WIN_MASK) |	\
60ec560175SHuang Ying 	 ((hits) & SWAP_RA_HITS_MASK))
61ec560175SHuang Ying 
62ec560175SHuang Ying /* Initial readahead hits is 4 to start up with a small window */
63ec560175SHuang Ying #define GET_SWAP_RA_VAL(vma)					\
64ec560175SHuang Ying 	(atomic_long_read(&(vma)->swap_readahead_info) ? : 4)
651da177e4SLinus Torvalds 
66579f8290SShaohua Li static atomic_t swapin_readahead_hits = ATOMIC_INIT(4);
67579f8290SShaohua Li 
show_swap_cache_info(void)681da177e4SLinus Torvalds void show_swap_cache_info(void)
691da177e4SLinus Torvalds {
7033806f06SShaohua Li 	printk("%lu pages in swap cache\n", total_swapcache_pages());
713cb8eaa4SZhangPeng 	printk("Free swap  = %ldkB\n", K(get_nr_swap_pages()));
723cb8eaa4SZhangPeng 	printk("Total swap = %lukB\n", K(total_swap_pages));
731da177e4SLinus Torvalds }
741da177e4SLinus Torvalds 
75f2812461SKairui Song /**
76f2812461SKairui Song  * swap_cache_get_folio - Looks up a folio in the swap cache.
77f2812461SKairui Song  * @entry: swap entry used for the lookup.
78f2812461SKairui Song  *
79f2812461SKairui Song  * A found folio will be returned unlocked and with its refcount increased.
80f2812461SKairui Song  *
81f2812461SKairui Song  * Context: Caller must ensure @entry is valid and protect the swap device
82f2812461SKairui Song  * with reference count or locks.
83f2812461SKairui Song  * Return: Returns the found folio on success, NULL otherwise. The caller
8462451ae3SKevin Lourenco  * must lock and check if the folio still matches the swap entry before
85fd8d4f86SKairui Song  * use (e.g., folio_matches_swap_entry).
86f2812461SKairui Song  */
swap_cache_get_folio(swp_entry_t entry)87f2812461SKairui Song struct folio *swap_cache_get_folio(swp_entry_t entry)
88f2812461SKairui Song {
898578e0c0SKairui Song 	unsigned long swp_tb;
908578e0c0SKairui Song 	struct folio *folio;
918578e0c0SKairui Song 
928578e0c0SKairui Song 	for (;;) {
9307adc4cfSKairui Song 		swp_tb = swap_table_get(__swap_entry_to_cluster(entry),
948578e0c0SKairui Song 					swp_cluster_offset(entry));
958578e0c0SKairui Song 		if (!swp_tb_is_folio(swp_tb))
96f2812461SKairui Song 			return NULL;
978578e0c0SKairui Song 		folio = swp_tb_to_folio(swp_tb);
988578e0c0SKairui Song 		if (likely(folio_try_get(folio)))
99f2812461SKairui Song 			return folio;
100f2812461SKairui Song 	}
101f2812461SKairui Song 
1028578e0c0SKairui Song 	return NULL;
1038578e0c0SKairui Song }
1048578e0c0SKairui Song 
105fd8d4f86SKairui Song /**
1064984d746SKairui Song  * swap_cache_has_folio - Check if a swap slot has cache.
1074984d746SKairui Song  * @entry: swap entry indicating the slot.
1084984d746SKairui Song  *
1094984d746SKairui Song  * Context: Caller must ensure @entry is valid and protect the swap
1104984d746SKairui Song  * device with reference count or locks.
1114984d746SKairui Song  */
swap_cache_has_folio(swp_entry_t entry)1124984d746SKairui Song bool swap_cache_has_folio(swp_entry_t entry)
1134984d746SKairui Song {
1144984d746SKairui Song 	unsigned long swp_tb;
1154984d746SKairui Song 
1164984d746SKairui Song 	swp_tb = swap_table_get(__swap_entry_to_cluster(entry),
1174984d746SKairui Song 				swp_cluster_offset(entry));
1184984d746SKairui Song 	return swp_tb_is_folio(swp_tb);
1194984d746SKairui Song }
1204984d746SKairui Song 
1214984d746SKairui Song /**
122fd8d4f86SKairui Song  * swap_cache_get_shadow - Looks up a shadow in the swap cache.
123fd8d4f86SKairui Song  * @entry: swap entry used for the lookup.
124fd8d4f86SKairui Song  *
125fd8d4f86SKairui Song  * Context: Caller must ensure @entry is valid and protect the swap device
126fd8d4f86SKairui Song  * with reference count or locks.
127fd8d4f86SKairui Song  * Return: Returns either NULL or an XA_VALUE (shadow).
128fd8d4f86SKairui Song  */
swap_cache_get_shadow(swp_entry_t entry)129fd8d4f86SKairui Song void *swap_cache_get_shadow(swp_entry_t entry)
130aae466b0SJoonsoo Kim {
1318578e0c0SKairui Song 	unsigned long swp_tb;
132aae466b0SJoonsoo Kim 
13307adc4cfSKairui Song 	swp_tb = swap_table_get(__swap_entry_to_cluster(entry),
1348578e0c0SKairui Song 				swp_cluster_offset(entry));
1358578e0c0SKairui Song 	if (swp_tb_is_shadow(swp_tb))
1368578e0c0SKairui Song 		return swp_tb_to_shadow(swp_tb);
137aae466b0SJoonsoo Kim 	return NULL;
138aae466b0SJoonsoo Kim }
139aae466b0SJoonsoo Kim 
__swap_cache_add_folio(struct swap_cluster_info * ci,struct folio * folio,swp_entry_t entry)140270f0951SKairui Song void __swap_cache_add_folio(struct swap_cluster_info *ci,
141270f0951SKairui Song 			    struct folio *folio, swp_entry_t entry)
1421da177e4SLinus Torvalds {
1430d6af9bcSKairui Song 	unsigned int ci_off = swp_cluster_offset(entry), ci_end;
1448578e0c0SKairui Song 	unsigned long nr_pages = folio_nr_pages(folio);
1450d6af9bcSKairui Song 	unsigned long pfn = folio_pfn(folio);
1460d6af9bcSKairui Song 	unsigned long old_tb;
1471da177e4SLinus Torvalds 
1488578e0c0SKairui Song 	VM_WARN_ON_ONCE_FOLIO(!folio_test_locked(folio), folio);
1498578e0c0SKairui Song 	VM_WARN_ON_ONCE_FOLIO(folio_test_swapcache(folio), folio);
1508578e0c0SKairui Song 	VM_WARN_ON_ONCE_FOLIO(!folio_test_swapbacked(folio), folio);
1515649d113SYang Yang 
1520d6af9bcSKairui Song 	ci_end = ci_off + nr_pages;
153270f0951SKairui Song 	do {
1540d6af9bcSKairui Song 		old_tb = __swap_table_get(ci, ci_off);
1550d6af9bcSKairui Song 		VM_WARN_ON_ONCE(swp_tb_is_folio(old_tb));
1560d6af9bcSKairui Song 		__swap_table_set(ci, ci_off, pfn_to_swp_tb(pfn, __swp_tb_get_count(old_tb)));
157270f0951SKairui Song 	} while (++ci_off < ci_end);
158270f0951SKairui Song 
159270f0951SKairui Song 	folio_ref_add(folio, nr_pages);
160270f0951SKairui Song 	folio_set_swapcache(folio);
161270f0951SKairui Song 	folio->swap = entry;
162270f0951SKairui Song 
163270f0951SKairui Song 	node_stat_mod_folio(folio, NR_FILE_PAGES, nr_pages);
164270f0951SKairui Song 	lruvec_stat_mod_folio(folio, NR_SWAPCACHE, nr_pages);
165270f0951SKairui Song }
166270f0951SKairui Song 
167270f0951SKairui Song /**
168270f0951SKairui Song  * swap_cache_add_folio - Add a folio into the swap cache.
169270f0951SKairui Song  * @folio: The folio to be added.
170270f0951SKairui Song  * @entry: The swap entry corresponding to the folio.
171270f0951SKairui Song  * @gfp: gfp_mask for XArray node allocation.
172270f0951SKairui Song  * @shadowp: If a shadow is found, return the shadow.
173270f0951SKairui Song  *
174270f0951SKairui Song  * Context: Caller must ensure @entry is valid and protect the swap device
175270f0951SKairui Song  * with reference count or locks.
176270f0951SKairui Song  */
swap_cache_add_folio(struct folio * folio,swp_entry_t entry,void ** shadowp)177270f0951SKairui Song static int swap_cache_add_folio(struct folio *folio, swp_entry_t entry,
178270f0951SKairui Song 				void **shadowp)
179270f0951SKairui Song {
180270f0951SKairui Song 	int err;
181270f0951SKairui Song 	void *shadow = NULL;
182270f0951SKairui Song 	unsigned long old_tb;
183270f0951SKairui Song 	struct swap_info_struct *si;
184270f0951SKairui Song 	struct swap_cluster_info *ci;
1850d6af9bcSKairui Song 	unsigned int ci_start, ci_off, ci_end;
186270f0951SKairui Song 	unsigned long nr_pages = folio_nr_pages(folio);
187270f0951SKairui Song 
188270f0951SKairui Song 	si = __swap_entry_to_info(entry);
189270f0951SKairui Song 	ci_start = swp_cluster_offset(entry);
1908578e0c0SKairui Song 	ci_end = ci_start + nr_pages;
1918578e0c0SKairui Song 	ci_off = ci_start;
1922732acdaSKairui Song 	ci = swap_cluster_lock(si, swp_offset(entry));
1932732acdaSKairui Song 	if (unlikely(!ci->table)) {
1942732acdaSKairui Song 		err = -ENOENT;
1952732acdaSKairui Song 		goto failed;
1962732acdaSKairui Song 	}
1978578e0c0SKairui Song 	do {
1982732acdaSKairui Song 		old_tb = __swap_table_get(ci, ci_off);
1992732acdaSKairui Song 		if (unlikely(swp_tb_is_folio(old_tb))) {
2002732acdaSKairui Song 			err = -EEXIST;
2012732acdaSKairui Song 			goto failed;
2022732acdaSKairui Song 		}
2030d6af9bcSKairui Song 		if (unlikely(!__swp_tb_get_count(old_tb))) {
2042732acdaSKairui Song 			err = -ENOENT;
2052732acdaSKairui Song 			goto failed;
2062732acdaSKairui Song 		}
2078578e0c0SKairui Song 		if (swp_tb_is_shadow(old_tb))
2088578e0c0SKairui Song 			shadow = swp_tb_to_shadow(old_tb);
2092732acdaSKairui Song 	} while (++ci_off < ci_end);
210270f0951SKairui Song 	__swap_cache_add_folio(ci, folio, entry);
2118578e0c0SKairui Song 	swap_cluster_unlock(ci);
2128578e0c0SKairui Song 	if (shadowp)
2138578e0c0SKairui Song 		*shadowp = shadow;
2142732acdaSKairui Song 	return 0;
2152732acdaSKairui Song 
2162732acdaSKairui Song failed:
2172732acdaSKairui Song 	swap_cluster_unlock(ci);
2182732acdaSKairui Song 	return err;
2191da177e4SLinus Torvalds }
2201da177e4SLinus Torvalds 
221fd8d4f86SKairui Song /**
222fd8d4f86SKairui Song  * __swap_cache_del_folio - Removes a folio from the swap cache.
2238578e0c0SKairui Song  * @ci: The locked swap cluster.
224fd8d4f86SKairui Song  * @folio: The folio.
225fd8d4f86SKairui Song  * @entry: The first swap entry that the folio corresponds to.
226fd8d4f86SKairui Song  * @shadow: shadow value to be filled in the swap cache.
227fd8d4f86SKairui Song  *
228fd8d4f86SKairui Song  * Removes a folio from the swap cache and fills a shadow in place.
229fd8d4f86SKairui Song  * This won't put the folio's refcount. The caller has to do that.
230fd8d4f86SKairui Song  *
2318578e0c0SKairui Song  * Context: Caller must ensure the folio is locked and in the swap cache
2328578e0c0SKairui Song  * using the index of @entry, and lock the cluster that holds the entries.
2331da177e4SLinus Torvalds  */
__swap_cache_del_folio(struct swap_cluster_info * ci,struct folio * folio,swp_entry_t entry,void * shadow)2348578e0c0SKairui Song void __swap_cache_del_folio(struct swap_cluster_info *ci, struct folio *folio,
2353852f676SJoonsoo Kim 			    swp_entry_t entry, void *shadow)
2361da177e4SLinus Torvalds {
2370d6af9bcSKairui Song 	int count;
2380d6af9bcSKairui Song 	unsigned long old_tb;
2392732acdaSKairui Song 	struct swap_info_struct *si;
2408578e0c0SKairui Song 	unsigned int ci_start, ci_off, ci_end;
241d3852f96SKairui Song 	bool folio_swapped = false, need_free = false;
2428578e0c0SKairui Song 	unsigned long nr_pages = folio_nr_pages(folio);
24333806f06SShaohua Li 
2448578e0c0SKairui Song 	VM_WARN_ON_ONCE(__swap_entry_to_cluster(entry) != ci);
2458578e0c0SKairui Song 	VM_WARN_ON_ONCE_FOLIO(!folio_test_locked(folio), folio);
2468578e0c0SKairui Song 	VM_WARN_ON_ONCE_FOLIO(!folio_test_swapcache(folio), folio);
2478578e0c0SKairui Song 	VM_WARN_ON_ONCE_FOLIO(folio_test_writeback(folio), folio);
2485649d113SYang Yang 
2492732acdaSKairui Song 	si = __swap_entry_to_info(entry);
2508578e0c0SKairui Song 	ci_start = swp_cluster_offset(entry);
2518578e0c0SKairui Song 	ci_end = ci_start + nr_pages;
2528578e0c0SKairui Song 	ci_off = ci_start;
2538578e0c0SKairui Song 	do {
2540d6af9bcSKairui Song 		old_tb = __swap_table_get(ci, ci_off);
2558578e0c0SKairui Song 		WARN_ON_ONCE(!swp_tb_is_folio(old_tb) ||
2568578e0c0SKairui Song 			     swp_tb_to_folio(old_tb) != folio);
2570d6af9bcSKairui Song 		count = __swp_tb_get_count(old_tb);
2580d6af9bcSKairui Song 		if (count)
259d3852f96SKairui Song 			folio_swapped = true;
260d3852f96SKairui Song 		else
261d3852f96SKairui Song 			need_free = true;
2620d6af9bcSKairui Song 		/* If shadow is NULL, we sets an empty shadow. */
2630d6af9bcSKairui Song 		__swap_table_set(ci, ci_off, shadow_to_swp_tb(shadow, count));
2648578e0c0SKairui Song 	} while (++ci_off < ci_end);
2651da177e4SLinus Torvalds 
2663d2c9087SDavid Hildenbrand 	folio->swap.val = 0;
267ceff9d33SMatthew Wilcox (Oracle) 	folio_clear_swapcache(folio);
2688578e0c0SKairui Song 	node_stat_mod_folio(folio, NR_FILE_PAGES, -nr_pages);
2698578e0c0SKairui Song 	lruvec_stat_mod_folio(folio, NR_SWAPCACHE, -nr_pages);
270d3852f96SKairui Song 
271d3852f96SKairui Song 	if (!folio_swapped) {
2720d6af9bcSKairui Song 		__swap_cluster_free_entries(si, ci, ci_start, nr_pages);
273d3852f96SKairui Song 	} else if (need_free) {
2740d6af9bcSKairui Song 		ci_off = ci_start;
275d3852f96SKairui Song 		do {
2760d6af9bcSKairui Song 			if (!__swp_tb_get_count(__swap_table_get(ci, ci_off)))
2770d6af9bcSKairui Song 				__swap_cluster_free_entries(si, ci, ci_off, 1);
2780d6af9bcSKairui Song 		} while (++ci_off < ci_end);
279d3852f96SKairui Song 	}
2801da177e4SLinus Torvalds }
2811da177e4SLinus Torvalds 
282fd8d4f86SKairui Song /**
283fd8d4f86SKairui Song  * swap_cache_del_folio - Removes a folio from the swap cache.
284fd8d4f86SKairui Song  * @folio: The folio.
285fd8d4f86SKairui Song  *
286fd8d4f86SKairui Song  * Same as __swap_cache_del_folio, but handles lock and refcount. The
287fd8d4f86SKairui Song  * caller must ensure the folio is either clean or has a swap count
288fd8d4f86SKairui Song  * equal to zero, or it may cause data loss.
289fd8d4f86SKairui Song  *
290fd8d4f86SKairui Song  * Context: Caller must ensure the folio is locked and in the swap cache.
2911da177e4SLinus Torvalds  */
swap_cache_del_folio(struct folio * folio)292fd8d4f86SKairui Song void swap_cache_del_folio(struct folio *folio)
2931da177e4SLinus Torvalds {
2948578e0c0SKairui Song 	struct swap_cluster_info *ci;
2953d2c9087SDavid Hildenbrand 	swp_entry_t entry = folio->swap;
2961da177e4SLinus Torvalds 
2978578e0c0SKairui Song 	ci = swap_cluster_lock(__swap_entry_to_info(entry), swp_offset(entry));
2988578e0c0SKairui Song 	__swap_cache_del_folio(ci, folio, entry, NULL);
2998578e0c0SKairui Song 	swap_cluster_unlock(ci);
3001da177e4SLinus Torvalds 
30175fa68a5SMatthew Wilcox (Oracle) 	folio_ref_sub(folio, folio_nr_pages(folio));
3021da177e4SLinus Torvalds }
3031da177e4SLinus Torvalds 
304fd8d4f86SKairui Song /**
305094dc8b0SKairui Song  * __swap_cache_replace_folio - Replace a folio in the swap cache.
3068578e0c0SKairui Song  * @ci: The locked swap cluster.
307094dc8b0SKairui Song  * @old: The old folio to be replaced.
308094dc8b0SKairui Song  * @new: The new folio.
309094dc8b0SKairui Song  *
310094dc8b0SKairui Song  * Replace an existing folio in the swap cache with a new folio. The
311094dc8b0SKairui Song  * caller is responsible for setting up the new folio's flag and swap
312094dc8b0SKairui Song  * entries. Replacement will take the new folio's swap entry value as
313094dc8b0SKairui Song  * the starting offset to override all slots covered by the new folio.
314094dc8b0SKairui Song  *
3158578e0c0SKairui Song  * Context: Caller must ensure both folios are locked, and lock the
3168578e0c0SKairui Song  * cluster that holds the old folio to be replaced.
317094dc8b0SKairui Song  */
__swap_cache_replace_folio(struct swap_cluster_info * ci,struct folio * old,struct folio * new)3188578e0c0SKairui Song void __swap_cache_replace_folio(struct swap_cluster_info *ci,
3198578e0c0SKairui Song 				struct folio *old, struct folio *new)
320094dc8b0SKairui Song {
321094dc8b0SKairui Song 	swp_entry_t entry = new->swap;
322094dc8b0SKairui Song 	unsigned long nr_pages = folio_nr_pages(new);
3238578e0c0SKairui Song 	unsigned int ci_off = swp_cluster_offset(entry);
3248578e0c0SKairui Song 	unsigned int ci_end = ci_off + nr_pages;
3250d6af9bcSKairui Song 	unsigned long pfn = folio_pfn(new);
3260d6af9bcSKairui Song 	unsigned long old_tb;
327094dc8b0SKairui Song 
328094dc8b0SKairui Song 	VM_WARN_ON_ONCE(!folio_test_swapcache(old) || !folio_test_swapcache(new));
329094dc8b0SKairui Song 	VM_WARN_ON_ONCE(!folio_test_locked(old) || !folio_test_locked(new));
330094dc8b0SKairui Song 	VM_WARN_ON_ONCE(!entry.val);
331094dc8b0SKairui Song 
332094dc8b0SKairui Song 	/* Swap cache still stores N entries instead of a high-order entry */
333094dc8b0SKairui Song 	do {
3340d6af9bcSKairui Song 		old_tb = __swap_table_get(ci, ci_off);
3358578e0c0SKairui Song 		WARN_ON_ONCE(!swp_tb_is_folio(old_tb) || swp_tb_to_folio(old_tb) != old);
3360d6af9bcSKairui Song 		__swap_table_set(ci, ci_off, pfn_to_swp_tb(pfn, __swp_tb_get_count(old_tb)));
3378578e0c0SKairui Song 	} while (++ci_off < ci_end);
3388578e0c0SKairui Song 
3398578e0c0SKairui Song 	/*
3408578e0c0SKairui Song 	 * If the old folio is partially replaced (e.g., splitting a large
3418578e0c0SKairui Song 	 * folio, the old folio is shrunk, and new split sub folios replace
3428578e0c0SKairui Song 	 * the shrunk part), ensure the new folio doesn't overlap it.
3438578e0c0SKairui Song 	 */
3448578e0c0SKairui Song 	if (IS_ENABLED(CONFIG_DEBUG_VM) &&
3458578e0c0SKairui Song 	    folio_order(old) != folio_order(new)) {
3468578e0c0SKairui Song 		ci_off = swp_cluster_offset(old->swap);
3478578e0c0SKairui Song 		ci_end = ci_off + folio_nr_pages(old);
3488578e0c0SKairui Song 		while (ci_off++ < ci_end)
3498578e0c0SKairui Song 			WARN_ON_ONCE(swp_tb_to_folio(__swap_table_get(ci, ci_off)) != old);
3508578e0c0SKairui Song 	}
351094dc8b0SKairui Song }
352094dc8b0SKairui Song 
3531da177e4SLinus Torvalds /*
3541da177e4SLinus Torvalds  * If we are the only user, then try to free up the swap cache.
3551da177e4SLinus Torvalds  *
356aedd74d4SMatthew Wilcox (Oracle)  * Its ok to check the swapcache flag without the folio lock
3571da177e4SLinus Torvalds  * here because we are going to recheck again inside
358aedd74d4SMatthew Wilcox (Oracle)  * folio_free_swap() _with_ the lock.
3591da177e4SLinus Torvalds  * 					- Marcelo
3601da177e4SLinus Torvalds  */
free_swap_cache(struct folio * folio)36163b77499SMatthew Wilcox (Oracle) void free_swap_cache(struct folio *folio)
3621da177e4SLinus Torvalds {
363aedd74d4SMatthew Wilcox (Oracle) 	if (folio_test_swapcache(folio) && !folio_mapped(folio) &&
364aedd74d4SMatthew Wilcox (Oracle) 	    folio_trylock(folio)) {
365aedd74d4SMatthew Wilcox (Oracle) 		folio_free_swap(folio);
366aedd74d4SMatthew Wilcox (Oracle) 		folio_unlock(folio);
3671da177e4SLinus Torvalds 	}
3681da177e4SLinus Torvalds }
3691da177e4SLinus Torvalds 
3701da177e4SLinus Torvalds /*
37106340b92SFan Ni  * Freeing a folio and also freeing any swap cache associated with
37206340b92SFan Ni  * this folio if it is the last user.
3731da177e4SLinus Torvalds  */
free_folio_and_swap_cache(struct folio * folio)37406340b92SFan Ni void free_folio_and_swap_cache(struct folio *folio)
3751da177e4SLinus Torvalds {
37663b77499SMatthew Wilcox (Oracle) 	free_swap_cache(folio);
3775beaee54SMatthew Wilcox (Oracle) 	if (!is_huge_zero_folio(folio))
37863b77499SMatthew Wilcox (Oracle) 		folio_put(folio);
3791da177e4SLinus Torvalds }
3801da177e4SLinus Torvalds 
3811da177e4SLinus Torvalds /*
3821da177e4SLinus Torvalds  * Passed an array of pages, drop them all from swapcache and then release
3831da177e4SLinus Torvalds  * them.  They are removed from the LRU and freed if this is their last use.
3841da177e4SLinus Torvalds  */
free_pages_and_swap_cache(struct encoded_page ** pages,int nr)3857cc8f9c7SLinus Torvalds void free_pages_and_swap_cache(struct encoded_page **pages, int nr)
3861da177e4SLinus Torvalds {
3874907e80bSMatthew Wilcox (Oracle) 	struct folio_batch folios;
388511f04aaSTal Zussman 	unsigned int refs[FOLIO_BATCH_SIZE];
389d7f861b9SDavid Hildenbrand 
3904907e80bSMatthew Wilcox (Oracle) 	folio_batch_init(&folios);
3914907e80bSMatthew Wilcox (Oracle) 	for (int i = 0; i < nr; i++) {
3924907e80bSMatthew Wilcox (Oracle) 		struct folio *folio = page_folio(encoded_page_ptr(pages[i]));
3934907e80bSMatthew Wilcox (Oracle) 
39463b77499SMatthew Wilcox (Oracle) 		free_swap_cache(folio);
3954907e80bSMatthew Wilcox (Oracle) 		refs[folios.nr] = 1;
396d7f861b9SDavid Hildenbrand 		if (unlikely(encoded_page_flags(pages[i]) &
397d7f861b9SDavid Hildenbrand 			     ENCODED_PAGE_BIT_NR_PAGES_NEXT))
3984907e80bSMatthew Wilcox (Oracle) 			refs[folios.nr] = encoded_nr_pages(pages[++i]);
399d7f861b9SDavid Hildenbrand 
4004907e80bSMatthew Wilcox (Oracle) 		if (folio_batch_add(&folios, folio) == 0)
4014907e80bSMatthew Wilcox (Oracle) 			folios_put_refs(&folios, refs);
402d7f861b9SDavid Hildenbrand 	}
4034907e80bSMatthew Wilcox (Oracle) 	if (folios.nr)
4044907e80bSMatthew Wilcox (Oracle) 		folios_put_refs(&folios, refs);
4051da177e4SLinus Torvalds }
4061da177e4SLinus Torvalds 
swap_use_vma_readahead(void)407e9e9b7ecSMinchan Kim static inline bool swap_use_vma_readahead(void)
408e9e9b7ecSMinchan Kim {
409e9e9b7ecSMinchan Kim 	return READ_ONCE(enable_vma_readahead) && !atomic_read(&nr_rotate_swap);
410e9e9b7ecSMinchan Kim }
411e9e9b7ecSMinchan Kim 
412f2812461SKairui Song /**
413f2812461SKairui Song  * swap_update_readahead - Update the readahead statistics of VMA or globally.
414f2812461SKairui Song  * @folio: the swap cache folio that just got hit.
415f2812461SKairui Song  * @vma: the VMA that should be updated, could be NULL for global update.
416f2812461SKairui Song  * @addr: the addr that triggered the swapin, ignored if @vma is NULL.
4171da177e4SLinus Torvalds  */
swap_update_readahead(struct folio * folio,struct vm_area_struct * vma,unsigned long addr)418f2812461SKairui Song void swap_update_readahead(struct folio *folio, struct vm_area_struct *vma,
419f2812461SKairui Song 			   unsigned long addr)
4201da177e4SLinus Torvalds {
421f2812461SKairui Song 	bool readahead, vma_ra = swap_use_vma_readahead();
422eaf649ebSMinchan Kim 
423eaf649ebSMinchan Kim 	/*
424eaf649ebSMinchan Kim 	 * At the moment, we don't support PG_readahead for anon THP
425eaf649ebSMinchan Kim 	 * so let's bail out rather than confusing the readahead stat.
426eaf649ebSMinchan Kim 	 */
427c9edc242SMatthew Wilcox (Oracle) 	if (unlikely(folio_test_large(folio)))
428f2812461SKairui Song 		return;
429eaf649ebSMinchan Kim 
430c9edc242SMatthew Wilcox (Oracle) 	readahead = folio_test_clear_readahead(folio);
431eaf649ebSMinchan Kim 	if (vma && vma_ra) {
432eaf649ebSMinchan Kim 		unsigned long ra_val;
433eaf649ebSMinchan Kim 		int win, hits;
434eaf649ebSMinchan Kim 
435eaf649ebSMinchan Kim 		ra_val = GET_SWAP_RA_VAL(vma);
436eaf649ebSMinchan Kim 		win = SWAP_RA_WIN(ra_val);
437eaf649ebSMinchan Kim 		hits = SWAP_RA_HITS(ra_val);
438ec560175SHuang Ying 		if (readahead)
439ec560175SHuang Ying 			hits = min_t(int, hits + 1, SWAP_RA_HITS_MAX);
440ec560175SHuang Ying 		atomic_long_set(&vma->swap_readahead_info,
441ec560175SHuang Ying 				SWAP_RA_VAL(addr, win, hits));
442ec560175SHuang Ying 	}
443eaf649ebSMinchan Kim 
444ec560175SHuang Ying 	if (readahead) {
445ec560175SHuang Ying 		count_vm_event(SWAP_RA_HIT);
446eaf649ebSMinchan Kim 		if (!vma || !vma_ra)
447ec560175SHuang Ying 			atomic_inc(&swapin_readahead_hits);
448ec560175SHuang Ying 	}
449c9edc242SMatthew Wilcox (Oracle) }
450c9edc242SMatthew Wilcox (Oracle) 
451d7cf0d54SKairui Song /**
45284eedc74SKairui Song  * __swap_cache_prepare_and_add - Prepare the folio and add it to swap cache.
45384eedc74SKairui Song  * @entry: swap entry to be bound to the folio.
45484eedc74SKairui Song  * @folio: folio to be added.
45584eedc74SKairui Song  * @gfp: memory allocation flags for charge, can be 0 if @charged if true.
45684eedc74SKairui Song  * @charged: if the folio is already charged.
45784eedc74SKairui Song  *
45884eedc74SKairui Song  * Update the swap_map and add folio as swap cache, typically before swapin.
45984eedc74SKairui Song  * All swap slots covered by the folio must have a non-zero swap count.
46084eedc74SKairui Song  *
46184eedc74SKairui Song  * Context: Caller must protect the swap device with reference count or locks.
46284eedc74SKairui Song  * Return: Returns the folio being added on success. Returns the existing folio
46384eedc74SKairui Song  * if @entry is already cached. Returns NULL if raced with swapin or swapoff.
46484eedc74SKairui Song  */
__swap_cache_prepare_and_add(swp_entry_t entry,struct folio * folio,gfp_t gfp,bool charged)46584eedc74SKairui Song static struct folio *__swap_cache_prepare_and_add(swp_entry_t entry,
46684eedc74SKairui Song 						  struct folio *folio,
467de85024bSKairui Song 						  gfp_t gfp, bool charged)
46884eedc74SKairui Song {
4692732acdaSKairui Song 	struct folio *swapcache = NULL;
47084eedc74SKairui Song 	void *shadow;
47184eedc74SKairui Song 	int ret;
47284eedc74SKairui Song 
4732732acdaSKairui Song 	__folio_set_locked(folio);
4742732acdaSKairui Song 	__folio_set_swapbacked(folio);
475*9acbe135SAlexandre Ghiti 
476*9acbe135SAlexandre Ghiti 	if (!charged && mem_cgroup_swapin_charge_folio(folio, NULL, gfp, entry))
477*9acbe135SAlexandre Ghiti 		goto failed;
478*9acbe135SAlexandre Ghiti 
47984eedc74SKairui Song 	for (;;) {
480270f0951SKairui Song 		ret = swap_cache_add_folio(folio, entry, &shadow);
48184eedc74SKairui Song 		if (!ret)
48284eedc74SKairui Song 			break;
48384eedc74SKairui Song 
48484eedc74SKairui Song 		/*
4852732acdaSKairui Song 		 * Large order allocation needs special handling on
48684eedc74SKairui Song 		 * race: if a smaller folio exists in cache, swapin needs
48784eedc74SKairui Song 		 * to fallback to order 0, and doing a swap cache lookup
48884eedc74SKairui Song 		 * might return a folio that is irrelevant to the faulting
48984eedc74SKairui Song 		 * entry because @entry is aligned down. Just return NULL.
49084eedc74SKairui Song 		 */
491de85024bSKairui Song 		if (ret != -EEXIST || folio_test_large(folio))
4922732acdaSKairui Song 			goto failed;
49384eedc74SKairui Song 
49484eedc74SKairui Song 		swapcache = swap_cache_get_folio(entry);
49584eedc74SKairui Song 		if (swapcache)
4962732acdaSKairui Song 			goto failed;
49784eedc74SKairui Song 	}
49884eedc74SKairui Song 
49984eedc74SKairui Song 	memcg1_swapin(entry, folio_nr_pages(folio));
50084eedc74SKairui Song 	if (shadow)
50184eedc74SKairui Song 		workingset_refault(folio, shadow);
50284eedc74SKairui Song 
50384eedc74SKairui Song 	/* Caller will initiate read into locked folio */
50484eedc74SKairui Song 	folio_add_lru(folio);
50584eedc74SKairui Song 	return folio;
5062732acdaSKairui Song 
5072732acdaSKairui Song failed:
5082732acdaSKairui Song 	folio_unlock(folio);
5092732acdaSKairui Song 	return swapcache;
51084eedc74SKairui Song }
51184eedc74SKairui Song 
51284eedc74SKairui Song /**
513d7cf0d54SKairui Song  * swap_cache_alloc_folio - Allocate folio for swapped out slot in swap cache.
514d7cf0d54SKairui Song  * @entry: the swapped out swap entry to be binded to the folio.
515d7cf0d54SKairui Song  * @gfp_mask: memory allocation flags
516d7cf0d54SKairui Song  * @mpol: NUMA memory allocation policy to be applied
517d7cf0d54SKairui Song  * @ilx: NUMA interleave index, for use only when MPOL_INTERLEAVE
518d7cf0d54SKairui Song  * @new_page_allocated: sets true if allocation happened, false otherwise
519d7cf0d54SKairui Song  *
520d7cf0d54SKairui Song  * Allocate a folio in the swap cache for one swap slot, typically before
521d7cf0d54SKairui Song  * doing IO (e.g. swap in or zswap writeback). The swap slot indicated by
522d7cf0d54SKairui Song  * @entry must have a non-zero swap count (swapped out).
523d7cf0d54SKairui Song  * Currently only supports order 0.
524d7cf0d54SKairui Song  *
525d7cf0d54SKairui Song  * Context: Caller must protect the swap device with reference count or locks.
526d7cf0d54SKairui Song  * Return: Returns the existing folio if @entry is cached already. Returns
527d7cf0d54SKairui Song  * NULL if failed due to -ENOMEM or @entry have a swap count < 1.
528d7cf0d54SKairui Song  */
swap_cache_alloc_folio(swp_entry_t entry,gfp_t gfp_mask,struct mempolicy * mpol,pgoff_t ilx,bool * new_page_allocated)529d7cf0d54SKairui Song struct folio *swap_cache_alloc_folio(swp_entry_t entry, gfp_t gfp_mask,
530d7cf0d54SKairui Song 				     struct mempolicy *mpol, pgoff_t ilx,
531de85024bSKairui Song 				     bool *new_page_allocated)
5321da177e4SLinus Torvalds {
5330fcf8ef4SKairui Song 	struct swap_info_struct *si = __swap_entry_to_info(entry);
534a0d3374bSMatthew Wilcox (Oracle) 	struct folio *folio;
5351d344030SZhaoyu Liu 	struct folio *result = NULL;
5364c6355b2SJohannes Weiner 
5375b999aadSDmitry Safonov 	*new_page_allocated = false;
53884eedc74SKairui Song 	/* Check the swap cache again for readahead path. */
539f2812461SKairui Song 	folio = swap_cache_get_folio(entry);
540f2812461SKairui Song 	if (folio)
54184eedc74SKairui Song 		return folio;
5421da177e4SLinus Torvalds 
543f7ad377aSKairui Song 	/* Skip allocation for unused and bad swap slot for readahead. */
5440ff67f99SKairui Song 	if (!swap_entry_swapped(si, entry))
54584eedc74SKairui Song 		return NULL;
546e8c26ab6STim Chen 
54784eedc74SKairui Song 	/* Allocate a new folio to be added into the swap cache. */
54884eedc74SKairui Song 	folio = folio_alloc_mpol(gfp_mask, 0, mpol, ilx, numa_node_id());
54984eedc74SKairui Song 	if (!folio)
55084eedc74SKairui Song 		return NULL;
55184eedc74SKairui Song 	/* Try add the new folio, returns existing folio or NULL on failure. */
552de85024bSKairui Song 	result = __swap_cache_prepare_and_add(entry, folio, gfp_mask, false);
55384eedc74SKairui Song 	if (result == folio)
5544c6355b2SJohannes Weiner 		*new_page_allocated = true;
55584eedc74SKairui Song 	else
55684eedc74SKairui Song 		folio_put(folio);
5571d344030SZhaoyu Liu 	return result;
5581da177e4SLinus Torvalds }
55946017e95SHugh Dickins 
560f1879e8aSKairui Song /**
561f1879e8aSKairui Song  * swapin_folio - swap-in one or multiple entries skipping readahead.
562f1879e8aSKairui Song  * @entry: starting swap entry to swap in
563f1879e8aSKairui Song  * @folio: a new allocated and charged folio
564f1879e8aSKairui Song  *
565f1879e8aSKairui Song  * Reads @entry into @folio, @folio will be added to the swap cache.
566f1879e8aSKairui Song  * If @folio is a large folio, the @entry will be rounded down to align
567f1879e8aSKairui Song  * with the folio size.
568f1879e8aSKairui Song  *
569f1879e8aSKairui Song  * Return: returns pointer to @folio on success. If folio is a large folio
570f1879e8aSKairui Song  * and this raced with another swapin, NULL will be returned to allow fallback
571f1879e8aSKairui Song  * to order 0. Else, if another folio was already added to the swap cache,
572f1879e8aSKairui Song  * return that swap cache folio instead.
573f1879e8aSKairui Song  */
swapin_folio(swp_entry_t entry,struct folio * folio)574f1879e8aSKairui Song struct folio *swapin_folio(swp_entry_t entry, struct folio *folio)
575f1879e8aSKairui Song {
576f1879e8aSKairui Song 	struct folio *swapcache;
577f1879e8aSKairui Song 	pgoff_t offset = swp_offset(entry);
578f1879e8aSKairui Song 	unsigned long nr_pages = folio_nr_pages(folio);
579f1879e8aSKairui Song 
580f1879e8aSKairui Song 	entry = swp_entry(swp_type(entry), round_down(offset, nr_pages));
581de85024bSKairui Song 	swapcache = __swap_cache_prepare_and_add(entry, folio, 0, true);
582f1879e8aSKairui Song 	if (swapcache == folio)
583f1879e8aSKairui Song 		swap_read_folio(folio, NULL);
584f1879e8aSKairui Song 	return swapcache;
585f1879e8aSKairui Song }
586f1879e8aSKairui Song 
5875b999aadSDmitry Safonov /*
5885b999aadSDmitry Safonov  * Locate a page of swap in physical memory, reserving swap cache space
5895b999aadSDmitry Safonov  * and reading the disk if it is not already cached.
5905b999aadSDmitry Safonov  * A failure return means that either the page allocation failed or that
5915b999aadSDmitry Safonov  * the swap entry is no longer in use.
5925b999aadSDmitry Safonov  */
read_swap_cache_async(swp_entry_t entry,gfp_t gfp_mask,struct vm_area_struct * vma,unsigned long addr,struct swap_iocb ** plug)5936e03492eSMatthew Wilcox (Oracle) struct folio *read_swap_cache_async(swp_entry_t entry, gfp_t gfp_mask,
5946e03492eSMatthew Wilcox (Oracle) 		struct vm_area_struct *vma, unsigned long addr,
5956e03492eSMatthew Wilcox (Oracle) 		struct swap_iocb **plug)
5965b999aadSDmitry Safonov {
59778524b05SKairui Song 	struct swap_info_struct *si;
598ddc1a5cbSHugh Dickins 	bool page_allocated;
599ddc1a5cbSHugh Dickins 	struct mempolicy *mpol;
600ddc1a5cbSHugh Dickins 	pgoff_t ilx;
60196c7b0b4SMatthew Wilcox (Oracle) 	struct folio *folio;
6025b999aadSDmitry Safonov 
60378524b05SKairui Song 	si = get_swap_device(entry);
60478524b05SKairui Song 	if (!si)
60578524b05SKairui Song 		return NULL;
60678524b05SKairui Song 
607ddc1a5cbSHugh Dickins 	mpol = get_vma_policy(vma, addr, 0, &ilx);
608d7cf0d54SKairui Song 	folio = swap_cache_alloc_folio(entry, gfp_mask, mpol, ilx,
609de85024bSKairui Song 				       &page_allocated);
610ddc1a5cbSHugh Dickins 	mpol_cond_put(mpol);
6115b999aadSDmitry Safonov 
612ddc1a5cbSHugh Dickins 	if (page_allocated)
613b2d1f38bSYosry Ahmed 		swap_read_folio(folio, plug);
61478524b05SKairui Song 
61578524b05SKairui Song 	put_swap_device(si);
6166e03492eSMatthew Wilcox (Oracle) 	return folio;
6175b999aadSDmitry Safonov }
6185b999aadSDmitry Safonov 
__swapin_nr_pages(unsigned long prev_offset,unsigned long offset,int hits,int max_pages,int prev_win)619ec560175SHuang Ying static unsigned int __swapin_nr_pages(unsigned long prev_offset,
620ec560175SHuang Ying 				      unsigned long offset,
621ec560175SHuang Ying 				      int hits,
622ec560175SHuang Ying 				      int max_pages,
623ec560175SHuang Ying 				      int prev_win)
624579f8290SShaohua Li {
625ec560175SHuang Ying 	unsigned int pages, last_ra;
626579f8290SShaohua Li 
627579f8290SShaohua Li 	/*
628579f8290SShaohua Li 	 * This heuristic has been found to work well on both sequential and
629579f8290SShaohua Li 	 * random loads, swapping to hard disk or to SSD: please don't ask
630579f8290SShaohua Li 	 * what the "+ 2" means, it just happens to work well, that's all.
631579f8290SShaohua Li 	 */
632ec560175SHuang Ying 	pages = hits + 2;
633579f8290SShaohua Li 	if (pages == 2) {
634579f8290SShaohua Li 		/*
635579f8290SShaohua Li 		 * We can have no readahead hits to judge by: but must not get
636579f8290SShaohua Li 		 * stuck here forever, so check for an adjacent offset instead
637579f8290SShaohua Li 		 * (and don't even bother to check whether swap type is same).
638579f8290SShaohua Li 		 */
639579f8290SShaohua Li 		if (offset != prev_offset + 1 && offset != prev_offset - 1)
640579f8290SShaohua Li 			pages = 1;
641579f8290SShaohua Li 	} else {
642579f8290SShaohua Li 		unsigned int roundup = 4;
643579f8290SShaohua Li 		while (roundup < pages)
644579f8290SShaohua Li 			roundup <<= 1;
645579f8290SShaohua Li 		pages = roundup;
646579f8290SShaohua Li 	}
647579f8290SShaohua Li 
648579f8290SShaohua Li 	if (pages > max_pages)
649579f8290SShaohua Li 		pages = max_pages;
650579f8290SShaohua Li 
651579f8290SShaohua Li 	/* Don't shrink readahead too fast */
652ec560175SHuang Ying 	last_ra = prev_win / 2;
653579f8290SShaohua Li 	if (pages < last_ra)
654579f8290SShaohua Li 		pages = last_ra;
655ec560175SHuang Ying 
656ec560175SHuang Ying 	return pages;
657ec560175SHuang Ying }
658ec560175SHuang Ying 
swapin_nr_pages(unsigned long offset)659ec560175SHuang Ying static unsigned long swapin_nr_pages(unsigned long offset)
660ec560175SHuang Ying {
661ec560175SHuang Ying 	static unsigned long prev_offset;
662ec560175SHuang Ying 	unsigned int hits, pages, max_pages;
663ec560175SHuang Ying 	static atomic_t last_readahead_pages;
664ec560175SHuang Ying 
665ec560175SHuang Ying 	max_pages = 1 << READ_ONCE(page_cluster);
666ec560175SHuang Ying 	if (max_pages <= 1)
667ec560175SHuang Ying 		return 1;
668ec560175SHuang Ying 
669ec560175SHuang Ying 	hits = atomic_xchg(&swapin_readahead_hits, 0);
670d6c1f098SQian Cai 	pages = __swapin_nr_pages(READ_ONCE(prev_offset), offset, hits,
671d6c1f098SQian Cai 				  max_pages,
672ec560175SHuang Ying 				  atomic_read(&last_readahead_pages));
673ec560175SHuang Ying 	if (!hits)
674d6c1f098SQian Cai 		WRITE_ONCE(prev_offset, offset);
675579f8290SShaohua Li 	atomic_set(&last_readahead_pages, pages);
676579f8290SShaohua Li 
677579f8290SShaohua Li 	return pages;
678579f8290SShaohua Li }
679579f8290SShaohua Li 
68046017e95SHugh Dickins /**
681e9e9b7ecSMinchan Kim  * swap_cluster_readahead - swap in pages in hope we need them soon
68246017e95SHugh Dickins  * @entry: swap entry of this memory
6837682486bSRandy Dunlap  * @gfp_mask: memory allocation flags
684ddc1a5cbSHugh Dickins  * @mpol: NUMA memory allocation policy to be applied
685ddc1a5cbSHugh Dickins  * @ilx: NUMA interleave index, for use only when MPOL_INTERLEAVE
68646017e95SHugh Dickins  *
687a4575c41SMatthew Wilcox (Oracle)  * Returns the struct folio for entry and addr, after queueing swapin.
68846017e95SHugh Dickins  *
68946017e95SHugh Dickins  * Primitive swap readahead code. We simply read an aligned block of
69046017e95SHugh Dickins  * (1 << page_cluster) entries in the swap area. This method is chosen
69146017e95SHugh Dickins  * because it doesn't cost us any seek time.  We also make sure to queue
69246017e95SHugh Dickins  * the 'original' request together with the readahead ones...
69346017e95SHugh Dickins  *
694ddc1a5cbSHugh Dickins  * Note: it is intentional that the same NUMA policy and interleave index
695ddc1a5cbSHugh Dickins  * are used for every page of the readahead: neighbouring pages on swap
696ddc1a5cbSHugh Dickins  * are fairly likely to have been swapped out from the same node.
69746017e95SHugh Dickins  */
swap_cluster_readahead(swp_entry_t entry,gfp_t gfp_mask,struct mempolicy * mpol,pgoff_t ilx)698a4575c41SMatthew Wilcox (Oracle) struct folio *swap_cluster_readahead(swp_entry_t entry, gfp_t gfp_mask,
699ddc1a5cbSHugh Dickins 				    struct mempolicy *mpol, pgoff_t ilx)
70046017e95SHugh Dickins {
70196c7b0b4SMatthew Wilcox (Oracle) 	struct folio *folio;
702579f8290SShaohua Li 	unsigned long entry_offset = swp_offset(entry);
703579f8290SShaohua Li 	unsigned long offset = entry_offset;
70467f96aa2SRik van Riel 	unsigned long start_offset, end_offset;
705579f8290SShaohua Li 	unsigned long mask;
7060fcf8ef4SKairui Song 	struct swap_info_struct *si = __swap_entry_to_info(entry);
7073fb5c298SChristian Ehrhardt 	struct blk_plug plug;
7085169b844SNeilBrown 	struct swap_iocb *splug = NULL;
709b243dcbfSSuren Baghdasaryan 	bool page_allocated;
71046017e95SHugh Dickins 
711579f8290SShaohua Li 	mask = swapin_nr_pages(offset) - 1;
712579f8290SShaohua Li 	if (!mask)
713579f8290SShaohua Li 		goto skip;
714579f8290SShaohua Li 
71567f96aa2SRik van Riel 	/* Read a page_cluster sized and aligned cluster around offset. */
71667f96aa2SRik van Riel 	start_offset = offset & ~mask;
71767f96aa2SRik van Riel 	end_offset = offset | mask;
71867f96aa2SRik van Riel 	if (!start_offset)	/* First page is swap header. */
71967f96aa2SRik van Riel 		start_offset++;
720e9a6effaSHuang Ying 	if (end_offset >= si->max)
721e9a6effaSHuang Ying 		end_offset = si->max - 1;
72267f96aa2SRik van Riel 
7233fb5c298SChristian Ehrhardt 	blk_start_plug(&plug);
72467f96aa2SRik van Riel 	for (offset = start_offset; offset <= end_offset ; offset++) {
72546017e95SHugh Dickins 		/* Ok, do the async read-ahead now */
726d7cf0d54SKairui Song 		folio = swap_cache_alloc_folio(
727d7cf0d54SKairui Song 			swp_entry(swp_type(entry), offset), gfp_mask, mpol, ilx,
728de85024bSKairui Song 			&page_allocated);
72996c7b0b4SMatthew Wilcox (Oracle) 		if (!folio)
73067f96aa2SRik van Riel 			continue;
731c4fa6309SHuang Ying 		if (page_allocated) {
732b2d1f38bSYosry Ahmed 			swap_read_folio(folio, &splug);
733eaf649ebSMinchan Kim 			if (offset != entry_offset) {
73496c7b0b4SMatthew Wilcox (Oracle) 				folio_set_readahead(folio);
735cbc65df2SHuang Ying 				count_vm_event(SWAP_RA);
736cbc65df2SHuang Ying 			}
737c4fa6309SHuang Ying 		}
73896c7b0b4SMatthew Wilcox (Oracle) 		folio_put(folio);
73946017e95SHugh Dickins 	}
7403fb5c298SChristian Ehrhardt 	blk_finish_plug(&plug);
7415169b844SNeilBrown 	swap_read_unplug(splug);
74246017e95SHugh Dickins 	lru_add_drain();	/* Push any new pages onto the LRU now */
743579f8290SShaohua Li skip:
7445169b844SNeilBrown 	/* The page was likely read above, so no need for plugging here */
745d7cf0d54SKairui Song 	folio = swap_cache_alloc_folio(entry, gfp_mask, mpol, ilx,
746de85024bSKairui Song 				       &page_allocated);
7470e400844SNhat Pham 	if (unlikely(page_allocated))
748b2d1f38bSYosry Ahmed 		swap_read_folio(folio, NULL);
749a4575c41SMatthew Wilcox (Oracle) 	return folio;
75046017e95SHugh Dickins }
7514b3ef9daSHuang, Ying 
swap_vma_ra_win(struct vm_fault * vmf,unsigned long * start,unsigned long * end)752ba518f4dSHuang Ying static int swap_vma_ra_win(struct vm_fault *vmf, unsigned long *start,
753ba518f4dSHuang Ying 			   unsigned long *end)
754ec560175SHuang Ying {
755ec560175SHuang Ying 	struct vm_area_struct *vma = vmf->vma;
756eaf649ebSMinchan Kim 	unsigned long ra_val;
757ba518f4dSHuang Ying 	unsigned long faddr, prev_faddr, left, right;
75816ba391eSKairui Song 	unsigned int max_win, hits, prev_win, win;
759ec560175SHuang Ying 
760ba518f4dSHuang Ying 	max_win = 1 << min(READ_ONCE(page_cluster), SWAP_RA_ORDER_CEILING);
761dce08dd2SHuang Ying 	if (max_win == 1)
762dce08dd2SHuang Ying 		return 1;
76361b63972SHuang Ying 
764ec560175SHuang Ying 	faddr = vmf->address;
765eaf649ebSMinchan Kim 	ra_val = GET_SWAP_RA_VAL(vma);
766ba518f4dSHuang Ying 	prev_faddr = SWAP_RA_ADDR(ra_val);
767eaf649ebSMinchan Kim 	prev_win = SWAP_RA_WIN(ra_val);
768eaf649ebSMinchan Kim 	hits = SWAP_RA_HITS(ra_val);
769ba518f4dSHuang Ying 	win = __swapin_nr_pages(PFN_DOWN(prev_faddr), PFN_DOWN(faddr), hits,
770ba518f4dSHuang Ying 				max_win, prev_win);
771ba518f4dSHuang Ying 	atomic_long_set(&vma->swap_readahead_info, SWAP_RA_VAL(faddr, win, 0));
77218ad72f5SKairui Song 	if (win == 1)
773dce08dd2SHuang Ying 		return 1;
774ec560175SHuang Ying 
775ba518f4dSHuang Ying 	if (faddr == prev_faddr + PAGE_SIZE)
776ba518f4dSHuang Ying 		left = faddr;
777ba518f4dSHuang Ying 	else if (prev_faddr == faddr + PAGE_SIZE)
778ba518f4dSHuang Ying 		left = faddr - (win << PAGE_SHIFT) + PAGE_SIZE;
779ba518f4dSHuang Ying 	else
780ba518f4dSHuang Ying 		left = faddr - (((win - 1) / 2) << PAGE_SHIFT);
781ba518f4dSHuang Ying 	right = left + (win << PAGE_SHIFT);
782ba518f4dSHuang Ying 	if ((long)left < 0)
783ba518f4dSHuang Ying 		left = 0;
784ba518f4dSHuang Ying 	*start = max3(left, vma->vm_start, faddr & PMD_MASK);
785ba518f4dSHuang Ying 	*end = min3(right, vma->vm_end, (faddr & PMD_MASK) + PMD_SIZE);
786dce08dd2SHuang Ying 
787dce08dd2SHuang Ying 	return win;
788ec560175SHuang Ying }
789ec560175SHuang Ying 
790e9f59873SYang Shi /**
791e9f59873SYang Shi  * swap_vma_readahead - swap in pages in hope we need them soon
792ddc1a5cbSHugh Dickins  * @targ_entry: swap entry of the targeted memory
793e9f59873SYang Shi  * @gfp_mask: memory allocation flags
794ddc1a5cbSHugh Dickins  * @mpol: NUMA memory allocation policy to be applied
795ddc1a5cbSHugh Dickins  * @targ_ilx: NUMA interleave index, for use only when MPOL_INTERLEAVE
796e9f59873SYang Shi  * @vmf: fault information
797e9f59873SYang Shi  *
798a4575c41SMatthew Wilcox (Oracle)  * Returns the struct folio for entry and addr, after queueing swapin.
799e9f59873SYang Shi  *
800cb152a1aSShijie Luo  * Primitive swap readahead code. We simply read in a few pages whose
801e9f59873SYang Shi  * virtual addresses are around the fault address in the same vma.
802e9f59873SYang Shi  *
803c1e8d7c6SMichel Lespinasse  * Caller must hold read mmap_lock if vmf->vma is not NULL.
804e9f59873SYang Shi  *
805e9f59873SYang Shi  */
swap_vma_readahead(swp_entry_t targ_entry,gfp_t gfp_mask,struct mempolicy * mpol,pgoff_t targ_ilx,struct vm_fault * vmf)806a4575c41SMatthew Wilcox (Oracle) static struct folio *swap_vma_readahead(swp_entry_t targ_entry, gfp_t gfp_mask,
807a4575c41SMatthew Wilcox (Oracle) 		struct mempolicy *mpol, pgoff_t targ_ilx, struct vm_fault *vmf)
808ec560175SHuang Ying {
809ec560175SHuang Ying 	struct blk_plug plug;
8105169b844SNeilBrown 	struct swap_iocb *splug = NULL;
81196c7b0b4SMatthew Wilcox (Oracle) 	struct folio *folio;
8124f8fcf4cSHugh Dickins 	pte_t *pte = NULL, pentry;
813ba518f4dSHuang Ying 	int win;
814ba518f4dSHuang Ying 	unsigned long start, end, addr;
815ddc1a5cbSHugh Dickins 	pgoff_t ilx;
816ec560175SHuang Ying 	bool page_allocated;
817ec560175SHuang Ying 
818ba518f4dSHuang Ying 	win = swap_vma_ra_win(vmf, &start, &end);
819dce08dd2SHuang Ying 	if (win == 1)
820ec560175SHuang Ying 		goto skip;
821ec560175SHuang Ying 
822ba518f4dSHuang Ying 	ilx = targ_ilx - PFN_DOWN(vmf->address - start);
8234f8fcf4cSHugh Dickins 
824ec560175SHuang Ying 	blk_start_plug(&plug);
825ba518f4dSHuang Ying 	for (addr = start; addr < end; ilx++, addr += PAGE_SIZE) {
8261c2a936eSKairui Song 		struct swap_info_struct *si = NULL;
82706fb6146SLorenzo Stoakes 		softleaf_t entry;
8281c2a936eSKairui Song 
8294f8fcf4cSHugh Dickins 		if (!pte++) {
8304f8fcf4cSHugh Dickins 			pte = pte_offset_map(vmf->pmd, addr);
8314f8fcf4cSHugh Dickins 			if (!pte)
8324f8fcf4cSHugh Dickins 				break;
8334f8fcf4cSHugh Dickins 		}
8344f8fcf4cSHugh Dickins 		pentry = ptep_get_lockless(pte);
83506fb6146SLorenzo Stoakes 		entry = softleaf_from_pte(pentry);
83606fb6146SLorenzo Stoakes 
83706fb6146SLorenzo Stoakes 		if (!softleaf_is_swap(entry))
838ec560175SHuang Ying 			continue;
8394f8fcf4cSHugh Dickins 		pte_unmap(pte);
8404f8fcf4cSHugh Dickins 		pte = NULL;
8411c2a936eSKairui Song 		/*
8421c2a936eSKairui Song 		 * Readahead entry may come from a device that we are not
8431c2a936eSKairui Song 		 * holding a reference to, try to grab a reference, or skip.
8441c2a936eSKairui Song 		 */
8451c2a936eSKairui Song 		if (swp_type(entry) != swp_type(targ_entry)) {
8461c2a936eSKairui Song 			si = get_swap_device(entry);
8471c2a936eSKairui Song 			if (!si)
8481c2a936eSKairui Song 				continue;
8491c2a936eSKairui Song 		}
850d7cf0d54SKairui Song 		folio = swap_cache_alloc_folio(entry, gfp_mask, mpol, ilx,
851de85024bSKairui Song 					       &page_allocated);
8521c2a936eSKairui Song 		if (si)
8531c2a936eSKairui Song 			put_swap_device(si);
85496c7b0b4SMatthew Wilcox (Oracle) 		if (!folio)
855ec560175SHuang Ying 			continue;
856ec560175SHuang Ying 		if (page_allocated) {
857b2d1f38bSYosry Ahmed 			swap_read_folio(folio, &splug);
858ba518f4dSHuang Ying 			if (addr != vmf->address) {
85996c7b0b4SMatthew Wilcox (Oracle) 				folio_set_readahead(folio);
860ec560175SHuang Ying 				count_vm_event(SWAP_RA);
861ec560175SHuang Ying 			}
862ec560175SHuang Ying 		}
86396c7b0b4SMatthew Wilcox (Oracle) 		folio_put(folio);
864ec560175SHuang Ying 	}
8654f8fcf4cSHugh Dickins 	if (pte)
8664f8fcf4cSHugh Dickins 		pte_unmap(pte);
867ec560175SHuang Ying 	blk_finish_plug(&plug);
8685169b844SNeilBrown 	swap_read_unplug(splug);
869ec560175SHuang Ying 	lru_add_drain();
870ec560175SHuang Ying skip:
87196c7b0b4SMatthew Wilcox (Oracle) 	/* The folio was likely read above, so no need for plugging here */
872d7cf0d54SKairui Song 	folio = swap_cache_alloc_folio(targ_entry, gfp_mask, mpol, targ_ilx,
873de85024bSKairui Song 				       &page_allocated);
8740e400844SNhat Pham 	if (unlikely(page_allocated))
875b2d1f38bSYosry Ahmed 		swap_read_folio(folio, NULL);
876a4575c41SMatthew Wilcox (Oracle) 	return folio;
877ec560175SHuang Ying }
878d9bfcfdcSHuang Ying 
879e9e9b7ecSMinchan Kim /**
880e9e9b7ecSMinchan Kim  * swapin_readahead - swap in pages in hope we need them soon
881e9e9b7ecSMinchan Kim  * @entry: swap entry of this memory
882e9e9b7ecSMinchan Kim  * @gfp_mask: memory allocation flags
883e9e9b7ecSMinchan Kim  * @vmf: fault information
884e9e9b7ecSMinchan Kim  *
88594dc8bffSMatthew Wilcox (Oracle)  * Returns the struct folio for entry and addr, after queueing swapin.
886e9e9b7ecSMinchan Kim  *
887e9e9b7ecSMinchan Kim  * It's a main entry function for swap readahead. By the configuration,
888e9e9b7ecSMinchan Kim  * it will read ahead blocks by cluster-based(ie, physical disk based)
889e9e9b7ecSMinchan Kim  * or vma-based(ie, virtual address based on faulty address) readahead.
890e9e9b7ecSMinchan Kim  */
swapin_readahead(swp_entry_t entry,gfp_t gfp_mask,struct vm_fault * vmf)89194dc8bffSMatthew Wilcox (Oracle) struct folio *swapin_readahead(swp_entry_t entry, gfp_t gfp_mask,
892e9e9b7ecSMinchan Kim 				struct vm_fault *vmf)
893e9e9b7ecSMinchan Kim {
894ddc1a5cbSHugh Dickins 	struct mempolicy *mpol;
895ddc1a5cbSHugh Dickins 	pgoff_t ilx;
896a4575c41SMatthew Wilcox (Oracle) 	struct folio *folio;
897ddc1a5cbSHugh Dickins 
898ddc1a5cbSHugh Dickins 	mpol = get_vma_policy(vmf->vma, vmf->address, 0, &ilx);
899a4575c41SMatthew Wilcox (Oracle) 	folio = swap_use_vma_readahead() ?
900ddc1a5cbSHugh Dickins 		swap_vma_readahead(entry, gfp_mask, mpol, ilx, vmf) :
901ddc1a5cbSHugh Dickins 		swap_cluster_readahead(entry, gfp_mask, mpol, ilx);
902ddc1a5cbSHugh Dickins 	mpol_cond_put(mpol);
903a4575c41SMatthew Wilcox (Oracle) 
90494dc8bffSMatthew Wilcox (Oracle) 	return folio;
905e9e9b7ecSMinchan Kim }
906e9e9b7ecSMinchan Kim 
907d9bfcfdcSHuang Ying #ifdef CONFIG_SYSFS
vma_ra_enabled_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)908d9bfcfdcSHuang Ying static ssize_t vma_ra_enabled_show(struct kobject *kobj,
909d9bfcfdcSHuang Ying 				     struct kobj_attribute *attr, char *buf)
910d9bfcfdcSHuang Ying {
911d3ea85c6SThorsten Blum 	return sysfs_emit(buf, "%s\n", str_true_false(enable_vma_readahead));
912d9bfcfdcSHuang Ying }
vma_ra_enabled_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)913d9bfcfdcSHuang Ying static ssize_t vma_ra_enabled_store(struct kobject *kobj,
914d9bfcfdcSHuang Ying 				      struct kobj_attribute *attr,
915d9bfcfdcSHuang Ying 				      const char *buf, size_t count)
916d9bfcfdcSHuang Ying {
917717aeab4SJagdish Gediya 	ssize_t ret;
918717aeab4SJagdish Gediya 
919717aeab4SJagdish Gediya 	ret = kstrtobool(buf, &enable_vma_readahead);
920717aeab4SJagdish Gediya 	if (ret)
921717aeab4SJagdish Gediya 		return ret;
922d9bfcfdcSHuang Ying 
923d9bfcfdcSHuang Ying 	return count;
924d9bfcfdcSHuang Ying }
9256106b93eSMiaohe Lin static struct kobj_attribute vma_ra_enabled_attr = __ATTR_RW(vma_ra_enabled);
926d9bfcfdcSHuang Ying 
927d9bfcfdcSHuang Ying static struct attribute *swap_attrs[] = {
928d9bfcfdcSHuang Ying 	&vma_ra_enabled_attr.attr,
929d9bfcfdcSHuang Ying 	NULL,
930d9bfcfdcSHuang Ying };
931d9bfcfdcSHuang Ying 
932e48333b6SRikard Falkeborn static const struct attribute_group swap_attr_group = {
933d9bfcfdcSHuang Ying 	.attrs = swap_attrs,
934d9bfcfdcSHuang Ying };
935d9bfcfdcSHuang Ying 
swap_init(void)9368578e0c0SKairui Song static int __init swap_init(void)
937d9bfcfdcSHuang Ying {
938d9bfcfdcSHuang Ying 	int err;
939d9bfcfdcSHuang Ying 	struct kobject *swap_kobj;
940d9bfcfdcSHuang Ying 
941d9bfcfdcSHuang Ying 	swap_kobj = kobject_create_and_add("swap", mm_kobj);
942d9bfcfdcSHuang Ying 	if (!swap_kobj) {
943d9bfcfdcSHuang Ying 		pr_err("failed to create swap kobject\n");
944d9bfcfdcSHuang Ying 		return -ENOMEM;
945d9bfcfdcSHuang Ying 	}
946d9bfcfdcSHuang Ying 	err = sysfs_create_group(swap_kobj, &swap_attr_group);
947d9bfcfdcSHuang Ying 	if (err) {
948d9bfcfdcSHuang Ying 		pr_err("failed to register swap group\n");
949d9bfcfdcSHuang Ying 		goto delete_obj;
950d9bfcfdcSHuang Ying 	}
9518578e0c0SKairui Song 	/* Swap cache writeback is LRU based, no tags for it */
9528578e0c0SKairui Song 	mapping_set_no_writeback_tags(&swap_space);
953d9bfcfdcSHuang Ying 	return 0;
954d9bfcfdcSHuang Ying 
955d9bfcfdcSHuang Ying delete_obj:
956d9bfcfdcSHuang Ying 	kobject_put(swap_kobj);
957d9bfcfdcSHuang Ying 	return err;
958d9bfcfdcSHuang Ying }
9598578e0c0SKairui Song subsys_initcall(swap_init);
960d9bfcfdcSHuang Ying #endif
961