Skip to content

Commit

Permalink
[PAL/Linux-SGX] Simplify is_rdtsc_available logic, rely on TSC emulation
Browse files Browse the repository at this point in the history
Signed-off-by: Jonathan Shamir <[email protected]>
  • Loading branch information
jonathan-sha committed Jul 23, 2024
1 parent fad2f84 commit 197f2d4
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 17 deletions.
2 changes: 2 additions & 0 deletions pal/src/host/linux-sgx/pal_exception.c
Original file line number Diff line number Diff line change
Expand Up @@ -113,9 +113,11 @@ static void save_pal_context(PAL_CONTEXT* ctx, sgx_cpu_context_t* uc,

#include "utils/fast_clock.h"

int g_atomic_is_rdtsc_emulated = 0;
static void emulate_rdtsc_and_print_warning(sgx_cpu_context_t* uc) {
if (FIRST_TIME()) {
/* if we end up emulating RDTSC/RDTSCP instruction, we cannot use TSC-based clock emulation */
__atomic_store_n(&g_atomic_is_rdtsc_emulated, 1, __ATOMIC_SEQ_CST);
fast_clock_disable(&g_fast_clock);
log_warning("all RDTSC/RDTSCP instructions are emulated (imprecisely) via gettime() "
"syscall.");
Expand Down
27 changes: 10 additions & 17 deletions pal/src/host/linux-sgx/utils/fast_clock.c
Original file line number Diff line number Diff line change
Expand Up @@ -191,26 +191,19 @@ static inline fast_clock_timepoint* get_timepoint(fast_clock* fast_clock, fast_c
}

static bool is_rdtsc_available(void) {
uint32_t words[CPUID_WORD_NUM];
// we just need to check if rdtsc opcode is emulated (otherwise using it is really slow) -
extern int g_atomic_is_rdtsc_emulated;

// rdtsc feature enabled
_PalCpuIdRetrieve(FEATURE_FLAGS_LEAF, 0, words);
if (!(words[CPUID_WORD_EDX] & (1 << 4)))
// "optimistic path", assume rdtsc() was called at least once
int is_emulated = __atomic_load_n(&g_atomic_is_rdtsc_emulated, __ATOMIC_SEQ_CST);
if (is_emulated) {
return false;
}

// SGX enabled (sanity check)
_PalCpuIdRetrieve(EXTENDED_FEATURE_FLAGS_LEAF, 0, words);
if (!(words[CPUID_WORD_EBX] & (1 << 2)))
return false;

// SGX2 capabilities - otherwise, rdtsc opcode is illegal in sgx enclave
_PalCpuIdRetrieve(INTEL_SGX_LEAF, 0, words);
if (!(words[CPUID_WORD_EAX] & (1 << 1)))
return false; // SGX1 features disabled
if (!(words[CPUID_WORD_EAX] & (1 << 2)))
return false; // SGX2 features disabled

return true;
// make sure the is_emulated guard is initialized
(void)get_tsc();
is_emulated = __atomic_load_n(&g_atomic_is_rdtsc_emulated, __ATOMIC_SEQ_CST);
return !is_emulated;
}

static int handle_state_rdtsc_disabled(uint64_t* time_usec)
Expand Down

0 comments on commit 197f2d4

Please sign in to comment.