core_timing.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. // SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <algorithm>
  4. #include <mutex>
  5. #include <string>
  6. #include <tuple>
  7. #ifdef _WIN32
  8. #include "common/windows/timer_resolution.h"
  9. #endif
  10. #ifdef ARCHITECTURE_x86_64
  11. #include "common/x64/cpu_wait.h"
  12. #endif
  13. #include "common/microprofile.h"
  14. #include "core/core_timing.h"
  15. #include "core/core_timing_util.h"
  16. #include "core/hardware_properties.h"
  17. namespace Core::Timing {
  18. constexpr s64 MAX_SLICE_LENGTH = 4000;
  19. std::shared_ptr<EventType> CreateEvent(std::string name, TimedCallback&& callback) {
  20. return std::make_shared<EventType>(std::move(callback), std::move(name));
  21. }
  22. struct CoreTiming::Event {
  23. s64 time;
  24. u64 fifo_order;
  25. std::uintptr_t user_data;
  26. std::weak_ptr<EventType> type;
  27. s64 reschedule_time;
  28. // Sort by time, unless the times are the same, in which case sort by
  29. // the order added to the queue
  30. friend bool operator>(const Event& left, const Event& right) {
  31. return std::tie(left.time, left.fifo_order) > std::tie(right.time, right.fifo_order);
  32. }
  33. friend bool operator<(const Event& left, const Event& right) {
  34. return std::tie(left.time, left.fifo_order) < std::tie(right.time, right.fifo_order);
  35. }
  36. };
  37. CoreTiming::CoreTiming()
  38. : cpu_clock{Common::CreateBestMatchingClock(Hardware::BASE_CLOCK_RATE, Hardware::CNTFREQ)},
  39. event_clock{Common::CreateStandardWallClock(Hardware::BASE_CLOCK_RATE, Hardware::CNTFREQ)} {}
  40. CoreTiming::~CoreTiming() {
  41. Reset();
  42. }
  43. void CoreTiming::ThreadEntry(CoreTiming& instance) {
  44. static constexpr char name[] = "HostTiming";
  45. MicroProfileOnThreadCreate(name);
  46. Common::SetCurrentThreadName(name);
  47. Common::SetCurrentThreadPriority(Common::ThreadPriority::High);
  48. instance.on_thread_init();
  49. instance.ThreadLoop();
  50. MicroProfileOnThreadExit();
  51. }
  52. void CoreTiming::Initialize(std::function<void()>&& on_thread_init_) {
  53. Reset();
  54. on_thread_init = std::move(on_thread_init_);
  55. event_fifo_id = 0;
  56. shutting_down = false;
  57. ticks = 0;
  58. const auto empty_timed_callback = [](std::uintptr_t, u64, std::chrono::nanoseconds)
  59. -> std::optional<std::chrono::nanoseconds> { return std::nullopt; };
  60. ev_lost = CreateEvent("_lost_event", empty_timed_callback);
  61. if (is_multicore) {
  62. timer_thread = std::make_unique<std::thread>(ThreadEntry, std::ref(*this));
  63. }
  64. }
  65. void CoreTiming::ClearPendingEvents() {
  66. event_queue.clear();
  67. }
  68. void CoreTiming::Pause(bool is_paused) {
  69. paused = is_paused;
  70. pause_event.Set();
  71. if (!is_paused) {
  72. pause_end_time = GetGlobalTimeNs().count();
  73. }
  74. }
  75. void CoreTiming::SyncPause(bool is_paused) {
  76. if (is_paused == paused && paused_set == paused) {
  77. return;
  78. }
  79. Pause(is_paused);
  80. if (timer_thread) {
  81. if (!is_paused) {
  82. pause_event.Set();
  83. }
  84. event.Set();
  85. while (paused_set != is_paused)
  86. ;
  87. }
  88. if (!is_paused) {
  89. pause_end_time = GetGlobalTimeNs().count();
  90. }
  91. }
  92. bool CoreTiming::IsRunning() const {
  93. return !paused_set;
  94. }
  95. bool CoreTiming::HasPendingEvents() const {
  96. return !(wait_set && event_queue.empty());
  97. }
  98. void CoreTiming::ScheduleEvent(std::chrono::nanoseconds ns_into_future,
  99. const std::shared_ptr<EventType>& event_type,
  100. std::uintptr_t user_data, bool absolute_time) {
  101. {
  102. std::scoped_lock scope{basic_lock};
  103. const auto next_time{absolute_time ? ns_into_future : GetGlobalTimeNs() + ns_into_future};
  104. event_queue.emplace_back(
  105. Event{next_time.count(), event_fifo_id++, user_data, event_type, 0});
  106. std::push_heap(event_queue.begin(), event_queue.end(), std::greater<>());
  107. }
  108. event.Set();
  109. }
  110. void CoreTiming::ScheduleLoopingEvent(std::chrono::nanoseconds start_time,
  111. std::chrono::nanoseconds resched_time,
  112. const std::shared_ptr<EventType>& event_type,
  113. std::uintptr_t user_data, bool absolute_time) {
  114. {
  115. std::scoped_lock scope{basic_lock};
  116. const auto next_time{absolute_time ? start_time : GetGlobalTimeNs() + start_time};
  117. event_queue.emplace_back(
  118. Event{next_time.count(), event_fifo_id++, user_data, event_type, resched_time.count()});
  119. std::push_heap(event_queue.begin(), event_queue.end(), std::greater<>());
  120. }
  121. event.Set();
  122. }
  123. void CoreTiming::UnscheduleEvent(const std::shared_ptr<EventType>& event_type,
  124. std::uintptr_t user_data, bool wait) {
  125. {
  126. std::scoped_lock lk{basic_lock};
  127. const auto itr =
  128. std::remove_if(event_queue.begin(), event_queue.end(), [&](const Event& e) {
  129. return e.type.lock().get() == event_type.get() && e.user_data == user_data;
  130. });
  131. // Removing random items breaks the invariant so we have to re-establish it.
  132. if (itr != event_queue.end()) {
  133. event_queue.erase(itr, event_queue.end());
  134. std::make_heap(event_queue.begin(), event_queue.end(), std::greater<>());
  135. }
  136. }
  137. // Force any in-progress events to finish
  138. if (wait) {
  139. std::scoped_lock lk{advance_lock};
  140. }
  141. }
  142. void CoreTiming::AddTicks(u64 ticks_to_add) {
  143. ticks += ticks_to_add;
  144. downcount -= static_cast<s64>(ticks);
  145. }
  146. void CoreTiming::Idle() {
  147. if (!event_queue.empty()) {
  148. const u64 next_event_time = event_queue.front().time;
  149. const u64 next_ticks = nsToCycles(std::chrono::nanoseconds(next_event_time)) + 10U;
  150. if (next_ticks > ticks) {
  151. ticks = next_ticks;
  152. }
  153. return;
  154. }
  155. ticks += 1000U;
  156. }
  157. void CoreTiming::ResetTicks() {
  158. downcount = MAX_SLICE_LENGTH;
  159. }
  160. u64 CoreTiming::GetCPUTicks() const {
  161. if (is_multicore) [[likely]] {
  162. return cpu_clock->GetCPUCycles();
  163. }
  164. return ticks;
  165. }
  166. u64 CoreTiming::GetClockTicks() const {
  167. if (is_multicore) [[likely]] {
  168. return cpu_clock->GetClockCycles();
  169. }
  170. return CpuCyclesToClockCycles(ticks);
  171. }
  172. std::optional<s64> CoreTiming::Advance() {
  173. std::scoped_lock lock{advance_lock, basic_lock};
  174. global_timer = GetGlobalTimeNs().count();
  175. while (!event_queue.empty() && event_queue.front().time <= global_timer) {
  176. Event evt = std::move(event_queue.front());
  177. std::pop_heap(event_queue.begin(), event_queue.end(), std::greater<>());
  178. event_queue.pop_back();
  179. if (const auto event_type{evt.type.lock()}) {
  180. basic_lock.unlock();
  181. const auto new_schedule_time{event_type->callback(
  182. evt.user_data, evt.time,
  183. std::chrono::nanoseconds{GetGlobalTimeNs().count() - evt.time})};
  184. basic_lock.lock();
  185. if (evt.reschedule_time != 0) {
  186. const auto next_schedule_time{new_schedule_time.has_value()
  187. ? new_schedule_time.value().count()
  188. : evt.reschedule_time};
  189. // If this event was scheduled into a pause, its time now is going to be way behind.
  190. // Re-set this event to continue from the end of the pause.
  191. auto next_time{evt.time + next_schedule_time};
  192. if (evt.time < pause_end_time) {
  193. next_time = pause_end_time + next_schedule_time;
  194. }
  195. event_queue.emplace_back(
  196. Event{next_time, event_fifo_id++, evt.user_data, evt.type, next_schedule_time});
  197. std::push_heap(event_queue.begin(), event_queue.end(), std::greater<>());
  198. }
  199. }
  200. global_timer = GetGlobalTimeNs().count();
  201. }
  202. if (!event_queue.empty()) {
  203. return event_queue.front().time;
  204. } else {
  205. return std::nullopt;
  206. }
  207. }
  208. void CoreTiming::ThreadLoop() {
  209. has_started = true;
  210. while (!shutting_down) {
  211. while (!paused) {
  212. paused_set = false;
  213. const auto next_time = Advance();
  214. if (next_time) {
  215. // There are more events left in the queue, wait until the next event.
  216. auto wait_time = *next_time - GetGlobalTimeNs().count();
  217. if (wait_time > 0) {
  218. #ifdef _WIN32
  219. const auto timer_resolution_ns =
  220. Common::Windows::GetCurrentTimerResolution().count();
  221. while (!paused && !event.IsSet() && wait_time > 0) {
  222. wait_time = *next_time - GetGlobalTimeNs().count();
  223. if (wait_time >= timer_resolution_ns) {
  224. Common::Windows::SleepForOneTick();
  225. } else {
  226. #ifdef ARCHITECTURE_x86_64
  227. Common::X64::MicroSleep();
  228. #else
  229. std::this_thread::yield();
  230. #endif
  231. }
  232. }
  233. if (event.IsSet()) {
  234. event.Reset();
  235. }
  236. #else
  237. event.WaitFor(std::chrono::nanoseconds(wait_time));
  238. #endif
  239. }
  240. } else {
  241. // Queue is empty, wait until another event is scheduled and signals us to continue.
  242. wait_set = true;
  243. event.Wait();
  244. }
  245. wait_set = false;
  246. }
  247. paused_set = true;
  248. event_clock->Pause(true);
  249. pause_event.Wait();
  250. event_clock->Pause(false);
  251. }
  252. }
  253. void CoreTiming::Reset() {
  254. paused = true;
  255. shutting_down = true;
  256. pause_event.Set();
  257. event.Set();
  258. if (timer_thread) {
  259. timer_thread->join();
  260. }
  261. timer_thread.reset();
  262. has_started = false;
  263. }
  264. std::chrono::nanoseconds CoreTiming::GetCPUTimeNs() const {
  265. if (is_multicore) [[likely]] {
  266. return cpu_clock->GetTimeNS();
  267. }
  268. return CyclesToNs(ticks);
  269. }
  270. std::chrono::nanoseconds CoreTiming::GetGlobalTimeNs() const {
  271. if (is_multicore) [[likely]] {
  272. return event_clock->GetTimeNS();
  273. }
  274. return CyclesToNs(ticks);
  275. }
  276. std::chrono::microseconds CoreTiming::GetGlobalTimeUs() const {
  277. if (is_multicore) [[likely]] {
  278. return event_clock->GetTimeUS();
  279. }
  280. return CyclesToUs(ticks);
  281. }
  282. } // namespace Core::Timing