xref: /linux/mm/swap_state.c (revision b8b9488d50b7150bd4830dfff487e8d4ef6589ba)
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/swapops.h>
16 #include <linux/init.h>
17 #include <linux/pagemap.h>
18 #include <linux/pagevec.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/swap_slots.h>
24 #include <linux/huge_mm.h>
25 #include <linux/shmem_fs.h>
26 #include "internal.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 	.writepage	= swap_writepage,
35 	.dirty_folio	= noop_dirty_folio,
36 #ifdef CONFIG_MIGRATION
37 	.migrate_folio	= migrate_folio,
38 #endif
39 };
40 
41 struct address_space *swapper_spaces[MAX_SWAPFILES] __read_mostly;
42 static unsigned int nr_swapper_spaces[MAX_SWAPFILES] __read_mostly;
43 static bool enable_vma_readahead __read_mostly = true;
44 
45 #define SWAP_RA_WIN_SHIFT	(PAGE_SHIFT / 2)
46 #define SWAP_RA_HITS_MASK	((1UL << SWAP_RA_WIN_SHIFT) - 1)
47 #define SWAP_RA_HITS_MAX	SWAP_RA_HITS_MASK
48 #define SWAP_RA_WIN_MASK	(~PAGE_MASK & ~SWAP_RA_HITS_MASK)
49 
50 #define SWAP_RA_HITS(v)		((v) & SWAP_RA_HITS_MASK)
51 #define SWAP_RA_WIN(v)		(((v) & SWAP_RA_WIN_MASK) >> SWAP_RA_WIN_SHIFT)
52 #define SWAP_RA_ADDR(v)		((v) & PAGE_MASK)
53 
54 #define SWAP_RA_VAL(addr, win, hits)				\
55 	(((addr) & PAGE_MASK) |					\
56 	 (((win) << SWAP_RA_WIN_SHIFT) & SWAP_RA_WIN_MASK) |	\
57 	 ((hits) & SWAP_RA_HITS_MASK))
58 
59 /* Initial readahead hits is 4 to start up with a small window */
60 #define GET_SWAP_RA_VAL(vma)					\
61 	(atomic_long_read(&(vma)->swap_readahead_info) ? : 4)
62 
63 static atomic_t swapin_readahead_hits = ATOMIC_INIT(4);
64 
65 void show_swap_cache_info(void)
66 {
67 	printk("%lu pages in swap cache\n", total_swapcache_pages());
68 	printk("Free swap  = %ldkB\n", K(get_nr_swap_pages()));
69 	printk("Total swap = %lukB\n", K(total_swap_pages));
70 }
71 
72 void *get_shadow_from_swap_cache(swp_entry_t entry)
73 {
74 	struct address_space *address_space = swap_address_space(entry);
75 	pgoff_t idx = swap_cache_index(entry);
76 	void *shadow;
77 
78 	shadow = xa_load(&address_space->i_pages, idx);
79 	if (xa_is_value(shadow))
80 		return shadow;
81 	return NULL;
82 }
83 
84 /*
85  * add_to_swap_cache resembles filemap_add_folio on swapper_space,
86  * but sets SwapCache flag and private instead of mapping and index.
87  */
88 int add_to_swap_cache(struct folio *folio, swp_entry_t entry,
89 			gfp_t gfp, void **shadowp)
90 {
91 	struct address_space *address_space = swap_address_space(entry);
92 	pgoff_t idx = swap_cache_index(entry);
93 	XA_STATE_ORDER(xas, &address_space->i_pages, idx, folio_order(folio));
94 	unsigned long i, nr = folio_nr_pages(folio);
95 	void *old;
96 
97 	xas_set_update(&xas, workingset_update_node);
98 
99 	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
100 	VM_BUG_ON_FOLIO(folio_test_swapcache(folio), folio);
101 	VM_BUG_ON_FOLIO(!folio_test_swapbacked(folio), folio);
102 
103 	folio_ref_add(folio, nr);
104 	folio_set_swapcache(folio);
105 	folio->swap = entry;
106 
107 	do {
108 		xas_lock_irq(&xas);
109 		xas_create_range(&xas);
110 		if (xas_error(&xas))
111 			goto unlock;
112 		for (i = 0; i < nr; i++) {
113 			VM_BUG_ON_FOLIO(xas.xa_index != idx + i, folio);
114 			if (shadowp) {
115 				old = xas_load(&xas);
116 				if (xa_is_value(old))
117 					*shadowp = old;
118 			}
119 			xas_store(&xas, folio);
120 			xas_next(&xas);
121 		}
122 		address_space->nrpages += nr;
123 		__node_stat_mod_folio(folio, NR_FILE_PAGES, nr);
124 		__lruvec_stat_mod_folio(folio, NR_SWAPCACHE, nr);
125 unlock:
126 		xas_unlock_irq(&xas);
127 	} while (xas_nomem(&xas, gfp));
128 
129 	if (!xas_error(&xas))
130 		return 0;
131 
132 	folio_clear_swapcache(folio);
133 	folio_ref_sub(folio, nr);
134 	return xas_error(&xas);
135 }
136 
137 /*
138  * This must be called only on folios that have
139  * been verified to be in the swap cache.
140  */
141 void __delete_from_swap_cache(struct folio *folio,
142 			swp_entry_t entry, void *shadow)
143 {
144 	struct address_space *address_space = swap_address_space(entry);
145 	int i;
146 	long nr = folio_nr_pages(folio);
147 	pgoff_t idx = swap_cache_index(entry);
148 	XA_STATE(xas, &address_space->i_pages, idx);
149 
150 	xas_set_update(&xas, workingset_update_node);
151 
152 	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
153 	VM_BUG_ON_FOLIO(!folio_test_swapcache(folio), folio);
154 	VM_BUG_ON_FOLIO(folio_test_writeback(folio), folio);
155 
156 	for (i = 0; i < nr; i++) {
157 		void *entry = xas_store(&xas, shadow);
158 		VM_BUG_ON_PAGE(entry != folio, entry);
159 		xas_next(&xas);
160 	}
161 	folio->swap.val = 0;
162 	folio_clear_swapcache(folio);
163 	address_space->nrpages -= nr;
164 	__node_stat_mod_folio(folio, NR_FILE_PAGES, -nr);
165 	__lruvec_stat_mod_folio(folio, NR_SWAPCACHE, -nr);
166 }
167 
168 /**
169  * add_to_swap - allocate swap space for a folio
170  * @folio: folio we want to move to swap
171  *
172  * Allocate swap space for the folio and add the folio to the
173  * swap cache.
174  *
175  * Context: Caller needs to hold the folio lock.
176  * Return: Whether the folio was added to the swap cache.
177  */
178 bool add_to_swap(struct folio *folio)
179 {
180 	swp_entry_t entry;
181 	int err;
182 
183 	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
184 	VM_BUG_ON_FOLIO(!folio_test_uptodate(folio), folio);
185 
186 	entry = folio_alloc_swap(folio);
187 	if (!entry.val)
188 		return false;
189 
190 	/*
191 	 * XArray node allocations from PF_MEMALLOC contexts could
192 	 * completely exhaust the page allocator. __GFP_NOMEMALLOC
193 	 * stops emergency reserves from being allocated.
194 	 *
195 	 * TODO: this could cause a theoretical memory reclaim
196 	 * deadlock in the swap out path.
197 	 */
198 	/*
199 	 * Add it to the swap cache.
200 	 */
201 	err = add_to_swap_cache(folio, entry,
202 			__GFP_HIGH|__GFP_NOMEMALLOC|__GFP_NOWARN, NULL);
203 	if (err)
204 		/*
205 		 * add_to_swap_cache() doesn't return -EEXIST, so we can safely
206 		 * clear SWAP_HAS_CACHE flag.
207 		 */
208 		goto fail;
209 	/*
210 	 * Normally the folio will be dirtied in unmap because its
211 	 * pte should be dirty. A special case is MADV_FREE page. The
212 	 * page's pte could have dirty bit cleared but the folio's
213 	 * SwapBacked flag is still set because clearing the dirty bit
214 	 * and SwapBacked flag has no lock protected. For such folio,
215 	 * unmap will not set dirty bit for it, so folio reclaim will
216 	 * not write the folio out. This can cause data corruption when
217 	 * the folio is swapped in later. Always setting the dirty flag
218 	 * for the folio solves the problem.
219 	 */
220 	folio_mark_dirty(folio);
221 
222 	return true;
223 
224 fail:
225 	put_swap_folio(folio, entry);
226 	return false;
227 }
228 
229 /*
230  * This must be called only on folios that have
231  * been verified to be in the swap cache and locked.
232  * It will never put the folio into the free list,
233  * the caller has a reference on the folio.
234  */
235 void delete_from_swap_cache(struct folio *folio)
236 {
237 	swp_entry_t entry = folio->swap;
238 	struct address_space *address_space = swap_address_space(entry);
239 
240 	xa_lock_irq(&address_space->i_pages);
241 	__delete_from_swap_cache(folio, entry, NULL);
242 	xa_unlock_irq(&address_space->i_pages);
243 
244 	put_swap_folio(folio, entry);
245 	folio_ref_sub(folio, folio_nr_pages(folio));
246 }
247 
248 void clear_shadow_from_swap_cache(int type, unsigned long begin,
249 				unsigned long end)
250 {
251 	unsigned long curr = begin;
252 	void *old;
253 
254 	for (;;) {
255 		swp_entry_t entry = swp_entry(type, curr);
256 		unsigned long index = curr & SWAP_ADDRESS_SPACE_MASK;
257 		struct address_space *address_space = swap_address_space(entry);
258 		XA_STATE(xas, &address_space->i_pages, index);
259 
260 		xas_set_update(&xas, workingset_update_node);
261 
262 		xa_lock_irq(&address_space->i_pages);
263 		xas_for_each(&xas, old, min(index + (end - curr), SWAP_ADDRESS_SPACE_PAGES)) {
264 			if (!xa_is_value(old))
265 				continue;
266 			xas_store(&xas, NULL);
267 		}
268 		xa_unlock_irq(&address_space->i_pages);
269 
270 		/* search the next swapcache until we meet end */
271 		curr >>= SWAP_ADDRESS_SPACE_SHIFT;
272 		curr++;
273 		curr <<= SWAP_ADDRESS_SPACE_SHIFT;
274 		if (curr > end)
275 			break;
276 	}
277 }
278 
279 /*
280  * If we are the only user, then try to free up the swap cache.
281  *
282  * Its ok to check the swapcache flag without the folio lock
283  * here because we are going to recheck again inside
284  * folio_free_swap() _with_ the lock.
285  * 					- Marcelo
286  */
287 void free_swap_cache(struct folio *folio)
288 {
289 	if (folio_test_swapcache(folio) && !folio_mapped(folio) &&
290 	    folio_trylock(folio)) {
291 		folio_free_swap(folio);
292 		folio_unlock(folio);
293 	}
294 }
295 
296 /*
297  * Perform a free_page(), also freeing any swap cache associated with
298  * this page if it is the last user of the page.
299  */
300 void free_page_and_swap_cache(struct page *page)
301 {
302 	struct folio *folio = page_folio(page);
303 
304 	free_swap_cache(folio);
305 	if (!is_huge_zero_folio(folio))
306 		folio_put(folio);
307 }
308 
309 /*
310  * Passed an array of pages, drop them all from swapcache and then release
311  * them.  They are removed from the LRU and freed if this is their last use.
312  */
313 void free_pages_and_swap_cache(struct encoded_page **pages, int nr)
314 {
315 	struct folio_batch folios;
316 	unsigned int refs[PAGEVEC_SIZE];
317 
318 	lru_add_drain();
319 	folio_batch_init(&folios);
320 	for (int i = 0; i < nr; i++) {
321 		struct folio *folio = page_folio(encoded_page_ptr(pages[i]));
322 
323 		free_swap_cache(folio);
324 		refs[folios.nr] = 1;
325 		if (unlikely(encoded_page_flags(pages[i]) &
326 			     ENCODED_PAGE_BIT_NR_PAGES_NEXT))
327 			refs[folios.nr] = encoded_nr_pages(pages[++i]);
328 
329 		if (folio_batch_add(&folios, folio) == 0)
330 			folios_put_refs(&folios, refs);
331 	}
332 	if (folios.nr)
333 		folios_put_refs(&folios, refs);
334 }
335 
336 static inline bool swap_use_vma_readahead(void)
337 {
338 	return READ_ONCE(enable_vma_readahead) && !atomic_read(&nr_rotate_swap);
339 }
340 
341 /*
342  * Lookup a swap entry in the swap cache. A found folio will be returned
343  * unlocked and with its refcount incremented - we rely on the kernel
344  * lock getting page table operations atomic even if we drop the folio
345  * lock before returning.
346  *
347  * Caller must lock the swap device or hold a reference to keep it valid.
348  */
349 struct folio *swap_cache_get_folio(swp_entry_t entry,
350 		struct vm_area_struct *vma, unsigned long addr)
351 {
352 	struct folio *folio;
353 
354 	folio = filemap_get_folio(swap_address_space(entry), swap_cache_index(entry));
355 	if (!IS_ERR(folio)) {
356 		bool vma_ra = swap_use_vma_readahead();
357 		bool readahead;
358 
359 		/*
360 		 * At the moment, we don't support PG_readahead for anon THP
361 		 * so let's bail out rather than confusing the readahead stat.
362 		 */
363 		if (unlikely(folio_test_large(folio)))
364 			return folio;
365 
366 		readahead = folio_test_clear_readahead(folio);
367 		if (vma && vma_ra) {
368 			unsigned long ra_val;
369 			int win, hits;
370 
371 			ra_val = GET_SWAP_RA_VAL(vma);
372 			win = SWAP_RA_WIN(ra_val);
373 			hits = SWAP_RA_HITS(ra_val);
374 			if (readahead)
375 				hits = min_t(int, hits + 1, SWAP_RA_HITS_MAX);
376 			atomic_long_set(&vma->swap_readahead_info,
377 					SWAP_RA_VAL(addr, win, hits));
378 		}
379 
380 		if (readahead) {
381 			count_vm_event(SWAP_RA_HIT);
382 			if (!vma || !vma_ra)
383 				atomic_inc(&swapin_readahead_hits);
384 		}
385 	} else {
386 		folio = NULL;
387 	}
388 
389 	return folio;
390 }
391 
392 /**
393  * filemap_get_incore_folio - Find and get a folio from the page or swap caches.
394  * @mapping: The address_space to search.
395  * @index: The page cache index.
396  *
397  * This differs from filemap_get_folio() in that it will also look for the
398  * folio in the swap cache.
399  *
400  * Return: The found folio or %NULL.
401  */
402 struct folio *filemap_get_incore_folio(struct address_space *mapping,
403 		pgoff_t index)
404 {
405 	swp_entry_t swp;
406 	struct swap_info_struct *si;
407 	struct folio *folio = filemap_get_entry(mapping, index);
408 
409 	if (!folio)
410 		return ERR_PTR(-ENOENT);
411 	if (!xa_is_value(folio))
412 		return folio;
413 	if (!shmem_mapping(mapping))
414 		return ERR_PTR(-ENOENT);
415 
416 	swp = radix_to_swp_entry(folio);
417 	/* There might be swapin error entries in shmem mapping. */
418 	if (non_swap_entry(swp))
419 		return ERR_PTR(-ENOENT);
420 	/* Prevent swapoff from happening to us */
421 	si = get_swap_device(swp);
422 	if (!si)
423 		return ERR_PTR(-ENOENT);
424 	index = swap_cache_index(swp);
425 	folio = filemap_get_folio(swap_address_space(swp), index);
426 	put_swap_device(si);
427 	return folio;
428 }
429 
430 struct folio *__read_swap_cache_async(swp_entry_t entry, gfp_t gfp_mask,
431 		struct mempolicy *mpol, pgoff_t ilx, bool *new_page_allocated,
432 		bool skip_if_exists)
433 {
434 	struct swap_info_struct *si;
435 	struct folio *folio;
436 	void *shadow = NULL;
437 
438 	*new_page_allocated = false;
439 	si = get_swap_device(entry);
440 	if (!si)
441 		return NULL;
442 
443 	for (;;) {
444 		int err;
445 		/*
446 		 * First check the swap cache.  Since this is normally
447 		 * called after swap_cache_get_folio() failed, re-calling
448 		 * that would confuse statistics.
449 		 */
450 		folio = filemap_get_folio(swap_address_space(entry),
451 					  swap_cache_index(entry));
452 		if (!IS_ERR(folio))
453 			goto got_folio;
454 
455 		/*
456 		 * Just skip read ahead for unused swap slot.
457 		 * During swap_off when swap_slot_cache is disabled,
458 		 * we have to handle the race between putting
459 		 * swap entry in swap cache and marking swap slot
460 		 * as SWAP_HAS_CACHE.  That's done in later part of code or
461 		 * else swap_off will be aborted if we return NULL.
462 		 */
463 		if (!swap_swapcount(si, entry) && swap_slot_cache_enabled)
464 			goto fail_put_swap;
465 
466 		/*
467 		 * Get a new folio to read into from swap.  Allocate it now,
468 		 * before marking swap_map SWAP_HAS_CACHE, when -EEXIST will
469 		 * cause any racers to loop around until we add it to cache.
470 		 */
471 		folio = (struct folio *)alloc_pages_mpol(gfp_mask, 0,
472 						mpol, ilx, numa_node_id());
473 		if (!folio)
474                         goto fail_put_swap;
475 
476 		/*
477 		 * Swap entry may have been freed since our caller observed it.
478 		 */
479 		err = swapcache_prepare(entry);
480 		if (!err)
481 			break;
482 
483 		folio_put(folio);
484 		if (err != -EEXIST)
485 			goto fail_put_swap;
486 
487 		/*
488 		 * Protect against a recursive call to __read_swap_cache_async()
489 		 * on the same entry waiting forever here because SWAP_HAS_CACHE
490 		 * is set but the folio is not the swap cache yet. This can
491 		 * happen today if mem_cgroup_swapin_charge_folio() below
492 		 * triggers reclaim through zswap, which may call
493 		 * __read_swap_cache_async() in the writeback path.
494 		 */
495 		if (skip_if_exists)
496 			goto fail_put_swap;
497 
498 		/*
499 		 * We might race against __delete_from_swap_cache(), and
500 		 * stumble across a swap_map entry whose SWAP_HAS_CACHE
501 		 * has not yet been cleared.  Or race against another
502 		 * __read_swap_cache_async(), which has set SWAP_HAS_CACHE
503 		 * in swap_map, but not yet added its folio to swap cache.
504 		 */
505 		schedule_timeout_uninterruptible(1);
506 	}
507 
508 	/*
509 	 * The swap entry is ours to swap in. Prepare the new folio.
510 	 */
511 
512 	__folio_set_locked(folio);
513 	__folio_set_swapbacked(folio);
514 
515 	if (mem_cgroup_swapin_charge_folio(folio, NULL, gfp_mask, entry))
516 		goto fail_unlock;
517 
518 	/* May fail (-ENOMEM) if XArray node allocation failed. */
519 	if (add_to_swap_cache(folio, entry, gfp_mask & GFP_RECLAIM_MASK, &shadow))
520 		goto fail_unlock;
521 
522 	mem_cgroup_swapin_uncharge_swap(entry);
523 
524 	if (shadow)
525 		workingset_refault(folio, shadow);
526 
527 	/* Caller will initiate read into locked folio */
528 	folio_add_lru(folio);
529 	*new_page_allocated = true;
530 got_folio:
531 	put_swap_device(si);
532 	return folio;
533 
534 fail_unlock:
535 	put_swap_folio(folio, entry);
536 	folio_unlock(folio);
537 	folio_put(folio);
538 fail_put_swap:
539 	put_swap_device(si);
540 	return NULL;
541 }
542 
543 /*
544  * Locate a page of swap in physical memory, reserving swap cache space
545  * and reading the disk if it is not already cached.
546  * A failure return means that either the page allocation failed or that
547  * the swap entry is no longer in use.
548  *
549  * get/put_swap_device() aren't needed to call this function, because
550  * __read_swap_cache_async() call them and swap_read_folio() holds the
551  * swap cache folio lock.
552  */
553 struct folio *read_swap_cache_async(swp_entry_t entry, gfp_t gfp_mask,
554 		struct vm_area_struct *vma, unsigned long addr,
555 		struct swap_iocb **plug)
556 {
557 	bool page_allocated;
558 	struct mempolicy *mpol;
559 	pgoff_t ilx;
560 	struct folio *folio;
561 
562 	mpol = get_vma_policy(vma, addr, 0, &ilx);
563 	folio = __read_swap_cache_async(entry, gfp_mask, mpol, ilx,
564 					&page_allocated, false);
565 	mpol_cond_put(mpol);
566 
567 	if (page_allocated)
568 		swap_read_folio(folio, false, plug);
569 	return folio;
570 }
571 
572 static unsigned int __swapin_nr_pages(unsigned long prev_offset,
573 				      unsigned long offset,
574 				      int hits,
575 				      int max_pages,
576 				      int prev_win)
577 {
578 	unsigned int pages, last_ra;
579 
580 	/*
581 	 * This heuristic has been found to work well on both sequential and
582 	 * random loads, swapping to hard disk or to SSD: please don't ask
583 	 * what the "+ 2" means, it just happens to work well, that's all.
584 	 */
585 	pages = hits + 2;
586 	if (pages == 2) {
587 		/*
588 		 * We can have no readahead hits to judge by: but must not get
589 		 * stuck here forever, so check for an adjacent offset instead
590 		 * (and don't even bother to check whether swap type is same).
591 		 */
592 		if (offset != prev_offset + 1 && offset != prev_offset - 1)
593 			pages = 1;
594 	} else {
595 		unsigned int roundup = 4;
596 		while (roundup < pages)
597 			roundup <<= 1;
598 		pages = roundup;
599 	}
600 
601 	if (pages > max_pages)
602 		pages = max_pages;
603 
604 	/* Don't shrink readahead too fast */
605 	last_ra = prev_win / 2;
606 	if (pages < last_ra)
607 		pages = last_ra;
608 
609 	return pages;
610 }
611 
612 static unsigned long swapin_nr_pages(unsigned long offset)
613 {
614 	static unsigned long prev_offset;
615 	unsigned int hits, pages, max_pages;
616 	static atomic_t last_readahead_pages;
617 
618 	max_pages = 1 << READ_ONCE(page_cluster);
619 	if (max_pages <= 1)
620 		return 1;
621 
622 	hits = atomic_xchg(&swapin_readahead_hits, 0);
623 	pages = __swapin_nr_pages(READ_ONCE(prev_offset), offset, hits,
624 				  max_pages,
625 				  atomic_read(&last_readahead_pages));
626 	if (!hits)
627 		WRITE_ONCE(prev_offset, offset);
628 	atomic_set(&last_readahead_pages, pages);
629 
630 	return pages;
631 }
632 
633 /**
634  * swap_cluster_readahead - swap in pages in hope we need them soon
635  * @entry: swap entry of this memory
636  * @gfp_mask: memory allocation flags
637  * @mpol: NUMA memory allocation policy to be applied
638  * @ilx: NUMA interleave index, for use only when MPOL_INTERLEAVE
639  *
640  * Returns the struct folio for entry and addr, after queueing swapin.
641  *
642  * Primitive swap readahead code. We simply read an aligned block of
643  * (1 << page_cluster) entries in the swap area. This method is chosen
644  * because it doesn't cost us any seek time.  We also make sure to queue
645  * the 'original' request together with the readahead ones...
646  *
647  * Note: it is intentional that the same NUMA policy and interleave index
648  * are used for every page of the readahead: neighbouring pages on swap
649  * are fairly likely to have been swapped out from the same node.
650  */
651 struct folio *swap_cluster_readahead(swp_entry_t entry, gfp_t gfp_mask,
652 				    struct mempolicy *mpol, pgoff_t ilx)
653 {
654 	struct folio *folio;
655 	unsigned long entry_offset = swp_offset(entry);
656 	unsigned long offset = entry_offset;
657 	unsigned long start_offset, end_offset;
658 	unsigned long mask;
659 	struct swap_info_struct *si = swp_swap_info(entry);
660 	struct blk_plug plug;
661 	struct swap_iocb *splug = NULL;
662 	bool page_allocated;
663 
664 	mask = swapin_nr_pages(offset) - 1;
665 	if (!mask)
666 		goto skip;
667 
668 	/* Read a page_cluster sized and aligned cluster around offset. */
669 	start_offset = offset & ~mask;
670 	end_offset = offset | mask;
671 	if (!start_offset)	/* First page is swap header. */
672 		start_offset++;
673 	if (end_offset >= si->max)
674 		end_offset = si->max - 1;
675 
676 	blk_start_plug(&plug);
677 	for (offset = start_offset; offset <= end_offset ; offset++) {
678 		/* Ok, do the async read-ahead now */
679 		folio = __read_swap_cache_async(
680 				swp_entry(swp_type(entry), offset),
681 				gfp_mask, mpol, ilx, &page_allocated, false);
682 		if (!folio)
683 			continue;
684 		if (page_allocated) {
685 			swap_read_folio(folio, false, &splug);
686 			if (offset != entry_offset) {
687 				folio_set_readahead(folio);
688 				count_vm_event(SWAP_RA);
689 			}
690 		}
691 		folio_put(folio);
692 	}
693 	blk_finish_plug(&plug);
694 	swap_read_unplug(splug);
695 	lru_add_drain();	/* Push any new pages onto the LRU now */
696 skip:
697 	/* The page was likely read above, so no need for plugging here */
698 	folio = __read_swap_cache_async(entry, gfp_mask, mpol, ilx,
699 					&page_allocated, false);
700 	if (unlikely(page_allocated)) {
701 		zswap_folio_swapin(folio);
702 		swap_read_folio(folio, false, NULL);
703 	}
704 	return folio;
705 }
706 
707 int init_swap_address_space(unsigned int type, unsigned long nr_pages)
708 {
709 	struct address_space *spaces, *space;
710 	unsigned int i, nr;
711 
712 	nr = DIV_ROUND_UP(nr_pages, SWAP_ADDRESS_SPACE_PAGES);
713 	spaces = kvcalloc(nr, sizeof(struct address_space), GFP_KERNEL);
714 	if (!spaces)
715 		return -ENOMEM;
716 	for (i = 0; i < nr; i++) {
717 		space = spaces + i;
718 		xa_init_flags(&space->i_pages, XA_FLAGS_LOCK_IRQ);
719 		atomic_set(&space->i_mmap_writable, 0);
720 		space->a_ops = &swap_aops;
721 		/* swap cache doesn't use writeback related tags */
722 		mapping_set_no_writeback_tags(space);
723 	}
724 	nr_swapper_spaces[type] = nr;
725 	swapper_spaces[type] = spaces;
726 
727 	return 0;
728 }
729 
730 void exit_swap_address_space(unsigned int type)
731 {
732 	int i;
733 	struct address_space *spaces = swapper_spaces[type];
734 
735 	for (i = 0; i < nr_swapper_spaces[type]; i++)
736 		VM_WARN_ON_ONCE(!mapping_empty(&spaces[i]));
737 	kvfree(spaces);
738 	nr_swapper_spaces[type] = 0;
739 	swapper_spaces[type] = NULL;
740 }
741 
742 #define SWAP_RA_ORDER_CEILING	5
743 
744 struct vma_swap_readahead {
745 	unsigned short win;
746 	unsigned short offset;
747 	unsigned short nr_pte;
748 };
749 
750 static void swap_ra_info(struct vm_fault *vmf,
751 			 struct vma_swap_readahead *ra_info)
752 {
753 	struct vm_area_struct *vma = vmf->vma;
754 	unsigned long ra_val;
755 	unsigned long faddr, pfn, fpfn, lpfn, rpfn;
756 	unsigned long start, end;
757 	unsigned int max_win, hits, prev_win, win;
758 
759 	max_win = 1 << min_t(unsigned int, READ_ONCE(page_cluster),
760 			     SWAP_RA_ORDER_CEILING);
761 	if (max_win == 1) {
762 		ra_info->win = 1;
763 		return;
764 	}
765 
766 	faddr = vmf->address;
767 	fpfn = PFN_DOWN(faddr);
768 	ra_val = GET_SWAP_RA_VAL(vma);
769 	pfn = PFN_DOWN(SWAP_RA_ADDR(ra_val));
770 	prev_win = SWAP_RA_WIN(ra_val);
771 	hits = SWAP_RA_HITS(ra_val);
772 	ra_info->win = win = __swapin_nr_pages(pfn, fpfn, hits,
773 					       max_win, prev_win);
774 	atomic_long_set(&vma->swap_readahead_info,
775 			SWAP_RA_VAL(faddr, win, 0));
776 	if (win == 1)
777 		return;
778 
779 	if (fpfn == pfn + 1) {
780 		lpfn = fpfn;
781 		rpfn = fpfn + win;
782 	} else if (pfn == fpfn + 1) {
783 		lpfn = fpfn - win + 1;
784 		rpfn = fpfn + 1;
785 	} else {
786 		unsigned int left = (win - 1) / 2;
787 
788 		lpfn = fpfn - left;
789 		rpfn = fpfn + win - left;
790 	}
791 	start = max3(lpfn, PFN_DOWN(vma->vm_start),
792 		     PFN_DOWN(faddr & PMD_MASK));
793 	end = min3(rpfn, PFN_DOWN(vma->vm_end),
794 		   PFN_DOWN((faddr & PMD_MASK) + PMD_SIZE));
795 
796 	ra_info->nr_pte = end - start;
797 	ra_info->offset = fpfn - start;
798 }
799 
800 /**
801  * swap_vma_readahead - swap in pages in hope we need them soon
802  * @targ_entry: swap entry of the targeted memory
803  * @gfp_mask: memory allocation flags
804  * @mpol: NUMA memory allocation policy to be applied
805  * @targ_ilx: NUMA interleave index, for use only when MPOL_INTERLEAVE
806  * @vmf: fault information
807  *
808  * Returns the struct folio for entry and addr, after queueing swapin.
809  *
810  * Primitive swap readahead code. We simply read in a few pages whose
811  * virtual addresses are around the fault address in the same vma.
812  *
813  * Caller must hold read mmap_lock if vmf->vma is not NULL.
814  *
815  */
816 static struct folio *swap_vma_readahead(swp_entry_t targ_entry, gfp_t gfp_mask,
817 		struct mempolicy *mpol, pgoff_t targ_ilx, struct vm_fault *vmf)
818 {
819 	struct blk_plug plug;
820 	struct swap_iocb *splug = NULL;
821 	struct folio *folio;
822 	pte_t *pte = NULL, pentry;
823 	unsigned long addr;
824 	swp_entry_t entry;
825 	pgoff_t ilx;
826 	unsigned int i;
827 	bool page_allocated;
828 	struct vma_swap_readahead ra_info = {
829 		.win = 1,
830 	};
831 
832 	swap_ra_info(vmf, &ra_info);
833 	if (ra_info.win == 1)
834 		goto skip;
835 
836 	addr = vmf->address - (ra_info.offset * PAGE_SIZE);
837 	ilx = targ_ilx - ra_info.offset;
838 
839 	blk_start_plug(&plug);
840 	for (i = 0; i < ra_info.nr_pte; i++, ilx++, addr += PAGE_SIZE) {
841 		if (!pte++) {
842 			pte = pte_offset_map(vmf->pmd, addr);
843 			if (!pte)
844 				break;
845 		}
846 		pentry = ptep_get_lockless(pte);
847 		if (!is_swap_pte(pentry))
848 			continue;
849 		entry = pte_to_swp_entry(pentry);
850 		if (unlikely(non_swap_entry(entry)))
851 			continue;
852 		pte_unmap(pte);
853 		pte = NULL;
854 		folio = __read_swap_cache_async(entry, gfp_mask, mpol, ilx,
855 						&page_allocated, false);
856 		if (!folio)
857 			continue;
858 		if (page_allocated) {
859 			swap_read_folio(folio, false, &splug);
860 			if (i != ra_info.offset) {
861 				folio_set_readahead(folio);
862 				count_vm_event(SWAP_RA);
863 			}
864 		}
865 		folio_put(folio);
866 	}
867 	if (pte)
868 		pte_unmap(pte);
869 	blk_finish_plug(&plug);
870 	swap_read_unplug(splug);
871 	lru_add_drain();
872 skip:
873 	/* The folio was likely read above, so no need for plugging here */
874 	folio = __read_swap_cache_async(targ_entry, gfp_mask, mpol, targ_ilx,
875 					&page_allocated, false);
876 	if (unlikely(page_allocated)) {
877 		zswap_folio_swapin(folio);
878 		swap_read_folio(folio, false, NULL);
879 	}
880 	return folio;
881 }
882 
883 /**
884  * swapin_readahead - swap in pages in hope we need them soon
885  * @entry: swap entry of this memory
886  * @gfp_mask: memory allocation flags
887  * @vmf: fault information
888  *
889  * Returns the struct page for entry and addr, after queueing swapin.
890  *
891  * It's a main entry function for swap readahead. By the configuration,
892  * it will read ahead blocks by cluster-based(ie, physical disk based)
893  * or vma-based(ie, virtual address based on faulty address) readahead.
894  */
895 struct page *swapin_readahead(swp_entry_t entry, gfp_t gfp_mask,
896 				struct vm_fault *vmf)
897 {
898 	struct mempolicy *mpol;
899 	pgoff_t ilx;
900 	struct folio *folio;
901 
902 	mpol = get_vma_policy(vmf->vma, vmf->address, 0, &ilx);
903 	folio = swap_use_vma_readahead() ?
904 		swap_vma_readahead(entry, gfp_mask, mpol, ilx, vmf) :
905 		swap_cluster_readahead(entry, gfp_mask, mpol, ilx);
906 	mpol_cond_put(mpol);
907 
908 	if (!folio)
909 		return NULL;
910 	return folio_file_page(folio, swp_offset(entry));
911 }
912 
913 #ifdef CONFIG_SYSFS
914 static ssize_t vma_ra_enabled_show(struct kobject *kobj,
915 				     struct kobj_attribute *attr, char *buf)
916 {
917 	return sysfs_emit(buf, "%s\n",
918 			  enable_vma_readahead ? "true" : "false");
919 }
920 static ssize_t vma_ra_enabled_store(struct kobject *kobj,
921 				      struct kobj_attribute *attr,
922 				      const char *buf, size_t count)
923 {
924 	ssize_t ret;
925 
926 	ret = kstrtobool(buf, &enable_vma_readahead);
927 	if (ret)
928 		return ret;
929 
930 	return count;
931 }
932 static struct kobj_attribute vma_ra_enabled_attr = __ATTR_RW(vma_ra_enabled);
933 
934 static struct attribute *swap_attrs[] = {
935 	&vma_ra_enabled_attr.attr,
936 	NULL,
937 };
938 
939 static const struct attribute_group swap_attr_group = {
940 	.attrs = swap_attrs,
941 };
942 
943 static int __init swap_init_sysfs(void)
944 {
945 	int err;
946 	struct kobject *swap_kobj;
947 
948 	swap_kobj = kobject_create_and_add("swap", mm_kobj);
949 	if (!swap_kobj) {
950 		pr_err("failed to create swap kobject\n");
951 		return -ENOMEM;
952 	}
953 	err = sysfs_create_group(swap_kobj, &swap_attr_group);
954 	if (err) {
955 		pr_err("failed to register swap group\n");
956 		goto delete_obj;
957 	}
958 	return 0;
959 
960 delete_obj:
961 	kobject_put(swap_kobj);
962 	return err;
963 }
964 subsys_initcall(swap_init_sysfs);
965 #endif
966