mm/mglru: MADV_RANDOM page cache never ages and thrashes the oldest generation
Subsystems (3)
cover mm/mglru: MADV_RANDOM page cache never ages and thrashes the oldest generation
Hi,
It looks like I've stumbled upon an awkward behaviour. When MGLRU is enabled, page cache faulted in through an MADV_RANDOM mapping goes into the oldest generation, and the refaults land there at the same rate as well. In my tests bpftrace shows the generations stay at seq 0-3, with no aging attempts and no new generations during the workload run, and /sys/kernel/debug/lru_gen_full shows for generation seq 0 15758245 pages evicted and 15580028 pages refaulted, which is 98.87%.
At the same time, a file read through a normal mmap lands one generation higher and none of its pages are evicted. It stays cached until the end of the workload, and the randomly read working set shrinks. With lru_gen disabled, the CLRU evicts the file instead, and throughput recovers 20-30 seconds after the file was read. I would expect the same behaviour for MGLRU.
I first saw this slowdown on a single-node OpenSearch 3.6 (Lucene 10.4) HNSW vector search workload [1]. The node had about 2.8 GiB of page cache for a 2.9 GiB index, and Lucene maps the .vec and .vex files with MADV_RANDOM. Kernel 7.2.10-200.fc44.aarch64.
Search latency and throughput on a single-node OpenSearch:
MGLRU on MGLRU off
p50, ms 286.0 73.6 p90, ms 512.1 135.6 p99, ms 687.0 191.0
queries/s 27.4 87.1
Disk reads, same runs:
MGLRU on MGLRU off
major faults/query 1484 325 disk reads/query 1484 325 read size, KiB 4.0 4.0
disk read, GiB/run 509.6 111.5
This is clearly visible on the page cache chart [2], where "blue" are page cache pages mapped into at least one process's address space and "orange" the rest of the page cache.
Then I reproduced it with a synthetic HNSW-like query script in python, and later with fio alone, on 7.2.10-200.fc44.aarch64, 7.2.14, 7.2.14 with the MGLRU-FG v4 series [3][4], and on mainline v7.3-rc7.
Kernel and setup
----------------
Arm64 Lima VM (vz) on an Apple M1 Max host, 8 vCPUs, 16 GiB RAM, virtio disk, btrfs, 4K pages, THP madvise. Tests run in a 2 GiB memcg with swap disabled.CONFIG_LRU_GEN=y, CONFIG_LRU_GEN_ENABLED=y, CONFIG_LRU_GEN_WALKS_MMU=y.
Reproducer
----------
The script below reproduces the stall with fio, MGLRU on (y) or off (n). 4 fio jobs read the vector file at random through an mmap in a 2 GiB memcg, with MADV_RANDOM or no advice (normal).
At t=90 a second fio reads a 600 MB cold file twice through a normal mmap. With MGLRU on and MADV_RANDOM, the cold file stays cached and IOPS doesn't recover.
./run.sh <y|n> [random|normal]
-------
#!/usr/bin/env bash
set -u
usage="usage: sudo $0 <y|n> [random|normal]"
lru=${1:?$usage}
advice=${2:-random}
case $advice in random) hint=1 ;; normal) hint=0 ;; *) echo "$usage" >&2; exit 1 ;; esac out=$(dirname "$(readlink -f "$0")")/results/$(uname -r)/$lru-$advice.txt [ ! -e "$out" ] || { echo "$out exists, move it aside first" >&2; exit 1; } vec=/var/tmp/mglru/vs-vec.bin
cold=/var/tmp/mglru/cold.bin
unit=mglru-06-$$
cg=/sys/fs/cgroup/system.slice/$unit.scope
log=/tmp/mglru-06-$$.fio
workload() {
fio --name=vec --filename=$vec --ioengine=mmap --rw=randread --bs=4k \
--fadvise_hint=$hint --random_distribution=zipf:0.8 --numjobs=4 \
--group_reporting --time_based --runtime=270 \
--status-interval=1 --output-format=terse --output=$log &
sleep 90
fio --name=cold --filename=$cold --ioengine=mmap --rw=read --bs=4k \
--fadvise_hint=0 --loops=2 > /dev/null
wait
}memstat() {
awk -v key=$1 '$1 == key { print $2 }' $cg/memory.stat
}cached_mb() {
fincore -nb -o RES $1 | awk '{ print int($1 / 2^20) }'
}render() {
local t=$1 kb faults refaults activated
kb=$(tail -n 1 $log | cut -d';' -f6)
faults=$(memstat pgmajfault)
refaults=$(memstat workingset_refault_file)
activated=$(memstat workingset_activate_file)
printf '%4s %9s %9s %9s %9s %7s %7s\n' $t \
$(( (kb - prev[0]) / 4 / 5 )) \
$(( (faults - prev[1]) / 5 )) \
$(( (refaults - prev[2]) / 5 )) \
$(( (activated - prev[3]) / 5 )) \
$(cached_mb $vec) $(cached_mb $cold)
prev=($kb $faults $refaults $activated)
}mkdir -p /var/tmp/mglru
[ -f $vec ] || dd if=/dev/urandom of=$vec bs=1M count=1905 status=none [ -f $cold ] || dd if=/dev/urandom of=$cold bs=1M count=600 status=none
echo $lru > /sys/kernel/mm/lru_gen/enabled
sync
echo 3 > /proc/sys/vm/drop_caches
mkdir -p "$(dirname "$out")"
exec > >(tee "$out")
echo "MGLRU $(cat /sys/kernel/mm/lru_gen/enabled), kernel $(uname -r), $advice advice, cold file read at t=90 s" printf '%4s %9s %9s %9s %9s %7s %7s\n' t IOPS majflt/s refault/s activ/s vec_MB cold_MB
export -f workload
export vec cold hint log
systemd-run --scope --quiet --unit=$unit -p MemoryMax=2G -p MemorySwapMax=0 bash -c workload &
until [ -e $cg/memory.stat ]; do kill -0 $! 2>/dev/null || exit 1; sleep 0.1; done prev=(0 $(memstat pgmajfault) $(memstat workingset_refault_file) $(memstat workingset_activate_file)) for t in $(seq 5 5 270); do
sleep 5
render $t
done
wait
-------
Results
-------
v7.3-rc7, cold file read at t=90
lru_gen on, random:
t IOPS majflt/s refault/s activ/s vec_MB cold_MB
85 4966675 0 0 0 1904 0 90 4863829 1150 1158 0 1729 277 95 174236 30664 30669 0 1408 600 120 202080 28161 28163 0 1408 600 180 207005 26665 26667 0 1408 600 270 226341 22677 22669 0 1409 600
lru_gen off, random:
t IOPS majflt/s refault/s activ/s vec_MB cold_MB
85 5007909 0 0 0 1904 0 90 5150972 140 228 51 1873 139 95 188806 29509 29504 9283 1413 600 110 342921 31803 31802 23547 1697 313 115 2563389 15857 15849 10540 1903 107 120 5157256 31 31 27 1904 107 270 5179181 2 28 27 1904 107
lru_gen on, normal:
t IOPS majflt/s refault/s activ/s vec_MB cold_MB
85 5093044 0 0 0 1904 0 90 4887136 0 0 0 1904 39 95 2612769 3665 88721 6458 1904 109 100 4997923 0 0 0 1904 106 180 5134344 0 0 0 1904 104 270 5025222 0 0 0 1904 104
lru_gen off, normal:
t IOPS majflt/s refault/s activ/s vec_MB cold_MB
85 4866859 0 0 0 1904 0 90 4466107 0 0 0 1904 103 95 2378250 3027 34135 33956 1885 127 100 2734588 5431 5520 5500 1903 109 105 4933296 62 69 67 1904 104 270 4822353 2 17 14 1904 104
As you can see, only MGLRU with MADV_RANDOM stalls, at about 220k IOPS until the end. It activates no refaults, and cold.bin stays at 600 MB while the vector file stays near 1408 MB. With MGLRU off, the same workload is back to ~5M IOPS 30 seconds after the cold read. With normal advice, both LRUs recover within 15 seconds.
With MGLRU and MADV_RANDOM, vs-vec.bin reads in my python reproducer drop from ~2.5M/s to ~300K/s after the cold read and never recover (chart [5]). On the same kernel with normal advice, MGLRU recovers normally (chart [6]).
What I traced
-------------
On 7.2.14 with bpftrace, every MADV_RANDOM fault and refault is inserted in the old gen. lru_gen_enter_fault() sets in_lru_fault from vma_has_recency(), which is false for VM_RAND_READ, so refaults are never activated. The aging walk and the look-around on eviction skip these mappings too.
On 7.2.14 with bpftrace, the oldest generation is evicted and refilled at the same rate, and never empties. min_seq doesn't advance, fentry:try_to_inc_max_seq is never called, and the window stays at seq 0-3.
On 7.2.10 (fio, no tracing), one manual aging step, "+ memcg_id 0 max_seq" written to /sys/kernel/debug/lru_gen, evicts the cold file within 10 seconds.
I also tested the MGLRU-FG v4 series [3][4] on top of 7.2.14. The stall is the same, refaults on the MADV_RANDOM mapping are still not activated. The series cover letter [3] describes this as intended, so I'm not sure what the right fix is here.
RFC patch
---------
Patch 1/1 is a draft against v7.3-rc7. I'm still not sure it is the right fix and would appreciate feedback. The simplest thing I found is one more condition in should_run_aging(), which does the same as the manual aging step above, at the cost of a few more reads and a comparison.
In short:
1. Run aging when eviction only recycles the oldest generation
2. Pass the evictable size that get_nr_to_scan() already computes down to should_run_aging(), so lruvec_evictable_size() is still called once per pass and not on every batch
The module parameter lru_gen_age_on_thrash and noinline was only for A/B runs and bpftrace and comparing results.
Results with the patch
----------------------
The fio reproducer from above on v7.3-rc7 with the patch. "checks" is the number of oldest_gen_thrashing() calls in the last 5 seconds, and "gens" the number of generations added by aging, both from bpftrace.
lru_gen on, random, lru_gen_age_on_thrash=Y:
t IOPS majflt/s refault/s activ/s vec_MB cold_MB checks gens
85 5019235 0 0 0 1904 0 0 0 90 5073570 377 384 0 1764 254 0 0 95 130923 20534 20527 0 1418 600 2441 0 105 218624 23462 23456 0 1418 600 1785 0 115 178889 26035 26043 0 1418 600 1338 0 120 175238 26918 26910 0 1418 600 2086 1 125 256621 27773 27780 0 1418 600 1959 0 130 253813 24509 24501 0 1677 342 1910 0 135 2678888 11649 11649 0 1904 116 1914 0 140 5064423 2 2 0 1904 116 297 0 180 4872187 0 0 0 1904 116 0 0 265 4939524 0 0 0 1904 115 0 0
The check returned true 3 times, and aging added one generation, at t=117 (seq 0-3 to 1-4).
lru_gen on, random, lru_gen_age_on_thrash=N:
t IOPS majflt/s refault/s activ/s vec_MB cold_MB checks gens
85 5127299 0 0 0 1904 0 0 0 90 5290342 409 417 0 1822 196 0 0 95 151082 27372 27372 0 1418 600 2739 0 120 251683 33784 33789 0 1418 600 2425 0 180 252607 31539 31542 0 1418 600 2314 0 265 223364 28211 28220 0 1418 600 2290 0
The recovery is still slower than with CLRU. With the patch IOPS recovers at t=135-140, with CLRU at t=115-120. I think the patch adds this delay, as the first aging step needs up to one lruvec worth of refaults after the stall starts.
In the OpenSearch workload reclaim runs from the start, so the counter is already close to the threshold when the cold file is read, and the recovery is comparable to CLRU (chart [7]).
The threshold could be lowered, but it's not clear to me yet how to pick it right. The patch is a draft to get feedback on the approach. Any thoughts?
Thanks,
Maxim Muzafarov
Links
-----
[1] https://docs.opensearch.org/latest/benchmark/workloads/vectorsearch/
[2] https://gist.github.com/user-attachments/assets/cbfa5c17-0a89-458f-b816-4d1bb72cb97c
[3] https://lore.kernel.org/all/[email protected]/
[4] https://github.com/zen-kernel/zen-kernel/commits/7.2/mglru-fg-v4/
[5] https://gist.github.com/user-attachments/assets/f65fbbf3-a30a-464f-8535-29d39e0dff43
[6] https://gist.github.com/user-attachments/assets/5d28512d-3a1d-4475-b20e-3690a8c9e196
[7] https://gist.github.com/user-attachments/assets/41b7aaa1-5e9c-43dc-8fc1-09d2df52f8d7
Maxim Muzafarov (1):
mm/mglru: age when the oldest generation is thrashing
mm/vmscan.c | 32 ++++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-)
base-commit: 24a19b953e2a3d0ea5a8c4951a0ab8f32720c907
Signature · 1 line
2.56.0
RFC PATCH 1/1 mm/mglru: age when the oldest generation is thrashing
With four generations, should_run_aging() only runs when the window shrinks. With every fault on MADV_RANDOM mapping landing in min_seq, and the oldest generation refilling as fast as it is evicted, min_seq never advances and pages in the generations above it are never evicted.
Run aging when the oldest file generation has refaulted more pages than the lruvec holds since it became the oldest.
--- mm/vmscan.c | 32 ++++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-)
mm/vmscan.c +28 -4
@@ -4966,8 +4966,26 @@ static int evict_folios(unsigned long nr_to_scan, struct lruvec *lruvec,return scanned; } +static bool oldest_gen_thrashing (struct lruvec *lruvec,unsigned long *min_seq, +int swappiness,unsigned long evictable) +{ +int tier; +unsigned long refaulted =0 ; +struct lru_gen_folio *lrugen = &lruvec->lrugen; +int hist =lru_hist_from_seq (min_seq[LRU_GEN_FILE ]); + +if (swappiness ==SWAPPINESS_ANON_ONLY ) +return false; + +for (tier =0 ; tier <MAX_NR_TIERS ; tier++) + refaulted +=atomic_long_read (&lrugen->refaulted[hist][LRU_GEN_FILE ][tier]); + +return refaulted > evictable; +} +static bool should_run_aging (struct lruvec *lruvec,unsigned long max_seq, -struct scan_control *sc,int swappiness) +struct scan_control *sc,int swappiness, +unsigned long evictable) {DEFINE_MIN_SEQ (lruvec);
@@ -4975,6 +4993,9 @@ static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq,if (evictable_min_seq (min_seq, swappiness) +MIN_NR_GENS > max_seq)return true; +if (oldest_gen_thrashing (lruvec, min_seq, swappiness, evictable)) +return true; +/* try to avoid aging, do gentle reclaim at the default priority */ if (sc->priority ==DEF_PRIORITY )return false;
@@ -4984,7 +5005,8 @@ static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq, }static long get_nr_to_scan (struct lruvec *lruvec,struct scan_control *sc, -struct mem_cgroup *memcg,int swappiness) +struct mem_cgroup *memcg,int swappiness, +unsigned long *nr_evictable) {unsigned long nr_to_scan, evictable;struct pglist_data *pgdat =lruvec_pgdat (lruvec);
@@ -5003,6 +5025,7 @@ static long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc, } evictable =lruvec_evictable_size (lruvec, swappiness); + *nr_evictable = evictable;/* try to scrape all its memory if this memcg was deleted */ if (!mem_cgroup_online (memcg))
@@ -5053,10 +5076,11 @@ static bool try_to_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc) {bool need_rotate = false, should_age = false;long nr_batch, nr_to_scan; +unsigned long evictable =0 ;int swappiness =get_swappiness (lruvec, sc);struct mem_cgroup *memcg =lruvec_memcg (lruvec); - nr_to_scan =get_nr_to_scan (lruvec, sc, memcg, swappiness); + nr_to_scan =get_nr_to_scan (lruvec, sc, memcg, swappiness, &evictable);while (nr_to_scan >0 ) {int delta;DEFINE_MAX_SEQ (lruvec);
@@ -5066,7 +5090,7 @@ static bool try_to_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)break ; } -if (should_run_aging (lruvec, max_seq, sc, swappiness)) { +if (should_run_aging (lruvec, max_seq, sc, swappiness, evictable)) {if (try_to_inc_max_seq (lruvec, max_seq, swappiness, false)) need_rotate = true; should_age = true;
base-commit: 24a19b953e2a3d0ea5a8c4951a0ab8f32720c907
Signature · 1 line
2.56.0
Quoted 2 lines · Maxim Muzafarov
Hi,
Hello Maxim!
Quoted 1 line
It looks like I've stumbled upon an awkward behaviour. When MGLRU is
You are not alone, I encountered same issue too :)
Quoted 35 lines
enabled, page cache faulted in through an
MADV_RANDOMmapping goes into the oldest generation, and the refaults land there at the same rate as well. In my tests bpftrace shows the generations stay at seq 0-3, with no aging attempts and no new generations during the workload run, and/sys/kernel/debug/lru_gen_fullshows for generation seq 0 15758245 pages evicted and 15580028 pages refaulted, which is 98.87%.At the same time, a file read through a normal mmap lands one generation higher and none of its pages are evicted. It stays cached until the end of the workload, and the randomly read working set shrinks. With
lru_gendisabled, the CLRU evicts the file instead, and throughput recovers 20-30 seconds after the file was read. I would expect the same behaviour for MGLRU.I first saw this slowdown on a single-node OpenSearch 3.6 (Lucene 10.4) HNSW vector search workload [1]. The node had about 2.8 GiB of page cache for a 2.9 GiB index, and Lucene maps the .vec and .vex files with
MADV_RANDOM. Kernel 7.2.10-200.fc44.aarch64.Search latency and throughput on a single-node OpenSearch:
MGLRU on MGLRU off
p50, ms 286.0 73.6 p90, ms 512.1 135.6 p99, ms 687.0 191.0queries/s 27.4 87.1
Disk reads, same runs:
MGLRU on MGLRU off
major faults/query 1484 325 disk reads/query 1484 325 read size, KiB 4.0 4.0disk read, GiB/run 509.6 111.5
Quoted 7 lines
This is clearly visible on the page cache chart [2], where "blue" are page cache pages mapped into at least one process's address space and "orange" the rest of the page cache.
Then I reproduced it with a synthetic HNSW-like query script in python, and later with fio alone, on 7.2.10-200.fc44.aarch64, 7.2.14, 7.2.14 with the MGLRU-FG v4 series [3][4], and on mainline v7.3-rc7.
The missing piece here is refault distance. Both MGLRU and CLRU ignore hotness on eviction for vma_has_recency() == false case, however, CLRU still has refault distance protection, while MGLRU doesn't.
I observed a similar issue, which disappeared after we added refault distance for MGLRU.
There is an early version of FG that have it:
https://lore.kernel.org/linux-mm/[email protected]/
See this patch, it too long so I have to split it out and dropped it for later version:
https://lore.kernel.org/linux-mm/[email protected]/
This code snip:
+ /* Set refault as active. */
+ if (distance < total / 2) {
+ folio_set_active(folio);
I may change it to something like folio_set_lru_refs(LRU_REFS_WORKINGSET) later for non in-fault case cause this kind of break FG for other cases.
That way, even a random folio will be put to the head directly instead of keep thrasing on tail. And placing on head or newer gen will trigger aging.
I think I got the problem right? I'll run your benchmark too a bit later, still tweaking it for some other issues. The refault distance part needs some rebasing and tweaking as it will have chemical reactions with many other MGLRU components and it may not work as expected yet (I also need to use it for an MRU fallback, because, in theory a pure random case may benifit more from fallback to MRU stragegy, but your case is a hybrid of hot random and cold non-random, so a bit tricky to get it right)...
(And we may also loose lru_gen_in_fault for refault case? Not sure...)
But I think we are getting there :), and your report is a really nice case!
[email protected]
AI reviewRe: [RFC PATCH 1/1] mm/mglru: age when the oldest generation is thrashing
In reply to Maxim MuzafarovThank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] mm/mglru: repeated back-to-back aging in oldest_gen_thrashing() --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] mm/mglru: repeated back-to-back aging in oldest_gen_thrashing() --
commit 17216aa0e22cf9bf70e1a34fa529d94d53089f2e
Author: Maxim Muzafarov <[email protected]>
mm/mglru: age when the oldest generation is thrashing
This commit triggers aging in should_run_aging() when the number of refaulted pages in the oldest file generation exceeds the total evictable size of the lruvec.
Quoted 33 lines
mm/vmscan.c +19
-1@@ -4966,8 +4966,26 @@ static int evict_folios(unsigned long nr_to_scan, struct lruvec *lruvec,return scanned; } +static bool oldest_gen_thrashing (struct lruvec *lruvec,unsigned long *min_seq, +int swappiness,unsigned long evictable) +{ +int tier; +unsigned long refaulted =0 ; +struct lru_gen_folio *lrugen = &lruvec->lrugen; +int hist =lru_hist_from_seq (min_seq[LRU_GEN_FILE ]); + +if (swappiness ==SWAPPINESS_ANON_ONLY ) +return false; + +for (tier =0 ; tier <MAX_NR_TIERS ; tier++) + refaulted +=atomic_long_read (&lrugen->refaulted[hist][LRU_GEN_FILE ][tier]); + +return refaulted > evictable; +} +static bool should_run_aging (struct lruvec *lruvec,unsigned long max_seq, -struct scan_control *sc,int swappiness) +struct scan_control *sc,int swappiness, +unsigned long evictable) {DEFINE_MIN_SEQ (lruvec);
mm/vmscan.c static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq, · line 4997
Quoted 5 lines
mm/vmscan.c +2
-0@@ -4975,6 +4993,9 @@ static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq,if (evictable_min_seq (min_seq, swappiness) +MIN_NR_GENS > max_seq)return true; +if (oldest_gen_thrashing (lruvec, min_seq, swappiness, evictable)) +return true;
[Severity: Medium]
Can this trigger repeated back-to-back aging passes when the file LRU has fewer than MAX_NR_GENS generations?
In should_run_aging(), oldest_gen_thrashing() is checked without verifying whether the file LRU has reached MAX_NR_GENS generations (for example, when there are 3 file generations at DEF_PRIORITY, or 2 file generations when min_seq[LRU_GEN_ANON] lags behind min_seq[LRU_GEN_FILE]).
When oldest_gen_thrashing() returns true while get_nr_gens(lruvec, LRU_GEN_FILE) is less than MAX_NR_GENS, try_to_shrink_lruvec() calls try_to_inc_max_seq() -> inc_max_seq():
mm/vmscan.c:inc_max_seq() {
...
for (type = 0; type < ANON_AND_FILE; type++) {
if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
continue;
if (inc_min_seq(lruvec, type, swappiness))
continue;
...
}Because get_nr_gens(lruvec, LRU_GEN_FILE) != MAX_NR_GENS, inc_max_seq() does not call inc_min_seq() for LRU_GEN_FILE. As a result, min_seq[LRU_GEN_FILE] does not advance, and reset_ctrl_pos(lruvec, LRU_GEN_FILE, true) is not called to clear or decay lrugen->refaulted[hist][LRU_GEN_FILE] (while reset_ctrl_pos(lruvec, LRU_GEN_FILE, false) only clears max_seq + 1 when NR_HIST_GENS > 1, and does nothing when NR_HIST_GENS == 1).
On the next iteration of the loop in try_to_shrink_lruvec() (such as during cgroup or proactive reclaim where !root_reclaim(sc) continues looping) or on the next reclaim invocation, should_run_aging() will see the same un-reset lrugen->refaulted[hist][LRU_GEN_FILE] > evictable and immediately run try_to_inc_max_seq() again until the file generation count reaches MAX_NR_GENS and forces inc_min_seq().
Should oldest_gen_thrashing() also check that min_seq[LRU_GEN_FILE] + MAX_NR_GENS - 1 == max_seq so that aging is only triggered when inc_max_seq() will actually advance min_seq[LRU_GEN_FILE] and reset its refault counters?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
Hi Maxim,
I can still reproduce this on mm-unstable (1b697248a755). I used a scaled-down version of your fio script: a 120 MiB vector file, a 38 MiB scan file, and a 128 MiB memcg without swap in a KVM guest (scan at about 5 seconds, vector readers for 14 seconds).
It looks like vma_has_recency() is why the hot pages aren't promoted. It returns false for VM_RAND_READ, so the MGLRU page-table walk and rmap skip the accessed bits for those mappings. Letting reclaim see those accesses again stops the thrashing. I don't think that's the right fix, though. In a single-pass random read test (warm a 64 MiB file, then read a 352 MiB file once in random order with MADV_RANDOM, in an 88 MiB memcg), that change evicted the whole hot set every time. I suspect that's the kind of case the check is meant to protect.
Your threshold stops the thrashing too, with more faults before things settle. Your patch no longer applies as-is, so I ported just the threshold to the current code. It never fired in the same single-pass test, and the hot set stayed resident. I'd fix this on the recovery side, along the lines of your patch or Kairui's refault-distance idea.
Major faults/s over the last four seconds or so, median of five runs:
Configuration Major faults/s
Stock MGLRU 27,283
MGLRU, count mapped accesses again 0 MGLRU, ported threshold 0 MGLRU, no random advice 0 Classic LRU, keep random advice 0
I saw the same difference between MGLRU and classic LRU in a small synthetic OpenSearch 3.6 test. The median post-scan p99 was 109 ms with MGLRU and 5.5 ms with classic LRU.
Tianyi Chen
Quoted 8 lines · Tianyi Chen
Hi Maxim,
I can still reproduce this on mm-unstable (
1b697248a755). I used a scaled-down version of your fio script: a 120 MiB vector file, a 38 MiB scan file, and a 128 MiB memcg without swap in a KVM guest (scan at about 5 seconds, vector readers for 14 seconds).It looks like
vma_has_recency()is why the hot pages aren't promoted.
Hi Tianyi,
Yeah I also described that here:
https://lore.kernel.org/linux-mm/[email protected]/
And in previous reply:
https://lore.kernel.org/linux-mm/CAMgjq7AEf_cJsLw4fxs7m5ntYPW9mjCOC_-w5j6ihk8F=xLRWA@mail.gmail.com/
Quoted 18 lines
It returns false for
VM_RAND_READ, so the MGLRU page-table walk and rmap skip the accessed bits for those mappings. Letting reclaim see those accesses again stops the thrashing. I don't think that's the right fix, though. In a single-pass random read test (warm a 64 MiB file, then read a 352 MiB file once in random order withMADV_RANDOM, in an 88 MiB memcg), that change evicted the whole hot set every time. I suspect that's the kind of case the check is meant to protect.Your threshold stops the thrashing too, with more faults before things settle. Your patch no longer applies as-is, so I ported just the threshold to the current code. It never fired in the same single-pass test, and the hot set stayed resident. I'd fix this on the recovery side, along the lines of your patch or Kairui's refault-distance idea.
Major faults/s over the last four seconds or so, median of five runs:
Configuration Major faults/s
Stock MGLRU 27,283
Quoted 8 lines
MGLRU, count mapped accesses again 0 MGLRU, ported threshold 0 MGLRU, no random advice 0 Classic LRU, keep random advice 0I saw the same difference between MGLRU and classic LRU in a small synthetic OpenSearch 3.6 test. The median post-scan p99 was 109 ms with MGLRU and 5.5 ms with classic LRU.
Can you share the test step on that one? I'm working on the long term goal of bring back refault distance:
https://lwn.net/Articles/945266
And the recent RFC:
https://lore.kernel.org/linux-mm/[email protected]/
And previous test with it:
https://lore.kernel.org/linux-mm/avd5bI-b9y1nKWw5@KASONG-MC4/
(Basically bring back refault distance will increase certain DB performance by 5X, fio by >60%, and it should resolve the workingset shift issue too).
MGLRU not performing well with certain over committed or workingset shift is a known problem. Unfortunately bring back refault distance is not that easy, the model doesn't simply fit and I'm trying to make more space in the shadow for both distance and gen marker so it won't break the planned readahead support.
The threshold of of refault distance re-activation is also very tricky to tune for MGLRU, I hope we can do that after the FG series, as demostrated by the RFC above (that RFC wasn't in the final shape either though, that's why it's RFC).
I'll include your case to be covered and help fix these in the upstream ASAP if you can help provide that :)
Quoted 1 line
Can you share the test step on that one?
Yes. The script I used for the rerun is below. I'd missed your discussion of MADV_RANDOM in the FG v4 cover and your note about vma_has_recency() earlier in this thread.
I ran OpenSearch 3.6.0 with k-NN 3.6.0.0 and a 384 MiB heap. The index is one Lucene HNSW segment: 80,000 vectors, 384 dimensions, m=16, ef_construction=80, mmapfs. Two HTTP connections issue top-10 queries. After 3,200 warmup and 1,600 measured queries, I pause the client and mmap-read a cold 96 MiB file once. The scanner and server share a 1 GiB cgroup with no swap. I then run 700 queries followed by another 1,000; the p99 below is for those last 1,000 only.
Save the script as repro.py. As root in a spare x86-64 VM with cgroup v2, CONFIG_LRU_GEN, Python 3.11+ and curl, run:
python3 repro.py build
python3 repro.py sweep
The first command downloads the two packages and builds the index. The second restarts OpenSearch on a cold copy for each run; it sets /sys/kernel/mm/lru_gen/enabled to 7 or 0. No global cache drop.
On the same mm-unstable commit (1b697248a755), this time with 5 GiB in the VM, median p99 over five seeds was 78.1 ms with MGLRU and 2.1 ms with classic LRU. Before the scan both had the full 117.2 MiB .vec file in cache. During the scan MGLRU dropped it to about 64 MiB, while classic LRU kept all of it. Over the last 1,000 queries the cgroup saw about 159k file refaults with MGLRU and none with classic LRU, and .vec stayed at about 98 MiB. Look for the PHASE line with phase set to late.
This is a synthetic index, not Maxim's workload. I've only run it on x86-64, with stock MGLRU on and off, not your refault-distance series.
If you point me to a branch, I can run the same test on it.
Thanks,
Tianyi
---8<---
#!/usr/bin/env python3
"""Run as root in a spare x86-64 Linux VM, not on a shared host.""" import ctypes, hashlib, http.client, json, math, mmap, os, random import re, resource, shutil, signal, socket, subprocess, sys, tarfile import time, zipfile, zlib
from concurrent.futures import ThreadPoolExecutor
from contextlib import closing
from pathlib import Path
M = 1 << 20
W = Path("/var/lib/sf-os-repro")
APP = W / "opensearch-3.6.0"
LIVE, BASE, SCAN = (W / x for x in ("live", "index-base", "scan")) CGROOT = Path("/sys/fs/cgroup")
CG = CGROOT / ("sf-search-%d" % os.getpid())
LRU = Path("/sys/kernel/mm/lru_gen/enabled")
PORT = 19280
ARCHIVE = "opensearch-min-3.6.0-linux-x64.tar.gz"
PLUGIN = "opensearch-knn-3.6.0.0.zip"
ART = "https://artifacts.opensearch.org/releases/core/opensearch/3.6.0/" MAV = "https://repo.maven.apache.org/maven2/org/opensearch/plugin/" FILES = [(ARCHIVE, ART + ARCHIVE,
"d12356c98bc544567f033d76236d4fcf"
"2a644abe705a6ba917304cf7388e67d4"),
(PLUGIN, MAV + "opensearch-knn/3.6.0.0/" + PLUGIN,
"ac392ca28a39b3bf290648a422ef30cb"
"149dda2963a9d7feb26060e932341c9a")]def emit(kind, **d):
print(kind, json.dumps(d, sort_keys=True), flush=True)
def install():
for name, url, wanted in FILES:
p = Path(name)
if not p.exists():
subprocess.run(["curl", "-fL", "--retry", "2", "-o",
name + ".part", url], check=True)
Path(name + ".part").rename(p)
with p.open("rb") as f:
got = hashlib.file_digest(f, "sha256").hexdigest() assert got == wanted, (name, got)
W.mkdir(mode=0o755) # refuse to overwrite an earlier installation with tarfile.open(ARCHIVE) as t:
t.extractall(W) # both distribution digests checked above
with zipfile.ZipFile(PLUGIN) as z:
z.extractall(APP / "plugins/opensearch-knn")
cfg = APP / "config/opensearch.yml" cfg.write_text(f"""cluster.name: sf-os-repro
node.name: sf
discovery.type: single-node
network.host: 127.0.0.1
http.port: {PORT}
transport.port: 19380
path.data: {LIVE}
path.logs: {W}/logs
knn.memory.circuit_breaker.enabled: true knn.memory.circuit_breaker.limit: 256mb
""")
for p in [LIVE, W/"logs", W/"home", APP/"logs", APP/"config"]:
p.mkdir(exist_ok=True)
os.chown(p, 65534, 65534)
for p in (APP/"config").rglob("*"):
os.chown(p,65534,65534)
with SCAN.open("xb") as f:
for _ in range(96):
f.write(os.urandom(M))
def conn():
return http.client.HTTPConnection("127.0.0.1", PORT, timeout=240)def req(c, method, url, obj=None, bulk=False):
data = obj if isinstance(obj, bytes) else (
json.dumps(obj,separators=(",",":")).encode() if obj else None)
typ = "application/x-ndjson" if bulk else "application/json"
c.request(method, url, data, {"Content-Type":typ})
r = c.getresponse()
raw = r.read()
if r.status // 100 != 2:
raise RuntimeError((url, r.status, raw[:1200]))
return raw
rng = random.Random(1919)
centers = [[rng.randrange(-40, 41) for _ in range(384)]
for _ in range(128)]
def vec(group, r):
return [a + (b >> 4) - 8 for a,b in
zip(centers[group], r.randbytes(384))]def build(c):
ix = {"knn":True, "number_of_shards":1, "number_of_replicas":0,
"refresh_interval":"-1", "compound_format":False,
"store.type":"mmapfs"}
method = {"name":"hnsw", "engine":"lucene", "space_type":"l2",
"parameters":{"m":16, "ef_construction":80}}
field = {"type":"knn_vector", "dimension":384, "method":method}
req(c, "PUT", "/sf", {"settings":{"index":ix}, "mappings":{
"_source":{"enabled":False}, "properties":{"v":field}}})
r = random.Random(9917)
for i in range(0, 80000, 400):
rows = bytearray()
for j in range(i, i+400):
rows += b'{"index":{}}\n' + json.dumps(
{"v":vec(j%128, r)}, separators=(",", ":")).encode()
rows += b"\n"
url = "/sf/_bulk?filter_path=errors,items.index.error"
result = json.loads(req(c,"POST",url,bytes(rows),True))
assert not result["errors"], str(result)[:1500]
if (i+400)%20000 == 0:
req(c,"POST","/sf/_flush?force=true")
emit("INDEX", docs=i+400)
req(c,"POST","/sf/_refresh")
req(c,"POST","/sf/_forcemerge?max_num_segments=1&flush=true")
assert json.loads(req(c,"GET","/sf/_count"))["count"] == 80000
assert len(list(LIVE.rglob("*.vec"))) == 1
def phase(seed, n):
r = random.Random(seed)
queries = []
for _ in range(n):
v = {"v":{"vector":vec(r.randrange(128),r),"k":10}}
q = {"size":10,"track_total_hits":False,"_source":False,
"query":{"knn":v}}
queries.append(json.dumps(q,separators=(",",":")).encode())
url = ("/sf/_search?request_cache=false&filter_path="
"took,hits.hits._id,error")
def worker(qs):
t, crc = [], 0
with closing(conn()) as c:
for q in qs:
start = time.perf_counter_ns()
raw = req(c,"POST",url,q)
t.append((time.perf_counter_ns()-start)/1e6)
found = json.loads(raw)["hits"]["hits"]
hits = [x["_id"] for x in found]
assert len(hits) == 10
crc = zlib.crc32(",".join(hits).encode(), crc)
return t, crc
with ThreadPoolExecutor(2) as pool:
a,b = pool.map(worker, (queries[::2], queries[1::2]))
t = sorted(a[0]+b[0])
return dict(n=n, p50_ms=t[math.ceil(.5*n)-1],
p99_ms=t[math.ceil(.99*n)-1], hits=[a[1],b[1]])def resident(p):
with p.open("rb") as f, mmap.mmap(f.fileno(), 0,
access=mmap.ACCESS_COPY) as m:
bits = (ctypes.c_ubyte * math.ceil(len(m)/mmap.PAGESIZE))() addr = ctypes.addressof(ctypes.c_char.from_buffer(m)) mc = ctypes.CDLL(None).mincore
assert not mc(ctypes.c_void_p(addr), ctypes.c_size_t(len(m)),
bits)
return sum(x&1 for x in bits)*mmap.PAGESIZE
def cold(p):
with p.open("rb") as f:
os.fsync(f.fileno())
os.posix_fadvise(f.fileno(), 0, 0, os.POSIX_FADV_DONTNEED)
def advice():
seen = set()
for pid in (CG/"cgroup.procs").read_text().split():
try:
lines = Path("/proc",pid,"smaps").read_text().splitlines()
except FileNotFoundError:
continue
ext = ""
for s in lines:
if re.match(r"^[0-9a-f]+-[0-9a-f]+ ", s):
ext = Path(s.split()[-1]).suffix
if ext in (".vec",".vex") and s.startswith("VmFlags:"):
assert "rr" in s.split(), s
seen.add(ext)
assert seen == {".vec",".vex"}
emit("SMAPS", rr=sorted(seen))def test(seed, arm, files):
def snap():
stat = dict(x.split() for x in (CG/"memory.stat")
.read_text().splitlines())
return int(stat["workingset_refault_file"])
def report(name, old, **extra):
rss = {x.suffix:resident(x) for x in files}
emit("PHASE", phase=name, seed=seed, arm=arm, resident_B=rss,
mem_B=int((CG/"memory.current").read_text()),
refault_pages=snap()-old, **extra)
for i,(name,n) in enumerate((("warm",3200),("pre",1600),
("early",700),("late",1000))):
if name == "early":
assert resident(SCAN) == 0
old = snap()
pid = os.fork()
if not pid:
try:
(CG/"cgroup.procs").write_text("0")
with SCAN.open("rb") as f, mmap.mmap(f.fileno(),0,
access=mmap.ACCESS_READ) as m:
m.madvise(mmap.MADV_NORMAL)
sum(m[j] for j in range(0,len(m),4096))
except BaseException:
os._exit(1)
os._exit(0)
assert os.waitpid(pid,0)[1] == 0
report("scan", old, scan_B=resident(SCAN))
old = snap()
report(name, old, **phase(seed+i,n))
if name == "warm":
advice()def trial(arm=None, seed=0):
oldmask = LRU.read_text().strip()
files = []
if arm is not None:
shutil.copytree(BASE, LIVE)
for p in [LIVE,*LIVE.rglob("*")]:
os.chown(p,65534,65534)
if p.is_file():
cold(p)
for p in APP.rglob("*"):
if p.is_file() and not p.is_symlink():
cold(p)
cold(SCAN)
files = [p for p in LIVE.rglob("*") if p.suffix in (
".vec",".vex")]
assert sorted(p.suffix for p in files) == [".vec",".vex"]
assert all(resident(p)==0 for p in [*files,SCAN])
with socket.socket() as s:
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
s.bind(("127.0.0.1",PORT))
(CGROOT/"cgroup.subtree_control").write_text("+memory")
CG.mkdir()
proc = None
def enter():
(CG/"cgroup.procs").write_text("0")
os.setgroups([])
os.setgid(65534)
os.setuid(65534)
try:
if arm is not None:
LRU.write_text(str(arm))
assert int(LRU.read_text(),0) == arm
(CG/"memory.max").write_text(str(1024*M))
(CG/"memory.swap.max").write_text("0")
emit("START", seed=seed, arm=arm, kernel=os.uname().release,
vec_bytes={p.suffix:p.stat().st_size for p in files})
opts = ("-Xms384m -Xmx384m -XX:ActiveProcessorCount=4 "
"--enable-native-access=ALL-UNNAMED")
with (W/f"server-{arm}-{seed}.log").open("wb") as log:
proc = subprocess.Popen([APP/"bin/opensearch"], cwd=APP,
stdout=log, stderr=log, preexec_fn=enter, env={
**os.environ,"HOME":str(W/"home"),
"OPENSEARCH_JAVA_HOME":str(APP/"jdk"),
"OPENSEARCH_JAVA_OPTS":opts},start_new_session=True)
with closing(conn()) as c:
for _ in range(240):
if proc.poll() is not None:
raise RuntimeError(f"see {log.name}")
try:
info = json.loads(req(c,"GET","/"))
break
except (OSError,http.client.HTTPException):
c.close()
time.sleep(.5)
else:
raise TimeoutError("OpenSearch startup")
assert info["cluster_name"] == "sf-os-repro"
assert info["version"]["number"] == "3.6.0"
assert info["version"]["lucene_version"] == "10.4.0"
h = "/_cluster/health?wait_for_status=yellow"
assert not json.loads(req(c,"GET",h))["timed_out"]
if arm is None:
build(c)
else:
test(seed,arm,files)
events = (CG/"memory.events").read_text().splitlines()
assert "oom_kill 0" in events, events
finally:
if proc and proc.poll() is None:
os.killpg(proc.pid,signal.SIGTERM)
try:
proc.wait(timeout=90)
except subprocess.TimeoutExpired:
os.killpg(proc.pid,signal.SIGKILL)
proc.wait()
LRU.write_text(str(int(oldmask,0)))
CG.rmdir()
if arm is None:
LIVE.rename(BASE)
else:
shutil.rmtree(LIVE)
emit("DONE",arm=arm,seed=seed)if __name__ == "__main__":
if not __debug__ or os.getuid() or os.uname().machine!="x86_64":
sys.exit("use root, x86-64 Linux, and Python without -O")
resource.setrlimit(resource.RLIMIT_NOFILE,(65536,65536))
args = sys.argv[1:]
if args == ["build"]:
install()
trial()
elif args == ["sweep"]:
for seed in range(8091,8096):
arms = [0,7]
random.Random(seed).shuffle(arms)
for arm in arms:
trial(arm,seed)
elif len(args)==3 and args[0]=="run" and args[1] in ("0","7"):
trial(int(args[1]),int(args[2]))
else:
sys.exit("usage: repro.py build | sweep | run {0,7} SEED")Hi Tianyi, Kairui,
Sorry for the late reply. There was a lot of new information for me to digest.
I've checked the reproducer you provided. It tests a slightly different scenario from the one I mentioned in my first email. However, I managed to adapt it [1] to my case and tested everything with the same setup (x86-64 VM), and I also reproduced your results.
The key difference [1] is that I added two new knobs:
- SCAN_PASSES (default 1, your value), how many times each scan page is touched
- SCAN_MB (default 96, your value), the cold scan size in MiB
This is important because 300 MiB scan forces reclaim to reach the pages during the first pass, which clears their accessed bits and evicts some of them. The second pass then gives the scan pages a second visible access. The reproducer from my first email also reads the cold data twice (--loops=2).
So the idea is to get the cold data promoted to newer generations and watch whether the workload recovers while the oldest generation is thrashing.
With a 300 MiB scan and 2 passes, neither MGLRU nor MGLRU-FG5 can recover. FG5 handles the 96 MiB scans and the 300 MiB single pass scan.
The Patch
---------
Kairui,
Quoted 4 lines · Kairui Song
This code snip:
+ /* Set refault as active. */
+ if (distance < total / 2) {
+folio_set_active(folio);
[...]
Quoted 3 lines
That way, even a random folio will be put to the head directly instead of keep thrasing on tail. And placing on head or newer gen will trigger aging.
As I understand it, the refault distance series will break this loop on tail. However, will the loop survive when the hot random set is much bigger than half of memory? E.g. when its refault distances exceed total / 2 and refaults land in the oldest generation again? Should we in this case use the aging logic from this patch as a fallback?
Anyway I'd be happy to test the refault distance implementation as part of this work when it's ready.
I also rebased the patch onto mm-new (25fee5b1762b) [2] and on top of the MGLRU-FG5 branch [3]. The patch applies unchanged to both.
Please, let me know if I need to send v2 of the patch to this thread.
Setup
-----
The same .config, and a fresh 4 vCPU x86-64 KVM guest per kernel. OpenSearch and a cold mmap scan (96/300 MiB, one/two passes) share a 1 GiB memcg with no swap. Median of 5 seeds, lru_gen enabled=7 vs 0.
mmbase 7.4.0-rc1-mmbase+, mm-new (25fee5b1762b) fg5 7.4.0-rc1-fg5+, 25fee5b1762b with 17 MGLRU-FG5 patches [4] age2 7.4.0-rc1-age2+, mmbase with the patch on top fg5age 7.4.0-rc1-fg5age+, fg5 with the patch on top
Results
-------
First, the good news. I can confirm that FG5 keeps .vec in memory with a 96 MiB scan and MGLRU doesn't. With passes=2 it also looks fine.
My guess is that at 96 MiB reclaim never reaches the scan pages between the two passes, so their accessed bits stay set and the second pass is not seen as a new access? I haven't confirmed this.
96 MiB scan:
kernel passes LRU p50 p99 refaults .vec scan .vec late fg5 1 MGLRU 1.1 2.6 2 117.2 117.2 fg5 1 classic 1.1 2.4 7 117.2 117.2 fg5 2 MGLRU 1.0 2.1 1 117.2 117.2 fg5 2 classic 1.0 2.0 0 117.2 117.2 mmbase 1 MGLRU 15.4 69.0 510691 75.3 102.2 mmbase 1 classic 1.0 2.2 3 117.2 117.2 mmbase 2 MGLRU 16.6 73.4 558370 70.1 100.0 mmbase 2 classic 1.1 2.6 3 117.2 117.2
With a 300 MiB scan, .vec is fully evicted during the scan on every kernel, so these runs show whether it comes back. With passes=2, MGLRU-FG5 is NOT able to recover, and this is where the refault distance implementation should help?
300 MiB scan:
kernel passes LRU p50 p99 refaults .vec scan .vec late scan late fg5 1 MGLRU 1.0 2.2 413 0.0 117.2 115.8 fg5 1 classic 1.1 2.4 409 0.0 117.2 104.5 fg5 2 MGLRU 156.1 248.5 12548335 0.0 4.7 292.0 fg5 2 classic 1.1 2.4 686 0.0 117.2 157.5 mmbase 1 MGLRU 146.3 227.4 11247224 0.0 15.0 293.5 mmbase 1 classic 1.0 2.3 409 0.0 117.2 102.0 mmbase 2 MGLRU 150.2 248.9 11643192 0.0 11.3 295.0 mmbase 2 classic 1.1 2.5 547 0.0 117.2 157.2
The patch runs aging when the oldest generation is thrashing, so min_seq moves again, and both MGLRU and MGLRU-FG5 recover.
300 MiB scan, with the patch:
kernel passes LRU p50 p99 refaults .vec scan .vec late scan late age 1 MGLRU 1.1 2.4 571 0.0 117.2 152.8 age 1 classic 1.1 2.3 410 0.0 117.2 106.5 age 2 MGLRU 1.1 2.3 565 0.0 117.2 150.8 age 2 classic 1.1 2.5 866 0.0 117.2 153.8 fg5age 1 MGLRU 1.1 2.3 410 0.0 117.2 112.1 fg5age 1 classic 1.1 2.3 407 0.0 117.2 102.2 fg5age 2 MGLRU 1.1 2.3 430 0.0 117.2 143.0 fg5age 2 classic 1.1 2.6 955 0.0 117.2 154.5
The full results are in the gist [5].
Links
-----
[1] https://gist.github.com/Mmuzaf/263806a5bfae85e75c3331467f85353e/030e6f11096e1980303aa153da0a35b220b4eecc
[2] https://github.com/Mmuzaf/linux/commit/cbd48001580bf1ad8a8767b1afd8e4ad969b3432
[3] https://github.com/Mmuzaf/linux/commit/1e889df5c555e99d437c608e25c22ccb5286ff8f
[4] https://lore.kernel.org/linux-mm/[email protected]/
[5] https://gist.github.com/Mmuzaf/e87acbefc15acc2cac40c2181de984dd
Thanks,
Maxim Muzafarov