Skip to contentSkip to conversation

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

PATCH Superseded Kairui Song 12 participants 104 messages Nov 23 – Dec 2 Page 1 of 2

Subsystems (19)

v6 of 7 Superseded Latest is v7 →

lore
Share & tools
lore

Kairui Song

author maintainer
#0 lore raw

v6 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 file reclaim much 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 recent swappiness fix also exposes the weakness of the PID controller, which almost stalls the build when reclaim is aimed at file folios, while FG promotes file folios much more proactively. This is consistent with the pgrefill counter below (Before -> After: the PID protects almost nothing at sw=200):

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

Note, this may read as if reclaim efficiency dropped slightly, which is quite the opposite: FG softens the ineffective PID factor, and the lazy promotion filters the workingset out proactively, so the scan count may look bigger. We are just lacking an activation counter for MGLRU to separate the two. Unfortunately that does not fit directly as there is no activation for MGLRU; we may discuss and improve MGLRU's statistic counters as a follow up.

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 an reference shows the reworked readings are indeed normal and reliable, which should hoefully 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 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. Similiar 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 (16):
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/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                            |   6 +-
 include/linux/memcontrol.h                    |  71 +++-
 include/linux/mm_inline.h                     | 388 ++++++++++++------
 include/linux/mmzone.h                        | 150 ++++---
 include/linux/page-flags.h                    |   2 -
 kernel/bounds.c                               |   2 +-
 mm/damon/paddr.c                              |   3 +-
 mm/filemap.c                                  |   1 +
 mm/folio.c                                    |  92 +----
 mm/gup.c                                      |   6 +-
 mm/huge_memory.c                              |   8 +-
 mm/khugepaged.c                               |   4 +-
 mm/madvise.c                                  |  54 ++-
 mm/memcontrol.c                               |  15 +-
 mm/migrate.c                                  |   2 -
 mm/page_io.c                                  |   1 +
 mm/vmscan.c                                   | 548 ++++++++++++++++++--------
 mm/vmscan.h                                   |   2 +-
 mm/workingset.c                               |  47 ++-
 22 files changed, 910 insertions(+), 500 deletions(-)

---
base-commit: 87cdbd9bd63174de47ba16555bfe9800a8f3da07
change-id: 20260722-mglru-fg-3a2c8574725b

Best regards,

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

PATCH v6 1/18 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.

[kasong: dropped the comment table part, the series rewrites it]
---
 include/linux/mm_inline.h | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)
include/linux/mm_inline.h +6 -6
index f6f4bc9a704f..2395ca8ee305 100644
@@ -302,7 +302,7 @@ static inline unsigned long lru_gen_folio_seq(const struct lruvec *lruvec,
 					      const struct folio *folio,
 					      bool reclaiming)
 {
-	int gen;
+	int age;
 	int type = folio_is_file_lru(folio);
 	const struct lru_gen_folio *lrugen = &lruvec->lrugen;
 
@@ -319,17 +319,17 @@ 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 (reclaiming)
-		gen = MAX_NR_GENS;
+		age = MAX_NR_GENS;
 	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]));
 }
 
 static inline bool __lru_gen_add_folio(struct lruvec *lruvec, struct folio *folio,
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: Tue, 24 Nov 2026 02:52:53 +0800

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

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 file reclaim much 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 recent swappiness fix also exposes the weakness of the PID controller, which almost stalls the build when reclaim is aimed at file folios, while FG promotes file folios much more proactively. This is consistent with the pgrefill counter below (Before -> After: the PID protects almost nothing at sw=200):

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

Note, this may read as if reclaim efficiency dropped slightly, which is quite the opposite: FG softens the ineffective PID factor, and the lazy promotion filters the workingset out proactively, so the scan count may look bigger. We are just lacking an activation counter for MGLRU to separate the two. Unfortunately that does not fit directly as there is no activation for MGLRU; we may discuss and improve MGLRU's statistic counters as a follow up.

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 an reference shows the reworked readings are indeed normal and reliable, which should hoefully 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 18):

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 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 Tianyi Chen <[email protected]>
Cc Harry Yoo <[email protected]>
 include/linux/mm_inline.h |   12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)
include/linux/mm_inline.h renamed from include/linux/mm_inline.h~mm-mglru-rename-the-generation-offset-in-lru_gen_folio_seq +6 -6
@@ -302,7 +302,7 @@ static inline unsigned long lru_gen_foli
 					      const struct folio *folio,
 					      bool reclaiming)
 {
-	int gen;
+	int age;
 	int type = folio_is_file_lru(folio);
 	const struct lru_gen_folio *lrugen = &lruvec->lrugen;
 
@@ -319,17 +319,17 @@ 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 (reclaiming)
-		gen = MAX_NR_GENS;
+		age = MAX_NR_GENS;
 	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]));
 }
 
 static inline bool __lru_gen_add_folio(struct lruvec *lruvec, struct folio *folio,

_

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-rename-the-generation-offset-in-lru_gen_folio_seq.patch mm-mglru-skip-the-flags-cmpxchg-when-nothing-changes.patch

maintainer Reviewed-by on v6 1/18
#3 lore raw

Re: [PATCH v6 01/18] mm/mglru: rename the generation offset in lru_gen_folio_seq()

In reply to Kairui Song
Quoted 11 lines · On Tue, 24 Nov 2026 02:52:53 +0800 Kairui Song via B4 Relay…

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.

Looks good to me.

Quoted 8 lines
[kasong: dropped the comment table part, the series rewrites it]

Thanks,
SJ

[...]

maintainer tree notice
#4 lore raw

[to-be-updated] mm-mglru-rename-the-generation-offset-in-lru_gen_folio_seq.patch removed from -mm tree

In reply to Kairui Song
The quilt patch titled Subject: mm/mglru: rename the generation offset in lru_gen_folio_seq() has been removed from the -mm tree. Its filename was…

The quilt patch titled
Subject: mm/mglru: rename the generation offset in lru_gen_folio_seq()
has been removed from the -mm tree. Its filename was
mm-mglru-rename-the-generation-offset-in-lru_gen_folio_seq.patch

This patch was dropped because an updated version will be issued

------------------------------------------------------
From: Ridong Chen <[email protected]>
Subject: mm/mglru: rename the generation offset in lru_gen_folio_seq()
Date: Tue, 24 Nov 2026 02:52:53 +0800

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

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 file reclaim much 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 recent swappiness fix also exposes the weakness of the PID controller, which almost stalls the build when reclaim is aimed at file folios, while FG promotes file folios much more proactively. This is consistent with the pgrefill counter below (Before -> After: the PID protects almost nothing at sw=200):

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

Note, this may read as if reclaim efficiency dropped slightly, which is quite the opposite: FG softens the ineffective PID factor, and the lazy promotion filters the workingset out proactively, so the scan count may look bigger. We are just lacking an activation counter for MGLRU to separate the two. Unfortunately that does not fit directly as there is no activation for MGLRU; we may discuss and improve MGLRU's statistic counters as a follow up.

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 an reference shows the reworked readings are indeed normal and reliable, which should hoefully 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 18):

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 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 Tianyi Chen <[email protected]>
Cc Harry Yoo <[email protected]>
 include/linux/mm_inline.h |   12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)
include/linux/mm_inline.h renamed from include/linux/mm_inline.h~mm-mglru-rename-the-generation-offset-in-lru_gen_folio_seq +6 -6
@@ -302,7 +302,7 @@ static inline unsigned long lru_gen_foli
 					      const struct folio *folio,
 					      bool reclaiming)
 {
-	int gen;
+	int age;
 	int type = folio_is_file_lru(folio);
 	const struct lru_gen_folio *lrugen = &lruvec->lrugen;
 
@@ -319,17 +319,17 @@ 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 (reclaiming)
-		gen = MAX_NR_GENS;
+		age = MAX_NR_GENS;
 	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]));
 }
 
 static inline bool __lru_gen_add_folio(struct lruvec *lruvec, struct folio *folio,

_

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-skip-the-flags-cmpxchg-when-nothing-changes.patch

author maintainer
#5 lore raw

PATCH v6 2/18 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.

---
 include/linux/mm_inline.h | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)
include/linux/mm_inline.h +2 -3
index 2395ca8ee305..2edb9beef6d3 100644
@@ -47,12 +47,11 @@ static __always_inline void __update_lru_size(struct lruvec *lruvec,
 {
 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
 
-	lockdep_assert_held(&lruvec->lru_lock);
 	WARN_ON_ONCE(nr_pages != (int)nr_pages);
 
 	mod_lruvec_state(lruvec, NR_LRU_BASE + lru, nr_pages);
-	__mod_zone_page_state(&pgdat->node_zones[zid],
-				NR_ZONE_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,
Signature · 1 line
2.56.1
maintainer tree notice
#6 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: Tue, 24 Nov 2026 02:52:54 +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.

Cc Johannes Weiner <[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 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 Tianyi Chen <[email protected]>
Cc Ridong Chen <[email protected]>
Cc Harry Yoo <[email protected]>
 include/linux/mm_inline.h |    5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)
include/linux/mm_inline.h renamed from include/linux/mm_inline.h~mm-memcontrol-allow-update-of-lru-statistic-without-holding-lru-lock +2 -3
@@ -47,12 +47,11 @@ static __always_inline void __update_lru
 {
 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
 
-	lockdep_assert_held(&lruvec->lru_lock);
 	WARN_ON_ONCE(nr_pages != (int)nr_pages);
 
 	mod_lruvec_state(lruvec, NR_LRU_BASE + lru, nr_pages);
-	__mod_zone_page_state(&pgdat->node_zones[zid],
-				NR_ZONE_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,

_

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-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 v6 2/18
#7 lore raw

Re: [PATCH v6 02/18] mm/memcontrol: allow update of LRU statistic without holding LRU lock

In reply to Kairui Song
Quoted 6 lines · On Tue, 24 Nov 2026 02:52:54 +0800 Kairui Song via B4 Relay…

From: Kairui Song <[email protected]>

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.

Makes sense to me.

Quoted 7 lines

Thanks,
SJ

[...]

Reviewed-by on v6 2/18
#8 lore raw

Re: [PATCH v6 02/18] mm/memcontrol: allow update of LRU statistic without holding LRU lock

In reply to Kairui Song
Quoted 27 lines · On 11/24/2026 2:52 AM, Kairui Song via B4 Relay wrote:

From: Kairui Song <[email protected]>

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.

---
  include/linux/mm_inline.h | 5 ++---
  1 file changed, 2 insertions(+), 3 deletions(-)
include/linux/mm_inline.h +0 -1
index 2395ca8ee305..2edb9beef6d3 100644
@@ -47,12 +47,11 @@ static __always_inline void __update_lru_size(struct lruvec *lruvec,
  {
  	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
 
-	lockdep_assert_held(&lruvec->lru_lock);

include/linux/mm_inline.h static __always_inline void __update_lru_size(struct lruvec *lruvec, · line 57

Quoted 10 lines
include/linux/mm_inline.h +2 -2
  	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);
+	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,

Thanks.

Signature · 2 lines
Best regards
Ridong
maintainer tree notice
#9 lore raw

[to-be-updated] mm-memcontrol-allow-update-of-lru-statistic-without-holding-lru-lock.patch removed from -mm tree

In reply to Kairui Song
The quilt patch titled Subject: mm/memcontrol: allow update of LRU statistic without holding LRU lock has been removed from the -mm tree. Its filename was…

The quilt patch titled
Subject: mm/memcontrol: allow update of LRU statistic without holding LRU lock
has been removed from the -mm tree. Its filename was
mm-memcontrol-allow-update-of-lru-statistic-without-holding-lru-lock.patch

This patch was dropped because an updated version will be issued

------------------------------------------------------
From: Kairui Song <[email protected]>
Subject: mm/memcontrol: allow update of LRU statistic without holding LRU lock
Date: Tue, 24 Nov 2026 02:52:54 +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.

Cc Johannes Weiner <[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 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 Tianyi Chen <[email protected]>
Cc Ridong Chen <[email protected]>
Cc Harry Yoo <[email protected]>
 include/linux/mm_inline.h |    5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)
include/linux/mm_inline.h renamed from include/linux/mm_inline.h~mm-memcontrol-allow-update-of-lru-statistic-without-holding-lru-lock +2 -3
@@ -47,12 +47,11 @@ static __always_inline void __update_lru
 {
 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
 
-	lockdep_assert_held(&lruvec->lru_lock);
 	WARN_ON_ONCE(nr_pages != (int)nr_pages);
 
 	mod_lruvec_state(lruvec, NR_LRU_BASE + lru, nr_pages);
-	__mod_zone_page_state(&pgdat->node_zones[zid],
-				NR_ZONE_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,

_

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

#10 lore raw

Re: [PATCH v6 02/18] mm/memcontrol: allow update of LRU statistic without holding LRU lock

In reply to Kairui Song
Quoted 27 lines · On 11/24/2026 2:52 AM, Kairui Song via B4 Relay wrote:

From: Kairui Song <[email protected]>

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.

---
  include/linux/mm_inline.h | 5 ++---
  1 file changed, 2 insertions(+), 3 deletions(-)
include/linux/mm_inline.h +0 -1
index 2395ca8ee305..2edb9beef6d3 100644
@@ -47,12 +47,11 @@ static __always_inline void __update_lru_size(struct lruvec *lruvec,
  {
  	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
 
-	lockdep_assert_held(&lruvec->lru_lock);

include/linux/mm_inline.h static __always_inline void __update_lru_size(struct lruvec *lruvec, · line 57

Quoted 10 lines
include/linux/mm_inline.h +2 -2
  	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);
+	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,

Hi Kairui,

Just a heads-up: this may conflict with Joanne's "mm: move LRU size stat updates out of lru_lock in folio batches" [1], which is in linux-next now.

That patch makes __update_lru_size() add to a batch attached to the lruvec by the lru_lock holder, and relies on lockdep_assert_held() there. Once this patch lets folio_inc_lru_refs()/folio_reset_lru_refs() call it without the lock, they could write into another CPU's on-stack batch. So the lockless paths probably need to bypass the batch.

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

Signature · 2 lines
Best regards
Ridong
#11 lore raw

Re: [PATCH v6 02/18] mm/memcontrol: allow update of LRU statistic without holding LRU lock

Quoted 43 lines · Ridong Chen
Quoted 24 lines · On 11/24/2026 2:52 AM, Kairui Song via B4 Relay wrote:

From: Kairui Song <[email protected]>

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.

---
  include/linux/mm_inline.h | 5 ++---
  1 file changed, 2 insertions(+), 3 deletions(-)
include/linux/mm_inline.h +0 -0
index 2395ca8ee305..2edb9beef6d3 100644
@@ -47,12 +47,11 @@ static __always_inline void __update_lru_size(struct lruvec *lruvec,
  {
  	struct pglist_data *pgdat = lruvec_pgdat(lruvec);

include/linux/mm_inline.h static __always_inline void __update_lru_size(struct lruvec *lruvec, · line 55

Quoted 10 lines
include/linux/mm_inline.h +2 -3
-	lockdep_assert_held(&lruvec->lru_lock);
  	WARN_ON_ONCE(nr_pages != (int)nr_pages);
  	mod_lruvec_state(lruvec, NR_LRU_BASE + lru, nr_pages);
-	__mod_zone_page_state(&pgdat->node_zones[zid],
-				NR_ZONE_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,
 

Hi Kairui,

Just a heads-up: this may conflict with Joanne's "mm: move LRU size stat updates out of lru_lock in folio batches" [1], which is in linux-next now.

Quoted 7 lines

That patch makes __update_lru_size() add to a batch attached to the lruvec by the lru_lock holder, and relies on lockdep_assert_held() there. Once this patch lets folio_inc_lru_refs()/folio_reset_lru_refs() call it without the lock, they could write into another CPU's on-stack batch. So the lockless paths probably need to bypass the batch.

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

Yes I'm aware of that, the fix is easy too, something like:

include/linux/mm_inline.h +12 -0
index 4ca8011bd288..fb5e3990402c 100644
@@ -64,6 +64,30 @@ static __always_inline void __update_lru_size(struct lruvec *lruvec,
 				NR_ZONE_LRU_BASE + lru, nr_pages);
 }
 
+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);
+
+	VM_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)

---

And I think that batch design could be somehow improved too, holding a stack variable in a global struct looks a bit odd, could be simplified if we audit and update all users for update_lru_size later.

author maintainer
#12 lore raw

PATCH v6 3/18 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 091401cecf39..3f551e2e3206 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
#13 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: Tue, 24 Nov 2026 02:52:55 +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 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]>
Cc Harry Yoo <[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
@@ -562,11 +562,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())
@@ -577,7 +576,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;
@@ -595,7 +601,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-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

Reviewed-by on v6 3/18
#14 lore raw

Re: [PATCH v6 03/18] mm/memcontrol: avoid potential counter leak when reparenting local stats

In reply to Kairui Song
Quoted 87 lines · On Tue, Nov 24, 2026 at 2:53 AM Kairui Song via B4 Relay…

From: Kairui Song <[email protected]>

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 -5
index 091401cecf39..3f551e2e3206 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);
 
--
Quoted 3 lines

2.56.1

Thanks for following up, Kairui. Reparenting the raw signed count fixes the case I had in mind. I also checked the clear_refs and workingset changes in v6. Both look good to me.

maintainer Reviewed-by on v6 3/18
#15 lore raw

Re: [PATCH v6 03/18] mm/memcontrol: avoid potential counter leak when reparenting local stats

In reply to Kairui Song
Quoted 29 lines · On Tue, 24 Nov 2026 02:52:55 +0800 Kairui Song <[email protected]> wrote:

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.

Quoted 2 lines

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

Makes sense to me.

Quoted 4 lines

Thanks,
SJ

[...]

maintainer tree notice
#16 lore raw

[to-be-updated] mm-memcontrol-avoid-potential-counter-leak-when-reparenting-local-stats.patch removed from -mm tree

In reply to Kairui Song
The quilt patch titled Subject: mm/memcontrol: avoid potential counter leak when reparenting local stats has been removed from the -mm tree. Its filename was…

The quilt patch titled
Subject: mm/memcontrol: avoid potential counter leak when reparenting local stats
has been removed from the -mm tree. Its filename was
mm-memcontrol-avoid-potential-counter-leak-when-reparenting-local-stats.patch

This patch was dropped because an updated version will be issued

------------------------------------------------------
From: Kairui Song <[email protected]>
Subject: mm/memcontrol: avoid potential counter leak when reparenting local stats
Date: Tue, 24 Nov 2026 02:52:55 +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 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]>
Cc Harry Yoo <[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
@@ -562,11 +562,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())
@@ -577,7 +576,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;
@@ -595,7 +601,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-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-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

Reviewed-by on v6 3/18
#17 lore raw

Re: [PATCH v6 03/18] mm/memcontrol: avoid potential counter leak when reparenting local stats

In reply to Kairui Song
Quoted 76 lines · On 11/24/2026 2:52 AM, Kairui Song via B4 Relay wrote:

From: Kairui Song <[email protected]>

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 +9 -3
index 091401cecf39..3f551e2e3206 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;

mm/memcontrol.c void reparent_memcg_lruvec_state_local(struct mem_cgroup *memcg, · line 608

Quoted 9 lines
mm/memcontrol.c +2 -1
@@ -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);

LGTM.

Thanks.

Signature · 2 lines
Best regards
Ridong
author maintainer
#18 lore raw

PATCH v6 4/18 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 2edb9beef6d3..46beded51c7d 100644
@@ -265,11 +265,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 bc7579d47f9b..202e0f874b23 100644
@@ -3350,8 +3350,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;
@@ -3971,11 +3970,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;
 	}
@@ -4093,8 +4089,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;
@@ -4625,8 +4621,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;
 
@@ -4634,9 +4635,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
#19 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: Tue, 24 Nov 2026 02:52:56 +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 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 Tianyi Chen <[email protected]>
Cc Ridong Chen <[email protected]>
Cc Harry Yoo <[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
@@ -265,11 +265,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
@@ -3350,8 +3350,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;
@@ -3971,11 +3970,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;
 	}
@@ -4093,8 +4089,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;
@@ -4625,8 +4621,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;
 
@@ -4634,9 +4635,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-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 v6 4/18
#20 lore raw

Re: [PATCH v6 04/18] mm/mglru: make generation page counters atomic

In reply to Kairui Song
Quoted 6 lines · On Tue, 24 Nov 2026 02:52:56 +0800 Kairui Song via B4 Relay…

From: Kairui Song <[email protected]>

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.

Makes sense to me.

Quoted 7 lines

Thanks,
SJ

[...]

maintainer tree notice
#21 lore raw

[to-be-updated] mm-mglru-make-generation-page-counters-atomic.patch removed from -mm tree

In reply to Kairui Song
The quilt patch titled Subject: mm/mglru: make generation page counters atomic has been removed from the -mm tree. Its filename was mm-mglru-make-generation-page-counters-atomic.patch

The quilt patch titled
Subject: mm/mglru: make generation page counters atomic
has been removed from the -mm tree. Its filename was
mm-mglru-make-generation-page-counters-atomic.patch

This patch was dropped because an updated version will be issued

------------------------------------------------------
From: Kairui Song <[email protected]>
Subject: mm/mglru: make generation page counters atomic
Date: Tue, 24 Nov 2026 02:52:56 +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 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 Tianyi Chen <[email protected]>
Cc Ridong Chen <[email protected]>
Cc Harry Yoo <[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
@@ -265,11 +265,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
@@ -3350,8 +3350,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;
@@ -3971,11 +3970,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;
 	}
@@ -4093,8 +4089,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;
@@ -4625,8 +4621,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;
 
@@ -4634,9 +4635,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-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-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

Reviewed-by on v6 4/18
#22 lore raw

Re: [PATCH v6 04/18] mm/mglru: make generation page counters atomic

In reply to Kairui Song
Quoted 123 lines · On 11/24/2026 2:52 AM, Kairui Song via B4 Relay wrote:

From: Kairui Song <[email protected]>

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 2edb9beef6d3..46beded51c7d 100644
@@ -265,11 +265,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 bc7579d47f9b..202e0f874b23 100644
@@ -3350,8 +3350,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;
@@ -3971,11 +3970,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;
  	}
@@ -4093,8 +4089,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;
@@ -4625,8 +4621,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;
 
@@ -4634,9 +4635,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 +0 -0
index c2cea36289f3..6551f0a6691a 100644

mm/vmscan.h static inline unsigned long lruvec_gen_size(struct lru_gen_folio *lrugen, · line 132

Quoted 8 lines
mm/vmscan.h +1 -1
@@ -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;
  }

Thanks.

Signature · 2 lines
Best regards
Ridong
author maintainer
#23 lore raw

PATCH v6 5/18 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 980358bc6f49..a03f9711522e 100644
@@ -571,6 +571,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,
@@ -1349,6 +1354,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)
@@ -1510,28 +1520,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;
 }
 
@@ -1561,6 +1584,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)
@@ -1826,11 +1877,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)
 {
@@ -1901,11 +1947,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
#24 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: Tue, 24 Nov 2026 02:52:57 +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]>
Cc Ridong Chen <[email protected]>
Cc Harry Yoo <[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
@@ -571,6 +571,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,
@@ -1349,6 +1354,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)
@@ -1510,28 +1520,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;
 }
 
@@ -1561,6 +1584,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)
@@ -1826,11 +1877,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)
 {
@@ -1901,11 +1947,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-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 tree notice
#25 lore raw

[to-be-updated] mm-memcg-add-folio-based-lruvec-live-helper.patch removed from -mm tree

In reply to Kairui Song
The quilt patch titled Subject: mm/memcg: add folio-based lruvec live helper has been removed from the -mm tree. Its filename was mm-memcg-add-folio-based-lruvec-live-helper.patch

The quilt patch titled
Subject: mm/memcg: add folio-based lruvec live helper
has been removed from the -mm tree. Its filename was
mm-memcg-add-folio-based-lruvec-live-helper.patch

This patch was dropped because an updated version will be issued

------------------------------------------------------
From: Kairui Song <[email protected]>
Subject: mm/memcg: add folio-based lruvec live helper
Date: Tue, 24 Nov 2026 02:52:57 +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]>
Cc Ridong Chen <[email protected]>
Cc Harry Yoo <[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
@@ -571,6 +571,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,
@@ -1349,6 +1354,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)
@@ -1510,28 +1520,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;
 }
 
@@ -1561,6 +1584,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)
@@ -1826,11 +1877,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)
 {
@@ -1901,11 +1947,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-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-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

Reviewed-by on v6 5/18
#26 lore raw

Re: [PATCH v6 05/18] mm/memcg: add folio-based lruvec live helper

In reply to Kairui Song
Quoted 155 lines · On 11/24/2026 2:52 AM, Kairui Song via B4 Relay wrote:

From: Kairui Song <[email protected]>

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 -10
index 980358bc6f49..a03f9711522e 100644
@@ -571,6 +571,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,
@@ -1349,6 +1354,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)
@@ -1510,28 +1520,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;
  }
 
@@ -1561,6 +1584,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)
@@ -1826,11 +1877,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)
  {
@@ -1901,11 +1947,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)

include/linux/memcontrol.h static inline void mem_cgroup_node_filter_allowed(struct mem_cgroup *memcg, · line 1952

Quoted 10 lines
include/linux/memcontrol.h +0 -5
  {
  }
-
-static inline bool memcg_is_dying(struct mem_cgroup *memcg)
-{
-	return false;
-}
  #endif /* CONFIG_MEMCG */
 
  #if defined(CONFIG_MEMCG) && defined(CONFIG_LRU_GEN)

LGTM.

Thanks.

Signature · 2 lines
Best regards
Ridong
author maintainer
#27 lore raw

PATCH v6 6/18 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 46beded51c7d..2571b3f01226 100644
@@ -233,6 +233,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 202e0f874b23..15df5618a3cf 100644
@@ -3274,6 +3274,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
#28 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: Tue, 24 Nov 2026 02:52:58 +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 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 Harry Yoo <[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
@@ -233,6 +233,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
@@ -3274,6 +3274,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-rename-the-generation-offset-in-lru_gen_folio_seq.patch mm-mglru-skip-the-flags-cmpxchg-when-nothing-changes.patch

Reviewed-by on v6 6/18
#29 lore raw

Re: [PATCH v6 06/18] mm/mglru: skip the flags cmpxchg when nothing changes

In reply to Kairui Song
Quoted 92 lines · On Tue, Nov 24, 2026 at 02:52:58AM +0800, Kairui Song via B4 Relay wrote:

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 46beded51c7d..2571b3f01226 100644
@@ -233,6 +233,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 -1
index 202e0f874b23..15df5618a3cf 100644
@@ -3274,6 +3274,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);
 
--
Quoted 4 lines

2.56.1

I have done similar tests before, simply skipping the identical old/new flags, and was able to get very good results.

Makes sense to me.

--
Cheers,
Vernon

maintainer tree notice
#30 lore raw

[to-be-updated] mm-mglru-skip-the-flags-cmpxchg-when-nothing-changes.patch removed from -mm tree

In reply to Kairui Song
The quilt patch titled Subject: mm/mglru: skip the flags cmpxchg when nothing changes has been removed from the -mm tree. Its filename was mm-mglru-skip-the-flags-cmpxchg-when-nothing-changes.patch

The quilt patch titled
Subject: mm/mglru: skip the flags cmpxchg when nothing changes
has been removed from the -mm tree. Its filename was
mm-mglru-skip-the-flags-cmpxchg-when-nothing-changes.patch

This patch was dropped because an updated version will be issued

------------------------------------------------------
From: Ridong Chen <[email protected]>
Subject: mm/mglru: skip the flags cmpxchg when nothing changes
Date: Tue, 24 Nov 2026 02:52:58 +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 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 Harry Yoo <[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
@@ -233,6 +233,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
@@ -3274,6 +3274,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

author maintainer
#31 lore raw

PATCH v6 7/18 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 2571b3f01226..f38dad1198fc 100644
@@ -144,12 +144,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);
 }
 
 /**
@@ -187,21 +189,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;
 }
 
 /**
@@ -210,22 +215,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));
@@ -238,14 +252,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);
 
@@ -302,23 +328,24 @@ static inline unsigned long lru_gen_folio_seq(const struct lruvec *lruvec,
 					      bool reclaiming)
 {
 	int age;
+	bool workingset = lru_refs_is_workingset(folio_lru_refs(folio));
 	int type = folio_is_file_lru(folio);
 	const struct lru_gen_folio *lrugen = &lruvec->lrugen;
 
 	/*
-	 * +-----------------------------------+-----------------------------------+
-	 * | Accessed through page tables and  | Accessed through file descriptors |
-	 * | promoted by folio_update_gen()    | and protected by folio_inc_gen()  |
-	 * +-----------------------------------+-----------------------------------+
-	 * | PG_active (set while isolated)    |                                   |
-	 * +-----------------+-----------------+-----------------+-----------------+
-	 * |  PG_workingset  |  PG_referenced  |  PG_workingset  |  LRU_REFS_FLAGS |
-	 * +-----------------------------------+-----------------------------------+
-	 * |<---------- MIN_NR_GENS ---------->|                                   |
-	 * |<---------------------------- MAX_NR_GENS ---------------------------->|
+	 * +------------------------------------------+------------------------------------------+
+	 * |     Accessed through page tables and     |     Accessed through file descriptors    |
+	 * | promoted by folio_inc_lru_refs_walk()    | protected by folio_inc_lru_refs/inc_gen  |
+	 * +------------------------------------------+------------------------------------------+
+	 * | PG_active (set at isolation or refault)  |                                          |
+	 * +--------------------+---------------------+--------------------+---------------------+
+	 * |     LRU_REFS_MAX   | LRU_REFS_WORKINGSET |    LRU_REFS_MAX    | LRU_REFS_WORKINGSET |
+	 * +------------------------------------------+------------------------------------------+
+	 * |<-------------- MIN_NR_GENS ------------->|                                          |
+	 * |<----------------------------------- MAX_NR_GENS ----------------------------------->|
 	 */
 	if (folio_test_active(folio))
-		age = MIN_NR_GENS - folio_test_workingset(folio);
+		age = MIN_NR_GENS - workingset;
 	else if (reclaiming)
 		age = MAX_NR_GENS;
 	else if ((!folio_is_file_lru(folio) && !folio_test_swapcache(folio)) ||
@@ -326,7 +353,7 @@ static inline unsigned long lru_gen_folio_seq(const struct lruvec *lruvec,
 		  (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]));
 }
@@ -341,6 +368,7 @@ static inline bool __lru_gen_add_folio(struct lruvec *lruvec, struct folio *foli
 	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)
@@ -408,7 +436,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 */
@@ -444,6 +471,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
#32 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: Tue, 24 Nov 2026 02:52:59 +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 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]>
Cc Harry Yoo <[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
@@ -144,12 +144,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);
 }
 
 /**
@@ -187,21 +189,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;
 }
 
 /**
@@ -210,22 +215,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));
@@ -238,14 +252,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);
 
@@ -302,23 +328,24 @@ static inline unsigned long lru_gen_foli
 					      bool reclaiming)
 {
 	int age;
+	bool workingset = lru_refs_is_workingset(folio_lru_refs(folio));
 	int type = folio_is_file_lru(folio);
 	const struct lru_gen_folio *lrugen = &lruvec->lrugen;
 
 	/*
-	 * +-----------------------------------+-----------------------------------+
-	 * | Accessed through page tables and  | Accessed through file descriptors |
-	 * | promoted by folio_update_gen()    | and protected by folio_inc_gen()  |
-	 * +-----------------------------------+-----------------------------------+
-	 * | PG_active (set while isolated)    |                                   |
-	 * +-----------------+-----------------+-----------------+-----------------+
-	 * |  PG_workingset  |  PG_referenced  |  PG_workingset  |  LRU_REFS_FLAGS |
-	 * +-----------------------------------+-----------------------------------+
-	 * |<---------- MIN_NR_GENS ---------->|                                   |
-	 * |<---------------------------- MAX_NR_GENS ---------------------------->|
+	 * +------------------------------------------+------------------------------------------+
+	 * |     Accessed through page tables and     |     Accessed through file descriptors    |
+	 * | promoted by folio_inc_lru_refs_walk()    | protected by folio_inc_lru_refs/inc_gen  |
+	 * +------------------------------------------+------------------------------------------+
+	 * | PG_active (set at isolation or refault)  |                                          |
+	 * +--------------------+---------------------+--------------------+---------------------+
+	 * |     LRU_REFS_MAX   | LRU_REFS_WORKINGSET |    LRU_REFS_MAX    | LRU_REFS_WORKINGSET |
+	 * +------------------------------------------+------------------------------------------+
+	 * |<-------------- MIN_NR_GENS ------------->|                                          |
+	 * |<----------------------------------- MAX_NR_GENS ----------------------------------->|
 	 */
 	if (folio_test_active(folio))
-		age = MIN_NR_GENS - folio_test_workingset(folio);
+		age = MIN_NR_GENS - workingset;
 	else if (reclaiming)
 		age = MAX_NR_GENS;
 	else if ((!folio_is_file_lru(folio) && !folio_test_swapcache(folio)) ||
@@ -326,7 +353,7 @@ static inline unsigned long lru_gen_foli
 		  (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]));
 }
@@ -341,6 +368,7 @@ static inline bool __lru_gen_add_folio(s
 	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)
@@ -408,7 +436,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 */
@@ -444,6 +471,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-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 tree notice
#33 lore raw

[to-be-updated] mm-mglru-frequency-guided-workingset-promotion-mglru-fg.patch removed from -mm tree

In reply to Kairui Song
The quilt patch titled Subject: mm/mglru: frequency guided workingset promotion (MGLRU-FG) has been removed from the -mm tree. Its filename was…

The quilt patch titled
Subject: mm/mglru: frequency guided workingset promotion (MGLRU-FG)
has been removed from the -mm tree. Its filename was
mm-mglru-frequency-guided-workingset-promotion-mglru-fg.patch

This patch was dropped because an updated version will be issued

------------------------------------------------------
From: Kairui Song <[email protected]>
Subject: mm/mglru: frequency guided workingset promotion (MGLRU-FG)
Date: Tue, 24 Nov 2026 02:52:59 +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 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]>
Cc Harry Yoo <[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
@@ -144,12 +144,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);
 }
 
 /**
@@ -187,21 +189,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;
 }
 
 /**
@@ -210,22 +215,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));
@@ -238,14 +252,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);
 
@@ -302,23 +328,24 @@ static inline unsigned long lru_gen_foli
 					      bool reclaiming)
 {
 	int age;
+	bool workingset = lru_refs_is_workingset(folio_lru_refs(folio));
 	int type = folio_is_file_lru(folio);
 	const struct lru_gen_folio *lrugen = &lruvec->lrugen;
 
 	/*
-	 * +-----------------------------------+-----------------------------------+
-	 * | Accessed through page tables and  | Accessed through file descriptors |
-	 * | promoted by folio_update_gen()    | and protected by folio_inc_gen()  |
-	 * +-----------------------------------+-----------------------------------+
-	 * | PG_active (set while isolated)    |                                   |
-	 * +-----------------+-----------------+-----------------+-----------------+
-	 * |  PG_workingset  |  PG_referenced  |  PG_workingset  |  LRU_REFS_FLAGS |
-	 * +-----------------------------------+-----------------------------------+
-	 * |<---------- MIN_NR_GENS ---------->|                                   |
-	 * |<---------------------------- MAX_NR_GENS ---------------------------->|
+	 * +------------------------------------------+------------------------------------------+
+	 * |     Accessed through page tables and     |     Accessed through file descriptors    |
+	 * | promoted by folio_inc_lru_refs_walk()    | protected by folio_inc_lru_refs/inc_gen  |
+	 * +------------------------------------------+------------------------------------------+
+	 * | PG_active (set at isolation or refault)  |                                          |
+	 * +--------------------+---------------------+--------------------+---------------------+
+	 * |     LRU_REFS_MAX   | LRU_REFS_WORKINGSET |    LRU_REFS_MAX    | LRU_REFS_WORKINGSET |
+	 * +------------------------------------------+------------------------------------------+
+	 * |<-------------- MIN_NR_GENS ------------->|                                          |
+	 * |<----------------------------------- MAX_NR_GENS ----------------------------------->|
 	 */
 	if (folio_test_active(folio))
-		age = MIN_NR_GENS - folio_test_workingset(folio);
+		age = MIN_NR_GENS - workingset;
 	else if (reclaiming)
 		age = MAX_NR_GENS;
 	else if ((!folio_is_file_lru(folio) && !folio_test_swapcache(folio)) ||
@@ -326,7 +353,7 @@ static inline unsigned long lru_gen_foli
 		  (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]));
 }
@@ -341,6 +368,7 @@ static inline bool __lru_gen_add_folio(s
 	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)
@@ -408,7 +436,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 */
@@ -444,6 +471,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-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-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

#34 lore raw

Re: [PATCH v6 07/18] mm/mglru: frequency guided workingset promotion (MGLRU-FG)

In reply to Kairui Song
Quoted 30 lines · On Tue, Nov 24, 2026 at 02:52:59AM +0800, Kairui Song via B4 Relay wrote:

From: Kairui Song <[email protected]>

[...]

include/linux/mmzone.h +5 -12
index 4e85bb520f76..27ba7fa6ddd6 100644
@@ -453,57 +453,103 @@ enum lruvec_flags {
 #define MAX_NR_GENS		4U
 
 /*
- * Each generation is divided into multiple tiers. A folio accessed N times
- * through file descriptors is in tier order_base_2(N). A folio in the first
- * tier (N=0,1) is marked by PG_referenced unless it was faulted in through page
- * tables or read ahead. A folio in the last tier (MAX_NR_TIERS-1) is marked by
- * PG_workingset. A folio in any other tier (1<N<5) between the first and last
- * is marked by additional bits of LRU_REFS_WIDTH in folio->flags.
+ * Each generation is divided into multiple tiers. A folio's referenced
+ * count maps to a tier as shown below (with one extra refs bit):
  *
- * In contrast to moving across generations which requires the LRU lock, moving
- * across tiers only involves atomic operations on folio->flags and therefore
- * has a negligible cost in the buffered access path. In the eviction path,
- * comparisons of refaulted/(evicted+protected) from the first tier and the rest
- * infer whether folios accessed multiple times through file descriptors are
- * statistically hot and thus worth protecting.
+ * MGLRU (frequency guidance)
+ *  Refs  Tier  |- Refs: observed accesses, capped on promotion.
+ *   0      0   |- Mostly cold pages, readahead, etc. [1]

include/linux/mmzone.h enum lruvec_flags { · line 471

Quoted 10 lines
include/linux/mmzone.h +9 -0
+ *   1      0   |= LRU_REFS_REFERENCED: Used at least once. [2]
+ * -WORKINGSET-+|- Workingset floor, unless explicitly reset. [3]
+ *   2      1<-+|= LRU_REFS_WORKINGSET: Classical workingset, accessed twice, protected. [4]
+ *   3      2   |- LRU_REFS_PROTECTED: Protected workingset, promoted pages capped at here. [5]
+ *   4      2   |
+ *   5      3   |- The tier here is MAX_NR_TIERS - 1
+ *   6      3   |
+ *   7      3   |= LRU_REFS_MAX: Promotion candidate. [6]
+ * -PROMOTION->-/
  *

Excellent design! Unifying the scattered PG_referenced and PG_workingset bits. Thank you very much for your hard work.

Quoted 125 lines

[...]

include/linux/mmzone.h +108 -11
+/**
+ * folio_inc_lru_refs - Update the folio's LRU refs and lazily promote it.
+ * @folio: The folio being accessed.
+ * @flags: The type of ref: FD access, or mapped access optionally with
+ * executable access.
+ *
+ * Used by both cache access (flags == 0) and page table access (flags ==
+ * LRU_REF_MAPPED, optionally with LRU_REF_EXEC).
+ * Context: The caller must keep the folio alive by a reference or the page
+ * table lock of a mapped folio.
+ */
+void folio_inc_lru_refs(struct folio *folio, unsigned int flags)
+{
+	int max_gen;
+	int type, refs, old_gen, gen;
+	unsigned long new_flags, old_flags, max_seq;
+	struct lru_gen_folio *lrugen;
+	struct lruvec *lruvec = NULL;
+
+	type = folio_is_file_lru(folio);
+	old_flags = READ_ONCE(*folio_flags(folio, 0));
+	do {
+		new_flags = old_flags;
+		old_gen = lru_get_gen_flags(old_flags);
+		refs = lru_get_refs_flags(old_flags) + 1;
+		gen = old_gen;
+		if (old_gen < 0)
+			goto out;
+		/*
+		 * Lock the lruvec if the folio is on-list. We are already
+		 * doing lazy promotion so in theory we don't need this,
+		 * but for now, concurrent aging would still corrupt the
+		 * size counters.  This is a temporary limitation and
+		 * will be lifted very soon, so the lock here is not a
+		 * performance concern.
+		 */
+		if (!lruvec) {
+			lruvec = lruvec_live_lock_irq(folio_lruvec(folio));
+			lrugen = &lruvec->lrugen;
 		}
+		max_seq = READ_ONCE(lrugen->max_seq);
+		max_gen = lru_gen_from_seq(max_seq);
+		if (old_gen == max_gen)
+			goto out;
 
-		folio_set_lru_refs(folio, 1);
-		return false;
-	}
+		if (flags & (LRU_REF_MAPPED | LRU_REF_EXEC)) {
+			/* Promote second page table access or executable */
+			if (refs > LRU_REFS_REFERENCED || flags & LRU_REF_EXEC)
+				gen = max_gen;
+			/* First access only defers eviction of an old generation */
+			else if (lru_gen_is_old(lruvec, type, old_gen))
+				gen = (old_gen + 1) % MAX_NR_GENS;
+			refs = min(refs, LRU_REFS_PROTECTED);
+		} else if (refs > LRU_REFS_MAX) {
+			/* LRU refs counting overflow, bump the gen */
+			gen = (old_gen + 1) % MAX_NR_GENS;
+			refs = LRU_REFS_PROTECTED;
+		} else if (lru_gen_is_old(lruvec, type, old_gen) &&
+			   lru_refs_is_workingset(refs)) {
+			/* Defer eviction of just accessed workingset */
+			gen = (old_gen + 1) % MAX_NR_GENS;
+			refs = min(refs, LRU_REFS_PROTECTED);
+		}
+out:
+		refs = min(refs, LRU_REFS_MAX);
+		lru_set_refs_flags(&new_flags, refs);
+		if (gen != old_gen)
+			lru_set_gen_flags(&new_flags, gen);
+		if (new_flags == old_flags)
+			break;
+	} while (!try_cmpxchg(folio_flags(folio, 0), &old_flags, new_flags));
 
-	/* Promote on second access */
-	if (folio_lru_refs(folio) > 1) {
-		folio_set_workingset(folio);
-		folio_set_lru_refs(folio, 0);
-	} else {
-		folio_mark_accessed(folio);
-	}
-	return true;
+	if (gen != old_gen)
+		lru_gen_update_size(lruvec, folio, old_gen, gen);
+	if (lruvec)
+		lruvec_unlock_irq(lruvec);
+}
+
+/**
+ * folio_inc_lru_refs_walk - Update the folio's LRU refs and lazily promote it.
+ * @folio: The folio.
+ * @lruvec: The lruvec the folio belongs to.
+ * @vma_flags: The flags of the VMA being walked.
+ * @new_gen: The gen the folio is moved to; may be unchanged.
+ * @type: Returns the folio's type: file or anon.
+ *
+ * Similar to folio_inc_lru_refs(), but for the page table walker and the
+ * look-around. The LRU size accounting is batched by the caller for
+ * better performance.
+ *
+ * Return: The old generation the folio belongs to if the folio is still
+ * on the LRU and not in the newest generation, or -1 otherwise. -1 means
+ * the folio should not be promoted and @new_gen is not set.
+ */
+static int folio_inc_lru_refs_walk(struct folio *folio, struct lruvec *lruvec,
+				   const vma_flags_t *vma_flags,
+				   int *new_gen, int *type)
+{
+	unsigned long new_flags, old_flags = READ_ONCE(*folio_flags(folio, 0));
+	int refs, gen, max_gen, ret;
+	unsigned long max_seq;
+
+	do {
+		max_seq = READ_ONCE(lruvec->lrugen.max_seq);
+		max_gen = lru_gen_from_seq(max_seq);
+		gen = lru_get_gen_flags(old_flags);
+		refs = lru_get_refs_flags(old_flags) + 1;
+		*type = folio_flags_is_file_lru(&old_flags);
+		new_flags = old_flags;
+
+		if (gen >= 0 && gen != max_gen) {

include/linux/mmzone.h

Quoted 10 lines
include/linux/mmzone.h +10 -0
+			ret = gen;
+			/* Promote second page table access or executable */
+			if (lru_refs_is_workingset(refs) || is_exec_file_folio(folio, vma_flags))
+				*new_gen = max_gen;
+			/* First access only defers eviction of an old generation */
+			else if (lru_gen_is_old(lruvec, *type, gen))
+				*new_gen = (gen + 1) % MAX_NR_GENS;
+			else
+				*new_gen = gen;
+			lru_set_gen_flags(&new_flags, *new_gen);

I see that when folio_inc_lru_refs() sets gen, it checks if (gen != old_gen), a similar check may be needed here as well.

include/linux/mmzone.h

Quoted 1 line
include/linux/mmzone.h +1 -0
+			lru_set_refs_flags(&new_flags, min(refs, LRU_REFS_PROTECTED));

The old refs may also already be equal to LRU_REFS_PROTECTED, do we need to check that as well?

But I also looked at the implementation code for lru_set_gen_flags()/lru_set_refs_flags(), which are simple clear/set operations, so I'm wondering whether the check is really necessary?

Quoted 22 lines
include/linux/mmzone.h +22 -0
+		} else {
+			ret = -1;
+			lru_set_refs_flags(&new_flags, min(refs, LRU_REFS_MAX));
+		}
+		if (new_flags == old_flags)
+			break;
+	} while (!try_cmpxchg(folio_flags(folio, 0), &old_flags, new_flags));
+
+	return ret;
+}
+
+/**
+ * folio_inc_lru_refs_isolated - Update the folio's LRU refs
+ * @folio: The folio.
+ * @vma_flags: The flags of all the VMAs that referenced the folio.
+ *
+ * Similar to folio_inc_lru_refs(), but the folio is isolated.  Only used
+ * on mapped folios upon the final eviction RMAP walk. Since the folio is
+ * isolated, folio promotion needs to be done by the caller.
+ *
+ * Return: true if the caller should activate the folio, false to put it
+ * back in an older gen and wait for a second chance.

include/linux/mmzone.h

Quoted 10 lines
include/linux/mmzone.h +10 -0
+ */
+static bool folio_inc_lru_refs_isolated(struct folio *folio, const vma_flags_t *vma_flags)
+{
+	unsigned long new_flags, old_flags = READ_ONCE(*folio_flags(folio, 0));
+	unsigned int refs;
+
+	do {
+		new_flags = old_flags;
+		refs = lru_get_refs_flags(old_flags) + 1;
+		lru_set_refs_flags(&new_flags, min(refs, LRU_REFS_PROTECTED));

When the old refs already be equal to LRU_REFS_PROTECTED, the following checks may also be needed.

		if (new_flags == old_flags)
			break;

include/linux/mmzone.h

Quoted 4 lines
include/linux/mmzone.h +3 -0
+	} while (!try_cmpxchg(folio_flags(folio, 0), &old_flags, new_flags));
+	/* Promote second page table access or executable */
+	return lru_refs_is_workingset(refs) || is_exec_file_folio(folio, vma_flags);
 }

--
Cheers,
Vernon

#35 lore raw

Re: [PATCH v6 07/18] mm/mglru: frequency guided workingset promotion (MGLRU-FG)

Quoted 37 lines · Vernon Yang
Quoted 35 lines · On Tue, Nov 24, 2026 at 02:52:59AM +0800, Kairui Song via B4 Relay wrote:

From: Kairui Song <[email protected]>

[...]

include/linux/mmzone.h +10 -12
index 4e85bb520f76..27ba7fa6ddd6 100644
@@ -453,57 +453,103 @@ enum lruvec_flags {
 #define MAX_NR_GENS          4U
 
 /*
- * Each generation is divided into multiple tiers. A folio accessed N times
- * through file descriptors is in tier order_base_2(N). A folio in the first
- * tier (N=0,1) is marked by PG_referenced unless it was faulted in through page
- * tables or read ahead. A folio in the last tier (MAX_NR_TIERS-1) is marked by
- * PG_workingset. A folio in any other tier (1<N<5) between the first and last
- * is marked by additional bits of LRU_REFS_WIDTH in folio->flags.
+ * Each generation is divided into multiple tiers. A folio's referenced
+ * count maps to a tier as shown below (with one extra refs bit):
  *
- * In contrast to moving across generations which requires the LRU lock, moving
- * across tiers only involves atomic operations on folio->flags and therefore
- * has a negligible cost in the buffered access path. In the eviction path,
- * comparisons of refaulted/(evicted+protected) from the first tier and the rest
- * infer whether folios accessed multiple times through file descriptors are
- * statistically hot and thus worth protecting.
+ * MGLRU (frequency guidance)
+ *  Refs  Tier  |- Refs: observed accesses, capped on promotion.
+ *   0      0   |- Mostly cold pages, readahead, etc. [1]
+ *   1      0   |= LRU_REFS_REFERENCED: Used at least once. [2]
+ * -WORKINGSET-+|- Workingset floor, unless explicitly reset. [3]
+ *   2      1<-+|= LRU_REFS_WORKINGSET: Classical workingset, accessed twice, protected. [4]
+ *   3      2   |- LRU_REFS_PROTECTED: Protected workingset, promoted pages capped at here. [5]
+ *   4      2   |
Quoted 8 lines

include/linux/mmzone.h enum lruvec_flags { · line 471

Quoted 5 lines
include/linux/mmzone.h +4 -0
+ *   5      3   |- The tier here is MAX_NR_TIERS - 1
+ *   6      3   |
+ *   7      3   |= LRU_REFS_MAX: Promotion candidate. [6]
+ * -PROMOTION->-/
  *

Excellent design! Unifying the scattered PG_referenced and PG_workingset bits. Thank you very much for your hard work.

Thank you for the review and comment!

Quoted 139 lines
Quoted 125 lines

[...]

include/linux/mmzone.h +108 -11
+/**
+ * folio_inc_lru_refs - Update the folio's LRU refs and lazily promote it.
+ * @folio: The folio being accessed.
+ * @flags: The type of ref: FD access, or mapped access optionally with
+ * executable access.
+ *
+ * Used by both cache access (flags == 0) and page table access (flags ==
+ * LRU_REF_MAPPED, optionally with LRU_REF_EXEC).
+ * Context: The caller must keep the folio alive by a reference or the page
+ * table lock of a mapped folio.
+ */
+void folio_inc_lru_refs(struct folio *folio, unsigned int flags)
+{
+     int max_gen;
+     int type, refs, old_gen, gen;
+     unsigned long new_flags, old_flags, max_seq;
+     struct lru_gen_folio *lrugen;
+     struct lruvec *lruvec = NULL;
+
+     type = folio_is_file_lru(folio);
+     old_flags = READ_ONCE(*folio_flags(folio, 0));
+     do {
+             new_flags = old_flags;
+             old_gen = lru_get_gen_flags(old_flags);
+             refs = lru_get_refs_flags(old_flags) + 1;
+             gen = old_gen;
+             if (old_gen < 0)
+                     goto out;
+             /*
+              * Lock the lruvec if the folio is on-list. We are already
+              * doing lazy promotion so in theory we don't need this,
+              * but for now, concurrent aging would still corrupt the
+              * size counters.  This is a temporary limitation and
+              * will be lifted very soon, so the lock here is not a
+              * performance concern.
+              */
+             if (!lruvec) {
+                     lruvec = lruvec_live_lock_irq(folio_lruvec(folio));
+                     lrugen = &lruvec->lrugen;
              }
+             max_seq = READ_ONCE(lrugen->max_seq);
+             max_gen = lru_gen_from_seq(max_seq);
+             if (old_gen == max_gen)
+                     goto out;
 
-             folio_set_lru_refs(folio, 1);
-             return false;
-     }
+             if (flags & (LRU_REF_MAPPED | LRU_REF_EXEC)) {
+                     /* Promote second page table access or executable */
+                     if (refs > LRU_REFS_REFERENCED || flags & LRU_REF_EXEC)
+                             gen = max_gen;
+                     /* First access only defers eviction of an old generation */
+                     else if (lru_gen_is_old(lruvec, type, old_gen))
+                             gen = (old_gen + 1) % MAX_NR_GENS;
+                     refs = min(refs, LRU_REFS_PROTECTED);
+             } else if (refs > LRU_REFS_MAX) {
+                     /* LRU refs counting overflow, bump the gen */
+                     gen = (old_gen + 1) % MAX_NR_GENS;
+                     refs = LRU_REFS_PROTECTED;
+             } else if (lru_gen_is_old(lruvec, type, old_gen) &&
+                        lru_refs_is_workingset(refs)) {
+                     /* Defer eviction of just accessed workingset */
+                     gen = (old_gen + 1) % MAX_NR_GENS;
+                     refs = min(refs, LRU_REFS_PROTECTED);
+             }
+out:
+             refs = min(refs, LRU_REFS_MAX);
+             lru_set_refs_flags(&new_flags, refs);
+             if (gen != old_gen)
+                     lru_set_gen_flags(&new_flags, gen);
+             if (new_flags == old_flags)
+                     break;
+     } while (!try_cmpxchg(folio_flags(folio, 0), &old_flags, new_flags));
 
-     /* Promote on second access */
-     if (folio_lru_refs(folio) > 1) {
-             folio_set_workingset(folio);
-             folio_set_lru_refs(folio, 0);
-     } else {
-             folio_mark_accessed(folio);
-     }
-     return true;
+     if (gen != old_gen)
+             lru_gen_update_size(lruvec, folio, old_gen, gen);
+     if (lruvec)
+             lruvec_unlock_irq(lruvec);
+}
+
+/**
+ * folio_inc_lru_refs_walk - Update the folio's LRU refs and lazily promote it.
+ * @folio: The folio.
+ * @lruvec: The lruvec the folio belongs to.
+ * @vma_flags: The flags of the VMA being walked.
+ * @new_gen: The gen the folio is moved to; may be unchanged.
+ * @type: Returns the folio's type: file or anon.
+ *
+ * Similar to folio_inc_lru_refs(), but for the page table walker and the
+ * look-around. The LRU size accounting is batched by the caller for
+ * better performance.
+ *
+ * Return: The old generation the folio belongs to if the folio is still
+ * on the LRU and not in the newest generation, or -1 otherwise. -1 means
+ * the folio should not be promoted and @new_gen is not set.
+ */
+static int folio_inc_lru_refs_walk(struct folio *folio, struct lruvec *lruvec,
+                                const vma_flags_t *vma_flags,
+                                int *new_gen, int *type)
+{
+     unsigned long new_flags, old_flags = READ_ONCE(*folio_flags(folio, 0));
+     int refs, gen, max_gen, ret;
+     unsigned long max_seq;
+
+     do {
+             max_seq = READ_ONCE(lruvec->lrugen.max_seq);
+             max_gen = lru_gen_from_seq(max_seq);
+             gen = lru_get_gen_flags(old_flags);
+             refs = lru_get_refs_flags(old_flags) + 1;
+             *type = folio_flags_is_file_lru(&old_flags);
+             new_flags = old_flags;
+
+             if (gen >= 0 && gen != max_gen) {

include/linux/mmzone.h

Quoted 10 lines
include/linux/mmzone.h +10 -0
+                     ret = gen;
+                     /* Promote second page table access or executable */
+                     if (lru_refs_is_workingset(refs) || is_exec_file_folio(folio, vma_flags))
+                             *new_gen = max_gen;
+                     /* First access only defers eviction of an old generation */
+                     else if (lru_gen_is_old(lruvec, *type, gen))
+                             *new_gen = (gen + 1) % MAX_NR_GENS;
+                     else
+                             *new_gen = gen;
+                     lru_set_gen_flags(&new_flags, *new_gen);

I see that when folio_inc_lru_refs() sets gen, it checks if (gen != old_gen), a similar check may be needed here as well.

Quoted 8 lines
Quoted 1 line

+ lru_set_refs_flags(&new_flags, min(refs, LRU_REFS_PROTECTED));

The old refs may also already be equal to LRU_REFS_PROTECTED, do we need to check that as well?

But I also looked at the implementation code for lru_set_gen_flags()/lru_set_refs_flags(), which are simple clear/set operations, so I'm wondering whether the check is really necessary?

I tend not to bloat the code too much for too trivial optimizations.., aging produces new gen, so a next aging is very likely to have to promote privous folios IMO :-)

Quoted 37 lines
Quoted 23 lines
include/linux/mmzone.h +22 -0
+             } else {
+                     ret = -1;
+                     lru_set_refs_flags(&new_flags, min(refs, LRU_REFS_MAX));
+             }
+             if (new_flags == old_flags)
+                     break;
+     } while (!try_cmpxchg(folio_flags(folio, 0), &old_flags, new_flags));
+
+     return ret;
+}
+
+/**
+ * folio_inc_lru_refs_isolated - Update the folio's LRU refs
+ * @folio: The folio.
+ * @vma_flags: The flags of all the VMAs that referenced the folio.
+ *
+ * Similar to folio_inc_lru_refs(), but the folio is isolated.  Only used
+ * on mapped folios upon the final eviction RMAP walk. Since the folio is
+ * isolated, folio promotion needs to be done by the caller.
+ *
+ * Return: true if the caller should activate the folio, false to put it
+ * back in an older gen and wait for a second chance.

include/linux/mmzone.h

Quoted 10 lines
include/linux/mmzone.h +10 -0
+ */
+static bool folio_inc_lru_refs_isolated(struct folio *folio, const vma_flags_t *vma_flags)
+{
+     unsigned long new_flags, old_flags = READ_ONCE(*folio_flags(folio, 0));
+     unsigned int refs;
+
+     do {
+             new_flags = old_flags;
+             refs = lru_get_refs_flags(old_flags) + 1;
+             lru_set_refs_flags(&new_flags, min(refs, LRU_REFS_PROTECTED));

When the old refs already be equal to LRU_REFS_PROTECTED, the following checks may also be needed.

Quoted 2 lines
                if (new_flags == old_flags)
                        break;

Same here I'm not sure if this is likely, folio_inc_lru_refs may hit folio in newest gen with max refs frequently, while here we are evicting cold folios.

Quoted 2 lines
Quoted 2 lines

+ } while (!try_cmpxchg(folio_flags(folio, 0), &old_flags, new_flags));

But I think we really need to have a variant of try_cmpxchg later, to skip the barrier when the old equals the new, speculatively.

Anyway, really thank you for the careful review!

#36 lore raw

Re: [PATCH v6 07/18] mm/mglru: frequency guided workingset promotion (MGLRU-FG)

Quoted 193 lines · Kairui Song
Quoted 37 lines · Vernon Yang
Quoted 35 lines · On Tue, Nov 24, 2026 at 02:52:59AM +0800, Kairui Song via B4 Relay wrote:

From: Kairui Song <[email protected]>

[...]

include/linux/mmzone.h +10 -12
index 4e85bb520f76..27ba7fa6ddd6 100644
@@ -453,57 +453,103 @@ enum lruvec_flags {
 #define MAX_NR_GENS          4U
 
 /*
- * Each generation is divided into multiple tiers. A folio accessed N times
- * through file descriptors is in tier order_base_2(N). A folio in the first
- * tier (N=0,1) is marked by PG_referenced unless it was faulted in through page
- * tables or read ahead. A folio in the last tier (MAX_NR_TIERS-1) is marked by
- * PG_workingset. A folio in any other tier (1<N<5) between the first and last
- * is marked by additional bits of LRU_REFS_WIDTH in folio->flags.
+ * Each generation is divided into multiple tiers. A folio's referenced
+ * count maps to a tier as shown below (with one extra refs bit):
  *
- * In contrast to moving across generations which requires the LRU lock, moving
- * across tiers only involves atomic operations on folio->flags and therefore
- * has a negligible cost in the buffered access path. In the eviction path,
- * comparisons of refaulted/(evicted+protected) from the first tier and the rest
- * infer whether folios accessed multiple times through file descriptors are
- * statistically hot and thus worth protecting.
+ * MGLRU (frequency guidance)
+ *  Refs  Tier  |- Refs: observed accesses, capped on promotion.
+ *   0      0   |- Mostly cold pages, readahead, etc. [1]
+ *   1      0   |= LRU_REFS_REFERENCED: Used at least once. [2]
+ * -WORKINGSET-+|- Workingset floor, unless explicitly reset. [3]
+ *   2      1<-+|= LRU_REFS_WORKINGSET: Classical workingset, accessed twice, protected. [4]
+ *   3      2   |- LRU_REFS_PROTECTED: Protected workingset, promoted pages capped at here. [5]
+ *   4      2   |
Quoted 8 lines

include/linux/mmzone.h enum lruvec_flags { · line 471

Quoted 5 lines
include/linux/mmzone.h +4 -0
+ *   5      3   |- The tier here is MAX_NR_TIERS - 1
+ *   6      3   |
+ *   7      3   |= LRU_REFS_MAX: Promotion candidate. [6]
+ * -PROMOTION->-/
  *

Excellent design! Unifying the scattered PG_referenced and PG_workingset bits. Thank you very much for your hard work.

Thank you for the review and comment!

Quoted 144 lines
Quoted 125 lines

[...]

include/linux/mmzone.h +108 -11
+/**
+ * folio_inc_lru_refs - Update the folio's LRU refs and lazily promote it.
+ * @folio: The folio being accessed.
+ * @flags: The type of ref: FD access, or mapped access optionally with
+ * executable access.
+ *
+ * Used by both cache access (flags == 0) and page table access (flags ==
+ * LRU_REF_MAPPED, optionally with LRU_REF_EXEC).
+ * Context: The caller must keep the folio alive by a reference or the page
+ * table lock of a mapped folio.
+ */
+void folio_inc_lru_refs(struct folio *folio, unsigned int flags)
+{
+     int max_gen;
+     int type, refs, old_gen, gen;
+     unsigned long new_flags, old_flags, max_seq;
+     struct lru_gen_folio *lrugen;
+     struct lruvec *lruvec = NULL;
+
+     type = folio_is_file_lru(folio);
+     old_flags = READ_ONCE(*folio_flags(folio, 0));
+     do {
+             new_flags = old_flags;
+             old_gen = lru_get_gen_flags(old_flags);
+             refs = lru_get_refs_flags(old_flags) + 1;
+             gen = old_gen;
+             if (old_gen < 0)
+                     goto out;
+             /*
+              * Lock the lruvec if the folio is on-list. We are already
+              * doing lazy promotion so in theory we don't need this,
+              * but for now, concurrent aging would still corrupt the
+              * size counters.  This is a temporary limitation and
+              * will be lifted very soon, so the lock here is not a
+              * performance concern.
+              */
+             if (!lruvec) {
+                     lruvec = lruvec_live_lock_irq(folio_lruvec(folio));
+                     lrugen = &lruvec->lrugen;
              }
+             max_seq = READ_ONCE(lrugen->max_seq);
+             max_gen = lru_gen_from_seq(max_seq);
+             if (old_gen == max_gen)
+                     goto out;
 
-             folio_set_lru_refs(folio, 1);
-             return false;
-     }
+             if (flags & (LRU_REF_MAPPED | LRU_REF_EXEC)) {
+                     /* Promote second page table access or executable */
+                     if (refs > LRU_REFS_REFERENCED || flags & LRU_REF_EXEC)
+                             gen = max_gen;
+                     /* First access only defers eviction of an old generation */
+                     else if (lru_gen_is_old(lruvec, type, old_gen))
+                             gen = (old_gen + 1) % MAX_NR_GENS;
+                     refs = min(refs, LRU_REFS_PROTECTED);
+             } else if (refs > LRU_REFS_MAX) {
+                     /* LRU refs counting overflow, bump the gen */
+                     gen = (old_gen + 1) % MAX_NR_GENS;
+                     refs = LRU_REFS_PROTECTED;
+             } else if (lru_gen_is_old(lruvec, type, old_gen) &&
+                        lru_refs_is_workingset(refs)) {
+                     /* Defer eviction of just accessed workingset */
+                     gen = (old_gen + 1) % MAX_NR_GENS;
+                     refs = min(refs, LRU_REFS_PROTECTED);
+             }
+out:
+             refs = min(refs, LRU_REFS_MAX);
+             lru_set_refs_flags(&new_flags, refs);
+             if (gen != old_gen)
+                     lru_set_gen_flags(&new_flags, gen);
+             if (new_flags == old_flags)
+                     break;
+     } while (!try_cmpxchg(folio_flags(folio, 0), &old_flags, new_flags));
 
-     /* Promote on second access */
-     if (folio_lru_refs(folio) > 1) {
-             folio_set_workingset(folio);
-             folio_set_lru_refs(folio, 0);
-     } else {
-             folio_mark_accessed(folio);
-     }
-     return true;
+     if (gen != old_gen)
+             lru_gen_update_size(lruvec, folio, old_gen, gen);
+     if (lruvec)
+             lruvec_unlock_irq(lruvec);
+}
+
+/**
+ * folio_inc_lru_refs_walk - Update the folio's LRU refs and lazily promote it.
+ * @folio: The folio.
+ * @lruvec: The lruvec the folio belongs to.
+ * @vma_flags: The flags of the VMA being walked.
+ * @new_gen: The gen the folio is moved to; may be unchanged.
+ * @type: Returns the folio's type: file or anon.
+ *
+ * Similar to folio_inc_lru_refs(), but for the page table walker and the
+ * look-around. The LRU size accounting is batched by the caller for
+ * better performance.
+ *
+ * Return: The old generation the folio belongs to if the folio is still
+ * on the LRU and not in the newest generation, or -1 otherwise. -1 means
+ * the folio should not be promoted and @new_gen is not set.
+ */
+static int folio_inc_lru_refs_walk(struct folio *folio, struct lruvec *lruvec,
+                                const vma_flags_t *vma_flags,
+                                int *new_gen, int *type)
+{
+     unsigned long new_flags, old_flags = READ_ONCE(*folio_flags(folio, 0));
+     int refs, gen, max_gen, ret;
+     unsigned long max_seq;
+
+     do {
+             max_seq = READ_ONCE(lruvec->lrugen.max_seq);
+             max_gen = lru_gen_from_seq(max_seq);
+             gen = lru_get_gen_flags(old_flags);
+             refs = lru_get_refs_flags(old_flags) + 1;
+             *type = folio_flags_is_file_lru(&old_flags);
+             new_flags = old_flags;
+
+             if (gen >= 0 && gen != max_gen) {

include/linux/mmzone.h

Quoted 10 lines
include/linux/mmzone.h +10 -0
+                     ret = gen;
+                     /* Promote second page table access or executable */
+                     if (lru_refs_is_workingset(refs) || is_exec_file_folio(folio, vma_flags))
+                             *new_gen = max_gen;
+                     /* First access only defers eviction of an old generation */
+                     else if (lru_gen_is_old(lruvec, *type, gen))
+                             *new_gen = (gen + 1) % MAX_NR_GENS;
+                     else
+                             *new_gen = gen;
+                     lru_set_gen_flags(&new_flags, *new_gen);

I see that when folio_inc_lru_refs() sets gen, it checks if (gen != old_gen), a similar check may be needed here as well.

Quoted 1 line

+ lru_set_refs_flags(&new_flags, min(refs, LRU_REFS_PROTECTED));

The old refs may also already be equal to LRU_REFS_PROTECTED, do we need to check that as well?

Quoted 8 lines
Quoted 3 lines

But I also looked at the implementation code for lru_set_gen_flags()/lru_set_refs_flags(), which are simple clear/set operations, so I'm wondering whether the check is really necessary?

I tend not to bloat the code too much for too trivial optimizations.., aging produces new gen, so a next aging is very likely to have to promote privous folios IMO :-)

Yes, that's my thinking too. Trivial optimizations are not necessary and instead make the code more complex.

In folio_inc_lru_refs() sets gen, removing checks if (gen != old_gen) that as well would be better. It avoids someone else later being confused like I was.

Quoted 45 lines
Quoted 37 lines
Quoted 23 lines
include/linux/mmzone.h +22 -0
+             } else {
+                     ret = -1;
+                     lru_set_refs_flags(&new_flags, min(refs, LRU_REFS_MAX));
+             }
+             if (new_flags == old_flags)
+                     break;
+     } while (!try_cmpxchg(folio_flags(folio, 0), &old_flags, new_flags));
+
+     return ret;
+}
+
+/**
+ * folio_inc_lru_refs_isolated - Update the folio's LRU refs
+ * @folio: The folio.
+ * @vma_flags: The flags of all the VMAs that referenced the folio.
+ *
+ * Similar to folio_inc_lru_refs(), but the folio is isolated.  Only used
+ * on mapped folios upon the final eviction RMAP walk. Since the folio is
+ * isolated, folio promotion needs to be done by the caller.
+ *
+ * Return: true if the caller should activate the folio, false to put it
+ * back in an older gen and wait for a second chance.

include/linux/mmzone.h

Quoted 10 lines
include/linux/mmzone.h +10 -0
+ */
+static bool folio_inc_lru_refs_isolated(struct folio *folio, const vma_flags_t *vma_flags)
+{
+     unsigned long new_flags, old_flags = READ_ONCE(*folio_flags(folio, 0));
+     unsigned int refs;
+
+     do {
+             new_flags = old_flags;
+             refs = lru_get_refs_flags(old_flags) + 1;
+             lru_set_refs_flags(&new_flags, min(refs, LRU_REFS_PROTECTED));

When the old refs already be equal to LRU_REFS_PROTECTED, the following checks may also be needed.

Quoted 2 lines
                if (new_flags == old_flags)
                        break;

Same here I'm not sure if this is likely, folio_inc_lru_refs may hit folio in newest gen with max refs frequently, while here we are evicting cold folios.

Quoted 1 line
Quoted 4 lines
Quoted 1 line
Quoted 1 line

+ } while (!try_cmpxchg(folio_flags(folio, 0), &old_flags, new_flags));

But I think we really need to have a variant of try_cmpxchg later, to skip the barrier when the old equals the new, speculatively.

Looks good to me. Thanks!

Quoted 3 lines

Anyway, really thank you for the careful review!

--
Cheers,
Vernon

author maintainer
#37 lore raw

PATCH v6 8/18 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 f38dad1198fc..180db43c3a85 100644
@@ -184,6 +184,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
@@ -206,7 +212,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;
 }
 
 /**
@@ -252,13 +259,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]);
@@ -424,20 +449,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)
@@ -470,16 +481,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 65869b8acec5..0430197fdc04 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
#38 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: Tue, 24 Nov 2026 02:53:00 +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 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]>
Cc Harry Yoo <[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
@@ -184,6 +184,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
@@ -206,7 +212,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;
 }
 
 /**
@@ -252,13 +259,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]);
@@ -424,20 +449,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)
@@ -470,16 +481,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-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

#39 lore raw

Re: [PATCH v6 08/18] mm/mglru: make folio lru referenced times count a generic API

In reply to Kairui Song
Quoted 17 lines · On 11/23/26 19:53, Kairui Song via B4 Relay wrote:

From: Kairui Song <[email protected]>

Pure code shuffle, no behavior change.

Make the folio LRU refs helpers available regardless of CONFIG_LRU_GEN. Without MGLRU the 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.

Quoted 6 lines
---
 include/linux/mm_inline.h | 55 ++++++++++++++++++++++++-----------------------

I'm starting to feel like all of these mglru/reclaim thingies should go into a dedicated helper.

Can you do that as a prio cleanup in this series, so we don't have to mess with mm_inline.h in later patches anymore?

On related notes, can we move mglru stuff into a mglru.c ?

Signature · 3 lines
Cheers,

David
#40 lore raw

Re: [PATCH v6 08/18] mm/mglru: make folio lru referenced times count a generic API

Quoted 25 lines · David Hildenbrand (Arm)
Quoted 17 lines · On 11/23/26 19:53, Kairui Song via B4 Relay wrote:

From: Kairui Song <[email protected]>

Pure code shuffle, no behavior change.

Make the folio LRU refs helpers available regardless of CONFIG_LRU_GEN. Without MGLRU the 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.

Quoted 6 lines
---
 include/linux/mm_inline.h | 55 ++++++++++++++++++++++++-----------------------
Quoted 2 lines

I'm starting to feel like all of these mglru/reclaim thingies should go into a dedicated helper.

Hi David

I saw your comment on other patches too, about the header mm_inline.h, about ~690 / 860 lines of code in it is for MGLRU / CLRU only. The rest ~200 are for VMA / TLB / MMU.

Quoted 3 lines

Can you do that as a prio cleanup in this series, so we don't have to mess with mm_inline.h in later patches anymore?

Perhaps we can instead move the non LRU helpers in it? These helpers:

- anon_vma_name_get
- anon_vma_name_put
- anon_vma_name_reuse
- dup_anon_vma_name
- free_anon_vma_name
- anon_vma_name_eq
- pfnmap_track_ctx_release
- init_tlb_flush_pending
- inc_tlb_flush_pending
- dec_tlb_flush_pending
- mm_tlb_flush_pending
- mm_tlb_flush_nested
- copy_pte_marker
- num_pages_contiguous

All other helper in mm_inline.h are for LRU. So we rename mm_inline.h to mm_lru.h?

Like the patch below, zero behavior change, pure code shuffle:

include/linux/mm.h +120 -0
index d8bafcd92791..2eb0e2fc8c2d 100644
@@ -1903,6 +1903,90 @@ static inline bool vma_is_anon_shmem(const struct vm_area_struct *vma) { return
 
 int vma_is_stack_for_current(const struct vm_area_struct *vma);
 
+static inline void init_tlb_flush_pending(struct mm_struct *mm)
+{
+	atomic_set(&mm->tlb_flush_pending, 0);
+}
+
+static inline void inc_tlb_flush_pending(struct mm_struct *mm)
+{
+	atomic_inc(&mm->tlb_flush_pending);
+	/*
+	 * The only time this value is relevant is when there are indeed pages
+	 * to flush. And we'll only flush pages after changing them, which
+	 * requires the PTL.
+	 *
+	 * So the ordering here is:
+	 *
+	 *	atomic_inc(&mm->tlb_flush_pending);
+	 *	spin_lock(&ptl);
+	 *	...
+	 *	set_pte_at();
+	 *	spin_unlock(&ptl);
+	 *
+	 *				spin_lock(&ptl)
+	 *				mm_tlb_flush_pending();
+	 *				....
+	 *				spin_unlock(&ptl);
+	 *
+	 *	flush_tlb_range();
+	 *	atomic_dec(&mm->tlb_flush_pending);
+	 *
+	 * Where the increment if constrained by the PTL unlock, it thus
+	 * ensures that the increment is visible if the PTE modification is
+	 * visible. After all, if there is no PTE modification, nobody cares
+	 * about TLB flushes either.
+	 *
+	 * This very much relies on users (mm_tlb_flush_pending() and
+	 * mm_tlb_flush_nested()) only caring about _specific_ PTEs (and
+	 * therefore specific PTLs), because with SPLIT_PTE_PTLOCKS and RCpc
+	 * locks (PPC) the unlock of one doesn't order against the lock of
+	 * another PTL.
+	 *
+	 * The decrement is ordered by the flush_tlb_range(), such that
+	 * mm_tlb_flush_pending() will not return false unless all flushes have
+	 * completed.
+	 */
+}
+
+static inline void dec_tlb_flush_pending(struct mm_struct *mm)
+{
+	/*
+	 * See inc_tlb_flush_pending().
+	 *
+	 * This cannot be smp_mb__before_atomic() because smp_mb() simply does
+	 * not order against TLB invalidate completion, which is what we need.
+	 *
+	 * Therefore we must rely on tlb_flush_*() to guarantee order.
+	 */
+	atomic_dec(&mm->tlb_flush_pending);
+}
+
+static inline bool mm_tlb_flush_pending(const struct mm_struct *mm)
+{
+	/*
+	 * Must be called after having acquired the PTL; orders against that
+	 * PTLs release and therefore ensures that if we observe the modified
+	 * PTE we must also observe the increment from inc_tlb_flush_pending().
+	 *
+	 * That is, it only guarantees to return true if there is a flush
+	 * pending for _this_ PTL.
+	 */
+	return atomic_read(&mm->tlb_flush_pending);
+}
+
+static inline bool mm_tlb_flush_nested(const struct mm_struct *mm)
+{
+	/*
+	 * Similar to mm_tlb_flush_pending(), we must have acquired the PTL
+	 * for which there is a TLB flush pending in order to guarantee
+	 * we've seen both that PTE modification and the increment.
+	 *
+	 * (no requirement on actually still holding the PTL, that is irrelevant)
+	 */
+	return atomic_read(&mm->tlb_flush_pending) > 1;
+}
+
 /* flush_tlb_range() takes a vma, not a mm, and can care about flags */
 #define TLB_FLUSH_VMA(mm,flags) { .vm_mm = (mm), .vm_flags = (flags) }
 
@@ -2887,6 +2971,42 @@ static inline unsigned long memdesc_section(const memdesc_flags_t *mdf)
 }
 #endif /* SECTION_IN_PAGE_FLAGS */
 
+/**
+ * num_pages_contiguous() - determine the number of contiguous pages
+ *			    that represent contiguous PFNs
+ * @pages: an array of page pointers
+ * @nr_pages: length of the array, at least 1
+ *
+ * Determine the number of contiguous pages that represent contiguous PFNs
+ * in @pages, starting from the first page.
+ *
+ * In some kernel configs contiguous PFNs will not have contiguous struct
+ * pages. In these configurations num_pages_contiguous() will return a num
+ * smaller than ideal number. The caller should continue to check for pfn
+ * contiguity after each call to num_pages_contiguous().
+ *
+ * Returns the number of contiguous pages.
+ */
+static inline size_t num_pages_contiguous(struct page **pages, size_t nr_pages)
+{
+	struct page *cur_page = pages[0];
+	unsigned long section = memdesc_section(&cur_page->flags);
+	size_t i;
+
+	for (i = 1; i < nr_pages; i++) {
+		if (++cur_page != pages[i])
+			break;
+		/*
+		 * In unproblematic kernel configs, page_to_section() == 0 and
+		 * the whole check will get optimized out.
+		 */
+		if (memdesc_section(&cur_page->flags) != section)
+			break;
+	}
+
+	return i;
+}
+
 /**
  * folio_pfn - Return the Page Frame Number of a folio.
  * @folio: The folio.
include/linux/mm_inline.h +0 -213

230 lines not on this page · raw message

mm/internal.h +94 -0

113 lines not on this page · raw message

mm/pgtable-generic.c +1 -0
index 6e83ce3801b8..61a0c0d4b47d 100644
@@ -7,6 +7,7 @@
  *  Copyright (C) 2010  Linus Torvalds
  */
 
+#include <linux/mm.h>
 #include <linux/pagemap.h>
 #include <linux/hugetlb.h>
 #include <linux/pgtable.h>
#41 lore raw

Re: [PATCH v6 08/18] mm/mglru: make folio lru referenced times count a generic API

Quoted 52 lines · Kairui Song
Quoted 18 lines · On 11/23/26 19:53, Kairui Song via B4 Relay wrote:
Quoted 17 lines

From: Kairui Song<[email protected]>

Pure code shuffle, no behavior change.

Make the folio LRU refs helpers available regardless of CONFIG_LRU_GEN. Without MGLRU the 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.

Quoted 8 lines
Quoted 6 lines
---
  include/linux/mm_inline.h | 55 ++++++++++++++++++++++++-----------------------

I'm starting to feel like all of these mglru/reclaim thingies should go into a dedicated helper.

Hi David

I saw your comment on other patches too, about the header mm_inline.h, about ~690 / 860 lines of code in it is for MGLRU / CLRU only. The rest ~200 are for VMA / TLB / MMU.

Quoted 2 lines

Can you do that as a prio cleanup in this series, so we don't have to mess with mm_inline.h in later patches anymore?

Perhaps we can instead move the non LRU helpers in it? These helpers:

- anon_vma_name_get
- anon_vma_name_put
- anon_vma_name_reuse
- dup_anon_vma_name
- free_anon_vma_name
- anon_vma_name_eq
- pfnmap_track_ctx_release
- init_tlb_flush_pending
- inc_tlb_flush_pending
- dec_tlb_flush_pending
- mm_tlb_flush_pending
- mm_tlb_flush_nested
- copy_pte_marker
- num_pages_contiguous

Quoted 2 lines

All other helper in mm_inline.h are for LRU. So we rename mm_inline.h to mm_lru.h?

Moving the VMA/TLB helpers out looks good to me as a first step.

For the LRU part, there is already mm/vmscan.h, added by "mm/vmscan:
move struct scan_control to a dedicated header" in mm-new. Most LRU helpers are only used inside mm/, e.g. lruvec_add_folio(), lruvec_add_folio_tail(), lru_gen_add_folio() and the refs encoding helpers, so they could move there instead of staying in a public header. Barry also suggested moving lruvec_add_folio() and friends to mm/vmscan.h in another thread.

A few are used outside mm/ and need to stay public:
folio_lru_list() in include/trace/events/pagemap.h, and folio_test_workingset() in fs/btrfs and fs/erofs after patch 16. So maybe keep a small public header for those, and move the rest to mm/vmscan.h, or to a separate mm/mglru.h if it gets too large, as David mentioned.

I can help with the mm/vmscan.h part if that works for you.

Signature · 2 lines
Best regards
Ridong
#42 lore raw

Re: [PATCH v6 08/18] mm/mglru: make folio lru referenced times count a generic API

Quoted 69 lines · Ridong Chen
Quoted 52 lines · Kairui Song
Quoted 18 lines · On 11/23/26 19:53, Kairui Song via B4 Relay wrote:
Quoted 17 lines

From: Kairui Song<[email protected]>

Pure code shuffle, no behavior change.

Make the folio LRU refs helpers available regardless of CONFIG_LRU_GEN. Without MGLRU the 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.

Quoted 8 lines
Quoted 6 lines
---
  include/linux/mm_inline.h | 55 ++++++++++++++++++++++++-----------------------

I'm starting to feel like all of these mglru/reclaim thingies should go into a dedicated helper.

Hi David

I saw your comment on other patches too, about the header mm_inline.h, about ~690 / 860 lines of code in it is for MGLRU / CLRU only. The rest ~200 are for VMA / TLB / MMU.

Quoted 2 lines

Can you do that as a prio cleanup in this series, so we don't have to mess with mm_inline.h in later patches anymore?

Perhaps we can instead move the non LRU helpers in it? These helpers:

- anon_vma_name_get
- anon_vma_name_put
- anon_vma_name_reuse
- dup_anon_vma_name
- free_anon_vma_name
- anon_vma_name_eq
- pfnmap_track_ctx_release
- init_tlb_flush_pending
- inc_tlb_flush_pending
- dec_tlb_flush_pending
- mm_tlb_flush_pending
- mm_tlb_flush_nested
- copy_pte_marker
- num_pages_contiguous

Quoted 2 lines

All other helper in mm_inline.h are for LRU. So we rename mm_inline.h to mm_lru.h?

Moving the VMA/TLB helpers out looks good to me as a first step.

For the LRU part, there is already mm/vmscan.h, added by "mm/vmscan:
move struct scan_control to a dedicated header" in mm-new. Most LRU helpers are only used inside mm/, e.g. lruvec_add_folio(), lruvec_add_folio_tail(), lru_gen_add_folio() and the refs encoding helpers, so they could move there instead of staying in a public header. Barry also suggested moving lruvec_add_folio() and friends to mm/vmscan.h in another thread.

Quoted 8 lines

A few are used outside mm/ and need to stay public:
folio_lru_list() in include/trace/events/pagemap.h, and folio_test_workingset() in fs/btrfs and fs/erofs after patch 16. So maybe keep a small public header for those, and move the rest to mm/vmscan.h, or to a separate mm/mglru.h if it gets too large, as David mentioned.

I can help with the mm/vmscan.h part if that works for you.

Good idea! Maybe you can send a series to do that which I'll rebase on top of. Feel free to take the first renaming patch too since they should all be zero-feature-change :-D

But please help keep some helpers in a public helper so when we are able to get rid of folio_*_referenced and folio_*_workingset, there wron't be some strange header inclusion issues. FS users quite often need to call them, especially the folio refs related ones.

Meanwhile I hope we won't take too long to get FG merged because users with swappiness 200 could experience serious regressions with the recent swappiness change, and there are already several long standing / recent regression that are waiting to be solved by FG :/

(Considering MGLRU even used to try to completely ignore anon reclaim at swappiness 200 about a year ago, maybe that isn't too much of a problem, but it's still a problem).

#43 lore raw

Re: [PATCH v6 08/18] mm/mglru: make folio lru referenced times count a generic API

Quoted 82 lines · Kairui Song
Quoted 67 lines · Ridong Chen
Quoted 52 lines · Kairui Song
Quoted 18 lines · On 11/23/26 19:53, Kairui Song via B4 Relay wrote:
Quoted 17 lines

From: Kairui Song<[email protected]>

Pure code shuffle, no behavior change.

Make the folio LRU refs helpers available regardless of CONFIG_LRU_GEN. Without MGLRU the 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.

Quoted 8 lines
Quoted 6 lines
---
  include/linux/mm_inline.h | 55 ++++++++++++++++++++++++-----------------------

I'm starting to feel like all of these mglru/reclaim thingies should go into a dedicated helper.

Hi David

I saw your comment on other patches too, about the header mm_inline.h, about ~690 / 860 lines of code in it is for MGLRU / CLRU only. The rest ~200 are for VMA / TLB / MMU.

Quoted 2 lines

Can you do that as a prio cleanup in this series, so we don't have to mess with mm_inline.h in later patches anymore?

Perhaps we can instead move the non LRU helpers in it? These helpers:

- anon_vma_name_get
- anon_vma_name_put
- anon_vma_name_reuse
- dup_anon_vma_name
- free_anon_vma_name
- anon_vma_name_eq
- pfnmap_track_ctx_release
- init_tlb_flush_pending
- inc_tlb_flush_pending
- dec_tlb_flush_pending
- mm_tlb_flush_pending
- mm_tlb_flush_nested
- copy_pte_marker
- num_pages_contiguous

Quoted 2 lines

All other helper in mm_inline.h are for LRU. So we rename mm_inline.h to mm_lru.h?

Moving the VMA/TLB helpers out looks good to me as a first step.

For the LRU part, there is already mm/vmscan.h, added by "mm/vmscan:
move struct scan_control to a dedicated header" in mm-new. Most LRU helpers are only used inside mm/, e.g. lruvec_add_folio(), lruvec_add_folio_tail(), lru_gen_add_folio() and the refs encoding helpers, so they could move there instead of staying in a public header. Barry also suggested moving lruvec_add_folio() and friends to mm/vmscan.h in another thread.

Quoted 8 lines

A few are used outside mm/ and need to stay public:
folio_lru_list() in include/trace/events/pagemap.h, and folio_test_workingset() in fs/btrfs and fs/erofs after patch 16. So maybe keep a small public header for those, and move the rest to mm/vmscan.h, or to a separate mm/mglru.h if it gets too large, as David mentioned.

I can help with the mm/vmscan.h part if that works for you.

Good idea! Maybe you can send a series to do that which I'll rebase on top of. Feel free to take the first renaming patch too since they should all be zero-feature-change :-D

Quoted 8 lines

But please help keep some helpers in a public helper so when we are able to get rid of folio_*_referenced and folio_*_workingset, there wron't be some strange header inclusion issues. FS users quite often need to call them, especially the folio refs related ones.

(Considering MGLRU even used to try to completely ignore anon reclaim at swappiness 200 about a year ago, maybe that isn't too much of a problem, but it's still a problem).

Sorry my mistake, I meant file reclaim, got it wrong in the opposite way :P

#44 lore raw

Re: [PATCH v6 08/18] mm/mglru: make folio lru referenced times count a generic API

Quoted 88 lines · Kairui Song
Quoted 87 lines · Kairui Song
Quoted 67 lines · Ridong Chen
Quoted 52 lines · Kairui Song
Quoted 18 lines · On 11/23/26 19:53, Kairui Song via B4 Relay wrote:
Quoted 17 lines

From: Kairui Song<[email protected]>

Pure code shuffle, no behavior change.

Make the folio LRU refs helpers available regardless of CONFIG_LRU_GEN. Without MGLRU the 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.

Quoted 8 lines
Quoted 6 lines
---
   include/linux/mm_inline.h | 55 ++++++++++++++++++++++++-----------------------

I'm starting to feel like all of these mglru/reclaim thingies should go into a dedicated helper.

Hi David

I saw your comment on other patches too, about the header mm_inline.h, about ~690 / 860 lines of code in it is for MGLRU / CLRU only. The rest ~200 are for VMA / TLB / MMU.

Quoted 2 lines

Can you do that as a prio cleanup in this series, so we don't have to mess with mm_inline.h in later patches anymore?

Perhaps we can instead move the non LRU helpers in it? These helpers:

- anon_vma_name_get
- anon_vma_name_put
- anon_vma_name_reuse
- dup_anon_vma_name
- free_anon_vma_name
- anon_vma_name_eq
- pfnmap_track_ctx_release
- init_tlb_flush_pending
- inc_tlb_flush_pending
- dec_tlb_flush_pending
- mm_tlb_flush_pending
- mm_tlb_flush_nested
- copy_pte_marker
- num_pages_contiguous

Quoted 2 lines

All other helper in mm_inline.h are for LRU. So we rename mm_inline.h to mm_lru.h?

Moving the VMA/TLB helpers out looks good to me as a first step.

For the LRU part, there is already mm/vmscan.h, added by "mm/vmscan:
move struct scan_control to a dedicated header" in mm-new. Most LRU helpers are only used inside mm/, e.g. lruvec_add_folio(), lruvec_add_folio_tail(), lru_gen_add_folio() and the refs encoding helpers, so they could move there instead of staying in a public header. Barry also suggested moving lruvec_add_folio() and friends to mm/vmscan.h in another thread.

Quoted 8 lines

A few are used outside mm/ and need to stay public:
folio_lru_list() in include/trace/events/pagemap.h, and folio_test_workingset() in fs/btrfs and fs/erofs after patch 16. So maybe keep a small public header for those, and move the rest to mm/vmscan.h, or to a separate mm/mglru.h if it gets too large, as David mentioned.

I can help with the mm/vmscan.h part if that works for you.

Good idea! Maybe you can send a series to do that which I'll rebase on top of. Feel free to take the first renaming patch too since they should all be zero-feature-change :-D

But please help keep some helpers in a public helper so when we are able to get rid of folio_*_referenced and folio_*_workingset, there wron't be some strange header inclusion issues. FS users quite often need to call them, especially the folio refs related ones.

Quoted 5 lines
Quoted 3 lines

(Considering MGLRU even used to try to completely ignore anon reclaim at swappiness 200 about a year ago, maybe that isn't too much of a problem, but it's still a problem).

Sorry my mistake, I meant file reclaim, got it wrong in the opposite way :P

Thinking about it more, the header move is not urgent, while this series has been iterated for a long time and fixes real problems, e.g. the swappiness 200 regression you mentioned. Making it depend on a code shuffle would only delay it.

So if David doesn't object, I would suggest landing MGLRU-FG first, and doing the mm_inline.h split as a follow-up on top of it. That also avoids rebasing this large series onto a moving header. I am happy to work on the follow-up then, keeping the folio refs helpers in a public header for the fs users as you said.

David, would that work for you?

Signature · 2 lines
Best regards
Ridong
#45 lore raw

Re: [PATCH v6 08/18] mm/mglru: make folio lru referenced times count a generic API

Quoted 4 lines · Ridong Chen

Thinking about it more, the header move is not urgent, while this series has been iterated for a long time and fixes real problems, e.g. the swappiness 200 regression you mentioned. Making it depend on a code shuffle would only delay it.

I also prefer to land the FG series first. It's not just a feature & optimization, it covers several "bug"-level issues for MGLRU and fixes regressions, which are hard to solve without a rework like this.

Quoted 5 lines

So if David doesn't object, I would suggest landing MGLRU-FG first, and doing the mm_inline.h split as a follow-up on top of it. That also avoids rebasing this large series onto a moving header. I am happy to work on the follow-up then, keeping the folio refs helpers in a public header for the fs users as you said.

Let's see how others think about this :)

Quoted 6 lines

David, would that work for you?

--
Best regards
Ridong

#46 lore raw

Re: [PATCH v6 08/18] mm/mglru: make folio lru referenced times count a generic API

Quoted 11 lines · Kairui Song
Quoted 4 lines · Ridong Chen

Thinking about it more, the header move is not urgent, while this series has been iterated for a long time and fixes real problems, e.g. the swappiness 200 regression you mentioned. Making it depend on a code shuffle would only delay it.

I also prefer to land the FG series first. It's not just a feature & optimization, it covers several "bug"-level issues for MGLRU and fixes regressions, which are hard to solve without a rework like this.

I'd also like to see FG go in first, with the header split as a follow-up.

Thanks,
Kunwu

Quoted 14 lines
Quoted 5 lines

So if David doesn't object, I would suggest landing MGLRU-FG first, and doing the mm_inline.h split as a follow-up on top of it. That also avoids rebasing this large series onto a moving header. I am happy to work on the follow-up then, keeping the folio refs helpers in a public header for the fs users as you said.

Let's see how others think about this :)

Quoted 6 lines

David, would that work for you?

--
Best regards
Ridong

maintainer tree notice
#47 lore raw

[to-be-updated] mm-mglru-make-folio-lru-referenced-times-count-a-generic-api.patch removed from -mm tree

In reply to Kairui Song
The quilt patch titled Subject: mm/mglru: make folio lru referenced times count a generic API has been removed from the -mm tree. Its filename was…

The quilt patch titled
Subject: mm/mglru: make folio lru referenced times count a generic API
has been removed from the -mm tree. Its filename was
mm-mglru-make-folio-lru-referenced-times-count-a-generic-api.patch

This patch was dropped because an updated version will be issued

------------------------------------------------------
From: Kairui Song <[email protected]>
Subject: mm/mglru: make folio lru referenced times count a generic API
Date: Tue, 24 Nov 2026 02:53:00 +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 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]>
Cc Harry Yoo <[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
@@ -184,6 +184,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
@@ -206,7 +212,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;
 }
 
 /**
@@ -252,13 +259,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]);
@@ -424,20 +449,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)
@@ -470,16 +481,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-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-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
#48 lore raw

PATCH v6 9/18 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 180db43c3a85..b15c3618a1f2 100644
@@ -322,21 +322,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)) {
@@ -391,6 +379,8 @@ static inline bool __lru_gen_add_folio(struct lruvec *lruvec, struct folio *foli
 	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);
@@ -408,6 +398,10 @@ static inline bool __lru_gen_add_folio(struct lruvec *lruvec, struct folio *foli
 	set_mask_bits(folio_flags(folio, 0), LRU_GEN_MASK | BIT(PG_active), flags);
 
 	lru_gen_update_size(lruvec, folio, -1, gen);
+	if (lru_gen_is_active(lruvec, gen))
+		lru += LRU_ACTIVE;
+	__update_lru_size(lruvec, lru, zone, delta);
+
 	/* for folio_rotate_reclaimable() */
 	if (reclaiming)
 		list_add_tail(&folio->lru, &lrugen->folios[gen][type][zone]);
@@ -432,6 +426,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;
@@ -445,6 +442,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
#49 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: Tue, 24 Nov 2026 02:53:01 +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 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]>
Cc Harry Yoo <[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
@@ -322,21 +322,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)) {
@@ -391,6 +379,8 @@ static inline bool __lru_gen_add_folio(s
 	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);
@@ -408,6 +398,10 @@ static inline bool __lru_gen_add_folio(s
 	set_mask_bits(folio_flags(folio, 0), LRU_GEN_MASK | BIT(PG_active), flags);
 
 	lru_gen_update_size(lruvec, folio, -1, gen);
+	if (lru_gen_is_active(lruvec, gen))
+		lru += LRU_ACTIVE;
+	__update_lru_size(lruvec, lru, zone, delta);
+
 	/* for folio_rotate_reclaimable() */
 	if (reclaiming)
 		list_add_tail(&folio->lru, &lrugen->folios[gen][type][zone]);
@@ -432,6 +426,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;
@@ -445,6 +442,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-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 tree notice
#50 lore raw

[to-be-updated] mm-mglru-move-add-del-lru-size-accounting-out-of-lru_gen_update_size.patch removed from -mm tree

In reply to Kairui Song
The quilt patch titled Subject: mm/mglru: move add/del LRU size accounting out of lru_gen_update_size() has been removed from the -mm tree. Its filename was…

The quilt patch titled
Subject: mm/mglru: move add/del LRU size accounting out of lru_gen_update_size()
has been removed from the -mm tree. Its filename was
mm-mglru-move-add-del-lru-size-accounting-out-of-lru_gen_update_size.patch

This patch was dropped because an updated version will be issued

------------------------------------------------------
From: Kairui Song <[email protected]>
Subject: mm/mglru: move add/del LRU size accounting out of lru_gen_update_size()
Date: Tue, 24 Nov 2026 02:53:01 +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 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]>
Cc Harry Yoo <[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
@@ -322,21 +322,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)) {
@@ -391,6 +379,8 @@ static inline bool __lru_gen_add_folio(s
 	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);
@@ -408,6 +398,10 @@ static inline bool __lru_gen_add_folio(s
 	set_mask_bits(folio_flags(folio, 0), LRU_GEN_MASK | BIT(PG_active), flags);
 
 	lru_gen_update_size(lruvec, folio, -1, gen);
+	if (lru_gen_is_active(lruvec, gen))
+		lru += LRU_ACTIVE;
+	__update_lru_size(lruvec, lru, zone, delta);
+
 	/* for folio_rotate_reclaimable() */
 	if (reclaiming)
 		list_add_tail(&folio->lru, &lrugen->folios[gen][type][zone]);
@@ -432,6 +426,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;
@@ -445,6 +442,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-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-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
#51 lore raw

PATCH v6 10/18 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. 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 | 62 +++++++++++++++++++++++++++++++++++------------
 mm/gup.c                  |  6 ++---
 2 files changed, 49 insertions(+), 19 deletions(-)
include/linux/mm_inline.h +46 -16
index b15c3618a1f2..13c8b6bce349 100644
@@ -105,6 +105,22 @@ static __always_inline enum lru_list folio_lru_list(const struct folio *folio)
 	return lru;
 }
 
+/**
+ * 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)
@@ -168,22 +184,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)));
@@ -483,6 +483,36 @@ 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.
+ */
+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;
+
+	do {
+		refs = lru_get_refs_flags(old_flags);
+		if (lru_get_gen_flags(old_flags) < 0 && !lru_gen_enabled()) {
+			/* For CLRU, just do folio_set_referenced() */
+			if (refs & LRU_REFS_REFERENCED)
+				break;
+			refs |= LRU_REFS_REFERENCED;
+		} else {
+			if (refs)
+				break;
+			refs = LRU_REFS_REFERENCED;
+		}
+		new_flags = old_flags;
+		lru_set_refs_flags(&new_flags, refs);
+	} 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
#52 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: Tue, 24 Nov 2026 02:53:02 +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. 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]>
Cc Harry Yoo <[email protected]>
 include/linux/mm_inline.h |   62 ++++++++++++++++++++++++++----------
 mm/gup.c                  |    6 +--
 2 files changed, 49 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 +46 -16
@@ -105,6 +105,22 @@ static __always_inline enum lru_list fol
 	return lru;
 }
 
+/**
+ * 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)
@@ -168,22 +184,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)));
@@ -483,6 +483,36 @@ 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.
+ */
+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;
+
+	do {
+		refs = lru_get_refs_flags(old_flags);
+		if (lru_get_gen_flags(old_flags) < 0 && !lru_gen_enabled()) {
+			/* For CLRU, just do folio_set_referenced() */
+			if (refs & LRU_REFS_REFERENCED)
+				break;
+			refs |= LRU_REFS_REFERENCED;
+		} else {
+			if (refs)
+				break;
+			refs = LRU_REFS_REFERENCED;
+		}
+		new_flags = old_flags;
+		lru_set_refs_flags(&new_flags, refs);
+	} 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-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

#53 lore raw

Re: [PATCH v6 10/18] mm/mglru, gup: mark folios referenced via a fast helper

In reply to Kairui Song
Quoted 86 lines · On 11/23/26 19:53, Kairui Song via B4 Relay wrote:

From: Kairui Song <[email protected]>

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. 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 | 62 +++++++++++++++++++++++++++++++++++------------
 mm/gup.c                  |  6 ++---
 2 files changed, 49 insertions(+), 19 deletions(-)
include/linux/mm_inline.h +16 -16
index b15c3618a1f2..13c8b6bce349 100644
@@ -105,6 +105,22 @@ static __always_inline enum lru_list folio_lru_list(const struct folio *folio)
 	return lru;
 }
 
+/**
+ * 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)
@@ -168,22 +184,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)));

include/linux/mm_inline.h static inline bool lru_gen_del_folio(struct lruvec *lruvec, struct folio *folio, · line 488

Quoted 6 lines
include/linux/mm_inline.h +3 -0
@@ -483,6 +483,36 @@ 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

It's unclear when this function should be used and why it should be used.

For someone reading/writing GUP code it's completely unclear why this magic is required.

Signature · 3 lines
Cheers,

David
#54 lore raw

Re: [PATCH v6 10/18] mm/mglru, gup: mark folios referenced via a fast helper

Quoted 91 lines · David Hildenbrand (Arm)
Quoted 89 lines · On 11/23/26 19:53, Kairui Song via B4 Relay wrote:

From: Kairui Song <[email protected]>

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. 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 | 62 +++++++++++++++++++++++++++++++++++------------
 mm/gup.c                  |  6 ++---
 2 files changed, 49 insertions(+), 19 deletions(-)
include/linux/mm_inline.h +16 -16
index b15c3618a1f2..13c8b6bce349 100644
@@ -105,6 +105,22 @@ static __always_inline enum lru_list folio_lru_list(const struct folio *folio)
      return lru;
 }
 
+/**
+ * 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)
@@ -168,22 +184,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)));
@@ -483,6 +483,36 @@ static inline bool lru_gen_del_folio(struct lruvec *lruvec, struct folio *folio,
 }
 #endif /* CONFIG_LRU_GEN */
 
Quoted 8 lines

include/linux/mm_inline.h static inline bool lru_gen_del_folio(struct lruvec *lruvec, struct folio *folio, · line 488

Quoted 3 lines
include/linux/mm_inline.h +3 -0
+/**
+ * folio_inc_lru_refs_fast - Bump folio refs count without promotion.
+ * @folio: the folio

It's unclear when this function should be used and why it should be used.

For someone reading/writing GUP code it's completely unclear why this magic is required.

Right I think I can add the context here in commit message and kdoc, MGLRU requires the user to avoid calling folio_set_referenced(), so folio_set_referenced() callers should use folio_inc_lru_refs* instead, and folio_inc_lru_refs_fast is a variant of that aim to be much faster, avoiding RCU / CAS / Memcg Counter update.

CLRU still uses folio_set_referenced() though. We can get rid of PG_referenced and helpers later to make it much cleaner (co-exist of two LRU is making this looks ugly indeed, I we can fix this step by step):
https://lore.kernel.org/linux-mm/[email protected]/

#55 lore raw

Re: [PATCH v6 10/18] mm/mglru, gup: mark folios referenced via a fast helper

In reply to Kairui Song
Quoted 108 lines · On Tue, Nov 24, 2026 at 02:53:02AM +0800, Kairui Song via B4 Relay wrote:

From: Kairui Song <[email protected]>

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. 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 | 62 +++++++++++++++++++++++++++++++++++------------
 mm/gup.c                  |  6 ++---
 2 files changed, 49 insertions(+), 19 deletions(-)
include/linux/mm_inline.h +35 -16
index b15c3618a1f2..13c8b6bce349 100644
@@ -105,6 +105,22 @@ static __always_inline enum lru_list folio_lru_list(const struct folio *folio)
 	return lru;
 }
 
+/**
+ * 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)
@@ -168,22 +184,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)));
@@ -483,6 +483,36 @@ 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.
+ */
+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;
+
+	do {
+		refs = lru_get_refs_flags(old_flags);
+		if (lru_get_gen_flags(old_flags) < 0 && !lru_gen_enabled()) {
+			/* For CLRU, just do folio_set_referenced() */
+			if (refs & LRU_REFS_REFERENCED)
+				break;

include/linux/mm_inline.h static inline bool lru_gen_del_folio(struct lruvec *lruvec, struct folio *folio, · line 514

Quoted 10 lines
include/linux/mm_inline.h +10 -0
+			refs |= LRU_REFS_REFERENCED;
+		} else {
+			if (refs)
+				break;
+			refs = LRU_REFS_REFERENCED;
+		}
+		new_flags = old_flags;
+		lru_set_refs_flags(&new_flags, refs);
+	} while (!try_cmpxchg(folio_flags(folio, 0), &old_flags, new_flags));
+}

The implementation code of this function looks a bit convoluted. Would it be better to simplify it into the following code?

	do {
		bool clru = !lru_gen_enabled() && lru_get_gen_flags(old_flags) < 0;

		refs = lru_get_refs_flags(old_flags);
		if (clru ? (refs & LRU_REFS_REFERENCED) : refs)
			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));

--
Cheers,
Vernon

#56 lore raw

Re: [PATCH v6 10/18] mm/mglru, gup: mark folios referenced via a fast helper

Quoted 34 lines · Vernon Yang
Quoted 19 lines · On Tue, Nov 24, 2026 at 02:53:02AM +0800, Kairui Song via B4 Relay wrote:
include/linux/mm_inline.h +19 -0
+/**
+ * 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.
+ */
+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;
+
+	do {
+		refs = lru_get_refs_flags(old_flags);
+		if (lru_get_gen_flags(old_flags) < 0 && !lru_gen_enabled()) {
+			/* For CLRU, just do folio_set_referenced() */
+			if (refs & LRU_REFS_REFERENCED)
+				break;

include/linux/mm_inline.h static inline bool lru_gen_del_folio(struct lruvec *lruvec, struct folio *folio, · line 514

Quoted 10 lines
include/linux/mm_inline.h +10 -0
+			refs |= LRU_REFS_REFERENCED;
+		} else {
+			if (refs)
+				break;
+			refs = LRU_REFS_REFERENCED;
+		}
+		new_flags = old_flags;
+		lru_set_refs_flags(&new_flags, refs);
+	} while (!try_cmpxchg(folio_flags(folio, 0), &old_flags, new_flags));
+}

The implementation code of this function looks a bit convoluted. Would it be better to simplify it into the following code?

Quoted 9 lines
	do {
		bool clru = !lru_gen_enabled() && lru_get_gen_flags(old_flags) < 0;

		refs = lru_get_refs_flags(old_flags);
		if (clru ? (refs & LRU_REFS_REFERENCED) : refs)
			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));

Hello Vernon,

That's very good suggestion!

Only one thing here is that
!lru_gen_enabled() && lru_get_gen_flags(old_flags) < 0 doesn't mean it's classical LRU, maybe it's just isolated. How about bool on_gen? Or bool has_gen?

#57 lore raw

Re: [PATCH v6 10/18] mm/mglru, gup: mark folios referenced via a fast helper

Quoted 45 lines · Kairui Song
Quoted 34 lines · Vernon Yang
Quoted 19 lines · On Tue, Nov 24, 2026 at 02:53:02AM +0800, Kairui Song via B4 Relay wrote:
include/linux/mm_inline.h +19 -0
+/**
+ * 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.
+ */
+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;
+
+	do {
+		refs = lru_get_refs_flags(old_flags);
+		if (lru_get_gen_flags(old_flags) < 0 && !lru_gen_enabled()) {
+			/* For CLRU, just do folio_set_referenced() */
+			if (refs & LRU_REFS_REFERENCED)
+				break;

include/linux/mm_inline.h static inline bool lru_gen_del_folio(struct lruvec *lruvec, struct folio *folio, · line 514

Quoted 10 lines
include/linux/mm_inline.h +10 -0
+			refs |= LRU_REFS_REFERENCED;
+		} else {
+			if (refs)
+				break;
+			refs = LRU_REFS_REFERENCED;
+		}
+		new_flags = old_flags;
+		lru_set_refs_flags(&new_flags, refs);
+	} while (!try_cmpxchg(folio_flags(folio, 0), &old_flags, new_flags));
+}

The implementation code of this function looks a bit convoluted. Would it be better to simplify it into the following code?

Quoted 9 lines
	do {
		bool clru = !lru_gen_enabled() && lru_get_gen_flags(old_flags) < 0;

		refs = lru_get_refs_flags(old_flags);
		if (clru ? (refs & LRU_REFS_REFERENCED) : refs)
			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));
Quoted 9 lines

Hello Vernon,

That's very good suggestion!

Only one thing here is that
!lru_gen_enabled() && lru_get_gen_flags(old_flags) < 0 doesn't mean it's classical LRU, maybe it's just isolated. How about bool on_gen? Or bool has_gen?

Thank you for your explanation!

For has_gen, looks to me good.

For on_gen, it could be misunderstood as "whether MGLRU is enabled". So I prefer has_gen personally.

--
Cheers,
Vernon

maintainer tree notice
#58 lore raw

[to-be-updated] mm-mglru-gup-mark-folios-referenced-via-a-fast-helper.patch removed from -mm tree

In reply to Kairui Song
The quilt patch titled Subject: mm/mglru, gup: mark folios referenced via a fast helper has been removed from the -mm tree. Its filename was mm-mglru-gup-mark-folios-referenced-via-a-fast-helper.patch

The quilt patch titled
Subject: mm/mglru, gup: mark folios referenced via a fast helper
has been removed from the -mm tree. Its filename was
mm-mglru-gup-mark-folios-referenced-via-a-fast-helper.patch

This patch was dropped because an updated version will be issued

------------------------------------------------------
From: Kairui Song <[email protected]>
Subject: mm/mglru, gup: mark folios referenced via a fast helper
Date: Tue, 24 Nov 2026 02:53:02 +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. 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]>
Cc Harry Yoo <[email protected]>
 include/linux/mm_inline.h |   62 ++++++++++++++++++++++++++----------
 mm/gup.c                  |    6 +--
 2 files changed, 49 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 +46 -16
@@ -105,6 +105,22 @@ static __always_inline enum lru_list fol
 	return lru;
 }
 
+/**
+ * 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)
@@ -168,22 +184,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)));
@@ -483,6 +483,36 @@ 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.
+ */
+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;
+
+	do {
+		refs = lru_get_refs_flags(old_flags);
+		if (lru_get_gen_flags(old_flags) < 0 && !lru_gen_enabled()) {
+			/* For CLRU, just do folio_set_referenced() */
+			if (refs & LRU_REFS_REFERENCED)
+				break;
+			refs |= LRU_REFS_REFERENCED;
+		} else {
+			if (refs)
+				break;
+			refs = LRU_REFS_REFERENCED;
+		}
+		new_flags = old_flags;
+		lru_set_refs_flags(&new_flags, refs);
+	} 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-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-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
#59 lore raw

PATCH v6 11/18 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_check_lru_refs() and folio_clear_lru_refs(), which use the refs count when MGLRU is enabled and PG_referenced otherwise, and switch the smaps paths over to them. The lru_gen_enabled() test stays inside the helpers, so its static key is not splattered over the few call sites.

Convert smaps as the first user of them. MGLRU now reports every folio with a nonzero count, so the reading no longer flickers and clearing no longer results in an ambiguous status.

The classical LRU case is unchanged.

---
 fs/proc/task_mmu.c        |  6 +++---
 include/linux/mm_inline.h | 31 +++++++++++++++++++++++++++++++
 2 files changed, 34 insertions(+), 3 deletions(-)
fs/proc/task_mmu.c +3 -3
index 540c936aad47..d2a524c6ad4b 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_young(folio) || folio_check_lru_refs(folio))
 		mss->referenced += size;
 
 	/*
@@ -1690,7 +1690,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;
@@ -1719,7 +1719,7 @@ static int clear_refs_pte_range(pmd_t *pmd, unsigned long addr,
 		/* Clear accessed and referenced bits. */
 		ptep_test_and_clear_young(vma, addr, pte);
 		folio_test_clear_young(folio);
-		folio_clear_referenced(folio);
+		folio_clear_lru_refs(folio);
 	}
 	pte_unmap_unlock(pte - 1, ptl);
 	cond_resched();
include/linux/mm_inline.h +31 -0
index 13c8b6bce349..0f470ddf5c48 100644
@@ -513,6 +513,37 @@ static __always_inline void folio_inc_lru_refs_fast(struct folio *folio)
 	} while (!try_cmpxchg(folio_flags(folio, 0), &old_flags, new_flags));
 }
 
+/**
+ * folio_check_lru_refs - Test if an LRU managed folio has been referenced.
+ * @folio: The folio to test.
+ *
+ * Returns true if the MGLRU refs count is nonzero, or PG_referenced is set,
+ * which is also correct for the non-MGLRU case. Kept as a separate helper,
+ * to avoid splattering the lru_gen_enabled() static key.
+ */
+static inline bool folio_check_lru_refs(const struct folio *folio)
+{
+	if (lru_gen_enabled())
+		return folio_lru_refs(folio) > 0;
+	return folio_test_referenced(folio);
+}
+
+/**
+ * folio_clear_lru_refs - Clear the referenced state of an LRU managed folio.
+ * @folio: The folio to clear.
+ *
+ * Reset the MGLRU refs count to zero, or clear PG_referenced, leaving
+ * PG_workingset alone for the non-MGLRU case. Kept as a separate helper
+ * just like folio_check_lru_refs().
+ */
+static inline void folio_clear_lru_refs(struct folio *folio)
+{
+	if (lru_gen_enabled())
+		folio_set_lru_refs(folio, 0);
+	else
+		folio_clear_referenced(folio);
+}
+
 static __always_inline
 void lruvec_add_folio(struct lruvec *lruvec, struct folio *folio)
 {
Signature · 1 line
2.56.1
reviewer Acked-by on v6 11/18
#60 lore raw

Re: [PATCH v6 11/18] mm/mglru, smaps: convert to LRU refs based operations for MGLRU

Quoted 28 lines · On Mon Nov 23, 2026 at 1:53 PM EST, Kairui Song via B4 Relay wrote:

From: Kairui Song <[email protected]>

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_check_lru_refs() and folio_clear_lru_refs(), which use the refs count when MGLRU is enabled and PG_referenced otherwise, and switch the smaps paths over to them. The lru_gen_enabled() test stays inside the helpers, so its static key is not splattered over the few call sites.

Convert smaps as the first user of them. MGLRU now reports every folio with a nonzero count, so the reading no longer flickers and clearing no longer results in an ambiguous status.

The classical LRU case is unchanged.

---
 fs/proc/task_mmu.c        |  6 +++---
 include/linux/mm_inline.h | 31 +++++++++++++++++++++++++++++++
 2 files changed, 34 insertions(+), 3 deletions(-)

<snip>

Quoted 24 lines
include/linux/mm_inline.h +24 -0
+/**
+ * folio_check_lru_refs - Test if an LRU managed folio has been referenced.
+ * @folio: The folio to test.
+ *
+ * Returns true if the MGLRU refs count is nonzero, or PG_referenced is set,
+ * which is also correct for the non-MGLRU case. Kept as a separate helper,
+ * to avoid splattering the lru_gen_enabled() static key.
+ */
+static inline bool folio_check_lru_refs(const struct folio *folio)
+{
+	if (lru_gen_enabled())
+		return folio_lru_refs(folio) > 0;
+	return folio_test_referenced(folio);
+}
+
+/**
+ * folio_clear_lru_refs - Clear the referenced state of an LRU managed folio.
+ * @folio: The folio to clear.
+ *
+ * Reset the MGLRU refs count to zero, or clear PG_referenced, leaving
+ * PG_workingset alone for the non-MGLRU case. Kept as a separate helper
+ * just like folio_check_lru_refs().
+ */
+static inline void folio_clear_lru_refs(struct folio *folio)

include/linux/mm_inline.h static __always_inline void folio_inc_lru_refs_fast(struct folio *folio) · line 549

Quoted 10 lines
include/linux/mm_inline.h +7 -0
+{
+	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)
 {

I assume this mean people should stop use folio_*_referenced() directly. Are you planning to remove PG_referenced helpers to achieve that?

Other than that, LGTM.

Signature · 2 lines
Best Regards,
Yan, Zi
#61 lore raw

Re: [PATCH v6 11/18] mm/mglru, smaps: convert to LRU refs based operations for MGLRU

Quoted 61 lines · Zi Yan
Quoted 28 lines · On Mon Nov 23, 2026 at 1:53 PM EST, Kairui Song via B4 Relay wrote:

From: Kairui Song <[email protected]>

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_check_lru_refs() and folio_clear_lru_refs(), which use the refs count when MGLRU is enabled and PG_referenced otherwise, and switch the smaps paths over to them. The lru_gen_enabled() test stays inside the helpers, so its static key is not splattered over the few call sites.

Convert smaps as the first user of them. MGLRU now reports every folio with a nonzero count, so the reading no longer flickers and clearing no longer results in an ambiguous status.

The classical LRU case is unchanged.

---
 fs/proc/task_mmu.c        |  6 +++---
 include/linux/mm_inline.h | 31 +++++++++++++++++++++++++++++++
 2 files changed, 34 insertions(+), 3 deletions(-)

<snip>

Quoted 29 lines
include/linux/mm_inline.h +29 -0
+/**
+ * folio_check_lru_refs - Test if an LRU managed folio has been referenced.
+ * @folio: The folio to test.
+ *
+ * Returns true if the MGLRU refs count is nonzero, or PG_referenced is set,
+ * which is also correct for the non-MGLRU case. Kept as a separate helper,
+ * to avoid splattering the lru_gen_enabled() static key.
+ */
+static inline bool folio_check_lru_refs(const struct folio *folio)
+{
+	if (lru_gen_enabled())
+		return folio_lru_refs(folio) > 0;
+	return folio_test_referenced(folio);
+}
+
+/**
+ * folio_clear_lru_refs - Clear the referenced state of an LRU managed folio.
+ * @folio: The folio to clear.
+ *
+ * Reset the MGLRU refs count to zero, or clear PG_referenced, leaving
+ * PG_workingset alone for the non-MGLRU case. Kept as a separate helper
+ * just like folio_check_lru_refs().
+ */
+static inline void folio_clear_lru_refs(struct folio *folio)
+{
+	if (lru_gen_enabled())
+		folio_set_lru_refs(folio, 0);
+	else
+		folio_clear_referenced(folio);
Quoted 8 lines

include/linux/mm_inline.h static __always_inline void folio_inc_lru_refs_fast(struct folio *folio) · line 549

Quoted 5 lines
include/linux/mm_inline.h +2 -0
+}
+
 static __always_inline
 void lruvec_add_folio(struct lruvec *lruvec, struct folio *folio)
 {

I assume this mean people should stop use folio_*_referenced() directly. Are you planning to remove PG_referenced helpers to achieve that?

They are still there for CLRU, but yeah, and actually there is an earlier RFC where we can remove PG_referenced and PG_workingset, just like this:
https://lore.kernel.org/linux-mm/[email protected]/

And this:
https://lore.kernel.org/linux-mm/[email protected]/

It doesn't really reduce the flags usage but make the code cleaner.

The co-exist of MGLRU & CLRU makes it looks weird, hopefully we can solve that soon, let's do it step by step.

Quoted 3 lines

Other than that, LGTM.

Thanks.

reviewer
#62 lore raw

Re: [PATCH v6 11/18] mm/mglru, smaps: convert to LRU refs based operations for MGLRU

Quoted 75 lines · Kairui Song
Quoted 61 lines · Zi Yan
Quoted 28 lines · On Mon Nov 23, 2026 at 1:53 PM EST, Kairui Song via B4 Relay wrote:

From: Kairui Song <[email protected]>

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_check_lru_refs() and folio_clear_lru_refs(), which use the refs count when MGLRU is enabled and PG_referenced otherwise, and switch the smaps paths over to them. The lru_gen_enabled() test stays inside the helpers, so its static key is not splattered over the few call sites.

Convert smaps as the first user of them. MGLRU now reports every folio with a nonzero count, so the reading no longer flickers and clearing no longer results in an ambiguous status.

The classical LRU case is unchanged.

---
 fs/proc/task_mmu.c        |  6 +++---
 include/linux/mm_inline.h | 31 +++++++++++++++++++++++++++++++
 2 files changed, 34 insertions(+), 3 deletions(-)

<snip>

Quoted 29 lines
include/linux/mm_inline.h +29 -0
+/**
+ * folio_check_lru_refs - Test if an LRU managed folio has been referenced.
+ * @folio: The folio to test.
+ *
+ * Returns true if the MGLRU refs count is nonzero, or PG_referenced is set,
+ * which is also correct for the non-MGLRU case. Kept as a separate helper,
+ * to avoid splattering the lru_gen_enabled() static key.
+ */
+static inline bool folio_check_lru_refs(const struct folio *folio)
+{
+	if (lru_gen_enabled())
+		return folio_lru_refs(folio) > 0;
+	return folio_test_referenced(folio);
+}
+
+/**
+ * folio_clear_lru_refs - Clear the referenced state of an LRU managed folio.
+ * @folio: The folio to clear.
+ *
+ * Reset the MGLRU refs count to zero, or clear PG_referenced, leaving
+ * PG_workingset alone for the non-MGLRU case. Kept as a separate helper
+ * just like folio_check_lru_refs().
+ */
+static inline void folio_clear_lru_refs(struct folio *folio)
+{
+	if (lru_gen_enabled())
+		folio_set_lru_refs(folio, 0);
+	else
+		folio_clear_referenced(folio);
Quoted 8 lines

include/linux/mm_inline.h static __always_inline void folio_inc_lru_refs_fast(struct folio *folio) · line 549

Quoted 5 lines
include/linux/mm_inline.h +2 -0
+}
+
 static __always_inline
 void lruvec_add_folio(struct lruvec *lruvec, struct folio *folio)
 {

I assume this mean people should stop use folio_*_referenced() directly. Are you planning to remove PG_referenced helpers to achieve that?

They are still there for CLRU, but yeah, and actually there is an earlier RFC where we can remove PG_referenced and PG_workingset, just like this:
https://lore.kernel.org/linux-mm/[email protected]/

Quoted 7 lines

And this:
https://lore.kernel.org/linux-mm/[email protected]/

It doesn't really reduce the flags usage but make the code cleaner.

The co-exist of MGLRU & CLRU makes it looks weird, hopefully we can solve that soon, let's do it step by step.

Makes sense. Thank you for the above info.

Quoted 6 lines
Quoted 4 lines

Other than that, LGTM.

Thanks.

Best Regards,
Yan, Zi

maintainer tree notice
#63 lore raw

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

In reply to Kairui Song
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: Tue, 24 Nov 2026 02:53:03 +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_check_lru_refs() and folio_clear_lru_refs(), which use the refs count when MGLRU is enabled and PG_referenced otherwise, and switch the smaps paths over to them. The lru_gen_enabled() test stays inside the helpers, so its static key is not splattered over the few call sites.

Convert smaps as the first user of them. MGLRU now reports every folio with a nonzero count, so the reading no longer flickers and clearing no longer results in an ambiguous status.

The classical LRU case is unchanged.

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]>
Cc Harry Yoo <[email protected]>
 fs/proc/task_mmu.c        |    6 +++---
 include/linux/mm_inline.h |   31 +++++++++++++++++++++++++++++++
 2 files changed, 34 insertions(+), 3 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 -3
@@ -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_young(folio) || folio_check_lru_refs(folio))
 		mss->referenced += size;
 
 	/*
@@ -1690,7 +1690,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;
@@ -1719,7 +1719,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 +31 -0
@@ -513,6 +513,37 @@ static __always_inline void folio_inc_lr
 	} while (!try_cmpxchg(folio_flags(folio, 0), &old_flags, new_flags));
 }
 
+/**
+ * folio_check_lru_refs - Test if an LRU managed folio has been referenced.
+ * @folio: The folio to test.
+ *
+ * Returns true if the MGLRU refs count is nonzero, or PG_referenced is set,
+ * which is also correct for the non-MGLRU case. Kept as a separate helper,
+ * to avoid splattering the lru_gen_enabled() static key.
+ */
+static inline bool folio_check_lru_refs(const struct folio *folio)
+{
+	if (lru_gen_enabled())
+		return folio_lru_refs(folio) > 0;
+	return folio_test_referenced(folio);
+}
+
+/**
+ * folio_clear_lru_refs - Clear the referenced state of an LRU managed folio.
+ * @folio: The folio to clear.
+ *
+ * Reset the MGLRU refs count to zero, or clear PG_referenced, leaving
+ * PG_workingset alone for the non-MGLRU case. Kept as a separate helper
+ * just like folio_check_lru_refs().
+ */
+static inline void folio_clear_lru_refs(struct folio *folio)
+{
+	if (lru_gen_enabled())
+		folio_set_lru_refs(folio, 0);
+	else
+		folio_clear_referenced(folio);
+}
+
 static __always_inline
 void lruvec_add_folio(struct lruvec *lruvec, struct folio *folio)
 {

_

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-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 tree notice
#64 lore raw

[to-be-updated] mm-mglru-smaps-convert-to-lru-refs-based-operations-for-mglru.patch removed from -mm tree

In reply to Kairui Song
The quilt patch titled Subject: mm/mglru, smaps: convert to LRU refs based operations for MGLRU has been removed from the -mm tree. Its filename was…

The quilt patch titled
Subject: mm/mglru, smaps: convert to LRU refs based operations for MGLRU
has been removed from the -mm tree. Its filename was
mm-mglru-smaps-convert-to-lru-refs-based-operations-for-mglru.patch

This patch was dropped because an updated version will be issued

------------------------------------------------------
From: Kairui Song <[email protected]>
Subject: mm/mglru, smaps: convert to LRU refs based operations for MGLRU
Date: Tue, 24 Nov 2026 02:53:03 +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_check_lru_refs() and folio_clear_lru_refs(), which use the refs count when MGLRU is enabled and PG_referenced otherwise, and switch the smaps paths over to them. The lru_gen_enabled() test stays inside the helpers, so its static key is not splattered over the few call sites.

Convert smaps as the first user of them. MGLRU now reports every folio with a nonzero count, so the reading no longer flickers and clearing no longer results in an ambiguous status.

The classical LRU case is unchanged.

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]>
Cc Harry Yoo <[email protected]>
 fs/proc/task_mmu.c        |    6 +++---
 include/linux/mm_inline.h |   31 +++++++++++++++++++++++++++++++
 2 files changed, 34 insertions(+), 3 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 -3
@@ -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_young(folio) || folio_check_lru_refs(folio))
 		mss->referenced += size;
 
 	/*
@@ -1690,7 +1690,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;
@@ -1719,7 +1719,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 +31 -0
@@ -513,6 +513,37 @@ static __always_inline void folio_inc_lr
 	} while (!try_cmpxchg(folio_flags(folio, 0), &old_flags, new_flags));
 }
 
+/**
+ * folio_check_lru_refs - Test if an LRU managed folio has been referenced.
+ * @folio: The folio to test.
+ *
+ * Returns true if the MGLRU refs count is nonzero, or PG_referenced is set,
+ * which is also correct for the non-MGLRU case. Kept as a separate helper,
+ * to avoid splattering the lru_gen_enabled() static key.
+ */
+static inline bool folio_check_lru_refs(const struct folio *folio)
+{
+	if (lru_gen_enabled())
+		return folio_lru_refs(folio) > 0;
+	return folio_test_referenced(folio);
+}
+
+/**
+ * folio_clear_lru_refs - Clear the referenced state of an LRU managed folio.
+ * @folio: The folio to clear.
+ *
+ * Reset the MGLRU refs count to zero, or clear PG_referenced, leaving
+ * PG_workingset alone for the non-MGLRU case. Kept as a separate helper
+ * just like folio_check_lru_refs().
+ */
+static inline void folio_clear_lru_refs(struct folio *folio)
+{
+	if (lru_gen_enabled())
+		folio_set_lru_refs(folio, 0);
+	else
+		folio_clear_referenced(folio);
+}
+
 static __always_inline
 void lruvec_add_folio(struct lruvec *lruvec, struct folio *folio)
 {

_

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-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-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
#65 lore raw

PATCH v6 12/18 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.

---
 mm/damon/paddr.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
mm/damon/paddr.c +2 -1
index e89cb14ee17b..411e1d557ba3 100644
@@ -279,7 +279,8 @@ static unsigned long damon_pa_pageout(struct damon_region *r,
 		else
 			*sz_filter_passed += folio_size(folio) / addr_unit;
 
-		folio_clear_referenced(folio);
+		/* The region is cold, better drop the hotness info. */
+		folio_clear_lru_refs(folio);
 		folio_test_clear_young(folio);
 		if (!folio_isolate_lru(folio))
 			goto put_folio;
Signature · 1 line
2.56.1
maintainer tree notice
#66 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: Tue, 24 Nov 2026 02:53:04 +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.

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]>
Cc Harry Yoo <[email protected]>
 mm/damon/paddr.c |    3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
mm/damon/paddr.c renamed from mm/damon/paddr.c~mm-damon-convert-to-lru-refs-based-operations-for-mglru +2 -1
@@ -279,7 +279,8 @@ static unsigned long damon_pa_pageout(st
 		else
 			*sz_filter_passed += folio_size(folio) / addr_unit;
 
-		folio_clear_referenced(folio);
+		/* The region is cold, better drop the hotness info. */
+		folio_clear_lru_refs(folio);
 		folio_test_clear_young(folio);
 		if (!folio_isolate_lru(folio))
 			goto put_folio;

_

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

#67 lore raw

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

In reply to Kairui Song
Quoted 21 lines · On 11/23/26 19:53, Kairui Song via B4 Relay wrote:

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.

---
 mm/damon/paddr.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
mm/damon/paddr.c +0 -0
index e89cb14ee17b..411e1d557ba3 100644

mm/damon/paddr.c static unsigned long damon_pa_pageout(struct damon_region *r, · line 284

Quoted 7 lines
mm/damon/paddr.c +2 -1
@@ -279,7 +279,8 @@ static unsigned long damon_pa_pageout(struct damon_region *r,
 		else
 			*sz_filter_passed += folio_size(folio) / addr_unit;
 
-		folio_clear_referenced(folio);
+		/* The region is cold, better drop the hotness info. */
+		folio_clear_lru_refs(folio);
 		folio_test_clear_young(folio);

I also wonder whether both operations here should be abstracted, such that MM code doesn't have to worry about the details of reclaim handling.

Signature · 3 lines
Cheers,

David
maintainer tree notice
#68 lore raw

[to-be-updated] mm-damon-convert-to-lru-refs-based-operations-for-mglru.patch removed from -mm tree

In reply to Kairui Song
The quilt patch titled Subject: mm/damon: convert to LRU refs based operations for MGLRU has been removed from the -mm tree. Its filename was…

The quilt patch titled
Subject: mm/damon: convert to LRU refs based operations for MGLRU
has been removed from the -mm tree. Its filename was
mm-damon-convert-to-lru-refs-based-operations-for-mglru.patch

This patch was dropped because an updated version will be issued

------------------------------------------------------
From: Kairui Song <[email protected]>
Subject: mm/damon: convert to LRU refs based operations for MGLRU
Date: Tue, 24 Nov 2026 02:53:04 +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.

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]>
Cc Harry Yoo <[email protected]>
 mm/damon/paddr.c |    3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
mm/damon/paddr.c renamed from mm/damon/paddr.c~mm-damon-convert-to-lru-refs-based-operations-for-mglru +2 -1
@@ -279,7 +279,8 @@ static unsigned long damon_pa_pageout(st
 		else
 			*sz_filter_passed += folio_size(folio) / addr_unit;
 
-		folio_clear_referenced(folio);
+		/* The region is cold, better drop the hotness info. */
+		folio_clear_lru_refs(folio);
 		folio_test_clear_young(folio);
 		if (!folio_isolate_lru(folio))
 			goto put_folio;

_

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-khugepaged-convert-to-lru-refs-based-operations-for-mglru.patch mm-madvise-adapt-for-lru-refs-based-operations-for-mglru.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
#69 lore raw

PATCH v6 13/18 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. The classical LRU keeps the plain bit test.

---
 mm/khugepaged.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
mm/khugepaged.c +3 -1
index 2dc4245814df..5e768481ac22 100644
@@ -579,7 +579,9 @@ static bool folio_pte_referenced(struct folio *folio,
 		struct vm_area_struct *vma, unsigned long addr, pte_t pteval)
 {
 	/* The folio was referenced previously ... */
-	if (folio_test_young(folio) || folio_test_referenced(folio))
+	if (folio_test_young(folio))
+		return true;
+	if (folio_check_lru_refs(folio))
 		return true;
 	/* ... or the PTE mapping was recently used */
 	return pte_young(pteval) || mmu_notifier_test_young(vma->vm_mm, addr);
Signature · 1 line
2.56.1
maintainer tree notice
#70 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: Tue, 24 Nov 2026 02:53:05 +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. 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]>
Cc Harry Yoo <[email protected]>
 mm/khugepaged.c |    4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
mm/khugepaged.c renamed from mm/khugepaged.c~mm-khugepaged-convert-to-lru-refs-based-operations-for-mglru +3 -1
@@ -579,7 +579,9 @@ 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_young(folio))
+		return true;
+	if (folio_check_lru_refs(folio))
 		return true;
 	/* ... or the PTE mapping was recently used */
 	return pte_young(pteval) || mmu_notifier_test_young(vma->vm_mm, addr);

_

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

#71 lore raw

Re: [PATCH v6 13/18] mm/khugepaged: convert to LRU refs based operations for MGLRU

In reply to Kairui Song
Quoted 24 lines · On 11/23/26 19:53, Kairui Song via B4 Relay wrote:

From: Kairui Song <[email protected]>

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. The classical LRU keeps the plain bit test.

---
 mm/khugepaged.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
mm/khugepaged.c +0 -0
index 2dc4245814df..5e768481ac22 100644

mm/khugepaged.c static bool folio_pte_referenced(struct folio *folio, · line 585

Quoted 8 lines
mm/khugepaged.c +3 -1
@@ -579,7 +579,9 @@ static bool folio_pte_referenced(struct folio *folio,
 		struct vm_area_struct *vma, unsigned long addr, pte_t pteval)
 {
 	/* The folio was referenced previously ... */
-	if (folio_test_young(folio) || folio_test_referenced(folio))
+	if (folio_test_young(folio))
+		return true;
+	if (folio_check_lru_refs(folio))
 		return true;

Why separate lines?

Also, is there some way to abstract this that core-mm has to worry less about the details?

Some helper that tells us using nice semantics exactly what we want to know.

Signature · 3 lines
Cheers,

David
#72 lore raw

Re: [PATCH v6 13/18] mm/khugepaged: convert to LRU refs based operations for MGLRU

Quoted 21 lines · David Hildenbrand (Arm)
Quoted 19 lines · On 11/23/26 19:53, Kairui Song via B4 Relay wrote:

From: Kairui Song <[email protected]>

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. The classical LRU keeps the plain bit test.

---
 mm/khugepaged.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
Quoted 15 lines

mm/khugepaged.c static bool folio_pte_referenced(struct folio *folio, · line 585

Quoted 13 lines
mm/khugepaged.c +3 -1
index 2dc4245814df..5e768481ac22 100644
@@ -579,7 +579,9 @@ static bool folio_pte_referenced(struct folio *folio,
              struct vm_area_struct *vma, unsigned long addr, pte_t pteval)
 {
      /* The folio was referenced previously ... */
-     if (folio_test_young(folio) || folio_test_referenced(folio))
+     if (folio_test_young(folio))
+             return true;
+     if (folio_check_lru_refs(folio))
              return true;

Why separate lines?

I thought separating them would make the git log easier to track if we changed one of them again in the future. I can change it back if it's not helpful.

Quoted 2 lines

Also, is there some way to abstract this that core-mm has to worry less about the details?

Let's just move folio_test_young into folio_check_lru_refs() then, PG_young is page idles's hint for LRU, so doing that makes sense.

And with FG, I think we will soon be able to retire PG_young completely, page idle's feed back can just call folio_inc_lru_refs(folio, LRU_REF_MAPPED), save one page flag. But can't do that yet, need to cover the CLRU case.

maintainer tree notice
#73 lore raw

[to-be-updated] mm-khugepaged-convert-to-lru-refs-based-operations-for-mglru.patch removed from -mm tree

In reply to Kairui Song
The quilt patch titled Subject: mm/khugepaged: convert to LRU refs based operations for MGLRU has been removed from the -mm tree. Its filename was…

The quilt patch titled
Subject: mm/khugepaged: convert to LRU refs based operations for MGLRU
has been removed from the -mm tree. Its filename was
mm-khugepaged-convert-to-lru-refs-based-operations-for-mglru.patch

This patch was dropped because an updated version will be issued

------------------------------------------------------
From: Kairui Song <[email protected]>
Subject: mm/khugepaged: convert to LRU refs based operations for MGLRU
Date: Tue, 24 Nov 2026 02:53:05 +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. 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]>
Cc Harry Yoo <[email protected]>
 mm/khugepaged.c |    4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
mm/khugepaged.c renamed from mm/khugepaged.c~mm-khugepaged-convert-to-lru-refs-based-operations-for-mglru +3 -1
@@ -579,7 +579,9 @@ 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_young(folio))
+		return true;
+	if (folio_check_lru_refs(folio))
 		return true;
 	/* ... or the PTE mapping was recently used */
 	return pte_young(pteval) || mmu_notifier_test_young(vma->vm_mm, addr);

_

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-madvise-adapt-for-lru-refs-based-operations-for-mglru.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
#74 lore raw

PATCH v6 14/18 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 | 54 ++++++++++++++++++++++++++++++++++++++++--------------
 1 file changed, 40 insertions(+), 14 deletions(-)
mm/madvise.c +40 -14
index a36cfe98dd81..7e562e78d52a 100644
@@ -360,6 +360,42 @@ static inline int madvise_folio_pte_batch(unsigned long addr, unsigned long end,
 				     FPB_MERGE_YOUNG_DIRTY);
 }
 
+static void madvise_cold_prep_folio(struct folio *folio)
+{
+	/*
+	 * VM couldn't reclaim the folio unless we clear PG_young.
+	 * As a side effect, idle-page tracking loses recent referenced history.
+	 */
+	folio_test_clear_young(folio);
+
+	/*
+	 * For the active/inactive LRU, a folio demoted out of the active
+	 * list should have PG_workingset so its refault is still accounted
+	 * as a workingset refault, and the referenced bit always needs to
+	 * be cleared even for inactive folios. 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);
+	}
+}
+
+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)
@@ -434,12 +470,10 @@ static int madvise_cold_or_pageout_pte_range(pmd_t *pmd,
 			tlb_remove_pmd_tlb_entry(tlb, pmd, addr);
 		}
 
-		folio_clear_referenced(folio);
-		folio_test_clear_young(folio);
-		if (folio_test_active(folio))
-			folio_set_workingset(folio);
+		madvise_cold_prep_folio(folio);
 		if (pageout) {
 			if (folio_isolate_lru(folio)) {
+				madvise_pageout_prep_folio(folio);
 				if (folio_test_unevictable(folio))
 					folio_putback_lru(folio);
 				else
@@ -544,18 +578,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
maintainer tree notice
#75 lore raw

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

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: Tue, 24 Nov 2026 02:53:06 +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]>
Cc Harry Yoo <[email protected]>
 mm/madvise.c |   54 ++++++++++++++++++++++++++++++++++++-------------
 1 file changed, 40 insertions(+), 14 deletions(-)
mm/madvise.c renamed from mm/madvise.c~mm-madvise-adapt-for-lru-refs-based-operations-for-mglru +40 -14
@@ -360,6 +360,42 @@ static inline int madvise_folio_pte_batc
 				     FPB_MERGE_YOUNG_DIRTY);
 }
 
+static void madvise_cold_prep_folio(struct folio *folio)
+{
+	/*
+	 * VM couldn't reclaim the folio unless we clear PG_young.
+	 * As a side effect, idle-page tracking loses recent referenced history.
+	 */
+	folio_test_clear_young(folio);
+
+	/*
+	 * For the active/inactive LRU, a folio demoted out of the active
+	 * list should have PG_workingset so its refault is still accounted
+	 * as a workingset refault, and the referenced bit always needs to
+	 * be cleared even for inactive folios. 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);
+	}
+}
+
+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)
@@ -434,12 +470,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
@@ -544,18 +578,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-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

#76 lore raw

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

In reply to Kairui Song
Quoted 51 lines · On 11/23/26 19:53, Kairui Song via B4 Relay wrote:

From: Kairui Song <[email protected]>

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 | 54 ++++++++++++++++++++++++++++++++++++++++--------------
 1 file changed, 40 insertions(+), 14 deletions(-)
mm/madvise.c +11 -0
index a36cfe98dd81..7e562e78d52a 100644
@@ -360,6 +360,42 @@ static inline int madvise_folio_pte_batch(unsigned long addr, unsigned long end,
 				     FPB_MERGE_YOUNG_DIRTY);
 }
 
+static void madvise_cold_prep_folio(struct folio *folio)
+{
+	/*
+	 * VM couldn't reclaim the folio unless we clear PG_young.
+	 * As a side effect, idle-page tracking loses recent referenced history.
+	 */
+	folio_test_clear_young(folio);
+
+	/*
+	 * For the active/inactive LRU, a folio demoted out of the active
+	 * list should have PG_workingset so its refault is still accounted

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

Quoted 10 lines
mm/madvise.c +10 -0
+	 * 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);
+	}
+}

These are all not things that madvise.c should have to worry about. Can we have some call into folio/reclaim code that will take care of this?

Signature · 3 lines
Cheers,

David
#77 lore raw

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

Quoted 58 lines · David Hildenbrand (Arm)
Quoted 56 lines · On 11/23/26 19:53, Kairui Song via B4 Relay wrote:

From: Kairui Song <[email protected]>

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 | 54 ++++++++++++++++++++++++++++++++++++++++--------------
 1 file changed, 40 insertions(+), 14 deletions(-)
mm/madvise.c +16 -0
index a36cfe98dd81..7e562e78d52a 100644
@@ -360,6 +360,42 @@ static inline int madvise_folio_pte_batch(unsigned long addr, unsigned long end,
                                   FPB_MERGE_YOUNG_DIRTY);
 }
 
+static void madvise_cold_prep_folio(struct folio *folio)
+{
+     /*
+      * VM couldn't reclaim the folio unless we clear PG_young.
+      * As a side effect, idle-page tracking loses recent referenced history.
+      */
+     folio_test_clear_young(folio);
+
+     /*
+      * For the active/inactive LRU, a folio demoted out of the active
+      * list should have PG_workingset so its refault is still accounted
+      * as a workingset refault, and the referenced bit always needs to
+      * be cleared even for inactive folios. For MGLRU, MADV_COLD clears
+      * refs in folio_deactivate(); MADV_PAGEOUT handles refs after isolation.
+      */
+     if (!lru_gen_enabled()) {
Quoted 8 lines

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

Quoted 5 lines
mm/madvise.c +5 -0
+             folio_clear_lru_refs(folio);
+             if (folio_test_active(folio))
+                     folio_set_workingset(folio);
+     }
+}

These are all not things that madvise.c should have to worry about. Can we have some call into folio/reclaim code that will take care of this?

I tried many times on this and found it's increadibly hard to do so without changing the behavior of CLRU globally, as the whole if (folio_test_active(folio)) then folio_set_workingset(folio) here is actually a "workaround" for CLRU, and we have two LRU...

I managed to reduce the code left in madvise here a little bit, though. I think we can clean this part further, later. It will be part of the work to better seperate CLRU with MGLRU, or making MGLRU the default one.

reviewer
#78 lore raw

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

Quoted 74 lines · Kairui Song
Quoted 58 lines · David Hildenbrand (Arm)
Quoted 56 lines · On 11/23/26 19:53, Kairui Song via B4 Relay wrote:

From: Kairui Song <[email protected]>

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 | 54 ++++++++++++++++++++++++++++++++++++++++--------------
 1 file changed, 40 insertions(+), 14 deletions(-)
mm/madvise.c +16 -0
index a36cfe98dd81..7e562e78d52a 100644
@@ -360,6 +360,42 @@ static inline int madvise_folio_pte_batch(unsigned long addr, unsigned long end,
                                   FPB_MERGE_YOUNG_DIRTY);
 }
 
+static void madvise_cold_prep_folio(struct folio *folio)
+{
+     /*
+      * VM couldn't reclaim the folio unless we clear PG_young.
+      * As a side effect, idle-page tracking loses recent referenced history.
+      */
+     folio_test_clear_young(folio);
+
+     /*
+      * For the active/inactive LRU, a folio demoted out of the active
+      * list should have PG_workingset so its refault is still accounted
+      * as a workingset refault, and the referenced bit always needs to
+      * be cleared even for inactive folios. For MGLRU, MADV_COLD clears
+      * refs in folio_deactivate(); MADV_PAGEOUT handles refs after isolation.
+      */
+     if (!lru_gen_enabled()) {
Quoted 8 lines

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

Quoted 5 lines
mm/madvise.c +5 -0
+             folio_clear_lru_refs(folio);
+             if (folio_test_active(folio))
+                     folio_set_workingset(folio);
+     }
+}

These are all not things that madvise.c should have to worry about. Can we have some call into folio/reclaim code that will take care of this?

I tried many times on this and found it's increadibly hard to do so without changing the behavior of CLRU globally, as the whole if (folio_test_active(folio)) then folio_set_workingset(folio) here is actually a "workaround" for CLRU, and we have two LRU...

Quoted 4 lines

I managed to reduce the code left in madvise here a little bit, though. I think we can clean this part further, later. It will be part of the work to better seperate CLRU with MGLRU, or making MGLRU the default one.

I agree with both, seperate CLRU with MGLRU, and making MGLRU the default one. The latter is being done on mobile phone by default afak, and the latter is also also enabled on some distrols and servers.

maintainer tree notice
#79 lore raw

[to-be-updated] mm-madvise-adapt-for-lru-refs-based-operations-for-mglru.patch removed from -mm tree

In reply to Kairui Song
The quilt patch titled Subject: mm/madvise: adapt for LRU refs based operations for MGLRU has been removed from the -mm tree. Its filename was…

The quilt patch titled
Subject: mm/madvise: adapt for LRU refs based operations for MGLRU
has been removed from the -mm tree. Its filename was
mm-madvise-adapt-for-lru-refs-based-operations-for-mglru.patch

This patch was dropped because an updated version will be issued

------------------------------------------------------
From: Kairui Song <[email protected]>
Subject: mm/madvise: adapt for LRU refs based operations for MGLRU
Date: Tue, 24 Nov 2026 02:53:06 +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]>
Cc Harry Yoo <[email protected]>
 mm/madvise.c |   54 ++++++++++++++++++++++++++++++++++++-------------
 1 file changed, 40 insertions(+), 14 deletions(-)
mm/madvise.c renamed from mm/madvise.c~mm-madvise-adapt-for-lru-refs-based-operations-for-mglru +40 -14
@@ -360,6 +360,42 @@ static inline int madvise_folio_pte_batc
 				     FPB_MERGE_YOUNG_DIRTY);
 }
 
+static void madvise_cold_prep_folio(struct folio *folio)
+{
+	/*
+	 * VM couldn't reclaim the folio unless we clear PG_young.
+	 * As a side effect, idle-page tracking loses recent referenced history.
+	 */
+	folio_test_clear_young(folio);
+
+	/*
+	 * For the active/inactive LRU, a folio demoted out of the active
+	 * list should have PG_workingset so its refault is still accounted
+	 * as a workingset refault, and the referenced bit always needs to
+	 * be cleared even for inactive folios. 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);
+	}
+}
+
+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)
@@ -434,12 +470,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
@@ -544,18 +578,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-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
#80 lore raw

PATCH v6 15/18 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(), and it also checks if the VMA has recency to avoid false updates.

So first just use the right helper here to be more consistent. 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 75e8641bf9ff..fa9f6d21e786 100644
@@ -3122,8 +3122,8 @@ static void __split_huge_pud_locked(struct vm_area_struct *vma, pud_t *pud,
 
 	if (!folio_test_dirty(folio) && pud_dirty(old_pud))
 		folio_mark_dirty(folio);
-	if (!folio_test_referenced(folio) && pud_young(old_pud))
-		folio_set_referenced(folio);
+	if (pud_young(old_pud) && vma_has_recency(vma))
+		folio_mark_accessed(folio);
 	folio_remove_rmap_pud(folio, page, vma);
 	add_mm_counter(vma->vm_mm, mm_counter_file(folio),
 		-HPAGE_PUD_NR);
@@ -3245,8 +3245,8 @@ static void __split_huge_pmd_locked(struct vm_area_struct *vma, pmd_t *pmd,
 			folio = page_folio(page);
 			if (!folio_test_dirty(folio) && pmd_dirty(old_pmd))
 				folio_mark_dirty(folio);
-			if (!folio_test_referenced(folio) && pmd_young(old_pmd))
-				folio_set_referenced(folio);
+			if (pmd_young(old_pmd) && vma_has_recency(vma))
+				folio_mark_accessed(folio);
 			folio_remove_rmap_pmd(folio, page, vma);
 			add_mm_counter(mm, mm_counter_file(folio), -HPAGE_PMD_NR);
 			folio_put(folio);
Signature · 1 line
2.56.1
reviewer
#81 lore raw

Re: [PATCH v6 15/18] mm/huge_memory: mark folio as accessed more accurately on split

Quoted 10 lines · On Mon Nov 23, 2026 at 1:53 PM EST, Kairui Song via B4 Relay wrote:

From: Kairui Song <[email protected]>

The behavior of updating the folio's access info isn't consistent for huge mapping splitting or ordinary unmapping. The page table's young flag has to be translated into folio's access info.

Right now it only 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(), and it also checks if the VMA has recency to avoid false updates.

Can you elaborate on why vma_has_recency() should be used? "false updates" might be too vague.

Quoted 39 lines

So first just use the right helper here to be more consistent. 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 75e8641bf9ff..fa9f6d21e786 100644
@@ -3122,8 +3122,8 @@ static void __split_huge_pud_locked(struct vm_area_struct *vma, pud_t *pud,
 
 	if (!folio_test_dirty(folio) && pud_dirty(old_pud))
 		folio_mark_dirty(folio);
-	if (!folio_test_referenced(folio) && pud_young(old_pud))
-		folio_set_referenced(folio);
+	if (pud_young(old_pud) && vma_has_recency(vma))
+		folio_mark_accessed(folio);
 	folio_remove_rmap_pud(folio, page, vma);
 	add_mm_counter(vma->vm_mm, mm_counter_file(folio),
 		-HPAGE_PUD_NR);
@@ -3245,8 +3245,8 @@ static void __split_huge_pmd_locked(struct vm_area_struct *vma, pmd_t *pmd,
 			folio = page_folio(page);
 			if (!folio_test_dirty(folio) && pmd_dirty(old_pmd))
 				folio_mark_dirty(folio);
-			if (!folio_test_referenced(folio) && pmd_young(old_pmd))
-				folio_set_referenced(folio);
+			if (pmd_young(old_pmd) && vma_has_recency(vma))
+				folio_mark_accessed(folio);
 			folio_remove_rmap_pmd(folio, page, vma);
 			add_mm_counter(mm, mm_counter_file(folio), -HPAGE_PMD_NR);
 			folio_put(folio);
Signature · 2 lines
Best Regards,
Yan, Zi
#82 lore raw

Re: [PATCH v6 15/18] mm/huge_memory: mark folio as accessed more accurately on split

Quoted 7 lines · Zi Yan
Quoted 6 lines · On Mon Nov 23, 2026 at 1:53 PM EST, Kairui Song via B4 Relay wrote:

From: Kairui Song <[email protected]>

The behavior of updating the folio's access info isn't consistent for huge mapping splitting or ordinary unmapping. The page table's young flag has to be translated into folio's access info.

Quoted 7 lines
Quoted 4 lines

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(), and it also checks if the VMA has recency to avoid false updates.

Can you elaborate on why vma_has_recency() should be used? "false updates" might be too vague.

Thanks for the careful review!

Right, maybe I shouldn't say these are "false updates" indeed. But it makes sense to do so, will reword that paragraph.

The young PTE becomes folio hotness via the LRU refs to help improve LRU accuracy: telling the LRU that the folio is accessed, so it should be protected as it is more likely to be reused soon.

But vma_has_recency() is the app's hint that these accesses are not a recency signal: MADV_RANDOM expects "page references in random order", POSIX_FADV_NOREUSE sets FMODE_NOREUSE, and MADV_SEQUENTIAL expects pages which "may be freed soon after they are accessed", which is the opposite of what the refs mean. In all these cases, marking the folio referenced from a PTE access hurts instead of helping.

zap_pte_range() and folio_referenced_one() already ignore the accessed bit for such VMAs. The split path is the last place translating a young PTE into folio hotness without it. So while converting to the more useful folio_mark_accessed(), also add the missing recency check to avoid wrong promotion.

reviewer Reviewed-by
#83 lore raw

Re: [PATCH v6 15/18] mm/huge_memory: mark folio as accessed more accurately on split

Quoted 32 lines · Kairui Song
Quoted 7 lines · Zi Yan
Quoted 6 lines · On Mon Nov 23, 2026 at 1:53 PM EST, Kairui Song via B4 Relay wrote:

From: Kairui Song <[email protected]>

The behavior of updating the folio's access info isn't consistent for huge mapping splitting or ordinary unmapping. The page table's young flag has to be translated into folio's access info.

Quoted 7 lines
Quoted 4 lines

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(), and it also checks if the VMA has recency to avoid false updates.

Can you elaborate on why vma_has_recency() should be used? "false updates" might be too vague.

Thanks for the careful review!

Right, maybe I shouldn't say these are "false updates" indeed. But it makes sense to do so, will reword that paragraph.

The young PTE becomes folio hotness via the LRU refs to help improve LRU accuracy: telling the LRU that the folio is accessed, so it should be protected as it is more likely to be reused soon.

But vma_has_recency() is the app's hint that these accesses are not a recency signal: MADV_RANDOM expects "page references in random order", POSIX_FADV_NOREUSE sets FMODE_NOREUSE, and MADV_SEQUENTIAL expects pages which "may be freed soon after they are accessed", which is the opposite of what the refs mean. In all these cases, marking the folio referenced from a PTE access hurts instead of helping.

Quoted 5 lines

zap_pte_range() and folio_referenced_one() already ignore the accessed bit for such VMAs. The split path is the last place translating a young PTE into folio hotness without it. So while converting to the more useful folio_mark_accessed(), also add the missing recency check to avoid wrong promotion.

The above explanation helps a lot. With that in the commit message, feel free to add

Thanks.

Best Regards,
Yan, Zi