core_timing.cpp 9.8 KB

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