-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathtsc.h
More file actions
111 lines (82 loc) · 2.2 KB
/
Copy pathtsc.h
File metadata and controls
111 lines (82 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/*
* Copyright The async-profiler authors
* Copyright 2025, Datadog, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef _TSC_H
#define _TSC_H
#include "arguments.h"
#include "os.h"
const u64 NANOTIME_FREQ = 1000000000;
#if defined(__x86_64__) || defined(__i386__)
#include <cpuid.h>
#define TSC_SUPPORTED true
static inline u64 rdtsc() {
#if defined(__x86_64__)
u32 lo, hi;
asm volatile("rdtsc" : "=a" (lo), "=d" (hi));
return ((u64)hi << 32) | lo;
#else
u64 result;
asm volatile("rdtsc" : "=A" (result));
return result;
#endif
}
// Returns true if this CPU has a good ("invariant") timestamp counter
inline bool cpuHasGoodTimestampCounter() {
unsigned int eax, ebx, ecx, edx;
// Check if CPUID supports misc feature flags
__cpuid(0x80000000, eax, ebx, ecx, edx);
if (eax < 0x80000007) {
return 0;
}
// Get misc feature flags
__cpuid(0x80000007, eax, ebx, ecx, edx);
// Bit 8 of EDX indicates invariant TSC
return (edx & (1 << 8)) != 0;
}
#elif defined(__aarch64__)
#define TSC_SUPPORTED true
static inline u64 rdtsc() {
u64 value;
asm volatile("mrs %0, cntvct_el0" : "=r"(value));
return value;
}
inline bool cpuHasGoodTimestampCounter() {
// AARCH64 always has a good timestamp counter.
return true;
}
#else
#define TSC_SUPPORTED false
#define rdtsc() 0
static bool cpuHasGoodTimestampCounter() {
return false;
}
#endif
class TSC {
private:
static bool _initialized;
static bool _available;
static bool _enabled;
static u64 _offset;
static u64 _frequency;
public:
static void enable(Clock clock);
static bool enabled() {
return TSC_SUPPORTED && _enabled;
}
static u64 ticks() {
return enabled() ? rdtsc() - _offset : OS::nanotime();
}
// Ticks per second.
// When using the TSC with no JVM, since there is no calibration,
// this function will return an incorrect value.
static u64 frequency() {
return enabled() ? _frequency : NANOTIME_FREQ;
}
// Convert ticks to milliseconds
static u64 ticks_to_millis(u64 ticks) {
return TSC_SUPPORTED ? 1000 * ticks / frequency() : ticks / 1000 / 1000;
}
};
#endif // _TSC_H