xref: /linux/mm/swap_state.c (revision 9907e1df31c0f4bdcebe16de809121baa754e5b5)
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/huge_mm.h>
24 #include <linux/shmem_fs.h>
25 #include "internal.h"
26 #include "swap.h"
27 
28 /*
29  * swapper_space is a fiction, retained to simplify the path through
30  * vmscan's shrink_folio_list.
31  */
32 static const struct address_space_operations swap_aops = {
33 	.dirty_folio	= noop_dirty_folio,
34 #ifdef CONFIG_MIGRATION
35 	.migrate_folio	= migrate_folio,
36 #endif
37 };
38 
39 struct address_space *swapper_spaces[MAX_SWAPFILES] __read_mostly;
40 static unsigned int nr_swapper_spaces[MAX_SWAPFILES] __read_mostly;
41 static bool enable_vma_readahead __read_mostly = true;
42 
43 #define SWAP_RA_ORDER_CEILING	5
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 'swap' 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  * This must be called only on folios that have
170  * been verified to be in the swap cache and locked.
171  * It will never put the folio into the free list,
172  * the caller has a reference on the folio.
173  */
174 void delete_from_swap_cache(struct folio *folio)
175 {
176 	swp_entry_t entry = folio->swap;
177 	struct address_space *address_space = swap_address_space(entry);
178 
179 	xa_lock_irq(&address_space->i_pages);
180 	__delete_from_swap_cache(folio, entry, NULL);
181 	xa_unlock_irq(&address_space->i_pages);
182 
183 	put_swap_folio(folio, entry);
184 	folio_ref_sub(folio, folio_nr_pages(folio));
185 }
186 
187 void clear_shadow_from_swap_cache(int type, unsigned long begin,
188 				unsigned long end)
189 {
190 	unsigned long curr = begin;
191 	void *old;
192 
193 	for (;;) {
194 		swp_entry_t entry = swp_entry(type, curr);
195 		unsigned long index = curr & SWAP_ADDRESS_SPACE_MASK;
196 		struct address_space *address_space = swap_address_space(entry);
197 		XA_STATE(xas, &address_space->i_pages, index);
198 
199 		xas_set_update(&xas, workingset_update_node);
200 
201 		xa_lock_irq(&address_space->i_pages);
202 		xas_for_each(&xas, old, min(index + (end - curr), SWAP_ADDRESS_SPACE_PAGES)) {
203 			if (!xa_is_value(old))
204 				continue;
205 			xas_store(&xas, NULL);
206 		}
207 		xa_unlock_irq(&address_space->i_pages);
208 
209 		/* search the next swapcache until we meet end */
210 		curr = ALIGN((curr + 1), SWAP_ADDRESS_SPACE_PAGES);
211 		if (curr > end)
212 			break;
213 	}
214 }
215 
216 /*
217  * If we are the only user, then try to free up the swap cache.
218  *
219  * Its ok to check the swapcache flag without the folio lock
220  * here because we are going to recheck again inside
221  * folio_free_swap() _with_ the lock.
222  * 					- Marcelo
223  */
224 void free_swap_cache(struct folio *folio)
225 {
226 	if (folio_test_swapcache(folio) && !folio_mapped(folio) &&
227 	    folio_trylock(folio)) {
228 		folio_free_swap(folio);
229 		folio_unlock(folio);
230 	}
231 }
232 
233 /*
234  * Freeing a folio and also freeing any swap cache associated with
235  * this folio if it is the last user.
236  */
237 void free_folio_and_swap_cache(struct folio *folio)
238 {
239 	free_swap_cache(folio);
240 	if (!is_huge_zero_folio(folio))
241 		folio_put(folio);
242 }
243 
244 /*
245  * Passed an array of pages, drop them all from swapcache and then release
246  * them.  They are removed from the LRU and freed if this is their last use.
247  */
248 void free_pages_and_swap_cache(struct encoded_page **pages, int nr)
249 {
250 	struct folio_batch folios;
251 	unsigned int refs[PAGEVEC_SIZE];
252 
253 	folio_batch_init(&folios);
254 	for (int i = 0; i < nr; i++) {
255 		struct folio *folio = page_folio(encoded_page_ptr(pages[i]));
256 
257 		free_swap_cache(folio);
258 		refs[folios.nr] = 1;
259 		if (unlikely(encoded_page_flags(pages[i]) &
260 			     ENCODED_PAGE_BIT_NR_PAGES_NEXT))
261 			refs[folios.nr] = encoded_nr_pages(pages[++i]);
262 
263 		if (folio_batch_add(&folios, folio) == 0)
264 			folios_put_refs(&folios, refs);
265 	}
266 	if (folios.nr)
267 		folios_put_refs(&folios, refs);
268 }
269 
270 static inline bool swap_use_vma_readahead(void)
271 {
272 	return READ_ONCE(enable_vma_readahead) && !atomic_read(&nr_rotate_swap);
273 }
274 
275 /*
276  * Lookup a swap entry in the swap cache. A found folio will be returned
277  * unlocked and with its refcount incremented - we rely on the kernel
278  * lock getting page table operations atomic even if we drop the folio
279  * lock before returning.
280  *
281  * Caller must lock the swap device or hold a reference to keep it valid.
282  */
283 struct folio *swap_cache_get_folio(swp_entry_t entry,
284 		struct vm_area_struct *vma, unsigned long addr)
285 {
286 	struct folio *folio;
287 
288 	folio = filemap_get_folio(swap_address_space(entry), swap_cache_index(entry));
289 	if (!IS_ERR(folio)) {
290 		bool vma_ra = swap_use_vma_readahead();
291 		bool readahead;
292 
293 		/*
294 		 * At the moment, we don't support PG_readahead for anon THP
295 		 * so let's bail out rather than confusing the readahead stat.
296 		 */
297 		if (unlikely(folio_test_large(folio)))
298 			return folio;
299 
300 		readahead = folio_test_clear_readahead(folio);
301 		if (vma && vma_ra) {
302 			unsigned long ra_val;
303 			int win, hits;
304 
305 			ra_val = GET_SWAP_RA_VAL(vma);
306 			win = SWAP_RA_WIN(ra_val);
307 			hits = SWAP_RA_HITS(ra_val);
308 			if (readahead)
309 				hits = min_t(int, hits + 1, SWAP_RA_HITS_MAX);
310 			atomic_long_set(&vma->swap_readahead_info,
311 					SWAP_RA_VAL(addr, win, hits));
312 		}
313 
314 		if (readahead) {
315 			count_vm_event(SWAP_RA_HIT);
316 			if (!vma || !vma_ra)
317 				atomic_inc(&swapin_readahead_hits);
318 		}
319 	} else {
320 		folio = NULL;
321 	}
322 
323 	return folio;
324 }
325 
326 struct folio *__read_swap_cache_async(swp_entry_t entry, gfp_t gfp_mask,
327 		struct mempolicy *mpol, pgoff_t ilx, bool *new_page_allocated,
328 		bool skip_if_exists)
329 {
330 	struct swap_info_struct *si = swp_swap_info(entry);
331 	struct folio *folio;
332 	struct folio *new_folio = NULL;
333 	struct folio *result = NULL;
334 	void *shadow = NULL;
335 
336 	*new_page_allocated = false;
337 	for (;;) {
338 		int err;
339 		/*
340 		 * First check the swap cache.  Since this is normally
341 		 * called after swap_cache_get_folio() failed, re-calling
342 		 * that would confuse statistics.
343 		 */
344 		folio = filemap_get_folio(swap_address_space(entry),
345 					  swap_cache_index(entry));
346 		if (!IS_ERR(folio))
347 			goto got_folio;
348 
349 		/*
350 		 * Just skip read ahead for unused swap slot.
351 		 */
352 		if (!swap_entry_swapped(si, entry))
353 			goto put_and_return;
354 
355 		/*
356 		 * Get a new folio to read into from swap.  Allocate it now if
357 		 * new_folio not exist, before marking swap_map SWAP_HAS_CACHE,
358 		 * when -EEXIST will cause any racers to loop around until we
359 		 * add it to cache.
360 		 */
361 		if (!new_folio) {
362 			new_folio = folio_alloc_mpol(gfp_mask, 0, mpol, ilx, numa_node_id());
363 			if (!new_folio)
364 				goto put_and_return;
365 		}
366 
367 		/*
368 		 * Swap entry may have been freed since our caller observed it.
369 		 */
370 		err = swapcache_prepare(entry, 1);
371 		if (!err)
372 			break;
373 		else if (err != -EEXIST)
374 			goto put_and_return;
375 
376 		/*
377 		 * Protect against a recursive call to __read_swap_cache_async()
378 		 * on the same entry waiting forever here because SWAP_HAS_CACHE
379 		 * is set but the folio is not the swap cache yet. This can
380 		 * happen today if mem_cgroup_swapin_charge_folio() below
381 		 * triggers reclaim through zswap, which may call
382 		 * __read_swap_cache_async() in the writeback path.
383 		 */
384 		if (skip_if_exists)
385 			goto put_and_return;
386 
387 		/*
388 		 * We might race against __delete_from_swap_cache(), and
389 		 * stumble across a swap_map entry whose SWAP_HAS_CACHE
390 		 * has not yet been cleared.  Or race against another
391 		 * __read_swap_cache_async(), which has set SWAP_HAS_CACHE
392 		 * in swap_map, but not yet added its folio to swap cache.
393 		 */
394 		schedule_timeout_uninterruptible(1);
395 	}
396 
397 	/*
398 	 * The swap entry is ours to swap in. Prepare the new folio.
399 	 */
400 	__folio_set_locked(new_folio);
401 	__folio_set_swapbacked(new_folio);
402 
403 	if (mem_cgroup_swapin_charge_folio(new_folio, NULL, gfp_mask, entry))
404 		goto fail_unlock;
405 
406 	/* May fail (-ENOMEM) if XArray node allocation failed. */
407 	if (add_to_swap_cache(new_folio, entry, gfp_mask & GFP_RECLAIM_MASK, &shadow))
408 		goto fail_unlock;
409 
410 	memcg1_swapin(entry, 1);
411 
412 	if (shadow)
413 		workingset_refault(new_folio, shadow);
414 
415 	/* Caller will initiate read into locked new_folio */
416 	folio_add_lru(new_folio);
417 	*new_page_allocated = true;
418 	folio = new_folio;
419 got_folio:
420 	result = folio;
421 	goto put_and_return;
422 
423 fail_unlock:
424 	put_swap_folio(new_folio, entry);
425 	folio_unlock(new_folio);
426 put_and_return:
427 	if (!(*new_page_allocated) && new_folio)
428 		folio_put(new_folio);
429 	return result;
430 }
431 
432 /*
433  * Locate a page of swap in physical memory, reserving swap cache space
434  * and reading the disk if it is not already cached.
435  * A failure return means that either the page allocation failed or that
436  * the swap entry is no longer in use.
437  *
438  * get/put_swap_device() aren't needed to call this function, because
439  * __read_swap_cache_async() call them and swap_read_folio() holds the
440  * swap cache folio lock.
441  */
442 struct folio *read_swap_cache_async(swp_entry_t entry, gfp_t gfp_mask,
443 		struct vm_area_struct *vma, unsigned long addr,
444 		struct swap_iocb **plug)
445 {
446 	struct swap_info_struct *si;
447 	bool page_allocated;
448 	struct mempolicy *mpol;
449 	pgoff_t ilx;
450 	struct folio *folio;
451 
452 	si = get_swap_device(entry);
453 	if (!si)
454 		return NULL;
455 
456 	mpol = get_vma_policy(vma, addr, 0, &ilx);
457 	folio = __read_swap_cache_async(entry, gfp_mask, mpol, ilx,
458 					&page_allocated, false);
459 	mpol_cond_put(mpol);
460 
461 	if (page_allocated)
462 		swap_read_folio(folio, plug);
463 
464 	put_swap_device(si);
465 	return folio;
466 }
467 
468 static unsigned int __swapin_nr_pages(unsigned long prev_offset,
469 				      unsigned long offset,
470 				      int hits,
471 				      int max_pages,
472 				      int prev_win)
473 {
474 	unsigned int pages, last_ra;
475 
476 	/*
477 	 * This heuristic has been found to work well on both sequential and
478 	 * random loads, swapping to hard disk or to SSD: please don't ask
479 	 * what the "+ 2" means, it just happens to work well, that's all.
480 	 */
481 	pages = hits + 2;
482 	if (pages == 2) {
483 		/*
484 		 * We can have no readahead hits to judge by: but must not get
485 		 * stuck here forever, so check for an adjacent offset instead
486 		 * (and don't even bother to check whether swap type is same).
487 		 */
488 		if (offset != prev_offset + 1 && offset != prev_offset - 1)
489 			pages = 1;
490 	} else {
491 		unsigned int roundup = 4;
492 		while (roundup < pages)
493 			roundup <<= 1;
494 		pages = roundup;
495 	}
496 
497 	if (pages > max_pages)
498 		pages = max_pages;
499 
500 	/* Don't shrink readahead too fast */
501 	last_ra = prev_win / 2;
502 	if (pages < last_ra)
503 		pages = last_ra;
504 
505 	return pages;
506 }
507 
508 static unsigned long swapin_nr_pages(unsigned long offset)
509 {
510 	static unsigned long prev_offset;
511 	unsigned int hits, pages, max_pages;
512 	static atomic_t last_readahead_pages;
513 
514 	max_pages = 1 << READ_ONCE(page_cluster);
515 	if (max_pages <= 1)
516 		return 1;
517 
518 	hits = atomic_xchg(&swapin_readahead_hits, 0);
519 	pages = __swapin_nr_pages(READ_ONCE(prev_offset), offset, hits,
520 				  max_pages,
521 				  atomic_read(&last_readahead_pages));
522 	if (!hits)
523 		WRITE_ONCE(prev_offset, offset);
524 	atomic_set(&last_readahead_pages, pages);
525 
526 	return pages;
527 }
528 
529 /**
530  * swap_cluster_readahead - swap in pages in hope we need them soon
531  * @entry: swap entry of this memory
532  * @gfp_mask: memory allocation flags
533  * @mpol: NUMA memory allocation policy to be applied
534  * @ilx: NUMA interleave index, for use only when MPOL_INTERLEAVE
535  *
536  * Returns the struct folio for entry and addr, after queueing swapin.
537  *
538  * Primitive swap readahead code. We simply read an aligned block of
539  * (1 << page_cluster) entries in the swap area. This method is chosen
540  * because it doesn't cost us any seek time.  We also make sure to queue
541  * the 'original' request together with the readahead ones...
542  *
543  * Note: it is intentional that the same NUMA policy and interleave index
544  * are used for every page of the readahead: neighbouring pages on swap
545  * are fairly likely to have been swapped out from the same node.
546  */
547 struct folio *swap_cluster_readahead(swp_entry_t entry, gfp_t gfp_mask,
548 				    struct mempolicy *mpol, pgoff_t ilx)
549 {
550 	struct folio *folio;
551 	unsigned long entry_offset = swp_offset(entry);
552 	unsigned long offset = entry_offset;
553 	unsigned long start_offset, end_offset;
554 	unsigned long mask;
555 	struct swap_info_struct *si = swp_swap_info(entry);
556 	struct blk_plug plug;
557 	struct swap_iocb *splug = NULL;
558 	bool page_allocated;
559 
560 	mask = swapin_nr_pages(offset) - 1;
561 	if (!mask)
562 		goto skip;
563 
564 	/* Read a page_cluster sized and aligned cluster around offset. */
565 	start_offset = offset & ~mask;
566 	end_offset = offset | mask;
567 	if (!start_offset)	/* First page is swap header. */
568 		start_offset++;
569 	if (end_offset >= si->max)
570 		end_offset = si->max - 1;
571 
572 	blk_start_plug(&plug);
573 	for (offset = start_offset; offset <= end_offset ; offset++) {
574 		/* Ok, do the async read-ahead now */
575 		folio = __read_swap_cache_async(
576 				swp_entry(swp_type(entry), offset),
577 				gfp_mask, mpol, ilx, &page_allocated, false);
578 		if (!folio)
579 			continue;
580 		if (page_allocated) {
581 			swap_read_folio(folio, &splug);
582 			if (offset != entry_offset) {
583 				folio_set_readahead(folio);
584 				count_vm_event(SWAP_RA);
585 			}
586 		}
587 		folio_put(folio);
588 	}
589 	blk_finish_plug(&plug);
590 	swap_read_unplug(splug);
591 	lru_add_drain();	/* Push any new pages onto the LRU now */
592 skip:
593 	/* The page was likely read above, so no need for plugging here */
594 	folio = __read_swap_cache_async(entry, gfp_mask, mpol, ilx,
595 					&page_allocated, false);
596 	if (unlikely(page_allocated))
597 		swap_read_folio(folio, NULL);
598 	return folio;
599 }
600 
601 int init_swap_address_space(unsigned int type, unsigned long nr_pages)
602 {
603 	struct address_space *spaces, *space;
604 	unsigned int i, nr;
605 
606 	nr = DIV_ROUND_UP(nr_pages, SWAP_ADDRESS_SPACE_PAGES);
607 	spaces = kvcalloc(nr, sizeof(struct address_space), GFP_KERNEL);
608 	if (!spaces)
609 		return -ENOMEM;
610 	for (i = 0; i < nr; i++) {
611 		space = spaces + i;
612 		xa_init_flags(&space->i_pages, XA_FLAGS_LOCK_IRQ);
613 		atomic_set(&space->i_mmap_writable, 0);
614 		space->a_ops = &swap_aops;
615 		/* swap cache doesn't use writeback related tags */
616 		mapping_set_no_writeback_tags(space);
617 	}
618 	nr_swapper_spaces[type] = nr;
619 	swapper_spaces[type] = spaces;
620 
621 	return 0;
622 }
623 
624 void exit_swap_address_space(unsigned int type)
625 {
626 	int i;
627 	struct address_space *spaces = swapper_spaces[type];
628 
629 	for (i = 0; i < nr_swapper_spaces[type]; i++)
630 		VM_WARN_ON_ONCE(!mapping_empty(&spaces[i]));
631 	kvfree(spaces);
632 	nr_swapper_spaces[type] = 0;
633 	swapper_spaces[type] = NULL;
634 }
635 
636 static int swap_vma_ra_win(struct vm_fault *vmf, unsigned long *start,
637 			   unsigned long *end)
638 {
639 	struct vm_area_struct *vma = vmf->vma;
640 	unsigned long ra_val;
641 	unsigned long faddr, prev_faddr, left, right;
642 	unsigned int max_win, hits, prev_win, win;
643 
644 	max_win = 1 << min(READ_ONCE(page_cluster), SWAP_RA_ORDER_CEILING);
645 	if (max_win == 1)
646 		return 1;
647 
648 	faddr = vmf->address;
649 	ra_val = GET_SWAP_RA_VAL(vma);
650 	prev_faddr = SWAP_RA_ADDR(ra_val);
651 	prev_win = SWAP_RA_WIN(ra_val);
652 	hits = SWAP_RA_HITS(ra_val);
653 	win = __swapin_nr_pages(PFN_DOWN(prev_faddr), PFN_DOWN(faddr), hits,
654 				max_win, prev_win);
655 	atomic_long_set(&vma->swap_readahead_info, SWAP_RA_VAL(faddr, win, 0));
656 	if (win == 1)
657 		return 1;
658 
659 	if (faddr == prev_faddr + PAGE_SIZE)
660 		left = faddr;
661 	else if (prev_faddr == faddr + PAGE_SIZE)
662 		left = faddr - (win << PAGE_SHIFT) + PAGE_SIZE;
663 	else
664 		left = faddr - (((win - 1) / 2) << PAGE_SHIFT);
665 	right = left + (win << PAGE_SHIFT);
666 	if ((long)left < 0)
667 		left = 0;
668 	*start = max3(left, vma->vm_start, faddr & PMD_MASK);
669 	*end = min3(right, vma->vm_end, (faddr & PMD_MASK) + PMD_SIZE);
670 
671 	return win;
672 }
673 
674 /**
675  * swap_vma_readahead - swap in pages in hope we need them soon
676  * @targ_entry: swap entry of the targeted memory
677  * @gfp_mask: memory allocation flags
678  * @mpol: NUMA memory allocation policy to be applied
679  * @targ_ilx: NUMA interleave index, for use only when MPOL_INTERLEAVE
680  * @vmf: fault information
681  *
682  * Returns the struct folio for entry and addr, after queueing swapin.
683  *
684  * Primitive swap readahead code. We simply read in a few pages whose
685  * virtual addresses are around the fault address in the same vma.
686  *
687  * Caller must hold read mmap_lock if vmf->vma is not NULL.
688  *
689  */
690 static struct folio *swap_vma_readahead(swp_entry_t targ_entry, gfp_t gfp_mask,
691 		struct mempolicy *mpol, pgoff_t targ_ilx, struct vm_fault *vmf)
692 {
693 	struct blk_plug plug;
694 	struct swap_iocb *splug = NULL;
695 	struct folio *folio;
696 	pte_t *pte = NULL, pentry;
697 	int win;
698 	unsigned long start, end, addr;
699 	swp_entry_t entry;
700 	pgoff_t ilx;
701 	bool page_allocated;
702 
703 	win = swap_vma_ra_win(vmf, &start, &end);
704 	if (win == 1)
705 		goto skip;
706 
707 	ilx = targ_ilx - PFN_DOWN(vmf->address - start);
708 
709 	blk_start_plug(&plug);
710 	for (addr = start; addr < end; ilx++, addr += PAGE_SIZE) {
711 		if (!pte++) {
712 			pte = pte_offset_map(vmf->pmd, addr);
713 			if (!pte)
714 				break;
715 		}
716 		pentry = ptep_get_lockless(pte);
717 		if (!is_swap_pte(pentry))
718 			continue;
719 		entry = pte_to_swp_entry(pentry);
720 		if (unlikely(non_swap_entry(entry)))
721 			continue;
722 		pte_unmap(pte);
723 		pte = NULL;
724 		folio = __read_swap_cache_async(entry, gfp_mask, mpol, ilx,
725 						&page_allocated, false);
726 		if (!folio)
727 			continue;
728 		if (page_allocated) {
729 			swap_read_folio(folio, &splug);
730 			if (addr != vmf->address) {
731 				folio_set_readahead(folio);
732 				count_vm_event(SWAP_RA);
733 			}
734 		}
735 		folio_put(folio);
736 	}
737 	if (pte)
738 		pte_unmap(pte);
739 	blk_finish_plug(&plug);
740 	swap_read_unplug(splug);
741 	lru_add_drain();
742 skip:
743 	/* The folio was likely read above, so no need for plugging here */
744 	folio = __read_swap_cache_async(targ_entry, gfp_mask, mpol, targ_ilx,
745 					&page_allocated, false);
746 	if (unlikely(page_allocated))
747 		swap_read_folio(folio, NULL);
748 	return folio;
749 }
750 
751 /**
752  * swapin_readahead - swap in pages in hope we need them soon
753  * @entry: swap entry of this memory
754  * @gfp_mask: memory allocation flags
755  * @vmf: fault information
756  *
757  * Returns the struct folio for entry and addr, after queueing swapin.
758  *
759  * It's a main entry function for swap readahead. By the configuration,
760  * it will read ahead blocks by cluster-based(ie, physical disk based)
761  * or vma-based(ie, virtual address based on faulty address) readahead.
762  */
763 struct folio *swapin_readahead(swp_entry_t entry, gfp_t gfp_mask,
764 				struct vm_fault *vmf)
765 {
766 	struct mempolicy *mpol;
767 	pgoff_t ilx;
768 	struct folio *folio;
769 
770 	mpol = get_vma_policy(vmf->vma, vmf->address, 0, &ilx);
771 	folio = swap_use_vma_readahead() ?
772 		swap_vma_readahead(entry, gfp_mask, mpol, ilx, vmf) :
773 		swap_cluster_readahead(entry, gfp_mask, mpol, ilx);
774 	mpol_cond_put(mpol);
775 
776 	return folio;
777 }
778 
779 #ifdef CONFIG_SYSFS
780 static ssize_t vma_ra_enabled_show(struct kobject *kobj,
781 				     struct kobj_attribute *attr, char *buf)
782 {
783 	return sysfs_emit(buf, "%s\n", str_true_false(enable_vma_readahead));
784 }
785 static ssize_t vma_ra_enabled_store(struct kobject *kobj,
786 				      struct kobj_attribute *attr,
787 				      const char *buf, size_t count)
788 {
789 	ssize_t ret;
790 
791 	ret = kstrtobool(buf, &enable_vma_readahead);
792 	if (ret)
793 		return ret;
794 
795 	return count;
796 }
797 static struct kobj_attribute vma_ra_enabled_attr = __ATTR_RW(vma_ra_enabled);
798 
799 static struct attribute *swap_attrs[] = {
800 	&vma_ra_enabled_attr.attr,
801 	NULL,
802 };
803 
804 static const struct attribute_group swap_attr_group = {
805 	.attrs = swap_attrs,
806 };
807 
808 static int __init swap_init_sysfs(void)
809 {
810 	int err;
811 	struct kobject *swap_kobj;
812 
813 	swap_kobj = kobject_create_and_add("swap", mm_kobj);
814 	if (!swap_kobj) {
815 		pr_err("failed to create swap kobject\n");
816 		return -ENOMEM;
817 	}
818 	err = sysfs_create_group(swap_kobj, &swap_attr_group);
819 	if (err) {
820 		pr_err("failed to register swap group\n");
821 		goto delete_obj;
822 	}
823 	return 0;
824 
825 delete_obj:
826 	kobject_put(swap_kobj);
827 	return err;
828 }
829 subsys_initcall(swap_init_sysfs);
830 #endif
831