WIP: perf(nvn): a call of several recordings makes room for all of them at once (HOS_NVN_CALL_RESERVE=0 to disable) #2023
Labels
No labels
area/accessibility
area/audio
area/input
area/install
area/menu
area/renderer
area/saves
area/tooling
area/upscaling
beanstalk: approved
beanstalk: failed
beanstalk: needs approval
beanstalk: running
beanstalk: tested
ci: approved
good first issue
gpu/amd
gpu/igpu
gpu/intel
gpu/nvidia
help wanted
kind
bug
kind
chore
kind
docs
kind
feature
kind
performance
kind
question
needs measurements
platform/linux
platform/macos
platform/steam-deck
platform/windows
preview
priority
critical
priority
high
priority
low
regression
risk
high
risk
low
risk
medium
status
blocked
status
confirmed
status
duplicate
status
invalid
status
needs-info
status
wontfix
ci: approved
No milestone
No project
No assignees
4 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
MagicBeanDev/Longshot!2023
Loading…
Reference in a new issue
No description provided.
Delete branch "siantm/Longshot:perf/nvn-call-reserve"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Summary
nvnCommandBufferCallCommandsandnvnCommandBufferCopyCommandscopy each called recording into the caller'srecording segment. They did it one recording at a time: each called recording that did not fit grew the segment by
doubling, a copy of everything the segment held at each step, so a call of several large recordings could grow (and
copy) the segment more than once.
With this, a call of 2 to 64 recordings reads the game's array of handles once, checks all of the handles and sizes
them (
called_size), makes room for all of their records once (cmd_reserve_rec), then checks each handle again justbefore its copy, as main does, and copies it (
inline_recording, whose reserve returns at once: the room is there). Thecheck-to-copy window is main's own; a recording the game releases while the room is made stops the call at its second
check, as on main, and released copies are freed as on main. A call whose recordings come to more than
CMD_SEG_MAX(4 GiB), and any segment growth past it, stops with the NVN diagnostic instead of wrapping a size. The bytes recorded
and the command memory counts are the same as one at a time. A handle that is not live still stops the game, now
before any of the call is copied, which the game does not see. The result expected: fewer segment growths and fewer
bytes copied by them in calls of several recordings.
Both ways, CallCommands and CopyCommands check their count and array in one place (
call_handles: a count of 0 readsnothing, a negative count or a count with no array stops with the diagnostic), read each handle once, and the
HOS_NVN_WATCH_DRAWwatch's table and watched command buffer are written and read atomically. The recordings' log line(every 50,000 recordings) now also counts the segments' growths, the bytes they copied and the calls given their room
at once, so the in-game A/B can compare them.
The switch:
HOS_NVN_CALL_RESERVE(new, a kill switch, bool, its row ingpu/vk/switches.def), on (unset), thevalue this change proposes;
=0(orfalse,off,no) is main's code, one recording at a time, the segment growingfor each that does not fit. It is read at the first call of several recordings and cached; threads making that call
together may each read the variable, and all keep the first answer stored. An empty value in
longshot_env.txtonWindows removes the variable (on, as unset);
=0is off everywhere.From 3e8a2abd on
exp/x86-asm-sync, where it was the second half ofHOS_NVN_SEG_PEAK; the first half (a grownsegment growing at once to the command buffer's recent peak) is not part of this. Prior work: #1812 (GummiNaomi)
prefetched the next handle in the same CallCommands / CopyCommands loops and started each first segment at a size
hint; its author closed it unmerged, having measured no change at 4 or 16 cores. This one does neither: it sizes the
caller's segment once for the whole call.
Read first:
call_reserve_on,inline_recordingsandcall_handlesinhost/nvn_native.c, thentests/test_nvn_call_reserve.py.Testing
Tested: Windows 11, i7-9700, RTX 4060, the builder's llvm-mingw clang 23; head
39fe40deon main9dd41326(rebased fromb62932a9,git range-diff"=" for every commit; main's move touched none of this PR's files). Queue jobs of this PC's job queue, every check in a hidden console with--timeout 1200:fb-2023-l9(light):tests/test_nvn_call_reserve.pyat the test commiteb4d64f6fails on the code before the fix (the switch's first read answers 0 where 1 is expected, and the run stops there); at the head,tests/run_all.py --strict --exact tests/test_nvn_call_reserve.py tests/test_switch_table.py tests/test_recording_log_handoff.py tests/test_host_alloc_wait.py: 4 passed;host/nvn_native.ccompiles with the game build's own command (-fsyntax-only).fb-2023-h9(build): every checktests/run_all.py --strict --changed 9dd41326picks: 52 checks, 40 passed, 9 failed, 3 skipped (Linux-only); the 9 fail on main @9dd41326too, run from a main worktree in the same job:tests/test_crash_dialog.py,tests/test_dev_ab.py,tests/test_dev_packs.py,tests/test_frame_overlap.py,tests/test_host_guest_writes.py,tests/test_linux_pressure.py,tests/test_present_queue_default.py,tests/test_target_reuse_memory.py,tests/test_vk_occlusion_queries.py. Not run here: Linux, the whole suite and lint.In the game on this PC: two sittings of
HOS_NVN_CALL_RESERVE=0against unset (on) in one runtime of this head,Kokiri Forest, 16 runs each, and a Market pair against main in each (Measurements); no
not a live recordingline, FATAL, device lostor Vulkan error in any run. With it on, the recordings' line counted about 12,700 calls of several recordings given
their room at once every 100,000 recordings in play, none with
=0.Still to test:
9dd41326, this PR unsetand this PR with
HOS_NVN_CALL_RESERVE=0, warmed, interleaved, at least three runs each, expecting nonot a live recordingline, no FATAL, the same picture all three ways, and average fps, 1% lows, median and p99 frame times andpeak host memory unset at least those of the other two (by hand)
main, on this PR unset and on this PR with
HOS_NVN_CALL_RESERVE=0, warmed and interleaved, expecting nonot a live recordingline, no FATAL and the same picture (the test farm: linux+nvidia, linux+amd, windows+amd, windows+intel,steamdeck: Kokiri Forest and Castle Town Market three minutes, main, HOS_NVN_CALL_RESERVE unset and =0, warmed and
interleaved, the log with its live copies (MB), frame times, peak host memory and a screenshot)
python3 -I -B tests/test_nvn_call_reserve.py --cc gcc, expecting PASS (by hand)mise run testandmise run lintat this head, expecting every failure tofail on main too and lint to pass (by hand; neither tool is installed on this PC)
Measurements
Verdict: in two sittings on this PC (Kokiri Forest, CPU-paced, 8 runs a side in each; In play below), the change
copies fewer bytes, shown twice, and no time is shown. With it on, the segments' growths copied 13 % fewer bytes: 426
against 373 MB every 100,000 recordings in play in the first sitting and 432 against 375 in the second, every run apart
in both (p = 0.0002 each); pooled 57 MB fewer every 100,000 recordings (95 % interval 52 to 64), a few tens of KB a frame
at the 50 to 110 recordings a frame this scene makes. The fewer growths it was expected to bring did not come: 3,390
against 3,389 and 3,435 against 3,443 every 100,000 recordings (pooled +0.5 %, p = 0.37). No line times the copies, and
nothing timed is shown: the first sitting's leans for it (the game's own code -1.2 %, draw -3.3 %) are gone in the second
(9.71 against 9.72 ms, 2.77 against 2.77 ms); pooled, the game's own code -0.8 % (p = 0.19), the replay's submit -1.5 %
(p = 0.15), median frame time -0.8 % (p = 0.29).
HOS_NVN_CALL_RESERVEships on, the value this change proposes. On the branch,HOS_NVN_SEG_PEAKas a whole (this and the peak growth) measured no difference inplay (2cc8489c); its micro-benchmark (3e8a2abd) is mostly the peak growth, which is not here, so it is not quoted.
Baseline: this PR with
HOS_NVN_CALL_RESERVE=0(one recording at a time, main's code) in the same runtime as unset:one build, the switch the only difference; and main @
9dd41326for the Market pair.In play (held job
fb-g2023, 04:38 to 05:23 UTC on 2026-11-24): one runtime of this head39fe40deon main9dd41326,Windows 11, i7-9700, RTX 4060; Threaded rendering at its default; Kokiri Forest from the scene's save, 60 s, the output
at 800x600 (CPU-paced, on an 800x600 desktop at 30 Hz), the GPU cooled to 70 C before each run; a warm-up a side, then
8 runs a side interleaved (off on on off, four times); all 16 counted, every one light, at create. The recordings'
figures are from its line (every 50,000 recordings), in steady play (after the last load); p from an exact swap test of
the 8 runs a side.
39fe40de,HOS_NVN_CALL_RESERVE=0, 8 runs39fe40de, unset (on), 8 runsa frame's replay time (ms): submitThe frames of 50 ms or more came by run: 12, 10, 3, 3, 3, 2, 0 and 0 with
=0, and 64, 8, 4, 2, 2, 1, 1 and 1 unset.The 64 are one run's, and its long frames in the last minute were the game's own thread (about 117 ms of its code and
121 ms blocked in each, the renderer 3 ms). Not shown either way.
The Market pair (60 s, one run a side): main @ 9dd41326's run took place while this PC was at its commit limit (50.9 of
52.2 GB committed), so the pair is spoiled and not read. This head's run (unset) had no
not a live recordingline andno FATAL, and counted 78,308 calls given their room at once by its last line.
In play, the second sitting (held job
fb-g2023b, chain 21, ended 08:40 UTC on 2026-11-24): the same script, runtimeand settings as the first, on the same 800x600 desktop; all 16 counted, every one light, at create; no load marker, no
run held, and no commit-limit line in any run.
39fe40de,HOS_NVN_CALL_RESERVE=0, 8 runs39fe40de, unset (on), 8 runsa frame's replay time (ms): submitThe two sittings pooled (labels swapped within a sitting only, 20,000 times; intervals by resampling runs within each
sitting and side): MB copied every 100,000 recordings in play -57.3 (-13.4 %, 95 % interval -63.9 to -51.7, p < 0.0001);
growths +16 (+0.5 %, -15 to +50, p = 0.37); calm-stretch game_ms -0.08 ms (-0.8 %, -0.19 to +0.03, p = 0.19); main thread
blocked -0.9 % (p = 0.17); median frame time -0.08 ms (-0.8 %, -0.21 to +0.06, p = 0.29).
The Market pair of this sitting (60 s, one run a side, a reference; sound this time, the PC at 46.6 of 49.2 GB committed at
its peak): main @
9dd41326against this head unset, calm-stretch game_ms 12.80 against 12.55, p99 44.2 against 24.0 ms,23 against 14 frames of 50 ms or more; not read either way.
Risks
What could break: a call's records copied wrong or counted wrong would show as wrong or missing draws in any scene, or
wrong heap sizes the game computes from the command memory counts; the test compares every recording's bytes and counts
with the switch on and off over 3,000 recordings, and a call's bytes and counts against the records as written. The
check-to-copy window is main's own, no wider: each handle is checked again just before its copy, so a recording released
while the room is made stops the call as on main (the
pincase), and nothing holds released copies: they are freedas on main. Its cost: one more lock-free check of each handle a call, and the room made with the sizes of the first
check. Turn it off with
HOS_NVN_CALL_RESERVE=0. Either way, what changes from main: a call with a negative count or acount but no array stops with the NVN diagnostic (it read memory at address 0 before), a recording segment past 4 GiB
stops with it, the watch is atomic and the log line has three more counts. Host code: the runtime is rebuilt; nothing
changes for players' saves, options or caches.
Overlap: #1780 (snaildev99's, WIP) also changes the end-of-recording log line in
nvnCommandBufferEndRecording(
host/nvn_native.c); the two conflict there and nowhere else. Whichever is merged first goes first and the otherrebases onto it: this one, if #1780 is first.
Checklist
Ready for review
main; the title is a Conventional Commit.mise run testpasses (any failure that also fails onmainis named).main, or Measurements says why there is nothing to measure.third_party/untouched; nothing GPL-incompatible.When it applies
gpu/vk/switches.def.Assisted-by:/Co-Authored-By:trailers.Ready to merge
main, measured again or a comment says why the numbers still hold.Possibly related, for context:
Recommendation: Request changes. The new path can use a different handle from the one it validated, can outlive a validated recording, and can overflow the batch capacity calculation. The reported fixture passes, but the player benefit and enabled default still need in-game evidence.
CallCommands and CopyCommands reserve space for a batch before copying records. This can avoid intermediate segment allocations and copies when a batch crosses several capacity thresholds. It also adds a handle-list and size pass to every multi-handle call, including calls whose segment already has room.
@fixwill do (12)host/nvn_native.c:1847: The batch copy re-reads the guest array after validation and reserve. (more on the line)host/nvn_native.c:1844: A live-set hit does not pin the recording. (more on the line)host/nvn_native.c:1843: The new batch total is unchecked, and cmd_reserve_rec adds used and OP_RESERVE and doubles cap unchecked. (more on the line)host/nvn_native.c:1846: The extracted watch path carries forward a shared-state race. (more on the line)host/nvn_native.c:1858: PN checks the reserved guest window. (more on the line)gpu/vk/switches.def:121: The row promises that an empty value disables the switch. (more on the line)tests/test_nvn_call_reserve.py:263: The growth assertion pools both entry points, and both sides share the copy helper. (more on the line)tests/test_nvn_call_reserve.py:124: The fixture primes the switch directly before the first NVN call and only uses live handles. (more on the line)tests/test_nvn_call_reserve.py:135: The fixture simulates reinitialization by zeroing the object, orphaning its slot and its potentially multi-megabyte segment. (more on the line)tests/test_nvn_call_reserve.py:216: The compiler picker treats CC as a single filename. (more on the line)host/nvn_native.c:1841: Count multi-handle calls, growths, and bytes copied by growth. Reuse validated sizes and skip redundant reserve checks on the batch path.40bfceb0and the tested base is75317e1f. The reported 47 checks are the changed-file selection and leave the whole-suite and lint requirements open. Keep the current-main box unticked until verified, and record the complete check and lint results for the updated head.For the author (1) (a run, a measurement or a decision)
host/nvn_native.c:1841: The malloc-backed fixture counts requests and cannot show whether batching helps in play. (more on the line)Checks: Still running:
CI / Conventional Commit title (pull_request),CI / Python source checks (ubuntu-24.04, part 1/2) (pull_request),CI / Python source checks (ubuntu-24.04, part 2/2) (pull_request),CI / SPIR-V fixtures (global narrow load/store, direct surface atomics, F2I immediate) (pull_request),CI / Workflow lint (actionlint) (pull_request),CI / Website build and checks (pull_request),Guide screenshots / Guide images and local UI source review (pull_request),Third-party parts / As their notes say (pull_request),Third-party parts / The same as upstream (pull_request).More: does it help, other systems, switches, what was read
Does it help: Unproven. The author reports equivalent output and fewer segment requests in a 3,000-recording synthetic fixture, with no request totals published. The earlier combined HOS_NVN_SEG_PEAK branch showed no measurable gain in play. This head has no isolated in-game comparison with
75317e1f.Other systems: The changed host path feeds every Vulkan vendor and both inline and threaded replay on Windows and Linux, including Steam Deck. Queue waits, deferred binding resolution and registration order are unchanged in the diff. Recording lifetime, diagnostic watches and host RAM are affected. The diff changes no save, audio, input, shader cache or renderer ABI code. No game run verifies rendering or frame pacing yet.
Switches: HOS_NVN_CALL_RESERVE is a new developer kill switch at gpu/vk/switches.def:121. Unset enables batching for calls with at least two handles. 0, false, off and no disable it, as does an empty value when the CRT preserves it. Enabled matches the branch's test configuration. Measurements still need to establish the shipping default.
Reviewed:
15dbbfd830against75317e1f31: Read AGENTS.md, CONTRIBUTING.md, docs/dev/standards.md, the Forgejo template, the commit and all three file diffs. Read the new test in full and the changed NVN functions with their allocation, handle publication and retirement, watch, guest range and submit code. Checked the switch table insertion, switch parser, source-cut helpers and test-runner discovery. No review checklist, PR run logs, comments or reviews were available. The rest of nvn_native.c, unrelated switch rows and unrelated recorded runs were skimmed.; nothing run (a code review).Checked and fine:
Testing: Read-only review. The author reports 38 of 47 selected Windows checks passed, including the new fixture and switch table, with the same nine failures on the base. Forgejo checks were still running. Linux build and GCC fixture results, the full suite, lint and in-game results remain outstanding.
Overlaps and merge order: No overlapping open PR found in the supplied evidence or local history. The description identifies #1812 as closed and unmerged. No merge-order dependency found.
Automated code review by BeanBot (gpt-6.2-sol), on the pull request's opening. Nothing was run; a maintainer decides.
@ -118,6 +118,7 @@ SW(HOS_NO_PRIORITIES, kill, bool, "Windows: boosted threads get above-normal orSW(HOS_NO_RENDERER_WAIT, kill, bool, "the game's first GPU work waits for the renderer", "Non-zero skips the wait for the renderer before the game's first GPU work, as before lighting-fix.")SW(HOS_NO_SDL, kill, bool, "SDL controllers on", "SDL's controller thread is never started: no SDL pads, only XInput.")SW(HOS_NO_THP, attempt, bool, "off: THP as the system sets it outside the guest window", "=1 disables transparent huge pages for the whole process (PR_SET_THP_DISABLE).")SW(HOS_NVN_CALL_RESERVE, kill, bool, "on: a CallCommands or CopyCommands of several recordings checks them all and makes room for all of them before copying any", "=0 (or false, off, no, empty; any other value is on) copies them one at a time, the segment growing for each that does not fit, as before. Read once, at the first such call.")L6 (minor): The row promises that an empty value disables the switch. On Windows, the file loader passes NAME= to _putenv, which removes the variable, so an empty HOS_NVN_CALL_RESERVE entry in longshot_env.txt leaves batching enabled. Document that case and give =0 as the portable spelling. Also describe the first value as cached, since simultaneous first callers can each read the environment before one publishes.
@ -1823,2 +1855,4 @@}}NV(nvnCommandBufferCallCommands) {const uint64_t *h = (const uint64_t *)PN(2, 8ull * (uint32_t)I(1));L5 (minor): PN checks the reserved guest window. A positive count with a null array still reaches h[0], and a list crossing into an unmapped region can pass PN and fault during the scan. This is inherited at these entry points. Share argument validation between both wrappers, handle zero count before pointer translation, and reject invalid counts, missing arrays and spans outside mapped guest memory through the NVN diagnostic.
@ -1823,0 +1838,4 @@return on;}static void inline_recordings(Ctx *c, nvn_cmd *o, const uint64_t *h, int n, const char *how) {if (n > 1 && call_reserve_on()) {L11 (minor): The malloc-backed fixture counts requests and cannot show whether batching helps in play. Run the base, head with the switch off and head with it unset on the same builds and settings, with warmed interleaved repeats in Kokiri Forest and a heavy area such as Castle Town Market. Report average FPS, 1% lows, median and p99 frame times, and peak host memory. Complete the own-PC game run and Tier 1 Windows, Linux and Deck checks before merge.
@ -1823,0 +1840,4 @@static void inline_recordings(Ctx *c, nvn_cmd *o, const uint64_t *h, int n, const char *how) {if (n > 1 && call_reserve_on()) {size_t all = 0;for (int i = 0; i < n; i++) check_handle(h[i]), all += called_size(h[i]);L3: The new batch total is unchecked, and cmd_reserve_rec adds used and OP_RESERVE and doubles cap unchecked. A list can repeat the same live large recording, so total bytes can exceed what a host segment can represent even when the source recording and array each fit. The sum can wrap or capacity can double through zero and loop forever before allocation. Check accumulation, reserve padding and capacity growth against a representable allocation limit, then fail through the normal fatal path. Cover the limit in the fixture with synthetic sizes.
@ -1823,0 +1841,4 @@if (n > 1 && call_reserve_on()) {size_t all = 0;for (int i = 0; i < n; i++) check_handle(h[i]), all += called_size(h[i]);if (all) cmd_reserve_rec(cmd_host(o), all);L2: A live-set hit does not pin the recording. AddControlMemory or the overwrite sweep can retire an early handle while this call validates the rest or waits in reserve. free_dead_copies waits for replay submits, which does not protect this CPU copy. The second pass can then read a freed or reused prefix. The old path already had a shorter check-to-copy window. Hold a lifetime reference from validation through memcpy, with retirement deferring reclamation until that reference is released. Keep allocation retries outside copy_lock.
@ -1823,0 +1843,4 @@for (int i = 0; i < n; i++) check_handle(h[i]), all += called_size(h[i]);if (all) cmd_reserve_rec(cmd_host(o), all);for (int i = 0; i < n; i++) {if (nwatch_handles) watch_handle_called(c, h[i], how);L4 (minor): The extracted watch path carries forward a shared-state race. EndRecording increments nwatch_handles while CallCommands and CopyCommands read it and scan watch_handles. Two writers that match watch_draw_cmd can also race through the 16-entry limit. With HOS_NVN_WATCH_DRAW enabled, synchronize the pending buffer and table update, publish initialized entries before the count, and read a stable snapshot before logging.
@ -1823,0 +1844,4 @@if (all) cmd_reserve_rec(cmd_host(o), all);for (int i = 0; i < n; i++) {if (nwatch_handles) watch_handle_called(c, h[i], how);inline_recording(o, h[i], called_size(h[i]));L1: The batch copy re-reads the guest array after validation and reserve. If a slot changes while the host allocates, called_size can follow the replacement without checking it. The fallback also reloads h[i] after check_handle, where main passed one value into inline_recording. Capture each handle once and use the captured handle and size for the copy. A bounded snapshot with the original one-at-a-time path for larger lists would keep temporary storage predictable.
@ -0,0 +121,4 @@int main(int argc, char **argv) {if (argc != 3) return 1;test_reserve = atoi(argv[1]);read_once(call_reserve_on, "HOS_NVN_CALL_RESERVE", test_reserve);L8 (minor): The fixture primes the switch directly before the first NVN call and only uses live handles. It would miss a single-handle call caching the answer early or the batch validation being removed. Drive first use through both entry points in fresh children, exercise invalid-handle rejection with a bad later handle, and cover simultaneous first callers. Add the advertised false and empty cases where the runtime preserves them.
@ -0,0 +132,4 @@for (int k = 0; k < recordings; k++) {const int which = (int)(rnd() % NCMD);nvn_cmd *o = &cmds[which];if (rnd() % 100 == 0) /* (initialized anew: a new slot, a new segment from 64 KiB; the old one is left) */L9 (minor): The fixture simulates reinitialization by zeroing the object, orphaning its slot and its potentially multi-megabyte segment. Real Initialize releases both. This makes the growth counts depend on leaked segments and increases memory use on small CI workers. Exercise the real release and initialization path and free surviving fixture allocations at teardown.
@ -0,0 +213,4 @@def compiler(given):"""--cc, else $CC, else the configured llvm-mingw's clang (LONGSHOT_MINGW, Windows: run_all.py sets it to theclone's folder), else clang, gcc or cc on PATH"""for c in (given, os.environ.get("CC")):L10 (minor): The compiler picker treats CC as a single filename. CC='ccache gcc' fails when subprocess tries to execute that literal name. A direct Windows invocation also misses the clone's llvm-mingw unless the runner has populated LONGSHOT_MINGW. Support compiler command arguments while preserving explicit executable paths with spaces, and try the clone-local toolchain as the runner does.
@ -0,0 +260,4 @@if len(a) != 3000 or multi < 1000:print("FAIL: %d recordings, %d calls of several" % (len(a), multi))sys.exit(1)if gets_on >= gets_off:L7 (minor): The growth assertion pools both entry points, and both sides share the copy helper. CopyCommands can fall back to the old growth pattern while CallCommands satisfies the aggregate. Dropping the same record on both sides can also leave their hashes equal. Add a small deterministic case per API that forces two old growths and one batched growth, and assert independently constructed bytes and memory counts.
15dbbfd830eac243608fWIP: perf(nvn): a call of several recordings makes room for all of them at once (HOS_NVN_CALL_RESERVE=0 to disable)to WIP: perf(nvn): a call of several recordings makes room for all of them at once (HOS_NVN_CALL_RESERVE=1 to try it)Thank you for the review (#issuecomment-64237). Pushed
eac24360, rebased on main @7c23d2be(main has since added only pipeline-state lists, #2041) (the branch's own commit unchanged by the rebase,git range-diff); test commit2c924d1a(its new checks fail on the branch's earlier code: queue job fb-2023-5; its cases one by one on that code in fb-2023-3), fixeac24360. All checks named below ran in queue jobs on this PC (fb-2023-1, fb-2023-3, fb-2023-5); nothing has run in the game.Default: there is no measurement in play, so
HOS_NVN_CALL_RESERVEis now off by default (kind attempt): unset is main's one-at-a-time copy,=1turns the batch on. The in-game A/B that could turn it on is in Still to test. The title says so.eac24360: a call of 2 to 64 handles copies the guest's array once into a local snapshot with each handle's size, checks those and copies those; a larger call goes one at a time, and that loop reads each handle once and passes the same value to the watch, the check and the copy. The fixture'spincase changes the game's array to another live recording while the call makes its room: the call copies the recordings it checked (bytes compared with the records as written), for CallCommands and CopyCommands.eac24360: the call counts itself incalls_copyingfrom before its first check to after its last copy, andfree_dead_copiesfrees nothing while that count is not zero (seq_cst fences on both sides, so either the call's check sees the release or the free sees the call); the next AddControlMemory or sweep frees what it left. The allocation stays outsidecopy_lock, which the call does not take. Thepincase releases the called recordings (their control memory added again) and runs another AddControlMemory with the replay past them while the call makes its room: nothing is freed during the call, the bytes are the recordings', and the next AddControlMemory frees both. On the branch's code that case fails. The one-at-a-time path (the default) is main's, with main's shorter window; I left it as it is.eac24360:CMD_SEG_MAX(4 GiB, a power of two as the capacities are): the call's sum is checked before each add, andcmd_reserve_recstops past it before its sum or its doubling can wrap, both throughdie(the NVN diagnostic). The fixture'shugecase calls a live handle claiming 2^63 bytes alone, twice and after a small recording, on and off: each stops with that message (on the branch's code, two of them loop forever doubling through zero and the others fail allocating).eac24360: the watched draw's command buffer is taken by one EndRecording with a compare-exchange, its slot claimed with an atomic add (past 16, none), the handle stored with a release store; the calls read each of the 16 slots once with an acquire load and skip empty ones. No test of its own: it is a race in a diagnostic, checked by reading; the fixture now runs the real watch code on every call.eac24360for both wrappers in one place (call_handles): a count of 0 reads nothing, a negative count or a count with no array stops with the diagnostic naming the call; the array must lie in the guest window as before (gw). The fixture'sargscase checks all three for both calls (a count with no array read address 0 before). I did not add a mapped-memory check of the array: the only one,hos_mem_mapped, takeshos_mem.c's lock, which would put a lock on every call on the default path; a guest array outside mapped memory faults as it does for every other guest pointer the NVN layer reads.eac24360: off unless set,=0off everywhere, an empty value inlongshot_env.txton Windows removes the variable (off, as unset), and the first value described as cached, with simultaneous first callers each possibly reading the variable and all keeping the first answer stored.2c924d1a: thefirstcase runs for CallCommands and for CopyCommands on its own: three 48 KiB recordings into a 64 KiB segment grow it twice one at a time and once with the room first, and the caller's bytes and command memory counts are compared with the records as the fixture wrote them and their sizes, not with another run.2c924d1a: no case primes the switch; infirsta call of one recording comes first and the variable is set only after it, so a single-handle call that read it would keep the other answer; the 3,000-recording run's first read is its first call of several. The realcheck_handleand live-handle set are cut from the source:badcalls two live handles and then one whose prefix is right but that EndRecording never made: on, the call stops with nothing copied; off, after the first two, as on main.race(a separate build ofcall_reserve_onwith its reader replaced) has eight threads come first together, the reader answering each differently: all keep one answer. False and empty are among the cases, each with the child's environment set explicitly (empty reads as off whether the runtime keeps it or not).2c924d1a: the fixture runs the realnvnCommandBufferInitialize(its segment and slot given back) andFinalize, and frees every command buffer, kept recording and fixture block at the end.2c924d1a:--ccandCCgo throughtests/compiler_command.py'sparse_compiler(a path with spaces kept, a command with arguments split), thenLONGSHOT_MINGW's clang, then the clone'sllvm-mingwasrun_all.pyfinds it, then clang, gcc or cc. It ran with no--ccand noCCin fb-2023-3, fb-2023-5.eac24360: the recordings' log line counts the segments' growths, the bytes those growths copied and the calls given their room at once (thefirstcase checks the counts against its own), and the batch copies with the sizes it checked into the room made once, without a reserve per handle. The A/B is pending, for the owner: main, this PR unset and with=1, warmed and interleaved, in Kokiri Forest and Castle Town Market, with average fps, 1% lows, median and p99 frame times, peak host memory and the log line's counts, and the Tier 1 runs; Still to test lists them.7c23d2be, which Tested names; main has since added only contributed pipeline-state lists (#2041), so the current-main box stays unticked. Tested lists what ran here: the PR's own checks and every check--changed 7c23d2bepicks, with the failures that fail on main too. The whole suite and lint did not run on this PC (pre-commit and ruff are not installed here); they are in Still to test, and themise run testbox stays unticked.@Beanstalk This adds HOS_NVN_CALL_RESERVE, off by default: with HOS_NVN_CALL_RESERVE=1, NVN CallCommands and CopyCommands of several recordings reserve their room once (host/nvn_native.c); unset, main's way. It has not run in the game on these PCs yet. Please play Hyrule Field for three minutes, the PR against main on the same PC, on the PR's side with HOS_NVN_CALL_RESERVE=1 and with it unset, with a picture compared with main's, on Linux with NVIDIA, Linux with AMD (RADV), Windows with Intel and the Steam Deck. The same picture, no crash, no FATAL line and no "not a live recording" line either way; set, fewer segment growths and fewer MB copied in the recordings' log line than unset, and frame time p99 equal to unset or better. Please report that line's counts.
@siantm only members of
BigBeanscan start the farm.One of them can approve this request by reacting 👍 to it or to this comment.This request was foreac2436, and the PR has changed since (39fe40d), so a 👍 no longer approves it. Comment@Beanstalkagain to ask for the new commit.Risks now says plainly that, with HOS_NVN_CALL_RESERVE=1, released recording copies held while calls of several recordings copy are not bounded at
eac24360(no cap, no wait, no point each frame where the count is zero), with the lines and the bound to add before it could be turned on; Still to test has the Market run that measures the held memory and the wait. No code change, no push.Verdict: Request changes. The revision closes BeanBot's use-after-free (L2), but it closes it with a global gate on
free_dead_copiesthat can hold released recording copies without bound while the switch is on, as Risks says itself. A simpler order needs no new lifetime mechanism: check and size the handles, make the room once, then check each handle again at its copy, as main does. That should change before the farm or the A/B measure this code.For a player, with
HOS_NVN_CALL_RESERVE=1a CallCommands or CopyCommands of 2 to 64 recordings grows the caller's segment once instead of once per recording that doesn't fit. Fewer reallocations and copies could mean a little less CPU on the recording threads, but nothing is measured yet, and the earlierHOS_NVN_SEG_PEAK(of which this was half) and #1812 measured no change in play. Unset, it is main's path plus hardening that regresses nothing:call_handlesstops on a null array or a negative count instead of reading address 0,CMD_SEG_MAXstops a wrapped size, the watch is atomic, and the log line has three more counts.Reviewed:
eac24360against7c23d2be(the merge base with main):host/nvn_native.c(the whole diff, and the code it relies on:check_handle, the live-handle set,release_copies,sweep_overwritten_copies,free_dead_copies,dead_copy_add,cmd_reserve_rec,gw/PN, the watch's setter inwatch_draw),gpu/vk/switches.def,tests/test_nvn_call_reserve.pyin full andtests/test_recording_log_handoff.py. BeanBot's points were checked against the code, not only the reply. Nothing run (a code review).Fixed in this review: nothing.
Checked and fine:
hs), then checks, sizes and copies those values. The one-at-a-time loop readsh[i]once and passes it to the watch, the check and the copy.free_dead_copiesfrees only under the exclusive lock. With the two seq_cst fences, either the call's check sees the removal and stops, or the free seescalls_copyingand skips. Thepincase fails if thecalls_copyingtest is taken out (the fixture's replay is always past the release).cmd_reserve_rec,usedstays at or belowCMD_SEG_MAX - OP_RESERVE(cap is a power of two at mostCMD_SEG_MAX, and the writes stay within what was reserved), so the new bound can't underflow and the doubling can't wrap.firstcases with the expected bytes built separately, a first read through a one-handle call,badwith a prefix that EndRecording never made, the real Initialize and Finalize, andparse_compiler(it is on main).mfenceinfree_dead_copieswhen something is due, under a lock it already holds. That is negligible.CALL_AT_ONCEputs 1 KiB on the stack, and a larger call falls back to main's loop. The test writes only to its own temporary folder and downloads nothing.Blocking (to change before merge)
host/nvn_native.c:1586(free_dead_copies) and:1889/:1904(inline_recordings): every free is skipped while any thread is inside a batched call. Nothing makes that count reach zero at a free: several job threads calling recordings back to back, as in the Market, can keep it above zero at each AddControlMemory and sweep. The held copies then grow with what the game releases, and on main they go once the replay passes them. Risks names this, and the "Still to test" Market run would only measure it. The epoch bound in Risks is one way to fix it. A simpler one removes the mechanism altogether:check_handle,called_sizeand the sum, thencmd_reserve_rec(r, all)once;check_handleagain, theninline_recording(itscmd_reserve_recreturns at once when the room is there) and the copy.The check-to-copy window is then main's, without even the allocation in it. A handle the game released meanwhile stops the call as main would, and a bad handle still stops the call before anything is copied.
calls_copying, the fences and the change tofree_dead_copiesall go. The second check is one lock-free probe per handle, small next to the memcpy. Thepincase would then check that a handle released during the room-making stops the call (or still copies its live replacement), and that the frees aren't held.Suggestions (the author may take or leave)
host/nvn_native.c:1586: ifcalls_copyingstays, its load wants__ATOMIC_ACQUIRE(or an acquire fence after it). The seq_cst fence comes before the load, so in C11 terms a call's memcpy reads are not ordered before thepool_putthat follows a read of 0. x86 hides this, but the compiler is free to move the later code.host/nvn_native.c:2323:watch_draw_cmd = P(0)is still a plain store, while the readers now use atomics. An__atomic_store_n(..., __ATOMIC_RELAXED)would make the L4 fix whole. It is a diagnostic only.Questions
HOS_NVN_SEG_PEAKshowing no difference, what segment-growth rate in a real Market call would make this worth a switch? The log line's new counts, from one own-PC run with it on, would answer that before a farm run.Testing: the author ran the PR's own checks and the
--changedselection on Windows (i7-9700, RTX 4060). The 9 failures also fail on main. It has not run in the game anywhere: AGENTS.md wants the author's own in-game run first, and the Test Farm is for hardware the author doesn't have. The @Beanstalk request (Hyrule Field, Linux NVIDIA and AMD, Windows Intel, Steam Deck) should wait for the change above, since it would measure code that changes. When it runs, it should also report the log line's live copies (MB) and peak host memory, on and off: that is the regression a batched call could cause. It should include Castle Town Market, where these calls are heaviest, and run more than one interleaved pass a side, so "p99 equal or better" has a spread to be judged against. CI is still pending.Overlaps and merge order:
release_copies,free_dead_copiesand the sweep. Blocking 1's way leavesfree_dead_copiesalone and avoids that clash.cmd_reserve_recinto an inline fast path and a slow path, and theCMD_SEG_MAXcheck belongs in its slow path. Whichever merges second rebases onto the other.switches.defrow is the usual textual conflict.@ -1568,2 +1583,4 @@const uint64_t done = rx_nvn_replayed();if (done < dead_first) return;__atomic_thread_fence(__ATOMIC_SEQ_CST);if (__atomic_load_n(&calls_copying, __ATOMIC_RELAXED)) return;Blocking 1: while any batched call copies, every free is skipped, and nothing brings the count to zero at a free, so the held copies can grow without bound with the switch on. Simpler: reserve once, then check each handle again at its copy, as main does; then calls_copying and this check go. If it stays, this load wants __ATOMIC_ACQUIRE: the fence before it doesn't order the call's memcpy before the pool_put.
@ -1832,0 +1886,4 @@size_t size[CALL_AT_ONCE], all = 0;memcpy(hs, h, sizeof *hs * (size_t)n);InterlockedIncrement64(&calls_reserved);__atomic_fetch_add(&calls_copying, 1, __ATOMIC_RELAXED);Blocking 1: phase 2 can re-run check_handle on each snapshot handle before its copy (inline_recording's cmd_reserve_rec returns at once when the room is there). That keeps main's check-to-copy window without the gate on free_dead_copies.
eac243608f39fe40deffWIP: perf(nvn): a call of several recordings makes room for all of them at once (HOS_NVN_CALL_RESERVE=1 to try it)to WIP: perf(nvn): a call of several recordings makes room for all of them at once (HOS_NVN_CALL_RESERVE=0 to disable)Thank you for the review (#2023 (comment)). Pushed
39fe40de, rebased on main @9dd41326(fromb62932a9;git range-diff"=" for every commit, main's move touched none of its files): the test commiteb4d64f6(fails on the code before the fix: the switch's first read answers 0 where 1 is expected, and the run stops there) and the fix39fe40de. What ran is in the description's Tested (queue jobs fb-2023-l9 and fb-2023-h9); nothing has run in the game.39fe40de. Phase 1 snapshots the array, checks and sizes each handle and makes the room once; phase 2 checks each snapshot handle again just before its copy and copies it withinline_recording(its reserve returns at once).calls_copying, the fences and the change tofree_dead_copiesare gone, sofree_dead_copiesis main's again. Thepincase (eb4d64f6) releases the called recordings while the call makes its room: the AddControlMemory that follows frees them (nothing holds them), and the call stops at its second check with nothing copied, as main would; the array changed to another live recording during the room is still copied as checked.calls_copyingload: moot, the count is gone.watch_draw_cmd = P(0): done in39fe40de:__atomic_store_n(..., __ATOMIC_RELAXED).HOS_NVN_CALL_RESERVEis on again (a kill switch,=0is main's one at a time), the value this change proposes: docs/dev/standards.md (Switches) has a switch ship at its intended value from the first push, never off just because it is unmeasured. Measurements says "not measured in play yet"; if the A/B goes against it, it is turned off or dropped before this leaves WIP. The title says=0 to disable.=0, which is in Still to test with the live copies (MB) and peak host memory; nothing was run in the game on this PC.=0against main, with live copies (MB) and peak host memory.free_dead_copiesleft as main has it, #2022 and #2025 no longer clash with this here; with #2050 whichever merges second rebases (theCMD_SEG_MAXcheck goes in its slow path).@Beanstalk This makes NVN CallCommands and CopyCommands of several recordings reserve their room once (host/nvn_native.c), on by default (HOS_NVN_CALL_RESERVE); HOS_NVN_CALL_RESERVE=0 turns it off. This head is on main
9dd41326: please compare with main at that merge base. Please start from the market-entrance save and play Castle Town Market, the heaviest scene for this, for three minutes, the PR against main on the same PC, on the PR's side with the switch unset and with HOS_NVN_CALL_RESERVE=0, with a picture compared with main's, on Linux with NVIDIA, Linux with AMD (RADV), Windows with Intel and the Steam Deck. The same picture, no crash, no FATAL line and no "not a live recording" line; unset, fewer segment growths and fewer MB copied in the recordings' log line than with it off, live copies (MB) and peak process memory no higher than with it off, and frame time p99 equal to main's or better. Please report that line.@siantm only members of
BigBeanscan start the farm. One of them can approve this request by reacting 👍 to it or to this comment.Description: Risks now says that this conflicts with #1780 in the end-of-recording log line of
nvnCommandBufferEndRecording(host/nvn_native.c), the overlap BeanBot pointed to (#issuecomment-64085), and nowhere else; whichever is merged first goes first and the other rebases onto it. No push.@Beanstalk One correction to my request 66182 above, for its picture point: please take each picture 5 s (300 frames at 60 fps) after the first frame whose picture is not a single uniform colour, with no input in between, and take the main-against-itself picture from the same point. A picture taken during the load's fade-in from black is not comparable: run 70269 on #2156 caught the fade in 3 of 4 starts.
@siantm only members of
BigBeanscan start the farm. One of them can approve this request by reacting 👍 to it or to this comment.@Beanstalk This replaces my request 66182 on this head and the corrections under it, in a form the farm can run: it cannot time a picture from the first frame that is not a uniform colour (its answer on #2131), so each picture here follows a fixed wait after the map event. This makes NVN CallCommands and CopyCommands of several recordings reserve their room once (host/nvn_native.c). Please start from the market-entrance save and take the picture 10 s (600 frames at 60 fps) after the map event that ends the load, a fixed wait with no input in between (the farm cannot time it from the first frame that is not a uniform colour), with a main-against-itself picture on the same PC from the same point; then, for frame times only, play Castle Town Market, the heaviest scene for this, for three minutes; at least two starts a side, interleaved, the PR against main on the same PC, on the PR's side unset (the default, on) and with HOS_NVN_CALL_RESERVE=0 (off), on Linux with an RTX 3080 Ti, Linux with an RX 6600 (RADV), Windows with an Arc B580 and the Steam Deck. The same picture as main within main's own difference from itself; with it unset, frame time p99 equal to main's or better, within the run-to-run spread, and equal to HOS_NVN_CALL_RESERVE=0 or better. The log must have no FATAL line and no "not a live recording" line, and no run may crash. Unset, the recordings' log line must show fewer segment growths and fewer MB copied than with HOS_NVN_CALL_RESERVE=0, and live copies (MB) and peak process memory no higher; please report that line.
@siantm only members of
BigBeanscan start the farm. One of them can approve this request by reacting 👍 to it or to this comment.@dyst the in-game run your review (65678) found missing is in Measurements. It was one sitting on this PC:
HOS_NVN_CALL_RESERVE=0against unset in one runtime of39fe40de, Kokiri Forest CPU-paced, 8 runs a side interleaved. Nonot a live recordingline, FATAL or device lost came in any run.One sitting, so not called a gain yet; a second sitting is in Still to test.
View command line instructions
Checkout
From your project repository, check out a new branch and test the changes.