#!/usr/bin/env bash # A/B of the memfd residency guard under pressure that is real but fenced into one cgroup (v2, or the v1 memory controller on a # hybrid host such as WSL2). Needs root for the cgroup and the memlock limit; run it in WSL2 or on a test box, never on a shared server. # # sudo scripts/memory/swap_ab.sh [--memfd-mib 6144] [--hog-mib 5120] [--limit-mib 9216] [--secs 60] [--reader FILE] # # Arms: A lock off, heal off | B lock off, heal on | C lock require (memlock unlimited). memory.max is below memfd + hog, so the kernel # MUST push 2 GiB or more out of the cgroup: it chooses between the memfd and the hog (and the reader's clean cache first). set -euo pipefail MEMFD=6144; HOG=5120; LIMIT=9216; SECS=60; READER="" while [ $# -gt 0 ]; do case $1 in --memfd-mib) MEMFD=$2;; --hog-mib) HOG=$2;; --limit-mib) LIMIT=$2;; --secs) SECS=$2;; --reader) READER=$2;; esac; shift 2; done BIN=${SWAP_AB_BIN:-target/release/examples/swap_ab} [ "$(id -u)" = 0 ] || { echo "run as root (cgroup + memlock)"; exit 1; } if grep -qw memory /sys/fs/cgroup/cgroup.controllers 2>/dev/null; then V=2; CG=/sys/fs/cgroup/leleka-swap-ab echo +memory > /sys/fs/cgroup/cgroup.subtree_control 2>/dev/null || true elif [ -d /sys/fs/cgroup/memory ]; then V=1; CG=/sys/fs/cgroup/memory/leleka-swap-ab else echo "no memory cgroup controller (v2 or v1) available"; exit 1 fi echo "cgroup v$V at $CG" run_arm() { local name=$1 lock=$2 heal=$3 rmdir $CG 2>/dev/null || true mkdir $CG if [ $V = 2 ]; then echo $((LIMIT * 1024 * 1024)) > $CG/memory.max echo max > $CG/memory.high echo 8G > $CG/memory.swap.max 2>/dev/null || true else echo $((LIMIT * 1024 * 1024)) > $CG/memory.limit_in_bytes echo $(((LIMIT + 8192) * 1024 * 1024)) > $CG/memory.memsw.limit_in_bytes 2>/dev/null || true fi echo "=== arm $name: lock=$lock heal=$heal memfd=${MEMFD}MiB hog=${HOG}MiB limit=${LIMIT}MiB" ( echo $BASHPID > $CG/cgroup.procs ulimit -l unlimited LELEKA_MEMORY_SOFT_FLOOR_MIB=64 LELEKA_MEMORY_HARD_FLOOR_MIB=32 LELEKA_MEMORY_RESERVE_MIB=16 LELEKA_MEMORY_HYSTERESIS_MIB=16 \ exec $BIN --memfd-mib $MEMFD --hog-mib $HOG --hog-release ${HOG_RELEASE:-0} --secs $SECS --lock $lock --heal $heal ${READER:+--reader $READER} ) | grep -E "^AB" | awk 'NR<=3 || /AB-RESULT/ || NR%10==0' if [ $V = 2 ]; then echo "cgroup events: $(tr '\n' ' ' < $CG/memory.events) swap.current: $(cat $CG/memory.swap.current 2>/dev/null)" else echo "cgroup: max_usage=$(( $(cat $CG/memory.max_usage_in_bytes) >> 20 )) MiB failcnt=$(cat $CG/memory.failcnt) $(tr '\n' ' ' < $CG/memory.oom_control)" fi rmdir $CG 2>/dev/null || true } ARMS=" ${ARMS:-A B C} " [[ $ARMS == *" A "* ]] && run_arm A-no-lock-no-heal off 0 [[ $ARMS == *" B "* ]] && run_arm B-heal off 1 [[ $ARMS == *" C "* ]] && run_arm C-mlock require 0 true