[RFC PATCH 10/18] mm/filemap: mark a folio accessed in one place in filemap_read()

From: Kiryl Shutsemau (Meta)

Date: Mon Oct 19 2026 - 12:25:27 EST


From: Linus Torvalds <torvalds@xxxxxxxxxxxxxxxxxxxx>

filemap_read() calls folio_mark_accessed() in two places. Before the
copy loop it marks the first folio of the batch, unless the previous
read through the file ended in that folio. In the loop it marks every
later folio.

The test made for the first folio also says "mark" for every later
one. The loop gets to a later folio only after the folio before it was
copied to its end, so last_pos is at the later folio's first byte and
pos_same_folio() is false.

Do both in one helper, filemap_read_accessed(), called for each folio
in the loop. For the first folio the call moves below the test of
end_offset against the folio's start, which is false for it: the folio
holds ki_pos, and end_offset is beyond ki_pos.

No change in behaviour intended. Preparation for deciding in the
helper which folios are worth reading without a reference.

Assisted-by: LLM
Signed-off-by: Linus Torvalds <torvalds@xxxxxxxxxxxxxxxxxxxx>
[kas: shorter changelog]
Signed-off-by: Kiryl Shutsemau (Meta) <kas@xxxxxxxxxx>
---
mm/filemap.c | 25 +++++++++++++++----------
1 file changed, 15 insertions(+), 10 deletions(-)

diff --git a/mm/filemap.c b/mm/filemap.c
index 00fd89cf6f55..3508eea44ad9 100644
--- a/mm/filemap.c
+++ b/mm/filemap.c
@@ -2759,6 +2759,20 @@ static inline bool pos_same_folio(loff_t pos1, loff_t pos2, struct folio *folio)
return (pos1 >> shift == pos2 >> shift);
}

+/*
+ * filemap_read() is about to copy from @folio at @pos. @last_pos is where
+ * the previous read of this open file ended, or how far this one has got.
+ *
+ * Reading on in the folio that the last read ended in is not another access
+ * to it: a folio read in small pieces is marked accessed once.
+ */
+static void filemap_read_accessed(struct folio *folio, loff_t pos,
+ loff_t last_pos)
+{
+ if (!pos_same_folio(pos, last_pos - 1, folio))
+ folio_mark_accessed(folio);
+}
+
static void filemap_end_dropbehind_read(struct folio *folio)
{
if (!folio_test_dropbehind(folio))
@@ -2844,14 +2858,6 @@ ssize_t filemap_read(struct kiocb *iocb, struct iov_iter *iter,
*/
writably_mapped = mapping_writably_mapped(mapping);

- /*
- * When a read accesses the same folio several times, only
- * mark it as accessed the first time.
- */
- if (!pos_same_folio(iocb->ki_pos, last_pos - 1,
- fbatch.folios[0]))
- folio_mark_accessed(fbatch.folios[0]);
-
for (i = 0; i < folio_batch_count(&fbatch); i++) {
struct folio *folio = fbatch.folios[i];
size_t fsize = folio_size(folio);
@@ -2862,8 +2868,7 @@ ssize_t filemap_read(struct kiocb *iocb, struct iov_iter *iter,

if (end_offset < folio_pos(folio))
break;
- if (i > 0)
- folio_mark_accessed(folio);
+ filemap_read_accessed(folio, iocb->ki_pos, last_pos);
/*
* If users can be writing to this folio using arbitrary
* virtual addresses, take care of potential aliasing
--
2.54.0