1 //===-- PerfTests.cpp -----------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #ifdef __x86_64__ 10 11 #include "Perf.h" 12 13 #include "llvm/Support/Error.h" 14 15 #include "gtest/gtest.h" 16 #include <chrono> 17 #include <cstdint> 18 19 using namespace lldb_private; 20 using namespace process_linux; 21 using namespace llvm; 22 23 /// Helper function to read current TSC value. 24 /// 25 /// This code is based on llvm/xray. 26 static Expected<uint64_t> readTsc() { 27 28 unsigned int eax, ebx, ecx, edx; 29 30 // We check whether rdtscp support is enabled. According to the x86_64 manual, 31 // level should be set at 0x80000001, and we should have a look at bit 27 in 32 // EDX. That's 0x8000000 (or 1u << 27). 33 __asm__ __volatile__("cpuid" 34 : "=a"(eax), "=b"(ebx), "=c"(ecx), "=d"(edx) 35 : "0"(0x80000001)); 36 if (!(edx & (1u << 27))) { 37 return createStringError(inconvertibleErrorCode(), 38 "Missing rdtscp support."); 39 } 40 41 unsigned cpu; 42 unsigned long rax, rdx; 43 44 __asm__ __volatile__("rdtscp\n" : "=a"(rax), "=d"(rdx), "=c"(cpu)::); 45 46 return (rdx << 32) + rax; 47 } 48 49 // Test TSC to walltime conversion based on perf conversion values. 50 TEST(Perf, TscConversion) { 51 // This test works by first reading the TSC value directly before 52 // and after sleeping, then converting these values to nanoseconds, and 53 // finally ensuring the difference is approximately equal to the sleep time. 54 // 55 // There will be slight overhead associated with the sleep call, so it isn't 56 // reasonable to expect the difference to be exactly equal to the sleep time. 57 58 const int SLEEP_SECS = 1; 59 std::chrono::nanoseconds SLEEP_NANOS{std::chrono::seconds(SLEEP_SECS)}; 60 61 Expected<LinuxPerfZeroTscConversion> params = 62 LoadPerfTscConversionParameters(); 63 64 // Skip the test if the conversion parameters aren't available. 65 if (!params) 66 GTEST_SKIP() << toString(params.takeError()); 67 68 Expected<uint64_t> tsc_before_sleep = readTsc(); 69 sleep(SLEEP_SECS); 70 Expected<uint64_t> tsc_after_sleep = readTsc(); 71 72 // Skip the test if we are unable to read the TSC value. 73 if (!tsc_before_sleep) 74 GTEST_SKIP() << toString(tsc_before_sleep.takeError()); 75 if (!tsc_after_sleep) 76 GTEST_SKIP() << toString(tsc_after_sleep.takeError()); 77 78 std::chrono::nanoseconds converted_tsc_diff = 79 params->Convert(*tsc_after_sleep) - params->Convert(*tsc_before_sleep); 80 81 std::chrono::microseconds acceptable_overhead(500); 82 83 ASSERT_GE(converted_tsc_diff.count(), SLEEP_NANOS.count()); 84 ASSERT_LT(converted_tsc_diff.count(), 85 (SLEEP_NANOS + acceptable_overhead).count()); 86 } 87 88 #endif // __x86_64__ 89