mm, iomap: account dirty at page granularity for per-block dirty folios
Subsystems (14)
cover mm, iomap: account dirty at page granularity for per-block dirty folios
Since iomap gained per-block dirty tracking, a large folio can be partially dirty: struct iomap_folio_state records exactly which blocks are dirty, and writeback only writes those ranges. The mm dirty accounting, however, still charges the whole folio even if a single block is dirty (up to 512x over-accounting for a 2 MB folio over 4 KB blocks).
balance_dirty_pages() then throttles writers against a number that is unrelated to how much data actually needs writing back. On workloads that repeatedly dirty small ranges of large folios -- e.g. PostgreSQL, which writes mostly 8/16 KB pages -- dirty_thresh is crossed and writers are throttled long before the real dirty data justifies it. On the benchmark below, run on v7.3-rc7, the unpatched kernel charges ~159 TB of dirtied pages while writing ~6 TB to the array, a factor of 27; with this series the dirtied pages charged match the data actually written.
This series makes iomap charge and discharge the mm dirty counters per dirty page for folios that carry per-block dirty state, so a partially dirty large folio is accounted for the dirty part only:
- Patch 1 adds the mm infrastructure: an AS_DIRTY_PER_BLOCK mapping flag, an @accounted argument to __folio_mark_dirty() and __filemap_dirty_folio() to skip the generic per-folio charge, and an address_space_operations::accounted_dirty_pages() callback used by the discharge and migration paths instead of folio_nr_pages(). No filesystem opts in, so it is a no-op on its own.
- Patch 2 makes iomap charge per dirty page from the per-block dirty bitmap and wires iomap_accounted_dirty_pages() into every iomap-based filesystem.
This was benchmarked with PostgreSQL using the pgbench simple-update workload on v7.3-rc7. Average throughput rises 46.8% (139.8k -> 205.2k tps) and run-to-run variability drops from a 23.60% to a 3.98% coefficient of variation: the worst iteration improves from 97.9k to 191.5k tps, while the best gains 8%, 199.4k -> 215.9k.
Ten iterations per kernel, same database and workload (tps):
Kernel Avg Min Max CV iters iters
1-5 6-10 ______________________ ______ ______ ______ ______ ______ ______ v7.3-rc7 139.8k 97.9k 199.4k 23.60% 164.4k 115.2k v7.3-rc7 + this series 205.2k 191.5k 215.9k 3.98% 200.1k 210.2k
On unpatched v7.3-rc7 the worst iteration lands ~51% below the best, and throughput decays as the run progresses: iterations 6-10 average 30% below iterations 1-5. With this series the decay is gone -- the second half is similar to the first -- and the coefficient of variation stays at 3.98%.
The over-accounting has existed since commit 4ce02c679722 ("iomap: Add per-block dirty state tracking to improve performance"), merged in v6.6, where the ifs bitmap started recording partial dirty state while the mm counters kept charging whole folios.
The throughput collapse bisects to the v6.17 readahead series, first bad commit c4602f9fa77f ("mm/readahead: store folio order in struct file_ra_state"), which lets readahead stay at the largest folio order once it has ramped up, so a single dirty block charges far more than is written. Patch 2 therefore carries:
Test environment:
Hardware: 2x AWS EC2 m8g.24xlarge
(SUT with 12x 1TB io2, 32000 IOPS each, RAID0, XFS) OS: AL2023 Kernels: v7.3-rc7, v7.3-rc7 + this series Database: PostgreSQL 17 (with huge_pages=on) Workload: pgbench simple-update
1024 clients, 96 threads, 600s duration scale factor 8470, fillfactor=90, prepared protocol
Runs: 10 iterations per configuration
How to replicate results:
This script starts two AWS EC2 m8g.24xlarge instances (SUT + driver), then installs, loads and benchmarks PostgreSQL using the repro-collection repository. To run it:
# Reproducer code (dirty-folio-regression branch):
git clone -b dirty-folio-regression \
https://github.com/aws/repro-collection.git ~/repro-collection # Concatenate patches 1 and 2 of this series, in order, into one file:
cat 0001-*.patch 0002-*.patch > dirty-per-block.patch
# Setup and start PostgreSQL benchmark: KERNEL_REPO="https://git.kernel.org/pub/scm/linux/kernel/git/next/linux-next.git" \ KERNEL_BRANCH="v7.3-rc7" \ ITERS=10 \ PLACEMENT_GROUP="pg-test" \ KEY="$HOME/.ssh/id_rsa" \ KEYPAIR="<aws keypair>" \ ./repros/repro-postgresql-dirty-folios/folio-reproduce.sh <benchmark name> \ --patch="<path to dirty-per-block.patch>"
Salvatore Dipietro (2):
mm: add infrastructure for per-dirty-page accounting mm, iomap: account dirty at page granularity for per-block dirty
folios
fs/buffer.c | 4 +- fs/exfat/inode.c | 1 + fs/fuse/file.c | 1 + fs/gfs2/aops.c | 1 + fs/iomap/buffered-io.c | 167 ++++++++++++++++++++++++++++++++++++++-- fs/ntfs/aops.c | 2 + fs/ntfs3/inode.c | 2 + fs/xfs/xfs_aops.c | 1 + fs/zonefs/file.c | 1 + include/linux/fs.h | 7 ++ include/linux/iomap.h | 1 + include/linux/pagemap.h | 20 ++++- mm/internal.h | 3 + mm/migrate.c | 17 +++- mm/page-writeback.c | 91 +++++++++++++++++----- 15 files changed, 286 insertions(+), 33 deletions(-)
base-commit: 24a19b953e2a3d0ea5a8c4951a0ab8f32720c907
Signature · 6 lines
2.50.1 AMAZON DEVELOPMENT CENTER ITALY SRL, viale Monte Grappa 3/5, 20124 Milano, Italia, Registro delle Imprese di Milano Monza Brianza Lodi REA n. 2504859, Capitale Sociale: 10.000 EUR i.v., Cod. Fisc. e P.IVA 10100050961, Societa con Socio Unico
PATCH 1/2 mm: add infrastructure for per-dirty-page accounting
Add the mm-side machinery that lets a filesystem charge the dirty counters (NR_FILE_DIRTY, NR_ZONE_WRITE_PENDING, WB_RECLAIMABLE) per dirty page instead of per whole folio, without yet enabling it for any filesystem.
Add an AS_DIRTY_PER_BLOCK mapping flag with mapping_set_dirty_per_block()/mapping_dirty_per_block() helpers, an accounted_dirty_pages() address_space_operations callback, and an @accounted argument to __folio_mark_dirty() (with filemap_dirty_folio() split into __filemap_dirty_folio()) so the generic per-folio charge can be suppressed for folios a filesystem has already accounted.
folio_accounted_dirty_pages() dispatches through the new a_ops callback, falling back to folio_nr_pages() when no filesystem opts in, and folio_account_cleaned() and folio migration use it in place of folio_nr_pages(). folio_clear_dirty_for_io() leaves the charge of per-block folios to the filesystem. No filesystem sets the flag or registers the callback yet, so this commit is a no-op on its own.
This is a prerequisite for the following iomap patch, which fixes the over-accounting; both are needed for stable.
--- fs/buffer.c | 4 +- include/linux/fs.h | 7 ++++ include/linux/pagemap.h | 20 ++++++++- mm/internal.h | 3 ++ mm/migrate.c | 17 ++++++-- mm/page-writeback.c | 91 ++++++++++++++++++++++++++++++++--------- 6 files changed, 115 insertions(+), 27 deletions(-)
fs/buffer.c +2 -2
@@ -693,7 +693,7 @@ bool block_dirty_folio(struct address_space *mapping, struct folio *folio)spin_unlock (&mapping->i_private_lock);if (newly_dirty) -__folio_mark_dirty (folio, mapping,1 ); +__folio_mark_dirty (folio, mapping,1 , false);if (newly_dirty)__mark_inode_dirty (mapping->host,I_DIRTY_PAGES );
@@ -1011,7 +1011,7 @@ void mark_buffer_dirty(struct buffer_head *bh)if (!folio_test_set_dirty (folio)) { mapping = folio->mapping;if (mapping) -__folio_mark_dirty (folio, mapping,0 ); +__folio_mark_dirty (folio, mapping,0 , false); }if (mapping)__mark_inode_dirty (mapping->host,I_DIRTY_PAGES );
include/linux/fs.h +7 -0
@@ -407,6 +407,13 @@ struct address_space_operations {/* Mark a folio dirty. Return true if this dirtied it */ bool (*dirty_folio)(struct address_space *,struct folio *); +/* +* Pages of the folio currently charged to the dirty counters, for +* filesystems that account dirty state at sub-folio (per-block) +* granularity. +*/ +long (*accounted_dirty_pages)(struct folio *folio); +void (*readahead)(struct readahead_control *); int (*write_begin)(const struct kiocb *, struct address_space *mapping,
include/linux/pagemap.h +19 -1
@@ -210,6 +210,7 @@ enum mapping_flags {AS_WRITEBACK_MAY_DEADLOCK_ON_RECLAIM =9 ,AS_KERNEL_FILE =10 ,/* mapping for a fake kernel file that shouldn't account usage to user cgroups */ +AS_DIRTY_PER_BLOCK =11 ,/* fs accounts dirty pages, not whole folios */ /* Bits 16-25 are used for FOLIO_ORDER */ AS_FOLIO_ORDER_BITS =5 , AS_FOLIO_ORDER_MIN = 16,
@@ -304,6 +305,20 @@ static inline void mapping_clear_release_always(struct address_space *mapping)clear_bit (AS_RELEASE_ALWAYS , &mapping->flags); } +/* +* Set by filesystems that charge the mm dirty counters per dirty page rather +* than per folio, so the generic paths must not also account whole folios. +*/ +static inline void mapping_set_dirty_per_block (struct address_space *mapping) +{ +set_bit (AS_DIRTY_PER_BLOCK , &mapping->flags); +} + +static inline bool mapping_dirty_per_block (const struct address_space *mapping) +{ +return test_bit (AS_DIRTY_PER_BLOCK , &mapping->flags); +} +static inline bool mapping_stable_writes (const struct address_space *mapping) {return test_bit (AS_STABLE_WRITES , &mapping->flags);
@@ -1311,7 +1326,10 @@ void folio_end_writeback(struct folio *folio);void folio_end_writeback_no_dropbehind (struct folio *folio);void folio_end_dropbehind (struct folio *folio);void folio_wait_stable (struct folio *folio); -void __folio_mark_dirty (struct folio *folio,struct address_space *,int warn); +void __folio_mark_dirty (struct folio *folio,struct address_space *mapping, +int warn,bool accounted); +bool __filemap_dirty_folio (struct address_space *mapping,struct folio *folio, +bool accounted);void folio_account_cleaned (struct folio *folio,struct bdi_writeback *wb);void __folio_cancel_dirty (struct folio *folio);static inline void folio_cancel_dirty (struct folio *folio)
mm/internal.h +3 -0
@@ -40,6 +40,9 @@ void *workingset_eviction(struct folio *folio,void workingset_refault (struct folio *folio,void *shadow);void workingset_activation (struct folio *folio); +/* mm/page-writeback.c */ +long folio_accounted_dirty_pages (struct folio *folio); +/* mm/folio.c */ void folio_add_lru_vma (struct folio *folio,struct vm_area_struct *vma);
mm/migrate.c +13 -4
@@ -588,6 +588,7 @@ static int __folio_migrate_mapping(struct address_space *mapping,struct zone *oldzone, *newzone;int dirty;long nr =folio_nr_pages (folio); +long nr_dirty = nr;if (!mapping) {/* Take off deferred split queue while frozen and memcg set */
@@ -614,6 +615,14 @@ static int __folio_migrate_mapping(struct address_space *mapping, oldzone =folio_zone (folio); newzone =folio_zone (newfolio); +/* +* Only what was charged moves between the zones below, which may be less +* than the whole folio. Sample it outside the i_pages lock, as it walks +* the per-block state, and while the folio is still dirty. +*/ +if (folio_test_dirty (folio)) + nr_dirty =folio_accounted_dirty_pages (folio); +if (folio_test_swapcache (folio)) ci =swap_cluster_get_and_lock_irq (folio);else
@@ -708,10 +717,10 @@ static int __folio_migrate_mapping(struct address_space *mapping, }#endif if (dirty &&mapping_can_writeback (mapping)) { -mod_lruvec_state (old_lruvec,NR_FILE_DIRTY , -nr); -__mod_zone_page_state (oldzone,NR_ZONE_WRITE_PENDING , -nr); -mod_lruvec_state (new_lruvec,NR_FILE_DIRTY , nr); -__mod_zone_page_state (newzone,NR_ZONE_WRITE_PENDING , nr); +mod_lruvec_state (old_lruvec,NR_FILE_DIRTY , -nr_dirty); +__mod_zone_page_state (oldzone,NR_ZONE_WRITE_PENDING , -nr_dirty); +mod_lruvec_state (new_lruvec,NR_FILE_DIRTY , nr_dirty); +__mod_zone_page_state (newzone,NR_ZONE_WRITE_PENDING , nr_dirty); }rcu_read_unlock (); }
mm/page-writeback.c +71 -20
149 lines not on this page · raw message
Signature · 6 lines
2.50.1 AMAZON DEVELOPMENT CENTER ITALY SRL, viale Monte Grappa 3/5, 20124 Milano, Italia, Registro delle Imprese di Milano Monza Brianza Lodi REA n. 2504859, Capitale Sociale: 10.000 EUR i.v., Cod. Fisc. e P.IVA 10100050961, Societa con Socio Unico
kernel test robot
build botRe: [PATCH 1/2] mm: add infrastructure for per-dirty-page accounting
kernel test robot noticed the following build warnings:
Hi Salvatore,
kernel test robot noticed the following build warnings:
[auto build test WARNING on 24a19b953e2a3d0ea5a8c4951a0ab8f32720c907]
url: https://github.com/intel-lab-lkp/linux/commits/Salvatore-Dipietro/mm-add-infrastructure-for-per-dirty-page-accounting/20261027-112701 base: 24a19b953e2a3d0ea5a8c4951a0ab8f32720c907 patch link: https://lore.kernel.org/r/20261027112702.3747009-2-dipiets%40amazon.it patch subject: [PATCH 1/2] mm: add infrastructure for per-dirty-page accounting config: parisc-allnoconfig (https://download.01.org/0day-ci/archive/20261028/[email protected]/config) compiler: hppa-linux-gcc (GCC) 16.2.0 reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20261028/[email protected]/reproduce)
If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/
All warnings (new ones prefixed by >>):
>> Warning: mm/page-writeback.c:2739 function parameter 'accounted' not described in '__filemap_dirty_folio' >> Warning: mm/page-writeback.c:2739 expecting prototype for filemap_dirty_folio(). Prototype was for __filemap_dirty_folio() instead
--
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
[email protected]
AI reviewRe: [PATCH 1/2] mm: add infrastructure for per-dirty-page accounting
In reply to Salvatore DipietroThank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider: - [Critical] mm: out-of-bounds read in folio_accounted_dirty_pages() on swapcache folios - [High] mm…
Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider:
- [Critical] mm: out-of-bounds read in folio_accounted_dirty_pages() on swapcache folios
- [High] mm: per-folio nr_dirtied in folio_account_dirtied() breaks dirty throttling
- [Medium] mm: writeback wb switch accounting drift for AS_DIRTY_PER_BLOCK mappings
- [Medium] mm: per-folio WB_DONTCACHE_DIRTY discharge in __filemap_get_folio_mpol()
- [Medium] mm: dirty counter leak and double charge after folio_clear_dirty_for_io() --
commit 1721442268f1f31932ef0e4f11e5d239eea01bb6
Author: Salvatore Dipietro <[email protected]>
mm: add infrastructure for per-dirty-page accounting
This commit adds memory management infrastructure to allow filesystems to account dirty pages at sub-folio granularity via the AS_DIRTY_PER_BLOCK flag and the accounted_dirty_pages address_space_operations callback. It updates folio dirtying, cleaning, writeback preparation, and migration paths to support per-page dirty accounting.
Quoted 32 lines
mm/page-writeback.c +8
-9@@ -2601,7 +2601,7 @@ EXPORT_SYMBOL(noop_dirty_folio);* NOTE: This relies on being atomic wrt interrupts. */ static void folio_account_dirtied (struct folio *folio, -struct address_space *mapping) +struct address_space *mapping,bool accounted) {struct inode *inode = mapping->host;@@ -2614,14 +2614,21 @@ static void folio_account_dirtied(struct folio *folio,inode_attach_wb (inode, folio); wb =inode_to_wb (inode); -lruvec_stat_mod_folio (folio,NR_FILE_DIRTY , nr); -if (folio_test_dropbehind (folio)) -wb_stat_mod (wb,WB_DONTCACHE_DIRTY , nr); -__zone_stat_mod_folio (folio,NR_ZONE_WRITE_PENDING , nr); -__node_stat_mod_folio (folio,NR_DIRTIED , nr); -wb_stat_mod (wb,WB_RECLAIMABLE , nr); -wb_stat_mod (wb,WB_DIRTIED , nr); -task_io_account_write (nr *PAGE_SIZE ); +/* +* @accounted means the filesystem charged these per dirty page +* already; the rate limiters below stay per-folio. Keep in sync +* with folio_account_cleaned() and folio_clear_dirty_for_io(). +*/ +if (!accounted) { +lruvec_stat_mod_folio (folio,NR_FILE_DIRTY , nr);
mm/page-writeback.c static void folio_account_dirtied(struct folio *folio, · line 2633
Quoted 10 lines
mm/page-writeback.c +8
-0+if (folio_test_dropbehind (folio)) +wb_stat_mod (wb,WB_DONTCACHE_DIRTY , nr); +__zone_stat_mod_folio (folio,NR_ZONE_WRITE_PENDING , nr); +wb_stat_mod (wb,WB_RECLAIMABLE , nr); +__node_stat_mod_folio (folio,NR_DIRTIED , nr); +wb_stat_mod (wb,WB_DIRTIED , nr); +task_io_account_write (nr *PAGE_SIZE ); + } current->nr_dirtied += nr;__this_cpu_add (bdp_ratelimits, nr);
[Severity: High]
When accounted is true, keeping current->nr_dirtied and bdp_ratelimits per-folio in folio_account_dirtied() appears to break dirty throttling in two ways.
First, __filemap_dirty_folio() only calls __folio_mark_dirty() -> folio_account_dirtied() when PG_dirty transitions from 0 to 1:
mm/page-writeback.c:__filemap_dirty_folio() {
if (folio_test_set_dirty(folio))
return false;
__folio_mark_dirty(folio, mapping, !folio_test_private(folio), accounted);
...
}If a writer dirties a single block of several large folios while below the freerun ceiling, only 1 page per folio is charged to NR_FILE_DIRTY and WB_RECLAIMABLE, and balance_dirty_pages() takes the freerun path and resets current->nr_dirtied to 0. When subsequent buffered writes dirty the remaining clean blocks of those already-dirty large folios, the filesystem charges the newly dirtied pages to NR_FILE_DIRTY, NR_ZONE_WRITE_PENDING, and WB_RECLAIMABLE, but __filemap_dirty_folio() returns early because PG_dirty is already set. Since current->nr_dirtied and bdp_ratelimits are never incremented for those subsequent writes, won't balance_dirty_pages_ratelimited_flags() fail to call balance_dirty_pages() to wake background writeback or throttle the task as NR_FILE_DIRTY and WB_RECLAIMABLE grow past bg_thresh and dirty_thresh?
Second, when dirty throttling is active and a writer dirties 1 page of each new large folio, the filesystem increments WB_DIRTIED by 1 page per folio while folio_account_dirtied() increments current->nr_dirtied by folio_nr_pages(folio). In wb_update_dirty_ratelimit(), dirty_rate is computed from WB_DIRTIED and balanced_dirty_ratelimit is clamped to write_bw:
mm/page-writeback.c:wb_update_dirty_ratelimit() {
...
balanced_dirty_ratelimit = div_u64((u64)task_ratelimit * write_bw,
dirty_rate | 1);
if (unlikely(balanced_dirty_ratelimit > write_bw))
balanced_dirty_ratelimit = write_bw;
}Because balance_dirty_pages() computes the pause duration from current->nr_dirtied divided by task_ratelimit, doesn't mixing per-page WB_DIRTIED with per-folio current->nr_dirtied cause severe over-throttling when partially dirtying large folios?
Quoted 15 lines
mm/page-writeback.c +10
-0@@ -2629,13 +2636,41 @@ static void folio_account_dirtied(struct folio *folio, } } +/** +* folio_accounted_dirty_pages - pages of @folio charged to the dirty counters +* @folio: folio to query +* +* Use this rather than folio_nr_pages() when moving or discharging a folio's dirty +* accounting, as a folio is not necessarily charged for all of its pages. Walks +* per-block state that truncation frees, so the caller must hold the folio lock. +* +* Return: the whole folio for the usual per-folio accounting, otherwise only the +* pages holding a dirty block, and zero once those have been discharged.
mm/page-writeback.c static void folio_account_dirtied(struct folio *folio, · line 2658
Quoted 10 lines
mm/page-writeback.c +10
-0+*/ +long folio_accounted_dirty_pages (struct folio *folio) +{ +struct address_space *mapping = folio->mapping; + +if (mapping &&mapping_dirty_per_block (mapping) && folio->private && + mapping->a_ops->accounted_dirty_pages) +return mapping->a_ops->accounted_dirty_pages (folio); +return folio_nr_pages (folio); +}
[Severity: Critical]
Can this cause an out-of-bounds read and invalid function pointer dereference when migrating dirty anonymous or KSM folios that are in the swap cache?
During migration, move_to_new_folio() obtains mapping via folio_mapping(src), which returns swap_address_space(folio->swap) for swap cache folios:
mm/util.c:folio_mapping() {
...
if (unlikely(folio_test_swapcache(folio)))
return swap_address_space(folio->swap);
mapping = folio->mapping;
if ((unsigned long)mapping & FOLIO_MAPPING_FLAGS)
return NULL;
...
}Because mapping is non-NULL, swap_aops.migrate_folio (migrate_folio()) calls __migrate_folio() -> __folio_migrate_mapping(), which invokes folio_accounted_dirty_pages(folio) when folio_test_dirty(folio) is true:
mm/migrate.c:__folio_migrate_mapping() {
...
if (folio_test_dirty(folio))
nr_dirty = folio_accounted_dirty_pages(folio);
}However, folio_accounted_dirty_pages() reads raw folio->mapping instead of folio_mapping(folio). For an anonymous or KSM folio in the swap cache, folio->mapping is a tagged pointer to struct anon_vma (FOLIO_MAPPING_ANON) or struct ksm_stable_node (FOLIO_MAPPING_KSM), and folio->private (union with folio->swap) is non-zero.
Calling mapping_dirty_per_block(mapping) then performs test_bit() on &mapping->flags at an unaligned offset past the end of struct anon_vma or struct ksm_stable_node, and if the bit happens to be set in adjacent slab memory, dereferences mapping->a_ops->accounted_dirty_pages(folio) out of bounds. Should folio_accounted_dirty_pages() use folio_mapping(folio) instead of folio->mapping?
[ ... ]
Quoted 12 lines
mm/page-writeback.c +2
-6@@ -2912,12 +2954,21 @@ bool folio_clear_dirty_for_io(struct folio *folio)*/ wb =unlocked_inode_to_wb_begin (inode, &cookie);if (folio_test_clear_dirty (folio)) { -long nr =folio_nr_pages (folio); -lruvec_stat_mod_folio (folio,NR_FILE_DIRTY , -nr); -if (folio_test_dropbehind (folio)) -wb_stat_mod (wb,WB_DONTCACHE_DIRTY , -nr); -zone_stat_mod_folio (folio,NR_ZONE_WRITE_PENDING , -nr); -wb_stat_mod (wb,WB_RECLAIMABLE , -nr); +/* +* Per-block folios keep their dirty bits, and the charge,
mm/page-writeback.c bool folio_clear_dirty_for_io(struct folio *folio) · line 2968
Quoted 10 lines
mm/page-writeback.c +10
-0+* until the fs writes them back. Folios of such a mapping +* that never got per-block state were charged whole, so +* they discharge here as usual. +*/ +if (!mapping_dirty_per_block (mapping) || !folio->private) { +long nr =folio_nr_pages (folio); + +lruvec_stat_mod_folio (folio,NR_FILE_DIRTY , -nr); +if (folio_test_dropbehind (folio)) +wb_stat_mod (wb,WB_DONTCACHE_DIRTY , -nr);
[Severity: Medium]
Does WB_DONTCACHE_DIRTY accounting stay balanced when PG_dropbehind is cleared on a lookup in __filemap_get_folio_mpol()?
In mm/filemap.c, __filemap_get_folio_mpol() clears PG_dropbehind on normal cached lookups and decrements WB_DONTCACHE_DIRTY by folio_nr_pages(folio):
mm/filemap.c:__filemap_get_folio_mpol() {
...
if (!(fgp_flags & FGP_DONTCACHE) && folio_test_clear_dropbehind(folio)) {
if (folio_test_dirty(folio) &&
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);
unlocked_inode_to_wb_end(inode, &cookie);
}
}
}If a large folio on an AS_DIRTY_PER_BLOCK mapping has PG_dropbehind set and only a subset of its pages are dirtied, subtracting folio_nr_pages(folio) instead of the accounted dirty pages will underflow WB_DONTCACHE_DIRTY.
Additionally, if an unlocked lookup such as filemap_fault() -> filemap_get_folio() calls __filemap_get_folio_mpol() after folio_clear_dirty_for_io() has cleared PG_dirty, but before the filesystem has discharged the per-block dirty pages during writeback, __filemap_get_folio_mpol() clears PG_dropbehind without decrementing WB_DONTCACHE_DIRTY because folio_test_dirty(folio) is already false, and the filesystem will later skip decrementing WB_DONTCACHE_DIRTY because folio_test_dropbehind(folio) is now false. Doesn't this leak the WB_DONTCACHE_DIRTY charge?
mm/page-writeback.c bool folio_clear_dirty_for_io(struct folio *folio) · line 2970
Quoted 2 lines
mm/page-writeback.c +2
-0+zone_stat_mod_folio (folio,NR_ZONE_WRITE_PENDING , -nr); +wb_stat_mod (wb,WB_RECLAIMABLE , -nr);
[Severity: Medium]
How does cgroup writeback switching in inode_do_switch_wbs() interact with AS_DIRTY_PER_BLOCK mappings?
In fs/fs-writeback.c, inode_do_switch_wbs() transfers WB_RECLAIMABLE and WB_DONTCACHE_DIRTY between old_wb and new_wb using folio_nr_pages(folio):
fs/fs-writeback.c:inode_do_switch_wbs() {
...
xas_for_each_marked(&xas, folio, ULONG_MAX, PAGECACHE_TAG_DIRTY) {
if (folio_test_dirty(folio)) {
long nr = folio_nr_pages(folio);
wb_stat_mod(old_wb, WB_RECLAIMABLE, -nr);
wb_stat_mod(new_wb, WB_RECLAIMABLE, nr);
if (folio_test_dropbehind(folio)) {
wb_stat_mod(old_wb, WB_DONTCACHE_DIRTY, -nr);
wb_stat_mod(new_wb, WB_DONTCACHE_DIRTY, nr);
}
}
}
}If a large folio only has a sub-folio range charged to old_wb, won't transferring folio_nr_pages(folio) underflow old_wb and over-charge new_wb?
Furthermore, unlocked_inode_to_wb_begin() and unlocked_inode_to_wb_end() serialize against inode_do_switch_wbs() under the assumption that PG_dirty indicates whether the folio's charge is still held on inode->i_wb. When folio_clear_dirty_for_io() clears PG_dirty without discharging WB_RECLAIMABLE and WB_DONTCACHE_DIRTY, if inode_do_switch_wbs() runs before the filesystem discharges the per-block dirty state during writeback, inode_do_switch_wbs() will see !folio_test_dirty(folio) and skip the folio, causing the filesystem to later discharge the pages from new_wb while leaving them stranded on old_wb.
mm/page-writeback.c bool folio_clear_dirty_for_io(struct folio *folio) · line 2971
Quoted 1 line
mm/page-writeback.c +1
-0+ }
[Severity: Medium]
When folio_clear_dirty_for_io() clears PG_dirty while leaving NR_FILE_DIRTY, WB_DONTCACHE_DIRTY, NR_ZONE_WRITE_PENDING, and WB_RECLAIMABLE charged for per-block folios, can those charges be leaked, double-charged, or left on the wrong zone if writeback does not immediately clear the per-block dirty bits?
Several paths in mm and filesystems rely on folio_test_dirty(folio) to know whether dirty accounting is active:
1. If ->writepages bails out after folio_clear_dirty_for_io() without writing or clearing the per-block dirty state (for example, in the following iomap patch when iomap_writeback_folio() returns early via iomap_writeback_handle_eof() because the folio is beyond i_size after a racing truncate, or in ntfs3 where ntfs_writepages() and ntfs_mft_writepages() use iomap_dirty_folio() without iomap_clear_range_dirty()), the folio is unlocked with PG_dirty cleared while per-block dirty pages remain charged.
2. Once PG_dirty and PG_writeback are both false, reclaim, eviction, or folio splitting can invoke ->release_folio() (such as iomap_release_folio(), which only checks folio_test_dirty(folio)) and free folio->private, or truncation can call folio_cancel_dirty(), which only calls folio_account_cleaned() when folio_test_dirty(folio) is true, permanently leaking NR_FILE_DIRTY, NR_ZONE_WRITE_PENDING, WB_RECLAIMABLE, and WB_DONTCACHE_DIRTY.
3. In __folio_migrate_mapping(), both folio_accounted_dirty_pages(folio) and the cross-zone NR_FILE_DIRTY / NR_ZONE_WRITE_PENDING transfer are gated on folio_test_dirty(folio), so migrating a folio in this state leaves the dirty counters on oldzone and old_lruvec while the subsequent discharge subtracts them from newzone and new_lruvec.
4. If folio_redirty_for_writepage() is called after folio_clear_dirty_for_io(), it calls filemap_dirty_folio() with accounted = false, charging the entire folio_nr_pages(folio) on top of the still-charged per-block dirty pages.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
PATCH 2/2 mm, iomap: account dirty at page granularity for per-block dirty folios
In reply to Salvatore DipietroThe mm dirty counters (NR_FILE_DIRTY, NR_ZONE_WRITE_PENDING, WB_RECLAIMABLE) are charged per folio, which charges up to 512 pages for a single dirty 4 kB block of a 2 MB folio. iomap knows exactly which blocks are dirty and writeback only writes those ranges, so balance_dirty_pages() ends up throttling writers against a dirty count far larger than the data that actually needs writeback.
Charge the counters per dirty page for folios carrying per-block dirty state, using the infrastructure from the previous patch:
struct iomap_folio_state counts the pages holding a dirty block, and each dirty bitmap change charges or discharges the difference. The charge survives folio_clear_dirty_for_io() and is dropped when writeback or invalidation clears the blocks. The monotonic NR_DIRTIED / WB_DIRTIED / task_io totals are charged only for newly dirtied data, and the dirty rate limiters stay per-folio.
Every iomap-based filesystem sets .accounted_dirty_pages alongside .dirty_folio = iomap_dirty_folio.
On pgbench simple-update (1024 clients, XFS, 96-vCPU arm64, 10 iterations) on v7.3-rc7, the unpatched kernel charges 159 TB of dirtied pages while writing 6 TB to the array, a factor of 27; with this patch the dirtied pages charged match the data written. Unpatched, nr_dirty is above dirty_threshold in ~17% of 5s samples and its peak exceeds it in 9 of 10 iterations; patched, it never reaches the threshold.
On v7.3-rc7, average throughput rises 46.8% (139.8k -> 205.2k tps) and run-to-run variability drops from 23.60% to 3.98% coefficient of variation. The best iteration improves by 8% (199.4k -> 215.9k tps); most of the gain comes from the worst iteration, up from 97.9k to 191.5k tps, i.e. from throttling episodes that no longer happen.
--- fs/exfat/inode.c | 1 + fs/fuse/file.c | 1 + fs/gfs2/aops.c | 1 + fs/iomap/buffered-io.c | 167 +++++++++++++++++++++++++++++++++++++++-- fs/ntfs/aops.c | 2 + fs/ntfs3/inode.c | 2 + fs/xfs/xfs_aops.c | 1 + fs/zonefs/file.c | 1 + include/linux/iomap.h | 1 + 9 files changed, 171 insertions(+), 6 deletions(-)
fs/exfat/inode.c +1 -0
@@ -302,6 +302,7 @@ static const struct address_space_operations exfat_aops = { .readahead = exfat_readahead, .writepages = exfat_writepages, .dirty_folio = iomap_dirty_folio, + .accounted_dirty_pages = iomap_accounted_dirty_pages, .bmap = exfat_aop_bmap, .migrate_folio = filemap_migrate_folio, .is_partially_uptodate = iomap_is_partially_uptodate,
fs/fuse/file.c +1 -0
@@ -3101,6 +3101,7 @@ static const struct address_space_operations fuse_file_aops = { .writepages = fuse_writepages, .launder_folio = fuse_launder_folio, .dirty_folio = iomap_dirty_folio, + .accounted_dirty_pages = iomap_accounted_dirty_pages, .release_folio = iomap_release_folio, .invalidate_folio = iomap_invalidate_folio, .is_partially_uptodate = iomap_is_partially_uptodate,
fs/gfs2/aops.c +1 -0
@@ -713,6 +713,7 @@ static const struct address_space_operations gfs2_aops = { .read_folio = gfs2_read_folio, .readahead = gfs2_readahead, .dirty_folio = iomap_dirty_folio, + .accounted_dirty_pages = iomap_accounted_dirty_pages, .release_folio = iomap_release_folio, .invalidate_folio = iomap_invalidate_folio, .bmap = gfs2_bmap,
fs/iomap/buffered-io.c +161 -6
261 lines not on this page · raw message
fs/ntfs/aops.c +2 -0
@@ -308,6 +308,7 @@ const struct address_space_operations ntfs_aops = { .readahead = ntfs_readahead, .writepages = ntfs_writepages, .dirty_folio = iomap_dirty_folio, + .accounted_dirty_pages = iomap_accounted_dirty_pages, .bmap = ntfs_bmap, .migrate_folio = filemap_migrate_folio, .is_partially_uptodate = iomap_is_partially_uptodate,
@@ -322,6 +323,7 @@ const struct address_space_operations ntfs_mft_aops = { .readahead = ntfs_readahead, .writepages = ntfs_mft_writepages, .dirty_folio = iomap_dirty_folio, + .accounted_dirty_pages = iomap_accounted_dirty_pages, .bmap = ntfs_bmap, .migrate_folio = filemap_migrate_folio, .is_partially_uptodate = iomap_is_partially_uptodate,
fs/ntfs3/inode.c +2 -0
@@ -2301,6 +2301,7 @@ const struct address_space_operations ntfs_aops = { .writepages = ntfs_writepages, .bmap = ntfs_bmap, .dirty_folio = iomap_dirty_folio, + .accounted_dirty_pages = iomap_accounted_dirty_pages, .migrate_folio = filemap_migrate_folio, .release_folio = iomap_release_folio, .invalidate_folio = iomap_invalidate_folio,
@@ -2309,6 +2310,7 @@ const struct address_space_operations ntfs_aops = {const struct address_space_operations ntfs_aops_cmpr = { .read_folio = ntfs_read_folio, .dirty_folio = iomap_dirty_folio, + .accounted_dirty_pages = iomap_accounted_dirty_pages, .release_folio = iomap_release_folio, .invalidate_folio = iomap_invalidate_folio, };
fs/xfs/xfs_aops.c +1 -0
@@ -682,6 +682,7 @@ const struct address_space_operations xfs_address_space_operations = { .readahead = xfs_vm_readahead, .writepages = xfs_vm_writepages, .dirty_folio = iomap_dirty_folio, + .accounted_dirty_pages = iomap_accounted_dirty_pages, .release_folio = iomap_release_folio, .invalidate_folio = iomap_invalidate_folio, .bmap = xfs_vm_bmap,
fs/zonefs/file.c +1 -0
@@ -192,6 +192,7 @@ const struct address_space_operations zonefs_file_aops = { .readahead = zonefs_readahead, .writepages = zonefs_writepages, .dirty_folio = iomap_dirty_folio, + .accounted_dirty_pages = iomap_accounted_dirty_pages, .release_folio = iomap_release_folio, .invalidate_folio = iomap_invalidate_folio, .migrate_folio = filemap_migrate_folio,
include/linux/iomap.h +1 -0
@@ -444,6 +444,7 @@ bool iomap_release_folio(struct folio *folio, gfp_t gfp_flags);void iomap_invalidate_folio (struct folio *folio,size_t offset,size_t len);bool iomap_dirty_folio (struct address_space *mapping,struct folio *folio);void iomap_folio_mark_uptodate (struct folio *folio); +long iomap_accounted_dirty_pages (struct folio *folio);int iomap_file_unshare (struct inode *inode,loff_t pos,loff_t len,const struct iomap_ops *ops,const struct iomap_write_ops *write_ops);
Signature · 6 lines
2.50.1 AMAZON DEVELOPMENT CENTER ITALY SRL, viale Monte Grappa 3/5, 20124 Milano, Italia, Registro delle Imprese di Milano Monza Brianza Lodi REA n. 2504859, Capitale Sociale: 10.000 EUR i.v., Cod. Fisc. e P.IVA 10100050961, Societa con Socio Unico
[email protected]
AI reviewThank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider: - [High] iomap: dirty counter leak on early EOF return in iomap_writeback_folio() - [High] ntfs, ntfs3…
Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider:
- [High] iomap: dirty counter leak on early EOF return in iomap_writeback_folio()
- [High] ntfs, ntfs3: dirty counter leak in ntfs_mft_writepages() and ntfs_writepages()
- [High] block: missing iomap per-block dirty callbacks in def_blk_aops
- [Medium] mm: wrong wb stats in inode_do_switch_wbs() and __filemap_get_folio_mpol()
- [Medium] gfs2: stale AS_DIRTY_PER_BLOCK flag after switching to gfs2_jdata_aops --
commit ec03cb36d468351e028d982f93868e296ff14cfc
Author: Salvatore Dipietro <[email protected]>
mm, iomap: account dirty at page granularity for per-block dirty folios
This commit updates iomap to account mm and writeback dirty page counters at page granularity rather than full folio granularity when folios carry per-block dirty state in struct iomap_folio_state, and wires up .accounted_dirty_pages = iomap_accounted_dirty_pages across iomap-based filesystems.
fs/gfs2/aops.c static const struct address_space_operations gfs2_aops = { · line 716
Quoted 9 lines
fs/gfs2/aops.c +1
-0@@ -713,6 +713,7 @@ static const struct address_space_operations gfs2_aops = { .read_folio = gfs2_read_folio, .readahead = gfs2_readahead, .dirty_folio = iomap_dirty_folio, + .accounted_dirty_pages = iomap_accounted_dirty_pages,
[Severity: Medium]
What happens if a GFS2 file using gfs2_aops with blocksize < folio_size() allocates struct iomap_folio_state via ifs_alloc() (which sets AS_DIRTY_PER_BLOCK on inode->i_mapping), and later has GFS2_DIF_JDATA enabled via gfs2_fileattr_set() -> do_gfs2_set_flags() -> gfs2_set_aops()?
fs/gfs2/aops.c:gfs2_set_aops() {
if (gfs2_is_jdata(GFS2_I(inode)))
inode->i_mapping->a_ops = &gfs2_jdata_aops;
else
inode->i_mapping->a_ops = &gfs2_aops;
}Switching inode->i_mapping->a_ops to gfs2_jdata_aops leaves AS_DIRTY_PER_BLOCK set on inode->i_mapping. Subsequent writes in jdata mode attach struct buffer_head rings to folio->private and charge folio_nr_pages(folio) via gfs2_jdata_dirty_folio() -> block_dirty_folio().
When gfs2_jdata_writepages() later runs folio_clear_dirty_for_io():
mm/page-writeback.c:folio_clear_dirty_for_io() {
...
if (folio_test_clear_dirty(folio)) {
if (!mapping_dirty_per_block(mapping) || !folio->private) {
long nr = folio_nr_pages(folio);
...
}Because mapping_dirty_per_block(mapping) is still true and folio->private is non-NULL (pointing to buffer_heads), won't folio_clear_dirty_for_io() skip discharging NR_FILE_DIRTY, WB_DONTCACHE_DIRTY, NR_ZONE_WRITE_PENDING, and WB_RECLAIMABLE on every writeback?
Quoted 4 lines
fs/iomap/buffered-io.c +0
-0
[ ... ]
Quoted 1 line
fs/iomap/buffered-io.c +0
-0@@ -180,6 +189,89 @@ static unsigned iomap_find_dirty_range(struct folio *folio, u64 *range_start,
[ ... ]
Quoted 16 lines
fs/iomap/buffered-io.c +16
-0+static void iomap_account_dirty_pages (struct folio *folio,long nr_pages, +bool new_dirty) +{ +struct address_space *mapping = folio->mapping; +struct inode *inode = mapping->host; +struct wb_lock_cookie cookie = {}; +struct bdi_writeback *wb; +bool dirtied = nr_pages >0 && new_dirty; + +if (!nr_pages || !mapping_can_writeback (mapping)) +return ; + +lruvec_stat_mod_folio (folio,NR_FILE_DIRTY , nr_pages); +zone_stat_mod_folio (folio,NR_ZONE_WRITE_PENDING , nr_pages); +if (dirtied) +node_stat_mod_folio (folio,NR_DIRTIED , nr_pages);
fs/iomap/buffered-io.c static unsigned iomap_find_dirty_range(struct folio *folio, u64 *range_start, · line 265
Quoted 10 lines
fs/iomap/buffered-io.c +10
-0+ +/* Pin the wb against a concurrent inode_do_switch_wbs(). */ +inode_attach_wb (inode, folio); + wb =unlocked_inode_to_wb_begin (inode, &cookie); +wb_stat_mod (wb,WB_RECLAIMABLE , nr_pages); +if (folio_test_dropbehind (folio)) +wb_stat_mod (wb,WB_DONTCACHE_DIRTY , nr_pages); +if (dirtied) +wb_stat_mod (wb,WB_DIRTIED , nr_pages); +unlocked_inode_to_wb_end (inode, &cookie);
[Severity: Medium]
Can charging WB_RECLAIMABLE and WB_DONTCACHE_DIRTY by nr_pages here corrupt per-wb counters when inode_do_switch_wbs() or __filemap_get_folio_mpol() runs on a partially dirty large folio?
In fs/fs-writeback.c, inode_do_switch_wbs() still transfers folio_nr_pages(folio) instead of folio_accounted_dirty_pages(folio):
fs/fs-writeback.c:inode_do_switch_wbs() {
...
xas_for_each_marked(&xas, folio, ULONG_MAX, PAGECACHE_TAG_DIRTY) {
if (folio_test_dirty(folio)) {
long nr = folio_nr_pages(folio);
wb_stat_mod(old_wb, WB_RECLAIMABLE, -nr);
wb_stat_mod(new_wb, WB_RECLAIMABLE, nr);
if (folio_test_dropbehind(folio)) {
wb_stat_mod(old_wb, WB_DONTCACHE_DIRTY, -nr);
wb_stat_mod(new_wb, WB_DONTCACHE_DIRTY, nr);
}
}
}
...
}When new_wb later writes back or invalidates the folio, iomap_clear_range_dirty() only subtracts ifs->dirty_pages from new_wb, leaving old_wb underflowed and new_wb inflated by folio_nr_pages(folio) - ifs->dirty_pages.
Also, because iomap_account_dirty_pages() updates WB_RECLAIMABLE and WB_DONTCACHE_DIRTY outside mapping->i_pages.xa_lock before __filemap_dirty_folio() sets PG_dirty, and because folio_clear_dirty_for_io() clears PG_dirty while keeping WB_RECLAIMABLE and WB_DONTCACHE_DIRTY charged until iomap_clear_range_dirty(), can a concurrent inode_do_switch_wbs() miss or misaccount a folio whose PG_dirty state does not match its active wb charge?
Similarly, in mm/filemap.c, __filemap_get_folio_mpol() decrements WB_DONTCACHE_DIRTY by folio_nr_pages(folio) when clearing PG_dropbehind:
mm/filemap.c:__filemap_get_folio_mpol() {
...
if (!(fgp_flags & FGP_DONTCACHE) && folio_test_clear_dropbehind(folio)) {
if (folio_test_dirty(folio) &&
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);
unlocked_inode_to_wb_end(inode, &cookie);
}
}
...
}Won't that underflow WB_DONTCACHE_DIRTY when a partially dirty folio was only charged ifs->dirty_pages, or leak WB_DONTCACHE_DIRTY if PG_dropbehind is cleared after folio_clear_dirty_for_io() cleared PG_dirty but before iomap_clear_range_dirty() runs?
[ ... ]
fs/iomap/buffered-io.c static struct iomap_folio_state *ifs_alloc(struct inode *inode, · line 405
Quoted 12 lines
fs/iomap/buffered-io.c +5
-1@@ -276,9 +396,13 @@ static struct iomap_folio_state *ifs_alloc(struct inode *inode,spin_lock_init (&ifs->state_lock);if (folio_test_uptodate (folio))bitmap_set (ifs->state,0 , nr_blocks); -if (folio_test_dirty (folio)) +if (folio_test_dirty (folio)) {bitmap_set (ifs->state, nr_blocks, nr_blocks); + ifs->dirty_pages =folio_nr_pages (folio); + }folio_attach_private (folio, ifs); +/* The mm dirty counters are now charged per dirty page for this file. */ +mapping_set_dirty_per_block (inode->i_mapping);
[Severity: High]
What happens on block devices when !CONFIG_BUFFER_HEAD is enabled?
In block/fops.c, def_blk_aops uses iomap for buffered I/O, writepages, release_folio, and invalidate_folio when !CONFIG_BUFFER_HEAD:
block/fops.c:
const struct address_space_operations def_blk_aops = {
.dirty_folio = filemap_dirty_folio,
.release_folio = iomap_release_folio,
.invalidate_folio = iomap_invalidate_folio,
.read_folio = blkdev_read_folio,
.readahead = blkdev_readahead,
.writepages = blkdev_writepages,
.is_partially_uptodate = iomap_is_partially_uptodate,
.error_remove_folio = generic_error_remove_folio,
.migrate_folio = filemap_migrate_folio,
};
When ifs_alloc() attaches ifs to a block device folio with i_blocks_per_folio(inode, folio) > 1, it sets AS_DIRTY_PER_BLOCK on the block device mapping, but def_blk_aops does not set .accounted_dirty_pages = iomap_accounted_dirty_pages or .dirty_folio = iomap_dirty_folio.
When iomap_invalidate_folio(folio, 0, folio_size(folio)) later runs on a dirty block device folio, it first calls iomap_clear_range_dirty() (which discharges ifs->dirty_pages and sets ifs->dirty_pages = 0) and then calls folio_cancel_dirty() -> folio_account_cleaned() -> folio_accounted_dirty_pages(). Because mapping->a_ops->accounted_dirty_pages is NULL, folio_accounted_dirty_pages() returns folio_nr_pages(folio) instead of 0, discharging the counters a second time.
Also, if a block device folio that already has ifs attached from a read is dirtied via mmap (filemap_dirty_folio()), the dirty bits in ifs->state are not set, so writeback via folio_clear_dirty_for_io() and iomap_writeback_folio() neither writes the blocks nor discharges the dirty counters. Should def_blk_aops also use iomap_dirty_folio and iomap_accounted_dirty_pages when !CONFIG_BUFFER_HEAD?
[ ... ]
Quoted 5 lines
fs/iomap/buffered-io.c +1
-0@@ -2001,8 +2151,13 @@ int iomap_writeback_folio(struct iomap_writepage_ctx *wpc, struct folio *folio)if (i_blocks_per_folio (inode, folio) >1 ) {if (!ifs) { +/*
fs/iomap/buffered-io.c int iomap_writeback_folio(struct iomap_writepage_ctx *wpc, struct folio *folio) · line 2163
Quoted 10 lines
fs/iomap/buffered-io.c +5
-1+* Dirtied before it had per-block state, so charged +* per-folio. Re-mark the blocks for the walk below, +* paired with the clear at the end of this function. +*/ ifs =ifs_alloc (inode, folio,0 ); -iomap_set_range_dirty (folio,0 , end_pos - pos); +iomap_redirty_range (folio,0 , end_pos - pos); }iomap_writeback_init (inode, folio);
[Severity: High]
Can iomap_writeback_folio() leak the dirty page counters when a folio with per-block state is at or beyond EOF?
Before calling iomap_writeback_folio() (via writeback_iter() -> folio_prepare_writeback() or fuse_launder_folio()), the caller invokes folio_clear_dirty_for_io(folio), which clears PG_dirty without discharging NR_FILE_DIRTY, WB_DONTCACHE_DIRTY, NR_ZONE_WRITE_PENDING, or WB_RECLAIMABLE when mapping_dirty_per_block(mapping) && folio->private is true.
However, at the start of iomap_writeback_folio():
fs/iomap/buffered-io.c:iomap_writeback_folio() {
...
if (!iomap_writeback_handle_eof(folio, wpc, &end_pos))
return 0;
...
}If iomap_writeback_handle_eof() returns false (for instance, when writeback races with truncate_setsize() after i_size_write() lowers i_size but before truncate_pagecache() locks the folio, or in folio_unmap_invalidate() -> fuse_launder_folio()), iomap_writeback_folio() returns 0 without calling iomap_clear_range_dirty(folio, 0, folio_size(folio)).
That leaves the folio clean (PG_dirty == false, PG_writeback == false) while ifs->dirty_pages remains charged. If filemap_release_folio() -> iomap_release_folio() then runs (immediately in folio_unmap_invalidate(), or via reclaim, splitting, or eviction before truncate_cleanup_folio() locks the folio):
fs/iomap/buffered-io.c:iomap_release_folio() {
...
if (folio_test_dirty(folio))
return false;
ifs_free(folio);
return true;
}Won't iomap_release_folio() see folio_test_dirty(folio) == false and free ifs without ever discharging ifs->dirty_pages?
Quoted 25 lines
fs/ntfs/aops.c +2
-0@@ -308,6 +308,7 @@ const struct address_space_operations ntfs_aops = { .readahead = ntfs_readahead, .writepages = ntfs_writepages, .dirty_folio = iomap_dirty_folio, + .accounted_dirty_pages = iomap_accounted_dirty_pages, .bmap = ntfs_bmap, .migrate_folio = filemap_migrate_folio, .is_partially_uptodate = iomap_is_partially_uptodate,@@ -322,6 +323,7 @@ const struct address_space_operations ntfs_mft_aops = { .readahead = ntfs_readahead, .writepages = ntfs_mft_writepages, .dirty_folio = iomap_dirty_folio, + .accounted_dirty_pages = iomap_accounted_dirty_pages, .bmap = ntfs_bmap, .migrate_folio = filemap_migrate_folio, .is_partially_uptodate = iomap_is_partially_uptodate,fs/ntfs3/inode.c +0
-0
fs/ntfs3/inode.c const struct address_space_operations ntfs_aops = { · line 2304
Quoted 4 lines
fs/ntfs3/inode.c +1
-0@@ -2301,6 +2301,7 @@ const struct address_space_operations ntfs_aops = { .writepages = ntfs_writepages, .bmap = ntfs_bmap, .dirty_folio = iomap_dirty_folio, + .accounted_dirty_pages = iomap_accounted_dirty_pages,
[Severity: High]
Does enabling per-block dirty accounting on ntfs_mft_aops (in fs/ntfs) and resident files using ntfs_aops (in fs/ntfs3) leak dirty page counters during writeback?
In fs/ntfs, ntfs_mft_aops uses ntfs_mft_writepages(), which iterates with writeback_iter() and calls ntfs_write_mft_block(folio, wbc) rather than iomap_writeback_folio():
fs/ntfs/mft.c:ntfs_mft_writepages() {
...
while ((folio = writeback_iter(mapping, wbc, folio, &error)))
error = ntfs_write_mft_block(folio, wbc);
...
}Similarly, in fs/ntfs3, ntfs_writepages() handles resident files via writeback_iter() and attr_data_write_resident(ni, folio) without calling iomap_writepages():
fs/ntfs3/inode.c:ntfs_writepages() {
...
if (is_resident(ni)) {
struct folio *folio = NULL;
err = 0;
while ((folio = writeback_iter(mapping, wbc, folio, &err))) {
int err2;
ni_lock(ni);
err2 = attr_data_write_resident(ni, folio);
ni_unlock(ni);
...
}When these folios are dirtied via iomap_dirty_folio() (such as ntfs_mft_mark_dirty() on $MFT or mmap writes on a resident file), ifs_alloc() attaches ifs and sets AS_DIRTY_PER_BLOCK, and iomap_set_range_dirty() charges ifs->dirty_pages. During writeback, writeback_iter() calls folio_clear_dirty_for_io(), which skips discharging the dirty counters because mapping_dirty_per_block(mapping) && folio->private is true, and neither ntfs_write_mft_block() nor attr_data_write_resident() clears ifs dirty state or discharges ifs->dirty_pages.
Won't this permanently leak NR_FILE_DIRTY, NR_ZONE_WRITE_PENDING, WB_RECLAIMABLE, and WB_DONTCACHE_DIRTY on writeback, and prevent subsequent calls to iomap_dirty_folio() on the same folio from charging the counters because all dirty bits in ifs->state remain set?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
David Hildenbrand (Arm)
maintainerQuoted 58 lines · Salvatore Dipietro
Since iomap gained per-block dirty tracking, a large folio can be partially dirty: struct
iomap_folio_staterecords exactly which blocks are dirty, and writeback only writes those ranges. The mm dirty accounting, however, still charges the whole folio even if a single block is dirty (up to 512x over-accounting for a 2 MB folio over 4 KB blocks).
balance_dirty_pages()then throttles writers against a number that is unrelated to how much data actually needs writing back. On workloads that repeatedly dirty small ranges of large folios -- e.g. PostgreSQL, which writes mostly 8/16 KB pages --dirty_threshis crossed and writers are throttled long before the real dirty data justifies it. On the benchmark below, run on v7.3-rc7, the unpatched kernel charges ~159 TB of dirtied pages while writing ~6 TB to the array, a factor of 27; with this series the dirtied pages charged match the data actually written.This series makes iomap charge and discharge the mm dirty counters per dirty page for folios that carry per-block dirty state, so a partially dirty large folio is accounted for the dirty part only:
- Patch 1 adds the mm infrastructure: an
AS_DIRTY_PER_BLOCKmapping flag, an @accounted argument to__folio_mark_dirty()and__filemap_dirty_folio()to skip the generic per-folio charge, and anaddress_space_operations::accounted_dirty_pages()callback used by the discharge and migration paths instead offolio_nr_pages(). No filesystem opts in, so it is a no-op on its own.- Patch 2 makes iomap charge per dirty page from the per-block dirty bitmap and wires
iomap_accounted_dirty_pages()into every iomap-based filesystem.This was benchmarked with PostgreSQL using the pgbench simple-update workload on v7.3-rc7. Average throughput rises 46.8% (139.8k -> 205.2k tps) and run-to-run variability drops from a 23.60% to a 3.98% coefficient of variation: the worst iteration improves from 97.9k to 191.5k tps, while the best gains 8%, 199.4k -> 215.9k.
Ten iterations per kernel, same database and workload (tps):
Kernel Avg Min Max CV iters iters
1-5 6-10 ______________________ ______ ______ ______ ______ ______ ______ v7.3-rc7 139.8k 97.9k 199.4k 23.60% 164.4k 115.2k v7.3-rc7 + this series 205.2k 191.5k 215.9k 3.98% 200.1k 210.2kOn unpatched v7.3-rc7 the worst iteration lands ~51% below the best, and throughput decays as the run progresses: iterations 6-10 average 30% below iterations 1-5. With this series the decay is gone -- the second half is similar to the first -- and the coefficient of variation stays at 3.98%.
The over-accounting has existed since commit
4ce02c679722("iomap: Add per-block dirty state tracking to improve performance"), merged in v6.6, where the ifs bitmap started recording partial dirty state while the mm counters kept charging whole folios.
Quoted 5 lines
The throughput collapse bisects to the v6.17 readahead series, first bad commit
c4602f9fa77f("mm/readahead: store folio order in structfile_ra_state"), which lets readahead stay at the largest folio order once it has ramped up, so a single dirty block charges far more than is written. Patch 2 therefore carries:
How does this relate to
[RFC PATCH 0/5] mm: sub-folio dirty tracking for PTE-mapped mmap writes
https://lore.kernel.org/all/[email protected]/
?
I assume they try to solve different problems, but would more fine-grained folio dirtying also make your solution benefit?
Signature · 3 lines
Cheers, David
Quoted 68 lines · David Hildenbrand (Arm)
Quoted 58 lines · Salvatore Dipietro
Since iomap gained per-block dirty tracking, a large folio can be partially dirty: struct
iomap_folio_staterecords exactly which blocks are dirty, and writeback only writes those ranges. The mm dirty accounting, however, still charges the whole folio even if a single block is dirty (up to 512x over-accounting for a 2 MB folio over 4 KB blocks).
balance_dirty_pages()then throttles writers against a number that is unrelated to how much data actually needs writing back. On workloads that repeatedly dirty small ranges of large folios -- e.g. PostgreSQL, which writes mostly 8/16 KB pages --dirty_threshis crossed and writers are throttled long before the real dirty data justifies it. On the benchmark below, run on v7.3-rc7, the unpatched kernel charges ~159 TB of dirtied pages while writing ~6 TB to the array, a factor of 27; with this series the dirtied pages charged match the data actually written.This series makes iomap charge and discharge the mm dirty counters per dirty page for folios that carry per-block dirty state, so a partially dirty large folio is accounted for the dirty part only:
- Patch 1 adds the mm infrastructure: an
AS_DIRTY_PER_BLOCKmapping flag, an @accounted argument to__folio_mark_dirty()and__filemap_dirty_folio()to skip the generic per-folio charge, and anaddress_space_operations::accounted_dirty_pages()callback used by the discharge and migration paths instead offolio_nr_pages(). No filesystem opts in, so it is a no-op on its own.- Patch 2 makes iomap charge per dirty page from the per-block dirty bitmap and wires
iomap_accounted_dirty_pages()into every iomap-based filesystem.This was benchmarked with PostgreSQL using the pgbench simple-update workload on v7.3-rc7. Average throughput rises 46.8% (139.8k -> 205.2k tps) and run-to-run variability drops from a 23.60% to a 3.98% coefficient of variation: the worst iteration improves from 97.9k to 191.5k tps, while the best gains 8%, 199.4k -> 215.9k.
Ten iterations per kernel, same database and workload (tps):
Kernel Avg Min Max CV iters iters
1-5 6-10 ______________________ ______ ______ ______ ______ ______ ______ v7.3-rc7 139.8k 97.9k 199.4k 23.60% 164.4k 115.2k v7.3-rc7 + this series 205.2k 191.5k 215.9k 3.98% 200.1k 210.2kOn unpatched v7.3-rc7 the worst iteration lands ~51% below the best, and throughput decays as the run progresses: iterations 6-10 average 30% below iterations 1-5. With this series the decay is gone -- the second half is similar to the first -- and the coefficient of variation stays at 3.98%.
The over-accounting has existed since commit
4ce02c679722("iomap: Add per-block dirty state tracking to improve performance"), merged in v6.6, where the ifs bitmap started recording partial dirty state while the mm counters kept charging whole folios.Quoted 5 lines
The throughput collapse bisects to the v6.17 readahead series, first bad commit
c4602f9fa77f("mm/readahead: store folio order in structfile_ra_state"), which lets readahead stay at the largest folio order once it has ramped up, so a single dirty block charges far more than is written. Patch 2 therefore carries:How does this relate to
Quoted 8 lines
[RFC PATCH 0/5] mm: sub-folio dirty tracking for PTE-mapped mmap writes
https://lore.kernel.org/all/[email protected]/
?
I assume they try to solve different problems, but would more fine-grained folio dirtying also make your solution benefit?
Yeah, it solves different problem.
And I abandoned my patchset. The right way to do this is to make page_mkwrite() per-page, not folio.
Signature · 1 line
Kiryl Shutsemau / Kirill A. Shutemov
Quoted 17 lines · Salvatore Dipietro
Since iomap gained per-block dirty tracking, a large folio can be partially dirty: struct
iomap_folio_staterecords exactly which blocks are dirty, and writeback only writes those ranges. The mm dirty accounting, however, still charges the whole folio even if a single block is dirty (up to 512x over-accounting for a 2 MB folio over 4 KB blocks).
balance_dirty_pages()then throttles writers against a number that is unrelated to how much data actually needs writing back. On workloads that repeatedly dirty small ranges of large folios -- e.g. PostgreSQL, which writes mostly 8/16 KB pages --dirty_threshis crossed and writers are throttled long before the real dirty data justifies it. On the benchmark below, run on v7.3-rc7, the unpatched kernel charges ~159 TB of dirtied pages while writing ~6 TB to the array, a factor of 27; with this series the dirtied pages charged match the data actually written.
Quoted 3 lines
This series makes iomap charge and discharge the mm dirty counters per dirty page for folios that carry per-block dirty state, so a partially dirty large folio is accounted for the dirty part only:
Why? This looks wrong. Yes, you may only have dirtied e.g 4K out of a 2MB folio, but the whole 2MB folio is still effectively pinned by the VM, awaiting cleaning + writeback. And that's precisely what we want to measure and throttle in certain cases, so that e.g the VM system never finds itself short of clean pages it can reclaim, and no easy way to start writeback on them.
Signature · 1 line
Pedro
Jan Kara
maintainerQuoted 22 lines · Pedro Falcato
Quoted 17 lines · Salvatore Dipietro
Since iomap gained per-block dirty tracking, a large folio can be partially dirty: struct
iomap_folio_staterecords exactly which blocks are dirty, and writeback only writes those ranges. The mm dirty accounting, however, still charges the whole folio even if a single block is dirty (up to 512x over-accounting for a 2 MB folio over 4 KB blocks).
balance_dirty_pages()then throttles writers against a number that is unrelated to how much data actually needs writing back. On workloads that repeatedly dirty small ranges of large folios -- e.g. PostgreSQL, which writes mostly 8/16 KB pages --dirty_threshis crossed and writers are throttled long before the real dirty data justifies it. On the benchmark below, run on v7.3-rc7, the unpatched kernel charges ~159 TB of dirtied pages while writing ~6 TB to the array, a factor of 27; with this series the dirtied pages charged match the data actually written.Quoted 3 lines
This series makes iomap charge and discharge the mm dirty counters per dirty page for folios that carry per-block dirty state, so a partially dirty large folio is accounted for the dirty part only:
Quoted 6 lines
Why? This looks wrong. Yes, you may only have dirtied e.g 4K out of a 2MB folio, but the whole 2MB folio is still effectively pinned by the VM, awaiting cleaning + writeback. And that's precisely what we want to measure and throttle in certain cases, so that e.g the VM system never finds itself short of clean pages it can reclaim, and no easy way to start writeback on them.
Fully agree on that. We have already discussed this with Joanne about one year ago [1]. There are some aspects of dirty accounting that could be made more finer grained but overall the whole folio is difficult to reclaim due to dirtiness so accounting it all is the correct approach.
Honza
[1] https://lore.kernel.org/all/[email protected]
Signature · 2 lines
Jan Kara <[email protected]> SUSE Labs, CR
Hi all,
Thanks Jan, Pedro, Dave, David and Kiryl for the feedback.
Following Dave's question about how PostgreSQL gets large folios on files it writes 8 KiB at a time, we looked deeper and found a reproducer that needs only fio and a single disk.
What happens:
1. A buffered sequential read (VACUUM, a backup, a scan) builds large folios through readahead. They stay large in the page cache until they are evicted.
2. The first small write into one of these clean folios charges the whole folio as dirty: a 4 KiB write into a 256 KiB folio charges 256 KiB, while writeback only writes the dirty 4 KiB.
3. With random writes, most writes land in a different clean folio, so the dirty count reaches the limits with little real data. balance_dirty_pages() then throttles the writers, and they end up paced by how many folios writeback can clean per second rather than by the bytes to write.
Reproducer: XFS on one EBS gp3 volume (3000 IOPS), m8g.8xlarge (32 CPUs, 128 GiB), default read_ahead_kb=128. fio's 1 MiB reads grow the readahead window up to the device's max_sectors_kb (256 KiB), so the read builds 256 KiB folios.
; create.fio: 16 x 3 GiB files, direct I/O so nothing is cached [global]
directory=/mnt/xfs/fio
filename_format=f.$jobnum
size=3072m
numjobs=16
group_reporting=1
[create]
rw=write
bs=1m
direct=1
ioengine=libaio
iodepth=16
; load.fio: buffered sequential read; builds the large folios [global]
directory=/mnt/xfs/fio
filename_format=f.$jobnum
size=3072m
numjobs=16
group_reporting=1
[load]
rw=read
bs=1m
direct=0
ioengine=psync
; randwrite.fio: random 4 KiB buffered writes, 32 x 312 = ~10k IOPS ; invalidate=0 keeps the cached folios when fio opens the files [randwrite]
directory=/mnt/xfs/fio filename=f.0:f.1:f.2:f.3:f.4:f.5:f.6:f.7:f.8:f.9:f.10:f.11:f.12:f.13:f.14:f.15 rw=randwrite
bs=4k
direct=0
ioengine=psync
invalidate=0
numjobs=32
rate_iops=312
time_based=1
runtime=120
group_reporting=1
To reproduce it, run (as root):
fio create.fio
sync; echo 3 > /proc/sys/vm/drop_caches
fio load.fio # skip this step for the control run
fio randwrite.fio
fio asks for ~10k write IOPS, more than the volume's 3000, so dirty data builds up in both runs. In the control run (no load step) each 4 KiB write creates a 4 KiB folio: after 120 s only 3.3G is dirty, below the 12.2G background threshold, and nothing is throttled. After the load step the same writes land in 256 KiB folios, and each write into a clean folio is charged 256 KiB: the dirty count passes the background threshold after 6 s and writers are throttled from 13 s.
Results on v7.4-rc2, one run per kernel, each on a fresh instance. Writer sleep is the total balance_dirty_pages() pause time over the 32 writers during the 120 s write phase:
write p99 / max writer max folio
IOPS lat ms sleep s dirty size
baseline, control 9,984 0.01 / 0.30 0 3.3G -
baseline 4,061 60 / 160 179 23.5G 256K
v1 (this series) 9,984 0.01 / 0.67 0 3.6G 256K
max order cap 64K 7,071 50 / 280 73 22.3G 64K
max order cap 16K 9,984 0.02 / 0.05 0 11.9G 16K
split on write 9,984 0.02 / 0.17 0 3.6G 256K
evict on write 9,984 0.03 / 0.19 0 3.3G 256K
POSIX_FADV_RANDOM 9,984 0.02 / 0.05 0 3.3G 4KThe control run gave 9,984 IOPS and max latency up to 0.30 ms on every kernel.
- max order cap: the global cap in mapping_max_folio_order() that Jan suggested trying. At 64 KiB a 4 KiB write still charges 16x and is throttled. At 16 KiB this run is not throttled, but dirty reached 11.9G, just below the 12.2G background threshold. The cap that avoids throttling depends on the write size, and it removes large folios for every file, including ones that never see small writes.
- split on write: when a buffered write (iomap opts in, not for zeroing or unshare) finds a clean, uptodate, unmapped folio at least 4x the write size, folio_split() it down to the write's order before dirtying it. The rest of the folio stays cached in large folios. On the concerns Jan raised about splitting [1]: split on write only splits clean, uptodate, unmapped folios, so it needs no new filesystem state beyond an opt-in flag in iomap, and if folio_split() fails the write simply proceeds as today; evict on write avoids splitting altogether.
- evict on write: same trigger, but mapping_evict_folio() the folio instead of splitting it (~40 lines). This discards the folio's other cached data; nothing reads it back in this test, so the read cost does not show here.
- POSIX_FADV_RANDOM (Dave's question): fio's fadvise_hint=random on the load job. It avoids the problem without a kernel change, but only where the application opts in: the hint is per open file, so every process that reads a file must issue it, and a reader that doesn't (a backup or copy tool, for example) still builds large folios. Every application that reads files sequentially and then rewrites them in place would have to adopt it, and keeps the regression until it does. It also turns readahead off for those files, so their sequential reads lose readahead.
Split and evict on write keep whole-folio accounting and act at write time, so they also cover large folios already in the page cache, whoever built them, without each application having to opt in. Both only touch clean, uptodate, unmapped folios at least 4x the write size, and only on iomap buffered writes. Split keeps the rest of the folio cached at the cost of the split; evict is simpler but drops it. I'd appreciate your opinion on these options, or any other direction you think is more appropriate.
Thanks,
Salvatore
[1] https://lore.kernel.org/all/oocwnxqgd4klrem6hkya3sddqoxkosml4ysz23if4j7wj2qdwi@5skgc4ftu7io/
AMAZON DEVELOPMENT CENTER ITALY SRL, viale Monte Grappa 3/5, 20124 Milano, Italia, Registro delle Imprese di Milano Monza Brianza Lodi REA n. 2504859, Capitale Sociale: 10.000 EUR i.v., Cod. Fisc. e P.IVA 10100050961, Societa con Socio Unico
Quoted 123 lines · Salvatore Dipietro
Hi all,
Thanks Jan, Pedro, Dave, David and Kiryl for the feedback.
Following Dave's question about how PostgreSQL gets large folios on files it writes 8 KiB at a time, we looked deeper and found a reproducer that needs only fio and a single disk.
What happens:
1. A buffered sequential read (VACUUM, a backup, a scan) builds large folios through readahead. They stay large in the page cache until they are evicted.
2. The first small write into one of these clean folios charges the whole folio as dirty: a 4 KiB write into a 256 KiB folio charges 256 KiB, while writeback only writes the dirty 4 KiB.
3. With random writes, most writes land in a different clean folio, so the dirty count reaches the limits with little real data.balance_dirty_pages()then throttles the writers, and they end up paced by how many folios writeback can clean per second rather than by the bytes to write.Reproducer: XFS on one EBS gp3 volume (3000 IOPS), m8g.8xlarge (32 CPUs, 128 GiB), default read_ahead_kb=128. fio's 1 MiB reads grow the readahead window up to the device's
max_sectors_kb(256 KiB), so the read builds 256 KiB folios.; create.fio: 16 x 3 GiB files, direct I/O so nothing is cached [global]
directory=/mnt/xfs/fio
filename_format=f.$jobnum
size=3072m
numjobs=16
group_reporting=1
[create]
rw=write
bs=1m
direct=1
ioengine=libaio
iodepth=16; load.fio: buffered sequential read; builds the large folios [global]
directory=/mnt/xfs/fio
filename_format=f.$jobnum
size=3072m
numjobs=16
group_reporting=1
[load]
rw=read
bs=1m
direct=0
ioengine=psync; randwrite.fio: random 4 KiB buffered writes, 32 x 312 = ~10k IOPS ; invalidate=0 keeps the cached folios when fio opens the files [randwrite]
directory=/mnt/xfs/fio filename=f.0:f.1:f.2:f.3:f.4:f.5:f.6:f.7:f.8:f.9:f.10:f.11:f.12:f.13:f.14:f.15 rw=randwrite
bs=4k
direct=0
ioengine=psync
invalidate=0
numjobs=32
rate_iops=312
time_based=1
runtime=120
group_reporting=1To reproduce it, run (as root):
fio create.fio
sync; echo 3 >/proc/sys/vm/drop_caches
fio load.fio # skip this step for the control run
fio randwrite.fiofio asks for ~10k write IOPS, more than the volume's 3000, so dirty data builds up in both runs. In the control run (no load step) each 4 KiB write creates a 4 KiB folio: after 120 s only 3.3G is dirty, below the 12.2G background threshold, and nothing is throttled. After the load step the same writes land in 256 KiB folios, and each write into a clean folio is charged 256 KiB: the dirty count passes the background threshold after 6 s and writers are throttled from 13 s.
Results on v7.4-rc2, one run per kernel, each on a fresh instance. Writer sleep is the total
balance_dirty_pages()pause time over the 32 writers during the 120 s write phase:write p99 / max writer max folio IOPS lat ms sleep s dirty size baseline, control 9,984 0.01 / 0.30 0 3.3G - baseline 4,061 60 / 160 179 23.5G 256K v1 (this series) 9,984 0.01 / 0.67 0 3.6G 256K max order cap 64K 7,071 50 / 280 73 22.3G 64K max order cap 16K 9,984 0.02 / 0.05 0 11.9G 16K split on write 9,984 0.02 / 0.17 0 3.6G 256K evict on write 9,984 0.03 / 0.19 0 3.3G 256K POSIX_FADV_RANDOM 9,984 0.02 / 0.05 0 3.3G 4KThe control run gave 9,984 IOPS and max latency up to 0.30 ms on every kernel.
- max order cap: the global cap in
mapping_max_folio_order()that Jan suggested trying. At 64 KiB a 4 KiB write still charges 16x and is throttled. At 16 KiB this run is not throttled, but dirty reached 11.9G, just below the 12.2G background threshold. The cap that avoids throttling depends on the write size, and it removes large folios for every file, including ones that never see small writes.
- split on write: when a buffered write (iomap opts in, not for zeroing or unshare) finds a clean, uptodate, unmapped folio at least 4x the write size,folio_split()it down to the write's order before dirtying it. The rest of the folio stays cached in large folios. On the concerns Jan raised about splitting [1]: split on write only splits clean, uptodate, unmapped folios, so it needs no new filesystem state beyond an opt-in flag in iomap, and iffolio_split()fails the write simply proceeds as today; evict on write avoids splitting altogether.
- evict on write: same trigger, butmapping_evict_folio()the folio instead of splitting it (~40 lines). This discards the folio's other cached data; nothing reads it back in this test, so the read cost does not show here.
-POSIX_FADV_RANDOM(Dave's question): fio's fadvise_hint=random on
Quoted 8 lines
the load job. It avoids the problem without a kernel change, but only where the application opts in: the hint is per open file, so every process that reads a file must issue it, and a reader that doesn't (a backup or copy tool, for example) still builds large folios. Every application that reads files sequentially and then rewrites them in place would have to adopt it, and keeps the regression until it does. It also turns readahead off for those files, so their sequential reads lose readahead.
Holy heck, did an LLM write this?
Quoted 9 lines
Split and evict on write keep whole-folio accounting and act at write time, so they also cover large folios already in the page cache, whoever built them, without each application having to opt in. Both only touch clean, uptodate, unmapped folios at least 4x the write size, and only on iomap buffered writes. Split keeps the rest of the folio cached at the cost of the split; evict is simpler but drops it. I'd appreciate your opinion on these options, or any other direction you think is more appropriate.
I think you'll face strong resistance to any of these options.
Signature · 1 line
Pedro
syzbot ci has tested the following series
syzbot ci has tested the following series
[v1] mm, iomap: account dirty at page granularity for per-block dirty folios
https://lore.kernel.org/all/[email protected]
* [PATCH 1/2] mm: add infrastructure for per-dirty-page accounting
* [PATCH 2/2] mm, iomap: account dirty at page granularity for per-block dirty folios
and found the following issues:
* KASAN: slab-out-of-bounds Read in folio_accounted_dirty_pages
* KASAN: slab-use-after-free Read in folio_accounted_dirty_pages
Full report is available here:
https://ci.syzbot.org/series/05041e6c-d357-4fc5-9bbe-6aae1760d639
***
KASAN: slab-out-of-bounds Read in folio_accounted_dirty_pages
tree: axboe URL: https://kernel.googlesource.com/pub/scm/linux/kernel/git/axboe/linux.git base: 24a19b953e2a3d0ea5a8c4951a0ab8f32720c907 arch: amd64 compiler: Debian clang version 22.1.8 (1~deb13u4), Debian LLD 22.1.8 config: https://ci.syzbot.org/builds/9865cf75-69fb-4fbd-b5fe-d0be9cd03802/config syz repro: https://ci.syzbot.org/findings/98cdf846-0b4c-4f94-8430-3b7db9efe057/syz_repro
==================================================================
BUG: KASAN: slab-out-of-bounds in instrument_atomic_read include/linux/instrumented.h:82 [inline] BUG: KASAN: slab-out-of-bounds in _test_bit include/asm-generic/bitops/instrumented-non-atomic.h:141 [inline] BUG: KASAN: slab-out-of-bounds in mapping_dirty_per_block include/linux/pagemap.h:319 [inline] BUG: KASAN: slab-out-of-bounds in folio_accounted_dirty_pages+0x53/0x1f0 mm/page-writeback.c:2654 Read of size 8 at addr ffff888168669f89 by task syz.1.47/5860 CPU: 0 UID: 0 PID: 5860 Comm: syz.1.47 Not tainted syzkaller #0 PREEMPT(full) Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS 1.16.2-debian-1.16.2-1 04/01/2014 Call Trace: <TASK> dump_stack_lvl+0xe8/0x150 lib/dump_stack.c:120 print_address_description+0x55/0x1e0 mm/kasan/report.c:378 print_report+0x58/0x70 mm/kasan/report.c:482 kasan_report+0x117/0x150 mm/kasan/report.c:595 check_region_inline mm/kasan/generic.c:-1 [inline] kasan_check_range+0x264/0x2c0 mm/kasan/generic.c:200 instrument_atomic_read include/linux/instrumented.h:82 [inline] _test_bit include/asm-generic/bitops/instrumented-non-atomic.h:141 [inline] mapping_dirty_per_block include/linux/pagemap.h:319 [inline] folio_accounted_dirty_pages+0x53/0x1f0 mm/page-writeback.c:2654 __folio_migrate_mapping+0x3d0/0x2830 mm/migrate.c:624 __migrate_folio mm/migrate.c:893 [inline] migrate_folio+0x10a/0x1a0 mm/migrate.c:920 move_to_new_folio+0x1ed/0x460 mm/migrate.c:1135 migrate_folio_move mm/migrate.c:1401 [inline] migrate_folios_move mm/migrate.c:1758 [inline] migrate_pages_batch+0x30b3/0x4f50 mm/migrate.c:2014 migrate_pages_sync mm/migrate.c:2044 [inline] migrate_pages+0x1b9f/0x2920 mm/migrate.c:2153 migrate_to_node mm/mempolicy.c:1322 [inline] do_migrate_pages+0x656/0x8b0 mm/mempolicy.c:1421 kernel_migrate_pages mm/mempolicy.c:1935 [inline] __do_sys_migrate_pages mm/mempolicy.c:1953 [inline] __se_sys_migrate_pages+0xaa2/0xc90 mm/mempolicy.c:1949 do_syscall_x64 arch/x86/entry/syscall_64.c:61 [inline] do_syscall_64+0x166/0x520 arch/x86/entry/syscall_64.c:84 entry_SYSCALL_64_after_hwframe+0x77/0x7f RIP: 0033:0x7f04fcf9f559 Code: ff c3 66 2e 0f 1f 84 00 00 00 00 00 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 e8 ff ff ff f7 d8 64 89 01 48 RSP: 002b:00007f04fc5fe028 EFLAGS: 00000246 ORIG_RAX: 0000000000000100 RAX: ffffffffffffffda RBX: 00007f04fd225fa0 RCX: 00007f04fcf9f559 RDX: 0000200000000040 RSI: 0000000000000009 RDI: 0000000000000000 RBP: 00007f04fd036b20 R08: 0000000000000000 R09: 0000000000000000 R10: 0000200000000380 R11: 0000000000000246 R12: 0000000000000000 R13: 00007f04fd226038 R14: 00007f04fd225fa0 R15: 00007ffc667db8b8 </TASK> Allocated by task 5729: kasan_save_stack mm/kasan/common.c:57 [inline] kasan_save_track+0x3e/0x80 mm/kasan/common.c:78 unpoison_slab_object mm/kasan/common.c:351 [inline] __kasan_slab_alloc+0x6c/0x80 mm/kasan/common.c:377 kasan_slab_alloc include/linux/kasan.h:253 [inline] slab_post_alloc_hook mm/slub.c:4683 [inline] slab_alloc_node mm/slub.c:4996 [inline] kmem_cache_alloc_noprof+0x2b9/0x600 mm/slub.c:5010 anon_vma_alloc mm/rmap.c:94 [inline] anon_vma_fork+0x88/0x540 mm/rmap.c:395 dup_mmap+0x954/0x1dc0 mm/mmap.c:1781 dup_mm kernel/fork.c:1543 [inline] copy_mm+0x115/0x480 kernel/fork.c:1595 copy_process+0x1e79/0x4400 kernel/fork.c:2311 kernel_clone+0x2d7/0x940 kernel/fork.c:2771 __do_sys_clone kernel/fork.c:2913 [inline] __se_sys_clone kernel/fork.c:2897 [inline] __x64_sys_clone+0x1b6/0x230 kernel/fork.c:2897 do_syscall_x64 arch/x86/entry/syscall_64.c:61 [inline] do_syscall_64+0x166/0x520 arch/x86/entry/syscall_64.c:84 entry_SYSCALL_64_after_hwframe+0x77/0x7f The buggy address belongs to the object at ffff888168669e70 which belongs to the cache anon_vma of size 200
The buggy address is located 81 bytes to the right of
allocated 200-byte region [ffff888168669e70, ffff888168669f38)
The buggy address belongs to the physical page:
page: refcount:0 mapcount:0 mapping:0000000000000000 index:0xffff888168669108 pfn:0x168669
memcg:ffff88816db0e201
flags: 0x57ff00000000200(workingset|node=1|zone=2|lastcpupid=0x7ff)
page_type: f5(slab)
raw: 057ff00000000200 ffff888101687140 ffff88816040c7c8 ffffea0005b62950
raw: ffff888168669108 00000002000f000b 00000000f5000000 ffff88816db0e201
page dumped because: kasan: bad access detected
page_owner tracks the page as allocated
page last allocated via order 0, migratetype Unmovable, gfp_mask 0xd2cc0(GFP_KERNEL|__GFP_NOWARN|__GFP_NORETRY|__GFP_COMP|__GFP_NOMEMALLOC), pid 5535, tgid 5535 (rm), ts 43255388535
set_page_owner include/linux/page_owner.h:33 [inline]
post_alloc_hook+0x1f9/0x250 mm/page_alloc.c:1871
prep_new_page mm/page_alloc.c:1879 [inline]
get_page_from_freelist+0x2209/0x2280 mm/page_alloc.c:3943
__alloc_frozen_pages_noprof+0x217/0x5a0 mm/page_alloc.c:5436
alloc_slab_page mm/slub.c:3347 [inline]
allocate_slab+0x7d/0x620 mm/slub.c:3462
new_slab mm/slub.c:3513 [inline]
refill_objects+0x2d5/0x350 mm/slub.c:7418
refill_sheaf mm/slub.c:2885 [inline]
__pcs_replace_empty_main+0x2c8/0x6c0 mm/slub.c:4774
alloc_from_pcs mm/slub.c:4850 [inline]
slab_alloc_node mm/slub.c:4984 [inline]
kmem_cache_alloc_noprof+0x399/0x600 mm/slub.c:5010
anon_vma_alloc mm/rmap.c:94 [inline]
__anon_vma_prepare+0x10e/0x4d0 mm/rmap.c:201
__vmf_anon_prepare mm/memory.c:3961 [inline]
vmf_anon_prepare mm/internal.h:572 [inline]
do_anonymous_page mm/memory.c:5478 [inline]
do_pte_missing+0x2f18/0x34b0 mm/memory.c:4698
handle_pte_fault mm/memory.c:6558 [inline]
__handle_mm_fault mm/memory.c:6707 [inline]
handle_mm_fault+0x1a53/0x3750 mm/memory.c:6876
do_user_addr_fault+0xa4f/0x1340 arch/x86/mm/fault.c:1343
handle_page_fault arch/x86/mm/fault.c:1483 [inline]
exc_page_fault+0x6a/0xc0 arch/x86/mm/fault.c:1536
asm_exc_page_fault+0x26/0x30 arch/x86/include/asm/idtentry.h:595
page last free pid 5049 tgid 5049 ts 18476194117 stack trace:
reset_page_owner include/linux/page_owner.h:26 [inline]
__free_pages_prepare mm/page_alloc.c:1418 [inline]
__free_frozen_pages+0xc93/0xd90 mm/page_alloc.c:2962
__slab_free+0x274/0x2c0 mm/slub.c:5823
qlink_free mm/kasan/quarantine.c:163 [inline]
qlist_free_all+0x99/0x100 mm/kasan/quarantine.c:179
kasan_quarantine_reduce+0x148/0x160 mm/kasan/quarantine.c:286
__kasan_slab_alloc+0x22/0x80 mm/kasan/common.c:361
kasan_slab_alloc include/linux/kasan.h:253 [inline]
slab_post_alloc_hook mm/slub.c:4683 [inline]
slab_alloc_node mm/slub.c:4996 [inline]
kmem_cache_alloc_node_noprof+0x354/0x610 mm/slub.c:5068
__alloc_skb+0x1db/0x7a0 net/core/skbuff.c:704
alloc_skb include/linux/skbuff.h:1384 [inline]
alloc_skb_with_frags+0xc6/0x760 net/core/skbuff.c:6803
sock_alloc_send_pskb+0x878/0x990 net/core/sock.c:3022
unix_dgram_sendmsg+0x4da/0x17b0 net/unix/af_unix.c:2144
sock_sendmsg_nosec+0x13a/0x180 net/socket.c:800
__sock_sendmsg net/socket.c:815 [inline]
sock_write_iter+0x2de/0x3e0 net/socket.c:1266
new_sync_write fs/read_write.c:595 [inline]
vfs_write+0x612/0xba0 fs/read_write.c:687
ksys_write+0x150/0x270 fs/read_write.c:739
do_syscall_x64 arch/x86/entry/syscall_64.c:61 [inline]
do_syscall_64+0x166/0x520 arch/x86/entry/syscall_64.c:84
entry_SYSCALL_64_after_hwframe+0x77/0x7f
Memory state around the buggy address:
ffff888168669e80: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
ffff888168669f00: 00 00 00 00 00 00 00 fc fc fc fc fc fc fc fc fc
>ffff888168669f80: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
^
ffff88816866a000: fa fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
ffff88816866a080: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fc fc
==================================================================***
KASAN: slab-use-after-free Read in folio_accounted_dirty_pages
tree: axboe URL: https://kernel.googlesource.com/pub/scm/linux/kernel/git/axboe/linux.git base: 24a19b953e2a3d0ea5a8c4951a0ab8f32720c907 arch: amd64 compiler: Debian clang version 22.1.8 (1~deb13u4), Debian LLD 22.1.8 config: https://ci.syzbot.org/builds/9865cf75-69fb-4fbd-b5fe-d0be9cd03802/config syz repro: https://ci.syzbot.org/findings/f9e47a91-9c37-465b-b43c-7404e404cbfd/syz_repro
==================================================================
BUG: KASAN: slab-use-after-free in instrument_atomic_read include/linux/instrumented.h:82 [inline] BUG: KASAN: slab-use-after-free in _test_bit include/asm-generic/bitops/instrumented-non-atomic.h:141 [inline] BUG: KASAN: slab-use-after-free in mapping_dirty_per_block include/linux/pagemap.h:319 [inline] BUG: KASAN: slab-use-after-free in folio_accounted_dirty_pages+0x53/0x1f0 mm/page-writeback.c:2654 Read of size 8 at addr ffff888111a3d539 by task syz.0.17/5870 CPU: 0 UID: 0 PID: 5870 Comm: syz.0.17 Not tainted syzkaller #0 PREEMPT(full) Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS 1.16.2-debian-1.16.2-1 04/01/2014 Call Trace: <TAS <TASK> dump_stack_lvl+0xe8/0x150 lib/dump_stack.c:120 print_address_description+0x55/0x1e0 mm/kasan/report.c:378 print_report+0x58/0x70 mm/kasan/report.c:482 kasan_report+0x117/0x150 mm/kasan/report.c:595 check_region_inline mm/kasan/generic.c:-1 [inline] kasan_check_range+0x264/0x2c0 mm/kasan/generic.c:200 instrument_atomic_read include/linux/instrumented.h:82 [inline] _test_bit include/asm-generic/bitops/instrumented-non-atomic.h:141 [inline] mapping_dirty_per_block include/linux/pagemap.h:319 [inline] folio_accounted_dirty_pages+0x53/0x1f0 mm/page-writeback.c:2654 __folio_migrate_mapping+0x3d0/0x2830 mm/migrate.c:624 __migrate_folio mm/migrate.c:893 [inline] migrate_folio+0x10a/0x1a0 mm/migrate.c:920 move_to_new_folio+0x1ed/0x460 mm/migrate.c:1135 migrate_folio_move mm/migrate.c:1401 [inline] migrate_folios_move mm/migrate.c:1758 [inline] migrate_pages_batch+0x30b3/0x4f50 mm/migrate.c:2014 migrate_pages_sync mm/migrate.c:2044 [inline] migrate_pages+0x1b9f/0x2920 mm/migrate.c:2153 migrate_to_node mm/mempolicy.c:1322 [inline] do_migrate_pages+0x656/0x8b0 mm/mempolicy.c:1421 kernel_migrate_pages mm/mempolicy.c:1935 [inline] __do_sys_migrate_pages mm/mempolicy.c:1953 [inline] __se_sys_migrate_pages+0xaa2/0xc90 mm/mempolicy.c:1949 do_syscall_x64 arch/x86/entry/syscall_64.c:61 [inline] do_syscall_64+0x166/0x520 arch/x86/entry/syscall_64.c:84 entry_SYSCALL_64_after_hwframe+0x77/0x7f RIP: 0033:0x7f600f39f559 Code: ff c3 66 2e 0f 1f 84 00 00 00 00 00 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 e8 ff ff ff f7 d8 64 89 01 48 RSP: 002b:00007f6010302028 EFLAGS: 00000246 ORIG_RAX: 0000000000000100 RAX: ffffffffffffffda RBX: 00007f600f625fa0 RCX: 00007f600f39f559 RDX: 0000200000000040 RSI: 0000000000000009 RDI: 0000000000000000 RBP: 00007f600f436b20 R08: 0000000000000000 R09: 0000000000000000 R10: 0000200000000380 R11: 0000000000000246 R12: 0000000000000000 R13: 00007f600f626038 R14: 00007f600f625fa0 R15: 00007ffcbfa14028 </TASK> Allocated by task 5645: kasan_save_stack mm/kasan/common.c:57 [inline] kasan_save_track+0x3e/0x80 mm/kasan/common.c:78 unpoison_slab_object mm/kasan/common.c:351 [inline] __kasan_slab_alloc+0x6c/0x80 mm/kasan/common.c:377 kasan_slab_alloc include/linux/kasan.h:253 [inline] slab_post_alloc_hook mm/slub.c:4683 [inline] slab_alloc_node mm/slub.c:4996 [inline] kmem_cache_alloc_noprof+0x2b9/0x600 mm/slub.c:5010 anon_vma_alloc mm/rmap.c:94 [inline] __anon_vma_prepare+0x10e/0x4d0 mm/rmap.c:201 __vmf_anon_prepare mm/memory.c:3961 [inline] vmf_anon_prepare mm/internal.h:572 [inline] do_anonymous_page mm/memory.c:5478 [inline] do_pte_missing+0x2f18/0x34b0 mm/memory.c:4698 handle_pte_fault mm/memory.c:6558 [inline] __handle_mm_fault mm/memory.c:6707 [inline] handle_mm_fault+0x1a53/0x3750 mm/memory.c:6876 do_user_addr_fault+0xa4f/0x1340 arch/x86/mm/fault.c:1343 handle_page_fault arch/x86/mm/fault.c:1483 [inline] exc_page_fault+0x6a/0xc0 arch/x86/mm/fault.c:1536 asm_exc_page_fault+0x26/0x30 arch/x86/include/asm/idtentry.h:595 Freed by task 5646: kasan_save_stack mm/kasan/common.c:57 [inline] kasan_save_track+0x3e/0x80 mm/kasan/common.c:78 kasan_save_free_info+0x40/0x50 mm/kasan/generic.c:584 poison_slab_object mm/kasan/common.c:264 [inline] __kasan_slab_free+0x5c/0x80 mm/kasan/common.c:296 kasan_slab_free include/linux/kasan.h:235 [inline] slab_free_hook mm/slub.c:2748 [inline] slab_free_after_rcu_debug+0x12a/0x220 mm/slub.c:6571 rcu_do_batch kernel/rcu/tree.c:2650 [inline] rcu_core+0x926/0x1260 kernel/rcu/tree.c:2919 handle_softirqs+0x226/0x860 kernel/softirq.c:645 __do_softirq kernel/softirq.c:679 [inline] invoke_softirq kernel/softirq.c:519 [inline] __irq_exit_rcu+0xcb/0x220 kernel/softirq.c:758 irq_exit_rcu+0x9/0x30 kernel/softirq.c:775 instr_sysvec_apic_timer_interrupt arch/x86/kernel/apic/apic.c:1062 [inline] sysvec_apic_timer_interrupt+0xa6/0xc0 arch/x86/kernel/apic/apic.c:1062 asm_sysvec_apic_timer_interrupt+0x1a/0x20 arch/x86/include/asm/idtentry.h:674 Last potentially related work creation: kasan_save_stack+0x3e/0x60 mm/kasan/common.c:57 kasan_record_aux_stack+0xbd/0xd0 mm/kasan/generic.c:556 slab_free_hook mm/slub.c:2709 [inline] slab_free mm/slub.c:6509 [inline] kmem_cache_free+0x45e/0x650 mm/slub.c:6636 anon_vma_free mm/rmap.c:137 [inline] __put_anon_vma+0x12b/0x2d0 mm/rmap.c:2974 put_anon_vma mm/internal.h:293 [inline] unlink_anon_vmas+0x544/0x720 mm/rmap.c:540 free_pgtables+0x663/0xb70 mm/memory.c:401 unmap_region+0x29d/0x330 mm/vma.c:534 vms_clear_ptes mm/vma.c:1383 [inline] vms_complete_munmap_vmas+0x427/0xbe0 mm/vma.c:1425 do_vmi_align_munmap+0x3b7/0x4b0 mm/vma.c:1684 do_vmi_munmap+0x252/0x2d0 mm/vma.c:1732 __vm_munmap+0x241/0x3e0 mm/vma.c:3415 __do_sys_munmap mm/mmap.c:1094 [inline] __se_sys_munmap mm/mmap.c:1091 [inline] __x64_sys_munmap+0x60/0x70 mm/mmap.c:1091 do_syscall_x64 arch/x86/entry/syscall_64.c:61 [inline] do_syscall_64+0x166/0x520 arch/x86/entry/syscall_64.c:84 entry_SYSCALL_64_after_hwframe+0x77/0x7f The buggy address belongs to the object at ffff888111a3d528 which belongs to the cache anon_vma of size 200
The buggy address is located 17 bytes inside of
freed 200-byte region [ffff888111a3d528, ffff888111a3d5f0)
The buggy address belongs to the physical page:
page: refcount:0 mapcount:0 mapping:0000000000000000 index:0xffff888111a3d528 pfn:0x111a3d
memcg:ffff888111a3df79
flags: 0x17ff00000000200(workingset|node=0|zone=2|lastcpupid=0x7ff)
page_type: f5(slab)
raw: 017ff00000000200 ffff888101688140 ffff8881006957c8 ffffea00047d6bd0
raw: ffff888111a3d528 00000002000f0009 00000000f5000000 ffff888111a3df79
page dumped because: kasan: bad access detected
page_owner tracks the page as allocated
page last allocated via order 0, migratetype Unmovable, gfp_mask 0xd2cc0(GFP_KERNEL|__GFP_NOWARN|__GFP_NORETRY|__GFP_COMP|__GFP_NOMEMALLOC), pid 5634, tgid 5634 (syz-executor), ts 59634551582
set_page_owner include/linux/page_owner.h:33 [inline]
post_alloc_hook+0x1f9/0x250 mm/page_alloc.c:1871
prep_new_page mm/page_alloc.c:1879 [inline]
get_page_from_freelist+0x2209/0x2280 mm/page_alloc.c:3943
__alloc_frozen_pages_noprof+0x217/0x5a0 mm/page_alloc.c:5436
alloc_slab_page mm/slub.c:3347 [inline]
allocate_slab+0x7d/0x620 mm/slub.c:3462
new_slab mm/slub.c:3513 [inline]
refill_objects+0x2d5/0x350 mm/slub.c:7418
refill_sheaf mm/slub.c:2885 [inline]
__pcs_replace_empty_main+0x2c8/0x6c0 mm/slub.c:4774
alloc_from_pcs mm/slub.c:4850 [inline]
slab_alloc_node mm/slub.c:4984 [inline]
kmem_cache_alloc_noprof+0x399/0x600 mm/slub.c:5010
anon_vma_alloc mm/rmap.c:94 [inline]
anon_vma_fork+0x88/0x540 mm/rmap.c:395
dup_mmap+0x954/0x1dc0 mm/mmap.c:1781
dup_mm kernel/fork.c:1543 [inline]
copy_mm+0x115/0x480 kernel/fork.c:1595
copy_process+0x1e79/0x4400 kernel/fork.c:2311
kernel_clone+0x2d7/0x940 kernel/fork.c:2771
__do_sys_clone kernel/fork.c:2913 [inline]
__se_sys_clone kernel/fork.c:2897 [inline]
__x64_sys_clone+0x1b6/0x230 kernel/fork.c:2897
do_syscall_x64 arch/x86/entry/syscall_64.c:61 [inline]
do_syscall_64+0x166/0x520 arch/x86/entry/syscall_64.c:84
entry_SYSCALL_64_after_hwframe+0x77/0x7f
page last free pid 805 tgid 805 ts 42732995302 stack trace:
reset_page_owner include/linux/page_owner.h:26 [inline]
__free_pages_prepare mm/page_alloc.c:1418 [inline]
__free_frozen_pages+0xc93/0xd90 mm/page_alloc.c:2962
__slab_free+0x274/0x2c0 mm/slub.c:5823
qlink_free mm/kasan/quarantine.c:163 [inline]
qlist_free_all+0x99/0x100 mm/kasan/quarantine.c:179
kasan_quarantine_reduce+0x148/0x160 mm/kasan/quarantine.c:286
__kasan_slab_alloc+0x22/0x80 mm/kasan/common.c:361
kasan_slab_alloc include/linux/kasan.h:253 [inline]
slab_post_alloc_hook mm/slub.c:4683 [inline]
slab_alloc_node mm/slub.c:4996 [inline]
__kmalloc_cache_noprof+0x29f/0x600 mm/slub.c:5559
_kmalloc_noprof include/linux/slab.h:991 [inline]
_kzalloc_noprof include/linux/slab.h:1312 [inline]
drm_atomic_commit_alloc+0xa9/0x100 drivers/gpu/drm/drm_atomic.c:258
drm_atomic_helper_dirtyfb+0x129/0xfd0 drivers/gpu/drm/drm_damage_helper.c:128
drm_fbdev_shmem_helper_fb_dirty+0x160/0x310 drivers/gpu/drm/drm_fbdev_shmem.c:117
drm_fb_helper_fb_dirty drivers/gpu/drm/drm_fb_helper.c:339 [inline]
drm_fb_helper_damage_work+0x84c/0xf20 drivers/gpu/drm/drm_fb_helper.c:365
process_one_work kernel/workqueue.c:3396 [inline]
process_scheduled_works+0xc3d/0x1630 kernel/workqueue.c:3479
worker_thread+0xa47/0xfb0 kernel/workqueue.c:3560
kthread+0x38b/0x480 kernel/kthread.c:436
ret_from_fork+0x514/0xb70 arch/x86/kernel/process.c:158
ret_from_fork_asm+0x1a/0x30 arch/x86/entry/entry_64.S:245
Memory state around the buggy address:
ffff888111a3d400: fc fc fc fc 00 00 00 00 00 00 00 00 00 00 00 00
ffff888111a3d480: 00 00 00 00 00 00 00 00 00 00 00 00 00 fc fc fc
>ffff888111a3d500: fc fc fc fc fc fa fb fb fb fb fb fb fb fb fb fb
^
ffff888111a3d580: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fc fc
ffff888111a3d600: fc fc fc fc fc fc fa fb fb fb fb fb fb fb fb fb
==================================================================***
If these findings have caused you to resend the series or submit a separate fix, please add the following tag to your commit message:
---
This report is generated by a bot. It may contain errors. syzbot ci engineers can be reached at [email protected].
To test a fix for this bug, please reply with #syz test (on a separate line) and attach the patch to the email.
Notes:
- The patch will be applied on top of the tested series (as an incremental fix).
- To test a new version of the whole series, please send it directly to [email protected].
- Arguments like custom git repos and branches are not supported.
Quoted 29 lines · Salvatore Dipietro
Since iomap gained per-block dirty tracking, a large folio can be partially dirty: struct
iomap_folio_staterecords exactly which blocks are dirty, and writeback only writes those ranges. The mm dirty accounting, however, still charges the whole folio even if a single block is dirty (up to 512x over-accounting for a 2 MB folio over 4 KB blocks).
balance_dirty_pages()then throttles writers against a number that is unrelated to how much data actually needs writing back. On workloads that repeatedly dirty small ranges of large folios -- e.g. PostgreSQL, which writes mostly 8/16 KB pages --dirty_threshis crossed and writers are throttled long before the real dirty data justifies it. On the benchmark below, run on v7.3-rc7, the unpatched kernel charges ~159 TB of dirtied pages while writing ~6 TB to the array, a factor of 27; with this series the dirtied pages charged match the data actually written.This series makes iomap charge and discharge the mm dirty counters per dirty page for folios that carry per-block dirty state, so a partially dirty large folio is accounted for the dirty part only:
- Patch 1 adds the mm infrastructure: an
AS_DIRTY_PER_BLOCKmapping flag, an @accounted argument to__folio_mark_dirty()and__filemap_dirty_folio()to skip the generic per-folio charge, and anaddress_space_operations::accounted_dirty_pages()callback used by the discharge and migration paths instead offolio_nr_pages(). No filesystem opts in, so it is a no-op on its own.
Quoted 3 lines
- Patch 2 makes iomap charge per dirty page from the per-block dirty bitmap and wires
iomap_accounted_dirty_pages()into every iomap-based filesystem.
This feels to me like a pretty gross layering violation.
iomap is tracking dirty filesystem block state, for the purposes of efficiently writing back dirty blocks.
iomap was designed to keep filesystem state entirely separate from the page cache, including the tracking of sub-page dirty filesystem state. One of the underlying design principles of iomap (all those years ago) was to avoid needing the page cache to know anything about filesystem block sizes at all. having the page cache track anything at filesystem block granularity was inefficient, wasteful in terms of memory needed to track each block, had coherency problems with filesystem state vs cached mm/pagecache state, etc.
iomap tracks block dirty state per folio for writeback efficiency, not for pagecache drity tracking optimisation. Large folios are a pagecache optimisation, and they were really only made possible by the isolation iomap provides between filesystem state and page cache state.
Pushing the mm dirty folio accounting implementations directly into iomap breaks that isolation - it once again tightly couples the filesystem dirty block tracking to mm pagecache accounting and accounting. Hence I think this approach is a non-starter - nothing should bleed across the filemap interfaces in either direction....
Quoted 5 lines
This was benchmarked with PostgreSQL using the pgbench simple-update workload on v7.3-rc7. Average throughput rises 46.8% (139.8k -> 205.2k tps) and run-to-run variability drops from a 23.60% to a 3.98% coefficient of variation: the worst iteration improves from 97.9k to 191.5k tps, while the best gains 8%, 199.4k -> 215.9k.
If postgresql is only doing 8/16kb writes, then how is it getting the page cache populated with large folios? That's the underlying fundamental problem here, yes?
I ask, because iomap caps the folio size to the write() IO length, so for 8/16kB writes it will only be asking for 8-16kB folios and so there won't be huge 2MB folios in the page cache to cause issues. Hence there must be something else populating the cache first....
Quoted 19 lines
Ten iterations per kernel, same database and workload (tps):
Kernel Avg Min Max CV iters iters
1-5 6-10 ______________________ ______ ______ ______ ______ ______ ______ v7.3-rc7 139.8k 97.9k 199.4k 23.60% 164.4k 115.2k v7.3-rc7 + this series 205.2k 191.5k 215.9k 3.98% 200.1k 210.2kOn unpatched v7.3-rc7 the worst iteration lands ~51% below the best, and throughput decays as the run progresses: iterations 6-10 average 30% below iterations 1-5. With this series the decay is gone -- the second half is similar to the first -- and the coefficient of variation stays at 3.98%.
The over-accounting has existed since commit
4ce02c679722("iomap: Add per-block dirty state tracking to improve performance"), merged in v6.6, where the ifs bitmap started recording partial dirty state while the mm counters kept charging whole folios.
Quoted 5 lines
The throughput collapse bisects to the v6.17 readahead series, first bad commit
c4602f9fa77f("mm/readahead: store folio order in structfile_ra_state"), which lets readahead stay at the largest folio order once it has ramped up, so a single dirty block charges far more than is written.
.... and that implies there is a sequential read portion of the benchmark that is first populating the page cache with large folios.
Do you get the same sort of improvement if you make postgres use POSIX_FADV_RANDOM on these files? This will cap the size of folios in the cache to whatever the postgresql read() IO size is. Yes, it will slow down whatever the sequential read portion of the benchmark is, but I don't care about that right now.
What I want to know is if the application preventing readahead from populating large folios gets you back all the write performance without needing to modify any kernel code at all. i.e. if we make a different choice for initial folio sizes in readahead, then does the write performance improve?
Alternatively, if there is distinct sequential read vs random write phases to postgres behaviour, then does issuing POSIX_FADV_DONTNEED between them restore the random write performance?
If choosing smaller folios for readhaead makes the problem go away, then the answer may be to add FADV_RANDOM_WRITE which allows full readahead but caps page cache folio size to, say, 64kB. That would allow sequential buffered reads to run at full speed, prevent the worst of the issues with PAGE_SIZE folios in the page cache, but also not perform terribly for random 8-16kB writes....
Indeed, we could use the fadvise64(count) parameter for something like FADV_RANDOM_WRITE to provide an IO size hint that would be used to derive the folio size we use for that file during readahead....
Cheers,
Dave.
Signature · 2 lines
Dave Chinner [email protected]