core_timing.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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() = default;
  34. void CoreTiming::ThreadEntry(CoreTiming& instance) {
  35. constexpr char name[] = "yuzu:HostTiming";
  36. MicroProfileOnThreadCreate(name);
  37. Common::SetCurrentThreadName(name);
  38. Common::SetCurrentThreadPriority(Common::ThreadPriority::Critical);
  39. instance.on_thread_init();
  40. instance.ThreadLoop();
  41. MicroProfileOnThreadExit();
  42. }
  43. void CoreTiming::Initialize(std::function<void()>&& on_thread_init_) {
  44. on_thread_init = std::move(on_thread_init_);
  45. event_fifo_id = 0;
  46. shutting_down = false;
  47. ticks = 0;
  48. const auto empty_timed_callback = [](std::uintptr_t, u64, std::chrono::nanoseconds)
  49. -> std::optional<std::chrono::nanoseconds> { return std::nullopt; };
  50. ev_lost = CreateEvent("_lost_event", empty_timed_callback);
  51. if (is_multicore) {
  52. timer_thread = std::make_unique<std::thread>(ThreadEntry, std::ref(*this));
  53. }
  54. }
  55. void CoreTiming::Shutdown() {
  56. paused = true;
  57. shutting_down = true;
  58. pause_event.Set();
  59. event.Set();
  60. if (timer_thread) {
  61. timer_thread->join();
  62. }
  63. pause_callbacks.clear();
  64. ClearPendingEvents();
  65. timer_thread.reset();
  66. has_started = false;
  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. for (auto& cb : pause_callbacks) {
  75. cb(is_paused);
  76. }
  77. }
  78. void CoreTiming::SyncPause(bool is_paused) {
  79. if (is_paused == paused && paused_set == paused) {
  80. return;
  81. }
  82. Pause(is_paused);
  83. if (timer_thread) {
  84. if (!is_paused) {
  85. pause_event.Set();
  86. }
  87. event.Set();
  88. while (paused_set != is_paused)
  89. ;
  90. }
  91. if (!is_paused) {
  92. pause_end_time = GetGlobalTimeNs().count();
  93. }
  94. for (auto& cb : pause_callbacks) {
  95. cb(is_paused);
  96. }
  97. }
  98. bool CoreTiming::IsRunning() const {
  99. return !paused_set;
  100. }
  101. bool CoreTiming::HasPendingEvents() const {
  102. return !(wait_set && event_queue.empty());
  103. }
  104. void CoreTiming::ScheduleEvent(std::chrono::nanoseconds ns_into_future,
  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 ? ns_into_future : GetGlobalTimeNs() + ns_into_future};
  110. event_queue.emplace_back(
  111. Event{next_time.count(), event_fifo_id++, user_data, event_type, 0});
  112. std::push_heap(event_queue.begin(), event_queue.end(), std::greater<>());
  113. }
  114. event.Set();
  115. }
  116. void CoreTiming::ScheduleLoopingEvent(std::chrono::nanoseconds start_time,
  117. std::chrono::nanoseconds resched_time,
  118. const std::shared_ptr<EventType>& event_type,
  119. std::uintptr_t user_data, bool absolute_time) {
  120. std::scoped_lock scope{basic_lock};
  121. const auto next_time{absolute_time ? start_time : GetGlobalTimeNs() + start_time};
  122. event_queue.emplace_back(
  123. Event{next_time.count(), event_fifo_id++, user_data, event_type, resched_time.count()});
  124. std::push_heap(event_queue.begin(), event_queue.end(), std::greater<>());
  125. }
  126. void CoreTiming::UnscheduleEvent(const std::shared_ptr<EventType>& event_type,
  127. std::uintptr_t user_data) {
  128. std::scoped_lock scope{basic_lock};
  129. const auto itr = std::remove_if(event_queue.begin(), event_queue.end(), [&](const Event& e) {
  130. return e.type.lock().get() == event_type.get() && e.user_data == user_data;
  131. });
  132. // Removing random items breaks the invariant so we have to re-establish it.
  133. if (itr != event_queue.end()) {
  134. event_queue.erase(itr, event_queue.end());
  135. std::make_heap(event_queue.begin(), event_queue.end(), std::greater<>());
  136. }
  137. }
  138. void CoreTiming::AddTicks(u64 ticks_to_add) {
  139. ticks += ticks_to_add;
  140. downcount -= static_cast<s64>(ticks);
  141. }
  142. void CoreTiming::Idle() {
  143. if (!event_queue.empty()) {
  144. const u64 next_event_time = event_queue.front().time;
  145. const u64 next_ticks = nsToCycles(std::chrono::nanoseconds(next_event_time)) + 10U;
  146. if (next_ticks > ticks) {
  147. ticks = next_ticks;
  148. }
  149. return;
  150. }
  151. ticks += 1000U;
  152. }
  153. void CoreTiming::ResetTicks() {
  154. downcount = MAX_SLICE_LENGTH;
  155. }
  156. u64 CoreTiming::GetCPUTicks() const {
  157. if (is_multicore) {
  158. return clock->GetCPUCycles();
  159. }
  160. return ticks;
  161. }
  162. u64 CoreTiming::GetClockTicks() const {
  163. if (is_multicore) {
  164. return clock->GetClockCycles();
  165. }
  166. return CpuCyclesToClockCycles(ticks);
  167. }
  168. void CoreTiming::ClearPendingEvents() {
  169. event_queue.clear();
  170. }
  171. void CoreTiming::RemoveEvent(const std::shared_ptr<EventType>& event_type) {
  172. std::scoped_lock lock{basic_lock};
  173. const auto itr = std::remove_if(event_queue.begin(), event_queue.end(), [&](const Event& e) {
  174. return e.type.lock().get() == event_type.get();
  175. });
  176. // Removing random items breaks the invariant so we have to re-establish it.
  177. if (itr != event_queue.end()) {
  178. event_queue.erase(itr, event_queue.end());
  179. std::make_heap(event_queue.begin(), event_queue.end(), std::greater<>());
  180. }
  181. }
  182. void CoreTiming::RegisterPauseCallback(PauseCallback&& callback) {
  183. std::scoped_lock lock{basic_lock};
  184. pause_callbacks.emplace_back(std::move(callback));
  185. }
  186. std::optional<s64> CoreTiming::Advance() {
  187. std::scoped_lock lock{advance_lock, basic_lock};
  188. global_timer = GetGlobalTimeNs().count();
  189. while (!event_queue.empty() && event_queue.front().time <= global_timer) {
  190. Event evt = std::move(event_queue.front());
  191. std::pop_heap(event_queue.begin(), event_queue.end(), std::greater<>());
  192. event_queue.pop_back();
  193. if (const auto event_type{evt.type.lock()}) {
  194. basic_lock.unlock();
  195. const auto new_schedule_time{event_type->callback(
  196. evt.user_data, evt.time,
  197. std::chrono::nanoseconds{GetGlobalTimeNs().count() - evt.time})};
  198. basic_lock.lock();
  199. if (evt.reschedule_time != 0) {
  200. const auto next_schedule_time{new_schedule_time.has_value()
  201. ? new_schedule_time.value().count()
  202. : evt.reschedule_time};
  203. // If this event was scheduled into a pause, its time now is going to be way behind.
  204. // Re-set this event to continue from the end of the pause.
  205. auto next_time{evt.time + next_schedule_time};
  206. if (evt.time < pause_end_time) {
  207. next_time = pause_end_time + next_schedule_time;
  208. }
  209. event_queue.emplace_back(
  210. Event{next_time, event_fifo_id++, evt.user_data, evt.type, next_schedule_time});
  211. std::push_heap(event_queue.begin(), event_queue.end(), std::greater<>());
  212. }
  213. }
  214. global_timer = GetGlobalTimeNs().count();
  215. }
  216. if (!event_queue.empty()) {
  217. return event_queue.front().time;
  218. } else {
  219. return std::nullopt;
  220. }
  221. }
  222. void CoreTiming::ThreadLoop() {
  223. has_started = true;
  224. while (!shutting_down) {
  225. while (!paused) {
  226. paused_set = false;
  227. const auto next_time = Advance();
  228. if (next_time) {
  229. // There are more events left in the queue, sleep until the next event.
  230. const auto diff_ns{*next_time - GetGlobalTimeNs().count()};
  231. if (diff_ns > 0) {
  232. // Only try to sleep if the remaining time is >= 1ms. Take off 500 microseconds
  233. // from the target time to account for possible over-sleeping, and spin the
  234. // remaining.
  235. const auto sleep_time_ns{diff_ns - 500LL * 1'000LL};
  236. const auto sleep_time_ms{sleep_time_ns / 1'000'000LL};
  237. if (sleep_time_ms >= 1) {
  238. event.WaitFor(std::chrono::nanoseconds(sleep_time_ns));
  239. }
  240. const auto end_time{std::chrono::nanoseconds(*next_time)};
  241. while (!paused && !event.IsSet() && GetGlobalTimeNs() < end_time) {
  242. }
  243. if (event.IsSet()) {
  244. event.Reset();
  245. }
  246. }
  247. } else {
  248. // Queue is empty, wait until another event is scheduled and signals us to continue.
  249. wait_set = true;
  250. event.Wait();
  251. }
  252. wait_set = false;
  253. }
  254. paused_set = true;
  255. clock->Pause(true);
  256. pause_event.Wait();
  257. clock->Pause(false);
  258. }
  259. }
  260. std::chrono::nanoseconds CoreTiming::GetGlobalTimeNs() const {
  261. if (is_multicore) {
  262. return clock->GetTimeNS();
  263. }
  264. return CyclesToNs(ticks);
  265. }
  266. std::chrono::microseconds CoreTiming::GetGlobalTimeUs() const {
  267. if (is_multicore) {
  268. return clock->GetTimeUS();
  269. }
  270. return CyclesToUs(ticks);
  271. }
  272. } // namespace Core::Timing