2023-08-28 12:31:18 +02:00
|
|
|
/* Measure time and sleep with IA-32 time-stamp counter.
|
2018-08-22 11:29:39 +02:00
|
|
|
*
|
2023-08-31 11:17:07 +02:00
|
|
|
* Author: Steffen Vogel <post@steffenvogel.de>
|
|
|
|
* SPDX-FileCopyrightText: 2014-2023 Institute for Automation of Complex Power Systems, RWTH Aachen University
|
|
|
|
* SPDX-License-Identifier: Apache-2.0
|
2023-08-28 12:31:18 +02:00
|
|
|
*/
|
2018-08-22 11:29:39 +02:00
|
|
|
|
2025-02-03 17:16:36 +00:00
|
|
|
#include <villas/kernel/kernel.hpp>
|
2021-08-11 12:40:19 -04:00
|
|
|
#include <villas/tsc.hpp>
|
2018-08-22 11:29:39 +02:00
|
|
|
|
2025-02-03 17:16:36 +00:00
|
|
|
using namespace villas;
|
|
|
|
|
2023-09-07 13:19:19 +02:00
|
|
|
int tsc_init(struct Tsc *t) {
|
2025-02-03 16:41:13 +00:00
|
|
|
#if defined(__x86_64__) || defined(__i386__)
|
2023-09-07 13:19:19 +02:00
|
|
|
uint32_t eax = 0, ebx = 0, ecx = 0, edx = 0;
|
|
|
|
|
|
|
|
// Check if TSC is supported
|
|
|
|
__get_cpuid(0x1, &eax, &ebx, &ecx, &edx);
|
|
|
|
if (!(edx & bit_TSC))
|
|
|
|
return -2;
|
|
|
|
|
|
|
|
// Check if RDTSCP instruction is supported
|
|
|
|
__get_cpuid(0x80000001, &eax, &ebx, &ecx, &edx);
|
|
|
|
t->rdtscp_supported = edx & bit_RDTSCP;
|
|
|
|
|
|
|
|
// Check if TSC is invariant
|
|
|
|
__get_cpuid(0x80000007, &eax, &ebx, &ecx, &edx);
|
|
|
|
t->is_invariant = edx & bit_TSC_INVARIANT;
|
|
|
|
|
|
|
|
// Intel SDM Vol 3, Section 18.7.3:
|
|
|
|
// Nominal TSC frequency = CPUID.15H.ECX[31:0] * CPUID.15H.EBX[31:0] ) ÷ CPUID.15H.EAX[31:0]
|
|
|
|
__get_cpuid(0x15, &eax, &ebx, &ecx, &edx);
|
|
|
|
|
|
|
|
if (ecx != 0)
|
|
|
|
t->frequency = ecx * ebx / eax;
|
|
|
|
else {
|
2018-08-22 11:29:39 +02:00
|
|
|
#ifdef __linux__
|
2025-02-03 16:41:13 +00:00
|
|
|
int ret = kernel::get_cpu_frequency(&t->frequency);
|
2023-09-07 13:19:19 +02:00
|
|
|
if (ret)
|
|
|
|
return ret;
|
2018-08-22 11:29:39 +02:00
|
|
|
#endif
|
2023-09-07 13:19:19 +02:00
|
|
|
}
|
2025-02-03 16:41:13 +00:00
|
|
|
#else
|
|
|
|
#ifdef __linux__
|
|
|
|
int ret = kernel::get_cpu_frequency(&t->frequency);
|
|
|
|
if (ret)
|
|
|
|
return ret;
|
|
|
|
#endif
|
|
|
|
#endif
|
2025-02-03 17:54:23 +00:00
|
|
|
if (t->frequency)
|
|
|
|
return 0; // Frequency determined with success
|
|
|
|
else
|
|
|
|
return -1;
|
2018-08-22 11:29:39 +02:00
|
|
|
}
|
|
|
|
|
2023-09-07 13:19:19 +02:00
|
|
|
uint64_t tsc_rate_to_cycles(struct Tsc *t, double rate) {
|
|
|
|
return t->frequency / rate;
|
2018-08-22 11:29:39 +02:00
|
|
|
}
|