core_timing.cpp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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/hardware_properties.h"
  16. namespace Core::Timing {
  17. constexpr s64 MAX_SLICE_LENGTH = 10000;
  18. std::shared_ptr<EventType> CreateEvent(std::string name, TimedCallback&& callback) {
  19. return std::make_shared<EventType>(std::move(callback), std::move(name));
  20. }
  21. struct CoreTiming::Event {
  22. s64 time;
  23. u64 fifo_order;
  24. std::uintptr_t user_data;
  25. std::weak_ptr<EventType> type;
  26. s64 reschedule_time;
  27. heap_t::handle_type handle{};
  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() : clock{Common::CreateOptimalClock()} {}
  38. CoreTiming::~CoreTiming() {
  39. Reset();
  40. }
  41. void CoreTiming::ThreadEntry(CoreTiming& instance) {
  42. static constexpr char name[] = "HostTiming";
  43. MicroProfileOnThreadCreate(name);
  44. Common::SetCurrentThreadName(name);
  45. Common::SetCurrentThreadPriority(Common::ThreadPriority::High);
  46. instance.on_thread_init();
  47. instance.ThreadLoop();
  48. MicroProfileOnThreadExit();
  49. }
  50. void CoreTiming::Initialize(std::function<void()>&& on_thread_init_) {
  51. Reset();
  52. on_thread_init = std::move(on_thread_init_);
  53. event_fifo_id = 0;
  54. shutting_down = false;
  55. cpu_ticks = 0;
  56. const auto empty_timed_callback = [](std::uintptr_t, u64, std::chrono::nanoseconds)
  57. -> std::optional<std::chrono::nanoseconds> { return std::nullopt; };
  58. ev_lost = CreateEvent("_lost_event", empty_timed_callback);
  59. if (is_multicore) {
  60. timer_thread = std::make_unique<std::jthread>(ThreadEntry, std::ref(*this));
  61. }
  62. }
  63. void CoreTiming::ClearPendingEvents() {
  64. event_queue.clear();
  65. }
  66. void CoreTiming::Pause(bool is_paused) {
  67. paused = is_paused;
  68. pause_event.Set();
  69. if (!is_paused) {
  70. pause_end_time = GetGlobalTimeNs().count();
  71. }
  72. }
  73. void CoreTiming::SyncPause(bool is_paused) {
  74. if (is_paused == paused && paused_set == paused) {
  75. return;
  76. }
  77. Pause(is_paused);
  78. if (timer_thread) {
  79. if (!is_paused) {
  80. pause_event.Set();
  81. }
  82. event.Set();
  83. while (paused_set != is_paused)
  84. ;
  85. }
  86. if (!is_paused) {
  87. pause_end_time = GetGlobalTimeNs().count();
  88. }
  89. }
  90. bool CoreTiming::IsRunning() const {
  91. return !paused_set;
  92. }
  93. bool CoreTiming::HasPendingEvents() const {
  94. return !(wait_set && event_queue.empty());
  95. }
  96. void CoreTiming::ScheduleEvent(std::chrono::nanoseconds ns_into_future,
  97. const std::shared_ptr<EventType>& event_type,
  98. std::uintptr_t user_data, bool absolute_time) {
  99. {
  100. std::scoped_lock scope{basic_lock};
  101. const auto next_time{absolute_time ? ns_into_future : GetGlobalTimeNs() + ns_into_future};
  102. auto h{event_queue.emplace(
  103. Event{next_time.count(), event_fifo_id++, user_data, event_type, 0})};
  104. (*h).handle = h;
  105. }
  106. event.Set();
  107. }
  108. void CoreTiming::ScheduleLoopingEvent(std::chrono::nanoseconds start_time,
  109. std::chrono::nanoseconds resched_time,
  110. const std::shared_ptr<EventType>& event_type,
  111. std::uintptr_t user_data, bool absolute_time) {
  112. {
  113. std::scoped_lock scope{basic_lock};
  114. const auto next_time{absolute_time ? start_time : GetGlobalTimeNs() + start_time};
  115. auto h{event_queue.emplace(Event{next_time.count(), event_fifo_id++, user_data, event_type,
  116. resched_time.count()})};
  117. (*h).handle = h;
  118. }
  119. event.Set();
  120. }
  121. void CoreTiming::UnscheduleEvent(const std::shared_ptr<EventType>& event_type,
  122. std::uintptr_t user_data, bool wait) {
  123. {
  124. std::scoped_lock lk{basic_lock};
  125. std::vector<heap_t::handle_type> to_remove;
  126. for (auto itr = event_queue.begin(); itr != event_queue.end(); itr++) {
  127. const Event& e = *itr;
  128. if (e.type.lock().get() == event_type.get() && e.user_data == user_data) {
  129. to_remove.push_back(itr->handle);
  130. }
  131. }
  132. for (auto h : to_remove) {
  133. event_queue.erase(h);
  134. }
  135. }
  136. // Force any in-progress events to finish
  137. if (wait) {
  138. std::scoped_lock lk{advance_lock};
  139. }
  140. }
  141. void CoreTiming::AddTicks(u64 ticks_to_add) {
  142. cpu_ticks += ticks_to_add;
  143. downcount -= static_cast<s64>(cpu_ticks);
  144. }
  145. void CoreTiming::Idle() {
  146. cpu_ticks += 1000U;
  147. }
  148. void CoreTiming::ResetTicks() {
  149. downcount = MAX_SLICE_LENGTH;
  150. }
  151. u64 CoreTiming::GetClockTicks() const {
  152. if (is_multicore) [[likely]] {
  153. return clock->GetCNTPCT();
  154. }
  155. return Common::WallClock::CPUTickToCNTPCT(cpu_ticks);
  156. }
  157. u64 CoreTiming::GetGPUTicks() const {
  158. if (is_multicore) [[likely]] {
  159. return clock->GetGPUTick();
  160. }
  161. return Common::WallClock::CPUTickToGPUTick(cpu_ticks);
  162. }
  163. std::optional<s64> CoreTiming::Advance() {
  164. std::scoped_lock lock{advance_lock, basic_lock};
  165. global_timer = GetGlobalTimeNs().count();
  166. while (!event_queue.empty() && event_queue.top().time <= global_timer) {
  167. const Event& evt = event_queue.top();
  168. if (const auto event_type{evt.type.lock()}) {
  169. if (evt.reschedule_time == 0) {
  170. const auto evt_user_data = evt.user_data;
  171. const auto evt_time = evt.time;
  172. event_queue.pop();
  173. basic_lock.unlock();
  174. event_type->callback(
  175. evt_user_data, evt_time,
  176. std::chrono::nanoseconds{GetGlobalTimeNs().count() - evt_time});
  177. basic_lock.lock();
  178. } else {
  179. basic_lock.unlock();
  180. const auto new_schedule_time{event_type->callback(
  181. evt.user_data, evt.time,
  182. std::chrono::nanoseconds{GetGlobalTimeNs().count() - evt.time})};
  183. basic_lock.lock();
  184. const auto next_schedule_time{new_schedule_time.has_value()
  185. ? new_schedule_time.value().count()
  186. : evt.reschedule_time};
  187. // If this event was scheduled into a pause, its time now is going to be way
  188. // behind. Re-set this event to continue from the end of the pause.
  189. auto next_time{evt.time + next_schedule_time};
  190. if (evt.time < pause_end_time) {
  191. next_time = pause_end_time + next_schedule_time;
  192. }
  193. event_queue.update(evt.handle, Event{next_time, event_fifo_id++, evt.user_data,
  194. evt.type, next_schedule_time, evt.handle});
  195. }
  196. }
  197. global_timer = GetGlobalTimeNs().count();
  198. }
  199. if (!event_queue.empty()) {
  200. return event_queue.top().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. while (!paused && !event.IsSet() && wait_time > 0) {
  217. wait_time = *next_time - GetGlobalTimeNs().count();
  218. if (wait_time >= timer_resolution_ns) {
  219. Common::Windows::SleepForOneTick();
  220. } else {
  221. #ifdef ARCHITECTURE_x86_64
  222. Common::X64::MicroSleep();
  223. #else
  224. std::this_thread::yield();
  225. #endif
  226. }
  227. }
  228. if (event.IsSet()) {
  229. event.Reset();
  230. }
  231. #else
  232. event.WaitFor(std::chrono::nanoseconds(wait_time));
  233. #endif
  234. }
  235. } else {
  236. // Queue is empty, wait until another event is scheduled and signals us to
  237. // continue.
  238. wait_set = true;
  239. event.Wait();
  240. }
  241. wait_set = false;
  242. }
  243. paused_set = true;
  244. pause_event.Wait();
  245. }
  246. }
  247. void CoreTiming::Reset() {
  248. paused = true;
  249. shutting_down = true;
  250. pause_event.Set();
  251. event.Set();
  252. if (timer_thread) {
  253. timer_thread->join();
  254. }
  255. timer_thread.reset();
  256. has_started = false;
  257. }
  258. std::chrono::nanoseconds CoreTiming::GetGlobalTimeNs() const {
  259. if (is_multicore) [[likely]] {
  260. return clock->GetTimeNS();
  261. }
  262. return std::chrono::nanoseconds{Common::WallClock::CPUTickToNS(cpu_ticks)};
  263. }
  264. std::chrono::microseconds CoreTiming::GetGlobalTimeUs() const {
  265. if (is_multicore) [[likely]] {
  266. return clock->GetTimeUS();
  267. }
  268. return std::chrono::microseconds{Common::WallClock::CPUTickToUS(cpu_ticks)};
  269. }
  270. #ifdef _WIN32
  271. void CoreTiming::SetTimerResolutionNs(std::chrono::nanoseconds ns) {
  272. timer_resolution_ns = ns.count();
  273. }
  274. #endif
  275. } // namespace Core::Timing