cpu_wait.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <thread>
  4. #ifdef _MSC_VER
  5. #include <intrin.h>
  6. #endif
  7. #include "common/x64/cpu_detect.h"
  8. #include "common/x64/cpu_wait.h"
  9. #include "common/x64/rdtsc.h"
  10. namespace Common::X64 {
  11. namespace {
  12. // 100,000 cycles is a reasonable amount of time to wait to save on CPU resources.
  13. // For reference:
  14. // At 1 GHz, 100K cycles is 100us
  15. // At 2 GHz, 100K cycles is 50us
  16. // At 4 GHz, 100K cycles is 25us
  17. constexpr auto PauseCycles = 100'000U;
  18. } // Anonymous namespace
  19. #ifdef _MSC_VER
  20. __forceinline static void TPAUSE() {
  21. static constexpr auto RequestC02State = 0U;
  22. _tpause(RequestC02State, FencedRDTSC() + PauseCycles);
  23. }
  24. __forceinline static void MWAITX() {
  25. static constexpr auto EnableWaitTimeFlag = 1U << 1;
  26. static constexpr auto RequestC1State = 0U;
  27. // monitor_var should be aligned to a cache line.
  28. alignas(64) u64 monitor_var{};
  29. _mm_monitorx(&monitor_var, 0, 0);
  30. _mm_mwaitx(EnableWaitTimeFlag, RequestC1State, PauseCycles);
  31. }
  32. #else
  33. static void TPAUSE() {
  34. static constexpr auto RequestC02State = 0U;
  35. const auto tsc = FencedRDTSC() + PauseCycles;
  36. const auto eax = static_cast<u32>(tsc & 0xFFFFFFFF);
  37. const auto edx = static_cast<u32>(tsc >> 32);
  38. asm volatile("tpause %0" : : "r"(RequestC02State), "d"(edx), "a"(eax));
  39. }
  40. static void MWAITX() {
  41. static constexpr auto EnableWaitTimeFlag = 1U << 1;
  42. static constexpr auto RequestC1State = 0U;
  43. // monitor_var should be aligned to a cache line.
  44. alignas(64) u64 monitor_var{};
  45. asm volatile("monitorx" : : "a"(&monitor_var), "c"(0), "d"(0));
  46. asm volatile("mwaitx" : : "a"(RequestC1State), "b"(PauseCycles), "c"(EnableWaitTimeFlag));
  47. }
  48. #endif
  49. void MicroSleep() {
  50. static const bool has_waitpkg = GetCPUCaps().waitpkg;
  51. static const bool has_monitorx = GetCPUCaps().monitorx;
  52. if (has_waitpkg) {
  53. TPAUSE();
  54. } else if (has_monitorx) {
  55. MWAITX();
  56. } else {
  57. std::this_thread::yield();
  58. }
  59. }
  60. } // namespace Common::X64