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/leafops.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_table.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 .dirty_folio = noop_dirty_folio,
35 #ifdef CONFIG_MIGRATION
36 .migrate_folio = migrate_folio,
37 #endif
38 };
39
40 struct address_space swap_space __read_mostly = {
41 .a_ops = &swap_aops,
42 };
43
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
75 /**
76 * swap_cache_get_folio - Looks up a folio in the swap cache.
77 * @entry: swap entry used for the lookup.
78 *
79 * A found folio will be returned unlocked and with its refcount increased.
80 *
81 * Context: Caller must ensure @entry is valid and protect the swap device
82 * with reference count or locks.
83 * Return: Returns the found folio on success, NULL otherwise. The caller
84 * must lock nd check if the folio still matches the swap entry before
85 * use (e.g., folio_matches_swap_entry).
86 */
swap_cache_get_folio(swp_entry_t entry)87 struct folio *swap_cache_get_folio(swp_entry_t entry)
88 {
89 unsigned long swp_tb;
90 struct folio *folio;
91
92 for (;;) {
93 swp_tb = swap_table_get(__swap_entry_to_cluster(entry),
94 swp_cluster_offset(entry));
95 if (!swp_tb_is_folio(swp_tb))
96 return NULL;
97 folio = swp_tb_to_folio(swp_tb);
98 if (likely(folio_try_get(folio)))
99 return folio;
100 }
101
102 return NULL;
103 }
104
105 /**
106 * swap_cache_get_shadow - Looks up a shadow in the swap cache.
107 * @entry: swap entry used for the lookup.
108 *
109 * Context: Caller must ensure @entry is valid and protect the swap device
110 * with reference count or locks.
111 * Return: Returns either NULL or an XA_VALUE (shadow).
112 */
swap_cache_get_shadow(swp_entry_t entry)113 void *swap_cache_get_shadow(swp_entry_t entry)
114 {
115 unsigned long swp_tb;
116
117 swp_tb = swap_table_get(__swap_entry_to_cluster(entry),
118 swp_cluster_offset(entry));
119 if (swp_tb_is_shadow(swp_tb))
120 return swp_tb_to_shadow(swp_tb);
121 return NULL;
122 }
123
124 /**
125 * swap_cache_add_folio - Add a folio into the swap cache.
126 * @folio: The folio to be added.
127 * @entry: The swap entry corresponding to the folio.
128 * @gfp: gfp_mask for XArray node allocation.
129 * @shadowp: If a shadow is found, return the shadow.
130 *
131 * Context: Caller must ensure @entry is valid and protect the swap device
132 * with reference count or locks.
133 * The caller also needs to update the corresponding swap_map slots with
134 * SWAP_HAS_CACHE bit to avoid race or conflict.
135 */
swap_cache_add_folio(struct folio * folio,swp_entry_t entry,void ** shadowp)136 void swap_cache_add_folio(struct folio *folio, swp_entry_t entry, void **shadowp)
137 {
138 void *shadow = NULL;
139 unsigned long old_tb, new_tb;
140 struct swap_cluster_info *ci;
141 unsigned int ci_start, ci_off, ci_end;
142 unsigned long nr_pages = folio_nr_pages(folio);
143
144 VM_WARN_ON_ONCE_FOLIO(!folio_test_locked(folio), folio);
145 VM_WARN_ON_ONCE_FOLIO(folio_test_swapcache(folio), folio);
146 VM_WARN_ON_ONCE_FOLIO(!folio_test_swapbacked(folio), folio);
147
148 new_tb = folio_to_swp_tb(folio);
149 ci_start = swp_cluster_offset(entry);
150 ci_end = ci_start + nr_pages;
151 ci_off = ci_start;
152 ci = swap_cluster_lock(__swap_entry_to_info(entry), swp_offset(entry));
153 do {
154 old_tb = __swap_table_xchg(ci, ci_off, new_tb);
155 WARN_ON_ONCE(swp_tb_is_folio(old_tb));
156 if (swp_tb_is_shadow(old_tb))
157 shadow = swp_tb_to_shadow(old_tb);
158 } while (++ci_off < ci_end);
159
160 folio_ref_add(folio, nr_pages);
161 folio_set_swapcache(folio);
162 folio->swap = entry;
163 swap_cluster_unlock(ci);
164
165 node_stat_mod_folio(folio, NR_FILE_PAGES, nr_pages);
166 lruvec_stat_mod_folio(folio, NR_SWAPCACHE, nr_pages);
167
168 if (shadowp)
169 *shadowp = shadow;
170 }
171
172 /**
173 * __swap_cache_del_folio - Removes a folio from the swap cache.
174 * @ci: The locked swap cluster.
175 * @folio: The folio.
176 * @entry: The first swap entry that the folio corresponds to.
177 * @shadow: shadow value to be filled in the swap cache.
178 *
179 * Removes a folio from the swap cache and fills a shadow in place.
180 * This won't put the folio's refcount. The caller has to do that.
181 *
182 * Context: Caller must ensure the folio is locked and in the swap cache
183 * using the index of @entry, and lock the cluster that holds the entries.
184 */
__swap_cache_del_folio(struct swap_cluster_info * ci,struct folio * folio,swp_entry_t entry,void * shadow)185 void __swap_cache_del_folio(struct swap_cluster_info *ci, struct folio *folio,
186 swp_entry_t entry, void *shadow)
187 {
188 unsigned long old_tb, new_tb;
189 unsigned int ci_start, ci_off, ci_end;
190 unsigned long nr_pages = folio_nr_pages(folio);
191
192 VM_WARN_ON_ONCE(__swap_entry_to_cluster(entry) != ci);
193 VM_WARN_ON_ONCE_FOLIO(!folio_test_locked(folio), folio);
194 VM_WARN_ON_ONCE_FOLIO(!folio_test_swapcache(folio), folio);
195 VM_WARN_ON_ONCE_FOLIO(folio_test_writeback(folio), folio);
196
197 new_tb = shadow_swp_to_tb(shadow);
198 ci_start = swp_cluster_offset(entry);
199 ci_end = ci_start + nr_pages;
200 ci_off = ci_start;
201 do {
202 /* If shadow is NULL, we sets an empty shadow */
203 old_tb = __swap_table_xchg(ci, ci_off, new_tb);
204 WARN_ON_ONCE(!swp_tb_is_folio(old_tb) ||
205 swp_tb_to_folio(old_tb) != folio);
206 } while (++ci_off < ci_end);
207
208 folio->swap.val = 0;
209 folio_clear_swapcache(folio);
210 node_stat_mod_folio(folio, NR_FILE_PAGES, -nr_pages);
211 lruvec_stat_mod_folio(folio, NR_SWAPCACHE, -nr_pages);
212 }
213
214 /**
215 * swap_cache_del_folio - Removes a folio from the swap cache.
216 * @folio: The folio.
217 *
218 * Same as __swap_cache_del_folio, but handles lock and refcount. The
219 * caller must ensure the folio is either clean or has a swap count
220 * equal to zero, or it may cause data loss.
221 *
222 * Context: Caller must ensure the folio is locked and in the swap cache.
223 */
swap_cache_del_folio(struct folio * folio)224 void swap_cache_del_folio(struct folio *folio)
225 {
226 struct swap_cluster_info *ci;
227 swp_entry_t entry = folio->swap;
228
229 ci = swap_cluster_lock(__swap_entry_to_info(entry), swp_offset(entry));
230 __swap_cache_del_folio(ci, folio, entry, NULL);
231 swap_cluster_unlock(ci);
232
233 put_swap_folio(folio, entry);
234 folio_ref_sub(folio, folio_nr_pages(folio));
235 }
236
237 /**
238 * __swap_cache_replace_folio - Replace a folio in the swap cache.
239 * @ci: The locked swap cluster.
240 * @old: The old folio to be replaced.
241 * @new: The new folio.
242 *
243 * Replace an existing folio in the swap cache with a new folio. The
244 * caller is responsible for setting up the new folio's flag and swap
245 * entries. Replacement will take the new folio's swap entry value as
246 * the starting offset to override all slots covered by the new folio.
247 *
248 * Context: Caller must ensure both folios are locked, and lock the
249 * cluster that holds the old folio to be replaced.
250 */
__swap_cache_replace_folio(struct swap_cluster_info * ci,struct folio * old,struct folio * new)251 void __swap_cache_replace_folio(struct swap_cluster_info *ci,
252 struct folio *old, struct folio *new)
253 {
254 swp_entry_t entry = new->swap;
255 unsigned long nr_pages = folio_nr_pages(new);
256 unsigned int ci_off = swp_cluster_offset(entry);
257 unsigned int ci_end = ci_off + nr_pages;
258 unsigned long old_tb, new_tb;
259
260 VM_WARN_ON_ONCE(!folio_test_swapcache(old) || !folio_test_swapcache(new));
261 VM_WARN_ON_ONCE(!folio_test_locked(old) || !folio_test_locked(new));
262 VM_WARN_ON_ONCE(!entry.val);
263
264 /* Swap cache still stores N entries instead of a high-order entry */
265 new_tb = folio_to_swp_tb(new);
266 do {
267 old_tb = __swap_table_xchg(ci, ci_off, new_tb);
268 WARN_ON_ONCE(!swp_tb_is_folio(old_tb) || swp_tb_to_folio(old_tb) != old);
269 } while (++ci_off < ci_end);
270
271 /*
272 * If the old folio is partially replaced (e.g., splitting a large
273 * folio, the old folio is shrunk, and new split sub folios replace
274 * the shrunk part), ensure the new folio doesn't overlap it.
275 */
276 if (IS_ENABLED(CONFIG_DEBUG_VM) &&
277 folio_order(old) != folio_order(new)) {
278 ci_off = swp_cluster_offset(old->swap);
279 ci_end = ci_off + folio_nr_pages(old);
280 while (ci_off++ < ci_end)
281 WARN_ON_ONCE(swp_tb_to_folio(__swap_table_get(ci, ci_off)) != old);
282 }
283 }
284
285 /**
286 * swap_cache_clear_shadow - Clears a set of shadows in the swap cache.
287 * @entry: The starting index entry.
288 * @nr_ents: How many slots need to be cleared.
289 *
290 * Context: Caller must ensure the range is valid, all in one single cluster,
291 * not occupied by any folio, and lock the cluster.
292 */
__swap_cache_clear_shadow(swp_entry_t entry,int nr_ents)293 void __swap_cache_clear_shadow(swp_entry_t entry, int nr_ents)
294 {
295 struct swap_cluster_info *ci = __swap_entry_to_cluster(entry);
296 unsigned int ci_off = swp_cluster_offset(entry), ci_end;
297 unsigned long old;
298
299 ci_end = ci_off + nr_ents;
300 do {
301 old = __swap_table_xchg(ci, ci_off, null_to_swp_tb());
302 WARN_ON_ONCE(swp_tb_is_folio(old));
303 } while (++ci_off < ci_end);
304 }
305
306 /*
307 * If we are the only user, then try to free up the swap cache.
308 *
309 * Its ok to check the swapcache flag without the folio lock
310 * here because we are going to recheck again inside
311 * folio_free_swap() _with_ the lock.
312 * - Marcelo
313 */
free_swap_cache(struct folio * folio)314 void free_swap_cache(struct folio *folio)
315 {
316 if (folio_test_swapcache(folio) && !folio_mapped(folio) &&
317 folio_trylock(folio)) {
318 folio_free_swap(folio);
319 folio_unlock(folio);
320 }
321 }
322
323 /*
324 * Freeing a folio and also freeing any swap cache associated with
325 * this folio if it is the last user.
326 */
free_folio_and_swap_cache(struct folio * folio)327 void free_folio_and_swap_cache(struct folio *folio)
328 {
329 free_swap_cache(folio);
330 if (!is_huge_zero_folio(folio))
331 folio_put(folio);
332 }
333
334 /*
335 * Passed an array of pages, drop them all from swapcache and then release
336 * them. They are removed from the LRU and freed if this is their last use.
337 */
free_pages_and_swap_cache(struct encoded_page ** pages,int nr)338 void free_pages_and_swap_cache(struct encoded_page **pages, int nr)
339 {
340 struct folio_batch folios;
341 unsigned int refs[PAGEVEC_SIZE];
342
343 folio_batch_init(&folios);
344 for (int i = 0; i < nr; i++) {
345 struct folio *folio = page_folio(encoded_page_ptr(pages[i]));
346
347 free_swap_cache(folio);
348 refs[folios.nr] = 1;
349 if (unlikely(encoded_page_flags(pages[i]) &
350 ENCODED_PAGE_BIT_NR_PAGES_NEXT))
351 refs[folios.nr] = encoded_nr_pages(pages[++i]);
352
353 if (folio_batch_add(&folios, folio) == 0)
354 folios_put_refs(&folios, refs);
355 }
356 if (folios.nr)
357 folios_put_refs(&folios, refs);
358 }
359
swap_use_vma_readahead(void)360 static inline bool swap_use_vma_readahead(void)
361 {
362 return READ_ONCE(enable_vma_readahead) && !atomic_read(&nr_rotate_swap);
363 }
364
365 /**
366 * swap_update_readahead - Update the readahead statistics of VMA or globally.
367 * @folio: the swap cache folio that just got hit.
368 * @vma: the VMA that should be updated, could be NULL for global update.
369 * @addr: the addr that triggered the swapin, ignored if @vma is NULL.
370 */
swap_update_readahead(struct folio * folio,struct vm_area_struct * vma,unsigned long addr)371 void swap_update_readahead(struct folio *folio, struct vm_area_struct *vma,
372 unsigned long addr)
373 {
374 bool readahead, vma_ra = swap_use_vma_readahead();
375
376 /*
377 * At the moment, we don't support PG_readahead for anon THP
378 * so let's bail out rather than confusing the readahead stat.
379 */
380 if (unlikely(folio_test_large(folio)))
381 return;
382
383 readahead = folio_test_clear_readahead(folio);
384 if (vma && vma_ra) {
385 unsigned long ra_val;
386 int win, hits;
387
388 ra_val = GET_SWAP_RA_VAL(vma);
389 win = SWAP_RA_WIN(ra_val);
390 hits = SWAP_RA_HITS(ra_val);
391 if (readahead)
392 hits = min_t(int, hits + 1, SWAP_RA_HITS_MAX);
393 atomic_long_set(&vma->swap_readahead_info,
394 SWAP_RA_VAL(addr, win, hits));
395 }
396
397 if (readahead) {
398 count_vm_event(SWAP_RA_HIT);
399 if (!vma || !vma_ra)
400 atomic_inc(&swapin_readahead_hits);
401 }
402 }
403
__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)404 struct folio *__read_swap_cache_async(swp_entry_t entry, gfp_t gfp_mask,
405 struct mempolicy *mpol, pgoff_t ilx, bool *new_page_allocated,
406 bool skip_if_exists)
407 {
408 struct swap_info_struct *si = __swap_entry_to_info(entry);
409 struct folio *folio;
410 struct folio *new_folio = NULL;
411 struct folio *result = NULL;
412 void *shadow = NULL;
413
414 *new_page_allocated = false;
415 for (;;) {
416 int err;
417
418 /*
419 * Check the swap cache first, if a cached folio is found,
420 * return it unlocked. The caller will lock and check it.
421 */
422 folio = swap_cache_get_folio(entry);
423 if (folio)
424 goto got_folio;
425
426 /*
427 * Just skip read ahead for unused swap slot.
428 */
429 if (!swap_entry_swapped(si, entry))
430 goto put_and_return;
431
432 /*
433 * Get a new folio to read into from swap. Allocate it now if
434 * new_folio not exist, before marking swap_map SWAP_HAS_CACHE,
435 * when -EEXIST will cause any racers to loop around until we
436 * add it to cache.
437 */
438 if (!new_folio) {
439 new_folio = folio_alloc_mpol(gfp_mask, 0, mpol, ilx, numa_node_id());
440 if (!new_folio)
441 goto put_and_return;
442 }
443
444 /*
445 * Swap entry may have been freed since our caller observed it.
446 */
447 err = swapcache_prepare(entry, 1);
448 if (!err)
449 break;
450 else if (err != -EEXIST)
451 goto put_and_return;
452
453 /*
454 * Protect against a recursive call to __read_swap_cache_async()
455 * on the same entry waiting forever here because SWAP_HAS_CACHE
456 * is set but the folio is not the swap cache yet. This can
457 * happen today if mem_cgroup_swapin_charge_folio() below
458 * triggers reclaim through zswap, which may call
459 * __read_swap_cache_async() in the writeback path.
460 */
461 if (skip_if_exists)
462 goto put_and_return;
463
464 /*
465 * We might race against __swap_cache_del_folio(), and
466 * stumble across a swap_map entry whose SWAP_HAS_CACHE
467 * has not yet been cleared. Or race against another
468 * __read_swap_cache_async(), which has set SWAP_HAS_CACHE
469 * in swap_map, but not yet added its folio to swap cache.
470 */
471 schedule_timeout_uninterruptible(1);
472 }
473
474 /*
475 * The swap entry is ours to swap in. Prepare the new folio.
476 */
477 __folio_set_locked(new_folio);
478 __folio_set_swapbacked(new_folio);
479
480 if (mem_cgroup_swapin_charge_folio(new_folio, NULL, gfp_mask, entry))
481 goto fail_unlock;
482
483 swap_cache_add_folio(new_folio, entry, &shadow);
484 memcg1_swapin(entry, 1);
485
486 if (shadow)
487 workingset_refault(new_folio, shadow);
488
489 /* Caller will initiate read into locked new_folio */
490 folio_add_lru(new_folio);
491 *new_page_allocated = true;
492 folio = new_folio;
493 got_folio:
494 result = folio;
495 goto put_and_return;
496
497 fail_unlock:
498 put_swap_folio(new_folio, entry);
499 folio_unlock(new_folio);
500 put_and_return:
501 if (!(*new_page_allocated) && new_folio)
502 folio_put(new_folio);
503 return result;
504 }
505
506 /*
507 * Locate a page of swap in physical memory, reserving swap cache space
508 * and reading the disk if it is not already cached.
509 * A failure return means that either the page allocation failed or that
510 * the swap entry is no longer in use.
511 */
read_swap_cache_async(swp_entry_t entry,gfp_t gfp_mask,struct vm_area_struct * vma,unsigned long addr,struct swap_iocb ** plug)512 struct folio *read_swap_cache_async(swp_entry_t entry, gfp_t gfp_mask,
513 struct vm_area_struct *vma, unsigned long addr,
514 struct swap_iocb **plug)
515 {
516 struct swap_info_struct *si;
517 bool page_allocated;
518 struct mempolicy *mpol;
519 pgoff_t ilx;
520 struct folio *folio;
521
522 si = get_swap_device(entry);
523 if (!si)
524 return NULL;
525
526 mpol = get_vma_policy(vma, addr, 0, &ilx);
527 folio = __read_swap_cache_async(entry, gfp_mask, mpol, ilx,
528 &page_allocated, false);
529 mpol_cond_put(mpol);
530
531 if (page_allocated)
532 swap_read_folio(folio, plug);
533
534 put_swap_device(si);
535 return folio;
536 }
537
__swapin_nr_pages(unsigned long prev_offset,unsigned long offset,int hits,int max_pages,int prev_win)538 static unsigned int __swapin_nr_pages(unsigned long prev_offset,
539 unsigned long offset,
540 int hits,
541 int max_pages,
542 int prev_win)
543 {
544 unsigned int pages, last_ra;
545
546 /*
547 * This heuristic has been found to work well on both sequential and
548 * random loads, swapping to hard disk or to SSD: please don't ask
549 * what the "+ 2" means, it just happens to work well, that's all.
550 */
551 pages = hits + 2;
552 if (pages == 2) {
553 /*
554 * We can have no readahead hits to judge by: but must not get
555 * stuck here forever, so check for an adjacent offset instead
556 * (and don't even bother to check whether swap type is same).
557 */
558 if (offset != prev_offset + 1 && offset != prev_offset - 1)
559 pages = 1;
560 } else {
561 unsigned int roundup = 4;
562 while (roundup < pages)
563 roundup <<= 1;
564 pages = roundup;
565 }
566
567 if (pages > max_pages)
568 pages = max_pages;
569
570 /* Don't shrink readahead too fast */
571 last_ra = prev_win / 2;
572 if (pages < last_ra)
573 pages = last_ra;
574
575 return pages;
576 }
577
swapin_nr_pages(unsigned long offset)578 static unsigned long swapin_nr_pages(unsigned long offset)
579 {
580 static unsigned long prev_offset;
581 unsigned int hits, pages, max_pages;
582 static atomic_t last_readahead_pages;
583
584 max_pages = 1 << READ_ONCE(page_cluster);
585 if (max_pages <= 1)
586 return 1;
587
588 hits = atomic_xchg(&swapin_readahead_hits, 0);
589 pages = __swapin_nr_pages(READ_ONCE(prev_offset), offset, hits,
590 max_pages,
591 atomic_read(&last_readahead_pages));
592 if (!hits)
593 WRITE_ONCE(prev_offset, offset);
594 atomic_set(&last_readahead_pages, pages);
595
596 return pages;
597 }
598
599 /**
600 * swap_cluster_readahead - swap in pages in hope we need them soon
601 * @entry: swap entry of this memory
602 * @gfp_mask: memory allocation flags
603 * @mpol: NUMA memory allocation policy to be applied
604 * @ilx: NUMA interleave index, for use only when MPOL_INTERLEAVE
605 *
606 * Returns the struct folio for entry and addr, after queueing swapin.
607 *
608 * Primitive swap readahead code. We simply read an aligned block of
609 * (1 << page_cluster) entries in the swap area. This method is chosen
610 * because it doesn't cost us any seek time. We also make sure to queue
611 * the 'original' request together with the readahead ones...
612 *
613 * Note: it is intentional that the same NUMA policy and interleave index
614 * are used for every page of the readahead: neighbouring pages on swap
615 * are fairly likely to have been swapped out from the same node.
616 */
swap_cluster_readahead(swp_entry_t entry,gfp_t gfp_mask,struct mempolicy * mpol,pgoff_t ilx)617 struct folio *swap_cluster_readahead(swp_entry_t entry, gfp_t gfp_mask,
618 struct mempolicy *mpol, pgoff_t ilx)
619 {
620 struct folio *folio;
621 unsigned long entry_offset = swp_offset(entry);
622 unsigned long offset = entry_offset;
623 unsigned long start_offset, end_offset;
624 unsigned long mask;
625 struct swap_info_struct *si = __swap_entry_to_info(entry);
626 struct blk_plug plug;
627 struct swap_iocb *splug = NULL;
628 bool page_allocated;
629
630 mask = swapin_nr_pages(offset) - 1;
631 if (!mask)
632 goto skip;
633
634 /* Read a page_cluster sized and aligned cluster around offset. */
635 start_offset = offset & ~mask;
636 end_offset = offset | mask;
637 if (!start_offset) /* First page is swap header. */
638 start_offset++;
639 if (end_offset >= si->max)
640 end_offset = si->max - 1;
641
642 blk_start_plug(&plug);
643 for (offset = start_offset; offset <= end_offset ; offset++) {
644 /* Ok, do the async read-ahead now */
645 folio = __read_swap_cache_async(
646 swp_entry(swp_type(entry), offset),
647 gfp_mask, mpol, ilx, &page_allocated, false);
648 if (!folio)
649 continue;
650 if (page_allocated) {
651 swap_read_folio(folio, &splug);
652 if (offset != entry_offset) {
653 folio_set_readahead(folio);
654 count_vm_event(SWAP_RA);
655 }
656 }
657 folio_put(folio);
658 }
659 blk_finish_plug(&plug);
660 swap_read_unplug(splug);
661 lru_add_drain(); /* Push any new pages onto the LRU now */
662 skip:
663 /* The page was likely read above, so no need for plugging here */
664 folio = __read_swap_cache_async(entry, gfp_mask, mpol, ilx,
665 &page_allocated, false);
666 if (unlikely(page_allocated))
667 swap_read_folio(folio, NULL);
668 return folio;
669 }
670
swap_vma_ra_win(struct vm_fault * vmf,unsigned long * start,unsigned long * end)671 static int swap_vma_ra_win(struct vm_fault *vmf, unsigned long *start,
672 unsigned long *end)
673 {
674 struct vm_area_struct *vma = vmf->vma;
675 unsigned long ra_val;
676 unsigned long faddr, prev_faddr, left, right;
677 unsigned int max_win, hits, prev_win, win;
678
679 max_win = 1 << min(READ_ONCE(page_cluster), SWAP_RA_ORDER_CEILING);
680 if (max_win == 1)
681 return 1;
682
683 faddr = vmf->address;
684 ra_val = GET_SWAP_RA_VAL(vma);
685 prev_faddr = SWAP_RA_ADDR(ra_val);
686 prev_win = SWAP_RA_WIN(ra_val);
687 hits = SWAP_RA_HITS(ra_val);
688 win = __swapin_nr_pages(PFN_DOWN(prev_faddr), PFN_DOWN(faddr), hits,
689 max_win, prev_win);
690 atomic_long_set(&vma->swap_readahead_info, SWAP_RA_VAL(faddr, win, 0));
691 if (win == 1)
692 return 1;
693
694 if (faddr == prev_faddr + PAGE_SIZE)
695 left = faddr;
696 else if (prev_faddr == faddr + PAGE_SIZE)
697 left = faddr - (win << PAGE_SHIFT) + PAGE_SIZE;
698 else
699 left = faddr - (((win - 1) / 2) << PAGE_SHIFT);
700 right = left + (win << PAGE_SHIFT);
701 if ((long)left < 0)
702 left = 0;
703 *start = max3(left, vma->vm_start, faddr & PMD_MASK);
704 *end = min3(right, vma->vm_end, (faddr & PMD_MASK) + PMD_SIZE);
705
706 return win;
707 }
708
709 /**
710 * swap_vma_readahead - swap in pages in hope we need them soon
711 * @targ_entry: swap entry of the targeted memory
712 * @gfp_mask: memory allocation flags
713 * @mpol: NUMA memory allocation policy to be applied
714 * @targ_ilx: NUMA interleave index, for use only when MPOL_INTERLEAVE
715 * @vmf: fault information
716 *
717 * Returns the struct folio for entry and addr, after queueing swapin.
718 *
719 * Primitive swap readahead code. We simply read in a few pages whose
720 * virtual addresses are around the fault address in the same vma.
721 *
722 * Caller must hold read mmap_lock if vmf->vma is not NULL.
723 *
724 */
swap_vma_readahead(swp_entry_t targ_entry,gfp_t gfp_mask,struct mempolicy * mpol,pgoff_t targ_ilx,struct vm_fault * vmf)725 static struct folio *swap_vma_readahead(swp_entry_t targ_entry, gfp_t gfp_mask,
726 struct mempolicy *mpol, pgoff_t targ_ilx, struct vm_fault *vmf)
727 {
728 struct blk_plug plug;
729 struct swap_iocb *splug = NULL;
730 struct folio *folio;
731 pte_t *pte = NULL, pentry;
732 int win;
733 unsigned long start, end, addr;
734 pgoff_t ilx;
735 bool page_allocated;
736
737 win = swap_vma_ra_win(vmf, &start, &end);
738 if (win == 1)
739 goto skip;
740
741 ilx = targ_ilx - PFN_DOWN(vmf->address - start);
742
743 blk_start_plug(&plug);
744 for (addr = start; addr < end; ilx++, addr += PAGE_SIZE) {
745 struct swap_info_struct *si = NULL;
746 softleaf_t entry;
747
748 if (!pte++) {
749 pte = pte_offset_map(vmf->pmd, addr);
750 if (!pte)
751 break;
752 }
753 pentry = ptep_get_lockless(pte);
754 entry = softleaf_from_pte(pentry);
755
756 if (!softleaf_is_swap(entry))
757 continue;
758 pte_unmap(pte);
759 pte = NULL;
760 /*
761 * Readahead entry may come from a device that we are not
762 * holding a reference to, try to grab a reference, or skip.
763 */
764 if (swp_type(entry) != swp_type(targ_entry)) {
765 si = get_swap_device(entry);
766 if (!si)
767 continue;
768 }
769 folio = __read_swap_cache_async(entry, gfp_mask, mpol, ilx,
770 &page_allocated, false);
771 if (si)
772 put_swap_device(si);
773 if (!folio)
774 continue;
775 if (page_allocated) {
776 swap_read_folio(folio, &splug);
777 if (addr != vmf->address) {
778 folio_set_readahead(folio);
779 count_vm_event(SWAP_RA);
780 }
781 }
782 folio_put(folio);
783 }
784 if (pte)
785 pte_unmap(pte);
786 blk_finish_plug(&plug);
787 swap_read_unplug(splug);
788 lru_add_drain();
789 skip:
790 /* The folio was likely read above, so no need for plugging here */
791 folio = __read_swap_cache_async(targ_entry, gfp_mask, mpol, targ_ilx,
792 &page_allocated, false);
793 if (unlikely(page_allocated))
794 swap_read_folio(folio, NULL);
795 return folio;
796 }
797
798 /**
799 * swapin_readahead - swap in pages in hope we need them soon
800 * @entry: swap entry of this memory
801 * @gfp_mask: memory allocation flags
802 * @vmf: fault information
803 *
804 * Returns the struct folio for entry and addr, after queueing swapin.
805 *
806 * It's a main entry function for swap readahead. By the configuration,
807 * it will read ahead blocks by cluster-based(ie, physical disk based)
808 * or vma-based(ie, virtual address based on faulty address) readahead.
809 */
swapin_readahead(swp_entry_t entry,gfp_t gfp_mask,struct vm_fault * vmf)810 struct folio *swapin_readahead(swp_entry_t entry, gfp_t gfp_mask,
811 struct vm_fault *vmf)
812 {
813 struct mempolicy *mpol;
814 pgoff_t ilx;
815 struct folio *folio;
816
817 mpol = get_vma_policy(vmf->vma, vmf->address, 0, &ilx);
818 folio = swap_use_vma_readahead() ?
819 swap_vma_readahead(entry, gfp_mask, mpol, ilx, vmf) :
820 swap_cluster_readahead(entry, gfp_mask, mpol, ilx);
821 mpol_cond_put(mpol);
822
823 return folio;
824 }
825
826 #ifdef CONFIG_SYSFS
vma_ra_enabled_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)827 static ssize_t vma_ra_enabled_show(struct kobject *kobj,
828 struct kobj_attribute *attr, char *buf)
829 {
830 return sysfs_emit(buf, "%s\n", str_true_false(enable_vma_readahead));
831 }
vma_ra_enabled_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)832 static ssize_t vma_ra_enabled_store(struct kobject *kobj,
833 struct kobj_attribute *attr,
834 const char *buf, size_t count)
835 {
836 ssize_t ret;
837
838 ret = kstrtobool(buf, &enable_vma_readahead);
839 if (ret)
840 return ret;
841
842 return count;
843 }
844 static struct kobj_attribute vma_ra_enabled_attr = __ATTR_RW(vma_ra_enabled);
845
846 static struct attribute *swap_attrs[] = {
847 &vma_ra_enabled_attr.attr,
848 NULL,
849 };
850
851 static const struct attribute_group swap_attr_group = {
852 .attrs = swap_attrs,
853 };
854
swap_init(void)855 static int __init swap_init(void)
856 {
857 int err;
858 struct kobject *swap_kobj;
859
860 swap_kobj = kobject_create_and_add("swap", mm_kobj);
861 if (!swap_kobj) {
862 pr_err("failed to create swap kobject\n");
863 return -ENOMEM;
864 }
865 err = sysfs_create_group(swap_kobj, &swap_attr_group);
866 if (err) {
867 pr_err("failed to register swap group\n");
868 goto delete_obj;
869 }
870 /* Swap cache writeback is LRU based, no tags for it */
871 mapping_set_no_writeback_tags(&swap_space);
872 return 0;
873
874 delete_obj:
875 kobject_put(swap_kobj);
876 return err;
877 }
878 subsys_initcall(swap_init);
879 #endif
880