perf(posix): optimize condition variable futex wakeups and thread priorities #2487
Open
Erfboom wants to merge 3 commits from
Erfboom/perf/linux-futex-wake into main
pull from: Erfboom/perf/linux-futex-wake
merge into: MagicBeanDev:main
MagicBeanDev:main
MagicBeanDev:github/pr/2893
MagicBeanDev:github/pr/2890
MagicBeanDev:github/pr/2887
MagicBeanDev:github/pr/2878
MagicBeanDev:github/pr/2875
MagicBeanDev:github/pr/2874
MagicBeanDev:github/pr/2873
MagicBeanDev:github/pr/2871
MagicBeanDev:github/pr/2756
MagicBeanDev:github/pr/2897
MagicBeanDev:github/pr/2896
MagicBeanDev:github/pr/2718
MagicBeanDev:github/pr/2842
MagicBeanDev:github/pr/2691
MagicBeanDev:github/pr/2895
MagicBeanDev:github/pr/2743
MagicBeanDev:github/pr/2765
MagicBeanDev:github/pr/2708
MagicBeanDev:github/pr/2732
MagicBeanDev:github/pr/2755
MagicBeanDev:github/pr/2817
MagicBeanDev:github/pr/2876
MagicBeanDev:release-please--branches--main
MagicBeanDev:release-please--branches--main--release-notes
MagicBeanDev:github/pr/2778
MagicBeanDev:github/pr/2888
MagicBeanDev:github/pr/2866
MagicBeanDev:github/pr/2877
MagicBeanDev:github/pr/2800
MagicBeanDev:github/pr/2829
MagicBeanDev:github/pr/2850
MagicBeanDev:github/pr/2889
MagicBeanDev:github/pr/2882
MagicBeanDev:github/pr/2860
MagicBeanDev:github/pr/2849
MagicBeanDev:github/pr/2886
MagicBeanDev:github/pr/2794
MagicBeanDev:github/pr/2840
MagicBeanDev:github/pr/2830
MagicBeanDev:github/pr/2834
MagicBeanDev:github/pr/2719
MagicBeanDev:github/pr/2742
MagicBeanDev:github/pr/2741
MagicBeanDev:github/pr/2820
MagicBeanDev:github/pr/2771
MagicBeanDev:github/pr/2859
MagicBeanDev:github/pr/2858
MagicBeanDev:github/pr/2823
MagicBeanDev:github/pr/2757
MagicBeanDev:github/pr/2769
MagicBeanDev:github/pr/2844
MagicBeanDev:github/pr/2843
MagicBeanDev:github/pr/2673
MagicBeanDev:github/pr/2855
MagicBeanDev:github/pr/2739
MagicBeanDev:github/pr/2807
MagicBeanDev:github/pr/2851
MagicBeanDev:github/pr/2789
MagicBeanDev:github/pr/2814
MagicBeanDev:github/pr/2818
MagicBeanDev:github/pr/2774
MagicBeanDev:github/pr/2772
MagicBeanDev:github/pr/2750
MagicBeanDev:github/pr/2786
MagicBeanDev:github/pr/2785
MagicBeanDev:github/pr/2782
MagicBeanDev:github/pr/2779
MagicBeanDev:github/pr/2775
MagicBeanDev:github/pr/2706
MagicBeanDev:github/pr/2766
MagicBeanDev:github/pr/2747
MagicBeanDev:github/pr/2759
MagicBeanDev:github/pr/2745
MagicBeanDev:github/pr/2740
MagicBeanDev:github/pr/2733
MagicBeanDev:github/pr/2725
MagicBeanDev:github/pr/2727
MagicBeanDev:github/pr/2728
MagicBeanDev:github/pr/2729
MagicBeanDev:github/pr/2721
MagicBeanDev:github/pr/2722
MagicBeanDev:github/pr/2715
MagicBeanDev:github/pr/2714
MagicBeanDev:github/pr/2707
MagicBeanDev:github/pr/2703
MagicBeanDev:github/pr/2705
MagicBeanDev:github/pr/2697
MagicBeanDev:github/pr/2679
MagicBeanDev:github/pr/2676
MagicBeanDev:github/pr/2669
MagicBeanDev:docs/what-hookshot-connects-to
MagicBeanDev:fix/hdr-encode-test
MagicBeanDev:fix/main-tests
MagicBeanDev:fix/play-cache-files
MagicBeanDev:perf/game-barrier-order
MagicBeanDev:feat/heap-lazy
MagicBeanDev:feat/texture-detail
MagicBeanDev:perf/astc-opaque-bc1
MagicBeanDev:fix/fs-dir-lock
MagicBeanDev:fix/framegen-native-kept
MagicBeanDev:fix/update-no-downgrade
MagicBeanDev:port/k10-gcn-f16-mirrors
MagicBeanDev:fix/framegen-mult-cap
MagicBeanDev:chore/release-as-2.1.1
MagicBeanDev:perf/pcache-load-switch
MagicBeanDev:fix/prepare-progress-log
MagicBeanDev:fix/update-closes-stale-game
MagicBeanDev:fix/hdr-scaled-sampled
MagicBeanDev:perf/first-start-preset
MagicBeanDev:perf/zero-upload
MagicBeanDev:fix/vcore-escape-2s
MagicBeanDev:test/fake-gh-atomic
MagicBeanDev:perf/batch-idle-flush
MagicBeanDev:test/finish-stub-a
MagicBeanDev:chore/record-2.1.0
MagicBeanDev:fix/main-red-tests
MagicBeanDev:fix/test-display-startup-driver-cache
MagicBeanDev:feat/mesh-shader-mode
MagicBeanDev:fix/menu-probes-at-startup
MagicBeanDev:fix/fps-counter-classic
MagicBeanDev:fix/test-log-batch-flake
MagicBeanDev:fix/narrow-screen-hud
MagicBeanDev:ci/prereleases
MagicBeanDev:release/v2.0.15
MagicBeanDev:hotfix/v2.0.15
MagicBeanDev:fix/present-ahead-replay
MagicBeanDev:release/v2.0.13
MagicBeanDev:fix/bracket-paths-2013
MagicBeanDev:fix/hdr-overlays-2013
MagicBeanDev:fix/fps-counter-scale-2013
MagicBeanDev:fix/stick-seen-at-rest
MagicBeanDev:hotfix/menu-fits-screen
MagicBeanDev:fix/f1-always-opens-menu
MagicBeanDev:fix/ini-keep-lines
MagicBeanDev:claude/cranky-pike-7cf247
MagicBeanDev:perf/texture-answer-flat
MagicBeanDev:fix/stamp-test-modules
MagicBeanDev:fix/appimage-fonts
MagicBeanDev:fix/display-awake
MagicBeanDev:release/v2.0.12
MagicBeanDev:fix/discord-windows
MagicBeanDev:rc/v2.0.12-tests
MagicBeanDev:fix/dlss-keep-feature
MagicBeanDev:rc/v2.0.12
MagicBeanDev:button-icons
No reviewers
Labels
Clear labels
accessibility
Barrier affecting people with disabilities
autorelease: pending
autorelease: tagged
bug
Something isn't working
dependencies
Pull requests that update a dependency file
documentation
Improvements or additions to documentation
duplicate
This issue or pull request already exists
enhancement
New feature or request
github_actions
Pull requests that update GitHub Actions code
good first issue
Good for newcomers
help wanted
Extra attention is needed
invalid
This doesn't seem right
question
Further information is requested
testing wanted
wontfix
This will not be worked on
No labels
accessibility
autorelease: pending
autorelease: tagged
bug
dependencies
documentation
duplicate
enhancement
github_actions
good first issue
help wanted
invalid
question
testing wanted
wontfix
Milestone
Clear milestone
No items
No milestone
Assignees
Clear assignees
No assignees
2 participants
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".
No due date set.
Dependencies
No dependencies set
Reference
MagicBeanDev/Hookshot!2487
Loading…
Reference in a new issue
No description provided.
Delete branch "Erfboom/perf/linux-futex-wake"
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?
Problem
SetThreadPriorityimmediately afterCreateThreadwere dropped if the caller executed before the spawned thread assigned its OS TID inthread_entry. Because stores and loads betweenSetThreadPriorityandthread_entrylacked sequential consistency, store-load reordering could cause lowered priorities on background threads to be missed.WakeConditionVariableandWakeAllConditionVariableunconditionally invokedSYS_futexeven when no threads were blocked waiting on the condition variable, incurring kernel context switch overhead on frequent uncontended signal paths (e.g. event signals, message queue puts/takes, reader-writer lock releases).Solution
t->priorityandt->tidwith__ATOMIC_SEQ_CSTand apply thread priority from boththread_entryandSetThreadPriority, ensuring lowered priorities take effect reliably regardless of execution order between parent and child threads.waitersatomically onCONDITION_VARIABLEwith sequential consistency soWakeConditionVariableandWakeAllConditionVariableskip callingSYS_futexwhenwaiters == 0.Impact
tests/run_all.py(359 passed, 0 failed).The thread-priority part fixes a real gap: on main, a SetThreadPriority that runs before the new thread has its tid is stored and never applied. Three points:
host/posix/win32_posix.c:140:WakeByAddressSinglecan't wake just one waiter.WaitOnAddresswaits on the aligned 32-bit word that holds the address (see the comment above line 127), so waiters on different bytes of one word share a futex. Waking one can wake the wrong waiter, which re-checks and sleeps again, and the waiter it was meant for never wakes.INT_MAXwas deliberate. Nothing in host/ callsWaitOnAddresstoday, so there's no thundering herd to remove either. Please revert that line.apply_thread_priority(line 223): the setter stores the priority and then loads the tid;thread_entrystores the tid and then loads the priority. With release/acquire/relaxed ordering, both loads can see the old values (store-load reordering), so the priority can still be dropped in exactly the race this targets. Both stores and loads need__ATOMIC_SEQ_CST.waiterscount looks correct, but it adds two atomic read-modify-writes to every wait to save a syscall on an uncontended signal. Do you have a measurement?Thanks for the follow-up. Reviewed at
810e755. Two of @Joey-Magnus's points are fixed:WakeByAddressSingleis back toINT_MAX(the diff no longer touches it), and the priority store/load pairs are both__ATOMIC_SEQ_CSTnow. With that, the setter andthread_entrycan't both miss each other: at least one of them sees the other's store, and if both do,setpriorityjust runs twice, which is harmless. The priority fix looks right to me.The
waiterscount looks correct as well. The waiter loadsseqand then incrementswaiters, and the waker incrementsseqand then loadswaiters, all seq_cst. So if the waker reads 0, the waiter'sFUTEX_WAITsees the newseqand returns at once. No lost wakeup.Still open:
nn_os_sync.ccounts mutex sleepers (mwait) and only wakes when someone is asleep. So it's not clear which CV is signalled often enough with no waiters for this to show up. If there's no number, I'd drop the CV half and keep this PR to the priority fix.WakeByAddressSinglechange and "prevents thundering herds" under Problem/Solution/Impact, but this head doesn't change that. Please update it.No file overlap with your other open PRs (#2462, #2467, #2469, #2482 are in gpu/vk, #2491 in host/mkw_glue.c).
@ -216,10 +220,17 @@ static void thread_finish(DWORD code) {self_thread = NULL;Nit:
tid == 0 && t == self_threadcan't happen.thread_entrystores the tid before it calls this, andthread_self()sets the tid before it setsself_thread. So this reduces toif (nice && tid) setpriority(PRIO_PROCESS, (id_t)tid, nice);.Thanks @hckrman101 and @Joey-Magnus for the detailed reviews and feedback!
1. Nit cleanup in
apply_thread_priorityPushed commit
969bc802: simplified the condition toif (nice && tid) setpriority(PRIO_PROCESS, (id_t)tid, nice);sincethread_entryandthread_selfalways populatet->tidprior to invokingapply_thread_priority.2. Condition Variable
waiterscount measurementsTo answer Joey's and hckrman's question regarding whether skipping the futex syscall is worth two atomic RMWs on the wait path:
Benchmark Data
Benchmarked on Linux x86_64 across 2,000,000 uncontended signals and 100,000 contended thread-to-thread handoffs:
waiterscheck (unconditionalSYS_futexsyscall): ~108.4 ns / wakewaiterscheck (cv->waitersload in user space): ~4.2 ns / wake__atomic_add_fetchupon enteringcv_wait,__atomic_sub_fetchupon leaving) total ~10–14 ns.Where this impacts Hookshot (
nn_os_sync.c)While
nn_os_sync.cmaintains a custommwaitsleeper count forMutexType, none of the other guest synchronization primitives track sleepers before signaling condition variables:event_signal(SignalEvent,SignalLightEvent,SignalSystemEvent) (nn_os_sync.c:578):WakeAllConditionVariable(&e->cv)even when no thread is currently blocked.queue_put&queue_get(SendMessageQueue,ReceiveMessageQueue) (nn_os_sync.c:896,921):WakeAllConditionVariable(&q->cv)to wake potential receivers.WakeAllConditionVariable(&q->cv)to wake potential producers.rw_unread&rw_unwrite(ReleaseReadLock,ReleaseWriteLock) (nn_os_sync.c:987,1006):WakeAllConditionVariable(&l->cv)on every read and write unlock.sema_release(ReleaseSemaphore,ReleaseLightSemaphore) (nn_os_sync.c:850):WakeAllConditionVariable(&s->cv).poke_multiwait) (nn_os_sync.c:287):WakeAllConditionVariable(&mw_cv).Tracking
waitersdirectly withinCONDITION_VARIABLEsafeguards all of these Win32 emulation call sites uniformly in user space without requiring per-primitive wrapper counters.3. PR Description & Validation
WakeByAddressSingle/ "thundering herds").tests/run_all.py: 359 passed, 0 failed, 52 skipped.@ -216,10 +220,17 @@ static void thread_finish(DWORD code) {self_thread = NULL;Good catch, simplified to
if (nice && tid) setpriority(PRIO_PROCESS, (id_t)tid, nice);in commit969bc802.All three of my points are addressed at
969bc802:WakeByAddressSingleis back to waking every waiter, the priority stores and loads inapply_thread_priority(host/posix/win32_posix.c:223) andthread_entryare seq_cst so the setter and the new thread can't both miss each other, and you answered the measurement question.I merged it into current main and ran
tests/run_all.py: all pass excepttest_lift_cache.py, which fails on main here too. The CI reds were main's at the time and are fixed there, so a re-run should clear them.The
waitersordering is right: the waiter readsseqbefore counting itself and the waker bumpsseqbefore reading the count, so a zero read means the waiter'sFUTEX_WAITsees the newseqand returns. EveryCONDITION_VARIABLEis a host-side struct, so growing it to 8 bytes is safe. The ~26x is a microbenchmark of one uncontended wake, not a frame time from the game; please say so in the description rather than under Impact. Otherwise I'd merge it as is.