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/folio_batch.h>
19 #include <linux/backing-dev.h>
20 #include <linux/blk_plug.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 <linux/sysctl.h>
26 #include <linux/swap_ops.h>
27 #include "internal.h"
28 #include "swap_table.h"
29 #include "swap.h"
30
31 /* Swap readahead cluster size, as a power of 2 pages. */
32 static int page_cluster;
33 static const int page_cluster_max = 31;
34
35 /*
36 * swapper_space is a fiction, retained to simplify the path through
37 * vmscan's shrink_folio_list.
38 */
39 static const struct address_space_operations swap_aops = {
40 .dirty_folio = noop_dirty_folio,
41 #ifdef CONFIG_MIGRATION
42 .migrate_folio = migrate_folio,
43 #endif
44 };
45
46 struct address_space swap_space __read_mostly = {
47 .a_ops = &swap_aops,
48 };
49
50 static bool enable_vma_readahead __read_mostly = true;
51
52 #define SWAP_RA_ORDER_CEILING 5
53
54 #define SWAP_RA_WIN_SHIFT (PAGE_SHIFT / 2)
55 #define SWAP_RA_HITS_MASK ((1UL << SWAP_RA_WIN_SHIFT) - 1)
56 #define SWAP_RA_HITS_MAX SWAP_RA_HITS_MASK
57 #define SWAP_RA_WIN_MASK (~PAGE_MASK & ~SWAP_RA_HITS_MASK)
58
59 #define SWAP_RA_HITS(v) ((v) & SWAP_RA_HITS_MASK)
60 #define SWAP_RA_WIN(v) (((v) & SWAP_RA_WIN_MASK) >> SWAP_RA_WIN_SHIFT)
61 #define SWAP_RA_ADDR(v) ((v) & PAGE_MASK)
62
63 #define SWAP_RA_VAL(addr, win, hits) \
64 (((addr) & PAGE_MASK) | \
65 (((win) << SWAP_RA_WIN_SHIFT) & SWAP_RA_WIN_MASK) | \
66 ((hits) & SWAP_RA_HITS_MASK))
67
68 /* Initial readahead hits is 4 to start up with a small window */
69 #define GET_SWAP_RA_VAL(vma) \
70 (atomic_long_read(&(vma)->swap_readahead_info) ? : 4)
71
72 static atomic_t swapin_readahead_hits = ATOMIC_INIT(4);
73
show_swap_cache_info(void)74 void show_swap_cache_info(void)
75 {
76 printk("%lu pages in swap cache\n", total_swapcache_pages());
77 printk("Free swap = %ldkB\n", K(get_nr_swap_pages()));
78 printk("Total swap = %lukB\n", K(total_swap_pages));
79 }
80
81 /**
82 * swap_cache_get_folio - Looks up a folio in the swap cache.
83 * @entry: swap entry used for the lookup.
84 *
85 * A found folio will be returned unlocked and with its refcount increased.
86 *
87 * Context: Caller must ensure @entry is valid and protect the swap device
88 * with reference count or locks.
89 * Return: Returns the found folio on success, NULL otherwise. The caller
90 * must lock and check if the folio still matches the swap entry before
91 * use (e.g., folio_matches_swap_entry).
92 */
swap_cache_get_folio(swp_entry_t entry)93 struct folio *swap_cache_get_folio(swp_entry_t entry)
94 {
95 unsigned long swp_tb;
96 struct folio *folio;
97
98 for (;;) {
99 swp_tb = swap_table_get(__swap_entry_to_cluster(entry),
100 swp_cluster_offset(entry));
101 if (!swp_tb_is_folio(swp_tb))
102 return NULL;
103 folio = swp_tb_to_folio(swp_tb);
104 if (likely(folio_try_get(folio)))
105 return folio;
106 }
107
108 return NULL;
109 }
110
111 /**
112 * swap_cache_has_folio - Check if a swap slot has cache.
113 * @entry: swap entry indicating the slot.
114 *
115 * Context: Caller must ensure @entry is valid and protect the swap
116 * device with reference count or locks.
117 */
swap_cache_has_folio(swp_entry_t entry)118 bool swap_cache_has_folio(swp_entry_t entry)
119 {
120 unsigned long swp_tb;
121
122 swp_tb = swap_table_get(__swap_entry_to_cluster(entry),
123 swp_cluster_offset(entry));
124 return swp_tb_is_folio(swp_tb);
125 }
126
127 /**
128 * swap_cache_get_shadow - Looks up a shadow in the swap cache.
129 * @entry: swap entry used for the lookup.
130 *
131 * Context: Caller must ensure @entry is valid and protect the swap device
132 * with reference count or locks.
133 * Return: Returns either NULL or an XA_VALUE (shadow).
134 */
swap_cache_get_shadow(swp_entry_t entry)135 void *swap_cache_get_shadow(swp_entry_t entry)
136 {
137 unsigned long swp_tb;
138
139 swp_tb = swap_table_get(__swap_entry_to_cluster(entry),
140 swp_cluster_offset(entry));
141 if (swp_tb_is_shadow(swp_tb))
142 return swp_tb_to_shadow(swp_tb);
143 return NULL;
144 }
145
146 /**
147 * __swap_cache_add_check - Check if a range is suitable for adding a folio.
148 * @ci: The locked swap cluster
149 * @targ_entry: The target swap entry to check, will be rounded down by @nr
150 * @nr: Number of slots to check, must be a power of 2
151 * @shadowp: Returns the shadow value if one exists in the range
152 * @memcg_id: Returns the memory cgroup id, NULL to ignore cgroup check
153 *
154 * Check if all slots covered by given range have a swap count >= 1.
155 * Retrieves the shadow if there is one. If @memcg_id is not NULL, also
156 * checks if all slots belong to the same cgroup and return the cgroup
157 * private id.
158 *
159 * Context: Caller must lock the cluster.
160 * Return: 0 if success, error code if failed.
161 */
__swap_cache_add_check(struct swap_cluster_info * ci,swp_entry_t targ_entry,unsigned long nr,void ** shadowp,unsigned short * memcg_id)162 static int __swap_cache_add_check(struct swap_cluster_info *ci,
163 swp_entry_t targ_entry,
164 unsigned long nr, void **shadowp,
165 unsigned short *memcg_id)
166 {
167 unsigned int ci_off, ci_end;
168 unsigned long old_tb;
169 bool is_zero;
170
171 lockdep_assert_held(&ci->lock);
172
173 /*
174 * If the target slot is not swapped out or already cached, return
175 * -ENOENT or -EEXIST. If the batch is not suitable, could be a
176 * race with concurrent free or cache add, return -EBUSY.
177 */
178 if (unlikely(!ci->table))
179 return -ENOENT;
180 ci_off = swp_cluster_offset(targ_entry);
181 old_tb = __swap_table_get(ci, ci_off);
182 if (swp_tb_is_folio(old_tb))
183 return -EEXIST;
184 if (!__swp_tb_get_count(old_tb))
185 return -ENOENT;
186 if (shadowp && swp_tb_is_shadow(old_tb))
187 *shadowp = swp_tb_to_shadow(old_tb);
188 if (memcg_id)
189 *memcg_id = __swap_cgroup_get(ci, ci_off);
190
191 if (nr == 1)
192 return 0;
193
194 is_zero = __swap_table_test_zero(ci, ci_off);
195 ci_off = round_down(ci_off, nr);
196 ci_end = ci_off + nr;
197 do {
198 old_tb = __swap_table_get(ci, ci_off);
199 if (unlikely(swp_tb_is_folio(old_tb) ||
200 !__swp_tb_get_count(old_tb) ||
201 is_zero != __swap_table_test_zero(ci, ci_off) ||
202 (memcg_id && *memcg_id != __swap_cgroup_get(ci, ci_off))))
203 return -EBUSY;
204 } while (++ci_off < ci_end);
205
206 return 0;
207 }
208
__swap_cache_do_add_folio(struct swap_cluster_info * ci,struct folio * folio,swp_entry_t entry)209 static void __swap_cache_do_add_folio(struct swap_cluster_info *ci,
210 struct folio *folio, swp_entry_t entry)
211 {
212 unsigned int ci_off = swp_cluster_offset(entry), ci_end;
213 unsigned long nr_pages = folio_nr_pages(folio);
214 unsigned long pfn = folio_pfn(folio);
215 unsigned long old_tb;
216
217 VM_WARN_ON_ONCE_FOLIO(!folio_test_locked(folio), folio);
218 VM_WARN_ON_ONCE_FOLIO(folio_test_swapcache(folio), folio);
219 VM_WARN_ON_ONCE_FOLIO(!folio_test_swapbacked(folio), folio);
220
221 ci_end = ci_off + nr_pages;
222 do {
223 old_tb = __swap_table_get(ci, ci_off);
224 VM_WARN_ON_ONCE(swp_tb_is_folio(old_tb));
225 __swap_table_set(ci, ci_off, pfn_to_swp_tb(pfn, __swp_tb_get_flags(old_tb)));
226 } while (++ci_off < ci_end);
227
228 folio_ref_add(folio, nr_pages);
229 folio_set_swapcache(folio);
230 folio->swap = entry;
231 }
232
233 /**
234 * __swap_cache_add_folio - Add a folio to the swap cache and update stats.
235 * @ci: The locked swap cluster.
236 * @folio: The folio to be added.
237 * @entry: The swap entry corresponding to the folio.
238 *
239 * Unconditionally add a folio to the swap cache. The caller must ensure
240 * all slots are usable and have no conflicts. This assigns entry to
241 * @folio->swap, increases folio refcount by the number of pages, and
242 * updates swap cache stats.
243 *
244 * Context: Caller must ensure the folio is locked and lock the cluster
245 * that holds the entries.
246 */
__swap_cache_add_folio(struct swap_cluster_info * ci,struct folio * folio,swp_entry_t entry)247 void __swap_cache_add_folio(struct swap_cluster_info *ci,
248 struct folio *folio, swp_entry_t entry)
249 {
250 unsigned long nr_pages = folio_nr_pages(folio);
251
252 __swap_cache_do_add_folio(ci, folio, entry);
253 node_stat_mod_folio(folio, NR_FILE_PAGES, nr_pages);
254 lruvec_stat_mod_folio(folio, NR_SWAPCACHE, nr_pages);
255 }
256
__swap_cache_do_del_folio(struct swap_cluster_info * ci,struct folio * folio,swp_entry_t entry,void * shadow)257 static void __swap_cache_do_del_folio(struct swap_cluster_info *ci,
258 struct folio *folio,
259 swp_entry_t entry, void *shadow)
260 {
261 unsigned long old_tb;
262 struct swap_info_struct *si;
263 unsigned int ci_start, ci_off, ci_end;
264 bool folio_swapped = false, need_free = false;
265 unsigned long nr_pages = folio_nr_pages(folio);
266
267 VM_WARN_ON_ONCE(__swap_entry_to_cluster(entry) != ci);
268 VM_WARN_ON_ONCE_FOLIO(!folio_test_locked(folio), folio);
269 VM_WARN_ON_ONCE_FOLIO(!folio_test_swapcache(folio), folio);
270 VM_WARN_ON_ONCE_FOLIO(folio_test_writeback(folio), folio);
271
272 si = __swap_entry_to_info(entry);
273 ci_start = swp_cluster_offset(entry);
274 ci_end = ci_start + nr_pages;
275 ci_off = ci_start;
276 do {
277 old_tb = __swap_table_get(ci, ci_off);
278 WARN_ON_ONCE(!swp_tb_is_folio(old_tb) ||
279 swp_tb_to_folio(old_tb) != folio);
280 if (__swp_tb_get_count(old_tb))
281 folio_swapped = true;
282 else
283 need_free = true;
284 /* If shadow is NULL, we set an empty shadow. */
285 __swap_table_set(ci, ci_off, shadow_to_swp_tb(shadow,
286 __swp_tb_get_flags(old_tb)));
287 } while (++ci_off < ci_end);
288
289 folio->swap.val = 0;
290 folio_clear_swapcache(folio);
291
292 if (!folio_swapped) {
293 __swap_cluster_free_entries(si, ci, ci_start, nr_pages);
294 } else if (need_free) {
295 ci_off = ci_start;
296 do {
297 if (!__swp_tb_get_count(__swap_table_get(ci, ci_off)))
298 __swap_cluster_free_entries(si, ci, ci_off, 1);
299 } while (++ci_off < ci_end);
300 }
301 }
302
303 /**
304 * __swap_cache_del_folio - Removes a folio from the swap cache.
305 * @ci: The locked swap cluster.
306 * @folio: The folio.
307 * @entry: The first swap entry that the folio corresponds to.
308 * @shadow: shadow value to be filled in the swap cache.
309 *
310 * Removes a folio from the swap cache and fills a shadow in place.
311 * This won't put the folio's refcount. The caller has to do that.
312 *
313 * Context: Caller must ensure the folio is locked and in the swap cache
314 * using the index of @entry, and lock the cluster that holds the entries.
315 */
__swap_cache_del_folio(struct swap_cluster_info * ci,struct folio * folio,swp_entry_t entry,void * shadow)316 void __swap_cache_del_folio(struct swap_cluster_info *ci, struct folio *folio,
317 swp_entry_t entry, void *shadow)
318 {
319 unsigned long nr_pages = folio_nr_pages(folio);
320
321 __swap_cache_do_del_folio(ci, folio, entry, shadow);
322 node_stat_mod_folio(folio, NR_FILE_PAGES, -nr_pages);
323 lruvec_stat_mod_folio(folio, NR_SWAPCACHE, -nr_pages);
324 }
325
326 /**
327 * swap_cache_del_folio - Removes a folio from the swap cache.
328 * @folio: The folio.
329 *
330 * Same as __swap_cache_del_folio, but handles lock and refcount. The
331 * caller must ensure the folio is either clean or has a swap count
332 * equal to zero, or it may cause data loss.
333 *
334 * Context: Caller must ensure the folio is locked and in the swap cache.
335 */
swap_cache_del_folio(struct folio * folio)336 void swap_cache_del_folio(struct folio *folio)
337 {
338 struct swap_cluster_info *ci;
339 swp_entry_t entry = folio->swap;
340
341 ci = swap_cluster_lock(__swap_entry_to_info(entry), swp_offset(entry));
342 __swap_cache_del_folio(ci, folio, entry, NULL);
343 swap_cluster_unlock(ci);
344
345 folio_ref_sub(folio, folio_nr_pages(folio));
346 }
347
348 /**
349 * __swap_cache_replace_folio - Replace a folio in the swap cache.
350 * @ci: The locked swap cluster.
351 * @old: The old folio to be replaced.
352 * @new: The new folio.
353 *
354 * Replace an existing folio in the swap cache with a new folio. The
355 * caller is responsible for setting up the new folio's flag and swap
356 * entries. Replacement will take the new folio's swap entry value as
357 * the starting offset to override all slots covered by the new folio.
358 *
359 * Context: Caller must ensure both folios are locked, and lock the
360 * cluster that holds the old folio to be replaced.
361 */
__swap_cache_replace_folio(struct swap_cluster_info * ci,struct folio * old,struct folio * new)362 void __swap_cache_replace_folio(struct swap_cluster_info *ci,
363 struct folio *old, struct folio *new)
364 {
365 swp_entry_t entry = new->swap;
366 unsigned long nr_pages = folio_nr_pages(new);
367 unsigned int ci_off = swp_cluster_offset(entry);
368 unsigned int ci_end = ci_off + nr_pages;
369 unsigned long pfn = folio_pfn(new);
370 unsigned long old_tb;
371
372 VM_WARN_ON_ONCE(!folio_test_swapcache(old) || !folio_test_swapcache(new));
373 VM_WARN_ON_ONCE(!folio_test_locked(old) || !folio_test_locked(new));
374 VM_WARN_ON_ONCE(!entry.val);
375
376 /* Swap cache still stores N entries instead of a high-order entry */
377 do {
378 old_tb = __swap_table_get(ci, ci_off);
379 WARN_ON_ONCE(!swp_tb_is_folio(old_tb) || swp_tb_to_folio(old_tb) != old);
380 __swap_table_set(ci, ci_off, pfn_to_swp_tb(pfn, __swp_tb_get_flags(old_tb)));
381 } while (++ci_off < ci_end);
382
383 /*
384 * If the old folio is partially replaced (e.g., splitting a large
385 * folio, the old folio is shrunk, and new split sub folios replace
386 * the shrunk part), ensure the new folio doesn't overlap it.
387 */
388 if (IS_ENABLED(CONFIG_DEBUG_VM) &&
389 folio_order(old) != folio_order(new)) {
390 ci_off = swp_cluster_offset(old->swap);
391 ci_end = ci_off + folio_nr_pages(old);
392 while (ci_off++ < ci_end)
393 WARN_ON_ONCE(swp_tb_to_folio(__swap_table_get(ci, ci_off)) != old);
394 }
395 }
396
397 /*
398 * Try to allocate a folio of given order in the swap cache.
399 *
400 * This helper resolves the potential races of swap allocation
401 * and prepares a folio to be used for swap IO. May return following
402 * value:
403 *
404 * -ENOMEM / -EBUSY: Order is too large or in conflict with sub slot,
405 * caller should shrink the order and retry
406 * -ENOENT / -EEXIST: Target swap entry is unavailable or cached, the caller
407 * should abort or try to use the cached folio instead
408 */
__swap_cache_alloc(struct swap_cluster_info * ci,swp_entry_t targ_entry,gfp_t gfp,unsigned int order,struct vm_fault * vmf,struct mempolicy * mpol,pgoff_t ilx)409 static struct folio *__swap_cache_alloc(struct swap_cluster_info *ci,
410 swp_entry_t targ_entry, gfp_t gfp,
411 unsigned int order, struct vm_fault *vmf,
412 struct mempolicy *mpol, pgoff_t ilx)
413 {
414 int err;
415 swp_entry_t entry;
416 struct folio *folio;
417 void *shadow = NULL;
418 unsigned short memcg_id;
419 unsigned long address, nr_pages = 1UL << order;
420 struct vm_area_struct *vma = vmf ? vmf->vma : NULL;
421
422 VM_WARN_ON_ONCE(nr_pages > SWAPFILE_CLUSTER);
423 entry.val = round_down(targ_entry.val, nr_pages);
424
425 /* Check if the slot and range are available, skip allocation if not */
426 spin_lock(&ci->lock);
427 err = __swap_cache_add_check(ci, targ_entry, nr_pages, NULL, NULL);
428 spin_unlock(&ci->lock);
429 if (unlikely(err))
430 return ERR_PTR(err);
431
432 /*
433 * Limit THP gfp. The limitation is a no-op for typical
434 * GFP_HIGHUSER_MOVABLE but matters for shmem.
435 */
436 if (order)
437 gfp = thp_shmem_limit_gfp_mask(vma_thp_gfp_mask(vma), gfp);
438
439 if (mpol || !vmf) {
440 folio = folio_alloc_mpol(gfp, order, mpol, ilx, numa_node_id());
441 } else {
442 address = round_down(vmf->address, PAGE_SIZE << order);
443 folio = vma_alloc_folio(gfp, order, vmf->vma, address);
444 }
445 if (unlikely(!folio))
446 return ERR_PTR(-ENOMEM);
447
448 /* Double check the range is still not in conflict */
449 spin_lock(&ci->lock);
450 err = __swap_cache_add_check(ci, targ_entry, nr_pages, &shadow, &memcg_id);
451 if (unlikely(err)) {
452 spin_unlock(&ci->lock);
453 folio_put(folio);
454 return ERR_PTR(err);
455 }
456
457 __folio_set_locked(folio);
458 __folio_set_swapbacked(folio);
459 __swap_cache_do_add_folio(ci, folio, entry);
460 spin_unlock(&ci->lock);
461
462 if (mem_cgroup_swapin_charge_folio(folio, memcg_id,
463 vmf ? vmf->vma->vm_mm : NULL, gfp)) {
464 spin_lock(&ci->lock);
465 __swap_cache_do_del_folio(ci, folio, entry, shadow);
466 spin_unlock(&ci->lock);
467 folio_unlock(folio);
468 /* nr_pages refs from swap cache, 1 from allocation */
469 folio_put_refs(folio, nr_pages + 1);
470 count_mthp_stat(order, MTHP_STAT_SWPIN_FALLBACK_CHARGE);
471 return ERR_PTR(-ENOMEM);
472 }
473
474 if (order > 1 && folio_memcg_alloc_deferred(folio)) {
475 spin_lock(&ci->lock);
476 __swap_cache_do_del_folio(ci, folio, entry, shadow);
477 spin_unlock(&ci->lock);
478 folio_unlock(folio);
479 /* nr_pages refs from swap cache, 1 from allocation */
480 folio_put_refs(folio, nr_pages + 1);
481 return ERR_PTR(-ENOMEM);
482 }
483
484 /* memsw uncharges swap when folio is added to swap cache */
485 memcg1_swapin(folio);
486 if (shadow)
487 workingset_refault(folio, shadow);
488
489 node_stat_mod_folio(folio, NR_FILE_PAGES, nr_pages);
490 lruvec_stat_mod_folio(folio, NR_SWAPCACHE, nr_pages);
491
492 /* Caller will initiate read into locked new_folio */
493 folio_add_lru(folio);
494 return folio;
495 }
496
497 /**
498 * swap_cache_alloc_folio - Allocate folio for swapped out slot in swap cache.
499 * @targ_entry: swap entry indicating the target slot
500 * @gfp: memory allocation flags
501 * @orders: allocation orders, must be non zero
502 * @vmf: fault information
503 * @mpol: NUMA memory allocation policy to be applied
504 * @ilx: NUMA interleave index, for use only when MPOL_INTERLEAVE
505 *
506 * Allocate a folio in the swap cache for one swap slot, typically before
507 * doing IO (e.g. swap in or zswap writeback). The swap slot indicated by
508 * @targ_entry must have a non-zero swap count (swapped out).
509 *
510 * Context: Caller must protect the swap device with reference count or locks.
511 * Return: Returns the folio if allocation succeeded and folio is in the swap
512 * cache. Returns error code if failed due to race, OOM or invalid arguments.
513 */
swap_cache_alloc_folio(swp_entry_t targ_entry,gfp_t gfp,unsigned long orders,struct vm_fault * vmf,struct mempolicy * mpol,pgoff_t ilx)514 struct folio *swap_cache_alloc_folio(swp_entry_t targ_entry, gfp_t gfp,
515 unsigned long orders, struct vm_fault *vmf,
516 struct mempolicy *mpol, pgoff_t ilx)
517 {
518 int order, err;
519 struct folio *ret;
520 struct swap_cluster_info *ci;
521
522 ci = __swap_entry_to_cluster(targ_entry);
523 order = highest_order(orders);
524
525 /* orders must be non-zero, and must not exceed cluster size. */
526 if (WARN_ON_ONCE(!orders || (1UL << order) > SWAPFILE_CLUSTER))
527 return ERR_PTR(-EINVAL);
528
529 do {
530 ret = __swap_cache_alloc(ci, targ_entry, gfp, order,
531 vmf, mpol, ilx);
532 if (!IS_ERR(ret))
533 break;
534 err = PTR_ERR(ret);
535 if (!order || (err && err != -EBUSY && err != -ENOMEM))
536 break;
537 count_mthp_stat(order, MTHP_STAT_SWPIN_FALLBACK);
538 order = next_order(&orders, order);
539 } while (orders);
540
541 return ret;
542 }
543
544 /*
545 * If we are the only user, then try to free up the swap cache.
546 *
547 * Its ok to check the swapcache flag without the folio lock
548 * here because we are going to recheck again inside
549 * folio_free_swap() _with_ the lock.
550 * - Marcelo
551 */
free_swap_cache(struct folio * folio)552 void free_swap_cache(struct folio *folio)
553 {
554 if (folio_test_swapcache(folio) && !folio_mapped(folio) &&
555 folio_trylock(folio)) {
556 folio_free_swap(folio);
557 folio_unlock(folio);
558 }
559 }
560
561 /*
562 * Freeing a folio and also freeing any swap cache associated with
563 * this folio if it is the last user.
564 */
free_folio_and_swap_cache(struct folio * folio)565 void free_folio_and_swap_cache(struct folio *folio)
566 {
567 free_swap_cache(folio);
568 if (!is_huge_zero_folio(folio))
569 folio_put(folio);
570 }
571
572 /*
573 * Passed an array of pages, drop them all from swapcache and then release
574 * them. They are removed from the LRU and freed if this is their last use.
575 */
free_pages_and_swap_cache(struct encoded_page ** pages,int nr)576 void free_pages_and_swap_cache(struct encoded_page **pages, int nr)
577 {
578 struct folio_batch folios;
579 unsigned int refs[FOLIO_BATCH_SIZE];
580
581 folio_batch_init(&folios);
582 for (int i = 0; i < nr; i++) {
583 struct folio *folio = page_folio(encoded_page_ptr(pages[i]));
584
585 free_swap_cache(folio);
586 refs[folios.nr] = 1;
587 if (unlikely(encoded_page_flags(pages[i]) &
588 ENCODED_PAGE_BIT_NR_PAGES_NEXT))
589 refs[folios.nr] = encoded_nr_pages(pages[++i]);
590
591 if (folio_batch_add(&folios, folio) == 0)
592 folios_put_refs(&folios, refs);
593 }
594 if (folios.nr)
595 folios_put_refs(&folios, refs);
596 }
597
swap_use_vma_readahead(void)598 static inline bool swap_use_vma_readahead(void)
599 {
600 return READ_ONCE(enable_vma_readahead) && !atomic_read(&nr_rotate_swap);
601 }
602
603 /**
604 * swap_update_readahead - Update the readahead statistics of VMA or globally.
605 * @folio: the swap cache folio that just got hit.
606 * @vma: the VMA that should be updated, could be NULL for global update.
607 * @addr: the addr that triggered the swapin, ignored if @vma is NULL.
608 */
swap_update_readahead(struct folio * folio,struct vm_area_struct * vma,unsigned long addr)609 void swap_update_readahead(struct folio *folio, struct vm_area_struct *vma,
610 unsigned long addr)
611 {
612 bool readahead, vma_ra = swap_use_vma_readahead();
613
614 /*
615 * At the moment, we don't support PG_readahead for anon THP
616 * so let's bail out rather than confusing the readahead stat.
617 */
618 if (unlikely(folio_test_large(folio)))
619 return;
620
621 readahead = folio_test_clear_readahead(folio);
622 if (vma && vma_ra) {
623 unsigned long ra_val;
624 int win, hits;
625
626 ra_val = GET_SWAP_RA_VAL(vma);
627 win = SWAP_RA_WIN(ra_val);
628 hits = SWAP_RA_HITS(ra_val);
629 if (readahead)
630 hits = min_t(int, hits + 1, SWAP_RA_HITS_MAX);
631 atomic_long_set(&vma->swap_readahead_info,
632 SWAP_RA_VAL(addr, win, hits));
633 }
634
635 if (readahead) {
636 count_vm_event(SWAP_RA_HIT);
637 if (!vma || !vma_ra)
638 atomic_inc(&swapin_readahead_hits);
639 }
640 }
641
swap_cache_read_folio(struct swap_io_ctx * ctx,swp_entry_t entry,gfp_t gfp,struct mempolicy * mpol,pgoff_t ilx,bool readahead)642 static struct folio *swap_cache_read_folio(struct swap_io_ctx *ctx,
643 swp_entry_t entry, gfp_t gfp, struct mempolicy *mpol,
644 pgoff_t ilx, bool readahead)
645 {
646 struct folio *folio;
647
648 do {
649 folio = swap_cache_get_folio(entry);
650 if (folio)
651 return folio;
652 folio = swap_cache_alloc_folio(entry, gfp, BIT(0), NULL, mpol, ilx);
653 } while (PTR_ERR(folio) == -EEXIST);
654
655 if (IS_ERR_OR_NULL(folio))
656 return NULL;
657
658 swap_read_folio(ctx, folio);
659 if (readahead) {
660 folio_set_readahead(folio);
661 count_vm_event(SWAP_RA);
662 }
663
664 return folio;
665 }
666
667 /**
668 * swapin_sync - swap-in one or multiple entries skipping readahead.
669 * @entry: swap entry indicating the target slot
670 * @gfp: memory allocation flags
671 * @orders: allocation orders
672 * @vmf: fault information
673 * @mpol: NUMA memory allocation policy to be applied
674 * @ilx: NUMA interleave index, for use only when MPOL_INTERLEAVE
675 *
676 * This allocates a folio suitable for given @orders, or returns the
677 * existing folio in the swap cache for @entry. This initiates the IO, too,
678 * if needed. @entry is rounded down if @orders allow large allocation.
679 *
680 * Context: Caller must ensure @entry is valid and pin the swap device with refcount.
681 * Return: Returns the folio on success, error code if failed.
682 */
swapin_sync(swp_entry_t entry,gfp_t gfp,unsigned long orders,struct vm_fault * vmf,struct mempolicy * mpol,pgoff_t ilx)683 struct folio *swapin_sync(swp_entry_t entry, gfp_t gfp, unsigned long orders,
684 struct vm_fault *vmf, struct mempolicy *mpol, pgoff_t ilx)
685 {
686 struct swap_io_ctx ctx = {};
687 struct folio *folio;
688
689 do {
690 folio = swap_cache_get_folio(entry);
691 if (folio)
692 return folio;
693 folio = swap_cache_alloc_folio(entry, gfp, orders, vmf, mpol, ilx);
694 } while (PTR_ERR(folio) == -EEXIST);
695
696 if (IS_ERR(folio))
697 return folio;
698
699 swap_read_folio(&ctx, folio);
700 swap_read_submit(&ctx);
701 return folio;
702 }
703
704 /*
705 * Locate a page of swap in physical memory, reserving swap cache space
706 * and reading the disk if it is not already cached.
707 * A failure return means that either the page allocation failed or that
708 * the swap entry is no longer in use.
709 */
read_swap_cache_async(struct swap_io_ctx * ctx,swp_entry_t entry,gfp_t gfp_mask,struct vm_area_struct * vma,unsigned long addr)710 struct folio *read_swap_cache_async(struct swap_io_ctx *ctx, swp_entry_t entry,
711 gfp_t gfp_mask, struct vm_area_struct *vma, unsigned long addr)
712 {
713 struct swap_info_struct *si;
714 struct mempolicy *mpol;
715 pgoff_t ilx;
716 struct folio *folio;
717
718 si = get_swap_device(entry);
719 if (!si)
720 return NULL;
721
722 mpol = get_vma_policy(vma, addr, 0, &ilx);
723 folio = swap_cache_read_folio(ctx, entry, gfp_mask, mpol, ilx, false);
724 mpol_cond_put(mpol);
725
726 put_swap_device(si);
727 return folio;
728 }
729
swap_cache_read_folio_sync(swp_entry_t entry,gfp_t gfp,struct mempolicy * mpol,pgoff_t ilx)730 static struct folio *swap_cache_read_folio_sync(swp_entry_t entry, gfp_t gfp,
731 struct mempolicy *mpol, pgoff_t ilx)
732 {
733 struct swap_io_ctx ctx = {};
734 struct folio *folio;
735
736 folio = swap_cache_read_folio(&ctx, entry, gfp, mpol, ilx, false);
737 swap_read_submit(&ctx);
738 return folio;
739 }
740
__swapin_nr_pages(unsigned long prev_offset,unsigned long offset,int hits,int max_pages,int prev_win)741 static unsigned int __swapin_nr_pages(unsigned long prev_offset,
742 unsigned long offset,
743 int hits,
744 int max_pages,
745 int prev_win)
746 {
747 unsigned int pages, last_ra;
748
749 /*
750 * This heuristic has been found to work well on both sequential and
751 * random loads, swapping to hard disk or to SSD: please don't ask
752 * what the "+ 2" means, it just happens to work well, that's all.
753 */
754 pages = hits + 2;
755 if (pages == 2) {
756 /*
757 * We can have no readahead hits to judge by: but must not get
758 * stuck here forever, so check for an adjacent offset instead
759 * (and don't even bother to check whether swap type is same).
760 */
761 if (offset != prev_offset + 1 && offset != prev_offset - 1)
762 pages = 1;
763 } else {
764 unsigned int roundup = 4;
765 while (roundup < pages)
766 roundup <<= 1;
767 pages = roundup;
768 }
769
770 if (pages > max_pages)
771 pages = max_pages;
772
773 /* Don't shrink readahead too fast */
774 last_ra = prev_win / 2;
775 if (pages < last_ra)
776 pages = last_ra;
777
778 return pages;
779 }
780
swapin_nr_pages(unsigned long offset)781 static unsigned long swapin_nr_pages(unsigned long offset)
782 {
783 static unsigned long prev_offset;
784 unsigned int hits, pages, max_pages;
785 static atomic_t last_readahead_pages;
786
787 max_pages = 1 << READ_ONCE(page_cluster);
788 if (max_pages <= 1)
789 return 1;
790
791 hits = atomic_xchg(&swapin_readahead_hits, 0);
792 pages = __swapin_nr_pages(READ_ONCE(prev_offset), offset, hits,
793 max_pages,
794 atomic_read(&last_readahead_pages));
795 if (!hits)
796 WRITE_ONCE(prev_offset, offset);
797 atomic_set(&last_readahead_pages, pages);
798
799 return pages;
800 }
801
802 /**
803 * swap_cluster_readahead - swap in pages in hope we need them soon
804 * @entry: swap entry of this memory
805 * @gfp_mask: memory allocation flags
806 * @mpol: NUMA memory allocation policy to be applied
807 * @ilx: NUMA interleave index, for use only when MPOL_INTERLEAVE
808 *
809 * Returns the struct folio for entry and addr, after queueing swapin.
810 *
811 * Primitive swap readahead code. We simply read an aligned block of
812 * (1 << page_cluster) entries in the swap area. This method is chosen
813 * because it doesn't cost us any seek time. We also make sure to queue
814 * the 'original' request together with the readahead ones...
815 *
816 * Note: it is intentional that the same NUMA policy and interleave index
817 * are used for every page of the readahead: neighbouring pages on swap
818 * are fairly likely to have been swapped out from the same node.
819 */
swap_cluster_readahead(swp_entry_t entry,gfp_t gfp_mask,struct mempolicy * mpol,pgoff_t ilx)820 struct folio *swap_cluster_readahead(swp_entry_t entry, gfp_t gfp_mask,
821 struct mempolicy *mpol, pgoff_t ilx)
822 {
823 struct folio *folio;
824 unsigned long entry_offset = swp_offset(entry);
825 unsigned long offset = entry_offset;
826 unsigned long start_offset, end_offset;
827 unsigned long mask;
828 struct swap_info_struct *si = __swap_entry_to_info(entry);
829 struct swap_io_ctx ctx = {};
830 struct blk_plug plug;
831 swp_entry_t ra_entry;
832
833 mask = swapin_nr_pages(offset) - 1;
834 if (!mask)
835 goto skip;
836
837 /* Read a page_cluster sized and aligned cluster around offset. */
838 start_offset = offset & ~mask;
839 end_offset = offset | mask;
840 if (!start_offset) /* First page is swap header. */
841 start_offset++;
842 if (end_offset >= si->max)
843 end_offset = si->max - 1;
844
845 blk_start_plug(&plug);
846 for (offset = start_offset; offset <= end_offset ; offset++) {
847 /* Ok, do the async read-ahead now */
848 ra_entry = swp_entry(swp_type(entry), offset);
849 folio = swap_cache_read_folio(&ctx, ra_entry, gfp_mask, mpol,
850 ilx, offset != entry_offset);
851 if (!folio)
852 continue;
853 folio_put(folio);
854 }
855 blk_finish_plug(&plug);
856 swap_read_submit(&ctx);
857 skip:
858 return swap_cache_read_folio_sync(entry, gfp_mask, mpol, ilx);
859 }
860
swap_vma_ra_win(struct vm_fault * vmf,unsigned long * start,unsigned long * end)861 static int swap_vma_ra_win(struct vm_fault *vmf, unsigned long *start,
862 unsigned long *end)
863 {
864 struct vm_area_struct *vma = vmf->vma;
865 unsigned long ra_val;
866 unsigned long faddr, prev_faddr, left, right;
867 unsigned int max_win, hits, prev_win, win;
868
869 max_win = 1 << min(READ_ONCE(page_cluster), SWAP_RA_ORDER_CEILING);
870 if (max_win == 1)
871 return 1;
872
873 faddr = vmf->address;
874 ra_val = GET_SWAP_RA_VAL(vma);
875 prev_faddr = SWAP_RA_ADDR(ra_val);
876 prev_win = SWAP_RA_WIN(ra_val);
877 hits = SWAP_RA_HITS(ra_val);
878 win = __swapin_nr_pages(PFN_DOWN(prev_faddr), PFN_DOWN(faddr), hits,
879 max_win, prev_win);
880 atomic_long_set(&vma->swap_readahead_info, SWAP_RA_VAL(faddr, win, 0));
881 if (win == 1)
882 return 1;
883
884 if (faddr == prev_faddr + PAGE_SIZE)
885 left = faddr;
886 else if (prev_faddr == faddr + PAGE_SIZE)
887 left = faddr - (win << PAGE_SHIFT) + PAGE_SIZE;
888 else
889 left = faddr - (((win - 1) / 2) << PAGE_SHIFT);
890 right = left + (win << PAGE_SHIFT);
891 if ((long)left < 0)
892 left = 0;
893 *start = max3(left, vma->vm_start, faddr & PMD_MASK);
894 *end = min3(right, vma->vm_end, (faddr & PMD_MASK) + PMD_SIZE);
895
896 return win;
897 }
898
899 /**
900 * swap_vma_readahead - swap in pages in hope we need them soon
901 * @targ_entry: swap entry of the targeted memory
902 * @gfp_mask: memory allocation flags
903 * @mpol: NUMA memory allocation policy to be applied
904 * @targ_ilx: NUMA interleave index, for use only when MPOL_INTERLEAVE
905 * @vmf: fault information
906 *
907 * Returns the struct folio for entry and addr, after queueing swapin.
908 *
909 * Primitive swap readahead code. We simply read in a few pages whose
910 * virtual addresses are around the fault address in the same vma.
911 *
912 * Caller must hold read mmap_lock if vmf->vma is not NULL.
913 *
914 */
swap_vma_readahead(swp_entry_t targ_entry,gfp_t gfp_mask,struct mempolicy * mpol,pgoff_t targ_ilx,struct vm_fault * vmf)915 static struct folio *swap_vma_readahead(swp_entry_t targ_entry, gfp_t gfp_mask,
916 struct mempolicy *mpol, pgoff_t targ_ilx, struct vm_fault *vmf)
917 {
918 struct swap_io_ctx ctx = {};
919 struct blk_plug plug;
920 struct folio *folio;
921 pte_t *pte = NULL, pentry;
922 int win;
923 unsigned long start, end, addr;
924 pgoff_t ilx = targ_ilx;
925
926 win = swap_vma_ra_win(vmf, &start, &end);
927 if (win == 1)
928 goto skip;
929
930 ilx = targ_ilx - PFN_DOWN(vmf->address - start);
931
932 blk_start_plug(&plug);
933 for (addr = start; addr < end; ilx++, addr += PAGE_SIZE) {
934 struct swap_info_struct *si = NULL;
935 softleaf_t entry;
936
937 if (!pte++) {
938 pte = pte_offset_map(vmf->pmd, addr);
939 if (!pte)
940 break;
941 }
942 pentry = ptep_get_lockless(pte);
943 entry = softleaf_from_pte(pentry);
944
945 if (!softleaf_is_swap(entry))
946 continue;
947 pte_unmap(pte);
948 pte = NULL;
949 /*
950 * Readahead entry may come from a device that we are not
951 * holding a reference to, try to grab a reference, or skip.
952 */
953 if (swp_type(entry) != swp_type(targ_entry)) {
954 si = get_swap_device(entry);
955 if (!si)
956 continue;
957 }
958 folio = swap_cache_read_folio(&ctx, entry, gfp_mask, mpol, ilx,
959 addr != vmf->address);
960 if (si)
961 put_swap_device(si);
962 if (!folio)
963 continue;
964 folio_put(folio);
965 }
966 if (pte)
967 pte_unmap(pte);
968 blk_finish_plug(&plug);
969 swap_read_submit(&ctx);
970 skip:
971 /* The folio was likely read above, so no need for plugging here */
972 return swap_cache_read_folio_sync(targ_entry, gfp_mask, mpol, targ_ilx);
973 }
974
975 /**
976 * swapin_readahead - swap in pages in hope we need them soon
977 * @entry: swap entry of this memory
978 * @gfp_mask: memory allocation flags
979 * @vmf: fault information
980 *
981 * Returns the struct folio for entry and addr, after queueing swapin.
982 *
983 * It's a main entry function for swap readahead. By the configuration,
984 * it will read ahead blocks by cluster-based(ie, physical disk based)
985 * or vma-based(ie, virtual address based on faulty address) readahead.
986 */
swapin_readahead(swp_entry_t entry,gfp_t gfp_mask,struct vm_fault * vmf)987 struct folio *swapin_readahead(swp_entry_t entry, gfp_t gfp_mask,
988 struct vm_fault *vmf)
989 {
990 struct mempolicy *mpol;
991 pgoff_t ilx;
992 struct folio *folio;
993
994 mpol = get_vma_policy(vmf->vma, vmf->address, 0, &ilx);
995 folio = swap_use_vma_readahead() ?
996 swap_vma_readahead(entry, gfp_mask, mpol, ilx, vmf) :
997 swap_cluster_readahead(entry, gfp_mask, mpol, ilx);
998 mpol_cond_put(mpol);
999
1000 return folio;
1001 }
1002
1003 static const struct ctl_table swap_readahead_sysctl_table[] = {
1004 {
1005 .procname = "page-cluster",
1006 .data = &page_cluster,
1007 .maxlen = sizeof(int),
1008 .mode = 0644,
1009 .proc_handler = proc_dointvec_minmax,
1010 .extra1 = SYSCTL_ZERO,
1011 .extra2 = (void *)&page_cluster_max,
1012 }
1013 };
1014
swap_readahead_setup(void)1015 static void __init swap_readahead_setup(void)
1016 {
1017 unsigned long megs = PAGES_TO_MB(totalram_pages());
1018
1019 /* Use a smaller cluster for small-memory machines */
1020 if (megs < 16)
1021 page_cluster = 2;
1022 else
1023 page_cluster = 3;
1024 /*
1025 * Right now other parts of the system means that we
1026 * _really_ don't want to cluster much more
1027 */
1028
1029 register_sysctl_init("vm", swap_readahead_sysctl_table);
1030 }
1031
1032 #ifdef CONFIG_SYSFS
vma_ra_enabled_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)1033 static ssize_t vma_ra_enabled_show(struct kobject *kobj,
1034 struct kobj_attribute *attr, char *buf)
1035 {
1036 return sysfs_emit(buf, "%s\n", str_true_false(enable_vma_readahead));
1037 }
vma_ra_enabled_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)1038 static ssize_t vma_ra_enabled_store(struct kobject *kobj,
1039 struct kobj_attribute *attr,
1040 const char *buf, size_t count)
1041 {
1042 ssize_t ret;
1043
1044 ret = kstrtobool(buf, &enable_vma_readahead);
1045 if (ret)
1046 return ret;
1047
1048 return count;
1049 }
1050 static struct kobj_attribute vma_ra_enabled_attr = __ATTR_RW(vma_ra_enabled);
1051
1052 static struct attribute *swap_attrs[] = {
1053 &vma_ra_enabled_attr.attr,
1054 NULL,
1055 };
1056
1057 static const struct attribute_group swap_attr_group = {
1058 .attrs = swap_attrs,
1059 };
1060
swap_sysfs_init(void)1061 static int __init swap_sysfs_init(void)
1062 {
1063 int err;
1064 struct kobject *swap_kobj;
1065
1066 swap_kobj = kobject_create_and_add("swap", mm_kobj);
1067 if (!swap_kobj) {
1068 pr_err("failed to create swap kobject\n");
1069 return -ENOMEM;
1070 }
1071 err = sysfs_create_group(swap_kobj, &swap_attr_group);
1072 if (err) {
1073 pr_err("failed to register swap group\n");
1074 goto delete_obj;
1075 }
1076 /* Swap cache writeback is LRU based, no tags for it */
1077 mapping_set_no_writeback_tags(&swap_space);
1078 return 0;
1079
1080 delete_obj:
1081 kobject_put(swap_kobj);
1082 return err;
1083 }
1084 #else
swap_sysfs_init(void)1085 static int __init swap_sysfs_init(void)
1086 {
1087 return 0;
1088 }
1089 #endif
1090
swap_init(void)1091 static int __init swap_init(void)
1092 {
1093 swap_readahead_setup();
1094
1095 return swap_sysfs_init();
1096 }
1097 subsys_initcall(swap_init);
1098