1 // Copyright 2013 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "src/base/platform/time.h"
6 
7 #if V8_OS_POSIX
8 #include <fcntl.h>  // for O_RDONLY
9 #include <sys/time.h>
10 #include <unistd.h>
11 #endif
12 #if V8_OS_MACOSX
13 #include <mach/mach.h>
14 #include <mach/mach_time.h>
15 #include <pthread.h>
16 #endif
17 
18 #include <cstring>
19 #include <ostream>
20 
21 #if V8_OS_WIN
22 #include "src/base/atomicops.h"
23 #include "src/base/lazy-instance.h"
24 #include "src/base/win32-headers.h"
25 #endif
26 #include "src/base/cpu.h"
27 #include "src/base/logging.h"
28 #include "src/base/platform/platform.h"
29 
30 namespace {
31 
32 #if V8_OS_MACOSX
ComputeThreadTicks()33 int64_t ComputeThreadTicks() {
34   mach_msg_type_number_t thread_info_count = THREAD_BASIC_INFO_COUNT;
35   thread_basic_info_data_t thread_info_data;
36   kern_return_t kr = thread_info(
37       pthread_mach_thread_np(pthread_self()),
38       THREAD_BASIC_INFO,
39       reinterpret_cast<thread_info_t>(&thread_info_data),
40       &thread_info_count);
41   CHECK_EQ(kr, KERN_SUCCESS);
42 
43   v8::base::CheckedNumeric<int64_t> absolute_micros(
44       thread_info_data.user_time.seconds +
45       thread_info_data.system_time.seconds);
46   absolute_micros *= v8::base::Time::kMicrosecondsPerSecond;
47   absolute_micros += (thread_info_data.user_time.microseconds +
48                       thread_info_data.system_time.microseconds);
49   return absolute_micros.ValueOrDie();
50 }
51 #elif V8_OS_POSIX
52 // Helper function to get results from clock_gettime() and convert to a
53 // microsecond timebase. Minimum requirement is MONOTONIC_CLOCK to be supported
54 // on the system. FreeBSD 6 has CLOCK_MONOTONIC but defines
55 // _POSIX_MONOTONIC_CLOCK to -1.
56 V8_INLINE int64_t ClockNow(clockid_t clk_id) {
57 #if (defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0) || \
58   defined(V8_OS_BSD) || defined(V8_OS_ANDROID)
59 // On AIX clock_gettime for CLOCK_THREAD_CPUTIME_ID outputs time with
60 // resolution of 10ms. thread_cputime API provides the time in ns
61 #if defined(V8_OS_AIX)
62   thread_cputime_t tc;
63   if (clk_id == CLOCK_THREAD_CPUTIME_ID) {
64     if (thread_cputime(-1, &tc) != 0) {
65       UNREACHABLE();
66     }
67   }
68 #endif
69   struct timespec ts;
70   if (clock_gettime(clk_id, &ts) != 0) {
71     UNREACHABLE();
72   }
73   v8::base::internal::CheckedNumeric<int64_t> result(ts.tv_sec);
74   result *= v8::base::Time::kMicrosecondsPerSecond;
75 #if defined(V8_OS_AIX)
76   if (clk_id == CLOCK_THREAD_CPUTIME_ID) {
77     result += (tc.stime / v8::base::Time::kNanosecondsPerMicrosecond);
78   } else {
79     result += (ts.tv_nsec / v8::base::Time::kNanosecondsPerMicrosecond);
80   }
81 #else
82   result += (ts.tv_nsec / v8::base::Time::kNanosecondsPerMicrosecond);
83 #endif
84   return result.ValueOrDie();
85 #else  // Monotonic clock not supported.
86   return 0;
87 #endif
88 }
89 #elif V8_OS_WIN
90 V8_INLINE bool IsQPCReliable() {
91   v8::base::CPU cpu;
92   // On Athlon X2 CPUs (e.g. model 15) QueryPerformanceCounter is unreliable.
93   return strcmp(cpu.vendor(), "AuthenticAMD") == 0 && cpu.family() == 15;
94 }
95 
96 // Returns the current value of the performance counter.
97 V8_INLINE uint64_t QPCNowRaw() {
98   LARGE_INTEGER perf_counter_now = {};
99   // According to the MSDN documentation for QueryPerformanceCounter(), this
100   // will never fail on systems that run XP or later.
101   // https://msdn.microsoft.com/library/windows/desktop/ms644904.aspx
102   BOOL result = ::QueryPerformanceCounter(&perf_counter_now);
103   DCHECK(result);
104   USE(result);
105   return perf_counter_now.QuadPart;
106 }
107 #endif  // V8_OS_MACOSX
108 
109 
110 }  // namespace
111 
112 namespace v8 {
113 namespace base {
114 
FromDays(int days)115 TimeDelta TimeDelta::FromDays(int days) {
116   return TimeDelta(days * Time::kMicrosecondsPerDay);
117 }
118 
119 
FromHours(int hours)120 TimeDelta TimeDelta::FromHours(int hours) {
121   return TimeDelta(hours * Time::kMicrosecondsPerHour);
122 }
123 
124 
FromMinutes(int minutes)125 TimeDelta TimeDelta::FromMinutes(int minutes) {
126   return TimeDelta(minutes * Time::kMicrosecondsPerMinute);
127 }
128 
129 
FromSeconds(int64_t seconds)130 TimeDelta TimeDelta::FromSeconds(int64_t seconds) {
131   return TimeDelta(seconds * Time::kMicrosecondsPerSecond);
132 }
133 
134 
FromMilliseconds(int64_t milliseconds)135 TimeDelta TimeDelta::FromMilliseconds(int64_t milliseconds) {
136   return TimeDelta(milliseconds * Time::kMicrosecondsPerMillisecond);
137 }
138 
139 
FromNanoseconds(int64_t nanoseconds)140 TimeDelta TimeDelta::FromNanoseconds(int64_t nanoseconds) {
141   return TimeDelta(nanoseconds / Time::kNanosecondsPerMicrosecond);
142 }
143 
144 
InDays() const145 int TimeDelta::InDays() const {
146   if (IsMax()) {
147     // Preserve max to prevent overflow.
148     return std::numeric_limits<int>::max();
149   }
150   return static_cast<int>(delta_ / Time::kMicrosecondsPerDay);
151 }
152 
InHours() const153 int TimeDelta::InHours() const {
154   if (IsMax()) {
155     // Preserve max to prevent overflow.
156     return std::numeric_limits<int>::max();
157   }
158   return static_cast<int>(delta_ / Time::kMicrosecondsPerHour);
159 }
160 
InMinutes() const161 int TimeDelta::InMinutes() const {
162   if (IsMax()) {
163     // Preserve max to prevent overflow.
164     return std::numeric_limits<int>::max();
165   }
166   return static_cast<int>(delta_ / Time::kMicrosecondsPerMinute);
167 }
168 
InSecondsF() const169 double TimeDelta::InSecondsF() const {
170   if (IsMax()) {
171     // Preserve max to prevent overflow.
172     return std::numeric_limits<double>::infinity();
173   }
174   return static_cast<double>(delta_) / Time::kMicrosecondsPerSecond;
175 }
176 
InSeconds() const177 int64_t TimeDelta::InSeconds() const {
178   if (IsMax()) {
179     // Preserve max to prevent overflow.
180     return std::numeric_limits<int64_t>::max();
181   }
182   return delta_ / Time::kMicrosecondsPerSecond;
183 }
184 
InMillisecondsF() const185 double TimeDelta::InMillisecondsF() const {
186   if (IsMax()) {
187     // Preserve max to prevent overflow.
188     return std::numeric_limits<double>::infinity();
189   }
190   return static_cast<double>(delta_) / Time::kMicrosecondsPerMillisecond;
191 }
192 
InMilliseconds() const193 int64_t TimeDelta::InMilliseconds() const {
194   if (IsMax()) {
195     // Preserve max to prevent overflow.
196     return std::numeric_limits<int64_t>::max();
197   }
198   return delta_ / Time::kMicrosecondsPerMillisecond;
199 }
200 
InMillisecondsRoundedUp() const201 int64_t TimeDelta::InMillisecondsRoundedUp() const {
202   if (IsMax()) {
203     // Preserve max to prevent overflow.
204     return std::numeric_limits<int64_t>::max();
205   }
206   return (delta_ + Time::kMicrosecondsPerMillisecond - 1) /
207          Time::kMicrosecondsPerMillisecond;
208 }
209 
InMicroseconds() const210 int64_t TimeDelta::InMicroseconds() const {
211   if (IsMax()) {
212     // Preserve max to prevent overflow.
213     return std::numeric_limits<int64_t>::max();
214   }
215   return delta_;
216 }
217 
InNanoseconds() const218 int64_t TimeDelta::InNanoseconds() const {
219   if (IsMax()) {
220     // Preserve max to prevent overflow.
221     return std::numeric_limits<int64_t>::max();
222   }
223   return delta_ * Time::kNanosecondsPerMicrosecond;
224 }
225 
226 
227 #if V8_OS_MACOSX
228 
FromMachTimespec(struct mach_timespec ts)229 TimeDelta TimeDelta::FromMachTimespec(struct mach_timespec ts) {
230   DCHECK_GE(ts.tv_nsec, 0);
231   DCHECK_LT(ts.tv_nsec,
232             static_cast<long>(Time::kNanosecondsPerSecond));  // NOLINT
233   return TimeDelta(ts.tv_sec * Time::kMicrosecondsPerSecond +
234                    ts.tv_nsec / Time::kNanosecondsPerMicrosecond);
235 }
236 
237 
ToMachTimespec() const238 struct mach_timespec TimeDelta::ToMachTimespec() const {
239   struct mach_timespec ts;
240   DCHECK_GE(delta_, 0);
241   ts.tv_sec = static_cast<unsigned>(delta_ / Time::kMicrosecondsPerSecond);
242   ts.tv_nsec = (delta_ % Time::kMicrosecondsPerSecond) *
243       Time::kNanosecondsPerMicrosecond;
244   return ts;
245 }
246 
247 #endif  // V8_OS_MACOSX
248 
249 
250 #if V8_OS_POSIX
251 
FromTimespec(struct timespec ts)252 TimeDelta TimeDelta::FromTimespec(struct timespec ts) {
253   DCHECK_GE(ts.tv_nsec, 0);
254   DCHECK_LT(ts.tv_nsec,
255             static_cast<long>(Time::kNanosecondsPerSecond));  // NOLINT
256   return TimeDelta(ts.tv_sec * Time::kMicrosecondsPerSecond +
257                    ts.tv_nsec / Time::kNanosecondsPerMicrosecond);
258 }
259 
260 
ToTimespec() const261 struct timespec TimeDelta::ToTimespec() const {
262   struct timespec ts;
263   ts.tv_sec = static_cast<time_t>(delta_ / Time::kMicrosecondsPerSecond);
264   ts.tv_nsec = (delta_ % Time::kMicrosecondsPerSecond) *
265       Time::kNanosecondsPerMicrosecond;
266   return ts;
267 }
268 
269 #endif  // V8_OS_POSIX
270 
271 
272 #if V8_OS_WIN
273 
274 // We implement time using the high-resolution timers so that we can get
275 // timeouts which are smaller than 10-15ms. To avoid any drift, we
276 // periodically resync the internal clock to the system clock.
277 class Clock final {
278  public:
Clock()279   Clock() : initial_ticks_(GetSystemTicks()), initial_time_(GetSystemTime()) {}
280 
Now()281   Time Now() {
282     // Time between resampling the un-granular clock for this API (1 minute).
283     const TimeDelta kMaxElapsedTime = TimeDelta::FromMinutes(1);
284 
285     LockGuard<Mutex> lock_guard(&mutex_);
286 
287     // Determine current time and ticks.
288     TimeTicks ticks = GetSystemTicks();
289     Time time = GetSystemTime();
290 
291     // Check if we need to synchronize with the system clock due to a backwards
292     // time change or the amount of time elapsed.
293     TimeDelta elapsed = ticks - initial_ticks_;
294     if (time < initial_time_ || elapsed > kMaxElapsedTime) {
295       initial_ticks_ = ticks;
296       initial_time_ = time;
297       return time;
298     }
299 
300     return initial_time_ + elapsed;
301   }
302 
NowFromSystemTime()303   Time NowFromSystemTime() {
304     LockGuard<Mutex> lock_guard(&mutex_);
305     initial_ticks_ = GetSystemTicks();
306     initial_time_ = GetSystemTime();
307     return initial_time_;
308   }
309 
310  private:
GetSystemTicks()311   static TimeTicks GetSystemTicks() {
312     return TimeTicks::Now();
313   }
314 
GetSystemTime()315   static Time GetSystemTime() {
316     FILETIME ft;
317     ::GetSystemTimeAsFileTime(&ft);
318     return Time::FromFiletime(ft);
319   }
320 
321   TimeTicks initial_ticks_;
322   Time initial_time_;
323   Mutex mutex_;
324 };
325 
326 
327 static LazyStaticInstance<Clock, DefaultConstructTrait<Clock>,
328                           ThreadSafeInitOnceTrait>::type clock =
329     LAZY_STATIC_INSTANCE_INITIALIZER;
330 
331 
Now()332 Time Time::Now() {
333   return clock.Pointer()->Now();
334 }
335 
336 
NowFromSystemTime()337 Time Time::NowFromSystemTime() {
338   return clock.Pointer()->NowFromSystemTime();
339 }
340 
341 
342 // Time between windows epoch and standard epoch.
343 static const int64_t kTimeToEpochInMicroseconds = int64_t{11644473600000000};
344 
FromFiletime(FILETIME ft)345 Time Time::FromFiletime(FILETIME ft) {
346   if (ft.dwLowDateTime == 0 && ft.dwHighDateTime == 0) {
347     return Time();
348   }
349   if (ft.dwLowDateTime == std::numeric_limits<DWORD>::max() &&
350       ft.dwHighDateTime == std::numeric_limits<DWORD>::max()) {
351     return Max();
352   }
353   int64_t us = (static_cast<uint64_t>(ft.dwLowDateTime) +
354                 (static_cast<uint64_t>(ft.dwHighDateTime) << 32)) / 10;
355   return Time(us - kTimeToEpochInMicroseconds);
356 }
357 
358 
ToFiletime() const359 FILETIME Time::ToFiletime() const {
360   DCHECK_GE(us_, 0);
361   FILETIME ft;
362   if (IsNull()) {
363     ft.dwLowDateTime = 0;
364     ft.dwHighDateTime = 0;
365     return ft;
366   }
367   if (IsMax()) {
368     ft.dwLowDateTime = std::numeric_limits<DWORD>::max();
369     ft.dwHighDateTime = std::numeric_limits<DWORD>::max();
370     return ft;
371   }
372   uint64_t us = static_cast<uint64_t>(us_ + kTimeToEpochInMicroseconds) * 10;
373   ft.dwLowDateTime = static_cast<DWORD>(us);
374   ft.dwHighDateTime = static_cast<DWORD>(us >> 32);
375   return ft;
376 }
377 
378 #elif V8_OS_POSIX
379 
Now()380 Time Time::Now() {
381   struct timeval tv;
382   int result = gettimeofday(&tv, nullptr);
383   DCHECK_EQ(0, result);
384   USE(result);
385   return FromTimeval(tv);
386 }
387 
388 
NowFromSystemTime()389 Time Time::NowFromSystemTime() {
390   return Now();
391 }
392 
393 
FromTimespec(struct timespec ts)394 Time Time::FromTimespec(struct timespec ts) {
395   DCHECK_GE(ts.tv_nsec, 0);
396   DCHECK_LT(ts.tv_nsec, kNanosecondsPerSecond);
397   if (ts.tv_nsec == 0 && ts.tv_sec == 0) {
398     return Time();
399   }
400   if (ts.tv_nsec == static_cast<long>(kNanosecondsPerSecond - 1) &&  // NOLINT
401       ts.tv_sec == std::numeric_limits<time_t>::max()) {
402     return Max();
403   }
404   return Time(ts.tv_sec * kMicrosecondsPerSecond +
405               ts.tv_nsec / kNanosecondsPerMicrosecond);
406 }
407 
408 
ToTimespec() const409 struct timespec Time::ToTimespec() const {
410   struct timespec ts;
411   if (IsNull()) {
412     ts.tv_sec = 0;
413     ts.tv_nsec = 0;
414     return ts;
415   }
416   if (IsMax()) {
417     ts.tv_sec = std::numeric_limits<time_t>::max();
418     ts.tv_nsec = static_cast<long>(kNanosecondsPerSecond - 1);  // NOLINT
419     return ts;
420   }
421   ts.tv_sec = static_cast<time_t>(us_ / kMicrosecondsPerSecond);
422   ts.tv_nsec = (us_ % kMicrosecondsPerSecond) * kNanosecondsPerMicrosecond;
423   return ts;
424 }
425 
426 
FromTimeval(struct timeval tv)427 Time Time::FromTimeval(struct timeval tv) {
428   DCHECK_GE(tv.tv_usec, 0);
429   DCHECK(tv.tv_usec < static_cast<suseconds_t>(kMicrosecondsPerSecond));
430   if (tv.tv_usec == 0 && tv.tv_sec == 0) {
431     return Time();
432   }
433   if (tv.tv_usec == static_cast<suseconds_t>(kMicrosecondsPerSecond - 1) &&
434       tv.tv_sec == std::numeric_limits<time_t>::max()) {
435     return Max();
436   }
437   return Time(tv.tv_sec * kMicrosecondsPerSecond + tv.tv_usec);
438 }
439 
440 
ToTimeval() const441 struct timeval Time::ToTimeval() const {
442   struct timeval tv;
443   if (IsNull()) {
444     tv.tv_sec = 0;
445     tv.tv_usec = 0;
446     return tv;
447   }
448   if (IsMax()) {
449     tv.tv_sec = std::numeric_limits<time_t>::max();
450     tv.tv_usec = static_cast<suseconds_t>(kMicrosecondsPerSecond - 1);
451     return tv;
452   }
453   tv.tv_sec = static_cast<time_t>(us_ / kMicrosecondsPerSecond);
454   tv.tv_usec = us_ % kMicrosecondsPerSecond;
455   return tv;
456 }
457 
458 #endif  // V8_OS_WIN
459 
460 // static
HighResolutionNow()461 TimeTicks TimeTicks::HighResolutionNow() {
462   // a DCHECK of TimeTicks::IsHighResolution() was removed from here
463   // as it turns out this path is used in the wild for logs and counters.
464   //
465   // TODO(hpayer) We may eventually want to split TimedHistograms based
466   // on low resolution clocks to avoid polluting metrics
467   return TimeTicks::Now();
468 }
469 
FromJsTime(double ms_since_epoch)470 Time Time::FromJsTime(double ms_since_epoch) {
471   // The epoch is a valid time, so this constructor doesn't interpret
472   // 0 as the null time.
473   if (ms_since_epoch == std::numeric_limits<double>::max()) {
474     return Max();
475   }
476   return Time(
477       static_cast<int64_t>(ms_since_epoch * kMicrosecondsPerMillisecond));
478 }
479 
480 
ToJsTime() const481 double Time::ToJsTime() const {
482   if (IsNull()) {
483     // Preserve 0 so the invalid result doesn't depend on the platform.
484     return 0;
485   }
486   if (IsMax()) {
487     // Preserve max without offset to prevent overflow.
488     return std::numeric_limits<double>::max();
489   }
490   return static_cast<double>(us_) / kMicrosecondsPerMillisecond;
491 }
492 
493 
operator <<(std::ostream & os,const Time & time)494 std::ostream& operator<<(std::ostream& os, const Time& time) {
495   return os << time.ToJsTime();
496 }
497 
498 
499 #if V8_OS_WIN
500 
501 namespace {
502 
503 // We define a wrapper to adapt between the __stdcall and __cdecl call of the
504 // mock function, and to avoid a static constructor.  Assigning an import to a
505 // function pointer directly would require setup code to fetch from the IAT.
timeGetTimeWrapper()506 DWORD timeGetTimeWrapper() { return timeGetTime(); }
507 
508 DWORD (*g_tick_function)(void) = &timeGetTimeWrapper;
509 
510 // A structure holding the most significant bits of "last seen" and a
511 // "rollover" counter.
512 union LastTimeAndRolloversState {
513   // The state as a single 32-bit opaque value.
514   base::Atomic32 as_opaque_32;
515 
516   // The state as usable values.
517   struct {
518     // The top 8-bits of the "last" time. This is enough to check for rollovers
519     // and the small bit-size means fewer CompareAndSwap operations to store
520     // changes in state, which in turn makes for fewer retries.
521     uint8_t last_8;
522     // A count of the number of detected rollovers. Using this as bits 47-32
523     // of the upper half of a 64-bit value results in a 48-bit tick counter.
524     // This extends the total rollover period from about 49 days to about 8800
525     // years while still allowing it to be stored with last_8 in a single
526     // 32-bit value.
527     uint16_t rollovers;
528   } as_values;
529 };
530 base::Atomic32 g_last_time_and_rollovers = 0;
531 static_assert(sizeof(LastTimeAndRolloversState) <=
532                   sizeof(g_last_time_and_rollovers),
533               "LastTimeAndRolloversState does not fit in a single atomic word");
534 
535 // We use timeGetTime() to implement TimeTicks::Now().  This can be problematic
536 // because it returns the number of milliseconds since Windows has started,
537 // which will roll over the 32-bit value every ~49 days.  We try to track
538 // rollover ourselves, which works if TimeTicks::Now() is called at least every
539 // 48.8 days (not 49 days because only changes in the top 8 bits get noticed).
RolloverProtectedNow()540 TimeTicks RolloverProtectedNow() {
541   LastTimeAndRolloversState state;
542   DWORD now;  // DWORD is always unsigned 32 bits.
543 
544   while (true) {
545     // Fetch the "now" and "last" tick values, updating "last" with "now" and
546     // incrementing the "rollovers" counter if the tick-value has wrapped back
547     // around. Atomic operations ensure that both "last" and "rollovers" are
548     // always updated together.
549     int32_t original = base::Acquire_Load(&g_last_time_and_rollovers);
550     state.as_opaque_32 = original;
551     now = g_tick_function();
552     uint8_t now_8 = static_cast<uint8_t>(now >> 24);
553     if (now_8 < state.as_values.last_8) ++state.as_values.rollovers;
554     state.as_values.last_8 = now_8;
555 
556     // If the state hasn't changed, exit the loop.
557     if (state.as_opaque_32 == original) break;
558 
559     // Save the changed state. If the existing value is unchanged from the
560     // original, exit the loop.
561     int32_t check = base::Release_CompareAndSwap(&g_last_time_and_rollovers,
562                                                  original, state.as_opaque_32);
563     if (check == original) break;
564 
565     // Another thread has done something in between so retry from the top.
566   }
567 
568   return TimeTicks() +
569          TimeDelta::FromMilliseconds(
570              now + (static_cast<uint64_t>(state.as_values.rollovers) << 32));
571 }
572 
573 // Discussion of tick counter options on Windows:
574 //
575 // (1) CPU cycle counter. (Retrieved via RDTSC)
576 // The CPU counter provides the highest resolution time stamp and is the least
577 // expensive to retrieve. However, on older CPUs, two issues can affect its
578 // reliability: First it is maintained per processor and not synchronized
579 // between processors. Also, the counters will change frequency due to thermal
580 // and power changes, and stop in some states.
581 //
582 // (2) QueryPerformanceCounter (QPC). The QPC counter provides a high-
583 // resolution (<1 microsecond) time stamp. On most hardware running today, it
584 // auto-detects and uses the constant-rate RDTSC counter to provide extremely
585 // efficient and reliable time stamps.
586 //
587 // On older CPUs where RDTSC is unreliable, it falls back to using more
588 // expensive (20X to 40X more costly) alternate clocks, such as HPET or the ACPI
589 // PM timer, and can involve system calls; and all this is up to the HAL (with
590 // some help from ACPI). According to
591 // http://blogs.msdn.com/oldnewthing/archive/2005/09/02/459952.aspx, in the
592 // worst case, it gets the counter from the rollover interrupt on the
593 // programmable interrupt timer. In best cases, the HAL may conclude that the
594 // RDTSC counter runs at a constant frequency, then it uses that instead. On
595 // multiprocessor machines, it will try to verify the values returned from
596 // RDTSC on each processor are consistent with each other, and apply a handful
597 // of workarounds for known buggy hardware. In other words, QPC is supposed to
598 // give consistent results on a multiprocessor computer, but for older CPUs it
599 // can be unreliable due bugs in BIOS or HAL.
600 //
601 // (3) System time. The system time provides a low-resolution (from ~1 to ~15.6
602 // milliseconds) time stamp but is comparatively less expensive to retrieve and
603 // more reliable. Time::EnableHighResolutionTimer() and
604 // Time::ActivateHighResolutionTimer() can be called to alter the resolution of
605 // this timer; and also other Windows applications can alter it, affecting this
606 // one.
607 
608 TimeTicks InitialTimeTicksNowFunction();
609 
610 // See "threading notes" in InitializeNowFunctionPointer() for details on how
611 // concurrent reads/writes to these globals has been made safe.
612 using TimeTicksNowFunction = decltype(&TimeTicks::Now);
613 TimeTicksNowFunction g_time_ticks_now_function = &InitialTimeTicksNowFunction;
614 int64_t g_qpc_ticks_per_second = 0;
615 
616 // As of January 2015, use of <atomic> is forbidden in Chromium code. This is
617 // what std::atomic_thread_fence does on Windows on all Intel architectures when
618 // the memory_order argument is anything but std::memory_order_seq_cst:
619 #define ATOMIC_THREAD_FENCE(memory_order) _ReadWriteBarrier();
620 
QPCValueToTimeDelta(LONGLONG qpc_value)621 TimeDelta QPCValueToTimeDelta(LONGLONG qpc_value) {
622   // Ensure that the assignment to |g_qpc_ticks_per_second|, made in
623   // InitializeNowFunctionPointer(), has happened by this point.
624   ATOMIC_THREAD_FENCE(memory_order_acquire);
625 
626   DCHECK_GT(g_qpc_ticks_per_second, 0);
627 
628   // If the QPC Value is below the overflow threshold, we proceed with
629   // simple multiply and divide.
630   if (qpc_value < TimeTicks::kQPCOverflowThreshold) {
631     return TimeDelta::FromMicroseconds(
632         qpc_value * TimeTicks::kMicrosecondsPerSecond / g_qpc_ticks_per_second);
633   }
634   // Otherwise, calculate microseconds in a round about manner to avoid
635   // overflow and precision issues.
636   int64_t whole_seconds = qpc_value / g_qpc_ticks_per_second;
637   int64_t leftover_ticks = qpc_value - (whole_seconds * g_qpc_ticks_per_second);
638   return TimeDelta::FromMicroseconds(
639       (whole_seconds * TimeTicks::kMicrosecondsPerSecond) +
640       ((leftover_ticks * TimeTicks::kMicrosecondsPerSecond) /
641        g_qpc_ticks_per_second));
642 }
643 
QPCNow()644 TimeTicks QPCNow() { return TimeTicks() + QPCValueToTimeDelta(QPCNowRaw()); }
645 
IsBuggyAthlon(const CPU & cpu)646 bool IsBuggyAthlon(const CPU& cpu) {
647   // On Athlon X2 CPUs (e.g. model 15) QueryPerformanceCounter is unreliable.
648   return strcmp(cpu.vendor(), "AuthenticAMD") == 0 && cpu.family() == 15;
649 }
650 
InitializeTimeTicksNowFunctionPointer()651 void InitializeTimeTicksNowFunctionPointer() {
652   LARGE_INTEGER ticks_per_sec = {};
653   if (!QueryPerformanceFrequency(&ticks_per_sec)) ticks_per_sec.QuadPart = 0;
654 
655   // If Windows cannot provide a QPC implementation, TimeTicks::Now() must use
656   // the low-resolution clock.
657   //
658   // If the QPC implementation is expensive and/or unreliable, TimeTicks::Now()
659   // will still use the low-resolution clock. A CPU lacking a non-stop time
660   // counter will cause Windows to provide an alternate QPC implementation that
661   // works, but is expensive to use. Certain Athlon CPUs are known to make the
662   // QPC implementation unreliable.
663   //
664   // Otherwise, Now uses the high-resolution QPC clock. As of 21 August 2015,
665   // ~72% of users fall within this category.
666   TimeTicksNowFunction now_function;
667   CPU cpu;
668   if (ticks_per_sec.QuadPart <= 0 || !cpu.has_non_stop_time_stamp_counter() ||
669       IsBuggyAthlon(cpu)) {
670     now_function = &RolloverProtectedNow;
671   } else {
672     now_function = &QPCNow;
673   }
674 
675   // Threading note 1: In an unlikely race condition, it's possible for two or
676   // more threads to enter InitializeNowFunctionPointer() in parallel. This is
677   // not a problem since all threads should end up writing out the same values
678   // to the global variables.
679   //
680   // Threading note 2: A release fence is placed here to ensure, from the
681   // perspective of other threads using the function pointers, that the
682   // assignment to |g_qpc_ticks_per_second| happens before the function pointers
683   // are changed.
684   g_qpc_ticks_per_second = ticks_per_sec.QuadPart;
685   ATOMIC_THREAD_FENCE(memory_order_release);
686   g_time_ticks_now_function = now_function;
687 }
688 
InitialTimeTicksNowFunction()689 TimeTicks InitialTimeTicksNowFunction() {
690   InitializeTimeTicksNowFunctionPointer();
691   return g_time_ticks_now_function();
692 }
693 
694 #undef ATOMIC_THREAD_FENCE
695 
696 }  // namespace
697 
698 // static
Now()699 TimeTicks TimeTicks::Now() {
700   // Make sure we never return 0 here.
701   TimeTicks ticks(g_time_ticks_now_function());
702   DCHECK(!ticks.IsNull());
703   return ticks;
704 }
705 
706 // static
IsHighResolution()707 bool TimeTicks::IsHighResolution() {
708   if (g_time_ticks_now_function == &InitialTimeTicksNowFunction)
709     InitializeTimeTicksNowFunctionPointer();
710   return g_time_ticks_now_function == &QPCNow;
711 }
712 
713 #else  // V8_OS_WIN
714 
Now()715 TimeTicks TimeTicks::Now() {
716   int64_t ticks;
717 #if V8_OS_MACOSX
718   static struct mach_timebase_info info;
719   if (info.denom == 0) {
720     kern_return_t result = mach_timebase_info(&info);
721     DCHECK_EQ(KERN_SUCCESS, result);
722     USE(result);
723   }
724   ticks = (mach_absolute_time() / Time::kNanosecondsPerMicrosecond *
725            info.numer / info.denom);
726 #elif V8_OS_SOLARIS
727   ticks = (gethrtime() / Time::kNanosecondsPerMicrosecond);
728 #elif V8_OS_POSIX
729   ticks = ClockNow(CLOCK_MONOTONIC);
730 #else
731 #error platform does not implement TimeTicks::HighResolutionNow.
732 #endif  // V8_OS_MACOSX
733   // Make sure we never return 0 here.
734   return TimeTicks(ticks + 1);
735 }
736 
737 // static
IsHighResolution()738 bool TimeTicks::IsHighResolution() { return true; }
739 
740 #endif  // V8_OS_WIN
741 
742 
IsSupported()743 bool ThreadTicks::IsSupported() {
744 #if (defined(_POSIX_THREAD_CPUTIME) && (_POSIX_THREAD_CPUTIME >= 0)) || \
745     defined(V8_OS_MACOSX) || defined(V8_OS_ANDROID) || defined(V8_OS_SOLARIS)
746   return true;
747 #elif defined(V8_OS_WIN)
748   return IsSupportedWin();
749 #else
750   return false;
751 #endif
752 }
753 
754 
Now()755 ThreadTicks ThreadTicks::Now() {
756 #if V8_OS_MACOSX
757   return ThreadTicks(ComputeThreadTicks());
758 #elif(defined(_POSIX_THREAD_CPUTIME) && (_POSIX_THREAD_CPUTIME >= 0)) || \
759   defined(V8_OS_ANDROID)
760   return ThreadTicks(ClockNow(CLOCK_THREAD_CPUTIME_ID));
761 #elif V8_OS_SOLARIS
762   return ThreadTicks(gethrvtime() / Time::kNanosecondsPerMicrosecond);
763 #elif V8_OS_WIN
764   return ThreadTicks::GetForThread(::GetCurrentThread());
765 #else
766   UNREACHABLE();
767 #endif
768 }
769 
770 
771 #if V8_OS_WIN
GetForThread(const HANDLE & thread_handle)772 ThreadTicks ThreadTicks::GetForThread(const HANDLE& thread_handle) {
773   DCHECK(IsSupported());
774 
775   // Get the number of TSC ticks used by the current thread.
776   ULONG64 thread_cycle_time = 0;
777   ::QueryThreadCycleTime(thread_handle, &thread_cycle_time);
778 
779   // Get the frequency of the TSC.
780   double tsc_ticks_per_second = TSCTicksPerSecond();
781   if (tsc_ticks_per_second == 0)
782     return ThreadTicks();
783 
784   // Return the CPU time of the current thread.
785   double thread_time_seconds = thread_cycle_time / tsc_ticks_per_second;
786   return ThreadTicks(
787       static_cast<int64_t>(thread_time_seconds * Time::kMicrosecondsPerSecond));
788 }
789 
790 // static
IsSupportedWin()791 bool ThreadTicks::IsSupportedWin() {
792   static bool is_supported = base::CPU().has_non_stop_time_stamp_counter() &&
793                              !IsQPCReliable();
794   return is_supported;
795 }
796 
797 // static
WaitUntilInitializedWin()798 void ThreadTicks::WaitUntilInitializedWin() {
799   while (TSCTicksPerSecond() == 0)
800     ::Sleep(10);
801 }
802 
TSCTicksPerSecond()803 double ThreadTicks::TSCTicksPerSecond() {
804   DCHECK(IsSupported());
805 
806   // The value returned by QueryPerformanceFrequency() cannot be used as the TSC
807   // frequency, because there is no guarantee that the TSC frequency is equal to
808   // the performance counter frequency.
809 
810   // The TSC frequency is cached in a static variable because it takes some time
811   // to compute it.
812   static double tsc_ticks_per_second = 0;
813   if (tsc_ticks_per_second != 0)
814     return tsc_ticks_per_second;
815 
816   // Increase the thread priority to reduces the chances of having a context
817   // switch during a reading of the TSC and the performance counter.
818   int previous_priority = ::GetThreadPriority(::GetCurrentThread());
819   ::SetThreadPriority(::GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
820 
821   // The first time that this function is called, make an initial reading of the
822   // TSC and the performance counter.
823   static const uint64_t tsc_initial = __rdtsc();
824   static const uint64_t perf_counter_initial = QPCNowRaw();
825 
826   // Make a another reading of the TSC and the performance counter every time
827   // that this function is called.
828   uint64_t tsc_now = __rdtsc();
829   uint64_t perf_counter_now = QPCNowRaw();
830 
831   // Reset the thread priority.
832   ::SetThreadPriority(::GetCurrentThread(), previous_priority);
833 
834   // Make sure that at least 50 ms elapsed between the 2 readings. The first
835   // time that this function is called, we don't expect this to be the case.
836   // Note: The longer the elapsed time between the 2 readings is, the more
837   //   accurate the computed TSC frequency will be. The 50 ms value was
838   //   chosen because local benchmarks show that it allows us to get a
839   //   stddev of less than 1 tick/us between multiple runs.
840   // Note: According to the MSDN documentation for QueryPerformanceFrequency(),
841   //   this will never fail on systems that run XP or later.
842   //   https://msdn.microsoft.com/library/windows/desktop/ms644905.aspx
843   LARGE_INTEGER perf_counter_frequency = {};
844   ::QueryPerformanceFrequency(&perf_counter_frequency);
845   DCHECK_GE(perf_counter_now, perf_counter_initial);
846   uint64_t perf_counter_ticks = perf_counter_now - perf_counter_initial;
847   double elapsed_time_seconds =
848       perf_counter_ticks / static_cast<double>(perf_counter_frequency.QuadPart);
849 
850   const double kMinimumEvaluationPeriodSeconds = 0.05;
851   if (elapsed_time_seconds < kMinimumEvaluationPeriodSeconds)
852     return 0;
853 
854   // Compute the frequency of the TSC.
855   DCHECK_GE(tsc_now, tsc_initial);
856   uint64_t tsc_ticks = tsc_now - tsc_initial;
857   tsc_ticks_per_second = tsc_ticks / elapsed_time_seconds;
858 
859   return tsc_ticks_per_second;
860 }
861 #endif  // V8_OS_WIN
862 
863 }  // namespace base
864 }  // namespace v8
865