core_timing.cpp 7.5 KB

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