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