Bumping manifests a=b2g-bump
[gecko.git] / xpcom / ds / TimeStamp_posix.cpp
blobe4546b349eb27d90a18758c63830fa3ec94aa08b
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim:set ts=2 sw=2 sts=2 et cindent: */
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/. */
7 //
8 // Implement TimeStamp::Now() with POSIX clocks.
9 //
10 // The "tick" unit for POSIX clocks is simply a nanosecond, as this is
11 // the smallest unit of time representable by struct timespec. That
12 // doesn't mean that a nanosecond is the resolution of TimeDurations
13 // obtained with this API; see TimeDuration::Resolution;
16 #include <sys/syscall.h>
17 #include <time.h>
18 #include <unistd.h>
20 #if defined(__DragonFly__) || defined(__FreeBSD__) \
21 || defined(__NetBSD__) || defined(__OpenBSD__)
22 #include <sys/param.h>
23 #include <sys/sysctl.h>
24 #endif
26 #if defined(__DragonFly__) || defined(__FreeBSD__)
27 #include <sys/user.h>
28 #endif
30 #if defined(__NetBSD__)
31 #undef KERN_PROC
32 #define KERN_PROC KERN_PROC2
33 #define KINFO_PROC struct kinfo_proc2
34 #else
35 #define KINFO_PROC struct kinfo_proc
36 #endif
38 #if defined(__DragonFly__)
39 #define KP_START_SEC kp_start.tv_sec
40 #define KP_START_USEC kp_start.tv_usec
41 #elif defined(__FreeBSD__)
42 #define KP_START_SEC ki_start.tv_sec
43 #define KP_START_USEC ki_start.tv_usec
44 #else
45 #define KP_START_SEC p_ustart_sec
46 #define KP_START_USEC p_ustart_usec
47 #endif
49 #include "mozilla/TimeStamp.h"
50 #include "nsCRT.h"
51 #include "prprf.h"
52 #include "prthread.h"
53 #include "nsDebug.h"
55 // Estimate of the smallest duration of time we can measure.
56 static uint64_t sResolution;
57 static uint64_t sResolutionSigDigs;
59 static const uint16_t kNsPerUs = 1000;
60 static const uint64_t kNsPerMs = 1000000;
61 static const uint64_t kNsPerSec = 1000000000;
62 static const double kNsPerMsd = 1000000.0;
63 static const double kNsPerSecd = 1000000000.0;
65 static uint64_t
66 TimespecToNs(const struct timespec& aTs)
68 uint64_t baseNs = uint64_t(aTs.tv_sec) * kNsPerSec;
69 return baseNs + uint64_t(aTs.tv_nsec);
72 static uint64_t
73 ClockTimeNs()
75 struct timespec ts;
76 // this can't fail: we know &ts is valid, and TimeStamp::Startup()
77 // checks that CLOCK_MONOTONIC is supported (and aborts if not)
78 clock_gettime(CLOCK_MONOTONIC, &ts);
80 // tv_sec is defined to be relative to an arbitrary point in time,
81 // but it would be madness for that point in time to be earlier than
82 // the Epoch. So we can safely assume that even if time_t is 32
83 // bits, tv_sec won't overflow while the browser is open. Revisit
84 // this argument if we're still building with 32-bit time_t around
85 // the year 2037.
86 return TimespecToNs(ts);
89 static uint64_t
90 ClockResolutionNs()
92 // NB: why not rely on clock_getres()? Two reasons: (i) it might
93 // lie, and (ii) it might return an "ideal" resolution that while
94 // theoretically true, could never be measured in practice. Since
95 // clock_gettime() likely involves a system call on your platform,
96 // the "actual" timing resolution shouldn't be lower than syscall
97 // overhead.
99 uint64_t start = ClockTimeNs();
100 uint64_t end = ClockTimeNs();
101 uint64_t minres = (end - start);
103 // 10 total trials is arbitrary: what we're trying to avoid by
104 // looping is getting unlucky and being interrupted by a context
105 // switch or signal, or being bitten by paging/cache effects
106 for (int i = 0; i < 9; ++i) {
107 start = ClockTimeNs();
108 end = ClockTimeNs();
110 uint64_t candidate = (start - end);
111 if (candidate < minres) {
112 minres = candidate;
116 if (0 == minres) {
117 // measurable resolution is either incredibly low, ~1ns, or very
118 // high. fall back on clock_getres()
119 struct timespec ts;
120 if (0 == clock_getres(CLOCK_MONOTONIC, &ts)) {
121 minres = TimespecToNs(ts);
125 if (0 == minres) {
126 // clock_getres probably failed. fall back on NSPR's resolution
127 // assumption
128 minres = 1 * kNsPerMs;
131 return minres;
134 namespace mozilla {
136 double
137 BaseTimeDurationPlatformUtils::ToSeconds(int64_t aTicks)
139 return double(aTicks) / kNsPerSecd;
142 double
143 BaseTimeDurationPlatformUtils::ToSecondsSigDigits(int64_t aTicks)
145 // don't report a value < mResolution ...
146 int64_t valueSigDigs = sResolution * (aTicks / sResolution);
147 // and chop off insignificant digits
148 valueSigDigs = sResolutionSigDigs * (valueSigDigs / sResolutionSigDigs);
149 return double(valueSigDigs) / kNsPerSecd;
152 int64_t
153 BaseTimeDurationPlatformUtils::TicksFromMilliseconds(double aMilliseconds)
155 double result = aMilliseconds * kNsPerMsd;
156 if (result > INT64_MAX) {
157 return INT64_MAX;
158 } else if (result < INT64_MIN) {
159 return INT64_MIN;
162 return result;
165 int64_t
166 BaseTimeDurationPlatformUtils::ResolutionInTicks()
168 return static_cast<int64_t>(sResolution);
171 static bool gInitialized = false;
173 nsresult
174 TimeStamp::Startup()
176 if (gInitialized) {
177 return NS_OK;
180 struct timespec dummy;
181 if (clock_gettime(CLOCK_MONOTONIC, &dummy) != 0) {
182 NS_RUNTIMEABORT("CLOCK_MONOTONIC is absent!");
185 sResolution = ClockResolutionNs();
187 // find the number of significant digits in sResolution, for the
188 // sake of ToSecondsSigDigits()
189 for (sResolutionSigDigs = 1;
190 !(sResolutionSigDigs == sResolution ||
191 10 * sResolutionSigDigs > sResolution);
192 sResolutionSigDigs *= 10);
194 gInitialized = true;
196 return NS_OK;
199 void
200 TimeStamp::Shutdown()
204 TimeStamp
205 TimeStamp::Now(bool aHighResolution)
207 return TimeStamp(ClockTimeNs());
210 #if defined(LINUX) || defined(ANDROID)
212 // Calculates the amount of jiffies that have elapsed since boot and up to the
213 // starttime value of a specific process as found in its /proc/*/stat file.
214 // Returns 0 if an error occurred.
216 static uint64_t
217 JiffiesSinceBoot(const char* aFile)
219 char stat[512];
221 FILE* f = fopen(aFile, "r");
222 if (!f) {
223 return 0;
226 int n = fread(&stat, 1, sizeof(stat) - 1, f);
228 fclose(f);
230 if (n <= 0) {
231 return 0;
234 stat[n] = 0;
236 long long unsigned startTime = 0; // instead of uint64_t to keep GCC quiet
237 char* s = strrchr(stat, ')');
239 if (!s) {
240 return 0;
243 int rv = sscanf(s + 2,
244 "%*c %*d %*d %*d %*d %*d %*u %*u %*u %*u "
245 "%*u %*u %*u %*d %*d %*d %*d %*d %*d %llu",
246 &startTime);
248 if (rv != 1 || !startTime) {
249 return 0;
252 return startTime;
255 // Computes the interval that has elapsed between the thread creation and the
256 // process creation by comparing the starttime fields in the respective
257 // /proc/*/stat files. The resulting value will be a good approximation of the
258 // process uptime. This value will be stored at the address pointed by aTime;
259 // if an error occurred 0 will be stored instead.
261 static void
262 ComputeProcessUptimeThread(void* aTime)
264 uint64_t* uptime = static_cast<uint64_t*>(aTime);
265 long hz = sysconf(_SC_CLK_TCK);
267 *uptime = 0;
269 if (!hz) {
270 return;
273 char threadStat[40];
274 sprintf(threadStat, "/proc/self/task/%d/stat", (pid_t)syscall(__NR_gettid));
276 uint64_t threadJiffies = JiffiesSinceBoot(threadStat);
277 uint64_t selfJiffies = JiffiesSinceBoot("/proc/self/stat");
279 if (!threadJiffies || !selfJiffies) {
280 return;
283 *uptime = ((threadJiffies - selfJiffies) * kNsPerSec) / hz;
286 // Computes and returns the process uptime in us on Linux & its derivatives.
287 // Returns 0 if an error was encountered.
289 uint64_t
290 TimeStamp::ComputeProcessUptime()
292 uint64_t uptime = 0;
293 PRThread* thread = PR_CreateThread(PR_USER_THREAD,
294 ComputeProcessUptimeThread,
295 &uptime,
296 PR_PRIORITY_NORMAL,
297 PR_GLOBAL_THREAD,
298 PR_JOINABLE_THREAD,
301 PR_JoinThread(thread);
303 return uptime / kNsPerUs;
306 #elif defined(__DragonFly__) || defined(__FreeBSD__) \
307 || defined(__NetBSD__) || defined(__OpenBSD__)
309 // Computes and returns the process uptime in us on various BSD flavors.
310 // Returns 0 if an error was encountered.
312 uint64_t
313 TimeStamp::ComputeProcessUptime()
315 struct timespec ts;
316 int rv = clock_gettime(CLOCK_REALTIME, &ts);
318 if (rv == -1) {
319 return 0;
322 int mib[] = {
323 CTL_KERN,
324 KERN_PROC,
325 KERN_PROC_PID,
326 getpid(),
327 #if defined(__NetBSD__) || defined(__OpenBSD__)
328 sizeof(KINFO_PROC),
330 #endif
332 u_int mibLen = sizeof(mib) / sizeof(mib[0]);
334 KINFO_PROC proc;
335 size_t bufferSize = sizeof(proc);
336 rv = sysctl(mib, mibLen, &proc, &bufferSize, nullptr, 0);
338 if (rv == -1) {
339 return 0;
342 uint64_t startTime = ((uint64_t)proc.KP_START_SEC * kNsPerSec) +
343 (proc.KP_START_USEC * kNsPerUs);
344 uint64_t now = ((uint64_t)ts.tv_sec * kNsPerSec) + ts.tv_nsec;
346 if (startTime > now) {
347 return 0;
350 return (now - startTime) / kNsPerUs;
353 #else
355 uint64_t
356 TimeStamp::ComputeProcessUptime()
358 return 0;
361 #endif
363 } // namespace mozilla