readahead.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * mm/readahead.c - address_space-level file readahead.
  4. *
  5. * Copyright (C) 2002, Linus Torvalds
  6. *
  7. * 09Apr2002 Andrew Morton
  8. * Initial version.
  9. */
  10. /**
  11. * DOC: Readahead Overview
  12. *
  13. * Readahead is used to read content into the page cache before it is
  14. * explicitly requested by the application. Readahead only ever
  15. * attempts to read folios that are not yet in the page cache. If a
  16. * folio is present but not up-to-date, readahead will not try to read
  17. * it. In that case a simple ->read_folio() will be requested.
  18. *
  19. * Readahead is triggered when an application read request (whether a
  20. * system call or a page fault) finds that the requested folio is not in
  21. * the page cache, or that it is in the page cache and has the
  22. * readahead flag set. This flag indicates that the folio was read
  23. * as part of a previous readahead request and now that it has been
  24. * accessed, it is time for the next readahead.
  25. *
  26. * Each readahead request is partly synchronous read, and partly async
  27. * readahead. This is reflected in the struct file_ra_state which
  28. * contains ->size being the total number of pages, and ->async_size
  29. * which is the number of pages in the async section. The readahead
  30. * flag will be set on the first folio in this async section to trigger
  31. * a subsequent readahead. Once a series of sequential reads has been
  32. * established, there should be no need for a synchronous component and
  33. * all readahead request will be fully asynchronous.
  34. *
  35. * When either of the triggers causes a readahead, three numbers need
  36. * to be determined: the start of the region to read, the size of the
  37. * region, and the size of the async tail.
  38. *
  39. * The start of the region is simply the first page address at or after
  40. * the accessed address, which is not currently populated in the page
  41. * cache. This is found with a simple search in the page cache.
  42. *
  43. * The size of the async tail is determined by subtracting the size that
  44. * was explicitly requested from the determined request size, unless
  45. * this would be less than zero - then zero is used. NOTE THIS
  46. * CALCULATION IS WRONG WHEN THE START OF THE REGION IS NOT THE ACCESSED
  47. * PAGE. ALSO THIS CALCULATION IS NOT USED CONSISTENTLY.
  48. *
  49. * The size of the region is normally determined from the size of the
  50. * previous readahead which loaded the preceding pages. This may be
  51. * discovered from the struct file_ra_state for simple sequential reads,
  52. * or from examining the state of the page cache when multiple
  53. * sequential reads are interleaved. Specifically: where the readahead
  54. * was triggered by the readahead flag, the size of the previous
  55. * readahead is assumed to be the number of pages from the triggering
  56. * page to the start of the new readahead. In these cases, the size of
  57. * the previous readahead is scaled, often doubled, for the new
  58. * readahead, though see get_next_ra_size() for details.
  59. *
  60. * If the size of the previous read cannot be determined, the number of
  61. * preceding pages in the page cache is used to estimate the size of
  62. * a previous read. This estimate could easily be misled by random
  63. * reads being coincidentally adjacent, so it is ignored unless it is
  64. * larger than the current request, and it is not scaled up, unless it
  65. * is at the start of file.
  66. *
  67. * In general readahead is accelerated at the start of the file, as
  68. * reads from there are often sequential. There are other minor
  69. * adjustments to the readahead size in various special cases and these
  70. * are best discovered by reading the code.
  71. *
  72. * The above calculation, based on the previous readahead size,
  73. * determines the size of the readahead, to which any requested read
  74. * size may be added.
  75. *
  76. * Readahead requests are sent to the filesystem using the ->readahead()
  77. * address space operation, for which mpage_readahead() is a canonical
  78. * implementation. ->readahead() should normally initiate reads on all
  79. * folios, but may fail to read any or all folios without causing an I/O
  80. * error. The page cache reading code will issue a ->read_folio() request
  81. * for any folio which ->readahead() did not read, and only an error
  82. * from this will be final.
  83. *
  84. * ->readahead() will generally call readahead_folio() repeatedly to get
  85. * each folio from those prepared for readahead. It may fail to read a
  86. * folio by:
  87. *
  88. * * not calling readahead_folio() sufficiently many times, effectively
  89. * ignoring some folios, as might be appropriate if the path to
  90. * storage is congested.
  91. *
  92. * * failing to actually submit a read request for a given folio,
  93. * possibly due to insufficient resources, or
  94. *
  95. * * getting an error during subsequent processing of a request.
  96. *
  97. * In the last two cases, the folio should be unlocked by the filesystem
  98. * to indicate that the read attempt has failed. In the first case the
  99. * folio will be unlocked by the VFS.
  100. *
  101. * Those folios not in the final ``async_size`` of the request should be
  102. * considered to be important and ->readahead() should not fail them due
  103. * to congestion or temporary resource unavailability, but should wait
  104. * for necessary resources (e.g. memory or indexing information) to
  105. * become available. Folios in the final ``async_size`` may be
  106. * considered less urgent and failure to read them is more acceptable.
  107. * In this case it is best to use filemap_remove_folio() to remove the
  108. * folios from the page cache as is automatically done for folios that
  109. * were not fetched with readahead_folio(). This will allow a
  110. * subsequent synchronous readahead request to try them again. If they
  111. * are left in the page cache, then they will be read individually using
  112. * ->read_folio() which may be less efficient.
  113. */
  114. #include <linux/blkdev.h>
  115. #include <linux/kernel.h>
  116. #include <linux/dax.h>
  117. #include <linux/gfp.h>
  118. #include <linux/export.h>
  119. #include <linux/backing-dev.h>
  120. #include <linux/task_io_accounting_ops.h>
  121. #include <linux/pagemap.h>
  122. #include <linux/psi.h>
  123. #include <linux/syscalls.h>
  124. #include <linux/file.h>
  125. #include <linux/mm_inline.h>
  126. #include <linux/blk-cgroup.h>
  127. #include <linux/fadvise.h>
  128. #include <linux/sched/mm.h>
  129. #define CREATE_TRACE_POINTS
  130. #include <trace/events/readahead.h>
  131. #include "internal.h"
  132. /*
  133. * Initialise a struct file's readahead state. Assumes that the caller has
  134. * memset *ra to zero.
  135. */
  136. void
  137. file_ra_state_init(struct file_ra_state *ra, struct address_space *mapping)
  138. {
  139. ra->ra_pages = inode_to_bdi(mapping->host)->ra_pages;
  140. ra->prev_pos = -1;
  141. }
  142. EXPORT_SYMBOL_GPL(file_ra_state_init);
  143. static void read_pages(struct readahead_control *rac)
  144. {
  145. const struct address_space_operations *aops = rac->mapping->a_ops;
  146. struct folio *folio;
  147. struct blk_plug plug;
  148. if (!readahead_count(rac))
  149. return;
  150. if (unlikely(rac->_workingset))
  151. psi_memstall_enter(&rac->_pflags);
  152. blk_start_plug(&plug);
  153. if (aops->readahead) {
  154. aops->readahead(rac);
  155. /* Clean up the remaining folios. */
  156. while ((folio = readahead_folio(rac)) != NULL) {
  157. folio_get(folio);
  158. filemap_remove_folio(folio);
  159. folio_unlock(folio);
  160. folio_put(folio);
  161. }
  162. } else {
  163. while ((folio = readahead_folio(rac)) != NULL)
  164. aops->read_folio(rac->file, folio);
  165. }
  166. blk_finish_plug(&plug);
  167. if (unlikely(rac->_workingset))
  168. psi_memstall_leave(&rac->_pflags);
  169. rac->_workingset = false;
  170. BUG_ON(readahead_count(rac));
  171. }
  172. static struct folio *ractl_alloc_folio(struct readahead_control *ractl,
  173. gfp_t gfp_mask, unsigned int order)
  174. {
  175. struct folio *folio;
  176. folio = filemap_alloc_folio(gfp_mask, order, NULL);
  177. if (folio && ractl->dropbehind)
  178. __folio_set_dropbehind(folio);
  179. return folio;
  180. }
  181. /**
  182. * page_cache_ra_unbounded - Start unchecked readahead.
  183. * @ractl: Readahead control.
  184. * @nr_to_read: The number of pages to read.
  185. * @lookahead_size: Where to start the next readahead.
  186. *
  187. * This function is for filesystems to call when they want to start
  188. * readahead beyond a file's stated i_size. This is almost certainly
  189. * not the function you want to call. Use page_cache_async_readahead()
  190. * or page_cache_sync_readahead() instead.
  191. *
  192. * Context: File is referenced by caller, and ractl->mapping->invalidate_lock
  193. * must be held by the caller at least in shared mode. Mutexes may be held by
  194. * caller. May sleep, but will not reenter filesystem to reclaim memory.
  195. */
  196. void page_cache_ra_unbounded(struct readahead_control *ractl,
  197. unsigned long nr_to_read, unsigned long lookahead_size)
  198. {
  199. struct address_space *mapping = ractl->mapping;
  200. unsigned long index = readahead_index(ractl);
  201. gfp_t gfp_mask = readahead_gfp_mask(mapping);
  202. unsigned long mark = ULONG_MAX, i = 0;
  203. unsigned int min_nrpages = mapping_min_folio_nrpages(mapping);
  204. /*
  205. * Partway through the readahead operation, we will have added
  206. * locked pages to the page cache, but will not yet have submitted
  207. * them for I/O. Adding another page may need to allocate memory,
  208. * which can trigger memory reclaim. Telling the VM we're in
  209. * the middle of a filesystem operation will cause it to not
  210. * touch file-backed pages, preventing a deadlock. Most (all?)
  211. * filesystems already specify __GFP_NOFS in their mapping's
  212. * gfp_mask, but let's be explicit here.
  213. */
  214. unsigned int nofs = memalloc_nofs_save();
  215. lockdep_assert_held(&mapping->invalidate_lock);
  216. trace_page_cache_ra_unbounded(mapping->host, index, nr_to_read,
  217. lookahead_size);
  218. index = mapping_align_index(mapping, index);
  219. /*
  220. * As iterator `i` is aligned to min_nrpages, round_up the
  221. * difference between nr_to_read and lookahead_size to mark the
  222. * index that only has lookahead or "async_region" to set the
  223. * readahead flag.
  224. */
  225. if (lookahead_size <= nr_to_read) {
  226. unsigned long ra_folio_index;
  227. ra_folio_index = round_up(readahead_index(ractl) +
  228. nr_to_read - lookahead_size,
  229. min_nrpages);
  230. mark = ra_folio_index - index;
  231. }
  232. nr_to_read += readahead_index(ractl) - index;
  233. ractl->_index = index;
  234. /*
  235. * Preallocate as many pages as we will need.
  236. */
  237. while (i < nr_to_read) {
  238. struct folio *folio = xa_load(&mapping->i_pages, index + i);
  239. int ret;
  240. if (folio && !xa_is_value(folio)) {
  241. /*
  242. * Page already present? Kick off the current batch
  243. * of contiguous pages before continuing with the
  244. * next batch. This page may be the one we would
  245. * have intended to mark as Readahead, but we don't
  246. * have a stable reference to this page, and it's
  247. * not worth getting one just for that.
  248. */
  249. read_pages(ractl);
  250. ractl->_index += min_nrpages;
  251. i = ractl->_index + ractl->_nr_pages - index;
  252. continue;
  253. }
  254. folio = ractl_alloc_folio(ractl, gfp_mask,
  255. mapping_min_folio_order(mapping));
  256. if (!folio)
  257. break;
  258. ret = filemap_add_folio(mapping, folio, index + i, gfp_mask);
  259. if (ret < 0) {
  260. folio_put(folio);
  261. if (ret == -ENOMEM)
  262. break;
  263. read_pages(ractl);
  264. ractl->_index += min_nrpages;
  265. i = ractl->_index + ractl->_nr_pages - index;
  266. continue;
  267. }
  268. if (i == mark)
  269. folio_set_readahead(folio);
  270. ractl->_workingset |= folio_test_workingset(folio);
  271. ractl->_nr_pages += min_nrpages;
  272. i += min_nrpages;
  273. }
  274. /*
  275. * Now start the IO. We ignore I/O errors - if the folio is not
  276. * uptodate then the caller will launch read_folio again, and
  277. * will then handle the error.
  278. */
  279. read_pages(ractl);
  280. memalloc_nofs_restore(nofs);
  281. }
  282. EXPORT_SYMBOL_GPL(page_cache_ra_unbounded);
  283. /*
  284. * do_page_cache_ra() actually reads a chunk of disk. It allocates
  285. * the pages first, then submits them for I/O. This avoids the very bad
  286. * behaviour which would occur if page allocations are causing VM writeback.
  287. * We really don't want to intermingle reads and writes like that.
  288. */
  289. static void do_page_cache_ra(struct readahead_control *ractl,
  290. unsigned long nr_to_read, unsigned long lookahead_size)
  291. {
  292. struct address_space *mapping = ractl->mapping;
  293. unsigned long index = readahead_index(ractl);
  294. loff_t isize = i_size_read(mapping->host);
  295. pgoff_t end_index; /* The last page we want to read */
  296. if (isize == 0)
  297. return;
  298. end_index = (isize - 1) >> PAGE_SHIFT;
  299. if (index > end_index)
  300. return;
  301. /* Don't read past the page containing the last byte of the file */
  302. if (nr_to_read > end_index - index)
  303. nr_to_read = end_index - index + 1;
  304. filemap_invalidate_lock_shared(mapping);
  305. page_cache_ra_unbounded(ractl, nr_to_read, lookahead_size);
  306. filemap_invalidate_unlock_shared(mapping);
  307. }
  308. /*
  309. * Chunk the readahead into 2 megabyte units, so that we don't pin too much
  310. * memory at once.
  311. */
  312. void force_page_cache_ra(struct readahead_control *ractl,
  313. unsigned long nr_to_read)
  314. {
  315. struct address_space *mapping = ractl->mapping;
  316. struct file_ra_state *ra = ractl->ra;
  317. struct backing_dev_info *bdi = inode_to_bdi(mapping->host);
  318. unsigned long max_pages;
  319. if (unlikely(!mapping->a_ops->read_folio && !mapping->a_ops->readahead))
  320. return;
  321. /*
  322. * If the request exceeds the readahead window, allow the read to
  323. * be up to the optimal hardware IO size
  324. */
  325. max_pages = max_t(unsigned long, bdi->io_pages, ra->ra_pages);
  326. nr_to_read = min_t(unsigned long, nr_to_read, max_pages);
  327. while (nr_to_read) {
  328. unsigned long this_chunk = (2 * 1024 * 1024) / PAGE_SIZE;
  329. if (this_chunk > nr_to_read)
  330. this_chunk = nr_to_read;
  331. do_page_cache_ra(ractl, this_chunk, 0);
  332. nr_to_read -= this_chunk;
  333. }
  334. }
  335. /*
  336. * Set the initial window size, round to next power of 2 and square
  337. * for small size, x 4 for medium, and x 2 for large
  338. * for 128k (32 page) max ra
  339. * 1-2 page = 16k, 3-4 page 32k, 5-8 page = 64k, > 8 page = 128k initial
  340. */
  341. static unsigned long get_init_ra_size(unsigned long size, unsigned long max)
  342. {
  343. unsigned long newsize = roundup_pow_of_two(size);
  344. if (newsize <= max / 32)
  345. newsize = newsize * 4;
  346. else if (newsize <= max / 4)
  347. newsize = newsize * 2;
  348. else
  349. newsize = max;
  350. return newsize;
  351. }
  352. /*
  353. * Get the previous window size, ramp it up, and
  354. * return it as the new window size.
  355. */
  356. static unsigned long get_next_ra_size(struct file_ra_state *ra,
  357. unsigned long max)
  358. {
  359. unsigned long cur = ra->size;
  360. if (cur < max / 16)
  361. return 4 * cur;
  362. if (cur <= max / 2)
  363. return 2 * cur;
  364. return max;
  365. }
  366. /*
  367. * On-demand readahead design.
  368. *
  369. * The fields in struct file_ra_state represent the most-recently-executed
  370. * readahead attempt:
  371. *
  372. * |<----- async_size ---------|
  373. * |------------------- size -------------------->|
  374. * |==================#===========================|
  375. * ^start ^page marked with PG_readahead
  376. *
  377. * To overlap application thinking time and disk I/O time, we do
  378. * `readahead pipelining': Do not wait until the application consumed all
  379. * readahead pages and stalled on the missing page at readahead_index;
  380. * Instead, submit an asynchronous readahead I/O as soon as there are
  381. * only async_size pages left in the readahead window. Normally async_size
  382. * will be equal to size, for maximum pipelining.
  383. *
  384. * In interleaved sequential reads, concurrent streams on the same fd can
  385. * be invalidating each other's readahead state. So we flag the new readahead
  386. * page at (start+size-async_size) with PG_readahead, and use it as readahead
  387. * indicator. The flag won't be set on already cached pages, to avoid the
  388. * readahead-for-nothing fuss, saving pointless page cache lookups.
  389. *
  390. * prev_pos tracks the last visited byte in the _previous_ read request.
  391. * It should be maintained by the caller, and will be used for detecting
  392. * small random reads. Note that the readahead algorithm checks loosely
  393. * for sequential patterns. Hence interleaved reads might be served as
  394. * sequential ones.
  395. *
  396. * There is a special-case: if the first page which the application tries to
  397. * read happens to be the first page of the file, it is assumed that a linear
  398. * read is about to happen and the window is immediately set to the initial size
  399. * based on I/O request size and the max_readahead.
  400. *
  401. * The code ramps up the readahead size aggressively at first, but slow down as
  402. * it approaches max_readahead.
  403. */
  404. static inline int ra_alloc_folio(struct readahead_control *ractl, pgoff_t index,
  405. pgoff_t mark, unsigned int order, gfp_t gfp)
  406. {
  407. int err;
  408. struct folio *folio = ractl_alloc_folio(ractl, gfp, order);
  409. if (!folio)
  410. return -ENOMEM;
  411. mark = round_down(mark, 1UL << order);
  412. if (index == mark)
  413. folio_set_readahead(folio);
  414. err = filemap_add_folio(ractl->mapping, folio, index, gfp);
  415. if (err) {
  416. folio_put(folio);
  417. return err;
  418. }
  419. ractl->_nr_pages += 1UL << order;
  420. ractl->_workingset |= folio_test_workingset(folio);
  421. return 0;
  422. }
  423. void page_cache_ra_order(struct readahead_control *ractl,
  424. struct file_ra_state *ra)
  425. {
  426. struct address_space *mapping = ractl->mapping;
  427. pgoff_t start = readahead_index(ractl);
  428. pgoff_t index = start;
  429. unsigned int min_order = mapping_min_folio_order(mapping);
  430. pgoff_t limit = (i_size_read(mapping->host) - 1) >> PAGE_SHIFT;
  431. pgoff_t mark = index + ra->size - ra->async_size;
  432. unsigned int nofs;
  433. int err = 0;
  434. gfp_t gfp = readahead_gfp_mask(mapping);
  435. unsigned int new_order = ra->order;
  436. trace_page_cache_ra_order(mapping->host, start, ra);
  437. if (!mapping_large_folio_support(mapping)) {
  438. ra->order = 0;
  439. goto fallback;
  440. }
  441. limit = min(limit, index + ra->size - 1);
  442. new_order = min(mapping_max_folio_order(mapping), new_order);
  443. new_order = min_t(unsigned int, new_order, ilog2(ra->size));
  444. new_order = max(new_order, min_order);
  445. ra->order = new_order;
  446. /* See comment in page_cache_ra_unbounded() */
  447. nofs = memalloc_nofs_save();
  448. filemap_invalidate_lock_shared(mapping);
  449. /*
  450. * If the new_order is greater than min_order and index is
  451. * already aligned to new_order, then this will be noop as index
  452. * aligned to new_order should also be aligned to min_order.
  453. */
  454. ractl->_index = mapping_align_index(mapping, index);
  455. index = readahead_index(ractl);
  456. while (index <= limit) {
  457. unsigned int order = new_order;
  458. /* Align with smaller pages if needed */
  459. if (index & ((1UL << order) - 1))
  460. order = __ffs(index);
  461. /* Don't allocate pages past EOF */
  462. while (order > min_order && index + (1UL << order) - 1 > limit)
  463. order--;
  464. err = ra_alloc_folio(ractl, index, mark, order, gfp);
  465. if (err)
  466. break;
  467. index += 1UL << order;
  468. }
  469. read_pages(ractl);
  470. filemap_invalidate_unlock_shared(mapping);
  471. memalloc_nofs_restore(nofs);
  472. /*
  473. * If there were already pages in the page cache, then we may have
  474. * left some gaps. Let the regular readahead code take care of this
  475. * situation below.
  476. */
  477. if (!err)
  478. return;
  479. fallback:
  480. /*
  481. * ->readahead() may have updated readahead window size so we have to
  482. * check there's still something to read.
  483. */
  484. if (ra->size > index - start)
  485. do_page_cache_ra(ractl, ra->size - (index - start),
  486. ra->async_size);
  487. }
  488. static unsigned long ractl_max_pages(struct readahead_control *ractl,
  489. unsigned long req_size)
  490. {
  491. struct backing_dev_info *bdi = inode_to_bdi(ractl->mapping->host);
  492. unsigned long max_pages = ractl->ra->ra_pages;
  493. /*
  494. * If the request exceeds the readahead window, allow the read to
  495. * be up to the optimal hardware IO size
  496. */
  497. if (req_size > max_pages && bdi->io_pages > max_pages)
  498. max_pages = min(req_size, bdi->io_pages);
  499. return max_pages;
  500. }
  501. void page_cache_sync_ra(struct readahead_control *ractl,
  502. unsigned long req_count)
  503. {
  504. pgoff_t index = readahead_index(ractl);
  505. bool do_forced_ra = ractl->file && (ractl->file->f_mode & FMODE_RANDOM);
  506. struct file_ra_state *ra = ractl->ra;
  507. unsigned long max_pages, contig_count;
  508. pgoff_t prev_index, miss;
  509. trace_page_cache_sync_ra(ractl->mapping->host, index, ra, req_count);
  510. /*
  511. * Even if readahead is disabled, issue this request as readahead
  512. * as we'll need it to satisfy the requested range. The forced
  513. * readahead will do the right thing and limit the read to just the
  514. * requested range, which we'll set to 1 page for this case.
  515. */
  516. if (!ra->ra_pages || blk_cgroup_congested()) {
  517. if (!ractl->file)
  518. return;
  519. req_count = 1;
  520. do_forced_ra = true;
  521. }
  522. /* be dumb */
  523. if (do_forced_ra) {
  524. force_page_cache_ra(ractl, req_count);
  525. return;
  526. }
  527. max_pages = ractl_max_pages(ractl, req_count);
  528. prev_index = (unsigned long long)ra->prev_pos >> PAGE_SHIFT;
  529. /*
  530. * A start of file, oversized read, or sequential cache miss:
  531. * trivial case: (index - prev_index) == 1
  532. * unaligned reads: (index - prev_index) == 0
  533. */
  534. if (!index || req_count > max_pages || index - prev_index <= 1UL) {
  535. ra->start = index;
  536. ra->size = get_init_ra_size(req_count, max_pages);
  537. ra->async_size = ra->size > req_count ? ra->size - req_count :
  538. ra->size >> 1;
  539. goto readit;
  540. }
  541. /*
  542. * Query the page cache and look for the traces(cached history pages)
  543. * that a sequential stream would leave behind.
  544. */
  545. rcu_read_lock();
  546. miss = page_cache_prev_miss(ractl->mapping, index - 1, max_pages);
  547. rcu_read_unlock();
  548. contig_count = index - miss - 1;
  549. /*
  550. * Standalone, small random read. Read as is, and do not pollute the
  551. * readahead state.
  552. */
  553. if (contig_count <= req_count) {
  554. do_page_cache_ra(ractl, req_count, 0);
  555. return;
  556. }
  557. /*
  558. * File cached from the beginning:
  559. * it is a strong indication of long-run stream (or whole-file-read)
  560. */
  561. if (miss == ULONG_MAX)
  562. contig_count *= 2;
  563. ra->start = index;
  564. ra->size = min(contig_count + req_count, max_pages);
  565. ra->async_size = 1;
  566. readit:
  567. ra->order = 0;
  568. ractl->_index = ra->start;
  569. page_cache_ra_order(ractl, ra);
  570. }
  571. EXPORT_SYMBOL_GPL(page_cache_sync_ra);
  572. void page_cache_async_ra(struct readahead_control *ractl,
  573. struct folio *folio, unsigned long req_count)
  574. {
  575. unsigned long max_pages;
  576. struct file_ra_state *ra = ractl->ra;
  577. pgoff_t index = readahead_index(ractl);
  578. pgoff_t expected, start, end, aligned_end, align;
  579. /* no readahead */
  580. if (!ra->ra_pages)
  581. return;
  582. /*
  583. * Same bit is used for PG_readahead and PG_reclaim.
  584. */
  585. if (folio_test_writeback(folio))
  586. return;
  587. trace_page_cache_async_ra(ractl->mapping->host, index, ra, req_count);
  588. folio_clear_readahead(folio);
  589. if (blk_cgroup_congested())
  590. return;
  591. max_pages = ractl_max_pages(ractl, req_count);
  592. /*
  593. * It's the expected callback index, assume sequential access.
  594. * Ramp up sizes, and push forward the readahead window.
  595. */
  596. expected = round_down(ra->start + ra->size - ra->async_size,
  597. folio_nr_pages(folio));
  598. if (index == expected) {
  599. ra->start += ra->size;
  600. /*
  601. * In the case of MADV_HUGEPAGE, the actual size might exceed
  602. * the readahead window.
  603. */
  604. ra->size = max(ra->size, get_next_ra_size(ra, max_pages));
  605. goto readit;
  606. }
  607. /*
  608. * Hit a marked folio without valid readahead state.
  609. * E.g. interleaved reads.
  610. * Query the pagecache for async_size, which normally equals to
  611. * readahead size. Ramp it up and use it as the new readahead size.
  612. */
  613. rcu_read_lock();
  614. start = page_cache_next_miss(ractl->mapping, index + 1, max_pages);
  615. rcu_read_unlock();
  616. if (!start || start - index > max_pages)
  617. return;
  618. ra->start = start;
  619. ra->size = start - index; /* old async_size */
  620. ra->size += req_count;
  621. ra->size = get_next_ra_size(ra, max_pages);
  622. readit:
  623. ra->order += 2;
  624. align = 1UL << min(ra->order, ffs(max_pages) - 1);
  625. end = ra->start + ra->size;
  626. aligned_end = round_down(end, align);
  627. if (aligned_end > ra->start)
  628. ra->size -= end - aligned_end;
  629. ra->async_size = ra->size;
  630. ractl->_index = ra->start;
  631. page_cache_ra_order(ractl, ra);
  632. }
  633. EXPORT_SYMBOL_GPL(page_cache_async_ra);
  634. ssize_t ksys_readahead(int fd, loff_t offset, size_t count)
  635. {
  636. struct file *file;
  637. const struct inode *inode;
  638. CLASS(fd, f)(fd);
  639. if (fd_empty(f))
  640. return -EBADF;
  641. file = fd_file(f);
  642. if (!(file->f_mode & FMODE_READ))
  643. return -EBADF;
  644. /*
  645. * The readahead() syscall is intended to run only on files
  646. * that can execute readahead. If readahead is not possible
  647. * on this file, then we must return -EINVAL.
  648. */
  649. if (!file->f_mapping)
  650. return -EINVAL;
  651. if (!file->f_mapping->a_ops)
  652. return -EINVAL;
  653. inode = file_inode(file);
  654. if (!S_ISREG(inode->i_mode) && !S_ISBLK(inode->i_mode))
  655. return -EINVAL;
  656. if (IS_ANON_FILE(inode))
  657. return -EINVAL;
  658. return vfs_fadvise(fd_file(f), offset, count, POSIX_FADV_WILLNEED);
  659. }
  660. SYSCALL_DEFINE3(readahead, int, fd, loff_t, offset, size_t, count)
  661. {
  662. return ksys_readahead(fd, offset, count);
  663. }
  664. #if defined(CONFIG_COMPAT) && defined(__ARCH_WANT_COMPAT_READAHEAD)
  665. COMPAT_SYSCALL_DEFINE4(readahead, int, fd, compat_arg_u64_dual(offset), size_t, count)
  666. {
  667. return ksys_readahead(fd, compat_arg_u64_glue(offset), count);
  668. }
  669. #endif
  670. /**
  671. * readahead_expand - Expand a readahead request
  672. * @ractl: The request to be expanded
  673. * @new_start: The revised start
  674. * @new_len: The revised size of the request
  675. *
  676. * Attempt to expand a readahead request outwards from the current size to the
  677. * specified size by inserting locked pages before and after the current window
  678. * to increase the size to the new window. This may involve the insertion of
  679. * THPs, in which case the window may get expanded even beyond what was
  680. * requested.
  681. *
  682. * The algorithm will stop if it encounters a conflicting page already in the
  683. * pagecache and leave a smaller expansion than requested.
  684. *
  685. * The caller must check for this by examining the revised @ractl object for a
  686. * different expansion than was requested.
  687. */
  688. void readahead_expand(struct readahead_control *ractl,
  689. loff_t new_start, size_t new_len)
  690. {
  691. struct address_space *mapping = ractl->mapping;
  692. struct file_ra_state *ra = ractl->ra;
  693. pgoff_t new_index, new_nr_pages;
  694. gfp_t gfp_mask = readahead_gfp_mask(mapping);
  695. unsigned long min_nrpages = mapping_min_folio_nrpages(mapping);
  696. unsigned int min_order = mapping_min_folio_order(mapping);
  697. new_index = new_start / PAGE_SIZE;
  698. /*
  699. * Readahead code should have aligned the ractl->_index to
  700. * min_nrpages before calling readahead aops.
  701. */
  702. VM_BUG_ON(!IS_ALIGNED(ractl->_index, min_nrpages));
  703. /* Expand the leading edge downwards */
  704. while (ractl->_index > new_index) {
  705. unsigned long index = ractl->_index - 1;
  706. struct folio *folio = xa_load(&mapping->i_pages, index);
  707. if (folio && !xa_is_value(folio))
  708. return; /* Folio apparently present */
  709. folio = ractl_alloc_folio(ractl, gfp_mask, min_order);
  710. if (!folio)
  711. return;
  712. index = mapping_align_index(mapping, index);
  713. if (filemap_add_folio(mapping, folio, index, gfp_mask) < 0) {
  714. folio_put(folio);
  715. return;
  716. }
  717. if (unlikely(folio_test_workingset(folio)) &&
  718. !ractl->_workingset) {
  719. ractl->_workingset = true;
  720. psi_memstall_enter(&ractl->_pflags);
  721. }
  722. ractl->_nr_pages += min_nrpages;
  723. ractl->_index = folio->index;
  724. }
  725. new_len += new_start - readahead_pos(ractl);
  726. new_nr_pages = DIV_ROUND_UP(new_len, PAGE_SIZE);
  727. /* Expand the trailing edge upwards */
  728. while (ractl->_nr_pages < new_nr_pages) {
  729. unsigned long index = ractl->_index + ractl->_nr_pages;
  730. struct folio *folio = xa_load(&mapping->i_pages, index);
  731. if (folio && !xa_is_value(folio))
  732. return; /* Folio apparently present */
  733. folio = ractl_alloc_folio(ractl, gfp_mask, min_order);
  734. if (!folio)
  735. return;
  736. index = mapping_align_index(mapping, index);
  737. if (filemap_add_folio(mapping, folio, index, gfp_mask) < 0) {
  738. folio_put(folio);
  739. return;
  740. }
  741. if (unlikely(folio_test_workingset(folio)) &&
  742. !ractl->_workingset) {
  743. ractl->_workingset = true;
  744. psi_memstall_enter(&ractl->_pflags);
  745. }
  746. ractl->_nr_pages += min_nrpages;
  747. if (ra) {
  748. ra->size += min_nrpages;
  749. ra->async_size += min_nrpages;
  750. }
  751. }
  752. }
  753. EXPORT_SYMBOL(readahead_expand);