[common/client] platform: make timing waits portable

This commit is contained in:
Geoffrey McRae
2026-09-12 08:13:16 +10:00
parent d045ac6ba7
commit 9c8343df96
18 changed files with 351 additions and 161 deletions

View File

@@ -22,9 +22,10 @@
#define _H_LG_COMMON_EVENT_
#include <stdbool.h>
#include <time.h>
#include <stdint.h>
#define TIMEOUT_INFINITE ((unsigned int)~0)
#define TIMEOUT_INFINITE_NS UINT64_MAX
typedef struct LGEvent LGEvent;
@@ -38,8 +39,7 @@ bool lgResetEvent (LGEvent * handle);
// for windows this is an event HANDLE
LGEvent * lgWrapEvent(void * handle);
// Posix specific, not implmented/possible in windows
bool lgWaitEventAbs(LGEvent * handle, struct timespec * ts);
bool lgWaitEventNS (LGEvent * handle, unsigned int timeout);
bool lgWaitEventDeadline(LGEvent * handle, uint64_t deadlineNs);
bool lgWaitEventNS (LGEvent * handle, uint64_t timeoutNs);
#endif

View File

@@ -20,120 +20,15 @@
#pragma once
#include <stdint.h>
#include <stdbool.h>
#include <time.h>
#include "common/util.h"
#if defined(_WIN32)
#include <windows.h>
void windowsSetTimerResolution(void);
NTSYSCALLAPI NTSTATUS NTAPI NtDelayExecution(
_In_ BOOLEAN Alertable,
_In_opt_ PLARGE_INTEGER DelayInterval
);
#endif
#include <stdint.h>
typedef struct LGTimer LGTimer;
static inline uint64_t microtime(void)
{
#if defined(_WIN32)
static unsigned long div = 0;
if (unlikely(div == 0))
{
LARGE_INTEGER freq = { .QuadPart = 0LL };
QueryPerformanceFrequency(&freq);
div = freq.QuadPart / 1000000LL;
if(div == 0)
abort();
}
LARGE_INTEGER time;
QueryPerformanceCounter(&time);
return time.QuadPart / div;
#else
struct timespec time;
clock_gettime(CLOCK_MONOTONIC, &time);
return (uint64_t)time.tv_sec * 1000000LL + time.tv_nsec / 1000LL;
#endif
}
static inline void nsleep(uint64_t ns)
{
#if defined(_WIN32)
LARGE_INTEGER interval = { .QuadPart = -(int64_t)(ns / 100LL) };
NtDelayExecution(FALSE, &interval);
#else
const struct timespec ts =
{
.tv_sec = ns / 1000000000,
.tv_nsec = ns % 1000000000,
};
nanosleep(&ts, NULL);
#endif
}
static inline uint64_t nanotime(void)
{
#if defined(_WIN32)
static double multiplier = 0.0;
if (unlikely(!multiplier))
{
LARGE_INTEGER freq = { .QuadPart = 0LL };
QueryPerformanceFrequency(&freq);
if (freq.QuadPart == 0)
abort();
multiplier = 1e9 / freq.QuadPart;
}
LARGE_INTEGER time;
QueryPerformanceCounter(&time);
return (uint64_t) (time.QuadPart * multiplier);
#else
struct timespec time;
clock_gettime(CLOCK_MONOTONIC_RAW, &time);
return ((uint64_t)time.tv_sec * 1000000000LL) + time.tv_nsec;
#endif
}
static inline void tsDiff(struct timespec *diff, const struct timespec *left,
const struct timespec *right)
{
diff->tv_sec = left->tv_sec - right->tv_sec;
diff->tv_nsec = left->tv_nsec - right->tv_nsec;
if (diff->tv_nsec < 0)
{
--diff->tv_sec;
diff->tv_nsec += 1000000000;
}
}
static inline uint32_t __iter_div_u64_rem(uint64_t dividend, uint32_t divisor, uint64_t *remainder)
{
uint32_t ret = 0;
while (dividend >= divisor) {
/* The following asm() prevents the compiler from
optimising this loop into a modulo operation. */
asm("" : "+rm"(dividend));
dividend -= divisor;
ret++;
}
*remainder = dividend;
return ret;
}
static inline void tsAdd(struct timespec *a, uint64_t ns)
{
a->tv_sec += __iter_div_u64_rem(a->tv_nsec + ns, 1000000000L, &ns);
a->tv_nsec = ns;
}
void lgTimeInit(void);
uint64_t microtime (void);
uint64_t nanotime (void);
void nsleep (uint64_t ns);
typedef bool (*LGTimerFn)(void * udata);

View File

@@ -21,6 +21,7 @@
#include "common/event.h"
#include "common/debug.h"
#include "common/time.h"
#include <stdlib.h>
#include <pthread.h>
@@ -87,7 +88,7 @@ void lgFreeEvent(LGEvent * handle)
free(handle);
}
bool lgWaitEventAbs(LGEvent * handle, struct timespec * ts)
static bool waitEventAbs(LGEvent * handle, const struct timespec * ts)
{
DEBUG_ASSERT(handle);
@@ -143,32 +144,38 @@ bool lgWaitEventAbs(LGEvent * handle, struct timespec * ts)
return ret;
}
static bool waitEventNS(LGEvent * handle, uint64_t timeout)
bool lgWaitEventDeadline(LGEvent * handle, uint64_t deadlineNs)
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
if (deadlineNs == TIMEOUT_INFINITE_NS)
return waitEventAbs(handle, NULL);
const uint64_t nsec = (uint64_t)ts.tv_nsec + timeout;
ts.tv_sec += nsec / 1000000000ULL;
ts.tv_nsec = nsec % 1000000000ULL;
return lgWaitEventAbs(handle, &ts);
const struct timespec ts =
{
.tv_sec = deadlineNs / UINT64_C(1000000000),
.tv_nsec = deadlineNs % UINT64_C(1000000000),
};
return waitEventAbs(handle, &ts);
}
bool lgWaitEventNS(LGEvent * handle, unsigned int timeout)
bool lgWaitEventNS(LGEvent * handle, uint64_t timeoutNs)
{
if (timeout == TIMEOUT_INFINITE)
return lgWaitEventAbs(handle, NULL);
if (timeoutNs == TIMEOUT_INFINITE_NS)
return waitEventAbs(handle, NULL);
return waitEventNS(handle, timeout);
const uint64_t now = nanotime();
if (UINT64_MAX - now < timeoutNs)
return waitEventAbs(handle, NULL);
return lgWaitEventDeadline(handle, now + timeoutNs);
}
bool lgWaitEvent(LGEvent * handle, unsigned int timeout)
{
if (timeout == TIMEOUT_INFINITE)
return lgWaitEventAbs(handle, NULL);
return waitEventAbs(handle, NULL);
return waitEventNS(handle, (uint64_t)timeout * 1000000ULL);
return lgWaitEventNS(handle,
(uint64_t)timeout * UINT64_C(1000000));
}
bool lgSignalEvent(LGEvent * handle)

View File

@@ -46,6 +46,44 @@ struct LGTimer
static struct LGTimerState l_ts = { 0 };
void lgTimeInit(void)
{
}
uint64_t microtime(void)
{
struct timespec time;
clock_gettime(CLOCK_MONOTONIC, &time);
return (uint64_t)time.tv_sec * UINT64_C(1000000) +
(uint64_t)time.tv_nsec / UINT64_C(1000);
}
uint64_t nanotime(void)
{
struct timespec time;
clock_gettime(CLOCK_MONOTONIC, &time);
return (uint64_t)time.tv_sec * UINT64_C(1000000000) +
(uint64_t)time.tv_nsec;
}
void nsleep(uint64_t ns)
{
struct timespec remaining =
{
.tv_sec = ns / UINT64_C(1000000000),
.tv_nsec = ns % UINT64_C(1000000000),
};
while (nanosleep(&remaining, &remaining) != 0 && errno == EINTR) {}
}
static void timespecAdd(struct timespec * time, uint64_t ns)
{
const uint64_t nsec = (uint64_t)time->tv_nsec + ns;
time->tv_sec += nsec / UINT64_C(1000000000);
time->tv_nsec = nsec % UINT64_C(1000000000);
}
static int timerFn(void * fn)
{
struct LGTimer * timer;
@@ -67,7 +105,7 @@ static int timerFn(void * fn)
}
ll_unlock(l_ts.timers);
tsAdd(&time, 1000000);
timespecAdd(&time, UINT64_C(1000000));
while(clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &time, NULL) != 0) {}
}

View File

@@ -27,6 +27,8 @@
LGEvent * lgCreateEvent(bool autoReset, unsigned int msSpinTime)
{
(void)msSpinTime;
HANDLE handle = CreateEvent(NULL, autoReset ? FALSE : TRUE, FALSE, NULL);
if (!handle)
{
@@ -77,6 +79,30 @@ bool lgWaitEvent(LGEvent * event, unsigned int timeout)
while(true);
}
bool lgWaitEventNS(LGEvent * event, uint64_t timeoutNs)
{
if (timeoutNs == TIMEOUT_INFINITE_NS)
return lgWaitEvent(event, TIMEOUT_INFINITE);
const uint64_t timeoutMs = timeoutNs / UINT64_C(1000000) +
(timeoutNs % UINT64_C(1000000) != 0);
return lgWaitEvent(event,
timeoutMs >= TIMEOUT_INFINITE ? TIMEOUT_INFINITE - 1U :
(unsigned int)timeoutMs);
}
bool lgWaitEventDeadline(LGEvent * event, uint64_t deadlineNs)
{
if (deadlineNs == TIMEOUT_INFINITE_NS)
return lgWaitEvent(event, TIMEOUT_INFINITE);
const uint64_t now = nanotime();
if (deadlineNs <= now)
return lgWaitEvent(event, 0);
return lgWaitEventNS(event, deadlineNs - now);
}
bool lgSignalEvent(LGEvent * event)
{
return SetEvent((HANDLE)event);

View File

@@ -20,28 +20,92 @@
#include "common/time.h"
#include "common/debug.h"
#include "common/windebug.h"
// decared by the platform
extern HWND MessageHWND;
#include <stdatomic.h>
#include <stdlib.h>
#include <windows.h>
NTSYSCALLAPI NTSTATUS NTAPI NtDelayExecution(
_In_ BOOLEAN Alertable,
_In_opt_ PLARGE_INTEGER DelayInterval
);
struct LGTimer
{
LGTimerFn fn;
void * udata;
UINT_PTR handle;
bool running;
HANDLE handle;
atomic_bool running;
};
static void TimerProc(HWND Arg1, UINT Arg2, UINT_PTR Arg3, DWORD Arg4)
static uint64_t performanceFrequency(void)
{
LGTimer * timer = (LGTimer *)Arg3;
static atomic_uint_fast64_t cached;
uint64_t result = atomic_load_explicit(&cached, memory_order_acquire);
if (result)
return result;
LARGE_INTEGER value;
if (!QueryPerformanceFrequency(&value) || value.QuadPart <= 0)
abort();
result = value.QuadPart;
atomic_store_explicit(&cached, result, memory_order_release);
return result;
}
static VOID CALLBACK timerProc(PVOID opaque, BOOLEAN fired)
{
(void)fired;
LGTimer * timer = opaque;
if (!atomic_load_explicit(&timer->running, memory_order_acquire))
return;
if (!timer->fn(timer->udata))
{
KillTimer(Arg1, timer->handle);
timer->running = false;
atomic_store_explicit(&timer->running, false, memory_order_release);
if (!ChangeTimerQueueTimer(NULL, timer->handle, INFINITE, 0))
DEBUG_WINERROR("Failed to stop timer", GetLastError());
}
}
uint64_t microtime(void)
{
LARGE_INTEGER value;
QueryPerformanceCounter(&value);
const uint64_t frequency = performanceFrequency();
const uint64_t seconds = (uint64_t)value.QuadPart / frequency;
const uint64_t ticks = (uint64_t)value.QuadPart % frequency;
return seconds * UINT64_C(1000000) +
ticks * UINT64_C(1000000) / frequency;
}
uint64_t nanotime(void)
{
LARGE_INTEGER value;
QueryPerformanceCounter(&value);
const uint64_t frequency = performanceFrequency();
const uint64_t seconds = (uint64_t)value.QuadPart / frequency;
const uint64_t ticks = (uint64_t)value.QuadPart % frequency;
return seconds * UINT64_C(1000000000) +
ticks * UINT64_C(1000000000) / frequency;
}
void nsleep(uint64_t ns)
{
if (!ns)
return;
LARGE_INTEGER interval =
{
.QuadPart = -(int64_t)((ns + UINT64_C(99)) / UINT64_C(100)),
};
NtDelayExecution(FALSE, &interval);
}
bool lgCreateTimer(const unsigned int intervalMS, LGTimerFn fn,
void * udata, LGTimer ** result)
{
@@ -52,10 +116,18 @@ bool lgCreateTimer(const unsigned int intervalMS, LGTimerFn fn,
return false;
}
ret->fn = fn;
ret->udata = udata;
ret->running = true;
ret->handle = SetTimer(MessageHWND, (UINT_PTR)ret, intervalMS, TimerProc);
ret->fn = fn;
ret->udata = udata;
ret->handle = NULL;
atomic_init(&ret->running, true);
if (!CreateTimerQueueTimer(&ret->handle, NULL, timerProc, ret,
intervalMS, intervalMS, WT_EXECUTEDEFAULT))
{
DEBUG_WINERROR("Failed to create timer", GetLastError());
free(ret);
return false;
}
*result = ret;
return true;
@@ -63,10 +135,13 @@ bool lgCreateTimer(const unsigned int intervalMS, LGTimerFn fn,
void lgTimerDestroy(LGTimer * timer)
{
if (timer->running)
atomic_store_explicit(&timer->running, false, memory_order_release);
if (timer->handle &&
!DeleteTimerQueueTimer(NULL, timer->handle, INVALID_HANDLE_VALUE))
{
if (MessageHWND && !KillTimer(MessageHWND, timer->handle))
DEBUG_ERROR("failed to destroy the timer");
const DWORD error = GetLastError();
if (error != ERROR_IO_PENDING)
DEBUG_WINERROR("Failed to destroy timer", error);
}
free(timer);
@@ -78,7 +153,7 @@ NTSYSCALLAPI NTSTATUS NTAPI NtSetTimerResolution(
_Out_ PULONG ActualTime
);
void windowsSetTimerResolution(void)
void lgTimeInit(void)
{
ULONG actualResolution;
NtSetTimerResolution(1, true, &actualResolution);