readahead.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  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. #include "internal.h"
  130. /*
  131. * Initialise a struct file's readahead state. Assumes that the caller has
  132. * memset *ra to zero.
  133. */
  134. void
  135. file_ra_state_init(struct file_ra_state *ra, struct address_space *mapping)
  136. {
  137. ra->ra_pages = inode_to_bdi(mapping->host)->ra_pages;
  138. ra->prev_pos = -1;
  139. }
  140. EXPORT_SYMBOL_GPL(file_ra_state_init);
  141. static void read_pages(struct readahead_control *rac)
  142. {
  143. const struct address_space_operations *aops = rac->mapping->a_ops;
  144. struct folio *folio;
  145. struct blk_plug plug;
  146. if (!readahead_count(rac))
  147. return;
  148. if (unlikely(rac->_workingset))
  149. psi_memstall_enter(&rac->_pflags);
  150. blk_start_plug(&plug);
  151. if (aops->readahead) {
  152. aops->readahead(rac);
  153. /*
  154. * Clean up the remaining folios. The sizes in ->ra
  155. * may be used to size the next readahead, so make sure
  156. * they accurately reflect what happened.
  157. */
  158. while ((folio = readahead_folio(rac)) != NULL) {
  159. unsigned long nr = folio_nr_pages(folio);
  160. folio_get(folio);
  161. rac->ra->size -= nr;
  162. if (rac->ra->async_size >= nr) {
  163. rac->ra->async_size -= nr;
  164. filemap_remove_folio(folio);
  165. }
  166. folio_unlock(folio);
  167. folio_put(folio);
  168. }
  169. } else {
  170. while ((folio = readahead_folio(rac)) != NULL)
  171. aops->read_folio(rac->file, folio);
  172. }
  173. blk_finish_plug(&plug);
  174. if (unlikely(rac->_workingset))
  175. psi_memstall_leave(&rac->_pflags);
  176. rac->_workingset = false;
  177. BUG_ON(readahead_count(rac));
  178. }
  179. /**
  180. * page_cache_ra_unbounded - Start unchecked readahead.
  181. * @ractl: Readahead control.
  182. * @nr_to_read: The number of pages to read.
  183. * @lookahead_size: Where to start the next readahead.
  184. *
  185. * This function is for filesystems to call when they want to start
  186. * readahead beyond a file's stated i_size. This is almost certainly
  187. * not the function you want to call. Use page_cache_async_readahead()
  188. * or page_cache_sync_readahead() instead.
  189. *
  190. * Context: File is referenced by caller. Mutexes may be held by caller.
  191. * May sleep, but will not reenter filesystem to reclaim memory.
  192. */
  193. void page_cache_ra_unbounded(struct readahead_control *ractl,
  194. unsigned long nr_to_read, unsigned long lookahead_size)
  195. {
  196. struct address_space *mapping = ractl->mapping;
  197. unsigned long ra_folio_index, index = readahead_index(ractl);
  198. gfp_t gfp_mask = readahead_gfp_mask(mapping);
  199. unsigned long mark, i = 0;
  200. unsigned int min_nrpages = mapping_min_folio_nrpages(mapping);
  201. /*
  202. * Partway through the readahead operation, we will have added
  203. * locked pages to the page cache, but will not yet have submitted
  204. * them for I/O. Adding another page may need to allocate memory,
  205. * which can trigger memory reclaim. Telling the VM we're in
  206. * the middle of a filesystem operation will cause it to not
  207. * touch file-backed pages, preventing a deadlock. Most (all?)
  208. * filesystems already specify __GFP_NOFS in their mapping's
  209. * gfp_mask, but let's be explicit here.
  210. */
  211. unsigned int nofs = memalloc_nofs_save();
  212. filemap_invalidate_lock_shared(mapping);
  213. index = mapping_align_index(mapping, index);
  214. /*
  215. * As iterator `i` is aligned to min_nrpages, round_up the
  216. * difference between nr_to_read and lookahead_size to mark the
  217. * index that only has lookahead or "async_region" to set the
  218. * readahead flag.
  219. */
  220. ra_folio_index = round_up(readahead_index(ractl) + nr_to_read - lookahead_size,
  221. min_nrpages);
  222. mark = ra_folio_index - index;
  223. nr_to_read += readahead_index(ractl) - index;
  224. ractl->_index = index;
  225. /*
  226. * Preallocate as many pages as we will need.
  227. */
  228. while (i < nr_to_read) {
  229. struct folio *folio = xa_load(&mapping->i_pages, index + i);
  230. int ret;
  231. if (folio && !xa_is_value(folio)) {
  232. /*
  233. * Page already present? Kick off the current batch
  234. * of contiguous pages before continuing with the
  235. * next batch. This page may be the one we would
  236. * have intended to mark as Readahead, but we don't
  237. * have a stable reference to this page, and it's
  238. * not worth getting one just for that.
  239. */
  240. read_pages(ractl);
  241. ractl->_index += min_nrpages;
  242. i = ractl->_index + ractl->_nr_pages - index;
  243. continue;
  244. }
  245. folio = filemap_alloc_folio(gfp_mask,
  246. mapping_min_folio_order(mapping));
  247. if (!folio)
  248. break;
  249. ret = filemap_add_folio(mapping, folio, index + i, gfp_mask);
  250. if (ret < 0) {
  251. folio_put(folio);
  252. if (ret == -ENOMEM)
  253. break;
  254. read_pages(ractl);
  255. ractl->_index += min_nrpages;
  256. i = ractl->_index + ractl->_nr_pages - index;
  257. continue;
  258. }
  259. if (i == mark)
  260. folio_set_readahead(folio);
  261. ractl->_workingset |= folio_test_workingset(folio);
  262. ractl->_nr_pages += min_nrpages;
  263. i += min_nrpages;
  264. }
  265. /*
  266. * Now start the IO. We ignore I/O errors - if the folio is not
  267. * uptodate then the caller will launch read_folio again, and
  268. * will then handle the error.
  269. */
  270. read_pages(ractl);
  271. filemap_invalidate_unlock_shared(mapping);
  272. memalloc_nofs_restore(nofs);
  273. }
  274. EXPORT_SYMBOL_GPL(page_cache_ra_unbounded);
  275. /*
  276. * do_page_cache_ra() actually reads a chunk of disk. It allocates
  277. * the pages first, then submits them for I/O. This avoids the very bad
  278. * behaviour which would occur if page allocations are causing VM writeback.
  279. * We really don't want to intermingle reads and writes like that.
  280. */
  281. static void do_page_cache_ra(struct readahead_control *ractl,
  282. unsigned long nr_to_read, unsigned long lookahead_size)
  283. {
  284. struct inode *inode = ractl->mapping->host;
  285. unsigned long index = readahead_index(ractl);
  286. loff_t isize = i_size_read(inode);
  287. pgoff_t end_index; /* The last page we want to read */
  288. if (isize == 0)
  289. return;
  290. end_index = (isize - 1) >> PAGE_SHIFT;
  291. if (index > end_index)
  292. return;
  293. /* Don't read past the page containing the last byte of the file */
  294. if (nr_to_read > end_index - index)
  295. nr_to_read = end_index - index + 1;
  296. page_cache_ra_unbounded(ractl, nr_to_read, lookahead_size);
  297. }
  298. /*
  299. * Chunk the readahead into 2 megabyte units, so that we don't pin too much
  300. * memory at once.
  301. */
  302. void force_page_cache_ra(struct readahead_control *ractl,
  303. unsigned long nr_to_read)
  304. {
  305. struct address_space *mapping = ractl->mapping;
  306. struct file_ra_state *ra = ractl->ra;
  307. struct backing_dev_info *bdi = inode_to_bdi(mapping->host);
  308. unsigned long max_pages;
  309. if (unlikely(!mapping->a_ops->read_folio && !mapping->a_ops->readahead))
  310. return;
  311. /*
  312. * If the request exceeds the readahead window, allow the read to
  313. * be up to the optimal hardware IO size
  314. */
  315. max_pages = max_t(unsigned long, bdi->io_pages, ra->ra_pages);
  316. nr_to_read = min_t(unsigned long, nr_to_read, max_pages);
  317. while (nr_to_read) {
  318. unsigned long this_chunk = (2 * 1024 * 1024) / PAGE_SIZE;
  319. if (this_chunk > nr_to_read)
  320. this_chunk = nr_to_read;
  321. do_page_cache_ra(ractl, this_chunk, 0);
  322. nr_to_read -= this_chunk;
  323. }
  324. }
  325. /*
  326. * Set the initial window size, round to next power of 2 and square
  327. * for small size, x 4 for medium, and x 2 for large
  328. * for 128k (32 page) max ra
  329. * 1-2 page = 16k, 3-4 page 32k, 5-8 page = 64k, > 8 page = 128k initial
  330. */
  331. static unsigned long get_init_ra_size(unsigned long size, unsigned long max)
  332. {
  333. unsigned long newsize = roundup_pow_of_two(size);
  334. if (newsize <= max / 32)
  335. newsize = newsize * 4;
  336. else if (newsize <= max / 4)
  337. newsize = newsize * 2;
  338. else
  339. newsize = max;
  340. return newsize;
  341. }
  342. /*
  343. * Get the previous window size, ramp it up, and
  344. * return it as the new window size.
  345. */
  346. static unsigned long get_next_ra_size(struct file_ra_state *ra,
  347. unsigned long max)
  348. {
  349. unsigned long cur = ra->size;
  350. if (cur < max / 16)
  351. return 4 * cur;
  352. if (cur <= max / 2)
  353. return 2 * cur;
  354. return max;
  355. }
  356. /*
  357. * On-demand readahead design.
  358. *
  359. * The fields in struct file_ra_state represent the most-recently-executed
  360. * readahead attempt:
  361. *
  362. * |<----- async_size ---------|
  363. * |------------------- size -------------------->|
  364. * |==================#===========================|
  365. * ^start ^page marked with PG_readahead
  366. *
  367. * To overlap application thinking time and disk I/O time, we do
  368. * `readahead pipelining': Do not wait until the application consumed all
  369. * readahead pages and stalled on the missing page at readahead_index;
  370. * Instead, submit an asynchronous readahead I/O as soon as there are
  371. * only async_size pages left in the readahead window. Normally async_size
  372. * will be equal to size, for maximum pipelining.
  373. *
  374. * In interleaved sequential reads, concurrent streams on the same fd can
  375. * be invalidating each other's readahead state. So we flag the new readahead
  376. * page at (start+size-async_size) with PG_readahead, and use it as readahead
  377. * indicator. The flag won't be set on already cached pages, to avoid the
  378. * readahead-for-nothing fuss, saving pointless page cache lookups.
  379. *
  380. * prev_pos tracks the last visited byte in the _previous_ read request.
  381. * It should be maintained by the caller, and will be used for detecting
  382. * small random reads. Note that the readahead algorithm checks loosely
  383. * for sequential patterns. Hence interleaved reads might be served as
  384. * sequential ones.
  385. *
  386. * There is a special-case: if the first page which the application tries to
  387. * read happens to be the first page of the file, it is assumed that a linear
  388. * read is about to happen and the window is immediately set to the initial size
  389. * based on I/O request size and the max_readahead.
  390. *
  391. * The code ramps up the readahead size aggressively at first, but slow down as
  392. * it approaches max_readhead.
  393. */
  394. static inline int ra_alloc_folio(struct readahead_control *ractl, pgoff_t index,
  395. pgoff_t mark, unsigned int order, gfp_t gfp)
  396. {
  397. int err;
  398. struct folio *folio = filemap_alloc_folio(gfp, order);
  399. if (!folio)
  400. return -ENOMEM;
  401. mark = round_down(mark, 1UL << order);
  402. if (index == mark)
  403. folio_set_readahead(folio);
  404. err = filemap_add_folio(ractl->mapping, folio, index, gfp);
  405. if (err) {
  406. folio_put(folio);
  407. return err;
  408. }
  409. ractl->_nr_pages += 1UL << order;
  410. ractl->_workingset |= folio_test_workingset(folio);
  411. return 0;
  412. }
  413. void page_cache_ra_order(struct readahead_control *ractl,
  414. struct file_ra_state *ra, unsigned int new_order)
  415. {
  416. struct address_space *mapping = ractl->mapping;
  417. pgoff_t index = readahead_index(ractl);
  418. unsigned int min_order = mapping_min_folio_order(mapping);
  419. pgoff_t limit = (i_size_read(mapping->host) - 1) >> PAGE_SHIFT;
  420. pgoff_t mark = index + ra->size - ra->async_size;
  421. unsigned int nofs;
  422. int err = 0;
  423. gfp_t gfp = readahead_gfp_mask(mapping);
  424. unsigned int min_ra_size = max(4, mapping_min_folio_nrpages(mapping));
  425. /*
  426. * Fallback when size < min_nrpages as each folio should be
  427. * at least min_nrpages anyway.
  428. */
  429. if (!mapping_large_folio_support(mapping) || ra->size < min_ra_size)
  430. goto fallback;
  431. limit = min(limit, index + ra->size - 1);
  432. if (new_order < mapping_max_folio_order(mapping))
  433. new_order += 2;
  434. new_order = min(mapping_max_folio_order(mapping), new_order);
  435. new_order = min_t(unsigned int, new_order, ilog2(ra->size));
  436. new_order = max(new_order, min_order);
  437. /* See comment in page_cache_ra_unbounded() */
  438. nofs = memalloc_nofs_save();
  439. filemap_invalidate_lock_shared(mapping);
  440. /*
  441. * If the new_order is greater than min_order and index is
  442. * already aligned to new_order, then this will be noop as index
  443. * aligned to new_order should also be aligned to min_order.
  444. */
  445. ractl->_index = mapping_align_index(mapping, index);
  446. index = readahead_index(ractl);
  447. while (index <= limit) {
  448. unsigned int order = new_order;
  449. /* Align with smaller pages if needed */
  450. if (index & ((1UL << order) - 1))
  451. order = __ffs(index);
  452. /* Don't allocate pages past EOF */
  453. while (order > min_order && index + (1UL << order) - 1 > limit)
  454. order--;
  455. err = ra_alloc_folio(ractl, index, mark, order, gfp);
  456. if (err)
  457. break;
  458. index += 1UL << order;
  459. }
  460. read_pages(ractl);
  461. filemap_invalidate_unlock_shared(mapping);
  462. memalloc_nofs_restore(nofs);
  463. /*
  464. * If there were already pages in the page cache, then we may have
  465. * left some gaps. Let the regular readahead code take care of this
  466. * situation.
  467. */
  468. if (!err)
  469. return;
  470. fallback:
  471. do_page_cache_ra(ractl, ra->size, ra->async_size);
  472. }
  473. static unsigned long ractl_max_pages(struct readahead_control *ractl,
  474. unsigned long req_size)
  475. {
  476. struct backing_dev_info *bdi = inode_to_bdi(ractl->mapping->host);
  477. unsigned long max_pages = ractl->ra->ra_pages;
  478. /*
  479. * If the request exceeds the readahead window, allow the read to
  480. * be up to the optimal hardware IO size
  481. */
  482. if (req_size > max_pages && bdi->io_pages > max_pages)
  483. max_pages = min(req_size, bdi->io_pages);
  484. return max_pages;
  485. }
  486. void page_cache_sync_ra(struct readahead_control *ractl,
  487. unsigned long req_count)
  488. {
  489. pgoff_t index = readahead_index(ractl);
  490. bool do_forced_ra = ractl->file && (ractl->file->f_mode & FMODE_RANDOM);
  491. struct file_ra_state *ra = ractl->ra;
  492. unsigned long max_pages, contig_count;
  493. pgoff_t prev_index, miss;
  494. /*
  495. * Even if readahead is disabled, issue this request as readahead
  496. * as we'll need it to satisfy the requested range. The forced
  497. * readahead will do the right thing and limit the read to just the
  498. * requested range, which we'll set to 1 page for this case.
  499. */
  500. if (!ra->ra_pages || blk_cgroup_congested()) {
  501. if (!ractl->file)
  502. return;
  503. req_count = 1;
  504. do_forced_ra = true;
  505. }
  506. /* be dumb */
  507. if (do_forced_ra) {
  508. force_page_cache_ra(ractl, req_count);
  509. return;
  510. }
  511. max_pages = ractl_max_pages(ractl, req_count);
  512. prev_index = (unsigned long long)ra->prev_pos >> PAGE_SHIFT;
  513. /*
  514. * A start of file, oversized read, or sequential cache miss:
  515. * trivial case: (index - prev_index) == 1
  516. * unaligned reads: (index - prev_index) == 0
  517. */
  518. if (!index || req_count > max_pages || index - prev_index <= 1UL) {
  519. ra->start = index;
  520. ra->size = get_init_ra_size(req_count, max_pages);
  521. ra->async_size = ra->size > req_count ? ra->size - req_count :
  522. ra->size >> 1;
  523. goto readit;
  524. }
  525. /*
  526. * Query the page cache and look for the traces(cached history pages)
  527. * that a sequential stream would leave behind.
  528. */
  529. rcu_read_lock();
  530. miss = page_cache_prev_miss(ractl->mapping, index - 1, max_pages);
  531. rcu_read_unlock();
  532. contig_count = index - miss - 1;
  533. /*
  534. * Standalone, small random read. Read as is, and do not pollute the
  535. * readahead state.
  536. */
  537. if (contig_count <= req_count) {
  538. do_page_cache_ra(ractl, req_count, 0);
  539. return;
  540. }
  541. /*
  542. * File cached from the beginning:
  543. * it is a strong indication of long-run stream (or whole-file-read)
  544. */
  545. if (miss == ULONG_MAX)
  546. contig_count *= 2;
  547. ra->start = index;
  548. ra->size = min(contig_count + req_count, max_pages);
  549. ra->async_size = 1;
  550. readit:
  551. ractl->_index = ra->start;
  552. page_cache_ra_order(ractl, ra, 0);
  553. }
  554. EXPORT_SYMBOL_GPL(page_cache_sync_ra);
  555. void page_cache_async_ra(struct readahead_control *ractl,
  556. struct folio *folio, unsigned long req_count)
  557. {
  558. unsigned long max_pages;
  559. struct file_ra_state *ra = ractl->ra;
  560. pgoff_t index = readahead_index(ractl);
  561. pgoff_t expected, start;
  562. unsigned int order = folio_order(folio);
  563. /* no readahead */
  564. if (!ra->ra_pages)
  565. return;
  566. /*
  567. * Same bit is used for PG_readahead and PG_reclaim.
  568. */
  569. if (folio_test_writeback(folio))
  570. return;
  571. folio_clear_readahead(folio);
  572. if (blk_cgroup_congested())
  573. return;
  574. max_pages = ractl_max_pages(ractl, req_count);
  575. /*
  576. * It's the expected callback index, assume sequential access.
  577. * Ramp up sizes, and push forward the readahead window.
  578. */
  579. expected = round_down(ra->start + ra->size - ra->async_size,
  580. 1UL << order);
  581. if (index == expected) {
  582. ra->start += ra->size;
  583. /*
  584. * In the case of MADV_HUGEPAGE, the actual size might exceed
  585. * the readahead window.
  586. */
  587. ra->size = max(ra->size, get_next_ra_size(ra, max_pages));
  588. ra->async_size = ra->size;
  589. goto readit;
  590. }
  591. /*
  592. * Hit a marked folio without valid readahead state.
  593. * E.g. interleaved reads.
  594. * Query the pagecache for async_size, which normally equals to
  595. * readahead size. Ramp it up and use it as the new readahead size.
  596. */
  597. rcu_read_lock();
  598. start = page_cache_next_miss(ractl->mapping, index + 1, max_pages);
  599. rcu_read_unlock();
  600. if (!start || start - index > max_pages)
  601. return;
  602. ra->start = start;
  603. ra->size = start - index; /* old async_size */
  604. ra->size += req_count;
  605. ra->size = get_next_ra_size(ra, max_pages);
  606. ra->async_size = ra->size;
  607. readit:
  608. ractl->_index = ra->start;
  609. page_cache_ra_order(ractl, ra, order);
  610. }
  611. EXPORT_SYMBOL_GPL(page_cache_async_ra);
  612. ssize_t ksys_readahead(int fd, loff_t offset, size_t count)
  613. {
  614. ssize_t ret;
  615. struct fd f;
  616. ret = -EBADF;
  617. f = fdget(fd);
  618. if (!fd_file(f) || !(fd_file(f)->f_mode & FMODE_READ))
  619. goto out;
  620. /*
  621. * The readahead() syscall is intended to run only on files
  622. * that can execute readahead. If readahead is not possible
  623. * on this file, then we must return -EINVAL.
  624. */
  625. ret = -EINVAL;
  626. if (!fd_file(f)->f_mapping || !fd_file(f)->f_mapping->a_ops ||
  627. (!S_ISREG(file_inode(fd_file(f))->i_mode) &&
  628. !S_ISBLK(file_inode(fd_file(f))->i_mode)))
  629. goto out;
  630. ret = vfs_fadvise(fd_file(f), offset, count, POSIX_FADV_WILLNEED);
  631. out:
  632. fdput(f);
  633. return ret;
  634. }
  635. SYSCALL_DEFINE3(readahead, int, fd, loff_t, offset, size_t, count)
  636. {
  637. return ksys_readahead(fd, offset, count);
  638. }
  639. #if defined(CONFIG_COMPAT) && defined(__ARCH_WANT_COMPAT_READAHEAD)
  640. COMPAT_SYSCALL_DEFINE4(readahead, int, fd, compat_arg_u64_dual(offset), size_t, count)
  641. {
  642. return ksys_readahead(fd, compat_arg_u64_glue(offset), count);
  643. }
  644. #endif
  645. /**
  646. * readahead_expand - Expand a readahead request
  647. * @ractl: The request to be expanded
  648. * @new_start: The revised start
  649. * @new_len: The revised size of the request
  650. *
  651. * Attempt to expand a readahead request outwards from the current size to the
  652. * specified size by inserting locked pages before and after the current window
  653. * to increase the size to the new window. This may involve the insertion of
  654. * THPs, in which case the window may get expanded even beyond what was
  655. * requested.
  656. *
  657. * The algorithm will stop if it encounters a conflicting page already in the
  658. * pagecache and leave a smaller expansion than requested.
  659. *
  660. * The caller must check for this by examining the revised @ractl object for a
  661. * different expansion than was requested.
  662. */
  663. void readahead_expand(struct readahead_control *ractl,
  664. loff_t new_start, size_t new_len)
  665. {
  666. struct address_space *mapping = ractl->mapping;
  667. struct file_ra_state *ra = ractl->ra;
  668. pgoff_t new_index, new_nr_pages;
  669. gfp_t gfp_mask = readahead_gfp_mask(mapping);
  670. unsigned long min_nrpages = mapping_min_folio_nrpages(mapping);
  671. unsigned int min_order = mapping_min_folio_order(mapping);
  672. new_index = new_start / PAGE_SIZE;
  673. /*
  674. * Readahead code should have aligned the ractl->_index to
  675. * min_nrpages before calling readahead aops.
  676. */
  677. VM_BUG_ON(!IS_ALIGNED(ractl->_index, min_nrpages));
  678. /* Expand the leading edge downwards */
  679. while (ractl->_index > new_index) {
  680. unsigned long index = ractl->_index - 1;
  681. struct folio *folio = xa_load(&mapping->i_pages, index);
  682. if (folio && !xa_is_value(folio))
  683. return; /* Folio apparently present */
  684. folio = filemap_alloc_folio(gfp_mask, min_order);
  685. if (!folio)
  686. return;
  687. index = mapping_align_index(mapping, index);
  688. if (filemap_add_folio(mapping, folio, index, gfp_mask) < 0) {
  689. folio_put(folio);
  690. return;
  691. }
  692. if (unlikely(folio_test_workingset(folio)) &&
  693. !ractl->_workingset) {
  694. ractl->_workingset = true;
  695. psi_memstall_enter(&ractl->_pflags);
  696. }
  697. ractl->_nr_pages += min_nrpages;
  698. ractl->_index = folio->index;
  699. }
  700. new_len += new_start - readahead_pos(ractl);
  701. new_nr_pages = DIV_ROUND_UP(new_len, PAGE_SIZE);
  702. /* Expand the trailing edge upwards */
  703. while (ractl->_nr_pages < new_nr_pages) {
  704. unsigned long index = ractl->_index + ractl->_nr_pages;
  705. struct folio *folio = xa_load(&mapping->i_pages, index);
  706. if (folio && !xa_is_value(folio))
  707. return; /* Folio apparently present */
  708. folio = filemap_alloc_folio(gfp_mask, min_order);
  709. if (!folio)
  710. return;
  711. index = mapping_align_index(mapping, index);
  712. if (filemap_add_folio(mapping, folio, index, gfp_mask) < 0) {
  713. folio_put(folio);
  714. return;
  715. }
  716. if (unlikely(folio_test_workingset(folio)) &&
  717. !ractl->_workingset) {
  718. ractl->_workingset = true;
  719. psi_memstall_enter(&ractl->_pflags);
  720. }
  721. ractl->_nr_pages += min_nrpages;
  722. if (ra) {
  723. ra->size += min_nrpages;
  724. ra->async_size += min_nrpages;
  725. }
  726. }
  727. }
  728. EXPORT_SYMBOL(readahead_expand);