core_timing.cpp 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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. // the queue for unscheduling the events from other threads threadsafe
  49. static Common::MPSCQueue<std::pair<const EventType*, u64>, false> unschedule_queue;
  50. constexpr int MAX_SLICE_LENGTH = 20000;
  51. static s64 idled_cycles;
  52. // Are we in a function that has been called from Advance()
  53. // If events are sheduled from a function that gets called from Advance(),
  54. // don't change slice_length and downcount.
  55. static bool is_global_timer_sane;
  56. static EventType* ev_lost = nullptr;
  57. static void EmptyTimedCallback(u64 userdata, s64 cyclesLate) {}
  58. EventType* RegisterEvent(const std::string& name, TimedCallback callback) {
  59. // check for existing type with same name.
  60. // we want event type names to remain unique so that we can use them for serialization.
  61. ASSERT_MSG(event_types.find(name) == event_types.end(),
  62. "CoreTiming Event \"{}\" is already registered. Events should only be registered "
  63. "during Init to avoid breaking save states.",
  64. name.c_str());
  65. auto info = event_types.emplace(name, EventType{callback, nullptr});
  66. EventType* event_type = &info.first->second;
  67. event_type->name = &info.first->first;
  68. return event_type;
  69. }
  70. void UnregisterAllEvents() {
  71. ASSERT_MSG(event_queue.empty(), "Cannot unregister events with events pending");
  72. event_types.clear();
  73. }
  74. void Init() {
  75. downcount = MAX_SLICE_LENGTH;
  76. slice_length = MAX_SLICE_LENGTH;
  77. global_timer = 0;
  78. idled_cycles = 0;
  79. // The time between CoreTiming being intialized and the first call to Advance() is considered
  80. // the slice boundary between slice -1 and slice 0. Dispatcher loops must call Advance() before
  81. // executing the first cycle of each slice to prepare the slice length and downcount for
  82. // that slice.
  83. is_global_timer_sane = true;
  84. event_fifo_id = 0;
  85. ev_lost = RegisterEvent("_lost_event", &EmptyTimedCallback);
  86. }
  87. void Shutdown() {
  88. MoveEvents();
  89. ClearPendingEvents();
  90. UnregisterAllEvents();
  91. }
  92. // This should only be called from the CPU thread. If you are calling
  93. // it from any other thread, you are doing something evil
  94. u64 GetTicks() {
  95. u64 ticks = static_cast<u64>(global_timer);
  96. if (!is_global_timer_sane) {
  97. ticks += slice_length - downcount;
  98. }
  99. return ticks;
  100. }
  101. void AddTicks(u64 ticks) {
  102. downcount -= static_cast<int>(ticks);
  103. }
  104. u64 GetIdleTicks() {
  105. return static_cast<u64>(idled_cycles);
  106. }
  107. void ClearPendingEvents() {
  108. event_queue.clear();
  109. }
  110. void ScheduleEvent(s64 cycles_into_future, const EventType* event_type, u64 userdata) {
  111. ASSERT(event_type != nullptr);
  112. s64 timeout = GetTicks() + cycles_into_future;
  113. // If this event needs to be scheduled before the next advance(), force one early
  114. if (!is_global_timer_sane)
  115. ForceExceptionCheck(cycles_into_future);
  116. event_queue.emplace_back(Event{timeout, event_fifo_id++, userdata, event_type});
  117. std::push_heap(event_queue.begin(), event_queue.end(), std::greater<>());
  118. }
  119. void ScheduleEventThreadsafe(s64 cycles_into_future, const EventType* event_type, u64 userdata) {
  120. ts_queue.Push(Event{global_timer + cycles_into_future, 0, userdata, event_type});
  121. }
  122. void UnscheduleEvent(const EventType* event_type, u64 userdata) {
  123. auto itr = std::remove_if(event_queue.begin(), event_queue.end(), [&](const Event& e) {
  124. return e.type == event_type && e.userdata == userdata;
  125. });
  126. // Removing random items breaks the invariant so we have to re-establish it.
  127. if (itr != event_queue.end()) {
  128. event_queue.erase(itr, event_queue.end());
  129. std::make_heap(event_queue.begin(), event_queue.end(), std::greater<>());
  130. }
  131. }
  132. void UnscheduleEventThreadsafe(const EventType* event_type, u64 userdata) {
  133. unschedule_queue.Push(std::make_pair(event_type, userdata));
  134. }
  135. void RemoveEvent(const EventType* event_type) {
  136. auto itr = std::remove_if(event_queue.begin(), event_queue.end(),
  137. [&](const Event& e) { return e.type == event_type; });
  138. // Removing random items breaks the invariant so we have to re-establish it.
  139. if (itr != event_queue.end()) {
  140. event_queue.erase(itr, event_queue.end());
  141. std::make_heap(event_queue.begin(), event_queue.end(), std::greater<>());
  142. }
  143. }
  144. void RemoveNormalAndThreadsafeEvent(const EventType* event_type) {
  145. MoveEvents();
  146. RemoveEvent(event_type);
  147. }
  148. void ForceExceptionCheck(s64 cycles) {
  149. cycles = std::max<s64>(0, cycles);
  150. if (downcount > cycles) {
  151. // downcount is always (much) smaller than MAX_INT so we can safely cast cycles to an int
  152. // here. Account for cycles already executed by adjusting the g.slice_length
  153. slice_length -= downcount - static_cast<int>(cycles);
  154. downcount = static_cast<int>(cycles);
  155. }
  156. }
  157. void MoveEvents() {
  158. for (Event ev; ts_queue.Pop(ev);) {
  159. ev.fifo_order = event_fifo_id++;
  160. event_queue.emplace_back(std::move(ev));
  161. std::push_heap(event_queue.begin(), event_queue.end(), std::greater<>());
  162. }
  163. }
  164. void Advance() {
  165. MoveEvents();
  166. for (std::pair<const EventType*, u64> ev; unschedule_queue.Pop(ev);) {
  167. UnscheduleEvent(ev.first, ev.second);
  168. }
  169. int cycles_executed = slice_length - downcount;
  170. global_timer += cycles_executed;
  171. slice_length = MAX_SLICE_LENGTH;
  172. is_global_timer_sane = true;
  173. while (!event_queue.empty() && event_queue.front().time <= global_timer) {
  174. Event evt = std::move(event_queue.front());
  175. std::pop_heap(event_queue.begin(), event_queue.end(), std::greater<>());
  176. event_queue.pop_back();
  177. evt.type->callback(evt.userdata, static_cast<int>(global_timer - evt.time));
  178. }
  179. is_global_timer_sane = false;
  180. // Still events left (scheduled in the future)
  181. if (!event_queue.empty()) {
  182. slice_length = static_cast<int>(
  183. std::min<s64>(event_queue.front().time - global_timer, MAX_SLICE_LENGTH));
  184. }
  185. downcount = slice_length;
  186. }
  187. void Idle() {
  188. idled_cycles += downcount;
  189. downcount = 0;
  190. }
  191. std::chrono::microseconds GetGlobalTimeUs() {
  192. return std::chrono::microseconds{GetTicks() * 1000000 / BASE_CLOCK_RATE};
  193. }
  194. int GetDowncount() {
  195. return downcount;
  196. }
  197. } // namespace CoreTiming