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