swap_state.c 26 KB

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