1 /*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #ifndef INCLUDE_PERFETTO_BASE_TIME_H_
18 #define INCLUDE_PERFETTO_BASE_TIME_H_
19
20 #include <stdint.h>
21 #include <time.h>
22
23 #include <chrono>
24 #include <optional>
25 #include <string>
26
27 #include "perfetto/base/build_config.h"
28 #include "perfetto/base/logging.h"
29
30 #if PERFETTO_BUILDFLAG(PERFETTO_OS_APPLE)
31 #include <mach/mach_init.h>
32 #include <mach/mach_port.h>
33 #include <mach/mach_time.h>
34 #include <mach/thread_act.h>
35 #endif
36
37 #if PERFETTO_BUILDFLAG(PERFETTO_OS_WASM)
38 #include <emscripten/emscripten.h>
39 #endif
40
41 #if PERFETTO_BUILDFLAG(PERFETTO_ARCH_CPU_X86_64)
42 #if PERFETTO_BUILDFLAG(PERFETTO_COMPILER_MSVC)
43 #include <intrin.h>
44 #endif
45 #endif
46
47 namespace perfetto {
48 namespace base {
49
50 using TimeSeconds = std::chrono::seconds;
51 using TimeMillis = std::chrono::milliseconds;
52 using TimeNanos = std::chrono::nanoseconds;
53
FromPosixTimespec(const struct timespec & ts)54 inline TimeNanos FromPosixTimespec(const struct timespec& ts) {
55 return TimeNanos(ts.tv_sec * 1000000000LL + ts.tv_nsec);
56 }
57
58 void SleepMicroseconds(unsigned interval_us);
59 void InitializeTime();
60
61 #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
62
63 TimeNanos GetWallTimeNs();
64 TimeNanos GetThreadCPUTimeNs();
GetWallTimeRawNs()65 inline TimeNanos GetWallTimeRawNs() {
66 return GetWallTimeNs();
67 }
68
69 // TODO: Clock that counts time during suspend is not implemented on Windows.
GetBootTimeNs()70 inline TimeNanos GetBootTimeNs() {
71 return GetWallTimeNs();
72 }
73
74 #elif PERFETTO_BUILDFLAG(PERFETTO_OS_APPLE)
75
GetWallTimeNs()76 inline TimeNanos GetWallTimeNs() {
77 auto init_timebase_info = []() -> mach_timebase_info_data_t {
78 mach_timebase_info_data_t timebase_info;
79 mach_timebase_info(&timebase_info);
80 return timebase_info;
81 };
82
83 static mach_timebase_info_data_t timebase_info = init_timebase_info();
84 uint64_t mach_time = mach_absolute_time();
85
86 // Take the fast path when the conversion is 1:1. The result will for sure fit
87 // into an int_64 because we're going from nanoseconds to microseconds.
88 if (timebase_info.numer == timebase_info.denom) {
89 return TimeNanos(mach_time);
90 }
91
92 // Nanoseconds is mach_time * timebase.numer // timebase.denom. Divide first
93 // to reduce the chance of overflow. Also stash the remainder right now,
94 // a likely byproduct of the division.
95 uint64_t nanoseconds = mach_time / timebase_info.denom;
96 const uint64_t mach_time_remainder = mach_time % timebase_info.denom;
97
98 // Now multiply, keeping an eye out for overflow.
99 PERFETTO_CHECK(!__builtin_umulll_overflow(nanoseconds, timebase_info.numer,
100 &nanoseconds));
101
102 // By dividing first we lose precision. Regain it by adding back the
103 // nanoseconds from the remainder, with an eye out for overflow.
104 uint64_t least_significant_nanoseconds =
105 (mach_time_remainder * timebase_info.numer) / timebase_info.denom;
106 PERFETTO_CHECK(!__builtin_uaddll_overflow(
107 nanoseconds, least_significant_nanoseconds, &nanoseconds));
108
109 return TimeNanos(nanoseconds);
110 }
111
GetWallTimeRawNs()112 inline TimeNanos GetWallTimeRawNs() {
113 return GetWallTimeNs();
114 }
115
116 // TODO: Clock that counts time during suspend is not implemented on Mac.
GetBootTimeNs()117 inline TimeNanos GetBootTimeNs() {
118 return GetWallTimeNs();
119 }
120
121 // Before MacOS 10.12 clock_gettime() was not implemented.
122 #if __MAC_OS_X_VERSION_MIN_REQUIRED < 101200
GetThreadCPUTimeNs()123 inline TimeNanos GetThreadCPUTimeNs() {
124 mach_port_t this_thread = mach_thread_self();
125 mach_msg_type_number_t count = THREAD_BASIC_INFO_COUNT;
126 thread_basic_info_data_t info{};
127 kern_return_t kr =
128 thread_info(this_thread, THREAD_BASIC_INFO,
129 reinterpret_cast<thread_info_t>(&info), &count);
130 mach_port_deallocate(mach_task_self(), this_thread);
131
132 if (kr != KERN_SUCCESS) {
133 PERFETTO_DFATAL("Failed to get CPU time.");
134 return TimeNanos(0);
135 }
136 return TimeNanos(info.user_time.seconds * 1000000000LL +
137 info.user_time.microseconds * 1000LL +
138 info.system_time.seconds * 1000000000LL +
139 info.system_time.microseconds * 1000LL);
140 }
141 #else
GetThreadCPUTimeNs()142 inline TimeNanos GetThreadCPUTimeNs() {
143 struct timespec ts = {};
144 PERFETTO_CHECK(clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts) == 0);
145 return FromPosixTimespec(ts);
146 }
147 #endif
148
149 #elif PERFETTO_BUILDFLAG(PERFETTO_OS_WASM)
150
GetWallTimeNs()151 inline TimeNanos GetWallTimeNs() {
152 return TimeNanos(static_cast<uint64_t>(emscripten_get_now()) * 1000000);
153 }
154
GetWallTimeRawNs()155 inline TimeNanos GetWallTimeRawNs() {
156 return GetWallTimeNs();
157 }
158
GetThreadCPUTimeNs()159 inline TimeNanos GetThreadCPUTimeNs() {
160 return TimeNanos(0);
161 }
162
163 // TODO: Clock that counts time during suspend is not implemented on WASM.
GetBootTimeNs()164 inline TimeNanos GetBootTimeNs() {
165 return GetWallTimeNs();
166 }
167
168 #elif PERFETTO_BUILDFLAG(PERFETTO_OS_NACL)
169
170 // Tracing time doesn't need to work on NaCl since its going away shortly. We
171 // just need to compile on it. The only function NaCl could support is
172 // GetWallTimeNs(), but to prevent false hope we leave it unimplemented.
173
GetWallTimeNs()174 inline TimeNanos GetWallTimeNs() {
175 return TimeNanos(0);
176 }
177
GetWallTimeRawNs()178 inline TimeNanos GetWallTimeRawNs() {
179 return TimeNanos(0);
180 }
181
GetThreadCPUTimeNs()182 inline TimeNanos GetThreadCPUTimeNs() {
183 return TimeNanos(0);
184 }
185
GetBootTimeNs()186 inline TimeNanos GetBootTimeNs() {
187 return TimeNanos(0);
188 }
189
190 #elif PERFETTO_BUILDFLAG(PERFETTO_OS_QNX)
191
192 constexpr clockid_t kWallTimeClockSource = CLOCK_MONOTONIC;
193
GetTimeInternalNs(clockid_t clk_id)194 inline TimeNanos GetTimeInternalNs(clockid_t clk_id) {
195 struct timespec ts = {};
196 PERFETTO_CHECK(clock_gettime(clk_id, &ts) == 0);
197 return FromPosixTimespec(ts);
198 }
199
GetWallTimeNs()200 inline TimeNanos GetWallTimeNs() {
201 return GetTimeInternalNs(kWallTimeClockSource);
202 }
203
GetWallTimeRawNs()204 inline TimeNanos GetWallTimeRawNs() {
205 return GetTimeInternalNs(CLOCK_MONOTONIC);
206 }
207
GetThreadCPUTimeNs()208 inline TimeNanos GetThreadCPUTimeNs() {
209 return GetTimeInternalNs(CLOCK_THREAD_CPUTIME_ID);
210 }
211
212 // TODO: Clock that counts time during suspend is not implemented on QNX.
GetBootTimeNs()213 inline TimeNanos GetBootTimeNs() {
214 return GetWallTimeNs();
215 }
216
217 #else // posix
218
219 constexpr clockid_t kWallTimeClockSource = CLOCK_MONOTONIC;
220
GetTimeInternalNs(clockid_t clk_id)221 inline TimeNanos GetTimeInternalNs(clockid_t clk_id) {
222 struct timespec ts = {};
223 PERFETTO_CHECK(clock_gettime(clk_id, &ts) == 0);
224 return FromPosixTimespec(ts);
225 }
226
227 // Return ns from boot. Conversely to GetWallTimeNs, this clock counts also time
228 // during suspend (when supported).
GetBootTimeNs()229 inline TimeNanos GetBootTimeNs() {
230 // Determine if CLOCK_BOOTTIME is available on the first call.
231 static const clockid_t kBootTimeClockSource = [] {
232 struct timespec ts = {};
233 int res = clock_gettime(CLOCK_BOOTTIME, &ts);
234 return res == 0 ? CLOCK_BOOTTIME : kWallTimeClockSource;
235 }();
236 return GetTimeInternalNs(kBootTimeClockSource);
237 }
238
GetWallTimeNs()239 inline TimeNanos GetWallTimeNs() {
240 return GetTimeInternalNs(kWallTimeClockSource);
241 }
242
GetWallTimeRawNs()243 inline TimeNanos GetWallTimeRawNs() {
244 return GetTimeInternalNs(CLOCK_MONOTONIC_RAW);
245 }
246
GetThreadCPUTimeNs()247 inline TimeNanos GetThreadCPUTimeNs() {
248 return GetTimeInternalNs(CLOCK_THREAD_CPUTIME_ID);
249 }
250 #endif
251
GetBootTimeS()252 inline TimeSeconds GetBootTimeS() {
253 return std::chrono::duration_cast<TimeSeconds>(GetBootTimeNs());
254 }
255
GetBootTimeMs()256 inline TimeMillis GetBootTimeMs() {
257 return std::chrono::duration_cast<TimeMillis>(GetBootTimeNs());
258 }
259
GetWallTimeMs()260 inline TimeMillis GetWallTimeMs() {
261 return std::chrono::duration_cast<TimeMillis>(GetWallTimeNs());
262 }
263
GetWallTimeS()264 inline TimeSeconds GetWallTimeS() {
265 return std::chrono::duration_cast<TimeSeconds>(GetWallTimeNs());
266 }
267
ToPosixTimespec(TimeMillis time)268 inline struct timespec ToPosixTimespec(TimeMillis time) {
269 struct timespec ts {};
270 const long time_s = static_cast<long>(time.count() / 1000);
271 ts.tv_sec = time_s;
272 ts.tv_nsec = (static_cast<long>(time.count()) - time_s * 1000L) * 1000000L;
273 return ts;
274 }
275
276 std::string GetTimeFmt(const std::string& fmt);
277
TimeGm(struct tm * tms)278 inline int64_t TimeGm(struct tm* tms) {
279 #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
280 return static_cast<int64_t>(_mkgmtime(tms));
281 #elif PERFETTO_BUILDFLAG(PERFETTO_OS_NACL)
282 // NaCL has no timegm.
283 if (tms) // Kinda if (true), but avoids "mark as noreturn" errors.
284 PERFETTO_FATAL("timegm not supported");
285 return -1;
286 #else
287 return static_cast<int64_t>(timegm(tms));
288 #endif
289 }
290
291 // Creates a time_t-compatible timestamp (seconds since epoch) from a tuple of
292 // y-m-d-h-m-s. It's a saner version of timegm(). Some remarks:
293 // The year is just the actual year (it's Y-1900 in timegm()).
294 // The month ranges 1-12 (it's 0-11 in timegm()).
MkTime(int year,int month,int day,int h,int m,int s)295 inline int64_t MkTime(int year, int month, int day, int h, int m, int s) {
296 PERFETTO_DCHECK(year >= 1900);
297 PERFETTO_DCHECK(month > 0 && month <= 12);
298 PERFETTO_DCHECK(day > 0 && day <= 31);
299 struct tm tms {};
300 tms.tm_year = year - 1900;
301 tms.tm_mon = month - 1;
302 tms.tm_mday = day;
303 tms.tm_hour = h;
304 tms.tm_min = m;
305 tms.tm_sec = s;
306 return TimeGm(&tms);
307 }
308
309 #if PERFETTO_BUILDFLAG(PERFETTO_ARCH_CPU_X86_64)
Rdtsc()310 inline uint64_t Rdtsc() {
311 #if PERFETTO_BUILDFLAG(PERFETTO_COMPILER_MSVC)
312 return static_cast<uint64_t>(__rdtsc());
313 #else
314 // Use inline asm for clang and gcc: rust ffi bindgen crashes in using
315 // intrinsics on ChromeOS.
316 uint64_t low, high;
317 __asm__ volatile("rdtsc" : "=a"(low), "=d"(high));
318 return (high << 32) | low;
319 #endif
320 }
321 #endif
322
323 std::optional<int32_t> GetTimezoneOffsetMins();
324
325 } // namespace base
326 } // namespace perfetto
327
328 #endif // INCLUDE_PERFETTO_BASE_TIME_H_
329