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