#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <sys/resource.h>
#if defined(_MSC_VER) && _MSC_VER >= 1400
#include <intrin.h>
#endif
#ifdef HAVE_PPSAPI
#include <timepps.h>
#undef EOPNOTSUPP
#endif
#include "ntp_stdlib.h"
#include "ntp_unixtime.h"
#include "ntp_timer.h"
#include "ntp_assert.h"
#include "ntp_leapsec.h"
#include "clockstuff.h"
#include "ntservice.h"
#include "ntpd.h"
#include "ntpd-opts.h"
extern double sys_residual;
static int modify_mm_timer = MM_TIMER_LORES;
#define MM_TIMER_INTV 1
static UINT wTimerRes;
BOOL init_randfile();
static long last_Adj = 0;
#define LS_CORR_INTV_SECS 2
#define LS_CORR_INTV ( 1000ul * LS_CORR_INTV_SECS )
#define LS_CORR_LIMIT ( 250ul ) // quarter second
typedef union ft_ull {
FILETIME ft;
ULONGLONG ull;
LONGLONG ll;
LARGE_INTEGER li;
} FT_ULL;
static FT_ULL ls_ft;
static DWORD ls_time_adjustment;
static BOOL winnt_time_initialized = FALSE;
static BOOL winnt_use_interpolation = FALSE;
static unsigned clock_thread_id;
void WINAPI GetInterpTimeAsFileTime(LPFILETIME pft);
static void StartClockThread(void);
static void tune_ctr_freq(LONGLONG, LONGLONG);
void StopClockThread(void);
void atexit_revert_mm_timer(void);
void win_time_stepped(void);
static HANDLE clock_thread = NULL;
static HANDLE TimerThreadExitRequest = NULL;
ULONGLONG interp_time(ULONGLONG, BOOL);
void add_counter_time_pair(ULONGLONG, LONGLONG);
#define BASELINES_TOT 256
#define BASELINES_USED 64
static volatile int newest_baseline = 0;
static volatile int newest_baseline_gen = 0;
static ULONGLONG baseline_counts[BASELINES_TOT] = {0};
static LONGLONG baseline_times[BASELINES_TOT] = {0};
#define CLOCK_BACK_THRESHOLD 100
static ULONGLONG clock_backward_max = CLOCK_BACK_THRESHOLD;
static int clock_backward_count;
static BOOL os_ignores_small_adjustment;
static DWORD clockperiod;
static ULONGLONG os_clock_precision;
volatile ULONGLONG PerfCtrFreq = 0;
ULONGLONG NomPerfCtrFreq = 0;
static LONGLONG QPC_offset = 0;
static int use_pcc = -1;
static int lock_interp_threads = -1;
static DOUBLE ppm_per_adjust_unit;
static long wintickadj;
static void choose_interp_counter(void);
static int is_qpc_built_on_pcc(void);
#define TUNE_CTR_DEPTH 3
static HANDLE ctr_freq_timer = INVALID_HANDLE_VALUE;
static ULONGLONG tune_ctr_freq_max_interval;
static unsigned tune_ctr_period;
void start_ctr_freq_timer(ULONGLONG now_time);
void reset_ctr_freq_timer(ULONGLONG when, ULONGLONG now);
void reset_ctr_freq_timer_abs(ULONGLONG when);
#define ROUND_TO_NEXT_SEC_BOTTOM(t) \
do { \
(t) += 3 * HECTONANOSECONDS / 2 - 1; \
(t) /= HECTONANOSECONDS; \
(t) *= HECTONANOSECONDS; \
(t) -= HECTONANOSECONDS / 2; \
} while (0)
#define HNS2PERF(hns) ((hns) * PerfCtrFreq / HECTONANOSECONDS)
#define PERF2HNS(ctr) ((ctr) * HECTONANOSECONDS / PerfCtrFreq)
#if defined(_MSC_VER) && _MSC_VER >= 1400
#define get_pcc() __rdtsc()
#else
ULONGLONG __forceinline
get_pcc(void)
{
__asm {
RDTSC
}
}
#endif
ULONGLONG WINAPI
perf_ctr(void)
{
FT_ULL ft;
if (use_pcc)
return get_pcc();
else {
QueryPerformanceCounter(&ft.li);
return ft.ull;
}
}
static void init_small_adjustment(void)
{
OSVERSIONINFO vi;
memset(&vi, 0, sizeof(vi));
vi.dwOSVersionInfoSize = sizeof(vi);
if (!GetVersionEx(&vi)) {
msyslog(LOG_WARNING, "GetVersionEx failed with error code %d.", GetLastError());
os_ignores_small_adjustment = FALSE;
return;
}
if (vi.dwMajorVersion == 6 && vi.dwMinorVersion == 1) {
os_ignores_small_adjustment = TRUE;
} else if (vi.dwMajorVersion == 6 && vi.dwMinorVersion == 0) {
os_ignores_small_adjustment = TRUE;
} else {
os_ignores_small_adjustment = FALSE;
}
}
static void
choose_interp_counter(void)
{
const char * ntpd_pcc_freq_text;
int qpc_built_on_pcc;
qpc_built_on_pcc = is_qpc_built_on_pcc();
lock_interp_threads = qpc_built_on_pcc;
if (HAVE_OPT(PCCFREQ))
ntpd_pcc_freq_text = OPT_ARG(PCCFREQ);
else
ntpd_pcc_freq_text = getenv("NTPD_PCC_FREQ");
if (!HAVE_OPT(USEPCC)
&& NULL == ntpd_pcc_freq_text
&& NULL == getenv("NTPD_PCC")) {
use_pcc = 0;
return;
}
if (!qpc_built_on_pcc && NULL == ntpd_pcc_freq_text) {
use_pcc = 0;
return;
}
use_pcc = 1;
if (ntpd_pcc_freq_text != NULL)
sscanf(ntpd_pcc_freq_text,
"%llu",
&NomPerfCtrFreq);
NLOG(NLOG_CLOCKINFO)
msyslog(LOG_INFO,
"using processor cycle counter "
"%.3f MHz",
NomPerfCtrFreq / 1e6);
return;
}
static int
is_qpc_built_on_pcc(void)
{
LONGLONG offset;
FT_ULL ft1;
FT_ULL ft2;
FT_ULL ft3;
FT_ULL ft4;
FT_ULL ft5;
REQUIRE(NomPerfCtrFreq != 0);
QueryPerformanceCounter(&ft1.li);
ft2.ull = get_pcc();
Sleep(1);
QueryPerformanceCounter(&ft3.li);
Sleep(1);
ft4.ull = get_pcc();
Sleep(1);
QueryPerformanceCounter(&ft5.li);
offset = ft2.ull - ft1.ull;
ft3.ull += offset;
ft5.ull += offset;
if (ft2.ull <= ft3.ull &&
ft3.ull <= ft4.ull &&
ft4.ull <= ft5.ull) {
QPC_offset = offset;
return TRUE;
}
return FALSE;
}
void
set_mm_timer(
int timerres
)
{
modify_mm_timer = timerres;
}
int
adj_systime(
double now
)
{
static const ULONGLONG HNS_JAN_1900 = 94354848000000000ull;
static DWORD ls_start_tick;
static double adjtime_carry;
double dtemp;
u_char isneg;
BOOL rc;
long TimeAdjustment;
SYSTEMTIME st;
DWORD ls_elapsed;
FT_ULL curr_ft;
leap_result_t lsi;
dtemp = adjtime_carry + sys_residual + now;
adjtime_carry = 0.;
sys_residual = 0.;
if (dtemp < 0) {
isneg = TRUE;
dtemp = -dtemp;
} else {
isneg = FALSE;
}
if (dtemp > NTP_MAXFREQ) {
adjtime_carry = dtemp - NTP_MAXFREQ;
dtemp = NTP_MAXFREQ;
}
if (isneg) {
dtemp = -dtemp;
adjtime_carry = -adjtime_carry;
}
dtemp = dtemp * 1e6;
TimeAdjustment = (long)(dtemp / ppm_per_adjust_unit +
((isneg)
? -0.5
: 0.5));
if (os_ignores_small_adjustment) {
if (TimeAdjustment > -16 && TimeAdjustment < 16) {
TimeAdjustment = 0;
}
}
dtemp -= TimeAdjustment * ppm_per_adjust_unit;
if (leapsec >= LSPROX_ALERT) {
if (0 == ls_ft.ull && leapsec_frame(&lsi)) {
if (lsi.tai_diff > 0) {
ls_ft.ull = lsi.ttime.Q_s * HECTONANOSECONDS
+ HNS_JAN_1900;
FileTimeToSystemTime(&ls_ft.ft, &st);
msyslog(LOG_NOTICE,
"Detected positive leap second announcement "
"for %04d-%02d-%02d %02d:%02d:%02d UTC",
st.wYear, st.wMonth, st.wDay,
st.wHour, st.wMinute, st.wSecond);
ls_ft.ull -= (HECTONANOSECONDS + HECTONANOSECONDS/2);
leapsec_electric(TRUE);
} else if (lsi.tai_diff < 0) {
leapsec_electric(FALSE);
}
}
} else {
if (ls_ft.ull != 0 && ls_time_adjustment == 0) {
ls_ft.ull = 0;
msyslog(LOG_NOTICE, "Leap second announcement disarmed");
}
}
if (ls_ft.ull != 0) {
if (0 == ls_time_adjustment) {
GetSystemTimeAsFileTime(&curr_ft.ft);
if (curr_ft.ull >= ls_ft.ull) {
ls_ft.ull = _UI64_MAX;
ls_time_adjustment = clockperiod / LS_CORR_INTV_SECS;
ls_start_tick = GetTickCount();
msyslog(LOG_NOTICE, "Started leap second insertion.");
}
ls_elapsed = 0;
} else {
ls_elapsed = GetTickCount() - ls_start_tick;
}
if (ls_time_adjustment != 0) {
if (ls_elapsed > (LS_CORR_INTV - LS_CORR_LIMIT)) {
ls_time_adjustment = 0;
msyslog(LOG_NOTICE, "Finished leap second insertion.");
}
TimeAdjustment -= ls_time_adjustment;
}
}
sys_residual = dtemp / 1e6;
DPRINTF(3, ("adj_systime: %.9f -> %.9f residual %.9f",
now, 1e-6 * (TimeAdjustment * ppm_per_adjust_unit),
sys_residual));
if (0. == adjtime_carry)
DPRINTF(3, ("\n"));
else
DPRINTF(3, (" adjtime %.9f\n", adjtime_carry));
TimeAdjustment += wintickadj;
if (last_Adj != TimeAdjustment) {
last_Adj = TimeAdjustment;
DPRINTF(2, ("SetSystemTimeAdjustment(%+ld)\n", TimeAdjustment));
rc = SetSystemTimeAdjustment(clockperiod + TimeAdjustment, FALSE);
if (!rc)
msyslog(LOG_ERR, "Can't adjust time: %m");
} else {
rc = TRUE;
}
return rc;
}
void
init_winnt_time(void)
{
static const char settod[] = "settimeofday=\"SetSystemTime\"";
char szMsgPath[MAX_PATH+1];
HANDLE hToken = INVALID_HANDLE_VALUE;
TOKEN_PRIVILEGES tkp;
TIMECAPS tc;
BOOL noslew;
DWORD adjclockperiod;
LARGE_INTEGER Freq;
FT_ULL initial_hectonanosecs;
FT_ULL next_hectonanosecs;
double adjppm;
double rawadj;
char * pch;
if (winnt_time_initialized)
return;
ntservice_init();
if (!SetConsoleCtrlHandler(OnConsoleEvent, TRUE)) {
msyslog(LOG_ERR, "Can't set console control handler: %m");
}
if (!GetModuleFileName(NULL, szMsgPath, sizeof(szMsgPath))) {
msyslog(LOG_ERR, "GetModuleFileName(PGM_EXE_FILE) failed: %m");
exit(1);
}
if (!init_randfile())
msyslog(LOG_ERR, "Unable to initialize .rnd file");
#pragma warning(push)
#pragma warning(disable: 4127)
#ifdef DEBUG
if (SIZEOF_TIME_T != sizeof(time_t)
|| SIZEOF_INT != sizeof(int)
|| SIZEOF_SIGNED_CHAR != sizeof(char)) {
msyslog(LOG_ERR, "config.h SIZEOF_* macros wrong, fatal");
exit(1);
}
#endif
#pragma warning(pop)
init_small_adjustment();
leapsec_electric(TRUE);
if (!OpenProcessToken(
GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
&hToken)) {
msyslog(LOG_ERR, "OpenProcessToken failed: %m");
exit(-1);
}
LookupPrivilegeValue(NULL, SE_SYSTEMTIME_NAME, &tkp.Privileges[0].Luid);
tkp.PrivilegeCount = 1;
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
(PTOKEN_PRIVILEGES) NULL, 0);
if (GetLastError() != ERROR_SUCCESS) {
msyslog(LOG_ERR, "AdjustTokenPrivileges failed: %m");
}
CloseHandle(hToken);
hToken = INVALID_HANDLE_VALUE;
set_sys_var(settod, sizeof(settod), RO);
if (-1 == setpriority(PRIO_PROCESS, 0, NTP_PRIO))
exit(-1);
if (!GetSystemTimeAdjustment(&adjclockperiod, &clockperiod, &noslew)) {
msyslog(LOG_ERR, "GetSystemTimeAdjustment failed: %m");
exit(-1);
}
last_Adj = adjclockperiod - clockperiod;
if (last_Adj)
msyslog(LOG_INFO,
"Clock interrupt period %.3f msec "
"(startup slew %.1f usec/period)",
clockperiod / 1e4,
last_Adj / 10.);
else
msyslog(LOG_INFO,
"Clock interrupt period %.3f msec",
clockperiod / 1e4);
ppm_per_adjust_unit = 1e6 / clockperiod;
pch = getenv("NTPD_TICKADJ_PPM");
if (pch != NULL && 1 == sscanf(pch, "%lf", &adjppm)) {
rawadj = adjppm / ppm_per_adjust_unit;
rawadj += (rawadj < 0)
? -0.5
: 0.5;
wintickadj = (long)rawadj;
msyslog(LOG_INFO,
"Using NTPD_TICKADJ_PPM %+g ppm (%+ld)",
adjppm, wintickadj);
}
if (!QueryPerformanceFrequency(&Freq) || !Freq.QuadPart) {
msyslog(LOG_ERR, "QueryPerformanceFrequency failed: %m");
exit(-1);
}
NomPerfCtrFreq = PerfCtrFreq = Freq.QuadPart;
msyslog(LOG_INFO,
"Performance counter frequency %.3f MHz",
PerfCtrFreq / 1e6);
if (NULL != pGetSystemTimePreciseAsFileTime) {
winnt_use_interpolation = FALSE;
winnt_time_initialized = TRUE;
return;
}
if (modify_mm_timer) {
if (timeGetDevCaps(&tc, sizeof(tc)) == TIMERR_NOERROR) {
wTimerRes = min(max(tc.wPeriodMin, MM_TIMER_INTV), tc.wPeriodMax);
timeBeginPeriod(wTimerRes);
atexit(atexit_revert_mm_timer);
msyslog(LOG_INFO, "MM timer resolution: %u..%u msec, set to %u msec",
tc.wPeriodMin, tc.wPeriodMax, wTimerRes );
Sleep( 33 );
} else {
msyslog(LOG_ERR, "Multimedia timer unavailable");
}
}
GetSystemTimeAsFileTime(&initial_hectonanosecs.ft);
do {
GetSystemTimeAsFileTime(&next_hectonanosecs.ft);
} while (initial_hectonanosecs.ull == next_hectonanosecs.ull);
os_clock_precision = next_hectonanosecs.ull -
initial_hectonanosecs.ull;
msyslog(LOG_INFO,
"Windows clock precision %.3f msec, min. slew %.3f ppm/s",
os_clock_precision / 1e4, ppm_per_adjust_unit);
winnt_time_initialized = TRUE;
choose_interp_counter();
if (getenv("NTPD_USE_SYSTEM_CLOCK") ||
(os_clock_precision < 4 * 10000 &&
!getenv("NTPD_USE_INTERP_DANGEROUS"))) {
msyslog(LOG_INFO, "using Windows clock directly");
} else {
winnt_use_interpolation = TRUE;
get_sys_time_as_filetime = GetInterpTimeAsFileTime;
StartClockThread();
}
}
void
atexit_revert_mm_timer(void)
{
timeEndPeriod(wTimerRes);
DPRINTF(1, ("MM timer resolution reset\n"));
}
void
reset_winnt_time(void)
{
SYSTEMTIME st;
if (sys_leap == LEAP_NOTINSYNC || ls_time_adjustment != 0)
SetSystemTimeAdjustment(0, TRUE);
if (ntservice_systemisshuttingdown() && sys_leap != LEAP_NOTINSYNC) {
GetSystemTime(&st);
SetSystemTime(&st);
NLOG(NLOG_SYSEVENT | NLOG_CLOCKINFO)
msyslog(LOG_NOTICE, "system is shutting down, CMOS time reset.");
}
}
void WINAPI
GetInterpTimeAsFileTime(
LPFILETIME pft
)
{
static ULONGLONG last_interp_time;
FT_ULL now_time;
FT_ULL now_count;
ULONGLONG clock_backward;
now_count.ull = perf_ctr();
now_time.ull = interp_time(now_count.ull, TRUE);
if (last_interp_time <= now_time.ull) {
last_interp_time = now_time.ull;
} else {
clock_backward = last_interp_time - now_time.ull;
if (clock_backward > clock_backward_max) {
clock_backward_max = clock_backward;
clock_backward_count++;
}
now_time.ull = last_interp_time;
}
*pft = now_time.ft;
return;
}
static void CALLBACK
TimerApcFunction(
LPVOID lpArgToCompletionRoutine,
DWORD dwTimerLowValue,
DWORD dwTimerHighValue
)
{
static BOOL ctr_freq_timer_started = FALSE;
static ULONGLONG prev_count;
ULONGLONG now_time;
FT_ULL now_count;
now_count.ull = perf_ctr();
now_time = (((ULONGLONG)dwTimerHighValue << 32) |
dwTimerLowValue);
add_counter_time_pair(now_count.ull, now_time);
if (INVALID_HANDLE_VALUE == ctr_freq_timer &&
LEAP_NOTINSYNC != sys_leap)
start_ctr_freq_timer(now_time);
}
unsigned WINAPI
ClockThread(
void *arg
)
{
LARGE_INTEGER DueTime;
HANDLE timer;
double HZ;
double TimerHz;
DWORD timer_period_msec;
DWORD res;
char *ntpd_int_int_text;
UNUSED_ARG(arg);
timer = CreateWaitableTimer(NULL, FALSE, NULL);
ntpd_int_int_text = getenv("NTPD_INT_INT");
HZ = (double)HECTONANOSECONDS / clockperiod;
if (HZ > 63 && HZ < 65) {
timer_period_msec = 43;
} else if (HZ > 98 && HZ < 102) {
timer_period_msec = 27;
if (NULL == ntpd_int_int_text)
msyslog(LOG_WARNING,
"%.3f Hz system clock may benefit from "
"custom NTPD_INT_INT env var timer interval "
"override between approx. 20 and 50 msecs.",
HZ);
} else {
timer_period_msec = (DWORD)(0.5 + (2.752 * clockperiod / 10000));
if (NULL == ntpd_int_int_text)
msyslog(LOG_WARNING,
"unfamiliar %.3f Hz system clock may benefit "
"from custom NTPD_INT_INT env var timer "
"interval override between approx. 20 and 50 "
"msecs.",
HZ);
}
if (ntpd_int_int_text != NULL) {
timer_period_msec = atoi(ntpd_int_int_text);
timer_period_msec = max(9, timer_period_msec);
msyslog(LOG_NOTICE,
"using NTPD_INT_INT env var override %u",
timer_period_msec);
}
TimerHz = 1e3 / timer_period_msec;
msyslog(LOG_NOTICE, "HZ %.3f using %u msec timer %.3f Hz %d deep",
HZ,
timer_period_msec,
TimerHz,
BASELINES_USED);
DueTime.QuadPart = -(int)timer_period_msec;
SetWaitableTimer(
timer,
&DueTime,
timer_period_msec,
TimerApcFunction,
&timer,
FALSE);
do res = WaitForSingleObjectEx(
TimerThreadExitRequest,
INFINITE,
TRUE);
while (WAIT_OBJECT_0 != res);
CloseHandle(timer);
if (ctr_freq_timer != INVALID_HANDLE_VALUE) {
CloseHandle(ctr_freq_timer);
ctr_freq_timer = INVALID_HANDLE_VALUE;
}
return 0;
}
static void
StartClockThread(void)
{
static BOOL done_once = FALSE;
FT_ULL StartTime;
GetSystemTimeAsFileTime(&StartTime.ft);
baseline_times[0] = StartTime.ull;
baseline_counts[0] = perf_ctr();
TimerThreadExitRequest = CreateEvent(NULL, FALSE, FALSE, NULL);
clock_thread =
(HANDLE)_beginthreadex(
NULL,
0,
ClockThread,
NULL,
CREATE_SUSPENDED,
&clock_thread_id);
if (clock_thread != NULL) {
if (!SetThreadPriority(clock_thread, THREAD_PRIORITY_TIME_CRITICAL)) {
DPRINTF(1, ("Error setting thread priority\n"));
}
lock_thread_to_processor(clock_thread);
ResumeThread(clock_thread);
if (FALSE == done_once) {
done_once = TRUE;
lock_thread_to_processor(GetCurrentThread());
atexit( StopClockThread );
}
Sleep(BASELINES_USED * 43);
}
}
void
StopClockThread(void)
{
if (GetCurrentThreadId() != clock_thread_id) {
if (!SetEvent(TimerThreadExitRequest) ||
WaitForSingleObject(clock_thread, 2 * 1000) !=
WAIT_OBJECT_0) {
msyslog(LOG_ERR, "Failed to stop clock thread.");
}
}
CloseHandle(TimerThreadExitRequest);
TimerThreadExitRequest = NULL;
CloseHandle(clock_thread);
clock_thread = NULL;
}
void
lock_thread_to_processor(HANDLE thread)
{
static DWORD_PTR ProcessAffinityMask;
static DWORD_PTR ThreadAffinityMask;
DWORD_PTR SystemAffinityMask;
char *cputext;
unsigned int cpu;
if ( ! winnt_time_initialized) {
DPRINTF(1, ("init_winnt_time() must be called before "
"lock_thread_to_processor(), exiting\n"));
exit(-1);
}
if (!winnt_use_interpolation)
return;
if (-1 == lock_interp_threads) {
DPRINTF(1, ("choose_interp_counter() is not called "
"before lock_thread_to_processor()\n"));
exit(-1);
} else if (!lock_interp_threads)
return;
if (!ProcessAffinityMask) {
GetProcessAffinityMask(
GetCurrentProcess(),
&ProcessAffinityMask,
&SystemAffinityMask);
cpu = 2;
cputext = getenv("NTPD_CPU");
if (cputext) {
cpu = (unsigned int) atoi(cputext);
cpu = min((8 * sizeof(DWORD_PTR)), cpu);
}
ThreadAffinityMask = (0 == cpu) ? 0 : (1 << (cpu - 1));
if (ThreadAffinityMask &&
!(ThreadAffinityMask & ProcessAffinityMask))
DPRINTF(1, ("Selected CPU %u (mask %x) is outside "
"process mask %x, using all CPUs.\n",
cpu, ThreadAffinityMask,
ProcessAffinityMask));
else
DPRINTF(1, ("Wiring to processor %u (0 means all) "
"affinity mask %x\n",
cpu, ThreadAffinityMask));
ThreadAffinityMask &= ProcessAffinityMask;
}
if (ThreadAffinityMask &&
!SetThreadAffinityMask(thread, ThreadAffinityMask))
msyslog(LOG_ERR,
"Unable to wire thread to mask %x: %m",
ThreadAffinityMask);
}
#ifdef HAVE_PPSAPI
static inline void ntp_timestamp_from_counter(l_fp *, ULONGLONG,
ULONGLONG);
void
pps_ntp_timestamp_from_counter(
ntp_fp_t *result,
ULONGLONG Timestamp,
ULONGLONG Counterstamp
)
{
ntp_timestamp_from_counter(
(l_fp *)result,
Timestamp,
Counterstamp);
}
static inline
void
ntp_timestamp_from_counter(
l_fp *result,
ULONGLONG Timestamp,
ULONGLONG Counterstamp
)
{
FT_ULL Now;
FT_ULL Ctr;
LONGLONG CtrDelta;
double seconds;
ULONGLONG InterpTimestamp;
if (winnt_use_interpolation) {
if (0 == Counterstamp) {
DPRINTF(1, ("ntp_timestamp_from_counter rejecting 0 counter.\n"));
ZERO(*result);
return;
}
InterpTimestamp = interp_time(Counterstamp + QPC_offset, FALSE);
} else {
if (NULL != pGetSystemTimePreciseAsFileTime &&
0 != Counterstamp) {
QueryPerformanceCounter(&Ctr.li);
(*pGetSystemTimePreciseAsFileTime)(&Now.ft);
CtrDelta = Ctr.ull - Counterstamp;
seconds = (double)CtrDelta / PerfCtrFreq;
InterpTimestamp = Now.ull -
(ULONGLONG)(seconds * HECTONANOSECONDS);
} else {
InterpTimestamp = Timestamp;
GetSystemTimeAsFileTime(&Now.ft);
}
}
InterpTimestamp -= FILETIME_1970;
result->l_ui = JAN_1970 + (u_int32)(InterpTimestamp / HECTONANOSECONDS);
result->l_uf = (u_int32)((InterpTimestamp % HECTONANOSECONDS) *
(ULONGLONG)FRAC / HECTONANOSECONDS);
}
#endif
void
win_time_stepped(void)
{
if (FALSE == winnt_use_interpolation)
return;
StopClockThread();
newest_baseline_gen++;
clock_backward_max = CLOCK_BACK_THRESHOLD;
clock_backward_count = 0;
newest_baseline = 0;
ZERO(baseline_counts);
ZERO(baseline_times);
StartClockThread();
}
int
log2ull(
ULONGLONG n
)
{
const ULONGLONG one = 1;
int log = 0;
if (n >= one<<32) { n >>= 32; log += 32; }
if (n >= one<<16) { n >>= 16; log += 16; }
if (n >= one<< 8) { n >>= 8; log += 8; }
if (n >= one<< 4) { n >>= 4; log += 4; }
if (n >= one<< 2) { n >>= 2; log += 2; }
if (n >= one<< 1) { log += 1; }
return (n) ? log : (-1);
}
static void CALLBACK
ctr_freq_timer_fired(
LPVOID arg,
DWORD dwTimeLow,
DWORD dwTimeHigh
)
{
static FT_ULL begin_time = {0};
static FT_ULL begin_count = {0};
static ULONGLONG next_period_time = 0;
static ULONGLONG report_systemtime = 0;
const ULONGLONG five_minutes = 5ui64 * 60 * HECTONANOSECONDS;
FT_ULL now_time;
FT_ULL now_count;
if (!begin_time.ull) {
begin_count.ull = perf_ctr();
begin_time.ft.dwLowDateTime = dwTimeLow;
begin_time.ft.dwHighDateTime = dwTimeHigh;
tune_ctr_period = 22680 / log2ull(NomPerfCtrFreq);
tune_ctr_freq_max_interval = tune_ctr_period - 2;
next_period_time = begin_time.ull +
(ULONGLONG)tune_ctr_period * HECTONANOSECONDS;
ROUND_TO_NEXT_SEC_BOTTOM(next_period_time);
reset_ctr_freq_timer(next_period_time, begin_time.ull);
return;
}
now_time.ft.dwLowDateTime = dwTimeLow;
now_time.ft.dwHighDateTime = dwTimeHigh;
if (now_time.ull >= next_period_time) {
now_count.ull = perf_ctr();
tune_ctr_freq(
now_count.ull - begin_count.ull,
now_time.ull - begin_time.ull);
next_period_time += (ULONGLONG)tune_ctr_period * HECTONANOSECONDS;
begin_count.ull = now_count.ull;
begin_time.ull = now_time.ull;
}
if (!report_systemtime) {
report_systemtime = now_time.ull + five_minutes;
} else if (report_systemtime <= now_time.ull) {
report_systemtime += five_minutes;
if (clock_backward_count) {
msyslog(LOG_WARNING,
"clock would have gone backward %d times, "
"max %.1f usec",
clock_backward_count,
clock_backward_max / 10.);
clock_backward_max = CLOCK_BACK_THRESHOLD;
clock_backward_count = 0;
}
}
reset_ctr_freq_timer(next_period_time, now_time.ull);
}
void
reset_ctr_freq_timer_abs(
ULONGLONG when
)
{
FT_ULL fire_time;
fire_time.ull = when;
SetWaitableTimer(
ctr_freq_timer,
&fire_time.li,
0,
ctr_freq_timer_fired,
NULL,
FALSE);
}
void
reset_ctr_freq_timer(
ULONGLONG when,
ULONGLONG now
)
{
if (when - now >
(tune_ctr_freq_max_interval * HECTONANOSECONDS + HECTONANOSECONDS))
when = now + tune_ctr_freq_max_interval * HECTONANOSECONDS;
reset_ctr_freq_timer_abs(when);
}
void
start_ctr_freq_timer(
ULONGLONG now_time
)
{
ULONGLONG when;
ctr_freq_timer = CreateWaitableTimer(NULL, FALSE, NULL);
when = now_time;
ROUND_TO_NEXT_SEC_BOTTOM(when);
reset_ctr_freq_timer_abs(when);
}
void
tune_ctr_freq(
LONGLONG ctr_delta,
LONGLONG time_delta
)
{
static unsigned count = 0;
static unsigned dispcount = 0;
static unsigned report_at_count = 0;
static int disbelieved = 0;
static int i = 0;
static double nom_freq = 0;
static LONGLONG diffs[TUNE_CTR_DEPTH] = {0};
static LONGLONG sum = 0;
char ctr_freq_eq[64];
LONGLONG delta;
LONGLONG deltadiff;
ULONGLONG ObsPerfCtrFreq;
double freq;
double this_freq;
BOOL isneg;
if (!report_at_count) {
report_at_count = 24 * 60 * 60 / tune_ctr_period;
nom_freq = NomPerfCtrFreq / 1e6;
}
delta = (LONGLONG)((double)ctr_delta * HECTONANOSECONDS /
time_delta);
deltadiff = delta - NomPerfCtrFreq;
if (0 > deltadiff) {
isneg = TRUE;
deltadiff = -deltadiff;
} else {
isneg = FALSE;
}
if ((ULONGLONG)deltadiff > (NomPerfCtrFreq / 1024)) {
disbelieved++;
dispcount++;
#ifdef DEBUG
msyslog(LOG_DEBUG, "ctr delta %s%lld exceeds limit %llu",
(isneg) ? "-" : "",
deltadiff,
NomPerfCtrFreq / 1024);
#endif
} else {
if (isneg)
deltadiff = -deltadiff;
sum -= diffs[i];
diffs[i] = deltadiff;
sum += deltadiff;
i = (i + 1) % COUNTOF(diffs);
count++;
dispcount++;
}
this_freq = delta / 1e6;
ObsPerfCtrFreq = NomPerfCtrFreq + (sum / COUNTOF(diffs));
#if 1
PerfCtrFreq = ObsPerfCtrFreq;
#endif
freq = PerfCtrFreq / 1e6;
snprintf(ctr_freq_eq, sizeof(ctr_freq_eq), "ctr_frequency=%.2f",
1e6 * (freq - nom_freq) / nom_freq);
set_sys_var(ctr_freq_eq, strlen(ctr_freq_eq) + 1, RO | DEF);
if (count > COUNTOF(diffs) &&
dispcount < report_at_count)
return;
NLOG(NLOG_CLOCKINFO)
if (count <= COUNTOF(diffs))
msyslog(LOG_INFO,
(freq > 100)
? "ctr %.3f MHz %+6.2f PPM using %.3f MHz %+6.2f PPM"
: "ctr %.6f MHz %+6.2f PPM using %.6f MHz %+6.2f PPM",
this_freq,
1e6 * (this_freq - nom_freq) / nom_freq,
freq,
1e6 * (freq - nom_freq) / nom_freq);
else
msyslog(LOG_INFO,
(freq > 100)
? "ctr %.3f MHz %+.2f PPM"
: "ctr %.6f MHz %+.2f PPM",
freq,
1e6 * (freq - nom_freq) / nom_freq);
if (disbelieved) {
msyslog(LOG_ERR,
"%d ctr samples exceed +/- 976 PPM range gate",
disbelieved);
disbelieved = 0;
}
dispcount = 0;
}
void
add_counter_time_pair(
ULONGLONG ctr,
LONGLONG time
)
{
int i;
i = (newest_baseline + 1) % BASELINES_TOT;
baseline_counts[i] = ctr;
baseline_times[i] = time;
newest_baseline = i;
}
ULONGLONG
interp_time(
ULONGLONG ctr,
BOOL current
)
{
static __declspec(thread) int last_newest = -1;
static __declspec(thread) int last_newest_gen;
static __declspec(thread) int best_index;
ULONGLONG this_ctr;
LONGLONG this_time;
LONGLONG latest_time;
LONGLONG ctr_diff;
int i;
int i_gen;
int c;
i = newest_baseline;
i_gen = newest_baseline_gen;
if (last_newest == i && last_newest_gen == i_gen) {
this_time = baseline_times[best_index];
ctr_diff = ctr - baseline_counts[best_index];
this_time += (LONGLONG)PERF2HNS((double)ctr_diff);
return this_time;
}
last_newest = i;
last_newest_gen = i_gen;
latest_time = 0;
for (c = 0; c < BASELINES_USED; c++) {
if (baseline_times[i]) {
this_time = baseline_times[i];
this_ctr = baseline_counts[i];
ctr_diff = ctr - this_ctr;
if (current && ctr_diff < 0) {
ctr_diff = 0;
}
this_time += (LONGLONG)PERF2HNS((double)ctr_diff);
if (this_time > latest_time) {
latest_time = this_time;
best_index = i;
}
}
i = i ? (i - 1) : (BASELINES_TOT - 1);
}
return latest_time;
}