Merge pull request #1676 from Recapi/feat/libkernel-thread-cpu-clock

feat(libkernel): implement pthread_getcpuclockid and per-thread CPU clocks
This commit is contained in:
Adrià
2026-10-10 00:01:18 +02:00
committed by GitHub
6 changed files with 256 additions and 1 deletions
+10
View File
@@ -277,6 +277,16 @@ if(BUILD_TESTING)
set_tests_properties(guest_freebsd_clocks PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libkernel>")
endif()
add_test_executable(guest_thread_cpu_clock_tests ${LIBS_INCLUDE_DIR}/tests/GuestThreadCpuClock.cpp)
target_include_directories(guest_thread_cpu_clock_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(guest_thread_cpu_clock_tests PRIVATE libkernel libc)
configure_windows_unwind(guest_thread_cpu_clock_tests)
add_test(NAME guest_thread_cpu_clock COMMAND guest_thread_cpu_clock_tests)
set_tests_properties(guest_thread_cpu_clock PROPERTIES TIMEOUT 30)
if(WIN32)
set_tests_properties(guest_thread_cpu_clock PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libkernel>")
endif()
add_test_executable(guest_nanosleep_tests ${LIBS_INCLUDE_DIR}/tests/GuestNanosleep.cpp)
target_include_directories(guest_nanosleep_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(guest_nanosleep_tests PRIVATE libkernel libc)
@@ -83,6 +83,14 @@ int APS5_VABI pthread_equal_nid_postfix(Pthread first, Pthread second) {
return first == second;
}
int APS5_VABI pthread_getcpuclockid_nid_postfix(Pthread thread, int* clockId) {
constexpr int guestFault = 14;
if (!thread) return PosixThread::GUEST_EINVAL;
if (!clockId) return guestFault;
*clockId = GuestThreadCpuClockId(thread);
return 0;
}
int APS5_VABI sched_yield_nid_postfix(void) {
std::this_thread::yield();
return 0;
@@ -9,6 +9,7 @@
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <ctime>
#include <mutex>
#include <shared_mutex>
#include <string>
@@ -63,6 +64,9 @@ struct PthreadSemPrivate {
static constexpr KernelCpumask DEFAULT_THREAD_AFFINITY = 0x1FFF;
static constexpr int DEFAULT_THREAD_PRIORITY = 700;
static constexpr std::uint32_t CPU_CLOCK_BIT = 0x80000000u;
static constexpr std::uint32_t CPU_CLOCK_PROCESS_BIT = 0x40000000u;
static constexpr std::uint32_t CPU_CLOCK_ID_MASK = ~(CPU_CLOCK_BIT | CPU_CLOCK_PROCESS_BIT);
inline int GuestCpuFromHost(unsigned hostCpu, KernelCpumask threadAffinity) {
KernelCpumask mask = threadAffinity & DEFAULT_THREAD_AFFINITY;
@@ -96,6 +100,11 @@ struct PthreadPrivate {
std::atomic<int> waitCount{0};
std::atomic<KernelCpumask> affinity{DEFAULT_THREAD_AFFINITY};
std::atomic<int> priority{DEFAULT_THREAD_PRIORITY};
int cpuClockThread = 0;
#ifndef _WIN32
clockid_t hostCpuClock{};
bool hostCpuClockBound = false;
#endif
std::mutex nameLock;
std::string name;
std::atomic<bool> _finished;
@@ -105,9 +114,14 @@ struct PthreadPrivate {
std::mutex _join_mtx;
std::condition_variable _join_cv;
PthreadPrivate() : _finished(false), _retval(nullptr), _detached(false), _adopted(false) {}
PthreadPrivate();
~PthreadPrivate();
PthreadPrivate(const PthreadPrivate&) = delete;
PthreadPrivate& operator=(const PthreadPrivate&) = delete;
};
bool GuestThreadStack(std::uintptr_t address, std::uintptr_t* start, std::uintptr_t* end);
int GuestThreadCpuClockId(const PthreadPrivate* thread);
bool GuestThreadCpuNanos(int cpuClockThread, std::uint64_t* nanos);
#endif
@@ -17,6 +17,7 @@
#include <system_error>
#ifndef _WIN32
#include <cerrno>
#include <csetjmp>
#include <pthread.h>
#endif
@@ -119,6 +120,90 @@ bool GuestThreadStack(std::uintptr_t address, std::uintptr_t* start, std::uintpt
}
return false;
}
struct CpuClockRegistry {
std::mutex lock;
std::map<int, PthreadPrivate*> threads;
int nextThread = 100000;
};
static CpuClockRegistry& CpuClocks() {
static auto* registry = new CpuClockRegistry();
return *registry;
}
PthreadPrivate::PthreadPrivate() : _finished(false), _retval(nullptr), _detached(false), _adopted(false) {
auto& registry = CpuClocks();
std::lock_guard lock(registry.lock);
if (registry.nextThread > static_cast<int>(CPU_CLOCK_ID_MASK))
throw std::runtime_error("Guest thread CPU clock identifiers are exhausted");
cpuClockThread = registry.nextThread++;
registry.threads.emplace(cpuClockThread, this);
}
PthreadPrivate::~PthreadPrivate() {
auto& registry = CpuClocks();
std::lock_guard lock(registry.lock);
registry.threads.erase(cpuClockThread);
}
static void BindHostCpuClock(PthreadPrivate* self) {
#ifdef _WIN32
(void)self;
#else
clockid_t clock{};
const int error = pthread_getcpuclockid(pthread_self(), &clock);
if (error != 0)
throw std::system_error(error, std::generic_category(), "Querying the guest thread CPU clock");
auto& registry = CpuClocks();
std::lock_guard lock(registry.lock);
self->hostCpuClock = clock;
self->hostCpuClockBound = true;
#endif
}
int GuestThreadCpuClockId(const PthreadPrivate* thread) {
return static_cast<int>(CPU_CLOCK_BIT | static_cast<std::uint32_t>(thread->cpuClockThread));
}
bool GuestThreadCpuNanos(int cpuClockThread, std::uint64_t* nanos) {
auto& registry = CpuClocks();
std::lock_guard lock(registry.lock);
const auto found = registry.threads.find(cpuClockThread);
if (found == registry.threads.end())
return false;
PthreadPrivate* thread = found->second;
if (thread->_finished.load(std::memory_order_acquire))
return false;
#ifdef _WIN32
if (thread->nativeHandle == nullptr) {
*nanos = 0;
return true;
}
if (WaitForSingleObject(thread->nativeHandle, 0) == WAIT_OBJECT_0)
return false;
FILETIME creation{};
FILETIME exitTime{};
FILETIME kernel{};
FILETIME user{};
if (!GetThreadTimes(thread->nativeHandle, &creation, &exitTime, &kernel, &user))
throw std::system_error(GetLastError(), std::system_category(), "Querying guest thread CPU time");
const auto toTicks = [](const FILETIME& time) {
return (static_cast<std::uint64_t>(time.dwHighDateTime) << 32) | time.dwLowDateTime;
};
*nanos = (toTicks(user) + toTicks(kernel)) * 100ULL;
#else
if (!thread->hostCpuClockBound) {
*nanos = 0;
return true;
}
struct timespec time{};
if (clock_gettime(thread->hostCpuClock, &time) != 0)
throw std::system_error(errno, std::generic_category(), "Querying guest thread CPU time");
*nanos = static_cast<std::uint64_t>(time.tv_sec) * 1000000000ULL + static_cast<std::uint64_t>(time.tv_nsec);
#endif
return true;
}
#ifndef _WIN32
static thread_local std::unique_ptr<PthreadPrivate> adoptedThread;
// pthread_exit force-unwinds through guest frames, whose personality resolves to
@@ -174,6 +259,7 @@ static void RunThread(std::unique_ptr<ThreadArgs> args) {
const auto entry = args->entry;
void* arg = args->arg;
PthreadPrivate* self = args->self;
BindHostCpuClock(self);
TimedWait::BindThreadWaitState(&self->waitCount);
if (!self->stackAddress) SetStackFromHost(self);
currentThread = self;
@@ -417,6 +503,7 @@ Pthread APS5_VABI scePthreadSelf() {
adoptedThread = std::make_unique<PthreadPrivate>();
adoptedThread->_detached = true;
adoptedThread->_adopted = true;
BindHostCpuClock(adoptedThread.get());
adoptedThread->threadId = std::this_thread::get_id();
SetStackFromHost(adoptedThread.get());
currentThread = adoptedThread.get();
+25
View File
@@ -3,6 +3,7 @@
#include "prx/libc/include/General.hpp"
#include "prx/libkernel/KernelErrors.hpp"
#include "prx/libkernel/Pthread/include/Pthread.hpp"
#include <algorithm>
#include <cerrno>
#include <cstdint>
@@ -29,6 +30,18 @@
extern "C" int* APS5_VABI __error_nid_postfix();
static constexpr int GUEST_EINVAL = 22;
static constexpr int GUEST_CLOCK_THREAD_CPUTIME_ID = 14;
static bool IsCpuClock(int clockId) {
const auto bits = static_cast<std::uint32_t>(clockId);
if ((bits & CPU_CLOCK_BIT) == 0)
return false;
if ((bits & CPU_CLOCK_PROCESS_BIT) != 0)
throw std::runtime_error("clock: unsupported process CPU clock_id " + std::to_string(clockId));
return true;
}
static std::uint64_t RawMonotonicNanos() {
#ifdef _WIN32
return TimedWait::NowNanos();
@@ -329,6 +342,16 @@ int APS5_VABI clock_gettime_nid_postfix(int clockId, KernelTimespec* tp) {
if (tp == nullptr) {
APS5_INVALID_ARG_EX;
}
if (IsCpuClock(clockId)) {
std::uint64_t nanos = 0;
if (!GuestThreadCpuNanos(static_cast<int>(static_cast<std::uint32_t>(clockId) & CPU_CLOCK_ID_MASK), &nanos)) {
*__error_nid_postfix() = GUEST_EINVAL;
return -1;
}
tp->tv_sec = static_cast<std::int64_t>(nanos / 1000000000ULL);
tp->tv_nsec = static_cast<std::int64_t>(nanos % 1000000000ULL);
return 0;
}
if (clockId == 1 || clockId == 2) {
const std::uint64_t nanos = ProcessCpuNanos(clockId == 2);
tp->tv_sec = static_cast<std::int64_t>(nanos / 1000000000ULL);
@@ -443,6 +466,8 @@ int APS5_VABI clock_getres_nid_postfix(int clockId, KernelTimespec* res) {
if (res == nullptr) {
APS5_INVALID_ARG_EX;
}
if (IsCpuClock(clockId))
return clock_getres_nid_postfix(GUEST_CLOCK_THREAD_CPUTIME_ID, res);
if (clockId == 1 || clockId == 2) {
const std::uint64_t nanos = ProcessCpuResolutionNanos();
res->tv_sec = static_cast<std::int64_t>(nanos / 1000000000ULL);
+111
View File
@@ -0,0 +1,111 @@
#include "SceTypes.hpp"
#include <atomic>
#include <chrono>
#include <cstdint>
#include <cstdlib>
#include <thread>
extern "C" {
int APS5_VABI pthread_getcpuclockid_nid_postfix(Pthread thread, int* clockId);
Pthread APS5_VABI pthread_self_nid_postfix(void);
int APS5_VABI clock_gettime_nid_postfix(int clockId, KernelTimespec* tp);
int APS5_VABI clock_getres_nid_postfix(int clockId, KernelTimespec* res);
int APS5_VABI scePthreadCreate(Pthread* thread, const PthreadAttr* attr, PthreadEntry entry, void* arg, const char* name);
int APS5_VABI scePthreadJoin(Pthread thread, void** retval);
int* APS5_VABI __error_nid_postfix();
}
static constexpr int GUEST_EFAULT = 14;
static constexpr int GUEST_EINVAL = 22;
static constexpr int GUEST_CLOCK_MONOTONIC = 4;
static constexpr int GUEST_CLOCK_THREAD_CPUTIME_ID = 14;
static constexpr std::int64_t NANOS_PER_SECOND = 1000000000LL;
static constexpr std::int64_t NANOS_PER_MILLISECOND = 1000000LL;
static constexpr std::int64_t BURN_NANOS = 200 * NANOS_PER_MILLISECOND;
static constexpr std::int64_t TICK_MARGIN_NANOS = 50 * NANOS_PER_MILLISECOND;
static constexpr std::int64_t GIVE_UP_NANOS = 10 * NANOS_PER_SECOND;
static void Require(bool value) { if (!value) std::abort(); }
static std::int64_t Nanos(int clockId) {
KernelTimespec time{-1, -1};
Require(clock_gettime_nid_postfix(clockId, &time) == 0);
Require(time.tv_sec >= 0);
Require(time.tv_nsec >= 0 && time.tv_nsec < NANOS_PER_SECOND);
return time.tv_sec * NANOS_PER_SECOND + time.tv_nsec;
}
static int CpuClock(Pthread thread) {
int clockId = 0;
Require(pthread_getcpuclockid_nid_postfix(thread, &clockId) == 0);
return clockId;
}
static void BurnOwnCpu(std::int64_t nanos) {
const std::int64_t wallStart = Nanos(GUEST_CLOCK_MONOTONIC);
const std::int64_t cpuStart = Nanos(GUEST_CLOCK_THREAD_CPUTIME_ID);
while (Nanos(GUEST_CLOCK_THREAD_CPUTIME_ID) - cpuStart < nanos)
Require(Nanos(GUEST_CLOCK_MONOTONIC) - wallStart < GIVE_UP_NANOS);
}
static std::atomic<int> workerClock{0};
static std::atomic<bool> workerBurned{false};
static std::atomic<bool> releaseWorker{false};
static void* APS5_VABI Worker(void*) {
workerClock.store(CpuClock(pthread_self_nid_postfix()));
BurnOwnCpu(BURN_NANOS);
workerBurned.store(true);
while (!releaseWorker.load())
std::this_thread::sleep_for(std::chrono::milliseconds(5));
return nullptr;
}
static void OwnClockFollowsThreadCpuTime() {
const int own = CpuClock(pthread_self_nid_postfix());
Require((static_cast<std::uint32_t>(own) & 0xC0000000u) == 0x80000000u);
Require(CpuClock(pthread_self_nid_postfix()) == own);
const std::int64_t start = Nanos(own);
BurnOwnCpu(BURN_NANOS);
const std::int64_t before = Nanos(own);
const std::int64_t reference = Nanos(GUEST_CLOCK_THREAD_CPUTIME_ID);
const std::int64_t after = Nanos(own);
Require(before - start >= BURN_NANOS - TICK_MARGIN_NANOS);
Require(before <= reference + TICK_MARGIN_NANOS && reference <= after + TICK_MARGIN_NANOS);
KernelTimespec ownResolution{-1, -1};
KernelTimespec threadResolution{-1, -1};
Require(clock_getres_nid_postfix(own, &ownResolution) == 0);
Require(clock_getres_nid_postfix(GUEST_CLOCK_THREAD_CPUTIME_ID, &threadResolution) == 0);
Require(ownResolution.tv_sec == threadResolution.tv_sec && ownResolution.tv_nsec == threadResolution.tv_nsec);
}
static void OtherThreadClockReadsThatThread() {
Pthread worker = nullptr;
Require(scePthreadCreate(&worker, nullptr, Worker, nullptr, "cpu clock worker") == 0);
const std::int64_t wallStart = Nanos(GUEST_CLOCK_MONOTONIC);
while (!workerBurned.load()) {
Require(Nanos(GUEST_CLOCK_MONOTONIC) - wallStart < GIVE_UP_NANOS);
std::this_thread::sleep_for(std::chrono::milliseconds(5));
}
const int clockId = workerClock.load();
Require(clockId == CpuClock(worker));
Require(clockId != CpuClock(pthread_self_nid_postfix()));
const std::int64_t burned = Nanos(clockId);
Require(burned >= BURN_NANOS - TICK_MARGIN_NANOS);
BurnOwnCpu(BURN_NANOS);
Require(Nanos(clockId) - burned <= TICK_MARGIN_NANOS);
releaseWorker.store(true);
Require(scePthreadJoin(worker, nullptr) == 0);
KernelTimespec time{-1, -1};
*__error_nid_postfix() = 0;
Require(clock_gettime_nid_postfix(clockId, &time) == -1);
Require(*__error_nid_postfix() == GUEST_EINVAL);
}
int main() {
int clockId = 0;
Require(pthread_getcpuclockid_nid_postfix(nullptr, &clockId) == GUEST_EINVAL);
Require(pthread_getcpuclockid_nid_postfix(pthread_self_nid_postfix(), nullptr) == GUEST_EFAULT);
OwnClockFollowsThreadCpuTime();
OtherThreadClockReadsThatThread();
}