Wed, 31 Dec 2014 06:09:35 +0100
Cloned upstream origin tor-browser at tor-browser-31.3.0esr-4.5-1-build1
revision ID fc1c9ff7c1b2defdbc039f12214767608f46423f for hacking purpose.
michael@0 | 1 | // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. |
michael@0 | 2 | // Use of this source code is governed by a BSD-style license that can be |
michael@0 | 3 | // found in the LICENSE file. |
michael@0 | 4 | |
michael@0 | 5 | |
michael@0 | 6 | // Windows Timer Primer |
michael@0 | 7 | // |
michael@0 | 8 | // A good article: http://www.ddj.com/windows/184416651 |
michael@0 | 9 | // A good mozilla bug: http://bugzilla.mozilla.org/show_bug.cgi?id=363258 |
michael@0 | 10 | // |
michael@0 | 11 | // The default windows timer, GetSystemTimeAsFileTime is not very precise. |
michael@0 | 12 | // It is only good to ~15.5ms. |
michael@0 | 13 | // |
michael@0 | 14 | // QueryPerformanceCounter is the logical choice for a high-precision timer. |
michael@0 | 15 | // However, it is known to be buggy on some hardware. Specifically, it can |
michael@0 | 16 | // sometimes "jump". On laptops, QPC can also be very expensive to call. |
michael@0 | 17 | // It's 3-4x slower than timeGetTime() on desktops, but can be 10x slower |
michael@0 | 18 | // on laptops. A unittest exists which will show the relative cost of various |
michael@0 | 19 | // timers on any system. |
michael@0 | 20 | // |
michael@0 | 21 | // The next logical choice is timeGetTime(). timeGetTime has a precision of |
michael@0 | 22 | // 1ms, but only if you call APIs (timeBeginPeriod()) which affect all other |
michael@0 | 23 | // applications on the system. By default, precision is only 15.5ms. |
michael@0 | 24 | // Unfortunately, we don't want to call timeBeginPeriod because we don't |
michael@0 | 25 | // want to affect other applications. Further, on mobile platforms, use of |
michael@0 | 26 | // faster multimedia timers can hurt battery life. See the intel |
michael@0 | 27 | // article about this here: |
michael@0 | 28 | // http://softwarecommunity.intel.com/articles/eng/1086.htm |
michael@0 | 29 | // |
michael@0 | 30 | // To work around all this, we're going to generally use timeGetTime(). We |
michael@0 | 31 | // will only increase the system-wide timer if we're not running on battery |
michael@0 | 32 | // power. Using timeBeginPeriod(1) is a requirement in order to make our |
michael@0 | 33 | // message loop waits have the same resolution that our time measurements |
michael@0 | 34 | // do. Otherwise, WaitForSingleObject(..., 1) will no less than 15ms when |
michael@0 | 35 | // there is nothing else to waken the Wait. |
michael@0 | 36 | |
michael@0 | 37 | #include "base/time.h" |
michael@0 | 38 | |
michael@0 | 39 | #pragma comment(lib, "winmm.lib") |
michael@0 | 40 | #include <windows.h> |
michael@0 | 41 | #include <mmsystem.h> |
michael@0 | 42 | |
michael@0 | 43 | #include "base/basictypes.h" |
michael@0 | 44 | #include "base/lock.h" |
michael@0 | 45 | #include "base/logging.h" |
michael@0 | 46 | #include "base/cpu.h" |
michael@0 | 47 | #include "base/singleton.h" |
michael@0 | 48 | #include "base/system_monitor.h" |
michael@0 | 49 | #include "mozilla/Casting.h" |
michael@0 | 50 | |
michael@0 | 51 | using base::Time; |
michael@0 | 52 | using base::TimeDelta; |
michael@0 | 53 | using base::TimeTicks; |
michael@0 | 54 | using mozilla::BitwiseCast; |
michael@0 | 55 | |
michael@0 | 56 | namespace { |
michael@0 | 57 | |
michael@0 | 58 | // From MSDN, FILETIME "Contains a 64-bit value representing the number of |
michael@0 | 59 | // 100-nanosecond intervals since January 1, 1601 (UTC)." |
michael@0 | 60 | int64_t FileTimeToMicroseconds(const FILETIME& ft) { |
michael@0 | 61 | // Need to BitwiseCast to fix alignment, then divide by 10 to convert |
michael@0 | 62 | // 100-nanoseconds to milliseconds. This only works on little-endian |
michael@0 | 63 | // machines. |
michael@0 | 64 | return BitwiseCast<int64_t>(ft) / 10; |
michael@0 | 65 | } |
michael@0 | 66 | |
michael@0 | 67 | void MicrosecondsToFileTime(int64_t us, FILETIME* ft) { |
michael@0 | 68 | DCHECK(us >= 0) << "Time is less than 0, negative values are not " |
michael@0 | 69 | "representable in FILETIME"; |
michael@0 | 70 | |
michael@0 | 71 | // Multiply by 10 to convert milliseconds to 100-nanoseconds. BitwiseCast will |
michael@0 | 72 | // handle alignment problems. This only works on little-endian machines. |
michael@0 | 73 | *ft = BitwiseCast<FILETIME>(us * 10); |
michael@0 | 74 | } |
michael@0 | 75 | |
michael@0 | 76 | int64_t CurrentWallclockMicroseconds() { |
michael@0 | 77 | FILETIME ft; |
michael@0 | 78 | ::GetSystemTimeAsFileTime(&ft); |
michael@0 | 79 | return FileTimeToMicroseconds(ft); |
michael@0 | 80 | } |
michael@0 | 81 | |
michael@0 | 82 | // Time between resampling the un-granular clock for this API. 60 seconds. |
michael@0 | 83 | const int kMaxMillisecondsToAvoidDrift = 60 * Time::kMillisecondsPerSecond; |
michael@0 | 84 | |
michael@0 | 85 | int64_t initial_time = 0; |
michael@0 | 86 | TimeTicks initial_ticks; |
michael@0 | 87 | |
michael@0 | 88 | void InitializeClock() { |
michael@0 | 89 | initial_ticks = TimeTicks::Now(); |
michael@0 | 90 | initial_time = CurrentWallclockMicroseconds(); |
michael@0 | 91 | } |
michael@0 | 92 | |
michael@0 | 93 | } // namespace |
michael@0 | 94 | |
michael@0 | 95 | // Time ----------------------------------------------------------------------- |
michael@0 | 96 | |
michael@0 | 97 | // The internal representation of Time uses FILETIME, whose epoch is 1601-01-01 |
michael@0 | 98 | // 00:00:00 UTC. ((1970-1601)*365+89)*24*60*60*1000*1000, where 89 is the |
michael@0 | 99 | // number of leap year days between 1601 and 1970: (1970-1601)/4 excluding |
michael@0 | 100 | // 1700, 1800, and 1900. |
michael@0 | 101 | // static |
michael@0 | 102 | const int64_t Time::kTimeTToMicrosecondsOffset = GG_INT64_C(11644473600000000); |
michael@0 | 103 | |
michael@0 | 104 | // static |
michael@0 | 105 | Time Time::Now() { |
michael@0 | 106 | if (initial_time == 0) |
michael@0 | 107 | InitializeClock(); |
michael@0 | 108 | |
michael@0 | 109 | // We implement time using the high-resolution timers so that we can get |
michael@0 | 110 | // timeouts which are smaller than 10-15ms. If we just used |
michael@0 | 111 | // CurrentWallclockMicroseconds(), we'd have the less-granular timer. |
michael@0 | 112 | // |
michael@0 | 113 | // To make this work, we initialize the clock (initial_time) and the |
michael@0 | 114 | // counter (initial_ctr). To compute the initial time, we can check |
michael@0 | 115 | // the number of ticks that have elapsed, and compute the delta. |
michael@0 | 116 | // |
michael@0 | 117 | // To avoid any drift, we periodically resync the counters to the system |
michael@0 | 118 | // clock. |
michael@0 | 119 | while(true) { |
michael@0 | 120 | TimeTicks ticks = TimeTicks::Now(); |
michael@0 | 121 | |
michael@0 | 122 | // Calculate the time elapsed since we started our timer |
michael@0 | 123 | TimeDelta elapsed = ticks - initial_ticks; |
michael@0 | 124 | |
michael@0 | 125 | // Check if enough time has elapsed that we need to resync the clock. |
michael@0 | 126 | if (elapsed.InMilliseconds() > kMaxMillisecondsToAvoidDrift) { |
michael@0 | 127 | InitializeClock(); |
michael@0 | 128 | continue; |
michael@0 | 129 | } |
michael@0 | 130 | |
michael@0 | 131 | return Time(elapsed + initial_time); |
michael@0 | 132 | } |
michael@0 | 133 | } |
michael@0 | 134 | |
michael@0 | 135 | // static |
michael@0 | 136 | Time Time::NowFromSystemTime() { |
michael@0 | 137 | // Force resync. |
michael@0 | 138 | InitializeClock(); |
michael@0 | 139 | return Time(initial_time); |
michael@0 | 140 | } |
michael@0 | 141 | |
michael@0 | 142 | // static |
michael@0 | 143 | Time Time::FromFileTime(FILETIME ft) { |
michael@0 | 144 | return Time(FileTimeToMicroseconds(ft)); |
michael@0 | 145 | } |
michael@0 | 146 | |
michael@0 | 147 | FILETIME Time::ToFileTime() const { |
michael@0 | 148 | FILETIME utc_ft; |
michael@0 | 149 | MicrosecondsToFileTime(us_, &utc_ft); |
michael@0 | 150 | return utc_ft; |
michael@0 | 151 | } |
michael@0 | 152 | |
michael@0 | 153 | // static |
michael@0 | 154 | Time Time::FromExploded(bool is_local, const Exploded& exploded) { |
michael@0 | 155 | // Create the system struct representing our exploded time. It will either be |
michael@0 | 156 | // in local time or UTC. |
michael@0 | 157 | SYSTEMTIME st; |
michael@0 | 158 | st.wYear = exploded.year; |
michael@0 | 159 | st.wMonth = exploded.month; |
michael@0 | 160 | st.wDayOfWeek = exploded.day_of_week; |
michael@0 | 161 | st.wDay = exploded.day_of_month; |
michael@0 | 162 | st.wHour = exploded.hour; |
michael@0 | 163 | st.wMinute = exploded.minute; |
michael@0 | 164 | st.wSecond = exploded.second; |
michael@0 | 165 | st.wMilliseconds = exploded.millisecond; |
michael@0 | 166 | |
michael@0 | 167 | // Convert to FILETIME. |
michael@0 | 168 | FILETIME ft; |
michael@0 | 169 | if (!SystemTimeToFileTime(&st, &ft)) { |
michael@0 | 170 | NOTREACHED() << "Unable to convert time"; |
michael@0 | 171 | return Time(0); |
michael@0 | 172 | } |
michael@0 | 173 | |
michael@0 | 174 | // Ensure that it's in UTC. |
michael@0 | 175 | if (is_local) { |
michael@0 | 176 | FILETIME utc_ft; |
michael@0 | 177 | LocalFileTimeToFileTime(&ft, &utc_ft); |
michael@0 | 178 | return Time(FileTimeToMicroseconds(utc_ft)); |
michael@0 | 179 | } |
michael@0 | 180 | return Time(FileTimeToMicroseconds(ft)); |
michael@0 | 181 | } |
michael@0 | 182 | |
michael@0 | 183 | void Time::Explode(bool is_local, Exploded* exploded) const { |
michael@0 | 184 | // FILETIME in UTC. |
michael@0 | 185 | FILETIME utc_ft; |
michael@0 | 186 | MicrosecondsToFileTime(us_, &utc_ft); |
michael@0 | 187 | |
michael@0 | 188 | // FILETIME in local time if necessary. |
michael@0 | 189 | BOOL success = TRUE; |
michael@0 | 190 | FILETIME ft; |
michael@0 | 191 | if (is_local) |
michael@0 | 192 | success = FileTimeToLocalFileTime(&utc_ft, &ft); |
michael@0 | 193 | else |
michael@0 | 194 | ft = utc_ft; |
michael@0 | 195 | |
michael@0 | 196 | // FILETIME in SYSTEMTIME (exploded). |
michael@0 | 197 | SYSTEMTIME st; |
michael@0 | 198 | if (!success || !FileTimeToSystemTime(&ft, &st)) { |
michael@0 | 199 | NOTREACHED() << "Unable to convert time, don't know why"; |
michael@0 | 200 | ZeroMemory(exploded, sizeof(*exploded)); |
michael@0 | 201 | return; |
michael@0 | 202 | } |
michael@0 | 203 | |
michael@0 | 204 | exploded->year = st.wYear; |
michael@0 | 205 | exploded->month = st.wMonth; |
michael@0 | 206 | exploded->day_of_week = st.wDayOfWeek; |
michael@0 | 207 | exploded->day_of_month = st.wDay; |
michael@0 | 208 | exploded->hour = st.wHour; |
michael@0 | 209 | exploded->minute = st.wMinute; |
michael@0 | 210 | exploded->second = st.wSecond; |
michael@0 | 211 | exploded->millisecond = st.wMilliseconds; |
michael@0 | 212 | } |
michael@0 | 213 | |
michael@0 | 214 | // TimeTicks ------------------------------------------------------------------ |
michael@0 | 215 | namespace { |
michael@0 | 216 | |
michael@0 | 217 | // We define a wrapper to adapt between the __stdcall and __cdecl call of the |
michael@0 | 218 | // mock function, and to avoid a static constructor. Assigning an import to a |
michael@0 | 219 | // function pointer directly would require setup code to fetch from the IAT. |
michael@0 | 220 | DWORD timeGetTimeWrapper() { |
michael@0 | 221 | return timeGetTime(); |
michael@0 | 222 | } |
michael@0 | 223 | |
michael@0 | 224 | |
michael@0 | 225 | DWORD (*tick_function)(void) = &timeGetTimeWrapper; |
michael@0 | 226 | |
michael@0 | 227 | // We use timeGetTime() to implement TimeTicks::Now(). This can be problematic |
michael@0 | 228 | // because it returns the number of milliseconds since Windows has started, |
michael@0 | 229 | // which will roll over the 32-bit value every ~49 days. We try to track |
michael@0 | 230 | // rollover ourselves, which works if TimeTicks::Now() is called at least every |
michael@0 | 231 | // 49 days. |
michael@0 | 232 | class NowSingleton { |
michael@0 | 233 | public: |
michael@0 | 234 | NowSingleton() |
michael@0 | 235 | : rollover_(TimeDelta::FromMilliseconds(0)), |
michael@0 | 236 | last_seen_(0) { |
michael@0 | 237 | } |
michael@0 | 238 | |
michael@0 | 239 | TimeDelta Now() { |
michael@0 | 240 | AutoLock locked(lock_); |
michael@0 | 241 | // We should hold the lock while calling tick_function to make sure that |
michael@0 | 242 | // we keep our last_seen_ stay correctly in sync. |
michael@0 | 243 | DWORD now = tick_function(); |
michael@0 | 244 | if (now < last_seen_) |
michael@0 | 245 | rollover_ += TimeDelta::FromMilliseconds(GG_LONGLONG(0x100000000)); // ~49.7 days. |
michael@0 | 246 | last_seen_ = now; |
michael@0 | 247 | return TimeDelta::FromMilliseconds(now) + rollover_; |
michael@0 | 248 | } |
michael@0 | 249 | |
michael@0 | 250 | private: |
michael@0 | 251 | Lock lock_; // To protected last_seen_ and rollover_. |
michael@0 | 252 | TimeDelta rollover_; // Accumulation of time lost due to rollover. |
michael@0 | 253 | DWORD last_seen_; // The last timeGetTime value we saw, to detect rollover. |
michael@0 | 254 | |
michael@0 | 255 | DISALLOW_COPY_AND_ASSIGN(NowSingleton); |
michael@0 | 256 | }; |
michael@0 | 257 | |
michael@0 | 258 | // Overview of time counters: |
michael@0 | 259 | // (1) CPU cycle counter. (Retrieved via RDTSC) |
michael@0 | 260 | // The CPU counter provides the highest resolution time stamp and is the least |
michael@0 | 261 | // expensive to retrieve. However, the CPU counter is unreliable and should not |
michael@0 | 262 | // be used in production. Its biggest issue is that it is per processor and it |
michael@0 | 263 | // is not synchronized between processors. Also, on some computers, the counters |
michael@0 | 264 | // will change frequency due to thermal and power changes, and stop in some |
michael@0 | 265 | // states. |
michael@0 | 266 | // |
michael@0 | 267 | // (2) QueryPerformanceCounter (QPC). The QPC counter provides a high- |
michael@0 | 268 | // resolution (100 nanoseconds) time stamp but is comparatively more expensive |
michael@0 | 269 | // to retrieve. What QueryPerformanceCounter actually does is up to the HAL. |
michael@0 | 270 | // (with some help from ACPI). |
michael@0 | 271 | // According to http://blogs.msdn.com/oldnewthing/archive/2005/09/02/459952.aspx |
michael@0 | 272 | // in the worst case, it gets the counter from the rollover interrupt on the |
michael@0 | 273 | // programmable interrupt timer. In best cases, the HAL may conclude that the |
michael@0 | 274 | // RDTSC counter runs at a constant frequency, then it uses that instead. On |
michael@0 | 275 | // multiprocessor machines, it will try to verify the values returned from |
michael@0 | 276 | // RDTSC on each processor are consistent with each other, and apply a handful |
michael@0 | 277 | // of workarounds for known buggy hardware. In other words, QPC is supposed to |
michael@0 | 278 | // give consistent result on a multiprocessor computer, but it is unreliable in |
michael@0 | 279 | // reality due to bugs in BIOS or HAL on some, especially old computers. |
michael@0 | 280 | // With recent updates on HAL and newer BIOS, QPC is getting more reliable but |
michael@0 | 281 | // it should be used with caution. |
michael@0 | 282 | // |
michael@0 | 283 | // (3) System time. The system time provides a low-resolution (typically 10ms |
michael@0 | 284 | // to 55 milliseconds) time stamp but is comparatively less expensive to |
michael@0 | 285 | // retrieve and more reliable. |
michael@0 | 286 | class HighResNowSingleton { |
michael@0 | 287 | public: |
michael@0 | 288 | HighResNowSingleton() |
michael@0 | 289 | : ticks_per_microsecond_(0.0), |
michael@0 | 290 | skew_(0) { |
michael@0 | 291 | InitializeClock(); |
michael@0 | 292 | |
michael@0 | 293 | // On Athlon X2 CPUs (e.g. model 15) QueryPerformanceCounter is |
michael@0 | 294 | // unreliable. Fallback to low-res clock. |
michael@0 | 295 | base::CPU cpu; |
michael@0 | 296 | if (cpu.vendor_name() == "AuthenticAMD" && cpu.family() == 15) |
michael@0 | 297 | DisableHighResClock(); |
michael@0 | 298 | } |
michael@0 | 299 | |
michael@0 | 300 | bool IsUsingHighResClock() { |
michael@0 | 301 | return ticks_per_microsecond_ != 0.0; |
michael@0 | 302 | } |
michael@0 | 303 | |
michael@0 | 304 | void DisableHighResClock() { |
michael@0 | 305 | ticks_per_microsecond_ = 0.0; |
michael@0 | 306 | } |
michael@0 | 307 | |
michael@0 | 308 | TimeDelta Now() { |
michael@0 | 309 | // Our maximum tolerance for QPC drifting. |
michael@0 | 310 | const int kMaxTimeDrift = 50 * Time::kMicrosecondsPerMillisecond; |
michael@0 | 311 | |
michael@0 | 312 | if (IsUsingHighResClock()) { |
michael@0 | 313 | int64_t now = UnreliableNow(); |
michael@0 | 314 | |
michael@0 | 315 | // Verify that QPC does not seem to drift. |
michael@0 | 316 | DCHECK(now - ReliableNow() - skew_ < kMaxTimeDrift); |
michael@0 | 317 | |
michael@0 | 318 | return TimeDelta::FromMicroseconds(now); |
michael@0 | 319 | } |
michael@0 | 320 | |
michael@0 | 321 | // Just fallback to the slower clock. |
michael@0 | 322 | return Singleton<NowSingleton>::get()->Now(); |
michael@0 | 323 | } |
michael@0 | 324 | |
michael@0 | 325 | private: |
michael@0 | 326 | // Synchronize the QPC clock with GetSystemTimeAsFileTime. |
michael@0 | 327 | void InitializeClock() { |
michael@0 | 328 | LARGE_INTEGER ticks_per_sec = {0}; |
michael@0 | 329 | if (!QueryPerformanceFrequency(&ticks_per_sec)) |
michael@0 | 330 | return; // Broken, we don't guarantee this function works. |
michael@0 | 331 | ticks_per_microsecond_ = static_cast<float>(ticks_per_sec.QuadPart) / |
michael@0 | 332 | static_cast<float>(Time::kMicrosecondsPerSecond); |
michael@0 | 333 | |
michael@0 | 334 | skew_ = UnreliableNow() - ReliableNow(); |
michael@0 | 335 | } |
michael@0 | 336 | |
michael@0 | 337 | // Get the number of microseconds since boot in a reliable fashion |
michael@0 | 338 | int64_t UnreliableNow() { |
michael@0 | 339 | LARGE_INTEGER now; |
michael@0 | 340 | QueryPerformanceCounter(&now); |
michael@0 | 341 | return static_cast<int64_t>(now.QuadPart / ticks_per_microsecond_); |
michael@0 | 342 | } |
michael@0 | 343 | |
michael@0 | 344 | // Get the number of microseconds since boot in a reliable fashion |
michael@0 | 345 | int64_t ReliableNow() { |
michael@0 | 346 | return Singleton<NowSingleton>::get()->Now().InMicroseconds(); |
michael@0 | 347 | } |
michael@0 | 348 | |
michael@0 | 349 | // Cached clock frequency -> microseconds. This assumes that the clock |
michael@0 | 350 | // frequency is faster than one microsecond (which is 1MHz, should be OK). |
michael@0 | 351 | float ticks_per_microsecond_; // 0 indicates QPF failed and we're broken. |
michael@0 | 352 | int64_t skew_; // Skew between lo-res and hi-res clocks (for debugging). |
michael@0 | 353 | |
michael@0 | 354 | DISALLOW_COPY_AND_ASSIGN(HighResNowSingleton); |
michael@0 | 355 | }; |
michael@0 | 356 | |
michael@0 | 357 | } // namespace |
michael@0 | 358 | |
michael@0 | 359 | // static |
michael@0 | 360 | TimeTicks::TickFunctionType TimeTicks::SetMockTickFunction( |
michael@0 | 361 | TickFunctionType ticker) { |
michael@0 | 362 | TickFunctionType old = tick_function; |
michael@0 | 363 | tick_function = ticker; |
michael@0 | 364 | return old; |
michael@0 | 365 | } |
michael@0 | 366 | |
michael@0 | 367 | // static |
michael@0 | 368 | TimeTicks TimeTicks::Now() { |
michael@0 | 369 | return TimeTicks() + Singleton<NowSingleton>::get()->Now(); |
michael@0 | 370 | } |
michael@0 | 371 | |
michael@0 | 372 | // static |
michael@0 | 373 | TimeTicks TimeTicks::HighResNow() { |
michael@0 | 374 | return TimeTicks() + Singleton<HighResNowSingleton>::get()->Now(); |
michael@0 | 375 | } |