Debian Codegraph @

mozglue/misc/TimeStamp_windows.cpp

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 // Implement TimeStamp::Now() with QueryPerformanceCounter() controlled with
8 // values of GetTickCount64().
9
10 #include "mozilla/DynamicallyLinkedFunctionPtr.h"
11 #include "mozilla/MathAlgorithms.h"
12 #include "mozilla/TimeStamp.h"
13 #include "mozilla/Uptime.h"
14
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <intrin.h>
18 #include <windows.h>
19
20 // To enable logging define to your favorite logging API
21 #define LOG(x)
22
23 class AutoCriticalSection {
24 public:
25 explicit AutoCriticalSection(LPCRITICAL_SECTION aSection)
26 : mSection(aSection) {
27 ::EnterCriticalSection(mSection);
28 }
29 ~AutoCriticalSection() { ::LeaveCriticalSection(mSection); }
30
31 private:
32 LPCRITICAL_SECTION mSection;
33 };
34
35 // Estimate of the smallest duration of time we can measure.
36 static volatile ULONGLONG sResolution;
37 static volatile ULONGLONG sResolutionSigDigs;
38 static const double kNsPerSecd = 1000000000.0;
39 static const LONGLONG kNsPerMillisec = 1000000;
40
41 // ----------------------------------------------------------------------------
42 // Global constants
43 // ----------------------------------------------------------------------------
44
45 // Tolerance to failures settings.
46 //
47 // What is the interval we want to have failure free.
48 // in [ms]
49 static const uint32_t kFailureFreeInterval = 5000;
50 // How many failures we are willing to tolerate in the interval.
51 static const uint32_t kMaxFailuresPerInterval = 4;
52 // What is the threshold to treat fluctuations as actual failures.
53 // in [ms]
54 static const uint32_t kFailureThreshold = 50;
55
56 // If we are not able to get the value of GTC time increment, use this value
57 // which is the most usual increment.
58 static const DWORD kDefaultTimeIncrement = 156001;
59
60 // ----------------------------------------------------------------------------
61 // Global variables, not changing at runtime
62 // ----------------------------------------------------------------------------
63
64 // Result of QueryPerformanceFrequency
65 // We use default of 1 for the case we can't use QueryPerformanceCounter
66 // to make mt/ms conversions work despite that.
67 static uint64_t sFrequencyPerSec = 1;
68
69 namespace mozilla {
70
71 MFBT_API uint64_t GetQueryPerformanceFrequencyPerSec() {
72 return sFrequencyPerSec;
73 }
74
75 } // namespace mozilla
76
77 // How much we are tolerant to GTC occasional loose of resoltion.
78 // This number says how many multiples of the minimal GTC resolution
79 // detected on the system are acceptable. This number is empirical.
80 static const LONGLONG kGTCTickLeapTolerance = 4;
81
82 // Base tolerance (more: "inability of detection" range) threshold is calculated
83 // dynamically, and kept in sGTCResolutionThreshold.
84 //
85 // Schematically, QPC worked "100%" correctly if ((GTC_now - GTC_epoch) -
86 // (QPC_now - QPC_epoch)) was in [-sGTCResolutionThreshold,
87 // sGTCResolutionThreshold] interval every time we'd compared two time stamps.
88 // If not, then we check the overflow behind this basic threshold
89 // is in kFailureThreshold. If not, we condider it as a QPC failure. If too
90 // many failures in short time are detected, QPC is considered faulty and
91 // disabled.
92 //
93 // Kept in [mt]
94 static LONGLONG sGTCResolutionThreshold;
95
96 // If QPC is found faulty for two stamps in this interval, we engage
97 // the fault detection algorithm. For duration larger then this limit
98 // we bypass using durations calculated from QPC when jitter is detected,
99 // but don't touch the sUseQPC flag.
100 //
101 // Value is in [ms].
102 static const uint32_t kHardFailureLimit = 2000;
103 // Conversion to [mt]
104 static LONGLONG sHardFailureLimit;
105
106 // Conversion of kFailureFreeInterval and kFailureThreshold to [mt]
107 static LONGLONG sFailureFreeInterval;
108 static LONGLONG sFailureThreshold;
109
110 // ----------------------------------------------------------------------------
111 // Systemm status flags
112 // ----------------------------------------------------------------------------
113
114 // Flag for stable TSC that indicates platform where QPC is stable.
115 static bool sHasStableTSC = false;
116
117 // ----------------------------------------------------------------------------
118 // Global state variables, changing at runtime
119 // ----------------------------------------------------------------------------
120
121 // Initially true, set to false when QPC is found unstable and never
122 // returns back to true since that time.
123 static bool volatile sUseQPC = true;
124
125 // ----------------------------------------------------------------------------
126 // Global lock
127 // ----------------------------------------------------------------------------
128
129 // Thread spin count before entering the full wait state for sTimeStampLock.
130 // Inspired by Rob Arnold's work on PRMJ_Now().
131 static const DWORD kLockSpinCount = 4096;
132
133 // Common mutex (thanks the relative complexity of the logic, this is better
134 // then using CMPXCHG8B.)
135 // It is protecting the globals bellow.
136 static CRITICAL_SECTION sTimeStampLock;
137
138 // ----------------------------------------------------------------------------
139 // Global lock protected variables
140 // ----------------------------------------------------------------------------
141
142 // Timestamp in future until QPC must behave correctly.
143 // Set to now + kFailureFreeInterval on first QPC failure detection.
144 // Set to now + E * kFailureFreeInterval on following errors,
145 // where E is number of errors detected during last kFailureFreeInterval
146 // milliseconds, calculated simply as:
147 // E = (sFaultIntoleranceCheckpoint - now) / kFailureFreeInterval + 1.
148 // When E > kMaxFailuresPerInterval -> disable QPC.
149 //
150 // Kept in [mt]
151 static ULONGLONG sFaultIntoleranceCheckpoint = 0;
152
153 namespace mozilla {
154
155 // Result is in [mt]
156 static inline ULONGLONG PerformanceCounter() {
157 LARGE_INTEGER pc;
158 ::QueryPerformanceCounter(&pc);
159
160 // QueryPerformanceCounter may slightly jitter (not be 100% monotonic.)
161 // This is a simple go-backward protection for such a faulty hardware.
162 AutoCriticalSection lock(&sTimeStampLock);
163
164 static decltype(LARGE_INTEGER::QuadPart) last;
165 if (last > pc.QuadPart) {
166 return last * 1000ULL;
167 }
168 last = pc.QuadPart;
169 return pc.QuadPart * 1000ULL;
170 }
171
172 static void InitThresholds() {
173 DWORD timeAdjustment = 0, timeIncrement = 0;
174 BOOL timeAdjustmentDisabled;
175 GetSystemTimeAdjustment(&timeAdjustment, &timeIncrement,
176 &timeAdjustmentDisabled);
177
178 LOG(("TimeStamp: timeIncrement=%d [100ns]", timeIncrement));
179
180 if (!timeIncrement) {
181 timeIncrement = kDefaultTimeIncrement;
182 }
183
184 // Ceiling to a millisecond
185 // Example values: 156001, 210000
186 DWORD timeIncrementCeil = timeIncrement;
187 // Don't want to round up if already rounded, values will be: 156000, 209999
188 timeIncrementCeil -= 1;
189 // Convert to ms, values will be: 15, 20
190 timeIncrementCeil /= 10000;
191 // Round up, values will be: 16, 21
192 timeIncrementCeil += 1;
193 // Convert back to 100ns, values will be: 160000, 210000
194 timeIncrementCeil *= 10000;
195
196 // How many milli-ticks has the interval rounded up
197 LONGLONG ticksPerGetTickCountResolutionCeiling =
198 (int64_t(timeIncrementCeil) * sFrequencyPerSec) / 10000LL;
199
200 // GTC may jump by 32 (2*16) ms in two steps, therefor use the ceiling value.
201 sGTCResolutionThreshold =
202 LONGLONG(kGTCTickLeapTolerance * ticksPerGetTickCountResolutionCeiling);
203
204 sHardFailureLimit = ms2mt(kHardFailureLimit);
205 sFailureFreeInterval = ms2mt(kFailureFreeInterval);
206 sFailureThreshold = ms2mt(kFailureThreshold);
207 }
208
209 static void InitResolution() {
210 // 10 total trials is arbitrary: what we're trying to avoid by
211 // looping is getting unlucky and being interrupted by a context
212 // switch or signal, or being bitten by paging/cache effects
213
214 ULONGLONG minres = ~0ULL;
215 if (sUseQPC) {
216 int loops = 10;
217 do {
218 ULONGLONG start = PerformanceCounter();
219 ULONGLONG end = PerformanceCounter();
220
221 ULONGLONG candidate = (end - start);
222 if (candidate < minres) {
223 minres = candidate;
224 }
225 } while (--loops && minres);
226
227 if (0 == minres) {
228 minres = 1;
229 }
230 } else {
231 // GetTickCount has only ~16ms known resolution
232 minres = ms2mt(16);
233 }
234
235 // Converting minres that is in [mt] to nanosecods, multiplicating
236 // the argument to preserve resolution.
237 ULONGLONG result = mt2ms(minres * kNsPerMillisec);
238 if (0 == result) {
239 result = 1;
240 }
241
242 sResolution = result;
243
244 // find the number of significant digits in mResolution, for the
245 // sake of ToSecondsSigDigits()
246 ULONGLONG sigDigs;
247 for (sigDigs = 1; !(sigDigs == result || 10 * sigDigs > result);
248 sigDigs *= 10);
249
250 sResolutionSigDigs = sigDigs;
251 }
252
253 // ----------------------------------------------------------------------------
254 // TimeStampValue implementation
255 // ----------------------------------------------------------------------------
256 MFBT_API TimeStampValue& TimeStampValue::operator+=(const int64_t aOther) {
257 mGTC += aOther;
258 mQPC += aOther;
259 return *this;
260 }
261
262 MFBT_API TimeStampValue& TimeStampValue::operator-=(const int64_t aOther) {
263 mGTC -= aOther;
264 mQPC -= aOther;
265 return *this;
266 }
267
268 // If the duration is less then two seconds, perform check of QPC stability
269 // by comparing both GTC and QPC calculated durations of this and aOther.
270 MFBT_API uint64_t TimeStampValue::CheckQPC(const TimeStampValue& aOther) const {
271 uint64_t deltaGTC = mGTC - aOther.mGTC;
272
273 if (!mHasQPC || !aOther.mHasQPC) { // Both not holding QPC
274 return deltaGTC;
275 }
276
277 uint64_t deltaQPC = mQPC - aOther.mQPC;
278
279 if (sHasStableTSC) { // For stable TSC there is no need to check
280 return deltaQPC;
281 }
282
283 // Check QPC is sane before using it.
284 int64_t diff = DeprecatedAbs(int64_t(deltaQPC) - int64_t(deltaGTC));
285 if (diff <= sGTCResolutionThreshold) {
286 return deltaQPC;
287 }
288
289 // Treat absolutely for calibration purposes
290 int64_t duration = DeprecatedAbs(int64_t(deltaGTC));
291 int64_t overflow = diff - sGTCResolutionThreshold;
292
293 LOG(("TimeStamp: QPC check after %llums with overflow %1.4fms",
294 mt2ms(duration), mt2ms_f(overflow)));
295
296 if (overflow <= sFailureThreshold) { // We are in the limit, let go.
297 return deltaQPC;
298 }
299
300 // QPC deviates, don't use it, since now this method may only return deltaGTC.
301
302 if (!sUseQPC) { // QPC already disabled, no need to run the fault tolerance
303 // algorithm.
304 return deltaGTC;
305 }
306
307 LOG(("TimeStamp: QPC jittered over failure threshold"));
308
309 if (duration < sHardFailureLimit) {
310 // Interval between the two time stamps is very short, consider
311 // QPC as unstable and record a failure.
312 uint64_t now = ms2mt(GetTickCount64());
313
314 AutoCriticalSection lock(&sTimeStampLock);
315
316 if (sFaultIntoleranceCheckpoint && sFaultIntoleranceCheckpoint > now) {
317 // There's already been an error in the last fault intollerant interval.
318 // Time since now to the checkpoint actually holds information on how many
319 // failures there were in the failure free interval we have defined.
320 uint64_t failureCount =
321 (sFaultIntoleranceCheckpoint - now + sFailureFreeInterval - 1) /
322 sFailureFreeInterval;
323 if (failureCount > kMaxFailuresPerInterval) {
324 sUseQPC = false;
325 LOG(("TimeStamp: QPC disabled"));
326 } else {
327 // Move the fault intolerance checkpoint more to the future, prolong it
328 // to reflect the number of detected failures.
329 ++failureCount;
330 sFaultIntoleranceCheckpoint = now + failureCount * sFailureFreeInterval;
331 LOG(("TimeStamp: recording %dth QPC failure", failureCount));
332 }
333 } else {
334 // Setup fault intolerance checkpoint in the future for first detected
335 // error.
336 sFaultIntoleranceCheckpoint = now + sFailureFreeInterval;
337 LOG(("TimeStamp: recording 1st QPC failure"));
338 }
339 }
340
341 return deltaGTC;
342 }
343
344 MFBT_API uint64_t
345 TimeStampValue::operator-(const TimeStampValue& aOther) const {
346 if (IsNull() && aOther.IsNull()) {
347 return uint64_t(0);
348 }
349
350 return CheckQPC(aOther);
351 }
352
353 class TimeStampValueTests {
354 // Check that nullity is set/not set correctly.
355 static_assert(TimeStampValue{0}.IsNull());
356 static_assert(!TimeStampValue{1}.IsNull());
357
358 // Check that we ignore GTC when both TimeStampValues have QPC. (In each of
359 // these tests, looking at GTC would give a different result.)
360 static_assert(TimeStampValue{1, 2, true} < TimeStampValue{1, 3, true});
361 static_assert(!(TimeStampValue{1, 2, true} == TimeStampValue{1, 3, true}));
362
363 static_assert(TimeStampValue{2, 2, true} < TimeStampValue{1, 3, true});
364 static_assert(TimeStampValue{2, 2, true} <= TimeStampValue{1, 3, true});
365 static_assert(!(TimeStampValue{2, 2, true} > TimeStampValue{1, 3, true}));
366
367 static_assert(TimeStampValue{1, 3, true} > TimeStampValue{1, 2, true});
368 static_assert(!(TimeStampValue{1, 3, true} == TimeStampValue{1, 2, true}));
369
370 static_assert(TimeStampValue{1, 3, true} > TimeStampValue{2, 2, true});
371 static_assert(TimeStampValue{1, 3, true} >= TimeStampValue{2, 2, true});
372 static_assert(!(TimeStampValue{1, 3, true} < TimeStampValue{2, 2, true}));
373
374 static_assert(TimeStampValue{1, 3, true} == TimeStampValue{2, 3, true});
375 static_assert(!(TimeStampValue{1, 3, true} < TimeStampValue{2, 3, true}));
376
377 static_assert(TimeStampValue{1, 2, true} != TimeStampValue{1, 3, true});
378 static_assert(!(TimeStampValue{1, 2, true} == TimeStampValue{1, 3, true}));
379
380 // Check that, if either TimeStampValue doesn't have QPC, we only look at the
381 // GTC values. These are the same cases as above, except that we accept the
382 // opposite results because we turn off QPC on one or both of the
383 // TimeStampValue's.
384 static_assert(TimeStampValue{1, 2, false} == TimeStampValue{1, 3, true});
385 static_assert(TimeStampValue{1, 2, true} == TimeStampValue{1, 3, false});
386 static_assert(TimeStampValue{1, 2, false} == TimeStampValue{1, 3, false});
387
388 static_assert(TimeStampValue{2, 2, false} > TimeStampValue{1, 3, true});
389 static_assert(TimeStampValue{2, 2, true} > TimeStampValue{1, 3, false});
390 static_assert(TimeStampValue{2, 2, false} > TimeStampValue{1, 3, false});
391
392 static_assert(TimeStampValue{1, 3, false} == TimeStampValue{1, 2, true});
393 static_assert(TimeStampValue{1, 3, true} == TimeStampValue{1, 2, false});
394 static_assert(TimeStampValue{1, 3, false} == TimeStampValue{1, 2, false});
395
396 static_assert(TimeStampValue{1, 3, false} < TimeStampValue{2, 2, true});
397 static_assert(TimeStampValue{1, 3, true} < TimeStampValue{2, 2, false});
398 static_assert(TimeStampValue{1, 3, false} < TimeStampValue{2, 2, false});
399
400 static_assert(TimeStampValue{1, 3, false} < TimeStampValue{2, 3, true});
401 static_assert(TimeStampValue{1, 3, true} < TimeStampValue{2, 3, false});
402 static_assert(TimeStampValue{1, 3, false} < TimeStampValue{2, 3, false});
403
404 static_assert(TimeStampValue{1, 2, false} == TimeStampValue{1, 3, true});
405 static_assert(TimeStampValue{1, 2, true} == TimeStampValue{1, 3, false});
406 static_assert(TimeStampValue{1, 2, false} == TimeStampValue{1, 3, false});
407 };
408
409 // ----------------------------------------------------------------------------
410 // TimeDuration and TimeStamp implementation
411 // ----------------------------------------------------------------------------
412
413 MFBT_API double BaseTimeDurationPlatformUtils::ToSeconds(int64_t aTicks) {
414 // Converting before arithmetic avoids blocked store forward
415 return double(aTicks) / (double(sFrequencyPerSec) * 1000.0);
416 }
417
418 MFBT_API double BaseTimeDurationPlatformUtils::ToSecondsSigDigits(
419 int64_t aTicks) {
420 // don't report a value < mResolution ...
421 LONGLONG resolution = sResolution;
422 LONGLONG resolutionSigDigs = sResolutionSigDigs;
423 LONGLONG valueSigDigs = resolution * (aTicks / resolution);
424 // and chop off insignificant digits
425 valueSigDigs = resolutionSigDigs * (valueSigDigs / resolutionSigDigs);
426 return double(valueSigDigs) / kNsPerSecd;
427 }
428
429 MFBT_API int64_t
430 BaseTimeDurationPlatformUtils::TicksFromMilliseconds(double aMilliseconds) {
431 double result = ms2mt(aMilliseconds);
432 if (result > double(INT64_MAX)) {
433 return INT64_MAX;
434 } else if (result < double(INT64_MIN)) {
435 return INT64_MIN;
436 }
437
438 return result;
439 }
440
441 MFBT_API int64_t BaseTimeDurationPlatformUtils::ResolutionInTicks() {
442 return static_cast<int64_t>(sResolution);
443 }
444
445 static bool HasStableTSC() {
446 #if defined(_M_ARM64)
447 // AArch64 defines that its system counter run at a constant rate
448 // regardless of the current clock frequency of the system. See "The
449 // Generic Timer", section D7, in the ARMARM for ARMv8.
450 return true;
451 #else
452 union {
453 int regs[4];
454 struct {
455 int nIds;
456 char cpuString[12];
457 };
458 } cpuInfo;
459
460 __cpuid(cpuInfo.regs, 0);
461 // Only allow Intel or AMD CPUs for now.
462 // The order of the registers is reg[1], reg[3], reg[2]. We just adjust the
463 // string so that we can compare in one go.
464 if (_strnicmp(cpuInfo.cpuString, "GenuntelineI", sizeof(cpuInfo.cpuString)) &&
465 _strnicmp(cpuInfo.cpuString, "AuthcAMDenti", sizeof(cpuInfo.cpuString))) {
466 return false;
467 }
468
469 int regs[4];
470
471 // detect if the Advanced Power Management feature is supported
472 __cpuid(regs, 0x80000000);
473 if ((unsigned int)regs[0] < 0x80000007) {
474 // XXX should we return true here? If there is no APM there may be
475 // no way how TSC can run out of sync among cores.
476 return false;
477 }
478
479 __cpuid(regs, 0x80000007);
480 // if bit 8 is set than TSC will run at a constant rate
481 // in all ACPI P-states, C-states and T-states
482 return regs[3] & (1 << 8);
483 #endif
484 }
485
486 static bool gInitialized = false;
487
488 MFBT_API void TimeStamp::Startup() {
489 if (gInitialized) {
490 return;
491 }
492
493 gInitialized = true;
494
495 // Decide which implementation to use for the high-performance timer.
496
497 InitializeCriticalSectionAndSpinCount(&sTimeStampLock, kLockSpinCount);
498
499 bool forceGTC = false;
500 bool forceQPC = false;
501
502 char* modevar = getenv("MOZ_TIMESTAMP_MODE");
503 if (modevar) {
504 if (!strcmp(modevar, "QPC")) {
505 forceQPC = true;
506 } else if (!strcmp(modevar, "GTC")) {
507 forceGTC = true;
508 }
509 }
510
511 LARGE_INTEGER freq;
512 sUseQPC = !forceGTC && ::QueryPerformanceFrequency(&freq);
513 if (!sUseQPC) {
514 // No Performance Counter. Fall back to use GetTickCount64.
515 InitResolution();
516
517 LOG(("TimeStamp: using GetTickCount64"));
518 return;
519 }
520
521 sHasStableTSC = forceQPC || HasStableTSC();
522 LOG(("TimeStamp: HasStableTSC=%d", sHasStableTSC));
523
524 sFrequencyPerSec = freq.QuadPart;
525 LOG(("TimeStamp: QPC frequency=%llu", sFrequencyPerSec));
526
527 InitThresholds();
528 InitResolution();
529
530 return;
531 }
532
533 MFBT_API void TimeStamp::Shutdown() { DeleteCriticalSection(&sTimeStampLock); }
534
535 TimeStampValue NowInternal(bool aHighResolution) {
536 // sUseQPC is volatile
537 bool useQPC = (aHighResolution && sUseQPC);
538
539 // Both values are in [mt] units.
540 ULONGLONG QPC = useQPC ? PerformanceCounter() : uint64_t(0);
541 ULONGLONG GTC = ms2mt(GetTickCount64());
542 return TimeStampValue(GTC, QPC, useQPC);
543 }
544
545 MFBT_API TimeStamp TimeStamp::Now(bool aHighResolution) {
546 return TimeStamp(NowInternal(aHighResolution));
547 }
548
549 // Computes and returns the process uptime in microseconds.
550 // Returns 0 if an error was encountered.
551
552 MFBT_API uint64_t TimeStamp::ComputeProcessUptime() {
553 FILETIME start, foo, bar, baz;
554 bool success = GetProcessTimes(GetCurrentProcess(), &start, &foo, &bar, &baz);
555 if (!success) {
556 return 0;
557 }
558
559 static const StaticDynamicallyLinkedFunctionPtr<void(WINAPI*)(LPFILETIME)>
560 pGetSystemTimePreciseAsFileTime(L"kernel32.dll",
561 "GetSystemTimePreciseAsFileTime");
562
563 FILETIME now;
564 if (pGetSystemTimePreciseAsFileTime) {
565 pGetSystemTimePreciseAsFileTime(&now);
566 } else {
567 GetSystemTimeAsFileTime(&now);
568 }
569
570 ULARGE_INTEGER startUsec = {{start.dwLowDateTime, start.dwHighDateTime}};
571 ULARGE_INTEGER nowUsec = {{now.dwLowDateTime, now.dwHighDateTime}};
572
573 return (nowUsec.QuadPart - startUsec.QuadPart) / 10ULL;
574 }
575
576 } // namespace mozilla