|
| 1 | +/* |
| 2 | +Copyright 2025 The Hyperlight Authors. |
| 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 | +/// Module for checking invariant TSC support and reading the timestamp counter |
| 18 | +use core::arch::x86_64::{__cpuid, _rdtsc}; |
| 19 | + |
| 20 | +/// Check if the processor supports invariant TSC |
| 21 | +/// |
| 22 | +/// Returns true if CPUID.80000007H:EDX[8] is set, indicating invariant TSC support |
| 23 | +pub fn has_invariant_tsc() -> bool { |
| 24 | + // Check if extended CPUID functions are available |
| 25 | + let max_extended = unsafe { __cpuid(0x80000000) }; |
| 26 | + if max_extended.eax < 0x80000007 { |
| 27 | + return false; |
| 28 | + } |
| 29 | + |
| 30 | + // Query CPUID.80000007H for invariant TSC support |
| 31 | + let cpuid_result = unsafe { __cpuid(0x80000007) }; |
| 32 | + |
| 33 | + // Check bit 8 of EDX register for invariant TSC support |
| 34 | + (cpuid_result.edx & (1 << 8)) != 0 |
| 35 | +} |
| 36 | + |
| 37 | +/// Read the timestamp counter |
| 38 | +/// |
| 39 | +/// This function provides a high-performance timestamp by reading the TSC. |
| 40 | +/// Should only be used when invariant TSC is supported for reliable timing. |
| 41 | +/// |
| 42 | +/// # Safety |
| 43 | +/// This function uses unsafe assembly instructions but is safe to call. |
| 44 | +/// However, the resulting timestamp is only meaningful if invariant TSC is supported. |
| 45 | +pub fn read_tsc() -> u64 { |
| 46 | + unsafe { _rdtsc() } |
| 47 | +} |
0 commit comments