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