Repository navigation
fix(libkernel): honor absolute ksem wait deadlines precisely - #14228
oneandonlydean merged 2 commits into
Conversation
MarcZX10
left a comment
There was a problem hiding this comment.
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 jobsResults
| 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
- Reviewed semaphore implementation and tests, pinned to head
- Repository test registration and build workflow result
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.
|
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.
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.
|
|
@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. |
|
Independent Linux runtime check of the far-future deadline path for head Method: a standalone probe linked to the real Observed A–B–A result, using the unchanged probe executable:
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: Scope: this confirms the production far-future path under Linux/glibc. It does not repair the synchronization in Host: CachyOS Linux Representative raw observations and reproduction commandsSave the source below as 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)$' -VProbe executable SHA-256: 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). |
|
A Windows run with GCC 16: Windows 11 Pro 10.0.22631, i9-9900K, MSYS2 UCRT64 GCC 16.1.0, Release, this PR (
AI-assisted: yes (Claude Code) |
91b0a61 to
ca542d1
Compare
|
@MarcZX10 Addressed in 812490e71b. Both I reran the negative control with main The PR description is updated with these results. Could you review this again? GitHub rejected the formal review re-request for my account ( |
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.
812490e to
d371daf
Compare
d371daf to
b77f99c
Compare
What
Use
TimedWait::Conditionfor kernel semaphore waits and check the absolute realtime deadline after each wake. This removes the remaining winpthreads timed wait fromksem_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=ONand adds no guest NID.Tested
Rebased 2026-11-07: head
b77f99c9ff, independently based on main8eb293447e.git range-diffconfirms 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.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_semandguest_semaphore.Negative control captured 2026-11-05 for the synchronized tests: restored main
1be4c77a8d'sKsem.cppand added only the test-gated waiter-count accessor, leaving the updated tests in place.guest_kernel_sys_ksemfailed 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 --checkand 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 headsb208fd6b21,d07deaa187, andc045c1e91f, 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=ONworkaround for #12994; installation was not tested. Linux/macOS and titles were not run.Checklist
main; no other open PR implements the same functionsNotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file.mdfiles or images added to the repository (attach them to this PR)