Skip to content

fix(libkernel): honor absolute ksem wait deadlines precisely - #14228

Merged
oneandonlydean merged 2 commits into
boykopovar:mainfrom
harry-z-kang:codex/fix-ksem-windows-timeouts
Nov 8, 2026
Merged

oneandonlydean merged 2 commits into
boykopovar:mainfrom
harry-z-kang:codex/fix-ksem-windows-timeouts

Conversation

@harry-z-kang

@harry-z-kang harry-z-kang commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

What

Use TimedWait::Condition for kernel semaphore waits and check the absolute realtime deadline after each wake. This removes the remaining winpthreads timed wait from ksem_timedwait, a focused follow-up to #1471.

Convert the remaining interval with bounded arithmetic and round it up to microseconds. Very distant deadlines are clamped per park and rechecked, avoiding overflow when constructing a host system_clock::time_point. Available tokens still win over expired deadlines, and only one waiter consumes each posted token.

Add coverage for short deadlines, expired deadlines with and without a token, extreme signed seconds, a posted far-future wait, and two timed waiters sharing one post.

Before posting, the far-future test confirms one registered waiter and the two-waiter test confirms both. A test-only accessor reads the existing waiter count under the semaphore mutex, so the post cannot bypass the empty-count/deadline path. Pre-call flags and fixed post delays are removed from both cases; early waiter completion fails the test. The accessor is compiled only with BUILD_TESTING=ON and adds no guest NID.

Tested

Rebased 2026-11-07: head b77f99c9ff, independently based on main 8eb293447e. git range-diff confirms both topic commits are unchanged, including the review follow-up that synchronizes both posting tests with registered waiters. The focused tests below were rebuilt and rerun on this head.

Windows 11 10.0.26300, AMD Ryzen 7 9800X3D, Release, BUILD_TESTING=ON.

Toolchain Build Focused CTests
WinLibs GCC 15.2.0 UCRT POSIX SEH r7 Selected test targets and required runtime libraries 9/9 passed
MSYS2 UCRT64 GCC 16.2.0 Selected test targets and required runtime libraries 9/9 passed

The focused set covers guest_kernel_sys_ksem, guest_timed_wait_cpu, guest_libc_cnd_timed_wait, guest_posix_sem_init, guest_posix_sem_post, guest_posix_named_sem, guest_cond_timedwait, guest_pthread_sem and guest_semaphore.

Negative control captured 2026-11-05 for the synchronized tests: restored main 1be4c77a8d's Ksem.cpp and added only the test-gated waiter-count accessor, leaving the updated tests in place. guest_kernel_sys_ksem failed before the post at the registration guard in all five attempts on each toolchain (ctest --repeat until-pass:5). Restored the changed implementation and rebuilt; the final focused runs passed 9/9 on each toolchain as shown above. These are API deadline checks, with no title or frame-rate measurement.

tools/check_conventions.py --base origin/main, git diff --check and the public-header declaration audit (--audit-only) pass. The original 2026-10-31 overlap scans reported upstream-conflicting #9293/#9297/#9302 and #13750, so their shared files were also compared manually. At heads b208fd6b21, d07deaa187, and c045c1e91f, the first three still carry the older #9284 ksem baseline and retain its standard-library wait; they do not implement this deadline fix. #13750 (5e65375b90) changes the latency-test reporting and bounds policy rather than semaphore waits.

Proposed merge order for @DavidSamir and @camezaro-intc: land this focused fix first, then preserve its condition/deadline logic and new test while rebasing those branches. Please confirm or suggest the reverse order. There is no functional dependency on those PRs. The separate font backoff fix, #14225, is merged into main.

MSYS2 uses the existing local CMAKE_SKIP_INSTALL_RULES=ON workaround for #12994; installation was not tested. Linux/macOS and titles were not run.

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: none
  • Fixes: none
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes

@MarcZX10 MarcZX10 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed — changes requested

The far-future regression test can pass without entering the deadline conversion path it is meant to protect.

What I ran

Reviewed head 91b0a61f5d9d7cf6d949e7e01328095da2339e06 against PR base b865ce7a939faea6e66451ceb9b8a2a189327d17 on Debian 12 x86_64, Python 3.11.2 and GCC 12.2.0. The preview onto current main a9ae365e546067b1ea98d209b1f045346691281f merged cleanly. The hosted Windows job built and ran the changed guest tests successfully; Linux and specialized jobs were skipped. I did not build or run CTest locally.

python3 tools/pr_precheck.py --repo boykopovar/AnyPS5 --pr 14228
git diff --check b865ce7a939faea6e66451ceb9b8a2a189327d17...91b0a61f5d9d7cf6d949e7e01328095da2339e06
git merge-tree --write-tree upstream/main refs/anyps5/review/14228
gh pr checks 14228 --repo boykopovar/AnyPS5
gh run view 41258937870 --repo boykopovar/AnyPS5 --json jobs

Results

Check Result
Diff check Passed.
Conventions and PR template Passed in local precheck and hosted CI.
Current-main merge preview Passed; tree 426e06d48620168a265f6211d080fc2c486726e7.
Hosted Windows changed guest tests Passed.
Hosted Linux and specialized jobs Skipped.
Local C++ build/CTest Not run.
Author-reported focused tests and negative controls PR description reports 9/9 tests on WinLibs and MSYS2 and a failing base negative control; these were not run locally.
Selected unedited output
426e06d48620168a265f6211d080fc2c486726e7
windows	pass	6m25s	https://github.com/boykopovar/AnyPS5/actions/runs/41258937870/job/124709333732
linux	skipping	0	https://github.com/boykopovar/AnyPS5/actions/runs/41258937870/job/124709334268

Negative control

Assertion Change to code under test New test failed?
Posted far-future deadline completes after a post No local negative control run. The PR reports that adding the regression tests to base main failed on both Windows toolchains. Author-reported; not independently verified.

Findings

Blocking

In AbsoluteTimeouts, the waiter sets started before calling ksem_timedwait_nid_postfix; the test then posts after a fixed 20 ms sleep. If the waiter is descheduled after setting the flag, the post can make the token available before the call. Wait consumes an already-available token without evaluating or converting the deadline, so this regression may pass without exercising the overflow path. Please synchronize on confirmed waiter registration before posting (for example, with a test-only wait-registration hook), rather than relying on elapsed sleep time.

Non-blocking

TimedWakeup also uses a fixed delay after a pre-call started signal, so it does not deterministically establish that both waiters are queued at the instant of the post. The implementation's bounded arithmetic and absolute-deadline recheck are otherwise consistent with the inspected source; I found no separate code defect in this review.

Sources

Not verified

No local build/CTest, Linux product run, macOS run, or console run. The focused two-toolchain test results and base negative control in the PR description are author-reported.

To get this to a good state

Add deterministic synchronization proving the timed waiter has registered before posting, then rerun the focused tests and negative control on the updated head. I will repeat the same relevant checks on that head.

@github-actions

github-actions Bot commented Nov 1, 2026 •

Copy link
Copy Markdown

Other open pull requests touch the same code. Merging one will break the other, or both implement the same thing. If this one builds on them, list them in Depends on.

Pull request Conflicting files (lines on main) Same exports Same new files
PR 12682 core/libs/prx/libkernel/CMakeLists.txt L117
PR 12688 core/libs/prx/libkernel/CMakeLists.txt L117
PR 12700 core/libs/prx/libkernel/CMakeLists.txt L117
PR 12965 core/libs/prx/libkernel/CMakeLists.txt L117

Some comparisons could not be completed because a pull request conflicts with the base branch. Review these shared files manually before concluding that there is no overlap.

Pull request Shared files not compared
PR 4563 core/libs/prx/libkernel/CMakeLists.txt
PR 5021 core/libs/CMakeLists.txt
core/libs/prx/libkernel/CMakeLists.txt
PR 6149 core/libs/prx/libkernel/CMakeLists.txt
PR 6936 core/libs/prx/libkernel/CMakeLists.txt
PR 7275 core/libs/CMakeLists.txt
PR 7622 core/libs/CMakeLists.txt
PR 8650 core/libs/CMakeLists.txt
PR 9156 core/libs/CMakeLists.txt
core/libs/prx/libkernel/CMakeLists.txt
PR 9161 core/libs/CMakeLists.txt
PR 9162 core/libs/CMakeLists.txt
PR 9293 core/libs/CMakeLists.txt
core/libs/prx/libkernel/CMakeLists.txt
core/libs/prx/libkernel/Semaphore/include/Ksem.hpp
core/libs/prx/libkernel/Semaphore/src/Ksem.cpp
core/libs/tests/GuestKernelSysKsem.cpp
PR 9297 core/libs/CMakeLists.txt
core/libs/prx/libkernel/CMakeLists.txt
core/libs/prx/libkernel/Semaphore/include/Ksem.hpp
core/libs/prx/libkernel/Semaphore/src/Ksem.cpp
core/libs/tests/GuestKernelSysKsem.cpp
PR 9302 core/libs/CMakeLists.txt
core/libs/prx/libkernel/CMakeLists.txt
core/libs/prx/libkernel/Semaphore/include/Ksem.hpp
core/libs/prx/libkernel/Semaphore/src/Ksem.cpp
core/libs/tests/GuestKernelSysKsem.cpp
PR 9383 core/libs/CMakeLists.txt
core/libs/prx/libkernel/CMakeLists.txt
PR 9389 core/libs/prx/libkernel/CMakeLists.txt
PR 9557 core/libs/prx/libkernel/CMakeLists.txt
PR 9566 core/libs/prx/libkernel/CMakeLists.txt
PR 9938 core/libs/prx/libkernel/CMakeLists.txt
PR 11896 core/libs/prx/libkernel/CMakeLists.txt
PR 12130 core/libs/CMakeLists.txt
PR 12544 core/libs/prx/libkernel/CMakeLists.txt
PR 12642 core/libs/CMakeLists.txt
PR 14304 core/libs/CMakeLists.txt
PR 15111 core/libs/CMakeLists.txt
PR 15807 core/libs/CMakeLists.txt
PR 15836 core/libs/CMakeLists.txt
PR 15838 core/libs/CMakeLists.txt

@camezaro-intc

Copy link
Copy Markdown
Contributor

@harry-z-kang Agreed on the merge order: please go ahead and land #14228 first. I will preserve your condition/deadline logic and tests when rebasing #13750.

@oneandonlydean oneandonlydean self-assigned this Nov 1, 2026
@RNK123

RNK123 commented Nov 1, 2026

Copy link
Copy Markdown

Independent Linux runtime check of the far-future deadline path for head 91b0a61f5d9d7cf6d949e7e01328095da2339e06, merged onto main 5e936063e3a74b7f03ff06905be04c5a00be60a7 (merged tree 834501d8285d9396b9897261f0b52bdcd5cd94d1).

Method: a standalone probe linked to the real libkernel.prx starts a zero-token semaphore and calls ksem_timedwait with {INT64_MAX, 999999999}. Executable-level interposition records the first pthread_cond_timedwait / pthread_cond_clockwait reached on that thread, including its converted deadline and matching host clock. The posting thread waits for that observation before posting. There is no fixed sleep or pre-call “started” signal. The wrappers forward to glibc, and no production code is instrumented.

Observed A–B–A result, using the unchanged probe executable:

  • Original main: the converted host deadline is 0.000000000 on CLOCK_REALTIME, already expired; the guest call returns -1, guest errno 60, probe exits 1 (one initial run).
  • Merged candidate: a future CLOCK_MONOTONIC host deadline approximately 4,294.967 seconds away is observed before posting; the post succeeds and the guest wait returns 0, probe exits 0 (3/3 runs).
  • Restored/rebuilt original main: the epoch-zero deadline and erroneous timeout return again, probe exits 1 (3/3 runs).

The invalid-deadline lane intentionally does not post, so an available token cannot mask the conversion failure. Each run has a 10-second external timeout plus 3-second observation/completion watchdogs; none fired.

Focused CTests: guest_kernel_sys_ksem and guest_timed_wait_cpu both passed on original main and again after restoration; the merged candidate's two entries passed three serial repetitions each, without skips. The candidate includes changed test sources, so those CTests are smoke checks, not an identical-source negative control; the unchanged external probe is the negative control.

Scope: this confirms the production far-future path under Linux/glibc. It does not repair the synchronization in AbsoluteTimeouts or prove both TimedWakeup waiters are queued, and is not a request to dismiss the existing review finding. The hook records entry into the host wait wrapper, not a measured period parked in the kernel. No macOS, console, title, GPU, or full-suite testing.

Host: CachyOS Linux 7.3.1-1-cachyos, x86-64, Intel i5-12400F, GCC 16.2.1 20260810, glibc 2.44, Release / BUILD_TESTING=ON. Source repository restored clean to the pinned main; no upstream code changes.

Representative raw observations and reproduction commands
original main:
host wait reached before post: clock=0 now=1793512959.865457695 deadline=0.000000000 future=0
wait result=-1 guest_errno=60

merged candidate:
host wait reached before post: clock=1 now=16106.155324489 deadline=20401.122617799 future=1
wait result=0 guest_errno=0

restored main:
host wait reached before post: clock=0 now=1793513265.655613079 deadline=0.000000000 future=0
wait result=-1 guest_errno=60

Save the source below as tester/ksem_deadline_probe.cpp, adjacent to the AnyPS5 checkout. Build the relevant library/tests on each tree, but compile the standalone probe only once:

cmake --build AnyPS5/build-main --target guest_kernel_sys_ksem_tests guest_timed_wait_cpu_tests --parallel 4
libdir="$PWD/AnyPS5/build-main/core/libs/libs/unpatched"
g++ -std=c++20 -O2 -pthread -rdynamic \
  -I AnyPS5/core/libs tester/ksem_deadline_probe.cpp \
  -L "$libdir" -Wl,-rpath,"$libdir" -Wl,-rpath-link,"$libdir" \
  -l:libkernel.prx -l:libc.prx -ldl -o tester/ksem_deadline_probe
timeout 10s tester/ksem_deadline_probe
ctest --test-dir AnyPS5/build-main \
  -R '^(guest_kernel_sys_ksem|guest_timed_wait_cpu)$' -V

Probe executable SHA-256: 17417919d0c1820a33af75389d8a8cd5ccff3819b0a4e6d0048c44567f2155e8.
Source SHA-256: 472a29b5f6bf19d09bfd667ad06131d51e3118f33e8e0095af4e9ab6734bfecf.

Standalone probe source (Linux/glibc diagnostic, not a proposed portable test)
#include "SceTypes.hpp"
#include "prx/libkernel/include/Api.hpp"
#include "prx/libc/include/Api.hpp"
#include <atomic>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <dlfcn.h>
#include <limits>
#include <pthread.h>
#include <thread>
#include <time.h>

namespace {

using TimedWait = int (*)(pthread_cond_t*, pthread_mutex_t*, const timespec*);
using ClockWait = int (*)(pthread_cond_t*, pthread_mutex_t*, clockid_t, const timespec*);
TimedWait realTimedWait = nullptr;
ClockWait realClockWait = nullptr;
thread_local bool observeWait = false;
std::atomic<bool> entered{false};
std::atomic<bool> completed{false};
timespec observedDeadline{};
timespec observedNow{};
clockid_t observedClock = CLOCK_REALTIME;

void Observe(clockid_t clock, const timespec* deadline) {
    if (!observeWait) return;
    observeWait = false;
    observedClock = clock;
    observedDeadline = *deadline;
    clock_gettime(clock, &observedNow);
    entered.store(true, std::memory_order_release);
}

void WaitFor(const std::atomic<bool>& flag, const char* reason) {
    const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(3);
    while (!flag.load(std::memory_order_acquire)) {
        if (std::chrono::steady_clock::now() >= deadline) {
            std::fprintf(stderr, "%s\n", reason);
            std::_Exit(2);
        }
        std::this_thread::yield();
    }
}

}

extern "C" int pthread_cond_timedwait(pthread_cond_t* condition, pthread_mutex_t* mutex, const timespec* deadline) {
    Observe(CLOCK_REALTIME, deadline);
    return realTimedWait(condition, mutex, deadline);
}

extern "C" int pthread_cond_clockwait(pthread_cond_t* condition, pthread_mutex_t* mutex, clockid_t clock, const timespec* deadline) {
    Observe(clock, deadline);
    return realClockWait(condition, mutex, clock, deadline);
}

int main() {
    realTimedWait = reinterpret_cast<TimedWait>(dlsym(RTLD_NEXT, "pthread_cond_timedwait"));
    realClockWait = reinterpret_cast<ClockWait>(dlsym(RTLD_NEXT, "pthread_cond_clockwait"));
    if (realTimedWait == nullptr || realClockWait == nullptr) return 2;
    std::intptr_t semaphore = -1;
    if (ksem_init_nid_postfix(&semaphore, 0) != 0) return 2;
    const KernelTimespec future{std::numeric_limits<std::int64_t>::max(), 999999999};
    int result = -2;
    int error = 0;
    std::thread waiter([&] {
        observeWait = true;
        result = ksem_timedwait_nid_postfix(semaphore, &future);
        error = *__error_nid_postfix();
        completed.store(true, std::memory_order_release);
    });
    WaitFor(entered, "the timed waiter did not reach a host condition wait");
    const bool futureDeadline = observedDeadline.tv_sec > observedNow.tv_sec ||
        (observedDeadline.tv_sec == observedNow.tv_sec && observedDeadline.tv_nsec > observedNow.tv_nsec);
    std::printf("host wait reached before post: clock=%d now=%lld.%09ld deadline=%lld.%09ld future=%d\n",
        static_cast<int>(observedClock), static_cast<long long>(observedNow.tv_sec), observedNow.tv_nsec,
        static_cast<long long>(observedDeadline.tv_sec), observedDeadline.tv_nsec, static_cast<int>(futureDeadline));
    if (futureDeadline && ksem_post_nid_postfix(semaphore) != 0) std::_Exit(2);
    WaitFor(completed, "the timed waiter did not complete after the observed deadline or post");
    waiter.join();
    std::printf("wait result=%d guest_errno=%d\n", result, error);
    if (ksem_destroy_nid_postfix(semaphore) != 0) return 2;
    return futureDeadline && result == 0 ? 0 : 1;
}

AI-assisted independent test run (Codex).

@bunbeans2-arch

Copy link
Copy Markdown
Contributor

A Windows run with GCC 16: Windows 11 Pro 10.0.22631, i9-9900K, MSYS2 UCRT64 GCC 16.1.0, Release, this PR (91b0a61f5d) merged into main 1f2c1da.

  • With this PR: guest_kernel_sys_ksem and guest_timed_wait_cpu both passed 5 of 5.
  • Same tree with only Ksem.cpp put back to main (this PR's tests kept): guest_kernel_sys_ksem failed and guest_timed_wait_cpu aborted (SIGABRT, exit 0xc0000409) in 5 of 5 runs.
  • main 1f2c1da alone (its own tests and source): both passed 3 of 3.

AI-assisted: yes (Claude Code)

@harry-z-kang
harry-z-kang force-pushed the codex/fix-ksem-windows-timeouts branch from 91b0a61 to ca542d1 Compare November 6, 2026 06:04
@harry-z-kang

harry-z-kang commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor Author

@MarcZX10 Addressed in 812490e71b.

Both AbsoluteTimeouts and TimedWakeup now wait for the required registered waiter count before posting (one and two respectively). The test-only accessor locks the same semaphore mutex as the wait path, so it cannot observe registration before the waiter releases that mutex through the condition wait. The pre-call flags and fixed 20-ms post delays are removed; an early waiter completion fails the registration check. The 1-ms polling sleep only backs off polling. The accessor is gated by BUILD_TESTING and adds no guest NID.

I reran the negative control with main 1be4c77a8d's Ksem.cpp, adding only the test accessor and retaining the updated tests. All five attempts on each toolchain failed at the registration guard before posting (ctest --repeat until-pass:5). After restoring and rebuilding the fixed implementation, the nine focused CTests passed on both WinLibs GCC 15.2.0 and MSYS2 UCRT64 GCC 16.2.0. Conventions checks passed as well.

The PR description is updated with these results. Could you review this again? GitHub rejected the formal review re-request for my account (RequestReviewsByLogin permission error; the REST endpoint also rejected it), so a maintainer may need to re-request the review to restore the review queue.

@oneandonlydean
oneandonlydean dismissed MarcZX10’s stale review November 6, 2026 07:32

Met at 812490e: the ksem test no longer sleeps for 20 ms. It waits on a lock-guarded registered-waiter count (Ksem.cpp:82, incremented under the lock taken at :79). The deadline is converted before WaitUntil releases that lock at :102, so the test only proceeds once the conversion has run. AbsoluteTimeouts expects 1 waiter, TimedWakeup expects 2, and the test fails if the waiter finishes first. Windows CI is green on this head.

@harry-z-kang
harry-z-kang force-pushed the codex/fix-ksem-windows-timeouts branch from 812490e to d371daf Compare November 7, 2026 19:34
@harry-z-kang
harry-z-kang force-pushed the codex/fix-ksem-windows-timeouts branch from d371daf to b77f99c Compare November 8, 2026 05:20
@oneandonlydean
oneandonlydean merged commit 34744ad into boykopovar:main Nov 8, 2026
13 of 14 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants