core_timing.cpp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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::weak_ptr<EventType> type;
  25. s64 reschedule_time;
  26. heap_t::handle_type handle{};
  27. // Sort by time, unless the times are the same, in which case sort by
  28. // the order added to the queue
  29. friend bool operator>(const Event& left, const Event& right) {
  30. return std::tie(left.time, left.fifo_order) > std::tie(right.time, right.fifo_order);
  31. }
  32. friend bool operator<(const Event& left, const Event& right) {
  33. return std::tie(left.time, left.fifo_order) < std::tie(right.time, right.fifo_order);
  34. }
  35. };
  36. CoreTiming::CoreTiming() : clock{Common::CreateOptimalClock()} {}
  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::High);
  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. cpu_ticks = 0;
  55. if (is_multicore) {
  56. timer_thread = std::make_unique<std::jthread>(ThreadEntry, std::ref(*this));
  57. }
  58. }
  59. void CoreTiming::ClearPendingEvents() {
  60. std::scoped_lock lock{advance_lock, basic_lock};
  61. event_queue.clear();
  62. event.Set();
  63. }
  64. void CoreTiming::Pause(bool is_paused) {
  65. paused = is_paused;
  66. pause_event.Set();
  67. if (!is_paused) {
  68. pause_end_time = GetGlobalTimeNs().count();
  69. }
  70. }
  71. void CoreTiming::SyncPause(bool is_paused) {
  72. if (is_paused == paused && paused_set == paused) {
  73. return;
  74. }
  75. Pause(is_paused);
  76. if (timer_thread) {
  77. if (!is_paused) {
  78. pause_event.Set();
  79. }
  80. event.Set();
  81. while (paused_set != is_paused)
  82. ;
  83. }
  84. if (!is_paused) {
  85. pause_end_time = GetGlobalTimeNs().count();
  86. }
  87. }
  88. bool CoreTiming::IsRunning() const {
  89. return !paused_set;
  90. }
  91. bool CoreTiming::HasPendingEvents() const {
  92. std::scoped_lock lock{basic_lock};
  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, bool absolute_time) {
  97. {
  98. std::scoped_lock scope{basic_lock};
  99. const auto next_time{absolute_time ? ns_into_future : GetGlobalTimeNs() + ns_into_future};
  100. auto h{event_queue.emplace(Event{next_time.count(), event_fifo_id++, event_type, 0})};
  101. (*h).handle = h;
  102. }
  103. event.Set();
  104. }
  105. void CoreTiming::ScheduleLoopingEvent(std::chrono::nanoseconds start_time,
  106. std::chrono::nanoseconds resched_time,
  107. const std::shared_ptr<EventType>& event_type,
  108. bool absolute_time) {
  109. {
  110. std::scoped_lock scope{basic_lock};
  111. const auto next_time{absolute_time ? start_time : GetGlobalTimeNs() + start_time};
  112. auto h{event_queue.emplace(
  113. Event{next_time.count(), event_fifo_id++, event_type, resched_time.count()})};
  114. (*h).handle = h;
  115. }
  116. event.Set();
  117. }
  118. void CoreTiming::UnscheduleEvent(const std::shared_ptr<EventType>& event_type,
  119. UnscheduleEventType type) {
  120. {
  121. std::scoped_lock lk{basic_lock};
  122. std::vector<heap_t::handle_type> to_remove;
  123. for (auto itr = event_queue.begin(); itr != event_queue.end(); itr++) {
  124. const Event& e = *itr;
  125. if (e.type.lock().get() == event_type.get()) {
  126. to_remove.push_back(itr->handle);
  127. }
  128. }
  129. for (auto& h : to_remove) {
  130. event_queue.erase(h);
  131. }
  132. event_type->sequence_number++;
  133. }
  134. // Force any in-progress events to finish
  135. if (type == UnscheduleEventType::Wait) {
  136. std::scoped_lock lk{advance_lock};
  137. }
  138. }
  139. void CoreTiming::AddTicks(u64 ticks_to_add) {
  140. cpu_ticks += ticks_to_add;
  141. downcount -= static_cast<s64>(cpu_ticks);
  142. }
  143. void CoreTiming::Idle() {
  144. cpu_ticks += 1000U;
  145. }
  146. void CoreTiming::ResetTicks() {
  147. downcount = MAX_SLICE_LENGTH;
  148. }
  149. u64 CoreTiming::GetClockTicks() const {
  150. if (is_multicore) [[likely]] {
  151. return clock->GetCNTPCT();
  152. }
  153. return Common::WallClock::CPUTickToCNTPCT(cpu_ticks);
  154. }
  155. u64 CoreTiming::GetGPUTicks() const {
  156. if (is_multicore) [[likely]] {
  157. return clock->GetGPUTick();
  158. }
  159. return Common::WallClock::CPUTickToGPUTick(cpu_ticks);
  160. }
  161. std::optional<s64> CoreTiming::Advance() {
  162. std::scoped_lock lock{advance_lock, basic_lock};
  163. global_timer = GetGlobalTimeNs().count();
  164. while (!event_queue.empty() && event_queue.top().time <= global_timer) {
  165. const Event& evt = event_queue.top();
  166. if (const auto event_type{evt.type.lock()}) {
  167. const auto evt_time = evt.time;
  168. const auto evt_sequence_num = event_type->sequence_number;
  169. if (evt.reschedule_time == 0) {
  170. event_queue.pop();
  171. basic_lock.unlock();
  172. event_type->callback(
  173. evt_time, std::chrono::nanoseconds{GetGlobalTimeNs().count() - evt_time});
  174. basic_lock.lock();
  175. } else {
  176. basic_lock.unlock();
  177. const auto new_schedule_time{event_type->callback(
  178. evt_time, std::chrono::nanoseconds{GetGlobalTimeNs().count() - evt_time})};
  179. basic_lock.lock();
  180. if (evt_sequence_num != event_type->sequence_number) {
  181. // Heap handle is invalidated after external modification.
  182. continue;
  183. }
  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.type,
  194. 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