Line data Source code
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 : //
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;
14 : //
15 :
16 : #include <sys/syscall.h>
17 : #include <time.h>
18 : #include <unistd.h>
19 : #include <string.h>
20 :
21 : #if defined(__DragonFly__) || defined(__FreeBSD__) \
22 : || defined(__NetBSD__) || defined(__OpenBSD__)
23 : #include <sys/param.h>
24 : #include <sys/sysctl.h>
25 : #endif
26 :
27 : #if defined(__DragonFly__) || defined(__FreeBSD__)
28 : #include <sys/user.h>
29 : #endif
30 :
31 : #if defined(__NetBSD__)
32 : #undef KERN_PROC
33 : #define KERN_PROC KERN_PROC2
34 : #define KINFO_PROC struct kinfo_proc2
35 : #else
36 : #define KINFO_PROC struct kinfo_proc
37 : #endif
38 :
39 : #if defined(__DragonFly__)
40 : #define KP_START_SEC kp_start.tv_sec
41 : #define KP_START_USEC kp_start.tv_usec
42 : #elif defined(__FreeBSD__)
43 : #define KP_START_SEC ki_start.tv_sec
44 : #define KP_START_USEC ki_start.tv_usec
45 : #else
46 : #define KP_START_SEC p_ustart_sec
47 : #define KP_START_USEC p_ustart_usec
48 : #endif
49 :
50 : #include "mozilla/Sprintf.h"
51 : #include "mozilla/TimeStamp.h"
52 : #include <pthread.h>
53 :
54 : // Estimate of the smallest duration of time we can measure.
55 : static uint64_t sResolution;
56 : static uint64_t sResolutionSigDigs;
57 :
58 : static const uint16_t kNsPerUs = 1000;
59 : static const uint64_t kNsPerMs = 1000000;
60 : static const uint64_t kNsPerSec = 1000000000;
61 : static const double kNsPerMsd = 1000000.0;
62 : static const double kNsPerSecd = 1000000000.0;
63 :
64 : static uint64_t
65 21453 : TimespecToNs(const struct timespec& aTs)
66 : {
67 21453 : uint64_t baseNs = uint64_t(aTs.tv_sec) * kNsPerSec;
68 21453 : return baseNs + uint64_t(aTs.tv_nsec);
69 : }
70 :
71 : static uint64_t
72 21450 : ClockTimeNs()
73 : {
74 : struct timespec ts;
75 : // this can't fail: we know &ts is valid, and TimeStamp::Startup()
76 : // checks that CLOCK_MONOTONIC is supported (and aborts if not)
77 21450 : clock_gettime(CLOCK_MONOTONIC, &ts);
78 :
79 : // tv_sec is defined to be relative to an arbitrary point in time,
80 : // but it would be madness for that point in time to be earlier than
81 : // the Epoch. So we can safely assume that even if time_t is 32
82 : // bits, tv_sec won't overflow while the browser is open. Revisit
83 : // this argument if we're still building with 32-bit time_t around
84 : // the year 2037.
85 21453 : return TimespecToNs(ts);
86 : }
87 :
88 : static uint64_t
89 3 : ClockResolutionNs()
90 : {
91 : // NB: why not rely on clock_getres()? Two reasons: (i) it might
92 : // lie, and (ii) it might return an "ideal" resolution that while
93 : // theoretically true, could never be measured in practice. Since
94 : // clock_gettime() likely involves a system call on your platform,
95 : // the "actual" timing resolution shouldn't be lower than syscall
96 : // overhead.
97 :
98 3 : uint64_t start = ClockTimeNs();
99 3 : uint64_t end = ClockTimeNs();
100 3 : uint64_t minres = (end - start);
101 :
102 : // 10 total trials is arbitrary: what we're trying to avoid by
103 : // looping is getting unlucky and being interrupted by a context
104 : // switch or signal, or being bitten by paging/cache effects
105 30 : for (int i = 0; i < 9; ++i) {
106 27 : start = ClockTimeNs();
107 27 : end = ClockTimeNs();
108 :
109 27 : uint64_t candidate = (start - end);
110 27 : if (candidate < minres) {
111 0 : minres = candidate;
112 : }
113 : }
114 :
115 3 : if (0 == minres) {
116 : // measurable resolution is either incredibly low, ~1ns, or very
117 : // high. fall back on clock_getres()
118 : struct timespec ts;
119 0 : if (0 == clock_getres(CLOCK_MONOTONIC, &ts)) {
120 0 : minres = TimespecToNs(ts);
121 : }
122 : }
123 :
124 3 : if (0 == minres) {
125 : // clock_getres probably failed. fall back on NSPR's resolution
126 : // assumption
127 0 : minres = 1 * kNsPerMs;
128 : }
129 :
130 3 : return minres;
131 : }
132 :
133 : namespace mozilla {
134 :
135 : double
136 8273 : BaseTimeDurationPlatformUtils::ToSeconds(int64_t aTicks)
137 : {
138 8273 : return double(aTicks) / kNsPerSecd;
139 : }
140 :
141 : double
142 0 : BaseTimeDurationPlatformUtils::ToSecondsSigDigits(int64_t aTicks)
143 : {
144 : // don't report a value < mResolution ...
145 0 : int64_t valueSigDigs = sResolution * (aTicks / sResolution);
146 : // and chop off insignificant digits
147 0 : valueSigDigs = sResolutionSigDigs * (valueSigDigs / sResolutionSigDigs);
148 0 : return double(valueSigDigs) / kNsPerSecd;
149 : }
150 :
151 : int64_t
152 1639 : BaseTimeDurationPlatformUtils::TicksFromMilliseconds(double aMilliseconds)
153 : {
154 1639 : double result = aMilliseconds * kNsPerMsd;
155 1639 : if (result > INT64_MAX) {
156 0 : return INT64_MAX;
157 : }
158 1639 : if (result < INT64_MIN) {
159 0 : return INT64_MIN;
160 : }
161 :
162 1639 : return result;
163 : }
164 :
165 : int64_t
166 0 : BaseTimeDurationPlatformUtils::ResolutionInTicks()
167 : {
168 0 : return static_cast<int64_t>(sResolution);
169 : }
170 :
171 : static bool gInitialized = false;
172 :
173 : void
174 3 : TimeStamp::Startup()
175 : {
176 3 : if (gInitialized) {
177 0 : return;
178 : }
179 :
180 : struct timespec dummy;
181 3 : if (clock_gettime(CLOCK_MONOTONIC, &dummy) != 0) {
182 0 : MOZ_CRASH("CLOCK_MONOTONIC is absent!");
183 : }
184 :
185 3 : sResolution = ClockResolutionNs();
186 :
187 : // find the number of significant digits in sResolution, for the
188 : // sake of ToSecondsSigDigits()
189 8 : for (sResolutionSigDigs = 1;
190 16 : !(sResolutionSigDigs == sResolution ||
191 8 : 10 * sResolutionSigDigs > sResolution);
192 5 : sResolutionSigDigs *= 10);
193 :
194 3 : gInitialized = true;
195 :
196 3 : return;
197 : }
198 :
199 : void
200 0 : TimeStamp::Shutdown()
201 : {
202 0 : }
203 :
204 : TimeStamp
205 21390 : TimeStamp::Now(bool aHighResolution)
206 : {
207 21390 : return TimeStamp(ClockTimeNs());
208 : }
209 :
210 : #if defined(XP_LINUX) || defined(ANDROID)
211 :
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.
215 :
216 : static uint64_t
217 6 : JiffiesSinceBoot(const char* aFile)
218 : {
219 : char stat[512];
220 :
221 6 : FILE* f = fopen(aFile, "r");
222 6 : if (!f) {
223 0 : return 0;
224 : }
225 :
226 6 : int n = fread(&stat, 1, sizeof(stat) - 1, f);
227 :
228 6 : fclose(f);
229 :
230 6 : if (n <= 0) {
231 0 : return 0;
232 : }
233 :
234 6 : stat[n] = 0;
235 :
236 6 : long long unsigned startTime = 0; // instead of uint64_t to keep GCC quiet
237 6 : char* s = strrchr(stat, ')');
238 :
239 6 : if (!s) {
240 0 : return 0;
241 : }
242 :
243 6 : 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 6 : &startTime);
247 :
248 6 : if (rv != 1 || !startTime) {
249 0 : return 0;
250 : }
251 :
252 6 : return startTime;
253 : }
254 :
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.
260 :
261 : static void*
262 3 : ComputeProcessUptimeThread(void* aTime)
263 : {
264 3 : uint64_t* uptime = static_cast<uint64_t*>(aTime);
265 3 : long hz = sysconf(_SC_CLK_TCK);
266 :
267 3 : *uptime = 0;
268 :
269 3 : if (!hz) {
270 0 : return nullptr;
271 : }
272 :
273 : char threadStat[40];
274 3 : SprintfLiteral(threadStat, "/proc/self/task/%d/stat", (pid_t)syscall(__NR_gettid));
275 :
276 3 : uint64_t threadJiffies = JiffiesSinceBoot(threadStat);
277 3 : uint64_t selfJiffies = JiffiesSinceBoot("/proc/self/stat");
278 :
279 3 : if (!threadJiffies || !selfJiffies) {
280 0 : return nullptr;
281 : }
282 :
283 3 : *uptime = ((threadJiffies - selfJiffies) * kNsPerSec) / hz;
284 3 : return nullptr;
285 : }
286 :
287 : // Computes and returns the process uptime in us on Linux & its derivatives.
288 : // Returns 0 if an error was encountered.
289 :
290 : uint64_t
291 3 : TimeStamp::ComputeProcessUptime()
292 : {
293 3 : uint64_t uptime = 0;
294 : pthread_t uptime_pthread;
295 :
296 3 : if (pthread_create(&uptime_pthread, nullptr, ComputeProcessUptimeThread, &uptime)) {
297 0 : MOZ_CRASH("Failed to create process uptime thread.");
298 : return 0;
299 : }
300 :
301 3 : pthread_join(uptime_pthread, NULL);
302 :
303 3 : return uptime / kNsPerUs;
304 : }
305 :
306 : #elif defined(__DragonFly__) || defined(__FreeBSD__) \
307 : || defined(__NetBSD__) || defined(__OpenBSD__)
308 :
309 : // Computes and returns the process uptime in us on various BSD flavors.
310 : // Returns 0 if an error was encountered.
311 :
312 : uint64_t
313 : TimeStamp::ComputeProcessUptime()
314 : {
315 : struct timespec ts;
316 : int rv = clock_gettime(CLOCK_REALTIME, &ts);
317 :
318 : if (rv == -1) {
319 : return 0;
320 : }
321 :
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),
329 : 1,
330 : #endif
331 : };
332 : u_int mibLen = sizeof(mib) / sizeof(mib[0]);
333 :
334 : KINFO_PROC proc;
335 : size_t bufferSize = sizeof(proc);
336 : rv = sysctl(mib, mibLen, &proc, &bufferSize, nullptr, 0);
337 :
338 : if (rv == -1) {
339 : return 0;
340 : }
341 :
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;
345 :
346 : if (startTime > now) {
347 : return 0;
348 : }
349 :
350 : return (now - startTime) / kNsPerUs;
351 : }
352 :
353 : #else
354 :
355 : uint64_t
356 : TimeStamp::ComputeProcessUptime()
357 : {
358 : return 0;
359 : }
360 :
361 : #endif
362 :
363 : } // namespace mozilla
|