Skip to contentSkip to conversation

mm/mglru: frequency guided promotion (MGLRU-FG) and flag cleanup

PATCH In review Kairui Song 6 participants 50 messages Dec 1 – Dec 3

Subsystems (19)
lore
Share & tools
lore

Kairui Song

author maintainer
#0 lore raw

v7 cover mm/mglru: frequency guided promotion (MGLRU-FG) and flag cleanup

This series implements MGLRU-FG following the idea proposed at LSF/MM/BPF this year [1], based on current mm-new. Depending on the workload, it improves the performance or reduces IO by roughly 10% to over 50%, fixes multiple long-standing issues with MGLRU metrics, and drops one page flag.

The series has been tested on multiple platforms (desktop, large server, Android phone, x86_64 and arm64 VM boxes) covering many typical benchmarks, databases and real applications, so far everything looks nice, with good test reports from other individual testers too.

Different workloads may get a flat, minor or dramatic improvement, the gain here is mostly from real improvement of LRU's ability to distinguish the hotter workingset.

It also redefines the Active workingset metric for MGLRU, which fixes under-accounted PSI and poor active workingset readings. Cloud platforms like Kubernetes derive pods' working set from it and use it to make eviction decisions, MGLRU gave an unstable one there, and users ended up disabling MGLRU to work around it [20]. That is also a major blocker for us to deploy MGLRU widely.

The new MGLRU-FG's design is kind of a mixture with LFU, it uses unified access frequency to distinguish hotter folios, but it still reclaims by generation. The generation and bounded refs together form a "logical refs count".

Accesses increase refs. When a folio's refs reach a threshold, the folio is promoted to the next newer gen, and promotion caps the refs at a lower threshold. A folio with lower physical refs in a newer gen is logically hotter than a folio in an older gen with higher physical refs. Hence gen aging lowers all logical refs without updating every folio, avoiding hot cache pollution at no added overhead, while greatly extending the ref counting and hotness distinguishing ability. It also balances page table access counting against file descriptor (FD) access with a defined rule.

The work here is mostly just a re-explanation of MGLRU's existing mechanisms, everything is already there, we just connect them together in a different way.

This version is rebased and retested on top of mm-new, which includes Barry's swappiness rework [16], and this series combines very well and became more important after that. High swappiness now drives aging and reclaim more aggressively, making the existing PID protection very inefficient. Meanwhile FG can promote reused file folios much more proactively, and the build kernel test shows a significant improvement for that case. I also observed FG performing better in generic cases after that series, as the more proactive aging populates more gens, which lets FG distribute folios among them more evenly [19].

Test results (CLRU means classical LRU):

Build kernel test:
==================
This test is reworked: with the recent swappiness changes, behavior differs dramatically between setups, so it is now split into two groups, mild swappiness under mild pressure, and extreme swappiness.

For the mild swappiness range (60/100/150), with ZRAM as swap (256G, lzo-rle) and a clean make -j48 defconfig build from an existing source tree on an NVMe drive in a 3G/2G memcg, the average of 2 rounds across the three swappiness levels:

Reading with 3G memcg (lower is better):
real sys pgpgin pgpgout pgmajfault refault_file refault_anon

CLRU     1m33s   10m08s     9.76M    38.05M      1.85M         466k        1.85M
Before   1m32s    9m27s    12.56M    40.49M      2.35M         345k        2.31M
After    1m32s    9m15s    10.44M    35.74M      1.80M         347k        1.76M
delta    -0.2%    -2.1%    -16.9%    -11.7%     -23.4%        +0.4%       -23.8%

Reading with 2G memcg (lower is better):

         real       sys    pgpgin   pgpgout pgmajfault refault_file refault_anon
CLRU     1m54s   25m47s    66.35M   158.02M     15.51M        1.57M       15.52M
Before   1m54s   25m15s    75.47M   183.48M     17.33M         973k       17.17M
After    1m52s   24m00s    69.67M   171.01M     15.51M        1.19M       15.36M

delta -2.0% -4.9% -7.7% -6.8% -10.5% +21.8% -10.5%

We can see the performance is better with lower sys time and total pgpgin with the mild setup. The slight drift of the file/anon counters is mostly swappiness balance policy differences, which looks OK to me as the total refault and IO dropped together with the build time.

Swappiness is still respected. The extreme points below show a major improvement with disk as swap:

Using the same setup, first with ZRAM as swap, then with an NVMe device as disk swap:
ZRAM as swap:
sw real pgpgin pg{steal/scan}_anon pg{steal/scan}_file {anon/file}_refault

CLRU     1  2m06s  68.70M       9.86M / 50.91M     15.14M / 25.67M  2.08M / 14.97M
       100  1m32s   8.88M       9.15M / 49.65M     562.0k / 667.9k  1.69M / 409.9k
       200  1m36s  22.35M      19.53M / 79.35M     151.1k / 227.7k  5.52M /  84.2k
Before   1  1m42s  36.95M       8.45M / 15.43M      7.02M / 15.49M  2.19M /  3.58M
       100  1m32s  11.80M       9.83M / 20.29M     780.5k / 830.1k  2.16M / 321.8k
       200  1m41s  46.04M      29.87M / 68.96M          0 /      0 11.68M /      0
After    1  1m46s  42.75M       8.84M / 15.80M      8.72M / 20.35M  1.96M /  4.54M
       100  1m32s  11.08M       9.69M / 19.64M     804.0k / 856.6k  1.95M / 364.1k
       200  1m41s  32.89M      27.00M / 57.04M       1148 /   1152  8.13M /    480

Disk as swap:
sw real pgpgin pg{steal/scan}_anon pg{steal/scan}_file {anon/file}_refault

CLRU     1  4m23s 153.56M      10.90M / 61.31M     36.00M / 55.81M   2.43M / 35.83M
       100  3m16s   9.95M       8.22M / 52.72M     588.5k / 652.4k   1.93M / 435.3k
       200  6m19s  25.36M      20.21M / 98.19M      94.6k /  94.7k   6.30M /   9365
Before   1  3m07s  27.18M       6.41M / 11.55M      4.83M /  8.80M   1.38M /  2.53M
       100  2m56s   9.52M       6.31M / 13.75M     609.1k / 628.3k   1.26M / 251.7k
       200 10m30s  71.66M      38.59M / 92.30M          0 /      0  13.87M /      0
After    1  3m18s  33.86M       7.60M / 14.89M      7.74M / 16.41M   1.37M /  4.14M
       100  2m46s   8.94M       5.69M / 13.86M     704.1k / 741.3k   1.09M / 268.8k
       200  6m03s  30.04M      19.72M / 49.85M        194 /    194   5.00M /    142

For sw=1, pgpgin looks higher, but that is because files are reclaimed even harder, as swappiness asks for, while the performance is still OK and better than CLRU.

For sw=100, the reading suggests the performance is better with a better reclaim balance: pgpgin and total refault are down with both swap devices, and building is ~10s faster on disk swap.

At sw=200 the disk swap build goes from 10m30s to 6m03s, almost halved. The existing protection almost stalls the build there, while FG promotes folios much more proactively. This is consistent with the pgrefill counter below (Before -> After):

pgrefill sw=1 sw=100 sw=200

DISK       3.78M -> 10.23M   16.02M -> 24.17M    8.17k -> 34.28M
ZRAM       6.28M -> 11.09M   22.21M -> 30.94M    5.20M -> 42.85M

In summary: MGLRU with FG respects swappiness well and improves the performance by a lot, with lower pgpgin and almost half the build time at the high swappiness values. The cases where MGLRU used to fall behind CLRU now lead as well.

FIO cached read with zipf
=========================
(This is a simplified version, fuller coverage can be seen in [17])

Using an NVMe device, in a 16G cgroup, total file size 40G, this measures the LRU's theoretical ability to distinguish the hotter portion, 2 interleaved runs per config (only n=2, but it reproduces the picture of the matrix in [17] just fine), THP off, swap off:

Using read()
------------
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=120s --runtime=600s --group_reporting

Avg IOPS (higher is better)
zipf:θ CLRU | MGLRU before (vs CLRU) | FG (vs CLRU) | Imprv.

  0.8       396,247|      403,014 ( +1.7%)  |    468,872 (+18.3%) |  +16.3%
  0.9       601,304|      616,291 ( +2.5%)  |    713,928 (+18.7%) |  +15.8%
  1.1     2,077,516|    2,158,626 ( +3.9%)  |  2,462,189 (+18.5%) |  +14.1%
  1.2     4,439,193|    4,546,680 ( +2.4%)  |  5,204,998 (+17.3%) |  +14.5%
  1.4    14,318,444|   14,122,531 ( -1.4%)  | 14,620,584 ( +2.1%) |   +3.5%

refault/read (lower is better, defined as workingset_refault_file / reads)
zipf:θ CLRU | MGLRU before (vs CLRU) | FG (vs CLRU) | Imprv.

  0.8     0.21707 |       0.21288 ( -1.9%) | 0.18887 (-13.0%) |  +11.3%
  0.9     0.14359 |       0.13994 ( -2.5%) | 0.12292 (-14.4%) |  +12.2%
  1.1     0.03919 |       0.03785 ( -3.4%) | 0.03267 (-16.6%) |  +13.7%
  1.2     0.01609 |       0.01551 ( -3.6%) | 0.01323 (-17.8%) |  +14.7%
  1.4     0.00167 |       0.00182 ( +9.0%) | 0.00133 (-20.4%) |  +26.9%

For typical read() following zipf distributions, FG improves every case, mean +12.9% IOPS and -15.7% refault rate. FG protects the hotter part of the workingset better when under pressure, the only case where MGLRU is behind CLRU is also ahead now.

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=120s --runtime=600s --group_reporting

Avg IOPS (higher is better)
zipf:θ CLRU | MGLRU before (vs CLRU) | FG (vs CLRU) | Imprv.

  0.8     1,062,221|    3,591,468 (+238.1%) | 4,066,055 (+282.8%) | +13.2%
  0.9       658,512|    3,785,168 (+474.8%) | 4,475,720 (+579.7%) | +18.2%
  1.1     2,183,796|     2,166,070 ( -0.8%) |  2,451,181 (+12.2%) | +13.2%
  1.2     4,785,117|     4,710,772 ( -1.6%) |  5,199,245 ( +8.7%) | +10.4%
  1.4    20,654,851|    20,685,287 ( +0.1%) | 21,598,890 ( +4.6%) |  +4.4%

refault/read (lower is better, defined as workingset_refault_file / reads)
zipf:θ CLRU | MGLRU before (vs CLRU) | FG (vs CLRU) | Imprv.

  0.8     0.12460|      0.02124 (-83.0%)  | 0.01898 (-84.8%) |  +10.6%
  0.9     0.13972|      0.02010 (-85.6%)  | 0.01717 (-87.7%) |  +14.6%
  1.1     0.04036|      0.03955 ( -2.0%)  | 0.03446 (-14.6%) |  +12.9%
  1.2     0.01689|      0.01673 ( -0.9%)  | 0.01507 (-10.8%) |   +9.9%
  1.4     0.00209|      0.00206 ( -1.4%)  | 0.00184 (-12.0%) |  +10.7%

For typical mmap read of file following zipf distributions, FG also improves every case here: mean +11.9% IOPS and -11.7% refault rate. MGLRU remains far ahead of CLRU at theta < 1.

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,949,856| 1,667,041 (-14.5%) | 1,708,521 (-12.4%) | +2.5%

That's because MGLRU deliberately disables hotness tracking for MADV_RANDOM areas while CLRU still has refault distance. I don't think this is a blocker: that is exactly what userspace asked for, and we do plan to unify refault distance and improve shadow usage [8], [9], which should also help with workingset shift [18]. FG is the baseline and we will revisit that later.

Worth mentioning: a previous version test showed FG slightly lower on IOPS for one config while its refault rate was actually lower. It is mostly due to locking contention:

The earlier perf lock contention analysis shows the lazy promotion could make MGLRU's isolation a bit slower than before:

command:
<same test command above, with 4G memcg, zipf:1.2 and a 300s runtime, and below tracing> perf lock contention -ab -- sleep 355

Result (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         |

MGLRU now promotes more folios due to FG lazy promotion while holding the LRU lock, which is a good thing for most cases since it protects the workingset better. The lazy promotion cost can be reduced later by batching and prefetching during scanning as demonstrated before [12].

MongoDB YCSB [2]
================
With recordcount:18000000 operationcount:27000000, threads:16, 100% zipfian reads, workloads a/b/c, in a 12G memcg, n=2, with a 5000 IOPS cap on the block device, and a 0.25G WiredTiger cache to simulate a slower device and stress the LRU more:

Throughput (ops/sec, higher is better):

CLRU:         13,474.85 ops/s
MGLRU Before: 14,101.40 ops/s (+4.6% vs CLRU)
MGLRU After:  16,577.92 ops/s (+23.0% vs CLRU) +17.6% vs Before

READ p99 latency (us, lower is better):

CLRU:         69,028.33 us
MGLRU Before: 65,065.67 us (-5.7% vs CLRU)
MGLRU After:  6,977.67 us (-89.9% vs CLRU) -89.3% vs Before

READ p50 latency is essentially unchanged. The setup differs from previous posted ones as I'm trying to enlarge the test matrix, but still we are seeing very nice results.

Chromium & Node.js test [3]
===========================
Using ZRAM as swap, 64 workers (32 memcgs x 2 NUMA nodes), 256G zram, 1h testing:

Total requests:

MGLRU Before:            146,229
MGLRU After:             242,644 (+65.9%)

Worth noting there seems to be some reclaim balance jitter for this test, while the balancing in upstream is not doing very well at this point too, so this is worth more investigation later.

LevelDB Scan/Get
================
I also retested the LevelDB benchmark from the cache_ext paper [4]. 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 [13]. 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 fixing more 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 [5]:

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 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.

An alternative fix was discussed previously too and I tested it as well [17]. FG is still better, and its gain holds on top of it.

Android (For reference)
=======================
Testing on Android is quite difficult: lack of mainline support, and it is very noisy, but I did an informal backport on top of the 6.1 GKI tree, testing with a Pixel 9 Pro (16 GB RAM, 8 GB ZRAM, Android 17), preserving the frozen kABI layouts so the implementation is limited [14].

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. (And BTW that alignment also improved the performance by a lot, which matches the report from previous MGLRU reclaim optimization series [11]).

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 behavior, 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%

Numbers are trimmed means over the 12 interleaved runs per kernel: the highest and lowest run are dropped and the middle ten averaged. It's 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).

Despite being noisy, every counter except pgpgout and workingset_refault_file is improved by ~10% on average, with a 95% CI that stays clear of zero. We have been seeing
positive readings since v2 of this series, and still holds the same pattern with a few days of testing. I think we can safely say that this series is beneficial for generic Android workloads.

I also ran the Android Jank test from Zicheng [6] for previous versions, and did a test on another Android phone with a 5.15 kernel on Xperia 1 V, [15], the results are all looking good or basically flat.

Redis / Valkey
==============
Valkey in a 2G ARM64 VM, 2.4G dataset, using 8G ZRAM as swap and THP never. Note, PT walk is missing there due to lack of hardware capability:

$ cat /sys/kernel/mm/lru_gen/enabled
0x0001

valkey-server --maxmemory 2560M
valkey-benchmark -r 3000000 -n 3000000 -d 1024 -c 12 -P 32 -t get

For every sample, 20 rounds each:

Before After

plain GET              679,151 rps   707,938 rps  +4.2%
plain GET + BGSAVE     481,886 rps   494,153 rps  +2.5%

Small wins: the dataset does not fit in the guest, so this case runs mostly under swap pressure. Nothing regresses, and GET throughput still improves by ~4%.

Metrics
=======
The new defined LRU refs based MGLRU metrics reading also provide a more stable and useful active / inactive / referenced metrics:

Pool over 3 test run with make -j48, defconfig, ZRAM as swap, 3G memory. reading during a build test:

      │ smaps Referenced/Rss % min/med/max │ span │ stdev
CLRU  │  99.4 / 100.0 / 100.0              │  0.6 │  0.0
MGLRU │  38.0 /  99.6 / 100.0              │ 62.0 │ 12.3 - erratic and unstable
FG    │  99.9 / 100.0 / 100.0              │  0.1 │  0.0 - matches CLRU
      │ active_anon % min/med/max │ span │ stdev
CLRU  │   0.0 /   1.1 /  24.9     │ 24.8 │  4.5
MGLRU │   3.7 /  96.4 / 100.0     │ 96.3 │ 23.7 * chaotic, almost random
FG    │   0.0 /   0.9 /  12.3     │ 12.2 │  1.9 - matches CLRU
      │ active_file % min/med/max │ span │ stdev
CLRU  │  34.1 / 43.8 / 52.2      │ 18.1 │  4.7
MGLRU │   0.0 /  0.1 /  0.1      │  0.1 │  0.0 * useless, always ~0
FG    │  24.3 / 33.5 / 42.2      │ 18.0 │  5.7 - matches CLRU

Note, the goal here is not to match CLRU, but CLRU was clearly doing much better on this, so using that as a reference shows the reworked readings are indeed normal and reliable, which should hopefully help solve the metrics problems, for example, the one in link [20].

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 [7].

Refault distance is not included yet, so MGLRU may respond more slowly to workingset shifts. That can be added later, as previously demonstrated [8], [9].

Extra note about future development: this series is actually highly compatible with ideas like workingset reporting [10]. 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. These older gens can be considered as expiring gen.

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 v7:
- Rebased onto mm-new.
- The changes are mostly about naming and folding and micro optimization, test shows no measureable performance difference from before.
- Rename folio_check_lru_refs to folio_test_lru_refs.
- lru_gen_del_folio(): check for a folio off the gen lists with a plain read, and clear the gen, set PG_active and read the refs in one try_cmpxchg.
https://lore.kernel.org/all/[email protected]/
- Add folio_mark_accessed_vma() for the zap and split paths.
- Fold PG_young into folio_test_lru_refs() and folio_clear_lru_refs().
- Add __update_lru_size_lockless() instead of relaxing __update_lru_size() to avoid conflict with other patches.
https://lore.kernel.org/[email protected]
- Reset the refs in lru_deactivate(), lru_deactivate_file() and lru_lazyfree() instead of clearing PG_referenced to avoid counter
leak on switching.
- Explain vma_has_recency() in the split patch and what folio_inc_lru_refs_fast() is for, and simplify its loop.
- Collect tags, and drop a few from the reworked parts.
- Link to v6: https://patch.msgid.link/[email protected]

Changes in v6:
- Fixes potential active / inactive counter drift when MGLRU enable / disable switching race with counter update.
- Minor optimization for clearing refs:
https://lore.kernel.org/all/CAMgjq7Dd=Y+GekSD9WO5oGdoa+S1eG3T-U=VsCexopvb723zFA@mail.gmail.com/
- Re-measure most tests, I got a +3.88% - +28.61% reading vs letter +3.5%
- +16.3% reading for FIO with a single round of testing, so kept
the old data as the code change is minimal and the readings basically matches. Similar result for build kernel and other tests.
- Avoid potential counter leak when reparenting local stats:
https://lore.kernel.org/linux-mm/CAN_Opa-+nb0vxQ+HsENCG2fEEMZoxG9Sy_DBC4CLkWjNLzDWKw@mail.gmail.com/
- Collect tags, and adjust according to patch update.
- Adjust a few patch order, rename one patch about PG_workingset helper.
- Link to v5: https://patch.msgid.link/[email protected]

Changes in v5:
- Rebased onto current mm-new.
- Code and design are basically the same, mostly rebase and adaption and comment updates.
- Drop "mm: mglru: reparent folios from all generations": the fix it carried is upstream now.
- Pick up two patches from Ridong Chen to avoid conflicts.
- Fix a build warning with CONFIG_LRU_GEN=n.
- Share the ancestor walk between lruvec_live_lock_irq() and the new folio_lruvec_live_get()
- Note in __lru_gen_reparent_memcg() why the read/set/add of the child's counter cannot lose a lockless update.
- Say in the gup fast helper changelog what the fast path gains from it.
- Re-measure almost all tests as the recent swappiness rework changes a lot of things, and it turns out most result are still same or even better.
- Comment and kdoc updated, documentations needs more systematic update later.
- Link to v4: https://patch.msgid.link/[email protected]

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/memcontrol: avoid potential counter leak when reparenting local stats 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: factor out folio_mark_accessed_vma()
mm/huge_memory: mark folio as accessed more accurately on split mm/mglru: make PG_workingset helpers work based on folio LRU refs mm/mglru: folio LRU refs based active/inactive number accounting mm/mglru: make folio_inc_lru_refs lruvec lockless

Ridong Chen (2):
mm/mglru: rename the generation offset in lru_gen_folio_seq() mm/mglru: skip the flags cmpxchg when nothing changes

 Documentation/admin-guide/mm/multigen_lru.rst |   4 +-
 fs/btrfs/compression.c                        |   1 +
 fs/erofs/zdata.c                              |   3 +-
 fs/proc/task_mmu.c                            |   8 +-
 include/linux/memcontrol.h                    |  71 +++-
 include/linux/mm_inline.h                     | 423 ++++++++++++++------
 include/linux/mmzone.h                        | 150 ++++---
 include/linux/page-flags.h                    |   2 -
 kernel/bounds.c                               |   2 +-
 mm/damon/paddr.c                              |   4 +-
 mm/filemap.c                                  |   1 +
 mm/folio.c                                    |  93 +----
 mm/gup.c                                      |   6 +-
 mm/huge_memory.c                              |  13 +-
 mm/khugepaged.c                               |   2 +-
 mm/madvise.c                                  |  50 ++-
 mm/memcontrol.c                               |  15 +-
 mm/memory.c                                   |   4 +-
 mm/migrate.c                                  |   2 -
 mm/page_io.c                                  |   1 +
 mm/vmscan.c                                   | 553 ++++++++++++++++++--------
 mm/vmscan.h                                   |   2 +-
 mm/workingset.c                               |  47 ++-
 23 files changed, 948 insertions(+), 509 deletions(-)

---
base-commit: 872ceec1e3caf227655a58f7407a9c8493dcf56f
change-id: 20260722-mglru-fg-3a2c8574725b

Best regards,

Signature · 1 line
Kairui Song <[email protected]>
author maintainer
#1 lore raw

PATCH v7 1/19 mm/mglru: rename the generation offset in lru_gen_folio_seq()

From: Ridong Chen <[email protected]>

lru_gen_folio_seq() computes how many generations below max_seq a folio should be added to, but stores it in a variable named "gen". Elsewhere in MGLRU "gen" means an index into lrugen->folios[], i.e. seq % MAX_NR_GENS, so reusing the name for a relative offset is confusing.

Rename it to "age", which matches what the value means: the newest generation is age 1, and a larger age is an older generation.

No functional change.

---
 include/linux/mm_inline.h | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)
include/linux/mm_inline.h +5 -5
index 27c7bba542bc..c6aa1d4b69fa 100644
@@ -305,7 +305,7 @@ static inline void lru_gen_update_size(struct lruvec *lruvec, struct folio *foli
 static inline unsigned long lru_gen_folio_seq(const struct lruvec *lruvec,
 					      const struct folio *folio)
 {
-	int gen;
+	int age;
 	int type = folio_is_file_lru(folio);
 	const struct lru_gen_folio *lrugen = &lruvec->lrugen;
 
@@ -322,15 +322,15 @@ 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);
+		age = MIN_NR_GENS - folio_test_workingset(folio);
 	else if ((!folio_is_file_lru(folio) && !folio_test_swapcache(folio)) ||
 		 (folio_test_reclaim(folio) &&
 		  (folio_test_dirty(folio) || folio_test_writeback(folio))))
-		gen = MIN_NR_GENS;
+		age = MIN_NR_GENS;
 	else
-		gen = MAX_NR_GENS - (folio_test_workingset(folio) || folio_test_referenced(folio));
+		age = MAX_NR_GENS - (folio_test_workingset(folio) || folio_test_referenced(folio));
 
-	return max(READ_ONCE(lrugen->max_seq) - gen + 1, READ_ONCE(lrugen->min_seq[type]));
+	return max(READ_ONCE(lrugen->max_seq) - age + 1, READ_ONCE(lrugen->min_seq[type]));
 }
 
 /*
Signature · 1 line
2.56.1
maintainer tree notice
#2 lore raw

+ mm-mglru-rename-the-generation-offset-in-lru_gen_folio_seq.patch added to mm-new branch

The patch titled Subject: mm/mglru: rename the generation offset in lru_gen_folio_seq() has been added to the -mm mm-new branch. Its filename is…

The patch titled
Subject: mm/mglru: rename the generation offset in lru_gen_folio_seq()
has been added to the -mm mm-new branch. Its filename is
mm-mglru-rename-the-generation-offset-in-lru_gen_folio_seq.patch

This patch will shortly appear at
https://git.kernel.org/pub/scm/linux/kernel/git/akpm/25-new.git/tree/patches/mm-mglru-rename-the-generation-offset-in-lru_gen_folio_seq.patch

This patch will later appear in the mm-new branch at
git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm

Note, mm-new is a provisional staging ground for work-in-progress patches, and acceptance into mm-new is a notification for others take notice and to finish up reviews. Please do not hesitate to respond to review feedback and post updated versions to replace or incrementally fixup patches in mm-new.

The mm-new branch of mm.git is not included in linux-next

If a few days of testing in mm-new is successful, the patch will me moved into mm.git's mm-unstable branch, which is included in linux-next

Before you just go and hit "reply", please:
a) Consider who else should be cc'ed
b) Prefer to cc a suitable mailing list as well
c) Ideally: find the original patch on the mailing list and do a reply-to-all to that, adding suitable additional cc's

*** Remember to use Documentation/process/submit-checklist.rst when testing your code ***

The -mm tree is included into linux-next via various branches at git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm
and is updated there most days

------------------------------------------------------
From: Ridong Chen <[email protected]>
Subject: mm/mglru: rename the generation offset in lru_gen_folio_seq()
Date: Wed, 02 Dec 2026 04:18:41 +0800

Patch series "mm/mglru: frequency guided promotion (MGLRU-FG) and flag cleanup", v7.

This series implements MGLRU-FG following the idea proposed at LSF/MM/BPF this year [1], based on current mm-new. Depending on the workload, it improves the performance or reduces IO by roughly 10% to over 50%, fixes multiple long-standing issues with MGLRU metrics, and drops one page flag.

The series has been tested on multiple platforms (desktop, large server, Android phone, x86_64 and arm64 VM boxes) covering many typical benchmarks, databases and real applications, so far everything looks nice, with good test reports from other individual testers too.

Different workloads may get a flat, minor or dramatic improvement, the gain here is mostly from real improvement of LRU's ability to distinguish the hotter workingset.

It also redefines the Active workingset metric for MGLRU, which fixes under-accounted PSI and poor active workingset readings. Cloud platforms like Kubernetes derive pods' working set from it and use it to make eviction decisions, MGLRU gave an unstable one there, and users ended up disabling MGLRU to work around it [20]. That is also a major blocker for us to deploy MGLRU widely.

The new MGLRU-FG's design is kind of a mixture with LFU, it uses unified access frequency to distinguish hotter folios, but it still reclaims by generation. The generation and bounded refs together form a "logical refs count".

Accesses increase refs. When a folio's refs reach a threshold, the folio is promoted to the next newer gen, and promotion caps the refs at a lower threshold. A folio with lower physical refs in a newer gen is logically hotter than a folio in an older gen with higher physical refs. Hence gen aging lowers all logical refs without updating every folio, avoiding hot cache pollution at no added overhead, while greatly extending the ref counting and hotness distinguishing ability. It also balances page table access counting against file descriptor (FD) access with a defined rule.

The work here is mostly just a re-explanation of MGLRU's existing mechanisms, everything is already there, we just connect them together in a different way.

This version is rebased and retested on top of mm-new, which includes Barry's swappiness rework [16], and this series combines very well and became more important after that. High swappiness now drives aging and reclaim more aggressively, making the existing PID protection very inefficient. Meanwhile FG can promote reused file folios much more proactively, and the build kernel test shows a significant improvement for that case. I also observed FG performing better in generic cases after that series, as the more proactive aging populates more gens, which lets FG distribute folios among them more evenly [19].

Test results (CLRU means classical LRU):

Build kernel test:
==================
This test is reworked: with the recent swappiness changes, behavior differs dramatically between setups, so it is now split into two groups, mild swappiness under mild pressure, and extreme swappiness.

For the mild swappiness range (60/100/150), with ZRAM as swap (256G, lzo-rle) and a clean make -j48 defconfig build from an existing source tree on an NVMe drive in a 3G/2G memcg, the average of 2 rounds across the three swappiness levels:

Reading with 3G memcg (lower is better):
real sys pgpgin pgpgout pgmajfault refault_file refault_anon

CLRU     1m33s   10m08s     9.76M    38.05M      1.85M         466k        1.85M
Before   1m32s    9m27s    12.56M    40.49M      2.35M         345k        2.31M
After    1m32s    9m15s    10.44M    35.74M      1.80M         347k        1.76M
delta    -0.2%    -2.1%    -16.9%    -11.7%     -23.4%        +0.4%       -23.8%

Reading with 2G memcg (lower is better):

         real       sys    pgpgin   pgpgout pgmajfault refault_file refault_anon
CLRU     1m54s   25m47s    66.35M   158.02M     15.51M        1.57M       15.52M
Before   1m54s   25m15s    75.47M   183.48M     17.33M         973k       17.17M
After    1m52s   24m00s    69.67M   171.01M     15.51M        1.19M       15.36M

delta -2.0% -4.9% -7.7% -6.8% -10.5% +21.8% -10.5%

We can see the performance is better with lower sys time and total pgpgin with the mild setup. The slight drift of the file/anon counters is mostly swappiness balance policy differences, which looks OK to me as the total refault and IO dropped together with the build time.

Swappiness is still respected. The extreme points below show a major improvement with disk as swap:

Using the same setup, first with ZRAM as swap, then with an NVMe device as disk swap:
ZRAM as swap:
sw real pgpgin pg{steal/scan}_anon pg{steal/scan}_file {anon/file}_refault

CLRU     1  2m06s  68.70M       9.86M / 50.91M     15.14M / 25.67M  2.08M / 14.97M
       100  1m32s   8.88M       9.15M / 49.65M     562.0k / 667.9k  1.69M / 409.9k
       200  1m36s  22.35M      19.53M / 79.35M     151.1k / 227.7k  5.52M /  84.2k
Before   1  1m42s  36.95M       8.45M / 15.43M      7.02M / 15.49M  2.19M /  3.58M
       100  1m32s  11.80M       9.83M / 20.29M     780.5k / 830.1k  2.16M / 321.8k
       200  1m41s  46.04M      29.87M / 68.96M          0 /      0 11.68M /      0
After    1  1m46s  42.75M       8.84M / 15.80M      8.72M / 20.35M  1.96M /  4.54M
       100  1m32s  11.08M       9.69M / 19.64M     804.0k / 856.6k  1.95M / 364.1k
       200  1m41s  32.89M      27.00M / 57.04M       1148 /   1152  8.13M /    480

Disk as swap:
sw real pgpgin pg{steal/scan}_anon pg{steal/scan}_file {anon/file}_refault

CLRU     1  4m23s 153.56M      10.90M / 61.31M     36.00M / 55.81M   2.43M / 35.83M
       100  3m16s   9.95M       8.22M / 52.72M     588.5k / 652.4k   1.93M / 435.3k
       200  6m19s  25.36M      20.21M / 98.19M      94.6k /  94.7k   6.30M /   9365
Before   1  3m07s  27.18M       6.41M / 11.55M      4.83M /  8.80M   1.38M /  2.53M
       100  2m56s   9.52M       6.31M / 13.75M     609.1k / 628.3k   1.26M / 251.7k
       200 10m30s  71.66M      38.59M / 92.30M          0 /      0  13.87M /      0
After    1  3m18s  33.86M       7.60M / 14.89M      7.74M / 16.41M   1.37M /  4.14M
       100  2m46s   8.94M       5.69M / 13.86M     704.1k / 741.3k   1.09M / 268.8k
       200  6m03s  30.04M      19.72M / 49.85M        194 /    194   5.00M /    142

For sw=1, pgpgin looks higher, but that is because files are reclaimed even harder, as swappiness asks for, while the performance is still OK and better than CLRU.

For sw=100, the reading suggests the performance is better with a better reclaim balance: pgpgin and total refault are down with both swap devices, and building is ~10s faster on disk swap.

At sw=200 the disk swap build goes from 10m30s to 6m03s, almost halved. The existing protection almost stalls the build there, while FG promotes folios much more proactively. This is consistent with the pgrefill counter below (Before -> After):

pgrefill sw=1 sw=100 sw=200

DISK       3.78M -> 10.23M   16.02M -> 24.17M    8.17k -> 34.28M
ZRAM       6.28M -> 11.09M   22.21M -> 30.94M    5.20M -> 42.85M

In summary: MGLRU with FG respects swappiness well and improves the performance by a lot, with lower pgpgin and almost half the build time at the high swappiness values. The cases where MGLRU used to fall behind CLRU now lead as well.

FIO cached read with zipf
=========================
(This is a simplified version, fuller coverage can be seen in [17])

Using an NVMe device, in a 16G cgroup, total file size 40G, this measures the LRU's theoretical ability to distinguish the hotter portion, 2 interleaved runs per config (only n=2, but it reproduces the picture of the matrix in [17] just fine), THP off, swap off:

Using read()
------------
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=120s --runtime=600s --group_reporting

Avg IOPS (higher is better)
zipf:θ CLRU | MGLRU before (vs CLRU) | FG (vs CLRU) | Imprv.

  0.8       396,247|      403,014 ( +1.7%)  |    468,872 (+18.3%) |  +16.3%
  0.9       601,304|      616,291 ( +2.5%)  |    713,928 (+18.7%) |  +15.8%
  1.1     2,077,516|    2,158,626 ( +3.9%)  |  2,462,189 (+18.5%) |  +14.1%
  1.2     4,439,193|    4,546,680 ( +2.4%)  |  5,204,998 (+17.3%) |  +14.5%
  1.4    14,318,444|   14,122,531 ( -1.4%)  | 14,620,584 ( +2.1%) |   +3.5%

refault/read (lower is better, defined as workingset_refault_file / reads)
zipf:θ CLRU | MGLRU before (vs CLRU) | FG (vs CLRU) | Imprv.

  0.8     0.21707 |       0.21288 ( -1.9%) | 0.18887 (-13.0%) |  +11.3%
  0.9     0.14359 |       0.13994 ( -2.5%) | 0.12292 (-14.4%) |  +12.2%
  1.1     0.03919 |       0.03785 ( -3.4%) | 0.03267 (-16.6%) |  +13.7%
  1.2     0.01609 |       0.01551 ( -3.6%) | 0.01323 (-17.8%) |  +14.7%
  1.4     0.00167 |       0.00182 ( +9.0%) | 0.00133 (-20.4%) |  +26.9%

For typical read() following zipf distributions, FG improves every case, mean +12.9% IOPS and -15.7% refault rate. FG protects the hotter part of the workingset better when under pressure, the only case where MGLRU is behind CLRU is also ahead now.

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=120s --runtime=600s --group_reporting

Avg IOPS (higher is better)
zipf:θ CLRU | MGLRU before (vs CLRU) | FG (vs CLRU) | Imprv.

  0.8     1,062,221|    3,591,468 (+238.1%) | 4,066,055 (+282.8%) | +13.2%
  0.9       658,512|    3,785,168 (+474.8%) | 4,475,720 (+579.7%) | +18.2%
  1.1     2,183,796|     2,166,070 ( -0.8%) |  2,451,181 (+12.2%) | +13.2%
  1.2     4,785,117|     4,710,772 ( -1.6%) |  5,199,245 ( +8.7%) | +10.4%
  1.4    20,654,851|    20,685,287 ( +0.1%) | 21,598,890 ( +4.6%) |  +4.4%

refault/read (lower is better, defined as workingset_refault_file / reads)
zipf:θ CLRU | MGLRU before (vs CLRU) | FG (vs CLRU) | Imprv.

  0.8     0.12460|      0.02124 (-83.0%)  | 0.01898 (-84.8%) |  +10.6%
  0.9     0.13972|      0.02010 (-85.6%)  | 0.01717 (-87.7%) |  +14.6%
  1.1     0.04036|      0.03955 ( -2.0%)  | 0.03446 (-14.6%) |  +12.9%
  1.2     0.01689|      0.01673 ( -0.9%)  | 0.01507 (-10.8%) |   +9.9%
  1.4     0.00209|      0.00206 ( -1.4%)  | 0.00184 (-12.0%) |  +10.7%

For typical mmap read of file following zipf distributions, FG also improves every case here: mean +11.9% IOPS and -11.7% refault rate. MGLRU remains far ahead of CLRU at theta < 1.

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,949,856| 1,667,041 (-14.5%) | 1,708,521 (-12.4%) | +2.5%

That's because MGLRU deliberately disables hotness tracking for MADV_RANDOM areas while CLRU still has refault distance. I don't think this is a blocker: that is exactly what userspace asked for, and we do plan to unify refault distance and improve shadow usage [8], [9], which should also help with workingset shift [18]. FG is the baseline and we will revisit that later.

Worth mentioning: a previous version test showed FG slightly lower on IOPS for one config while its refault rate was actually lower. It is mostly due to locking contention:

The earlier perf lock contention analysis shows the lazy promotion could make MGLRU's isolation a bit slower than before:

command:
<same test command above, with 4G memcg, zipf:1.2 and a 300s runtime, and below tracing> perf lock contention -ab -- sleep 355

Result (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         |

MGLRU now promotes more folios due to FG lazy promotion while holding the LRU lock, which is a good thing for most cases since it protects the workingset better. The lazy promotion cost can be reduced later by batching and prefetching during scanning as demonstrated before [12].

MongoDB YCSB [2]
================
With recordcount:18000000 operationcount:27000000, threads:16, 100% zipfian reads, workloads a/b/c, in a 12G memcg, n=2, with a 5000 IOPS cap on the block device, and a 0.25G WiredTiger cache to simulate a slower device and stress the LRU more:

Throughput (ops/sec, higher is better):

CLRU:         13,474.85 ops/s
MGLRU Before: 14,101.40 ops/s (+4.6% vs CLRU)
MGLRU After:  16,577.92 ops/s (+23.0% vs CLRU) +17.6% vs Before

READ p99 latency (us, lower is better):

CLRU:         69,028.33 us
MGLRU Before: 65,065.67 us (-5.7% vs CLRU)
MGLRU After:  6,977.67 us (-89.9% vs CLRU) -89.3% vs Before

READ p50 latency is essentially unchanged. The setup differs from previous posted ones as I'm trying to enlarge the test matrix, but still we are seeing very nice results.

Chromium & Node.js test [3]
===========================
Using ZRAM as swap, 64 workers (32 memcgs x 2 NUMA nodes), 256G zram, 1h testing:

Total requests:

MGLRU Before:            146,229
MGLRU After:             242,644 (+65.9%)

Worth noting there seems to be some reclaim balance jitter for this test, while the balancing in upstream is not doing very well at this point too, so this is worth more investigation later.

LevelDB Scan/Get
================
I also retested the LevelDB benchmark from the cache_ext paper [4]. 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 [13]. 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 fixing more 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 [5]:

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 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.

An alternative fix was discussed previously too and I tested it as well [17]. FG is still better, and its gain holds on top of it.

Android (For reference)
=======================
Testing on Android is quite difficult: lack of mainline support, and it is very noisy, but I did an informal backport on top of the 6.1 GKI tree, testing with a Pixel 9 Pro (16 GB RAM, 8 GB ZRAM, Android 17), preserving the frozen kABI layouts so the implementation is limited [14].

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. (And BTW that alignment also improved the performance by a lot, which matches the report from previous MGLRU reclaim optimization series [11]).

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 behavior, 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%

Numbers are trimmed means over the 12 interleaved runs per kernel: the highest and lowest run are dropped and the middle ten averaged. It's 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).

Despite being noisy, every counter except pgpgout and workingset_refault_file is improved by ~10% on average, with a 95% CI that stays clear of zero. We have been seeing
positive readings since v2 of this series, and still holds the same pattern with a few days of testing. I think we can safely say that this series is beneficial for generic Android workloads.

I also ran the Android Jank test from Zicheng [6] for previous versions, and did a test on another Android phone with a 5.15 kernel on Xperia 1 V, [15], the results are all looking good or basically flat.

Redis / Valkey
==============
Valkey in a 2G ARM64 VM, 2.4G dataset, using 8G ZRAM as swap and THP never. Note, PT walk is missing there due to lack of hardware capability:

$ cat /sys/kernel/mm/lru_gen/enabled
0x0001

valkey-server --maxmemory 2560M
valkey-benchmark -r 3000000 -n 3000000 -d 1024 -c 12 -P 32 -t get

For every sample, 20 rounds each:

Before After

plain GET              679,151 rps   707,938 rps  +4.2%
plain GET + BGSAVE     481,886 rps   494,153 rps  +2.5%

Small wins: the dataset does not fit in the guest, so this case runs mostly under swap pressure. Nothing regresses, and GET throughput still improves by ~4%.

Metrics
=======
The new defined LRU refs based MGLRU metrics reading also provide a more stable and useful active / inactive / referenced metrics:

Pool over 3 test run with make -j48, defconfig, ZRAM as swap, 3G memory. reading during a build test:

      │ smaps Referenced/Rss % min/med/max │ span │ stdev
CLRU  │  99.4 / 100.0 / 100.0              │  0.6 │  0.0
MGLRU │  38.0 /  99.6 / 100.0              │ 62.0 │ 12.3 - erratic and unstable
FG    │  99.9 / 100.0 / 100.0              │  0.1 │  0.0 - matches CLRU
      │ active_anon % min/med/max │ span │ stdev
CLRU  │   0.0 /   1.1 /  24.9     │ 24.8 │  4.5
MGLRU │   3.7 /  96.4 / 100.0     │ 96.3 │ 23.7 * chaotic, almost random
FG    │   0.0 /   0.9 /  12.3     │ 12.2 │  1.9 - matches CLRU
      │ active_file % min/med/max │ span │ stdev
CLRU  │  34.1 / 43.8 / 52.2      │ 18.1 │  4.7
MGLRU │   0.0 /  0.1 /  0.1      │  0.1 │  0.0 * useless, always ~0
FG    │  24.3 / 33.5 / 42.2      │ 18.0 │  5.7 - matches CLRU

Note, the goal here is not to match CLRU, but CLRU was clearly doing much better on this, so using that as a reference shows the reworked readings are indeed normal and reliable, which should hopefully help solve the metrics problems, for example, the one in link [20].

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 [7].

Refault distance is not included yet, so MGLRU may respond more slowly to workingset shifts. That can be added later, as previously demonstrated [8], [9].

Extra note about future development: this series is actually highly compatible with ideas like workingset reporting [10]. 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. These older gens can be considered as expiring gen.

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.

This patch (of 19):

lru_gen_folio_seq() computes how many generations below max_seq a folio should be added to, but stores it in a variable named "gen". Elsewhere in MGLRU "gen" means an index into lrugen->folios[], i.e. seq % MAX_NR_GENS, so reusing the name for a relative offset is confusing.

Rename it to "age", which matches what the value means: the newest generation is age 1, and a larger age is an older generation.

No functional change.

[[email protected]: dropped the comment table part, the series rewrites it]
Cc Johannes Weiner <[email protected]>
Cc Muchun Song <[email protected]>
Cc Qi Zheng <[email protected]>
Cc Ying Huang <[email protected]>
Cc Christopher Li <[email protected]>
Cc Baoquan He <[email protected]>
Cc Nico Pache <[email protected]>
Cc Usama Arif <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Roman Gushchin <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Axel Rasmussen <[email protected]>
Cc Yuanchu Xie <[email protected]>
Cc Wei Xu <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Nhat Pham <[email protected]>
Cc Youngjun Park <[email protected]>
Cc Zi Yan <[email protected]>
Cc Gregory Price <[email protected]>
Cc Matthew Wilcox (Oracle) <[email protected]>
Cc Baolin Wang <[email protected]>
Cc Ryan Roberts <[email protected]>
Cc Dev Jain <[email protected]>
Cc Lance Yang <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc David Rientjes <[email protected]>
Cc Yu Zhao <[email protected]>
Cc Vernon Yang <[email protected]>
Cc wangzicheng <[email protected]>
Cc Tal Zussman <[email protected]>
Cc Kairui Song <[email protected]>
Cc Xiang Liu <[email protected]>
Cc Ehab Ababneh <[email protected]>
Cc zhaozhengzhuo <[email protected]>
Cc Joanne Koong <[email protected]>
Cc Hui Zhu <[email protected]>
Cc Maxim Muzafarov <[email protected]>
 include/linux/mm_inline.h |   10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)
include/linux/mm_inline.h renamed from include/linux/mm_inline.h~mm-mglru-rename-the-generation-offset-in-lru_gen_folio_seq +5 -5
@@ -305,7 +305,7 @@ static inline void lru_gen_update_size(s
 static inline unsigned long lru_gen_folio_seq(const struct lruvec *lruvec,
 					      const struct folio *folio)
 {
-	int gen;
+	int age;
 	int type = folio_is_file_lru(folio);
 	const struct lru_gen_folio *lrugen = &lruvec->lrugen;
 
@@ -322,15 +322,15 @@ static inline unsigned long lru_gen_foli
 	 * |<---------------------------- MAX_NR_GENS ---------------------------->|
 	 */
 	if (folio_test_active(folio))
-		gen = MIN_NR_GENS - folio_test_workingset(folio);
+		age = MIN_NR_GENS - folio_test_workingset(folio);
 	else if ((!folio_is_file_lru(folio) && !folio_test_swapcache(folio)) ||
 		 (folio_test_reclaim(folio) &&
 		  (folio_test_dirty(folio) || folio_test_writeback(folio))))
-		gen = MIN_NR_GENS;
+		age = MIN_NR_GENS;
 	else
-		gen = MAX_NR_GENS - (folio_test_workingset(folio) || folio_test_referenced(folio));
+		age = MAX_NR_GENS - (folio_test_workingset(folio) || folio_test_referenced(folio));
 
-	return max(READ_ONCE(lrugen->max_seq) - gen + 1, READ_ONCE(lrugen->min_seq[type]));
+	return max(READ_ONCE(lrugen->max_seq) - age + 1, READ_ONCE(lrugen->min_seq[type]));
 }
 
 /*

_

Patches currently in -mm which might be from [email protected] are

mm-memcontrol-drop-unused-vmscan-tracepoint-include.patch mm-vmscan-move-vmscan-tracepoints-to-a-local-header.patch mm-vmscan-move-struct-scan_control-to-a-dedicated-header.patch mm-vmscan-pass-scan_control-to-the-vmscan-tracepoints.patch mm-mglru-add-tracepoint-for-scan_folios.patch mm-mglru-add-lruvec_gen_size-helper.patch mm-mglru-add-tracepoint-for-aging.patch mm-mglru-pass-a-seq-range-to-lru_gen_add_folio.patch mm-mglru-deactivate-anon-folios-into-the-oldest-generation.patch mm-mglru-rename-the-generation-offset-in-lru_gen_folio_seq.patch mm-mglru-skip-the-flags-cmpxchg-when-nothing-changes.patch

author maintainer
#3 lore raw

PATCH v7 2/19 mm/memcontrol: allow update of LRU statistic without holding LRU lock

In reply to Kairui Song

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 the counter is eventually consistent and only serves as an estimate.

Use a standalone helper and leaves __update_lru_size() with its lockdep assertion to the lock holders, which may batch the updates [1].

---
 include/linux/mm_inline.h | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)
include/linux/mm_inline.h +17 -0
index c6aa1d4b69fa..b68b971d5a25 100644
@@ -55,6 +55,23 @@ static __always_inline void __update_lru_size(struct lruvec *lruvec,
 				NR_ZONE_LRU_BASE + lru, nr_pages);
 }
 
+/*
+ * __update_lru_size() for callers that don't hold lru_lock, so can't rely
+ * on it disabling IRQs.
+ */
+static __always_inline void __update_lru_size_lockless(struct lruvec *lruvec,
+				enum lru_list lru, enum zone_type zid,
+				long nr_pages)
+{
+	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
+
+	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],
+			    NR_ZONE_LRU_BASE + lru, nr_pages);
+}
+
 static __always_inline void update_lru_size(struct lruvec *lruvec,
 				enum lru_list lru, enum zone_type zid,
 				long nr_pages)
Signature · 1 line
2.56.1
maintainer tree notice
#4 lore raw

+ mm-memcontrol-allow-update-of-lru-statistic-without-holding-lru-lock.patch added to mm-new branch

The patch titled Subject: mm/memcontrol: allow update of LRU statistic without holding LRU lock has been added to the -mm mm-new branch. Its filename is…

The patch titled
Subject: mm/memcontrol: allow update of LRU statistic without holding LRU lock
has been added to the -mm mm-new branch. Its filename is
mm-memcontrol-allow-update-of-lru-statistic-without-holding-lru-lock.patch

This patch will shortly appear at
https://git.kernel.org/pub/scm/linux/kernel/git/akpm/25-new.git/tree/patches/mm-memcontrol-allow-update-of-lru-statistic-without-holding-lru-lock.patch

This patch will later appear in the mm-new branch at
git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm

Note, mm-new is a provisional staging ground for work-in-progress patches, and acceptance into mm-new is a notification for others take notice and to finish up reviews. Please do not hesitate to respond to review feedback and post updated versions to replace or incrementally fixup patches in mm-new.

The mm-new branch of mm.git is not included in linux-next

If a few days of testing in mm-new is successful, the patch will me moved into mm.git's mm-unstable branch, which is included in linux-next

Before you just go and hit "reply", please:
a) Consider who else should be cc'ed
b) Prefer to cc a suitable mailing list as well
c) Ideally: find the original patch on the mailing list and do a reply-to-all to that, adding suitable additional cc's

*** Remember to use Documentation/process/submit-checklist.rst when testing your code ***

The -mm tree is included into linux-next via various branches at git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm
and is updated there most days

------------------------------------------------------
From: Kairui Song <[email protected]>
Subject: mm/memcontrol: allow update of LRU statistic without holding LRU lock
Date: Wed, 02 Dec 2026 04:18:42 +0800

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 the counter is eventually consistent and only serves as an estimate.

Use a standalone helper and leaves __update_lru_size() with its lockdep assertion to the lock holders, which may batch the updates [1].

Cc Johannes Weiner <[email protected]>
Cc Muchun Song <[email protected]>
Cc Qi Zheng <[email protected]>
Cc Ying Huang <[email protected]>
Cc Christopher Li <[email protected]>
Cc Baoquan He <[email protected]>
Cc Nico Pache <[email protected]>
Cc Usama Arif <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Roman Gushchin <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Axel Rasmussen <[email protected]>
Cc Yuanchu Xie <[email protected]>
Cc Wei Xu <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Nhat Pham <[email protected]>
Cc Youngjun Park <[email protected]>
Cc Zi Yan <[email protected]>
Cc Gregory Price <[email protected]>
Cc Matthew Wilcox (Oracle) <[email protected]>
Cc Baolin Wang <[email protected]>
Cc Ryan Roberts <[email protected]>
Cc Dev Jain <[email protected]>
Cc Lance Yang <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc David Rientjes <[email protected]>
Cc Yu Zhao <[email protected]>
Cc Vernon Yang <[email protected]>
Cc wangzicheng <[email protected]>
Cc Tal Zussman <[email protected]>
Cc Kairui Song <[email protected]>
Cc Xiang Liu <[email protected]>
Cc Ehab Ababneh <[email protected]>
Cc zhaozhengzhuo <[email protected]>
Cc Joanne Koong <[email protected]>
Cc Hui Zhu <[email protected]>
Cc Maxim Muzafarov <[email protected]>
Cc Tianyi Chen <[email protected]>
 include/linux/mm_inline.h |   17 +++++++++++++++++
 1 file changed, 17 insertions(+)
include/linux/mm_inline.h renamed from include/linux/mm_inline.h~mm-memcontrol-allow-update-of-lru-statistic-without-holding-lru-lock +17 -0
@@ -55,6 +55,23 @@ static __always_inline void __update_lru
 				NR_ZONE_LRU_BASE + lru, nr_pages);
 }
 
+/*
+ * __update_lru_size() for callers that don't hold lru_lock, so can't rely
+ * on it disabling IRQs.
+ */
+static __always_inline void __update_lru_size_lockless(struct lruvec *lruvec,
+				enum lru_list lru, enum zone_type zid,
+				long nr_pages)
+{
+	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
+
+	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],
+			    NR_ZONE_LRU_BASE + lru, nr_pages);
+}
+
 static __always_inline void update_lru_size(struct lruvec *lruvec,
 				enum lru_list lru, enum zone_type zid,
 				long nr_pages)

_

Patches currently in -mm which might be from [email protected] are

mm-mglru-report-evictable-sizes-per-type.patch mm-mglru-extract-lruvec_populated_min_seq-helper.patch mm-mglru-reclaim-from-the-oldest-populated-gen.patch mm-mglru-lift-the-forced-protection-of-reclaimer.patch mm-mglru-skip-zones-above-reclaim_idx-instead-of-rotating-them.patch mm-mglru-return-for-unavailable-anon-reclaim-earlier.patch mm-mglru-balance-anon-and-file-scan-budget-by-refault-rate.patch mm-mglru-lift-youngest-gen-protection-for-higher-priority.patch mm-memcontrol-allow-update-of-lru-statistic-without-holding-lru-lock.patch mm-memcontrol-avoid-potential-counter-leak-when-reparenting-local-stats.patch mm-mglru-make-generation-page-counters-atomic.patch mm-memcg-add-folio-based-lruvec-live-helper.patch mm-mglru-frequency-guided-workingset-promotion-mglru-fg.patch mm-mglru-make-folio-lru-referenced-times-count-a-generic-api.patch mm-mglru-move-add-del-lru-size-accounting-out-of-lru_gen_update_size.patch mm-mglru-gup-mark-folios-referenced-via-a-fast-helper.patch mm-mglru-smaps-convert-to-lru-refs-based-operations-for-mglru.patch mm-damon-convert-to-lru-refs-based-operations-for-mglru.patch mm-khugepaged-convert-to-lru-refs-based-operations-for-mglru.patch mm-madvise-adapt-for-lru-refs-based-operations-for-mglru.patch mm-factor-out-folio_mark_accessed_vma.patch mm-huge_memory-mark-folio-as-accessed-more-accurately-on-split.patch mm-mglru-make-pg_workingset-helpers-work-based-on-folio-lru-refs.patch mm-mglru-folio-lru-refs-based-active-inactive-number-accounting.patch mm-mglru-make-folio_inc_lru_refs-lruvec-lockless.patch

author maintainer
#5 lore raw

PATCH v7 3/19 mm/memcontrol: avoid potential counter leak when reparenting local stats

In reply to Kairui Song

lruvec_page_state_local() clamps negative values to zero on SMP. That is right for readers reporting page counts, but can be wrong for reparenting once MGLRU updates the counters without the lruvec lock.

Reparenting runs after the forced stats flush, so a negative is a real balance that has to move to the parent, not be discarded. We will introduce lockless MGLRU promotion which may cause following problem:

1. A refs CAS on a folio on the child's lruvec moves it from inactive to active, and its active/inactive counter update follows as a separate step.

2. A concurrent isolation of the folio reads the folio as active, debits the child's NR_ACTIVE_* by delta before CSS_DYING is visible to it.

3. The child is killed, and the two __update_lru_size() calls from step 1 land on the parent: NR_INACTIVE_* -delta, then NR_ACTIVE_* +delta.

The child is left with NR_ACTIVE_* -delta while the parent holds the matching +delta, and reparenting the child's raw value is what cancels the parent's credit. However, if the child happens to hold few enough folios for that counter to be negative, lruvec_page_state_local() clamps the child's negative to zero, which drops the debit instead, so the parent keeps NR_ACTIVE_* overcounted by delta, and its active + inactive total overcounted as well, permanently: the child's local counters are gone once reparenting is done.

So use a raw signed helper and reparent with that. Ordinary readers still keep the clamp.

---
 mm/memcontrol.c | 15 +++++++++++----
 1 file changed, 11 insertions(+), 4 deletions(-)
mm/memcontrol.c +11 -4
index df02308bb80a..b27759d4999c 100644
@@ -562,11 +562,10 @@ unsigned long lruvec_page_state_monotonic(const struct lruvec *lruvec,
 	return (unsigned long)READ_ONCE(pn->lruvec_stats->state[i]);
 }
 
-unsigned long lruvec_page_state_local(const struct lruvec *lruvec,
+static long __lruvec_page_state_local(const struct lruvec *lruvec,
 				      enum node_stat_item idx)
 {
 	const struct mem_cgroup_per_node *pn;
-	long x;
 	int i;
 
 	if (mem_cgroup_disabled())
@@ -577,7 +576,14 @@ unsigned long lruvec_page_state_local(const struct lruvec *lruvec,
 		return 0;
 
 	pn = container_of_const(lruvec, struct mem_cgroup_per_node, lruvec);
-	x = READ_ONCE(pn->lruvec_stats->state_local[i]);
+	return READ_ONCE(pn->lruvec_stats->state_local[i]);
+}
+
+unsigned long lruvec_page_state_local(const struct lruvec *lruvec,
+				      enum node_stat_item idx)
+{
+	long x = __lruvec_page_state_local(lruvec, idx);
+
 #ifdef CONFIG_SMP
 	if (x < 0)
 		x = 0;
@@ -595,7 +601,8 @@ void reparent_memcg_lruvec_state_local(struct mem_cgroup *memcg,
 
 	for_each_node(nid) {
 		struct lruvec *lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
-		unsigned long value = lruvec_page_state_local(lruvec, idx);
+		/* Reparent the raw value: the clamp drops the child's debit. */
+		long value = __lruvec_page_state_local(lruvec, idx);
 
 		__mod_memcg_lruvec_state(memcg, nid, idx, -value);
 		__mod_memcg_lruvec_state(parent, nid, idx, value);
Signature · 1 line
2.56.1
maintainer tree notice
#6 lore raw

+ mm-memcontrol-avoid-potential-counter-leak-when-reparenting-local-stats.patch added to mm-new branch

The patch titled Subject: mm/memcontrol: avoid potential counter leak when reparenting local stats has been added to the -mm mm-new branch. Its filename is…

The patch titled
Subject: mm/memcontrol: avoid potential counter leak when reparenting local stats
has been added to the -mm mm-new branch. Its filename is
mm-memcontrol-avoid-potential-counter-leak-when-reparenting-local-stats.patch

This patch will shortly appear at
https://git.kernel.org/pub/scm/linux/kernel/git/akpm/25-new.git/tree/patches/mm-memcontrol-avoid-potential-counter-leak-when-reparenting-local-stats.patch

This patch will later appear in the mm-new branch at
git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm

Note, mm-new is a provisional staging ground for work-in-progress patches, and acceptance into mm-new is a notification for others take notice and to finish up reviews. Please do not hesitate to respond to review feedback and post updated versions to replace or incrementally fixup patches in mm-new.

The mm-new branch of mm.git is not included in linux-next

If a few days of testing in mm-new is successful, the patch will me moved into mm.git's mm-unstable branch, which is included in linux-next

Before you just go and hit "reply", please:
a) Consider who else should be cc'ed
b) Prefer to cc a suitable mailing list as well
c) Ideally: find the original patch on the mailing list and do a reply-to-all to that, adding suitable additional cc's

*** Remember to use Documentation/process/submit-checklist.rst when testing your code ***

The -mm tree is included into linux-next via various branches at git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm
and is updated there most days

------------------------------------------------------
From: Kairui Song <[email protected]>
Subject: mm/memcontrol: avoid potential counter leak when reparenting local stats
Date: Wed, 02 Dec 2026 04:18:43 +0800

lruvec_page_state_local() clamps negative values to zero on SMP. That is right for readers reporting page counts, but can be wrong for reparenting once MGLRU updates the counters without the lruvec lock.

Reparenting runs after the forced stats flush, so a negative is a real balance that has to move to the parent, not be discarded. We will introduce lockless MGLRU promotion which may cause following problem:

1. A refs CAS on a folio on the child's lruvec moves it from inactive to active, and its active/inactive counter update follows as a separate step.

2. A concurrent isolation of the folio reads the folio as active, debits the child's NR_ACTIVE_* by delta before CSS_DYING is visible to it.

3. The child is killed, and the two __update_lru_size() calls from step 1 land on the parent: NR_INACTIVE_* -delta, then NR_ACTIVE_* +delta.

The child is left with NR_ACTIVE_* -delta while the parent holds the matching +delta, and reparenting the child's raw value is what cancels the parent's credit. However, if the child happens to hold few enough folios for that counter to be negative, lruvec_page_state_local() clamps the child's negative to zero, which drops the debit instead, so the parent keeps NR_ACTIVE_* overcounted by delta, and its active + inactive total overcounted as well, permanently: the child's local counters are gone once reparenting is done.

So use a raw signed helper and reparent with that. Ordinary readers still keep the clamp.

Cc Johannes Weiner <[email protected]>
Cc Muchun Song <[email protected]>
Cc Qi Zheng <[email protected]>
Cc Ying Huang <[email protected]>
Cc Christopher Li <[email protected]>
Cc Baoquan He <[email protected]>
Cc Nico Pache <[email protected]>
Cc Usama Arif <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Roman Gushchin <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Barry Song <[email protected]>
Cc Axel Rasmussen <[email protected]>
Cc Yuanchu Xie <[email protected]>
Cc Wei Xu <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Nhat Pham <[email protected]>
Cc Youngjun Park <[email protected]>
Cc Zi Yan <[email protected]>
Cc Gregory Price <[email protected]>
Cc Matthew Wilcox (Oracle) <[email protected]>
Cc Baolin Wang <[email protected]>
Cc Ryan Roberts <[email protected]>
Cc Dev Jain <[email protected]>
Cc Lance Yang <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc David Rientjes <[email protected]>
Cc Yu Zhao <[email protected]>
Cc Vernon Yang <[email protected]>
Cc wangzicheng <[email protected]>
Cc Tal Zussman <[email protected]>
Cc Kairui Song <[email protected]>
Cc Xiang Liu <[email protected]>
Cc Ehab Ababneh <[email protected]>
Cc zhaozhengzhuo <[email protected]>
Cc wang lian <[email protected]>
Cc Joanne Koong <[email protected]>
Cc Hui Zhu <[email protected]>
Cc Maxim Muzafarov <[email protected]>
Cc Tianyi Chen <[email protected]>
 mm/memcontrol.c |   15 +++++++++++----
 1 file changed, 11 insertions(+), 4 deletions(-)
mm/memcontrol.c renamed from mm/memcontrol.c~mm-memcontrol-avoid-potential-counter-leak-when-reparenting-local-stats +11 -4
@@ -569,11 +569,10 @@ unsigned long lruvec_page_state_monotoni
 	return (unsigned long)READ_ONCE(pn->lruvec_stats->state[i]);
 }
 
-unsigned long lruvec_page_state_local(const struct lruvec *lruvec,
+static long __lruvec_page_state_local(const struct lruvec *lruvec,
 				      enum node_stat_item idx)
 {
 	const struct mem_cgroup_per_node *pn;
-	long x;
 	int i;
 
 	if (mem_cgroup_disabled())
@@ -584,7 +583,14 @@ unsigned long lruvec_page_state_local(co
 		return 0;
 
 	pn = container_of_const(lruvec, struct mem_cgroup_per_node, lruvec);
-	x = READ_ONCE(pn->lruvec_stats->state_local[i]);
+	return READ_ONCE(pn->lruvec_stats->state_local[i]);
+}
+
+unsigned long lruvec_page_state_local(const struct lruvec *lruvec,
+				      enum node_stat_item idx)
+{
+	long x = __lruvec_page_state_local(lruvec, idx);
+
 #ifdef CONFIG_SMP
 	if (x < 0)
 		x = 0;
@@ -602,7 +608,8 @@ void reparent_memcg_lruvec_state_local(s
 
 	for_each_node(nid) {
 		struct lruvec *lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
-		unsigned long value = lruvec_page_state_local(lruvec, idx);
+		/* Reparent the raw value: the clamp drops the child's debit. */
+		long value = __lruvec_page_state_local(lruvec, idx);
 
 		__mod_memcg_lruvec_state(memcg, nid, idx, -value);
 		__mod_memcg_lruvec_state(parent, nid, idx, value);

_

Patches currently in -mm which might be from [email protected] are

mm-mglru-report-evictable-sizes-per-type.patch mm-mglru-extract-lruvec_populated_min_seq-helper.patch mm-mglru-reclaim-from-the-oldest-populated-gen.patch mm-mglru-lift-the-forced-protection-of-reclaimer.patch mm-mglru-skip-zones-above-reclaim_idx-instead-of-rotating-them.patch mm-mglru-return-for-unavailable-anon-reclaim-earlier.patch mm-mglru-balance-anon-and-file-scan-budget-by-refault-rate.patch mm-mglru-lift-youngest-gen-protection-for-higher-priority.patch mm-memcontrol-allow-update-of-lru-statistic-without-holding-lru-lock.patch mm-memcontrol-avoid-potential-counter-leak-when-reparenting-local-stats.patch mm-mglru-make-generation-page-counters-atomic.patch mm-memcg-add-folio-based-lruvec-live-helper.patch mm-mglru-frequency-guided-workingset-promotion-mglru-fg.patch mm-mglru-make-folio-lru-referenced-times-count-a-generic-api.patch mm-mglru-move-add-del-lru-size-accounting-out-of-lru_gen_update_size.patch mm-mglru-gup-mark-folios-referenced-via-a-fast-helper.patch mm-mglru-smaps-convert-to-lru-refs-based-operations-for-mglru.patch mm-damon-convert-to-lru-refs-based-operations-for-mglru.patch mm-khugepaged-convert-to-lru-refs-based-operations-for-mglru.patch mm-madvise-adapt-for-lru-refs-based-operations-for-mglru.patch mm-factor-out-folio_mark_accessed_vma.patch mm-huge_memory-mark-folio-as-accessed-more-accurately-on-split.patch mm-mglru-make-pg_workingset-helpers-work-based-on-folio-lru-refs.patch mm-mglru-folio-lru-refs-based-active-inactive-number-accounting.patch mm-mglru-make-folio_inc_lru_refs-lruvec-lockless.patch

author maintainer
#7 lore raw

PATCH v7 4/19 mm/mglru: make generation page counters atomic

In reply to Kairui Song

No feature change, convert them to atomic so we can update them without holding the LRU lock. A temporary underflow is fine: readers clamp a negative value to zero, and the counters only need to be eventually consistent.

---
 include/linux/mm_inline.h |  6 ++----
 include/linux/mmzone.h    |  2 +-
 mm/vmscan.c               | 26 +++++++++++++-------------
 mm/vmscan.h               |  2 +-
 4 files changed, 17 insertions(+), 19 deletions(-)
include/linux/mm_inline.h +2 -4
index b68b971d5a25..48d617bb04e2 100644
@@ -287,11 +287,9 @@ static inline void lru_gen_update_size(struct lruvec *lruvec, struct folio *foli
 	VM_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
index 6a2ad0cff795..4e85bb520f76 100644
@@ -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 +13 -13
index 99cb209797b4..34014a58b044 100644
@@ -3413,8 +3413,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;
@@ -4034,11 +4033,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;
 	}
@@ -4156,8 +4152,8 @@ static bool inc_max_seq(struct lruvec *lruvec, unsigned long seq, int swappiness
 	for (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;
@@ -4693,8 +4689,13 @@ static void __lru_gen_reparent_memcg(struct lruvec *child_lruvec, struct lruvec
 	child_lrugen = &child_lruvec->lrugen;
 	parent_lrugen = &parent_lruvec->lrugen;
 
+	/*
+	 * The child is offline and the lockless updaters, which hold
+	 * rcu_read_lock() over the update, avoid racing with reparenting,
+	 * so the read/set/add operations below are safe.
+	 */
 	for (gen = 0; gen < MAX_NR_GENS; gen++) {
-		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;
 
@@ -4702,9 +4703,8 @@ static void __lru_gen_reparent_memcg(struct lruvec *child_lruvec, struct lruvec
 		list_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);
mm/vmscan.h +1 -1
index c2cea36289f3..6551f0a6691a 100644
@@ -126,7 +126,7 @@ static inline unsigned long lruvec_gen_size(struct lru_gen_folio *lrugen,
 	unsigned long size = 0;
 
 	for (int zone = 0; zone < max_zone; zone++)
-		size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
+		size += max(atomic_long_read(&lrugen->nr_pages[gen][type][zone]), 0L);
 
 	return size;
 }
Signature · 1 line
2.56.1
maintainer tree notice
#8 lore raw

+ mm-mglru-make-generation-page-counters-atomic.patch added to mm-new branch

The patch titled Subject: mm/mglru: make generation page counters atomic has been added to the -mm mm-new branch. Its filename is mm-mglru-make-generation-page-counters-atomic.patch

The patch titled
Subject: mm/mglru: make generation page counters atomic
has been added to the -mm mm-new branch. Its filename is
mm-mglru-make-generation-page-counters-atomic.patch

This patch will shortly appear at
https://git.kernel.org/pub/scm/linux/kernel/git/akpm/25-new.git/tree/patches/mm-mglru-make-generation-page-counters-atomic.patch

This patch will later appear in the mm-new branch at
git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm

Note, mm-new is a provisional staging ground for work-in-progress patches, and acceptance into mm-new is a notification for others take notice and to finish up reviews. Please do not hesitate to respond to review feedback and post updated versions to replace or incrementally fixup patches in mm-new.

The mm-new branch of mm.git is not included in linux-next

If a few days of testing in mm-new is successful, the patch will me moved into mm.git's mm-unstable branch, which is included in linux-next

Before you just go and hit "reply", please:
a) Consider who else should be cc'ed
b) Prefer to cc a suitable mailing list as well
c) Ideally: find the original patch on the mailing list and do a reply-to-all to that, adding suitable additional cc's

*** Remember to use Documentation/process/submit-checklist.rst when testing your code ***

The -mm tree is included into linux-next via various branches at git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm
and is updated there most days

------------------------------------------------------
From: Kairui Song <[email protected]>
Subject: mm/mglru: make generation page counters atomic
Date: Wed, 02 Dec 2026 04:18:44 +0800

No feature change, convert them to atomic so we can update them without holding the LRU lock. A temporary underflow is fine: readers clamp a negative value to zero, and the counters only need to be eventually consistent.

Cc Johannes Weiner <[email protected]>
Cc Muchun Song <[email protected]>
Cc Qi Zheng <[email protected]>
Cc Ying Huang <[email protected]>
Cc Christopher Li <[email protected]>
Cc Baoquan He <[email protected]>
Cc Nico Pache <[email protected]>
Cc Usama Arif <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Roman Gushchin <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Axel Rasmussen <[email protected]>
Cc Yuanchu Xie <[email protected]>
Cc Wei Xu <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Nhat Pham <[email protected]>
Cc Youngjun Park <[email protected]>
Cc Zi Yan <[email protected]>
Cc Gregory Price <[email protected]>
Cc Matthew Wilcox (Oracle) <[email protected]>
Cc Baolin Wang <[email protected]>
Cc Ryan Roberts <[email protected]>
Cc Dev Jain <[email protected]>
Cc Lance Yang <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc David Rientjes <[email protected]>
Cc Yu Zhao <[email protected]>
Cc Vernon Yang <[email protected]>
Cc wangzicheng <[email protected]>
Cc Tal Zussman <[email protected]>
Cc Kairui Song <[email protected]>
Cc Xiang Liu <[email protected]>
Cc Ehab Ababneh <[email protected]>
Cc Joanne Koong <[email protected]>
Cc Hui Zhu <[email protected]>
Cc Maxim Muzafarov <[email protected]>
 include/linux/mm_inline.h |    6 ++----
 include/linux/mmzone.h    |    2 +-
 mm/vmscan.c               |   26 +++++++++++++-------------
 mm/vmscan.h               |    2 +-
 4 files changed, 17 insertions(+), 19 deletions(-)
include/linux/mm_inline.h renamed from include/linux/mm_inline.h~mm-mglru-make-generation-page-counters-atomic +2 -4
@@ -287,11 +287,9 @@ static inline void lru_gen_update_size(s
 	VM_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 renamed from include/linux/mmzone.h~mm-mglru-make-generation-page-counters-atomic +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 renamed from mm/vmscan.c~mm-mglru-make-generation-page-counters-atomic +13 -13
@@ -3413,8 +3413,7 @@ static void reset_batch_size(struct lru_
 			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;
@@ -4034,11 +4033,8 @@ static bool inc_min_seq(struct lruvec *l
 				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;
 	}
@@ -4156,8 +4152,8 @@ restart:
 	for (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;
@@ -4693,8 +4689,13 @@ static void __lru_gen_reparent_memcg(str
 	child_lrugen = &child_lruvec->lrugen;
 	parent_lrugen = &parent_lruvec->lrugen;
 
+	/*
+	 * The child is offline and the lockless updaters, which hold
+	 * rcu_read_lock() over the update, avoid racing with reparenting,
+	 * so the read/set/add operations below are safe.
+	 */
 	for (gen = 0; gen < MAX_NR_GENS; gen++) {
-		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;
 
@@ -4702,9 +4703,8 @@ static void __lru_gen_reparent_memcg(str
 		list_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);
mm/vmscan.h renamed from mm/vmscan.h~mm-mglru-make-generation-page-counters-atomic +1 -1
@@ -126,7 +126,7 @@ static inline unsigned long lruvec_gen_s
 	unsigned long size = 0;
 
 	for (int zone = 0; zone < max_zone; zone++)
-		size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
+		size += max(atomic_long_read(&lrugen->nr_pages[gen][type][zone]), 0L);
 
 	return size;
 }

_

Patches currently in -mm which might be from [email protected] are

mm-mglru-report-evictable-sizes-per-type.patch mm-mglru-extract-lruvec_populated_min_seq-helper.patch mm-mglru-reclaim-from-the-oldest-populated-gen.patch mm-mglru-lift-the-forced-protection-of-reclaimer.patch mm-mglru-skip-zones-above-reclaim_idx-instead-of-rotating-them.patch mm-mglru-return-for-unavailable-anon-reclaim-earlier.patch mm-mglru-balance-anon-and-file-scan-budget-by-refault-rate.patch mm-mglru-lift-youngest-gen-protection-for-higher-priority.patch mm-memcontrol-allow-update-of-lru-statistic-without-holding-lru-lock.patch mm-memcontrol-avoid-potential-counter-leak-when-reparenting-local-stats.patch mm-mglru-make-generation-page-counters-atomic.patch mm-memcg-add-folio-based-lruvec-live-helper.patch mm-mglru-frequency-guided-workingset-promotion-mglru-fg.patch mm-mglru-make-folio-lru-referenced-times-count-a-generic-api.patch mm-mglru-move-add-del-lru-size-accounting-out-of-lru_gen_update_size.patch mm-mglru-gup-mark-folios-referenced-via-a-fast-helper.patch mm-mglru-smaps-convert-to-lru-refs-based-operations-for-mglru.patch mm-damon-convert-to-lru-refs-based-operations-for-mglru.patch mm-khugepaged-convert-to-lru-refs-based-operations-for-mglru.patch mm-madvise-adapt-for-lru-refs-based-operations-for-mglru.patch mm-factor-out-folio_mark_accessed_vma.patch mm-huge_memory-mark-folio-as-accessed-more-accurately-on-split.patch mm-mglru-make-pg_workingset-helpers-work-based-on-folio-lru-refs.patch mm-mglru-folio-lru-refs-based-active-inactive-number-accounting.patch mm-mglru-make-folio_inc_lru_refs-lruvec-lockless.patch

author maintainer
#9 lore raw

PATCH v7 5/19 mm/memcg: add folio-based lruvec live helper

In reply to Kairui Song

Add a helper that resolves a live 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. The first user is the lockless folio_inc_lru_refs() path later in the series.

Factor the ancestor walk out of lruvec_live_lock_irq() into __lruvec_get_live(), so that both entry points share it, and spell out why the walk is enough while only the RCU read lock is held:
reparenting of a memcg that starts dying waits for a grace period, so it cannot race with the caller until the lock is released.

Move memcg_is_dying() up in memcontrol.h, next to the other memcg state predicates, and use it for the walk rather than repeating the open coded css_is_dying() test a few definitions away from where it is explained.

No functional change for existing callers.

---
 include/linux/memcontrol.h | 71 ++++++++++++++++++++++++++++++++++++----------
 1 file changed, 56 insertions(+), 15 deletions(-)
include/linux/memcontrol.h +56 -15
index 536375a32691..0a4639cea0e6 100644
@@ -573,6 +573,11 @@ static inline bool mem_cgroup_disabled(void)
 	return !cgroup_subsys_enabled(memory_cgrp_subsys);
 }
 
+static inline bool memcg_is_dying(struct mem_cgroup *memcg)
+{
+	return memcg ? css_is_dying(&memcg->css) : false;
+}
+
 static inline void mem_cgroup_protection(const struct mem_cgroup *root,
 					 const struct mem_cgroup *memcg,
 					 unsigned long *min,
@@ -1351,6 +1356,11 @@ static inline bool mem_cgroup_online(struct mem_cgroup *memcg)
 	return true;
 }
 
+static inline bool memcg_is_dying(struct mem_cgroup *memcg)
+{
+	return false;
+}
+
 static inline
 unsigned long mem_cgroup_get_zone_lru_size(const struct lruvec *lruvec,
 		enum lru_list lru, int zone_idx)
@@ -1512,28 +1522,41 @@ static inline void lruvec_lock_irq(struct lruvec *lruvec)
 	spin_lock_irq(&lruvec->lru_lock);
 }
 
-static inline struct lruvec *lruvec_live_lock_irq(struct lruvec *lruvec)
+/*
+ * Reparenting moves a dying memcg's LRU state to its parent at any time,
+ * so anything added to that LRU afterwards would be lost.  This helper
+ * walks up to the nearest live ancestor while the caller must hold the
+ * RCU read lock: reparenting of a memcg that starts dying waits for a
+ * grace period, so it cannot race with the caller until the lock is
+ * released.
+ */
+static inline struct lruvec *__lruvec_get_live(struct lruvec *lruvec)
 {
 #ifdef CONFIG_MEMCG
 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
 
-	rcu_read_lock();
-
 	/*
 	 * The memcg can be NULL when the memory controller is disabled.
 	 * Otherwise, the caller keeps the memcg owning @lruvec alive.
 	 */
-	while (unlikely(memcg && css_is_dying(&memcg->css))) {
+	while (unlikely(memcg_is_dying(memcg))) {
 		memcg = parent_mem_cgroup(memcg);
 		lruvec = mem_cgroup_lruvec(memcg, pgdat);
 	}
+#endif
+	return lruvec;
+}
 
+static inline struct lruvec *lruvec_live_lock_irq(struct lruvec *lruvec)
+{
+#ifdef CONFIG_MEMCG
+	rcu_read_lock();
+	lruvec = __lruvec_get_live(lruvec);
 	spin_lock_irq(&lruvec->lru_lock);
 #else
 	lruvec_lock_irq(lruvec);
 #endif
-
 	return lruvec;
 }
 
@@ -1563,6 +1586,34 @@ static inline bool folio_matches_lruvec(const struct folio *folio,
 	       lruvec_memcg(lruvec) == folio_memcg(folio);
 }
 
+/**
+ * folio_lruvec_live_get - get a live lruvec for a folio under RCU
+ * @folio: the folio
+ *
+ * Same as folio_lruvec(), except that a folio whose memcg is dying is
+ * accounted to the nearest live ancestor, which is where reparenting
+ * would put it anyway.
+ *
+ * Return: the live lruvec, with rcu_read_lock() held.  Pair it with
+ * folio_lruvec_live_put().
+ */
+static inline struct lruvec *folio_lruvec_live_get(const struct folio *folio)
+{
+#ifdef CONFIG_MEMCG
+	rcu_read_lock();
+	return __lruvec_get_live(folio_lruvec(folio));
+#else
+	return folio_lruvec(folio);
+#endif
+}
+
+static inline void folio_lruvec_live_put(const struct lruvec *lruvec)
+{
+#ifdef CONFIG_MEMCG
+	rcu_read_unlock();
+#endif
+}
+
 /* Don't lock again iff page's lruvec locked */
 static inline struct lruvec *folio_lruvec_relock_irq(const struct folio *folio,
 		struct lruvec *locked_lruvec)
@@ -1828,11 +1879,6 @@ void mem_cgroup_node_filter_allowed(struct mem_cgroup *memcg, nodemask_t *mask);
 
 void mem_cgroup_show_protected_memory(struct mem_cgroup *memcg);
 
-static inline bool memcg_is_dying(struct mem_cgroup *memcg)
-{
-	return memcg ? css_is_dying(&memcg->css) : false;
-}
-
 #else
 static inline bool mem_cgroup_kmem_disabled(void)
 {
@@ -1903,11 +1949,6 @@ static inline void mem_cgroup_node_filter_allowed(struct mem_cgroup *memcg,
 static inline void mem_cgroup_show_protected_memory(struct mem_cgroup *memcg)
 {
 }
-
-static inline bool memcg_is_dying(struct mem_cgroup *memcg)
-{
-	return false;
-}
 #endif /* CONFIG_MEMCG */
 
 #if defined(CONFIG_MEMCG) && defined(CONFIG_LRU_GEN)
Signature · 1 line
2.56.1
maintainer tree notice
#10 lore raw

+ mm-memcg-add-folio-based-lruvec-live-helper.patch added to mm-new branch

The patch titled Subject: mm/memcg: add folio-based lruvec live helper has been added to the -mm mm-new branch. Its filename is mm-memcg-add-folio-based-lruvec-live-helper.patch

The patch titled
Subject: mm/memcg: add folio-based lruvec live helper
has been added to the -mm mm-new branch. Its filename is
mm-memcg-add-folio-based-lruvec-live-helper.patch

This patch will shortly appear at
https://git.kernel.org/pub/scm/linux/kernel/git/akpm/25-new.git/tree/patches/mm-memcg-add-folio-based-lruvec-live-helper.patch

This patch will later appear in the mm-new branch at
git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm

Note, mm-new is a provisional staging ground for work-in-progress patches, and acceptance into mm-new is a notification for others take notice and to finish up reviews. Please do not hesitate to respond to review feedback and post updated versions to replace or incrementally fixup patches in mm-new.

The mm-new branch of mm.git is not included in linux-next

If a few days of testing in mm-new is successful, the patch will me moved into mm.git's mm-unstable branch, which is included in linux-next

Before you just go and hit "reply", please:
a) Consider who else should be cc'ed
b) Prefer to cc a suitable mailing list as well
c) Ideally: find the original patch on the mailing list and do a reply-to-all to that, adding suitable additional cc's

*** Remember to use Documentation/process/submit-checklist.rst when testing your code ***

The -mm tree is included into linux-next via various branches at git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm
and is updated there most days

------------------------------------------------------
From: Kairui Song <[email protected]>
Subject: mm/memcg: add folio-based lruvec live helper
Date: Wed, 02 Dec 2026 04:18:45 +0800

Add a helper that resolves a live 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. The first user is the lockless folio_inc_lru_refs() path later in the series.

Factor the ancestor walk out of lruvec_live_lock_irq() into __lruvec_get_live(), so that both entry points share it, and spell out why the walk is enough while only the RCU read lock is held:
reparenting of a memcg that starts dying waits for a grace period, so it cannot race with the caller until the lock is released.

Move memcg_is_dying() up in memcontrol.h, next to the other memcg state predicates, and use it for the walk rather than repeating the open coded css_is_dying() test a few definitions away from where it is explained.

No functional change for existing callers.

Cc Johannes Weiner <[email protected]>
Cc Ying Huang <[email protected]>
Cc Christopher Li <[email protected]>
Cc Baoquan He <[email protected]>
Cc Nico Pache <[email protected]>
Cc Usama Arif <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Roman Gushchin <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Barry Song <[email protected]>
Cc Axel Rasmussen <[email protected]>
Cc Yuanchu Xie <[email protected]>
Cc Wei Xu <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Nhat Pham <[email protected]>
Cc Youngjun Park <[email protected]>
Cc Zi Yan <[email protected]>
Cc Gregory Price <[email protected]>
Cc Matthew Wilcox (Oracle) <[email protected]>
Cc Baolin Wang <[email protected]>
Cc Ryan Roberts <[email protected]>
Cc Dev Jain <[email protected]>
Cc Lance Yang <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc SJ Park <[email protected]>
Cc David Rientjes <[email protected]>
Cc Yu Zhao <[email protected]>
Cc Vernon Yang <[email protected]>
Cc wangzicheng <[email protected]>
Cc Tal Zussman <[email protected]>
Cc Kairui Song <[email protected]>
Cc Xiang Liu <[email protected]>
Cc Ehab Ababneh <[email protected]>
Cc wang lian <[email protected]>
Cc Joanne Koong <[email protected]>
Cc Hui Zhu <[email protected]>
Cc Maxim Muzafarov <[email protected]>
Cc Tianyi Chen <[email protected]>
 include/linux/memcontrol.h |   71 +++++++++++++++++++++++++++--------
 1 file changed, 56 insertions(+), 15 deletions(-)
include/linux/memcontrol.h renamed from include/linux/memcontrol.h~mm-memcg-add-folio-based-lruvec-live-helper +56 -15
@@ -573,6 +573,11 @@ static inline bool mem_cgroup_disabled(v
 	return !cgroup_subsys_enabled(memory_cgrp_subsys);
 }
 
+static inline bool memcg_is_dying(struct mem_cgroup *memcg)
+{
+	return memcg ? css_is_dying(&memcg->css) : false;
+}
+
 static inline void mem_cgroup_protection(const struct mem_cgroup *root,
 					 const struct mem_cgroup *memcg,
 					 unsigned long *min,
@@ -1352,6 +1357,11 @@ static inline bool mem_cgroup_online(str
 	return true;
 }
 
+static inline bool memcg_is_dying(struct mem_cgroup *memcg)
+{
+	return false;
+}
+
 static inline
 unsigned long mem_cgroup_get_zone_lru_size(const struct lruvec *lruvec,
 		enum lru_list lru, int zone_idx)
@@ -1517,28 +1527,41 @@ static inline void lruvec_lock_irq(struc
 	spin_lock_irq(&lruvec->lru_lock);
 }
 
-static inline struct lruvec *lruvec_live_lock_irq(struct lruvec *lruvec)
+/*
+ * Reparenting moves a dying memcg's LRU state to its parent at any time,
+ * so anything added to that LRU afterwards would be lost.  This helper
+ * walks up to the nearest live ancestor while the caller must hold the
+ * RCU read lock: reparenting of a memcg that starts dying waits for a
+ * grace period, so it cannot race with the caller until the lock is
+ * released.
+ */
+static inline struct lruvec *__lruvec_get_live(struct lruvec *lruvec)
 {
 #ifdef CONFIG_MEMCG
 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
 
-	rcu_read_lock();
-
 	/*
 	 * The memcg can be NULL when the memory controller is disabled.
 	 * Otherwise, the caller keeps the memcg owning @lruvec alive.
 	 */
-	while (unlikely(memcg && css_is_dying(&memcg->css))) {
+	while (unlikely(memcg_is_dying(memcg))) {
 		memcg = parent_mem_cgroup(memcg);
 		lruvec = mem_cgroup_lruvec(memcg, pgdat);
 	}
+#endif
+	return lruvec;
+}
 
+static inline struct lruvec *lruvec_live_lock_irq(struct lruvec *lruvec)
+{
+#ifdef CONFIG_MEMCG
+	rcu_read_lock();
+	lruvec = __lruvec_get_live(lruvec);
 	spin_lock_irq(&lruvec->lru_lock);
 #else
 	lruvec_lock_irq(lruvec);
 #endif
-
 	return lruvec;
 }
 
@@ -1568,6 +1591,34 @@ static inline bool folio_matches_lruvec(
 	       lruvec_memcg(lruvec) == folio_memcg(folio);
 }
 
+/**
+ * folio_lruvec_live_get - get a live lruvec for a folio under RCU
+ * @folio: the folio
+ *
+ * Same as folio_lruvec(), except that a folio whose memcg is dying is
+ * accounted to the nearest live ancestor, which is where reparenting
+ * would put it anyway.
+ *
+ * Return: the live lruvec, with rcu_read_lock() held.  Pair it with
+ * folio_lruvec_live_put().
+ */
+static inline struct lruvec *folio_lruvec_live_get(const struct folio *folio)
+{
+#ifdef CONFIG_MEMCG
+	rcu_read_lock();
+	return __lruvec_get_live(folio_lruvec(folio));
+#else
+	return folio_lruvec(folio);
+#endif
+}
+
+static inline void folio_lruvec_live_put(const struct lruvec *lruvec)
+{
+#ifdef CONFIG_MEMCG
+	rcu_read_unlock();
+#endif
+}
+
 /* Don't lock again iff page's lruvec locked */
 static inline struct lruvec *folio_lruvec_relock_irq(const struct folio *folio,
 		struct lruvec *locked_lruvec)
@@ -1833,11 +1884,6 @@ void mem_cgroup_node_filter_allowed(stru
 
 void mem_cgroup_show_protected_memory(struct mem_cgroup *memcg);
 
-static inline bool memcg_is_dying(struct mem_cgroup *memcg)
-{
-	return memcg ? css_is_dying(&memcg->css) : false;
-}
-
 #else
 static inline bool mem_cgroup_kmem_disabled(void)
 {
@@ -1908,11 +1954,6 @@ static inline void mem_cgroup_node_filte
 static inline void mem_cgroup_show_protected_memory(struct mem_cgroup *memcg)
 {
 }
-
-static inline bool memcg_is_dying(struct mem_cgroup *memcg)
-{
-	return false;
-}
 #endif /* CONFIG_MEMCG */
 
 #if defined(CONFIG_MEMCG) && defined(CONFIG_LRU_GEN)

_

Patches currently in -mm which might be from [email protected] are

mm-mglru-report-evictable-sizes-per-type.patch mm-mglru-extract-lruvec_populated_min_seq-helper.patch mm-mglru-reclaim-from-the-oldest-populated-gen.patch mm-mglru-lift-the-forced-protection-of-reclaimer.patch mm-mglru-skip-zones-above-reclaim_idx-instead-of-rotating-them.patch mm-mglru-return-for-unavailable-anon-reclaim-earlier.patch mm-mglru-balance-anon-and-file-scan-budget-by-refault-rate.patch mm-mglru-lift-youngest-gen-protection-for-higher-priority.patch mm-memcontrol-allow-update-of-lru-statistic-without-holding-lru-lock.patch mm-memcontrol-avoid-potential-counter-leak-when-reparenting-local-stats.patch mm-mglru-make-generation-page-counters-atomic.patch mm-memcg-add-folio-based-lruvec-live-helper.patch mm-mglru-frequency-guided-workingset-promotion-mglru-fg.patch mm-mglru-make-folio-lru-referenced-times-count-a-generic-api.patch mm-mglru-move-add-del-lru-size-accounting-out-of-lru_gen_update_size.patch mm-mglru-gup-mark-folios-referenced-via-a-fast-helper.patch mm-mglru-smaps-convert-to-lru-refs-based-operations-for-mglru.patch mm-damon-convert-to-lru-refs-based-operations-for-mglru.patch mm-khugepaged-convert-to-lru-refs-based-operations-for-mglru.patch mm-madvise-adapt-for-lru-refs-based-operations-for-mglru.patch mm-factor-out-folio_mark_accessed_vma.patch mm-huge_memory-mark-folio-as-accessed-more-accurately-on-split.patch mm-mglru-make-pg_workingset-helpers-work-based-on-folio-lru-refs.patch mm-mglru-folio-lru-refs-based-active-inactive-number-accounting.patch mm-mglru-make-folio_inc_lru_refs-lruvec-lockless.patch

author maintainer
#11 lore raw

PATCH v7 6/19 mm/mglru: skip the flags cmpxchg when nothing changes

In reply to Kairui Song

From: Ridong Chen <[email protected]>

folio_update_gen() and folio_set_lru_refs() always end with a try_cmpxchg() on folio->flags, even when the new value equals the old one. The locked instruction still takes the struct page cacheline in exclusive state.

That is common in practice: a folio mapped by many processes is visited once per mm during a page table walk, and after the first visit it is already in the youngest generation with refs cleared and PG_workingset set. isolate_folio() and the eviction paths also call folio_set_lru_refs(folio, 0) on folios whose refs are already zero.

Break out of the loop when the flags would not change. The update is complete at the point of that read: the flags already hold the target value, and a concurrent change to them is ordered after it. When the cmpxchg would have succeeded, the value written is the same, so no new state becomes reachable.

What the patch drops is the retry. A retry re-reads the flags and recomputes new_flags from the newer value, so it overwrites a concurrent update with what this CPU wanted. For folio_update_gen(), a walker that read an older max_seq can lose the cmpxchg against a promotion done by another CPU, and then write its older generation back on the retry. folio_set_lru_refs() can likewise clear a refs increment that raced with it. Breaking out keeps the newer state.

No caller relies on the full barrier that the locked instruction implied on the skipped path: the eviction and isolation callers run under the LRU lock, and the others (page table walks, folio_mark_accessed(), lru_gen_clear_refs()) only care about the resulting flags value, which is already in place. Note that lru_gen_inc_refs() already returns without any atomic when refs is at LRU_REFS_MAX and the folio is in the workingset.

Tested on an i7-13700HX with turbo disabled and the performance governor. N processes map the same 2GiB tmpfs file (huge=never) and read every page, then one aging pass is triggered on their memcg through /sys/kernel/debug/lru_gen ("+ <memcg_id> 0 <max_seq> 200 1"). Time per aging pass in ms, median of 5 runs of 10 passes each, averaged over 2 boots of each kernel:

processes base patched

          1    32.9      31.7   -3.5%
          8   195.1     160.2  -17.9%
         32   755.8     592.2  -21.7%
         64  1597.2    1260.6  -21.1%

With one process, every visit changes the generation, so there is nothing to skip. Before the patch, perf annotate attributes 53-58% of the walk_update_folio() samples to the lock cmpxchg in the inlined folio_update_gen() in this test.

---
 include/linux/mm_inline.h | 2 ++
 mm/vmscan.c               | 2 ++
 2 files changed, 4 insertions(+)
include/linux/mm_inline.h +2 -0
index 48d617bb04e2..a86f680f1257 100644
@@ -255,6 +255,8 @@ static inline void folio_set_lru_refs(struct folio *folio, unsigned int refs)
 	do {
 		new_flags = old_flags;
 		lru_set_refs_flags(&new_flags, refs);
+		if (new_flags == old_flags)
+			break;
 	} while (!try_cmpxchg(folio_flags(folio, 0), &old_flags, new_flags));
 }
 
mm/vmscan.c +2 -0
index 34014a58b044..e6dd61583607 100644
@@ -3337,6 +3337,8 @@ static int folio_update_gen(struct folio *folio, int new_gen, int *type,
 		lru_set_gen_flags(&new_flags, new_gen);
 		lru_set_refs_flags(&new_flags, 0);
 		new_flags |= BIT(PG_workingset);
+		if (new_flags == old_flags)
+			break;
 	} while (!try_cmpxchg(folio_flags(folio, 0), &old_flags, new_flags));
 
 	*type = folio_flags_is_file_lru(&old_flags);
Signature · 1 line
2.56.1
maintainer tree notice
#12 lore raw

+ mm-mglru-skip-the-flags-cmpxchg-when-nothing-changes.patch added to mm-new branch

The patch titled Subject: mm/mglru: skip the flags cmpxchg when nothing changes has been added to the -mm mm-new branch. Its filename is mm-mglru-skip-the-flags-cmpxchg-when-nothing-changes.patch

The patch titled
Subject: mm/mglru: skip the flags cmpxchg when nothing changes
has been added to the -mm mm-new branch. Its filename is
mm-mglru-skip-the-flags-cmpxchg-when-nothing-changes.patch

This patch will shortly appear at
https://git.kernel.org/pub/scm/linux/kernel/git/akpm/25-new.git/tree/patches/mm-mglru-skip-the-flags-cmpxchg-when-nothing-changes.patch

This patch will later appear in the mm-new branch at
git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm

Note, mm-new is a provisional staging ground for work-in-progress patches, and acceptance into mm-new is a notification for others take notice and to finish up reviews. Please do not hesitate to respond to review feedback and post updated versions to replace or incrementally fixup patches in mm-new.

The mm-new branch of mm.git is not included in linux-next

If a few days of testing in mm-new is successful, the patch will me moved into mm.git's mm-unstable branch, which is included in linux-next

Before you just go and hit "reply", please:
a) Consider who else should be cc'ed
b) Prefer to cc a suitable mailing list as well
c) Ideally: find the original patch on the mailing list and do a reply-to-all to that, adding suitable additional cc's

*** Remember to use Documentation/process/submit-checklist.rst when testing your code ***

The -mm tree is included into linux-next via various branches at git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm
and is updated there most days

------------------------------------------------------
From: Ridong Chen <[email protected]>
Subject: mm/mglru: skip the flags cmpxchg when nothing changes
Date: Wed, 02 Dec 2026 04:18:46 +0800

folio_update_gen() and folio_set_lru_refs() always end with a try_cmpxchg() on folio->flags, even when the new value equals the old one. The locked instruction still takes the struct page cacheline in exclusive state.

That is common in practice: a folio mapped by many processes is visited once per mm during a page table walk, and after the first visit it is already in the youngest generation with refs cleared and PG_workingset set. isolate_folio() and the eviction paths also call folio_set_lru_refs(folio, 0) on folios whose refs are already zero.

Break out of the loop when the flags would not change. The update is complete at the point of that read: the flags already hold the target value, and a concurrent change to them is ordered after it. When the cmpxchg would have succeeded, the value written is the same, so no new state becomes reachable.

What the patch drops is the retry. A retry re-reads the flags and recomputes new_flags from the newer value, so it overwrites a concurrent update with what this CPU wanted. For folio_update_gen(), a walker that read an older max_seq can lose the cmpxchg against a promotion done by another CPU, and then write its older generation back on the retry. folio_set_lru_refs() can likewise clear a refs increment that raced with it. Breaking out keeps the newer state.

No caller relies on the full barrier that the locked instruction implied on the skipped path: the eviction and isolation callers run under the LRU lock, and the others (page table walks, folio_mark_accessed(), lru_gen_clear_refs()) only care about the resulting flags value, which is already in place. Note that lru_gen_inc_refs() already returns without any atomic when refs is at LRU_REFS_MAX and the folio is in the workingset.

Tested on an i7-13700HX with turbo disabled and the performance governor. N processes map the same 2GiB tmpfs file (huge=never) and read every page, then one aging pass is triggered on their memcg through /sys/kernel/debug/lru_gen ("+ <memcg_id> 0 <max_seq> 200 1"). Time per aging pass in ms, median of 5 runs of 10 passes each, averaged over 2 boots of each kernel:

processes base patched

          1    32.9      31.7   -3.5%
          8   195.1     160.2  -17.9%
         32   755.8     592.2  -21.7%
         64  1597.2    1260.6  -21.1%

With one process, every visit changes the generation, so there is nothing to skip. Before the patch, perf annotate attributes 53-58% of the walk_update_folio() samples to the lock cmpxchg in the inlined folio_update_gen() in this test.

[[email protected]: adapted and rebased for the series]
Cc Johannes Weiner <[email protected]>
Cc Muchun Song <[email protected]>
Cc Qi Zheng <[email protected]>
Cc Ying Huang <[email protected]>
Cc Christopher Li <[email protected]>
Cc Baoquan He <[email protected]>
Cc Nico Pache <[email protected]>
Cc Usama Arif <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Roman Gushchin <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Barry Song <[email protected]>
Cc Axel Rasmussen <[email protected]>
Cc Yuanchu Xie <[email protected]>
Cc Wei Xu <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Nhat Pham <[email protected]>
Cc Youngjun Park <[email protected]>
Cc Zi Yan <[email protected]>
Cc Gregory Price <[email protected]>
Cc Matthew Wilcox (Oracle) <[email protected]>
Cc Baolin Wang <[email protected]>
Cc Ryan Roberts <[email protected]>
Cc Dev Jain <[email protected]>
Cc Lance Yang <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc SJ Park <[email protected]>
Cc David Rientjes <[email protected]>
Cc Yu Zhao <[email protected]>
Cc wangzicheng <[email protected]>
Cc Tal Zussman <[email protected]>
Cc Kairui Song <[email protected]>
Cc Xiang Liu <[email protected]>
Cc Ehab Ababneh <[email protected]>
Cc zhaozhengzhuo <[email protected]>
Cc Joanne Koong <[email protected]>
Cc Hui Zhu <[email protected]>
Cc Maxim Muzafarov <[email protected]>
 include/linux/mm_inline.h |    2 ++
 mm/vmscan.c               |    2 ++
 2 files changed, 4 insertions(+)
include/linux/mm_inline.h renamed from include/linux/mm_inline.h~mm-mglru-skip-the-flags-cmpxchg-when-nothing-changes +2 -0
@@ -255,6 +255,8 @@ static inline void folio_set_lru_refs(st
 	do {
 		new_flags = old_flags;
 		lru_set_refs_flags(&new_flags, refs);
+		if (new_flags == old_flags)
+			break;
 	} while (!try_cmpxchg(folio_flags(folio, 0), &old_flags, new_flags));
 }
 
mm/vmscan.c renamed from mm/vmscan.c~mm-mglru-skip-the-flags-cmpxchg-when-nothing-changes +2 -0
@@ -3337,6 +3337,8 @@ static int folio_update_gen(struct folio
 		lru_set_gen_flags(&new_flags, new_gen);
 		lru_set_refs_flags(&new_flags, 0);
 		new_flags |= BIT(PG_workingset);
+		if (new_flags == old_flags)
+			break;
 	} while (!try_cmpxchg(folio_flags(folio, 0), &old_flags, new_flags));
 
 	*type = folio_flags_is_file_lru(&old_flags);

_

Patches currently in -mm which might be from [email protected] are

mm-memcontrol-drop-unused-vmscan-tracepoint-include.patch mm-vmscan-move-vmscan-tracepoints-to-a-local-header.patch mm-vmscan-move-struct-scan_control-to-a-dedicated-header.patch mm-vmscan-pass-scan_control-to-the-vmscan-tracepoints.patch mm-mglru-add-tracepoint-for-scan_folios.patch mm-mglru-add-lruvec_gen_size-helper.patch mm-mglru-add-tracepoint-for-aging.patch mm-mglru-pass-a-seq-range-to-lru_gen_add_folio.patch mm-mglru-deactivate-anon-folios-into-the-oldest-generation.patch mm-mglru-rename-the-generation-offset-in-lru_gen_folio_seq.patch mm-mglru-skip-the-flags-cmpxchg-when-nothing-changes.patch

author maintainer
#13 lore raw

PATCH v7 7/19 mm/mglru: frequency guided workingset promotion (MGLRU-FG)

In reply to Kairui Song

Complement MGLRU's eviction-time tier-PID protection with access-time frequency-guided promotion. Introduce a unified set of helpers based on the referenced (access) count of a folio.

Like LFU, this uses access frequency to distinguish hotter folios, but it still reclaims by generation: the generation and the bounded refs together form a "logical refs" count.

Accesses increase refs; refs crossing a threshold trigger promotion, which moves the folio one generation newer and caps its refs at a lower threshold, so a folio in a newer generation with lower refs is hotter than a folio in an older generation with higher refs. Gen aging then lowers the logical refs without updating every folio. Accesses from the page table and from file descriptors are balanced with defined rules.

This limits protection from old hotness at close to no overhead, and enhances MGLRU's ability to distinguish hotness levels over a much larger range.

A folio's refs still map to a logarithmic tier just like before, but with more formal bit definitions and more finely defined thresholds:
LRU_REFS_REFERENCED (1), LRU_REFS_WORKINGSET (2), LRU_REFS_PROTECTED (3), and LRU_REFS_MAX (7). The PID controller can still operate coherently with the new FG promotion, but the protection ratio is softer (2:3 -> 1:2) since proactive promotion is mostly good enough. The setpoint now also spans the cumulative mass of the tiers below the candidate instead of tier 0 alone, as the new thresholds are fallback tiers that a folio never falls below.

By making use of the newly defined thresholds, 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.

This doesn't affect classical LRU, and it addresses several shortcomings of MGLRU's file-descriptor cache protection:

- Long feedback loop: protection is only activated after enough re-faults, by which time the hot folios are already evicted, or no longer hot.

- Limited tier resolution: once the refs count saturated, MGLRU could no longer distinguish hotter folios within a tier. PG_workingset also 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 are done by the helpers below, check their inline comments for details. They collect references from different access channels, following the same rule but different context:

- 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. This performs lazy promotion.

- folio_inc_lru_refs_walk(): Used by the PTE walk path during aging and by the batched look-around, both without the LRU lock. 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 refs and PG_active placement hint.

Refaults restore the saved refs, capped at LRU_REFS_PROTECTED. Fault-driven refaults with prior references also set PG_active, keeping the stronger protection for page table access.

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.

PG_workingset and PG_referenced are no longer independent flags under MGLRU, so existing raw folio_test_*() callers need to be adjusted, which is covered by the following commits.

---
 include/linux/mm_inline.h | 107 +++++++++------
 include/linux/mmzone.h    | 126 +++++++++++------
 kernel/bounds.c           |   2 +-
 mm/folio.c                |  49 +------
 mm/vmscan.c               | 341 +++++++++++++++++++++++++++++++---------------
 mm/workingset.c           |  47 ++++---
 6 files changed, 416 insertions(+), 256 deletions(-)
include/linux/mm_inline.h +69 -38
index a86f680f1257..3cdad5765b58 100644
@@ -166,12 +166,14 @@ 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);
+	/* The refs range must map into the tier index space. */
+	BUILD_BUG_ON(BIT(LRU_TIER_MAX) < LRU_REFS_MAX);
+	VM_WARN_ON_ONCE(refs > LRU_REFS_MAX);
+	if (refs < LRU_REFS_WORKINGSET)
+		return 0;
+	return fls(refs - 1);
 }
 
 /**
@@ -209,21 +211,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 have 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
+ * encode the low two bits in binary order.
  */
 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;
 }
 
 /**
@@ -232,22 +237,31 @@ static inline void lru_set_refs_flags(unsigned long *flags, unsigned int refs)
  *
  * Reads the LRU referenced count set by lru_set_refs_flags().
  */
-static inline int lru_get_refs_flags(unsigned long flags)
+static inline unsigned 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;
+	unsigned int refs;
+
+	/* Decode the per-folio reference state. */
+	refs  = !!(flags & BIT(PG_referenced));
+	refs |= !!(flags & BIT(PG_workingset)) << 1;
+	refs |= ((flags & LRU_REFS_MASK) >> LRU_REFS_PGOFF) << 2;
+	return refs;
 }
 
-static inline int folio_lru_refs(const struct folio *folio)
+static inline unsigned int folio_lru_refs(const struct folio *folio)
 {
 	return lru_get_refs_flags(READ_ONCE(*const_folio_flags(folio, 0)));
 }
 
+/*
+ * Referenced at least twice. Unlike lru_refs_is_active() this is not
+ * bounds-checked: folio_inc_lru_refs() evaluates refs unclamped.
+ */
+static inline bool lru_refs_is_workingset(unsigned int refs)
+{
+	return refs >= LRU_REFS_WORKINGSET;
+}
+
 static inline void folio_set_lru_refs(struct folio *folio, unsigned int refs)
 {
 	unsigned long new_flags, old_flags = READ_ONCE(*folio_flags(folio, 0));
@@ -260,14 +274,26 @@ 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_is_old(struct lruvec *lruvec, int type, int gen)
+{
+	unsigned long min_seq = READ_ONCE(lruvec->lrugen.min_seq[type]);
+
+	/* The MIN_NR_GENS oldest generations, which eviction scans next */
+	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);
 
@@ -325,27 +351,28 @@ static inline unsigned long lru_gen_folio_seq(const struct lruvec *lruvec,
 	int age;
 	int type = folio_is_file_lru(folio);
 	const struct lru_gen_folio *lrugen = &lruvec->lrugen;
+	bool workingset = lru_refs_is_workingset(folio_lru_refs(folio));
 
 	/*
-	 * +-----------------------------------+-----------------------------------+
-	 * | 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))
-		age = MIN_NR_GENS - folio_test_workingset(folio);
+		age = MIN_NR_GENS - workingset;
 	else if ((!folio_is_file_lru(folio) && !folio_test_swapcache(folio)) ||
 		 (folio_test_reclaim(folio) &&
 		  (folio_test_dirty(folio) || folio_test_writeback(folio))))
 		age = MIN_NR_GENS;
 	else
-		age = MAX_NR_GENS - (folio_test_workingset(folio) || folio_test_referenced(folio));
+		age = MAX_NR_GENS - workingset;
 
 	return max(READ_ONCE(lrugen->max_seq) - age + 1, READ_ONCE(lrugen->min_seq[type]));
 }
@@ -366,6 +393,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)
@@ -422,7 +450,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 */
@@ -454,6 +481,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 +86 -40

143 lines not on this page · raw message

kernel/bounds.c +1 -1
index 02b619eb6106..06a034713b5d 100644
@@ -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 -47

79 lines not on this page · raw message

mm/vmscan.c +230 -111

465 lines not on this page · raw message

mm/workingset.c +28 -19

93 lines not on this page · raw message

Signature · 1 line
2.56.1
maintainer tree notice
#14 lore raw

+ mm-mglru-frequency-guided-workingset-promotion-mglru-fg.patch added to mm-new branch

The patch titled Subject: mm/mglru: frequency guided workingset promotion (MGLRU-FG) has been added to the -mm mm-new branch. Its filename is…

The patch titled
Subject: mm/mglru: frequency guided workingset promotion (MGLRU-FG)
has been added to the -mm mm-new branch. Its filename is
mm-mglru-frequency-guided-workingset-promotion-mglru-fg.patch

This patch will shortly appear at
https://git.kernel.org/pub/scm/linux/kernel/git/akpm/25-new.git/tree/patches/mm-mglru-frequency-guided-workingset-promotion-mglru-fg.patch

This patch will later appear in the mm-new branch at
git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm

Note, mm-new is a provisional staging ground for work-in-progress patches, and acceptance into mm-new is a notification for others take notice and to finish up reviews. Please do not hesitate to respond to review feedback and post updated versions to replace or incrementally fixup patches in mm-new.

The mm-new branch of mm.git is not included in linux-next

If a few days of testing in mm-new is successful, the patch will me moved into mm.git's mm-unstable branch, which is included in linux-next

Before you just go and hit "reply", please:
a) Consider who else should be cc'ed
b) Prefer to cc a suitable mailing list as well
c) Ideally: find the original patch on the mailing list and do a reply-to-all to that, adding suitable additional cc's

*** Remember to use Documentation/process/submit-checklist.rst when testing your code ***

The -mm tree is included into linux-next via various branches at git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm
and is updated there most days

------------------------------------------------------
From: Kairui Song <[email protected]>
Subject: mm/mglru: frequency guided workingset promotion (MGLRU-FG)
Date: Wed, 02 Dec 2026 04:18:47 +0800

Complement MGLRU's eviction-time tier-PID protection with access-time frequency-guided promotion. Introduce a unified set of helpers based on the referenced (access) count of a folio.

Like LFU, this uses access frequency to distinguish hotter folios, but it still reclaims by generation: the generation and the bounded refs together form a "logical refs" count.

Accesses increase refs; refs crossing a threshold trigger promotion, which moves the folio one generation newer and caps its refs at a lower threshold, so a folio in a newer generation with lower refs is hotter than a folio in an older generation with higher refs. Gen aging then lowers the logical refs without updating every folio. Accesses from the page table and from file descriptors are balanced with defined rules.

This limits protection from old hotness at close to no overhead, and enhances MGLRU's ability to distinguish hotness levels over a much larger range.

A folio's refs still map to a logarithmic tier just like before, but with more formal bit definitions and more finely defined thresholds:
LRU_REFS_REFERENCED (1), LRU_REFS_WORKINGSET (2), LRU_REFS_PROTECTED (3), and LRU_REFS_MAX (7). The PID controller can still operate coherently with the new FG promotion, but the protection ratio is softer (2:3 -> 1:2) since proactive promotion is mostly good enough. The setpoint now also spans the cumulative mass of the tiers below the candidate instead of tier 0 alone, as the new thresholds are fallback tiers that a folio never falls below.

By making use of the newly defined thresholds, 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.

This doesn't affect classical LRU, and it addresses several shortcomings of MGLRU's file-descriptor cache protection:

- Long feedback loop: protection is only activated after enough re-faults, by which time the hot folios are already evicted, or no longer hot.

- Limited tier resolution: once the refs count saturated, MGLRU could no longer distinguish hotter folios within a tier. PG_workingset also 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 are done by the helpers below, check their inline comments for details. They collect references from different access channels, following the same rule but different context:

- 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. This performs lazy promotion.

- folio_inc_lru_refs_walk(): Used by the PTE walk path during aging and by the batched look-around, both without the LRU lock. 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 refs and PG_active placement hint.

Refaults restore the saved refs, capped at LRU_REFS_PROTECTED. Fault-driven refaults with prior references also set PG_active, keeping the stronger protection for page table access.

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.

PG_workingset and PG_referenced are no longer independent flags under MGLRU, so existing raw folio_test_*() callers need to be adjusted, which is covered by the following commits.

Cc Johannes Weiner <[email protected]>
Cc Muchun Song <[email protected]>
Cc Qi Zheng <[email protected]>
Cc Ying Huang <[email protected]>
Cc Christopher Li <[email protected]>
Cc Baoquan He <[email protected]>
Cc Nico Pache <[email protected]>
Cc Usama Arif <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Roman Gushchin <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Barry Song <[email protected]>
Cc Axel Rasmussen <[email protected]>
Cc Yuanchu Xie <[email protected]>
Cc Wei Xu <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Nhat Pham <[email protected]>
Cc Youngjun Park <[email protected]>
Cc Zi Yan <[email protected]>
Cc Gregory Price <[email protected]>
Cc Matthew Wilcox (Oracle) <[email protected]>
Cc Baolin Wang <[email protected]>
Cc Ryan Roberts <[email protected]>
Cc Dev Jain <[email protected]>
Cc Lance Yang <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc SJ Park <[email protected]>
Cc David Rientjes <[email protected]>
Cc Yu Zhao <[email protected]>
Cc Vernon Yang <[email protected]>
Cc wangzicheng <[email protected]>
Cc Tal Zussman <[email protected]>
Cc Kairui Song <[email protected]>
Cc Xiang Liu <[email protected]>
Cc Ehab Ababneh <[email protected]>
Cc zhaozhengzhuo <[email protected]>
Cc Joanne Koong <[email protected]>
Cc Hui Zhu <[email protected]>
Cc Maxim Muzafarov <[email protected]>
Cc Ridong Chen <[email protected]>
 include/linux/mm_inline.h |  107 +++++++----
 include/linux/mmzone.h    |  130 +++++++++----
 kernel/bounds.c           |    2 
 mm/folio.c                |   49 -----
 mm/vmscan.c               |  339 ++++++++++++++++++++++++------------
 mm/workingset.c           |   47 ++--
 6 files changed, 417 insertions(+), 257 deletions(-)
include/linux/mm_inline.h renamed from include/linux/mm_inline.h~mm-mglru-frequency-guided-workingset-promotion-mglru-fg +69 -38
@@ -166,12 +166,14 @@ static inline int lru_hist_from_seq(unsi
 	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);
+	/* The refs range must map into the tier index space. */
+	BUILD_BUG_ON(BIT(LRU_TIER_MAX) < LRU_REFS_MAX);
+	VM_WARN_ON_ONCE(refs > LRU_REFS_MAX);
+	if (refs < LRU_REFS_WORKINGSET)
+		return 0;
+	return fls(refs - 1);
 }
 
 /**
@@ -209,21 +211,24 @@ static inline int lru_get_gen_flags(unsi
  * @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 have 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
+ * encode the low two bits in binary order.
  */
 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;
 }
 
 /**
@@ -232,22 +237,31 @@ static inline void lru_set_refs_flags(un
  *
  * Reads the LRU referenced count set by lru_set_refs_flags().
  */
-static inline int lru_get_refs_flags(unsigned long flags)
+static inline unsigned 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;
+	unsigned int refs;
+
+	/* Decode the per-folio reference state. */
+	refs  = !!(flags & BIT(PG_referenced));
+	refs |= !!(flags & BIT(PG_workingset)) << 1;
+	refs |= ((flags & LRU_REFS_MASK) >> LRU_REFS_PGOFF) << 2;
+	return refs;
 }
 
-static inline int folio_lru_refs(const struct folio *folio)
+static inline unsigned int folio_lru_refs(const struct folio *folio)
 {
 	return lru_get_refs_flags(READ_ONCE(*const_folio_flags(folio, 0)));
 }
 
+/*
+ * Referenced at least twice. Unlike lru_refs_is_active() this is not
+ * bounds-checked: folio_inc_lru_refs() evaluates refs unclamped.
+ */
+static inline bool lru_refs_is_workingset(unsigned int refs)
+{
+	return refs >= LRU_REFS_WORKINGSET;
+}
+
 static inline void folio_set_lru_refs(struct folio *folio, unsigned int refs)
 {
 	unsigned long new_flags, old_flags = READ_ONCE(*folio_flags(folio, 0));
@@ -260,14 +274,26 @@ static inline void folio_set_lru_refs(st
 	} 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_is_old(struct lruvec *lruvec, int type, int gen)
+{
+	unsigned long min_seq = READ_ONCE(lruvec->lrugen.min_seq[type]);
+
+	/* The MIN_NR_GENS oldest generations, which eviction scans next */
+	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);
 
@@ -325,27 +351,28 @@ static inline unsigned long lru_gen_foli
 	int age;
 	int type = folio_is_file_lru(folio);
 	const struct lru_gen_folio *lrugen = &lruvec->lrugen;
+	bool workingset = lru_refs_is_workingset(folio_lru_refs(folio));
 
 	/*
-	 * +-----------------------------------+-----------------------------------+
-	 * | 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))
-		age = MIN_NR_GENS - folio_test_workingset(folio);
+		age = MIN_NR_GENS - workingset;
 	else if ((!folio_is_file_lru(folio) && !folio_test_swapcache(folio)) ||
 		 (folio_test_reclaim(folio) &&
 		  (folio_test_dirty(folio) || folio_test_writeback(folio))))
 		age = MIN_NR_GENS;
 	else
-		age = MAX_NR_GENS - (folio_test_workingset(folio) || folio_test_referenced(folio));
+		age = MAX_NR_GENS - workingset;
 
 	return max(READ_ONCE(lrugen->max_seq) - age + 1, READ_ONCE(lrugen->min_seq[type]));
 }
@@ -366,6 +393,7 @@ static inline bool lru_gen_add_folio(str
 	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)
@@ -422,7 +450,6 @@ static inline bool lru_gen_del_folio(str
  */
 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 */
@@ -454,6 +481,10 @@ static inline bool lru_gen_del_folio(str
 	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 renamed from include/linux/mmzone.h~mm-mglru-frequency-guided-workingset-promotion-mglru-fg +88 -42

145 lines not on this page · raw message

kernel/bounds.c renamed from kernel/bounds.c~mm-mglru-frequency-guided-workingset-promotion-mglru-fg +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 renamed from mm/folio.c~mm-mglru-frequency-guided-workingset-promotion-mglru-fg +2 -47

79 lines not on this page · raw message

mm/vmscan.c renamed from mm/vmscan.c~mm-mglru-frequency-guided-workingset-promotion-mglru-fg +229 -110

464 lines not on this page · raw message

mm/workingset.c renamed from mm/workingset.c~mm-mglru-frequency-guided-workingset-promotion-mglru-fg +28 -19

93 lines not on this page · raw message

_

Patches currently in -mm which might be from [email protected] are

mm-mglru-report-evictable-sizes-per-type.patch mm-mglru-extract-lruvec_populated_min_seq-helper.patch mm-mglru-reclaim-from-the-oldest-populated-gen.patch mm-mglru-lift-the-forced-protection-of-reclaimer.patch mm-mglru-skip-zones-above-reclaim_idx-instead-of-rotating-them.patch mm-mglru-return-for-unavailable-anon-reclaim-earlier.patch mm-mglru-balance-anon-and-file-scan-budget-by-refault-rate.patch mm-mglru-lift-youngest-gen-protection-for-higher-priority.patch mm-memcontrol-allow-update-of-lru-statistic-without-holding-lru-lock.patch mm-memcontrol-avoid-potential-counter-leak-when-reparenting-local-stats.patch mm-mglru-make-generation-page-counters-atomic.patch mm-memcg-add-folio-based-lruvec-live-helper.patch mm-mglru-frequency-guided-workingset-promotion-mglru-fg.patch mm-mglru-make-folio-lru-referenced-times-count-a-generic-api.patch mm-mglru-move-add-del-lru-size-accounting-out-of-lru_gen_update_size.patch mm-mglru-gup-mark-folios-referenced-via-a-fast-helper.patch mm-mglru-smaps-convert-to-lru-refs-based-operations-for-mglru.patch mm-damon-convert-to-lru-refs-based-operations-for-mglru.patch mm-khugepaged-convert-to-lru-refs-based-operations-for-mglru.patch mm-madvise-adapt-for-lru-refs-based-operations-for-mglru.patch mm-factor-out-folio_mark_accessed_vma.patch mm-huge_memory-mark-folio-as-accessed-more-accurately-on-split.patch mm-mglru-make-pg_workingset-helpers-work-based-on-folio-lru-refs.patch mm-mglru-folio-lru-refs-based-active-inactive-number-accounting.patch mm-mglru-make-folio_inc_lru_refs-lruvec-lockless.patch

author maintainer
#15 lore raw

PATCH v7 8/19 mm/mglru: make folio lru referenced times count a generic API

In reply to Kairui Song

Pure code shuffle, no behavior change.

Make the folio LRU refs helpers available regardless of CONFIG_LRU_GEN. Without MGLRU the extra 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, preserving the two independent flags 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
index 3cdad5765b58..1749cbddf125 100644
@@ -206,6 +206,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
@@ -228,7 +234,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;
 }
 
 /**
@@ -274,13 +281,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_is_old(struct lruvec *lruvec, int type, int gen)
 {
 	unsigned long min_seq = READ_ONCE(lruvec->lrugen.min_seq[type]);
@@ -438,20 +463,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)
@@ -480,16 +491,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
index 96b66a272379..f59dd50b3f22 100644
@@ -807,8 +807,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.1
maintainer tree notice
#16 lore raw

+ mm-mglru-make-folio-lru-referenced-times-count-a-generic-api.patch added to mm-new branch

The patch titled Subject: mm/mglru: make folio lru referenced times count a generic API has been added to the -mm mm-new branch. Its filename is…

The patch titled
Subject: mm/mglru: make folio lru referenced times count a generic API
has been added to the -mm mm-new branch. Its filename is
mm-mglru-make-folio-lru-referenced-times-count-a-generic-api.patch

This patch will shortly appear at
https://git.kernel.org/pub/scm/linux/kernel/git/akpm/25-new.git/tree/patches/mm-mglru-make-folio-lru-referenced-times-count-a-generic-api.patch

This patch will later appear in the mm-new branch at
git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm

Note, mm-new is a provisional staging ground for work-in-progress patches, and acceptance into mm-new is a notification for others take notice and to finish up reviews. Please do not hesitate to respond to review feedback and post updated versions to replace or incrementally fixup patches in mm-new.

The mm-new branch of mm.git is not included in linux-next

If a few days of testing in mm-new is successful, the patch will me moved into mm.git's mm-unstable branch, which is included in linux-next

Before you just go and hit "reply", please:
a) Consider who else should be cc'ed
b) Prefer to cc a suitable mailing list as well
c) Ideally: find the original patch on the mailing list and do a reply-to-all to that, adding suitable additional cc's

*** Remember to use Documentation/process/submit-checklist.rst when testing your code ***

The -mm tree is included into linux-next via various branches at git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm
and is updated there most days

------------------------------------------------------
From: Kairui Song <[email protected]>
Subject: mm/mglru: make folio lru referenced times count a generic API
Date: Wed, 02 Dec 2026 04:18:48 +0800

Pure code shuffle, no behavior change.

Make the folio LRU refs helpers available regardless of CONFIG_LRU_GEN. Without MGLRU the extra 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, preserving the two independent flags for !CONFIG_LRU_GEN builds.

Cc Johannes Weiner <[email protected]>
Cc Muchun Song <[email protected]>
Cc Qi Zheng <[email protected]>
Cc Ying Huang <[email protected]>
Cc Christopher Li <[email protected]>
Cc Baoquan He <[email protected]>
Cc Nico Pache <[email protected]>
Cc Usama Arif <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Roman Gushchin <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Barry Song <[email protected]>
Cc Axel Rasmussen <[email protected]>
Cc Yuanchu Xie <[email protected]>
Cc Wei Xu <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Nhat Pham <[email protected]>
Cc Youngjun Park <[email protected]>
Cc Zi Yan <[email protected]>
Cc Gregory Price <[email protected]>
Cc Matthew Wilcox (Oracle) <[email protected]>
Cc Baolin Wang <[email protected]>
Cc Ryan Roberts <[email protected]>
Cc Dev Jain <[email protected]>
Cc Lance Yang <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc SJ Park <[email protected]>
Cc David Rientjes <[email protected]>
Cc Yu Zhao <[email protected]>
Cc Vernon Yang <[email protected]>
Cc wangzicheng <[email protected]>
Cc Tal Zussman <[email protected]>
Cc Kairui Song <[email protected]>
Cc Xiang Liu <[email protected]>
Cc Ehab Ababneh <[email protected]>
Cc Joanne Koong <[email protected]>
Cc Hui Zhu <[email protected]>
Cc Maxim Muzafarov <[email protected]>
Cc Ridong Chen <[email protected]>
 include/linux/mm_inline.h |   55 ++++++++++++++++++------------------
 mm/migrate.c              |    2 -
 2 files changed, 28 insertions(+), 29 deletions(-)
include/linux/mm_inline.h renamed from include/linux/mm_inline.h~mm-mglru-make-folio-lru-referenced-times-count-a-generic-api +28 -27
@@ -206,6 +206,12 @@ static inline int lru_get_gen_flags(unsi
 	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
@@ -228,7 +234,8 @@ static inline void lru_set_refs_flags(un
 		*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;
 }
 
 /**
@@ -274,13 +281,31 @@ static inline void folio_set_lru_refs(st
 	} 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_is_old(struct lruvec *lruvec, int type, int gen)
 {
 	unsigned long min_seq = READ_ONCE(lruvec->lrugen.min_seq[type]);
@@ -438,20 +463,6 @@ static inline bool lru_gen_del_folio(str
 
 	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)
@@ -480,16 +491,6 @@ static inline bool lru_gen_del_folio(str
 {
 	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 renamed from mm/migrate.c~mm-mglru-make-folio-lru-referenced-times-count-a-generic-api +0 -2
@@ -807,8 +807,6 @@ void folio_migrate_flags(struct folio *n
 		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);
 	/*

_

Patches currently in -mm which might be from [email protected] are

mm-mglru-report-evictable-sizes-per-type.patch mm-mglru-extract-lruvec_populated_min_seq-helper.patch mm-mglru-reclaim-from-the-oldest-populated-gen.patch mm-mglru-lift-the-forced-protection-of-reclaimer.patch mm-mglru-skip-zones-above-reclaim_idx-instead-of-rotating-them.patch mm-mglru-return-for-unavailable-anon-reclaim-earlier.patch mm-mglru-balance-anon-and-file-scan-budget-by-refault-rate.patch mm-mglru-lift-youngest-gen-protection-for-higher-priority.patch mm-memcontrol-allow-update-of-lru-statistic-without-holding-lru-lock.patch mm-memcontrol-avoid-potential-counter-leak-when-reparenting-local-stats.patch mm-mglru-make-generation-page-counters-atomic.patch mm-memcg-add-folio-based-lruvec-live-helper.patch mm-mglru-frequency-guided-workingset-promotion-mglru-fg.patch mm-mglru-make-folio-lru-referenced-times-count-a-generic-api.patch mm-mglru-move-add-del-lru-size-accounting-out-of-lru_gen_update_size.patch mm-mglru-gup-mark-folios-referenced-via-a-fast-helper.patch mm-mglru-smaps-convert-to-lru-refs-based-operations-for-mglru.patch mm-damon-convert-to-lru-refs-based-operations-for-mglru.patch mm-khugepaged-convert-to-lru-refs-based-operations-for-mglru.patch mm-madvise-adapt-for-lru-refs-based-operations-for-mglru.patch mm-factor-out-folio_mark_accessed_vma.patch mm-huge_memory-mark-folio-as-accessed-more-accurately-on-split.patch mm-mglru-make-pg_workingset-helpers-work-based-on-folio-lru-refs.patch mm-mglru-folio-lru-refs-based-active-inactive-number-accounting.patch mm-mglru-make-folio_inc_lru_refs-lruvec-lockless.patch

author maintainer
#17 lore raw

PATCH v7 9/19 mm/mglru: move add/del LRU size accounting out of lru_gen_update_size()

In reply to Kairui Song

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 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
index 1749cbddf125..e88229aeb641 100644
@@ -344,21 +344,9 @@ static inline void lru_gen_update_size(struct lruvec *lruvec, struct folio *foli
 	if (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)) {
@@ -416,6 +404,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);
@@ -433,6 +423,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 (tail)
 		list_add_tail(&folio->lru, &lrugen->folios[gen][type][zone]);
@@ -446,6 +440,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;
@@ -459,6 +456,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.1
maintainer tree notice
#18 lore raw

+ mm-mglru-move-add-del-lru-size-accounting-out-of-lru_gen_update_size.patch added to mm-new branch

The patch titled Subject: mm/mglru: move add/del LRU size accounting out of lru_gen_update_size() has been added to the -mm mm-new branch. Its filename is…

The patch titled
Subject: mm/mglru: move add/del LRU size accounting out of lru_gen_update_size()
has been added to the -mm mm-new branch. Its filename is
mm-mglru-move-add-del-lru-size-accounting-out-of-lru_gen_update_size.patch

This patch will shortly appear at
https://git.kernel.org/pub/scm/linux/kernel/git/akpm/25-new.git/tree/patches/mm-mglru-move-add-del-lru-size-accounting-out-of-lru_gen_update_size.patch

This patch will later appear in the mm-new branch at
git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm

Note, mm-new is a provisional staging ground for work-in-progress patches, and acceptance into mm-new is a notification for others take notice and to finish up reviews. Please do not hesitate to respond to review feedback and post updated versions to replace or incrementally fixup patches in mm-new.

The mm-new branch of mm.git is not included in linux-next

If a few days of testing in mm-new is successful, the patch will me moved into mm.git's mm-unstable branch, which is included in linux-next

Before you just go and hit "reply", please:
a) Consider who else should be cc'ed
b) Prefer to cc a suitable mailing list as well
c) Ideally: find the original patch on the mailing list and do a reply-to-all to that, adding suitable additional cc's

*** Remember to use Documentation/process/submit-checklist.rst when testing your code ***

The -mm tree is included into linux-next via various branches at git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm
and is updated there most days

------------------------------------------------------
From: Kairui Song <[email protected]>
Subject: mm/mglru: move add/del LRU size accounting out of lru_gen_update_size()
Date: Wed, 02 Dec 2026 04:18:49 +0800

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 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.

Cc Johannes Weiner <[email protected]>
Cc Muchun Song <[email protected]>
Cc Qi Zheng <[email protected]>
Cc Ying Huang <[email protected]>
Cc Christopher Li <[email protected]>
Cc Baoquan He <[email protected]>
Cc Nico Pache <[email protected]>
Cc Usama Arif <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Roman Gushchin <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Barry Song <[email protected]>
Cc Axel Rasmussen <[email protected]>
Cc Yuanchu Xie <[email protected]>
Cc Wei Xu <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Nhat Pham <[email protected]>
Cc Youngjun Park <[email protected]>
Cc Zi Yan <[email protected]>
Cc Gregory Price <[email protected]>
Cc Matthew Wilcox (Oracle) <[email protected]>
Cc Baolin Wang <[email protected]>
Cc Ryan Roberts <[email protected]>
Cc Dev Jain <[email protected]>
Cc Lance Yang <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc SJ Park <[email protected]>
Cc David Rientjes <[email protected]>
Cc Yu Zhao <[email protected]>
Cc Vernon Yang <[email protected]>
Cc wangzicheng <[email protected]>
Cc Tal Zussman <[email protected]>
Cc Kairui Song <[email protected]>
Cc Xiang Liu <[email protected]>
Cc Ehab Ababneh <[email protected]>
Cc Joanne Koong <[email protected]>
Cc Hui Zhu <[email protected]>
Cc Maxim Muzafarov <[email protected]>
Cc Ridong Chen <[email protected]>
 include/linux/mm_inline.h |   28 ++++++++++++++--------------
 1 file changed, 14 insertions(+), 14 deletions(-)
include/linux/mm_inline.h renamed from include/linux/mm_inline.h~mm-mglru-move-add-del-lru-size-accounting-out-of-lru_gen_update_size +14 -14
@@ -344,21 +344,9 @@ static inline void lru_gen_update_size(s
 	if (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)) {
@@ -416,6 +404,8 @@ static inline bool lru_gen_add_folio(str
 	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);
@@ -433,6 +423,10 @@ static inline bool lru_gen_add_folio(str
 	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 (tail)
 		list_add_tail(&folio->lru, &lrugen->folios[gen][type][zone]);
@@ -446,6 +440,9 @@ static inline bool lru_gen_del_folio(str
 {
 	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;
@@ -459,6 +456,9 @@ static inline bool lru_gen_del_folio(str
 	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;

_

Patches currently in -mm which might be from [email protected] are

mm-mglru-report-evictable-sizes-per-type.patch mm-mglru-extract-lruvec_populated_min_seq-helper.patch mm-mglru-reclaim-from-the-oldest-populated-gen.patch mm-mglru-lift-the-forced-protection-of-reclaimer.patch mm-mglru-skip-zones-above-reclaim_idx-instead-of-rotating-them.patch mm-mglru-return-for-unavailable-anon-reclaim-earlier.patch mm-mglru-balance-anon-and-file-scan-budget-by-refault-rate.patch mm-mglru-lift-youngest-gen-protection-for-higher-priority.patch mm-memcontrol-allow-update-of-lru-statistic-without-holding-lru-lock.patch mm-memcontrol-avoid-potential-counter-leak-when-reparenting-local-stats.patch mm-mglru-make-generation-page-counters-atomic.patch mm-memcg-add-folio-based-lruvec-live-helper.patch mm-mglru-frequency-guided-workingset-promotion-mglru-fg.patch mm-mglru-make-folio-lru-referenced-times-count-a-generic-api.patch mm-mglru-move-add-del-lru-size-accounting-out-of-lru_gen_update_size.patch mm-mglru-gup-mark-folios-referenced-via-a-fast-helper.patch mm-mglru-smaps-convert-to-lru-refs-based-operations-for-mglru.patch mm-damon-convert-to-lru-refs-based-operations-for-mglru.patch mm-khugepaged-convert-to-lru-refs-based-operations-for-mglru.patch mm-madvise-adapt-for-lru-refs-based-operations-for-mglru.patch mm-factor-out-folio_mark_accessed_vma.patch mm-huge_memory-mark-folio-as-accessed-more-accurately-on-split.patch mm-mglru-make-pg_workingset-helpers-work-based-on-folio-lru-refs.patch mm-mglru-folio-lru-refs-based-active-inactive-number-accounting.patch mm-mglru-make-folio_inc_lru_refs-lruvec-lockless.patch

author maintainer
#19 lore raw

PATCH v7 10/19 mm/mglru, gup: mark folios referenced via a fast helper

In reply to Kairui Song

Introduce 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 or promotion is needed, nonzero MGLRU refs are left unchanged.

The classical path is taken for a folio that is off the gen lists while MGLRU is off, not on lru_gen_enabled() alone: while MGLRU is being turned off, a folio can still be on a gen list after the static key flips, and setting PG_referenced there would bump its refs count.

That check uses lru_get_gen_flags(), so move the helper out of the CONFIG_LRU_GEN block, it is now built with the option off, where LRU_GEN_WIDTH is 0 and LRU_GEN_MASK is zero. Keep the decoded value in an int so the subtraction of the offset-by-one encoding cannot fold to ULONG_MAX before it happens to avoid -Woverflow error with CONFIG_WERROR.

This helper only aims to be fast, it exists so the gup fast path can stay a fast path: folio_set_referenced() would corrupt the MGLRU refs count, of which PG_referenced is bit 0, and folio_inc_lru_refs() is too heavy, while this one only raises the count to LRU_REFS_REFERENCED and never moves the folio to another generation, so a cmpxchg is all it needs. The new helper doesn't account for refs above LRU_REFS_REFERENCED but that's fine for now as GUP never used that or anything similar for CLRU either.

Convert the gup fast-path sites. No behavior change for classical LRU, no regression for MGLRU either. Just prepare for the following changes by providing a helper that follows the new convention.

---
 include/linux/mm_inline.h | 63 +++++++++++++++++++++++++++++++++++------------
 mm/gup.c                  |  6 ++---
 2 files changed, 50 insertions(+), 19 deletions(-)
include/linux/mm_inline.h +47 -16
index e88229aeb641..dde3fc6e7c0c 100644
@@ -127,6 +127,22 @@ static __always_inline enum lru_list folio_lru_list(const struct folio *folio)
 #define MIN_SEQ_UNBOUNDED	0UL
 #define MAX_SEQ_UNBOUNDED	ULONG_MAX
 
+/**
+ * lru_get_gen_flags - Return the LRU generation number from folio flags.
+ * @flags: folio flags
+ *
+ * Returns: A number between 0 and (MAX_NR_GENS - 1), inclusive. Returns
+ * -1 if the flags indicate the folio is off the list (e.g., isolated).
+ */
+static inline int lru_get_gen_flags(unsigned long flags)
+{
+	int gen = (int)((flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF);
+
+	/* The gen is stored offset by one, so zero means off-list */
+	VM_WARN_ON_ONCE(gen > MAX_NR_GENS);
+	return gen - 1;
+}
+
 #ifdef CONFIG_LRU_GEN
 
 static inline bool lru_gen_switching(void)
@@ -190,22 +206,6 @@ static inline void lru_set_gen_flags(unsigned long *flags, int gen)
 	*flags |= (gen + 1UL) << LRU_GEN_PGOFF;
 }
 
-/**
- * lru_get_gen_flags - Return the LRU generation number from folio flags.
- * @flags: folio flags
- *
- * Returns: A number between 0 and (MAX_NR_GENS - 1), inclusive. Returns
- * -1 if the flags indicate the folio is off the list (e.g., isolated).
- */
-static inline int lru_get_gen_flags(unsigned long flags)
-{
-	int gen = ((flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
-
-	/* Exclude the legal -1 from the unsigned MAX_NR_GENS comparison */
-	VM_WARN_ON_ONCE(gen != -1 && gen >= MAX_NR_GENS);
-	return gen;
-}
-
 static inline int folio_lru_gen(const struct folio *folio)
 {
 	return lru_get_gen_flags(READ_ONCE(*const_folio_flags(folio, 0)));
@@ -493,6 +493,37 @@ 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 a folio off the gen lists with MGLRU off, a plain
+ * PG_referenced set. This replaces folio_set_referenced(), which corrupts
+ * the MGLRU refs count, for paths that must stay cheap like GUP-fast: no
+ * lruvec lookup, accounting or promotion. Use folio_mark_accessed()
+ * everywhere else.
+ */
+static __always_inline void folio_inc_lru_refs_fast(struct folio *folio)
+{
+	unsigned long new_flags, old_flags = READ_ONCE(*folio_flags(folio, 0));
+	unsigned int refs;
+	bool has_gen;
+
+	do {
+		has_gen = lru_get_gen_flags(old_flags) >= 0;
+		refs = lru_get_refs_flags(old_flags);
+		if (has_gen || lru_gen_enabled()) {
+			if (refs)
+				break;
+		} else if (refs & LRU_REFS_REFERENCED) {
+			break;
+		}
+		new_flags = old_flags;
+		lru_set_refs_flags(&new_flags, refs | 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
index 7605da0e06d8..da04bebfff43 100644
@@ -2921,7 +2921,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);
@@ -2990,7 +2990,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;
 }
 
@@ -3032,7 +3032,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.1
maintainer tree notice
#20 lore raw

+ mm-mglru-gup-mark-folios-referenced-via-a-fast-helper.patch added to mm-new branch

The patch titled Subject: mm/mglru, gup: mark folios referenced via a fast helper has been added to the -mm mm-new branch. Its filename is mm-mglru-gup-mark-folios-referenced-via-a-fast-helper.patch

The patch titled
Subject: mm/mglru, gup: mark folios referenced via a fast helper
has been added to the -mm mm-new branch. Its filename is
mm-mglru-gup-mark-folios-referenced-via-a-fast-helper.patch

This patch will shortly appear at
https://git.kernel.org/pub/scm/linux/kernel/git/akpm/25-new.git/tree/patches/mm-mglru-gup-mark-folios-referenced-via-a-fast-helper.patch

This patch will later appear in the mm-new branch at
git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm

Note, mm-new is a provisional staging ground for work-in-progress patches, and acceptance into mm-new is a notification for others take notice and to finish up reviews. Please do not hesitate to respond to review feedback and post updated versions to replace or incrementally fixup patches in mm-new.

The mm-new branch of mm.git is not included in linux-next

If a few days of testing in mm-new is successful, the patch will me moved into mm.git's mm-unstable branch, which is included in linux-next

Before you just go and hit "reply", please:
a) Consider who else should be cc'ed
b) Prefer to cc a suitable mailing list as well
c) Ideally: find the original patch on the mailing list and do a reply-to-all to that, adding suitable additional cc's

*** Remember to use Documentation/process/submit-checklist.rst when testing your code ***

The -mm tree is included into linux-next via various branches at git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm
and is updated there most days

------------------------------------------------------
From: Kairui Song <[email protected]>
Subject: mm/mglru, gup: mark folios referenced via a fast helper
Date: Wed, 02 Dec 2026 04:18:50 +0800

Introduce 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 or promotion is needed, nonzero MGLRU refs are left unchanged.

The classical path is taken for a folio that is off the gen lists while MGLRU is off, not on lru_gen_enabled() alone: while MGLRU is being turned off, a folio can still be on a gen list after the static key flips, and setting PG_referenced there would bump its refs count.

That check uses lru_get_gen_flags(), so move the helper out of the CONFIG_LRU_GEN block, it is now built with the option off, where LRU_GEN_WIDTH is 0 and LRU_GEN_MASK is zero. Keep the decoded value in an int so the subtraction of the offset-by-one encoding cannot fold to ULONG_MAX before it happens to avoid -Woverflow error with CONFIG_WERROR.

This helper only aims to be fast, it exists so the gup fast path can stay a fast path: folio_set_referenced() would corrupt the MGLRU refs count, of which PG_referenced is bit 0, and folio_inc_lru_refs() is too heavy, while this one only raises the count to LRU_REFS_REFERENCED and never moves the folio to another generation, so a cmpxchg is all it needs. The new helper doesn't account for refs above LRU_REFS_REFERENCED but that's fine for now as GUP never used that or anything similar for CLRU either.

Convert the gup fast-path sites. No behavior change for classical LRU, no regression for MGLRU either. Just prepare for the following changes by providing a helper that follows the new convention.

Cc Johannes Weiner <[email protected]>
Cc Muchun Song <[email protected]>
Cc Qi Zheng <[email protected]>
Cc Ying Huang <[email protected]>
Cc Christopher Li <[email protected]>
Cc Baoquan He <[email protected]>
Cc Nico Pache <[email protected]>
Cc Usama Arif <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Roman Gushchin <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Barry Song <[email protected]>
Cc Axel Rasmussen <[email protected]>
Cc Yuanchu Xie <[email protected]>
Cc Wei Xu <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Nhat Pham <[email protected]>
Cc Youngjun Park <[email protected]>
Cc Zi Yan <[email protected]>
Cc Gregory Price <[email protected]>
Cc Matthew Wilcox (Oracle) <[email protected]>
Cc Baolin Wang <[email protected]>
Cc Ryan Roberts <[email protected]>
Cc Dev Jain <[email protected]>
Cc Lance Yang <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc SJ Park <[email protected]>
Cc David Rientjes <[email protected]>
Cc Yu Zhao <[email protected]>
Cc Vernon Yang <[email protected]>
Cc wangzicheng <[email protected]>
Cc Tal Zussman <[email protected]>
Cc Kairui Song <[email protected]>
Cc Xiang Liu <[email protected]>
Cc Ehab Ababneh <[email protected]>
Cc wang lian <[email protected]>
Cc Joanne Koong <[email protected]>
Cc Hui Zhu <[email protected]>
Cc Maxim Muzafarov <[email protected]>
Cc Tianyi Chen <[email protected]>
Cc Ridong Chen <[email protected]>
 include/linux/mm_inline.h |   63 ++++++++++++++++++++++++++----------
 mm/gup.c                  |    6 +--
 2 files changed, 50 insertions(+), 19 deletions(-)
include/linux/mm_inline.h renamed from include/linux/mm_inline.h~mm-mglru-gup-mark-folios-referenced-via-a-fast-helper +47 -16
@@ -127,6 +127,22 @@ static __always_inline enum lru_list fol
 #define MIN_SEQ_UNBOUNDED	0UL
 #define MAX_SEQ_UNBOUNDED	ULONG_MAX
 
+/**
+ * lru_get_gen_flags - Return the LRU generation number from folio flags.
+ * @flags: folio flags
+ *
+ * Returns: A number between 0 and (MAX_NR_GENS - 1), inclusive. Returns
+ * -1 if the flags indicate the folio is off the list (e.g., isolated).
+ */
+static inline int lru_get_gen_flags(unsigned long flags)
+{
+	int gen = (int)((flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF);
+
+	/* The gen is stored offset by one, so zero means off-list */
+	VM_WARN_ON_ONCE(gen > MAX_NR_GENS);
+	return gen - 1;
+}
+
 #ifdef CONFIG_LRU_GEN
 
 static inline bool lru_gen_switching(void)
@@ -190,22 +206,6 @@ static inline void lru_set_gen_flags(uns
 	*flags |= (gen + 1UL) << LRU_GEN_PGOFF;
 }
 
-/**
- * lru_get_gen_flags - Return the LRU generation number from folio flags.
- * @flags: folio flags
- *
- * Returns: A number between 0 and (MAX_NR_GENS - 1), inclusive. Returns
- * -1 if the flags indicate the folio is off the list (e.g., isolated).
- */
-static inline int lru_get_gen_flags(unsigned long flags)
-{
-	int gen = ((flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
-
-	/* Exclude the legal -1 from the unsigned MAX_NR_GENS comparison */
-	VM_WARN_ON_ONCE(gen != -1 && gen >= MAX_NR_GENS);
-	return gen;
-}
-
 static inline int folio_lru_gen(const struct folio *folio)
 {
 	return lru_get_gen_flags(READ_ONCE(*const_folio_flags(folio, 0)));
@@ -493,6 +493,37 @@ static inline bool lru_gen_del_folio(str
 }
 #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 a folio off the gen lists with MGLRU off, a plain
+ * PG_referenced set. This replaces folio_set_referenced(), which corrupts
+ * the MGLRU refs count, for paths that must stay cheap like GUP-fast: no
+ * lruvec lookup, accounting or promotion. Use folio_mark_accessed()
+ * everywhere else.
+ */
+static __always_inline void folio_inc_lru_refs_fast(struct folio *folio)
+{
+	unsigned long new_flags, old_flags = READ_ONCE(*folio_flags(folio, 0));
+	unsigned int refs;
+	bool has_gen;
+
+	do {
+		has_gen = lru_get_gen_flags(old_flags) >= 0;
+		refs = lru_get_refs_flags(old_flags);
+		if (has_gen || lru_gen_enabled()) {
+			if (refs)
+				break;
+		} else if (refs & LRU_REFS_REFERENCED) {
+			break;
+		}
+		new_flags = old_flags;
+		lru_set_refs_flags(&new_flags, refs | 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 renamed from mm/gup.c~mm-mglru-gup-mark-folios-referenced-via-a-fast-helper +3 -3
@@ -2921,7 +2921,7 @@ static unsigned long gup_fast_pte_range(
 			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);
@@ -2990,7 +2990,7 @@ static unsigned long gup_fast_pmd_leaf(p
 
 	for (i = 0; i < nr_pages; i++)
 		*(pages++) = page++;
-	folio_set_referenced(folio);
+	folio_inc_lru_refs_fast(folio);
 	return nr_pages;
 }
 
@@ -3032,7 +3032,7 @@ static unsigned long gup_fast_pud_leaf(p
 
 	for (i = 0; i < nr_pages; i++)
 		*(pages++) = page++;
-	folio_set_referenced(folio);
+	folio_inc_lru_refs_fast(folio);
 	return nr_pages;
 }
 

_

Patches currently in -mm which might be from [email protected] are

mm-mglru-report-evictable-sizes-per-type.patch mm-mglru-extract-lruvec_populated_min_seq-helper.patch mm-mglru-reclaim-from-the-oldest-populated-gen.patch mm-mglru-lift-the-forced-protection-of-reclaimer.patch mm-mglru-skip-zones-above-reclaim_idx-instead-of-rotating-them.patch mm-mglru-return-for-unavailable-anon-reclaim-earlier.patch mm-mglru-balance-anon-and-file-scan-budget-by-refault-rate.patch mm-mglru-lift-youngest-gen-protection-for-higher-priority.patch mm-memcontrol-allow-update-of-lru-statistic-without-holding-lru-lock.patch mm-memcontrol-avoid-potential-counter-leak-when-reparenting-local-stats.patch mm-mglru-make-generation-page-counters-atomic.patch mm-memcg-add-folio-based-lruvec-live-helper.patch mm-mglru-frequency-guided-workingset-promotion-mglru-fg.patch mm-mglru-make-folio-lru-referenced-times-count-a-generic-api.patch mm-mglru-move-add-del-lru-size-accounting-out-of-lru_gen_update_size.patch mm-mglru-gup-mark-folios-referenced-via-a-fast-helper.patch mm-mglru-smaps-convert-to-lru-refs-based-operations-for-mglru.patch mm-damon-convert-to-lru-refs-based-operations-for-mglru.patch mm-khugepaged-convert-to-lru-refs-based-operations-for-mglru.patch mm-madvise-adapt-for-lru-refs-based-operations-for-mglru.patch mm-factor-out-folio_mark_accessed_vma.patch mm-huge_memory-mark-folio-as-accessed-more-accurately-on-split.patch mm-mglru-make-pg_workingset-helpers-work-based-on-folio-lru-refs.patch mm-mglru-folio-lru-refs-based-active-inactive-number-accounting.patch mm-mglru-make-folio_inc_lru_refs-lruvec-lockless.patch

author maintainer
#21 lore raw

PATCH v7 11/19 mm/mglru, smaps: convert to LRU refs based operations for MGLRU

In reply to Kairui Song

PG_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_test_lru_refs() and folio_clear_lru_refs(), which cover the PG_young page-idle hint and use the refs count when MGLRU is enabled and PG_referenced otherwise, and switch the smaps paths over to them.

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, and its internals keep using the raw PG_referenced helpers.

---
 fs/proc/task_mmu.c        |  8 +++-----
 include/linux/mm_inline.h | 35 +++++++++++++++++++++++++++++++++++
 2 files changed, 38 insertions(+), 5 deletions(-)
fs/proc/task_mmu.c +3 -5
index 0d1c941790b0..44a347bc65d2 100644
@@ -890,7 +890,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_lru_refs(folio))
 		mss->referenced += size;
 
 	/*
@@ -1693,8 +1693,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;
@@ -1722,8 +1721,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 +35 -0
index dde3fc6e7c0c..d3f0c29ac340 100644
@@ -9,6 +9,7 @@
 #include <linux/string.h>
 #include <linux/userfaultfd_k.h>
 #include <linux/leafops.h>
+#include <linux/page_idle.h>
 
 /**
  * folio_is_file_lru - Should the folio be on a file LRU or anon LRU?
@@ -524,6 +525,40 @@ static __always_inline void folio_inc_lru_refs_fast(struct folio *folio)
 	} while (!try_cmpxchg(folio_flags(folio, 0), &old_flags, new_flags));
 }
 
+/**
+ * folio_test_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, or if PG_young is set. Kept
+ * as a separate helper, to avoid splattering the lru_gen_enabled() static key.
+ */
+static inline bool folio_test_lru_refs(const struct folio *folio)
+{
+	if (folio_test_young(folio))
+		return true;
+	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, and clear PG_young. Kept as a
+ * separate helper just like folio_test_lru_refs().
+ */
+static inline void folio_clear_lru_refs(struct folio *folio)
+{
+	folio_test_clear_young(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.1
maintainer tree notice
#22 lore raw

+ mm-mglru-smaps-convert-to-lru-refs-based-operations-for-mglru.patch added to mm-new branch

The patch titled Subject: mm/mglru, smaps: convert to LRU refs based operations for MGLRU has been added to the -mm mm-new branch. Its filename is…

The patch titled
Subject: mm/mglru, smaps: convert to LRU refs based operations for MGLRU
has been added to the -mm mm-new branch. Its filename is
mm-mglru-smaps-convert-to-lru-refs-based-operations-for-mglru.patch

This patch will shortly appear at
https://git.kernel.org/pub/scm/linux/kernel/git/akpm/25-new.git/tree/patches/mm-mglru-smaps-convert-to-lru-refs-based-operations-for-mglru.patch

This patch will later appear in the mm-new branch at
git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm

Note, mm-new is a provisional staging ground for work-in-progress patches, and acceptance into mm-new is a notification for others take notice and to finish up reviews. Please do not hesitate to respond to review feedback and post updated versions to replace or incrementally fixup patches in mm-new.

The mm-new branch of mm.git is not included in linux-next

If a few days of testing in mm-new is successful, the patch will me moved into mm.git's mm-unstable branch, which is included in linux-next

Before you just go and hit "reply", please:
a) Consider who else should be cc'ed
b) Prefer to cc a suitable mailing list as well
c) Ideally: find the original patch on the mailing list and do a reply-to-all to that, adding suitable additional cc's

*** Remember to use Documentation/process/submit-checklist.rst when testing your code ***

The -mm tree is included into linux-next via various branches at git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm
and is updated there most days

------------------------------------------------------
From: Kairui Song <[email protected]>
Subject: mm/mglru, smaps: convert to LRU refs based operations for MGLRU
Date: Wed, 02 Dec 2026 04:18:51 +0800

PG_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_test_lru_refs() and folio_clear_lru_refs(), which cover the PG_young page-idle hint and use the refs count when MGLRU is enabled and PG_referenced otherwise, and switch the smaps paths over to them.

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, and its internals keep using the raw PG_referenced helpers.

Cc Johannes Weiner <[email protected]>
Cc Muchun Song <[email protected]>
Cc Qi Zheng <[email protected]>
Cc Ying Huang <[email protected]>
Cc Christopher Li <[email protected]>
Cc Baoquan He <[email protected]>
Cc Nico Pache <[email protected]>
Cc Usama Arif <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Roman Gushchin <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Barry Song <[email protected]>
Cc Axel Rasmussen <[email protected]>
Cc Yuanchu Xie <[email protected]>
Cc Wei Xu <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Nhat Pham <[email protected]>
Cc Youngjun Park <[email protected]>
Cc Gregory Price <[email protected]>
Cc Matthew Wilcox (Oracle) <[email protected]>
Cc Baolin Wang <[email protected]>
Cc Ryan Roberts <[email protected]>
Cc Dev Jain <[email protected]>
Cc Lance Yang <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc SJ Park <[email protected]>
Cc David Rientjes <[email protected]>
Cc Yu Zhao <[email protected]>
Cc Vernon Yang <[email protected]>
Cc wangzicheng <[email protected]>
Cc Tal Zussman <[email protected]>
Cc Kairui Song <[email protected]>
Cc Xiang Liu <[email protected]>
Cc Ehab Ababneh <[email protected]>
Cc zhaozhengzhuo <[email protected]>
Cc wang lian <[email protected]>
Cc Joanne Koong <[email protected]>
Cc Hui Zhu <[email protected]>
Cc Maxim Muzafarov <[email protected]>
Cc Tianyi Chen <[email protected]>
Cc Ridong Chen <[email protected]>
 fs/proc/task_mmu.c        |    8 +++-----
 include/linux/mm_inline.h |   35 +++++++++++++++++++++++++++++++++++
 2 files changed, 38 insertions(+), 5 deletions(-)
fs/proc/task_mmu.c renamed from fs/proc/task_mmu.c~mm-mglru-smaps-convert-to-lru-refs-based-operations-for-mglru +3 -5
@@ -890,7 +890,7 @@ static void smaps_account(struct mem_siz
 
 	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_lru_refs(folio))
 		mss->referenced += size;
 
 	/*
@@ -1693,8 +1693,7 @@ static int clear_refs_pte_range(pmd_t *p
 
 		/* 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;
@@ -1722,8 +1721,7 @@ out:
 
 		/* 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 renamed from include/linux/mm_inline.h~mm-mglru-smaps-convert-to-lru-refs-based-operations-for-mglru +35 -0
@@ -9,6 +9,7 @@
 #include <linux/string.h>
 #include <linux/userfaultfd_k.h>
 #include <linux/leafops.h>
+#include <linux/page_idle.h>
 
 /**
  * folio_is_file_lru - Should the folio be on a file LRU or anon LRU?
@@ -524,6 +525,40 @@ static __always_inline void folio_inc_lr
 	} while (!try_cmpxchg(folio_flags(folio, 0), &old_flags, new_flags));
 }
 
+/**
+ * folio_test_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, or if PG_young is set. Kept
+ * as a separate helper, to avoid splattering the lru_gen_enabled() static key.
+ */
+static inline bool folio_test_lru_refs(const struct folio *folio)
+{
+	if (folio_test_young(folio))
+		return true;
+	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, and clear PG_young. Kept as a
+ * separate helper just like folio_test_lru_refs().
+ */
+static inline void folio_clear_lru_refs(struct folio *folio)
+{
+	folio_test_clear_young(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)
 {

_

Patches currently in -mm which might be from [email protected] are

mm-mglru-report-evictable-sizes-per-type.patch mm-mglru-extract-lruvec_populated_min_seq-helper.patch mm-mglru-reclaim-from-the-oldest-populated-gen.patch mm-mglru-lift-the-forced-protection-of-reclaimer.patch mm-mglru-skip-zones-above-reclaim_idx-instead-of-rotating-them.patch mm-mglru-return-for-unavailable-anon-reclaim-earlier.patch mm-mglru-balance-anon-and-file-scan-budget-by-refault-rate.patch mm-mglru-lift-youngest-gen-protection-for-higher-priority.patch mm-memcontrol-allow-update-of-lru-statistic-without-holding-lru-lock.patch mm-memcontrol-avoid-potential-counter-leak-when-reparenting-local-stats.patch mm-mglru-make-generation-page-counters-atomic.patch mm-memcg-add-folio-based-lruvec-live-helper.patch mm-mglru-frequency-guided-workingset-promotion-mglru-fg.patch mm-mglru-make-folio-lru-referenced-times-count-a-generic-api.patch mm-mglru-move-add-del-lru-size-accounting-out-of-lru_gen_update_size.patch mm-mglru-gup-mark-folios-referenced-via-a-fast-helper.patch mm-mglru-smaps-convert-to-lru-refs-based-operations-for-mglru.patch mm-damon-convert-to-lru-refs-based-operations-for-mglru.patch mm-khugepaged-convert-to-lru-refs-based-operations-for-mglru.patch mm-madvise-adapt-for-lru-refs-based-operations-for-mglru.patch mm-factor-out-folio_mark_accessed_vma.patch mm-huge_memory-mark-folio-as-accessed-more-accurately-on-split.patch mm-mglru-make-pg_workingset-helpers-work-based-on-folio-lru-refs.patch mm-mglru-folio-lru-refs-based-active-inactive-number-accounting.patch mm-mglru-make-folio_inc_lru_refs-lruvec-lockless.patch

author maintainer
#23 lore raw

PATCH v7 12/19 mm/damon: convert to LRU refs based operations for MGLRU

In reply to Kairui Song

damon_pa_pageout() cleared PG_referenced directly, which under MGLRU corrupts the folio's refs count. That flag is now
bit 0 of the count (LRU_REFS_FLAGS).

Reset the count instead under MGLRU, with folio_clear_lru_refs(), which also clears PG_young.

---
 mm/damon/paddr.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
mm/damon/paddr.c +2 -2
index b9d83e64a588..4104b8eb76f6 100644
@@ -290,8 +290,8 @@ static unsigned long damon_pa_pageout(struct damon_region *r,
 		else
 			*sz_filter_passed += folio_size(folio) / addr_unit;
 
-		folio_clear_referenced(folio);
-		folio_test_clear_young(folio);
+		/* The region is cold, better drop the hotness info. */
+		folio_clear_lru_refs(folio);
 		if (!folio_isolate_lru(folio))
 			goto put_folio;
 		if (folio_test_unevictable(folio))
Signature · 1 line
2.56.1
maintainer tree notice
#24 lore raw

+ mm-damon-convert-to-lru-refs-based-operations-for-mglru.patch added to mm-new branch

The patch titled Subject: mm/damon: convert to LRU refs based operations for MGLRU has been added to the -mm mm-new branch. Its filename is…

The patch titled
Subject: mm/damon: convert to LRU refs based operations for MGLRU
has been added to the -mm mm-new branch. Its filename is
mm-damon-convert-to-lru-refs-based-operations-for-mglru.patch

This patch will shortly appear at
https://git.kernel.org/pub/scm/linux/kernel/git/akpm/25-new.git/tree/patches/mm-damon-convert-to-lru-refs-based-operations-for-mglru.patch

This patch will later appear in the mm-new branch at
git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm

Note, mm-new is a provisional staging ground for work-in-progress patches, and acceptance into mm-new is a notification for others take notice and to finish up reviews. Please do not hesitate to respond to review feedback and post updated versions to replace or incrementally fixup patches in mm-new.

The mm-new branch of mm.git is not included in linux-next

If a few days of testing in mm-new is successful, the patch will me moved into mm.git's mm-unstable branch, which is included in linux-next

Before you just go and hit "reply", please:
a) Consider who else should be cc'ed
b) Prefer to cc a suitable mailing list as well
c) Ideally: find the original patch on the mailing list and do a reply-to-all to that, adding suitable additional cc's

*** Remember to use Documentation/process/submit-checklist.rst when testing your code ***

The -mm tree is included into linux-next via various branches at git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm
and is updated there most days

------------------------------------------------------
From: Kairui Song <[email protected]>
Subject: mm/damon: convert to LRU refs based operations for MGLRU
Date: Wed, 02 Dec 2026 04:18:52 +0800

damon_pa_pageout() cleared PG_referenced directly, which under MGLRU corrupts the folio's refs count. That flag is now
bit 0 of the count (LRU_REFS_FLAGS).

Reset the count instead under MGLRU, with folio_clear_lru_refs(), which also clears PG_young.

Cc Johannes Weiner <[email protected]>
Cc Muchun Song <[email protected]>
Cc Qi Zheng <[email protected]>
Cc Ying Huang <[email protected]>
Cc Christopher Li <[email protected]>
Cc Baoquan He <[email protected]>
Cc Nico Pache <[email protected]>
Cc Usama Arif <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Roman Gushchin <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Barry Song <[email protected]>
Cc Axel Rasmussen <[email protected]>
Cc Yuanchu Xie <[email protected]>
Cc Wei Xu <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Nhat Pham <[email protected]>
Cc Youngjun Park <[email protected]>
Cc Zi Yan <[email protected]>
Cc Gregory Price <[email protected]>
Cc Matthew Wilcox (Oracle) <[email protected]>
Cc Baolin Wang <[email protected]>
Cc Ryan Roberts <[email protected]>
Cc Dev Jain <[email protected]>
Cc Lance Yang <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc SJ Park <[email protected]>
Cc David Rientjes <[email protected]>
Cc Yu Zhao <[email protected]>
Cc Vernon Yang <[email protected]>
Cc wangzicheng <[email protected]>
Cc Tal Zussman <[email protected]>
Cc Kairui Song <[email protected]>
Cc Xiang Liu <[email protected]>
Cc Ehab Ababneh <[email protected]>
Cc wang lian <[email protected]>
Cc Joanne Koong <[email protected]>
Cc Hui Zhu <[email protected]>
Cc Maxim Muzafarov <[email protected]>
Cc Tianyi Chen <[email protected]>
Cc Ridong Chen <[email protected]>
 mm/damon/paddr.c |    4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
mm/damon/paddr.c renamed from mm/damon/paddr.c~mm-damon-convert-to-lru-refs-based-operations-for-mglru +2 -2
@@ -290,8 +290,8 @@ static unsigned long damon_pa_pageout(st
 		else
 			*sz_filter_passed += folio_size(folio) / addr_unit;
 
-		folio_clear_referenced(folio);
-		folio_test_clear_young(folio);
+		/* The region is cold, better drop the hotness info. */
+		folio_clear_lru_refs(folio);
 		if (!folio_isolate_lru(folio))
 			goto put_folio;
 		if (folio_test_unevictable(folio))

_

Patches currently in -mm which might be from [email protected] are

mm-mglru-report-evictable-sizes-per-type.patch mm-mglru-extract-lruvec_populated_min_seq-helper.patch mm-mglru-reclaim-from-the-oldest-populated-gen.patch mm-mglru-lift-the-forced-protection-of-reclaimer.patch mm-mglru-skip-zones-above-reclaim_idx-instead-of-rotating-them.patch mm-mglru-return-for-unavailable-anon-reclaim-earlier.patch mm-mglru-balance-anon-and-file-scan-budget-by-refault-rate.patch mm-mglru-lift-youngest-gen-protection-for-higher-priority.patch mm-memcontrol-allow-update-of-lru-statistic-without-holding-lru-lock.patch mm-memcontrol-avoid-potential-counter-leak-when-reparenting-local-stats.patch mm-mglru-make-generation-page-counters-atomic.patch mm-memcg-add-folio-based-lruvec-live-helper.patch mm-mglru-frequency-guided-workingset-promotion-mglru-fg.patch mm-mglru-make-folio-lru-referenced-times-count-a-generic-api.patch mm-mglru-move-add-del-lru-size-accounting-out-of-lru_gen_update_size.patch mm-mglru-gup-mark-folios-referenced-via-a-fast-helper.patch mm-mglru-smaps-convert-to-lru-refs-based-operations-for-mglru.patch mm-damon-convert-to-lru-refs-based-operations-for-mglru.patch mm-khugepaged-convert-to-lru-refs-based-operations-for-mglru.patch mm-madvise-adapt-for-lru-refs-based-operations-for-mglru.patch mm-factor-out-folio_mark_accessed_vma.patch mm-huge_memory-mark-folio-as-accessed-more-accurately-on-split.patch mm-mglru-make-pg_workingset-helpers-work-based-on-folio-lru-refs.patch mm-mglru-folio-lru-refs-based-active-inactive-number-accounting.patch mm-mglru-make-folio_inc_lru_refs-lruvec-lockless.patch

maintainer Reviewed-by on v7 12/19
#25 lore raw

Re: [PATCH v7 12/19] mm/damon: convert to LRU refs based operations for MGLRU

In reply to Kairui Song
Quoted 8 lines · On Wed, 02 Dec 2026 04:18:52 +0800 Kairui Song via B4 Relay…

From: Kairui Song <[email protected]>

damon_pa_pageout() cleared PG_referenced directly, which under MGLRU corrupts the folio's refs count. That flag is now
bit 0 of the count (LRU_REFS_FLAGS).

Reset the count instead under MGLRU, with folio_clear_lru_refs(), which also clears PG_young.

Looks good to me, thank you!

Quoted 5 lines

Thanks,
SJ

[...]

author maintainer
#26 lore raw

PATCH v7 13/19 mm/khugepaged: convert to LRU refs based operations for MGLRU

In reply to Kairui Song

For MGLRU, PG_referenced is only the lowest bit of the folio LRU refs count, so folios with nonzero even refs no longer have the bit set. folio_pte_referenced() testing the raw bit misses hot folios at refs 2, 4 or 6, 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 with folio_test_lru_refs(), which also covers PG_young. The classical LRU keeps the plain bit test.

---
 mm/khugepaged.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
mm/khugepaged.c +1 -1
index c27c967d3b66..9fdbf2f148e2 100644
@@ -579,7 +579,7 @@ 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_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.1
maintainer tree notice
#27 lore raw

+ mm-khugepaged-convert-to-lru-refs-based-operations-for-mglru.patch added to mm-new branch

The patch titled Subject: mm/khugepaged: convert to LRU refs based operations for MGLRU has been added to the -mm mm-new branch. Its filename is…

The patch titled
Subject: mm/khugepaged: convert to LRU refs based operations for MGLRU
has been added to the -mm mm-new branch. Its filename is
mm-khugepaged-convert-to-lru-refs-based-operations-for-mglru.patch

This patch will shortly appear at
https://git.kernel.org/pub/scm/linux/kernel/git/akpm/25-new.git/tree/patches/mm-khugepaged-convert-to-lru-refs-based-operations-for-mglru.patch

This patch will later appear in the mm-new branch at
git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm

Note, mm-new is a provisional staging ground for work-in-progress patches, and acceptance into mm-new is a notification for others take notice and to finish up reviews. Please do not hesitate to respond to review feedback and post updated versions to replace or incrementally fixup patches in mm-new.

The mm-new branch of mm.git is not included in linux-next

If a few days of testing in mm-new is successful, the patch will me moved into mm.git's mm-unstable branch, which is included in linux-next

Before you just go and hit "reply", please:
a) Consider who else should be cc'ed
b) Prefer to cc a suitable mailing list as well
c) Ideally: find the original patch on the mailing list and do a reply-to-all to that, adding suitable additional cc's

*** Remember to use Documentation/process/submit-checklist.rst when testing your code ***

The -mm tree is included into linux-next via various branches at git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm
and is updated there most days

------------------------------------------------------
From: Kairui Song <[email protected]>
Subject: mm/khugepaged: convert to LRU refs based operations for MGLRU
Date: Wed, 02 Dec 2026 04:18:53 +0800

For MGLRU, PG_referenced is only the lowest bit of the folio LRU refs count, so folios with nonzero even refs no longer have the bit set. folio_pte_referenced() testing the raw bit misses hot folios at refs 2, 4 or 6, 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 with folio_test_lru_refs(), which also covers PG_young. The classical LRU keeps the plain bit test.

Cc Johannes Weiner <[email protected]>
Cc Muchun Song <[email protected]>
Cc Qi Zheng <[email protected]>
Cc Ying Huang <[email protected]>
Cc Christopher Li <[email protected]>
Cc Baoquan He <[email protected]>
Cc Nico Pache <[email protected]>
Cc Usama Arif <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Roman Gushchin <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Barry Song <[email protected]>
Cc Axel Rasmussen <[email protected]>
Cc Yuanchu Xie <[email protected]>
Cc Wei Xu <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Nhat Pham <[email protected]>
Cc Youngjun Park <[email protected]>
Cc Zi Yan <[email protected]>
Cc Gregory Price <[email protected]>
Cc Matthew Wilcox (Oracle) <[email protected]>
Cc Baolin Wang <[email protected]>
Cc Ryan Roberts <[email protected]>
Cc Dev Jain <[email protected]>
Cc Lance Yang <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc SJ Park <[email protected]>
Cc David Rientjes <[email protected]>
Cc Yu Zhao <[email protected]>
Cc Vernon Yang <[email protected]>
Cc wangzicheng <[email protected]>
Cc Tal Zussman <[email protected]>
Cc Kairui Song <[email protected]>
Cc Xiang Liu <[email protected]>
Cc Ehab Ababneh <[email protected]>
Cc wang lian <[email protected]>
Cc Joanne Koong <[email protected]>
Cc Hui Zhu <[email protected]>
Cc Maxim Muzafarov <[email protected]>
Cc Tianyi Chen <[email protected]>
Cc Ridong Chen <[email protected]>
 mm/khugepaged.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
mm/khugepaged.c renamed from mm/khugepaged.c~mm-khugepaged-convert-to-lru-refs-based-operations-for-mglru +1 -1
@@ -579,7 +579,7 @@ static bool folio_pte_referenced(struct
 		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_lru_refs(folio))
 		return true;
 	/* ... or the PTE mapping was recently used */
 	return pte_young(pteval) || mmu_notifier_test_young(vma->vm_mm, addr);

_

Patches currently in -mm which might be from [email protected] are

mm-mglru-report-evictable-sizes-per-type.patch mm-mglru-extract-lruvec_populated_min_seq-helper.patch mm-mglru-reclaim-from-the-oldest-populated-gen.patch mm-mglru-lift-the-forced-protection-of-reclaimer.patch mm-mglru-skip-zones-above-reclaim_idx-instead-of-rotating-them.patch mm-mglru-return-for-unavailable-anon-reclaim-earlier.patch mm-mglru-balance-anon-and-file-scan-budget-by-refault-rate.patch mm-mglru-lift-youngest-gen-protection-for-higher-priority.patch mm-memcontrol-allow-update-of-lru-statistic-without-holding-lru-lock.patch mm-memcontrol-avoid-potential-counter-leak-when-reparenting-local-stats.patch mm-mglru-make-generation-page-counters-atomic.patch mm-memcg-add-folio-based-lruvec-live-helper.patch mm-mglru-frequency-guided-workingset-promotion-mglru-fg.patch mm-mglru-make-folio-lru-referenced-times-count-a-generic-api.patch mm-mglru-move-add-del-lru-size-accounting-out-of-lru_gen_update_size.patch mm-mglru-gup-mark-folios-referenced-via-a-fast-helper.patch mm-mglru-smaps-convert-to-lru-refs-based-operations-for-mglru.patch mm-damon-convert-to-lru-refs-based-operations-for-mglru.patch mm-khugepaged-convert-to-lru-refs-based-operations-for-mglru.patch mm-madvise-adapt-for-lru-refs-based-operations-for-mglru.patch mm-factor-out-folio_mark_accessed_vma.patch mm-huge_memory-mark-folio-as-accessed-more-accurately-on-split.patch mm-mglru-make-pg_workingset-helpers-work-based-on-folio-lru-refs.patch mm-mglru-folio-lru-refs-based-active-inactive-number-accounting.patch mm-mglru-make-folio_inc_lru_refs-lruvec-lockless.patch

author maintainer
#28 lore raw

PATCH v7 14/19 mm/madvise: adapt for LRU refs based operations for MGLRU

In reply to Kairui Song

For 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 requests deactivation.
- MADV_PAGEOUT clears non-workingset refs and caps the rest at LRU_REFS_WORKINGSET after isolation, 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 | 50 ++++++++++++++++++++++++++++++++++++--------------
 1 file changed, 36 insertions(+), 14 deletions(-)
mm/madvise.c +36 -14
index 66600e82605c..c6c2e8189f4b 100644
@@ -359,6 +359,38 @@ 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)
+{
+	/*
+	 * 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. For MGLRU, MADV_COLD clears
+	 * refs in folio_deactivate(); MADV_PAGEOUT handles refs after isolation.
+	 */
+	if (!lru_gen_enabled()) {
+		folio_clear_lru_refs(folio);
+		if (folio_test_active(folio))
+			folio_set_workingset(folio);
+	} else {
+		folio_test_clear_young(folio);
+	}
+}
+
+static void madvise_pageout_prep_folio(struct folio *folio)
+{
+	unsigned int refs = folio_lru_refs(folio);
+
+	/*
+	 * For MGLRU, clear refs below LRU_REFS_WORKINGSET and cap
+	 * the rest at it: MADV suggests the folio is 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)
@@ -433,12 +465,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
@@ -543,18 +573,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.1
#29 lore raw

Re: [PATCH v7 14/19] mm/madvise: adapt for LRU refs based operations for MGLRU

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] mm/madvise: open-coded LRU and MGLRU ref manipulation in mm/madvise.c --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] mm/madvise: open-coded LRU and MGLRU ref manipulation in mm/madvise.c
--

commit afb8e93f4729e4e9ddecb1a2901862b67ca1c853
Author: Kairui Song <[email protected]>

mm/madvise: adapt for LRU refs based operations for MGLRU

This commit introduces madvise_cold_prep_folio() and madvise_pageout_prep_folio() in mm/madvise.c so that MADV_COLD and MADV_PAGEOUT update folio LRU reference counts and workingset state appropriately for both classical LRU and MGLRU.

Quoted 29 lines
mm/madvise.c +21 -0
index 66600e82605c2..c6c2e8189f4b1 100644
@@ -359,6 +359,38 @@ 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)
+{
+	/*
+	 * 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. For MGLRU, MADV_COLD clears
+	 * refs in folio_deactivate(); MADV_PAGEOUT handles refs after isolation.
+	 */
+	if (!lru_gen_enabled()) {
+		folio_clear_lru_refs(folio);
+		if (folio_test_active(folio))
+			folio_set_workingset(folio);
+	} else {
+		folio_test_clear_young(folio);
+	}
+}
+
+static void madvise_pageout_prep_folio(struct folio *folio)
+{
+	unsigned int refs = folio_lru_refs(folio);

mm/madvise.c static inline int madvise_folio_pte_batch(unsigned long addr, unsigned long end, · line 392

Quoted 10 lines
mm/madvise.c +10 -0
+
+	/*
+	 * For MGLRU, clear refs below LRU_REFS_WORKINGSET and cap
+	 * the rest at it: MADV suggests the folio is 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);
+}

[Severity: Low]
As reported by David Hildenbrand (Arm) on v6 [1], can the LRU and MGLRU reference, workingset, and young state handling in madvise_cold_prep_folio() and madvise_pageout_prep_folio() be moved into folio or reclaim helpers so mm/madvise.c does not have to branch on lru_gen_enabled() and manipulate LRU internals directly?

[1] https://lore.kernel.org/r/[email protected]

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

Re: [PATCH v7 14/19] mm/madvise: adapt for LRU refs based operations for MGLRU

Quoted 63 lines · On Tue, Dec 01, 2026 at 08:31:15PM +0800, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] mm/madvise: open-coded LRU and MGLRU ref manipulation in mm/madvise.c
--

commit afb8e93f4729e4e9ddecb1a2901862b67ca1c853
Author: Kairui Song <[email protected]>

mm/madvise: adapt for LRU refs based operations for MGLRU

This commit introduces madvise_cold_prep_folio() and madvise_pageout_prep_folio() in mm/madvise.c so that MADV_COLD and MADV_PAGEOUT update folio LRU reference counts and workingset state appropriately for both classical LRU and MGLRU.

Quoted 29 lines
mm/madvise.c +21 -0
index 66600e82605c2..c6c2e8189f4b1 100644
@@ -359,6 +359,38 @@ 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)
+{
+	/*
+	 * 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. For MGLRU, MADV_COLD clears
+	 * refs in folio_deactivate(); MADV_PAGEOUT handles refs after isolation.
+	 */
+	if (!lru_gen_enabled()) {
+		folio_clear_lru_refs(folio);
+		if (folio_test_active(folio))
+			folio_set_workingset(folio);
+	} else {
+		folio_test_clear_young(folio);
+	}
+}
+
+static void madvise_pageout_prep_folio(struct folio *folio)
+{
+	unsigned int refs = folio_lru_refs(folio);

mm/madvise.c static inline int madvise_folio_pte_batch(unsigned long addr, unsigned long end, · line 392

Quoted 10 lines
mm/madvise.c +10 -0
+
+	/*
+	 * For MGLRU, clear refs below LRU_REFS_WORKINGSET and cap
+	 * the rest at it: MADV suggests the folio is 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);
+}

[Severity: Low]
As reported by David Hildenbrand (Arm) on v6 [1], can the LRU and MGLRU reference, workingset, and young state handling in madvise_cold_prep_folio() and madvise_pageout_prep_folio() be moved into folio or reclaim helpers so mm/madvise.c does not have to branch on lru_gen_enabled() and manipulate LRU internals directly?

Quoted 1 line

[1] https://lore.kernel.org/r/[email protected]

This is not really an issue, it's a clean up, we will do later. A proper cleanup may need more attention and review too since it may change some more generic helpers.

maintainer tree notice
#31 lore raw

+ mm-madvise-adapt-for-lru-refs-based-operations-for-mglru.patch added to mm-new branch

In reply to Kairui Song
The patch titled Subject: mm/madvise: adapt for LRU refs based operations for MGLRU has been added to the -mm mm-new branch. Its filename is…

The patch titled
Subject: mm/madvise: adapt for LRU refs based operations for MGLRU
has been added to the -mm mm-new branch. Its filename is
mm-madvise-adapt-for-lru-refs-based-operations-for-mglru.patch

This patch will shortly appear at
https://git.kernel.org/pub/scm/linux/kernel/git/akpm/25-new.git/tree/patches/mm-madvise-adapt-for-lru-refs-based-operations-for-mglru.patch

This patch will later appear in the mm-new branch at
git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm

Note, mm-new is a provisional staging ground for work-in-progress patches, and acceptance into mm-new is a notification for others take notice and to finish up reviews. Please do not hesitate to respond to review feedback and post updated versions to replace or incrementally fixup patches in mm-new.

The mm-new branch of mm.git is not included in linux-next

If a few days of testing in mm-new is successful, the patch will me moved into mm.git's mm-unstable branch, which is included in linux-next

Before you just go and hit "reply", please:
a) Consider who else should be cc'ed
b) Prefer to cc a suitable mailing list as well
c) Ideally: find the original patch on the mailing list and do a reply-to-all to that, adding suitable additional cc's

*** Remember to use Documentation/process/submit-checklist.rst when testing your code ***

The -mm tree is included into linux-next via various branches at git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm
and is updated there most days

------------------------------------------------------
From: Kairui Song <[email protected]>
Subject: mm/madvise: adapt for LRU refs based operations for MGLRU
Date: Wed, 02 Dec 2026 04:18:54 +0800

For 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 requests deactivation.
- MADV_PAGEOUT clears non-workingset refs and caps the rest at LRU_REFS_WORKINGSET after isolation, 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.

Cc Johannes Weiner <[email protected]>
Cc Muchun Song <[email protected]>
Cc Qi Zheng <[email protected]>
Cc Ying Huang <[email protected]>
Cc Christopher Li <[email protected]>
Cc Baoquan He <[email protected]>
Cc Nico Pache <[email protected]>
Cc Usama Arif <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Roman Gushchin <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Barry Song <[email protected]>
Cc Axel Rasmussen <[email protected]>
Cc Yuanchu Xie <[email protected]>
Cc Wei Xu <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Nhat Pham <[email protected]>
Cc Youngjun Park <[email protected]>
Cc Zi Yan <[email protected]>
Cc Gregory Price <[email protected]>
Cc Matthew Wilcox (Oracle) <[email protected]>
Cc Baolin Wang <[email protected]>
Cc Ryan Roberts <[email protected]>
Cc Dev Jain <[email protected]>
Cc Lance Yang <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc SJ Park <[email protected]>
Cc David Rientjes <[email protected]>
Cc Yu Zhao <[email protected]>
Cc Vernon Yang <[email protected]>
Cc wangzicheng <[email protected]>
Cc Tal Zussman <[email protected]>
Cc Kairui Song <[email protected]>
Cc Xiang Liu <[email protected]>
Cc Ehab Ababneh <[email protected]>
Cc zhaozhengzhuo <[email protected]>
Cc wang lian <[email protected]>
Cc Joanne Koong <[email protected]>
Cc Hui Zhu <[email protected]>
Cc Maxim Muzafarov <[email protected]>
Cc Tianyi Chen <[email protected]>
Cc Ridong Chen <[email protected]>
 mm/madvise.c |   50 +++++++++++++++++++++++++++++++++++--------------
 1 file changed, 36 insertions(+), 14 deletions(-)
mm/madvise.c renamed from mm/madvise.c~mm-madvise-adapt-for-lru-refs-based-operations-for-mglru +36 -14
@@ -368,6 +368,38 @@ static inline int madvise_folio_pte_batc
 				     FPB_MERGE_YOUNG_DIRTY);
 }
 
+static void madvise_cold_prep_folio(struct folio *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. For MGLRU, MADV_COLD clears
+	 * refs in folio_deactivate(); MADV_PAGEOUT handles refs after isolation.
+	 */
+	if (!lru_gen_enabled()) {
+		folio_clear_lru_refs(folio);
+		if (folio_test_active(folio))
+			folio_set_workingset(folio);
+	} else {
+		folio_test_clear_young(folio);
+	}
+}
+
+static void madvise_pageout_prep_folio(struct folio *folio)
+{
+	unsigned int refs = folio_lru_refs(folio);
+
+	/*
+	 * For MGLRU, clear refs below LRU_REFS_WORKINGSET and cap
+	 * the rest at it: MADV suggests the folio is 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)
@@ -442,12 +474,10 @@ static int madvise_cold_or_pageout_pte_r
 			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
@@ -552,18 +582,10 @@ restart:
 			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

_

Patches currently in -mm which might be from [email protected] are

mm-mglru-report-evictable-sizes-per-type.patch mm-mglru-extract-lruvec_populated_min_seq-helper.patch mm-mglru-reclaim-from-the-oldest-populated-gen.patch mm-mglru-lift-the-forced-protection-of-reclaimer.patch mm-mglru-skip-zones-above-reclaim_idx-instead-of-rotating-them.patch mm-mglru-return-for-unavailable-anon-reclaim-earlier.patch mm-mglru-balance-anon-and-file-scan-budget-by-refault-rate.patch mm-mglru-lift-youngest-gen-protection-for-higher-priority.patch mm-memcontrol-allow-update-of-lru-statistic-without-holding-lru-lock.patch mm-memcontrol-avoid-potential-counter-leak-when-reparenting-local-stats.patch mm-mglru-make-generation-page-counters-atomic.patch mm-memcg-add-folio-based-lruvec-live-helper.patch mm-mglru-frequency-guided-workingset-promotion-mglru-fg.patch mm-mglru-make-folio-lru-referenced-times-count-a-generic-api.patch mm-mglru-move-add-del-lru-size-accounting-out-of-lru_gen_update_size.patch mm-mglru-gup-mark-folios-referenced-via-a-fast-helper.patch mm-mglru-smaps-convert-to-lru-refs-based-operations-for-mglru.patch mm-damon-convert-to-lru-refs-based-operations-for-mglru.patch mm-khugepaged-convert-to-lru-refs-based-operations-for-mglru.patch mm-madvise-adapt-for-lru-refs-based-operations-for-mglru.patch mm-factor-out-folio_mark_accessed_vma.patch mm-huge_memory-mark-folio-as-accessed-more-accurately-on-split.patch mm-mglru-make-pg_workingset-helpers-work-based-on-folio-lru-refs.patch mm-mglru-folio-lru-refs-based-active-inactive-number-accounting.patch mm-mglru-make-folio_inc_lru_refs-lruvec-lockless.patch

author maintainer
#32 lore raw

PATCH v7 15/19 mm: factor out folio_mark_accessed_vma()

In reply to Kairui Song

The zap paths translate a young page table entry into folio hotness with folio_mark_accessed(), but only for a VMA with recency: vma_has_recency() is false for VM_SEQ_READ, VM_RAND_READ and FMODE_NOREUSE areas, where an access carries no recency info by definition. [1]

Factor that rule out into folio_mark_accessed_vma(), so it lives in one place instead of in every page table walk that feeds the LRU, and convert the two zap paths. The huge mapping split paths will follow.

No functional change.

---
 include/linux/mm_inline.h | 12 ++++++++++++
 mm/huge_memory.c          |  5 ++---
 mm/memory.c               |  4 ++--
 3 files changed, 16 insertions(+), 5 deletions(-)
include/linux/mm_inline.h +12 -0
index d3f0c29ac340..65bf16503b8b 100644
@@ -797,6 +797,18 @@ static inline bool vma_has_recency(const struct vm_area_struct *vma)
 
 	return true;
 }
+
+/*
+ * Mark a folio accessed if the VMA has recency: accesses to a VM_SEQ_READ,
+ * VM_RAND_READ or FMODE_NOREUSE mapping do not predict reuse, so bumping
+ * the folio's LRU refs for them may even hurt the performance.
+ */
+static inline void folio_mark_accessed_vma(struct folio *folio,
+					   const struct vm_area_struct *vma)
+{
+	if (likely(vma_has_recency(vma)))
+		folio_mark_accessed(folio);
+}
 #endif
 
 /**
mm/huge_memory.c +2 -3
index 4fc888ddfb69..7c535d3bc501 100644
@@ -2525,9 +2525,8 @@ static void zap_huge_pmd_folio(struct mmu_gather *tlb, struct vm_area_struct *vm
 			    mapping_can_writeback(vma->vm_file->f_mapping))
 				delay_rmap = tlb_can_delay_rmap();
 		}
-		if (is_present && pmd_young(pmdval) &&
-		    likely(vma_has_recency(vma)))
-			folio_mark_accessed(folio);
+		if (is_present && pmd_young(pmdval))
+			folio_mark_accessed_vma(folio, vma);
 	}
 
 	if (!is_present && !is_device_private)
mm/memory.c +2 -2
index 82e1ec8e44e7..a6b15a4b7ca9 100644
@@ -1761,8 +1761,8 @@ static __always_inline void zap_present_folio_ptes(struct mmu_gather *tlb,
 				*force_flush = true;
 			}
 		}
-		if (pte_young(ptent) && likely(vma_has_recency(vma)))
-			folio_mark_accessed(folio);
+		if (pte_young(ptent))
+			folio_mark_accessed_vma(folio, vma);
 		rss[mm_counter(folio)] -= nr;
 	} else {
 		/* We don't need up-to-date accessed/dirty bits. */
Signature · 1 line
2.56.1
maintainer tree notice
#33 lore raw

+ mm-factor-out-folio_mark_accessed_vma.patch added to mm-new branch

The patch titled Subject: mm: factor out folio_mark_accessed_vma() has been added to the -mm mm-new branch. Its filename is mm-factor-out-folio_mark_accessed_vma.patch

The patch titled
Subject: mm: factor out folio_mark_accessed_vma()
has been added to the -mm mm-new branch. Its filename is
mm-factor-out-folio_mark_accessed_vma.patch

This patch will shortly appear at
https://git.kernel.org/pub/scm/linux/kernel/git/akpm/25-new.git/tree/patches/mm-factor-out-folio_mark_accessed_vma.patch

This patch will later appear in the mm-new branch at
git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm

Note, mm-new is a provisional staging ground for work-in-progress patches, and acceptance into mm-new is a notification for others take notice and to finish up reviews. Please do not hesitate to respond to review feedback and post updated versions to replace or incrementally fixup patches in mm-new.

The mm-new branch of mm.git is not included in linux-next

If a few days of testing in mm-new is successful, the patch will me moved into mm.git's mm-unstable branch, which is included in linux-next

Before you just go and hit "reply", please:
a) Consider who else should be cc'ed
b) Prefer to cc a suitable mailing list as well
c) Ideally: find the original patch on the mailing list and do a reply-to-all to that, adding suitable additional cc's

*** Remember to use Documentation/process/submit-checklist.rst when testing your code ***

The -mm tree is included into linux-next via various branches at git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm
and is updated there most days

------------------------------------------------------
From: Kairui Song <[email protected]>
Subject: mm: factor out folio_mark_accessed_vma()
Date: Wed, 02 Dec 2026 04:18:55 +0800

The zap paths translate a young page table entry into folio hotness with folio_mark_accessed(), but only for a VMA with recency: vma_has_recency() is false for VM_SEQ_READ, VM_RAND_READ and FMODE_NOREUSE areas, where an access carries no recency info by definition. [1]

Factor that rule out into folio_mark_accessed_vma(), so it lives in one place instead of in every page table walk that feeds the LRU, and convert the two zap paths. The huge mapping split paths will follow.

No functional change.

Cc Johannes Weiner <[email protected]>
Cc Muchun Song <[email protected]>
Cc Qi Zheng <[email protected]>
Cc Ying Huang <[email protected]>
Cc Christopher Li <[email protected]>
Cc Baoquan He <[email protected]>
Cc Nico Pache <[email protected]>
Cc Usama Arif <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Roman Gushchin <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Barry Song <[email protected]>
Cc Axel Rasmussen <[email protected]>
Cc Yuanchu Xie <[email protected]>
Cc Wei Xu <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Nhat Pham <[email protected]>
Cc Youngjun Park <[email protected]>
Cc Zi Yan <[email protected]>
Cc Gregory Price <[email protected]>
Cc Matthew Wilcox (Oracle) <[email protected]>
Cc Baolin Wang <[email protected]>
Cc Ryan Roberts <[email protected]>
Cc Dev Jain <[email protected]>
Cc Lance Yang <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc SJ Park <[email protected]>
Cc David Rientjes <[email protected]>
Cc Yu Zhao <[email protected]>
Cc Vernon Yang <[email protected]>
Cc wangzicheng <[email protected]>
Cc Tal Zussman <[email protected]>
Cc Kairui Song <[email protected]>
Cc Xiang Liu <[email protected]>
Cc Ehab Ababneh <[email protected]>
Cc zhaozhengzhuo <[email protected]>
Cc wang lian <[email protected]>
Cc Joanne Koong <[email protected]>
Cc Kunwu Chan <[email protected]>
Cc Hui Zhu <[email protected]>
Cc Maxim Muzafarov <[email protected]>
Cc Tianyi Chen <[email protected]>
Cc Ridong Chen <[email protected]>
 include/linux/mm_inline.h |   12 ++++++++++++
 mm/huge_memory.c          |    5 ++---
 mm/memory.c               |    4 ++--
 3 files changed, 16 insertions(+), 5 deletions(-)
include/linux/mm_inline.h renamed from include/linux/mm_inline.h~mm-factor-out-folio_mark_accessed_vma +12 -0
@@ -797,6 +797,18 @@ static inline bool vma_has_recency(const
 
 	return true;
 }
+
+/*
+ * Mark a folio accessed if the VMA has recency: accesses to a VM_SEQ_READ,
+ * VM_RAND_READ or FMODE_NOREUSE mapping do not predict reuse, so bumping
+ * the folio's LRU refs for them may even hurt the performance.
+ */
+static inline void folio_mark_accessed_vma(struct folio *folio,
+					   const struct vm_area_struct *vma)
+{
+	if (likely(vma_has_recency(vma)))
+		folio_mark_accessed(folio);
+}
 #endif
 
 /**
mm/huge_memory.c renamed from mm/huge_memory.c~mm-factor-out-folio_mark_accessed_vma +2 -3
@@ -2525,9 +2525,8 @@ static void zap_huge_pmd_folio(struct mm
 			    mapping_can_writeback(vma->vm_file->f_mapping))
 				delay_rmap = tlb_can_delay_rmap();
 		}
-		if (is_present && pmd_young(pmdval) &&
-		    likely(vma_has_recency(vma)))
-			folio_mark_accessed(folio);
+		if (is_present && pmd_young(pmdval))
+			folio_mark_accessed_vma(folio, vma);
 	}
 
 	if (!is_present && !is_device_private)
mm/memory.c renamed from mm/memory.c~mm-factor-out-folio_mark_accessed_vma +2 -2
@@ -1762,8 +1762,8 @@ static __always_inline void zap_present_
 				*force_flush = true;
 			}
 		}
-		if (pte_young(ptent) && likely(vma_has_recency(vma)))
-			folio_mark_accessed(folio);
+		if (pte_young(ptent))
+			folio_mark_accessed_vma(folio, vma);
 		rss[mm_counter(folio)] -= nr;
 	} else {
 		/* We don't need up-to-date accessed/dirty bits. */

_

Patches currently in -mm which might be from [email protected] are

mm-mglru-report-evictable-sizes-per-type.patch mm-mglru-extract-lruvec_populated_min_seq-helper.patch mm-mglru-reclaim-from-the-oldest-populated-gen.patch mm-mglru-lift-the-forced-protection-of-reclaimer.patch mm-mglru-skip-zones-above-reclaim_idx-instead-of-rotating-them.patch mm-mglru-return-for-unavailable-anon-reclaim-earlier.patch mm-mglru-balance-anon-and-file-scan-budget-by-refault-rate.patch mm-mglru-lift-youngest-gen-protection-for-higher-priority.patch mm-memcontrol-allow-update-of-lru-statistic-without-holding-lru-lock.patch mm-memcontrol-avoid-potential-counter-leak-when-reparenting-local-stats.patch mm-mglru-make-generation-page-counters-atomic.patch mm-memcg-add-folio-based-lruvec-live-helper.patch mm-mglru-frequency-guided-workingset-promotion-mglru-fg.patch mm-mglru-make-folio-lru-referenced-times-count-a-generic-api.patch mm-mglru-move-add-del-lru-size-accounting-out-of-lru_gen_update_size.patch mm-mglru-gup-mark-folios-referenced-via-a-fast-helper.patch mm-mglru-smaps-convert-to-lru-refs-based-operations-for-mglru.patch mm-damon-convert-to-lru-refs-based-operations-for-mglru.patch mm-khugepaged-convert-to-lru-refs-based-operations-for-mglru.patch mm-madvise-adapt-for-lru-refs-based-operations-for-mglru.patch mm-factor-out-folio_mark_accessed_vma.patch mm-huge_memory-mark-folio-as-accessed-more-accurately-on-split.patch mm-mglru-make-pg_workingset-helpers-work-based-on-folio-lru-refs.patch mm-mglru-folio-lru-refs-based-active-inactive-number-accounting.patch mm-mglru-make-folio_inc_lru_refs-lruvec-lockless.patch

author maintainer
#34 lore raw

PATCH v7 16/19 mm/huge_memory: mark folio as accessed more accurately on split

In reply to Kairui Song

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 checks and sets the folio's referenced flag, which isn't enough since folio flag updates on access have their own rules. Ordinary unmapping (zapping) calls folio_mark_accessed(), but only for a VMA with
recency: vma_has_recency() is false for VM_SEQ_READ, VM_RAND_READ and FMODE_NOREUSE areas, where an access carries no recency info by definition, so a split must not promote such a folio either.

So use folio_mark_accessed_vma() here too, like the zapping paths. Keep accounting the young PTE as a cache access, sticking to the current behavior.

---
 mm/huge_memory.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
mm/huge_memory.c +4 -4
index 7c535d3bc501..fc4ae1efed17 100644
@@ -3112,8 +3112,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))
+		folio_mark_accessed_vma(folio, vma);
 	folio_remove_rmap_pud(folio, page, vma);
 	add_mm_counter(vma->vm_mm, mm_counter_file(folio),
 		-HPAGE_PUD_NR);
@@ -3235,8 +3235,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))
+				folio_mark_accessed_vma(folio, vma);
 			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.1
maintainer tree notice
#35 lore raw

+ mm-huge_memory-mark-folio-as-accessed-more-accurately-on-split.patch added to mm-new branch

The patch titled Subject: mm/huge_memory: mark folio as accessed more accurately on split has been added to the -mm mm-new branch. Its filename is…

The patch titled
Subject: mm/huge_memory: mark folio as accessed more accurately on split
has been added to the -mm mm-new branch. Its filename is
mm-huge_memory-mark-folio-as-accessed-more-accurately-on-split.patch

This patch will shortly appear at
https://git.kernel.org/pub/scm/linux/kernel/git/akpm/25-new.git/tree/patches/mm-huge_memory-mark-folio-as-accessed-more-accurately-on-split.patch

This patch will later appear in the mm-new branch at
git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm

Note, mm-new is a provisional staging ground for work-in-progress patches, and acceptance into mm-new is a notification for others take notice and to finish up reviews. Please do not hesitate to respond to review feedback and post updated versions to replace or incrementally fixup patches in mm-new.

The mm-new branch of mm.git is not included in linux-next

If a few days of testing in mm-new is successful, the patch will me moved into mm.git's mm-unstable branch, which is included in linux-next

Before you just go and hit "reply", please:
a) Consider who else should be cc'ed
b) Prefer to cc a suitable mailing list as well
c) Ideally: find the original patch on the mailing list and do a reply-to-all to that, adding suitable additional cc's

*** Remember to use Documentation/process/submit-checklist.rst when testing your code ***

The -mm tree is included into linux-next via various branches at git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm
and is updated there most days

------------------------------------------------------
From: Kairui Song <[email protected]>
Subject: mm/huge_memory: mark folio as accessed more accurately on split
Date: Wed, 02 Dec 2026 04:18:56 +0800

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 checks and sets the folio's referenced flag, which isn't enough since folio flag updates on access have their own rules. Ordinary unmapping (zapping) calls folio_mark_accessed(), but only for a VMA with
recency: vma_has_recency() is false for VM_SEQ_READ, VM_RAND_READ and FMODE_NOREUSE areas, where an access carries no recency info by definition, so a split must not promote such a folio either.

So use folio_mark_accessed_vma() here too, like the zapping paths. Keep accounting the young PTE as a cache access, sticking to the current behavior.

Cc Johannes Weiner <[email protected]>
Cc Muchun Song <[email protected]>
Cc Qi Zheng <[email protected]>
Cc Ying Huang <[email protected]>
Cc Christopher Li <[email protected]>
Cc Baoquan He <[email protected]>
Cc Nico Pache <[email protected]>
Cc Usama Arif <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Roman Gushchin <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Barry Song <[email protected]>
Cc Axel Rasmussen <[email protected]>
Cc Yuanchu Xie <[email protected]>
Cc Wei Xu <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Nhat Pham <[email protected]>
Cc Youngjun Park <[email protected]>
Cc Gregory Price <[email protected]>
Cc Matthew Wilcox (Oracle) <[email protected]>
Cc Baolin Wang <[email protected]>
Cc Ryan Roberts <[email protected]>
Cc Dev Jain <[email protected]>
Cc Lance Yang <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc SJ Park <[email protected]>
Cc David Rientjes <[email protected]>
Cc Yu Zhao <[email protected]>
Cc Vernon Yang <[email protected]>
Cc wangzicheng <[email protected]>
Cc Tal Zussman <[email protected]>
Cc Kairui Song <[email protected]>
Cc Xiang Liu <[email protected]>
Cc Ehab Ababneh <[email protected]>
Cc Joanne Koong <[email protected]>
Cc Hui Zhu <[email protected]>
Cc Maxim Muzafarov <[email protected]>
Cc Ridong Chen <[email protected]>
 mm/huge_memory.c |    8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
mm/huge_memory.c renamed from mm/huge_memory.c~mm-huge_memory-mark-folio-as-accessed-more-accurately-on-split +4 -4
@@ -3112,8 +3112,8 @@ static void __split_huge_pud_locked(stru
 
 	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))
+		folio_mark_accessed_vma(folio, vma);
 	folio_remove_rmap_pud(folio, page, vma);
 	add_mm_counter(vma->vm_mm, mm_counter_file(folio),
 		-HPAGE_PUD_NR);
@@ -3235,8 +3235,8 @@ static void __split_huge_pmd_locked(stru
 			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))
+				folio_mark_accessed_vma(folio, vma);
 			folio_remove_rmap_pmd(folio, page, vma);
 			add_mm_counter(mm, mm_counter_file(folio), -HPAGE_PMD_NR);
 			folio_put(folio);

_

Patches currently in -mm which might be from [email protected] are

mm-mglru-report-evictable-sizes-per-type.patch mm-mglru-extract-lruvec_populated_min_seq-helper.patch mm-mglru-reclaim-from-the-oldest-populated-gen.patch mm-mglru-lift-the-forced-protection-of-reclaimer.patch mm-mglru-skip-zones-above-reclaim_idx-instead-of-rotating-them.patch mm-mglru-return-for-unavailable-anon-reclaim-earlier.patch mm-mglru-balance-anon-and-file-scan-budget-by-refault-rate.patch mm-mglru-lift-youngest-gen-protection-for-higher-priority.patch mm-memcontrol-allow-update-of-lru-statistic-without-holding-lru-lock.patch mm-memcontrol-avoid-potential-counter-leak-when-reparenting-local-stats.patch mm-mglru-make-generation-page-counters-atomic.patch mm-memcg-add-folio-based-lruvec-live-helper.patch mm-mglru-frequency-guided-workingset-promotion-mglru-fg.patch mm-mglru-make-folio-lru-referenced-times-count-a-generic-api.patch mm-mglru-move-add-del-lru-size-accounting-out-of-lru_gen_update_size.patch mm-mglru-gup-mark-folios-referenced-via-a-fast-helper.patch mm-mglru-smaps-convert-to-lru-refs-based-operations-for-mglru.patch mm-damon-convert-to-lru-refs-based-operations-for-mglru.patch mm-khugepaged-convert-to-lru-refs-based-operations-for-mglru.patch mm-madvise-adapt-for-lru-refs-based-operations-for-mglru.patch mm-factor-out-folio_mark_accessed_vma.patch mm-huge_memory-mark-folio-as-accessed-more-accurately-on-split.patch mm-mglru-make-pg_workingset-helpers-work-based-on-folio-lru-refs.patch mm-mglru-folio-lru-refs-based-active-inactive-number-accounting.patch mm-mglru-make-folio_inc_lru_refs-lruvec-lockless.patch

author maintainer
#36 lore raw

PATCH v7 17/19 mm/mglru: make PG_workingset helpers work based on folio LRU refs

In reply to Kairui Song

folio_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 refs 4 or 5 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 earlier generation promotion.

Move both helpers into mm_inline.h, the test as an inline helper based on folio_lru_refs(), checking refs >= LRU_REFS_WORKINGSET.

The set stays reserved for the classical LRU, as under MGLRU the refs count is maintained by folio_inc_lru_refs(): it now warns when the folio is on a gen list, where the raw bit would corrupt its refs count.

The one PageWorkingset() user in erofs is converted to the folio helper.

There is no behavior change for the classical LRU: it does not maintain the refs count, so for a folio that was never on a gen list the test is equivalent to the PG_workingset bit test.

This prepares the convention for follow up MGLRU change.

---
 fs/btrfs/compression.c     |  1 +
 fs/erofs/zdata.c           |  3 ++-
 include/linux/mm_inline.h  | 30 ++++++++++++++++++++++++++++++
 include/linux/page-flags.h |  2 --
 mm/filemap.c               |  1 +
 mm/page_io.c               |  1 +
 6 files changed, 35 insertions(+), 3 deletions(-)
fs/btrfs/compression.c +1 -0
index ad90e14032db..127c5ee38979 100644
@@ -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
index e981e371d6c2..34ee41e1ccdc 100644
@@ -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 +30 -0
index 65bf16503b8b..4dac237f5f57 100644
@@ -306,6 +306,21 @@ 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 flag encoding,
+ * this is just testing the PG_workingset bit.
+ *
+ * Return: true if the folio is workingset.
+ */
+static __always_inline bool folio_test_workingset(const struct folio *folio)
+{
+	return lru_refs_is_workingset(folio_lru_refs(folio));
+}
+
 #ifdef CONFIG_LRU_GEN
 static inline bool lru_gen_is_old(struct lruvec *lruvec, int type, int gen)
 {
@@ -559,6 +574,21 @@ static inline void folio_clear_lru_refs(struct folio *folio)
 		folio_clear_referenced(folio);
 }
 
+/*
+ * For the classical LRU or isolated folios only: with MGLRU the PG_workingset
+ * bit is part of the folio refs count maintained by folio_inc_lru_refs(),
+ * a raw set would corrupt it.  The warning below catches folios still on a
+ * gen list, the classical paths in the switching window only see off-list ones.
+ */
+static __always_inline void folio_set_workingset(struct folio *folio)
+{
+	unsigned long flags;
+
+	flags = set_mask_bits(folio_flags(folio, 0), BIT(PG_workingset),
+			      BIT(PG_workingset));
+	VM_WARN_ON_ONCE(lru_get_gen_flags(flags) != -1);
+}
+
 static __always_inline
 void lruvec_add_folio(struct lruvec *lruvec, struct folio *folio)
 {
include/linux/page-flags.h +0 -2
index b0ddc652e76c..f6625dc042da 100644
@@ -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
index 64eefcdb24b3..b529d7511cbd 100644
@@ -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
index a57cdcf2892d..12deab296718 100644
@@ -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.1
#37 lore raw

Re: [PATCH v7 17/19] mm/mglru: make PG_workingset helpers work based on folio LRU refs

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] mm/mglru: race in madvise_cold_prep_folio() calling folio_set_workingset() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] mm/mglru: race in madvise_cold_prep_folio() calling folio_set_workingset()
--

commit e2fb2c7a825775390cc63d4b84ea016b798c9ab7
Author: Kairui Song <[email protected]>

mm/mglru: make PG_workingset helpers work based on folio LRU refs

This commit replaces the page-flag generated workingset helpers with inline helpers in mm_inline.h so folio_test_workingset() checks the folio LRU refs count and folio_set_workingset() warns if called on a folio on an MGLRU generation list.

Quoted 4 lines
include/linux/mm_inline.h +0 -0
index 65bf16503b8bd..4dac237f5f57a 100644

[ ... ]

Quoted 12 lines
include/linux/mm_inline.h +8 -0
@@ -559,6 +574,21 @@ static inline void folio_clear_lru_refs(struct folio *folio)
 		folio_clear_referenced(folio);
 }
 
+/*
+ * For the classical LRU or isolated folios only: with MGLRU the PG_workingset
+ * bit is part of the folio refs count maintained by folio_inc_lru_refs(),
+ * a raw set would corrupt it.  The warning below catches folios still on a
+ * gen list, the classical paths in the switching window only see off-list ones.
+ */
+static __always_inline void folio_set_workingset(struct folio *folio)
+{

include/linux/mm_inline.h static inline void folio_clear_lru_refs(struct folio *folio) · line 594

Quoted 10 lines
include/linux/mm_inline.h +7 -0
+	unsigned long flags;
+
+	flags = set_mask_bits(folio_flags(folio, 0), BIT(PG_workingset),
+			      BIT(PG_workingset));
+	VM_WARN_ON_ONCE(lru_get_gen_flags(flags) != -1);
+}
+
 static __always_inline
 void lruvec_add_folio(struct lruvec *lruvec, struct folio *folio)
 {

[Severity: Medium]
Can folio_set_workingset() race with lru_gen_change_state(true) when called from madvise_cold_prep_folio(), corrupting the MGLRU refs count and triggering this warning?

Unlike shrink_active_list() and workingset_refault(), which operate on isolated folios, madvise_cold_or_pageout_pte_range() calls madvise_cold_prep_folio() on a mapped on-LRU folio while holding only the page table lock:

mm/madvise.c:madvise_cold_prep_folio() {
	if (!lru_gen_enabled()) {
		folio_clear_lru_refs(folio);
		if (folio_test_active(folio))
			folio_set_workingset(folio);
	} else {

...
}

If MGLRU is enabled concurrently via /sys/kernel/mm/lru_gen/enabled, fill_evictable() can move the folio onto a generation list between folio_test_active() and folio_set_workingset():

CPU0 CPU1
madvise_cold_prep_folio(folio)
!lru_gen_enabled() -> true
folio_clear_lru_refs(folio)
folio_test_active(folio) -> true

                                      lru_gen_change_state(true)
                                        static_branch_enable(&lru_gen_caps[...])
                                        fill_evictable(lruvec)
                                          lru_gen_add_folio(lruvec, folio, ...)
                                            /* clears PG_active, sets gen */
  folio_set_workingset(folio)
    set_mask_bits(..., BIT(PG_workingset))
    VM_WARN_ON_ONCE(gen != -1)  <-- warns and mutates MGLRU refs on-list

Because set_mask_bits() unconditionally sets BIT(PG_workingset), it modifies bit 1 of the MGLRU refs encoding while the folio is on a generation list. With the per-folio active/inactive accounting in commit "mm/mglru: folio LRU refs based active/inactive number accounting", if the folio reached refs == 1 before folio_set_workingset() ran, setting BIT(PG_workingset) bumps refs to 3 (LRU_REFS_ACTIVATED) without updating the active/inactive LRU size counters, causing permanent NR_ACTIVE and NR_INACTIVE counter drift.

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

Re: [PATCH v7 17/19] mm/mglru: make PG_workingset helpers work based on folio LRU refs

Quoted 81 lines · On Tue, Dec 01, 2026 at 08:35:26PM +0800, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] mm/mglru: race in madvise_cold_prep_folio() calling folio_set_workingset()
--

commit e2fb2c7a825775390cc63d4b84ea016b798c9ab7
Author: Kairui Song <[email protected]>

mm/mglru: make PG_workingset helpers work based on folio LRU refs

This commit replaces the page-flag generated workingset helpers with inline helpers in mm_inline.h so folio_test_workingset() checks the folio LRU refs count and folio_set_workingset() warns if called on a folio on an MGLRU generation list.

Quoted 4 lines
include/linux/mm_inline.h +0 -0
index 65bf16503b8bd..4dac237f5f57a 100644

[ ... ]

Quoted 12 lines
include/linux/mm_inline.h +8 -0
@@ -559,6 +574,21 @@ static inline void folio_clear_lru_refs(struct folio *folio)
 		folio_clear_referenced(folio);
 }
 
+/*
+ * For the classical LRU or isolated folios only: with MGLRU the PG_workingset
+ * bit is part of the folio refs count maintained by folio_inc_lru_refs(),
+ * a raw set would corrupt it.  The warning below catches folios still on a
+ * gen list, the classical paths in the switching window only see off-list ones.
+ */
+static __always_inline void folio_set_workingset(struct folio *folio)
+{

include/linux/mm_inline.h static inline void folio_clear_lru_refs(struct folio *folio) · line 594

Quoted 10 lines
include/linux/mm_inline.h +7 -0
+	unsigned long flags;
+
+	flags = set_mask_bits(folio_flags(folio, 0), BIT(PG_workingset),
+			      BIT(PG_workingset));
+	VM_WARN_ON_ONCE(lru_get_gen_flags(flags) != -1);
+}
+
 static __always_inline
 void lruvec_add_folio(struct lruvec *lruvec, struct folio *folio)
 {

[Severity: Medium]
Can folio_set_workingset() race with lru_gen_change_state(true) when called from madvise_cold_prep_folio(), corrupting the MGLRU refs count and triggering this warning?

Unlike shrink_active_list() and workingset_refault(), which operate on isolated folios, madvise_cold_or_pageout_pte_range() calls madvise_cold_prep_folio() on a mapped on-LRU folio while holding only the page table lock:

mm/madvise.c:madvise_cold_prep_folio() {
	if (!lru_gen_enabled()) {
		folio_clear_lru_refs(folio);
		if (folio_test_active(folio))
			folio_set_workingset(folio);
	} else {

...
}

If MGLRU is enabled concurrently via /sys/kernel/mm/lru_gen/enabled, fill_evictable() can move the folio onto a generation list between folio_test_active() and folio_set_workingset():

CPU0 CPU1
madvise_cold_prep_folio(folio)
!lru_gen_enabled() -> true
folio_clear_lru_refs(folio)
folio_test_active(folio) -> true

                                      lru_gen_change_state(true)
                                        static_branch_enable(&lru_gen_caps[...])
                                        fill_evictable(lruvec)
                                          lru_gen_add_folio(lruvec, folio, ...)
                                            /* clears PG_active, sets gen */
  folio_set_workingset(folio)
    set_mask_bits(..., BIT(PG_workingset))
    VM_WARN_ON_ONCE(gen != -1)  <-- warns and mutates MGLRU refs on-list
Quoted 8 lines

Because set_mask_bits() unconditionally sets BIT(PG_workingset), it modifies bit 1 of the MGLRU refs encoding while the folio is on a generation list. With the per-folio active/inactive accounting in commit "mm/mglru: folio LRU refs based active/inactive number accounting", if the folio reached refs == 1 before folio_set_workingset() ran, setting BIT(PG_workingset) bumps refs to 3 (LRU_REFS_ACTIVATED) without updating the active/inactive LRU size counters, causing permanent NR_ACTIVE and NR_INACTIVE counter drift.

My bad, sorry about this. I got it right from v1 - v6, but while doing rebase in v7 I missed it. We just need to squash this here:

mm/madvise.c +1 -1
index c6c2e8189f4b..7603d56a94fc 100644
@@ -371,7 +371,7 @@ static void madvise_cold_prep_folio(struct folio *folio)
        if (!lru_gen_enabled()) {
                folio_clear_lru_refs(folio);
                if (folio_test_active(folio))
-                       folio_set_workingset(folio);
+                       folio_set_lru_refs(folio, LRU_REFS_WORKINGSET);
        } else {
                folio_test_clear_young(folio);
        }
Quoted 2 lines
Signature · 1 line
-- 

In the next commit there will be a conflict, isn't hard to solve, the diff in next commit for this part will be (just rename folio_set_lru_refs to __folio_set_lru_refs):

mm/madvise.c +1 -1
index 7603d56a94fc..a4a4df9f627c 100644
@@ -371,7 +371,7 @@ static void madvise_cold_prep_folio(struct folio *folio)
        if (!lru_gen_enabled()) {
                folio_clear_lru_refs(folio);
                if (folio_test_active(folio))
-                       folio_set_lru_refs(folio, LRU_REFS_WORKINGSET);
+                       __folio_set_lru_refs(folio, LRU_REFS_WORKINGSET);
        } else {
                folio_test_clear_young(folio);
        }

---

Hi Andrew, do you think you can help update this part? Or I can send a v8 later to cover this.

maintainer tree notice
#39 lore raw

+ mm-mglru-make-pg_workingset-helpers-work-based-on-folio-lru-refs.patch added to mm-new branch

In reply to Kairui Song
The patch titled Subject: mm/mglru: make PG_workingset helpers work based on folio LRU refs has been added to the -mm mm-new branch. Its filename is…

The patch titled
Subject: mm/mglru: make PG_workingset helpers work based on folio LRU refs
has been added to the -mm mm-new branch. Its filename is
mm-mglru-make-pg_workingset-helpers-work-based-on-folio-lru-refs.patch

This patch will shortly appear at
https://git.kernel.org/pub/scm/linux/kernel/git/akpm/25-new.git/tree/patches/mm-mglru-make-pg_workingset-helpers-work-based-on-folio-lru-refs.patch

This patch will later appear in the mm-new branch at
git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm

Note, mm-new is a provisional staging ground for work-in-progress patches, and acceptance into mm-new is a notification for others take notice and to finish up reviews. Please do not hesitate to respond to review feedback and post updated versions to replace or incrementally fixup patches in mm-new.

The mm-new branch of mm.git is not included in linux-next

If a few days of testing in mm-new is successful, the patch will me moved into mm.git's mm-unstable branch, which is included in linux-next

Before you just go and hit "reply", please:
a) Consider who else should be cc'ed
b) Prefer to cc a suitable mailing list as well
c) Ideally: find the original patch on the mailing list and do a reply-to-all to that, adding suitable additional cc's

*** Remember to use Documentation/process/submit-checklist.rst when testing your code ***

The -mm tree is included into linux-next via various branches at git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm
and is updated there most days

------------------------------------------------------
From: Kairui Song <[email protected]>
Subject: mm/mglru: make PG_workingset helpers work based on folio LRU refs
Date: Wed, 02 Dec 2026 04:18:57 +0800

folio_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 refs 4 or 5 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 earlier generation promotion.

Move both helpers into mm_inline.h, the test as an inline helper based on folio_lru_refs(), checking refs >= LRU_REFS_WORKINGSET.

The set stays reserved for the classical LRU, as under MGLRU the refs count is maintained by folio_inc_lru_refs(): it now warns when the folio is on a gen list, where the raw bit would corrupt its refs count.

The one PageWorkingset() user in erofs is converted to the folio helper.

There is no behavior change for the classical LRU: it does not maintain the refs count, so for a folio that was never on a gen list the test is equivalent to the PG_workingset bit test.

This prepares the convention for follow up MGLRU change.

Cc Johannes Weiner <[email protected]>
Cc Muchun Song <[email protected]>
Cc Qi Zheng <[email protected]>
Cc Ying Huang <[email protected]>
Cc Christopher Li <[email protected]>
Cc Baoquan He <[email protected]>
Cc Nico Pache <[email protected]>
Cc Usama Arif <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Roman Gushchin <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Barry Song <[email protected]>
Cc Axel Rasmussen <[email protected]>
Cc Yuanchu Xie <[email protected]>
Cc Wei Xu <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Nhat Pham <[email protected]>
Cc Youngjun Park <[email protected]>
Cc Zi Yan <[email protected]>
Cc Gregory Price <[email protected]>
Cc Matthew Wilcox (Oracle) <[email protected]>
Cc Baolin Wang <[email protected]>
Cc Ryan Roberts <[email protected]>
Cc Dev Jain <[email protected]>
Cc Lance Yang <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc SJ Park <[email protected]>
Cc David Rientjes <[email protected]>
Cc Yu Zhao <[email protected]>
Cc Vernon Yang <[email protected]>
Cc wangzicheng <[email protected]>
Cc Tal Zussman <[email protected]>
Cc Kairui Song <[email protected]>
Cc Xiang Liu <[email protected]>
Cc Ehab Ababneh <[email protected]>
Cc wang lian <[email protected]>
Cc Joanne Koong <[email protected]>
Cc Hui Zhu <[email protected]>
Cc Maxim Muzafarov <[email protected]>
Cc Tianyi Chen <[email protected]>
Cc Ridong Chen <[email protected]>
 fs/btrfs/compression.c     |    1 +
 fs/erofs/zdata.c           |    3 ++-
 include/linux/mm_inline.h  |   30 ++++++++++++++++++++++++++++++
 include/linux/page-flags.h |    2 --
 mm/filemap.c               |    1 +
 mm/page_io.c               |    1 +
 6 files changed, 35 insertions(+), 3 deletions(-)
fs/btrfs/compression.c renamed from fs/btrfs/compression.c~mm-mglru-make-pg_workingset-helpers-work-based-on-folio-lru-refs +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 renamed from fs/erofs/zdata.c~mm-mglru-make-pg_workingset-helpers-work-based-on-folio-lru-refs +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 @@ drain_io:
 				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 renamed from include/linux/mm_inline.h~mm-mglru-make-pg_workingset-helpers-work-based-on-folio-lru-refs +30 -0
@@ -306,6 +306,21 @@ static inline void folio_migrate_lru_ref
 	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 flag encoding,
+ * this is just testing the PG_workingset bit.
+ *
+ * Return: true if the folio is workingset.
+ */
+static __always_inline bool folio_test_workingset(const struct folio *folio)
+{
+	return lru_refs_is_workingset(folio_lru_refs(folio));
+}
+
 #ifdef CONFIG_LRU_GEN
 static inline bool lru_gen_is_old(struct lruvec *lruvec, int type, int gen)
 {
@@ -559,6 +574,21 @@ static inline void folio_clear_lru_refs(
 		folio_clear_referenced(folio);
 }
 
+/*
+ * For the classical LRU or isolated folios only: with MGLRU the PG_workingset
+ * bit is part of the folio refs count maintained by folio_inc_lru_refs(),
+ * a raw set would corrupt it.  The warning below catches folios still on a
+ * gen list, the classical paths in the switching window only see off-list ones.
+ */
+static __always_inline void folio_set_workingset(struct folio *folio)
+{
+	unsigned long flags;
+
+	flags = set_mask_bits(folio_flags(folio, 0), BIT(PG_workingset),
+			      BIT(PG_workingset));
+	VM_WARN_ON_ONCE(lru_get_gen_flags(flags) != -1);
+}
+
 static __always_inline
 void lruvec_add_folio(struct lruvec *lruvec, struct folio *folio)
 {
include/linux/page-flags.h renamed from include/linux/page-flags.h~mm-mglru-make-pg_workingset-helpers-work-based-on-folio-lru-refs +0 -2
@@ -551,8 +551,6 @@ PAGEFLAG(LRU, lru, PF_HEAD) __CLEARPAGEF
 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 renamed from mm/filemap.c~mm-mglru-make-pg_workingset-helpers-work-based-on-folio-lru-refs +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 renamed from mm/page_io.c~mm-mglru-make-pg_workingset-helpers-work-based-on-folio-lru-refs +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>

_

Patches currently in -mm which might be from [email protected] are

mm-mglru-report-evictable-sizes-per-type.patch mm-mglru-extract-lruvec_populated_min_seq-helper.patch mm-mglru-reclaim-from-the-oldest-populated-gen.patch mm-mglru-lift-the-forced-protection-of-reclaimer.patch mm-mglru-skip-zones-above-reclaim_idx-instead-of-rotating-them.patch mm-mglru-return-for-unavailable-anon-reclaim-earlier.patch mm-mglru-balance-anon-and-file-scan-budget-by-refault-rate.patch mm-mglru-lift-youngest-gen-protection-for-higher-priority.patch mm-memcontrol-allow-update-of-lru-statistic-without-holding-lru-lock.patch mm-memcontrol-avoid-potential-counter-leak-when-reparenting-local-stats.patch mm-mglru-make-generation-page-counters-atomic.patch mm-memcg-add-folio-based-lruvec-live-helper.patch mm-mglru-frequency-guided-workingset-promotion-mglru-fg.patch mm-mglru-make-folio-lru-referenced-times-count-a-generic-api.patch mm-mglru-move-add-del-lru-size-accounting-out-of-lru_gen_update_size.patch mm-mglru-gup-mark-folios-referenced-via-a-fast-helper.patch mm-mglru-smaps-convert-to-lru-refs-based-operations-for-mglru.patch mm-damon-convert-to-lru-refs-based-operations-for-mglru.patch mm-khugepaged-convert-to-lru-refs-based-operations-for-mglru.patch mm-madvise-adapt-for-lru-refs-based-operations-for-mglru.patch mm-factor-out-folio_mark_accessed_vma.patch mm-huge_memory-mark-folio-as-accessed-more-accurately-on-split.patch mm-mglru-make-pg_workingset-helpers-work-based-on-folio-lru-refs.patch mm-mglru-folio-lru-refs-based-active-inactive-number-accounting.patch mm-mglru-make-folio_inc_lru_refs-lruvec-lockless.patch

author maintainer
#40 lore raw

PATCH v7 18/19 mm/mglru: folio LRU refs based active/inactive number accounting

In reply to Kairui Song

Currently 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 causes several problems:

- Unmapped file folios can stay in older gens despite repeated use, so active files can be 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 without any change in use.

- The reading is reversed on swapless machines. When swapping is disabled or unavailable, MGLRU ages anon by moving the gens directly without walking or touching any folio, to reduce the overhead. So inactive anon folios can suddenly count as active, or vice versa, despite no change in their hotness.

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 reaching this threshold, folios are accounted to the active part. On forced per-folio aging or PID protection, refs are capped at LRU_REFS_WORKINGSET, dropping active folios to the inactive part. Note that on swapless machines anon refs are not reset by aging (the shortcut skips the per-folio walk), but the counts no longer oscillate as the generation indices wrap.

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. Local stats move in bulk after the lists, and the active/inactive bucket follows the folio's refs rather than the lruvec, so it does not change when the folio is reparented.

folio_migrate_lru_refs() also gains off-LRU VM_WARN_ON_ONCE checks and __folio_set_lru_refs() leaves a folio that is still on a gen list alone, as its refs are already in the active/inactive counters. Such a folio is reset with folio_reset_lru_refs() instead, which updates the counters without lru_lock, and the deactivation paths now use it too instead of clearing PG_referenced, bit 0 of the MGLRU refs count. lru_gen_del_folio() reads the refs for the accounting from the same try_cmpxchg that clears the gen.

---
 Documentation/admin-guide/mm/multigen_lru.rst |   4 +-
 include/linux/mm_inline.h                     | 106 +++++++-----
 include/linux/mmzone.h                        |  23 ++-
 mm/folio.c                                    |  44 +----
 mm/madvise.c                                  |   2 +-
 mm/vmscan.c                                   | 230 +++++++++++++++++---------
 mm/workingset.c                               |   2 +-
 7 files changed, 239 insertions(+), 172 deletions(-)
Documentation/admin-guide/mm/multigen_lru.rst +2 -2
index 9cb54b4ff5d9..808d2e97b3f3 100644
@@ -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 +61 -45

213 lines not on this page · raw message

include/linux/mmzone.h +15 -8
index 27ba7fa6ddd6..42afb5375c27 100644
@@ -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
@@ -524,11 +524,15 @@ enum lruvec_flags {
  * and the bits masked by LRU_REFS_MASK as the higher bits, so the refs
  * count ranges from 0 to LRU_REFS_MAX.
  *
- * Cold hints can reset refs with lru_gen_clear_refs(). Refault restores
+ * Cold hints can reset refs with folio_reset_lru_refs(). Refault restores
  * its referenced count, capped at LRU_REFS_PROTECTED, which aligns with
  * promotion.  Fault-driven refaults of previous workingset folios set
  * PG_active, so they are placed in the latest gen.
  *
+ * For the active/inactive LRU ABI (/proc/vmstat), a folio is active
+ * if its referenced count reaches LRU_REFS_ACTIVATED. The threshold
+ * is 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.
  */
@@ -543,6 +547,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
 
@@ -651,6 +656,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 +7 -37

94 lines not on this page · raw message

mm/madvise.c +1 -1
index c6c2e8189f4b..93807b27b374 100644
@@ -388,7 +388,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 +152 -78

419 lines not on this page · raw message

mm/workingset.c +1 -1
index eea711057c72..79cfaefad772 100644
@@ -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 (lru_refs_is_workingset(refs))
Signature · 1 line
2.56.1
maintainer tree notice
#41 lore raw

+ mm-mglru-folio-lru-refs-based-active-inactive-number-accounting.patch added to mm-new branch

The patch titled Subject: mm/mglru: folio LRU refs based active/inactive number accounting has been added to the -mm mm-new branch. Its filename is…

The patch titled
Subject: mm/mglru: folio LRU refs based active/inactive number accounting
has been added to the -mm mm-new branch. Its filename is
mm-mglru-folio-lru-refs-based-active-inactive-number-accounting.patch

This patch will shortly appear at
https://git.kernel.org/pub/scm/linux/kernel/git/akpm/25-new.git/tree/patches/mm-mglru-folio-lru-refs-based-active-inactive-number-accounting.patch

This patch will later appear in the mm-new branch at
git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm

Note, mm-new is a provisional staging ground for work-in-progress patches, and acceptance into mm-new is a notification for others take notice and to finish up reviews. Please do not hesitate to respond to review feedback and post updated versions to replace or incrementally fixup patches in mm-new.

The mm-new branch of mm.git is not included in linux-next

If a few days of testing in mm-new is successful, the patch will me moved into mm.git's mm-unstable branch, which is included in linux-next

Before you just go and hit "reply", please:
a) Consider who else should be cc'ed
b) Prefer to cc a suitable mailing list as well
c) Ideally: find the original patch on the mailing list and do a reply-to-all to that, adding suitable additional cc's

*** Remember to use Documentation/process/submit-checklist.rst when testing your code ***

The -mm tree is included into linux-next via various branches at git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm
and is updated there most days

------------------------------------------------------
From: Kairui Song <[email protected]>
Subject: mm/mglru: folio LRU refs based active/inactive number accounting
Date: Wed, 02 Dec 2026 04:18:58 +0800

Currently 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 causes several problems:

- Unmapped file folios can stay in older gens despite repeated use, so active files can be 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 without any change in use.

- The reading is reversed on swapless machines. When swapping is disabled or unavailable, MGLRU ages anon by moving the gens directly without walking or touching any folio, to reduce the overhead. So inactive anon folios can suddenly count as active, or vice versa, despite no change in their hotness.

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 reaching this threshold, folios are accounted to the active part. On forced per-folio aging or PID protection, refs are capped at LRU_REFS_WORKINGSET, dropping active folios to the inactive part. Note that on swapless machines anon refs are not reset by aging (the shortcut skips the per-folio walk), but the counts no longer oscillate as the generation indices wrap.

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. Local stats move in bulk after the lists, and the active/inactive bucket follows the folio's refs rather than the lruvec, so it does not change when the folio is reparented.

folio_migrate_lru_refs() also gains off-LRU VM_WARN_ON_ONCE checks and __folio_set_lru_refs() leaves a folio that is still on a gen list alone, as its refs are already in the active/inactive counters. Such a folio is reset with folio_reset_lru_refs() instead, which updates the counters without lru_lock, and the deactivation paths now use it too instead of clearing PG_referenced, bit 0 of the MGLRU refs count. lru_gen_del_folio() reads the refs for the accounting from the same try_cmpxchg that clears the gen.

Cc Johannes Weiner <[email protected]>
Cc Muchun Song <[email protected]>
Cc Qi Zheng <[email protected]>
Cc Ying Huang <[email protected]>
Cc Christopher Li <[email protected]>
Cc Baoquan He <[email protected]>
Cc Nico Pache <[email protected]>
Cc Usama Arif <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Roman Gushchin <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Barry Song <[email protected]>
Cc Axel Rasmussen <[email protected]>
Cc Yuanchu Xie <[email protected]>
Cc Wei Xu <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Nhat Pham <[email protected]>
Cc Youngjun Park <[email protected]>
Cc Zi Yan <[email protected]>
Cc Gregory Price <[email protected]>
Cc Matthew Wilcox (Oracle) <[email protected]>
Cc Baolin Wang <[email protected]>
Cc Ryan Roberts <[email protected]>
Cc Dev Jain <[email protected]>
Cc Lance Yang <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc SJ Park <[email protected]>
Cc David Rientjes <[email protected]>
Cc Yu Zhao <[email protected]>
Cc Vernon Yang <[email protected]>
Cc wangzicheng <[email protected]>
Cc Tal Zussman <[email protected]>
Cc Kairui Song <[email protected]>
Cc Xiang Liu <[email protected]>
Cc Ehab Ababneh <[email protected]>
Cc zhaozhengzhuo <[email protected]>
Cc wang lian <[email protected]>
Cc Joanne Koong <[email protected]>
Cc Hui Zhu <[email protected]>
Cc Maxim Muzafarov <[email protected]>
Cc Tianyi Chen <[email protected]>
Cc Ridong Chen <[email protected]>
 Documentation/admin-guide/mm/multigen_lru.rst |    4 
 include/linux/mm_inline.h                     |  106 ++++---
 include/linux/mmzone.h                        |   23 +
 mm/folio.c                                    |   44 ---
 mm/madvise.c                                  |    2 
 mm/vmscan.c                                   |  230 ++++++++++------
 mm/workingset.c                               |    2 
 7 files changed, 239 insertions(+), 172 deletions(-)
Documentation/admin-guide/mm/multigen_lru.rst renamed from Documentation/admin-guide/mm/multigen_lru.rst~mm-mglru-folio-lru-refs-based-active-inactive-number-accounting +2 -2
@@ -149,8 +149,8 @@ generations less than or equal to ``min_
     ``- 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 renamed from include/linux/mm_inline.h~mm-mglru-folio-lru-refs-based-active-inactive-number-accounting +61 -45

213 lines not on this page · raw message

include/linux/mmzone.h renamed from include/linux/mmzone.h~mm-mglru-folio-lru-refs-based-active-inactive-number-accounting +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
@@ -524,11 +524,15 @@ enum lruvec_flags {
  * and the bits masked by LRU_REFS_MASK as the higher bits, so the refs
  * count ranges from 0 to LRU_REFS_MAX.
  *
- * Cold hints can reset refs with lru_gen_clear_refs(). Refault restores
+ * Cold hints can reset refs with folio_reset_lru_refs(). Refault restores
  * its referenced count, capped at LRU_REFS_PROTECTED, which aligns with
  * promotion.  Fault-driven refaults of previous workingset folios set
  * PG_active, so they are placed in the latest gen.
  *
+ * For the active/inactive LRU ABI (/proc/vmstat), a folio is active
+ * if its referenced count reaches LRU_REFS_ACTIVATED. The threshold
+ * is 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.
  */
@@ -543,6 +547,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
 
@@ -651,6 +656,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 renamed from mm/folio.c~mm-mglru-folio-lru-refs-based-active-inactive-number-accounting +7 -37

94 lines not on this page · raw message

mm/madvise.c renamed from mm/madvise.c~mm-mglru-folio-lru-refs-based-active-inactive-number-accounting +1 -1
@@ -397,7 +397,7 @@ static void madvise_pageout_prep_folio(s
 	 * 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 renamed from mm/vmscan.c~mm-mglru-folio-lru-refs-based-active-inactive-number-accounting +152 -78

419 lines not on this page · raw message

mm/workingset.c renamed from mm/workingset.c~mm-mglru-folio-lru-refs-based-active-inactive-number-accounting +1 -1
@@ -334,7 +334,7 @@ static void lru_gen_refault(struct folio
 			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 (lru_refs_is_workingset(refs))

_

Patches currently in -mm which might be from [email protected] are

mm-mglru-report-evictable-sizes-per-type.patch mm-mglru-extract-lruvec_populated_min_seq-helper.patch mm-mglru-reclaim-from-the-oldest-populated-gen.patch mm-mglru-lift-the-forced-protection-of-reclaimer.patch mm-mglru-skip-zones-above-reclaim_idx-instead-of-rotating-them.patch mm-mglru-return-for-unavailable-anon-reclaim-earlier.patch mm-mglru-balance-anon-and-file-scan-budget-by-refault-rate.patch mm-mglru-lift-youngest-gen-protection-for-higher-priority.patch mm-memcontrol-allow-update-of-lru-statistic-without-holding-lru-lock.patch mm-memcontrol-avoid-potential-counter-leak-when-reparenting-local-stats.patch mm-mglru-make-generation-page-counters-atomic.patch mm-memcg-add-folio-based-lruvec-live-helper.patch mm-mglru-frequency-guided-workingset-promotion-mglru-fg.patch mm-mglru-make-folio-lru-referenced-times-count-a-generic-api.patch mm-mglru-move-add-del-lru-size-accounting-out-of-lru_gen_update_size.patch mm-mglru-gup-mark-folios-referenced-via-a-fast-helper.patch mm-mglru-smaps-convert-to-lru-refs-based-operations-for-mglru.patch mm-damon-convert-to-lru-refs-based-operations-for-mglru.patch mm-khugepaged-convert-to-lru-refs-based-operations-for-mglru.patch mm-madvise-adapt-for-lru-refs-based-operations-for-mglru.patch mm-factor-out-folio_mark_accessed_vma.patch mm-huge_memory-mark-folio-as-accessed-more-accurately-on-split.patch mm-mglru-make-pg_workingset-helpers-work-based-on-folio-lru-refs.patch mm-mglru-folio-lru-refs-based-active-inactive-number-accounting.patch mm-mglru-make-folio_inc_lru_refs-lruvec-lockless.patch

author maintainer
#42 lore raw

PATCH v7 19/19 mm/mglru: make folio_inc_lru_refs lruvec lockless

In reply to Kairui Song

The 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 is what lets folio_reset_lru_refs() update the counters without the lruvec lock.

Use folio_lruvec_live_get()/folio_lruvec_live_put() to hold the RCU read lock around the lruvec lookup, drop the spinlock entirely, and update the active/inactive counters with __update_lru_size_lockless(), like folio_reset_lru_refs().

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               | 62 +++++++++++++++++++++++++++++------------------
 3 files changed, 46 insertions(+), 29 deletions(-)
include/linux/mm_inline.h +5 -5
index 13fc8dbe8531..622fd447ac7f 100644
@@ -358,10 +358,9 @@ static inline bool lru_gen_is_old(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;
@@ -443,7 +442,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);
@@ -462,6 +461,7 @@ static inline bool lru_gen_del_folio(struct lruvec *lruvec, struct folio *folio,
 	unsigned long flags = READ_ONCE(*folio_flags(folio, 0)), new_flags;
 	unsigned int refs;
 	int gen;
+	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;
@@ -486,7 +486,7 @@ static inline bool lru_gen_del_folio(struct lruvec *lruvec, struct folio *folio,
 			new_flags |= BIT(PG_active);
 	} while (!try_cmpxchg(folio_flags(folio, 0), &flags, new_flags));
 
-	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
index 42afb5375c27..14c58bbd1606 100644
@@ -540,9 +540,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 +39 -23

106 lines not on this page · raw message

Signature · 1 line
2.56.1
maintainer tree notice
#43 lore raw

+ mm-mglru-make-folio_inc_lru_refs-lruvec-lockless.patch added to mm-new branch

The patch titled Subject: mm/mglru: make folio_inc_lru_refs lruvec lockless has been added to the -mm mm-new branch. Its filename is mm-mglru-make-folio_inc_lru_refs-lruvec-lockless.patch

The patch titled
Subject: mm/mglru: make folio_inc_lru_refs lruvec lockless
has been added to the -mm mm-new branch. Its filename is
mm-mglru-make-folio_inc_lru_refs-lruvec-lockless.patch

This patch will shortly appear at
https://git.kernel.org/pub/scm/linux/kernel/git/akpm/25-new.git/tree/patches/mm-mglru-make-folio_inc_lru_refs-lruvec-lockless.patch

This patch will later appear in the mm-new branch at
git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm

Note, mm-new is a provisional staging ground for work-in-progress patches, and acceptance into mm-new is a notification for others take notice and to finish up reviews. Please do not hesitate to respond to review feedback and post updated versions to replace or incrementally fixup patches in mm-new.

The mm-new branch of mm.git is not included in linux-next

If a few days of testing in mm-new is successful, the patch will me moved into mm.git's mm-unstable branch, which is included in linux-next

Before you just go and hit "reply", please:
a) Consider who else should be cc'ed
b) Prefer to cc a suitable mailing list as well
c) Ideally: find the original patch on the mailing list and do a reply-to-all to that, adding suitable additional cc's

*** Remember to use Documentation/process/submit-checklist.rst when testing your code ***

The -mm tree is included into linux-next via various branches at git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm
and is updated there most days

------------------------------------------------------
From: Kairui Song <[email protected]>
Subject: mm/mglru: make folio_inc_lru_refs lruvec lockless
Date: Wed, 02 Dec 2026 04:18:59 +0800

The 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 is what lets folio_reset_lru_refs() update the counters without the lruvec lock.

Use folio_lruvec_live_get()/folio_lruvec_live_put() to hold the RCU read lock around the lruvec lookup, drop the spinlock entirely, and update the active/inactive counters with __update_lru_size_lockless(), like folio_reset_lru_refs().

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.

Cc Johannes Weiner <[email protected]>
Cc Muchun Song <[email protected]>
Cc Qi Zheng <[email protected]>
Cc Ying Huang <[email protected]>
Cc Christopher Li <[email protected]>
Cc Baoquan He <[email protected]>
Cc Nico Pache <[email protected]>
Cc Usama Arif <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Roman Gushchin <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Barry Song <[email protected]>
Cc Axel Rasmussen <[email protected]>
Cc Yuanchu Xie <[email protected]>
Cc Wei Xu <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Nhat Pham <[email protected]>
Cc Youngjun Park <[email protected]>
Cc Zi Yan <[email protected]>
Cc Gregory Price <[email protected]>
Cc Matthew Wilcox (Oracle) <[email protected]>
Cc Baolin Wang <[email protected]>
Cc Ryan Roberts <[email protected]>
Cc Dev Jain <[email protected]>
Cc Lance Yang <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc SJ Park <[email protected]>
Cc David Rientjes <[email protected]>
Cc Yu Zhao <[email protected]>
Cc Vernon Yang <[email protected]>
Cc wangzicheng <[email protected]>
Cc Tal Zussman <[email protected]>
Cc Kairui Song <[email protected]>
Cc Xiang Liu <[email protected]>
Cc Ehab Ababneh <[email protected]>
Cc zhaozhengzhuo <[email protected]>
Cc Joanne Koong <[email protected]>
Cc Hui Zhu <[email protected]>
Cc Maxim Muzafarov <[email protected]>
Cc Ridong Chen <[email protected]>
 include/linux/mm_inline.h |   10 ++---
 include/linux/mmzone.h    |    3 +
 mm/vmscan.c               |   62 ++++++++++++++++++++++--------------
 3 files changed, 46 insertions(+), 29 deletions(-)
include/linux/mm_inline.h renamed from include/linux/mm_inline.h~mm-mglru-make-folio_inc_lru_refs-lruvec-lockless +5 -5
@@ -358,10 +358,9 @@ static inline bool lru_gen_is_old(struct
 	       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;
@@ -443,7 +442,7 @@ static inline bool lru_gen_add_folio(str
 	/* 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);
@@ -462,6 +461,7 @@ static inline bool lru_gen_del_folio(str
 	unsigned long flags = READ_ONCE(*folio_flags(folio, 0)), new_flags;
 	unsigned int refs;
 	int gen;
+	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;
@@ -486,7 +486,7 @@ static inline bool lru_gen_del_folio(str
 			new_flags |= BIT(PG_active);
 	} while (!try_cmpxchg(folio_flags(folio, 0), &flags, new_flags));
 
-	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 renamed from include/linux/mmzone.h~mm-mglru-make-folio_inc_lru_refs-lruvec-lockless +2 -1
@@ -540,9 +540,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 renamed from mm/vmscan.c~mm-mglru-make-folio_inc_lru_refs-lruvec-lockless +39 -23

106 lines not on this page · raw message

_

Patches currently in -mm which might be from [email protected] are

mm-mglru-report-evictable-sizes-per-type.patch mm-mglru-extract-lruvec_populated_min_seq-helper.patch mm-mglru-reclaim-from-the-oldest-populated-gen.patch mm-mglru-lift-the-forced-protection-of-reclaimer.patch mm-mglru-skip-zones-above-reclaim_idx-instead-of-rotating-them.patch mm-mglru-return-for-unavailable-anon-reclaim-earlier.patch mm-mglru-balance-anon-and-file-scan-budget-by-refault-rate.patch mm-mglru-lift-youngest-gen-protection-for-higher-priority.patch mm-memcontrol-allow-update-of-lru-statistic-without-holding-lru-lock.patch mm-memcontrol-avoid-potential-counter-leak-when-reparenting-local-stats.patch mm-mglru-make-generation-page-counters-atomic.patch mm-memcg-add-folio-based-lruvec-live-helper.patch mm-mglru-frequency-guided-workingset-promotion-mglru-fg.patch mm-mglru-make-folio-lru-referenced-times-count-a-generic-api.patch mm-mglru-move-add-del-lru-size-accounting-out-of-lru_gen_update_size.patch mm-mglru-gup-mark-folios-referenced-via-a-fast-helper.patch mm-mglru-smaps-convert-to-lru-refs-based-operations-for-mglru.patch mm-damon-convert-to-lru-refs-based-operations-for-mglru.patch mm-khugepaged-convert-to-lru-refs-based-operations-for-mglru.patch mm-madvise-adapt-for-lru-refs-based-operations-for-mglru.patch mm-factor-out-folio_mark_accessed_vma.patch mm-huge_memory-mark-folio-as-accessed-more-accurately-on-split.patch mm-mglru-make-pg_workingset-helpers-work-based-on-folio-lru-refs.patch mm-mglru-folio-lru-refs-based-active-inactive-number-accounting.patch mm-mglru-make-folio_inc_lru_refs-lruvec-lockless.patch

#44 lore raw
In reply to Kairui Song
Sashiko has finished reviewing this 19-patch series:

Sashiko has finished reviewing this 19-patch series:

- Patches 1-13, 15, 16, 18, and 19: no issues found.
- Patch 14 ("mm/madvise: adapt for LRU refs based operations for..."): 1 potential issue (1 Low)
- Patch 17 ("mm/mglru: make PG_workingset helpers work based on f..."):
1 potential issue (1 Medium)

Detailed reviews have been sent as separate replies to patches 14 and 17.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]
#46 lore raw
Quoted 6 lines · zhaozhengzhuo

Hi Kairui,

Nit: the Tested-by name is missing a "g" -- it should be "Zhao Zhengzhuo", not "Zhao Zhenzhuo". The human-readable form is fine, and the email address is correct.

Quoted 7 lines
Quoted 1 line

The correct line is:

If this is already in your tree, please fix it up when applying.

Terribly sorry about this! It seems Andrew already help fixed that.

maintainer
#47 lore raw
In reply to Kairui Song
Quoted 6 lines · On Wed, 02 Dec 2026 04:18:40 +0800 Kairui Song <[email protected]> wrote:

This series implements MGLRU-FG following the idea proposed at LSF/MM/BPF this year [1], based on current mm-new. Depending on the workload, it improves the performance or reduces IO by roughly 10% to over 50%, fixes multiple long-standing issues with MGLRU metrics, and drops one page flag.

I gave this a 2-hour workout on 64 vCPU QEMU. Everything checks out. It might have found one thing:

: The test gives a 128 MiB cgroup a 4 MiB file that it reads repeatedly : and a 512 MiB file whose reads force reclaim. The 4 MiB file is the : hotset: 1,024 pages we expect to survive the cold-file scans. :
: With three hot-file reads per scan, the kernel before the series (A) : kept all 1,024 pages after warmup. The 19-patch kernel (B) sometimes : evicted every one: in 6 of 10 cycles in one run and 3 of 10 in another. : Reading the hot file then took about 2.4-3.2 ms on B versus about 1.3 : ms on A. B also scanned more pages.
:
: The result depends on access rate: with one hot-file read per scan, B : kept the pages and A mostly lost them. So the series helped one : workload but regressed this more frequently read one. The trace points : to hot pages being selected for eviction, but the run did not establish : a safe correction or isolate which of the 19 patches causes it.

And it proposed a little GUP speedup:

From: Andrew Morton <[email protected]>
Subject: mm/mglru: skip refs decoding for already referenced GUP folios
Date: Tue, 01 Dec 2026 17:59:24 -0800

GUP-fast calls folio_inc_lru_refs_fast() for every folio it pins. After its first reference, a folio with PG_referenced set still incurs the generation decode, refs decode and static-key test on every pin. The v7 GUP helper is measurably slower than the preceding queue endpoint in this repeated-pin workload.

Test PG_referenced first. If set, both the MGLRU refs count and the classical LRU referenced state are already nonzero, so the helper has nothing to change. Otherwise, check the remaining MGLRU refs bits and atomically set PG_referenced only when needed. Reevaluate all tests after a failed cmpxchg. This retains the original behavior for MGLRU on, off and during switching, including a folio still on a generation list after the static key turns off.

In fresh 7.4.0-rc4 guests with the 19 v7 patches, GUP_FAST_BENCHMARK pinned 16 MiB of 4 KiB pages in 64-page batches for 8192 calls per thread. Across two interleaved baseline/fix pairs, the single-thread median kernel get time fell from 52.9/53.8 to 49.3/50.1 us per call. The 64-CPU medians fell from 88.3/85.7 to 79.8/85.8 us, with wider run-to-run variation. GUP selftests passed 60/60 with MGLRU enabled and 60/60 with it disabled; MADV selftests passed 24/24 with MGLRU disabled. No kernel warnings were observed.

 include/linux/mm_inline.h | 15 +++++----------
 1 file changed, 5 insertions(+), 10 deletions(-)
include/linux/mm_inline.h +5 -10
@@ -538,21 +538,16 @@
 static __always_inline void folio_inc_lru_refs_fast(struct folio *folio)
 {
 	unsigned long new_flags, old_flags = READ_ONCE(*folio_flags(folio, 0));
-	unsigned int refs;
-	bool has_gen;
 
 	BUILD_BUG_ON(LRU_REFS_REFERENCED >= LRU_REFS_ACTIVATED);
 	do {
-		has_gen = lru_get_gen_flags(old_flags) >= 0;
-		refs = lru_get_refs_flags(old_flags);
-		if (has_gen || lru_gen_enabled()) {
-			if (refs)
-				break;
-		} else if (refs & LRU_REFS_REFERENCED) {
+		if (old_flags & BIT(PG_referenced))
 			break;
+		if (lru_get_gen_flags(old_flags) >= 0 || lru_gen_enabled()) {
+			if (old_flags & LRU_REFS_FLAGS)
+				break;
 		}
-		new_flags = old_flags;
-		lru_set_refs_flags(&new_flags, refs | LRU_REFS_REFERENCED);
+		new_flags = old_flags | BIT(PG_referenced);
 	} while (!try_cmpxchg(folio_flags(folio, 0), &old_flags, new_flags));
 }
 
#48 lore raw
Quoted 12 lines · Andrew Morton
Quoted 6 lines · On Wed, 02 Dec 2026 04:18:40 +0800 Kairui Song <[email protected]> wrote:

This series implements MGLRU-FG following the idea proposed at LSF/MM/BPF this year [1], based on current mm-new. Depending on the workload, it improves the performance or reduces IO by roughly 10% to over 50%, fixes multiple long-standing issues with MGLRU metrics, and drops one page flag.

I gave this a 2-hour workout on 64 vCPU QEMU. Everything checks out. It might have found one thing:

Quoted 15 lines

: The test gives a 128 MiB cgroup a 4 MiB file that it reads repeatedly : and a 512 MiB file whose reads force reclaim. The 4 MiB file is the : hotset: 1,024 pages we expect to survive the cold-file scans. :
: With three hot-file reads per scan, the kernel before the series (A) : kept all 1,024 pages after warmup. The 19-patch kernel (B) sometimes : evicted every one: in 6 of 10 cycles in one run and 3 of 10 in another. : Reading the hot file then took about 2.4-3.2 ms on B versus about 1.3 : ms on A. B also scanned more pages.
:
: The result depends on access rate: with one hot-file read per scan, B : kept the pages and A mostly lost them. So the series helped one : workload but regressed this more frequently read one. The trace points : to hot pages being selected for eviction, but the run did not establish : a safe correction or isolate which of the 19 patches causes it.

Ah I see, this is the typical hot cache pollution vs code cache pollution issue. Here it's trying to fit 512MB + 4MB in a 128MB cgroup, so clearly it won't fit and if the 512MB is the cold part, it will turns the memcg LRU over about 4 times.

Still TLDR (as LRU related things are always complex to explain):
It's a trade off and I consider it a good one, and the problem will be fully covered by refault distance with no regression.

I'm not sure how the agent actually conducted it, and maybe in the test env LRU_REFS_WIDTH is shrunk? But right now, FG does tend to be more proactive to avoid stall cache pollution, while mainline MGLRU does have the trend of (over)protect stall cache in some cases.

Note the case here has a "warm up" which generates shadow, so the 512MB is not actually cold but more like "warm". A "warm" scan will trigger aging, and by trigging the aging 4 times, it will replace previous hotter workingset, as that workingset is now considered stalled.

Without that, in mainline, stall cache pollution is a sometimes even worse problem. Many people reported that issues in previous discussions.

See this table which I collected from my VM (30 rounds):

setup    | 512M warm + 4M hot (3 reads)        | 64M hot (3 reads) -> 72M hot (loop)
baseline | keeps the 4M (27/30)                | keeps 64M, FAILS to cache 72M (fd)
FG       | LOSES 4M (14/30) try cache the 512M | keeps 64M, fully caches 72M
FG+RD    | keeps the 4M (30/30)                | keeps 64M, fully caches 72M

The 64+72 column is to demostrate the stall-LRU problem: 64M is scanned 3 times, then it loops on the 72M set. Mainline over protects the old 64M set, so the new 72M only gets 64M cached and thrashes every scan (cost ~473ms per scan). FG demotes the old set and caches 72M fully (only 5-7ms per scan now). The stall LRU issue is harder to handler as it could get stuck there forever.

Clearly for the 512M / 4M case we should not try cache the 512M part at all since it won't fit anyway. To solve that properly we can use refault distance, which is described in the cover letter (refault distance can help the workingset shift go faster too in some case, in this case is can help to prevent invalid shift). This RD code is also what I posted previously:

https://lore.kernel.org/linux-mm/avd5bI-b9y1nKWw5@KASONG-MC4/

Also results on Maxim case here:
https://lore.kernel.org/linux-mm/CAMgjq7DDUHrHEXiGDnPn6+keL6VxWWMabAr-BRrNM_bwsKPZnQ@mail.gmail.com/

With the above refault distance adaption, FG + RD behaves better in all rounds.

The idea of FD is when the cold part is way larger than memcg (random or scan), folios faulting back with a too long distance should not be protected at all (the 512M part). And meanwhile if the refault distance is short, consider protect it more proactively.

I have to say we are still trying to tweak the refault distance part better, but I think we are good and in the right direction.

Quoted 29 lines

And it proposed a little GUP speedup:

From: Andrew Morton <[email protected]>
Subject: mm/mglru: skip refs decoding for already referenced GUP folios
Date: Tue, 01 Dec 2026 17:59:24 -0800

GUP-fast calls folio_inc_lru_refs_fast() for every folio it pins. After its first reference, a folio with PG_referenced set still incurs the generation decode, refs decode and static-key test on every pin. The v7 GUP helper is measurably slower than the preceding queue endpoint in this repeated-pin workload.

Test PG_referenced first. If set, both the MGLRU refs count and the classical LRU referenced state are already nonzero, so the helper has nothing to change. Otherwise, check the remaining MGLRU refs bits and atomically set PG_referenced only when needed. Reevaluate all tests after a failed cmpxchg. This retains the original behavior for MGLRU on, off and during switching, including a folio still on a generation list after the static key turns off.

In fresh 7.4.0-rc4 guests with the 19 v7 patches, GUP_FAST_BENCHMARK pinned 16 MiB of 4 KiB pages in 64-page batches for 8192 calls per thread. Across two interleaved baseline/fix pairs, the single-thread median kernel get time fell from 52.9/53.8 to 49.3/50.1 us per call. The 64-CPU medians fell from 88.3/85.7 to 79.8/85.8 us, with wider run-to-run variation. GUP selftests passed 60/60 with MGLRU enabled and 60/60 with it disabled; MADV selftests passed 24/24 with MGLRU disabled. No kernel warnings were observed.

Quoted 6 lines
 include/linux/mm_inline.h | 15 +++++----------
 1 file changed, 5 insertions(+), 10 deletions(-)

This one looks good to me, thanks!

maintainer
#49 lore raw
Quoted 34 lines · On Thu, 3 Dec 2026 01:25:14 +0800 Kairui Song <[email protected]> wrote:
Quoted 12 lines · Andrew Morton
Quoted 6 lines · On Wed, 02 Dec 2026 04:18:40 +0800 Kairui Song <[email protected]> wrote:

This series implements MGLRU-FG following the idea proposed at LSF/MM/BPF this year [1], based on current mm-new. Depending on the workload, it improves the performance or reduces IO by roughly 10% to over 50%, fixes multiple long-standing issues with MGLRU metrics, and drops one page flag.

I gave this a 2-hour workout on 64 vCPU QEMU. Everything checks out. It might have found one thing:

Quoted 15 lines

: The test gives a 128 MiB cgroup a 4 MiB file that it reads repeatedly : and a 512 MiB file whose reads force reclaim. The 4 MiB file is the : hotset: 1,024 pages we expect to survive the cold-file scans. :
: With three hot-file reads per scan, the kernel before the series (A) : kept all 1,024 pages after warmup. The 19-patch kernel (B) sometimes : evicted every one: in 6 of 10 cycles in one run and 3 of 10 in another. : Reading the hot file then took about 2.4-3.2 ms on B versus about 1.3 : ms on A. B also scanned more pages.
:
: The result depends on access rate: with one hot-file read per scan, B : kept the pages and A mostly lost them. So the series helped one : workload but regressed this more frequently read one. The trace points : to hot pages being selected for eviction, but the run did not establish : a safe correction or isolate which of the 19 patches causes it.

Ah I see, this is the typical hot cache pollution vs code cache pollution issue. Here it's trying to fit 512MB + 4MB in a 128MB cgroup, so clearly it won't fit and if the 512MB is the cold part, it will turns the memcg LRU over about 4 times.

Quoted 6 lines

Still TLDR (as LRU related things are always complex to explain):
It's a trade off and I consider it a good one, and the problem will be fully covered by refault distance with no regression.

I'm not sure how the agent actually conducted it, and maybe in the test env LRU_REFS_WIDTH is shrunk?

I asked. I'm just playing middle-man here ;)

: The test used the v7 patch's one-bit LRU_REFS_WIDTH. It was not ; reduced further by the guest configuration. The 512 MiB file was read : once per cycle, so I agree it became a repeatedly refaulted set rather : than a cold scan.

Quoted 22 lines

See this table which I collected from my VM (30 rounds):

setup    | 512M warm + 4M hot (3 reads)        | 64M hot (3 reads) -> 72M hot (loop)
baseline | keeps the 4M (27/30)                | keeps 64M, FAILS to cache 72M (fd)
FG       | LOSES 4M (14/30) try cache the 512M | keeps 64M, fully caches 72M
FG+RD    | keeps the 4M (30/30)                | keeps 64M, fully caches 72M

The 64+72 column is to demostrate the stall-LRU problem: 64M is scanned 3 times, then it loops on the 72M set. Mainline over protects the old 64M set, so the new 72M only gets 64M cached and thrashes every scan (cost ~473ms per scan). FG demotes the old set and caches 72M fully (only 5-7ms per scan now). The stall LRU issue is harder to handler as it could get stuck there forever.

Clearly for the 512M / 4M case we should not try cache the 512M part at all since it won't fit anyway. To solve that properly we can use refault distance, which is described in the cover letter (refault distance can help the workingset shift go faster too in some case, in this case is can help to prevent invalid shift). This RD code is also what I posted previously:

Quoted 7 lines

https://lore.kernel.org/linux-mm/avd5bI-b9y1nKWw5@KASONG-MC4/

Also results on Maxim case here:
https://lore.kernel.org/linux-mm/CAMgjq7DDUHrHEXiGDnPn6+keL6VxWWMabAr-BRrNM_bwsKPZnQ@mail.gmail.com/

With the above refault distance adaption, FG + RD behaves better in all rounds.

The tested v7 series doesn't contain RD, and the May RFC may differ from what I tested. Once that's ready I can redo some testing if that's useful.

Quoted 4 lines
Quoted 2 lines

And it proposed a little GUP speedup:

This one looks good to me, thanks!

Cool, please do whatever you like with it.
(are you sure that function should be inlined? It's pretty large, has several callsites).

I had it prepare and test a userspace repro for the possible issue which it reported. Hopefully useful.

: I reran the attached C program using the attached guest shell script in : fresh x86-64 QEMU guests (64 vCPUs, two NUMA nodes, 16 GiB). A ended : before the 19 MGLRU-FG v7 patches; B ended after all 19. Both used the : same effective .config, with later queue patches excluded. Each run : used ext4 files, a 4 MiB hot file read three times per cycle, a : 512 MiB file read once per cycle, and a 128 MiB memory cgroup. :
: The A/B/B/A runs each completed ten cycles. After the first cycle, : both A runs retained all 1,024 hot pages after every large-file scan. : B retained none after six scans in its first run and four in its : second. Mean hot-file read time over cycles 1-9 was 1.52/1.53 ms on : A and 2.48/2.13 ms on B. B scanned 1.75 million pages per run, : versus 1.28 million on A. There were no OOM events. The shell script : and C source hashes matched in every guest, and all guests shut down. :
: The whole v7 series again loses the hot file in this workload. The : 512 MiB file is reread each cycle, so its pages repeatedly refault. : This comparison does not identify an individual patch responsible or : test the proposed refault-distance changes.

#!/usr/bin/env bash
# Run as root in a disposable guest. Keep mglru-fg-hotset.c alongside this # script, or pass the C file as its sole argument. Reboot between A/B runs. set -e

src=${1:-mglru-fg-hotset.c}
cg=/sys/fs/cgroup/mglru-hotset

cc -O2 -Wall -Wextra -o mglru-hotset "$src"
dd if=/dev/zero of=/root/hot bs=1M count=4 conv=fdatasync status=none dd if=/dev/zero of=/root/cold bs=1M count=512 conv=fdatasync status=none sync
echo 3 > /proc/sys/vm/drop_caches
echo 0x0007 > /sys/kernel/mm/lru_gen/enabled
cat /sys/kernel/mm/lru_gen/enabled
mkdir "$cg"
test -e "$cg/memory.max"
echo 134217728 > "$cg/memory.max"
sh -c 'echo $$ > "$1/cgroup.procs"; exec "$2" "$3" "$4"' \
sh "$cg" ./mglru-hotset /root/hot /root/cold
cat "$cg/memory.events"
grep -E '^(workingset_refault_file|pgscan|pgsteal|file) ' "$cg/memory.stat" rmdir "$cg"

/*
* MGLRU-FG hot-file eviction reproducer
*
* Compare A (without the 19 MGLRU-FG v7 patches) with B (all 19 patches).
* Use the same effective kernel configuration and a fresh boot for each
* run. The reported case used a 64-vCPU, two-node, 16-GiB x86-64 guest;
* the 128-MiB memory cgroup, not guest RAM, provides the pressure. *
* The companion run-mglru-fg-hotset.sh script performs all guest setup,
* runs this program, prints the cgroup counters and removes what it
* created. Put both files in one directory; inside each guest run:
*
* chmod +x run-mglru-fg-hotset.sh
* ./run-mglru-fg-hotset.sh | tee /root/hotset-run.log
*
* Run once per fresh boot in A/B/B/A order. The script does not build or
* select a kernel; boot the chosen A or B kernel before invoking it.
* These are the script's guest operations, shown here for inspection.
* Run the commands below as root inside each disposable guest. Use a
* disk-backed filesystem with at least 516 MiB free for the input files;
* /root on an ext4 guest root works. Do not put the files on tmpfs. The
* guest needs 4096-byte pages, cgroup v2 with its memory controller, and
* CONFIG_LRU_GEN=y. Prepare the files outside the constrained cgroup.
* CONFIG_LRU_GEN_ENABLED need not be set: enable MGLRU at runtime below.
* Check the guest before running: the commands below must print cgroup2fs,
* 4096, memory, and at least 516 MiB of available disk space, respectively. *

 *   stat -fc %T /sys/fs/cgroup
 *   getconf PAGESIZE
 *   grep -w memory /sys/fs/cgroup/cgroup.controllers
 *   df -BM /root
 *
 * The memory controller must be enabled for children of the root cgroup:
 * after mkdir below, check that "$cg/memory.max" exists. If it does not,
 * enable +memory in the parent's cgroup.subtree_control in a guest with
 * a suitable cgroup hierarchy, then recreate the child and check again.
 * Stop if any prerequisite fails; an unbounded run is not comparable.
 *
 *   cc -O2 -Wall -Wextra -o mglru-fg-hotset mglru-fg-hotset.c
 *   dd if=/dev/zero of=/root/hot bs=1M count=4 \
 *      conv=fdatasync status=none
 *   dd if=/dev/zero of=/root/cold bs=1M count=512 \
 *      conv=fdatasync status=none
 *   sync
 *   echo 3 > /proc/sys/vm/drop_caches
 *   echo 0x0007 > /sys/kernel/mm/lru_gen/enabled
 *   cat /sys/kernel/mm/lru_gen/enabled
 *   cg=/sys/fs/cgroup/mglru-hotset
 *   mkdir "$cg"
 *   test -e "$cg/memory.max"
 *   echo 134217728 > "$cg/memory.max"
 *   sh -c 'echo $$ > "$1/cgroup.procs"; exec "$2" "$3" "$4"' \

* sh "$cg" ./mglru-fg-hotset /root/hot /root/cold
* cat "$cg/memory.events"
* grep -E '^(workingset_refault_file|pgscan|pgsteal|file) ' \
* "$cg/memory.stat"
* rmdir "$cg"
*
* The drop_caches command discards the guest's page cache, including
* unrelated cached files: run it only in the disposable guest. Verify
* that lru_gen/enabled reads back as 0x0007 and memory.events shows no
* oom or oom_kill. Create a fresh cgroup for each run. Repeat with fresh
* boots in A/B/B/A order to see whether results vary between runs.
* Check that each run prints exactly ten cycle lines and exits with 0;
* retain its source checksum, boot ID, output and cgroup counters. A
* missing controller, OOM kill, or failed read invalidates that run. *
* Each cycle reads every page of the 4-MiB file three times with pread,
* reads every page of the 512-MiB file once, and uses mincore on a
* never-touched mapping of the hot file to count its cached pages. There
* are ten cycles. The 512-MiB file is reread on each cycle: later scans
* refault pages from this file, so it is not a one-time cold scan. *
* hot_resident reports the hot pages present immediately after that
* cycle's large-file scan, out of 1024 possible pages. hot_ms measures
* the three hot-file reads BEFORE the large-file scan in that cycle.
* Eviction reported at the end of cycle N can therefore slow the hot
* reads in cycle N+1. The observed A runs retained 1024/1024 after
* warmup; B sometimes retained 0/1024. Compare paired run counts and
* timings, not one cycle alone. mincore observes page-cache residency;
* this program does not measure refault distance or establish why the
* pages were selected for eviction.
*/
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>

enum { PAGE_BYTES = 4096, HOT_BYTES = 4 * 1024 * 1024,

       COLD_BYTES = 512 * 1024 * 1024, CYCLES = 10 };

static double seconds(void)

{
	struct timespec ts;

	if (clock_gettime(CLOCK_MONOTONIC, &ts)) {
		perror("clock_gettime");
		exit(1);
	}
	return ts.tv_sec + ts.tv_nsec / 1e9;
}

static void read_pages(int fd, size_t bytes, int passes)

{
	char buf[PAGE_BYTES];

	for (int pass = 0; pass < passes; pass++) {
		for (size_t offset = 0; offset < bytes; offset += sizeof(buf)) {
			ssize_t n = pread(fd, buf, sizeof(buf), (off_t)offset);

			if (n != sizeof(buf)) {
				if (n < 0)
					perror("pread");
				else
					fprintf(stderr, "short pread at offset %zu\n", offset);
				exit(1);
			}
		}
	}
}

static int open_file(const char *path, off_t min_size)

{
	struct stat st;
	int fd = open(path, O_RDONLY);

	if (fd < 0 || fstat(fd, &st)) {
		perror(path);
		exit(1);
	}
	if (!S_ISREG(st.st_mode) || st.st_size < min_size) {
		fprintf(stderr, "%s must be a regular file of at least %lld bytes\n",
			path, (long long)min_size);
		exit(1);
	}
	return fd;
}

int main(int argc, char **argv)

{
	unsigned char present[HOT_BYTES / PAGE_BYTES];
	double start, hot_ms, cold_ms;
	void *mapping;
	int hot, cold;

	if (argc != 3) {
		fprintf(stderr, "usage: %s HOT_FILE COLD_FILE\n", argv[0]);
		return 2;
	}
	if (sysconf(_SC_PAGESIZE) != PAGE_BYTES) {
		fprintf(stderr, "this test needs 4096-byte pages\n");
		return 2;
	}
	hot = open_file(argv[1], HOT_BYTES);
	cold = open_file(argv[2], COLD_BYTES);
	mapping = mmap(NULL, HOT_BYTES, PROT_READ, MAP_SHARED, hot, 0);
	if (mapping == MAP_FAILED) {
		perror("mmap");
		return 1;
	}
	for (int cycle = 0; cycle < CYCLES; cycle++) {
		size_t resident = 0;

		start = seconds();
		read_pages(hot, HOT_BYTES, 3);
		hot_ms = (seconds() - start) * 1000;
		start = seconds();
		read_pages(cold, COLD_BYTES, 1);
		cold_ms = (seconds() - start) * 1000;
		if (mincore(mapping, HOT_BYTES, present)) {
			perror("mincore");
			return 1;
		}
		for (size_t i = 0; i < sizeof(present); i++)
			resident += !!(present[i] & 1);
		printf("cycle=%d hot_ms=%.2f cold_ms=%.2f "
		       "hot_resident=%zu/1024\n",
		       cycle, hot_ms, cold_ms, resident);
		fflush(stdout);
	}
	munmap(mapping, HOT_BYTES);
	close(cold);
	close(hot);
	return 0;
}