xref: /linux/mm/swap_state.c (revision fafaeceb89a5e2e856ff04c2cacb6cae4a2ecb67)
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 	if (order > 1 && folio_memcg_alloc_deferred(folio)) {
469 		spin_lock(&ci->lock);
470 		__swap_cache_do_del_folio(ci, folio, entry, shadow);
471 		spin_unlock(&ci->lock);
472 		folio_unlock(folio);
473 		/* nr_pages refs from swap cache, 1 from allocation */
474 		folio_put_refs(folio, nr_pages + 1);
475 		return ERR_PTR(-ENOMEM);
476 	}
477 
478 	/* memsw uncharges swap when folio is added to swap cache */
479 	memcg1_swapin(folio);
480 	if (shadow)
481 		workingset_refault(folio, shadow);
482 
483 	node_stat_mod_folio(folio, NR_FILE_PAGES, nr_pages);
484 	lruvec_stat_mod_folio(folio, NR_SWAPCACHE, nr_pages);
485 
486 	/* Caller will initiate read into locked new_folio */
487 	folio_add_lru(folio);
488 	return folio;
489 }
490 
491 /**
492  * swap_cache_alloc_folio - Allocate folio for swapped out slot in swap cache.
493  * @targ_entry: swap entry indicating the target slot
494  * @gfp: memory allocation flags
495  * @orders: allocation orders, must be non zero
496  * @vmf: fault information
497  * @mpol: NUMA memory allocation policy to be applied
498  * @ilx: NUMA interleave index, for use only when MPOL_INTERLEAVE
499  *
500  * Allocate a folio in the swap cache for one swap slot, typically before
501  * doing IO (e.g. swap in or zswap writeback). The swap slot indicated by
502  * @targ_entry must have a non-zero swap count (swapped out).
503  *
504  * Context: Caller must protect the swap device with reference count or locks.
505  * Return: Returns the folio if allocation succeeded and folio is in the swap
506  * cache. Returns error code if failed due to race, OOM or invalid arguments.
507  */
508 struct folio *swap_cache_alloc_folio(swp_entry_t targ_entry, gfp_t gfp,
509 				     unsigned long orders, struct vm_fault *vmf,
510 				     struct mempolicy *mpol, pgoff_t ilx)
511 {
512 	int order, err;
513 	struct folio *ret;
514 	struct swap_cluster_info *ci;
515 
516 	ci = __swap_entry_to_cluster(targ_entry);
517 	order = highest_order(orders);
518 
519 	/* orders must be non-zero, and must not exceed cluster size. */
520 	if (WARN_ON_ONCE(!orders || (1UL << order) > SWAPFILE_CLUSTER))
521 		return ERR_PTR(-EINVAL);
522 
523 	do {
524 		ret = __swap_cache_alloc(ci, targ_entry, gfp, order,
525 					 vmf, mpol, ilx);
526 		if (!IS_ERR(ret))
527 			break;
528 		err = PTR_ERR(ret);
529 		if (!order || (err && err != -EBUSY && err != -ENOMEM))
530 			break;
531 		count_mthp_stat(order, MTHP_STAT_SWPIN_FALLBACK);
532 		order = next_order(&orders, order);
533 	} while (orders);
534 
535 	return ret;
536 }
537 
538 /*
539  * If we are the only user, then try to free up the swap cache.
540  *
541  * Its ok to check the swapcache flag without the folio lock
542  * here because we are going to recheck again inside
543  * folio_free_swap() _with_ the lock.
544  * 					- Marcelo
545  */
546 void free_swap_cache(struct folio *folio)
547 {
548 	if (folio_test_swapcache(folio) && !folio_mapped(folio) &&
549 	    folio_trylock(folio)) {
550 		folio_free_swap(folio);
551 		folio_unlock(folio);
552 	}
553 }
554 
555 /*
556  * Freeing a folio and also freeing any swap cache associated with
557  * this folio if it is the last user.
558  */
559 void free_folio_and_swap_cache(struct folio *folio)
560 {
561 	free_swap_cache(folio);
562 	if (!is_huge_zero_folio(folio))
563 		folio_put(folio);
564 }
565 
566 /*
567  * Passed an array of pages, drop them all from swapcache and then release
568  * them.  They are removed from the LRU and freed if this is their last use.
569  */
570 void free_pages_and_swap_cache(struct encoded_page **pages, int nr)
571 {
572 	struct folio_batch folios;
573 	unsigned int refs[FOLIO_BATCH_SIZE];
574 
575 	folio_batch_init(&folios);
576 	for (int i = 0; i < nr; i++) {
577 		struct folio *folio = page_folio(encoded_page_ptr(pages[i]));
578 
579 		free_swap_cache(folio);
580 		refs[folios.nr] = 1;
581 		if (unlikely(encoded_page_flags(pages[i]) &
582 			     ENCODED_PAGE_BIT_NR_PAGES_NEXT))
583 			refs[folios.nr] = encoded_nr_pages(pages[++i]);
584 
585 		if (folio_batch_add(&folios, folio) == 0)
586 			folios_put_refs(&folios, refs);
587 	}
588 	if (folios.nr)
589 		folios_put_refs(&folios, refs);
590 }
591 
592 static inline bool swap_use_vma_readahead(void)
593 {
594 	return READ_ONCE(enable_vma_readahead) && !atomic_read(&nr_rotate_swap);
595 }
596 
597 /**
598  * swap_update_readahead - Update the readahead statistics of VMA or globally.
599  * @folio: the swap cache folio that just got hit.
600  * @vma: the VMA that should be updated, could be NULL for global update.
601  * @addr: the addr that triggered the swapin, ignored if @vma is NULL.
602  */
603 void swap_update_readahead(struct folio *folio, struct vm_area_struct *vma,
604 			   unsigned long addr)
605 {
606 	bool readahead, vma_ra = swap_use_vma_readahead();
607 
608 	/*
609 	 * At the moment, we don't support PG_readahead for anon THP
610 	 * so let's bail out rather than confusing the readahead stat.
611 	 */
612 	if (unlikely(folio_test_large(folio)))
613 		return;
614 
615 	readahead = folio_test_clear_readahead(folio);
616 	if (vma && vma_ra) {
617 		unsigned long ra_val;
618 		int win, hits;
619 
620 		ra_val = GET_SWAP_RA_VAL(vma);
621 		win = SWAP_RA_WIN(ra_val);
622 		hits = SWAP_RA_HITS(ra_val);
623 		if (readahead)
624 			hits = min_t(int, hits + 1, SWAP_RA_HITS_MAX);
625 		atomic_long_set(&vma->swap_readahead_info,
626 				SWAP_RA_VAL(addr, win, hits));
627 	}
628 
629 	if (readahead) {
630 		count_vm_event(SWAP_RA_HIT);
631 		if (!vma || !vma_ra)
632 			atomic_inc(&swapin_readahead_hits);
633 	}
634 }
635 
636 static struct folio *swap_cache_read_folio(swp_entry_t entry, gfp_t gfp,
637 					   struct mempolicy *mpol, pgoff_t ilx,
638 					   struct swap_iocb **plug, bool readahead)
639 {
640 	struct folio *folio;
641 
642 	do {
643 		folio = swap_cache_get_folio(entry);
644 		if (folio)
645 			return folio;
646 		folio = swap_cache_alloc_folio(entry, gfp, BIT(0), NULL, mpol, ilx);
647 	} while (PTR_ERR(folio) == -EEXIST);
648 
649 	if (IS_ERR_OR_NULL(folio))
650 		return NULL;
651 
652 	swap_read_folio(folio, plug);
653 	if (readahead) {
654 		folio_set_readahead(folio);
655 		count_vm_event(SWAP_RA);
656 	}
657 
658 	return folio;
659 }
660 
661 /**
662  * swapin_sync - swap-in one or multiple entries skipping readahead.
663  * @entry: swap entry indicating the target slot
664  * @gfp: memory allocation flags
665  * @orders: allocation orders
666  * @vmf: fault information
667  * @mpol: NUMA memory allocation policy to be applied
668  * @ilx: NUMA interleave index, for use only when MPOL_INTERLEAVE
669  *
670  * This allocates a folio suitable for given @orders, or returns the
671  * existing folio in the swap cache for @entry. This initiates the IO, too,
672  * if needed. @entry is rounded down if @orders allow large allocation.
673  *
674  * Context: Caller must ensure @entry is valid and pin the swap device with refcount.
675  * Return: Returns the folio on success, error code if failed.
676  */
677 struct folio *swapin_sync(swp_entry_t entry, gfp_t gfp, unsigned long orders,
678 			   struct vm_fault *vmf, struct mempolicy *mpol, pgoff_t ilx)
679 {
680 	struct folio *folio;
681 
682 	do {
683 		folio = swap_cache_get_folio(entry);
684 		if (folio)
685 			return folio;
686 		folio = swap_cache_alloc_folio(entry, gfp, orders, vmf, mpol, ilx);
687 	} while (PTR_ERR(folio) == -EEXIST);
688 
689 	if (IS_ERR(folio))
690 		return folio;
691 
692 	swap_read_folio(folio, NULL);
693 	return folio;
694 }
695 
696 /*
697  * Locate a page of swap in physical memory, reserving swap cache space
698  * and reading the disk if it is not already cached.
699  * A failure return means that either the page allocation failed or that
700  * the swap entry is no longer in use.
701  */
702 struct folio *read_swap_cache_async(swp_entry_t entry, gfp_t gfp_mask,
703 		struct vm_area_struct *vma, unsigned long addr,
704 		struct swap_iocb **plug)
705 {
706 	struct swap_info_struct *si;
707 	struct mempolicy *mpol;
708 	pgoff_t ilx;
709 	struct folio *folio;
710 
711 	si = get_swap_device(entry);
712 	if (!si)
713 		return NULL;
714 
715 	mpol = get_vma_policy(vma, addr, 0, &ilx);
716 	folio = swap_cache_read_folio(entry, gfp_mask, mpol, ilx, plug, false);
717 	mpol_cond_put(mpol);
718 
719 	put_swap_device(si);
720 	return folio;
721 }
722 
723 static unsigned int __swapin_nr_pages(unsigned long prev_offset,
724 				      unsigned long offset,
725 				      int hits,
726 				      int max_pages,
727 				      int prev_win)
728 {
729 	unsigned int pages, last_ra;
730 
731 	/*
732 	 * This heuristic has been found to work well on both sequential and
733 	 * random loads, swapping to hard disk or to SSD: please don't ask
734 	 * what the "+ 2" means, it just happens to work well, that's all.
735 	 */
736 	pages = hits + 2;
737 	if (pages == 2) {
738 		/*
739 		 * We can have no readahead hits to judge by: but must not get
740 		 * stuck here forever, so check for an adjacent offset instead
741 		 * (and don't even bother to check whether swap type is same).
742 		 */
743 		if (offset != prev_offset + 1 && offset != prev_offset - 1)
744 			pages = 1;
745 	} else {
746 		unsigned int roundup = 4;
747 		while (roundup < pages)
748 			roundup <<= 1;
749 		pages = roundup;
750 	}
751 
752 	if (pages > max_pages)
753 		pages = max_pages;
754 
755 	/* Don't shrink readahead too fast */
756 	last_ra = prev_win / 2;
757 	if (pages < last_ra)
758 		pages = last_ra;
759 
760 	return pages;
761 }
762 
763 static unsigned long swapin_nr_pages(unsigned long offset)
764 {
765 	static unsigned long prev_offset;
766 	unsigned int hits, pages, max_pages;
767 	static atomic_t last_readahead_pages;
768 
769 	max_pages = 1 << READ_ONCE(page_cluster);
770 	if (max_pages <= 1)
771 		return 1;
772 
773 	hits = atomic_xchg(&swapin_readahead_hits, 0);
774 	pages = __swapin_nr_pages(READ_ONCE(prev_offset), offset, hits,
775 				  max_pages,
776 				  atomic_read(&last_readahead_pages));
777 	if (!hits)
778 		WRITE_ONCE(prev_offset, offset);
779 	atomic_set(&last_readahead_pages, pages);
780 
781 	return pages;
782 }
783 
784 /**
785  * swap_cluster_readahead - swap in pages in hope we need them soon
786  * @entry: swap entry of this memory
787  * @gfp_mask: memory allocation flags
788  * @mpol: NUMA memory allocation policy to be applied
789  * @ilx: NUMA interleave index, for use only when MPOL_INTERLEAVE
790  *
791  * Returns the struct folio for entry and addr, after queueing swapin.
792  *
793  * Primitive swap readahead code. We simply read an aligned block of
794  * (1 << page_cluster) entries in the swap area. This method is chosen
795  * because it doesn't cost us any seek time.  We also make sure to queue
796  * the 'original' request together with the readahead ones...
797  *
798  * Note: it is intentional that the same NUMA policy and interleave index
799  * are used for every page of the readahead: neighbouring pages on swap
800  * are fairly likely to have been swapped out from the same node.
801  */
802 struct folio *swap_cluster_readahead(swp_entry_t entry, gfp_t gfp_mask,
803 				     struct mempolicy *mpol, pgoff_t ilx)
804 {
805 	struct folio *folio;
806 	unsigned long entry_offset = swp_offset(entry);
807 	unsigned long offset = entry_offset;
808 	unsigned long start_offset, end_offset;
809 	unsigned long mask;
810 	struct swap_info_struct *si = __swap_entry_to_info(entry);
811 	struct blk_plug plug;
812 	struct swap_iocb *splug = NULL;
813 	swp_entry_t ra_entry;
814 
815 	mask = swapin_nr_pages(offset) - 1;
816 	if (!mask)
817 		goto skip;
818 
819 	/* Read a page_cluster sized and aligned cluster around offset. */
820 	start_offset = offset & ~mask;
821 	end_offset = offset | mask;
822 	if (!start_offset)	/* First page is swap header. */
823 		start_offset++;
824 	if (end_offset >= si->max)
825 		end_offset = si->max - 1;
826 
827 	blk_start_plug(&plug);
828 	for (offset = start_offset; offset <= end_offset ; offset++) {
829 		/* Ok, do the async read-ahead now */
830 		ra_entry = swp_entry(swp_type(entry), offset);
831 		folio = swap_cache_read_folio(ra_entry, gfp_mask, mpol, ilx,
832 					      &splug, offset != entry_offset);
833 		if (!folio)
834 			continue;
835 		folio_put(folio);
836 	}
837 	blk_finish_plug(&plug);
838 	swap_read_unplug(splug);
839 	lru_add_drain();	/* Push any new pages onto the LRU now */
840 skip:
841 	/* The page was likely read above, so no need for plugging here */
842 	return swap_cache_read_folio(entry, gfp_mask, mpol, ilx, NULL, false);
843 }
844 
845 static int swap_vma_ra_win(struct vm_fault *vmf, unsigned long *start,
846 			   unsigned long *end)
847 {
848 	struct vm_area_struct *vma = vmf->vma;
849 	unsigned long ra_val;
850 	unsigned long faddr, prev_faddr, left, right;
851 	unsigned int max_win, hits, prev_win, win;
852 
853 	max_win = 1 << min(READ_ONCE(page_cluster), SWAP_RA_ORDER_CEILING);
854 	if (max_win == 1)
855 		return 1;
856 
857 	faddr = vmf->address;
858 	ra_val = GET_SWAP_RA_VAL(vma);
859 	prev_faddr = SWAP_RA_ADDR(ra_val);
860 	prev_win = SWAP_RA_WIN(ra_val);
861 	hits = SWAP_RA_HITS(ra_val);
862 	win = __swapin_nr_pages(PFN_DOWN(prev_faddr), PFN_DOWN(faddr), hits,
863 				max_win, prev_win);
864 	atomic_long_set(&vma->swap_readahead_info, SWAP_RA_VAL(faddr, win, 0));
865 	if (win == 1)
866 		return 1;
867 
868 	if (faddr == prev_faddr + PAGE_SIZE)
869 		left = faddr;
870 	else if (prev_faddr == faddr + PAGE_SIZE)
871 		left = faddr - (win << PAGE_SHIFT) + PAGE_SIZE;
872 	else
873 		left = faddr - (((win - 1) / 2) << PAGE_SHIFT);
874 	right = left + (win << PAGE_SHIFT);
875 	if ((long)left < 0)
876 		left = 0;
877 	*start = max3(left, vma->vm_start, faddr & PMD_MASK);
878 	*end = min3(right, vma->vm_end, (faddr & PMD_MASK) + PMD_SIZE);
879 
880 	return win;
881 }
882 
883 /**
884  * swap_vma_readahead - swap in pages in hope we need them soon
885  * @targ_entry: swap entry of the targeted memory
886  * @gfp_mask: memory allocation flags
887  * @mpol: NUMA memory allocation policy to be applied
888  * @targ_ilx: NUMA interleave index, for use only when MPOL_INTERLEAVE
889  * @vmf: fault information
890  *
891  * Returns the struct folio for entry and addr, after queueing swapin.
892  *
893  * Primitive swap readahead code. We simply read in a few pages whose
894  * virtual addresses are around the fault address in the same vma.
895  *
896  * Caller must hold read mmap_lock if vmf->vma is not NULL.
897  *
898  */
899 static struct folio *swap_vma_readahead(swp_entry_t targ_entry, gfp_t gfp_mask,
900 		struct mempolicy *mpol, pgoff_t targ_ilx, struct vm_fault *vmf)
901 {
902 	struct blk_plug plug;
903 	struct swap_iocb *splug = NULL;
904 	struct folio *folio;
905 	pte_t *pte = NULL, pentry;
906 	int win;
907 	unsigned long start, end, addr;
908 	pgoff_t ilx = targ_ilx;
909 
910 	win = swap_vma_ra_win(vmf, &start, &end);
911 	if (win == 1)
912 		goto skip;
913 
914 	ilx = targ_ilx - PFN_DOWN(vmf->address - start);
915 
916 	blk_start_plug(&plug);
917 	for (addr = start; addr < end; ilx++, addr += PAGE_SIZE) {
918 		struct swap_info_struct *si = NULL;
919 		softleaf_t entry;
920 
921 		if (!pte++) {
922 			pte = pte_offset_map(vmf->pmd, addr);
923 			if (!pte)
924 				break;
925 		}
926 		pentry = ptep_get_lockless(pte);
927 		entry = softleaf_from_pte(pentry);
928 
929 		if (!softleaf_is_swap(entry))
930 			continue;
931 		pte_unmap(pte);
932 		pte = NULL;
933 		/*
934 		 * Readahead entry may come from a device that we are not
935 		 * holding a reference to, try to grab a reference, or skip.
936 		 */
937 		if (swp_type(entry) != swp_type(targ_entry)) {
938 			si = get_swap_device(entry);
939 			if (!si)
940 				continue;
941 		}
942 		folio = swap_cache_read_folio(entry, gfp_mask, mpol, ilx,
943 					      &splug, addr != vmf->address);
944 		if (si)
945 			put_swap_device(si);
946 		if (!folio)
947 			continue;
948 		folio_put(folio);
949 	}
950 	if (pte)
951 		pte_unmap(pte);
952 	blk_finish_plug(&plug);
953 	swap_read_unplug(splug);
954 	lru_add_drain();
955 skip:
956 	/* The folio was likely read above, so no need for plugging here */
957 	folio = swap_cache_read_folio(targ_entry, gfp_mask, mpol, targ_ilx,
958 				      NULL, false);
959 	return folio;
960 }
961 
962 /**
963  * swapin_readahead - swap in pages in hope we need them soon
964  * @entry: swap entry of this memory
965  * @gfp_mask: memory allocation flags
966  * @vmf: fault information
967  *
968  * Returns the struct folio for entry and addr, after queueing swapin.
969  *
970  * It's a main entry function for swap readahead. By the configuration,
971  * it will read ahead blocks by cluster-based(ie, physical disk based)
972  * or vma-based(ie, virtual address based on faulty address) readahead.
973  */
974 struct folio *swapin_readahead(swp_entry_t entry, gfp_t gfp_mask,
975 				struct vm_fault *vmf)
976 {
977 	struct mempolicy *mpol;
978 	pgoff_t ilx;
979 	struct folio *folio;
980 
981 	mpol = get_vma_policy(vmf->vma, vmf->address, 0, &ilx);
982 	folio = swap_use_vma_readahead() ?
983 		swap_vma_readahead(entry, gfp_mask, mpol, ilx, vmf) :
984 		swap_cluster_readahead(entry, gfp_mask, mpol, ilx);
985 	mpol_cond_put(mpol);
986 
987 	return folio;
988 }
989 
990 #ifdef CONFIG_SYSFS
991 static ssize_t vma_ra_enabled_show(struct kobject *kobj,
992 				     struct kobj_attribute *attr, char *buf)
993 {
994 	return sysfs_emit(buf, "%s\n", str_true_false(enable_vma_readahead));
995 }
996 static ssize_t vma_ra_enabled_store(struct kobject *kobj,
997 				      struct kobj_attribute *attr,
998 				      const char *buf, size_t count)
999 {
1000 	ssize_t ret;
1001 
1002 	ret = kstrtobool(buf, &enable_vma_readahead);
1003 	if (ret)
1004 		return ret;
1005 
1006 	return count;
1007 }
1008 static struct kobj_attribute vma_ra_enabled_attr = __ATTR_RW(vma_ra_enabled);
1009 
1010 static struct attribute *swap_attrs[] = {
1011 	&vma_ra_enabled_attr.attr,
1012 	NULL,
1013 };
1014 
1015 static const struct attribute_group swap_attr_group = {
1016 	.attrs = swap_attrs,
1017 };
1018 
1019 static int __init swap_init(void)
1020 {
1021 	int err;
1022 	struct kobject *swap_kobj;
1023 
1024 	swap_kobj = kobject_create_and_add("swap", mm_kobj);
1025 	if (!swap_kobj) {
1026 		pr_err("failed to create swap kobject\n");
1027 		return -ENOMEM;
1028 	}
1029 	err = sysfs_create_group(swap_kobj, &swap_attr_group);
1030 	if (err) {
1031 		pr_err("failed to register swap group\n");
1032 		goto delete_obj;
1033 	}
1034 	/* Swap cache writeback is LRU based, no tags for it */
1035 	mapping_set_no_writeback_tags(&swap_space);
1036 	return 0;
1037 
1038 delete_obj:
1039 	kobject_put(swap_kobj);
1040 	return err;
1041 }
1042 subsys_initcall(swap_init);
1043 #endif
1044