xref: /linux/mm/swap_state.c (revision 00c010e130e58301db2ea0cec1eadc931e1cb8cf)
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 
show_swap_cache_info(void)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 
get_shadow_from_swap_cache(swp_entry_t entry)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  */
add_to_swap_cache(struct folio * folio,swp_entry_t entry,gfp_t gfp,void ** shadowp)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  */
__delete_from_swap_cache(struct folio * folio,swp_entry_t entry,void * shadow)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  */
delete_from_swap_cache(struct folio * folio)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 
clear_shadow_from_swap_cache(int type,unsigned long begin,unsigned long end)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  */
free_swap_cache(struct folio * folio)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  */
free_folio_and_swap_cache(struct folio * folio)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  */
free_pages_and_swap_cache(struct encoded_page ** pages,int nr)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 
swap_use_vma_readahead(void)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  */
swap_cache_get_folio(swp_entry_t entry,struct vm_area_struct * vma,unsigned long addr)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 /**
327  * filemap_get_incore_folio - Find and get a folio from the page or swap caches.
328  * @mapping: The address_space to search.
329  * @index: The page cache index.
330  *
331  * This differs from filemap_get_folio() in that it will also look for the
332  * folio in the swap cache.
333  *
334  * Return: The found folio or %NULL.
335  */
filemap_get_incore_folio(struct address_space * mapping,pgoff_t index)336 struct folio *filemap_get_incore_folio(struct address_space *mapping,
337 		pgoff_t index)
338 {
339 	swp_entry_t swp;
340 	struct swap_info_struct *si;
341 	struct folio *folio = filemap_get_entry(mapping, index);
342 
343 	if (!folio)
344 		return ERR_PTR(-ENOENT);
345 	if (!xa_is_value(folio))
346 		return folio;
347 	if (!shmem_mapping(mapping))
348 		return ERR_PTR(-ENOENT);
349 
350 	swp = radix_to_swp_entry(folio);
351 	/* There might be swapin error entries in shmem mapping. */
352 	if (non_swap_entry(swp))
353 		return ERR_PTR(-ENOENT);
354 	/* Prevent swapoff from happening to us */
355 	si = get_swap_device(swp);
356 	if (!si)
357 		return ERR_PTR(-ENOENT);
358 	index = swap_cache_index(swp);
359 	folio = filemap_get_folio(swap_address_space(swp), index);
360 	put_swap_device(si);
361 	return folio;
362 }
363 
__read_swap_cache_async(swp_entry_t entry,gfp_t gfp_mask,struct mempolicy * mpol,pgoff_t ilx,bool * new_page_allocated,bool skip_if_exists)364 struct folio *__read_swap_cache_async(swp_entry_t entry, gfp_t gfp_mask,
365 		struct mempolicy *mpol, pgoff_t ilx, bool *new_page_allocated,
366 		bool skip_if_exists)
367 {
368 	struct swap_info_struct *si = swp_swap_info(entry);
369 	struct folio *folio;
370 	struct folio *new_folio = NULL;
371 	struct folio *result = NULL;
372 	void *shadow = NULL;
373 
374 	*new_page_allocated = false;
375 	for (;;) {
376 		int err;
377 		/*
378 		 * First check the swap cache.  Since this is normally
379 		 * called after swap_cache_get_folio() failed, re-calling
380 		 * that would confuse statistics.
381 		 */
382 		folio = filemap_get_folio(swap_address_space(entry),
383 					  swap_cache_index(entry));
384 		if (!IS_ERR(folio))
385 			goto got_folio;
386 
387 		/*
388 		 * Just skip read ahead for unused swap slot.
389 		 */
390 		if (!swap_entry_swapped(si, entry))
391 			goto put_and_return;
392 
393 		/*
394 		 * Get a new folio to read into from swap.  Allocate it now if
395 		 * new_folio not exist, before marking swap_map SWAP_HAS_CACHE,
396 		 * when -EEXIST will cause any racers to loop around until we
397 		 * add it to cache.
398 		 */
399 		if (!new_folio) {
400 			new_folio = folio_alloc_mpol(gfp_mask, 0, mpol, ilx, numa_node_id());
401 			if (!new_folio)
402 				goto put_and_return;
403 		}
404 
405 		/*
406 		 * Swap entry may have been freed since our caller observed it.
407 		 */
408 		err = swapcache_prepare(entry, 1);
409 		if (!err)
410 			break;
411 		else if (err != -EEXIST)
412 			goto put_and_return;
413 
414 		/*
415 		 * Protect against a recursive call to __read_swap_cache_async()
416 		 * on the same entry waiting forever here because SWAP_HAS_CACHE
417 		 * is set but the folio is not the swap cache yet. This can
418 		 * happen today if mem_cgroup_swapin_charge_folio() below
419 		 * triggers reclaim through zswap, which may call
420 		 * __read_swap_cache_async() in the writeback path.
421 		 */
422 		if (skip_if_exists)
423 			goto put_and_return;
424 
425 		/*
426 		 * We might race against __delete_from_swap_cache(), and
427 		 * stumble across a swap_map entry whose SWAP_HAS_CACHE
428 		 * has not yet been cleared.  Or race against another
429 		 * __read_swap_cache_async(), which has set SWAP_HAS_CACHE
430 		 * in swap_map, but not yet added its folio to swap cache.
431 		 */
432 		schedule_timeout_uninterruptible(1);
433 	}
434 
435 	/*
436 	 * The swap entry is ours to swap in. Prepare the new folio.
437 	 */
438 	__folio_set_locked(new_folio);
439 	__folio_set_swapbacked(new_folio);
440 
441 	if (mem_cgroup_swapin_charge_folio(new_folio, NULL, gfp_mask, entry))
442 		goto fail_unlock;
443 
444 	/* May fail (-ENOMEM) if XArray node allocation failed. */
445 	if (add_to_swap_cache(new_folio, entry, gfp_mask & GFP_RECLAIM_MASK, &shadow))
446 		goto fail_unlock;
447 
448 	memcg1_swapin(entry, 1);
449 
450 	if (shadow)
451 		workingset_refault(new_folio, shadow);
452 
453 	/* Caller will initiate read into locked new_folio */
454 	folio_add_lru(new_folio);
455 	*new_page_allocated = true;
456 	folio = new_folio;
457 got_folio:
458 	result = folio;
459 	goto put_and_return;
460 
461 fail_unlock:
462 	put_swap_folio(new_folio, entry);
463 	folio_unlock(new_folio);
464 put_and_return:
465 	if (!(*new_page_allocated) && new_folio)
466 		folio_put(new_folio);
467 	return result;
468 }
469 
470 /*
471  * Locate a page of swap in physical memory, reserving swap cache space
472  * and reading the disk if it is not already cached.
473  * A failure return means that either the page allocation failed or that
474  * the swap entry is no longer in use.
475  *
476  * get/put_swap_device() aren't needed to call this function, because
477  * __read_swap_cache_async() call them and swap_read_folio() holds the
478  * swap cache folio lock.
479  */
read_swap_cache_async(swp_entry_t entry,gfp_t gfp_mask,struct vm_area_struct * vma,unsigned long addr,struct swap_iocb ** plug)480 struct folio *read_swap_cache_async(swp_entry_t entry, gfp_t gfp_mask,
481 		struct vm_area_struct *vma, unsigned long addr,
482 		struct swap_iocb **plug)
483 {
484 	struct swap_info_struct *si;
485 	bool page_allocated;
486 	struct mempolicy *mpol;
487 	pgoff_t ilx;
488 	struct folio *folio;
489 
490 	si = get_swap_device(entry);
491 	if (!si)
492 		return NULL;
493 
494 	mpol = get_vma_policy(vma, addr, 0, &ilx);
495 	folio = __read_swap_cache_async(entry, gfp_mask, mpol, ilx,
496 					&page_allocated, false);
497 	mpol_cond_put(mpol);
498 
499 	if (page_allocated)
500 		swap_read_folio(folio, plug);
501 
502 	put_swap_device(si);
503 	return folio;
504 }
505 
__swapin_nr_pages(unsigned long prev_offset,unsigned long offset,int hits,int max_pages,int prev_win)506 static unsigned int __swapin_nr_pages(unsigned long prev_offset,
507 				      unsigned long offset,
508 				      int hits,
509 				      int max_pages,
510 				      int prev_win)
511 {
512 	unsigned int pages, last_ra;
513 
514 	/*
515 	 * This heuristic has been found to work well on both sequential and
516 	 * random loads, swapping to hard disk or to SSD: please don't ask
517 	 * what the "+ 2" means, it just happens to work well, that's all.
518 	 */
519 	pages = hits + 2;
520 	if (pages == 2) {
521 		/*
522 		 * We can have no readahead hits to judge by: but must not get
523 		 * stuck here forever, so check for an adjacent offset instead
524 		 * (and don't even bother to check whether swap type is same).
525 		 */
526 		if (offset != prev_offset + 1 && offset != prev_offset - 1)
527 			pages = 1;
528 	} else {
529 		unsigned int roundup = 4;
530 		while (roundup < pages)
531 			roundup <<= 1;
532 		pages = roundup;
533 	}
534 
535 	if (pages > max_pages)
536 		pages = max_pages;
537 
538 	/* Don't shrink readahead too fast */
539 	last_ra = prev_win / 2;
540 	if (pages < last_ra)
541 		pages = last_ra;
542 
543 	return pages;
544 }
545 
swapin_nr_pages(unsigned long offset)546 static unsigned long swapin_nr_pages(unsigned long offset)
547 {
548 	static unsigned long prev_offset;
549 	unsigned int hits, pages, max_pages;
550 	static atomic_t last_readahead_pages;
551 
552 	max_pages = 1 << READ_ONCE(page_cluster);
553 	if (max_pages <= 1)
554 		return 1;
555 
556 	hits = atomic_xchg(&swapin_readahead_hits, 0);
557 	pages = __swapin_nr_pages(READ_ONCE(prev_offset), offset, hits,
558 				  max_pages,
559 				  atomic_read(&last_readahead_pages));
560 	if (!hits)
561 		WRITE_ONCE(prev_offset, offset);
562 	atomic_set(&last_readahead_pages, pages);
563 
564 	return pages;
565 }
566 
567 /**
568  * swap_cluster_readahead - swap in pages in hope we need them soon
569  * @entry: swap entry of this memory
570  * @gfp_mask: memory allocation flags
571  * @mpol: NUMA memory allocation policy to be applied
572  * @ilx: NUMA interleave index, for use only when MPOL_INTERLEAVE
573  *
574  * Returns the struct folio for entry and addr, after queueing swapin.
575  *
576  * Primitive swap readahead code. We simply read an aligned block of
577  * (1 << page_cluster) entries in the swap area. This method is chosen
578  * because it doesn't cost us any seek time.  We also make sure to queue
579  * the 'original' request together with the readahead ones...
580  *
581  * Note: it is intentional that the same NUMA policy and interleave index
582  * are used for every page of the readahead: neighbouring pages on swap
583  * are fairly likely to have been swapped out from the same node.
584  */
swap_cluster_readahead(swp_entry_t entry,gfp_t gfp_mask,struct mempolicy * mpol,pgoff_t ilx)585 struct folio *swap_cluster_readahead(swp_entry_t entry, gfp_t gfp_mask,
586 				    struct mempolicy *mpol, pgoff_t ilx)
587 {
588 	struct folio *folio;
589 	unsigned long entry_offset = swp_offset(entry);
590 	unsigned long offset = entry_offset;
591 	unsigned long start_offset, end_offset;
592 	unsigned long mask;
593 	struct swap_info_struct *si = swp_swap_info(entry);
594 	struct blk_plug plug;
595 	struct swap_iocb *splug = NULL;
596 	bool page_allocated;
597 
598 	mask = swapin_nr_pages(offset) - 1;
599 	if (!mask)
600 		goto skip;
601 
602 	/* Read a page_cluster sized and aligned cluster around offset. */
603 	start_offset = offset & ~mask;
604 	end_offset = offset | mask;
605 	if (!start_offset)	/* First page is swap header. */
606 		start_offset++;
607 	if (end_offset >= si->max)
608 		end_offset = si->max - 1;
609 
610 	blk_start_plug(&plug);
611 	for (offset = start_offset; offset <= end_offset ; offset++) {
612 		/* Ok, do the async read-ahead now */
613 		folio = __read_swap_cache_async(
614 				swp_entry(swp_type(entry), offset),
615 				gfp_mask, mpol, ilx, &page_allocated, false);
616 		if (!folio)
617 			continue;
618 		if (page_allocated) {
619 			swap_read_folio(folio, &splug);
620 			if (offset != entry_offset) {
621 				folio_set_readahead(folio);
622 				count_vm_event(SWAP_RA);
623 			}
624 		}
625 		folio_put(folio);
626 	}
627 	blk_finish_plug(&plug);
628 	swap_read_unplug(splug);
629 	lru_add_drain();	/* Push any new pages onto the LRU now */
630 skip:
631 	/* The page was likely read above, so no need for plugging here */
632 	folio = __read_swap_cache_async(entry, gfp_mask, mpol, ilx,
633 					&page_allocated, false);
634 	if (unlikely(page_allocated))
635 		swap_read_folio(folio, NULL);
636 	return folio;
637 }
638 
init_swap_address_space(unsigned int type,unsigned long nr_pages)639 int init_swap_address_space(unsigned int type, unsigned long nr_pages)
640 {
641 	struct address_space *spaces, *space;
642 	unsigned int i, nr;
643 
644 	nr = DIV_ROUND_UP(nr_pages, SWAP_ADDRESS_SPACE_PAGES);
645 	spaces = kvcalloc(nr, sizeof(struct address_space), GFP_KERNEL);
646 	if (!spaces)
647 		return -ENOMEM;
648 	for (i = 0; i < nr; i++) {
649 		space = spaces + i;
650 		xa_init_flags(&space->i_pages, XA_FLAGS_LOCK_IRQ);
651 		atomic_set(&space->i_mmap_writable, 0);
652 		space->a_ops = &swap_aops;
653 		/* swap cache doesn't use writeback related tags */
654 		mapping_set_no_writeback_tags(space);
655 	}
656 	nr_swapper_spaces[type] = nr;
657 	swapper_spaces[type] = spaces;
658 
659 	return 0;
660 }
661 
exit_swap_address_space(unsigned int type)662 void exit_swap_address_space(unsigned int type)
663 {
664 	int i;
665 	struct address_space *spaces = swapper_spaces[type];
666 
667 	for (i = 0; i < nr_swapper_spaces[type]; i++)
668 		VM_WARN_ON_ONCE(!mapping_empty(&spaces[i]));
669 	kvfree(spaces);
670 	nr_swapper_spaces[type] = 0;
671 	swapper_spaces[type] = NULL;
672 }
673 
swap_vma_ra_win(struct vm_fault * vmf,unsigned long * start,unsigned long * end)674 static int swap_vma_ra_win(struct vm_fault *vmf, unsigned long *start,
675 			   unsigned long *end)
676 {
677 	struct vm_area_struct *vma = vmf->vma;
678 	unsigned long ra_val;
679 	unsigned long faddr, prev_faddr, left, right;
680 	unsigned int max_win, hits, prev_win, win;
681 
682 	max_win = 1 << min(READ_ONCE(page_cluster), SWAP_RA_ORDER_CEILING);
683 	if (max_win == 1)
684 		return 1;
685 
686 	faddr = vmf->address;
687 	ra_val = GET_SWAP_RA_VAL(vma);
688 	prev_faddr = SWAP_RA_ADDR(ra_val);
689 	prev_win = SWAP_RA_WIN(ra_val);
690 	hits = SWAP_RA_HITS(ra_val);
691 	win = __swapin_nr_pages(PFN_DOWN(prev_faddr), PFN_DOWN(faddr), hits,
692 				max_win, prev_win);
693 	atomic_long_set(&vma->swap_readahead_info, SWAP_RA_VAL(faddr, win, 0));
694 	if (win == 1)
695 		return 1;
696 
697 	if (faddr == prev_faddr + PAGE_SIZE)
698 		left = faddr;
699 	else if (prev_faddr == faddr + PAGE_SIZE)
700 		left = faddr - (win << PAGE_SHIFT) + PAGE_SIZE;
701 	else
702 		left = faddr - (((win - 1) / 2) << PAGE_SHIFT);
703 	right = left + (win << PAGE_SHIFT);
704 	if ((long)left < 0)
705 		left = 0;
706 	*start = max3(left, vma->vm_start, faddr & PMD_MASK);
707 	*end = min3(right, vma->vm_end, (faddr & PMD_MASK) + PMD_SIZE);
708 
709 	return win;
710 }
711 
712 /**
713  * swap_vma_readahead - swap in pages in hope we need them soon
714  * @targ_entry: swap entry of the targeted memory
715  * @gfp_mask: memory allocation flags
716  * @mpol: NUMA memory allocation policy to be applied
717  * @targ_ilx: NUMA interleave index, for use only when MPOL_INTERLEAVE
718  * @vmf: fault information
719  *
720  * Returns the struct folio for entry and addr, after queueing swapin.
721  *
722  * Primitive swap readahead code. We simply read in a few pages whose
723  * virtual addresses are around the fault address in the same vma.
724  *
725  * Caller must hold read mmap_lock if vmf->vma is not NULL.
726  *
727  */
swap_vma_readahead(swp_entry_t targ_entry,gfp_t gfp_mask,struct mempolicy * mpol,pgoff_t targ_ilx,struct vm_fault * vmf)728 static struct folio *swap_vma_readahead(swp_entry_t targ_entry, gfp_t gfp_mask,
729 		struct mempolicy *mpol, pgoff_t targ_ilx, struct vm_fault *vmf)
730 {
731 	struct blk_plug plug;
732 	struct swap_iocb *splug = NULL;
733 	struct folio *folio;
734 	pte_t *pte = NULL, pentry;
735 	int win;
736 	unsigned long start, end, addr;
737 	swp_entry_t entry;
738 	pgoff_t ilx;
739 	bool page_allocated;
740 
741 	win = swap_vma_ra_win(vmf, &start, &end);
742 	if (win == 1)
743 		goto skip;
744 
745 	ilx = targ_ilx - PFN_DOWN(vmf->address - start);
746 
747 	blk_start_plug(&plug);
748 	for (addr = start; addr < end; ilx++, addr += PAGE_SIZE) {
749 		if (!pte++) {
750 			pte = pte_offset_map(vmf->pmd, addr);
751 			if (!pte)
752 				break;
753 		}
754 		pentry = ptep_get_lockless(pte);
755 		if (!is_swap_pte(pentry))
756 			continue;
757 		entry = pte_to_swp_entry(pentry);
758 		if (unlikely(non_swap_entry(entry)))
759 			continue;
760 		pte_unmap(pte);
761 		pte = NULL;
762 		folio = __read_swap_cache_async(entry, gfp_mask, mpol, ilx,
763 						&page_allocated, false);
764 		if (!folio)
765 			continue;
766 		if (page_allocated) {
767 			swap_read_folio(folio, &splug);
768 			if (addr != vmf->address) {
769 				folio_set_readahead(folio);
770 				count_vm_event(SWAP_RA);
771 			}
772 		}
773 		folio_put(folio);
774 	}
775 	if (pte)
776 		pte_unmap(pte);
777 	blk_finish_plug(&plug);
778 	swap_read_unplug(splug);
779 	lru_add_drain();
780 skip:
781 	/* The folio was likely read above, so no need for plugging here */
782 	folio = __read_swap_cache_async(targ_entry, gfp_mask, mpol, targ_ilx,
783 					&page_allocated, false);
784 	if (unlikely(page_allocated))
785 		swap_read_folio(folio, NULL);
786 	return folio;
787 }
788 
789 /**
790  * swapin_readahead - swap in pages in hope we need them soon
791  * @entry: swap entry of this memory
792  * @gfp_mask: memory allocation flags
793  * @vmf: fault information
794  *
795  * Returns the struct folio for entry and addr, after queueing swapin.
796  *
797  * It's a main entry function for swap readahead. By the configuration,
798  * it will read ahead blocks by cluster-based(ie, physical disk based)
799  * or vma-based(ie, virtual address based on faulty address) readahead.
800  */
swapin_readahead(swp_entry_t entry,gfp_t gfp_mask,struct vm_fault * vmf)801 struct folio *swapin_readahead(swp_entry_t entry, gfp_t gfp_mask,
802 				struct vm_fault *vmf)
803 {
804 	struct mempolicy *mpol;
805 	pgoff_t ilx;
806 	struct folio *folio;
807 
808 	mpol = get_vma_policy(vmf->vma, vmf->address, 0, &ilx);
809 	folio = swap_use_vma_readahead() ?
810 		swap_vma_readahead(entry, gfp_mask, mpol, ilx, vmf) :
811 		swap_cluster_readahead(entry, gfp_mask, mpol, ilx);
812 	mpol_cond_put(mpol);
813 
814 	return folio;
815 }
816 
817 #ifdef CONFIG_SYSFS
vma_ra_enabled_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)818 static ssize_t vma_ra_enabled_show(struct kobject *kobj,
819 				     struct kobj_attribute *attr, char *buf)
820 {
821 	return sysfs_emit(buf, "%s\n", str_true_false(enable_vma_readahead));
822 }
vma_ra_enabled_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)823 static ssize_t vma_ra_enabled_store(struct kobject *kobj,
824 				      struct kobj_attribute *attr,
825 				      const char *buf, size_t count)
826 {
827 	ssize_t ret;
828 
829 	ret = kstrtobool(buf, &enable_vma_readahead);
830 	if (ret)
831 		return ret;
832 
833 	return count;
834 }
835 static struct kobj_attribute vma_ra_enabled_attr = __ATTR_RW(vma_ra_enabled);
836 
837 static struct attribute *swap_attrs[] = {
838 	&vma_ra_enabled_attr.attr,
839 	NULL,
840 };
841 
842 static const struct attribute_group swap_attr_group = {
843 	.attrs = swap_attrs,
844 };
845 
swap_init_sysfs(void)846 static int __init swap_init_sysfs(void)
847 {
848 	int err;
849 	struct kobject *swap_kobj;
850 
851 	swap_kobj = kobject_create_and_add("swap", mm_kobj);
852 	if (!swap_kobj) {
853 		pr_err("failed to create swap kobject\n");
854 		return -ENOMEM;
855 	}
856 	err = sysfs_create_group(swap_kobj, &swap_attr_group);
857 	if (err) {
858 		pr_err("failed to register swap group\n");
859 		goto delete_obj;
860 	}
861 	return 0;
862 
863 delete_obj:
864 	kobject_put(swap_kobj);
865 	return err;
866 }
867 subsys_initcall(swap_init_sysfs);
868 #endif
869