SupervisedUserSyncService cleanup: Implement SigninManagerBase::Observer
[chromium-blink-merge.git] / base / time / time_win.cc
blobd2403f21b7ff5538f0449bde39e423a5777f8998
1 // Copyright (c) 2012 The Chromium 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.
6 // Windows Timer Primer
7 //
8 // A good article: http://www.ddj.com/windows/184416651
9 // A good mozilla bug: http://bugzilla.mozilla.org/show_bug.cgi?id=363258
11 // The default windows timer, GetSystemTimeAsFileTime is not very precise.
12 // It is only good to ~15.5ms.
14 // QueryPerformanceCounter is the logical choice for a high-precision timer.
15 // However, it is known to be buggy on some hardware. Specifically, it can
16 // sometimes "jump". On laptops, QPC can also be very expensive to call.
17 // It's 3-4x slower than timeGetTime() on desktops, but can be 10x slower
18 // on laptops. A unittest exists which will show the relative cost of various
19 // timers on any system.
21 // The next logical choice is timeGetTime(). timeGetTime has a precision of
22 // 1ms, but only if you call APIs (timeBeginPeriod()) which affect all other
23 // applications on the system. By default, precision is only 15.5ms.
24 // Unfortunately, we don't want to call timeBeginPeriod because we don't
25 // want to affect other applications. Further, on mobile platforms, use of
26 // faster multimedia timers can hurt battery life. See the intel
27 // article about this here:
28 // http://softwarecommunity.intel.com/articles/eng/1086.htm
30 // To work around all this, we're going to generally use timeGetTime(). We
31 // will only increase the system-wide timer if we're not running on battery
32 // power.
34 #include "base/time/time.h"
36 #pragma comment(lib, "winmm.lib")
37 #include <windows.h>
38 #include <mmsystem.h>
40 #include "base/basictypes.h"
41 #include "base/cpu.h"
42 #include "base/lazy_instance.h"
43 #include "base/logging.h"
44 #include "base/synchronization/lock.h"
46 using base::Time;
47 using base::TimeDelta;
48 using base::TimeTicks;
50 namespace {
52 // From MSDN, FILETIME "Contains a 64-bit value representing the number of
53 // 100-nanosecond intervals since January 1, 1601 (UTC)."
54 int64 FileTimeToMicroseconds(const FILETIME& ft) {
55 // Need to bit_cast to fix alignment, then divide by 10 to convert
56 // 100-nanoseconds to milliseconds. This only works on little-endian
57 // machines.
58 return bit_cast<int64, FILETIME>(ft) / 10;
61 void MicrosecondsToFileTime(int64 us, FILETIME* ft) {
62 DCHECK_GE(us, 0LL) << "Time is less than 0, negative values are not "
63 "representable in FILETIME";
65 // Multiply by 10 to convert milliseconds to 100-nanoseconds. Bit_cast will
66 // handle alignment problems. This only works on little-endian machines.
67 *ft = bit_cast<FILETIME, int64>(us * 10);
70 int64 CurrentWallclockMicroseconds() {
71 FILETIME ft;
72 ::GetSystemTimeAsFileTime(&ft);
73 return FileTimeToMicroseconds(ft);
76 // Time between resampling the un-granular clock for this API. 60 seconds.
77 const int kMaxMillisecondsToAvoidDrift = 60 * Time::kMillisecondsPerSecond;
79 int64 initial_time = 0;
80 TimeTicks initial_ticks;
82 void InitializeClock() {
83 initial_ticks = TimeTicks::Now();
84 initial_time = CurrentWallclockMicroseconds();
87 // The two values that ActivateHighResolutionTimer uses to set the systemwide
88 // timer interrupt frequency on Windows. It controls how precise timers are
89 // but also has a big impact on battery life.
90 const int kMinTimerIntervalHighResMs = 1;
91 const int kMinTimerIntervalLowResMs = 4;
92 // Track if kMinTimerIntervalHighResMs or kMinTimerIntervalLowResMs is active.
93 bool g_high_res_timer_enabled = false;
94 // How many times the high resolution timer has been called.
95 uint32_t g_high_res_timer_count = 0;
96 // The lock to control access to the above two variables.
97 base::LazyInstance<base::Lock>::Leaky g_high_res_lock =
98 LAZY_INSTANCE_INITIALIZER;
100 } // namespace
102 // Time -----------------------------------------------------------------------
104 // The internal representation of Time uses FILETIME, whose epoch is 1601-01-01
105 // 00:00:00 UTC. ((1970-1601)*365+89)*24*60*60*1000*1000, where 89 is the
106 // number of leap year days between 1601 and 1970: (1970-1601)/4 excluding
107 // 1700, 1800, and 1900.
108 // static
109 const int64 Time::kTimeTToMicrosecondsOffset = GG_INT64_C(11644473600000000);
111 // static
112 Time Time::Now() {
113 if (initial_time == 0)
114 InitializeClock();
116 // We implement time using the high-resolution timers so that we can get
117 // timeouts which are smaller than 10-15ms. If we just used
118 // CurrentWallclockMicroseconds(), we'd have the less-granular timer.
120 // To make this work, we initialize the clock (initial_time) and the
121 // counter (initial_ctr). To compute the initial time, we can check
122 // the number of ticks that have elapsed, and compute the delta.
124 // To avoid any drift, we periodically resync the counters to the system
125 // clock.
126 while (true) {
127 TimeTicks ticks = TimeTicks::Now();
129 // Calculate the time elapsed since we started our timer
130 TimeDelta elapsed = ticks - initial_ticks;
132 // Check if enough time has elapsed that we need to resync the clock.
133 if (elapsed.InMilliseconds() > kMaxMillisecondsToAvoidDrift) {
134 InitializeClock();
135 continue;
138 return Time(elapsed + Time(initial_time));
142 // static
143 Time Time::NowFromSystemTime() {
144 // Force resync.
145 InitializeClock();
146 return Time(initial_time);
149 // static
150 Time Time::FromFileTime(FILETIME ft) {
151 if (bit_cast<int64, FILETIME>(ft) == 0)
152 return Time();
153 if (ft.dwHighDateTime == std::numeric_limits<DWORD>::max() &&
154 ft.dwLowDateTime == std::numeric_limits<DWORD>::max())
155 return Max();
156 return Time(FileTimeToMicroseconds(ft));
159 FILETIME Time::ToFileTime() const {
160 if (is_null())
161 return bit_cast<FILETIME, int64>(0);
162 if (is_max()) {
163 FILETIME result;
164 result.dwHighDateTime = std::numeric_limits<DWORD>::max();
165 result.dwLowDateTime = std::numeric_limits<DWORD>::max();
166 return result;
168 FILETIME utc_ft;
169 MicrosecondsToFileTime(us_, &utc_ft);
170 return utc_ft;
173 // static
174 void Time::EnableHighResolutionTimer(bool enable) {
175 base::AutoLock lock(g_high_res_lock.Get());
176 if (g_high_res_timer_enabled == enable)
177 return;
178 g_high_res_timer_enabled = enable;
179 if (!g_high_res_timer_count)
180 return;
181 // Since g_high_res_timer_count != 0, an ActivateHighResolutionTimer(true)
182 // was called which called timeBeginPeriod with g_high_res_timer_enabled
183 // with a value which is the opposite of |enable|. With that information we
184 // call timeEndPeriod with the same value used in timeBeginPeriod and
185 // therefore undo the period effect.
186 if (enable) {
187 timeEndPeriod(kMinTimerIntervalLowResMs);
188 timeBeginPeriod(kMinTimerIntervalHighResMs);
189 } else {
190 timeEndPeriod(kMinTimerIntervalHighResMs);
191 timeBeginPeriod(kMinTimerIntervalLowResMs);
195 // static
196 bool Time::ActivateHighResolutionTimer(bool activating) {
197 // We only do work on the transition from zero to one or one to zero so we
198 // can easily undo the effect (if necessary) when EnableHighResolutionTimer is
199 // called.
200 const uint32_t max = std::numeric_limits<uint32_t>::max();
202 base::AutoLock lock(g_high_res_lock.Get());
203 UINT period = g_high_res_timer_enabled ? kMinTimerIntervalHighResMs
204 : kMinTimerIntervalLowResMs;
205 if (activating) {
206 DCHECK_NE(g_high_res_timer_count, max);
207 ++g_high_res_timer_count;
208 if (g_high_res_timer_count == 1)
209 timeBeginPeriod(period);
210 } else {
211 DCHECK_NE(g_high_res_timer_count, 0u);
212 --g_high_res_timer_count;
213 if (g_high_res_timer_count == 0)
214 timeEndPeriod(period);
216 return (period == kMinTimerIntervalHighResMs);
219 // static
220 bool Time::IsHighResolutionTimerInUse() {
221 base::AutoLock lock(g_high_res_lock.Get());
222 return g_high_res_timer_enabled && g_high_res_timer_count > 0;
225 // static
226 Time Time::FromExploded(bool is_local, const Exploded& exploded) {
227 // Create the system struct representing our exploded time. It will either be
228 // in local time or UTC.
229 SYSTEMTIME st;
230 st.wYear = static_cast<WORD>(exploded.year);
231 st.wMonth = static_cast<WORD>(exploded.month);
232 st.wDayOfWeek = static_cast<WORD>(exploded.day_of_week);
233 st.wDay = static_cast<WORD>(exploded.day_of_month);
234 st.wHour = static_cast<WORD>(exploded.hour);
235 st.wMinute = static_cast<WORD>(exploded.minute);
236 st.wSecond = static_cast<WORD>(exploded.second);
237 st.wMilliseconds = static_cast<WORD>(exploded.millisecond);
239 FILETIME ft;
240 bool success = true;
241 // Ensure that it's in UTC.
242 if (is_local) {
243 SYSTEMTIME utc_st;
244 success = TzSpecificLocalTimeToSystemTime(NULL, &st, &utc_st) &&
245 SystemTimeToFileTime(&utc_st, &ft);
246 } else {
247 success = !!SystemTimeToFileTime(&st, &ft);
250 if (!success) {
251 NOTREACHED() << "Unable to convert time";
252 return Time(0);
254 return Time(FileTimeToMicroseconds(ft));
257 void Time::Explode(bool is_local, Exploded* exploded) const {
258 if (us_ < 0LL) {
259 // We are not able to convert it to FILETIME.
260 ZeroMemory(exploded, sizeof(*exploded));
261 return;
264 // FILETIME in UTC.
265 FILETIME utc_ft;
266 MicrosecondsToFileTime(us_, &utc_ft);
268 // FILETIME in local time if necessary.
269 bool success = true;
270 // FILETIME in SYSTEMTIME (exploded).
271 SYSTEMTIME st = {0};
272 if (is_local) {
273 SYSTEMTIME utc_st;
274 // We don't use FileTimeToLocalFileTime here, since it uses the current
275 // settings for the time zone and daylight saving time. Therefore, if it is
276 // daylight saving time, it will take daylight saving time into account,
277 // even if the time you are converting is in standard time.
278 success = FileTimeToSystemTime(&utc_ft, &utc_st) &&
279 SystemTimeToTzSpecificLocalTime(NULL, &utc_st, &st);
280 } else {
281 success = !!FileTimeToSystemTime(&utc_ft, &st);
284 if (!success) {
285 NOTREACHED() << "Unable to convert time, don't know why";
286 ZeroMemory(exploded, sizeof(*exploded));
287 return;
290 exploded->year = st.wYear;
291 exploded->month = st.wMonth;
292 exploded->day_of_week = st.wDayOfWeek;
293 exploded->day_of_month = st.wDay;
294 exploded->hour = st.wHour;
295 exploded->minute = st.wMinute;
296 exploded->second = st.wSecond;
297 exploded->millisecond = st.wMilliseconds;
300 // TimeTicks ------------------------------------------------------------------
301 namespace {
303 // We define a wrapper to adapt between the __stdcall and __cdecl call of the
304 // mock function, and to avoid a static constructor. Assigning an import to a
305 // function pointer directly would require setup code to fetch from the IAT.
306 DWORD timeGetTimeWrapper() {
307 return timeGetTime();
310 DWORD (*g_tick_function)(void) = &timeGetTimeWrapper;
312 // Accumulation of time lost due to rollover (in milliseconds).
313 int64 g_rollover_ms = 0;
315 // The last timeGetTime value we saw, to detect rollover.
316 DWORD g_last_seen_now = 0;
318 // Lock protecting rollover_ms and last_seen_now.
319 // Note: this is a global object, and we usually avoid these. However, the time
320 // code is low-level, and we don't want to use Singletons here (it would be too
321 // easy to use a Singleton without even knowing it, and that may lead to many
322 // gotchas). Its impact on startup time should be negligible due to low-level
323 // nature of time code.
324 base::Lock g_rollover_lock;
326 // We use timeGetTime() to implement TimeTicks::Now(). This can be problematic
327 // because it returns the number of milliseconds since Windows has started,
328 // which will roll over the 32-bit value every ~49 days. We try to track
329 // rollover ourselves, which works if TimeTicks::Now() is called at least every
330 // 49 days.
331 TimeTicks RolloverProtectedNow() {
332 base::AutoLock locked(g_rollover_lock);
333 // We should hold the lock while calling tick_function to make sure that
334 // we keep last_seen_now stay correctly in sync.
335 DWORD now = g_tick_function();
336 if (now < g_last_seen_now)
337 g_rollover_ms += 0x100000000I64; // ~49.7 days.
338 g_last_seen_now = now;
339 return TimeTicks() + TimeDelta::FromMilliseconds(now + g_rollover_ms);
342 // Discussion of tick counter options on Windows:
344 // (1) CPU cycle counter. (Retrieved via RDTSC)
345 // The CPU counter provides the highest resolution time stamp and is the least
346 // expensive to retrieve. However, on older CPUs, two issues can affect its
347 // reliability: First it is maintained per processor and not synchronized
348 // between processors. Also, the counters will change frequency due to thermal
349 // and power changes, and stop in some states.
351 // (2) QueryPerformanceCounter (QPC). The QPC counter provides a high-
352 // resolution (<1 microsecond) time stamp. On most hardware running today, it
353 // auto-detects and uses the constant-rate RDTSC counter to provide extremely
354 // efficient and reliable time stamps.
356 // On older CPUs where RDTSC is unreliable, it falls back to using more
357 // expensive (20X to 40X more costly) alternate clocks, such as HPET or the ACPI
358 // PM timer, and can involve system calls; and all this is up to the HAL (with
359 // some help from ACPI). According to
360 // http://blogs.msdn.com/oldnewthing/archive/2005/09/02/459952.aspx, in the
361 // worst case, it gets the counter from the rollover interrupt on the
362 // programmable interrupt timer. In best cases, the HAL may conclude that the
363 // RDTSC counter runs at a constant frequency, then it uses that instead. On
364 // multiprocessor machines, it will try to verify the values returned from
365 // RDTSC on each processor are consistent with each other, and apply a handful
366 // of workarounds for known buggy hardware. In other words, QPC is supposed to
367 // give consistent results on a multiprocessor computer, but for older CPUs it
368 // can be unreliable due bugs in BIOS or HAL.
370 // (3) System time. The system time provides a low-resolution (from ~1 to ~15.6
371 // milliseconds) time stamp but is comparatively less expensive to retrieve and
372 // more reliable. Time::EnableHighResolutionTimer() and
373 // Time::ActivateHighResolutionTimer() can be called to alter the resolution of
374 // this timer; and also other Windows applications can alter it, affecting this
375 // one.
377 using NowFunction = TimeTicks (*)(void);
379 TimeTicks InitialNowFunction();
380 TimeTicks InitialSystemTraceNowFunction();
382 // See "threading notes" in InitializeNowFunctionPointers() for details on how
383 // concurrent reads/writes to these globals has been made safe.
384 NowFunction g_now_function = &InitialNowFunction;
385 NowFunction g_system_trace_now_function = &InitialSystemTraceNowFunction;
386 int64 g_qpc_ticks_per_second = 0;
388 // As of January 2015, use of <atomic> is forbidden in Chromium code. This is
389 // what std::atomic_thread_fence does on Windows on all Intel architectures when
390 // the memory_order argument is anything but std::memory_order_seq_cst:
391 #define ATOMIC_THREAD_FENCE(memory_order) _ReadWriteBarrier();
393 TimeDelta QPCValueToTimeDelta(LONGLONG qpc_value) {
394 // Ensure that the assignment to |g_qpc_ticks_per_second|, made in
395 // InitializeNowFunctionPointers(), has happened by this point.
396 ATOMIC_THREAD_FENCE(memory_order_acquire);
398 DCHECK_GT(g_qpc_ticks_per_second, 0);
400 // If the QPC Value is below the overflow threshold, we proceed with
401 // simple multiply and divide.
402 if (qpc_value < Time::kQPCOverflowThreshold) {
403 return TimeDelta::FromMicroseconds(
404 qpc_value * Time::kMicrosecondsPerSecond / g_qpc_ticks_per_second);
406 // Otherwise, calculate microseconds in a round about manner to avoid
407 // overflow and precision issues.
408 int64 whole_seconds = qpc_value / g_qpc_ticks_per_second;
409 int64 leftover_ticks = qpc_value - (whole_seconds * g_qpc_ticks_per_second);
410 return TimeDelta::FromMicroseconds(
411 (whole_seconds * Time::kMicrosecondsPerSecond) +
412 ((leftover_ticks * Time::kMicrosecondsPerSecond) /
413 g_qpc_ticks_per_second));
416 TimeTicks QPCNow() {
417 LARGE_INTEGER now;
418 QueryPerformanceCounter(&now);
419 return TimeTicks() + QPCValueToTimeDelta(now.QuadPart);
422 bool IsBuggyAthlon(const base::CPU& cpu) {
423 // On Athlon X2 CPUs (e.g. model 15) QueryPerformanceCounter is unreliable.
424 return cpu.vendor_name() == "AuthenticAMD" && cpu.family() == 15;
427 void InitializeNowFunctionPointers() {
428 LARGE_INTEGER ticks_per_sec = {0};
429 if (!QueryPerformanceFrequency(&ticks_per_sec))
430 ticks_per_sec.QuadPart = 0;
432 // If Windows cannot provide a QPC implementation, both Now() and
433 // NowFromSystemTraceTime() must use the low-resolution clock.
435 // If the QPC implementation is expensive and/or unreliable, Now() will use
436 // the low-resolution clock, but NowFromSystemTraceTime() will use the QPC (in
437 // the hope that it is still useful for tracing purposes). A CPU lacking a
438 // non-stop time counter will cause Windows to provide an alternate QPC
439 // implementation that works, but is expensive to use. Certain Athlon CPUs are
440 // known to make the QPC implementation unreliable.
442 // Otherwise, both Now functions can use the high-resolution QPC clock. As of
443 // 4 January 2015, ~68% of users fall within this category.
444 NowFunction now_function;
445 NowFunction system_trace_now_function;
446 base::CPU cpu;
447 if (ticks_per_sec.QuadPart <= 0) {
448 now_function = system_trace_now_function = &RolloverProtectedNow;
449 } else if (!cpu.has_non_stop_time_stamp_counter() || IsBuggyAthlon(cpu)) {
450 now_function = &RolloverProtectedNow;
451 system_trace_now_function = &QPCNow;
452 } else {
453 now_function = system_trace_now_function = &QPCNow;
456 // Threading note 1: In an unlikely race condition, it's possible for two or
457 // more threads to enter InitializeNowFunctionPointers() in parallel. This is
458 // not a problem since all threads should end up writing out the same values
459 // to the global variables.
461 // Threading note 2: A release fence is placed here to ensure, from the
462 // perspective of other threads using the function pointers, that the
463 // assignment to |g_qpc_ticks_per_second| happens before the function pointers
464 // are changed.
465 g_qpc_ticks_per_second = ticks_per_sec.QuadPart;
466 ATOMIC_THREAD_FENCE(memory_order_release);
467 g_now_function = now_function;
468 g_system_trace_now_function = system_trace_now_function;
471 TimeTicks InitialNowFunction() {
472 InitializeNowFunctionPointers();
473 return g_now_function();
476 TimeTicks InitialSystemTraceNowFunction() {
477 InitializeNowFunctionPointers();
478 return g_system_trace_now_function();
481 } // namespace
483 // static
484 TimeTicks::TickFunctionType TimeTicks::SetMockTickFunction(
485 TickFunctionType ticker) {
486 base::AutoLock locked(g_rollover_lock);
487 TickFunctionType old = g_tick_function;
488 g_tick_function = ticker;
489 g_rollover_ms = 0;
490 g_last_seen_now = 0;
491 return old;
494 // static
495 TimeTicks TimeTicks::Now() {
496 return g_now_function();
499 // static
500 bool TimeTicks::IsHighResolution() {
501 if (g_now_function == &InitialNowFunction)
502 InitializeNowFunctionPointers();
503 return g_now_function == &QPCNow;
506 // static
507 TimeTicks TimeTicks::ThreadNow() {
508 NOTREACHED();
509 return TimeTicks();
512 // static
513 TimeTicks TimeTicks::NowFromSystemTraceTime() {
514 return g_system_trace_now_function();
517 // static
518 TimeTicks TimeTicks::FromQPCValue(LONGLONG qpc_value) {
519 return TimeTicks() + QPCValueToTimeDelta(qpc_value);
522 // TimeDelta ------------------------------------------------------------------
524 // static
525 TimeDelta TimeDelta::FromQPCValue(LONGLONG qpc_value) {
526 return QPCValueToTimeDelta(qpc_value);