xref: /linux/mm/swap_state.c (revision f4e98954234b104c23902ee5bb4e59be6f9904a7)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *  linux/mm/swap_state.c
4  *
5  *  Copyright (C) 1991, 1992, 1993, 1994  Linus Torvalds
6  *  Swap reorganised 29.12.95, Stephen Tweedie
7  *
8  *  Rewritten to use page cache, (C) 1998 Stephen Tweedie
9  */
10 #include <linux/mm.h>
11 #include <linux/gfp.h>
12 #include <linux/kernel_stat.h>
13 #include <linux/mempolicy.h>
14 #include <linux/swap.h>
15 #include <linux/leafops.h>
16 #include <linux/init.h>
17 #include <linux/pagemap.h>
18 #include <linux/folio_batch.h>
19 #include <linux/backing-dev.h>
20 #include <linux/blkdev.h>
21 #include <linux/migrate.h>
22 #include <linux/vmalloc.h>
23 #include <linux/huge_mm.h>
24 #include <linux/shmem_fs.h>
25 #include "internal.h"
26 #include "swap_table.h"
27 #include "swap.h"
28 
29 /*
30  * swapper_space is a fiction, retained to simplify the path through
31  * vmscan's shrink_folio_list.
32  */
33 static const struct address_space_operations swap_aops = {
34 	.dirty_folio	= noop_dirty_folio,
35 #ifdef CONFIG_MIGRATION
36 	.migrate_folio	= migrate_folio,
37 #endif
38 };
39 
40 struct address_space swap_space __read_mostly = {
41 	.a_ops = &swap_aops,
42 };
43 
44 static bool enable_vma_readahead __read_mostly = true;
45 
46 #define SWAP_RA_ORDER_CEILING	5
47 
48 #define SWAP_RA_WIN_SHIFT	(PAGE_SHIFT / 2)
49 #define SWAP_RA_HITS_MASK	((1UL << SWAP_RA_WIN_SHIFT) - 1)
50 #define SWAP_RA_HITS_MAX	SWAP_RA_HITS_MASK
51 #define SWAP_RA_WIN_MASK	(~PAGE_MASK & ~SWAP_RA_HITS_MASK)
52 
53 #define SWAP_RA_HITS(v)		((v) & SWAP_RA_HITS_MASK)
54 #define SWAP_RA_WIN(v)		(((v) & SWAP_RA_WIN_MASK) >> SWAP_RA_WIN_SHIFT)
55 #define SWAP_RA_ADDR(v)		((v) & PAGE_MASK)
56 
57 #define SWAP_RA_VAL(addr, win, hits)				\
58 	(((addr) & PAGE_MASK) |					\
59 	 (((win) << SWAP_RA_WIN_SHIFT) & SWAP_RA_WIN_MASK) |	\
60 	 ((hits) & SWAP_RA_HITS_MASK))
61 
62 /* Initial readahead hits is 4 to start up with a small window */
63 #define GET_SWAP_RA_VAL(vma)					\
64 	(atomic_long_read(&(vma)->swap_readahead_info) ? : 4)
65 
66 static atomic_t swapin_readahead_hits = ATOMIC_INIT(4);
67 
68 void show_swap_cache_info(void)
69 {
70 	printk("%lu pages in swap cache\n", total_swapcache_pages());
71 	printk("Free swap  = %ldkB\n", K(get_nr_swap_pages()));
72 	printk("Total swap = %lukB\n", K(total_swap_pages));
73 }
74 
75 /**
76  * swap_cache_get_folio - Looks up a folio in the swap cache.
77  * @entry: swap entry used for the lookup.
78  *
79  * A found folio will be returned unlocked and with its refcount increased.
80  *
81  * Context: Caller must ensure @entry is valid and protect the swap device
82  * with reference count or locks.
83  * Return: Returns the found folio on success, NULL otherwise. The caller
84  * must lock and check if the folio still matches the swap entry before
85  * use (e.g., folio_matches_swap_entry).
86  */
87 struct folio *swap_cache_get_folio(swp_entry_t entry)
88 {
89 	unsigned long swp_tb;
90 	struct folio *folio;
91 
92 	for (;;) {
93 		swp_tb = swap_table_get(__swap_entry_to_cluster(entry),
94 					swp_cluster_offset(entry));
95 		if (!swp_tb_is_folio(swp_tb))
96 			return NULL;
97 		folio = swp_tb_to_folio(swp_tb);
98 		if (likely(folio_try_get(folio)))
99 			return folio;
100 	}
101 
102 	return NULL;
103 }
104 
105 /**
106  * swap_cache_has_folio - Check if a swap slot has cache.
107  * @entry: swap entry indicating the slot.
108  *
109  * Context: Caller must ensure @entry is valid and protect the swap
110  * device with reference count or locks.
111  */
112 bool swap_cache_has_folio(swp_entry_t entry)
113 {
114 	unsigned long swp_tb;
115 
116 	swp_tb = swap_table_get(__swap_entry_to_cluster(entry),
117 				swp_cluster_offset(entry));
118 	return swp_tb_is_folio(swp_tb);
119 }
120 
121 /**
122  * swap_cache_get_shadow - Looks up a shadow in the swap cache.
123  * @entry: swap entry used for the lookup.
124  *
125  * Context: Caller must ensure @entry is valid and protect the swap device
126  * with reference count or locks.
127  * Return: Returns either NULL or an XA_VALUE (shadow).
128  */
129 void *swap_cache_get_shadow(swp_entry_t entry)
130 {
131 	unsigned long swp_tb;
132 
133 	swp_tb = swap_table_get(__swap_entry_to_cluster(entry),
134 				swp_cluster_offset(entry));
135 	if (swp_tb_is_shadow(swp_tb))
136 		return swp_tb_to_shadow(swp_tb);
137 	return NULL;
138 }
139 
140 /**
141  * __swap_cache_add_check - Check if a range is suitable for adding a folio.
142  * @ci: The locked swap cluster
143  * @targ_entry: The target swap entry to check, will be rounded down by @nr
144  * @nr: Number of slots to check, must be a power of 2
145  * @shadowp: Returns the shadow value if one exists in the range
146  * @memcg_id: Returns the memory cgroup id, NULL to ignore cgroup check
147  *
148  * Check if all slots covered by given range have a swap count >= 1.
149  * Retrieves the shadow if there is one. If @memcg_id is not NULL, also
150  * checks if all slots belong to the same cgroup and return the cgroup
151  * private id.
152  *
153  * Context: Caller must lock the cluster.
154  * Return: 0 if success, error code if failed.
155  */
156 static int __swap_cache_add_check(struct swap_cluster_info *ci,
157 				  swp_entry_t targ_entry,
158 				  unsigned long nr, void **shadowp,
159 				  unsigned short *memcg_id)
160 {
161 	unsigned int ci_off, ci_end;
162 	unsigned long old_tb;
163 	bool is_zero;
164 
165 	lockdep_assert_held(&ci->lock);
166 
167 	/*
168 	 * If the target slot is not swapped out or already cached, return
169 	 * -ENOENT or -EEXIST. If the batch is not suitable, could be a
170 	 * race with concurrent free or cache add, return -EBUSY.
171 	 */
172 	if (unlikely(!ci->table))
173 		return -ENOENT;
174 	ci_off = swp_cluster_offset(targ_entry);
175 	old_tb = __swap_table_get(ci, ci_off);
176 	if (swp_tb_is_folio(old_tb))
177 		return -EEXIST;
178 	if (!__swp_tb_get_count(old_tb))
179 		return -ENOENT;
180 	if (shadowp && swp_tb_is_shadow(old_tb))
181 		*shadowp = swp_tb_to_shadow(old_tb);
182 	if (memcg_id)
183 		*memcg_id = __swap_cgroup_get(ci, ci_off);
184 
185 	if (nr == 1)
186 		return 0;
187 
188 	is_zero = __swap_table_test_zero(ci, ci_off);
189 	ci_off = round_down(ci_off, nr);
190 	ci_end = ci_off + nr;
191 	do {
192 		old_tb = __swap_table_get(ci, ci_off);
193 		if (unlikely(swp_tb_is_folio(old_tb) ||
194 			     !__swp_tb_get_count(old_tb) ||
195 			     is_zero != __swap_table_test_zero(ci, ci_off) ||
196 			     (memcg_id && *memcg_id != __swap_cgroup_get(ci, ci_off))))
197 			return -EBUSY;
198 	} while (++ci_off < ci_end);
199 
200 	return 0;
201 }
202 
203 static void __swap_cache_do_add_folio(struct swap_cluster_info *ci,
204 				      struct folio *folio, swp_entry_t entry)
205 {
206 	unsigned int ci_off = swp_cluster_offset(entry), ci_end;
207 	unsigned long nr_pages = folio_nr_pages(folio);
208 	unsigned long pfn = folio_pfn(folio);
209 	unsigned long old_tb;
210 
211 	VM_WARN_ON_ONCE_FOLIO(!folio_test_locked(folio), folio);
212 	VM_WARN_ON_ONCE_FOLIO(folio_test_swapcache(folio), folio);
213 	VM_WARN_ON_ONCE_FOLIO(!folio_test_swapbacked(folio), folio);
214 
215 	ci_end = ci_off + nr_pages;
216 	do {
217 		old_tb = __swap_table_get(ci, ci_off);
218 		VM_WARN_ON_ONCE(swp_tb_is_folio(old_tb));
219 		__swap_table_set(ci, ci_off, pfn_to_swp_tb(pfn, __swp_tb_get_flags(old_tb)));
220 	} while (++ci_off < ci_end);
221 
222 	folio_ref_add(folio, nr_pages);
223 	folio_set_swapcache(folio);
224 	folio->swap = entry;
225 }
226 
227 /**
228  * __swap_cache_add_folio - Add a folio to the swap cache and update stats.
229  * @ci: The locked swap cluster.
230  * @folio: The folio to be added.
231  * @entry: The swap entry corresponding to the folio.
232  *
233  * Unconditionally add a folio to the swap cache. The caller must ensure
234  * all slots are usable and have no conflicts. This assigns entry to
235  * @folio->swap, increases folio refcount by the number of pages, and
236  * updates swap cache stats.
237  *
238  * Context: Caller must ensure the folio is locked and lock the cluster
239  * that holds the entries.
240  */
241 void __swap_cache_add_folio(struct swap_cluster_info *ci,
242 			    struct folio *folio, swp_entry_t entry)
243 {
244 	unsigned long nr_pages = folio_nr_pages(folio);
245 
246 	__swap_cache_do_add_folio(ci, folio, entry);
247 	node_stat_mod_folio(folio, NR_FILE_PAGES, nr_pages);
248 	lruvec_stat_mod_folio(folio, NR_SWAPCACHE, nr_pages);
249 }
250 
251 static void __swap_cache_do_del_folio(struct swap_cluster_info *ci,
252 				      struct folio *folio,
253 				      swp_entry_t entry, void *shadow)
254 {
255 	unsigned long old_tb;
256 	struct swap_info_struct *si;
257 	unsigned int ci_start, ci_off, ci_end;
258 	bool folio_swapped = false, need_free = false;
259 	unsigned long nr_pages = folio_nr_pages(folio);
260 
261 	VM_WARN_ON_ONCE(__swap_entry_to_cluster(entry) != ci);
262 	VM_WARN_ON_ONCE_FOLIO(!folio_test_locked(folio), folio);
263 	VM_WARN_ON_ONCE_FOLIO(!folio_test_swapcache(folio), folio);
264 	VM_WARN_ON_ONCE_FOLIO(folio_test_writeback(folio), folio);
265 
266 	si = __swap_entry_to_info(entry);
267 	ci_start = swp_cluster_offset(entry);
268 	ci_end = ci_start + nr_pages;
269 	ci_off = ci_start;
270 	do {
271 		old_tb = __swap_table_get(ci, ci_off);
272 		WARN_ON_ONCE(!swp_tb_is_folio(old_tb) ||
273 			     swp_tb_to_folio(old_tb) != folio);
274 		if (__swp_tb_get_count(old_tb))
275 			folio_swapped = true;
276 		else
277 			need_free = true;
278 		/* If shadow is NULL, we set an empty shadow. */
279 		__swap_table_set(ci, ci_off, shadow_to_swp_tb(shadow,
280 				 __swp_tb_get_flags(old_tb)));
281 	} while (++ci_off < ci_end);
282 
283 	folio->swap.val = 0;
284 	folio_clear_swapcache(folio);
285 
286 	if (!folio_swapped) {
287 		__swap_cluster_free_entries(si, ci, ci_start, nr_pages);
288 	} else if (need_free) {
289 		ci_off = ci_start;
290 		do {
291 			if (!__swp_tb_get_count(__swap_table_get(ci, ci_off)))
292 				__swap_cluster_free_entries(si, ci, ci_off, 1);
293 		} while (++ci_off < ci_end);
294 	}
295 }
296 
297 /**
298  * __swap_cache_del_folio - Removes a folio from the swap cache.
299  * @ci: The locked swap cluster.
300  * @folio: The folio.
301  * @entry: The first swap entry that the folio corresponds to.
302  * @shadow: shadow value to be filled in the swap cache.
303  *
304  * Removes a folio from the swap cache and fills a shadow in place.
305  * This won't put the folio's refcount. The caller has to do that.
306  *
307  * Context: Caller must ensure the folio is locked and in the swap cache
308  * using the index of @entry, and lock the cluster that holds the entries.
309  */
310 void __swap_cache_del_folio(struct swap_cluster_info *ci, struct folio *folio,
311 			    swp_entry_t entry, void *shadow)
312 {
313 	unsigned long nr_pages = folio_nr_pages(folio);
314 
315 	__swap_cache_do_del_folio(ci, folio, entry, shadow);
316 	node_stat_mod_folio(folio, NR_FILE_PAGES, -nr_pages);
317 	lruvec_stat_mod_folio(folio, NR_SWAPCACHE, -nr_pages);
318 }
319 
320 /**
321  * swap_cache_del_folio - Removes a folio from the swap cache.
322  * @folio: The folio.
323  *
324  * Same as __swap_cache_del_folio, but handles lock and refcount. The
325  * caller must ensure the folio is either clean or has a swap count
326  * equal to zero, or it may cause data loss.
327  *
328  * Context: Caller must ensure the folio is locked and in the swap cache.
329  */
330 void swap_cache_del_folio(struct folio *folio)
331 {
332 	struct swap_cluster_info *ci;
333 	swp_entry_t entry = folio->swap;
334 
335 	ci = swap_cluster_lock(__swap_entry_to_info(entry), swp_offset(entry));
336 	__swap_cache_del_folio(ci, folio, entry, NULL);
337 	swap_cluster_unlock(ci);
338 
339 	folio_ref_sub(folio, folio_nr_pages(folio));
340 }
341 
342 /**
343  * __swap_cache_replace_folio - Replace a folio in the swap cache.
344  * @ci: The locked swap cluster.
345  * @old: The old folio to be replaced.
346  * @new: The new folio.
347  *
348  * Replace an existing folio in the swap cache with a new folio. The
349  * caller is responsible for setting up the new folio's flag and swap
350  * entries. Replacement will take the new folio's swap entry value as
351  * the starting offset to override all slots covered by the new folio.
352  *
353  * Context: Caller must ensure both folios are locked, and lock the
354  * cluster that holds the old folio to be replaced.
355  */
356 void __swap_cache_replace_folio(struct swap_cluster_info *ci,
357 				struct folio *old, struct folio *new)
358 {
359 	swp_entry_t entry = new->swap;
360 	unsigned long nr_pages = folio_nr_pages(new);
361 	unsigned int ci_off = swp_cluster_offset(entry);
362 	unsigned int ci_end = ci_off + nr_pages;
363 	unsigned long pfn = folio_pfn(new);
364 	unsigned long old_tb;
365 
366 	VM_WARN_ON_ONCE(!folio_test_swapcache(old) || !folio_test_swapcache(new));
367 	VM_WARN_ON_ONCE(!folio_test_locked(old) || !folio_test_locked(new));
368 	VM_WARN_ON_ONCE(!entry.val);
369 
370 	/* Swap cache still stores N entries instead of a high-order entry */
371 	do {
372 		old_tb = __swap_table_get(ci, ci_off);
373 		WARN_ON_ONCE(!swp_tb_is_folio(old_tb) || swp_tb_to_folio(old_tb) != old);
374 		__swap_table_set(ci, ci_off, pfn_to_swp_tb(pfn, __swp_tb_get_flags(old_tb)));
375 	} while (++ci_off < ci_end);
376 
377 	/*
378 	 * If the old folio is partially replaced (e.g., splitting a large
379 	 * folio, the old folio is shrunk, and new split sub folios replace
380 	 * the shrunk part), ensure the new folio doesn't overlap it.
381 	 */
382 	if (IS_ENABLED(CONFIG_DEBUG_VM) &&
383 	    folio_order(old) != folio_order(new)) {
384 		ci_off = swp_cluster_offset(old->swap);
385 		ci_end = ci_off + folio_nr_pages(old);
386 		while (ci_off++ < ci_end)
387 			WARN_ON_ONCE(swp_tb_to_folio(__swap_table_get(ci, ci_off)) != old);
388 	}
389 }
390 
391 /*
392  * Try to allocate a folio of given order in the swap cache.
393  *
394  * This helper resolves the potential races of swap allocation
395  * and prepares a folio to be used for swap IO. May return following
396  * value:
397  *
398  * -ENOMEM / -EBUSY: Order is too large or in conflict with sub slot,
399  *                   caller should shrink the order and retry
400  * -ENOENT / -EEXIST: Target swap entry is unavailable or cached, the caller
401  *                    should abort or try to use the cached folio instead
402  */
403 static struct folio *__swap_cache_alloc(struct swap_cluster_info *ci,
404 					swp_entry_t targ_entry, gfp_t gfp,
405 					unsigned int order, struct vm_fault *vmf,
406 					struct mempolicy *mpol, pgoff_t ilx)
407 {
408 	int err;
409 	swp_entry_t entry;
410 	struct folio *folio;
411 	void *shadow = NULL;
412 	unsigned short memcg_id;
413 	unsigned long address, nr_pages = 1UL << order;
414 	struct vm_area_struct *vma = vmf ? vmf->vma : NULL;
415 
416 	VM_WARN_ON_ONCE(nr_pages > SWAPFILE_CLUSTER);
417 	entry.val = round_down(targ_entry.val, nr_pages);
418 
419 	/* Check if the slot and range are available, skip allocation if not */
420 	spin_lock(&ci->lock);
421 	err = __swap_cache_add_check(ci, targ_entry, nr_pages, NULL, NULL);
422 	spin_unlock(&ci->lock);
423 	if (unlikely(err))
424 		return ERR_PTR(err);
425 
426 	/*
427 	 * Limit THP gfp. The limitation is a no-op for typical
428 	 * GFP_HIGHUSER_MOVABLE but matters for shmem.
429 	 */
430 	if (order)
431 		gfp = thp_shmem_limit_gfp_mask(vma_thp_gfp_mask(vma), gfp);
432 
433 	if (mpol || !vmf) {
434 		folio = folio_alloc_mpol(gfp, order, mpol, ilx, numa_node_id());
435 	} else {
436 		address = round_down(vmf->address, PAGE_SIZE << order);
437 		folio = vma_alloc_folio(gfp, order, vmf->vma, address);
438 	}
439 	if (unlikely(!folio))
440 		return ERR_PTR(-ENOMEM);
441 
442 	/* Double check the range is still not in conflict */
443 	spin_lock(&ci->lock);
444 	err = __swap_cache_add_check(ci, targ_entry, nr_pages, &shadow, &memcg_id);
445 	if (unlikely(err)) {
446 		spin_unlock(&ci->lock);
447 		folio_put(folio);
448 		return ERR_PTR(err);
449 	}
450 
451 	__folio_set_locked(folio);
452 	__folio_set_swapbacked(folio);
453 	__swap_cache_do_add_folio(ci, folio, entry);
454 	spin_unlock(&ci->lock);
455 
456 	if (mem_cgroup_swapin_charge_folio(folio, memcg_id,
457 					   vmf ? vmf->vma->vm_mm : NULL, gfp)) {
458 		spin_lock(&ci->lock);
459 		__swap_cache_do_del_folio(ci, folio, entry, shadow);
460 		spin_unlock(&ci->lock);
461 		folio_unlock(folio);
462 		/* nr_pages refs from swap cache, 1 from allocation */
463 		folio_put_refs(folio, nr_pages + 1);
464 		count_mthp_stat(order, MTHP_STAT_SWPIN_FALLBACK_CHARGE);
465 		return ERR_PTR(-ENOMEM);
466 	}
467 
468 	/* memsw uncharges swap when folio is added to swap cache */
469 	memcg1_swapin(folio);
470 	if (shadow)
471 		workingset_refault(folio, shadow);
472 
473 	node_stat_mod_folio(folio, NR_FILE_PAGES, nr_pages);
474 	lruvec_stat_mod_folio(folio, NR_SWAPCACHE, nr_pages);
475 
476 	/* Caller will initiate read into locked new_folio */
477 	folio_add_lru(folio);
478 	return folio;
479 }
480 
481 /**
482  * swap_cache_alloc_folio - Allocate folio for swapped out slot in swap cache.
483  * @targ_entry: swap entry indicating the target slot
484  * @gfp: memory allocation flags
485  * @orders: allocation orders, must be non zero
486  * @vmf: fault information
487  * @mpol: NUMA memory allocation policy to be applied
488  * @ilx: NUMA interleave index, for use only when MPOL_INTERLEAVE
489  *
490  * Allocate a folio in the swap cache for one swap slot, typically before
491  * doing IO (e.g. swap in or zswap writeback). The swap slot indicated by
492  * @targ_entry must have a non-zero swap count (swapped out).
493  *
494  * Context: Caller must protect the swap device with reference count or locks.
495  * Return: Returns the folio if allocation succeeded and folio is in the swap
496  * cache. Returns error code if failed due to race, OOM or invalid arguments.
497  */
498 struct folio *swap_cache_alloc_folio(swp_entry_t targ_entry, gfp_t gfp,
499 				     unsigned long orders, struct vm_fault *vmf,
500 				     struct mempolicy *mpol, pgoff_t ilx)
501 {
502 	int order, err;
503 	struct folio *ret;
504 	struct swap_cluster_info *ci;
505 
506 	ci = __swap_entry_to_cluster(targ_entry);
507 	order = highest_order(orders);
508 
509 	/* orders must be non-zero, and must not exceed cluster size. */
510 	if (WARN_ON_ONCE(!orders || (1UL << order) > SWAPFILE_CLUSTER))
511 		return ERR_PTR(-EINVAL);
512 
513 	do {
514 		ret = __swap_cache_alloc(ci, targ_entry, gfp, order,
515 					 vmf, mpol, ilx);
516 		if (!IS_ERR(ret))
517 			break;
518 		err = PTR_ERR(ret);
519 		if (!order || (err && err != -EBUSY && err != -ENOMEM))
520 			break;
521 		count_mthp_stat(order, MTHP_STAT_SWPIN_FALLBACK);
522 		order = next_order(&orders, order);
523 	} while (orders);
524 
525 	return ret;
526 }
527 
528 /*
529  * If we are the only user, then try to free up the swap cache.
530  *
531  * Its ok to check the swapcache flag without the folio lock
532  * here because we are going to recheck again inside
533  * folio_free_swap() _with_ the lock.
534  * 					- Marcelo
535  */
536 void free_swap_cache(struct folio *folio)
537 {
538 	if (folio_test_swapcache(folio) && !folio_mapped(folio) &&
539 	    folio_trylock(folio)) {
540 		folio_free_swap(folio);
541 		folio_unlock(folio);
542 	}
543 }
544 
545 /*
546  * Freeing a folio and also freeing any swap cache associated with
547  * this folio if it is the last user.
548  */
549 void free_folio_and_swap_cache(struct folio *folio)
550 {
551 	free_swap_cache(folio);
552 	if (!is_huge_zero_folio(folio))
553 		folio_put(folio);
554 }
555 
556 /*
557  * Passed an array of pages, drop them all from swapcache and then release
558  * them.  They are removed from the LRU and freed if this is their last use.
559  */
560 void free_pages_and_swap_cache(struct encoded_page **pages, int nr)
561 {
562 	struct folio_batch folios;
563 	unsigned int refs[FOLIO_BATCH_SIZE];
564 
565 	folio_batch_init(&folios);
566 	for (int i = 0; i < nr; i++) {
567 		struct folio *folio = page_folio(encoded_page_ptr(pages[i]));
568 
569 		free_swap_cache(folio);
570 		refs[folios.nr] = 1;
571 		if (unlikely(encoded_page_flags(pages[i]) &
572 			     ENCODED_PAGE_BIT_NR_PAGES_NEXT))
573 			refs[folios.nr] = encoded_nr_pages(pages[++i]);
574 
575 		if (folio_batch_add(&folios, folio) == 0)
576 			folios_put_refs(&folios, refs);
577 	}
578 	if (folios.nr)
579 		folios_put_refs(&folios, refs);
580 }
581 
582 static inline bool swap_use_vma_readahead(void)
583 {
584 	return READ_ONCE(enable_vma_readahead) && !atomic_read(&nr_rotate_swap);
585 }
586 
587 /**
588  * swap_update_readahead - Update the readahead statistics of VMA or globally.
589  * @folio: the swap cache folio that just got hit.
590  * @vma: the VMA that should be updated, could be NULL for global update.
591  * @addr: the addr that triggered the swapin, ignored if @vma is NULL.
592  */
593 void swap_update_readahead(struct folio *folio, struct vm_area_struct *vma,
594 			   unsigned long addr)
595 {
596 	bool readahead, vma_ra = swap_use_vma_readahead();
597 
598 	/*
599 	 * At the moment, we don't support PG_readahead for anon THP
600 	 * so let's bail out rather than confusing the readahead stat.
601 	 */
602 	if (unlikely(folio_test_large(folio)))
603 		return;
604 
605 	readahead = folio_test_clear_readahead(folio);
606 	if (vma && vma_ra) {
607 		unsigned long ra_val;
608 		int win, hits;
609 
610 		ra_val = GET_SWAP_RA_VAL(vma);
611 		win = SWAP_RA_WIN(ra_val);
612 		hits = SWAP_RA_HITS(ra_val);
613 		if (readahead)
614 			hits = min_t(int, hits + 1, SWAP_RA_HITS_MAX);
615 		atomic_long_set(&vma->swap_readahead_info,
616 				SWAP_RA_VAL(addr, win, hits));
617 	}
618 
619 	if (readahead) {
620 		count_vm_event(SWAP_RA_HIT);
621 		if (!vma || !vma_ra)
622 			atomic_inc(&swapin_readahead_hits);
623 	}
624 }
625 
626 static struct folio *swap_cache_read_folio(swp_entry_t entry, gfp_t gfp,
627 					   struct mempolicy *mpol, pgoff_t ilx,
628 					   struct swap_iocb **plug, bool readahead)
629 {
630 	struct folio *folio;
631 
632 	do {
633 		folio = swap_cache_get_folio(entry);
634 		if (folio)
635 			return folio;
636 		folio = swap_cache_alloc_folio(entry, gfp, BIT(0), NULL, mpol, ilx);
637 	} while (PTR_ERR(folio) == -EEXIST);
638 
639 	if (IS_ERR_OR_NULL(folio))
640 		return NULL;
641 
642 	swap_read_folio(folio, plug);
643 	if (readahead) {
644 		folio_set_readahead(folio);
645 		count_vm_event(SWAP_RA);
646 	}
647 
648 	return folio;
649 }
650 
651 /**
652  * swapin_sync - swap-in one or multiple entries skipping readahead.
653  * @entry: swap entry indicating the target slot
654  * @gfp: memory allocation flags
655  * @orders: allocation orders
656  * @vmf: fault information
657  * @mpol: NUMA memory allocation policy to be applied
658  * @ilx: NUMA interleave index, for use only when MPOL_INTERLEAVE
659  *
660  * This allocates a folio suitable for given @orders, or returns the
661  * existing folio in the swap cache for @entry. This initiates the IO, too,
662  * if needed. @entry is rounded down if @orders allow large allocation.
663  *
664  * Context: Caller must ensure @entry is valid and pin the swap device with refcount.
665  * Return: Returns the folio on success, error code if failed.
666  */
667 struct folio *swapin_sync(swp_entry_t entry, gfp_t gfp, unsigned long orders,
668 			   struct vm_fault *vmf, struct mempolicy *mpol, pgoff_t ilx)
669 {
670 	struct folio *folio;
671 
672 	do {
673 		folio = swap_cache_get_folio(entry);
674 		if (folio)
675 			return folio;
676 		folio = swap_cache_alloc_folio(entry, gfp, orders, vmf, mpol, ilx);
677 	} while (PTR_ERR(folio) == -EEXIST);
678 
679 	if (IS_ERR(folio))
680 		return folio;
681 
682 	swap_read_folio(folio, NULL);
683 	return folio;
684 }
685 
686 /*
687  * Locate a page of swap in physical memory, reserving swap cache space
688  * and reading the disk if it is not already cached.
689  * A failure return means that either the page allocation failed or that
690  * the swap entry is no longer in use.
691  */
692 struct folio *read_swap_cache_async(swp_entry_t entry, gfp_t gfp_mask,
693 		struct vm_area_struct *vma, unsigned long addr,
694 		struct swap_iocb **plug)
695 {
696 	struct swap_info_struct *si;
697 	struct mempolicy *mpol;
698 	pgoff_t ilx;
699 	struct folio *folio;
700 
701 	si = get_swap_device(entry);
702 	if (!si)
703 		return NULL;
704 
705 	mpol = get_vma_policy(vma, addr, 0, &ilx);
706 	folio = swap_cache_read_folio(entry, gfp_mask, mpol, ilx, plug, false);
707 	mpol_cond_put(mpol);
708 
709 	put_swap_device(si);
710 	return folio;
711 }
712 
713 static unsigned int __swapin_nr_pages(unsigned long prev_offset,
714 				      unsigned long offset,
715 				      int hits,
716 				      int max_pages,
717 				      int prev_win)
718 {
719 	unsigned int pages, last_ra;
720 
721 	/*
722 	 * This heuristic has been found to work well on both sequential and
723 	 * random loads, swapping to hard disk or to SSD: please don't ask
724 	 * what the "+ 2" means, it just happens to work well, that's all.
725 	 */
726 	pages = hits + 2;
727 	if (pages == 2) {
728 		/*
729 		 * We can have no readahead hits to judge by: but must not get
730 		 * stuck here forever, so check for an adjacent offset instead
731 		 * (and don't even bother to check whether swap type is same).
732 		 */
733 		if (offset != prev_offset + 1 && offset != prev_offset - 1)
734 			pages = 1;
735 	} else {
736 		unsigned int roundup = 4;
737 		while (roundup < pages)
738 			roundup <<= 1;
739 		pages = roundup;
740 	}
741 
742 	if (pages > max_pages)
743 		pages = max_pages;
744 
745 	/* Don't shrink readahead too fast */
746 	last_ra = prev_win / 2;
747 	if (pages < last_ra)
748 		pages = last_ra;
749 
750 	return pages;
751 }
752 
753 static unsigned long swapin_nr_pages(unsigned long offset)
754 {
755 	static unsigned long prev_offset;
756 	unsigned int hits, pages, max_pages;
757 	static atomic_t last_readahead_pages;
758 
759 	max_pages = 1 << READ_ONCE(page_cluster);
760 	if (max_pages <= 1)
761 		return 1;
762 
763 	hits = atomic_xchg(&swapin_readahead_hits, 0);
764 	pages = __swapin_nr_pages(READ_ONCE(prev_offset), offset, hits,
765 				  max_pages,
766 				  atomic_read(&last_readahead_pages));
767 	if (!hits)
768 		WRITE_ONCE(prev_offset, offset);
769 	atomic_set(&last_readahead_pages, pages);
770 
771 	return pages;
772 }
773 
774 /**
775  * swap_cluster_readahead - swap in pages in hope we need them soon
776  * @entry: swap entry of this memory
777  * @gfp_mask: memory allocation flags
778  * @mpol: NUMA memory allocation policy to be applied
779  * @ilx: NUMA interleave index, for use only when MPOL_INTERLEAVE
780  *
781  * Returns the struct folio for entry and addr, after queueing swapin.
782  *
783  * Primitive swap readahead code. We simply read an aligned block of
784  * (1 << page_cluster) entries in the swap area. This method is chosen
785  * because it doesn't cost us any seek time.  We also make sure to queue
786  * the 'original' request together with the readahead ones...
787  *
788  * Note: it is intentional that the same NUMA policy and interleave index
789  * are used for every page of the readahead: neighbouring pages on swap
790  * are fairly likely to have been swapped out from the same node.
791  */
792 struct folio *swap_cluster_readahead(swp_entry_t entry, gfp_t gfp_mask,
793 				     struct mempolicy *mpol, pgoff_t ilx)
794 {
795 	struct folio *folio;
796 	unsigned long entry_offset = swp_offset(entry);
797 	unsigned long offset = entry_offset;
798 	unsigned long start_offset, end_offset;
799 	unsigned long mask;
800 	struct swap_info_struct *si = __swap_entry_to_info(entry);
801 	struct blk_plug plug;
802 	struct swap_iocb *splug = NULL;
803 	swp_entry_t ra_entry;
804 
805 	mask = swapin_nr_pages(offset) - 1;
806 	if (!mask)
807 		goto skip;
808 
809 	/* Read a page_cluster sized and aligned cluster around offset. */
810 	start_offset = offset & ~mask;
811 	end_offset = offset | mask;
812 	if (!start_offset)	/* First page is swap header. */
813 		start_offset++;
814 	if (end_offset >= si->max)
815 		end_offset = si->max - 1;
816 
817 	blk_start_plug(&plug);
818 	for (offset = start_offset; offset <= end_offset ; offset++) {
819 		/* Ok, do the async read-ahead now */
820 		ra_entry = swp_entry(swp_type(entry), offset);
821 		folio = swap_cache_read_folio(ra_entry, gfp_mask, mpol, ilx,
822 					      &splug, offset != entry_offset);
823 		if (!folio)
824 			continue;
825 		folio_put(folio);
826 	}
827 	blk_finish_plug(&plug);
828 	swap_read_unplug(splug);
829 	lru_add_drain();	/* Push any new pages onto the LRU now */
830 skip:
831 	/* The page was likely read above, so no need for plugging here */
832 	return swap_cache_read_folio(entry, gfp_mask, mpol, ilx, NULL, false);
833 }
834 
835 static int swap_vma_ra_win(struct vm_fault *vmf, unsigned long *start,
836 			   unsigned long *end)
837 {
838 	struct vm_area_struct *vma = vmf->vma;
839 	unsigned long ra_val;
840 	unsigned long faddr, prev_faddr, left, right;
841 	unsigned int max_win, hits, prev_win, win;
842 
843 	max_win = 1 << min(READ_ONCE(page_cluster), SWAP_RA_ORDER_CEILING);
844 	if (max_win == 1)
845 		return 1;
846 
847 	faddr = vmf->address;
848 	ra_val = GET_SWAP_RA_VAL(vma);
849 	prev_faddr = SWAP_RA_ADDR(ra_val);
850 	prev_win = SWAP_RA_WIN(ra_val);
851 	hits = SWAP_RA_HITS(ra_val);
852 	win = __swapin_nr_pages(PFN_DOWN(prev_faddr), PFN_DOWN(faddr), hits,
853 				max_win, prev_win);
854 	atomic_long_set(&vma->swap_readahead_info, SWAP_RA_VAL(faddr, win, 0));
855 	if (win == 1)
856 		return 1;
857 
858 	if (faddr == prev_faddr + PAGE_SIZE)
859 		left = faddr;
860 	else if (prev_faddr == faddr + PAGE_SIZE)
861 		left = faddr - (win << PAGE_SHIFT) + PAGE_SIZE;
862 	else
863 		left = faddr - (((win - 1) / 2) << PAGE_SHIFT);
864 	right = left + (win << PAGE_SHIFT);
865 	if ((long)left < 0)
866 		left = 0;
867 	*start = max3(left, vma->vm_start, faddr & PMD_MASK);
868 	*end = min3(right, vma->vm_end, (faddr & PMD_MASK) + PMD_SIZE);
869 
870 	return win;
871 }
872 
873 /**
874  * swap_vma_readahead - swap in pages in hope we need them soon
875  * @targ_entry: swap entry of the targeted memory
876  * @gfp_mask: memory allocation flags
877  * @mpol: NUMA memory allocation policy to be applied
878  * @targ_ilx: NUMA interleave index, for use only when MPOL_INTERLEAVE
879  * @vmf: fault information
880  *
881  * Returns the struct folio for entry and addr, after queueing swapin.
882  *
883  * Primitive swap readahead code. We simply read in a few pages whose
884  * virtual addresses are around the fault address in the same vma.
885  *
886  * Caller must hold read mmap_lock if vmf->vma is not NULL.
887  *
888  */
889 static struct folio *swap_vma_readahead(swp_entry_t targ_entry, gfp_t gfp_mask,
890 		struct mempolicy *mpol, pgoff_t targ_ilx, struct vm_fault *vmf)
891 {
892 	struct blk_plug plug;
893 	struct swap_iocb *splug = NULL;
894 	struct folio *folio;
895 	pte_t *pte = NULL, pentry;
896 	int win;
897 	unsigned long start, end, addr;
898 	pgoff_t ilx = targ_ilx;
899 
900 	win = swap_vma_ra_win(vmf, &start, &end);
901 	if (win == 1)
902 		goto skip;
903 
904 	ilx = targ_ilx - PFN_DOWN(vmf->address - start);
905 
906 	blk_start_plug(&plug);
907 	for (addr = start; addr < end; ilx++, addr += PAGE_SIZE) {
908 		struct swap_info_struct *si = NULL;
909 		softleaf_t entry;
910 
911 		if (!pte++) {
912 			pte = pte_offset_map(vmf->pmd, addr);
913 			if (!pte)
914 				break;
915 		}
916 		pentry = ptep_get_lockless(pte);
917 		entry = softleaf_from_pte(pentry);
918 
919 		if (!softleaf_is_swap(entry))
920 			continue;
921 		pte_unmap(pte);
922 		pte = NULL;
923 		/*
924 		 * Readahead entry may come from a device that we are not
925 		 * holding a reference to, try to grab a reference, or skip.
926 		 */
927 		if (swp_type(entry) != swp_type(targ_entry)) {
928 			si = get_swap_device(entry);
929 			if (!si)
930 				continue;
931 		}
932 		folio = swap_cache_read_folio(entry, gfp_mask, mpol, ilx,
933 					      &splug, addr != vmf->address);
934 		if (si)
935 			put_swap_device(si);
936 		if (!folio)
937 			continue;
938 		folio_put(folio);
939 	}
940 	if (pte)
941 		pte_unmap(pte);
942 	blk_finish_plug(&plug);
943 	swap_read_unplug(splug);
944 	lru_add_drain();
945 skip:
946 	/* The folio was likely read above, so no need for plugging here */
947 	folio = swap_cache_read_folio(targ_entry, gfp_mask, mpol, targ_ilx,
948 				      NULL, false);
949 	return folio;
950 }
951 
952 /**
953  * swapin_readahead - swap in pages in hope we need them soon
954  * @entry: swap entry of this memory
955  * @gfp_mask: memory allocation flags
956  * @vmf: fault information
957  *
958  * Returns the struct folio for entry and addr, after queueing swapin.
959  *
960  * It's a main entry function for swap readahead. By the configuration,
961  * it will read ahead blocks by cluster-based(ie, physical disk based)
962  * or vma-based(ie, virtual address based on faulty address) readahead.
963  */
964 struct folio *swapin_readahead(swp_entry_t entry, gfp_t gfp_mask,
965 				struct vm_fault *vmf)
966 {
967 	struct mempolicy *mpol;
968 	pgoff_t ilx;
969 	struct folio *folio;
970 
971 	mpol = get_vma_policy(vmf->vma, vmf->address, 0, &ilx);
972 	folio = swap_use_vma_readahead() ?
973 		swap_vma_readahead(entry, gfp_mask, mpol, ilx, vmf) :
974 		swap_cluster_readahead(entry, gfp_mask, mpol, ilx);
975 	mpol_cond_put(mpol);
976 
977 	return folio;
978 }
979 
980 #ifdef CONFIG_SYSFS
981 static ssize_t vma_ra_enabled_show(struct kobject *kobj,
982 				     struct kobj_attribute *attr, char *buf)
983 {
984 	return sysfs_emit(buf, "%s\n", str_true_false(enable_vma_readahead));
985 }
986 static ssize_t vma_ra_enabled_store(struct kobject *kobj,
987 				      struct kobj_attribute *attr,
988 				      const char *buf, size_t count)
989 {
990 	ssize_t ret;
991 
992 	ret = kstrtobool(buf, &enable_vma_readahead);
993 	if (ret)
994 		return ret;
995 
996 	return count;
997 }
998 static struct kobj_attribute vma_ra_enabled_attr = __ATTR_RW(vma_ra_enabled);
999 
1000 static struct attribute *swap_attrs[] = {
1001 	&vma_ra_enabled_attr.attr,
1002 	NULL,
1003 };
1004 
1005 static const struct attribute_group swap_attr_group = {
1006 	.attrs = swap_attrs,
1007 };
1008 
1009 static int __init swap_init(void)
1010 {
1011 	int err;
1012 	struct kobject *swap_kobj;
1013 
1014 	swap_kobj = kobject_create_and_add("swap", mm_kobj);
1015 	if (!swap_kobj) {
1016 		pr_err("failed to create swap kobject\n");
1017 		return -ENOMEM;
1018 	}
1019 	err = sysfs_create_group(swap_kobj, &swap_attr_group);
1020 	if (err) {
1021 		pr_err("failed to register swap group\n");
1022 		goto delete_obj;
1023 	}
1024 	/* Swap cache writeback is LRU based, no tags for it */
1025 	mapping_set_no_writeback_tags(&swap_space);
1026 	return 0;
1027 
1028 delete_obj:
1029 	kobject_put(swap_kobj);
1030 	return err;
1031 }
1032 subsys_initcall(swap_init);
1033 #endif
1034