core_timing.cpp 10 KB

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