Skip to contentSkip to conversation

mm: drop folios under writeback on POSIX_FADV_DONTNEED

PATCH Applied Usama Arif 7 participants 25 messages Dec 2 – Dec 4

Subsystems (8)
lore
Share & tools
lore

Usama Arif

author
#0 lore raw

cover mm: drop folios under writeback on POSIX_FADV_DONTNEED

POSIX_FADV_DONTNEED starts writeback on the dirty folios in the range without waiting for it, then invalidates what it can and skips folios under writeback. With small folios most bios complete while DONTNEED is still invalidating. With large folios on XFS a single bio can carry hundreds of megabytes, none of which leaves writeback until all of it completes, so DONTNEED right after writing a new 256 MiB file leaves all of it cached.

This is affecting production workloads after a kernel upgrade that started using large folios on XFS: an application that writes files through a shared mapping, unmaps them and calls DONTNEED without syncing now fills its memory limit with page cache that DONTNEED used to drop.

Patch 4 marks the unmapped dirty folios in the range dropbehind before starting writeback, and the unmapped folios still under writeback after it, so that writeback completion drops them as it does for RWF_DONTCACHE writes. Only regular files on filesystems that support RWF_DONTCACHE are marked, and not the folio extending past EOF, which an appender calling DONTNEED after each write would have to read back.

Patches 1-3 fix dropbehind bugs that patch 4 makes easier to hit:

1. Migration does not copy PG_dropbehind, so WB_DONTCACHE_DIRTY leaks.
2. Lookups clear PG_dropbehind without the folio lock, racing with dirtying and cleaning, so WB_DONTCACHE_DIRTY drifts.
3. folio_end_dropbehind() can invalidate with interrupts disabled in a forced-threaded handler, as ext4 RWF_DONTCACHE overwrites did with threadirqs from v6.17 until commit 7d7c9c83c822.

Patches 1-3 are stable candidates.

With the series, new files and overwrites on XFS and ext4 were dropped within a second of DONTNEED apart from the folio at EOF; without the series most of them stayed cached.

Alternatives considered:
- fdatasync() before DONTNEED works, but blocks the caller and needs every application changed.
- Restoring the PG_reclaim that DONTNEED set on these folios until commit 5c211ba29deb ("mm: add and use find_lock_entries") only moves them to the tail of the inactive list, still cached and charged.
- Calling bio_complete_in_task() for every bio with a dropbehind folio would also catch folios marked after submission, but needs a pass over every write bio's folios before completing it.

Limitations:
- Folios already under writeback that complete in interrupt context stay cached.

base-commit: 872ceec1e3caf227655a58f7407a9c8493dcf56f

Usama Arif (4):
mm/migrate: preserve PG_dropbehind across folio migration mm/filemap: clear PG_dropbehind on lookup under the folio lock mm/filemap: don't drop dropbehind folios with interrupts disabled mm/fadvise: drop folios under writeback on POSIX_FADV_DONTNEED

 mm/fadvise.c        | 60 +++++++++++++++++++++++++++++++++++++++++----
 mm/filemap.c        | 30 +++++++++++++++++------
 mm/internal.h       |  1 +
 mm/migrate.c        |  3 +++
 mm/page-writeback.c | 23 +++++++++++++++++
 5 files changed, 104 insertions(+), 13 deletions(-)
Signature · 1 line
2.53.1-Meta
author
#1 lore raw

PATCH 1/4 mm/migrate: preserve PG_dropbehind across folio migration

Migration moves PG_dirty to the new folio but not PG_dropbehind, so a migrated dirty dropbehind folio is cleaned without decrementing WB_DONTCACHE_DIRTY. The counter leaks, and every later RWF_DONTCACHE kick asks the flusher for that many more pages. Copy the flag along with PG_dirty, before the new folio becomes visible.

With RWF_DONTCACHE writes and compaction running for five minutes, 1313 to 1709 pages leaked, all of them migrated.

Fixes 88d6f128d06d ("mm: track DONTCACHE dirty pages per bdi_writeback")
---
 mm/migrate.c | 3 +++
 1 file changed, 3 insertions(+)
mm/migrate.c +3 -0
index 96b66a272379f9..81a8e46778610f 100644
@@ -663,6 +663,9 @@ static int __folio_migrate_mapping(struct address_space *mapping,
 		folio_clear_dirty(folio);
 		folio_set_dirty(newfolio);
 	}
+	/* WB_DONTCACHE_DIRTY counts pages that are both dirty and dropbehind */
+	if (folio_test_dropbehind(folio))
+		folio_set_dropbehind(newfolio);
 
 	if (folio_test_swapcache(folio))
 		__swap_cache_replace_folio(ci, folio, newfolio);
Signature · 1 line
2.53.1-Meta
maintainer Reviewed-by on v1 1/4
#2 lore raw

Re: [PATCH 1/4] mm/migrate: preserve PG_dropbehind across folio migration

Quoted 6 lines · Usama Arif

Migration moves PG_dirty to the new folio but not PG_dropbehind, so a migrated dirty dropbehind folio is cleaned without decrementing WB_DONTCACHE_DIRTY. The counter leaks, and every later RWF_DONTCACHE kick asks the flusher for that many more pages. Copy the flag along with PG_dirty, before the new folio becomes visible.

Quoted 6 lines

With RWF_DONTCACHE writes and compaction running for five minutes, 1313 to 1709 pages leaked, all of them migrated.

Fixes 88d6f128d06d ("mm: track DONTCACHE dirty pages per bdi_writeback")

Looks good. Feel free to add:

Honza

Quoted 21 lines
---
 mm/migrate.c | 3 +++
 1 file changed, 3 insertions(+)
mm/migrate.c +3 -0
index 96b66a272379f9..81a8e46778610f 100644
@@ -663,6 +663,9 @@ static int __folio_migrate_mapping(struct address_space *mapping,
 		folio_clear_dirty(folio);
 		folio_set_dirty(newfolio);
 	}
+	/* WB_DONTCACHE_DIRTY counts pages that are both dirty and dropbehind */
+	if (folio_test_dropbehind(folio))
+		folio_set_dropbehind(newfolio);
 
 	if (folio_test_swapcache(folio))
 		__swap_cache_replace_folio(ci, folio, newfolio);
Signature · 1 line
2.53.1-Meta
Signature · 2 lines
Jan Kara <[email protected]>
SUSE Labs, CR
Reviewed-by on v1 1/4
#3 lore raw

Re: [PATCH 1/4] mm/migrate: preserve PG_dropbehind across folio migration

In reply to Usama Arif
Quoted 21 lines · Usama Arif

Migration moves PG_dirty to the new folio but not PG_dropbehind, so a migrated dirty dropbehind folio is cleaned without decrementing WB_DONTCACHE_DIRTY. The counter leaks, and every later RWF_DONTCACHE kick asks the flusher for that many more pages. Copy the flag along with PG_dirty, before the new folio becomes visible.

With RWF_DONTCACHE writes and compaction running for five minutes, 1313 to 1709 pages leaked, all of them migrated.

Fixes 88d6f128d06d ("mm: track DONTCACHE dirty pages per bdi_writeback")
---
 mm/migrate.c | 3 +++
 1 file changed, 3 insertions(+)
mm/migrate.c +0 -0
index 96b66a272379f9..81a8e46778610f 100644

mm/migrate.c static int __folio_migrate_mapping(struct address_space *mapping, · line 671

Quoted 9 lines
mm/migrate.c +3 -0
@@ -663,6 +663,9 @@ static int __folio_migrate_mapping(struct address_space *mapping,
 		folio_clear_dirty(folio);
 		folio_set_dirty(newfolio);
 	}
+	/* WB_DONTCACHE_DIRTY counts pages that are both dirty and dropbehind */
+	if (folio_test_dropbehind(folio))
+		folio_set_dropbehind(newfolio);
 
 	if (folio_test_swapcache(folio))
 		__swap_cache_replace_folio(ci, folio, newfolio);
reviewer Reviewed-by on v1 1/4
#4 lore raw

Re: [PATCH 1/4] mm/migrate: preserve PG_dropbehind across folio migration

In reply to Usama Arif
Quoted 9 lines · Usama Arif

Migration moves PG_dirty to the new folio but not PG_dropbehind, so a migrated dirty dropbehind folio is cleaned without decrementing WB_DONTCACHE_DIRTY. The counter leaks, and every later RWF_DONTCACHE kick asks the flusher for that many more pages. Copy the flag along with PG_dirty, before the new folio becomes visible.

With RWF_DONTCACHE writes and compaction running for five minutes, 1313 to 1709 pages leaked, all of them migrated.

Quoted 6 lines
Fixes 88d6f128d06d ("mm: track DONTCACHE dirty pages per bdi_writeback")
---
 mm/migrate.c | 3 +++
 1 file changed, 3 insertions(+)

Makes sense to me. Thanks.

Quoted 6 lines
mm/migrate.c +0 -0
index 96b66a272379f9..81a8e46778610f 100644

mm/migrate.c static int __folio_migrate_mapping(struct address_space *mapping, · line 671

Quoted 9 lines
mm/migrate.c +3 -0
@@ -663,6 +663,9 @@ static int __folio_migrate_mapping(struct address_space *mapping,
 		folio_clear_dirty(folio);
 		folio_set_dirty(newfolio);
 	}
+	/* WB_DONTCACHE_DIRTY counts pages that are both dirty and dropbehind */
+	if (folio_test_dropbehind(folio))
+		folio_set_dropbehind(newfolio);
 
 	if (folio_test_swapcache(folio))
 		__swap_cache_replace_folio(ci, folio, newfolio);

This "test then set" pattern fills the most of __folio_migrate_mapping(), I wonder if we can do that in bulk in a follow-up cleanup.

Signature · 2 lines
Best Regards,
Yan, Zi
maintainer Reviewed-by on v1 1/4
#5 lore raw

Re: [PATCH 1/4] mm/migrate: preserve PG_dropbehind across folio migration

In reply to Usama Arif
Quoted 21 lines · Usama Arif

Migration moves PG_dirty to the new folio but not PG_dropbehind, so a migrated dirty dropbehind folio is cleaned without decrementing WB_DONTCACHE_DIRTY. The counter leaks, and every later RWF_DONTCACHE kick asks the flusher for that many more pages. Copy the flag along with PG_dirty, before the new folio becomes visible.

With RWF_DONTCACHE writes and compaction running for five minutes, 1313 to 1709 pages leaked, all of them migrated.

Fixes 88d6f128d06d ("mm: track DONTCACHE dirty pages per bdi_writeback")
---
 mm/migrate.c | 3 +++
 1 file changed, 3 insertions(+)
mm/migrate.c +0 -0
index 96b66a272379f9..81a8e46778610f 100644

mm/migrate.c static int __folio_migrate_mapping(struct address_space *mapping, · line 668

Quoted 6 lines
mm/migrate.c +3 -0
@@ -663,6 +663,9 @@ static int __folio_migrate_mapping(struct address_space *mapping,
 		folio_clear_dirty(folio);
 		folio_set_dirty(newfolio);
 	}
+	/* WB_DONTCACHE_DIRTY counts pages that are both dirty and dropbehind */
+	if (folio_test_dropbehind(folio))
+		folio_set_dropbehind(newfolio);

I think I assigned Jan a Sashiko report about this yesterday :)

I assume I can pick this independent of the other ones (this through my tree, the other stuff through Andrews tree)?

Signature · 3 lines
Cheers,

David
author
#6 lore raw

Re: [PATCH 1/4] mm/migrate: preserve PG_dropbehind across folio migration

Quoted 31 lines · On Wed, 2 Dec 2026 16:08:05 +0100 "David Hildenbrand (Arm)" <[email protected]>…
Quoted 21 lines · Usama Arif

Migration moves PG_dirty to the new folio but not PG_dropbehind, so a migrated dirty dropbehind folio is cleaned without decrementing WB_DONTCACHE_DIRTY. The counter leaks, and every later RWF_DONTCACHE kick asks the flusher for that many more pages. Copy the flag along with PG_dirty, before the new folio becomes visible.

With RWF_DONTCACHE writes and compaction running for five minutes, 1313 to 1709 pages leaked, all of them migrated.

Fixes 88d6f128d06d ("mm: track DONTCACHE dirty pages per bdi_writeback")
---
 mm/migrate.c | 3 +++
 1 file changed, 3 insertions(+)
mm/migrate.c +0 -0
index 96b66a272379f9..81a8e46778610f 100644

mm/migrate.c static int __folio_migrate_mapping(struct address_space *mapping, · line 668

Quoted 6 lines
mm/migrate.c +3 -0
@@ -663,6 +663,9 @@ static int __folio_migrate_mapping(struct address_space *mapping,
 		folio_clear_dirty(folio);
 		folio_set_dirty(newfolio);
 	}
+	/* WB_DONTCACHE_DIRTY counts pages that are both dirty and dropbehind */
+	if (folio_test_dropbehind(folio))
+		folio_set_dropbehind(newfolio);

I think I assigned Jan a Sashiko report about this yesterday :)

Quoted 4 lines

I assume I can pick this independent of the other ones (this through my tree, the other stuff through Andrews tree)?

Thanks for the review!

Yes, the 3 fixes are independent of each other. They should go in before patch 4 though, as patch 4 makes it more likely to hit these bugs.

Quoted 6 lines
Signature · 4 lines
-- 
Cheers,

David
author
#7 lore raw

PATCH 2/4 mm/filemap: clear PG_dropbehind on lookup under the folio lock

In reply to Usama Arif

Lookups without FGP_LOCK clear PG_dropbehind and then test PG_dirty to adjust WB_DONTCACHE_DIRTY without holding the folio lock, so they race with dirtying and cleaning and the counter drifts. Do it under the folio lock and inside the wb transaction, and leave the flag set if the lock is contended.

With a 50us delay widening the race, the counter was left at 25 to 522 pages after sync in three five-minute runs; with this it was 0.

Fixes 88d6f128d06d ("mm: track DONTCACHE dirty pages per bdi_writeback")
---
 mm/filemap.c | 25 +++++++++++++++++++------
 1 file changed, 19 insertions(+), 6 deletions(-)
mm/filemap.c +19 -6
index 64eefcdb24b393..a49cca600f8c3e 100644
@@ -2104,19 +2104,32 @@ struct folio *__filemap_get_folio_mpol(struct address_space *mapping,
 
 	if (!folio)
 		return ERR_PTR(-ENOENT);
-	/* not an uncached lookup, clear uncached if set */
-	if (!(fgp_flags & FGP_DONTCACHE) && folio_test_clear_dropbehind(folio)) {
-		if (folio_test_dirty(folio) &&
-		    mapping_can_writeback(mapping)) {
+	/*
+	 * Not an uncached lookup, clear uncached if set. Dirtying and cleaning
+	 * normally hold the folio lock; take it to keep WB_DONTCACHE_DIRTY in
+	 * sync.
+	 */
+	if (!(fgp_flags & FGP_DONTCACHE) && folio_test_dropbehind(folio)) {
+		bool locked = fgp_flags & FGP_LOCK;
+
+		if (!locked && !folio_trylock(folio))
+			return folio;
+		if (mapping_can_writeback(mapping)) {
 			struct inode *inode = mapping->host;
 			struct bdi_writeback *wb;
 			struct wb_lock_cookie cookie = {};
-			long nr = folio_nr_pages(folio);
 
 			wb = unlocked_inode_to_wb_begin(inode, &cookie);
-			wb_stat_mod(wb, WB_DONTCACHE_DIRTY, -nr);
+			if (folio_test_clear_dropbehind(folio) &&
+			    folio_test_dirty(folio))
+				wb_stat_mod(wb, WB_DONTCACHE_DIRTY,
+					    -folio_nr_pages(folio));
 			unlocked_inode_to_wb_end(inode, &cookie);
+		} else {
+			folio_clear_dropbehind(folio);
 		}
+		if (!locked)
+			folio_unlock(folio);
 	}
 	return folio;
 }
Signature · 1 line
2.53.1-Meta
maintainer Reviewed-by on v1 2/4
#8 lore raw

Re: [PATCH 2/4] mm/filemap: clear PG_dropbehind on lookup under the folio lock

Quoted 6 lines · Usama Arif

Lookups without FGP_LOCK clear PG_dropbehind and then test PG_dirty to adjust WB_DONTCACHE_DIRTY without holding the folio lock, so they race with dirtying and cleaning and the counter drifts. Do it under the folio lock and inside the wb transaction, and leave the flag set if the lock is contended.

Quoted 6 lines

With a 50us delay widening the race, the counter was left at 25 to 522 pages after sync in three five-minute runs; with this it was 0.

Fixes 88d6f128d06d ("mm: track DONTCACHE dirty pages per bdi_writeback")

Looks good. Feel free to add:

Although I have a nagging feeling I've seen a fix for this somewhere already.

Honza

Quoted 50 lines
---
 mm/filemap.c | 25 +++++++++++++++++++------
 1 file changed, 19 insertions(+), 6 deletions(-)
mm/filemap.c +19 -6
index 64eefcdb24b393..a49cca600f8c3e 100644
@@ -2104,19 +2104,32 @@ struct folio *__filemap_get_folio_mpol(struct address_space *mapping,
 
 	if (!folio)
 		return ERR_PTR(-ENOENT);
-	/* not an uncached lookup, clear uncached if set */
-	if (!(fgp_flags & FGP_DONTCACHE) && folio_test_clear_dropbehind(folio)) {
-		if (folio_test_dirty(folio) &&
-		    mapping_can_writeback(mapping)) {
+	/*
+	 * Not an uncached lookup, clear uncached if set. Dirtying and cleaning
+	 * normally hold the folio lock; take it to keep WB_DONTCACHE_DIRTY in
+	 * sync.
+	 */
+	if (!(fgp_flags & FGP_DONTCACHE) && folio_test_dropbehind(folio)) {
+		bool locked = fgp_flags & FGP_LOCK;
+
+		if (!locked && !folio_trylock(folio))
+			return folio;
+		if (mapping_can_writeback(mapping)) {
 			struct inode *inode = mapping->host;
 			struct bdi_writeback *wb;
 			struct wb_lock_cookie cookie = {};
-			long nr = folio_nr_pages(folio);
 
 			wb = unlocked_inode_to_wb_begin(inode, &cookie);
-			wb_stat_mod(wb, WB_DONTCACHE_DIRTY, -nr);
+			if (folio_test_clear_dropbehind(folio) &&
+			    folio_test_dirty(folio))
+				wb_stat_mod(wb, WB_DONTCACHE_DIRTY,
+					    -folio_nr_pages(folio));
 			unlocked_inode_to_wb_end(inode, &cookie);
+		} else {
+			folio_clear_dropbehind(folio);
 		}
+		if (!locked)
+			folio_unlock(folio);
 	}
 	return folio;
 }
Signature · 1 line
2.53.1-Meta
Signature · 2 lines
Jan Kara <[email protected]>
SUSE Labs, CR
Reviewed-by on v1 2/4
#9 lore raw

Re: [PATCH 2/4] mm/filemap: clear PG_dropbehind on lookup under the folio lock

In reply to Usama Arif
Quoted 49 lines · Usama Arif

Lookups without FGP_LOCK clear PG_dropbehind and then test PG_dirty to adjust WB_DONTCACHE_DIRTY without holding the folio lock, so they race with dirtying and cleaning and the counter drifts. Do it under the folio lock and inside the wb transaction, and leave the flag set if the lock is contended.

With a 50us delay widening the race, the counter was left at 25 to 522 pages after sync in three five-minute runs; with this it was 0.

Fixes 88d6f128d06d ("mm: track DONTCACHE dirty pages per bdi_writeback")
---
 mm/filemap.c | 25 +++++++++++++++++++------
 1 file changed, 19 insertions(+), 6 deletions(-)
mm/filemap.c +14 -6
index 64eefcdb24b393..a49cca600f8c3e 100644
@@ -2104,19 +2104,32 @@ struct folio *__filemap_get_folio_mpol(struct address_space *mapping,
 
 	if (!folio)
 		return ERR_PTR(-ENOENT);
-	/* not an uncached lookup, clear uncached if set */
-	if (!(fgp_flags & FGP_DONTCACHE) && folio_test_clear_dropbehind(folio)) {
-		if (folio_test_dirty(folio) &&
-		    mapping_can_writeback(mapping)) {
+	/*
+	 * Not an uncached lookup, clear uncached if set. Dirtying and cleaning
+	 * normally hold the folio lock; take it to keep WB_DONTCACHE_DIRTY in
+	 * sync.
+	 */
+	if (!(fgp_flags & FGP_DONTCACHE) && folio_test_dropbehind(folio)) {
+		bool locked = fgp_flags & FGP_LOCK;
+
+		if (!locked && !folio_trylock(folio))
+			return folio;
+		if (mapping_can_writeback(mapping)) {
 			struct inode *inode = mapping->host;
 			struct bdi_writeback *wb;
 			struct wb_lock_cookie cookie = {};
-			long nr = folio_nr_pages(folio);
 
 			wb = unlocked_inode_to_wb_begin(inode, &cookie);
-			wb_stat_mod(wb, WB_DONTCACHE_DIRTY, -nr);
+			if (folio_test_clear_dropbehind(folio) &&
+			    folio_test_dirty(folio))
+				wb_stat_mod(wb, WB_DONTCACHE_DIRTY,

mm/filemap.c struct folio *__filemap_get_folio_mpol(struct address_space *mapping, · line 2135

Quoted 10 lines
mm/filemap.c +5 -0
+					    -folio_nr_pages(folio));
 			unlocked_inode_to_wb_end(inode, &cookie);
+		} else {
+			folio_clear_dropbehind(folio);
 		}
+		if (!locked)
+			folio_unlock(folio);
 	}
 	return folio;
 }
#10 lore raw

Re: [PATCH 2/4] mm/filemap: clear PG_dropbehind on lookup under the folio lock

In reply to Usama Arif
Quoted 4 lines · Usama Arif
mm/filemap.c +1 -0
+		if (mapping_can_writeback(mapping)) {
 			struct inode *inode = mapping->host;
 			struct bdi_writeback *wb;
 			struct wb_lock_cookie cookie = {};

mm/filemap.c struct folio *__filemap_get_folio_mpol(struct address_space *mapping, · line 2128

Quoted 10 lines
mm/filemap.c +5 -2
-			long nr = folio_nr_pages(folio);
 
 			wb = unlocked_inode_to_wb_begin(inode, &cookie);
-			wb_stat_mod(wb, WB_DONTCACHE_DIRTY, -nr);
+			if (folio_test_clear_dropbehind(folio) &&
+			    folio_test_dirty(folio))
+				wb_stat_mod(wb, WB_DONTCACHE_DIRTY,
+					    -folio_nr_pages(folio));
 			unlocked_inode_to_wb_end(inode, &cookie);
+		} else {

Not urgent, but at some point it would be really nice to split this logic into a helper as it really distracts from the main logic in the function.

#11 lore raw

Re: [PATCH 2/4] mm/filemap: clear PG_dropbehind on lookup under the folio lock

In reply to Usama Arif
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] mm/filemap: 32-bit unsigned negation in __filemap_get_folio_mpol() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] mm/filemap: 32-bit unsigned negation in __filemap_get_folio_mpol()
--

commit 692fa43d891b2d863f2536d0298d2c5c841d89bb
Author: Usama Arif <[email protected]>

mm/filemap: clear PG_dropbehind on lookup under the folio lock

This commit clears PG_dropbehind and updates WB_DONTCACHE_DIRTY under the folio lock and within the wb transaction during cached folio lookups.

Quoted 24 lines
mm/filemap.c +11 -4
index 64eefcdb24b39..a49cca600f8c3 100644
@@ -2104,19 +2104,32 @@ struct folio *__filemap_get_folio_mpol(struct address_space *mapping,
 
 	if (!folio)
 		return ERR_PTR(-ENOENT);
-	/* not an uncached lookup, clear uncached if set */
-	if (!(fgp_flags & FGP_DONTCACHE) && folio_test_clear_dropbehind(folio)) {
-		if (folio_test_dirty(folio) &&
-		    mapping_can_writeback(mapping)) {
+	/*
+	 * Not an uncached lookup, clear uncached if set. Dirtying and cleaning
+	 * normally hold the folio lock; take it to keep WB_DONTCACHE_DIRTY in
+	 * sync.
+	 */
+	if (!(fgp_flags & FGP_DONTCACHE) && folio_test_dropbehind(folio)) {
+		bool locked = fgp_flags & FGP_LOCK;
+
+		if (!locked && !folio_trylock(folio))
+			return folio;
+		if (mapping_can_writeback(mapping)) {
 			struct inode *inode = mapping->host;

mm/filemap.c struct folio *__filemap_get_folio_mpol(struct address_space *mapping, · line 2126

Quoted 10 lines
mm/filemap.c +4 -2
 			struct bdi_writeback *wb;
 			struct wb_lock_cookie cookie = {};
-			long nr = folio_nr_pages(folio);
 
 			wb = unlocked_inode_to_wb_begin(inode, &cookie);
-			wb_stat_mod(wb, WB_DONTCACHE_DIRTY, -nr);
+			if (folio_test_clear_dropbehind(folio) &&
+			    folio_test_dirty(folio))
+				wb_stat_mod(wb, WB_DONTCACHE_DIRTY,
+					    -folio_nr_pages(folio));

[Severity: Medium]
On 32-bit architectures, does passing -folio_nr_pages(folio) to wb_stat_mod() corrupt WB_DONTCACHE_DIRTY?

folio_nr_pages() returns unsigned long, so negating it directly produces an unsigned 32-bit value that zero-extends to a large positive s64 amount in wb_stat_mod() instead of subtracting the page count. Keeping the signed long nr variable or casting folio_nr_pages(folio) to long before negating would avoid this.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
author
#12 lore raw

PATCH 3/4 mm/filemap: don't drop dropbehind folios with interrupts disabled

In reply to Usama Arif

Forced-threaded interrupt handlers pass the in_task() check in folio_end_dropbehind() but run with interrupts disabled on !PREEMPT_RT, and invalidating the folio turns them back on. ext4 RWF_DONTCACHE overwrites hit this with threadirqs until commit 7d7c9c83c822 ("ext4:
complete dropbehind writeback in task context"), and folios marked dropbehind after their writeback was submitted still can.

Skip the drop when interrupts are disabled. The folio stays cached, as it does when the completion runs in hardirq context.

Fixes ae21c0c0ac56 ("ext4: support uncached buffered I/O")
---
 mm/filemap.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
mm/filemap.c +3 -2
index a49cca600f8c3e..6674c4ef8fe036 100644
@@ -1663,9 +1663,10 @@ void folio_end_dropbehind(struct folio *folio)
 	 * but can happen if normal writeback just happens to find dirty folios
 	 * that were created as part of uncached writeback, and that writeback
 	 * would otherwise not need non-IRQ handling. Just skip the
-	 * invalidation in that case.
+	 * invalidation in that case, and also when interrupts are disabled,
+	 * as they are in forced-threaded interrupt handlers.
 	 */
-	if (in_task() && folio_trylock(folio)) {
+	if (in_task() && !irqs_disabled() && folio_trylock(folio)) {
 		filemap_end_dropbehind(folio);
 		folio_unlock(folio);
 	}
Signature · 1 line
2.53.1-Meta
maintainer Reviewed-by on v1 3/4
#13 lore raw

Re: [PATCH 3/4] mm/filemap: don't drop dropbehind folios with interrupts disabled

Quoted 7 lines · Usama Arif

Forced-threaded interrupt handlers pass the in_task() check in folio_end_dropbehind() but run with interrupts disabled on !PREEMPT_RT, and invalidating the folio turns them back on. ext4 RWF_DONTCACHE overwrites hit this with threadirqs until commit 7d7c9c83c822 ("ext4:
complete dropbehind writeback in task context"), and folios marked dropbehind after their writeback was submitted still can.

Quoted 6 lines

Skip the drop when interrupts are disabled. The folio stays cached, as it does when the completion runs in hardirq context.

Fixes ae21c0c0ac56 ("ext4: support uncached buffered I/O")

Ah, this checking for proper context is so subtle it makes me wanna cry. Anyway the fix looks good. Feel free to add:

Honza

Quoted 24 lines
---
 mm/filemap.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
mm/filemap.c +3 -2
index a49cca600f8c3e..6674c4ef8fe036 100644
@@ -1663,9 +1663,10 @@ void folio_end_dropbehind(struct folio *folio)
 	 * but can happen if normal writeback just happens to find dirty folios
 	 * that were created as part of uncached writeback, and that writeback
 	 * would otherwise not need non-IRQ handling. Just skip the
-	 * invalidation in that case.
+	 * invalidation in that case, and also when interrupts are disabled,
+	 * as they are in forced-threaded interrupt handlers.
 	 */
-	if (in_task() && folio_trylock(folio)) {
+	if (in_task() && !irqs_disabled() && folio_trylock(folio)) {
 		filemap_end_dropbehind(folio);
 		folio_unlock(folio);
 	}
Signature · 1 line
2.53.1-Meta
Signature · 2 lines
Jan Kara <[email protected]>
SUSE Labs, CR
Reviewed-by on v1 3/4
#14 lore raw

Re: [PATCH 3/4] mm/filemap: don't drop dropbehind folios with interrupts disabled

In reply to Usama Arif
Quoted 24 lines · Usama Arif

Forced-threaded interrupt handlers pass the in_task() check in folio_end_dropbehind() but run with interrupts disabled on !PREEMPT_RT, and invalidating the folio turns them back on. ext4 RWF_DONTCACHE overwrites hit this with threadirqs until commit 7d7c9c83c822 ("ext4:
complete dropbehind writeback in task context"), and folios marked dropbehind after their writeback was submitted still can.

Skip the drop when interrupts are disabled. The folio stays cached, as it does when the completion runs in hardirq context.

Fixes ae21c0c0ac56 ("ext4: support uncached buffered I/O")
---
 mm/filemap.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
mm/filemap.c +0 -0
index a49cca600f8c3e..6674c4ef8fe036 100644
@@ -1663,9 +1663,10 @@ void folio_end_dropbehind(struct folio *folio)
 	 * but can happen if normal writeback just happens to find dirty folios
 	 * that were created as part of uncached writeback, and that writeback

mm/filemap.c void folio_end_dropbehind(struct folio *folio) · line 1672

Quoted 10 lines
mm/filemap.c +3 -2
 	 * would otherwise not need non-IRQ handling. Just skip the
-	 * invalidation in that case.
+	 * invalidation in that case, and also when interrupts are disabled,
+	 * as they are in forced-threaded interrupt handlers.
 	 */
-	if (in_task() && folio_trylock(folio)) {
+	if (in_task() && !irqs_disabled() && folio_trylock(folio)) {
 		filemap_end_dropbehind(folio);
 		folio_unlock(folio);
 	}

Good catch!

#15 lore raw

Re: [PATCH 3/4] mm/filemap: don't drop dropbehind folios with interrupts disabled

In reply to Usama Arif

mm/filemap.c void folio_end_dropbehind(struct folio *folio) · line 1669

Quoted 2 lines · Usama Arif
mm/filemap.c +1 -1
-	if (in_task() && folio_trylock(folio)) {
+	if (in_task() && !irqs_disabled() && folio_trylock(folio)) {

I wonder if this should use similar logic to bio_in_atomic().

author
#16 lore raw

Re: [PATCH 3/4] mm/filemap: don't drop dropbehind folios with interrupts disabled

Quoted 5 lines · Christoph Hellwig

mm/filemap.c void folio_end_dropbehind(struct folio *folio) · line 1669

Quoted 2 lines · Usama Arif
mm/filemap.c +1 -1
-	if (in_task() && folio_trylock(folio)) {
+	if (in_task() && !irqs_disabled() && folio_trylock(folio)) {

I wonder if this should use similar logic to bio_in_atomic().

I don't think it fits here. bio_in_atomic() answers whether the completion may sleep, and says yes whenever it can't tell, which is the safe default for deciding to defer. The drop doesn't sleep: dirty folios are skipped, mapped ones are kept, and filemap_release_folio() gets no gfp flags. It only needs task context with interrupts on, because folio_unmap_invalidate() takes the i_pages lock with xa_lock_irq(), so preemption being disabled doesn't matter.

Copying bio_in_atomic() would also stop the drop entirely without CONFIG_PREEMPT_COUNT, which is still possible with ARCH_NO_PREEMPT:
there it returns true even in the workqueue that BIO_COMPLETE_IN_TASK completes from, so RWF_DONTCACHE writes would never be dropped.

#17 lore raw

Re: [PATCH 3/4] mm/filemap: don't drop dropbehind folios with interrupts disabled

In reply to Usama Arif
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] mm/filemap: inaccurate Fixes trailer in folio_end_dropbehind() fix --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] mm/filemap: inaccurate Fixes trailer in folio_end_dropbehind() fix
--

commit fa3358ee2feeec78d1d81bdc2f73fcecfd3a6f0b
Author: Usama Arif <[email protected]>

Quoted 9 lines

mm/filemap: don't drop dropbehind folios with interrupts disabled

Forced-threaded interrupt handlers pass the in_task() check in folio_end_dropbehind() but run with interrupts disabled on !PREEMPT_RT, and invalidating the folio turns them back on. ext4 RWF_DONTCACHE overwrites hit this with threadirqs until commit 7d7c9c83c822 ("ext4:
complete dropbehind writeback in task context"), and folios marked dropbehind after their writeback was submitted still can.

Quoted 6 lines

Skip the drop when interrupts are disabled. The folio stays cached, as it does when the completion runs in hardirq context.

Fixes ae21c0c0ac56 ("ext4: support uncached buffered I/O")

[Severity: Low]
Should the Fixes tag reference fb7d3bc41493 ("mm/filemap: drop streaming/uncached pages when writeback completes") instead?

ae21c0c0ac56 ("ext4: support uncached buffered I/O") only enabled FOP_DONTCACHE in ext4, whereas the in_task() check guarding folio_unmap_invalidate() in mm/filemap.c was introduced by fb7d3bc41493 ("mm/filemap: drop streaming/uncached pages when writeback completes").

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
author
#18 lore raw

PATCH 4/4 mm/fadvise: drop folios under writeback on POSIX_FADV_DONTNEED

In reply to Usama Arif

POSIX_FADV_DONTNEED starts writeback on dirty folios but skips folios under writeback when invalidating. With large folios one writeback bio can hold hundreds of megabytes, none of which leaves writeback until all of it completes, so on XFS DONTNEED right after writing a new 256 MiB file left all of it cached. Syncing first avoids this but blocks the caller, and RWF_DONTCACHE does not help writers using a shared mapping.

Mark the unmapped dirty folios in the range dropbehind before starting writeback, and the unmapped writeback folios after it, so that writeback completion drops them as it does for RWF_DONTCACHE writes. Marking the dirty ones before submission lets their writeback complete in task context, where they can be dropped. Folios that were already under writeback and complete in interrupt context stay cached.

Skip the folio extending past EOF, which an appender calling DONTNEED after each write would otherwise have to read back. Only do this for regular files on filesystems that support RWF_DONTCACHE: those are prepared to drop folios at writeback completion, and unlike block devices, regular files rarely dirty an unmapped folio without its lock, which would race with the WB_DONTCACHE_DIRTY accounting.

On XFS and ext4, new files and overwrites, written with write() or through a shared mapping, were then dropped within a second, apart from the EOF folio; before, most stayed cached.

---
 mm/fadvise.c        | 60 +++++++++++++++++++++++++++++++++++++++++----
 mm/internal.h       |  1 +
 mm/page-writeback.c | 23 +++++++++++++++++
 3 files changed, 79 insertions(+), 5 deletions(-)
mm/fadvise.c +55 -5
index b63fe21416ff21..6e7b86f072fe84 100644
@@ -13,6 +13,7 @@
 #include <linux/fs.h>
 #include <linux/mm.h>
 #include <linux/pagemap.h>
+#include <linux/folio_batch.h>
 #include <linux/backing-dev.h>
 #include <linux/fadvise.h>
 #include <linux/writeback.h>
@@ -28,6 +29,43 @@
  * deactivate the pages and clear PG_Referenced.
  */
 
+/*
+ * Folios under writeback cannot be invalidated. Mark the unmapped dirty and
+ * writeback ones dropbehind so that writeback completion drops them, as for
+ * RWF_DONTCACHE writes. Only filesystems that support those can do that.
+ */
+static void fadvise_mark_dropbehind(struct address_space *mapping,
+		pgoff_t start, pgoff_t end, xa_mark_t tag)
+{
+	loff_t isize = i_size_read(mapping->host);
+	struct folio_batch fbatch;
+	pgoff_t index = start;
+	unsigned int i;
+
+	folio_batch_init(&fbatch);
+	while (filemap_get_folios_tag(mapping, &index, end, tag, &fbatch)) {
+		for (i = 0; i < folio_batch_count(&fbatch); i++) {
+			struct folio *folio = fbatch.folios[i];
+
+			/* Don't mark the EOF folio, appenders write it again */
+			if (folio->index < start ||
+			    folio_next_index(folio) - 1 > end ||
+			    folio_next_pos(folio) > isize)
+				continue;
+			if (folio_test_dropbehind(folio) ||
+			    !folio_trylock(folio))
+				continue;
+			if (folio->mapping == mapping && !folio_mapped(folio) &&
+			    (folio_test_dirty(folio) ||
+			     folio_test_writeback(folio)))
+				folio_mark_dropbehind(folio);
+			folio_unlock(folio);
+		}
+		folio_batch_release(&fbatch);
+		cond_resched();
+	}
+}
+
 int generic_fadvise(struct file *file, loff_t offset, loff_t len, int advice)
 {
 	struct inode *inode;
@@ -37,6 +75,7 @@ int generic_fadvise(struct file *file, loff_t offset, loff_t len, int advice)
 	pgoff_t start_index;
 	pgoff_t end_index;
 	unsigned long nrpages;
+	bool dropbehind;
 
 	inode = file_inode(file);
 	if (S_ISFIFO(inode->i_mode))
@@ -111,8 +150,6 @@ int generic_fadvise(struct file *file, loff_t offset, loff_t len, int advice)
 		spin_unlock(&file->f_lock);
 		break;
 	case POSIX_FADV_DONTNEED:
-		filemap_flush_range(mapping, offset, endbyte);
-
 		/*
 		 * First and last FULL page! Partial pages are deliberately
 		 * preserved on the expectation that it is better to preserve
@@ -135,14 +172,27 @@ int generic_fadvise(struct file *file, loff_t offset, loff_t len, int advice)
 			 * file cache which is not what was asked.
 			 */
 			if (end_index == 0)
-				break;
-
-			end_index--;
+				start_index = 1;
+			else
+				end_index--;
 		}
 
+		dropbehind = end_index >= start_index &&
+			     S_ISREG(inode->i_mode) &&
+			     (file->f_op->fop_flags & FOP_DONTCACHE);
+		if (dropbehind)
+			fadvise_mark_dropbehind(mapping, start_index, end_index,
+						PAGECACHE_TAG_DIRTY);
+
+		filemap_flush_range(mapping, offset, endbyte);
+
 		if (end_index >= start_index) {
 			unsigned long nr_failed = 0;
 
+			if (dropbehind)
+				fadvise_mark_dropbehind(mapping, start_index,
+						end_index, PAGECACHE_TAG_WRITEBACK);
+
 			/*
 			 * It's common to FADV_DONTNEED right after
 			 * the read or write that instantiates the
mm/internal.h +1 -0
index 8942e57744a96e..7a64b5c27f3064 100644
@@ -626,6 +626,7 @@ static inline void hugetlb_folio_restore_rsv_on_unmap(struct vm_area_struct *vma
 #endif
 int folio_unmap_invalidate(struct address_space *mapping, struct folio *folio,
 			   gfp_t gfp);
+void folio_mark_dropbehind(struct folio *folio);
 
 void page_cache_ra_order(struct readahead_control *, struct file_ra_state *);
 void force_page_cache_ra(struct readahead_control *, unsigned long nr);
mm/page-writeback.c +23 -0
index 5939f781fc5402..13f4408f068d5e 100644
@@ -2654,6 +2654,29 @@ void folio_account_cleaned(struct folio *folio, struct bdi_writeback *wb)
 	task_io_account_cancelled_write(nr * PAGE_SIZE);
 }
 
+/*
+ * Mark a locked page cache folio dropbehind, and account it in
+ * WB_DONTCACHE_DIRTY if it is dirty.
+ */
+void folio_mark_dropbehind(struct folio *folio)
+{
+	struct address_space *mapping = folio->mapping;
+	struct inode *inode = mapping->host;
+	struct wb_lock_cookie cookie = {};
+	struct bdi_writeback *wb;
+
+	VM_WARN_ON_ONCE_FOLIO(!folio_test_locked(folio), folio);
+
+	if (folio_test_dropbehind(folio))
+		return;
+
+	wb = unlocked_inode_to_wb_begin(inode, &cookie);
+	folio_set_dropbehind(folio);
+	if (folio_test_dirty(folio) && mapping_can_writeback(mapping))
+		wb_stat_mod(wb, WB_DONTCACHE_DIRTY, folio_nr_pages(folio));
+	unlocked_inode_to_wb_end(inode, &cookie);
+}
+
 /*
  * Mark the folio dirty, and set it dirty in the page cache.
  *
Signature · 1 line
2.53.1-Meta
Reviewed-by on v1 4/4
#19 lore raw

Re: [PATCH 4/4] mm/fadvise: drop folios under writeback on POSIX_FADV_DONTNEED

Quoted 172 lines · Usama Arif

POSIX_FADV_DONTNEED starts writeback on dirty folios but skips folios under writeback when invalidating. With large folios one writeback bio can hold hundreds of megabytes, none of which leaves writeback until all of it completes, so on XFS DONTNEED right after writing a new 256 MiB file left all of it cached. Syncing first avoids this but blocks the caller, and RWF_DONTCACHE does not help writers using a shared mapping.

Mark the unmapped dirty folios in the range dropbehind before starting writeback, and the unmapped writeback folios after it, so that writeback completion drops them as it does for RWF_DONTCACHE writes. Marking the dirty ones before submission lets their writeback complete in task context, where they can be dropped. Folios that were already under writeback and complete in interrupt context stay cached.

Skip the folio extending past EOF, which an appender calling DONTNEED after each write would otherwise have to read back. Only do this for regular files on filesystems that support RWF_DONTCACHE: those are prepared to drop folios at writeback completion, and unlike block devices, regular files rarely dirty an unmapped folio without its lock, which would race with the WB_DONTCACHE_DIRTY accounting.

On XFS and ext4, new files and overwrites, written with write() or through a shared mapping, were then dropped within a second, apart from the EOF folio; before, most stayed cached.

---
 mm/fadvise.c        | 60 +++++++++++++++++++++++++++++++++++++++++----
 mm/internal.h       |  1 +
 mm/page-writeback.c | 23 +++++++++++++++++
 3 files changed, 79 insertions(+), 5 deletions(-)
mm/fadvise.c +55 -5
index b63fe21416ff21..6e7b86f072fe84 100644
@@ -13,6 +13,7 @@
 #include <linux/fs.h>
 #include <linux/mm.h>
 #include <linux/pagemap.h>
+#include <linux/folio_batch.h>
 #include <linux/backing-dev.h>
 #include <linux/fadvise.h>
 #include <linux/writeback.h>
@@ -28,6 +29,43 @@
  * deactivate the pages and clear PG_Referenced.
  */
 
+/*
+ * Folios under writeback cannot be invalidated. Mark the unmapped dirty and
+ * writeback ones dropbehind so that writeback completion drops them, as for
+ * RWF_DONTCACHE writes. Only filesystems that support those can do that.
+ */
+static void fadvise_mark_dropbehind(struct address_space *mapping,
+		pgoff_t start, pgoff_t end, xa_mark_t tag)
+{
+	loff_t isize = i_size_read(mapping->host);
+	struct folio_batch fbatch;
+	pgoff_t index = start;
+	unsigned int i;
+
+	folio_batch_init(&fbatch);
+	while (filemap_get_folios_tag(mapping, &index, end, tag, &fbatch)) {
+		for (i = 0; i < folio_batch_count(&fbatch); i++) {
+			struct folio *folio = fbatch.folios[i];
+
+			/* Don't mark the EOF folio, appenders write it again */
+			if (folio->index < start ||
+			    folio_next_index(folio) - 1 > end ||
+			    folio_next_pos(folio) > isize)
+				continue;
+			if (folio_test_dropbehind(folio) ||
+			    !folio_trylock(folio))
+				continue;
+			if (folio->mapping == mapping && !folio_mapped(folio) &&
+			    (folio_test_dirty(folio) ||
+			     folio_test_writeback(folio)))
+				folio_mark_dropbehind(folio);
+			folio_unlock(folio);
+		}
+		folio_batch_release(&fbatch);
+		cond_resched();
+	}
+}
+
 int generic_fadvise(struct file *file, loff_t offset, loff_t len, int advice)
 {
 	struct inode *inode;
@@ -37,6 +75,7 @@ int generic_fadvise(struct file *file, loff_t offset, loff_t len, int advice)
 	pgoff_t start_index;
 	pgoff_t end_index;
 	unsigned long nrpages;
+	bool dropbehind;
 
 	inode = file_inode(file);
 	if (S_ISFIFO(inode->i_mode))
@@ -111,8 +150,6 @@ int generic_fadvise(struct file *file, loff_t offset, loff_t len, int advice)
 		spin_unlock(&file->f_lock);
 		break;
 	case POSIX_FADV_DONTNEED:
-		filemap_flush_range(mapping, offset, endbyte);
-
 		/*
 		 * First and last FULL page! Partial pages are deliberately
 		 * preserved on the expectation that it is better to preserve
@@ -135,14 +172,27 @@ int generic_fadvise(struct file *file, loff_t offset, loff_t len, int advice)
 			 * file cache which is not what was asked.
 			 */
 			if (end_index == 0)
-				break;
-
-			end_index--;
+				start_index = 1;
+			else
+				end_index--;
 		}
 
+		dropbehind = end_index >= start_index &&
+			     S_ISREG(inode->i_mode) &&
+			     (file->f_op->fop_flags & FOP_DONTCACHE);
+		if (dropbehind)
+			fadvise_mark_dropbehind(mapping, start_index, end_index,
+						PAGECACHE_TAG_DIRTY);
+
+		filemap_flush_range(mapping, offset, endbyte);
+
 		if (end_index >= start_index) {
 			unsigned long nr_failed = 0;
 
+			if (dropbehind)
+				fadvise_mark_dropbehind(mapping, start_index,
+						end_index, PAGECACHE_TAG_WRITEBACK);
+
 			/*
 			 * It's common to FADV_DONTNEED right after
 			 * the read or write that instantiates the
mm/internal.h +1 -0
index 8942e57744a96e..7a64b5c27f3064 100644
@@ -626,6 +626,7 @@ static inline void hugetlb_folio_restore_rsv_on_unmap(struct vm_area_struct *vma
 #endif
 int folio_unmap_invalidate(struct address_space *mapping, struct folio *folio,
 			   gfp_t gfp);
+void folio_mark_dropbehind(struct folio *folio);
 
 void page_cache_ra_order(struct readahead_control *, struct file_ra_state *);
 void force_page_cache_ra(struct readahead_control *, unsigned long nr);
mm/page-writeback.c +16 -0
index 5939f781fc5402..13f4408f068d5e 100644
@@ -2654,6 +2654,29 @@ void folio_account_cleaned(struct folio *folio, struct bdi_writeback *wb)
 	task_io_account_cancelled_write(nr * PAGE_SIZE);
 }
 
+/*
+ * Mark a locked page cache folio dropbehind, and account it in
+ * WB_DONTCACHE_DIRTY if it is dirty.
+ */
+void folio_mark_dropbehind(struct folio *folio)
+{
+	struct address_space *mapping = folio->mapping;
+	struct inode *inode = mapping->host;
+	struct wb_lock_cookie cookie = {};
+	struct bdi_writeback *wb;
+
+	VM_WARN_ON_ONCE_FOLIO(!folio_test_locked(folio), folio);
+
+	if (folio_test_dropbehind(folio))
+		return;
+

mm/page-writeback.c void folio_account_cleaned(struct folio *folio, struct bdi_writeback *wb) · line 2682

Quoted 10 lines
mm/page-writeback.c +7 -0
+	wb = unlocked_inode_to_wb_begin(inode, &cookie);
+	folio_set_dropbehind(folio);
+	if (folio_test_dirty(folio) && mapping_can_writeback(mapping))
+		wb_stat_mod(wb, WB_DONTCACHE_DIRTY, folio_nr_pages(folio));
+	unlocked_inode_to_wb_end(inode, &cookie);
+}
+
 /*
  * Mark the folio dirty, and set it dirty in the page cache.
  *

I like this idea. I think that the only reason we don't mark these dropbehind today is because all of the DONTCACHE code was added more recently than the posix_fadvise() handling, and no one thought to do it until now.

#20 lore raw

Re: [PATCH 4/4] mm/fadvise: drop folios under writeback on POSIX_FADV_DONTNEED

In reply to Usama Arif
Quoted 4 lines · Usama Arif

POSIX_FADV_DONTNEED starts writeback on dirty folios but skips folios under writeback when invalidating. With large folios one writeback bio can hold hundreds of megabytes, none of which leaves writeback until all of it completes, so on XFS DONTNEED right after writing a new 256 MiB

s/XFS/fadvise/ ?

author
#21 lore raw

Re: [PATCH 4/4] mm/fadvise: drop folios under writeback on POSIX_FADV_DONTNEED

Quoted 7 lines · Christoph Hellwig
Quoted 4 lines · Usama Arif

POSIX_FADV_DONTNEED starts writeback on dirty folios but skips folios under writeback when invalidating. With large folios one writeback bio can hold hundreds of megabytes, none of which leaves writeback until all of it completes, so on XFS DONTNEED right after writing a new 256 MiB

s/XFS/fadvise/ ?

XFS is the filesystem where we see this. "on XFS DONTNEED" reads badly. I've changed it to "DONTNEED right after writing a new 256 MiB file on XFS left all of it cached" if there is a v2.

Thanks for the review!

maintainer
#22 lore raw

Re: [PATCH 4/4] mm/fadvise: drop folios under writeback on POSIX_FADV_DONTNEED

In reply to Usama Arif
Quoted 14 lines · Usama Arif

POSIX_FADV_DONTNEED starts writeback on dirty folios but skips folios under writeback when invalidating. With large folios one writeback bio can hold hundreds of megabytes, none of which leaves writeback until all of it completes, so on XFS DONTNEED right after writing a new 256 MiB file left all of it cached. Syncing first avoids this but blocks the caller, and RWF_DONTCACHE does not help writers using a shared mapping.

Mark the unmapped dirty folios in the range dropbehind before starting writeback, and the unmapped writeback folios after it, so that writeback completion drops them as it does for RWF_DONTCACHE writes. Marking the dirty ones before submission lets their writeback complete in task context, where they can be dropped. Folios that were already under writeback and complete in interrupt context stay cached.

Quoted 5 lines

Skip the folio extending past EOF, which an appender calling DONTNEED after each write would otherwise have to read back. Only do this for regular files on filesystems that support RWF_DONTCACHE: those are prepared to drop folios at writeback completion, and unlike block devices, regular files rarely dirty an unmapped folio without its lock,

			^^^^^^^^

This doesn't put peace into my mind. So we "sometimes" corrupt the WB_DONTCACHE_DIRTY counter. Not good and I'm not sure why you thought this is good enough. See below for more details.

Quoted 7 lines

which would race with the WB_DONTCACHE_DIRTY accounting.

On XFS and ext4, new files and overwrites, written with write() or through a shared mapping, were then dropped within a second, apart from the EOF folio; before, most stayed cached.

...

Quoted 65 lines
mm/fadvise.c +39 -5
+/*
+ * Folios under writeback cannot be invalidated. Mark the unmapped dirty and
+ * writeback ones dropbehind so that writeback completion drops them, as for
+ * RWF_DONTCACHE writes. Only filesystems that support those can do that.
+ */
+static void fadvise_mark_dropbehind(struct address_space *mapping,
+		pgoff_t start, pgoff_t end, xa_mark_t tag)
+{
+	loff_t isize = i_size_read(mapping->host);
+	struct folio_batch fbatch;
+	pgoff_t index = start;
+	unsigned int i;
+
+	folio_batch_init(&fbatch);
+	while (filemap_get_folios_tag(mapping, &index, end, tag, &fbatch)) {
+		for (i = 0; i < folio_batch_count(&fbatch); i++) {
+			struct folio *folio = fbatch.folios[i];
+
+			/* Don't mark the EOF folio, appenders write it again */
+			if (folio->index < start ||
+			    folio_next_index(folio) - 1 > end ||
+			    folio_next_pos(folio) > isize)
+				continue;
+			if (folio_test_dropbehind(folio) ||
+			    !folio_trylock(folio))
+				continue;
+			if (folio->mapping == mapping && !folio_mapped(folio) &&
+			    (folio_test_dirty(folio) ||
+			     folio_test_writeback(folio)))
+				folio_mark_dropbehind(folio);
+			folio_unlock(folio);
+		}
+		folio_batch_release(&fbatch);
+		cond_resched();
+	}
+}
+
 int generic_fadvise(struct file *file, loff_t offset, loff_t len, int advice)
 {
 	struct inode *inode;
@@ -37,6 +75,7 @@ int generic_fadvise(struct file *file, loff_t offset, loff_t len, int advice)
 	pgoff_t start_index;
 	pgoff_t end_index;
 	unsigned long nrpages;
+	bool dropbehind;
 
 	inode = file_inode(file);
 	if (S_ISFIFO(inode->i_mode))
@@ -111,8 +150,6 @@ int generic_fadvise(struct file *file, loff_t offset, loff_t len, int advice)
 		spin_unlock(&file->f_lock);
 		break;
 	case POSIX_FADV_DONTNEED:
-		filemap_flush_range(mapping, offset, endbyte);
-
 		/*
 		 * First and last FULL page! Partial pages are deliberately
 		 * preserved on the expectation that it is better to preserve
@@ -135,14 +172,27 @@ int generic_fadvise(struct file *file, loff_t offset, loff_t len, int advice)
 			 * file cache which is not what was asked.
 			 */
 			if (end_index == 0)
-				break;
-
-			end_index--;
+				start_index = 1;

mm/fadvise.c int generic_fadvise(struct file *file, loff_t offset, loff_t len, int advice) · line 185

Quoted 10 lines
mm/fadvise.c +8 -0
+			else
+				end_index--;
 		}
 
+		dropbehind = end_index >= start_index &&
+			     S_ISREG(inode->i_mode) &&
+			     (file->f_op->fop_flags & FOP_DONTCACHE);
+		if (dropbehind)
+			fadvise_mark_dropbehind(mapping, start_index, end_index,
+						PAGECACHE_TAG_DIRTY);

Why do you mark dirty folios as dropbehind here? Isn't that unnecessarily expensive? We could just filemap_flush_range(), then mark dropbehind folios under writeback and then invalidate whatever is already clean and that should be good enough, shouldn't it?

Quoted 10 lines
mm/fadvise.c +7 -0
+
+		filemap_flush_range(mapping, offset, endbyte);
+
 		if (end_index >= start_index) {
 			unsigned long nr_failed = 0;
 
+			if (dropbehind)
+				fadvise_mark_dropbehind(mapping, start_index,
+						end_index, PAGECACHE_TAG_WRITEBACK);
+

...

Quoted 12 lines
mm/page-writeback.c +12 -0
+/*
+ * Mark a locked page cache folio dropbehind, and account it in
+ * WB_DONTCACHE_DIRTY if it is dirty.
+ */
+void folio_mark_dropbehind(struct folio *folio)
+{
+	struct address_space *mapping = folio->mapping;
+	struct inode *inode = mapping->host;
+	struct wb_lock_cookie cookie = {};
+	struct bdi_writeback *wb;
+
+	VM_WARN_ON_ONCE_FOLIO(!folio_test_locked(folio), folio);

mm/page-writeback.c void folio_account_cleaned(struct folio *folio, struct bdi_writeback *wb) · line 2678

Quoted 10 lines
mm/page-writeback.c +10 -0
+
+	if (folio_test_dropbehind(folio))
+		return;
+
+	wb = unlocked_inode_to_wb_begin(inode, &cookie);
+	folio_set_dropbehind(folio);
+	if (folio_test_dirty(folio) && mapping_can_writeback(mapping))
+		wb_stat_mod(wb, WB_DONTCACHE_DIRTY, folio_nr_pages(folio));
+	unlocked_inode_to_wb_end(inode, &cookie);
+}

So as you glossed over in the changelog, this can race with folio_account_dirtied() which isn't necessarily called under the folio lock. Both places will see dirty & dropbehind set and increase WB_DONTCACHE_DIRTY. You need to hold xa_lock for &mapping->i_pages to make this safe, which luckily shouldn't be that hard to do...

Honza

Signature · 2 lines
Jan Kara <[email protected]>
SUSE Labs, CR
author
#23 lore raw

Re: [PATCH 4/4] mm/fadvise: drop folios under writeback on POSIX_FADV_DONTNEED

Quoted 104 lines · On Thu, 3 Dec 2026 10:58:15 +0100 Jan Kara <[email protected]> wrote:
Quoted 14 lines · Usama Arif

POSIX_FADV_DONTNEED starts writeback on dirty folios but skips folios under writeback when invalidating. With large folios one writeback bio can hold hundreds of megabytes, none of which leaves writeback until all of it completes, so on XFS DONTNEED right after writing a new 256 MiB file left all of it cached. Syncing first avoids this but blocks the caller, and RWF_DONTCACHE does not help writers using a shared mapping.

Mark the unmapped dirty folios in the range dropbehind before starting writeback, and the unmapped writeback folios after it, so that writeback completion drops them as it does for RWF_DONTCACHE writes. Marking the dirty ones before submission lets their writeback complete in task context, where they can be dropped. Folios that were already under writeback and complete in interrupt context stay cached.

Quoted 5 lines

Skip the folio extending past EOF, which an appender calling DONTNEED after each write would otherwise have to read back. Only do this for regular files on filesystems that support RWF_DONTCACHE: those are prepared to drop folios at writeback completion, and unlike block devices, regular files rarely dirty an unmapped folio without its lock,

			^^^^^^^^

This doesn't put peace into my mind. So we "sometimes" corrupt the WB_DONTCACHE_DIRTY counter. Not good and I'm not sure why you thought this is good enough. See below for more details.

Quoted 7 lines

which would race with the WB_DONTCACHE_DIRTY accounting.

On XFS and ext4, new files and overwrites, written with write() or through a shared mapping, were then dropped within a second, apart from the EOF folio; before, most stayed cached.

...

Quoted 69 lines
mm/fadvise.c +41 -5
+/*
+ * Folios under writeback cannot be invalidated. Mark the unmapped dirty and
+ * writeback ones dropbehind so that writeback completion drops them, as for
+ * RWF_DONTCACHE writes. Only filesystems that support those can do that.
+ */
+static void fadvise_mark_dropbehind(struct address_space *mapping,
+		pgoff_t start, pgoff_t end, xa_mark_t tag)
+{
+	loff_t isize = i_size_read(mapping->host);
+	struct folio_batch fbatch;
+	pgoff_t index = start;
+	unsigned int i;
+
+	folio_batch_init(&fbatch);
+	while (filemap_get_folios_tag(mapping, &index, end, tag, &fbatch)) {
+		for (i = 0; i < folio_batch_count(&fbatch); i++) {
+			struct folio *folio = fbatch.folios[i];
+
+			/* Don't mark the EOF folio, appenders write it again */
+			if (folio->index < start ||
+			    folio_next_index(folio) - 1 > end ||
+			    folio_next_pos(folio) > isize)
+				continue;
+			if (folio_test_dropbehind(folio) ||
+			    !folio_trylock(folio))
+				continue;
+			if (folio->mapping == mapping && !folio_mapped(folio) &&
+			    (folio_test_dirty(folio) ||
+			     folio_test_writeback(folio)))
+				folio_mark_dropbehind(folio);
+			folio_unlock(folio);
+		}
+		folio_batch_release(&fbatch);
+		cond_resched();
+	}
+}
+
 int generic_fadvise(struct file *file, loff_t offset, loff_t len, int advice)
 {
 	struct inode *inode;
@@ -37,6 +75,7 @@ int generic_fadvise(struct file *file, loff_t offset, loff_t len, int advice)
 	pgoff_t start_index;
 	pgoff_t end_index;
 	unsigned long nrpages;
+	bool dropbehind;
 
 	inode = file_inode(file);
 	if (S_ISFIFO(inode->i_mode))
@@ -111,8 +150,6 @@ int generic_fadvise(struct file *file, loff_t offset, loff_t len, int advice)
 		spin_unlock(&file->f_lock);
 		break;
 	case POSIX_FADV_DONTNEED:
-		filemap_flush_range(mapping, offset, endbyte);
-
 		/*
 		 * First and last FULL page! Partial pages are deliberately
 		 * preserved on the expectation that it is better to preserve
@@ -135,14 +172,27 @@ int generic_fadvise(struct file *file, loff_t offset, loff_t len, int advice)
 			 * file cache which is not what was asked.
 			 */
 			if (end_index == 0)
-				break;
-
-			end_index--;
+				start_index = 1;
+			else
+				end_index--;
 		}
 
Quoted 11 lines

mm/fadvise.c int generic_fadvise(struct file *file, loff_t offset, loff_t len, int advice) · line 185

Quoted 6 lines
mm/fadvise.c +6 -0
+		dropbehind = end_index >= start_index &&
+			     S_ISREG(inode->i_mode) &&
+			     (file->f_op->fop_flags & FOP_DONTCACHE);
+		if (dropbehind)
+			fadvise_mark_dropbehind(mapping, start_index, end_index,
+						PAGECACHE_TAG_DIRTY);

Why do you mark dirty folios as dropbehind here? Isn't that unnecessarily expensive? We could just filemap_flush_range(), then mark dropbehind folios under writeback and then invalidate whatever is already clean and that should be good enough, shouldn't it?

It was for overwrites: BIO_COMPLETE_IN_TASK is set from PG_dropbehind when the bio is built, so overwrites marked only after the flush complete in interrupt context and aren't dropped. It wasn't measurably slower (median DONTNEED 1.9 ms vs 1.8 ms without), but as dirty folios can't be marked safely as you said above, I will drop this in the next revision . New files, the case that hit us, are still dropped, as XFS and ext4 complete them from their workqueues.

Quoted 34 lines
Quoted 11 lines
mm/fadvise.c +7 -0
+
+		filemap_flush_range(mapping, offset, endbyte);
+
 		if (end_index >= start_index) {
 			unsigned long nr_failed = 0;
 
+			if (dropbehind)
+				fadvise_mark_dropbehind(mapping, start_index,
+						end_index, PAGECACHE_TAG_WRITEBACK);
+

...

Quoted 20 lines
mm/page-writeback.c +20 -0
+/*
+ * Mark a locked page cache folio dropbehind, and account it in
+ * WB_DONTCACHE_DIRTY if it is dirty.
+ */
+void folio_mark_dropbehind(struct folio *folio)
+{
+	struct address_space *mapping = folio->mapping;
+	struct inode *inode = mapping->host;
+	struct wb_lock_cookie cookie = {};
+	struct bdi_writeback *wb;
+
+	VM_WARN_ON_ONCE_FOLIO(!folio_test_locked(folio), folio);
+
+	if (folio_test_dropbehind(folio))
+		return;
+
+	wb = unlocked_inode_to_wb_begin(inode, &cookie);
+	folio_set_dropbehind(folio);
+	if (folio_test_dirty(folio) && mapping_can_writeback(mapping))
+		wb_stat_mod(wb, WB_DONTCACHE_DIRTY, folio_nr_pages(folio));
Quoted 9 lines

mm/page-writeback.c void folio_account_cleaned(struct folio *folio, struct bdi_writeback *wb) · line 2678

Quoted 2 lines
mm/page-writeback.c +2 -0
+	unlocked_inode_to_wb_end(inode, &cookie);
+}

So as you glossed over in the changelog, this can race with folio_account_dirtied() which isn't necessarily called under the folio lock. Both places will see dirty & dropbehind set and increase WB_DONTCACHE_DIRTY. You need to hold xa_lock for &mapping->i_pages to make this safe, which luckily shouldn't be that hard to do...

It looks like xa_lock alone isn't enough for a dirty folio, as filemap_dirty_folio(), block_dirty_folio() and mark_buffer_dirty() set PG_dirty before taking it. So the next revision will mark folio under xa_lock only if it is clean, and never touches the counter. The lookup clear in this revision patch 2 also has the same problem, so next revision applies the same rule there.

Quoted 5 lines

Honza

Signature · 2 lines
Jan Kara <[email protected]>
SUSE Labs, CR
maintainer Applied
#24 lore raw

Re: (subset) [PATCH 0/4] mm: drop folios under writeback on POSIX_FADV_DONTNEED

In reply to Usama Arif
Quoted 9 lines · Usama Arif

POSIX_FADV_DONTNEED starts writeback on the dirty folios in the range without waiting for it, then invalidates what it can and skips folios under writeback. With small folios most bios complete while DONTNEED is still invalidating. With large folios on XFS a single bio can carry hundreds of megabytes, none of which leaves writeback until all of it completes, so DONTNEED right after writing a new 256 MiB file leaves all of it cached.

[...]

Applied, thanks!

tree: mm/core.git
branch: migrate-7.5.misc

Applied patches will appear soon in mm-next, followed by linux-next.

Please report any outstanding bugs that were missed during review, so we can either drop the patch series or decide how to fix it up.

It is encouraged to provide Acked-bys, Reviewed-bys, and Tested-bys even though the patches have already been applied. If possible, patch trailers will be updated.

Note that commit hashes shown below are subject to change due to rebase, trailer updates or similar. Further, this is not a guarantee that the patches will go upstream. If in doubt, please check the listed branch.

[1/4] mm/migrate: preserve PG_dropbehind across folio migration

      https://git.kernel.org/mm/core/c/282fe7c7
Signature · 3 lines
Cheers,

David