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