Re: [PATCH v2 4/5] mm/mglru: avoid redundant rotations of young memcgs

From: Max Kellermann

Date: Mon Nov 23 2026 - 08:20:09 EST


On Wed, Nov 4, 2026 at 10:08 AM Barry Song <baohua@xxxxxxxxxx> wrote:
>
> On Wed, Nov 4, 2026 at 4:27 PM Max Kellermann <max.kellermann@xxxxxxxxx> wrote:
> >
> > On Wed, Nov 4, 2026 at 6:18 AM Barry Song <baohua@xxxxxxxxxx> wrote:
> > > > In my micro benchmark, this increases the request rate by 36% and
> > > > reduces the average duration of each write request by 27%.
> > >
> > > Could you share your microbenchmark somewhere (or post it here
> > > if it's not too lengthy), perhaps on GitHub, so others can
> > > reproduce it? You could then refer to it in your changelog.
> >
> > Will do. A note of warning: it's ugly LLM slop, and if I had written
> > it manually, probably 99% of it could be removed because it's
> > pointless garbage. The LLM wrote it for me before I had any clue
> > where the problem could be. It helped me find the problem, but
> > uploading this garbage triggers a bit of shame in me ;-)

Here's the script; to avoid the pain of reading it, I let the LLM
remove lots of features that turned out to be unnecessary for
reproducing the problem. Prepare with:

echo 3 >/sys/kernel/mm/lru_gen/enabled; ./lrugen-repro.py prepare --live 1500

Then run:

./lrugen-repro.py run --workers 8 --duration 60

--
Max Kellermann
Principal Architect
Hosting Technology

cm4all | Im Mediapark 6a | 50670 Köln | Germany
General information about the company can be found here:
https://www.cm4all.com/impressum
A member of the IONOS Group
#!/usr/bin/env python3
"""Exercise MGLRU memcg rotation on a dedicated cgroup-v2 test host.

Run as root:
./lrugen-repro.py prepare --live 1500
./lrugen-repro.py run --workers 8 --duration 60
./lrugen-repro.py cleanup

Workers reclaim from the HOST ROOT, affecting the entire machine. Duration
requests a stop; an in-flight kernel reclaim call must still finish.
"""

import argparse
import errno
import multiprocessing as mp
import os
from pathlib import Path
import signal
import sys
import time


CGROOT = Path('/sys/fs/cgroup')
CGROUP = CGROOT / 'lrugen-repro'


def check_host():
if os.geteuid() != 0:
raise RuntimeError('Run as root on the test server.')
if not (CGROOT / 'cgroup.controllers').exists():
raise RuntimeError('Expected cgroup v2 at /sys/fs/cgroup.')
if (CGROOT / 'memory.current').exists():
raise RuntimeError('Run in the host cgroup namespace, not a subtree.')
if not (CGROOT / 'memory.reclaim').exists():
raise RuntimeError('The host root has no memory.reclaim interface.')
if int(Path('/sys/kernel/mm/lru_gen/enabled').read_text(), 0) != 3:
raise RuntimeError('This test expects MGLRU enabled with 0x3.')
swaps = Path('/proc/swaps')
if swaps.exists() and len(swaps.read_text().splitlines()) > 1:
raise RuntimeError('This test expects no active swap.')


def prepare(count):
check_host()
CGROUP.mkdir() # Refuse to reuse an existing population.
created = []
try:
(CGROOT / 'cgroup.subtree_control').write_text('+memory\n')
(CGROUP / 'cgroup.subtree_control').write_text('+memory\n')
for i in range(count):
group = CGROUP / f'live-{i:06d}'
group.mkdir()
created.append(group)
except BaseException:
for group in reversed(created):
group.rmdir()
CGROUP.rmdir()
raise
print(f'Created {count} empty cgroups in {CGROUP}')


def cleanup():
if os.geteuid() != 0:
raise RuntimeError('Cleanup requires root.')
groups = [p for p in CGROUP.iterdir() if p.is_dir()]
if any(not p.name.startswith('live-') or not p.name[5:].isdigit()
for p in groups):
raise RuntimeError('Unexpected child cgroup; refusing cleanup.')
for group in groups:
group.rmdir() # Fails if populated or containing child cgroups.
CGROUP.rmdir()
print('Removed test cgroups.')


def reclaim_worker(request, start, stop, stats):
signal.signal(signal.SIGINT, signal.SIG_IGN)
signal.signal(signal.SIGTERM, signal.SIG_IGN)
start.wait()
while not stop.is_set():
began = time.monotonic_ns()
try:
fd = os.open(CGROOT / 'memory.reclaim', os.O_WRONLY)
try:
if os.write(fd, request) != len(request):
raise OSError('Short memory.reclaim write')
finally:
os.close(fd)
stats[1] += 1
except OSError as exc:
if exc.errno == errno.EAGAIN:
stats[2] += 1
else:
stats[3] += 1
print(f'Worker {os.getpid()}: {exc}', file=sys.stderr, flush=True)
stop.set()
elapsed = time.monotonic_ns() - began
stats[0] += 1
stats[4] += elapsed
stats[5] = max(stats[5], elapsed)


def run(args):
check_host()
if not CGROUP.is_dir():
raise RuntimeError('Run prepare first.')
if 'memory' not in (CGROUP / 'cgroup.subtree_control').read_text().split():
raise RuntimeError('The test cgroup memory controller is disabled.')
count = sum(p.is_dir() for p in CGROUP.iterdir())
if not count:
raise RuntimeError('The test cgroup population is empty.')
ctx = mp.get_context('fork')
start, stop = ctx.Event(), ctx.Event()
# One writer per row: completed, success, EAGAIN, errors, total_ns, max_ns.
stats = [ctx.Array('Q', 6, lock=False) for _ in range(args.workers)]
request = f'{args.reclaim_mib}M swappiness=0\n'.encode()
children = []
interrupted = False

def request_stop(signum, frame):
# Setting an Event here could deadlock if the signal interrupted its lock.
nonlocal interrupted
interrupted = True

old_handlers = {sig: signal.signal(sig, request_stop)
for sig in (signal.SIGINT, signal.SIGTERM)}
try:
for row in stats:
child = ctx.Process(target=reclaim_worker, args=(request, start, stop, row))
child.start()
children.append(child)
print(f'Running {args.workers} workers with {count} cgroups; '
f'{args.reclaim_mib} MiB per request', flush=True)
began = time.monotonic()
next_print = began + 5
stop_at = None
warned = False
start.set()
while any(child.is_alive() for child in children):
now = time.monotonic()
failed = any(child.exitcode not in (None, 0) for child in children)
if interrupted or failed or now - began >= args.duration:
stop.set()
if now >= next_print:
print(f'{now - began:.1f}s: {sum(s[0] for s in stats)} '
'completed requests', flush=True)
next_print = now + 5
if stop.is_set() and stop_at is None:
stop_at = now
if stop_at is not None and now - stop_at > 5 and not warned:
print('Stop requested; waiting for in-flight reclaim calls.', flush=True)
warned = True
time.sleep(0.2)
elapsed = time.monotonic() - began
finally:
stop.set()
start.set()
for child in children:
child.join()
for sig, handler in old_handlers.items():
signal.signal(sig, handler)

completed, success, eagain, errors, total_ns = (
sum(row[i] for row in stats) for i in range(5))
max_ns = max(row[5] for row in stats)
print(f'Completed: {completed} (success: {success}, EAGAIN: {eagain}, errors: {errors})')
print(f'Elapsed: {elapsed:.2f} s; requests/s: {completed / elapsed:.2f}')
if completed:
print(f'Latency: mean {total_ns / completed / 1e6:.2f} ms; '
f'max {max_ns / 1e6:.2f} ms')
if errors or any(child.exitcode != 0 for child in children):
raise RuntimeError('A reclaim worker failed.')
if interrupted:
return 130
return 0


def positive(value):
n = int(value)
if n <= 0:
raise argparse.ArgumentTypeError('Must be positive.')
return n


def main():
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
commands = parser.add_subparsers(dest='command', required=True)
p = commands.add_parser('prepare', help='create empty live cgroups')
p.add_argument('--live', type=positive, default=1000)
p = commands.add_parser('run', help='issue concurrent host-root reclaim requests')
p.add_argument('--workers', type=positive, default=8)
p.add_argument('--duration', type=positive, default=60, help='seconds until stop request')
p.add_argument('--reclaim-mib', type=positive, default=1024)
commands.add_parser('cleanup', help='remove test cgroups')
args = parser.parse_args()
if args.command == 'prepare':
prepare(args.live)
elif args.command == 'run':
return run(args)
else:
cleanup()
return 0


if __name__ == '__main__':
try:
sys.exit(main())
except KeyboardInterrupt:
sys.exit(130)
except (OSError, RuntimeError, ValueError) as exc:
print(f'Error: {exc}', file=sys.stderr)
sys.exit(1)