core_timing.cpp 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. // Copyright 2008 Dolphin Emulator Project / 2017 Citra Emulator Project
  2. // Licensed under GPLv2+
  3. // Refer to the license.txt file included.
  4. #include "core/core_timing.h"
  5. #include <algorithm>
  6. #include <mutex>
  7. #include <string>
  8. #include <tuple>
  9. #include <unordered_map>
  10. #include <vector>
  11. #include "common/assert.h"
  12. #include "common/thread.h"
  13. #include "common/threadsafe_queue.h"
  14. #include "core/core_timing_util.h"
  15. namespace CoreTiming {
  16. static s64 global_timer;
  17. static int slice_length;
  18. static int downcount;
  19. struct EventType {
  20. TimedCallback callback;
  21. const std::string* name;
  22. };
  23. struct Event {
  24. s64 time;
  25. u64 fifo_order;
  26. u64 userdata;
  27. const EventType* type;
  28. };
  29. // Sort by time, unless the times are the same, in which case sort by the order added to the queue
  30. static 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. static 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. // unordered_map stores each element separately as a linked list node so pointers to elements
  37. // remain stable regardless of rehashes/resizing.
  38. static std::unordered_map<std::string, EventType> event_types;
  39. // The queue is a min-heap using std::make_heap/push_heap/pop_heap.
  40. // We don't use std::priority_queue because we need to be able to serialize, unserialize and
  41. // erase arbitrary events (RemoveEvent()) regardless of the queue order. These aren't accomodated
  42. // by the standard adaptor class.
  43. static std::vector<Event> event_queue;
  44. static u64 event_fifo_id;
  45. // the queue for storing the events from other threads threadsafe until they will be added
  46. // to the event_queue by the emu thread
  47. static Common::MPSCQueue<Event, false> ts_queue;
  48. constexpr int MAX_SLICE_LENGTH = 20000;
  49. static s64 idled_cycles;
  50. // Are we in a function that has been called from Advance()
  51. // If events are sheduled from a function that gets called from Advance(),
  52. // don't change slice_length and downcount.
  53. static bool is_global_timer_sane;
  54. static EventType* ev_lost = nullptr;
  55. static void EmptyTimedCallback(u64 userdata, s64 cyclesLate) {}
  56. EventType* RegisterEvent(const std::string& name, TimedCallback callback) {
  57. // check for existing type with same name.
  58. // we want event type names to remain unique so that we can use them for serialization.
  59. ASSERT_MSG(event_types.find(name) == event_types.end(),
  60. "CoreTiming Event \"{}\" is already registered. Events should only be registered "
  61. "during Init to avoid breaking save states.",
  62. name.c_str());
  63. auto info = event_types.emplace(name, EventType{callback, nullptr});
  64. EventType* event_type = &info.first->second;
  65. event_type->name = &info.first->first;
  66. return event_type;
  67. }
  68. void UnregisterAllEvents() {
  69. ASSERT_MSG(event_queue.empty(), "Cannot unregister events with events pending");
  70. event_types.clear();
  71. }
  72. void Init() {
  73. downcount = MAX_SLICE_LENGTH;
  74. slice_length = MAX_SLICE_LENGTH;
  75. global_timer = 0;
  76. idled_cycles = 0;
  77. // The time between CoreTiming being intialized and the first call to Advance() is considered
  78. // the slice boundary between slice -1 and slice 0. Dispatcher loops must call Advance() before
  79. // executing the first cycle of each slice to prepare the slice length and downcount for
  80. // that slice.
  81. is_global_timer_sane = true;
  82. event_fifo_id = 0;
  83. ev_lost = RegisterEvent("_lost_event", &EmptyTimedCallback);
  84. }
  85. void Shutdown() {
  86. MoveEvents();
  87. ClearPendingEvents();
  88. UnregisterAllEvents();
  89. }
  90. // This should only be called from the CPU thread. If you are calling
  91. // it from any other thread, you are doing something evil
  92. u64 GetTicks() {
  93. u64 ticks = static_cast<u64>(global_timer);
  94. if (!is_global_timer_sane) {
  95. ticks += slice_length - downcount;
  96. }
  97. return ticks;
  98. }
  99. void AddTicks(u64 ticks) {
  100. downcount -= static_cast<int>(ticks);
  101. }
  102. u64 GetIdleTicks() {
  103. return static_cast<u64>(idled_cycles);
  104. }
  105. void ClearPendingEvents() {
  106. event_queue.clear();
  107. }
  108. void ScheduleEvent(s64 cycles_into_future, const EventType* event_type, u64 userdata) {
  109. ASSERT(event_type != nullptr);
  110. s64 timeout = GetTicks() + cycles_into_future;
  111. // If this event needs to be scheduled before the next advance(), force one early
  112. if (!is_global_timer_sane)
  113. ForceExceptionCheck(cycles_into_future);
  114. event_queue.emplace_back(Event{timeout, event_fifo_id++, userdata, event_type});
  115. std::push_heap(event_queue.begin(), event_queue.end(), std::greater<>());
  116. }
  117. void ScheduleEventThreadsafe(s64 cycles_into_future, const EventType* event_type, u64 userdata) {
  118. ts_queue.Push(Event{global_timer + cycles_into_future, 0, userdata, event_type});
  119. }
  120. void UnscheduleEvent(const EventType* event_type, u64 userdata) {
  121. auto itr = std::remove_if(event_queue.begin(), event_queue.end(), [&](const Event& e) {
  122. return e.type == event_type && e.userdata == userdata;
  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. void RemoveEvent(const EventType* event_type) {
  131. auto itr = std::remove_if(event_queue.begin(), event_queue.end(),
  132. [&](const Event& e) { return e.type == event_type; });
  133. // Removing random items breaks the invariant so we have to re-establish it.
  134. if (itr != event_queue.end()) {
  135. event_queue.erase(itr, event_queue.end());
  136. std::make_heap(event_queue.begin(), event_queue.end(), std::greater<>());
  137. }
  138. }
  139. void RemoveNormalAndThreadsafeEvent(const EventType* event_type) {
  140. MoveEvents();
  141. RemoveEvent(event_type);
  142. }
  143. void ForceExceptionCheck(s64 cycles) {
  144. cycles = std::max<s64>(0, cycles);
  145. if (downcount > cycles) {
  146. // downcount is always (much) smaller than MAX_INT so we can safely cast cycles to an int
  147. // here. Account for cycles already executed by adjusting the g.slice_length
  148. slice_length -= downcount - static_cast<int>(cycles);
  149. downcount = static_cast<int>(cycles);
  150. }
  151. }
  152. void MoveEvents() {
  153. for (Event ev; ts_queue.Pop(ev);) {
  154. ev.fifo_order = event_fifo_id++;
  155. event_queue.emplace_back(std::move(ev));
  156. std::push_heap(event_queue.begin(), event_queue.end(), std::greater<>());
  157. }
  158. }
  159. void Advance() {
  160. MoveEvents();
  161. int cycles_executed = slice_length - downcount;
  162. global_timer += cycles_executed;
  163. slice_length = MAX_SLICE_LENGTH;
  164. is_global_timer_sane = true;
  165. while (!event_queue.empty() && event_queue.front().time <= global_timer) {
  166. Event evt = std::move(event_queue.front());
  167. std::pop_heap(event_queue.begin(), event_queue.end(), std::greater<>());
  168. event_queue.pop_back();
  169. evt.type->callback(evt.userdata, static_cast<int>(global_timer - evt.time));
  170. }
  171. is_global_timer_sane = false;
  172. // Still events left (scheduled in the future)
  173. if (!event_queue.empty()) {
  174. slice_length = static_cast<int>(
  175. std::min<s64>(event_queue.front().time - global_timer, MAX_SLICE_LENGTH));
  176. }
  177. downcount = slice_length;
  178. }
  179. void Idle() {
  180. idled_cycles += downcount;
  181. downcount = 0;
  182. }
  183. std::chrono::microseconds GetGlobalTimeUs() {
  184. return std::chrono::microseconds{GetTicks() * 1000000 / BASE_CLOCK_RATE};
  185. }
  186. int GetDowncount() {
  187. return downcount;
  188. }
  189. } // namespace CoreTiming