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