diff --git a/docs/README.md b/docs/README.md index 6856349124..7a563f57b3 100644 --- a/docs/README.md +++ b/docs/README.md @@ -13,6 +13,7 @@ method, scope and caveats. No game data is included. | [boot_leads.md](boot_leads.md) | Open leads that may move the retail boot further (TLS at module index 0, feature level at device creation, command-list replay, descriptor words, shader corpus count, frame pacing), each with where it lands, how to implement it and how to test it. Hypotheses, not measurements. | | [rpf.md](rpf.md) | RPF9 archive layout, the carve tools and the unreadable encrypted TOC. | | [linux.md](linux.md) | Linux in one page: what runs natively and what runs under Wine or Proton, the Ubuntu packages, `Build.sh`, the runtime cross-build, and why there is no native Linux `gta6rt`. | +| [linux_proton.md](linux_proton.md) | The boot scripts in `scripts/linux-boot`: the cross-build configure, booting the loader under Wine or Proton with the network off, and a `systemd --user` unit that samples memory and writes a digest of how the boot ended. | | [testing.md](testing.md) | Running the GPU tests on your own GPU: setup per OS, wave64 emulation, running without a GPU on Mesa llvmpipe, and known problems. | | [gpu_test_results.md](gpu_test_results.md) | Published GPU test results by hardware, driver and commit, with pass, skip and failure counts. | | [modding.md](modding.md) | The mod format: `mods//mod.json`, checked and loaded in name order by `gta6rt`; a swap takes effect once the game's archetype lookup is hooked (needs the executable, RT-5). A mod names game models and holds no game data. | diff --git a/docs/linux_proton.md b/docs/linux_proton.md index f98aacf149..0aa399a1e1 100644 --- a/docs/linux_proton.md +++ b/docs/linux_proton.md @@ -25,40 +25,82 @@ Windows A reaches every stage three to five times faster than the Linux machine ~180 s, story load from ~110 s against ~240-300 s), so it is the better machine for iterating on the world phase; the Linux machine is the one that shows what 16 GB of RAM allows. -## Building on Linux +## Building from a checkout -The runtime is a Windows executable. On Linux it is cross-built with clang-cl against an [xwin](https://github.com/Jake-Shadle/xwin) -copy of the Windows SDK: +The runtime is a Windows program. On Linux it is cross-built with clang-cl against an +[xwin](https://github.com/Jake-Shadle/xwin) copy of the Windows SDK ([linux.md](linux.md) has the packages and the +one-time `xwin` command): ```sh -scripts/linux-boot/configure-worktree.sh # XWIN_DIR=, SDL3_SRC= for an offline configure +scripts/linux-boot/configure-worktree.sh # XWIN_DIR=; SDL3_SRC= configures offline cmake --build /runtime/build/boot --target gta6rt -j6 ``` -`gta6rt_tls_host.dll` is built with the `gta6rt` target and must stay next to the executable. Unit tests are Windows -executables too and run under Wine (`scripts/run_wine_tests.py`, or directly with the same `wine` binary and a -prefix of their own: sharing the game's prefix with tests breaks its window). - -## Booting on Linux - -`scripts/linux-boot/boot.sh` is the plain launcher and `run-boot.sh` wraps it as a `systemd --user` unit with a -memory sampler, a GPU lock, a build lock (no compile while the game runs) and a digest after the boot. They assume -the layout the comments at their top describe (`/opt/leonida` for traces, overlay and caches; the package under -`/opt/gta6`); adjust the paths at the top to yours. What matters: - -- **Wine:** Proton Experimental's `files/bin/wine` with its own prefix (`WINEPREFIX`), `WINEDLLOVERRIDES="mscoree,mshtml="`. -- **No network:** the title runs inside `unshare -rn` (new user and network namespace). Nothing is online. -- **Backend:** `LEONIDA_D3D12=vulkan`, `LEONIDA_SHADERS=`. -- **NVIDIA shader cache:** `__GL_SHADER_DISK_CACHE_SIZE` raised (the library is ~19 GB of SPIR-V) and - `__GL_SHADER_DISK_CACHE_SKIP_CLEANUP=1`. -- **Input:** a pad through GameInput/SDL3, or the keyboard pad (`LEONIDA_KEYBOARD_PAD=always`), or a script: - `LEONIDA_INPUT_SCRIPT=a@210,a@240` presses A at those seconds (any length since this branch; it was cut at 63 - characters before). -- **Window:** frames are presented in the title's own window; `LEONIDA_PRESENT_WINDOW=own|hidden` chooses otherwise. - -Three setup mistakes each give a blank or empty picture without an error: the executable's embedded shaders missing -from the library (`exe/index.json`), a build without SDL3 (no pad), and a BCPack predictor file that was never -generated (`tools/build_dstorage_history.py`; without it the loading art and most BC7 textures stay empty). +`configure-worktree.sh` configures a Ninja Release build in `/runtime/build/boot` with +`runtime/cmake/clang-cl-xwin.cmake`. `gta6rt_tls_host.dll` is built with the `gta6rt` target and must stay next to the +executable: without it the title gets no module TLS index and exits at once, so `run-boot.sh` refuses to start. + +## Booting + +`boot.sh` is the plain launcher. `run-boot.sh` wraps it as a `systemd --user` unit. + +```sh +export LEONIDA_GAME_DIR= # the folder with game_scarlett_master.exe +export LEONIDA_SHADERS=/shaders/spirv # the translated library make_game.py built +scripts/linux-boot/boot.sh dry-run # imports only +scripts/linux-boot/boot.sh init # TLS callbacks and DLL initialization +scripts/linux-boot/boot.sh run 150 # start the title, stop it after 150 s +scripts/linux-boot/run-boot.sh first runtime/build/boot/gta6rt.exe 150 LEONIDA_ARENA_MB=2048 +``` + +| Variable | Default | Meaning | +|---|---|---| +| `LEONIDA_GAME_DIR` | none, required | The folder of your copy of the package. It is read in place. | +| `LEONIDA_SHADERS` | none, required for `run` | The translated shader library. | +| `LEONIDA_BOOT_DIR` | `~/.local/share/leonida-boot` | Where traces, the overlay (the title's writes), the driver's shader cache, the locks and the runs go. | +| `GTA6RT` | `runtime/build/boot/gta6rt.exe` of the checkout | The loader `boot.sh` starts. `run-boot.sh` takes it as its second argument. | +| `WINE` | Proton Experimental's `files/bin/wine` when Steam has it, else `wine` | The Wine to use. **One Wine per prefix, always.** A Proton prefix links to files inside the Proton installation, and another Wine version that starts in it updates the prefix by writing through those links. On the machine below that overwrote about 1,200 of Proton's own files, and every Proton start failed afterwards; the tool's files then have to be verified or reinstalled through Steam. | +| `WINEPREFIX` | `~/.local/share/leonida-boot-prefix` | A prefix for boots alone. | +| `LEONIDA_BOOT_MIN_FREE_MB` | `6500` | `run-boot.sh` waits up to ten minutes for this much memory before it boots. | + +What the scripts set, and why: + +- **No network.** The loader runs inside `unshare -rn`, a new user and network namespace that needs no root. The + title has no network at all, which is the project's rule (nothing online) enforced by the kernel. +- **Wine.** `WINEDLLOVERRIDES="mscoree,mshtml=;winedbg.exe=d"`: a new prefix does not ask to install Mono and Gecko, + and a process that crashes ends instead of starting `winedbg`. With the Wine installation broken as the table + above describes, `winedbg` started for a crashing Wine service crashed as well and was started again for itself, + about ten thousand times, until memory ran out; the loader's own trace already records the title's exceptions. + Keep the + boot prefix apart from the one unit tests use. On the machine below, a test's `wineserver` that was still alive + (started without a display) was joined by the next boot, which then had no window. +- **Backend.** `LEONIDA_D3D12=vulkan` and `LEONIDA_SHADERS` for `run`. +- **NVIDIA's shader disk cache** is moved under `LEONIDA_BOOT_DIR` and its size limit raised + (`__GL_SHADER_DISK_CACHE_SIZE`, 20 GiB unless you set it), with `__GL_SHADER_DISK_CACHE_SKIP_CLEANUP=1`, so that + the pipelines one boot compiled are still there for the next. +- **Traces.** `--trace` always and `--trace-d3d12` for `run`; `tools/boot_trace.py` summarises them next to the logs. + +Other switches pass through: any `KEY=VALUE` after the seconds of `run-boot.sh` is set in the unit, for example +`LEONIDA_KEYBOARD_PAD=always` ([gameinput.md](gameinput.md)) or `LEONIDA_SKIP_INT3=1` ([boot.md](boot.md)). + +## What `run-boot.sh` adds + +- The boot runs outside your shell's process tree, with `OOMScoreAdjust=900`: when memory runs out the kernel takes + the game, not the session that started it. +- It waits for memory headroom and for swap below 70 %, then holds a GPU lock (one boot at a time) and a build lock + for the whole boot. A build that takes the same lock never competes with the game for memory: + `flock "$LEONIDA_BOOT_DIR/.build.lock" cmake --build ...`. +- RAM, swap, the unit's own memory and VRAM (`nvidia-smi`, when present) are sampled every 2 s into `resources.tsv`. +- A frame capture is on (`LEONIDA_CAPTURE`, every 4800th presented frame) and so is Wine's error channel. +- A second small unit waits for the boot to end, also when `systemd-oomd` or the kernel killed it, and writes + `digest.txt`: the verdict (`OK`, `EXITED WITH ERROR`, `KILLED BY OOM`, `KILLED BY SIGNAL`), how long it queued and + ran, counts from the D3D12 trace, captured frames and how many are not black, memory peaks, kernel events (OOM, + NVIDIA Xid, segfaults), every distinct error line with its count, and the last lines of the trace. One line per + boot is appended to `boots.tsv`. + +Everything is in `$LEONIDA_BOOT_DIR/runs//` and `$LEONIDA_BOOT_DIR/traces/`. `run-boot.sh` prints the digest +and exits 0 only for `OK`. **Traces, logs and digests can quote the title's own text. Keep them on the machine that +produced them**: no trace, log or capture goes into a commit, an issue or a pull request. ## What a healthy boot looks like (Linux machine) diff --git a/scripts/linux-boot/boot-digest.sh b/scripts/linux-boot/boot-digest.sh index dd2289e30a..71b4406172 100755 --- a/scripts/linux-boot/boot-digest.sh +++ b/scripts/linux-boot/boot-digest.sh @@ -1,53 +1,55 @@ #!/bin/bash -# ExecStopPost of a leonida-boot-* unit: runs after the boot ends however it ended (exit, crash, oomd kill, timeout). -# Writes /opt/leonida/work//boot-.digest.txt and appends a line to /opt/leonida/work/boots.tsv. -# Local only: digests quote trace lines, so they never go into commits or PRs. +# usage: boot-digest.sh (run-boot.sh starts it when the leonida-boot- unit has ended) +# Runs after the boot however it ended (exit, crash, oomd kill, time limit). Writes +# $LEONIDA_BOOT_DIR/runs//digest.txt and appends one line to $LEONIDA_BOOT_DIR/boots.tsv. +# Local only: a digest quotes trace lines, so it never goes into a commit, an issue or a pull request. set -u -AGENT=$1; N=$2; WORK=/opt/leonida/work/$AGENT; LOG=$WORK/boot-$N.log; RES=$WORK/boot-$N.resources.tsv -META=$WORK/boot-$N.meta; OUT=$WORK/boot-$N.digest.txt; LEDGER=/opt/leonida/work/boots.tsv +NAME=${1:?name}; BASE=${LEONIDA_BOOT_DIR:-$HOME/.local/share/leonida-boot}; RUN=$BASE/runs/$NAME +LOG=$RUN/boot.log; RES=$RUN/resources.tsv; META=$RUN/meta; OUT=$RUN/digest.txt; LEDGER=$BASE/boots.tsv START=$(sed -n 's/^start_epoch=//p' "$META" 2>/dev/null); BOOT=$(sed -n 's/^boot_epoch=//p' "$META" 2>/dev/null) START=${START:-$(date +%s)}; BOOT=${BOOT:-$START}; END=$(date +%s) -RESULT=${SERVICE_RESULT:-?}; ECODE=${EXIT_CODE:-?}; ESTAT=${EXIT_STATUS:-?} +RESULT=${SERVICE_RESULT:-?} D3D=$(grep -o 'd3d12=[^ ]*' "$LOG" 2>/dev/null | tail -1 | cut -d= -f2) STDOUT=${D3D/d3d12-run-/stdout-run-} -CAP=/opt/leonida/capture/$AGENT-$N +CAP=$RUN/capture verdict=OK # systemd-oomd can kill the unit's processes without the unit ending in "oom-kill" (boot.sh then exits on its own). -if journalctl --user -u "leonida-boot-$AGENT-$N" --since "@$START" -q --no-pager 2>/dev/null | grep -q 'systemd-oomd killed'; then RESULT=oom-kill; fi +if journalctl --user -u "leonida-boot-$NAME" --since "@$START" -q --no-pager 2>/dev/null | grep -q 'systemd-oomd killed'; then RESULT=oom-kill; fi +# The loader's own exit code, as boot-inner.sh logged it (124 is the time limit and was turned into 0 there). +RC=$(sed -n 's/^\[run-boot\] .* boot\.sh exit \([0-9]*\)$/\1/p' "$LOG" 2>/dev/null | tail -1) +[ "$RESULT" = success ] && [ -n "$RC" ] && [ "$RC" != 0 ] && [ "$RC" != 124 ] && RESULT=exit-code case "$RESULT" in oom-kill) verdict="KILLED BY OOM (systemd-oomd or kernel): memory, not a crash" ;; timeout) verdict="TIMEOUT" ;; - exit-code) verdict="EXITED WITH ERROR (code $ECODE status $ESTAT)" ;; - signal|core-dump) verdict="KILLED BY SIGNAL ($ESTAT)" ;; + exit-code) verdict="EXITED WITH ERROR (boot.sh exit ${RC:-?})" ;; + signal|core-dump) verdict="KILLED BY SIGNAL" ;; success) verdict="OK (ran to its time limit or exited cleanly)" ;; esac grep -q 'time limit reached' "$LOG" 2>/dev/null && [ "$RESULT" = success ] && verdict="OK (ran its full time limit)" cnt() { local c=0; [ -f "$D3D" ] && c=$(grep -a -c -E "$@" "$D3D"); echo "${c:-0}"; } { - echo "== leonida boot $AGENT-$N: $verdict" - echo "unit result=$RESULT exit_code=$ECODE exit_status=$ESTAT" + echo "== leonida boot $NAME: $verdict" + echo "unit result=$RESULT" echo "queued $((BOOT-START)) s, ran $((END-BOOT)) s; trace $D3D" sed -n '/^LEONIDA_\|^WINEDEBUG\|^unit=/p' "$META" 2>/dev/null | tr '\n' ' '; echo echo - echo "-- counts" - echo "PresentX ok $(cnt 'XboxPresentation::PresentX ok') refused $(cnt 'XboxPresentation::PresentX failed')" - echo "CreatePipelineState failed $(cnt 'CreatePipelineState failed') FSPX compute misses $(cnt 'no translated compute shader for FSPX') slot-67 failed $(cnt 'slot 67 call .* failed')" - echo "E_NOTIMPL $(cnt 'E_NOTIMPL') wine err: lines $(cnt '^[0-9a-f]{4}:err:|:err:') exceptions $(cnt -i 'exception|unhandled|page fault|access violation')" - grep -a -m1 -E 'translated shaders \(' "$D3D" 2>/dev/null - grep -a 'present-probe: source frame .* via' "$D3D" 2>/dev/null | tail -1 | sed 's/.*via/source via/' | cut -c1-120 + echo "-- counts in the D3D12 trace" + echo "no translated shader $(cnt 'no translated ') E_NOTIMPL $(cnt 'E_NOTIMPL') failed with an HRESULT $(cnt 'failed with 0x8')" + echo "Wine err: lines $(cnt ':err:') exceptions $(cnt -i 'exception|unhandled|page fault|access violation')" echo - echo "-- frames (swapchain; then the title's own backbuffer when LEONIDA_CAPTURE_SOURCE=1)" - [ -f "$CAP/index.txt" ] && { echo "$(wc -l < "$CAP/index.txt") captured; last: $(tail -1 "$CAP/index.txt" | cut -c1-110)"; awk '{m=$(NF-2)+$(NF-1)+$NF; if (m>0) n++} END{print n+0 " of " NR " frames non-black"}' "$CAP/index.txt"; } || echo "no capture index" - grep -a 'present-probe: source frame .* mean' "$D3D" 2>/dev/null | tail -2 | sed 's/.*source frame/source frame/' | cut -c1-140 + echo "-- frames (every LEONIDA_CAPTURE_EVERY-th presented frame of the swapchain)" + if [ -f "$CAP/index.txt" ]; then + echo "$(wc -l < "$CAP/index.txt") captured; last: $(tail -1 "$CAP/index.txt" | cut -c1-110)" + awk '{m=$(NF-2)+$(NF-1)+$NF; if (m>0) n++} END{print n+0 " of " NR " frames non-black"}' "$CAP/index.txt" + else + echo "none captured" + fi echo echo "-- resources (2 s samples)" - [ -s "$RES" ] && awk -F'\t' 'NR>1{ if(min==""||$2sw)sw=$3; if($4>um)um=$4; if($5>us)us=$5; if($6+0>gm)gm=$6 } END{printf "min RAM available %s MB, max swap used %s MB, game peak %s MB RAM + %s MB swap, VRAM peak %s MB\n",min,sw,um,us,gm}' "$RES" || echo "no samples" - journalctl --user -u "leonida-boot-$AGENT-$N" --since "@$START" -q --no-pager 2>/dev/null | grep -E 'Consumed|oom|Failed' | sed 's/^.*\]: //' | sort -u | cut -c1-200 - # Compare with other boots instead of guessing: on the console (Series S) path the title itself grows to ~20 GB of - # RAM+swap by ~130 s (fsdraw-6: 9.9 GB + 11.2 GB), mostly zero pages that zram compresses well. - [ -s "$RES" ] && awk -F'\t' 'NR>1{t=$4+$5; if(t>m)m=t} END{printf "game peak RAM+swap %.1f GB (console-path baseline ~20 GB at 130 s; oomd kills when zram swap passes 98%%)\n", m/1024}' "$RES" + [ -s "$RES" ] && awk -F'\t' 'NR>1{ if(min==""||$2sw)sw=$3; if($4>um)um=$4; if($5>us)us=$5; if($6+0>gm)gm=$6 } END{printf "min RAM available %d MB, max swap used %d MB, game peak %d MB RAM + %d MB swap, VRAM peak %d MB\n", min, sw, um, us, gm}' "$RES" + journalctl --user -u "leonida-boot-$NAME" --since "@$START" -q --no-pager 2>/dev/null | grep -E 'Consumed|oom|Failed' | sed 's/^.*\]: //' | sort -u | cut -c1-200 echo echo "-- system events during the boot (OOM, GPU Xid, segfaults)" { journalctl --since "@$BOOT" -q --no-pager 2>/dev/null | grep -i -E 'systemd-oomd.*(Marked|killed)|oom-kill|out of memory|NVRM: Xid|segfault|gta6rt|wineserver.*crash' ; } | cut -c1-200 | tail -15 @@ -61,15 +63,13 @@ cnt() { local c=0; [ -f "$D3D" ] && c=$(grep -a -c -E "$@" "$D3D"); echo "${c:-0 echo echo "-- where the trace ended" [ -f "$D3D" ] && tail -n 8 "$D3D" | cut -c1-200 -} > "$OUT" 2>&1 +} > "$OUT.tmp" 2>&1 +mv "$OUT.tmp" "$OUT" frames=$( [ -f "$CAP/index.txt" ] && awk '{m=$(NF-2)+$(NF-1)+$NF; if (m>0) n++} END{print (n+0) "/" NR}' "$CAP/index.txt" || echo "-") peak=$( [ -s "$RES" ] && awk -F'\t' 'NR>1{if($4>u)u=$4} END{print u+0}' "$RES" || echo "-") exec 7>>"$LEDGER"; flock 7 -# Both the unit's ExecStopPost and the outer wrapper call this; the first one to finish records the boot. -grep -q -P "^[^\t]*\t$AGENT\t$N\t" "$LEDGER" 2>/dev/null && exit 0 -[ -s "$LEDGER" ] || printf 'end\tagent\tn\tresult\tran_s\tpresentx_ok\tpso_failed\tfspx_miss\tnonblack_frames\tpeak_mb\tgta6rt\n' >&7 -printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$(date '+%F %T')" "$AGENT" "$N" "$RESULT" "$((END-BOOT))" \ - "$(cnt 'XboxPresentation::PresentX ok')" "$(cnt 'CreatePipelineState failed')" "$(cnt 'no translated compute shader for FSPX')" \ - "$frames" "$peak" "$(sed -n 's/^unit=.*gta6rt=\([^ ]*\).*/\1/p' "$META")" >&7 +[ -s "$LEDGER" ] || printf 'end\tname\tresult\tran_s\tnonblack_frames\tpeak_mb\tgta6rt\n' >&7 +printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$(date '+%F %T')" "$NAME" "$RESULT" "$((END-BOOT))" "$frames" "$peak" \ + "$(sed -n 's/^unit=.*gta6rt=\([^ ]*\).*/\1/p' "$META")" >&7 exit 0 diff --git a/scripts/linux-boot/boot-inner.sh b/scripts/linux-boot/boot-inner.sh index e52d3daeff..d6a66b454b 100755 --- a/scripts/linux-boot/boot-inner.sh +++ b/scripts/linux-boot/boot-inner.sh @@ -1,27 +1,27 @@ #!/bin/bash -# Runs inside the leonida-boot-* unit (see run-boot.sh). Waits for memory, takes the locks, samples resources, boots. +# Runs inside the leonida-boot- unit (see run-boot.sh). Waits for memory, takes the locks, samples resources, boots. set -u -WORK=/opt/leonida/work/$BOOT_AGENT; N=$BOOT_N; LOG=$WORK/boot-$N.log; RES=$WORK/boot-$N.resources.tsv -META=$WORK/boot-$N.meta +HERE=$(cd "$(dirname "$(readlink -f "$0")")" && pwd) +OUT=${LEONIDA_BOOT_DIR:?}; RUN=$OUT/runs/${BOOT_NAME:?}; LOG=$RUN/boot.log; RES=$RUN/resources.tsv; META=$RUN/meta : > "$LOG" echo "start_epoch=$(date +%s)" > "$META" -echo "unit=leonida-boot-$BOOT_AGENT-$N gta6rt=$GTA6RT secs=$BOOT_SECS" >> "$META" -env | grep -E '^(LEONIDA_|WINEDEBUG=)' | sort >> "$META" +echo "unit=leonida-boot-$BOOT_NAME gta6rt=$GTA6RT secs=$BOOT_SECS" >> "$META" +env | grep -E '^(LEONIDA_|WINEDEBUG=)' | grep -v -E '^LEONIDA_(GAME_DIR|SHADERS|BOOT_DIR|CAPTURE)=' | sort >> "$META" -mem_free_mb() { # RAM available plus a third of free zram swap (zram pages cost RAM, roughly 3:1) +mem_free_mb() { # RAM available plus a third of the free swap (swap on zram costs RAM, roughly 3:1) awk '/^MemAvailable:/{a=$2} /^SwapFree:/{s=$2} END{printf "%d", (a + s/3)/1024}' /proc/meminfo } NEED=${LEONIDA_BOOT_MIN_FREE_MB:-6500} swap_pct() { awk '/^SwapTotal:/{t=$2} /^SwapFree:/{f=$2} END{printf "%d", t ? (t-f)*100/t : 0}' /proc/meminfo; } -exec 8>/opt/leonida/.gpu.lock; flock 8 # one boot at a time +exec 8>"$OUT/.gpu.lock"; flock 8 # one boot at a time echo "[run-boot] $(date +%T) got the GPU lock" >> "$LOG" for i in $(seq 1 40); do # up to 10 min for memory headroom f=$(mem_free_mb); sp=$(swap_pct); [ "$f" -ge "$NEED" ] && [ "$sp" -lt 70 ] && break echo "[run-boot] $(date +%T) waiting for memory: ${f} MB free (need ${NEED}), swap ${sp}% (need < 70%)" >> "$LOG"; sleep 15 done echo "[run-boot] $(date +%T) memory before boot: $(mem_free_mb) MB free, swap $(swap_pct)%" >> "$LOG" -exec 9>/opt/leonida/.build.lock; flock 9 # no compiles while the game runs +exec 9>"$OUT/.build.lock"; flock 9 # no compiles while the game runs echo "[run-boot] $(date +%T) got the build lock; booting" >> "$LOG" echo "boot_epoch=$(date +%s)" >> "$META" @@ -30,13 +30,13 @@ CG=/sys/fs/cgroup$(cut -d: -f3 /proc/self/cgroup) while :; do read -r ma su < <(awk '/^MemAvailable:/{a=$2} /^SwapTotal:/{t=$2} /^SwapFree:/{f=$2} END{print int(a/1024), int((t-f)/1024)}' /proc/meminfo) um=$(( $(cat "$CG/memory.current" 2>/dev/null || echo 0) / 1048576 )); us=$(( $(cat "$CG/memory.swap.current" 2>/dev/null || echo 0) / 1048576 )) - g=$(nvidia-smi --query-gpu=memory.used,utilization.gpu --format=csv,noheader,nounits 2>/dev/null | tr -d ' ' | tr ',' '\t') + g=$(nvidia-smi --query-gpu=memory.used,utilization.gpu --format=csv,noheader,nounits 2>/dev/null | head -1 | tr -d ' ' | tr ',' '\t') printf '%s\t%s\t%s\t%s\t%s\t%s\n' "$(date +%T)" "$ma" "$su" "$um" "$us" "${g:-? ?}" sleep 2 done ) > "$RES" 2>/dev/null & SAMPLER=$! -/opt/leonida/boot.sh run "$BOOT_SECS" >> "$LOG" 2>&1 +"$HERE/boot.sh" run "$BOOT_SECS" >> "$LOG" 2>&1 rc=$? kill $SAMPLER 2>/dev/null echo "[run-boot] $(date +%T) boot.sh exit $rc" >> "$LOG" diff --git a/scripts/linux-boot/boot.sh b/scripts/linux-boot/boot.sh index 55f84f019d..4a69ef2c4e 100755 --- a/scripts/linux-boot/boot.sh +++ b/scripts/linux-boot/boot.sh @@ -1,42 +1,56 @@ #!/bin/bash -# Boot the packaged port under Wine with the network off (unshare -rn: user + network namespace, no root). -# usage: boot.sh dry-run|init|run [seconds] (run defaults to 150 s, then the title is stopped) -# Traces stay local in /opt/leonida/traces: they can quote game data, never post them. +# Boot the loader under Wine or Proton with the network off (unshare -rn: a new user and network namespace, no root). +# usage: boot.sh dry-run|init|run [seconds] (run stops the title after `seconds`, default 150) +# LEONIDA_GAME_DIR the folder of your copy of the package (the one with game_scarlett_master.exe); required +# LEONIDA_SHADERS the translated shader library (/shaders/spirv of make_game.py); required for run +# LEONIDA_BOOT_DIR where traces, the overlay and the driver's shader cache go (default ~/.local/share/leonida-boot) +# GTA6RT the loader to boot (default: runtime/build/boot/gta6rt.exe of this checkout) +# WINE, WINEPREFIX the Wine to use (default: Proton Experimental's files/bin/wine when Steam has it, else `wine`) +# and a prefix kept for boots alone. Use one Wine per prefix. +# Traces stay on this machine: they can quote game data, so never post them. set -u MODE=${1:?dry-run|init|run}; SECS=${2:-150} -OUT=/opt/leonida -REPO=${LEONIDA_REPO:-$(cd "$(dirname "$(readlink -f "$0")")/../.." && pwd)} # the checkout this script is in +case "$MODE" in dry-run|init|run) ;; *) echo "boot.sh: the mode is dry-run, init or run" >&2; exit 2 ;; esac +[ -n "${LEONIDA_GAME_DIR:-}" ] || { echo "boot.sh: set LEONIDA_GAME_DIR to the folder of your copy of the package" >&2; exit 2; } +GAME=$(realpath -m "$LEONIDA_GAME_DIR") +EXE=$GAME/game_scarlett_master.exe +[ -f "$EXE" ] || { echo "boot.sh: $EXE not found" >&2; exit 2; } +REPO=$(cd "$(dirname "$(readlink -f "$0")")/../.." && pwd) # the checkout this script is in +OUT=$(realpath -m "${LEONIDA_BOOT_DIR:-$HOME/.local/share/leonida-boot}") +GTA6RT=${GTA6RT:-$REPO/runtime/build/boot/gta6rt.exe} +[ -f "$GTA6RT" ] || { echo "boot.sh: no loader at $GTA6RT (build the gta6rt target or set GTA6RT)" >&2; exit 2; } +if [ "$MODE" = run ]; then + [ -n "${LEONIDA_SHADERS:-}" ] || { echo "boot.sh: set LEONIDA_SHADERS to the translated shader library" >&2; exit 2; } + SHADERS=$(realpath -m "$LEONIDA_SHADERS") + [ -d "$SHADERS" ] || { echo "boot.sh: no shader library at $SHADERS" >&2; exit 2; } + export LEONIDA_SHADERS="$SHADERS" LEONIDA_D3D12=vulkan +fi STAMP=$(date +%H%M%S) -T=$OUT/traces; mkdir -p "$T" "$OUT/overlay" "$OUT/cache/nv" +T=$OUT/traces; mkdir -p "$T" "$OUT/overlay" "$OUT/cache/nv" || exit 2 -WINE=${WINE:-wine} # e.g. WINE=".../Proton - Experimental/files/bin/wine" WINEPREFIX=~/.local/share/leonida-proton/pfx -export WINEPREFIX=${WINEPREFIX:-$HOME/.local/share/leonida-wine} WINEDEBUG=${WINEDEBUG:--all} WINEDLLOVERRIDES="mscoree,mshtml=" -export LEONIDA_D3D12=vulkan -export LEONIDA_SHADERS=$OUT/work/shaders/spirv -export LEONIDA_ARENA_MB=${LEONIDA_ARENA_MB:-2048} -export LEONIDA_PIPELINE_CACHE_BYTES=${LEONIDA_PIPELINE_CACHE_BYTES:-4294967296} -export LEONIDA_STARTUP_CACHE_CHECKPOINTS=1 -export __GL_SHADER_DISK_CACHE=1 __GL_SHADER_DISK_CACHE_PATH=$OUT/cache/nv __GL_SHADER_DISK_CACHE_SIZE=21474836480 -export __GL_SHADER_DISK_CACHE_SKIP_CLEANUP=1 -[ -n "${SKIP_INT3:-}" ] && export LEONIDA_SKIP_INT3=1 +win() { local p=${1//\//\\}; printf 'Z:%s' "$p"; } # a Linux path as Wine's Z: drive sees it +PROTON="$HOME/.local/share/Steam/steamapps/common/Proton - Experimental/files/bin/wine" +WINE=${WINE:-$( [ -x "$PROTON" ] && echo "$PROTON" || echo wine )} +export WINEPREFIX=${WINEPREFIX:-$HOME/.local/share/leonida-boot-prefix} WINEDEBUG=${WINEDEBUG:--all} +# No Mono or Gecko install prompt in a new prefix, and no crash debugger: a process that crashes ends, instead of +# starting winedbg (which can crash in turn and start itself again without end). +export WINEDLLOVERRIDES="mscoree,mshtml=;winedbg.exe=d" +# NVIDIA's shader disk cache: kept under the boot folder, with a limit large enough to keep a library's pipelines. +export __GL_SHADER_DISK_CACHE=1 __GL_SHADER_DISK_CACHE_PATH=$OUT/cache/nv +export __GL_SHADER_DISK_CACHE_SIZE=${__GL_SHADER_DISK_CACHE_SIZE:-21474836480} __GL_SHADER_DISK_CACHE_SKIP_CLEANUP=1 -GAME_WIN='Z:\opt\gta6\GTA6.Xbox.v1.0.2.1' -EXE=/opt/gta6/GTA6.Xbox.v1.0.2.1/game_scarlett_master.exe -TRACE_WIN="Z:\\opt\\leonida\\traces\\boot-$MODE-$STAMP.jsonl" +TRACE=$T/boot-$MODE-$STAMP.jsonl D3D=$T/d3d12-$MODE-$STAMP.log -GTA6RT=${GTA6RT:-$OUT/gta6rt.exe}; [ -f "$GTA6RT" ] || GTA6RT=$REPO/runtime/build/boot/gta6rt.exe # GTA6RT=/gta6rt.exe boots a private build without installing it - -args=(--"$MODE" "$EXE" --game-dir "$GAME_WIN" --overlay 'Z:\opt\leonida\overlay' --trace "$TRACE_WIN") +args=(--"$MODE" "$(win "$EXE")" --game-dir "$(win "$GAME")" --overlay "$(win "$OUT/overlay")" --trace "$(win "$TRACE")") [ "$MODE" = run ] && args+=(--trace-d3d12) -echo "[boot] $MODE gta6rt=$GTA6RT trace=$T/boot-$MODE-$STAMP.jsonl d3d12=$D3D" -# unshare: new user + network namespace, so the title has no network at all +echo "[boot] $MODE gta6rt=$GTA6RT trace=$TRACE d3d12=$D3D" if [ "$MODE" = run ]; then timeout --signal=INT --kill-after=20 "$SECS" unshare -rn "$WINE" "$GTA6RT" "${args[@]}" > "$T/stdout-$MODE-$STAMP.log" 2> "$D3D" else unshare -rn "$WINE" "$GTA6RT" "${args[@]}" > "$T/stdout-$MODE-$STAMP.log" 2> "$D3D" fi rc=$?; echo "[boot] exit=$rc" -sleep 0 -python3 -I "$REPO/tools/boot_trace.py" "$T/boot-$MODE-$STAMP.jsonl" --d3d12 "$D3D" > "$T/summary-$MODE-$STAMP.txt" 2>&1 +summary=("$TRACE"); [ "$MODE" = run ] && summary+=(--d3d12 "$D3D") +python3 -I "$REPO/tools/boot_trace.py" "${summary[@]}" > "$T/summary-$MODE-$STAMP.txt" 2>&1 echo "[boot] summary: $T/summary-$MODE-$STAMP.txt" exit $rc diff --git a/scripts/linux-boot/run-boot.sh b/scripts/linux-boot/run-boot.sh index 523d177950..c511e16440 100755 --- a/scripts/linux-boot/run-boot.sh +++ b/scripts/linux-boot/run-boot.sh @@ -1,56 +1,68 @@ #!/bin/bash -# Boot gta6rt as its own systemd --user unit, protected from the swarm and logged in full. +# Boot gta6rt as its own systemd --user unit, with the memory it used and a digest of the result afterwards. # -# usage: run-boot.sh [seconds=150] [KEY=VALUE ...] -# e.g. run-boot.sh fsdraw 3 /path/wt-fsdraw/runtime/build/boot/gta6rt.exe 150 LEONIDA_FOO=1 +# usage: run-boot.sh [seconds=150] [KEY=VALUE ...] +# e.g. run-boot.sh first runtime/build/boot/gta6rt.exe 150 LEONIDA_ARENA_MB=2048 +# LEONIDA_GAME_DIR, LEONIDA_SHADERS and WINE as for boot.sh (from the environment or as KEY=VALUE). # -# What it does for you: -# - runs the boot outside your agent's process tree (survives agent/session restarts); -# - waits for memory headroom before starting, then holds the GPU lock AND the build lock for the whole boot, -# so no compile competes with the game for RAM; -# - Series S profile, late-frame capture, source capture and Wine's error channel on by default (override with KEY=VALUE); -# - samples RAM / swap / the game's memory / VRAM every 2 s; -# - after the boot, even when systemd-oomd or a crash kills it, writes a digest with the unit result, OOM and GPU -# kernel events and every distinct error line, and appends one line to the shared ledger /opt/leonida/work/boots.tsv. +# What it adds to boot.sh: +# - the boot runs outside your shell's process tree, so it survives the terminal; +# - it waits for memory headroom, then holds a GPU lock (one boot at a time) and a build lock for the whole boot. +# A build that takes the same lock never competes with the game for memory: +# flock "${LEONIDA_BOOT_DIR:-$HOME/.local/share/leonida-boot}/.build.lock" cmake --build ... --target gta6rt +# - RAM, swap, the unit's own memory and VRAM are sampled every 2 s; +# - a frame capture (every 4800th presented frame) and Wine's error channel are on by default; +# - after the boot, also when the kernel or systemd-oomd killed it, a digest is written: the unit's result, memory +# and GPU kernel events, and every distinct error line with its count. # -# Outputs (in /opt/leonida/work//): boot-.log boot-.resources.tsv boot-.digest.txt +# Outputs, in $LEONIDA_BOOT_DIR/runs//: boot.log resources.tsv digest.txt capture/ +# They can quote the title's own log text: keep them on this machine. set -u -AGENT=${1:?agent}; N=${2:?n}; EXE=${3:?gta6rt.exe}; SECS=${4:-150}; shift $(( $# >= 4 ? 4 : $# )) +NAME=${1:?name}; EXE=${2:?gta6rt.exe}; SECS=${3:-150}; shift $(( $# >= 3 ? 3 : $# )) +case "$NAME" in *[!A-Za-z0-9_-]*|"") echo "run-boot: the name may hold letters, digits, - and _" >&2; exit 2 ;; esac [ -f "$EXE" ] || { echo "run-boot: no such gta6rt: $EXE" >&2; exit 2; } +EXE=$(realpath "$EXE") # gta6rt loads gta6rt_tls_host.dll from its own folder; without it the title gets no module TLS index and exits at once. -[ -f "$(dirname "$EXE")/gta6rt_tls_host.dll" ] || { echo "run-boot: $(dirname "$EXE")/gta6rt_tls_host.dll is missing: copy it next to the exe (build it with the gta6rt target) or boot the exe from its build folder" >&2; exit 2; } -WORK=/opt/leonida/work/$AGENT; mkdir -p "$WORK" -UNIT=leonida-boot-$AGENT-$N +[ -f "$(dirname "$EXE")/gta6rt_tls_host.dll" ] || { echo "run-boot: $(dirname "$EXE")/gta6rt_tls_host.dll is missing: build it with the gta6rt target and keep it next to the exe" >&2; exit 2; } +HERE=$(cd "$(dirname "$(readlink -f "$0")")" && pwd) +OUT=$(realpath -m "${LEONIDA_BOOT_DIR:-$HOME/.local/share/leonida-boot}") +RUN=$OUT/runs/$NAME +UNIT=leonida-boot-$NAME if systemctl --user is-active --quiet "$UNIT"; then echo "run-boot: $UNIT is already running" >&2; exit 2; fi declare -A ENV=( - [WINE]="$HOME/.local/share/Steam/steamapps/common/Proton - Experimental/files/bin/wine" - [WINEPREFIX]="$HOME/.local/share/leonida-proton/pfx" + [WINEPREFIX]="${WINEPREFIX:-$HOME/.local/share/leonida-boot-prefix}" [WINEDEBUG]="-all,err+all" [GTA6RT]="$EXE" - [LEONIDA_CAPTURE]="Z:\\opt\\leonida\\capture\\$AGENT-$N" - [LEONIDA_CAPTURE_EVERY]=4800 [LEONIDA_CAPTURE_LIMIT]=24 [LEONIDA_CAPTURE_SOURCE]=1 - [LEONIDA_DEVICE_TYPE]=6 - [LEONIDA_PIPELINE_CACHE_DIR]="Z:\\opt\\leonida\\cache\\pipelines" + [LEONIDA_BOOT_DIR]="$OUT" + [LEONIDA_CAPTURE]="Z:${RUN//\//\\}\\capture" + [LEONIDA_CAPTURE_EVERY]=4800 ) +for k in WINE LEONIDA_GAME_DIR LEONIDA_SHADERS; do [ -n "${!k:-}" ] && ENV[$k]=${!k}; done for kv in "$@"; do ENV[${kv%%=*}]="${kv#*=}"; done +[ -n "${ENV[LEONIDA_GAME_DIR]:-}" ] || { echo "run-boot: set LEONIDA_GAME_DIR to the folder of your copy of the package" >&2; exit 2; } +[ -n "${ENV[LEONIDA_SHADERS]:-}" ] || { echo "run-boot: set LEONIDA_SHADERS to the translated shader library" >&2; exit 2; } args=() for k in "${!ENV[@]}"; do args+=(--setenv="$k=${ENV[$k]}"); done +mkdir -p "$RUN/capture" || exit 2 echo "run-boot: $UNIT starting (queues for memory headroom, the GPU lock and the build lock)" -rm -f "$WORK/boot-$N.digest.txt" -systemd-run --user --collect --quiet --unit="$UNIT" -p WorkingDirectory=/opt/leonida \ - --setenv=BOOT_AGENT="$AGENT" --setenv=BOOT_N="$N" --setenv=BOOT_SECS="$SECS" "${args[@]}" \ - /opt/leonida/boot-inner.sh || { echo "run-boot: could not start $UNIT" >&2; exit 2; } -# The digest is written by a separate, tiny watcher unit: it survives systemd-oomd killing the boot's cgroup and the -# caller's shell going away. It waits for the boot unit to end, reads its result from the journal and writes the digest. -systemd-run --user --collect --quiet --unit="leonida-digest-$AGENT-$N" -p MemoryMax=256M \ - /bin/bash -c 'while systemctl --user is-active --quiet "$0" || systemctl --user is-activating --quiet "$0"; do sleep 3; done - START=$(sed -n "s/^start_epoch=//p" "/opt/leonida/work/$1/boot-$2.meta" 2>/dev/null) - RES=$(journalctl --user -u "$0" ${START:+--since "@$START"} -q --no-pager 2>/dev/null | grep -o "Failed with result .[a-z-]*." | tail -1 | tr -d "\x27" | sed "s/Failed with result //") - SERVICE_RESULT=${RES:-success} exec /opt/leonida/boot-digest.sh "$1" "$2"' "$UNIT" "$AGENT" "$N" +rm -f "$RUN/digest.txt" "$RUN/meta" +# OOMScoreAdjust: when the machine runs out of memory, the kernel takes the game and not the session that started it. +systemd-run --user --collect --quiet --unit="$UNIT" -p WorkingDirectory="$OUT" -p OOMScoreAdjust=900 \ + --setenv=BOOT_NAME="$NAME" --setenv=BOOT_SECS="$SECS" "${args[@]}" \ + "$HERE/boot-inner.sh" || { echo "run-boot: could not start $UNIT" >&2; exit 2; } +# The digest is written by a separate, small unit: it survives systemd-oomd killing the boot's cgroup and this shell +# going away. It waits for the boot unit to end (leftover Wine processes included: systemd stops them after the +# title has exited), reads its result from the journal and writes the digest. +systemd-run --user --collect --quiet --unit="leonida-digest-$NAME" -p MemoryMax=256M --setenv=LEONIDA_BOOT_DIR="$OUT" \ + /bin/bash -c 'while s=$(systemctl --user show -p ActiveState --value "$0"); [ "$s" = active ] || [ "$s" = activating ] || [ "$s" = deactivating ]; do sleep 3; done + START=$(sed -n "s/^start_epoch=//p" "$2/meta" 2>/dev/null) + RES=$(journalctl --user -u "$0" ${START:+--since "@$START"} -q --no-pager 2>/dev/null | grep -o "Failed with result .[a-z-]*." | tail -1 | tr -d "\047" | sed "s/Failed with result //") + SERVICE_RESULT=${RES:-success} exec "$3/boot-digest.sh" "$1"' "$UNIT" "$NAME" "$RUN" "$HERE" \ + || { echo "run-boot: could not start the digest unit" >&2; exit 2; } # Block until the digest exists (so a caller that waits on this script gets the result), then print it. -while [ ! -s "$WORK/boot-$N.digest.txt" ] || systemctl --user is-active --quiet "leonida-digest-$AGENT-$N"; do sleep 5; done +while [ ! -s "$RUN/digest.txt" ] || systemctl --user is-active --quiet "leonida-digest-$NAME"; do sleep 5; done echo "run-boot: $UNIT finished. Digest:" -cat "$WORK/boot-$N.digest.txt" -head -1 "$WORK/boot-$N.digest.txt" | grep -q ': OK' && exit 0 || exit 1 +cat "$RUN/digest.txt" +head -1 "$RUN/digest.txt" | grep -q ': OK' && exit 0 || exit 1 diff --git a/tests/test_linux_boot_scripts.py b/tests/test_linux_boot_scripts.py new file mode 100644 index 0000000000..3cccb00cf3 --- /dev/null +++ b/tests/test_linux_boot_scripts.py @@ -0,0 +1,91 @@ +"""scripts/linux-boot: the scripts parse, are executable and refuse wrong input before they start anything. + +No Wine, no systemd unit and no game files are involved: every case below ends in a script's own argument checks. + + python -I tests/test_linux_boot_scripts.py -v +""" +import os +import shutil +import subprocess +import sys +import tempfile +import unittest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +BOOT = os.path.join(ROOT, "scripts", "linux-boot") +SCRIPTS = ("boot.sh", "boot-inner.sh", "boot-digest.sh", "run-boot.sh", "configure-worktree.sh") +BASH = shutil.which("bash") + + +@unittest.skipUnless(sys.platform.startswith("linux") and BASH, "the boot scripts are for Linux and need bash") +class LinuxBootScripts(unittest.TestCase): + def run_script(self, name, *args, **env): + """(exit code, stderr) of one script with only the given LEONIDA_*/GTA6RT variables set.""" + clean = {k: v for k, v in os.environ.items() if not k.startswith("LEONIDA_") and k != "GTA6RT"} + clean.update(env) + done = subprocess.run([BASH, os.path.join(BOOT, name), *args], env=clean, capture_output=True, text=True, + timeout=60) + return done.returncode, done.stderr + + def test_scripts_parse_and_are_executable(self): + for name in SCRIPTS: + with self.subTest(script=name): + path = os.path.join(BOOT, name) + self.assertTrue(os.access(path, os.X_OK), "not executable") + self.assertEqual(subprocess.run([BASH, "-n", path], capture_output=True).returncode, 0) + with open(path, "rb") as f: + self.assertNotIn(b"\r", f.read()) + + def test_boot_refuses_wrong_input(self): + with tempfile.TemporaryDirectory() as tmp: + game = os.path.join(tmp, "game") + os.mkdir(game) + out = os.path.join(tmp, "boot-dir") + + def boot(*args, **env): + return self.run_script("boot.sh", *args, LEONIDA_BOOT_DIR=out, **env) + + code, err = boot("play") + self.assertEqual(code, 2) + self.assertIn("dry-run, init or run", err) + code, err = boot("dry-run") + self.assertEqual(code, 2) + self.assertIn("LEONIDA_GAME_DIR", err) + code, err = boot("dry-run", LEONIDA_GAME_DIR=game) + self.assertEqual(code, 2) + self.assertIn("game_scarlett_master.exe not found", err) + # An empty stand-in for the executable: the next check is the loader, then the shader library. + open(os.path.join(game, "game_scarlett_master.exe"), "wb").close() + missing = os.path.join(tmp, "none", "gta6rt.exe") + code, err = boot("dry-run", LEONIDA_GAME_DIR=game, GTA6RT=missing) + self.assertEqual(code, 2) + self.assertIn("no loader at", err) + loader = os.path.join(tmp, "gta6rt.exe") + open(loader, "wb").close() + code, err = boot("run", LEONIDA_GAME_DIR=game, GTA6RT=loader) + self.assertEqual(code, 2) + self.assertIn("LEONIDA_SHADERS", err) + code, err = boot("run", LEONIDA_GAME_DIR=game, GTA6RT=loader, LEONIDA_SHADERS=os.path.join(tmp, "no-library")) + self.assertEqual(code, 2) + self.assertIn("no shader library", err) + self.assertFalse(os.path.exists(out), "a refused boot must not create its folders") + + def test_run_boot_refuses_wrong_input(self): + with tempfile.TemporaryDirectory() as tmp: + out = os.path.join(tmp, "boot-dir") + code, err = self.run_script("run-boot.sh", "bad name", "x.exe", LEONIDA_BOOT_DIR=out) + self.assertEqual(code, 2) + self.assertIn("letters, digits", err) + code, err = self.run_script("run-boot.sh", "one", os.path.join(tmp, "gta6rt.exe"), LEONIDA_BOOT_DIR=out) + self.assertEqual(code, 2) + self.assertIn("no such gta6rt", err) + loader = os.path.join(tmp, "gta6rt.exe") + open(loader, "wb").close() + code, err = self.run_script("run-boot.sh", "one", loader, LEONIDA_BOOT_DIR=out) + self.assertEqual(code, 2) + self.assertIn("gta6rt_tls_host.dll is missing", err) + self.assertFalse(os.path.exists(out), "a refused boot must not create its run folder") + + +if __name__ == "__main__": + unittest.main()