mm: batch per-task lruvec stat updates on the writeback path
Subsystems (7)
PATCH 1/1 mm: batch per-task lruvec stat updates on the writeback path
The writeback path updates two lruvec stats per folio through the memcg rstat machinery: NR_FILE_DIRTY when a folio is dirtied and again when writeback clears it, and NR_WRITEBACK when writeback starts on it. Consecutive folios almost always share a lruvec, so the same counters are updated over and over. On a 4k buffered write + fsync workload __mod_memcg_lruvec_state() is about 8% of the profile.
Hold those deltas in the task instead and apply them through mod_lruvec_state() once a counter would grow past 64 pages. Three task_struct fields hold the pending delta: a lruvec pointer and two signed counters, 16 bytes that fit in existing padding, and nothing without CONFIG_MEMCG. Besides the size limit, the batch is flushed when a folio from another lruvec arrives, before balance_dirty_pages() reads the dirty stats, at file_write_and_wait_range() entry before it writes back and waits, when a writeback round ends, and on task exit. The per-folio RCU section, folio_memcg() and mem_cgroup_lruvec() lookup stay; only the update through the lruvec is batched.
A task therefore applies its own pending delta before its dirty throttling decision and before its own writeback-and-wait, so neither runs with the task's own pages missing from the counters. Deltas pending in other tasks are not visible until those tasks flush, so a counter can lag by up to 64 pages per task and item. That is a fixed amount, so it matters in proportion to the dirty threshold: 64 tasks that each dirty a few pages and then idle hide 7.4MB, which is 7.2% of the threshold of a 512M memcg at dirty_ratio=20 and 29% of it at 256M and dirty_ratio=10. I was not able to measure whether this delays another writer's throttling; see below the ---.
fio 3.36 on ext4 in a 16 vCPU arm64 guest, raw block backend, pinned to one NUMA node, in a cgroup v2, 6 runs per side over alternating boots:
seqwrite 4k +fsync: 547 -> 591 MiB/s (+7.9%), system 63.9 -> 59.7%
randwrite 4k +fsync: 550 -> 575 MiB/s (+4.6%)
1M blocks, fsync-per-write and sqlite synchronous=FULL do not change, and neither does anything with cgroup_disable=memory (p=0.31, n=12 per side). For one 256MB write+fsync in a non-root memcg, lruvec_stat_mod_folio() drops from 393464 to 196858 calls.
Those are call counts, not CPU time. A 384MiB buffered write with no fsync and periodic writeback off, where only the dirty side batches, drops lruvec_stat_mod_folio() from 196747 to 98443 and __mod_memcg_lruvec_state() from 297789 to 201019, and that is worth 1.27% fewer instructions and no measurable change in cycles.
In testing, memory.stat file_dirty followed a write in progress, matched the bytes written once it completed, and returned to zero after sync; a fork()+exit() writer and 200 short-lived writers accounted for the same number of pages as without the patch. No reports with DEBUG_VM, PROVE_LOCKING and DEBUG_ATOMIC_SLEEP, including on PREEMPT_RT.
---
Against 7.4-rc3. mod_lruvec_state() and lruvec_stat_mod_folio() are unchanged on mm-unstable and this patch does not touch mm/memcontrol.c, but I have not test-applied or built it on that tree.
Interaction with c78842919368 ("memcg: don't go through the lruvec for folio and kmem lruvec stat updates") in mm-unstable: that commit stops routing per-folio stat updates through the lruvec because lruvec->pgdat and mem_cgroup_per_node->memcg share cachelines with fields the lru_lock holder writes. This patch caches a lruvec and reads both fields in its flush path, so the two go in opposite directions at the API level. Caching memcg+nid here instead would need an exported helper, since mod_memcg_node_state() is static to mm/memcontrol.c; the css reference this patch takes would cover the lifetime either way. I have not measured that variant or the two changes stacked. I can respin it that way if you prefer.
The 7.4MB of hidden dirty state in the changelog is from 64 writers that each dirty a few pages and sleep (4 measurements, sd 92KB, zero without the patch). I could not turn that into a throttling
measurement: with periodic writeback off balance_dirty_pages() never reached its pause path on either kernel, and with dirty_ratio=10 in a 256M memcg it does throttle but throughput varied 5x between boots of the same kernel on this setup. It needs a bandwidth-limited backing device, which I don't have. If 29% of a small cgroup's threshold is too much, STAT_BATCH_MAX is the knob - lowering it cuts the staleness and the number of avoided updates together.
Only the writeback-start side of NR_WRITEBACK is batched. Completion keeps the existing direct update, since it may run in interrupt context, where current is not the task that owns the batch. That counter can therefore also read low by up to 64 pages per task, in the same direction as the NR_FILE_DIRTY lag.
Benchmarks, in addition to what the changelog describes:
seqwrite: fio --name=t --size=256M --ioengine=psync --rw=write \
--bs=4k --end_fsync=1
randwrite: same with --rw=randwriteCall counts come from the ftrace function tracer filtered to the one symbol (11MiB per-cpu buffer, overrun and dropped both zero), cross- checked with perf stat on a kprobe. They count the named symbol only, so inlined callers are missing and the numbers should not be composed with each other. The dirty-only comparison is a 384MiB buffered write with no fsync and periodic writeback off, PMU cycles and instructions, 3 groups of 5 runs per side.
Also built and booted with CONFIG_PREEMPT_RT=y, PROVE_LOCKING, DEBUG_VM and DEBUG_ATOMIC_SLEEP. CONFIG_DEBUG_VM=n and CONFIG_MEMCG=n build clean.
fs/fs-writeback.c | 3 + include/linux/mm.h | 6 ++ include/linux/sched.h | 11 ++++ kernel/exit.c | 2 + kernel/fork.c | 5 ++ mm/filemap.c | 2 + mm/page-writeback.c | 128 +++++++++++++++++++++++++++++++++++++++++- 7 files changed, 154 insertions(+), 3 deletions(-)
fs/fs-writeback.c +3 -0
@@ -2491,6 +2491,9 @@ static long wb_do_writeback(struct bdi_writeback *wb) wrote +=wb_check_background_flush (wb);clear_bit (WB_writeback_running, &wb->state); +/* Don't pin another cgroup's memcg via a pending batch while idle. */ +dirty_stat_flush_current (); +return wrote; }
include/linux/mm.h +6 -0
@@ -2134,6 +2134,12 @@ int folio_mc_copy(struct folio *dst, struct folio *src);unsigned long nr_free_buffer_pages (void ); +#ifdef CONFIG_MEMCG +void dirty_stat_flush_current (void ); +#else +static inline void dirty_stat_flush_current (void ) { } +#endif +/* Returns the number of bytes in this potentially compound page. */ static inline unsigned long page_size (const struct page *page) {
include/linux/sched.h +11 -0
@@ -67,6 +67,7 @@ struct cfs_rq;struct fs_struct ;struct io_context ;struct io_uring_task ; +struct lruvec ;struct mempolicy ;struct nameidata ;struct nsproxy ;
@@ -1476,6 +1477,16 @@ struct task_struct {int nr_dirtied_pause;/* Start of a write-and-pause period: */ unsigned long dirty_paused_when; +#ifdef CONFIG_MEMCG +/* +* Pending NR_FILE_DIRTY/NR_WRITEBACK lruvec deltas; the lruvec is +* kept alive by a css reference on its memcg (not for the root). +* See stat_batch_mod() in mm/page-writeback.c. +*/ +struct lruvec *stat_batch_lruvec; +int stat_batch_dirty; +int stat_batch_writeback; +#endif #ifdef CONFIG_LATENCYTOP int latency_record_count;
kernel/exit.c +2 -0
@@ -979,6 +979,8 @@ void __noreturn do_exit(long code)exit_nsproxy_namespaces (tsk);exit_task_work (tsk);exit_thread (tsk); +/* After exit_task_work(): a deferred fput() can still dirty pages. */ +dirty_stat_flush_current ();sched_autogroup_exit_task (tsk);cgroup_task_exit (tsk);
kernel/fork.c +5 -0
@@ -2412,6 +2412,11 @@ __latent_entropy struct task_struct *copy_process( p->nr_dirtied =0 ; p->nr_dirtied_pause =128 >> (PAGE_SHIFT -10 ); p->dirty_paused_when =0 ; +#ifdef CONFIG_MEMCG + p->stat_batch_lruvec =NULL ; + p->stat_batch_dirty =0 ; + p->stat_batch_writeback =0 ; +#endif p->pdeath_signal =0 ; p->task_works =NULL ;
mm/filemap.c +2 -0
@@ -781,6 +781,8 @@ int file_write_and_wait_range(struct file *file, loff_t lstart, loff_t lend)if (lend < lstart)return 0 ; +dirty_stat_flush_current (); +if (mapping_needs_writeback (mapping)) { err =filemap_fdatawrite_range (mapping, lstart, lend);/* See comment of filemap_write_and_wait() */
mm/page-writeback.c +125 -3
158 lines not on this page · raw message
Signature · 1 line
2.43.0
Matthew Wilcox
maintainerQuoted 6 lines · Xavier Xia
The writeback path updates two lruvec stats per folio through the memcg rstat machinery:
NR_FILE_DIRTYwhen a folio is dirtied and again when writeback clears it, andNR_WRITEBACKwhen writeback starts on it. Consecutive folios almost always share a lruvec, so the same counters are updated over and over. On a 4k buffered write + fsync workload__mod_memcg_lruvec_state()is about 8% of the profile.
Is this a realistic benchmark? Does it represent some real life workload, or did you just choose it because it shows the best benefit of this patch? This is a fairly significant chunk of extra code, and it'd be nice to know that it benefits a real-world use-case before applying it.
If the real world usecase is more "there's some pretty high overhead when flushing accumulated megabytes of dirtied page cache", then there are simpler solutions that don't involve messing with task_struct.
Hi Willy,
Thanks for the feedback. That's a fair concern.
The original fio benchmark uses 4K buffered writes with fsync at the end of each job, rather than after every write. The improvement is reproducible in that setup, but it is a synthetic workload.
I also tested extracting a tar archive and copying a tree of small files on ext4 backed by a ramdisk. Initial runs showed 4.3% and 3.5% reductions in wall time, respectively. However, these improvements were not consistent across independent boots, so I don't have convincing evidence of a real-world benefit that justifies the added complexity.
Further testing also uncovered correctness issues in the patch. Deferred NR_WRITEBACK increments can temporarily be missing from the counters while completion decrements are applied immediately, potentially affecting dirty throttling. I also reproduced 8-12 KiB of stale file_dirty accounting after fsync in a non-root memcg with periodic writeback disabled.
I explored a writeback-local alternative without modifying task_struct. Although it passed the correctness tests I ran, it did not demonstrate a reproducible end-to-end performance improvement.
Given these findings, I don't think the current patch is suitable for merging. Please consider it withdrawn.
Thanks,
Xavier
Quoted 17 lines · Matthew Wilcox
Quoted 6 lines · Xavier Xia
The writeback path updates two lruvec stats per folio through the memcg rstat machinery:
NR_FILE_DIRTYwhen a folio is dirtied and again when writeback clears it, andNR_WRITEBACKwhen writeback starts on it. Consecutive folios almost always share a lruvec, so the same counters are updated over and over. On a 4k buffered write + fsync workload__mod_memcg_lruvec_state()is about 8% of the profile.Is this a realistic benchmark? Does it represent some real life workload, or did you just choose it because it shows the best benefit of this patch? This is a fairly significant chunk of extra code, and it'd be nice to know that it benefits a real-world use-case before applying it.
If the real world usecase is more "there's some pretty high overhead when flushing accumulated megabytes of dirtied page cache", then there are simpler solutions that don't involve messing with
task_struct.
[email protected]
AI reviewThank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [Medium] mm: misplaced dirty_stat_flush_current() in file_write_and_wait_range() - [Medium] mm: unflushed…
Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Medium] mm: misplaced dirty_stat_flush_current() in file_write_and_wait_range()
- [Medium] mm: unflushed stat_batch_mod() batches pin memcg CSS in idle kernel threads
- [Medium] mm: deferred positive stat_batch_mod() deltas cause node counter underflow
--
commit 511c77828659ec57163ac423dd938977a7ca7614
Author: Xavier Xia <[email protected]>
mm: batch per-task lruvec stat updates on the writeback path
This commit batches per-task NR_FILE_DIRTY and NR_WRITEBACK lruvec stat updates in task_struct up to 64 pages, flushing when switching lruvecs, before dirty throttling, on writeback and task exit.
fs/fs-writeback.c static long wb_do_writeback(struct bdi_writeback *wb) · line 2498
Quoted 13 lines
fs/fs-writeback.c +3
-0@@ -2491,6 +2491,9 @@ static long wb_do_writeback(struct bdi_writeback *wb) wrote +=wb_check_background_flush (wb);clear_bit (WB_writeback_running, &wb->state); +/* Don't pin another cgroup's memcg via a pending batch while idle. */ +dirty_stat_flush_current (); +return wrote; }
[Severity: Medium]
Can kernel threads that start writeback outside wb_do_writeback() pin a removed cgroup's mem_cgroup css in current->stat_batch_lruvec while idle?
For example, kswapd calls shrink_folio_list() -> pageout() -> __swap_writeout() -> folio_start_writeback() -> stat_batch_mod(), which takes a css_tryget(&memcg->css) reference on non-root memcgs, and then sleeps in kswapd_try_to_sleep() without calling dirty_stat_flush_current(). The same happens in khugepaged via khugepaged_scan_mm_slot() -> filemap_write_and_wait_range() and in the workqueue rescuer branch of wb_workfn(), which calls writeback_inodes_wb() directly.
Also, inside wb_do_writeback(), dirty_stat_flush_current() runs after finish_writeback_work() has already woken completion waiters and after wb_writeback() and wb_check_background_flush() have checked wb_over_bg_thresh() with the flusher's own negative NR_FILE_DIRTY batch still unapplied.
[ ... ]
mm/filemap.c int file_write_and_wait_range(struct file *file, loff_t lstart, loff_t lend) · line 788
Quoted 13 lines
mm/filemap.c +2
-0@@ -781,6 +781,8 @@ int file_write_and_wait_range(struct file *file, loff_t lstart, loff_t lend)if (lend < lstart)return 0 ; +dirty_stat_flush_current (); +if (mapping_needs_writeback (mapping)) { err =filemap_fdatawrite_range (mapping, lstart, lend);/* See comment of filemap_write_and_wait() */
[Severity: Medium]
Should dirty_stat_flush_current() be called after writeback submission (for example in filemap_writeback() after do_writepages()) rather than at the entry of file_write_and_wait_range()?
Nothing in mapping_needs_writeback() or filemap_fdatawrite_range() reads NR_FILE_DIRTY or NR_WRITEBACK, so flushing before filemap_fdatawrite_range() only prevents a small write's positive NR_FILE_DIRTY delta from cancelling with folio_clear_dirty_for_io()'s negative delta. During filemap_fdatawrite_range(), current runs do_writepages() and buffers up to 64 pages of -NR_FILE_DIRTY and +NR_WRITEBACK in current->stat_batch_dirty and current->stat_batch_writeback while pinning memcg->css in current->stat_batch_lruvec. When __filemap_fdatawait_range() completes, __folio_end_writeback() decrements NR_WRITEBACK directly, and file_write_and_wait_range() returns with those deltas still unflushed and the memcg pinned. Sibling callers of filemap_writeback() such as filemap_write_and_wait_range() and filemap_flush() do not flush at all.
Quoted 4 lines
mm/page-writeback.c +0
-0
[ ... ]
Quoted 28 lines
mm/page-writeback.c +28
-0+static void stat_batch_mod (struct folio *folio,enum node_stat_item item, +long nr) +{ +struct task_struct *t = current; +struct mem_cgroup *memcg; +struct lruvec *lruvec; +bool pinned; +int *slot; + +rcu_read_lock (); + memcg =folio_memcg (folio); +/* An untracked folio has no lruvec, only a node. */ +if (!memcg) { +rcu_read_unlock (); +mod_node_page_state (folio_pgdat (folio), item, nr); +return ; + } + + lruvec =mem_cgroup_lruvec (memcg,folio_pgdat (folio)); + +/* current is not the owner in interrupt context. */ +if (unlikely (!in_task () || nr >STAT_BATCH_MAX || + nr < -STAT_BATCH_MAX )) { +mod_lruvec_state (lruvec, item, nr); +rcu_read_unlock (); +return ; + } +
mm/page-writeback.c bool noop_dirty_folio(struct address_space *mapping, struct folio *folio) · line 2695
Quoted 10 lines
mm/page-writeback.c +10
-0+ slot = item ==NR_FILE_DIRTY ? + &t->stat_batch_dirty : &t->stat_batch_writeback; + +if (likely (t->stat_batch_lruvec == lruvec && + *slot + nr <=STAT_BATCH_MAX && + *slot + nr >= -STAT_BATCH_MAX )) { + *slot += nr; +rcu_read_unlock (); +return ; + }
[Severity: Medium]
Can buffering positive NR_FILE_DIRTY and NR_WRITEBACK increments in task_struct drive the node and memcg counters negative when the matching decrements are applied unbatched?
When a task dirties up to 64 pages and truncates them, __folio_cancel_dirty() -> folio_account_cleaned() subtracts NR_FILE_DIRTY directly via lruvec_stat_mod_folio() while the positive increment is still held in current->stat_batch_dirty; similarly, __folio_end_writeback() subtracts NR_WRITEBACK directly while current->stat_batch_writeback holds the positive increment.
On !CONFIG_SMP kernels with CONFIG_MEMCG=y, global_node_page_state_pages(), lruvec_page_state(), and memcg_page_state() compile out their negative-to- zero clamp:
include/linux/vmstat.h:global_node_page_state_pages() {
long x = atomic_long_read(&vm_node_stat[item]);
#ifdef CONFIG_SMP
if (x < 0)
x = 0;
#endif
return x;
}A negative counter then wraps to ~ULONG_MAX, corrupting dirty throttling calculations in domain_dirty_avail() and balance_dirty_pages() as well as reported stats. Even on CONFIG_SMP, vmstat_refresh() only exempts NR_WRITEBACK from negative-counter warnings and will warn on negative vm_node_stat[NR_FILE_DIRTY], and cgroup v1 offline reparenting in reparent_memcg_lruvec_state_local() clamps a dying child's negative local counter to 0 while the task's later flush redirects its positive batch to the parent via get_non_dying_memcg_start(), permanently inflating the parent's local counter.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1