mm/mglru: frequency guided promotion (MGLRU-FG) and flag cleanup
Subsystems (20)
Kairui Song
maintainerv4 cover mm/mglru: frequency guided promotion (MGLRU-FG) and flag cleanup
Hi all, this cover letter is going to be very long, as it includes a systematic test and analysis. And moving this series out of RFC phase as almost all readings are positive, tested on at least five different platforms (desktop, large server, Android, x86_64 and arm64 boxes) covering typical benchmarks, database, real applications, and has good test reports from other individual testers. It's also pretty clear about the next steps, and this blocks or breaks nothing AFAIK, which should be a pure gain, improving the performance or reducing IO of many workloads by ~10-40%.
Still following the idea proposed at LSF/MM/BPF [1], based on current mm-new. Different workloads get a minor or dramatic improvement, while reducing the page flags usage by 1 bit. The gain here is mostly from a real improvement of LRU's ability to distinguish the hotter workingset. Tested across multiple servers of different archs, desktops, and Android.
It also fixes several long-standing issues including under-accounted PSI and poor workingset tracking (especially for page cache).
Test results (CLRU means classical LRU):
Build kernel test:
==================
Running make -j48 in a 3G memcg, using ZRAM as swap (256G, lzo-rle) and holding the kernel and build output on a NVMe drive, 3 runs of 5 swappiness configurations (15 builds per kernel) [2]; the patched version is better than mainline at every swappiness value, measuring the total on average:
real sys pgpgin pswpin pswpout refault_file refault_anon CLRU 1m39s 14m59s 21.47M 2.81M 11.47M 2.40M 2.87M Before 1m32s 9m18s 12.57M 2.10M 9.05M 476k 2.07M After 1m32s 9m01s 9.99M 1.62M 8.40M 369k 1.60M delta -0.4s -17s(-3%) -20.5% -22.4% -7.1% -22.4% -22.6%
Same -j48 test, disk swap instead of ZRAM (SSD-backed; the kernel and build output stay on NVMe). The regression reported for earlier revisions is gone:
it is now a small net win, with every I/O counter improved, at the cost of ~1% more system time spent on the extra promotion work:
real sys pgpgin pswpin pswpout refault_file refault_anon CLRU 4m22s 21m54s 36.80M 3.00M 10.56M 6.03M 3.05M Before 2m51s 10m12s 10.04M 1.55M 5.02M 416k 1.02M After 2m48s 10m18s 8.95M 1.41M 4.93M 341k 931k delta -4s(-2%) +6s(+1%) -10.9% -8.8% -1.8% -18.1% -9.0%
FIO cached read with zipf
=========================
Using an NVMe disk, in a 16G cgroup, total file size 40G, this measures the LRU's theoretical ability to distinguish the hotter portion, 3 test runs per config:
Using read()
------------
command: numactl --membind=0 --cpunodebind=0 \
fio --name=fg --numjobs=16 --nrfiles=1 \
--filename_format="/var/lib/kmultibench/realdk.\$jobnum.img" \
--size=2560M \
--buffered=1 --ioengine=sync --rw=randread \
--random_distribution=zipf:$ZIPF --bs=4k --time_based \
--ramp_time=45s --runtime=600s --group_reportingREADING: Avg IOPS (higher is better)
zipf:θ CLRU | MGLRU before (vs CLRU) | FG (vs CLRU) | Imprv. |
0.8 397,572| 396,046 ( -0.4%) | 449,714 (+13.1%) | +13.6% | 0.9 605,862| 602,201 ( -0.6%) | 692,524 (+14.3%) | +15.0% | 1.1 2,092,280| 2,122,415 ( +1.4%) | 2,457,564 (+17.5%) | +15.8% | 1.2 4,444,665| 4,513,839 ( +1.6%) | 5,066,901 (+14.0%) | +12.3% |
READING: refault/read (lower is better)
zipf:θ CLRU | MGLRU before (vs CLRU) | FG (vs CLRU) | Imprv. |
0.8 0.20108 | 0.20074 (-0.2%) | 0.17660 (-12.2%) | +12.0% | 0.9 0.13356 | 0.13186 (-1.3%) | 0.11522 (-13.7%) | +12.6% | 1.1 0.03641 | 0.03586 (-1.5%) | 0.03065 (-15.8%) | +14.5% | 1.2 0.01479 | 0.01466 (-0.8%) | 0.01230 (-16.9%) | +16.1% |
For typical read() following zipf distributions, MGLRU was basically the same as CLRU before or slightly worse in certain cases, now it's ~12-16% better and leading. Worth noting we also observed in certain systems MGLRU was worse than CLRU before in v2 - v3, which is now also optimized into a gain.
Using mmap
----------
command: numactl --membind=0 --cpunodebind=0 \
fio --name=fg --numjobs=16 --nrfiles=1 \
--filename_format="/var/lib/kmultibench/realdk.\$jobnum.img" \
--size=2560M \
--ioengine=mmap --rw=randread --fadvise_hint=0 \
--random_distribution=zipf:$ZIPF --bs=4k --time_based \
--ramp_time=45s --runtime=600s --group_reportingREADING: Avg IOPS (higher is better)
zipf:θ CLRU | MGLRU before (vs CLRU) | FG (vs CLRU) | Imprv. |
0.8 1,521,315| 3,610,516 (+137.3%) | 3,980,874 (+161.7%) | +10.3% | 0.9 926,158| 3,856,644 (+316.4%) | 4,423,859 (+377.7%) | +14.7% | 1.1 2,303,035| 2,225,641 ( -3.4%) | 2,715,460 (+17.9%) | +22.0% | 1.2 5,015,274| 4,811,580 ( -4.1%) | 5,357,325 ( +6.8%) | +11.3% |
READING: refault/read (lower is better)
zipf:θ CLRU | MGLRU before (vs CLRU) | FG (vs CLRU) | Imprv. |
0.8 0.05403| 0.02009 (-62.8%) | 0.01805 (-66.6%) | +10.2% | 0.9 0.08937| 0.01899 (-78.8%) | 0.01638 (-81.7%) | +13.8% | 1.1 0.03549| 0.03644 ( +2.7%) | 0.02925 (-17.6%) | +19.7% | 1.2 0.01529| 0.01569 ( +2.6%) | 0.01375 (-10.1%) | +12.4% |
For typical mmap read of file following zipf distributions, MGLRU was behaving much better for theta < 1 and with a slight regression for theta > 1. And FG greatly improved both cases, no more regression in any case with an improvement ~10-20%.
Worth noting, without fadvise_hint=0, we will see a regression like this:
zipf:θ CLRU | MGLRU before (vs CLRU) | FG (vs CLRU) | Imprv. |
1.1 1,873,230| 1,641,981 (-12.3%) | 1,648,997 (-12.0%) | +0.4% |
That's because MGLRU deliberately disables hotness tracking for MADV_RANDOM areas and meanwhile for CLRU refault distance is still taking effect. I don't think this is an issue or blocker as that's exactly what the userspace asked and we also have plan to unify or improve shadow or refault distance usage [9], [10].
Tighter cache
-------------
command: following the mmap test, adjusting cgroup limit and zipf theta, 2 tests per case:
READING: Avg IOPS (higher is better)
memcg/θ CLRU | MGLRU before (vs CLRU) | FG (vs CLRU) | Imprv. |
16G/1.4 20,563,861| 20,408,851 ( -0.8%) | 21,314,656 ( +3.7%) | +4.4% | 8G/1.4 14,606,000| 13,650,929 ( -6.5%) | 14,603,348 ( 0.0%) | +7.0% | 4G/1.4 10,102,227| 9,392,019 ( -7.0%) | 9,992,258 ( -1.1%) | +6.4% | 12G/1.2 3,688,008| 3,502,117 ( -5.0%) | 3,795,627 ( +2.9%) | +8.4% | 8G/1.2 2,726,922| 2,511,410 ( -7.9%) | 2,735,389 ( +0.3%) | +8.9% | 4G/1.2 1,906,548| 1,672,370 (-12.3%) | 1,785,545 ( -6.3%)*| +6.8% | 12G/1.1 1,618,437| 1,520,102 ( -6.1%) | 1,641,287 ( +1.4%) | +8.0% | 8G/1.1 1,209,058| 1,100,118 ( -9.0%) | 1,196,796 ( -1.0%) | +8.8% | 6G/1.1 1,024,652| 910,669 (-11.1%) | 1,030,723 ( +0.6%) | +13.2% |
READING: refault per read (lower is better)
memcg:θ CLRU | MGLRU before (vs CLRU) | FG (vs CLRU) | Imprv. |
16G/1.4 0.00205 | 0.00210 ( +2.4%) | 0.00180 (-12.2%) | +14.3% | 8G/1.4 0.00392 | 0.00430 ( +9.7%) | 0.00379 ( -3.3%) | +11.9% | 4G/1.4 0.00645 | 0.00722 (+11.9%) | 0.00650 ( +0.8%) | +10.0% | 12G/1.2 0.02169 | 0.02245 ( +3.5%) | 0.02055 ( -5.3%) | +8.5% | 8G/1.2 0.02944 | 0.03209 ( +9.0%) | 0.02875 ( -2.3%) | +10.4% | 4G/1.2 0.04459 | 0.04897 ( +9.8%) | 0.04388 ( -1.6%)*| +10.4% | 12G/1.1 0.05159 | 0.05361 ( +3.9%) | 0.04907 ( -4.9%) | +8.5% | 8G/1.1 0.06830 | 0.07387 ( +8.2%) | 0.06708 ( -1.8%) | +9.2% | 6G/1.1 0.08064 | 0.08816 ( +9.3%) | 0.08046 ( -0.2%) | +8.7% |
It can be clearly seen that MGLRU was worse than CLRU before under tight cache usage, and with FG all cases improved. And the missing rate measured by refault per read shows FG is better than unpatched MGLRU and CLRU in almost every configuration.
If we re-run the only obvious regression, the 4G/1.2 case (*), with perf, the bottleneck is the lruvec lock, with the contention concentrated in try_to_shrink_lruvec() where the lazy promotion work happens:
command:
<same test command above, with 4G memcg and zipf:1.2, and below tracing> perf lock contention -ab -- sleep 355
READING (runtime=300s, 4G memcg, zipf:1.2):
config:θ IOPS | mean clat | sys% | lruvec lock total wait |
CLRU 1,868k| 8195 ns| 6.01%| ~10 s | MGLRU before 1,677k| 9173 ns| 7.25%| ~75 s | MGLRU after 1,837k| 8488 ns| 7.33%| ~78 s |
The wait column is a per-run total. MGLRU now promotes more folios either due to PID protection or FG promotion while holding the LRU lock. And FG achieves comparable or even better performance by reducing actual IO already, which is a net improvement compared to unpatched MGLRU. The remaining gap over CLRU is inherited lock cost, which can be reduced by batching and prefetching during scanning as demonstrated before [13] (and interestingly, you can see the benchmark kind of matches the improvement that I measured at that time).
MongoDB YCSB workloadb [3]
==========================
With recordcount:20000000 operationcount:6000000, threads:48, in a 16G memcg, 3 runs:
CLRU: 97,856.45 ops/s MGLRU Before: 85,702.39 ops/s (-12.4% vs CLRU) MGLRU After: 98,569.77 ops/s ( +0.7% vs CLRU) +15.0% vs Before
MGLRU was doing worse than CLRU before, now it's doing better.
Chromium & Node.js test [4]
===========================
Using ZRAM as swap, on a 48c96t machine with 128G memory, 64 workers, run for 1 hour:
Total requests:
CLRU: 63822 MGLRU Before: 130650 MGLRU After: 228864 (+75.1%)
Worth noting there seems to be some reclaim balance jitter for this test but MGLRU is far better already and now leading even more.
LevelDB Scan/Get
================
I also retested the LevelDB benchmark from the cache_ext paper [5]. Interestingly, mainline MGLRU already beats CLRU on this one after a recent change in lru_gen_folio_seq that bumps new folios with refs == 1 to the second-oldest generation as discussed. That change accidentally gave random reads a higher hotness level while making sequential reads much colder as described before [14]. However it's unreliable and incorrect because it depends on LRU drain timing, and hurts some workloads as reported, or where the sequential part is actually hotter (any workload involving hotter large file and many small cold files will be affected) which is reproduced below.
This series improves it while covering ordinary workloads too and should fix regressions:
LevelDB Scan / Get, Throughput Total:
CLRU: 4708.3 ops/s MGLRU: 5026.9 ops/s (faster than CLRU, but hurts other workloads) MGLRU After: 5179.2 ops/s (even better in all cases, and no regression)
The hot-sequential and cold-random workload can be easily reproduced with SQLite and grep. SQLite continuously scans and looks up a small hot portion of a DB file, while grep iterates over a set of small files much larger than RAM [6]:
SQLite scan & lookup time: Grep iterate time:
CLRU: 14.51ms 13281.37ms MGLRU mainline: 567.05ms 13694.47ms MGLRU After this series: 10.58ms 12930.43ms
The grep cold portion is larger than RAM and accessed only once per iteration, so there's no promotion of any of it. CLRU handles this reasonably; mainline MGLRU has a clear regression; MGLRU-FG now not only recovers but is able to catch some hot parts from the cold grep workload. This test is somewhat subjective, but the signal is clear.
Android (For reference)
=======================
Testing on Android is quite difficult: lack of mainline support, and it is very noisy with real apps to get a stable result. I did an informal backport of the latest MGLRU-FG patches onto the 6.1 GKI tree of a Pixel 9 Pro (16 GB RAM, 8 GB ZRAM, Android 17), preserving the frozen kABI layouts so the implementation is limited (see the code here [15]). The "before" and "after" kernels share the same base and differ only by the FG series: the "before" tree has MGLRU aligned to the current upstream code, so that unrelated backport deltas cancel out. (And BTW that alignment also improved the performance by a lot, which matches the report from previous MGLRU reclaim optimization series [12]).
The workload is a churn loop driven over adb: 34 common apps and 20 Chrome tabs are launched and cycled, with a brief scroll per app during the cold build of each iteration, 16 iterations per run, about one hour per run. The loop exhausts memory in every iteration (zram peaks at 6.9-7.8 GB of 8 GB, MemFree down to 130-335 MB in every run). The two kernels are run in an interleaved rotation and compared both on matched per-iteration samples (same period, same iteration index) and on paired run totals, which cancels most of the run-to-run drift. I've repeated the test for several days and times getting similar results.
The memory-management stack in Android is built around the non-FG MGLRU behaviour, and the 6.1 base lacks some of the upstream infrastructure. Even so, FG holds its own, it lowers reclaim traffic on both the file and the anon side:
Before After Delta 95% CI Avg Improv.
-----------------------------------------------------------------------
workingset_refault_anon 1.43M 1.25M [-23%, -3%] +12% workingset_refault_file 1.54M 1.39M [-17%, +2%] +10% pgscan_anon 4.04M 3.56M [-20%, -5%] +12% pgsteal_anon 1.64M 1.45M [-23%, -1%] +12% pgscan_file 7.49M 6.52M [-17%, -5%] +13% pgsteal_file 6.55M 5.63M [-18%, -7%] +14% pswpout 1.82M 1.62M [-22%, -1%] +11% pgpgin 23.56M 20.33M [-18%, -7%] +14% pgmajfault 1.61M 1.42M [-21%, -4%] +12% pgpgout 3.39M 3.48M [ +0%, +5%] -3%
"Before" is the aligned tree without the FG series, "After" adds FG. The numbers are trimmed means over the 12 interleaved runs per kernel: for each counter's avg, the highest and lowest run are dropped and the middle ten averaged. Each counter is the vmstat delta of one full run. The 95% CI is a bootstrap over the 12 rounds of the paired run-total ratio (After vs Before).
The environment is noisy, but given the fact that every counter except pgpgout is improved by ~10% on average and the 95% CI reading is also looking good, and we have been seeing positive readings since v2 of this series, I think we can safely say that this series reduced IO by about 10% for the same Android workload and has a very positive effect on it.
I also ran the Android Jank test from Zicheng [7] on this device (chrome scroll, FrameTimeline), plus a 34-app keepalive run. No obvious difference was observed: the run-mean chrome scroll fps of every kernel sits in a 100.6-103.6 band on a 120 Hz panel, and the jank ratios are all below 8% per scroll round with no consistent ordering across kernels. The keepalive test does not discriminate on this build: 31-32 of 34 apps stay alive with every kernel. On the previous build a run kept slightly more apps alive with FG (average 4.8 vs 4.5, peak 23 vs 20), that could be noise or a slight improvement. Both kernels saturate all 8 cores with no obvious CPU usage difference (99.8-99.9% utilization, ~518s busy per 65s window).
I also did a test on another Android phone with a 5.15 kernel (Xperia 1 V, code here [16]), which has all apps in one global memcg (this Pixel 9 Pro has each app in a separate memcg). The result looks much better there, either due to the memcg layout or the non-reclaiming anon shadow (the 6.1 kernel reclaims anon shadow). But in either case, the performance is a positive reading.
So in summary: with this revision we get lower file refaults, lower pgpgin, and lower anon reclaim and swap traffic.
Redis / Valkey
==============
Valkey in a 1.5G ARM64 VM using 8G ZRAM as swap:
valkey-server --maxmemory 2560M
redis-benchmark -r 3000000 -n 3000000 -d 1024 -c 12 -P 32 -t get
With BGSAVE running Without BGSAVE running
Before: 308356.47 RPS 431468.44 TPS After: 336300.34 RPS (+9.0%) 442151.81 TPS (+2.4%)
Looking good with some improvement, tested 3 times. Note on that VM we have
$ cat /sys/kernel/mm/lru_gen/enabled 0x0001
So page table walker is not available, but still working well.
Others
======
Additionally, PSI, smaps, and readahead should all benefit from better accuracy since this series unifies the flag usage between classical LRU and MGLRU.
Other tests such as MySQL are looking fine, with no regressions. There is also community test report [8].
Refault distance is not included yet, so MGLRU may respond more slowly to workingset shifts. That can be added later, as previously demonstrated [9], [10].
Extra note about future development: this series is actually highly compatible with ideas like workingset reporting [11]. The "gen climbing folio" design may appear to conflict with workingset reporting's idea, but it doesn't. The solution is simple and straightforward: once we can extend the generation number to a larger value (e.g. 64 or 128), the refs-driven promotion can stop at a lower gen (e.g. oldest_gen + 16), leaving the remaining newer generations as perfectly time-gap-separated bins.
The tier count is not fixed either; we'll need to find a way to tune it if tiers go beyond 4 though, but that shouldn't be hard, not a blocker either.
More details are in the individual commit messages. LLM is used to help improve the comments and tests; all results are double checked.
---
Changes in v4:
- Defer folios at the tail of their LRU instead of min_seq only:
https://lore.kernel.org/linux-mm/CAMgjq7AOhDkuZZnWrGDguMvNtarZ7s0Ouzs1xYi2O4AkPEPbTQ@mail.gmail.com/
- Re-read max_seq inside the folio_inc_lru_refs_walk() cmpxchg loop, and apply the reparent fix before the lockless change.
- Tidy up a few code shuffles.
- Use generic refs-based helper for smaps, DAMON, khugepaged
and madvise with better kdocs.
- Add community Tested-by tags for unchanged parts.
- Link to v3: https://patch.msgid.link/[email protected]
Changes in v3:
- Micro-optimization for page flags operations: if the flags are unchanged after calculation, skip the cmpxchg.
- Avoid touching folio_activate even in the cold path. I tried multiple ways for that lockless promotion, PG_lru in the earlier RFC, and previous folio_activate, the new speculative barrier + retry seem the best solution.
- Apply tier cap for MADV_PAGEOUT.
- Only promote folio during page table walk or rmap if the folio
is in the min gen. May be worth trying to enlarge the range to (max_seq - MIN_NR_GENS) in the next version.
- Fix a potential folio leak caused by reparenting.
- Retest shows great results especially for the Android case.
- Link to v2: https://patch.msgid.link/[email protected]
Changes in v2:
- Rebased; dropped v1 03/05/06 (already upstream), folded v1 01 and 07 into patches 01 and 04; new patches 06, 07, 10, 12, 13.
- Make folio_test_workingset() itself arbitrate, dropping the parallel folio_is_* helpers; convert the last raw PageWorkingset() user (erofs). (Johannes)
- Use LRU_REF_MAPPED/LRU_REF_EXEC flags instead of is_fault/is_exec booleans. (Barry)
- Fix syzbot "WARNING in folio_inc_lru_refs" on off-LRU folios.
- Account active/inactive per folio from refs, not the gen window:
/proc/vmstat and memory.stat no longer jump on aging or reverse on swapless machines.
- Make folio_inc_lru_refs() lockless; add folio_inc_lru_refs_fast()
for the gup fast paths.
- Convert DAMON and khugepaged to the refs-based operations.
- Drop the lru_size WARN_ON_ONCE() and lockdep_assert_held(): the counter is lockless now, so transient negatives are expected.
- Link to v1: https://patch.msgid.link/[email protected]
---
Kairui Song (17):
mm/memcontrol: allow update of LRU statistic without holding LRU lock mm/mglru: make generation page counters atomic
mm/memcg: add folio-based lruvec live helper
mm/mglru: frequency guided workingset promotion (MGLRU-FG) mm/mglru: make folio lru referenced times count a generic API mm/mglru: move add/del LRU size accounting out of lru_gen_update_size() mm/mglru, gup: mark folios referenced via a fast helper mm/mglru, smaps: convert to LRU refs based operations for MGLRU mm/damon: convert to LRU refs based operations for MGLRU mm/khugepaged: convert to LRU refs based operations for MGLRU mm/madvise: adapt for LRU refs based operations for MGLRU mm/huge_memory: mark folio as accessed more accurately on split mm/mglru: folio LRU refs based active/inactive number accounting mm/mglru: reparent folios from all generations
mm/mglru: make folio_inc_lru_refs lruvec lockless
mm/mglru: make folio_test_workingset() work based on folio LRU refs Documentation/mm: multi-gen LRU: update for frequency guided promotion
Documentation/admin-guide/mm/multigen_lru.rst | 4 +- Documentation/mm/multigen_lru.rst | 57 +-- fs/btrfs/compression.c | 1 + fs/erofs/zdata.c | 3 +- fs/proc/task_mmu.c | 6 +- include/linux/memcontrol.h | 39 ++ include/linux/mm_inline.h | 354 ++++++++++++------ include/linux/mmzone.h | 169 ++++++--- include/linux/page-flags.h | 2 - kernel/bounds.c | 2 +- mm/damon/paddr.c | 3 +- mm/filemap.c | 1 + mm/folio.c | 85 +---- mm/gup.c | 6 +- mm/huge_memory.c | 8 +- mm/khugepaged.c | 4 +- mm/madvise.c | 57 ++- mm/migrate.c | 2 - mm/page_io.c | 1 + mm/vmscan.c | 520 +++++++++++++++++--------- mm/workingset.c | 45 ++- 21 files changed, 875 insertions(+), 494 deletions(-)
---
base-commit: 71a9b024444eba184335b67867897714e4da143c
change-id: 20260722-mglru-fg-3a2c8574725b
Best regards,
Signature · 1 line
Kairui Song <[email protected]>
Kairui Song
maintainerPATCH v4 1/17 mm/memcontrol: allow update of LRU statistic without holding LRU lock
To enable moving file pages in folio_mark_accessed directly and lazily for MGLRU, allow updating the LRU statistic atomically without holding a lock. It may cause temporary counter underflow, which should be fine as we still follow final consistency of the counter, and it only serves as a estimated metrics, a little inaccuracy has no visible effect.
--- include/linux/mm_inline.h | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
include/linux/mm_inline.h +1 -2
@@ -47,11 +47,10 @@ static __always_inline void __update_lru_size(struct lruvec *lruvec, {struct pglist_data *pgdat =lruvec_pgdat (lruvec); -lockdep_assert_held (&lruvec->lru_lock);WARN_ON_ONCE (nr_pages != (int )nr_pages);mod_lruvec_state (lruvec,NR_LRU_BASE + lru, nr_pages); -__mod_zone_page_state (&pgdat->node_zones[zid], +mod_zone_page_state (&pgdat->node_zones[zid],NR_ZONE_LRU_BASE + lru, nr_pages); }
Signature · 1 line
2.56.0
[email protected]
AI reviewRe: [PATCH v4 01/17] mm/memcontrol: allow update of LRU statistic without holding LRU lock
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 9 lines
From: Kairui Song <[email protected]>
To enable moving file pages in
folio_mark_accesseddirectly and lazily for MGLRU, allow updating the LRU statistic atomically without holding a lock. It may cause temporary counter underflow, which should be fine as we still follow final consistency of the counter, and it only serves as a estimated metrics, a little inaccuracy has no visible effect.Signed-off-by Kairui Song <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
Barry Song (Xiaomi)
reviewerPATCH v4 1/17 mm/memcontrol: allow update of LRU statistic without holding LRU lock
In reply to Kairui SongQuoted 8 lines · On Fri, Oct 16, 2026 at 2:15 AM Kairui Song via B4 Relay…
From: Kairui Song <[email protected]>
To enable moving file pages in
folio_mark_accesseddirectly and lazily for MGLRU, allow updating the LRU statistic atomically without holding a lock. It may cause temporary counter underflow, which should be fine as we still follow final consistency of the counter, and it only serves as a estimated metrics, a little inaccuracy has no visible effect.
This might be a good idea. Updating the LRU size without holding lru_lock could open up possibilities for further optimizations.
Recently, I've been thinking about something in the aging path. For example, suppose a folio belongs to the root memcg and is heavily shared by some of its descendant memcgs, which also access it.
Currently, aging in those descendant memcgs will simply skip this folio. Eventually, we'll have to rely on the rmap of the root memcg to determine whether the folio is hot or cold within the root memcg.
Since the shared folio may have a very large mapcount, walking its rmap could be quite expensive.
So I've been thinking about this and put together some very PoC code. It doesn't really work; it's just meant to illustrate what I have in mind:
mm/vmscan.c +7 -7
@@ -3618,7 +3618,7 @@ static struct folio *get_pfn_folio(unsigned long pfn, struct mem_cgroup *memcg,return NULL ;rcu_read_lock (); -if (folio_memcg (folio) != memcg) +if (!mem_cgroup_is_descendant (memcg,folio_memcg (folio))) folio =NULL ;rcu_read_unlock ();
@@ -3723,7 +3723,7 @@ static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,continue ;if (last != folio) { -walk_update_folio (walk, args->vma, walk->lruvec, last, dirty); +walk_update_folio (walk, args->vma,folio_lruvec (last), last, dirty); last = folio; dirty = false;
@@ -3736,7 +3736,7 @@ static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end, walk->mm_stats[MM_LEAF_YOUNG ] += nr; } -walk_update_folio (walk, args->vma, walk->lruvec, last, dirty); +walk_update_folio (walk, args->vma,folio_lruvec (last), last, dirty); last =NULL ;if (i <PTRS_PER_PTE &&get_next_vma (PMD_MASK ,PAGE_SIZE , args, &start, &end))
@@ -3812,7 +3812,7 @@ static void walk_pmd_range_locked(pud_t *pud, unsigned long addr, struct vm_area goto next;if (last != folio) { -walk_update_folio (walk, vma, walk->lruvec, last, dirty); +walk_update_folio (walk, vma,folio_lruvec (last), last, dirty); last = folio; dirty = false;
@@ -3826,7 +3826,7 @@ static void walk_pmd_range_locked(pud_t *pud, unsigned long addr, struct vm_area i = i >MIN_LRU_BATCH ?0 :find_next_bit (bitmap,MIN_LRU_BATCH , i) +1 ; }while (i <=MIN_LRU_BATCH ); -walk_update_folio (walk, vma, walk->lruvec, last, dirty); +walk_update_folio (walk, vma,folio_lruvec (last), last, dirty);lazy_mmu_mode_disable ();spin_unlock (ptl);
@@ -4499,7 +4499,7 @@ bool lru_gen_look_around(struct page_vma_mapped_walk *pvmw, unsigned int nr)continue ;if (last != folio) { -walk_update_folio (walk, vma, lruvec, last, dirty); +walk_update_folio (walk, vma,folio_lruvec (last), last, dirty); last = folio; dirty = false;
@@ -4511,7 +4511,7 @@ bool lru_gen_look_around(struct page_vma_mapped_walk *pvmw, unsigned int nr) young += nr; } -walk_update_folio (walk, vma, lruvec, last, dirty); +walk_update_folio (walk, vma,folio_lruvec (last), last, dirty);lazy_mmu_mode_disable ();
We may want to explore this after mglru-fg. What are your thoughts on this?
Quoted 25 lines
Signed-off-by Kairui Song <[email protected]>--- include/linux/mm_inline.h | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)include/linux/mm_inline.h +1
-3@@ -47,11 +47,10 @@ static __always_inline void __update_lru_size(struct lruvec *lruvec, {struct pglist_data *pgdat =lruvec_pgdat (lruvec); -lockdep_assert_held (&lruvec->lru_lock);WARN_ON_ONCE (nr_pages != (int )nr_pages);mod_lruvec_state (lruvec,NR_LRU_BASE + lru, nr_pages); -__mod_zone_page_state (&pgdat->node_zones[zid], +mod_zone_page_state (&pgdat->node_zones[zid],NR_ZONE_LRU_BASE + lru, nr_pages); } --
Quoted 3 lines
2.56.0
Best,
Barry
Kairui Song
maintainerPATCH v4 2/17 mm/mglru: make generation page counters atomic
In reply to Kairui SongNo feature change, convert them to atomic so we can update them without holding the LRU lock. There is no risk of overflow. The reader always compares and uses zero instead if the counter values are negative. It follows final consistency.
--- include/linux/mm_inline.h | 6 ++---- include/linux/mmzone.h | 2 +- mm/vmscan.c | 27 ++++++++++++--------------- 3 files changed, 15 insertions(+), 20 deletions(-)
include/linux/mm_inline.h +2 -4
@@ -265,11 +265,9 @@ static inline void lru_gen_update_size(struct lruvec *lruvec, struct folio *foliVM_WARN_ON_ONCE (old_gen ==-1 && new_gen ==-1 );if (old_gen >=0 ) -WRITE_ONCE (lrugen->nr_pages[old_gen][type][zone], - lrugen->nr_pages[old_gen][type][zone] - delta); +atomic_long_sub (delta, &lrugen->nr_pages[old_gen][type][zone]);if (new_gen >=0 ) -WRITE_ONCE (lrugen->nr_pages[new_gen][type][zone], - lrugen->nr_pages[new_gen][type][zone] + delta); +atomic_long_add (delta, &lrugen->nr_pages[new_gen][type][zone]);/* addition */ if (old_gen <0 ) {
include/linux/mmzone.h +1 -1
@@ -554,7 +554,7 @@ struct lru_gen_folio {/* the multi-gen LRU lists, lazily sorted on eviction */ struct list_head folios[MAX_NR_GENS ][ANON_AND_FILE ][MAX_NR_ZONES ];/* the multi-gen LRU sizes, eventually consistent */ -long nr_pages[MAX_NR_GENS ][ANON_AND_FILE ][MAX_NR_ZONES ]; +atomic_long_t nr_pages[MAX_NR_GENS ][ANON_AND_FILE ][MAX_NR_ZONES ];/* the exponential moving average of refaulted */ unsigned long avg_refaulted[ANON_AND_FILE ][MAX_NR_TIERS ];/* the exponential moving average of evicted+protected */
mm/vmscan.c +12 -15
@@ -3495,8 +3495,7 @@ static void reset_batch_size(struct lru_gen_mm_walk *walk)continue ; walk->nr_pages[gen][type][zone] =0 ; -WRITE_ONCE (lrugen->nr_pages[gen][type][zone], - lrugen->nr_pages[gen][type][zone] + delta); +atomic_long_add (delta, &lrugen->nr_pages[gen][type][zone]);if (lru_gen_is_active (lruvec, gen)) lru +=LRU_ACTIVE ;
@@ -4116,11 +4115,8 @@ static bool inc_min_seq(struct lruvec *lruvec, int type, int swappiness)break ; }flush_lru_batch (head, &batch_end, target_list); - -WRITE_ONCE (lrugen->nr_pages[old_gen][type][zone], - lrugen->nr_pages[old_gen][type][zone] - delta); -WRITE_ONCE (lrugen->nr_pages[target_gen][type][zone], - lrugen->nr_pages[target_gen][type][zone] + delta); +atomic_long_sub (delta, &lrugen->nr_pages[old_gen][type][zone]); +atomic_long_add (delta, &lrugen->nr_pages[target_gen][type][zone]);if (!remaining)return false; }
@@ -4225,8 +4221,8 @@ static bool inc_max_seq(struct lruvec *lruvec, unsigned long seq, int swappinessfor (type =0 ; type <ANON_AND_FILE ; type++) {for (zone =0 ; zone <MAX_NR_ZONES ; zone++) {enum lru_list lru = type *LRU_INACTIVE_FILE ; -long delta = lrugen->nr_pages[prev][type][zone] - - lrugen->nr_pages[next][type][zone]; +long delta =atomic_long_read (&lrugen->nr_pages[prev][type][zone]) - +atomic_long_read (&lrugen->nr_pages[next][type][zone]);if (!delta)continue ;
@@ -4344,7 +4340,8 @@ static unsigned long lruvec_evictable_size(struct lruvec *lruvec, int swappinessfor (seq = min_seq[type]; seq <= max_seq; seq++) { gen =lru_gen_from_seq (seq);for (zone =0 ; zone <MAX_NR_ZONES ; zone++) - total +=max (READ_ONCE (lrugen->nr_pages[gen][type][zone]),0L ); + total +=max (atomic_long_read (&lrugen->nr_pages[gen][type][zone]), +0L ); } }
@@ -4764,7 +4761,7 @@ static void __lru_gen_reparent_memcg(struct lruvec *child_lruvec, struct lruvecfor (i =0 ; i <get_nr_gens (child_lruvec, type); i++) {int gen =lru_gen_from_seq (child_lrugen->max_seq - i); -long nr_pages = child_lrugen->nr_pages[gen][type][zone]; +long nr_pages =atomic_long_read (&child_lrugen->nr_pages[gen][type][zone]);int child_lru_active =lru_gen_is_active (child_lruvec, gen) ?LRU_ACTIVE :0 ;int parent_lru_active =lru_gen_is_active (parent_lruvec, gen) ?LRU_ACTIVE :0 ;
@@ -4772,9 +4769,8 @@ static void __lru_gen_reparent_memcg(struct lruvec *child_lruvec, struct lruveclist_splice_tail_init (&child_lrugen->folios[gen][type][zone], &parent_lrugen->folios[gen][type][zone]); -WRITE_ONCE (child_lrugen->nr_pages[gen][type][zone],0 ); -WRITE_ONCE (parent_lrugen->nr_pages[gen][type][zone], - parent_lrugen->nr_pages[gen][type][zone] + nr_pages); +atomic_long_set (&child_lrugen->nr_pages[gen][type][zone],0 ); +atomic_long_add (nr_pages, &parent_lrugen->nr_pages[gen][type][zone]);if (lru_gen_is_active (child_lruvec, gen) !=lru_gen_is_active (parent_lruvec, gen)) {__update_lru_size (child_lruvec, lru + child_lru_active, zone, -nr_pages);
@@ -5859,7 +5855,8 @@ static int lru_gen_seq_show(struct seq_file *m, void *v)char mark = full && seq < min_seq[type] ?'x' :' ' ;for (zone =0 ; zone <MAX_NR_ZONES ; zone++) - size +=max (READ_ONCE (lrugen->nr_pages[gen][type][zone]),0L ); + size +=max (atomic_long_read (&lrugen->nr_pages[gen][type][zone]), +0L );seq_printf (m," %10lu%c" , size, mark); }
Signature · 1 line
2.56.0
[email protected]
AI reviewRe: [PATCH v4 02/17] mm/mglru: make generation page counters atomic
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] mm: mglru: lost LRU page counter updates in __lru_gen_reparent_memcg() --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] mm: mglru: lost LRU page counter updates in __lru_gen_reparent_memcg() --
commit 82d0af39bfdf4a479c7e716d6991b3cf9cc6e2b4
Author: Kairui Song <[email protected]>
mm/mglru: make generation page counters atomic
This commit converts the multi-gen LRU generation page counters to atomic longs. This allows the counters to be updated without holding the LRU lock, relying on eventual consistency.
Quoted 4 lines
mm/vmscan.c +0
-0
[ ... ]
Quoted 10 lines
mm/vmscan.c +1
-1@@ -4764,7 +4761,7 @@ static void __lru_gen_reparent_memcg(struct lruvec *child_lruvec, struct lruvecfor (i =0 ; i <get_nr_gens (child_lruvec, type); i++) {int gen =lru_gen_from_seq (child_lrugen->max_seq - i); -long nr_pages = child_lrugen->nr_pages[gen][type][zone]; +long nr_pages =atomic_long_read (&child_lrugen->nr_pages[gen][type][zone]);int child_lru_active =lru_gen_is_active (child_lruvec, gen) ?LRU_ACTIVE :0 ;int parent_lru_active =lru_gen_is_active (parent_lruvec, gen) ?LRU_ACTIVE :0 ;
mm/vmscan.c static void __lru_gen_reparent_memcg(struct lruvec *child_lruvec, struct lruvec · line 4773
Quoted 8 lines
mm/vmscan.c +2
-3@@ -4772,9 +4769,8 @@ static void __lru_gen_reparent_memcg(struct lruvec *child_lruvec, struct lruveclist_splice_tail_init (&child_lrugen->folios[gen][type][zone], &parent_lrugen->folios[gen][type][zone]); -WRITE_ONCE (child_lrugen->nr_pages[gen][type][zone],0 ); -WRITE_ONCE (parent_lrugen->nr_pages[gen][type][zone], - parent_lrugen->nr_pages[gen][type][zone] + nr_pages); +atomic_long_set (&child_lrugen->nr_pages[gen][type][zone],0 ); +atomic_long_add (nr_pages, &parent_lrugen->nr_pages[gen][type][zone]);
[Severity: High]
Does the non-atomic extraction and clearing of the child's counter create a read-modify-write window that wipes out lockless updates from folio_inc_lru_refs()?
Because __lru_gen_reparent_memcg() reads the child's counter, executes a list_splice, and then unconditionally overwrites the counter via atomic_long_set(0), any concurrent lockless counter additions or subtractions that land during this window appear to be completely wiped out and never propagated to the parent memcg.
Could we replace the read and zeroing with atomic_long_xchg(&..., 0) after the list splice? This would atomically extract and clear the counter, ensuring updates during the window are passed to the parent.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
Kairui Song
maintainerPATCH v4 3/17 mm/memcg: add folio-based lruvec live helper
In reply to Kairui SongAdd a helper that resolves a stable lruvec for a folio under RCU without taking the lruvec lock. It takes a folio directly so the lruvec lookup happens inside the RCU read-side critical section, which a lruvec-based interface cannot guarantee.
No functional change.
--- include/linux/memcontrol.h | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+)
include/linux/memcontrol.h +39 -0
@@ -1535,6 +1535,45 @@ static inline void lruvec_lock_irq(struct lruvec *lruvec)spin_lock_irq (&lruvec->lru_lock); } +/** +* folio_lruvec_live_get - get a live lruvec for a folio under RCU +* @folio: the folio +* +* Computes @folio's lruvec and walks up to the nearest live ancestor +* if the folio's memcg is dying. Paired with folio_lruvec_live_put(). +* The result may be stale: RCU keeps it alive but does not pin @folio +* to it. That is fine as the counters are fixed up on reparenting. +* +* Return: the live lruvec, with rcu_read_lock held. +*/ +static inline struct lruvec *folio_lruvec_live_get (struct folio *folio) +{ +#ifdef CONFIG_MEMCG +struct lruvec *lruvec; +struct pglist_data *pgdat; +struct mem_cgroup *memcg; + +rcu_read_lock (); + lruvec =folio_lruvec (folio); + pgdat =lruvec_pgdat (lruvec); + memcg =lruvec_memcg (lruvec); +while (unlikely (memcg &&css_is_dying (&memcg->css))) { + memcg =parent_mem_cgroup (memcg); + lruvec =mem_cgroup_lruvec (memcg, pgdat); + } +return lruvec; +#else +return folio_lruvec (folio); +#endif +} + +static inline void folio_lruvec_live_put (struct lruvec *lruvec) +{ +#ifdef CONFIG_MEMCG +rcu_read_unlock (); +#endif +} +static inline struct lruvec *lruvec_live_lock_irq (struct lruvec *lruvec) {#ifdef CONFIG_MEMCG
Signature · 1 line
2.56.0
[email protected]
AI reviewRe: [PATCH v4 03/17] mm/memcg: add folio-based lruvec live helper
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 11 lines
From: Kairui Song <[email protected]>
Add a helper that resolves a stable lruvec for a folio under RCU without taking the lruvec lock. It takes a folio directly so the lruvec lookup happens inside the RCU read-side critical section, which a lruvec-based interface cannot guarantee.
No functional change.
Tested-by zhaozhengzhuo <[email protected]>Signed-off-by Kairui Song <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
Re: [PATCH v4 03/17] mm/memcg: add folio-based lruvec live helper
In reply to Kairui SongQuoted 7 lines · On Fri, Oct 16, 2026 at 02:15:52AM +0800, Kairui Song via B4 Relay wrote:
From: Kairui Song <[email protected]>
Add a helper that resolves a stable lruvec for a folio under RCU without taking the lruvec lock. It takes a folio directly so the lruvec lookup happens inside the RCU read-side critical section, which a lruvec-based interface cannot guarantee.
Quoted 5 lines
No functional change.
Tested-by zhaozhengzhuo <[email protected]>Signed-off-by Kairui Song <[email protected]>---
This new helper is doing the the same thing as what get_non_dying_memcg_start/end() do.
Quoted 56 lines
include/linux/memcontrol.h | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+)include/linux/memcontrol.h +39
-0@@ -1535,6 +1535,45 @@ static inline void lruvec_lock_irq(struct lruvec *lruvec)spin_lock_irq (&lruvec->lru_lock); } +/** +* folio_lruvec_live_get - get a live lruvec for a folio under RCU +* @folio: the folio +* +* Computes @folio's lruvec and walks up to the nearest live ancestor +* if the folio's memcg is dying. Paired with folio_lruvec_live_put(). +* The result may be stale: RCU keeps it alive but does not pin @folio +* to it. That is fine as the counters are fixed up on reparenting. +* +* Return: the live lruvec, with rcu_read_lock held. +*/ +static inline struct lruvec *folio_lruvec_live_get (struct folio *folio) +{ +#ifdef CONFIG_MEMCG +struct lruvec *lruvec; +struct pglist_data *pgdat; +struct mem_cgroup *memcg; + +rcu_read_lock (); + lruvec =folio_lruvec (folio); + pgdat =lruvec_pgdat (lruvec); + memcg =lruvec_memcg (lruvec); +while (unlikely (memcg &&css_is_dying (&memcg->css))) { + memcg =parent_mem_cgroup (memcg); + lruvec =mem_cgroup_lruvec (memcg, pgdat); + } +return lruvec; +#else +return folio_lruvec (folio); +#endif +} + +static inline void folio_lruvec_live_put (struct lruvec *lruvec) +{ +#ifdef CONFIG_MEMCG +rcu_read_unlock (); +#endif +} +static inline struct lruvec *lruvec_live_lock_irq (struct lruvec *lruvec) {#ifdef CONFIG_MEMCG Signature · 2 lines
-- 2.56.0
Signature · 2 lines
Cheers, Harry / Hyeonggon
Re: [PATCH v4 03/17] mm/memcg: add folio-based lruvec live helper
Quoted 9 lines · Harry Yoo
Quoted 7 lines · On Fri, Oct 16, 2026 at 02:15:52AM +0800, Kairui Song via B4 Relay wrote:
From: Kairui Song <[email protected]>
Add a helper that resolves a stable lruvec for a folio under RCU without taking the lruvec lock. It takes a folio directly so the lruvec lookup happens inside the RCU read-side critical section, which a lruvec-based interface cannot guarantee.
Quoted 9 lines
Quoted 5 lines
No functional change.
Tested-by zhaozhengzhuo <[email protected]>Signed-off-by Kairui Song <[email protected]>---
This new helper is doing the the same thing as what get_non_dying_memcg_start/end() do.
Hi Harry, thanks for letting me know, I wasn't aware this helper exists, this series started before the re-planting work, so I missed it.
But it's a bit different though, get_non_dying_memcg_start assumes the caller holds a reference to memcg, while folio_lruvec_live_get only assumes the caller holds an reference to the folio.
I'll check if I can deduplicate it though.
Re: [PATCH v4 03/17] mm/memcg: add folio-based lruvec live helper
Quoted 16 lines · Kairui Song
Quoted 15 lines · Harry Yoo
Quoted 12 lines · On Fri, Oct 16, 2026 at 02:15:52AM +0800, Kairui Song via B4 Relay wrote:
From: Kairui Song <[email protected]>
Add a helper that resolves a stable lruvec for a folio under RCU without taking the lruvec lock. It takes a folio directly so the lruvec lookup happens inside the RCU read-side critical section, which a lruvec-based interface cannot guarantee.
No functional change.
Tested-by zhaozhengzhuo <[email protected]>Signed-off-by Kairui Song <[email protected]>---
Quoted 7 lines
Quoted 3 lines
This new helper is doing the the same thing as what get_non_dying_memcg_start/end() do.
Hi Harry, thanks for letting me know, I wasn't aware this helper exists, this series started before the re-planting work, so I missed it.
No worries!
Quoted 3 lines
But it's a bit different though,
get_non_dying_memcg_startassumes the caller holds a reference to memcg, whilefolio_lruvec_live_getonly assumes the caller holds an reference to the folio.
Not sure I follow. I think get_non_dying_memcg_start() has the same assumption (a reference to the folio). A folio no longer pins the memcg, which was a key requirement for the reparenting work.
In the function, RCU is the only mechanism that prevents release of the memcg and guarantees correct reparenting of local memcg stats (state_local) as it's reparented in an RCU work.
Quoted 1 line
I'll check if I can deduplicate it though.
Thanks!
Signature · 2 lines
Cheers, Harry / Hyeonggon
Re: [PATCH v4 03/17] mm/memcg: add folio-based lruvec live helper
Quoted 2 lines · Harry Yoo
In the function, RCU is the only mechanism that prevents release of the memcg
Uh, no. looking at the code again I might have been confused!
The caller is expected to have either 1) acquired RCU read lock, or 2) have a reference to the cgroup.
I see a bunch of callers that acquires rcu_read_lock() before reading memcg/lruvec from folio and passing it to mod_lruvec_state() (and then get_non_dying_memcg_start()/end().
Callers like reclaim e.g.) mem_cgroup_iter() hold a reference to the cgroup...
Signature · 2 lines
Cheers, Harry / Hyeonggon
Muchun Song
reviewerRe: [PATCH v4 03/17] mm/memcg: add folio-based lruvec live helper
In reply to Kairui SongQuoted 44 lines · On Oct 16, 2026, at 02:15, Kairui Song via B4 Relay…
From: Kairui Song <[email protected]>
Add a helper that resolves a stable lruvec for a folio under RCU without taking the lruvec lock. It takes a folio directly so the lruvec lookup happens inside the RCU read-side critical section, which a lruvec-based interface cannot guarantee.
No functional change.
Tested-by zhaozhengzhuo <[email protected]>Signed-off-by Kairui Song <[email protected]>---
include/linux/memcontrol.h| 39 +++++++++++++++++++++++++++++++++++++++1 file changed, 39 insertions(+)include/linux/memcontrol.h +17
-0@@ -1535,6 +1535,45 @@ static inline void lruvec_lock_irq(struct lruvec *lruvec)spin_lock_irq (&lruvec->lru_lock); } +/** +* folio_lruvec_live_get - get a live lruvec for a folio under RCU +* @folio: the folio +* +* Computes @folio's lruvec and walks up to the nearest live ancestor +* if the folio's memcg is dying. Paired with folio_lruvec_live_put(). +* The result may be stale: RCU keeps it alive but does not pin @folio +* to it. That is fine as the counters are fixed up on reparenting. +* +* Return: the live lruvec, with rcu_read_lock held. +*/ +static inline struct lruvec *folio_lruvec_live_get (struct folio *folio) +{ +#ifdef CONFIG_MEMCG +struct lruvec *lruvec; +struct pglist_data *pgdat; +struct mem_cgroup *memcg;
include/linux/memcontrol.h static inline void lruvec_lock_irq(struct lruvec *lruvec) · line 1564
Quoted 10 lines
include/linux/memcontrol.h +10
-0+ +rcu_read_lock (); + lruvec =folio_lruvec (folio); + pgdat =lruvec_pgdat (lruvec); + memcg =lruvec_memcg (lruvec); +while (unlikely (memcg &&css_is_dying (&memcg->css))) { + memcg =parent_mem_cgroup (memcg); + lruvec =mem_cgroup_lruvec (memcg, pgdat); + } +return lruvec;
Hi Kairui,
Actually, we don't have any means to guarantee that the memcg to which the returned lruvec belongs will not become dying after the return, right?
include/linux/memcontrol.h static inline void lruvec_lock_irq(struct lruvec *lruvec) · line 1566
Quoted 2 lines
include/linux/memcontrol.h +2
-0+#else +return folio_lruvec (folio);
Then, I'm wondering why folio_lruvec() doesn't apply to the memcg scenario.
Internally, folio_lruvec() obtains the memcg through obj_cgroup_memcg(). So when the memcg becomes dying, it should be reparented to the parent memcg within a short time.
Likewise, folio_lruvec() may also return an lruvec whose memcg may also be in a short-lived dying state.
Since the results of the two are similar, why not just use folio_lruvec() directly? Or is there something I misunderstood?
Thanks,
Muchun
Quoted 18 lines
include/linux/memcontrol.h +10
-0+#endif +} + +static inline void folio_lruvec_live_put (struct lruvec *lruvec) +{ +#ifdef CONFIG_MEMCG +rcu_read_unlock (); +#endif +} +static inline struct lruvec *lruvec_live_lock_irq (struct lruvec *lruvec) {#ifdef CONFIG_MEMCG Signature · 2 lines
-- 2.56.0
Re: [PATCH v4 03/17] mm/memcg: add folio-based lruvec live helper
Quoted 47 lines · Muchun Song
Quoted 47 lines · On Oct 16, 2026, at 02:15, Kairui Song via B4 Relay…
From: Kairui Song <[email protected]>
Add a helper that resolves a stable lruvec for a folio under RCU without taking the lruvec lock. It takes a folio directly so the lruvec lookup happens inside the RCU read-side critical section, which a lruvec-based interface cannot guarantee.
No functional change.
Tested-by zhaozhengzhuo <[email protected]>Signed-off-by Kairui Song <[email protected]>---
include/linux/memcontrol.h| 39 +++++++++++++++++++++++++++++++++++++++1 file changed, 39 insertions(+)include/linux/memcontrol.h +21
-0@@ -1535,6 +1535,45 @@ static inline void lruvec_lock_irq(struct lruvec *lruvec)spin_lock_irq (&lruvec->lru_lock); } +/** +* folio_lruvec_live_get - get a live lruvec for a folio under RCU +* @folio: the folio +* +* Computes @folio's lruvec and walks up to the nearest live ancestor +* if the folio's memcg is dying. Paired with folio_lruvec_live_put(). +* The result may be stale: RCU keeps it alive but does not pin @folio +* to it. That is fine as the counters are fixed up on reparenting. +* +* Return: the live lruvec, with rcu_read_lock held. +*/ +static inline struct lruvec *folio_lruvec_live_get (struct folio *folio) +{ +#ifdef CONFIG_MEMCG +struct lruvec *lruvec; +struct pglist_data *pgdat; +struct mem_cgroup *memcg; + +rcu_read_lock (); + lruvec =folio_lruvec (folio); + pgdat =lruvec_pgdat (lruvec);
Quoted 9 lines
include/linux/memcontrol.h static inline void lruvec_lock_irq(struct lruvec *lruvec) · line 1564
Quoted 6 lines
include/linux/memcontrol.h +6
-0+ memcg =lruvec_memcg (lruvec); +while (unlikely (memcg &&css_is_dying (&memcg->css))) { + memcg =parent_mem_cgroup (memcg); + lruvec =mem_cgroup_lruvec (memcg, pgdat); + } +return lruvec;Hi Kairui,
Hi Muchun, thanks for the review.
Quoted 3 lines
Actually, we don't have any means to guarantee that the memcg to which the returned lruvec belongs will not become dying after the return, right?
Yeah but Qi once mentioned that RCU prevents reparenting, right? Even if the memcg is dead after return, things happended to it (non-hieratical counter reparenting, ones in __lru_gen_reparent_memcg) will only occurs after RCU unlock so we can apply counter update to it without grabbing an ref, just hold the RCU.
Quoted 9 lines
include/linux/memcontrol.h static inline void lruvec_lock_irq(struct lruvec *lruvec) · line 1566
Quoted 2 lines
include/linux/memcontrol.h +2
-0+#else +return folio_lruvec (folio);Then, I'm wondering why
folio_lruvec()doesn't apply to the memcg scenario.Internally,
folio_lruvec()obtains the memcg throughobj_cgroup_memcg(). So when the memcg becomes dying, it should be reparented to the parent memcg within a short time.
I wasn't sure if grabbing RCU can ensure an already dead cgroup has not been reparented yet. If we apply the counter update to a already reparented lruvec, then the counter is leaked. This new helper is just a folio version of lruvec_live_lock_irq.
I got the idea from commit de4660898b7a, which says:
"""
.... check CSS_DYING under RCU before
flushing the pending batch. A non-dying memcg keeps the original lruvec stable against RCU-delayed offlining; a dying memcg redirects the deltas to the first non-dying ancestor.
"""
Applying counter update to a dead but not reparented lruvec is fine though.
Muchun Song
reviewerRe: [PATCH v4 03/17] mm/memcg: add folio-based lruvec live helper
Quoted 68 lines · Kairui Song
Quoted 47 lines · Muchun Song
Quoted 47 lines · On Oct 16, 2026, at 02:15, Kairui Song via B4 Relay…
From: Kairui Song <[email protected]>
Add a helper that resolves a stable lruvec for a folio under RCU without taking the lruvec lock. It takes a folio directly so the lruvec lookup happens inside the RCU read-side critical section, which a lruvec-based interface cannot guarantee.
No functional change.
Tested-by zhaozhengzhuo <[email protected]>Signed-off-by Kairui Song <[email protected]>---
include/linux/memcontrol.h| 39 +++++++++++++++++++++++++++++++++++++++1 file changed, 39 insertions(+)include/linux/memcontrol.h +21
-0@@ -1535,6 +1535,45 @@ static inline void lruvec_lock_irq(struct lruvec *lruvec)spin_lock_irq (&lruvec->lru_lock); } +/** +* folio_lruvec_live_get - get a live lruvec for a folio under RCU +* @folio: the folio +* +* Computes @folio's lruvec and walks up to the nearest live ancestor +* if the folio's memcg is dying. Paired with folio_lruvec_live_put(). +* The result may be stale: RCU keeps it alive but does not pin @folio +* to it. That is fine as the counters are fixed up on reparenting. +* +* Return: the live lruvec, with rcu_read_lock held. +*/ +static inline struct lruvec *folio_lruvec_live_get (struct folio *folio) +{ +#ifdef CONFIG_MEMCG +struct lruvec *lruvec; +struct pglist_data *pgdat; +struct mem_cgroup *memcg; + +rcu_read_lock (); + lruvec =folio_lruvec (folio); + pgdat =lruvec_pgdat (lruvec);Quoted 9 lines
include/linux/memcontrol.h static inline void lruvec_lock_irq(struct lruvec *lruvec) · line 1564
Quoted 6 lines
include/linux/memcontrol.h +6
-0+ memcg =lruvec_memcg (lruvec); +while (unlikely (memcg &&css_is_dying (&memcg->css))) { + memcg =parent_mem_cgroup (memcg); + lruvec =mem_cgroup_lruvec (memcg, pgdat); + } +return lruvec;Hi Kairui,
Hi Muchun, thanks for the review.
Quoted 3 lines
Actually, we don't have any means to guarantee that the memcg to which the returned lruvec belongs will not become dying after the return, right?
Quoted 5 lines
Yeah but Qi once mentioned that RCU prevents reparenting, right? Even if the memcg is dead after return, things happended to it (non-hieratical counter reparenting, ones in
__lru_gen_reparent_memcg) will only occurs after RCU unlock so we can apply counter update to it without grabbing an ref, just hold the RCU.
Thanks for the info. I checked the code and confirmed that, aside from keeping the memcg from being freed, RCU also ensures the memcg doesn't get reparented. If your scenario requires mutual exclusion with the reparenting operation, RCU can handle that.
Thanks,
Muchun
Quoted 26 lines
Quoted 10 lines
include/linux/memcontrol.h static inline void lruvec_lock_irq(struct lruvec *lruvec) · line 1566
Quoted 3 lines
include/linux/memcontrol.h +2
-0+#else +return folio_lruvec (folio);Then, I'm wondering why
folio_lruvec()doesn't apply to the memcg scenario.Internally,
folio_lruvec()obtains the memcg throughobj_cgroup_memcg(). So when the memcg becomes dying, it should be reparented to the parent memcg within a short time.I wasn't sure if grabbing RCU can ensure an already dead cgroup has not been reparented yet. If we apply the counter update to a already reparented lruvec, then the counter is leaked. This new helper is just a folio version of
lruvec_live_lock_irq.I got the idea from commit
de4660898b7a, which says:"""
.... checkCSS_DYINGunder RCU before
flushing the pending batch. A non-dying memcg keeps the original lruvec stable against RCU-delayed offlining; a dying memcg redirects the deltas to the first non-dying ancestor.
"""Applying counter update to a dead but not reparented lruvec is fine though.
Kairui Song
maintainerPATCH v4 4/17 mm/mglru: frequency guided workingset promotion (MGLRU-FG)
In reply to Kairui SongComplement MGLRU's eviction-time tier-PID protection with access-time frequency-guided promotion. Introduce a unified set of helpers built based on referenced (access) count of a folio.
Each access increments a folio's referenced count stored in folio flags (refs), refs still maps to a logarithmic tier just like before, but with more formal bit definitions, a few special thresholds are introduced:LRU_REFS_REFERENCED (1), LRU_REFS_WORKINGSET (2), LRU_REFS_PROTECTED (3), and LRU_REFS_MAX (7). When refs reaches a certain threshold, the folio is promoted proactively instead of waiting for the PID controller to kick in.
Also simplify MGLRU's usage of PG_workingset and PG_referenced: they become the low two bits of the refs count, with the higher bits provided by LRU_REFS_MASK. This reduces MGLRU's original refs count bit usage by one, since only one extra bit is now needed to record a max referenced count of 7, and makes MGLRU's refs accounting more accurate.
This doesn't affect classical LRU in any way, and it addresses several shortcomings of MGLRU's old tier-only cache protection model:
- Long feedback loop: protection only activated after enough re-faults, by which time the hot folios are already evicted, or no longer hot.
- Limited tier resolution: once referenced count exceeded the bits limit (8 previously), MGLRU could no longer distinguish hotter folios as they are capped by the tier. And what's worse, PG_workingset forces a folio to stay on tier 3.
- Eviction hotness reversion: because PID protection activates upon eviction and always targets the LRU tail, it tends to protect cold tail folios at the expense of hotter head folios. Once the tail folios consume the PID protection budget, head folios lose their protection.
- Additionally, the PID cannot distinguish the access time of folios that share the same reference count, and there are only 4 tiers.
To achieve a frequency-guided framework, this commit introduces and reworks the LRU_REFS related helpers and definitions; most of the work is done by the helpers below, and their inline comments describe the details.
- folio_inc_lru_refs(): Called on any cache access (folio_mark_accessed) or page table access. This is the main helper: it promotes folios according to their access frequency.
A first access only defers eviction for a folio at the tail of its LRU, i.e., in one of the MIN_NR_GENS oldest generations of its own type (see lru_gen_at_tail()), and a workingset folio accessed through a file descriptor is deferred from the same tail. Those are the generations the eviction scans next, so the deferral moves the folio out of its way for one generation.
Promotion is lazy: the gen bits and size counters are updated eagerly, while the list move is deferred to the next isolation. NOTE: For now, the lruvec lock is unconditionally taken on every on-list access to block concurrent aging; a lockless fast path will be implemented very soon in a following commit.
- folio_inc_lru_refs_walk(): Used by the PTE walk path during aging and by the batched look-around, both without the LRU lock, so max_seq may be stale. A first page table access only advances a folio at the tail of its LRU, i.e., in one of the MIN_NR_GENS oldest generations of its own type (second chance), a second access promotes it to the newest generation; this also performs lazy promotion.
- folio_inc_lru_refs_isolated(): Used by the rmap check before eviction. The folio is isolated and hence this doesn't perform promotion by itself; the folio will be added back to the right gen upon return according to the access frequency. This path also has a higher promotion bias.
The eviction-time folio_inc_gen() still handles PID protection, but the protection ratio is softer than before since proactive promotion is mostly good enough already. The PID gain factors are relaxed from (2:3) to (1:2) and the setpoint now spans the cumulative mass of the tiers below the candidate instead of tier 0 alone. folio_inc_gen() caps refs at WORKINGSET so the folio retains enough history to stay above the cold tier. Tier 1 is the fallback tier for PID, and tier 2 is the fallback tier for frequency-guided promotion. The forced protection for full-refs folios is removed, obsoleted by the proactive promotion.
Refaults are now activated purely according to access frequency:
the old fault bias applied in folio_add_lru() is simplified, since a folio's access history is a more consistent signal than the context of the faulting task. Page table access is still considered a slightly stronger signal.
Consequently the placement hint for newly added file folios also uses LRU_REFS_WORKINGSET instead of PG_referenced, so a folio accessed only once now starts in the oldest generation rather than the second oldest. The previous one-generation grace was an artifact of the fault bias which is well described in the cover letter of this series, and it depended on LRU drain timing.
This also redefines PG_workingset and PG_referenced as the low two bits of the refs count, eliminating the old restriction where LRU_REFS_MASK was only valid when PG_referenced was set, and allows all paths to use the same encoding consistently. Following this idea, a workingset folio is now defined as refs >= LRU_REFS_WORKINGSET (2), matching the active/inactive LRU's definition and giving in-kernel consumers (PSI, readahead) consistent behavior on MGLRU, fixing the longstanding issue that these users don't work well with MGLRU.
PG_workingset and PG_referenced are no longer independent flags under MGLRU. Adjusting existing raw folio_test_*() callers to the new semantics is left as follow-ups.
--- include/linux/mm_inline.h | 96 ++++++++------ include/linux/mmzone.h | 145 +++++++++++++++------ kernel/bounds.c | 2 +- mm/folio.c | 50 +------- mm/vmscan.c | 320 +++++++++++++++++++++++++++++++--------------- mm/workingset.c | 45 ++++--- 6 files changed, 409 insertions(+), 249 deletions(-)
include/linux/mm_inline.h +60 -36
@@ -144,12 +144,13 @@ static inline int lru_hist_from_seq(unsigned long seq)return seq %NR_HIST_GENS ; } -static inline int lru_tier_from_refs (int refs,bool workingset) +static inline int lru_tier_from_refs (unsigned int refs) { -VM_WARN_ON_ONCE (refs >BIT (LRU_REFS_WIDTH )); - -/* see the comment on MAX_NR_TIERS */ -return workingset ?MAX_NR_TIERS -1 :order_base_2 (refs); +BUILD_BUG_ON (fls (LRU_REFS_MAX -1 ) >MAX_NR_TIERS -1 ); +VM_WARN_ON_ONCE (refs >LRU_REFS_MAX ); +if (refs <LRU_REFS_WORKINGSET ) +return 0 ; +return fls (refs -1 ); }/**
@@ -187,21 +188,24 @@ static inline int lru_get_gen_flags(unsigned long flags)* @flags: pointer to the folio flags * @refs: referenced / access count number, between 0 and LRU_REFS_MAX, inclusive. * -* For MGLRU, PG_referenced holds the first ref, and the extra bits hold the -* remaining refs. For classical LRU the extra bits are not used, so it can -* also be seen as the refs count never exceeds 1. In both cases, refs == 1 -* means PG_referenced is set and the extra bits are zero, and refs == 0 means -* PG_referenced and the extra bits are all unset. +* For MGLRU, PG_referenced, PG_workingset are used as the lower two bits of +* refs counter, and extra bits hold the remaining higher bits. For classical +* LRU the extra bits are not used, and the two flags has no direct +* relationship with each other, but this helper can still be used to sync +* them. For both cases, refs == 0 means these two flags and the extra bits +* are all unset. And refs == 1 / 2 / 3 means PG_referenced and PG_workingset +* are set in an bit order way, which is more meaningful for MGLRU though. */ static inline void lru_set_refs_flags (unsigned long *flags,unsigned int refs) {VM_WARN_ON_ONCE (refs >LRU_REFS_MAX ); -BUILD_BUG_ON (LRU_REFS_MAX != (LRU_REFS_MASK >>LRU_REFS_PGOFF ) +1 ); - +BUILD_BUG_ON (LRU_REFS_MASK & (BIT (PG_referenced) |BIT (PG_workingset))); *flags &= ~LRU_REFS_FLAGS ; -if (!refs) -return ; - *flags |= (BIT (PG_referenced) | ((refs -1UL ) <<LRU_REFS_PGOFF )); +if (refs &BIT (0 )) + *flags |=BIT (PG_referenced); +if (refs &BIT (1 )) + *flags |=BIT (PG_workingset); + *flags |= ((unsigned long )refs >>2 ) <<LRU_REFS_PGOFF ; }/**
@@ -212,13 +216,13 @@ static inline void lru_set_refs_flags(unsigned long *flags, unsigned int refs)*/ static inline int lru_get_refs_flags (unsigned long flags) { -if (!(flags &BIT (PG_referenced))) -return 0 ; -/* -* Return the total number of accesses including PG_referenced. Also see -* the comment on LRU_REFS_FLAGS. -*/ -return ((flags &LRU_REFS_MASK ) >>LRU_REFS_PGOFF ) +1 ; +int refs; + +/* Return the total number of accesses. See the comment above MAX_NR_TIERS. */ + refs = (flags &BIT (PG_referenced)) ?BIT (0 ) :0 ; + refs += (flags &BIT (PG_workingset)) ?BIT (1 ) :0 ; + refs += ((flags &LRU_REFS_MASK ) >>LRU_REFS_PGOFF ) <<2 ; +return refs; }static inline int folio_lru_refs (const struct folio *folio)
@@ -236,14 +240,29 @@ static inline void folio_set_lru_refs(struct folio *folio, unsigned int refs) }while (!try_cmpxchg (folio_flags (folio,0 ), &old_flags, new_flags)); } +void folio_inc_lru_refs (struct folio *folio,unsigned int flags); +static inline int folio_lru_gen (const struct folio *folio) {return lru_get_gen_flags (READ_ONCE (*const_folio_flags (folio,0 ))); } +static inline bool lru_gen_at_tail (struct lruvec *lruvec,int type,int gen) +{ +unsigned long min_seq =READ_ONCE (lruvec->lrugen.min_seq[type]); + +/* +* Consider a folio is at the tail of its LRU when it is within +* MIN_NR_GENS of the oldest generation of its own type +*/ +BUILD_BUG_ON (MIN_NR_GENS !=2 ); +return gen ==lru_gen_from_seq (min_seq) || + gen ==lru_gen_from_seq (min_seq +1 ); +} +static inline bool lru_gen_is_active (const struct lruvec *lruvec,int gen) { -unsigned long max_seq = lruvec->lrugen.max_seq; +unsigned long max_seq =READ_ONCE (lruvec->lrugen.max_seq);VM_WARN_ON_ONCE (gen >=MAX_NR_GENS );
@@ -300,23 +319,24 @@ static inline unsigned long lru_gen_folio_seq(const struct lruvec *lruvec, bool reclaiming) {int gen; +int refs =folio_lru_refs (folio);int type =folio_is_file_lru (folio);const struct lru_gen_folio *lrugen = &lruvec->lrugen;/* -* +-----------------------------------+-----------------------------------+ -* | Accessed through page tables and | Accessed through file descriptors | -* | promoted by folio_update_gen() | and protected by folio_inc_gen() | -* +-----------------------------------+-----------------------------------+ -* | PG_active (set while isolated) | | -* +-----------------+-----------------+-----------------+-----------------+ -* | PG_workingset | PG_referenced | PG_workingset | LRU_REFS_FLAGS | -* +-----------------------------------+-----------------------------------+ -* |<---------- MIN_NR_GENS ---------->| | -* |<---------------------------- MAX_NR_GENS ---------------------------->| +* +------------------------------------------+------------------------------------------+ +* | Accessed through page tables and | Accessed through file descriptors | +* | promoted by folio_inc_lru_refs_walk() | protected by folio_inc_lru_refs/inc_gen | +* +------------------------------------------+------------------------------------------+ +* | PG_active (set at isolation or refault) | | +* +--------------------+---------------------+--------------------+---------------------+ +* | LRU_REFS_MAX | LRU_REFS_WORKINGSET | LRU_REFS_MAX | LRU_REFS_WORKINGSET | +* +------------------------------------------+------------------------------------------+ +* |<-------------- MIN_NR_GENS ------------->| | +* |<----------------------------------- MAX_NR_GENS ----------------------------------->| */ if (folio_test_active (folio)) - gen =MIN_NR_GENS -folio_test_workingset (folio); + gen =MIN_NR_GENS - (refs >=LRU_REFS_WORKINGSET );else if (reclaiming) gen =MAX_NR_GENS ; else if ((!folio_is_file_lru(folio) && !folio_test_swapcache(folio)) ||
@@ -324,7 +344,7 @@ static inline unsigned long lru_gen_folio_seq(const struct lruvec *lruvec, (folio_test_dirty(folio) || folio_test_writeback(folio)))) gen =MIN_NR_GENS ; else - gen =MAX_NR_GENS - (folio_test_workingset (folio) ||folio_test_referenced (folio)); + gen =MAX_NR_GENS - (refs >=LRU_REFS_WORKINGSET );return max (READ_ONCE (lrugen->max_seq) - gen +1 ,READ_ONCE (lrugen->min_seq[type])); }
@@ -338,6 +358,7 @@ static inline bool lru_gen_add_folio(struct lruvec *lruvec, struct folio *folio,int zone =folio_zonenum (folio);struct lru_gen_folio *lrugen = &lruvec->lrugen; +BUILD_BUG_ON (BIT (LRU_GEN_WIDTH -1 ) !=MAX_NR_GENS );VM_WARN_ON_ONCE_FOLIO (gen !=-1 , folio);if (folio_test_unevictable (folio) || !lrugen->enabled)
@@ -392,7 +413,6 @@ static inline bool lru_gen_del_folio(struct lruvec *lruvec, struct folio *folio,*/ static inline void folio_migrate_lru_refs (struct folio *new,const struct folio *old) { -BUILD_BUG_ON (LRU_REFS_MASK &BIT (PG_referenced));folio_set_lru_refs (new,folio_lru_refs (old)); }#else /* !CONFIG_LRU_GEN */
@@ -422,6 +442,10 @@ static inline bool lru_gen_del_folio(struct lruvec *lruvec, struct folio *folio,return false; } +static inline void folio_inc_lru_refs (struct folio *folio,unsigned int flags) +{ +} +static inline void folio_migrate_lru_refs (struct folio *new,const struct folio *old) {if (folio_test_referenced (old))
include/linux/mmzone.h +105 -40
162 lines not on this page · raw message
kernel/bounds.c +1 -1
@@ -25,7 +25,7 @@ int main(void)DEFINE (SPINLOCK_SIZE ,sizeof (spinlock_t));#ifdef CONFIG_LRU_GEN DEFINE (LRU_GEN_WIDTH ,order_base_2 (MAX_NR_GENS +1 )); -DEFINE (__LRU_REFS_WIDTH,MAX_NR_TIERS -2 ); +DEFINE (__LRU_REFS_WIDTH,MAX_NR_TIERS -3 );#else DEFINE (LRU_GEN_WIDTH ,0 );DEFINE (__LRU_REFS_WIDTH,0 );
mm/folio.c +2 -48
86 lines not on this page · raw message
mm/vmscan.c +214 -106
449 lines not on this page · raw message
mm/workingset.c +27 -18
91 lines not on this page · raw message
Signature · 1 line
2.56.0
[email protected]
AI reviewRe: [PATCH v4 04/17] mm/mglru: frequency guided workingset promotion (MGLRU-FG)
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 13 lines
From: Kairui Song <[email protected]>
Complement MGLRU's eviction-time tier-PID protection with access-time frequency-guided promotion. Introduce a unified set of helpers built based on referenced (access) count of a folio.
Each access increments a folio's referenced count stored in folio flags (refs), refs still maps to a logarithmic tier just like before, but with more formal bit definitions, a few special thresholds are introduced:
LRU_REFS_REFERENCED(1),LRU_REFS_WORKINGSET(2),LRU_REFS_PROTECTED(3), andLRU_REFS_MAX(7). When refs reaches a certain threshold, the folio is promoted proactively instead of waiting for the PID controller to kick in.
Quoted 8 lines
Also simplify MGLRU's usage of
PG_workingsetandPG_referenced: they become the low two bits of the refs count, with the higher bits [ ... ]PG_workingsetandPG_referencedare no longer independent flags under MGLRU. Adjusting existing raw folio_test_*() callers to the new semantics is left as follow-ups.Signed-off-by Kairui Song <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
Barry Song
reviewerRe: [PATCH v4 04/17] mm/mglru: frequency guided workingset promotion (MGLRU-FG)
In reply to Kairui SongQuoted 107 lines · On Fri, Oct 16, 2026 at 2:15 AM Kairui Song via B4 Relay…
From: Kairui Song <[email protected]>
Complement MGLRU's eviction-time tier-PID protection with access-time frequency-guided promotion. Introduce a unified set of helpers built based on referenced (access) count of a folio.
Each access increments a folio's referenced count stored in folio flags (refs), refs still maps to a logarithmic tier just like before, but with more formal bit definitions, a few special thresholds are introduced:
LRU_REFS_REFERENCED(1),LRU_REFS_WORKINGSET(2),LRU_REFS_PROTECTED(3), andLRU_REFS_MAX(7). When refs reaches a certain threshold, the folio is promoted proactively instead of waiting for the PID controller to kick in.Also simplify MGLRU's usage of
PG_workingsetandPG_referenced: they become the low two bits of the refs count, with the higher bits provided byLRU_REFS_MASK. This reduces MGLRU's original refs count bit usage by one, since only one extra bit is now needed to record a max referenced count of 7, and makes MGLRU's refs accounting more accurate.This doesn't affect classical LRU in any way, and it addresses several shortcomings of MGLRU's old tier-only cache protection model:
- Long feedback loop: protection only activated after enough re-faults, by which time the hot folios are already evicted, or no longer hot.
- Limited tier resolution: once referenced count exceeded the bits limit (8 previously), MGLRU could no longer distinguish hotter folios as they are capped by the tier. And what's worse,
PG_workingsetforces a folio to stay on tier 3.- Eviction hotness reversion: because PID protection activates upon eviction and always targets the LRU tail, it tends to protect cold tail folios at the expense of hotter head folios. Once the tail folios consume the PID protection budget, head folios lose their protection.
- Additionally, the PID cannot distinguish the access time of folios that share the same reference count, and there are only 4 tiers.
To achieve a frequency-guided framework, this commit introduces and reworks the
LRU_REFSrelated helpers and definitions; most of the work is done by the helpers below, and their inline comments describe the details.-
folio_inc_lru_refs(): Called on any cache access (folio_mark_accessed) or page table access. This is the main helper: it promotes folios according to their access frequency.A first access only defers eviction for a folio at the tail of its LRU, i.e., in one of the
MIN_NR_GENSoldest generations of its own type (seelru_gen_at_tail()), and a workingset folio accessed through a file descriptor is deferred from the same tail. Those are the generations the eviction scans next, so the deferral moves the folio out of its way for one generation.Promotion is lazy: the gen bits and size counters are updated eagerly, while the list move is deferred to the next isolation. NOTE: For now, the lruvec lock is unconditionally taken on every on-list access to block concurrent aging; a lockless fast path will be implemented very soon in a following commit.
-
folio_inc_lru_refs_walk(): Used by the PTE walk path during aging and by the batched look-around, both without the LRU lock, somax_seqmay be stale. A first page table access only advances a folio at the tail of its LRU, i.e., in one of theMIN_NR_GENSoldest generations of its own type (second chance), a second access promotes it to the newest generation; this also performs lazy promotion.-
folio_inc_lru_refs_isolated(): Used by the rmap check before eviction. The folio is isolated and hence this doesn't perform promotion by itself; the folio will be added back to the right gen upon return according to the access frequency. This path also has a higher promotion bias.The eviction-time
folio_inc_gen()still handles PID protection, but the protection ratio is softer than before since proactive promotion is mostly good enough already. The PID gain factors are relaxed from (2:3) to (1:2) and the setpoint now spans the cumulative mass of the tiers below the candidate instead of tier 0 alone.folio_inc_gen()caps refs at WORKINGSET so the folio retains enough history to stay above the cold tier. Tier 1 is the fallback tier for PID, and tier 2 is the fallback tier for frequency-guided promotion. The forced protection for full-refs folios is removed, obsoleted by the proactive promotion.Refaults are now activated purely according to access frequency:
the old fault bias applied infolio_add_lru()is simplified, since a folio's access history is a more consistent signal than the context of the faulting task. Page table access is still considered a slightly stronger signal.Consequently the placement hint for newly added file folios also uses
LRU_REFS_WORKINGSETinstead ofPG_referenced, so a folio accessed only once now starts in the oldest generation rather than the second oldest. The previous one-generation grace was an artifact of the fault bias which is well described in the cover letter of this series, and it depended on LRU drain timing.This also redefines
PG_workingsetandPG_referencedas the low two bits of the refs count, eliminating the old restriction whereLRU_REFS_MASKwas only valid whenPG_referencedwas set, and allows all paths to use the same encoding consistently. Following this idea, a workingset folio is now defined as refs >=LRU_REFS_WORKINGSET(2), matching the active/inactive LRU's definition and giving in-kernel consumers (PSI, readahead) consistent behavior on MGLRU, fixing the longstanding issue that these users don't work well with MGLRU.
Quoted 3 lines
PG_workingsetandPG_referencedare no longer independent flags under MGLRU. Adjusting existing raw folio_test_*() callers to the new semantics is left as follow-ups.
So this is the main course, with the earlier ones as appetizers and the later ones as desserts?
Overall, this dish looks very delicious to me.
I ran kernel build on my machine, the result is quite similar with[1].
W/o patch:
eal 1m49.094s
user 25m31.484s
sys 3m40.959s
pswpin: 662112
pswpout: 2504415
pgpgin: 4424336
pgpgout: 10355273refault_file: 359626refault_anon: 670724
W/ patch:
real 1m48.944s
user 25m30.987s
sys 3m34.605s
pswpin: 467952
pswpout: 2319080
pgpgin: 3481187
pgpgout: 9603332swpout_zero: 602042swpin_zero: 6250refault_file: 310538refault_anon: 474154
But it behaves in a much more sensible way.
I've had a preliminary look, but haven't reviewed it in detail yet. I have a few comments.
[1] https://lore.kernel.org/linux-mm/[email protected]/
Quoted 78 lines
Signed-off-by Kairui Song <[email protected]>--- include/linux/mm_inline.h | 96 ++++++++------ include/linux/mmzone.h | 145 +++++++++++++++------ kernel/bounds.c | 2 +- mm/folio.c | 50 +------- mm/vmscan.c | 320 +++++++++++++++++++++++++++++++--------------- mm/workingset.c | 45 ++++--- 6 files changed, 409 insertions(+), 249 deletions(-)include/linux/mm_inline.h +19
-20@@ -144,12 +144,13 @@ static inline int lru_hist_from_seq(unsigned long seq)return seq %NR_HIST_GENS ; } -static inline int lru_tier_from_refs (int refs,bool workingset) +static inline int lru_tier_from_refs (unsigned int refs) { -VM_WARN_ON_ONCE (refs >BIT (LRU_REFS_WIDTH )); - -/* see the comment on MAX_NR_TIERS */ -return workingset ?MAX_NR_TIERS -1 :order_base_2 (refs); +BUILD_BUG_ON (fls (LRU_REFS_MAX -1 ) >MAX_NR_TIERS -1 ); +VM_WARN_ON_ONCE (refs >LRU_REFS_MAX ); +if (refs <LRU_REFS_WORKINGSET ) +return 0 ; +return fls (refs -1 ); }/** @@ -187,21 +188,24 @@ static inline int lru_get_gen_flags(unsigned long flags)* @flags: pointer to the folio flags * @refs: referenced / access count number, between 0 and LRU_REFS_MAX, inclusive. * -* For MGLRU, PG_referenced holds the first ref, and the extra bits hold the -* remaining refs. For classical LRU the extra bits are not used, so it can -* also be seen as the refs count never exceeds 1. In both cases, refs == 1 -* means PG_referenced is set and the extra bits are zero, and refs == 0 means -* PG_referenced and the extra bits are all unset. +* For MGLRU, PG_referenced, PG_workingset are used as the lower two bits of +* refs counter, and extra bits hold the remaining higher bits. For classical +* LRU the extra bits are not used, and the two flags has no direct +* relationship with each other, but this helper can still be used to sync +* them. For both cases, refs == 0 means these two flags and the extra bits +* are all unset. And refs == 1 / 2 / 3 means PG_referenced and PG_workingset +* are set in an bit order way, which is more meaningful for MGLRU though. */ static inline void lru_set_refs_flags (unsigned long *flags,unsigned int refs) {VM_WARN_ON_ONCE (refs >LRU_REFS_MAX ); -BUILD_BUG_ON (LRU_REFS_MAX != (LRU_REFS_MASK >>LRU_REFS_PGOFF ) +1 ); - +BUILD_BUG_ON (LRU_REFS_MASK & (BIT (PG_referenced) |BIT (PG_workingset))); *flags &= ~LRU_REFS_FLAGS ; -if (!refs) -return ; - *flags |= (BIT (PG_referenced) | ((refs -1UL ) <<LRU_REFS_PGOFF )); +if (refs &BIT (0 )) + *flags |=BIT (PG_referenced); +if (refs &BIT (1 )) + *flags |=BIT (PG_workingset); + *flags |= ((unsigned long )refs >>2 ) <<LRU_REFS_PGOFF ; }/** @@ -212,13 +216,13 @@ static inline void lru_set_refs_flags(unsigned long *flags, unsigned int refs)*/ static inline int lru_get_refs_flags (unsigned long flags) { -if (!(flags &BIT (PG_referenced))) -return 0 ; -/* -* Return the total number of accesses including PG_referenced. Also see -* the comment on LRU_REFS_FLAGS.
include/linux/mm_inline.h static inline void lru_set_refs_flags(unsigned long *flags, unsigned int refs) · line 226
Quoted 10 lines
include/linux/mm_inline.h +7
-2-*/ -return ((flags &LRU_REFS_MASK ) >>LRU_REFS_PGOFF ) +1 ; +int refs; + +/* Return the total number of accesses. See the comment above MAX_NR_TIERS. */ + refs = (flags &BIT (PG_referenced)) ?BIT (0 ) :0 ; + refs += (flags &BIT (PG_workingset)) ?BIT (1 ) :0 ; + refs += ((flags &LRU_REFS_MASK ) >>LRU_REFS_PGOFF ) <<2 ; +return refs; }
Could we use the following instead? Coming from a hardware register background, this looks more like register encoding to me:
static inline int lru_get_refs_flags(unsigned long flags)
{
int refs;
refs = !!(flags & BIT(PG_referenced));
refs |= !!(flags & BIT(PG_workingset)) << 1;
refs |= ((flags & LRU_REFS_MASK) >> LRU_REFS_PGOFF) << 2;
return refs;
}Quoted 15 lines
include/linux/mm_inline.h +4
-0static inline int folio_lru_refs (const struct folio *folio)@@ -236,14 +240,29 @@ static inline void folio_set_lru_refs(struct folio *folio, unsigned int refs) }while (!try_cmpxchg (folio_flags (folio,0 ), &old_flags, new_flags)); } +void folio_inc_lru_refs (struct folio *folio,unsigned int flags); +static inline int folio_lru_gen (const struct folio *folio) {return lru_get_gen_flags (READ_ONCE (*const_folio_flags (folio,0 ))); } +static inline bool lru_gen_at_tail (struct lruvec *lruvec,int type,int gen) +{
include/linux/mm_inline.h static inline void folio_set_lru_refs(struct folio *folio, unsigned int refs) · line 261
Quoted 10 lines
include/linux/mm_inline.h +10
-0+unsigned long min_seq =READ_ONCE (lruvec->lrugen.min_seq[type]); + +/* +* Consider a folio is at the tail of its LRU when it is within +* MIN_NR_GENS of the oldest generation of its own type +*/ +BUILD_BUG_ON (MIN_NR_GENS !=2 ); +return gen ==lru_gen_from_seq (min_seq) || + gen ==lru_gen_from_seq (min_seq +1 ); +}
If only two generations remain, should both be considered hot? If three generations remain, is only the oldest generation old?
Also, the name is a bit confusing, as "tail" usually refers to a list. Could we rename it to one of the following?
lru_gen_is_old()
orlru_gen_is_near_oldest()
Quoted 31 lines
include/linux/mm_inline.h +7
-11+static inline bool lru_gen_is_active (const struct lruvec *lruvec,int gen) { -unsigned long max_seq = lruvec->lrugen.max_seq; +unsigned long max_seq =READ_ONCE (lruvec->lrugen.max_seq);VM_WARN_ON_ONCE (gen >=MAX_NR_GENS );@@ -300,23 +319,24 @@ static inline unsigned long lru_gen_folio_seq(const struct lruvec *lruvec, bool reclaiming) {int gen; +int refs =folio_lru_refs (folio);int type =folio_is_file_lru (folio);const struct lru_gen_folio *lrugen = &lruvec->lrugen;/* -* +-----------------------------------+-----------------------------------+ -* | Accessed through page tables and | Accessed through file descriptors | -* | promoted by folio_update_gen() | and protected by folio_inc_gen() | -* +-----------------------------------+-----------------------------------+ -* | PG_active (set while isolated) | | -* +-----------------+-----------------+-----------------+-----------------+ -* | PG_workingset | PG_referenced | PG_workingset | LRU_REFS_FLAGS | -* +-----------------------------------+-----------------------------------+ -* |<---------- MIN_NR_GENS ---------->| | -* |<---------------------------- MAX_NR_GENS ---------------------------->| +* +------------------------------------------+------------------------------------------+ +* | Accessed through page tables and | Accessed through file descriptors | +* | promoted by folio_inc_lru_refs_walk() | protected by folio_inc_lru_refs/inc_gen | +* +------------------------------------------+------------------------------------------+
include/linux/mm_inline.h static inline unsigned long lru_gen_folio_seq(const struct lruvec *lruvec, · line 339
Quoted 10 lines
include/linux/mm_inline.h +7
-1+* | PG_active (set at isolation or refault) | | +* +--------------------+---------------------+--------------------+---------------------+ +* | LRU_REFS_MAX | LRU_REFS_WORKINGSET | LRU_REFS_MAX | LRU_REFS_WORKINGSET | +* +------------------------------------------+------------------------------------------+ +* |<-------------- MIN_NR_GENS ------------->| | +* |<----------------------------------- MAX_NR_GENS ----------------------------------->| */ if (folio_test_active (folio)) - gen =MIN_NR_GENS -folio_test_workingset (folio); + gen =MIN_NR_GENS - (refs >=LRU_REFS_WORKINGSET );
Could we define the "workingset" variant earlier so we can reuse it here?
workingset = refs >= LRU_REFS_WORKINGSET;
include/linux/mm_inline.h static inline unsigned long lru_gen_folio_seq(const struct lruvec *lruvec, · line 347
Quoted 9 lines
include/linux/mm_inline.h +1
-1else if (reclaiming) gen =MAX_NR_GENS ; else if ((!folio_is_file_lru(folio) && !folio_test_swapcache(folio)) ||@@ -324,7 +344,7 @@ static inline unsigned long lru_gen_folio_seq(const struct lruvec *lruvec, (folio_test_dirty(folio) || folio_test_writeback(folio)))) gen =MIN_NR_GENS ; else - gen =MAX_NR_GENS - (folio_test_workingset (folio) ||folio_test_referenced (folio)); + gen =MAX_NR_GENS - (refs >=LRU_REFS_WORKINGSET );
As above.
Quoted 401 lines
include/linux/mm_inline.h +5
-1return max (READ_ONCE (lrugen->max_seq) - gen +1 ,READ_ONCE (lrugen->min_seq[type])); }@@ -338,6 +358,7 @@ static inline bool lru_gen_add_folio(struct lruvec *lruvec, struct folio *folio,int zone =folio_zonenum (folio);struct lru_gen_folio *lrugen = &lruvec->lrugen; +BUILD_BUG_ON (BIT (LRU_GEN_WIDTH -1 ) !=MAX_NR_GENS );VM_WARN_ON_ONCE_FOLIO (gen !=-1 , folio);if (folio_test_unevictable (folio) || !lrugen->enabled)@@ -392,7 +413,6 @@ static inline bool lru_gen_del_folio(struct lruvec *lruvec, struct folio *folio,*/ static inline void folio_migrate_lru_refs (struct folio *new,const struct folio *old) { -BUILD_BUG_ON (LRU_REFS_MASK &BIT (PG_referenced));folio_set_lru_refs (new,folio_lru_refs (old)); }#else /* !CONFIG_LRU_GEN */ @@ -422,6 +442,10 @@ static inline bool lru_gen_del_folio(struct lruvec *lruvec, struct folio *folio,return false; } +static inline void folio_inc_lru_refs (struct folio *folio,unsigned int flags) +{ +} +static inline void folio_migrate_lru_refs (struct folio *new,const struct folio *old) {if (folio_test_referenced (old))include/linux/mmzone.h +105
-40@@ -453,57 +453,122 @@ enum lruvec_flags {#define MAX_NR_GENS 4U/* -* Each generation is divided into multiple tiers. A folio accessed N times -* through file descriptors is in tier order_base_2(N). A folio in the first -* tier (N=0,1) is marked by PG_referenced unless it was faulted in through page -* tables or read ahead. A folio in the last tier (MAX_NR_TIERS-1) is marked by -* PG_workingset. A folio in any other tier (1<N<5) between the first and last -* is marked by additional bits of LRU_REFS_WIDTH in folio->flags. +* Each generation is divided into multiple tiers. A folio's referenced +* count maps to a tier as shown below: * -* In contrast to moving across generations which requires the LRU lock, moving -* across tiers only involves atomic operations on folio->flags and therefore -* has a negligible cost in the buffered access path. In the eviction path, -* comparisons of refaulted/(evicted+protected) from the first tier and the rest -* infer whether folios accessed multiple times through file descriptors are -* statistically hot and thus worth protecting. +* MGLRU (frequency guidance) +* Refs Tier |- Refs: how many times (at least) a folio has been referenced. +* 0 0 |- Mostly cold pages, readahead, etc. [1] +* 1 0 |= LRU_REFS_REFERENCED: Used at least once. [2] +* -WORKINGSET-+|- Pages beyond are workingset and never fall below this floor. [3] +* 2 1<-+|= LRU_REFS_WORKINGSET: Classical workingset, accessed twice, protected. [4] +* 3 2 |- LRU_REFS_PROTECTED: Protected workingset, promoted pages capped at here. [5] +* 4 2 | +* 5 3 |- The tier here is MAX_NR_TIERS - 1 +* 6 3 | +* 7 3 |= LRU_REFS_MAX: Promotion candidate. [6] +* -PROMOTION->-/ * -* MAX_NR_TIERS is set to 4 so that the multi-gen LRU can support twice the -* number of categories of the active/inactive LRU when keeping track of -* accesses through file descriptors. This uses MAX_NR_TIERS-2 spare bits in -* folio->flags, masked by LRU_REFS_MASK. +* Ideally each tier holds folios of similar access patterns: lower tiers +* are less important and evicted faster. A page's reference count and +* tier are capped when it changes generation, preventing it from +* dominating the new generation based on old-generation access history. +* Generation ordering already ensures a newer-gen page is hotter than an +* older-gen one regardless of tier. +* +* Refs tracks accesses from two sources: page table (lazily collected by +* the page table aging walk or rmap eviction lookup) and file descriptors +* (by folio_mark_accessed). Page table accesses are weighted heavier +* because the accessed bit is sticky (undercounts repeated accesses), +* passively collected, and page faults are generally more important as +* userspace does not expect a memory access to block on reclaim. Both +* access types increment refs by one; the result is capped at +* LRU_REFS_PROTECTED on promotion or deferral, or LRU_REFS_MAX otherwise. +* +* 1. Tier is fls(N-1) for N > 1, 0 otherwise. Folios with zero +* accesses (refs == 0) are generally cold, e.g. readahead folios. +* +* Freshly allocated folios start with refs == 0; faulted and mapped +* folios have their page table access bit set, so the first page table +* access check always sets LRU_REFS_REFERENCED. That is the second +* chance described above MIN_NR_GENS: it moves the folio one +* generation forward if it is at the tail of its LRU, i.e., in one +* of the two oldest generations of its type. +* +* 2. Folios accessed once stay on tier 0: one-time usage does not +* qualify for protection. A second access advances the folio, +* aligning with classical LRU's use-twice threshold. A second page +* table access promotes to the latest gen; file access only defers +* eviction from the tail gens of its type. +* +* 3. Folios accessed at least twice are considered workingset. This +* mostly aligns with classical LRU: at least one I/O is saved by +* keeping them in memory. Folios at or above this level never fall +* below tier 1 (the workingset floor), so tier 0 stays a clean tier +* for cold cache while tier 1 serves as the fallback line for +* actually reused or historically hot folios. +* +* Folios refaulted through a page fault at refs 1 will enter the second +* newest gen, so faulting will be protected better. +* +* 4. Starting from tier 1, PID protection sacrifices lower tiers to +* protect higher tiers by comparing refault rates for long-term +* accuracy, and caps higher refs to this value. Since PID protection +* bypasses page table lookup and clearing, when a further eviction +* attempt occurs after PID loosens, the folio's page table access is +* rechecked and a referenced folio is put back with refs capped to +* this value as well. This also gives folios a fair opportunity to be +* promoted by file access again. +* +* Folios refaulted through a page fault at tier 1 or above are activated +* and enter the newest gen. Non fault page will enter second oldest gen, +* driving aging and workingset shifting. +* +* 5. Pages beyond the ordinary workingset tier form new tiers for the +* PID controller to protect differently. Folios at or above this +* level are capped at LRU_REFS_PROTECTED on promotion or deferral, +* and at LRU_REFS_WORKINGSET under PID protection in the oldest +* generation, where they represent a historical workingset. +* +* 6. Folios that reach LRU_REFS_MAX are advanced to the next generation +* on further access, with refs capped to LRU_REFS_PROTECTED. This +* gives them a fair start for advancement to an even newer generation +* while keeping hot folios distinguishable. +* +* Tiering uses PG_referenced and PG_workingset as the lower two bits, +* and the bits masked by LRU_REFS_MASK as the higher bits, so the refs +* count ranges from 0 to LRU_REFS_MAX. A folio is on the workingset +* tier once accessed at least twice, which is more consistent with the +* classical LRU. +* +* A folio's referenced count never goes backwards except upon gen +* increase as described above, or when explicitly reset by +* lru_gen_clear_refs(). Refault of a reclaimed folio restores +* its referenced count, capped at LRU_REFS_PROTECTED, which aligns with +* promotion. Page table refaults of previous workingset folios send +* them to the latest gen, driving aging faster. +* +* MAX_NR_TIERS is set to 4 so that the multi-gen LRU can support twice +* the number of categories of the active/inactive LRU. */ #define MAX_NR_TIERS 4U#define LRU_TIER_MIN 0U#define LRU_TIER_MAX (MAX_NR_TIERS - 1) +/* Access source flags for folio_inc_lru_refs() */ +#define LRU_REF_MAPPED 0x1U +#define LRU_REF_EXEC 0x2U + +#define LRU_REFS_REFERENCED 0x1 +#define LRU_REFS_WORKINGSET 0x2 +#define LRU_REFS_PROTECTED 0x3 +#ifndef __GENERATING_BOUNDS_H#define LRU_GEN_MASK ((BIT(LRU_GEN_WIDTH) - 1) << LRU_GEN_PGOFF)#define LRU_REFS_MASK ((BIT(LRU_REFS_WIDTH) - 1) << LRU_REFS_PGOFF) -#define LRU_REFS_MAX BIT(LRU_REFS_WIDTH) - -/* -* For folios accessed multiple times through file descriptors, -* lru_gen_inc_refs() sets additional bits of LRU_REFS_WIDTH in folio->flags -* after PG_referenced, then PG_workingset after LRU_REFS_WIDTH. After all its -* bits are set, i.e., LRU_REFS_FLAGS|BIT(PG_workingset), a folio is lazily -* promoted into the second oldest generation in the eviction path. And when -* folio_inc_gen() does that, it clears LRU_REFS_FLAGS so that -* lru_gen_inc_refs() can start over. Note that for this case, LRU_REFS_MASK is -* only valid when PG_referenced is set. -* -* For folios accessed multiple times through page tables, folio_update_gen() -* from a page table walk or lru_gen_set_refs() from a rmap walk sets -* PG_referenced after the accessed bit is cleared for the first time. -* Thereafter, those two paths set PG_workingset and promote folios to the -* youngest generation. Like folio_inc_gen(), folio_update_gen() also clears -* PG_referenced. Note that for this case, LRU_REFS_MASK is not used. -* -* For both cases above, after PG_workingset is set on a folio, it remains until -* this folio is either reclaimed, or "deactivated" by lru_gen_clear_refs(). It -* can be set again if lru_gen_test_recent() returns true upon a refault. -*/ -#define LRU_REFS_FLAGS (LRU_REFS_MASK | BIT(PG_referenced)) +#define LRU_REFS_FLAGS (LRU_REFS_MASK | BIT(PG_referenced) | BIT(PG_workingset)) +#define LRU_REFS_MAX (BIT(LRU_REFS_WIDTH + 2) - 1)struct lruvec ;struct page_vma_mapped_walk ;kernel/bounds.c +1
-1@@ -25,7 +25,7 @@ int main(void)DEFINE (SPINLOCK_SIZE ,sizeof (spinlock_t));#ifdef CONFIG_LRU_GEN DEFINE (LRU_GEN_WIDTH ,order_base_2 (MAX_NR_GENS +1 )); -DEFINE (__LRU_REFS_WIDTH,MAX_NR_TIERS -2 ); +DEFINE (__LRU_REFS_WIDTH,MAX_NR_TIERS -3 );#else DEFINE (LRU_GEN_WIDTH ,0 );DEFINE (__LRU_REFS_WIDTH,0 );mm/folio.c +2
-48@@ -273,7 +273,6 @@ static void lru_activate(struct lruvec *lruvec, struct folio *folio)if (folio_test_active (folio) ||folio_test_unevictable (folio))return ; -lruvec_del_folio (lruvec, folio);folio_set_active (folio);lruvec_add_folio (lruvec, folio);@@ -352,32 +351,6 @@ static void __lru_cache_activate_folio(struct folio *folio)#ifdef CONFIG_LRU_GEN -static void lru_gen_inc_refs (struct folio *folio) -{ -unsigned long new_flags, old_flags =READ_ONCE (*folio_flags (folio,0 )); -int refs; - -if (folio_test_unevictable (folio)) -return ; - -/* see the comment on LRU_REFS_FLAGS */ -if (!folio_lru_refs (folio)) { -folio_set_lru_refs (folio,1 ); -return ; - } - -do { - new_flags = old_flags; - refs =lru_get_refs_flags (old_flags); -if (refs ==LRU_REFS_MAX ) { -if (!folio_test_workingset (folio)) -folio_set_workingset (folio); -return ; - } -lru_set_refs_flags (&new_flags, refs +1 ); - }while (!try_cmpxchg (folio_flags (folio,0 ), &old_flags, new_flags)); -} -static bool lru_gen_clear_refs (struct folio *folio) {int gen =folio_lru_gen (folio);@@ -388,7 +361,6 @@ static bool lru_gen_clear_refs(struct folio *folio)return true;folio_set_lru_refs (folio,0 ); -folio_clear_workingset (folio);rcu_read_lock (); seq =READ_ONCE (folio_lruvec (folio)->lrugen.min_seq[type]);@@ -399,10 +371,6 @@ static bool lru_gen_clear_refs(struct folio *folio)#else /* !CONFIG_LRU_GEN */ -static void lru_gen_inc_refs (struct folio *folio) -{ -} -static bool lru_gen_clear_refs (struct folio *folio) {return false;@@ -428,7 +396,8 @@ void folio_mark_accessed(struct folio *folio)if (folio_test_dropbehind (folio))return ;if (lru_gen_enabled ()) { -lru_gen_inc_refs (folio); +if (!folio_test_unevictable (folio)) +folio_inc_lru_refs (folio,0 );return ; }@@ -474,21 +443,6 @@ void folio_add_lru(struct folio *folio) folio_test_unevictable(folio), folio);VM_BUG_ON_FOLIO (folio_test_lru (folio), folio); -/* -* For refaulted workingset folios, set PG_active so they -* can be added to active generations. -* For prefaulted file folios, folio_mark_accessed() sets -* PG_referenced so lru_gen_folio_seq() places them into -* the second oldest generation. -*/ -if (lru_gen_enabled () && !folio_test_unevictable (folio) && -lru_gen_in_fault () && !(current->flags &PF_MEMALLOC )) { -if (folio_test_workingset (folio)) -folio_set_active (folio); -else if (!folio_test_referenced (folio)) -folio_mark_accessed (folio); - } -folio_batch_add_and_move (folio, lru_add); }EXPORT_SYMBOL (folio_add_lru);mm/vmscan.c +71
-13@@ -931,38 +931,186 @@ enum folio_references { };#ifdef CONFIG_LRU_GEN +/****************************************************************************** +* Referenced count feedback +******************************************************************************/ +/* -* Only used on a mapped folio in the eviction (rmap walk) path, where promotion -* needs to be done by taking the folio off the LRU list and then adding it back -* with PG_active set. In contrast, the aging (page table walk) path uses -* folio_update_gen(). +* The folio_inc_lru_refs{_*} helpers below collect the referenced info +* (hotness) from other parts, including the page table walker, the rmap walk +* upon eviction, the rmap lookaround, and file descriptors +* (folio_mark_accessed). +* +* Page table accesses use refs from either source. The first reference +* advances tail-gen folios by one generation; a second promotes to the +* newest. Executable file folios promote on their first access to avoid +* I/O thrashing. Isolated rmap accesses use evict_folios() for putback. +* +* Promotion changes folio->flags; sort_folio() or inc_min_seq() moves the +* folio later. Young PTEs found during unmapping use folio_mark_accessed() +* and follow the file descriptor rules below. +* +* File descriptor accesses do not promote. They only defer eviction from +* the tail gens of their type, and only once the folio is a workingset +* folio (LRU_REFS_WORKINGSET), leaving the rest to PID protection. Page +* table accesses are treated more generously because the accessed bit is +* sticky (it under-counts repeated accesses) and because a page fault is +* more costly than file descriptor I/O. +* +* PID protection operates on tier > 0 folios. The one proactive promotion +* outside of it and the page table path is the overflow case where the +* referenced count exceeds LRU_REFS_MAX, which means the folio is hotter +* than everything else in its generation. +* +* Whenever a folio changes generation here its referenced count is capped at +* LRU_REFS_PROTECTED, so it starts at or below the protected tier regardless +* of its old-generation access history. PID protection (folio_inc_gen) caps +* at LRU_REFS_WORKINGSET independently. */ -static bool lru_gen_set_refs (struct folio *folio,const vma_flags_t *vma_flags) -{ -/* see the comment on LRU_REFS_FLAGS */ -if (!folio_test_referenced (folio) && !folio_test_workingset (folio)) { -/* Activate file-backed executable folios after first usage. */ -if (is_exec_file_folio (folio, vma_flags)) { -folio_set_workingset (folio); -folio_set_lru_refs (folio,0 ); -return true; + +/* +* Update the folio's lru refs indicator. The caller doesn't need to hold +* the folio lock, isolate the folio, or hold the lruvec lock. Used by both +* cache access (flags == 0) and page table access (LRU_REF_MAPPED, +* optionally with LRU_REF_EXEC). +*/ +void folio_inc_lru_refs (struct folio *folio,unsigned int flags) +{ +int max_gen; +int type, refs, old_gen, gen; +unsigned long new_flags, old_flags, max_seq; +struct lru_gen_folio *lrugen; +struct lruvec *lruvec =NULL ; + + type =folio_is_file_lru (folio); + old_flags =READ_ONCE (*folio_flags (folio,0 )); + do { + new_flags = old_flags; + old_gen = lru_get_gen_flags(old_flags); + refs = lru_get_refs_flags(old_flags) + 1; + gen = old_gen; + if (old_gen < 0) + goto out; + /* + * Lock the lruvec if the folio is on-list. We are already + * doing lazy promotion so in theory we don't need this, + * but for now, concurrent aging would still corrupt the + * size counters. This is a temporary limitation and + * will be lifted very soon, so the lock here is not a + * performance concern. + */ + if (!lruvec) { + lruvec = lruvec_live_lock_irq(folio_lruvec(folio)); + lrugen = &lruvec->lrugen; } + max_seq = READ_ONCE(lrugen->max_seq); + max_gen = lru_gen_from_seq(max_seq);
mm/vmscan.c enum folio_references { · line 1014
Quoted 10 lines
mm/vmscan.c +6
-3+if (old_gen == max_gen) + goto out; -folio_set_lru_refs (folio,1 ); -return false; - } +if (flags & (LRU_REF_MAPPED |LRU_REF_EXEC )) { +/* Promote second page table access or executable */ +if (refs >LRU_REFS_REFERENCED || flags &LRU_REF_EXEC ) + gen = max_gen;
This looks a bit odd to me. Could we handle LRU_REF_EXEC in a separate branch instead of mixing it with refs > LRU_REFS_REFERENCED?
mm/vmscan.c enum folio_references { · line 1017
Quoted 3 lines
mm/vmscan.c +3
-0+/* First access only defers eviction of a tail gen */ + else if (lru_gen_at_tail(lruvec, type, old_gen)) + gen = (old_gen +1 ) %MAX_NR_GENS ;
The logic makes a lot of sense to me. It should be able to differentiate readahead folios from those that are actually mapped and likely to be accessed more than once.
If we allow two generations to remain, this could be a problem because old_gen + 1 would overflow. Maybe add a VM_WARN_ON() to guard against this case?
mm/vmscan.c enum folio_references { · line 1023
Quoted 6 lines
mm/vmscan.c +6
-0+ refs =min (refs,LRU_REFS_PROTECTED ); + }else if (refs >LRU_REFS_MAX ) { +/* LRU refs counting overflow, bump the gen */ + gen = (old_gen +1 ) %MAX_NR_GENS ; + refs =LRU_REFS_PROTECTED ; + }else if (lru_gen_at_tail (lruvec, type, old_gen) && refs >=LRU_REFS_WORKINGSET ) {
Sometimes you use >= LRU_REFS_WORKINGSET, while elsewhere you use refs > LRU_REFS_REFERENCED. Can we unify these checks or define a workingset variant?
Quoted 81 lines
mm/vmscan.c +72
-8+/* Defer eviction of just accessed workingset */ + gen = (old_gen +1 ) %MAX_NR_GENS ; + refs =min (refs,LRU_REFS_PROTECTED ); + } +out: + refs =min (refs,LRU_REFS_MAX ); +lru_set_refs_flags (&new_flags, refs); +if (gen != old_gen) +lru_set_gen_flags (&new_flags, gen); +if (new_flags == old_flags) +break ; + }while (!try_cmpxchg (folio_flags (folio,0 ), &old_flags, new_flags)); -/* Promote on second access */ -if (folio_lru_refs (folio) >1 ) { -folio_set_workingset (folio); -folio_set_lru_refs (folio,0 ); - }else { -folio_mark_accessed (folio); - } -return true; +if (gen != old_gen) +lru_gen_update_size (lruvec, folio, old_gen, gen); +if (lruvec) +lruvec_unlock_irq (lruvec); +} + +/* +* Update the folio's lru refs indicator during a page table walk or the +* look-around. max_seq can be stale as neither holds the LRU lock. +* +* Returns the old generation and stores the new generation in @new_gen if +* the folio is on the LRU and not in the newest generation, or -1 otherwise. +*/ +static int folio_inc_lru_refs_walk (struct folio *folio,struct lruvec *lruvec, +const vma_flags_t *vma_flags, +int *new_gen,int *type) +{ +unsigned long new_flags, old_flags =READ_ONCE (*folio_flags (folio,0 )); +int refs, gen, max_gen, ret; +unsigned long max_seq; + +do { + max_seq =READ_ONCE (lruvec->lrugen.max_seq); + max_gen =lru_gen_from_seq (max_seq); + gen =lru_get_gen_flags (old_flags); + refs =lru_get_refs_flags (old_flags) +1 ; + *type =folio_flags_is_file_lru (&old_flags); + new_flags = old_flags; + +if (gen >=0 && gen != max_gen) { + ret = gen; +/* Promote second page table access or executable */ +if (refs >LRU_REFS_REFERENCED ||is_exec_file_folio (folio, vma_flags)) + *new_gen = max_gen; +/* First access only defers eviction of a tail gen */ +else if (lru_gen_at_tail (lruvec, *type, gen)) + *new_gen = (gen +1 ) %MAX_NR_GENS ; +else + *new_gen = gen; +lru_set_gen_flags (&new_flags, *new_gen); +lru_set_refs_flags (&new_flags,min (refs,LRU_REFS_PROTECTED )); + }else { + ret =-1 ; +lru_set_refs_flags (&new_flags,min (refs,LRU_REFS_MAX )); + } +if (new_flags == old_flags) +break ; + }while (!try_cmpxchg (folio_flags (folio,0 ), &old_flags, new_flags)); + +return ret; +} + +/* +* Update the lru refs indicator of an isolated folio, only used on +* mapped folios upon the final eviction. +* +* Increments the refs count (capped at LRU_REFS_PROTECTED, evict_folios() +* then caps it at LRU_REFS_WORKINGSET). Returns true if the caller should +* activate the folio (second access or executable), false to put it back +* for a second chance.
mm/vmscan.c enum folio_references { · line 1106
Quoted 10 lines
mm/vmscan.c +10
-0+*/ +static bool folio_inc_lru_refs_isolated (struct folio *folio,const vma_flags_t *vma_flags) +{ +unsigned long new_flags, old_flags =READ_ONCE (*folio_flags (folio,0 )); +int refs; + + do { + new_flags = old_flags; + refs = lru_get_refs_flags(old_flags) + 1; + lru_set_refs_flags(&new_flags, min(refs, LRU_REFS_PROTECTED));
I'm having a hard time understanding why an activated folio still keeps LRU_REFS_PROTECTED, since it will be promoted to the active list anyway :-)
Later, I see that you set it to LRU_REFS_WORKINGSET in evict_folios():
folio_set_lru_refs(folio, min(folio_lru_refs(folio), LRU_REFS_WORKINGSET));
So, is the purpose to distinguish between max_seq and max_seq - 1 even when we know the folio will be placed on the active list?
My concern is that after the folio is moved to the appropriate generation, LRU_REFS_PROTECTED or LRU_REFS_WORKINGSET may still remain set. Are these flags cleared somewhere?
Quoted 12 lines
mm/vmscan.c +5
-1+ } while (!try_cmpxchg(folio_flags(folio, 0), &old_flags, new_flags)); + +/* Promote second page table access or executable */ +return refs >LRU_REFS_REFERENCED ||is_exec_file_folio (folio, vma_flags); }#else -static bool lru_gen_set_refs (struct folio *folio,const vma_flags_t *vma_flags) +static bool folio_inc_lru_refs_isolated (struct folio *folio,const vma_flags_t *vma_flags) {return false; }
mm/vmscan.c static enum folio_references folio_check_references(struct folio *folio, · line 1152
Quoted 9 lines
mm/vmscan.c +2
-1@@ -997,7 +1145,8 @@ static enum folio_references folio_check_references(struct folio *folio,if (!referenced_ptes)return FOLIOREF_RECLAIM ; -return lru_gen_set_refs (folio, &vma_flags) ?FOLIOREF_ACTIVATE :FOLIOREF_KEEP ; +return folio_inc_lru_refs_isolated (folio, &vma_flags) ? +FOLIOREF_ACTIVATE :FOLIOREF_KEEP ; } referenced_folio =folio_test_clear_referenced (folio);
Thanks
Barry
Re: [PATCH v4 04/17] mm/mglru: frequency guided workingset promotion (MGLRU-FG)
Quoted 146 lines · Barry Song
Quoted 107 lines · On Fri, Oct 16, 2026 at 2:15 AM Kairui Song via B4 Relay…
From: Kairui Song <[email protected]>
Complement MGLRU's eviction-time tier-PID protection with access-time frequency-guided promotion. Introduce a unified set of helpers built based on referenced (access) count of a folio.
Each access increments a folio's referenced count stored in folio flags (refs), refs still maps to a logarithmic tier just like before, but with more formal bit definitions, a few special thresholds are introduced:
LRU_REFS_REFERENCED(1),LRU_REFS_WORKINGSET(2),LRU_REFS_PROTECTED(3), andLRU_REFS_MAX(7). When refs reaches a certain threshold, the folio is promoted proactively instead of waiting for the PID controller to kick in.Also simplify MGLRU's usage of
PG_workingsetandPG_referenced: they become the low two bits of the refs count, with the higher bits provided byLRU_REFS_MASK. This reduces MGLRU's original refs count bit usage by one, since only one extra bit is now needed to record a max referenced count of 7, and makes MGLRU's refs accounting more accurate.This doesn't affect classical LRU in any way, and it addresses several shortcomings of MGLRU's old tier-only cache protection model:
- Long feedback loop: protection only activated after enough re-faults, by which time the hot folios are already evicted, or no longer hot.
- Limited tier resolution: once referenced count exceeded the bits limit (8 previously), MGLRU could no longer distinguish hotter folios as they are capped by the tier. And what's worse,
PG_workingsetforces a folio to stay on tier 3.- Eviction hotness reversion: because PID protection activates upon eviction and always targets the LRU tail, it tends to protect cold tail folios at the expense of hotter head folios. Once the tail folios consume the PID protection budget, head folios lose their protection.
- Additionally, the PID cannot distinguish the access time of folios that share the same reference count, and there are only 4 tiers.
To achieve a frequency-guided framework, this commit introduces and reworks the
LRU_REFSrelated helpers and definitions; most of the work is done by the helpers below, and their inline comments describe the details.-
folio_inc_lru_refs(): Called on any cache access (folio_mark_accessed) or page table access. This is the main helper: it promotes folios according to their access frequency.A first access only defers eviction for a folio at the tail of its LRU, i.e., in one of the
MIN_NR_GENSoldest generations of its own type (seelru_gen_at_tail()), and a workingset folio accessed through a file descriptor is deferred from the same tail. Those are the generations the eviction scans next, so the deferral moves the folio out of its way for one generation.Promotion is lazy: the gen bits and size counters are updated eagerly, while the list move is deferred to the next isolation. NOTE: For now, the lruvec lock is unconditionally taken on every on-list access to block concurrent aging; a lockless fast path will be implemented very soon in a following commit.
-
folio_inc_lru_refs_walk(): Used by the PTE walk path during aging and by the batched look-around, both without the LRU lock, somax_seqmay be stale. A first page table access only advances a folio at the tail of its LRU, i.e., in one of theMIN_NR_GENSoldest generations of its own type (second chance), a second access promotes it to the newest generation; this also performs lazy promotion.-
folio_inc_lru_refs_isolated(): Used by the rmap check before eviction. The folio is isolated and hence this doesn't perform promotion by itself; the folio will be added back to the right gen upon return according to the access frequency. This path also has a higher promotion bias.The eviction-time
folio_inc_gen()still handles PID protection, but the protection ratio is softer than before since proactive promotion is mostly good enough already. The PID gain factors are relaxed from (2:3) to (1:2) and the setpoint now spans the cumulative mass of the tiers below the candidate instead of tier 0 alone.folio_inc_gen()caps refs at WORKINGSET so the folio retains enough history to stay above the cold tier. Tier 1 is the fallback tier for PID, and tier 2 is the fallback tier for frequency-guided promotion. The forced protection for full-refs folios is removed, obsoleted by the proactive promotion.Refaults are now activated purely according to access frequency:
the old fault bias applied infolio_add_lru()is simplified, since a folio's access history is a more consistent signal than the context of the faulting task. Page table access is still considered a slightly stronger signal.Consequently the placement hint for newly added file folios also uses
LRU_REFS_WORKINGSETinstead ofPG_referenced, so a folio accessed only once now starts in the oldest generation rather than the second oldest. The previous one-generation grace was an artifact of the fault bias which is well described in the cover letter of this series, and it depended on LRU drain timing.This also redefines
PG_workingsetandPG_referencedas the low two bits of the refs count, eliminating the old restriction whereLRU_REFS_MASKwas only valid whenPG_referencedwas set, and allows all paths to use the same encoding consistently. Following this idea, a workingset folio is now defined as refs >=LRU_REFS_WORKINGSET(2), matching the active/inactive LRU's definition and giving in-kernel consumers (PSI, readahead) consistent behavior on MGLRU, fixing the longstanding issue that these users don't work well with MGLRU.Quoted 3 lines
PG_workingsetandPG_referencedare no longer independent flags under MGLRU. Adjusting existing raw folio_test_*() callers to the new semantics is left as follow-ups.So this is the main course, with the earlier ones as appetizers and the later ones as desserts?
Overall, this dish looks very delicious to me.I ran kernel build on my machine, the result is quite similar with[1].
W/o patch:
eal 1m49.094s
user 25m31.484s
sys 3m40.959s
pswpin: 662112
pswpout: 2504415
pgpgin: 4424336
pgpgout: 10355273refault_file: 359626refault_anon: 670724W/ patch:
real 1m48.944s
user 25m30.987s
sys 3m34.605s
pswpin: 467952
pswpout: 2319080
pgpgin: 3481187
pgpgout: 9603332swpout_zero: 602042swpin_zero: 6250refault_file: 310538refault_anon: 474154
Quoted 1 line
But it behaves in a much more sensible way.
Hi Barry,
Thanks for the review and testing. Glad to see it worked for you.
Quoted 5 lines
I've had a preliminary look, but haven't reviewed it in detail yet. I have a few comments.
Right there could be some similarities, and some differences, e.g. no more lru_gen_in_fault hanlding here, or difference between anon / file. BTW did you test the whole series or just this patch? This patch have a few workaround as intermeidate step (e.g. the forced LRU lock in folio_mark_access, which is a pure burden but have to stay until very end of the series).
Quoted 25 lines
Quoted 10 lines
/**
include/linux/mm_inline.h +0
-5@@ -212,13 +216,13 @@ static inline void lru_set_refs_flags(unsigned long *flags, unsigned int refs)*/ static inline int lru_get_refs_flags (unsigned long flags) { -if (!(flags &BIT (PG_referenced))) -return 0 ; -/* -* Return the total number of accesses including PG_referenced. Also see -* the comment on LRU_REFS_FLAGS. include/linux/mm_inline.h static inline void lru_set_refs_flags(unsigned long *flags, unsigned int refs) · line 226
Quoted 10 lines
include/linux/mm_inline.h +7
-2-*/ -return ((flags &LRU_REFS_MASK ) >>LRU_REFS_PGOFF ) +1 ; +int refs; + +/* Return the total number of accesses. See the comment above MAX_NR_TIERS. */ + refs = (flags &BIT (PG_referenced)) ?BIT (0 ) :0 ; + refs += (flags &BIT (PG_workingset)) ?BIT (1 ) :0 ; + refs += ((flags &LRU_REFS_MASK ) >>LRU_REFS_PGOFF ) <<2 ; +return refs; }Could we use the following instead? Coming from a hardware register background, this looks more like register encoding to me:
static inline int
lru_get_refs_flags(unsigned long flags)
Quoted 8 lines
{
int refs;
refs = !!(flags & BIT(PG_referenced));
refs |= !!(flags & BIT(PG_workingset)) << 1;
refs |= ((flags & LRU_REFS_MASK) >> LRU_REFS_PGOFF) << 2;
return refs;
}No problem; it means the same thing and looks better indeed. I think I better change the return type to unsigned too, refs can never be negative (gen could be though, as a reserved value).
Quoted 30 lines
Quoted 16 lines
include/linux/mm_inline.h +4
-0static inline int folio_lru_refs (const struct folio *folio)@@ -236,14 +240,29 @@ static inline void folio_set_lru_refs(struct folio *folio, unsigned int refs) }while (!try_cmpxchg (folio_flags (folio,0 ), &old_flags, new_flags)); } +void folio_inc_lru_refs (struct folio *folio,unsigned int flags); +static inline int folio_lru_gen (const struct folio *folio) {return lru_get_gen_flags (READ_ONCE (*const_folio_flags (folio,0 ))); } +static inline bool lru_gen_at_tail (struct lruvec *lruvec,int type,int gen) +{include/linux/mm_inline.h static inline void folio_set_lru_refs(struct folio *folio, unsigned int refs) · line 261
Quoted 10 lines
include/linux/mm_inline.h +10
-0+unsigned long min_seq =READ_ONCE (lruvec->lrugen.min_seq[type]); + +/* +* Consider a folio is at the tail of its LRU when it is within +* MIN_NR_GENS of the oldest generation of its own type +*/ +BUILD_BUG_ON (MIN_NR_GENS !=2 ); +return gen ==lru_gen_from_seq (min_seq) || + gen ==lru_gen_from_seq (min_seq +1 ); +}If only two generations remain, should both be considered hot? If three generations remain, is only the oldest generation old?
Quoted 6 lines
Also, the name is a bit confusing, as "tail" usually refers to a list. Could we rename it to one of the following?
lru_gen_is_old()
orlru_gen_is_near_oldest()
Right, I wanted to introduce an idea of something called tailing gens (e.g. 8 tailing gens when there are 64 gens in total, folios in tailing gens are promoted on each access instead of multiple access, this works really well for fine grained hotness detection, and avoids over protection too). But for now this helper is just meant to tell the caller if the folio is close to be evicted or not, checking min_seq only could easily fall into a pitfall where the oldest gen is very short.
Maybe lru_gen_at_expiry? Or lru_gen_at_salvage?
BTW the whole picture involves three kinds of gens:
{tailing/expiry/salvage} gens (promote by one gen on each one FD access), frequency gens (promote by one gen on multiple FD access), times gens (promote to latest gen on PTE access); We now only have expiry gens and frequency gens, timed gens are extensions for the workingset report or pghot design. e.g we have 64 gens, then 8 tailing gens are expiry gens, 16 frequency gens, and 48 newest gens are timed gens.
https://lwn.net/Articles/976985/
I mentioned this in the cover letter that the "climbing of the file cache" will stop at 8 gens or 16 gens, this is the whole story, there is a lot of context and plan so I trimed them off to focus on the FG improvement first..
Quoted 45 lines
Quoted 32 lines
include/linux/mm_inline.h +7
-11+static inline bool lru_gen_is_active (const struct lruvec *lruvec,int gen) { -unsigned long max_seq = lruvec->lrugen.max_seq; +unsigned long max_seq =READ_ONCE (lruvec->lrugen.max_seq);VM_WARN_ON_ONCE (gen >=MAX_NR_GENS );@@ -300,23 +319,24 @@ static inline unsigned long lru_gen_folio_seq(const struct lruvec *lruvec, bool reclaiming) {int gen; +int refs =folio_lru_refs (folio);int type =folio_is_file_lru (folio);const struct lru_gen_folio *lrugen = &lruvec->lrugen;/* -* +-----------------------------------+-----------------------------------+ -* | Accessed through page tables and | Accessed through file descriptors | -* | promoted by folio_update_gen() | and protected by folio_inc_gen() | -* +-----------------------------------+-----------------------------------+ -* | PG_active (set while isolated) | | -* +-----------------+-----------------+-----------------+-----------------+ -* | PG_workingset | PG_referenced | PG_workingset | LRU_REFS_FLAGS | -* +-----------------------------------+-----------------------------------+ -* |<---------- MIN_NR_GENS ---------->| | -* |<---------------------------- MAX_NR_GENS ---------------------------->| +* +------------------------------------------+------------------------------------------+ +* | Accessed through page tables and | Accessed through file descriptors | +* | promoted by folio_inc_lru_refs_walk() | protected by folio_inc_lru_refs/inc_gen | +* +------------------------------------------+------------------------------------------+ include/linux/mm_inline.h static inline unsigned long lru_gen_folio_seq(const struct lruvec *lruvec, · line 339
Quoted 10 lines
include/linux/mm_inline.h +7
-1+* | PG_active (set at isolation or refault) | | +* +--------------------+---------------------+--------------------+---------------------+ +* | LRU_REFS_MAX | LRU_REFS_WORKINGSET | LRU_REFS_MAX | LRU_REFS_WORKINGSET | +* +------------------------------------------+------------------------------------------+ +* |<-------------- MIN_NR_GENS ------------->| | +* |<----------------------------------- MAX_NR_GENS ----------------------------------->| */ if (folio_test_active (folio)) - gen =MIN_NR_GENS -folio_test_workingset (folio); + gen =MIN_NR_GENS - (refs >=LRU_REFS_WORKINGSET );Could we define the "workingset" variant earlier so we can reuse it here?
Quoted 1 line
workingset = refs >=
LRU_REFS_WORKINGSET;
Looks good, will do.
Quoted 40 lines
Quoted 40 lines
mm/vmscan.c +38
-0+/* +* Update the folio's lru refs indicator. The caller doesn't need to hold +* the folio lock, isolate the folio, or hold the lruvec lock. Used by both +* cache access (flags == 0) and page table access (LRU_REF_MAPPED, +* optionally with LRU_REF_EXEC). +*/ +void folio_inc_lru_refs (struct folio *folio,unsigned int flags) +{ +int max_gen; +int type, refs, old_gen, gen; +unsigned long new_flags, old_flags, max_seq; +struct lru_gen_folio *lrugen; +struct lruvec *lruvec =NULL ; + + type =folio_is_file_lru (folio); + old_flags =READ_ONCE (*folio_flags (folio,0 )); + do { + new_flags = old_flags; + old_gen = lru_get_gen_flags(old_flags); + refs = lru_get_refs_flags(old_flags) + 1; + gen = old_gen; + if (old_gen < 0) + goto out; + /* + * Lock the lruvec if the folio is on-list. We are already + * doing lazy promotion so in theory we don't need this, + * but for now, concurrent aging would still corrupt the + * size counters. This is a temporary limitation and + * will be lifted very soon, so the lock here is not a + * performance concern. + */ + if (!lruvec) { + lruvec = lruvec_live_lock_irq(folio_lruvec(folio)); + lrugen = &lruvec->lrugen; } + max_seq = READ_ONCE(lrugen->max_seq); + max_gen = lru_gen_from_seq(max_seq); + if (old_gen == max_gen) + goto out;
Quoted 10 lines
mm/vmscan.c enum folio_references { · line 1014
Quoted 7 lines
mm/vmscan.c +4
-3-folio_set_lru_refs (folio,1 ); -return false; - } +if (flags & (LRU_REF_MAPPED |LRU_REF_EXEC )) { +/* Promote second page table access or executable */ +if (refs >LRU_REFS_REFERENCED || flags &LRU_REF_EXEC ) + gen = max_gen;This looks a bit odd to me. Could we handle
LRU_REF_EXECin a separate branch instead of mixing it with refs >LRU_REFS_REFERENCED?
Not sure how? They seem to want the same thing: promote the folio.
Quoted 11 lines
mm/vmscan.c enum folio_references { · line 1017
Quoted 3 lines
mm/vmscan.c +3
-0+/* First access only defers eviction of a tail gen */ + else if (lru_gen_at_tail(lruvec, type, old_gen)) + gen = (old_gen +1 ) %MAX_NR_GENS ;The logic makes a lot of sense to me. It should be able to differentiate readahead folios from those that are actually mapped and likely to be accessed more than once.
If we allow two generations to remain, this could be a problem because
old_gen+ 1 would overflow. Maybe add aVM_WARN_ON()to guard against this case?
We just checked if (old_gen == max_gen), so this should be fine? I mean overflow and the mod MAX_NR_GENS is also part of the sliding window logic.
Quoted 10 lines
mm/vmscan.c enum folio_references { · line 1023
Quoted 6 lines
mm/vmscan.c +6
-0+ refs =min (refs,LRU_REFS_PROTECTED ); + }else if (refs >LRU_REFS_MAX ) { +/* LRU refs counting overflow, bump the gen */ + gen = (old_gen +1 ) %MAX_NR_GENS ; + refs =LRU_REFS_PROTECTED ; + }else if (lru_gen_at_tail (lruvec, type, old_gen) && refs >=LRU_REFS_WORKINGSET ) {Sometimes you use >=
LRU_REFS_WORKINGSET, while elsewhere you use refs >LRU_REFS_REFERENCED. Can we unify these checks or define a workingset variant?
No problem; I can use a macro for that, as they mean the same thing.
Quoted 14 lines
Quoted 14 lines
mm/vmscan.c +14
-0+/* +* Update the lru refs indicator of an isolated folio, only used on +* mapped folios upon the final eviction. +* +* Increments the refs count (capped at LRU_REFS_PROTECTED, evict_folios() +* then caps it at LRU_REFS_WORKINGSET). Returns true if the caller should +* activate the folio (second access or executable), false to put it back +* for a second chance. +*/ +static bool folio_inc_lru_refs_isolated (struct folio *folio,const vma_flags_t *vma_flags) +{ +unsigned long new_flags, old_flags =READ_ONCE (*folio_flags (folio,0 )); +int refs; +
Quoted 8 lines
mm/vmscan.c enum folio_references { · line 1106
Quoted 4 lines
mm/vmscan.c +4
-0+ do { + new_flags = old_flags; + refs = lru_get_refs_flags(old_flags) + 1; + lru_set_refs_flags(&new_flags, min(refs, LRU_REFS_PROTECTED));I'm having a hard time understanding why an activated folio still keeps
LRU_REFS_PROTECTED, since it will be promoted to the active list anyway :-)
Right the FG idea is to always retain the frequency counts, instead of resetting them to 0, so folio_inc_lru_refs can promote FD accessed folios much more proactively, when a folio reaches LRU_REFS_MAX it will be promoted by one gen.
I did a in depth analyze of runtime distribution, with this, we can see very hot folio being promoted from max_seq - 1 to max_seq, and after aging, the hotness info is still kept and workingset stay stable and accurate (it's like the global aging of traditional LFU, which is obsoluted in upstream due to overhead despite having better accuracy, but now it comes with almost zero cost).
Quoted 5 lines
Later, I see that you set it to
LRU_REFS_WORKINGSETinevict_folios():
folio_set_lru_refs(folio, min(folio_lru_refs(folio), LRU_REFS_WORKINGSET));
Right that part is meant for aging the older folios and PID controller though. LRU_REFS_WORKINGSET could means historical workingset, and LRU_REFS_PROTECTED means folios being currently actively protected.
Also we are now giving the PID tiers a proper defination, tier 0 is readahead / cold cache, tier 1 is folios used at least once, and LRU_REFS_WORKINGSET is just the tier 1 fallback line, tier 2 is LRU_REFS_PROTECTED which is the proactive promotion wokringset /candidates, consistent with each other.
Quoted 8 lines
So, is the purpose to distinguish between
max_seqandmax_seq- 1 even when we know the folio will be placed on the active list?My concern is that after the folio is moved to the appropriate generation,
LRU_REFS_PROTECTEDorLRU_REFS_WORKINGSETmay still remain set. Are these flags cleared somewhere?
They are never cleared, only PID protection / eviction protection can reset it to LRU_REFS_WORKINGSET, which is the idea of FG. And it worked really well checking the zipf read data and especially for multi tier DB benchmarks. Folios in
And actually for the current mainline MGLRU impelmentation, PG_workinset is also never cleared and it will pin a folio at tier 3 causing over protection very easily, we will reset it to tier 1 here and with a softer PID protection factor, it seems much better in real workloads.
Barry Song
reviewerRe: [PATCH v4 04/17] mm/mglru: frequency guided workingset promotion (MGLRU-FG)
Quoted 3 lines · Kairui Song
Quoted 1 line · Barry Song
[...]
Quoted 40 lines
Quoted 33 lines
So this is the main course, with the earlier ones as appetizers and the later ones as desserts?
Overall, this dish looks very delicious to me.I ran kernel build on my machine, the result is quite similar with[1].
W/o patch:
eal 1m49.094s
user 25m31.484s
sys 3m40.959s
pswpin: 662112
pswpout: 2504415
pgpgin: 4424336
pgpgout: 10355273refault_file: 359626refault_anon: 670724W/ patch:
real 1m48.944s
user 25m30.987s
sys 3m34.605s
pswpin: 467952
pswpout: 2319080
pgpgin: 3481187
pgpgout: 9603332swpout_zero: 602042swpin_zero: 6250refault_file: 310538refault_anon: 474154Quoted 1 line
But it behaves in a much more sensible way.
Hi Barry,
Thanks for the review and testing. Glad to see it worked for you.
Quoted 1 line
Quoted 8 lines
Quoted 4 lines
I've had a preliminary look, but haven't reviewed it in detail yet. I have a few comments.
Right there could be some similarities, and some differences, e.g. no more
lru_gen_in_faulthanlding here, or difference between anon / file. BTW did you test the whole series or just this patch? This patch
I tested the whole series rather than this patch in isolation.
[...]
Quoted 13 lines
Quoted 4 lines
Could we use the following instead? Coming from a hardware register background, this looks more like register encoding to me:
static inline int
lru_get_refs_flags(unsigned long flags)Quoted 8 lines
{ int refs; refs = !!(flags & BIT(PG_referenced)); refs |= !!(flags & BIT(PG_workingset)) << 1; refs |= ((flags & LRU_REFS_MASK) >> LRU_REFS_PGOFF) << 2; return refs; }
Quoted 3 lines
No problem; it means the same thing and looks better indeed. I think I better change the return type to unsigned too, refs can never be negative (gen could be though, as a reserved value).
make sense to me. lru_get_refs_flags() is impossible to be negative.
Quoted 47 lines
Quoted 31 lines
Quoted 17 lines
static inline int
folio_lru_refs(const struct folio *folio)include/linux/mm_inline.h +4
-0@@ -236,14 +240,29 @@ static inline void folio_set_lru_refs(struct folio *folio, unsigned int refs) }while (!try_cmpxchg (folio_flags (folio,0 ), &old_flags, new_flags)); } +void folio_inc_lru_refs (struct folio *folio,unsigned int flags); +static inline int folio_lru_gen (const struct folio *folio) {return lru_get_gen_flags (READ_ONCE (*const_folio_flags (folio,0 ))); } +static inline bool lru_gen_at_tail (struct lruvec *lruvec,int type,int gen) +{include/linux/mm_inline.h static inline void folio_set_lru_refs(struct folio *folio, unsigned int refs) · line 261
Quoted 10 lines
include/linux/mm_inline.h +10
-0+unsigned long min_seq =READ_ONCE (lruvec->lrugen.min_seq[type]); + +/* +* Consider a folio is at the tail of its LRU when it is within +* MIN_NR_GENS of the oldest generation of its own type +*/ +BUILD_BUG_ON (MIN_NR_GENS !=2 ); +return gen ==lru_gen_from_seq (min_seq) || + gen ==lru_gen_from_seq (min_seq +1 ); +}If only two generations remain, should both be considered hot? If three generations remain, is only the oldest generation old?
Quoted 6 lines
Also, the name is a bit confusing, as "tail" usually refers to a list. Could we rename it to one of the following?
lru_gen_is_old()
orlru_gen_is_near_oldest()Right, I wanted to introduce an idea of something called tailing gens (e.g. 8 tailing gens when there are 64 gens in total, folios in tailing gens are promoted on each access instead of multiple access, this works really well for fine grained hotness detection, and avoids over protection too). But for now this helper is just meant to tell the caller if the folio is close to be evicted or not, checking
min_seqonly could easily fall into a pitfall where the oldest gen is very short.
Quoted 2 lines
Maybe
lru_gen_at_expiry? Orlru_gen_at_salvage?
at_expiry gives the impression that a timer is involved in triggering a timeout, while at_salvage is not very intuitive for non-native English speakers.
I'd still prefer lru_gen_is_old(); it's simpler and easier to understand.
Quoted 15 lines
BTW the whole picture involves three kinds of gens:
{tailing/expiry/salvage} gens (promote by one gen on each one FD access), frequency gens (promote by one gen on multiple FD access), times gens (promote to latest gen on PTE access); We now only have expiry gens and frequency gens, timed gens are extensions for the workingset report or pghot design. e.g we have 64 gens, then 8 tailing gens are expiry gens, 16 frequency gens, and 48 newest gens are timed gens.
https://lwn.net/Articles/976985/I mentioned this in the cover letter that the "climbing of the file cache" will stop at 8 gens or 16 gens, this is the whole story, there is a lot of context and plan so I trimed them off to focus on the FG improvement first..
[...]
Quoted 9 lines
Quoted 7 lines
include/linux/mm_inline.h static inline unsigned long lru_gen_folio_seq(const struct lruvec *lruvec, · line 339
Quoted 3 lines
if (
folio_test_active(folio))include/linux/mm_inline.h +1
-1- gen =MIN_NR_GENS -folio_test_workingset (folio); + gen =MIN_NR_GENS - (refs >=LRU_REFS_WORKINGSET );Could we define the "workingset" variant earlier so we can reuse it here?
workingset = refs >=
LRU_REFS_WORKINGSET;Looks good, will do.
thanks!
Quoted 52 lines
Quoted 41 lines
Quoted 41 lines
mm/vmscan.c +38
-0+/* +* Update the folio's lru refs indicator. The caller doesn't need to hold +* the folio lock, isolate the folio, or hold the lruvec lock. Used by both +* cache access (flags == 0) and page table access (LRU_REF_MAPPED, +* optionally with LRU_REF_EXEC). +*/ +void folio_inc_lru_refs (struct folio *folio,unsigned int flags) +{ +int max_gen; +int type, refs, old_gen, gen; +unsigned long new_flags, old_flags, max_seq; +struct lru_gen_folio *lrugen; +struct lruvec *lruvec =NULL ; + + type =folio_is_file_lru (folio); + old_flags =READ_ONCE (*folio_flags (folio,0 )); + do { + new_flags = old_flags; + old_gen = lru_get_gen_flags(old_flags); + refs = lru_get_refs_flags(old_flags) + 1; + gen = old_gen; + if (old_gen < 0) + goto out; + /* + * Lock the lruvec if the folio is on-list. We are already + * doing lazy promotion so in theory we don't need this, + * but for now, concurrent aging would still corrupt the + * size counters. This is a temporary limitation and + * will be lifted very soon, so the lock here is not a + * performance concern. + */ + if (!lruvec) { + lruvec = lruvec_live_lock_irq(folio_lruvec(folio)); + lrugen = &lruvec->lrugen; } + max_seq = READ_ONCE(lrugen->max_seq); + max_gen = lru_gen_from_seq(max_seq); + if (old_gen == max_gen) + goto out;Quoted 10 lines
mm/vmscan.c enum folio_references { · line 1014
Quoted 7 lines
mm/vmscan.c +4
-3-folio_set_lru_refs (folio,1 ); -return false; - } +if (flags & (LRU_REF_MAPPED |LRU_REF_EXEC )) { +/* Promote second page table access or executable */ +if (refs >LRU_REFS_REFERENCED || flags &LRU_REF_EXEC ) + gen = max_gen;This looks a bit odd to me. Could we handle
LRU_REF_EXECin a separate branch instead of mixing it with refs >LRU_REFS_REFERENCED?
Quoted 1 line
Not sure how? They seem to want the same thing: promote the folio.
I mean we could have a separate branch for LRU_REF_EXEC | LRU_REF_FORCE:
if (flags & (LRU_REF_EXEC | LRU_REF_FORCE)) {
gen = max_gen;
refs = min(refs, LRU_REFS_PROTECTED);
} else if (flags & LRU_REF_MAPPED) {
if (refs > LRU_REFS_REFERENCED)
gen = max_gen;
/* First access only defers eviction of a tail gen */
else if (lru_gen_at_tail(lruvec, file, old_gen))
gen = (old_gen + 1) % MAX_NR_GENS;
refs = min(refs, LRU_REFS_PROTECTED);
} else if (refs > LRU_REFS_MAX) {right now, it is:
if (flags & (LRU_REF_MAPPED | LRU_REF_EXEC | LRU_REF_FORCE)) {
if (refs > LRU_REFS_REFERENCED ||
flags & (LRU_REF_EXEC | LRU_REF_FORCE))
gen = max_gen;
/* First access only defers eviction of a tail gen */
else if (lru_gen_at_tail(lruvec, file, old_gen))
gen = (old_gen + 1) % MAX_NR_GENS;
refs = min(refs, LRU_REFS_PROTECTED);
} else if (refs > LRU_REFS_MAX) {a bit hard to follow.
Quoted 9 lines
Quoted 9 lines
mm/vmscan.c enum folio_references { · line 1017
Quoted 4 lines
mm/vmscan.c +3
-0+/* First access only defers eviction of a tail gen */ + else if (lru_gen_at_tail(lruvec, type, old_gen)) + gen = (old_gen +1 ) %MAX_NR_GENS ;The logic makes a lot of sense to me. It should be able to differentiate readahead folios from those that are actually mapped and likely to be accessed more than once.
Quoted 7 lines
Quoted 3 lines
If we allow two generations to remain, this could be a problem because
old_gen+ 1 would overflow. Maybe add aVM_WARN_ON()to guard against this case?We just checked if (
old_gen==max_gen), so this should be fine? I mean overflow and the modMAX_NR_GENSis also part of the sliding window logic.
Yep, I missed your check:
if (old_gen == max_gen)
goto out;[...]
Quoted 5 lines
Quoted 3 lines
Sometimes you use >=
LRU_REFS_WORKINGSET, while elsewhere you use refs >LRU_REFS_REFERENCED. Can we unify these checks or define a workingset variant?No problem; I can use a macro for that, as they mean the same thing.
right, thanks!
Quoted 24 lines
Quoted 15 lines
Quoted 15 lines
mm/vmscan.c +14
-0+/* +* Update the lru refs indicator of an isolated folio, only used on +* mapped folios upon the final eviction. +* +* Increments the refs count (capped at LRU_REFS_PROTECTED, evict_folios() +* then caps it at LRU_REFS_WORKINGSET). Returns true if the caller should +* activate the folio (second access or executable), false to put it back +* for a second chance. +*/ +static bool folio_inc_lru_refs_isolated (struct folio *folio,const vma_flags_t *vma_flags) +{ +unsigned long new_flags, old_flags =READ_ONCE (*folio_flags (folio,0 )); +int refs; +Quoted 8 lines
mm/vmscan.c enum folio_references { · line 1106
Quoted 4 lines
mm/vmscan.c +4
-0+ do { + new_flags = old_flags; + refs = lru_get_refs_flags(old_flags) + 1; + lru_set_refs_flags(&new_flags, min(refs, LRU_REFS_PROTECTED));I'm having a hard time understanding why an activated folio still keeps
LRU_REFS_PROTECTED, since it will be promoted to the active list anyway :-)
Quoted 5 lines
Right the FG idea is to always retain the frequency counts, instead of resetting them to 0, so
folio_inc_lru_refscan promote FD accessed folios much more proactively, when a folio reachesLRU_REFS_MAXit will be promoted by one gen.
folio_inc_lru_refs_isolated() is only called when referenced_ptes is true, so these should always be mapped folios:
if (lru_gen_enabled() && !lru_gen_switching()) {
if (!referenced_ptes)
return FOLIOREF_RECLAIM;
return folio_inc_lru_refs_isolated(folio, &vma_flags) ?
FOLIOREF_ACTIVATE : FOLIOREF_KEEP;
}When you say "FD-accessed folios" here, do you mean that these mapped folios can also be accessed through syscalls, and that you keep the refs to detect further FD accesses?
Quoted 8 lines
I did a in depth analyze of runtime distribution, with this, we can see very hot folio being promoted from
max_seq- 1 tomax_seq, and after aging, the hotness info is still kept and workingset stay stable and accurate (it's like the global aging of traditional LFU, which is obsoluted in upstream due to overhead despite having better accuracy, but now it comes with almost zero cost).Quoted 1 line
Quoted 9 lines
Quoted 4 lines
Later, I see that you set it to
LRU_REFS_WORKINGSETinevict_folios():
folio_set_lru_refs(folio, min(folio_lru_refs(folio), LRU_REFS_WORKINGSET));Right that part is meant for aging the older folios and PID controller though.
LRU_REFS_WORKINGSETcould means historical workingset, andLRU_REFS_PROTECTEDmeans folios being currently actively protected.
folio_inc_lru_refs_isolated() is called from the eviction path. Folios that are not reclaimed will go through:
__folio_set_lru_refs(folio, min(folio_lru_refs(folio), LRU_REFS_WORKINGSET));
in evict_folios().
So LRU_REFS_PROTECTED eventually becomesLRU_REFS_WORKINGSET(or 0, 1).
I'm still struggling to understand why we need a transition from LRU_REFS_PROTECTED to LRU_REFS_WORKINGSET (or 0/1 if folio_lru_refs() < LRU_REFS_WORKINGSET), since those folios will always end up in LRU_REFS_WORKINGSET (or 0/1) anyway.
Thanks
Barry
Kairui Song
maintainerPATCH v4 5/17 mm/mglru: make folio lru referenced times count a generic API
In reply to Kairui SongPure code shuffle, no behavior change.
Make the folio LRU refs helpers available regardless of CONFIG_LRU_GEN. Without MGLRU the refs bits are never set, so they are inert. Move the lru_gen_* helpers into the CONFIG_LRU_GEN section. This prepares for unifying the API for checking folio referenced and workingset status.
folio_migrate_lru_refs() now migrates the complete refs count, including PG_workingset (bit 1 of the encoding), bitwise identical to the direct copy dropped from folio_migrate_flags().
lru_set_refs_flags() skips the nonexistent mask bits when LRU_REFS_WIDTH collapses to 0, keeping the generic helpers inert for !CONFIG_LRU_GEN builds.
--- include/linux/mm_inline.h | 55 ++++++++++++++++++++++++----------------------- mm/migrate.c | 2 -- 2 files changed, 28 insertions(+), 29 deletions(-)
include/linux/mm_inline.h +28 -27
@@ -183,6 +183,12 @@ static inline int lru_get_gen_flags(unsigned long flags) return gen; } +static inline int folio_lru_gen (const struct folio *folio) +{ +return lru_get_gen_flags (READ_ONCE (*const_folio_flags (folio,0 ))); +} +#endif +/** * lru_set_refs_flags - Set the LRU referenced count to folio flags. * @flags: pointer to the folio flags
@@ -205,7 +211,8 @@ static inline void lru_set_refs_flags(unsigned long *flags, unsigned int refs) *flags |=BIT (PG_referenced);if (refs &BIT (1 )) *flags |=BIT (PG_workingset); - *flags |= ((unsigned long )refs >>2 ) <<LRU_REFS_PGOFF ; +if (LRU_REFS_WIDTH ) + *flags |= ((unsigned long )refs >>2 ) <<LRU_REFS_PGOFF ; }/**
@@ -240,13 +247,31 @@ static inline void folio_set_lru_refs(struct folio *folio, unsigned int refs) }while (!try_cmpxchg (folio_flags (folio,0 ), &old_flags, new_flags)); } +#ifdef CONFIG_LRU_GEN void folio_inc_lru_refs (struct folio *folio,unsigned int flags); +#else +static inline void folio_inc_lru_refs (struct folio *folio,unsigned int flags) +{ +/* Should not be called with !CONFIG_LRU_GEN */ +WARN_ON_ONCE (1 ); +} +#endif -static inline int folio_lru_gen (const struct folio *folio) +/** +* folio_migrate_lru_refs - copy the reference state to a new folio +* @new: the destination folio +* @old: the source folio +* +* Transfer the reference state to @new during migration: the MGLRU +* refs count, or PG_referenced and PG_workingset (bits 0-1 of the +* encoding) for the active/inactive LRU. +*/ +static inline void folio_migrate_lru_refs (struct folio *new,const struct folio *old) { -return lru_get_gen_flags (READ_ONCE (*const_folio_flags (folio,0 ))); +folio_set_lru_refs (new,folio_lru_refs (old)); } +#ifdef CONFIG_LRU_GEN static inline bool lru_gen_at_tail (struct lruvec *lruvec,int type,int gen) {unsigned long min_seq =READ_ONCE (lruvec->lrugen.min_seq[type]);
@@ -401,20 +426,6 @@ static inline bool lru_gen_del_folio(struct lruvec *lruvec, struct folio *folio, return true; } - -/** -* folio_migrate_lru_refs - copy the reference state to a new folio -* @new: the destination folio -* @old: the source folio -* -* Transfer the reference state to @new during migration: the MGLRU -* refs count, including PG_referenced, or just PG_referenced for the -* active/inactive LRU. -*/ -static inline void folio_migrate_lru_refs (struct folio *new,const struct folio *old) -{ -folio_set_lru_refs (new,folio_lru_refs (old)); -}#else /* !CONFIG_LRU_GEN */ static inline bool lru_gen_enabled (void )
@@ -441,16 +452,6 @@ static inline bool lru_gen_del_folio(struct lruvec *lruvec, struct folio *folio, {return false; } - -static inline void folio_inc_lru_refs (struct folio *folio,unsigned int flags) -{ -} - -static inline void folio_migrate_lru_refs (struct folio *new,const struct folio *old) -{ -if (folio_test_referenced (old)) -folio_set_referenced (new); -}#endif /* CONFIG_LRU_GEN */ static __always_inline
mm/migrate.c +0 -2
@@ -786,8 +786,6 @@ void folio_migrate_flags(struct folio *newfolio, struct folio *folio)folio_set_active (newfolio); }else if (folio_test_clear_unevictable (folio))folio_set_unevictable (newfolio); -if (folio_test_workingset (folio)) -folio_set_workingset (newfolio);if (folio_test_checked (folio))folio_set_checked (newfolio);/*
Signature · 1 line
2.56.0
[email protected]
AI reviewRe: [PATCH v4 05/17] mm/mglru: make folio lru referenced times count a generic API
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 13 lines
From: Kairui Song <[email protected]>
Pure code shuffle, no behavior change.
Make the folio LRU refs helpers available regardless of
CONFIG_LRU_GEN. Without MGLRU the refs bits are never set, so they are inert. Move the lru_gen_* helpers into theCONFIG_LRU_GENsection. This prepares for unifying the API for checking folio referenced and workingset status.
folio_migrate_lru_refs()now migrates the complete refs count, includingPG_workingset(bit 1 of the encoding), bitwise identical to the direct copy dropped fromfolio_migrate_flags().
Quoted 6 lines
lru_set_refs_flags()skips the nonexistent mask bits whenLRU_REFS_WIDTHcollapses to 0, keeping the generic helpers inert for !CONFIG_LRU_GEN builds.Tested-by zhaozhengzhuo <[email protected]>Signed-off-by Kairui Song <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
Kairui Song
maintainerPATCH v4 6/17 mm/mglru: move add/del LRU size accounting out of lru_gen_update_size()
In reply to Kairui SongPure code shuffle, no behavior change. lru_gen_update_size() now only updates the per-generation counters plus the promotion move; the addition and deletion active/inactive accounting move to lru_gen_add_folio() and lru_gen_del_folio(), which know the generation and can apply the active-window test directly.
The unevictable case is untouched: unevictable folios never enter lru_gen_add_folio() and keep being accounted by lruvec_add_folio() as before.
--- include/linux/mm_inline.h | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-)
include/linux/mm_inline.h +14 -14
@@ -313,21 +313,9 @@ static inline void lru_gen_update_size(struct lruvec *lruvec, struct folio *foliif (new_gen >=0 )atomic_long_add (delta, &lrugen->nr_pages[new_gen][type][zone]); -/* addition */ -if (old_gen <0 ) { -if (lru_gen_is_active (lruvec, new_gen)) - lru +=LRU_ACTIVE ; -__update_lru_size (lruvec, lru, zone, delta); +/* return now if not a promotion */ +if (old_gen <0 || new_gen <0 )return ; - } - -/* deletion */ -if (new_gen <0 ) { -if (lru_gen_is_active (lruvec, old_gen)) - lru +=LRU_ACTIVE ; -__update_lru_size (lruvec, lru, zone, -delta); -return ; - }/* promotion */ if (!lru_gen_is_active (lruvec, old_gen) &&lru_gen_is_active (lruvec, new_gen)) {
@@ -381,6 +369,8 @@ static inline bool lru_gen_add_folio(struct lruvec *lruvec, struct folio *folio,int gen =folio_lru_gen (folio);int type =folio_is_file_lru (folio);int zone =folio_zonenum (folio); +int delta =folio_nr_pages (folio); +enum lru_list lru = type *LRU_INACTIVE_FILE ;struct lru_gen_folio *lrugen = &lruvec->lrugen;BUILD_BUG_ON (BIT (LRU_GEN_WIDTH -1 ) !=MAX_NR_GENS );
@@ -396,6 +386,10 @@ static inline bool lru_gen_add_folio(struct lruvec *lruvec, struct folio *folio,set_mask_bits (folio_flags (folio,0 ),LRU_GEN_MASK |BIT (PG_active), flags);lru_gen_update_size (lruvec, folio,-1 , gen); +if (lru_gen_is_active (lruvec, gen)) + lru +=LRU_ACTIVE ; +__update_lru_size (lruvec, lru, zone, delta); +/* for folio_rotate_reclaimable() */ if (reclaiming)list_add_tail (&folio->lru, &lrugen->folios[gen][type][zone]);
@@ -409,6 +403,9 @@ static inline bool lru_gen_del_folio(struct lruvec *lruvec, struct folio *folio, {unsigned long flags;int gen =folio_lru_gen (folio); +int zone =folio_zonenum (folio); +int delta =folio_nr_pages (folio); +enum lru_list lru =folio_is_file_lru (folio) *LRU_INACTIVE_FILE ;if (gen <0 )return false;
@@ -422,6 +419,9 @@ static inline bool lru_gen_del_folio(struct lruvec *lruvec, struct folio *folio, gen = ((flags &LRU_GEN_MASK ) >>LRU_GEN_PGOFF ) -1 ;lru_gen_update_size (lruvec, folio, gen,-1 ); +if (lru_gen_is_active (lruvec, gen)) + lru +=LRU_ACTIVE ; +__update_lru_size (lruvec, lru, zone, -delta);list_del (&folio->lru);return true;
Signature · 1 line
2.56.0
[email protected]
AI reviewRe: [PATCH v4 06/17] mm/mglru: move add/del LRU size accounting out of lru_gen_update_size()
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 8 lines
From: Kairui Song <[email protected]>
Pure code shuffle, no behavior change.
lru_gen_update_size()now only updates the per-generation counters plus the promotion move; the addition and deletion active/inactive accounting move tolru_gen_add_folio()andlru_gen_del_folio(), which know the generation and can apply the active-window test directly.
Quoted 6 lines
The unevictable case is untouched: unevictable folios never enter
lru_gen_add_folio()and keep being accounted bylruvec_add_folio()as before.Tested-by zhaozhengzhuo <[email protected]>Signed-off-by Kairui Song <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
Barry Song
reviewerRe: [PATCH v4 06/17] mm/mglru: move add/del LRU size accounting out of lru_gen_update_size()
In reply to Kairui SongQuoted 9 lines · On Fri, Oct 16, 2026 at 2:15 AM Kairui Song via B4 Relay…
From: Kairui Song <[email protected]>
Pure code shuffle, no behavior change.
lru_gen_update_size()now only updates the per-generation counters plus the promotion move; the addition and deletion active/inactive accounting move tolru_gen_add_folio()andlru_gen_del_folio(), which know the generation and can apply the active-window test directly.
Quoted 7 lines
The unevictable case is untouched: unevictable folios never enter
lru_gen_add_folio()and keep being accounted bylruvec_add_folio()as before.Tested-by zhaozhengzhuo <[email protected]>Signed-off-by Kairui Song <[email protected]>---
The patch looks good to me.
Meanwhile, I've been struggling with the names of __update_lru_size() and lru_gen_update_size() for a long time.
Given that lru_gen_update_size() now only updatesnr_pages:
static inline void lru_gen_update_size(struct lruvec *lruvec, int type,
struct folio *folio, int old_gen, int new_gen)
{
...
if (old_gen >= 0)
atomic_long_sub(delta, &lrugen->nr_pages[old_gen][type][zone]);
if (new_gen >= 0)
atomic_long_add(delta, &lrugen->nr_pages[new_gen][type][zone]);
}while __update_lru_size() only handles active/inactive accounting, could we rename them to make their roles clearer? For example:
lru_gen_update_nr_pages()lru_gen_update_active_inactive_size()
The names are longer, but the lru_gen_ prefix helps distinguish this accounting from the actual active/inactive LRU lists.
Quoted 73 lines
include/linux/mm_inline.h | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-)include/linux/mm_inline.h +14
-15@@ -313,21 +313,9 @@ static inline void lru_gen_update_size(struct lruvec *lruvec, struct folio *foliif (new_gen >=0 )atomic_long_add (delta, &lrugen->nr_pages[new_gen][type][zone]); -/* addition */ -if (old_gen <0 ) { -if (lru_gen_is_active (lruvec, new_gen)) - lru +=LRU_ACTIVE ; -__update_lru_size (lruvec, lru, zone, delta); +/* return now if not a promotion */ +if (old_gen <0 || new_gen <0 )return ; - } - -/* deletion */ -if (new_gen <0 ) { -if (lru_gen_is_active (lruvec, old_gen)) - lru +=LRU_ACTIVE ; -__update_lru_size (lruvec, lru, zone, -delta); -return ; - }/* promotion */ if (!lru_gen_is_active (lruvec, old_gen) &&lru_gen_is_active (lruvec, new_gen)) {@@ -381,6 +369,8 @@ static inline bool lru_gen_add_folio(struct lruvec *lruvec, struct folio *folio,int gen =folio_lru_gen (folio);int type =folio_is_file_lru (folio);int zone =folio_zonenum (folio); +int delta =folio_nr_pages (folio); +enum lru_list lru = type *LRU_INACTIVE_FILE ;struct lru_gen_folio *lrugen = &lruvec->lrugen;BUILD_BUG_ON (BIT (LRU_GEN_WIDTH -1 ) !=MAX_NR_GENS );@@ -396,6 +386,10 @@ static inline bool lru_gen_add_folio(struct lruvec *lruvec, struct folio *folio,set_mask_bits (folio_flags (folio,0 ),LRU_GEN_MASK |BIT (PG_active), flags);lru_gen_update_size (lruvec, folio,-1 , gen); +if (lru_gen_is_active (lruvec, gen)) + lru +=LRU_ACTIVE ; +__update_lru_size (lruvec, lru, zone, delta); +/* for folio_rotate_reclaimable() */ if (reclaiming)list_add_tail (&folio->lru, &lrugen->folios[gen][type][zone]);@@ -409,6 +403,9 @@ static inline bool lru_gen_del_folio(struct lruvec *lruvec, struct folio *folio, {unsigned long flags;int gen =folio_lru_gen (folio); +int zone =folio_zonenum (folio); +int delta =folio_nr_pages (folio); +enum lru_list lru =folio_is_file_lru (folio) *LRU_INACTIVE_FILE ;if (gen <0 )return false;@@ -422,6 +419,9 @@ static inline bool lru_gen_del_folio(struct lruvec *lruvec, struct folio *folio, gen = ((flags &LRU_GEN_MASK ) >>LRU_GEN_PGOFF ) -1 ;lru_gen_update_size (lruvec, folio, gen,-1 ); +if (lru_gen_is_active (lruvec, gen)) + lru +=LRU_ACTIVE ; +__update_lru_size (lruvec, lru, zone, -delta);list_del (&folio->lru);return true; --
Quoted 3 lines
2.56.0
Thanks,
Barry
Re: [PATCH v4 06/17] mm/mglru: move add/del LRU size accounting out of lru_gen_update_size()
Quoted 39 lines · Barry Song
Quoted 9 lines · On Fri, Oct 16, 2026 at 2:15 AM Kairui Song via B4 Relay…
From: Kairui Song <[email protected]>
Pure code shuffle, no behavior change.
lru_gen_update_size()now only updates the per-generation counters plus the promotion move; the addition and deletion active/inactive accounting move tolru_gen_add_folio()andlru_gen_del_folio(), which know the generation and can apply the active-window test directly.Quoted 7 lines
The unevictable case is untouched: unevictable folios never enter
lru_gen_add_folio()and keep being accounted bylruvec_add_folio()as before.Tested-by zhaozhengzhuo <[email protected]>Signed-off-by Kairui Song <[email protected]>---
The patch looks good to me.
Meanwhile, I've been struggling with the names of
__update_lru_size()andlru_gen_update_size()for a long time.Given that
lru_gen_update_size()now only updatesnr_pages:
static inline void lru_gen_update_size(struct lruvec *lruvec, int type,
struct folio *folio, intold_gen, intnew_gen){ ... if (old_gen >= 0) atomic_long_sub(delta, &lrugen->nr_pages[old_gen][type][zone]); if (new_gen >= 0) atomic_long_add(delta, &lrugen->nr_pages[new_gen][type][zone]); }
Quoted 6 lines
while
__update_lru_size()only handles active/inactive accounting, could we rename them to make their roles clearer? For example:
lru_gen_update_nr_pages()lru_gen_update_active_inactive_size()
Hmm but __update_lru_size is also used by CLRU, so it's not a "lru_gen" specific helper. If we can merge CLRU/MGLRU, then maybe we can rename them?
Barry Song
reviewerRe: [PATCH v4 06/17] mm/mglru: move add/del LRU size accounting out of lru_gen_update_size()
Quoted 45 lines · Kairui Song
Quoted 43 lines · Barry Song
Quoted 9 lines · On Fri, Oct 16, 2026 at 2:15 AM Kairui Song via B4 Relay…
From: Kairui Song <[email protected]>
Pure code shuffle, no behavior change.
lru_gen_update_size()now only updates the per-generation counters plus the promotion move; the addition and deletion active/inactive accounting move tolru_gen_add_folio()andlru_gen_del_folio(), which know the generation and can apply the active-window test directly.Quoted 7 lines
The unevictable case is untouched: unevictable folios never enter
lru_gen_add_folio()and keep being accounted bylruvec_add_folio()as before.Tested-by zhaozhengzhuo <[email protected]>Signed-off-by Kairui Song <[email protected]>---
The patch looks good to me.
Meanwhile, I've been struggling with the names of
__update_lru_size()andlru_gen_update_size()for a long time.Given that
lru_gen_update_size()now only updatesnr_pages:
static inline void lru_gen_update_size(struct lruvec *lruvec, int type,
struct folio *folio, intold_gen, intnew_gen){ ... if (old_gen >= 0) atomic_long_sub(delta, &lrugen->nr_pages[old_gen][type][zone]); if (new_gen >= 0) atomic_long_add(delta, &lrugen->nr_pages[new_gen][type][zone]); }while
__update_lru_size()only handles active/inactive accounting, could we rename them to make their roles clearer? For example:
Quoted 6 lines
Quoted 2 lines
lru_gen_update_nr_pages()lru_gen_update_active_inactive_size()Hmm but
__update_lru_sizeis also used by CLRU, so it's not a "lru_gen" specific helper. If we can merge CLRU/MGLRU, then maybe we can rename them?
I did a quick search in mm/vmscan.c and found that everything is MGLRU. But you're right, I missed update_lru_size(), which is part of CLRU.
1 62 include/linux/mm_inline.h <<update_lru_size>>
__update_lru_size(lruvec, lru, zid, nr_pages);
2 279 include/linux/mm_inline.h <<lru_gen_update_size>>
__update_lru_size(lruvec, lru, zone, delta);
3 287 include/linux/mm_inline.h <<lru_gen_update_size>>
__update_lru_size(lruvec, lru, zone, -delta);
4 293 include/linux/mm_inline.h <<lru_gen_update_size>>
__update_lru_size(lruvec, lru, zone, -delta);
5 294 include/linux/mm_inline.h <<lru_gen_update_size>>
__update_lru_size(lruvec, lru + LRU_ACTIVE, zone, delta);
6 3355 mm/vmscan.c <<reset_batch_size>>
__update_lru_size(lruvec, lru, zone, delta);
7 4101 mm/vmscan.c <<inc_max_seq>>
__update_lru_size(lruvec, lru, zone, delta);
8 4102 mm/vmscan.c <<inc_max_seq>>
__update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta); 9 4632 mm/vmscan.c <<__lru_gen_reparent_memcg>>
__update_lru_size(child_lruvec, lru + child_lru_active,
zone, -nr_pages);
10 4633 mm/vmscan.c <<__lru_gen_reparent_memcg>>
__update_lru_size(parent_lruvec, lru + parent_lru_active,
zone, nr_pages);
Thanks,
Barry
Kairui Song
maintainerPATCH v4 7/17 mm/mglru, gup: mark folios referenced via a fast helper
In reply to Kairui SongIntroduce folio_inc_lru_refs_fast(): raise refs from 0 to LRU_REFS_REFERENCED via cmpxchg, or just set PG_referenced for the classical LRU as before. No counter update, promotion, and guarteens no other complex operations in following commits.
Convert the gup fast-path sites. No behavior change for classical LRU.
--- include/linux/mm_inline.h | 25 +++++++++++++++++++++++++ mm/gup.c | 6 +++--- 2 files changed, 28 insertions(+), 3 deletions(-)
include/linux/mm_inline.h +25 -0
@@ -454,6 +454,31 @@ static inline bool lru_gen_del_folio(struct lruvec *lruvec, struct folio *folio, }#endif /* CONFIG_LRU_GEN */ +/** +* folio_inc_lru_refs_fast - Bump folio refs count without promotion. +* @folio: the folio +* +* Raise refs from 0 to LRU_REFS_REFERENCED and leave hotter folios +* untouched. For the classical LRU, a plain PG_referenced set. +*/ +static __always_inline void folio_inc_lru_refs_fast(struct folio *folio) +{ +unsigned long new_flags, old_flags; + +if (!lru_gen_enabled ()) { +folio_set_referenced (folio); +return ; + } + + old_flags =READ_ONCE (*folio_flags (folio,0 )); +do { +if (lru_get_refs_flags (old_flags)) +break ; + new_flags = old_flags; +lru_set_refs_flags (&new_flags,LRU_REFS_REFERENCED ); + }while (!try_cmpxchg (folio_flags (folio,0 ), &old_flags, new_flags)); +} +static __always_inline void lruvec_add_folio(struct lruvec *lruvec, struct folio *folio) {
mm/gup.c +3 -3
@@ -2896,7 +2896,7 @@ static unsigned long gup_fast_pte_range(pmd_t pmd, pmd_t *pmdp,gup_put_folio (folio,1 , flags); goto pte_unmap; } -folio_set_referenced (folio); +folio_inc_lru_refs_fast (folio); pages[nr_pages] = page; nr_pages++; }while (ptep++, addr +=PAGE_SIZE , addr != end);
@@ -2965,7 +2965,7 @@ static unsigned long gup_fast_pmd_leaf(pmd_t orig, pmd_t *pmdp,for (i =0 ; i < nr_pages; i++) *(pages++) = page++; -folio_set_referenced (folio); +folio_inc_lru_refs_fast (folio);return nr_pages; }
@@ -3007,7 +3007,7 @@ static unsigned long gup_fast_pud_leaf(pud_t orig, pud_t *pudp,for (i =0 ; i < nr_pages; i++) *(pages++) = page++; -folio_set_referenced (folio); +folio_inc_lru_refs_fast (folio);return nr_pages; }
Signature · 1 line
2.56.0
[email protected]
AI reviewRe: [PATCH v4 07/17] mm/mglru, gup: mark folios referenced via a fast helper
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 11 lines
From: Kairui Song <[email protected]>
Introduce
folio_inc_lru_refs_fast(): raise refs from 0 toLRU_REFS_REFERENCEDvia cmpxchg, or just setPG_referencedfor the classical LRU as before. No counter update, promotion, and guarteens no other complex operations in following commits.Convert the gup fast-path sites. No behavior change for classical LRU.
Tested-by zhaozhengzhuo <[email protected]>Signed-off-by Kairui Song <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
Barry Song
reviewerRe: [PATCH v4 07/17] mm/mglru, gup: mark folios referenced via a fast helper
In reply to Kairui SongQuoted 39 lines · On Fri, Oct 16, 2026 at 2:15 AM Kairui Song via B4 Relay…
From: Kairui Song <[email protected]>
Introduce
folio_inc_lru_refs_fast(): raise refs from 0 toLRU_REFS_REFERENCEDvia cmpxchg, or just setPG_referencedfor the classical LRU as before. No counter update, promotion, and guarteens no other complex operations in following commits.Convert the gup fast-path sites. No behavior change for classical LRU.
Tested-by zhaozhengzhuo <[email protected]>Signed-off-by Kairui Song <[email protected]>--- include/linux/mm_inline.h | 25 +++++++++++++++++++++++++ mm/gup.c | 6 +++--- 2 files changed, 28 insertions(+), 3 deletions(-)include/linux/mm_inline.h +14
-0@@ -454,6 +454,31 @@ static inline bool lru_gen_del_folio(struct lruvec *lruvec, struct folio *folio, }#endif /* CONFIG_LRU_GEN */ +/** +* folio_inc_lru_refs_fast - Bump folio refs count without promotion. +* @folio: the folio +* +* Raise refs from 0 to LRU_REFS_REFERENCED and leave hotter folios +* untouched. For the classical LRU, a plain PG_referenced set. +*/ +static __always_inline void folio_inc_lru_refs_fast(struct folio *folio) +{ +unsigned long new_flags, old_flags; + +if (!lru_gen_enabled ()) { +folio_set_referenced (folio); +return ;
include/linux/mm_inline.h static inline bool lru_gen_del_folio(struct lruvec *lruvec, struct folio *folio, · line 480
Quoted 10 lines
include/linux/mm_inline.h +10
-0+ } + + old_flags =READ_ONCE (*folio_flags (folio,0 )); +do { +if (lru_get_refs_flags (old_flags)) +break ; + new_flags = old_flags; +lru_set_refs_flags (&new_flags,LRU_REFS_REFERENCED ); + }while (!try_cmpxchg (folio_flags (folio,0 ), &old_flags, new_flags)); +}
What is the actual purpose of this patch? Is it to skip cmpxchg() when the folio already has non-zero refs for better performance?
Thanks,
Barry
Re: [PATCH v4 07/17] mm/mglru, gup: mark folios referenced via a fast helper
Quoted 48 lines · Barry Song
Quoted 45 lines · On Fri, Oct 16, 2026 at 2:15 AM Kairui Song via B4 Relay…
From: Kairui Song <[email protected]>
Introduce
folio_inc_lru_refs_fast(): raise refs from 0 toLRU_REFS_REFERENCEDvia cmpxchg, or just setPG_referencedfor the classical LRU as before. No counter update, promotion, and guarteens no other complex operations in following commits.Convert the gup fast-path sites. No behavior change for classical LRU.
Tested-by zhaozhengzhuo <[email protected]>Signed-off-by Kairui Song <[email protected]>--- include/linux/mm_inline.h | 25 +++++++++++++++++++++++++ mm/gup.c | 6 +++--- 2 files changed, 28 insertions(+), 3 deletions(-)include/linux/mm_inline.h +20
-0@@ -454,6 +454,31 @@ static inline bool lru_gen_del_folio(struct lruvec *lruvec, struct folio *folio, }#endif /* CONFIG_LRU_GEN */ +/** +* folio_inc_lru_refs_fast - Bump folio refs count without promotion. +* @folio: the folio +* +* Raise refs from 0 to LRU_REFS_REFERENCED and leave hotter folios +* untouched. For the classical LRU, a plain PG_referenced set. +*/ +static __always_inline void folio_inc_lru_refs_fast(struct folio *folio) +{ +unsigned long new_flags, old_flags; + +if (!lru_gen_enabled ()) { +folio_set_referenced (folio); +return ; + } + + old_flags =READ_ONCE (*folio_flags (folio,0 )); + do { + if (lru_get_refs_flags(old_flags)) + break;
Quoted 8 lines
include/linux/mm_inline.h static inline bool lru_gen_del_folio(struct lruvec *lruvec, struct folio *folio, · line 480
Quoted 4 lines
include/linux/mm_inline.h +4
-0+ new_flags = old_flags; +lru_set_refs_flags (&new_flags,LRU_REFS_REFERENCED ); + }while (!try_cmpxchg (folio_flags (folio,0 ), &old_flags, new_flags)); +}What is the actual purpose of this patch? Is it to skip
cmpxchg()when the folio already has non-zero refs for better performance?
Right, as the name suggests, it's a faster helper, sacrificing some recency accuracy (limited to LRU_REFS_REFERENCED, so it never touch any counter). But the low bar for this helper is still equal to mainline so I think it's fine at this point. I can add more commit message or comment on this.
Kairui Song
maintainerPATCH v4 8/17 mm/mglru, smaps: convert to LRU refs based operations for MGLRU
In reply to Kairui SongPG_referenced is only the lowest bit of the folio LRU refs count (LRU_REFS_FLAGS) now, and MGLRU never kept it stable: promotion used to clear it, and now it toggles as the count grows. But with the LRU referenced count as a stable API now, we can use two helpers to provide in-kernel users a stable and sane reading of the referenced status of an LRU managed folio.
Add folio_check_lru_refs() and folio_clear_lru_refs(), which use the refs count when MGLRU is enabled and PG_referenced otherwise, and switch the smaps paths over to them. The lru_gen_enabled() test stays inside the helpers, so its static key is not splattered over the few call sites.
Convert smaps as the first user of them. MGLRU now reports every folio with a nonzero count, so the reading no longer flickers and clearing no longer results in an ambiguous status.
The classical LRU case is unchanged.
--- fs/proc/task_mmu.c | 6 +++--- include/linux/mm_inline.h | 31 +++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 3 deletions(-)
fs/proc/task_mmu.c +3 -3
@@ -888,7 +888,7 @@ static void smaps_account(struct mem_size_stats *mss, struct page *page, mss->resident += size;/* Accumulate the size in pages that have been accessed. */ -if (young ||folio_test_young (folio) ||folio_test_referenced (folio)) +if (young ||folio_test_young (folio) ||folio_check_lru_refs (folio)) mss->referenced += size;/*
@@ -1685,7 +1685,7 @@ static int clear_refs_pte_range(pmd_t *pmd, unsigned long addr,/* Clear accessed and referenced bits. */ pmdp_test_and_clear_young (vma, addr, pmd);folio_test_clear_young (folio); -folio_clear_referenced (folio); +folio_clear_lru_refs (folio); out:spin_unlock (ptl);return 0 ;
@@ -1714,7 +1714,7 @@ static int clear_refs_pte_range(pmd_t *pmd, unsigned long addr,/* Clear accessed and referenced bits. */ ptep_test_and_clear_young (vma, addr, pte);folio_test_clear_young (folio); -folio_clear_referenced (folio); +folio_clear_lru_refs (folio); }pte_unmap_unlock (pte -1 , ptl);cond_resched ();
include/linux/mm_inline.h +31 -0
@@ -479,6 +479,37 @@ static __always_inline void folio_inc_lru_refs_fast(struct folio *folio) }while (!try_cmpxchg (folio_flags (folio,0 ), &old_flags, new_flags)); } +/** +* folio_check_lru_refs - Test if an LRU managed folio has been referenced. +* @folio: The folio to test. +* +* Returns true if the MGLRU refs count is nonzero, or PG_referenced is set, +* which is also correct for the non-MGLRU case. Kept as a separate helper, +* to avoid splattering the lru_gen_enabled() static key. +*/ +static inline bool folio_check_lru_refs (const struct folio *folio) +{ +if (lru_gen_enabled ()) +return folio_lru_refs (folio) >0 ; +return folio_test_referenced (folio); +} + +/** +* folio_clear_lru_refs - Clear the referenced state of an LRU managed folio. +* @folio: The folio to clear. +* +* Reset the MGLRU refs count to zero, or clear PG_referenced, leaving +* PG_workingset alone for the non-MGLRU case. Kept as a separate helper +* just like folio_check_lru_refs(). +*/ +static inline void folio_clear_lru_refs (struct folio *folio) +{ +if (lru_gen_enabled ()) +folio_set_lru_refs (folio,0 ); +else +folio_clear_referenced (folio); +} +static __always_inline void lruvec_add_folio(struct lruvec *lruvec, struct folio *folio) {
Signature · 1 line
2.56.0
[email protected]
AI reviewRe: [PATCH v4 08/17] mm/mglru, smaps: convert to LRU refs based operations for MGLRU
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 14 lines
From: Kairui Song <[email protected]>
PG_referencedis only the lowest bit of the folio LRU refs count (LRU_REFS_FLAGS) now, and MGLRU never kept it stable: promotion used to clear it, and now it toggles as the count grows. But with the LRU referenced count as a stable API now, we can use two helpers to provide in-kernel users a stable and sane reading of the referenced status of an LRU managed folio.Add
folio_check_lru_refs()andfolio_clear_lru_refs(), which use the refs count when MGLRU is enabled andPG_referencedotherwise, and switch the smaps paths over to them. Thelru_gen_enabled()test stays inside the helpers, so its static key is not splattered over the few call sites.
Quoted 7 lines
Convert smaps as the first user of them. MGLRU now reports every folio with a nonzero count, so the reading no longer flickers and clearing no longer results in an ambiguous status.
The classical LRU case is unchanged.
Signed-off-by Kairui Song <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
Kairui Song
maintainerPATCH v4 9/17 mm/damon: convert to LRU refs based operations for MGLRU
In reply to Kairui Songdamon_pa_pageout() cleared PG_referenced directly, which under MGLRU may corrupts the folio's refs count in later commits. That flag is now bit 0 of the count (LRU_REFS_FLAGS).
Reset the count instead under MGLRU.
--- mm/damon/paddr.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
mm/damon/paddr.c +2 -1
@@ -279,7 +279,8 @@ static unsigned long damon_pa_pageout(struct damon_region *r,else *sz_filter_passed +=folio_size (folio) / addr_unit; -folio_clear_referenced (folio); +/* The regions is cold, better drop the hotness info */ +folio_clear_lru_refs (folio);folio_test_clear_young (folio);if (!folio_isolate_lru (folio)) goto put_folio;
Signature · 1 line
2.56.0
[email protected]
AI reviewRe: [PATCH v4 09/17] mm/damon: convert to LRU refs based operations for MGLRU
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 10 lines
From: Kairui Song <[email protected]>
damon_pa_pageout()clearedPG_referenceddirectly, which under MGLRU may corrupts the folio's refs count in later commits. That flag is now bit 0 of the count (LRU_REFS_FLAGS).Reset the count instead under MGLRU.
Tested-by zhaozhengzhuo <[email protected]>Signed-off-by Kairui Song <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
Kairui Song
maintainerPATCH v4 10/17 mm/khugepaged: convert to LRU refs based operations for MGLRU
In reply to Kairui SongFor MGLRU, PG_referenced is only the lowest bit of the folio LRU refs count, so folios with a higher refs count no longer have the bit set. folio_pte_referenced() testing the raw bit misses hot folios at refs >= 2, under-counting the referenced folios of a candidate range and aborting otherwise good collapses with SCAN_LACK_REFERENCED_PAGE.
Test the refs count directly when MGLRU is enabled, mirroring the smaps conversion. The classical LRU keeps the plain bit test.
--- mm/khugepaged.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
mm/khugepaged.c +3 -1
@@ -579,7 +579,9 @@ static bool folio_pte_referenced(struct folio *folio, struct vm_area_struct *vma, unsigned long addr, pte_t pteval) { /* The folio was referenced previously ... */ - if (folio_test_young(folio) || folio_test_referenced(folio)) + if (folio_test_young(folio)) + return true; +if (folio_check_lru_refs (folio))return true;/* ... or the PTE mapping was recently used */ return pte_young (pteval) ||mmu_notifier_test_young (vma->vm_mm, addr);
Signature · 1 line
2.56.0
[email protected]
AI reviewRe: [PATCH v4 10/17] mm/khugepaged: convert to LRU refs based operations for MGLRU
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 8 lines
From: Kairui Song <[email protected]>
For MGLRU,
PG_referencedis only the lowest bit of the folio LRU refs count, so folios with a higher refs count no longer have the bit set.folio_pte_referenced()testing the raw bit misses hot folios at refs >= 2, under-counting the referenced folios of a candidate range and aborting otherwise good collapses withSCAN_LACK_REFERENCED_PAGE.
Quoted 5 lines
Test the refs count directly when MGLRU is enabled, mirroring the smaps conversion. The classical LRU keeps the plain bit test.
Tested-by zhaozhengzhuo <[email protected]>Signed-off-by Kairui Song <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10
Kairui Song
maintainerPATCH v4 11/17 mm/madvise: adapt for LRU refs based operations for MGLRU
In reply to Kairui SongFor the active/inactive LRU, madvise clears PG_referenced so that one more access is not enough to reactivate a folio, and keeps PG_workingset on a folio demoted out of the active list so its refault is still accounted as a workingset refault (PSI).
MGLRU keeps that history in the folio's refs count instead, which now lives in PG_referenced, PG_workingset and LRU_REFS_MASK, so writing to those bits directly corrupts the count. The two hints want different things:
- MADV_COLD resets the count in folio_deactivate(), which also moves the folio to the oldest generation.
- MADV_PAGEOUT caps the count at LRU_REFS_WORKINGSET before handing the folio to reclaim_pages(). The hint marks the folio as cold, so the eviction shadow records the capped count and does not inflate the eviction/refault counters of the hot tiers that drive aging, while folios at or above the workingset threshold keep their PSI classification.
PG_young is cleared for both LRUs as before, so the referenced walk does not count stale history as a recent access.
--- mm/madvise.c | 56 ++++++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 42 insertions(+), 14 deletions(-)
mm/madvise.c +42 -14
@@ -360,6 +360,44 @@ static inline int madvise_folio_pte_batch(unsigned long addr, unsigned long end, FPB_MERGE_YOUNG_DIRTY); } +static void madvise_cold_prep_folio (struct folio *folio) +{ +/* +* VM couldn't reclaim the folio unless we clear PG_young. +* As a side effect, it makes confuse idle-page tracking +* because they will miss recent referenced history. +*/ +folio_test_clear_young (folio); + +/* +* For the active/inactive LRU, a folio demoted out of the active +* list should have PG_workingset so its refault is still accounted +* as a workingset refault, and the referenced bit always needs to +* be cleared even for inactive folios. Nothing to do for MGLRU as +* folio_deactivate() always calls lru_gen_clear_refs(). +*/ +if (!lru_gen_enabled ()) { +folio_clear_referenced (folio); +if (folio_test_active (folio)) +folio_set_workingset (folio); + } +} + +static void madvise_pageout_prep_folio (struct folio *folio) +{ +int refs =folio_lru_refs (folio); + +/* +* For MGLRU, drop the count below LRU_REFS_WORKINGSET and cap +* the rest at it: MADV is +* suggesting the folio is actually cold, so the eviction shadow +* should not record its hotness in the high tier counters, but +* the workingset classification is preserved for PSI. +*/ +if (lru_gen_enabled ()) +folio_set_lru_refs (folio, refs >=LRU_REFS_WORKINGSET ?LRU_REFS_WORKINGSET :0 ); +} +static int madvise_cold_or_pageout_pte_range (pmd_t *pmd,unsigned long addr,unsigned long end,struct mm_walk *walk)
@@ -434,12 +472,10 @@ static int madvise_cold_or_pageout_pte_range(pmd_t *pmd,tlb_remove_pmd_tlb_entry (tlb, pmd, addr); } -folio_clear_referenced (folio); -folio_test_clear_young (folio); -if (folio_test_active (folio)) -folio_set_workingset (folio); +madvise_cold_prep_folio (folio);if (pageout) {if (folio_isolate_lru (folio)) { +madvise_pageout_prep_folio (folio);if (folio_test_unevictable (folio))folio_putback_lru (folio);else
@@ -544,18 +580,10 @@ static int madvise_cold_or_pageout_pte_range(pmd_t *pmd,tlb_remove_tlb_entries (tlb, pte, nr, addr); } -/* -* We are deactivating a folio for accelerating reclaiming. -* VM couldn't reclaim the folio unless we clear PG_young. -* As a side effect, it makes confuse idle-page tracking -* because they will miss recent referenced history. -*/ -folio_clear_referenced (folio); -folio_test_clear_young (folio); -if (folio_test_active (folio)) -folio_set_workingset (folio); +madvise_cold_prep_folio (folio);if (pageout) {if (folio_isolate_lru (folio)) { +madvise_pageout_prep_folio (folio);if (folio_test_unevictable (folio))folio_putback_lru (folio);else
Signature · 1 line
2.56.0
[email protected]
AI reviewRe: [PATCH v4 11/17] mm/madvise: adapt for LRU refs based operations for MGLRU
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 21 lines
From: Kairui Song <[email protected]>
For the active/inactive LRU, madvise clears
PG_referencedso that one more access is not enough to reactivate a folio, and keepsPG_workingseton a folio demoted out of the active list so its refault is still accounted as a workingset refault (PSI).MGLRU keeps that history in the folio's refs count instead, which now lives in
PG_referenced,PG_workingsetandLRU_REFS_MASK, so writing to those bits directly corrupts the count. The two hints want different things:-
MADV_COLDresets the count infolio_deactivate(), which also moves the folio to the oldest generation.
-MADV_PAGEOUTcaps the count atLRU_REFS_WORKINGSETbefore handing the folio toreclaim_pages(). The hint marks the folio as cold, so the eviction shadow records the capped count and does not inflate the eviction/refault counters of the hot tiers that drive aging, while folios at or above the workingset threshold keep their PSI classification.
Quoted 4 lines
PG_youngis cleared for both LRUs as before, so the referenced walk does not count stale history as a recent access.Signed-off-by Kairui Song <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11
Kairui Song
maintainerPATCH v4 12/17 mm/huge_memory: mark folio as accessed more accurately on split
In reply to Kairui SongThe behavior of updating the folio's access info isn't consistent for huge mapping splitting or ordinary unmapping. The page table's young flag has to be translated into folio's access info.
Right now it only check and set folio's referenced flag, which isn't enough since folio flags update on access have its rules. Ordinary unmapping (zapping) calls folio_mark_accessed(), and it also checks if the VMA has recency to avoid false updates.
So first just use the right helper here to be more consistent.
--- mm/huge_memory.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
mm/huge_memory.c +4 -4
@@ -3093,8 +3093,8 @@ static void __split_huge_pud_locked(struct vm_area_struct *vma, pud_t *pud,if (!folio_test_dirty (folio) &&pud_dirty (old_pud))folio_mark_dirty (folio); -if (!folio_test_referenced (folio) &&pud_young (old_pud)) -folio_set_referenced (folio); +if (pud_young (old_pud) &&vma_has_recency (vma)) +folio_mark_accessed (folio);folio_remove_rmap_pud (folio, page, vma);add_mm_counter (vma->vm_mm,mm_counter_file (folio), -HPAGE_PUD_NR );
@@ -3216,8 +3216,8 @@ static void __split_huge_pmd_locked(struct vm_area_struct *vma, pmd_t *pmd, folio =page_folio (page);if (!folio_test_dirty (folio) &&pmd_dirty (old_pmd))folio_mark_dirty (folio); -if (!folio_test_referenced (folio) &&pmd_young (old_pmd)) -folio_set_referenced (folio); +if (pmd_young (old_pmd) &&vma_has_recency (vma)) +folio_mark_accessed (folio);folio_remove_rmap_pmd (folio, page, vma);add_mm_counter (mm,mm_counter_file (folio), -HPAGE_PMD_NR );folio_put (folio);
Signature · 1 line
2.56.0
[email protected]
AI reviewRe: [PATCH v4 12/17] mm/huge_memory: mark folio as accessed more accurately on split
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 11 lines
From: Kairui Song <[email protected]>
The behavior of updating the folio's access info isn't consistent for huge mapping splitting or ordinary unmapping. The page table's young flag has to be translated into folio's access info.
Right now it only check and set folio's referenced flag, which isn't enough since folio flags update on access have its rules. Ordinary unmapping (zapping) calls
folio_mark_accessed(), and it also checks if the VMA has recency to avoid false updates.
Quoted 4 lines
So first just use the right helper here to be more consistent.
Tested-by zhaozhengzhuo <[email protected]>Signed-off-by Kairui Song <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=12
Barry Song
reviewerRe: [PATCH v4 12/17] mm/huge_memory: mark folio as accessed more accurately on split
In reply to Kairui SongQuoted 11 lines · On Fri, Oct 16, 2026 at 2:16 AM Kairui Song via B4 Relay…
From: Kairui Song <[email protected]>
The behavior of updating the folio's access info isn't consistent for huge mapping splitting or ordinary unmapping. The page table's young flag has to be translated into folio's access info.
Right now it only check and set folio's referenced flag, which isn't enough since folio flags update on access have its rules. Ordinary unmapping (zapping) calls
folio_mark_accessed(), and it also checks if the VMA has recency to avoid false updates.
This might be a bit off-topic, but I once proposed recency fading for the zapping case in Android workloads:
https://lore.kernel.org/linux-mm/[email protected]/
folio_mark_accessed() might not be ideal for Android apps that are being killed, as we expect them to be relaunched only after a long period of time.
But for the splitting case, I guess there is no doubt that the accessed state should be set.
Quoted 25 lines
So first just use the right helper here to be more consistent.
Tested-by zhaozhengzhuo <[email protected]>Signed-off-by Kairui Song <[email protected]>--- mm/huge_memory.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)mm/huge_memory.c +2
-2@@ -3093,8 +3093,8 @@ static void __split_huge_pud_locked(struct vm_area_struct *vma, pud_t *pud,if (!folio_test_dirty (folio) &&pud_dirty (old_pud))folio_mark_dirty (folio); -if (!folio_test_referenced (folio) &&pud_young (old_pud)) -folio_set_referenced (folio); +if (pud_young (old_pud) &&vma_has_recency (vma)) +folio_mark_accessed (folio);folio_remove_rmap_pud (folio, page, vma);add_mm_counter (vma->vm_mm,mm_counter_file (folio), -HPAGE_PUD_NR );
mm/huge_memory.c static void __split_huge_pmd_locked(struct vm_area_struct *vma, pmd_t *pmd, · line 3220
Quoted 7 lines
mm/huge_memory.c +2
-2@@ -3216,8 +3216,8 @@ static void __split_huge_pmd_locked(struct vm_area_struct *vma, pmd_t *pmd, folio =page_folio (page);if (!folio_test_dirty (folio) &&pmd_dirty (old_pmd))folio_mark_dirty (folio); -if (!folio_test_referenced (folio) &&pmd_young (old_pmd)) -folio_set_referenced (folio); +if (pmd_young (old_pmd) &&vma_has_recency (vma)) +folio_mark_accessed (folio);
We now have two inc_refs paths:
- folio_inc_lru_refs_walk() for mapped folios;
- folio_inc_lru_refs() for syscall accesses, or possibly mapped folios with the appropriate flags such as LRU_REF_MAPPED, LRU_REF_EXEC, LRU_REF_FORCE, etc.
The interface is:
void folio_inc_lru_refs(struct folio *folio, unsigned int flags);
Here we call folio_mark_accessed(folio), which is the syscall path with flags = 0:
folio_inc_lru_refs(folio, 0);
Are we somehow applying the syscall access policy to folios accessed through the page table?
This seems a bit strange to me, no?
Quoted 6 lines
mm/huge_memory.c +0
-1folio_remove_rmap_pmd (folio, page, vma);add_mm_counter (mm,mm_counter_file (folio), -HPAGE_PMD_NR );folio_put (folio); --2.56.0
Thanks,
Barry
Re: [PATCH v4 12/17] mm/huge_memory: mark folio as accessed more accurately on split
Quoted 18 lines · Barry Song
Quoted 11 lines · On Fri, Oct 16, 2026 at 2:16 AM Kairui Song via B4 Relay…
From: Kairui Song <[email protected]>
The behavior of updating the folio's access info isn't consistent for huge mapping splitting or ordinary unmapping. The page table's young flag has to be translated into folio's access info.
Right now it only check and set folio's referenced flag, which isn't enough since folio flags update on access have its rules. Ordinary unmapping (zapping) calls
folio_mark_accessed(), and it also checks if the VMA has recency to avoid false updates.This might be a bit off-topic, but I once proposed recency fading for the zapping case in Android workloads:
Quoted 8 lines
https://lore.kernel.org/linux-mm/[email protected]/
folio_mark_accessed()might not be ideal for Android apps that are being killed, as we expect them to be relaunched only after a long period of time.But for the splitting case, I guess there is no doubt that the accessed state should be set.
Hi Barry,
Thanks for the review.
I agree with these points. BTW that recency fading patch seems interesting too, but perhaps we need something stronger than folio_maybe_mapped_shared, maybe folio_maybe_shared, and do that when "current's cgroup matches the folio's cgroup and have a ref count ~= 1"?
Quoted 20 lines
mm/huge_memory.c static void __split_huge_pmd_locked(struct vm_area_struct *vma, pmd_t *pmd, · line 3220
Quoted 8 lines
mm/huge_memory.c +2
-2@@ -3216,8 +3216,8 @@ static void __split_huge_pmd_locked(struct vm_area_struct *vma, pmd_t *pmd, folio =page_folio (page);if (!folio_test_dirty (folio) &&pmd_dirty (old_pmd))folio_mark_dirty (folio); -if (!folio_test_referenced (folio) &&pmd_young (old_pmd)) -folio_set_referenced (folio); +if (pmd_young (old_pmd) &&vma_has_recency (vma)) +folio_mark_accessed (folio);We now have two
inc_refspaths:-
folio_inc_lru_refs_walk()for mapped folios;
-folio_inc_lru_refs()for syscall accesses, or possibly mapped folios with the appropriate flags such asLRU_REF_MAPPED,LRU_REF_EXEC,LRU_REF_FORCE, etc.The interface is:
void
folio_inc_lru_refs(struct folio *folio, unsigned int flags);
Quoted 7 lines
Here we call
folio_mark_accessed(folio), which is the syscall path with flags = 0:
folio_inc_lru_refs(folio, 0);Are we somehow applying the syscall access policy to folios accessed through the page table?
Right at this point I'm just trying to stick with the current upstream behavior, and not promote these folios aggressively. The results are looking OK for end to end benchmarks so far, maybe they can be tweaked further like a LRU_REF_MEAN so it won't promote them, just inc the ref, I didn't find any oberable differenence at this point as THP alloc success rate is very low when under pressure so sticking with the current behavior seems not a bad idea.
Kairui Song
maintainerPATCH v4 13/17 mm/mglru: folio LRU refs based active/inactive number accounting
In reply to Kairui SongCurrently the active/inactive LRU sizes exported through /proc/vmstat and memory.stat are derived from the generation window: folios in the two newest generations are accounted as active, the rest as inactive. This has always caused many problems:
- Unmapped file folios stick to the oldest gens, so active files are always under-reported, unlike classical LRU.
- The reading is jumpy: on aging, the second-newest gen, previously active, becomes inactive all at once, causing a huge drop of active folios for no reason from time to time.
- The reading is reversed on swapless machines, and the active anon number is an oscillating random number. When swappiness is 0 (no swap or swap is full), MGLRU ages anon by moving the gens directly without walk or touching any folio, to reduce the overhead. So all inactive anon folios will suddenly count as active, or vice versa, which breaks many metric reading components, and the reading itself doesn't make any sense in any way.
With frequency guided promotion, hotness is already tracked per folio by its referenced count, so we can do folio level accounting instead: a folio is active once its refs reach LRU_REFS_ACTIVATED (currently LRU_REFS_PROTECTED).
On access, folios are accounted to the active part. On forced aging or PID protecting, folios are reset to LRU_REFS_WORKINGSET, dropping them to the inactive part. The reading is now smooth and consistent, and much closer to classical LRU. Note that on swapless machines anon refs are never reset by aging (the shortcut skips the per-folio walk), so active anon grows monotonically, but the reading is stable and still much more meaningful than the previous oscillating random number.
The accounting is now per folio and lruvec independent, so no size adjustment is needed when reparenting a dying memcg: the hierarchical stats keep the counts in the parent automatically.
folio_migrate_lru_refs() also gains off-LRU VM_WARN_ON_ONCE checks and __folio_set_lru_refs() warns when the folio is still on an LRU list.
--- Documentation/admin-guide/mm/multigen_lru.rst | 4 +- include/linux/mm_inline.h | 115 +++++++------- include/linux/mmzone.h | 23 ++- mm/folio.c | 35 +---- mm/madvise.c | 5 +- mm/vmscan.c | 211 ++++++++++++++++---------- mm/workingset.c | 2 +- 7 files changed, 220 insertions(+), 175 deletions(-)
Documentation/admin-guide/mm/multigen_lru.rst +2 -2
@@ -149,8 +149,8 @@ generations less than or equal to ``min_gen_nr``. ``- memcg_id node_id min_gen_nr [swappiness [nr_to_reclaim]]`` ``min_gen_nr`` should be less than ``max_gen_nr-1``, since -``max_gen_nr`` and ``max_gen_nr-1`` are not fully aged (equivalent to -the active list) and therefore cannot be evicted. ``swappiness`` +``max_gen_nr`` and ``max_gen_nr-1`` are not fully aged and therefore +cannot be evicted. ``swappiness`` overrides the default value in ``/proc/sys/vm/swappiness`` and the valid range is [0-200, max], with max being exclusively used for the reclamation of anonymous memory. ``nr_to_reclaim`` limits the number of pages to evict.
include/linux/mm_inline.h +62 -53
227 lines not on this page · raw message
include/linux/mmzone.h +15 -8
@@ -434,15 +434,15 @@ enum lruvec_flags {* least twice before handing this folio over to the eviction. The first check * clears the accessed bit from the initial fault; the second check makes sure * this folio hasn't been used since then. This process, AKA second chance, -* requires a minimum of two generations, hence MIN_NR_GENS. And to maintain ABI -* compatibility with the active/inactive LRU, e.g., /proc/vmstat, these two -* generations are considered active; the rest of generations, if they exist, -* are considered inactive. See lru_gen_is_active(). +* requires a minimum of two generations, hence MIN_NR_GENS. +* +* Active/inactive is per-folio based on the referenced count; +* see the comment above MAX_NR_TIERS. * * PG_active is always cleared while a folio is on one of lrugen->folios[] so -* that the sliding window needs not to worry about it. And it's set again when -* a folio considered active is isolated for non-reclaiming purposes, e.g., -* migration. See lru_gen_add_folio() and lru_gen_del_folio(). +* that the sliding window needs not to worry about it. It is set on a +* fault-driven refault (see lru_gen_refault), or isolation (see +* lru_gen_del_folio). * * MAX_NR_GENS is set to 4 so that the multi-gen LRU can support twice the * number of categories of the active/inactive LRU when keeping track of
@@ -543,11 +543,15 @@ enum lruvec_flags {* * A folio's referenced count never goes backwards except upon gen * increase as described above, or when explicitly reset by -* lru_gen_clear_refs(). Refault of a reclaimed folio restores +* folio_reset_lru_refs(). Refault of a reclaimed folio restores * its referenced count, capped at LRU_REFS_PROTECTED, which aligns with * promotion. Page table refaults of previous workingset folios send * them to the latest gen, driving aging faster. * +* For the active/inactive LRU ABI (/proc/vmstat), a folio is active +* if its referenced count reaches LRU_REFS_ACTIVATED. The threshold +* currently set to LRU_REFS_PROTECTED, which is tier 2. +* * MAX_NR_TIERS is set to 4 so that the multi-gen LRU can support twice * the number of categories of the active/inactive LRU. */
@@ -562,6 +566,7 @@ enum lruvec_flags {#define LRU_REFS_REFERENCED 0x1#define LRU_REFS_WORKINGSET 0x2#define LRU_REFS_PROTECTED 0x3 +#define LRU_REFS_ACTIVATED LRU_REFS_PROTECTED#ifndef __GENERATING_BOUNDS_H
@@ -670,6 +675,8 @@ struct lru_gen_mm_walk {unsigned long seq;/* the next address within an mm to scan */ unsigned long next_addr; +/* to batch activated pages */ +int nr_activated[ANON_AND_FILE ][MAX_NR_ZONES ];/* to batch promoted pages */ int nr_pages[MAX_NR_GENS ][ANON_AND_FILE ][MAX_NR_ZONES ];/* to batch the mm stats */
mm/folio.c +3 -32
@@ -349,35 +349,6 @@ static void __lru_cache_activate_folio(struct folio *folio)local_unlock (&cpu_fbatches.lock); } -#ifdef CONFIG_LRU_GEN - -static bool lru_gen_clear_refs (struct folio *folio) -{ -int gen =folio_lru_gen (folio); -int type =folio_is_file_lru (folio); -unsigned long seq; - -if (gen <0 ) -return true; - -folio_set_lru_refs (folio,0 ); - -rcu_read_lock (); - seq =READ_ONCE (folio_lruvec (folio)->lrugen.min_seq[type]); -rcu_read_unlock (); -/* whether can do without shuffling under the LRU lock */ -return gen ==lru_gen_from_seq (seq); -} - -#else /* !CONFIG_LRU_GEN */ - -static bool lru_gen_clear_refs (struct folio *folio) -{ -return false; -} - -#endif /* CONFIG_LRU_GEN */ -/** * folio_mark_accessed - Mark a folio as having seen activity. * @folio: The folio to mark.
@@ -554,7 +525,7 @@ static void lru_lazyfree(struct lruvec *lruvec, struct folio *folio)lruvec_del_folio (lruvec, folio);folio_clear_active (folio);if (lru_gen_enabled ()) -lru_gen_clear_refs (folio); +__folio_set_lru_refs (folio,0 );else folio_clear_referenced (folio);/*
@@ -627,7 +598,7 @@ void deactivate_file_folio(struct folio *folio)if (folio_test_unevictable (folio) || !folio_test_lru (folio))return ; -if (lru_gen_enabled () &&lru_gen_clear_refs (folio)) +if (lru_gen_enabled () && !folio_reset_lru_refs (folio))return ;folio_batch_add_and_move (folio, lru_deactivate_file);
@@ -646,7 +617,7 @@ void folio_deactivate(struct folio *folio)if (folio_test_unevictable (folio) || !folio_test_lru (folio))return ; -if (lru_gen_enabled () ?lru_gen_clear_refs (folio) : !folio_test_active (folio)) +if (lru_gen_enabled () ? !folio_reset_lru_refs (folio) : !folio_test_active (folio))return ;folio_batch_add_and_move (folio, lru_deactivate);
mm/madvise.c +3 -2
@@ -374,7 +374,8 @@ static void madvise_cold_prep_folio(struct folio *folio)* list should have PG_workingset so its refault is still accounted * as a workingset refault, and the referenced bit always needs to * be cleared even for inactive folios. Nothing to do for MGLRU as -* folio_deactivate() always calls lru_gen_clear_refs(). +* folio_deactivate() clears the refs count through +* folio_reset_lru_refs(). */ if (!lru_gen_enabled ()) {folio_clear_referenced (folio);
@@ -395,7 +396,7 @@ static void madvise_pageout_prep_folio(struct folio *folio)* the workingset classification is preserved for PSI. */ if (lru_gen_enabled ()) -folio_set_lru_refs (folio, refs >=LRU_REFS_WORKINGSET ?LRU_REFS_WORKINGSET :0 ); +__folio_set_lru_refs (folio, refs >=LRU_REFS_WORKINGSET ?LRU_REFS_WORKINGSET :0 ); } static int madvise_cold_or_pageout_pte_range(pmd_t *pmd,
mm/vmscan.c +134 -77
392 lines not on this page · raw message
mm/workingset.c +1 -1
@@ -334,7 +334,7 @@ static void lru_gen_refault(struct folio *folio, void *shadow)mod_lruvec_state (lruvec,WORKINGSET_ACTIVATE_BASE + type, delta); }/* Refault is also promotion, cap the refs like folio_inc_lru_refs */ -folio_set_lru_refs (folio,min (refs,LRU_REFS_PROTECTED )); +__folio_set_lru_refs (folio,min (refs,LRU_REFS_PROTECTED )); }if (refs >=LRU_REFS_WORKINGSET )
Signature · 1 line
2.56.0
[email protected]
AI reviewRe: [PATCH v4 13/17] mm/mglru: folio LRU refs based active/inactive number accounting
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] mm: MGLRU tier bits (LRU_REFS_FLAGS) not cleared when updating LRU_GEN_MASK --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] mm: MGLRU tier bits (LRU_REFS_FLAGS) not cleared when updating LRU_GEN_MASK --
commit 97ee7d2a683879e87f8e211218beb97d5cbbba1b
Author: Kairui Song <[email protected]>
mm/mglru: folio LRU refs based active/inactive number accounting
This commit updates the active/inactive LRU size tracking to use per-folio referenced counts instead of the generation window. Folios are now accounted as active once their references reach LRU_REFS_ACTIVATED.
Quoted 4 lines
include/linux/mm_inline.h +0
-0
[ ... ]
Quoted 10 lines
include/linux/mm_inline.h +1
-1@@ -374,7 +373,7 @@ static inline bool lru_gen_add_folio(struct lruvec *lruvec, struct folio *folio,struct lru_gen_folio *lrugen = &lruvec->lrugen;BUILD_BUG_ON (BIT (LRU_GEN_WIDTH -1 ) !=MAX_NR_GENS ); -VM_WARN_ON_ONCE_FOLIO (gen !=-1 , folio); +VM_WARN_ON_ONCE_FOLIO (folio_lru_gen (folio) !=-1 , folio);if (folio_test_unevictable (folio) || !lrugen->enabled)return false;
include/linux/mm_inline.h static inline bool lru_gen_add_folio(struct lruvec *lruvec, struct folio *folio, · line 385
Quoted 5 lines
include/linux/mm_inline.h +1
-1@@ -383,10 +382,12 @@ static inline bool lru_gen_add_folio(struct lruvec *lruvec, struct folio *folio, gen =lru_gen_from_seq (seq); flags = (gen +1UL ) <<LRU_GEN_PGOFF ;/* see the comment on MIN_NR_GENS about PG_active */ -set_mask_bits (folio_flags (folio,0 ),LRU_GEN_MASK |BIT (PG_active), flags); + flags =set_mask_bits (folio_flags (folio,0 ),LRU_GEN_MASK |BIT (PG_active), flags);
[Severity: Medium]
Should LRU_REFS_FLAGS be included in the mask cleared by set_mask_bits() here?
When a folio is added to a generation and LRU_GEN_MASK is modified, leaving stale tier bits (LRU_REFS_FLAGS) intact can allow them to persist. This could inadvertently inflate access counts and distort future eviction tracking.
Quoted 4 lines
include/linux/mm_inline.h +2
-0+/* use the refs from the atomic snapshot to avoid raced update */ + refs =lru_get_refs_flags (flags);lru_gen_update_size (lruvec, folio,-1 , gen);
[ ... ]
include/linux/mm_inline.h static inline bool lru_gen_add_folio(struct lruvec *lruvec, struct folio *folio, · line 412
Quoted 12 lines
include/linux/mm_inline.h +3
-1@@ -402,24 +403,31 @@ static inline bool lru_gen_add_folio(struct lruvec *lruvec, struct folio *folio,static inline bool lru_gen_del_folio (struct lruvec *lruvec,struct folio *folio,bool reclaiming) {unsigned long flags; -int gen =folio_lru_gen (folio); +int gen, refs;int zone =folio_zonenum (folio);int delta =folio_nr_pages (folio);enum lru_list lru =folio_is_file_lru (folio) *LRU_INACTIVE_FILE ; +unsigned long max_seq =READ_ONCE (lruvec->lrugen.max_seq); + flags =set_mask_bits (folio_flags (folio,0 ),LRU_GEN_MASK ,0 );
[Severity: Medium]
Could this mask also be missing the LRU_REFS_FLAGS bit clear?
Similar to the addition path above, when isolating a folio and clearing LRU_GEN_MASK, the tier tracking bits might also need to be explicitly cleared so they are not improperly carried over.
Quoted 4 lines
include/linux/mm_inline.h +2
-0+ gen =lru_get_gen_flags (flags); + refs =lru_get_refs_flags (flags);if (gen <0 )return false;
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=13
Kairui Song
maintainerPATCH v4 14/17 mm/mglru: reparent folios from all generations
In reply to Kairui SongA lockless promotion racing with aging can reuse a generation index, see folio_inc_lru_refs(). The retry repairs the folio flags, but sort_folio() may have already moved the folio to the list of a generation outside the [min_seq, max_seq] window.
__lru_gen_reparent_memcg() only splices the lists inside the child's window, so such a folio would be left on a list of the dying memcg. Splice the lists and move the counters of all MAX_NR_GENS generations instead. Those outside the window are empty in the common case.
--- mm/vmscan.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
mm/vmscan.c +2 -1
@@ -4936,7 +4936,8 @@ static void __lru_gen_reparent_memcg(struct lruvec *child_lruvec, struct lruvec child_lrugen = &child_lruvec->lrugen; parent_lrugen = &parent_lruvec->lrugen; -for (i =0 ; i <get_nr_gens (child_lruvec, type); i++) { +/* Lockless promotion may leave folios outside the child's window */ +for (i =0 ; i <MAX_NR_GENS ; i++) {int gen =lru_gen_from_seq (child_lrugen->max_seq - i);long nr_pages =atomic_long_read (&child_lrugen->nr_pages[gen][type][zone]);
Signature · 1 line
2.56.0
[email protected]
AI reviewRe: [PATCH v4 14/17] mm/mglru: reparent folios from all generations
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 7 lines
From: Kairui Song <[email protected]>
A lockless promotion racing with aging can reuse a generation index, see
folio_inc_lru_refs(). The retry repairs the folio flags, butsort_folio()may have already moved the folio to the list of a generation outside the [min_seq,max_seq] window.
Quoted 7 lines
__lru_gen_reparent_memcg()only splices the lists inside the child's window, so such a folio would be left on a list of the dying memcg. Splice the lists and move the counters of allMAX_NR_GENSgenerations instead. Those outside the window are empty in the common case.Assisted-by LLMSigned-off-by Kairui Song <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=14
Kairui Song
maintainerPATCH v4 15/17 mm/mglru: make folio_inc_lru_refs lruvec lockless
In reply to Kairui SongThe lruvec spinlock in folio_inc_lru_refs was only taken to keep concurrent aging from corrupting the size counters. This is no longer needed: the per-generation counters are atomic, and the active/inactive ABI counters are updated per folio and linearized by the CAS on the folio flags, so concurrent aging can no longer corrupt them. The same argument already allowed folio_reset_lru_refs() to drop the lock.
Use folio_lruvec_live_get()/folio_lruvec_live_put() to hold the RCU read lock around the lruvec lookup, and drop the spinlock entirely.
Without the lock, aging can advance max_seq while a promotion is in flight. Generations are indexed by seq % MAX_NR_GENS, so the folio flags can return to the value read earlier and the cmpxchg succeeds with a target gen computed from a stale max_seq. Recheck max_seq after a gen-changing cmpxchg: if it moved, account the committed update and retry with LRU_REF_FORCE, which promotes the folio to the newest gen. The retry may count the access twice, which is acceptable and avoids folio_activate(), whose LRU lock causes latency jitter. smp_rmb() orders the flags read, including the one returned by a failed cmpxchg(), before the max_seq read.
Also simplify the post-CAS accounting guards: gen is only assigned non-negative values after the old_gen < 0 early exit, so gen != old_gen implies gen >= 0, and lru_gen_update_size() needs no explicit guard. The active/inactive ABI update keeps its gen >= 0 check because an off-LRU folio has no lruvec to update.
--- include/linux/mm_inline.h | 10 ++++----- include/linux/mmzone.h | 3 ++- mm/vmscan.c | 53 ++++++++++++++++++++++++++++++----------------- 3 files changed, 41 insertions(+), 25 deletions(-)
include/linux/mm_inline.h +5 -5
@@ -308,10 +308,9 @@ static inline bool lru_gen_at_tail(struct lruvec *lruvec, int type, int gen) gen ==lru_gen_from_seq (min_seq +1 ); } -static inline void lru_gen_update_size (struct lruvec *lruvec,struct folio *folio, -int old_gen,int new_gen) +static inline void lru_gen_update_size (struct lruvec *lruvec,int type, +struct folio *folio,int old_gen,int new_gen) { -int type =folio_is_file_lru (folio);int zone =folio_zonenum (folio);int delta =folio_nr_pages (folio);struct lru_gen_folio *lrugen = &lruvec->lrugen;
@@ -386,7 +385,7 @@ static inline bool lru_gen_add_folio(struct lruvec *lruvec, struct folio *folio,/* use the refs from the atomic snapshot to avoid raced update */ refs =lru_get_refs_flags (flags); -lru_gen_update_size (lruvec, folio,-1 , gen); +lru_gen_update_size (lruvec, type, folio,-1 , gen);if (lru_refs_is_active (refs)) lru +=LRU_ACTIVE ;__update_lru_size (lruvec, lru, zone, delta);
@@ -404,6 +403,7 @@ static inline bool lru_gen_del_folio(struct lruvec *lruvec, struct folio *folio, {unsigned long flags;int gen, refs; +int type =folio_is_file_lru (folio);int zone =folio_zonenum (folio);int delta =folio_nr_pages (folio);enum lru_list lru =folio_is_file_lru (folio) *LRU_INACTIVE_FILE ;
@@ -426,7 +426,7 @@ static inline bool lru_gen_del_folio(struct lruvec *lruvec, struct folio *folio,if (!reclaiming && ((max_seq - gen) %MAX_NR_GENS ) <MIN_NR_GENS )folio_set_active (folio); -lru_gen_update_size (lruvec, folio, gen,-1 ); +lru_gen_update_size (lruvec, type, folio, gen,-1 );if (lru_refs_is_active (refs)) lru +=LRU_ACTIVE ;__update_lru_size (lruvec, lru, zone, -delta);
include/linux/mmzone.h +2 -1
@@ -559,9 +559,10 @@ enum lruvec_flags {#define LRU_TIER_MIN 0U#define LRU_TIER_MAX (MAX_NR_TIERS - 1) -/* Access source flags for folio_inc_lru_refs() */ +/* Flags for folio_inc_lru_refs() */ #define LRU_REF_MAPPED 0x1U#define LRU_REF_EXEC 0x2U +#define LRU_REF_FORCE 0x4U#define LRU_REFS_REFERENCED 0x1#define LRU_REFS_WORKINGSET 0x2
mm/vmscan.c +34 -19
101 lines not on this page · raw message
Signature · 1 line
2.56.0
[email protected]
AI reviewRe: [PATCH v4 15/17] mm/mglru: make folio_inc_lru_refs lruvec lockless
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 13 lines
From: Kairui Song <[email protected]>
The lruvec spinlock in
folio_inc_lru_refswas only taken to keep concurrent aging from corrupting the size counters. This is no longer needed: the per-generation counters are atomic, and the active/inactive ABI counters are updated per folio and linearized by the CAS on the folio flags, so concurrent aging can no longer corrupt them. The same argument already allowedfolio_reset_lru_refs()to drop the lock.Use folio_lruvec_live_get()/folio_lruvec_live_put() to hold the RCU read lock around the lruvec lookup, and drop the spinlock entirely.
Quoted 8 lines
Without the lock, aging can advance
max_seqwhile a promotion is in flight. Generations are indexed by seq %MAX_NR_GENS, so the folio [ ... ]
implies gen >= 0, andlru_gen_update_size()needs no explicit guard. The active/inactive ABI update keeps its gen >= 0 check because an off-LRU folio has no lruvec to update.Signed-off-by Kairui Song <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=15
Barry Song
reviewerRe: [PATCH v4 15/17] mm/mglru: make folio_inc_lru_refs lruvec lockless
In reply to Kairui SongQuoted 11 lines · On Fri, Oct 16, 2026 at 2:16 AM Kairui Song via B4 Relay…
From: Kairui Song <[email protected]>
The lruvec spinlock in
folio_inc_lru_refswas only taken to keep concurrent aging from corrupting the size counters. This is no longer needed: the per-generation counters are atomic, and the active/inactive ABI counters are updated per folio and linearized by the CAS on the folio flags, so concurrent aging can no longer corrupt them. The same argument already allowedfolio_reset_lru_refs()to drop the lock.
Quoted 3 lines
Use folio_lruvec_live_get()/folio_lruvec_live_put() to hold the RCU read lock around the lruvec lookup, and drop the spinlock entirely.
Yes, this is cool. We have two paths calling folio_inc_lru_refs() or folio_inc_lru_refs_walk().
1. folio_mark_accessed() from syscall access
2. walk_update_folio() from page table walker or look_around
For the latter, we can't actually cross multiple lruvecs/memcgs, because of get_pfn_folio() as shown below:
static struct folio *get_pfn_folio(unsigned long pfn, struct mem_cgroup *memcg,
struct pglist_data *pgdat)
{
...
rcu_read_lock();
if (folio_memcg(folio) != memcg)
folio = NULL;
rcu_read_unlock();
...
}Consider a common library file used by 100 memcgs, with its folio residing in the root memcg.
When walking the 99 non-root memcgs, even if the folio has been accessed, we won't get a chance to call folio_inc_lru_refs_walk() for it. As a result, this folio may eventually reach the eviction rmap path. With a high mapcount, folio_referenced() could become quite expensive.
That's what I was trying to point out here as well:
https://lore.kernel.org/linux-mm/[email protected]/#t
For the former, you can get the lruvec with:
lruvec = lruvec_live_lock_irq(folio_lruvec(folio));
I'm wondering whether we could eventually unify them so that both support cross-memcg inc_refs.
This isn't a blocker for the patch, just something I've been thinking about.
Quoted 11 lines
Without the lock, aging can advance
max_seqwhile a promotion is in flight. Generations are indexed by seq %MAX_NR_GENS, so the folio flags can return to the value read earlier and the cmpxchg succeeds with a target gen computed from a stalemax_seq. Recheckmax_seqafter a gen-changing cmpxchg: if it moved, account the committed update and retry withLRU_REF_FORCE, which promotes the folio to the newest gen. The retry may count the access twice, which is acceptable and avoidsfolio_activate(), whose LRU lock causes latency jitter.smp_rmb()orders the flags read, including the one returned by a failedcmpxchg(), before themax_seqread.
Quoted 8 lines
Also simplify the post-CAS accounting guards: gen is only assigned non-negative values after the
old_gen< 0 early exit, so gen !=old_genimplies gen >= 0, andlru_gen_update_size()needs no explicit guard. The active/inactive ABI update keeps its gen >= 0 check because an off-LRU folio has no lruvec to update.Signed-off-by Kairui Song <[email protected]>---
Thanks,
Barry
Re: [PATCH v4 15/17] mm/mglru: make folio_inc_lru_refs lruvec lockless
Quoted 49 lines · Barry Song
Quoted 11 lines · On Fri, Oct 16, 2026 at 2:16 AM Kairui Song via B4 Relay…
From: Kairui Song <[email protected]>
The lruvec spinlock in
folio_inc_lru_refswas only taken to keep concurrent aging from corrupting the size counters. This is no longer needed: the per-generation counters are atomic, and the active/inactive ABI counters are updated per folio and linearized by the CAS on the folio flags, so concurrent aging can no longer corrupt them. The same argument already allowedfolio_reset_lru_refs()to drop the lock.Quoted 3 lines
Use folio_lruvec_live_get()/folio_lruvec_live_put() to hold the RCU read lock around the lruvec lookup, and drop the spinlock entirely.
Yes, this is cool. We have two paths calling
folio_inc_lru_refs()orfolio_inc_lru_refs_walk().1.
folio_mark_accessed()from syscall access
2.walk_update_folio()from page table walker orlook_aroundFor the latter, we can't actually cross multiple lruvecs/memcgs, because of
get_pfn_folio()as shown below:static struct folio *get_pfn_folio(unsigned long pfn, struct
mem_cgroup*memcg,
structpglist_data*pgdat){ ... rcu_read_lock(); if (folio_memcg(folio) != memcg) folio = NULL; rcu_read_unlock(); ... }Consider a common library file used by 100 memcgs, with its folio residing in the root memcg.
When walking the 99 non-root memcgs, even if the folio has been accessed, we won't get a chance to call
folio_inc_lru_refs_walk()for it. As a result, this folio may eventually reach the eviction rmap path. With a high mapcount,folio_referenced()could become quite expensive.
Quoted 3 lines
That's what I was trying to point out here as well:
Hi Barry,
Thanks for the review, I saw that too, very interesting approach! And I believe it will helpful.
Quoted 6 lines
For the former, you can get the lruvec with:
lruvec = lruvec_live_lock_irq(folio_lruvec(folio));
I'm wondering whether we could eventually unify them so that both support cross-memcg
inc_refs.
Definately, actually for that link you posted, combined with the code snip above, after FG, I think we can further simplify that, no need to check mem_cgroup_is_descendant, we just do:
- folio_inc_lru_refs_walk: if the folio belongs to the lruvec being walked, the batch stays in walk->lruvec
- folio_inc_lru_refs: if the folio is a remote one, per-folio, no batch
non-descendant folio sharing across memcg are actually quite common e.g., libc and shared mapped memory, this could be more helpful? And it seems fast for the walker.
folio_inc_lru_refs_walk follow the same rule as folio_inc_lru_refs (with MAPPED flag), just faster, skipping RCU and the speculative check afterwards as the walker owns the seq it is advancing, and caller handles the batch update of counter. While folio_inc_lru_refs only requires the caller to hold an reference to the folio it heavily relies on RCU / CAS conventions, not easy to batch things there, but it's still accetablily fast already (e.g. the fio read test showed almost no performance penalty).
And I think the main reason MGLRU can't operate cross memcg was, lack of a protocol to stablilze the memcg's gen and holding a lock is too costly, now folio_inc_lru_refs handles that, and FG
lives on top of that. So we can try that out right after the FG series.
Barry Song
reviewerRe: [PATCH v4 15/17] mm/mglru: make folio_inc_lru_refs lruvec lockless
Quoted 71 lines · Kairui Song
Quoted 49 lines · Barry Song
Quoted 11 lines · On Fri, Oct 16, 2026 at 2:16 AM Kairui Song via B4 Relay…
From: Kairui Song <[email protected]>
The lruvec spinlock in
folio_inc_lru_refswas only taken to keep concurrent aging from corrupting the size counters. This is no longer needed: the per-generation counters are atomic, and the active/inactive ABI counters are updated per folio and linearized by the CAS on the folio flags, so concurrent aging can no longer corrupt them. The same argument already allowedfolio_reset_lru_refs()to drop the lock.Quoted 3 lines
Use folio_lruvec_live_get()/folio_lruvec_live_put() to hold the RCU read lock around the lruvec lookup, and drop the spinlock entirely.
Yes, this is cool. We have two paths calling
folio_inc_lru_refs()orfolio_inc_lru_refs_walk().1.
folio_mark_accessed()from syscall access
2.walk_update_folio()from page table walker orlook_aroundFor the latter, we can't actually cross multiple lruvecs/memcgs, because of
get_pfn_folio()as shown below:static struct folio *get_pfn_folio(unsigned long pfn, struct
mem_cgroup*memcg,
structpglist_data*pgdat){ ... rcu_read_lock(); if (folio_memcg(folio) != memcg) folio = NULL; rcu_read_unlock(); ... }Consider a common library file used by 100 memcgs, with its folio residing in the root memcg.
When walking the 99 non-root memcgs, even if the folio has been accessed, we won't get a chance to call
folio_inc_lru_refs_walk()for it. As a result, this folio may eventually reach the eviction rmap path. With a high mapcount,folio_referenced()could become quite expensive.Quoted 3 lines
That's what I was trying to point out here as well:
Hi Barry,
Thanks for the review, I saw that too, very interesting approach! And I believe it will helpful.
Quoted 6 lines
For the former, you can get the lruvec with:
lruvec = lruvec_live_lock_irq(folio_lruvec(folio));
I'm wondering whether we could eventually unify them so that both support cross-memcg
inc_refs.Definately, actually for that link you posted, combined with the code snip above, after FG, I think we can further simplify that, no need to check
mem_cgroup_is_descendant, we just do:
Quoted 7 lines
-
folio_inc_lru_refs_walk: if the folio belongs to the lruvec being walked, the batch stays inwalk->lruvec
-folio_inc_lru_refs: if the folio is a remote one, per-folio, no batchnon-descendant folio sharing across memcg are actually quite common e.g., libc and shared mapped memory, this could be more helpful? And it seems fast for the walker.
I agree. I mentioned mem_cgroup_is_descendant() because folio_referenced() checks for descendants and ignores folios belonging to non-descendant memcgs:
static bool invalid_folio_referenced_vma(struct vm_area_struct *vma, void *arg)
{
struct folio_referenced_arg *pra = arg;
struct mem_cgroup *memcg = pra->memcg;
...
/*
* If we are reclaiming on behalf of a cgroup, skip counting on behalf
* of references from different cgroups.
*/
if (memcg && !mm_match_cgroup(vma->vm_mm, memcg))
return true;
return false;
}static inline bool mm_match_cgroup(struct mm_struct *mm,
const struct mem_cgroup *memcg)
{
struct mem_cgroup *task_memcg;
bool match = false;
rcu_read_lock();
task_memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
if (task_memcg)
match = mem_cgroup_is_descendant(task_memcg, memcg);
rcu_read_unlock();
return match;
}I actually wonder whether this is really correct...
Quoted 9 lines
folio_inc_lru_refs_walkfollow the same rule asfolio_inc_lru_refs(with MAPPED flag), just faster, skipping RCU and the speculative check afterwards as the walker owns the seq it is advancing, and caller handles the batch update of counter. Whilefolio_inc_lru_refsonly requires the caller to hold an reference to the folio it heavily relies on RCU / CAS conventions, not easy to batch things there, but it's still accetablily fast already (e.g. the fio read test showed almost no performance penalty).
Yes. One tricky aspect is that update_batch_size() is designed for the current lruvec, not a remote one.
static void walk_update_folio(struct lru_gen_mm_walk *walk, struct vm_area_struct *vma,
struct lruvec *lruvec, struct folio *folio, bool dirty)
{
...
if (walk) {
old_gen = folio_update_gen(folio, new_gen, &type, &vma->flags);
if (old_gen >= 0 && old_gen != new_gen)
update_batch_size(walk, folio, old_gen, new_gen, type);
} else if (lru_gen_set_refs(folio, &vma->flags)) {
...
}
}Quoted 5 lines
And I think the main reason MGLRU can't operate cross memcg was, lack of a protocol to stablilze the memcg's gen and holding a lock is too costly, now
folio_inc_lru_refshandles that, and FG
lives on top of that. So we can try that out right after the FG series.
Yes, absolutely. With MGLRU-FG, we lay the groundwork for further cross-memcg optimizations.
On Android, we observed that folios with very large mapcounts still reach the rmap path because walk and look-around cannot promote them across memcgs. In more than 99% of cases, folio_referenced() finds them PTE-young. As a result, these folios incur the rmap overhead but are unlikely to be reclaimed. It's essentially wasted rmap work.
With the cross-memcg optimizations, we are likely to eliminate this overhead.
Thanks,
Barry
Kairui Song
maintainerPATCH v4 16/17 mm/mglru: make folio_test_workingset() work based on folio LRU refs
In reply to Kairui Songfolio_test_workingset() currently tests the PG_workingset bit, which is only the second lowest access bit of the folio LRU refs count now. Folios with a higher refs count carry it in the LRU_REFS_MASK field and no longer have PG_workingset set, so the bit test misses them.
folio_set_workingset() currently sets the PG_workingset bit with a plain set_bit(), which also over-promotes folios at a higher refs
count: e.g. a folio at refs 4 is bumped to refs 6, advancing it toward LRU_REFS_MAX and an unintended generation promotion on the next access.
Move the test into mm_inline.h as an inline helper based on folio_lru_refs(), checking refs >= LRU_REFS_WORKINGSET. The set stays a plain PG_workingset bit operation reserved for the classical LRU: under MGLRU the refs count is maintained by folio_inc_lru_refs(), and now triggers a debug WARN when called while MGLRU is fully on (the switching window is exempt, as the classical paths legitimately run alongside MGLRU then). The one PageWorkingset() user in erofs is converted to the folio helper.
Under the classical LRU the refs count is not maintained, so the test falls back to the PG_workingset bit test, which is the old behavior.
--- fs/btrfs/compression.c | 1 + fs/erofs/zdata.c | 3 ++- include/linux/mm_inline.h | 29 +++++++++++++++++++++++++++++ include/linux/page-flags.h | 2 -- mm/filemap.c | 1 + mm/page_io.c | 1 + 6 files changed, 34 insertions(+), 3 deletions(-)
fs/btrfs/compression.c +1 -0
@@ -8,6 +8,7 @@#include <linux/file.h> #include <linux/fs.h> #include <linux/pagemap.h> +#include <linux/mm_inline.h> #include <linux/folio_batch.h> #include <linux/highmem.h> #include <linux/kthread.h>
fs/erofs/zdata.c +2 -1
@@ -6,6 +6,7 @@*/ #include "compress.h" #include <linux/psi.h> +#include <linux/mm_inline.h> #include <linux/cpuhotplug.h> #include <trace/events/erofs.h>
@@ -1713,7 +1714,7 @@ static void z_erofs_submit_queue(struct z_erofs_frontend *f,DBG_BUGON (bvec.bv_len < sb->s_blocksize); } -if (unlikely (PageWorkingset (bvec.bv_page)) && +if (unlikely (folio_test_workingset (page_folio (bvec.bv_page))) && !memstall) {psi_memstall_enter (&pflags); memstall =1 ;
include/linux/mm_inline.h +29 -0
@@ -288,6 +288,23 @@ static inline void folio_migrate_lru_refs(struct folio *new, const struct folio__folio_set_lru_refs (new,folio_lru_refs (old)); } +/** +* folio_test_workingset - Test if a folio is in the workingset. +* @folio: the folio +* +* A folio is workingset when its LRU refs count reaches +* LRU_REFS_WORKINGSET. Under the classical LRU the extra refs counter +* are always zero so this is just testing the PG_workingset bit. +* NOTE: folio_set_workingset() must not be used under MGLRU, as the +* folio refs are tracked by folio_inc_lru_refs() with rules. +* +* Return: true if the folio is workingset. +*/ +static __always_inline bool folio_test_workingset(const struct folio *folio) +{ +return folio_lru_refs (folio) >=LRU_REFS_WORKINGSET ; +} +#ifdef CONFIG_LRU_GEN static inline bool lru_refs_is_active (unsigned int refs) {
@@ -519,6 +536,18 @@ static inline void folio_clear_lru_refs(struct folio *folio)folio_clear_referenced (folio); } +/* +* For the classical LRU only: with MGLRU the PG_workingset bit is +* part of the folio refs count maintained by folio_inc_lru_refs(), +* and a raw set would corrupt it. The switching window is exempt +* because the classical paths legitimately run alongside MGLRU then. +*/ +static __always_inline void folio_set_workingset(struct folio *folio) +{ +VM_WARN_ON_ONCE (lru_gen_enabled () && !lru_gen_switching ()); +set_bit (PG_workingset,folio_flags (folio,FOLIO_HEAD_PAGE )); +} +static __always_inline void lruvec_add_folio(struct lruvec *lruvec, struct folio *folio) {
include/linux/page-flags.h +0 -2
@@ -549,8 +549,6 @@ PAGEFLAG(LRU, lru, PF_HEAD) __CLEARPAGEFLAG(LRU, lru, PF_HEAD) FOLIO_FLAG(active, FOLIO_HEAD_PAGE) __FOLIO_CLEAR_FLAG(active, FOLIO_HEAD_PAGE) FOLIO_TEST_CLEAR_FLAG(active, FOLIO_HEAD_PAGE) -PAGEFLAG(Workingset, workingset, PF_HEAD) - TESTCLEARFLAG(Workingset, workingset, PF_HEAD)PAGEFLAG (Checked, checked,PF_NO_COMPOUND )/* Used by some filesystems */ /* Xen */
mm/filemap.c +1 -0
@@ -21,6 +21,7 @@#include <linux/gfp.h> #include <linux/mm.h> #include <linux/swap.h> +#include <linux/mm_inline.h> #include <linux/leafops.h> #include <linux/syscalls.h> #include <linux/mman.h>
mm/page_io.c +1 -0
@@ -16,6 +16,7 @@#include <linux/gfp.h> #include <linux/pagemap.h> #include <linux/swap.h> +#include <linux/mm_inline.h> #include <linux/bio.h> #include <linux/swapops.h> #include <linux/writeback.h>
Signature · 1 line
2.56.0
[email protected]
AI reviewRe: [PATCH v4 16/17] mm/mglru: make folio_test_workingset() work based on folio LRU refs
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 22 lines
From: Kairui Song <[email protected]>
folio_test_workingset()currently tests thePG_workingsetbit, which is only the second lowest access bit of the folio LRU refs count now. Folios with a higher refs count carry it in theLRU_REFS_MASKfield and no longer havePG_workingsetset, so the bit test misses them.
folio_set_workingset()currently sets thePG_workingsetbit with a plainset_bit(), which also over-promotes folios at a higher refs
count: e.g. a folio at refs 4 is bumped to refs 6, advancing it towardLRU_REFS_MAXand an unintended generation promotion on the next access.Move the test into
mm_inline.has an inline helper based onfolio_lru_refs(), checking refs >=LRU_REFS_WORKINGSET. The set stays a plainPG_workingsetbit operation reserved for the classical LRU: under MGLRU the refs count is maintained byfolio_inc_lru_refs(), and now triggers a debug WARN when called while MGLRU is fully on (the switching window is exempt, as the classical paths legitimately run alongside MGLRU then). The onePageWorkingset()user in erofs is converted to the folio helper.
Quoted 6 lines
Under the classical LRU the refs count is not maintained, so the test falls back to the
PG_workingsetbit test, which is the old behavior.Tested-by zhaozhengzhuo <[email protected]>Signed-off-by Kairui Song <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=16
Kairui Song
maintainerPATCH v4 17/17 Documentation/mm: multi-gen LRU: update for frequency guided promotion
In reply to Kairui SongThe design doc still describes the old tier and promotion model:
- Tiers are no longer order_base_2() of the file descriptor accesses. A folio's tier is derived from its referenced count, which counts accesses from both page tables and file descriptors.
- A young PTE no longer always promotes a folio to the newest generation. The first access only moves a folio one generation forward if it is at the tail of its LRU, i.e., in one of the two oldest generations of its type, a second access promotes it, and executable file folios are promoted on their first access.
- The eviction no longer uses the first tier as the only baseline. The type is selected by comparing all tiers of each type, and a tier is protected by comparing it against the tiers below it.
Update the aging and eviction sections accordingly.
--- Documentation/mm/multigen_lru.rst | 57 ++++++++++++++++++++++----------------- 1 file changed, 33 insertions(+), 24 deletions(-)
Documentation/mm/multigen_lru.rst +33 -24
@@ -95,16 +95,19 @@ at most ``MAX_NR_GENS`` generations. The gen counter stores a value within ``[1, MAX_NR_GENS]`` while a page is on one of ``lrugen->folios[]``; otherwise it stores zero. -Each generation is divided into multiple tiers. A page accessed ``N`` -times through file descriptors is in tier ``order_base_2(N)``. Unlike -generations, tiers do not have dedicated ``lrugen->folios[]``. In -contrast to moving across generations, which requires the LRU lock, -moving across tiers only involves atomic operations on -``folio->flags`` and therefore has a negligible cost. A feedback loop -modeled after the PID controller monitors refaults over all the tiers -from anon and file types and decides which tiers from which types to -evict or protect. The desired effect is to balance refault percentages -between anon and file types proportional to the swappiness level. +Each generation is divided into multiple tiers. A page's tier is +derived from its referenced count, which counts the accesses collected +from both channels above and is capped at ``LRU_REFS_MAX``: pages +accessed at most once are in the lowest tier, and the tiers above hold +pages accessed at least twice. Unlike generations, tiers do not have +dedicated ``lrugen->folios[]``. In contrast to moving across +generations, which requires the LRU lock, updating the referenced +count only involves atomic operations on ``folio->flags`` and +therefore has a negligible cost. A feedback loop modeled after the PID +controller monitors refaults over all the tiers from anon and file +types and decides which tiers from which types to evict or protect. +The desired effect is to balance refault percentages between anon and +file types proportional to the swappiness level. There are two conceptually independent procedures: the aging and the eviction. They form a closed-loop system, i.e., the page reclaim.
@@ -122,25 +125,31 @@ and calls ``walk_page_range()`` with each ``mm_struct`` on this list to scan PTEs, and after each iteration, it increments ``max_seq``. For the latter, when the eviction walks the rmap and finds a young PTE, the aging scans the adjacent PTEs. For both, on finding a young PTE, -the aging clears the accessed bit and updates the gen counter of the -page mapped by this PTE to ``(max_seq%MAX_NR_GENS)+1``. +the aging clears the accessed bit and bumps the referenced count of +the page mapped by this PTE. A second access promotes the page by +updating its gen counter to ``(max_seq%MAX_NR_GENS)+1``; the first +access only moves a page one generation forward if it is at the tail +of its LRU, i.e., in one of the two oldest generations of its type, +so that the next time it becomes the oldest one, its accessed bit +reflects whether it has been used again. Executable file pages are +promoted on their first access, since reclaiming them causes typical +I/O thrashing. Eviction -------- The eviction consumes old generations. Given an ``lruvec``, it increments ``min_seq`` when ``lrugen->folios[]`` indexed by -``min_seq%MAX_NR_GENS`` becomes empty. To select a type and a tier to -evict from, it first compares ``min_seq[]`` to select the older type. -If both types are equally old, it selects the one whose first tier has -a lower refault percentage. The first tier contains single-use -unmapped clean pages, which are the best bet. The eviction sorts a -page according to its gen counter if the aging has found this page -accessed through page tables and updated its gen counter. It also -moves a page to the next generation, i.e., ``min_seq+1``, if this page -was accessed multiple times through file descriptors and the feedback -loop has detected outlying refaults from the tier this page is in. To -this end, the feedback loop uses the first tier as the baseline, for -the reason stated earlier. +``min_seq%MAX_NR_GENS`` becomes empty. To select a type to evict from, +it first compares ``min_seq[]`` to select the older type. If both +types are equally old, it compares the refault percentages of all the +tiers of each type proportional to the swappiness level. To select a +tier to protect, it compares the refault percentage of each tier +against that of the tiers below it. The lowest tier contains pages +accessed at most once, which are the best bet. The eviction sorts a +page according to its gen counter if the aging or an access has +updated its gen counter. It also moves a page to the next generation, +i.e., ``min_seq+1``, if the feedback loop has detected outlying +refaults from the tier this page is in. Working set protection ----------------------
Signature · 1 line
2.56.0
[email protected]
AI reviewRe: [PATCH v4 17/17] Documentation/mm: multi-gen LRU: update for frequency guided promotion
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 14 lines
From: Kairui Song <[email protected]>
The design doc still describes the old tier and promotion model:
- Tiers are no longer
order_base_2()of the file descriptor accesses. A folio's tier is derived from its referenced count, which counts accesses from both page tables and file descriptors.- A young PTE no longer always promotes a folio to the newest generation. The first access only moves a folio one generation forward if it is at the tail of its LRU, i.e., in one of the two oldest generations of its type, a second access promotes it, and executable file folios are promoted on their first access.
Quoted 8 lines
- The eviction no longer uses the first tier as the only baseline. The type is selected by comparing all tiers of each type, and a tier is protected by comparing it against the tiers below it.
Update the aging and eviction sections accordingly.
Assisted-by LLMSigned-off-by Kairui Song <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=17
Barry Song (Xiaomi)
reviewerOn Fri, Oct 16, 2026 at 2:15 AM Kairui Song via B4 Relay <[email protected]> wrote:
[...]
Quoted 27 lines
LevelDB Scan/Get
================
I also retested the LevelDB benchmark from thecache_extpaper [5]. Interestingly, mainline MGLRU already beats CLRU on this one after a recent change inlru_gen_folio_seqthat bumps new folios with refs == 1 to the second-oldest generation as discussed. That change accidentally gave random reads a higher hotness level while making sequential reads much colder as described before [14]. However it's unreliable and incorrect because it depends on LRU drain timing, and hurts some workloads as reported, or where the sequential part is actually hotter (any workload involving hotter large file and many small cold files will be affected) which is reproduced below.This series improves it while covering ordinary workloads too and should fix regressions:
LevelDB Scan / Get, Throughput Total:
CLRU: 4708.3 ops/s
MGLRU: 5026.9 ops/s (faster than CLRU, but hurts other workloads) MGLRU After: 5179.2 ops/s (even better in all cases, and no regression)The hot-sequential and cold-random workload can be easily reproduced with SQLite and grep. SQLite continuously scans and looks up a small hot portion of a DB file, while grep iterates over a set of small files much larger than RAM [6]:
Quoted 5 lines
SQLite scan & lookup time: Grep iterate time:
CLRU: 14.51ms 13281.37ms MGLRU mainline: 567.05ms 13694.47ms MGLRU After this series: 10.58ms 12930.43ms
Thanks, Kairui. I'll do a thorough review of the whole patchset over the next two weeks.
BTW, do you think we need a quick fix patch like the one below for the above problem before this patchset, so that it can be backported to stable? I assume your patchset is too large to backport?
From f9683205d2ab6e3b185022d7d5af3496dfe5f35f Mon Sep 17 00:00:00 2001
From: "Barry Song (Xiaomi)" <[email protected]>
Date: Fri, 16 Oct 2026 11:48:06 +0800
Subject: [PATCH] mm/mglru: fix using folio_mark_accessed to replace
folio_set_active
Commit 6cbdd9726fb5 ("mm/mglru: use folio_mark_accessed to replace folio_set_active") tried to avoid over-protecting fault-around read-ahead file folios by placing them in the second-oldest generation instead of the youngest generations.
However, it abuses PG_referenced on read-ahead file folios for this purpose, potentially coupling their handling with normal syscall-based file accesses that also use PG_referenced.
This could regress some workloads, as reported by Kairui Song[1] and Ehab Ababneh[2]. Many thanks to both for reporting these issues!
The long-term fix is Kairui's MGLRU-FG, but in the meantime, we also need a quick fix that can be backported to stable.
This patch reverts all of the original commit's behavior that abuses PG_referenced, while preserving the semantics of avoiding over-protection of fault-around read-ahead file folios by adjusting only lru_gen_folio_seq(). Specifically, fault-around read-ahead file folios with PG_active set but PG_workingset clear are placed in the second-oldest generation.
Activated file folios and refaulted workingset file folios are still placed in the youngest generations.
Build kernel cases in a memcg shows it not only perserve the benefit of original patch, but also even improve performance further.
w/o fix:
real 1m49.094s user 25m31.484s sys 3m40.959s
pswpin: 662112
pswpout: 2504415
pgpgin: 4424336
pgpgout: 10355273refault_file: 359626refault_anon: 670724
w/ fix:
real 1m48.913s
user 25m31.639s
sys 3m30.875s
pswpin: 689815
pswpout: 2689894
pgpgin: 4422659
pgpgout: 11043464refault_file: 326566refault_anon: 697138
Revert original patch:
real 1m50.044s
user 25m37.137s
sys 4m4.493s
pswpin: 1349087
pswpout: 4317933
pgpgin: 7083597
pgpgout: 17602735refault_file: 337676refault_anon: 1368542
[1] https://lore.kernel.org/linux-mm/[email protected]/
[2] https://lore.kernel.org/linux-mm/[email protected]/
--- include/linux/mm_inline.h | 8 +++++--- mm/folio.c | 16 +++------------- mm/vmscan.c | 9 ++------- mm/workingset.c | 10 ++++------ 4 files changed, 14 insertions(+), 29 deletions(-)
include/linux/mm_inline.h +5 -3
@@ -311,7 +311,8 @@ static inline unsigned long lru_gen_folio_seq(const struct lruvec *lruvec,* | Accessed through page tables and | Accessed through file descriptors | * | promoted by folio_update_gen() | and protected by folio_inc_gen() | * +-----------------------------------+-----------------------------------+ -* | PG_active (set while isolated) | | +* | PG_active (set while isolated) | PG_active (files| | +* | | fault-readahead)| | * +-----------------+-----------------+-----------------+-----------------+ * | PG_workingset | PG_referenced | PG_workingset | LRU_REFS_FLAGS | * +-----------------------------------+-----------------------------------+
@@ -319,7 +320,8 @@ static inline unsigned long lru_gen_folio_seq(const struct lruvec *lruvec,* |<---------------------------- MAX_NR_GENS ---------------------------->| */ if (folio_test_active (folio)) - gen =MIN_NR_GENS -folio_test_workingset (folio); + gen =MIN_NR_GENS -folio_test_workingset (folio) + + (type ? !folio_test_workingset (folio) :0 );else if (reclaiming) gen =MAX_NR_GENS ; else if ((!folio_is_file_lru(folio) && !folio_test_swapcache(folio)) ||
@@ -327,7 +329,7 @@ static inline unsigned long lru_gen_folio_seq(const struct lruvec *lruvec, (folio_test_dirty(folio) || folio_test_writeback(folio)))) gen =MIN_NR_GENS ; else - gen =MAX_NR_GENS - (folio_test_workingset (folio) ||folio_test_referenced (folio)); + gen =MAX_NR_GENS -folio_test_workingset (folio);return max (READ_ONCE (lrugen->max_seq) - gen +1 ,READ_ONCE (lrugen->min_seq[type])); }
mm/folio.c +3 -13
@@ -474,20 +474,10 @@ void folio_add_lru(struct folio *folio) folio_test_unevictable(folio), folio);VM_BUG_ON_FOLIO (folio_test_lru (folio), folio); -/* -* For refaulted workingset folios, set PG_active so they -* can be added to active generations. -* For prefaulted file folios, folio_mark_accessed() sets -* PG_referenced so lru_gen_folio_seq() places them into -* the second oldest generation. -*/ +/* see the comment in lru_gen_folio_seq() */ if (lru_gen_enabled () && !folio_test_unevictable (folio) && -lru_gen_in_fault () && !(current->flags &PF_MEMALLOC )) { -if (folio_test_workingset (folio)) -folio_set_active (folio); -else if (!folio_test_referenced (folio)) -folio_mark_accessed (folio); - } +lru_gen_in_fault () && !(current->flags &PF_MEMALLOC )) +folio_set_active (folio);folio_batch_add_and_move (folio, lru_add); }
mm/vmscan.c +2 -7
@@ -952,13 +952,8 @@ static bool lru_gen_set_refs(struct folio *folio, const vma_flags_t *vma_flags) return false; } -/* Promote on second access */ -if (folio_lru_refs (folio) >1 ) { -folio_set_workingset (folio); -folio_set_lru_refs (folio,0 ); - }else { -folio_mark_accessed (folio); - } +folio_set_workingset (folio); +folio_set_lru_refs (folio,0 );return true; }#else
mm/workingset.c +4 -6
@@ -319,13 +319,11 @@ static void lru_gen_refault(struct folio *folio, void *shadow)atomic_long_add (delta, &lrugen->refaulted[hist][type][tier]); +/* see folio_add_lru() where folio_set_active() will be called */ +if (lru_gen_in_fault ()) +mod_lruvec_state (lruvec,WORKINGSET_ACTIVATE_BASE + type, delta); +if (workingset) { -/* -* see folio_add_lru(), where folio_set_active() is -* called for workingset folios -*/ -if (lru_gen_in_fault ()) -mod_lruvec_state (lruvec,WORKINGSET_ACTIVATE_BASE + type, delta);folio_set_workingset (folio);mod_lruvec_state (lruvec,WORKINGSET_RESTORE_BASE + type, delta); }else
--
2.34.1
Quoted 36 lines · Barry Song (Xiaomi)
On Fri, Oct 16, 2026 at 2:15 AM Kairui Song via B4 Relay <[email protected]> wrote:
[...]Quoted 27 lines
LevelDB Scan/Get
================
I also retested the LevelDB benchmark from thecache_extpaper [5]. Interestingly, mainline MGLRU already beats CLRU on this one after a recent change inlru_gen_folio_seqthat bumps new folios with refs == 1 to the second-oldest generation as discussed. That change accidentally gave random reads a higher hotness level while making sequential reads much colder as described before [14]. However it's unreliable and incorrect because it depends on LRU drain timing, and hurts some workloads as reported, or where the sequential part is actually hotter (any workload involving hotter large file and many small cold files will be affected) which is reproduced below.This series improves it while covering ordinary workloads too and should fix regressions:
LevelDB Scan / Get, Throughput Total:
CLRU: 4708.3 ops/s MGLRU: 5026.9 ops/s (faster than CLRU, but hurts other workloads) MGLRU After: 5179.2 ops/s (even better in all cases, and no regression)The hot-sequential and cold-random workload can be easily reproduced with SQLite and grep. SQLite continuously scans and looks up a small hot portion of a DB file, while grep iterates over a set of small files much larger than RAM [6]:
Quoted 5 lines
SQLite scan & lookup time: Grep iterate time:
CLRU: 14.51ms 13281.37ms MGLRU mainline: 567.05ms 13694.47ms MGLRU After this series: 10.58ms 12930.43ms
Quoted 7 lines
Thanks, Kairui. I'll do a thorough review of the whole patchset over the next two weeks.
BTW, do you think we need a quick fix patch like the one below for the above problem before this patchset, so that it can be backported to stable? I assume your patchset is too large to backport?
Hi Barry,
Good question, I think we can patch it first.
Quoted 90 lines
From
f9683205d2ab6e3b185022d7d5af3496dfe5f35fMon Sep 17 00:00:00 2001
From: "Barry Song (Xiaomi)" <[email protected]>
Date: Fri, 16 Oct 2026 11:48:06 +0800
Subject: [PATCH] mm/mglru: fix usingfolio_mark_accessedto replace
folio_set_activeCommit
6cbdd9726fb5("mm/mglru: usefolio_mark_accessedto replacefolio_set_active") tried to avoid over-protecting fault-around read-ahead file folios by placing them in the second-oldest generation instead of the youngest generations.However, it abuses
PG_referencedon read-ahead file folios for this purpose, potentially coupling their handling with normal syscall-based file accesses that also usePG_referenced.This could regress some workloads, as reported by Kairui Song[1] and Ehab Ababneh[2]. Many thanks to both for reporting these issues!
The long-term fix is Kairui's MGLRU-FG, but in the meantime, we also need a quick fix that can be backported to stable.
This patch reverts all of the original commit's behavior that abuses
PG_referenced, while preserving the semantics of avoiding over-protection of fault-around read-ahead file folios by adjusting onlylru_gen_folio_seq(). Specifically, fault-around read-ahead file folios withPG_activeset butPG_workingsetclear are placed in the second-oldest generation.
Activated file folios and refaulted workingset file folios are still placed in the youngest generations.Build kernel cases in a memcg shows it not only perserve the benefit of original patch, but also even improve performance further.
w/o fix:
real 1m49.094s user 25m31.484s sys 3m40.959spswpin: 662112
pswpout: 2504415
pgpgin: 4424336
pgpgout: 10355273refault_file: 359626refault_anon: 670724w/ fix:
real 1m48.913s user 25m31.639s sys 3m30.875spswpin: 689815
pswpout: 2689894
pgpgin: 4422659
pgpgout: 11043464refault_file: 326566refault_anon: 697138Revert original patch:
real 1m50.044s user 25m37.137s sys 4m4.493spswpin: 1349087
pswpout: 4317933
pgpgin: 7083597
pgpgout: 17602735refault_file: 337676refault_anon: 1368542[1] https://lore.kernel.org/linux-mm/[email protected]/
[2] https://lore.kernel.org/linux-mm/[email protected]/Fixes 6cbdd9726fb5 ("mm/mglru: use folio_mark_accessed to replace folio_set_active")Cc <[email protected]>Signed-off-by Barry Song (Xiaomi) <[email protected]>--- include/linux/mm_inline.h | 8 +++++--- mm/folio.c | 16 +++------------- mm/vmscan.c | 9 ++------- mm/workingset.c | 10 ++++------ 4 files changed, 14 insertions(+), 29 deletions(-)include/linux/mm_inline.h +0
-0
include/linux/mm_inline.h static inline unsigned long lru_gen_folio_seq(const struct lruvec *lruvec, · line 315
Quoted 6 lines
include/linux/mm_inline.h +2
-1@@ -311,7 +311,8 @@ static inline unsigned long lru_gen_folio_seq(const struct lruvec *lruvec,* | Accessed through page tables and | Accessed through file descriptors | * | promoted by folio_update_gen() | and protected by folio_inc_gen() | * +-----------------------------------+-----------------------------------+ -* | PG_active (set while isolated) | | +* | PG_active (set while isolated) | PG_active (files| | +* | | fault-readahead)| |
This comment is not correct I think, faulting file folios are not access through fd, we may just better leave it uncommented.
include/linux/mm_inline.h static inline unsigned long lru_gen_folio_seq(const struct lruvec *lruvec, · line 324
Quoted 10 lines
include/linux/mm_inline.h +2
-1* +-----------------+-----------------+-----------------+-----------------+ * | PG_workingset | PG_referenced | PG_workingset | LRU_REFS_FLAGS | * +-----------------------------------+-----------------------------------+ @@ -319,7 +320,8 @@ static inline unsigned long lru_gen_folio_seq(const struct lruvec *lruvec,* |<---------------------------- MAX_NR_GENS ---------------------------->| */ if (folio_test_active (folio)) - gen =MIN_NR_GENS -folio_test_workingset (folio); + gen =MIN_NR_GENS -folio_test_workingset (folio) + + (type ? !folio_test_workingset (folio) :0 );
This looks a bit hard to follow. Does it mean that for active but non-workingset files, they are put into the third newest generation? It creates more divergence of file / anon but if it work for now, I'm fine with it.
include/linux/mm_inline.h static inline unsigned long lru_gen_folio_seq(const struct lruvec *lruvec, · line 332
Quoted 9 lines
include/linux/mm_inline.h +1
-1else if (reclaiming) gen =MAX_NR_GENS ; else if ((!folio_is_file_lru(folio) && !folio_test_swapcache(folio)) ||@@ -327,7 +329,7 @@ static inline unsigned long lru_gen_folio_seq(const struct lruvec *lruvec, (folio_test_dirty(folio) || folio_test_writeback(folio)))) gen =MIN_NR_GENS ; else - gen =MAX_NR_GENS - (folio_test_workingset (folio) ||folio_test_referenced (folio)); + gen =MAX_NR_GENS -folio_test_workingset (folio);
This is a nice change, but meanwhile the LevelDB and cerain workload gain are gone too, we will again have a ~40% regression for similiar workloads, I just double checked it. But that's fine, though, it was never meant to be optimized that way, and the long-term fix can be done later.
A quick test on another of my test machine using Tal's LevelDB test case:
CLRU: 3098 ops/s
MGLRU mainline: 3035 ops/s
MGLRU-FG: 3233 ops/s
MGLRU with this patch: 2194 ops/sec (should be same result with reverting 6cbdd9726fb5)
Quoted 74 lines
include/linux/mm_inline.h +0
-0return max (READ_ONCE (lrugen->max_seq) - gen +1 ,READ_ONCE (lrugen->min_seq[type])); }mm/folio.c +3
-13@@ -474,20 +474,10 @@ void folio_add_lru(struct folio *folio) folio_test_unevictable(folio), folio);VM_BUG_ON_FOLIO (folio_test_lru (folio), folio); -/* -* For refaulted workingset folios, set PG_active so they -* can be added to active generations. -* For prefaulted file folios, folio_mark_accessed() sets -* PG_referenced so lru_gen_folio_seq() places them into -* the second oldest generation. -*/ +/* see the comment in lru_gen_folio_seq() */ if (lru_gen_enabled () && !folio_test_unevictable (folio) && -lru_gen_in_fault () && !(current->flags &PF_MEMALLOC )) { -if (folio_test_workingset (folio)) -folio_set_active (folio); -else if (!folio_test_referenced (folio)) -folio_mark_accessed (folio); - } +lru_gen_in_fault () && !(current->flags &PF_MEMALLOC )) +folio_set_active (folio);folio_batch_add_and_move (folio, lru_add); }mm/vmscan.c +2
-7@@ -952,13 +952,8 @@ static bool lru_gen_set_refs(struct folio *folio, const vma_flags_t *vma_flags) return false; } -/* Promote on second access */ -if (folio_lru_refs (folio) >1 ) { -folio_set_workingset (folio); -folio_set_lru_refs (folio,0 ); - }else { -folio_mark_accessed (folio); - } +folio_set_workingset (folio); +folio_set_lru_refs (folio,0 );return true; }#else mm/workingset.c +4
-7@@ -319,13 +319,11 @@ static void lru_gen_refault(struct folio *folio, void *shadow)atomic_long_add (delta, &lrugen->refaulted[hist][type][tier]); +/* see folio_add_lru() where folio_set_active() will be called */ +if (lru_gen_in_fault ()) +mod_lruvec_state (lruvec,WORKINGSET_ACTIVATE_BASE + type, delta); +if (workingset) { -/* -* see folio_add_lru(), where folio_set_active() is -* called for workingset folios -*/ -if (lru_gen_in_fault ()) -mod_lruvec_state (lruvec,WORKINGSET_ACTIVATE_BASE + type, delta);folio_set_workingset (folio);mod_lruvec_state (lruvec,WORKINGSET_RESTORE_BASE + type, delta); }else --
Quoted 2 lines
2.34.1
The rest most looks clean to me.
Quoted 166 lines · Kairui Song
Quoted 36 lines · Barry Song (Xiaomi)
On Fri, Oct 16, 2026 at 2:15 AM Kairui Song via B4 Relay <[email protected]> wrote:
[...]Quoted 27 lines
LevelDB Scan/Get
================
I also retested the LevelDB benchmark from thecache_extpaper [5]. Interestingly, mainline MGLRU already beats CLRU on this one after a recent change inlru_gen_folio_seqthat bumps new folios with refs == 1 to the second-oldest generation as discussed. That change accidentally gave random reads a higher hotness level while making sequential reads much colder as described before [14]. However it's unreliable and incorrect because it depends on LRU drain timing, and hurts some workloads as reported, or where the sequential part is actually hotter (any workload involving hotter large file and many small cold files will be affected) which is reproduced below.This series improves it while covering ordinary workloads too and should fix regressions:
LevelDB Scan / Get, Throughput Total:
CLRU: 4708.3 ops/s MGLRU: 5026.9 ops/s (faster than CLRU, but hurts other workloads) MGLRU After: 5179.2 ops/s (even better in all cases, and no regression)The hot-sequential and cold-random workload can be easily reproduced with SQLite and grep. SQLite continuously scans and looks up a small hot portion of a DB file, while grep iterates over a set of small files much larger than RAM [6]:
Quoted 5 lines
SQLite scan & lookup time: Grep iterate time:
CLRU: 14.51ms 13281.37ms MGLRU mainline: 567.05ms 13694.47ms MGLRU After this series: 10.58ms 12930.43msQuoted 7 lines
Thanks, Kairui. I'll do a thorough review of the whole patchset over the next two weeks.
BTW, do you think we need a quick fix patch like the one below for the above problem before this patchset, so that it can be backported to stable? I assume your patchset is too large to backport?
Hi Barry,
Good question, I think we can patch it first.
Quoted 90 lines
From
f9683205d2ab6e3b185022d7d5af3496dfe5f35fMon Sep 17 00:00:00 2001
From: "Barry Song (Xiaomi)" <[email protected]>
Date: Fri, 16 Oct 2026 11:48:06 +0800
Subject: [PATCH] mm/mglru: fix usingfolio_mark_accessedto replace
folio_set_activeCommit
6cbdd9726fb5("mm/mglru: usefolio_mark_accessedto replacefolio_set_active") tried to avoid over-protecting fault-around read-ahead file folios by placing them in the second-oldest generation instead of the youngest generations.However, it abuses
PG_referencedon read-ahead file folios for this purpose, potentially coupling their handling with normal syscall-based file accesses that also usePG_referenced.This could regress some workloads, as reported by Kairui Song[1] and Ehab Ababneh[2]. Many thanks to both for reporting these issues!
The long-term fix is Kairui's MGLRU-FG, but in the meantime, we also need a quick fix that can be backported to stable.
This patch reverts all of the original commit's behavior that abuses
PG_referenced, while preserving the semantics of avoiding over-protection of fault-around read-ahead file folios by adjusting onlylru_gen_folio_seq(). Specifically, fault-around read-ahead file folios withPG_activeset butPG_workingsetclear are placed in the second-oldest generation.
Activated file folios and refaulted workingset file folios are still placed in the youngest generations.Build kernel cases in a memcg shows it not only perserve the benefit of original patch, but also even improve performance further.
w/o fix:
real 1m49.094s user 25m31.484s sys 3m40.959spswpin: 662112
pswpout: 2504415
pgpgin: 4424336
pgpgout: 10355273refault_file: 359626refault_anon: 670724w/ fix:
real 1m48.913s user 25m31.639s sys 3m30.875spswpin: 689815
pswpout: 2689894
pgpgin: 4422659
pgpgout: 11043464refault_file: 326566refault_anon: 697138Revert original patch:
real 1m50.044s user 25m37.137s sys 4m4.493spswpin: 1349087
pswpout: 4317933
pgpgin: 7083597
pgpgout: 17602735refault_file: 337676refault_anon: 1368542[1] https://lore.kernel.org/linux-mm/[email protected]/
[2] https://lore.kernel.org/linux-mm/[email protected]/Fixes 6cbdd9726fb5 ("mm/mglru: use folio_mark_accessed to replace folio_set_active")Cc <[email protected]>Signed-off-by Barry Song (Xiaomi) <[email protected]>--- include/linux/mm_inline.h | 8 +++++--- mm/folio.c | 16 +++------------- mm/vmscan.c | 9 ++------- mm/workingset.c | 10 ++++------ 4 files changed, 14 insertions(+), 29 deletions(-)include/linux/mm_inline.h +0
-0include/linux/mm_inline.h static inline unsigned long lru_gen_folio_seq(const struct lruvec *lruvec, · line 315
Quoted 6 lines
include/linux/mm_inline.h +2
-1@@ -311,7 +311,8 @@ static inline unsigned long lru_gen_folio_seq(const struct lruvec *lruvec,* | Accessed through page tables and | Accessed through file descriptors | * | promoted by folio_update_gen() | and protected by folio_inc_gen() | * +-----------------------------------+-----------------------------------+ -* | PG_active (set while isolated) | | +* | PG_active (set while isolated) | PG_active (files| | +* | | fault-readahead)| | This comment is not correct I think, faulting file folios are not access through fd, we may just better leave it uncommented.
include/linux/mm_inline.h static inline unsigned long lru_gen_folio_seq(const struct lruvec *lruvec, · line 324
Quoted 10 lines
include/linux/mm_inline.h +2
-1* +-----------------+-----------------+-----------------+-----------------+ * | PG_workingset | PG_referenced | PG_workingset | LRU_REFS_FLAGS | * +-----------------------------------+-----------------------------------+ @@ -319,7 +320,8 @@ static inline unsigned long lru_gen_folio_seq(const struct lruvec *lruvec,* |<---------------------------- MAX_NR_GENS ---------------------------->| */ if (folio_test_active (folio)) - gen =MIN_NR_GENS -folio_test_workingset (folio); + gen =MIN_NR_GENS -folio_test_workingset (folio) + + (type ? !folio_test_workingset (folio) :0 );This looks a bit hard to follow. Does it mean that for active but non-workingset files, they are put into the third newest generation? It creates more divergence of file / anon but if it work for now, I'm fine with it.
Quoted 15 lines
include/linux/mm_inline.h static inline unsigned long lru_gen_folio_seq(const struct lruvec *lruvec, · line 332
Quoted 9 lines
include/linux/mm_inline.h +1
-1else if (reclaiming) gen =MAX_NR_GENS ; else if ((!folio_is_file_lru(folio) && !folio_test_swapcache(folio)) ||@@ -327,7 +329,7 @@ static inline unsigned long lru_gen_folio_seq(const struct lruvec *lruvec, (folio_test_dirty(folio) || folio_test_writeback(folio)))) gen =MIN_NR_GENS ; else - gen =MAX_NR_GENS - (folio_test_workingset (folio) ||folio_test_referenced (folio)); + gen =MAX_NR_GENS -folio_test_workingset (folio);This is a nice change, but meanwhile the LevelDB and cerain workload gain are gone too, we will again have a ~40% regression for similiar workloads, I just double checked it. But that's fine, though, it was never meant to be optimized that way, and the long-term fix can be done later.
Here I mean the "optimization" of 6cbdd9726fb5 is more like a side effect, and not reliable, that is simply not the goal of 6cbdd9726fb5. So I think it stands well as a fixes for 6cbdd9726fb5.
Barry Song
reviewerQuoted 11 lines · Kairui Song
Quoted 3 lines · Barry Song (Xiaomi)
On Fri, Oct 16, 2026 at 2:15 AM Kairui Song via B4 Relay <[email protected]> wrote:
[...]This is a nice change, but meanwhile the LevelDB and cerain workload gain are gone too, we will again have a ~40% regression for similiar workloads, I just double checked it. But that's fine, though, it was never meant to be optimized that way, and the long-term fix can be done later.
Quoted 7 lines
A quick test on another of my test machine using Tal's LevelDB test case:
CLRU: 3098 ops/s
MGLRU mainline: 3035 ops/s
MGLRU-FG: 3233 ops/s
MGLRU with this patch: 2194 ops/sec (should be same result with reverting6cbdd9726fb5)
Sashiko is raising serious concerns about this approach, so I'm really considering reverting the commit. The downside is that the revert would also regress some workloads, such as kernel builds and LevelDB Scan/Get.
Before we have to revert it, I'm wondering if the one-line change below could fix the SQLite scan and lookup regressions:
include/linux/mm_inline.h +0 -0
@@ -327,7 +327,7 @@ static inline unsigned long
lru_gen_folio_seq(const struct lruvec *lruvec,
(folio_test_dirty(folio) || folio_test_writeback(folio))))
gen = MIN_NR_GENS;
else- gen = MAX_NR_GENS - (folio_test_workingset(folio) ||folio_test_referenced(folio));
+ gen = MAX_NR_GENS - (folio_test_workingset(folio) ||folio_lru_refs(folio) > 1);
return max(READ_ONCE(lrugen->max_seq) - gen + 1,
READ_ONCE(lrugen->min_seq[type]));
}
If it works, It should be entirely thanks to the inspiration from your MGLRU-FG.
Quoted 9 lines · On Fri, Oct 16, 2026 at 02:15:49AM +0800, Kairui Song via B4 Relay wrote:
Hi all, this cover letter is going to be very long, as it includes a systematic test and analysis. And moving this series out of RFC phase as almost all readings are positive, tested on at least five different platforms (desktop, large server, Android,
x86_64and arm64 boxes) covering typical benchmarks, database, real applications, and has good test reports from other individual testers. It's also pretty clear about the next steps, and this blocks or breaks nothing AFAIK, which should be a pure gain, improving the performance or reducing IO of many workloads by ~10-40%.
A little update on the testing result: I've been running a week-long, four-arm test matrix on this, and the tests took 2 weeks to finish because it's a very large matrix based on this V4, on top of the partial reversion of 6cbdd9726fb5:
include/linux/mm_inline.h +0 -0
@@ -337,7 +337,7 @@ static inline unsigned long
lru_gen_folio_seq(const struct lruvec *lruvec,
(folio_test_dirty(folio) || folio_test_writeback(folio))))
gen = MIN_NR_GENS;
else
- gen = MAX_NR_GENS - (folio_test_workingset(folio) || folio_test_referenced(folio));
+ gen = MAX_NR_GENS - (folio_test_workingset(folio) || folio_lru_refs(folio) > 1);return max(READ_ONCE(lrugen->max_seq) - gen + 1, READ_ONCE(lrugen->min_seq[type]));
}
mm/workingset.c +0 -0
@@ -317,15 +317,14 @@ static void lru_gen_refault(struct folio *folio,
void *shadow)
refs = (token & (BIT(LRU_REFS_WIDTH) - 1)) + 1;
tier = lru_tier_from_refs(refs, workingset);+ if (lru_gen_in_fault()) {
+ mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + type, delta);
+ folio_set_active(folio);
+ }
+
atomic_long_add(delta, &lrugen->refaulted[hist][type][tier]);
if (workingset) {
- /*
- * see folio_add_lru(), where folio_set_active() is
- * called for workingset folios
- */- if (lru_gen_in_fault())
- mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + type, delta);
The four arms are:
- ORIG: mm-unstable 2 weeks ago
- FIXED: mm-unstable 2 weeks ago with the fix above
- FG: MGLRU-FG on top of FIXED
- RD: Refault distance on top of FG
- The refault distance algorithm is from:
- https://lore.kernel.org/linux-mm/[email protected]/
- The refault distance part is still being tweaked frequently, so RD results are just for reference.
I didn't include CLRU this time or it will be too long, all tests are done for 12 interleave boots, could be noise but given the size of the matrix I think it's quite reliable.
Test spec:
Zipf is widely used here, as it is commonly recognized as a good way to represent different kinds of workloads covering server, desktop interacrtive workloads, CDN, router, etc, depending on the theta factor and memory limit size:
None of the test involves MADV_FREE / MADV_COLD, MADV_RANDOM is also bypassed.
### fio
# Test is done with a NVME drive, memory limitation using memcg, THP off,
# swap off. 40 GiB working set (16 × 2560 MiB files) Common cmdline part:
numactl --membind=0 --cpunodebind=0 \
fio --name=fg --numjobs=16 --nrfiles=1 \
--filename_format=/var/lib/kmultibench/realdk.$jobnum.img \
--size=2560M --rw=randread --bs=4k --time_based \
--random_distribution=zipf:${θ} \
--ramp_time=120s --runtime=600s --group_reporting# fio fd reading: --buffered=1 --ioengine=sync
# fio mmap reading (bypassing MADV_RANDOM at the moment): --ioengine=mmap --fadvise_hint=0
### YCSB
# MongoDB 7 container, --network host, --memory 12G --memory-swap 12G (no swap),
# workload {a,b,c}, mem 12G, threads 16, iops limited to 5000.
# Also wiredTigerCacheSizeGB 0.25 (forces the hot set into the OS page cache)# LOAD (untimed): 18,000,000 records x 10 fields x 100 B ~= 18 GB ycsb load mongodb -s -p mongodb.url=mongodb://localhost:27017/ycsb \
-p recordcount=18000000 -p fieldcount=10 -p fieldlength=100 \
-threads 16 -P workloads/workloada
# RUN (timed): 100% zipfian read, 27,000,000 ops (1.5 x recordcount), 16 threads ycsb run mongodb -s -p mongodb.url=mongodb://localhost:27017/ycsb \
-p recordcount=18000000 -p fieldcount=10 -p fieldlength=100 -threads 16 \
-p requestdistribution=zipfian -p readproportion=1 -p updateproportion=0 \
-P workloads/workloada -p operationcount=27000000 -t
And the results are:
fio FD READ: Avg IOPS (higher is better)
memcg/θ ORIG | FIXED (vs ORIG) | FG (vs ORIG) | RD (vs ORIG) |
-----------------------------------------------------------------------------------------
16G/1.4 13,993,868| 14,153,014 ( +1.1%) | 14,619,834 ( +4.5%) | 14,492,871 ( +3.6%) | 16G/1.2 4,557,469| 4,564,882 ( +0.2%) | 5,188,226 ( +13.8%) | 5,066,064 ( +11.2%) | 16G/1.1 2,167,267| 2,158,549 ( -0.4%) | 2,453,911 ( +13.2%) | 2,417,420 ( +11.5%) | 16G/0.9 610,129| 617,994 ( +1.3%) | 718,869 ( +17.8%) | 708,871 ( +16.2%) | 16G/0.8 401,362| 406,178 ( +1.2%) | 465,164 ( +15.9%) | 454,454 ( +13.2%) |
fio FD READ: refault per read (lower is better)
memcg/θ ORIG | FIXED (vs ORIG) | FG (vs ORIG) | RD (vs ORIG) |
-----------------------------------------------------------------------------------------
16G/1.4 0.00182| 0.00169 ( -7.0%) | 0.00131 ( -28.1%) | 0.00135 ( -25.7%) | 16G/1.2 0.01557| 0.01551 ( -0.4%) | 0.01323 ( -15.0%) | 0.01342 ( -13.8%) | 16G/1.1 0.03785| 0.03782 ( -0.1%) | 0.03261 ( -13.8%) | 0.03313 ( -12.5%) | 16G/0.9 0.13992| 0.13978 ( -0.1%) | 0.12301 ( -12.1%) | 0.12495 ( -10.7%) | 16G/0.8 0.21259| 0.21256 ( -0.0%) | 0.18853 ( -11.3%) | 0.19146 ( -9.9%) |
fio MMAP: Avg IOPS (higher is better)
memcg/θ ORIG | FIXED (vs ORIG) | FG (vs ORIG) | RD (vs ORIG) |
-----------------------------------------------------------------------------------------
16G/1.4 20,670,288| 18,601,708 ( -10.0%) | 21,428,715 ( +3.7%) | 21,604,461 ( +4.5%) | 16G/1.2 4,739,384| 4,959,906 ( +4.7%) | 5,126,105 ( +8.2%) | 5,270,792 ( +11.2%) | 16G/1.1 2,145,716| 2,422,244 ( +12.9%) | 2,560,802 ( +19.3%)*| 3,554,448 ( +65.7%)*| 16G/0.9 3,887,814| 4,259,544 ( +9.6%) | 4,372,044 ( +12.5%) | 4,431,153 ( +14.0%) | 16G/0.8 3,566,541| 3,907,269 ( +9.6%) | 4,085,982 ( +14.6%) | 4,040,826 ( +13.3%) | 8G/1.4 13,471,704| 14,102,398 ( +4.7%) | 14,524,256 ( +7.8%) | 15,528,982 ( +15.3%) | 4G/1.4 9,222,754| 9,540,640 ( +3.4%) | 9,973,791 ( +8.1%) | 11,066,377 ( +20.0%) | 12G/1.2 3,565,213| 3,593,112 ( +0.8%) | 3,826,527 ( +7.3%) | 4,019,067 ( +12.7%) | 8G/1.2 2,504,381| 2,649,853 ( +5.8%) | 2,776,443 ( +10.9%) | 2,990,251 ( +19.4%) | 4G/1.2 1,676,208| 1,728,339 ( +3.1%) | 1,825,272 ( +8.9%) | 2,064,706 ( +23.2%) | 12G/1.1 1,592,245| 1,579,824 ( -0.8%) | 1,726,557 ( +8.4%) | 1,775,451 ( +11.5%) | 8G/1.1 1,117,784| 1,169,936 ( +4.7%) | 1,229,181 ( +10.0%) | 1,325,119 ( +18.5%) | 6G/1.1 939,984| 980,984 ( +4.4%) | 996,724 ( +6.0%) | 1,134,737 ( +20.7%) |
fio MMAP: refault per read (lower is better)
memcg/θ ORIG | FIXED (vs ORIG) | FG (vs ORIG) | RD (vs ORIG) |
-----------------------------------------------------------------------------------------
16G/1.4 0.00202| 0.00317 ( +57.0%) | 0.00187 ( -7.7%) | 0.00179 ( -11.3%) | 16G/1.2 0.01671| 0.01550 ( -7.2%) | 0.01529 ( -8.5%) | 0.01462 ( -12.5%) | 16G/1.1 0.03965| 0.03394 ( -14.4%) | 0.03318 ( -16.3%)*| 0.02312 ( -41.7%)*| 16G/0.9 0.01982| 0.01791 ( -9.6%) | 0.01771 ( -10.6%) | 0.01735 ( -12.4%) | 16G/0.8 0.02149| 0.01957 ( -8.9%) | 0.01889 ( -12.1%) | 0.01923 ( -10.5%) | 8G/1.4 0.00446| 0.00408 ( -8.5%) | 0.00394 ( -11.7%) | 0.00359 ( -19.4%) | 4G/1.4 0.00745| 0.00700 ( -6.1%) | 0.00668 ( -10.3%) | 0.00583 ( -21.7%) | 12G/1.2 0.02338| 0.02252 ( -3.7%) | 0.02131 ( -8.8%) | 0.02016 ( -13.8%) | 8G/1.2 0.03311| 0.03076 ( -7.1%) | 0.02984 ( -9.9%) | 0.02766 ( -16.5%) | 4G/1.2 0.05043| 0.04746 ( -5.9%) | 0.04574 ( -9.3%) | 0.04071 ( -19.3%) | 12G/1.1 0.05536| 0.05371 ( -3.0%) | 0.05099 ( -7.9%) | 0.04847 ( -12.4%) | 8G/1.1 0.07682| 0.07110 ( -7.4%) | 0.06966 ( -9.3%) | 0.06507 ( -15.3%) | 6G/1.1 0.09150| 0.08489 ( -7.2%) | 0.08313 ( -9.1%) | 0.07650 ( -16.4%) |
YCSB: throughput ops/sec (higher is better), n=3
workload ORIG | FIXED (vs ORIG) | FG (vs ORIG) | RD (vs ORIG) |
----------------------------------------------------------------------------------------
workloada 14,657| 14,284 ( -2.5%) | 16,788 ( +14.5%) | 17,836 ( +21.7%) | workloadb 14,309| 14,304 ( -0.0%) | 16,504 ( +15.3%) | 17,957 ( +25.5%) | workloadc 14,458| 13,777 ( -4.7%) | 16,806 ( +16.2%) | 17,868 ( +23.6%) |
YCSB READ p99 latency (lower is better):
workload ORIG | FIXED (vs ORIG) | FG (vs ORIG) | RD (vs ORIG) |
----------------------------------------------------------------------------------------
10-wla 61535.0| 65375.0 ( +6.2%) | 3474.3 ( -94.4%) | 2888.3 ( -95.3%) |
20-wlb 65641.7| 64265.7 ( -2.1%) | 3901.0 ( -94.1%) | 2757.0 ( -95.8%) |
30-wlc 63348.3| 71188.3 ( +12.4%) | 3251.0 ( -94.9%) | 2724.3 ( -95.7%) |So in conclusion:
1. The FIXED is helpful for the MMAP read by ~5-10%, harmless in most cases and with certain regressions in one or two cases, it may correspond to the LevelDB regression I described a while ago:
https://lore.kernel.org/linux-mm/CAMgjq7AtuK22FsuqvGRLVZ2eWrp-N4qQ_MHoXsXDkVBprekdDA@mail.gmail.com/
Which I think it's fine to have as the previous change that FIXED is trying to patch is causing other DB regression too.
2. MGLRU-FG is suitable across all cases covered above and outperformance everything we have in upstream so far by ~9-20% in these generic tests, and a huge improvement for lower latency (-90%).
3. Refault Distance will greatly help with cases where working set sits at the cgroup boundary on top of FG, offering up ~65% vs ORIG (~38% over FG) performance gain for certain cases. I think Refault distance will also cover the workingset shift case, with a slight regression for buffered read which could be the counter update overhead, I will explore that further after FG.
Posting these here so I can reference them later and try make the test result less bloated for later versions, and will be rebasing for V5 soon, maybe with a shorter test process.