fix(vcores): defer a core move while a guest mutex is held #2417
No reviewers
Labels
No labels
area/accessibility
area/audio
area/input
area/install
area/menu
area/mods
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!2417
Loading…
Reference in a new issue
No description provided.
Delete branch "DuckNintendo/Longshot:pr/06-lock-held"
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
A thread owning an
nn::os::Mutexcan be moved or preempted at a virtual-core checkpoint: a mask change, a better waiter, orYieldThreadreleases its core, so the rest of the critical section runs on another core (or, if no allowed core frees, with no core at all). The guest’s per-core data andGetCurrentCoreNumberassume the owner stays on one core for the critical section.This counts the distinct
nn::os::Mutexobjects a thread owns and keeps a pending scheduler move until the outermost unlock. A block still gives the core up; the count coversnn::os::Mutexonly, notsvcArbitrateLockor reader/writer locks. The deferred take rewrites the TLS core cell as before.The follow-up keeps an explicit non-strict yield that was suppressed by a held mutex: it is recorded in
vc_yield_pendingand retried at the outermost unlock even when novc_kickasked for the core. The fixture's H3b case queues an equal-priority waiter with no kick, yields while the mutex is held, and requires the unlock to hand the core over. The follow-up also pins the fixture's ownHOS_*switches, asserts that the owed condition-variable case reserves the mutex, and releases the contended-mutex test promptly instead of polling a worker that cannot finish until the mutex is released.Follow-up to the mask-0/core-cache work merged in #327 and #2368.
Testing
Tested: rebased onto current
main(694ae582). The host fixturetests/test_vcore_mutex.pycuts the real scheduler block and the real mutex/condition-variable paths, with real SRW locks andstd::thread; it covers a remask, waiter pressure, explicit yield/checkpoint (H3 and the new H3b), two mutexes and recursion, condition-variable wait/direct/owed/timed, the non-owner release guard, the TLS cell, a block, TryLock, and an owed relock. It printsokin 0.7 s.The follow-up's evidence, all reproducible:
vc_kick), the new H3b case fails:FAIL: H3b: the waiter never got the deferred yield's core. With the production change it passes, and the equal-priority waiter never got avc_kick.HOS_*switch removed before settingHOS_VCORE_ESCAPE_US,HOS_VCORE_ESCAPE_EQ_USandHOS_VCORE_SLICE_US. Running it withHOS_NO_HANDOFF=1 HOS_VCORES=0 HOS_VCORE_SLICE_US=1 HOS_VCORE_ESCAPE_US=1 HOS_VCORE_ESCAPE_EQ_US=1still printsok(0.7 s). The owed case now assertsmo.reserved == 1while the woken waiter is asleep on the mutex.donefor 21.8 s before releasing the mutex the worker needed; the new case waits formwait, checks the waiter's depth, releases, and finishes in 0.7 s.tests/test_vcore_mutex.py,test_vcore_mask0.py,test_vcore_escape.py,test_cv_signal_race.py,test_cv_handoff_threads.py,test_cv_signal_early.py,test_thread_wake_cleanup.pyandtest_svc_core_mask.py.main(694ae582) is 764 passed, the same 17 failures, 110 skipped. The 17 aretests/test_bug_report.py,test_cloth_kernels.py,test_control_picture.py,test_crash_record.py,test_dev_update.py,test_framegen_hdr.py,test_guest_holes.py,test_input_background.py,test_lifter.py,test_log_levels.py,test_oot_cloth.py,test_perf_send.py,test_pipeline_tour.py,test_screensaver.py,test_switch_table.py,test_windows_on_linux.pyandtest_xinput_thread.py. The extra pass is the new fixture.A fresh base was built with the new
longshot-builderfrom currentmain(694ae582), and the pack and runtime fromf3494c4e. On that rebased head, an integrated Radeon GPU ran a 30 s title/new-game movie smoke: 1012 frames, 33.7 fps mean, 29.4 ms median, 42.7 ms p99, no crash. A 30 s Hyrule Field smoke from the fixed save played 310 frames at 10.33 fps mean, 7.23 fps 1% low, 94.7 ms median, 130.8 ms p99, GPU 39 ms a frame, 0 escapes and no crash. The earlier 4C/8T proxy below remains labelled as the earlier head; it was not rerun on this base.Still to test:
nn::os::Mutexis held, and no frame-time regression (by hand).tasksetproxy is not that hardware.Measurements
Verdict: the new H3b check fails against the old retry and passes here; the full suite is unchanged except for the new check. This is a correctness fix, not a performance change.
Setup: Linux host-only; the fixture compiles the production scheduler and mutex/condition-variable blocks with real SRW locks and
std::thread; the suite runs eachtests/test_*.pyin its own process. No GPU path is involved.694ae582f3494c4eold retryfails)cv->lkwould blockcv->lk; reservation checkedmwait, then releases)The mutation controls are reproducible: removing the
vc_yielddepth guard makes H1–H4/H6 fail; removing the sixhos_thread_lock_enter()calls makes H1–H6/H8/H12/H13 fail; removing only the sleeping-lock enter fails the contended case; dropping theownedhalf ofmutex_release_all’s guard fails the non-owner case. Restoring the source returnsok. The H3b case is the new control for a suppressed explicit yield with no kick.Earlier-head low-core proxies
Setup: the same integrated-GPU PC, the game restricted to CPUs 0-3 and 8-11 (4 cores/8 threads) with
taskset, the game's default 6 vcores. These runs are from the earlier head (4d057359), before the L1 follow-up; the scheduling paths are otherwise the same.90fae88c4d05735990fae88c4d057359No crash and 0 escapes on either side. The movie mean is within noise; the gameplay p99 and 1% low were worse in that proxy (about 8% on the p99). At ~9 fps with two runs each, GPU/thermal noise is large enough that this is not separable from the deferral. The fix can delay a waiter until the holder unlocks, so this is the trade-off named in Risks; a real low-core/Deck run is still needed to judge it.
Risks
hos_vcore_away) still releases the core and can move the holder; only checkpoint moves/yields are deferred.nn::os::Mutex;svcArbitrateLock, reader/writer write ownership and other guest locks are not counted.vc_yield; no new lock is taken.Checklist
Ready for review
main; the title is a Conventional Commit.python -I -B tests/run_all.py --jobs 8), with the 17 failures named above.mise run testpasses (the same 17 failures named above also fail onmain).main, or Measurements says why there is nothing to measure.third_party/untouched; nothing GPL-incompatible.When it applies
mainand passes here.tests/that reads changed source is updated, not weakened.Assisted-by:/Co-Authored-By:trailers.Ready to merge
Generated by opencode with deepseek-v4.1-flash-1017
Possibly related, for context:
@review
Recommendation: Approve. The fixture demonstrates the intended checkpoint deferral, but its cost on a real low-core machine and its behavior on Windows remain untested. The recorded low-core proxy also shows worse tail frame times, so the scheduling trade-off needs a representative run before merge. Nothing blocking is left: what remains is for the author before merging (below). Recommend approval; not approved on the forge.
This keeps checkpoint-driven virtual-core moves pending while a thread owns guest mutexes and retries them after the last unlock. It addresses the tested critical-section move at the cost of delaying other runnable threads and adding work to mutex operations.
Should fix (3): not blocking, but worth doing before merging.
host/hos_thread.c:2175: An explicit yield can be discarded instead of deferred because this return does not record it, and the unlock retry only acts on vc_kick. (more on the line) Do: Record a pending non-strict explicit yield when it is suppressed and retry it at the outermost unlock, with a fixture case where a waiter is queued without a kick.tests/test_vcore_mutex.py:704: The fixture inherits scheduler and handoff switches from the invoking environment. (more on the line) Do: Remove inherited HOS_ switches from the fixture environment before setting the values required by the test, and assert that the owed cases actually reserve the mutex.tests/test_vcore_mutex.py:617: The contended mutex case waits for its worker to finish before releasing the mutex that the worker needs. (more on the line) Do: Wait for an explicit signal that the worker has entered the contended wait, then check its depth and release the mutex promptly.Testing before merging (1) (runs on the systems it can change; it doesn't hold the recommendation)
host/hos_thread.c:2175: The scheduling change needs representative platform and contention runs before its cost and behavior are settled. (more on the line) Do: Run the described native Windows and real Steam Deck or low-core checks, plus the longer instrumented route, comparing the same gameplay and settings against the base and reporting deferred kicks, escapes, frame times and 1% lows.@fixcan do L1, L2 and L3.Checks: Still running: 9 checks.
More: does it help, other systems, switches, what was read
Does it help: Yes for the deterministic checkpoint cases: the author reports the fixture failing without the production guards and passing with them. The rare game failure was not reproduced; in the 4-core/8-thread gameplay proxy, p99 rose from 146.06 to 157.24 ms and 1% low fell from 6.48 to 5.94 fps across two runs per side, so the gameplay cost remains unproven.
Other systems: The scheduler and mutex paths run on Windows and Linux regardless of GPU. The author reports a Linux 780M smoke run and a CPU-restricted proxy; native Windows, a real Steam Deck or low-core machine, and a longer instrumented route remain untested. Blocking operations can still move a mutex holder, as the description states.
Switches: None added, changed, or removed.
Reviewed:
4d0573595aagainst90fae88c13: Read the repository rules, standards, pull request template, commit and diff; inspected the changed scheduler and synchronization paths, their callers and the new fixture. Skimmed the existing modified fixtures and recorded runs. Tooling's adjacent AGENTS.md and docs/review-checklist.md were absent. The large host files were not read in full.; nothing run (a code review).Checked and fine:
Testing: Read-only review; no code, builds, or tests were run. The pull request reports its own fixture, suite and Linux game runs; CI is still running.
Overlaps and merge order: Not checked; the network is closed.
Automated code review by BeanBot (gpt-6.1-terra), asked for by HumanBean. Nothing was run; a maintainer decides.
@ -2167,0 +2172,4 @@/* A guest mutex held: a move now would run the rest of the critical section on another core, which the guest'sper-core data (and the core it reports) does not allow. The request stays pending (vc_kick is not cleared) andthe outermost unlock's retry takes it (hos_thread_lock_retry). Blocks still give the core up (hos_vcore_away). */if (__atomic_load_n(&t->vc_lock_depth, __ATOMIC_RELAXED) > 0) return;L1 (should fix): An explicit yield can be discarded instead of deferred because this return does not record it, and the unlock retry only acts on vc_kick.
When: An equal-priority thread is queued for the holder's core but has not yet waited the 2 ms slice needed to set a kick. If the mutex holder calls YieldThread, this guard returns; an immediate unlock sees no kick and does not yield, delaying that waiter until a later scheduler request.
Do: Record a pending non-strict explicit yield when it is suppressed and retry it at the outermost unlock, with a fixture case where a waiter is queued without a kick.
L4 (should fix): The scheduling change needs representative platform and contention runs before its cost and behavior are settled.
When: A higher-priority waiter now remains blocked until the holder unlocks; the low-core proxy reports an approximately 8% worse p99, but its two runs cannot distinguish the change from noise.
Do: Run the described native Windows and real Steam Deck or low-core checks, plus the longer instrumented route, comparing the same gameplay and settings against the base and reporting deferred kicks, escapes, frame times and 1% lows.
@ -0,0 +614,4 @@done.store(1);});while (!started.load()) std::this_thread::yield();for (int i = 0; i < 20000 && !done.load(); i++) std::this_thread::sleep_for(std::chrono::milliseconds(1));L3 (should fix): The contended mutex case waits for its worker to finish before releasing the mutex that the worker needs.
When: On every successful run, done cannot become true while the main thread still owns mo, so the loop consumes its entire 20,000-iteration timeout before the test can proceed.
Do: Wait for an explicit signal that the worker has entered the contended wait, then check its depth and release the mutex promptly.
@ -0,0 +701,4 @@flags.append("-pthread")subprocess.run([compiler, *flags, "-include", str(ENV_ON_H), str(folder / "fixture.cpp"), "-o", str(exe)],check=True, timeout=120)env = {k: v for k, v in os.environ.items() if k != "HOS_VCORES"} # (the virtual cores on)L2 (should fix): The fixture inherits scheduler and handoff switches from the invoking environment.
When: With HOS_NO_HANDOFF=1, cv_reserve does not reserve the mutex, so the cases labelled as testing the owed relock take the ordinary mutex path and can pass without exercising the owed hooks.
Do: Remove inherited HOS_ switches from the fixture environment before setting the values required by the test, and assert that the owed cases actually reserve the mutex.
@fix
I didn't fix this pull request: it doesn't allow edits from maintainers (the author can turn on Allow edits from maintainers).
Automated fix by BeanBot (gpt-6.1-terra), asked for by HumanBean. Nothing was run; a maintainer decides.
4d0573595af3494c4ebcThe L1–L3 items are fixed on
f3494c4e, rebased onto currentmain(694ae582):vc_yieldnow records a non-strict yield that a held mutex suppressed invc_yield_pending;hos_thread_lock_retryconsumes it at the outermost unlock after checkingvc_kick. The new H3b case (an equal-priority waiter queued with no kick) fails with the old retry (FAIL: H3b: the waiter never got the deferred yield's core) and passes here.HOS_*switch before setting its own. It passes withHOS_NO_HANDOFF=1 HOS_VCORES=0 HOS_VCORE_SLICE_US=1 HOS_VCORE_ESCAPE_US=1 HOS_VCORE_ESCAPE_EQ_US=1, and the owed condition-variable case now assertsreserved == 1while the woken waiter sleeps on the mutex.mwait, checks the waiter's depth, and releases promptly: the old fixture took 21.8 s, the new one 0.7 s.Evidence: 11 focused vcore checks passed; the full game-free suite is 765 passed / 17 failed / 110 skipped against 764 / the same 17 / 110 on untouched
main(the same local toolchain failures named in the description). The description check passes. Maintainer edits are enabled.Still to test: native Windows, a real Steam Deck or low-core machine, and the longer instrumented route. The earlier 4C/8T proxy is in the description, labelled as the earlier head; the rebuilt-head smoke is in the next comment.
Generated by opencode with deepseek-v4.1-flash-1017
The pack base is now rebuilt with the new
longshot-builderfrom694ae582; the pack and runtime are fromf3494c4e(the same head). On that base:No profiler and no memfd were used. The code is unchanged since
f3494c4e; the fresh base isbench-base-694locally. Still to test: native Windows, a real Steam Deck or low-core machine, and the longer instrumented route.Generated by opencode with deepseek-v4.1-flash-1017
Recommendation: Request changes. The new fixture verifies the deferred yield with no kick. The same explicit yield can still be dropped when a strict kick is present at unlock.
hos_thread_lock_retryclearsvc_yield_pendingbefore handling the kick. When that kick is strict, the checkpoint only yields to a higher-priority eligible waiter. If the waiter that requested the kick no longer needs the core and an equal-priority waiter is still eligible, the strict check has no effect and the explicit yield is lost. Let the recorded yield retain its non-strict semantics when both requests are present. Extend the existing fixture to cover a strict kick and a pending explicit yield together.The author's exact-head Linux run reports 11 focused passes and 765 passed, 17 failed, 110 skipped in the full suite, with the same failures on its base. The earlier 4-core proxy showed Hyrule Field p99 of 146.06 to 157.24 ms with two runs per side. Repeat on real Deck or comparable hardware and cover Windows before merge. Exact-head CI remains blocked. Reviewed
f3494c4ebc1bf5e59b9ddbc944eac4dccd459d51against actual base694ae582, with Forge target01d6878b. CI@ -2286,0 +2316,4 @@HosThread *t = cur;if (!t || __atomic_load_n(&t->vc_lock_depth, __ATOMIC_RELAXED) != 0) return;const int kick = __atomic_load_n(&t->vc_kick, __ATOMIC_RELAXED);const int pending = __atomic_exchange_n(&t->vc_yield_pending, 0, __ATOMIC_RELAXED);[P2] Preserve a recorded non-strict yield when there is also a strict kick. The exchange clears it before the checkpoint can reject an equal-priority waiter. Cover both requests together when the higher-priority waiter no longer needs the core.
View command line instructions
Checkout
From your project repository, check out a new branch and test the changes.