Semaphore, event flag, condition variable, rwlock and equeue signals each ended in notify_one or notify_all on a condition_variable_any, which locks its internal mutex and calls the host even when nobody waits. A condition now counts the threads that are inside its wait; a notification with a count of zero returns after one atomic load. A signal+wait pair on a kernel semaphore drops from 39 ns to 21 ns and from 1069 to 579 instructions, an event flag set+wait from 64 ns to 55 ns, and a condition signal or broadcast with no waiter from 20 ns to 10 ns.
A waiter registers before it releases the caller's lock and leaves after it takes the lock back. A notifier that changed its state under that lock, the discipline of the callers reviewed (kernel semaphores, event flags, rwlocks, equeue, sync-on-address, POSIX semaphores, thread join, AvPlayer, HTTP), acquires the lock after the waiter released it inside the wait, so it observes the registration and notifies; a waiter that registers later checks its predicate after the change. For the cancel path, scePthreadCancel repeats its notification until the cancelled thread leaves the wait. A notifier that changes state outside the lock and notifies at once can lose a wakeup only inside the few nanoseconds between the waiter's predicate check and its registration, which the previous code could also lose between the predicate check and the wait entry. The Windows park queue is unchanged.
The new wakeup test drives ping-pong rounds over semaphores, event flags and condition variables with five second patience, plus broadcasts to six waiters, and fails if any wakeup is missed.
A sleep below 50 us was a single SwitchToThread, which returns in about
9 us with nothing else ready, so a thread polling with usleep(20) made
over 100,000 system calls a second on a full core and never slept the
time it asked for.
Such a sleep now spins on pause instructions to its deadline, under a
delivery deferral and followed by an APC drain like the spin that ends
longer sleeps. When a thread has issued short sleeps back to back for
1 ms, the following ones block on its high-resolution timer until the
thread next stays awake for at least the length of a request, so an idle
polling loop leaves the processor and a busy one keeps its latency. The
same path serves APS5_COARSE_TIMED_WAITS.
guest_short_sleep pins that 1, 5, 20 and 49 us sleeps and a 20 us
nanosleep never return early, that 2000 sleeps of 20 us take 40 ms or
more, that 500 ms of back-to-back 20 us sleeps use at most 40% of the
calling thread's time, and that a 20 us sleep after 200 us of work has a
median under 100 us. guest_raise_short_sleep also raises at a thread
sleeping 20 us in a loop.
AI-assisted (Claude Code).
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
SleepWake's per-thread state and the nesting depth of TimerWait were
thread_local, which MinGW resolves through __emutls_get_address,
pthread_getspecific and a process-wide winpthreads spinlock on every
sleep. Both now live in the fiber-local storage the neighbouring code
already uses (WindowsThreadLocal), so a sleep takes no emulated TLS
lookup. Behaviour is unchanged; other hosts keep thread_local.
AI-assisted (Claude Code).
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
QueueForDeliveryDrain ran after ResumeThread with no coordination with
the target's final ReapDeliveryDrain: a target could exit between resume
and enqueue, leaving the post in a box nothing would drain again and
retaining the QueuedDelivery reference.
Admission is now decided under drainBoxesLock against the target's
_finished flag, which is stored before the final reap in program order;
denied posts run their callback inline so the entry and the reference
are resolved exactly once on either path.
The GuestRaiseException regression arms a post hook, holds the producer
between resume and enqueue, lets the target finish and reap, then
completes the post and requires the drain to stay empty; the churn
rounds also assert the post hook observed mailbox posts alongside the
delivered raises.
On Windows a sleep shorter than TimedWait's 0.5 ms lead, and the last 0.5 ms of a longer one, is a YieldProcessor spin in host code with no wait counted. A raise that found the target there could only be delivered through the return-address breakpoint or sampling, so sceKernelRaiseException at a thread looping on such sleeps was lost: a thread looping on sceKernelUsleep(200) lost the first raise in 5 of 5 runs.
The spins in SleepUntil and SleepNanosUnlessChanged now run under a DeliveryDeferral and drain APCs afterwards, as BeginPark and Unpark already do. A raise that finds the target spinning is queued as an APC and runs when the sleep ends.
GuestRaiseShortSleep raises 100 times each at a thread sleeping 100, 200 and 400 us in a loop, with sleep wakes on (SleepNanosUnlessChanged) and with APS5_NO_SLEEP_WAKE (SleepUntil). Both fail on main at the first or second raise.
AI-assisted (Claude Code).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The process, thread and clock functions that read /proc or call glibc
extensions:
- The program arguments come from _NSGetArgc and _NSGetArgv instead of
/proc/self/cmdline.
- The current CPU comes from pthread_cpu_number_np.
- getrusage for a thread, the CPU clock of a thread and the CPU time of a
guest thread (clock_gettime with the thread CPU clock) read the Mach
thread_info of the thread. macOS has no pthread_getcpuclockid, and under
Rosetta CLOCK_THREAD_CPUTIME_ID advances by about 1/41.7 of the thread's
CPU time (24 MHz ticks read as nanoseconds), where natively it matches
thread_info.
- The stack limits of a thread come from pthread_get_stackaddr_np and
pthread_get_stacksize_np.
- sleeping with nanosleep restores errno, because macOS leaves ETIMEDOUT
in it on success and the guest's errno is the host's.
The first local of a guest thread lies 4,464 bytes below the top of its
stack on macOS, more than the frame the pthread stack test allowed, so the
test allows two frames there.
On Linux and macOS, sceKernelRaiseException runs the guest handler in
the target's SIGUSR1 handler wherever the thread was interrupted. A
thread interrupted while it held the address-wait lock of
sceKernelSyncOnAddressWait, sceKernelSyncOnAddressWake or _umtx_op ran
the handler with the lock held, so a handler that waits, as a
stop-the-world collector's does, blocked every other thread that waits
on or wakes an address. #5756 fixed this on Windows.
The address-wait lock is now taken under DeliveryDeferral on every
host. On POSIX the deferral is a count per thread: while it is raised
the SIGUSR1 handler only records the signal, and DeliverDeferred sends
it to the thread again once the lock is released. An address waiter
waits on its own semaphore (sem_t, a dispatch semaphore on macOS) with
the lock released and the deferral lifted, so a raise reaches a thread
that waits for an address without a timeout.
The address-lock phases of guest_raise_exception now run on every
host, with a new phase that raises at a thread in an unbounded address
wait.
A wake set after the previous wait returned left the per-thread
auto-reset event signalled, so the next short sleep returned from its
wait at once and spun to its deadline. With APS5_COARSE_TIMED_WAITS or
a request under 50 us the sleep now takes TimedWait::SleepNanos as on
main.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A sleep of 1 ms or less returns once the AGC driver sees a GPU batch
complete (a thread waits on the recorder's timeline semaphore), runs a
batch's completion actions, or VideoOut completes a flip. A thread
returns early at most 8 times in a run of back-to-back sleeps; the run
restarts when the thread submits AGC work or did not sleep for the
requested time. APS5_NO_SLEEP_WAKE=1 keeps every sleep in full.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
SleepUntil, PollSleepUntil and SleepNanosCoarse each wait on one
thread_local high-resolution timer. A sceKernelRaiseException handler
that runs as an APC inside a sleeping thread's wait and sleeps itself
re-armed that timer and consumed its signal, so the interrupted sleep
never returned. A nested TimerWait now waits on its own timer.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A thread had one TimedWait waiter for every wait. When
sceKernelRaiseException reached a thread blocked in a TimedWait
condition, its handler ran as an APC inside that wait, and a wait in
the handler queued the same waiter on a second condition while it was
still linked into the first. The links of the first queue were
overwritten, so waiters behind it were never woken, and a wake of the
outer wait set the shared event and was consumed by the inner wait.
A wait now takes the thread's first waiter that is not in use, and
creates a deeper one for a wait nested inside another.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HeC9bA3n74TzJRYv9AgBE8
A raise that suspends the thread after its wait returned but before the
wait count drops queued an APC that only ran at the next alertable wait.
Pending APCs are now run right after the count drops. The 0 ms poll in
Condition::waitSignalUntil runs under queueLock and is no longer
alertable, and a target that exits during the raise returns ESRCH.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The APC delivery was allocated after SuspendThread, so a target holding
the allocator lock deadlocked the raising thread; it is now allocated
before the suspend. The wait count a raise checks lived in the target's
thread_local storage and dangled once the thread exited; it is now a
member of PthreadPrivate, which TimedWait counts into through a
thread-local pointer bound when the thread starts, and a raise on a
thread that already finished returns ESRCH. TechnicalDebt gets one line
per unverified choice: Windows only, the FreeBSD ucontext layout, the
signal mask, the YMM upper halves, and delivery to threads outside
TimedWait.
AI-assisted: yes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Run the SIGUSR1 handler recorded by sceKernelInstallExceptionHandler on the
target thread with a PS5 ucontext (uc_mcontext at 0x40, FreeBSD amd64
layout) of its interrupted state:
- on the calling thread, directly;
- on a thread in a libkernel wait, from an APC: the TimedWait waits are
alertable and count themselves in a per-thread wait state, so the
handler runs inside the wait, which then continues;
- on a running thread, by suspending it and redirecting it to an entry
that calls the handler and restores the possibly modified context.
Other signals return EINVAL, as in shadPS4; raising without a handler
throws. Linux still throws.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
libkernel: a TimedWait service for condition variables, semaphores, event flags, rwlocks and
equeues with the scheduler tick; mutex/cond/sem corner cases the title hits; job worker
affinity is opt-in (APS5_JOB_AFFINITY). libc: calloc/realloc heap slot swap, a default
terminate handler with a backtrace, CPU topology helper. libSceRtc export fixes with tests.
libSceVideoOut: APS5_NO_PAD_INPUT ignores host input for unattended measurements,
APS5_FLIP_QUEUE_WAIT keeps a stalled process alive for a debugger. ApplicationHeap and
GuestRtc tests wired into the test build.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0177gthrWEBBfBu5xJDXgBfo