core_timing.h 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. // Copyright 2020 yuzu Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #pragma once
  5. #include <atomic>
  6. #include <chrono>
  7. #include <functional>
  8. #include <memory>
  9. #include <mutex>
  10. #include <optional>
  11. #include <string>
  12. #include <thread>
  13. #include <vector>
  14. #include "common/common_types.h"
  15. #include "common/spin_lock.h"
  16. #include "common/thread.h"
  17. #include "common/wall_clock.h"
  18. namespace Core::Timing {
  19. /// A callback that may be scheduled for a particular core timing event.
  20. using TimedCallback =
  21. std::function<void(std::uintptr_t user_data, std::chrono::nanoseconds ns_late)>;
  22. /// Contains the characteristics of a particular event.
  23. struct EventType {
  24. explicit EventType(TimedCallback&& callback_, std::string&& name_)
  25. : callback{std::move(callback_)}, name{std::move(name_)} {}
  26. /// The event's callback function.
  27. TimedCallback callback;
  28. /// A pointer to the name of the event.
  29. const std::string name;
  30. };
  31. /**
  32. * This is a system to schedule events into the emulated machine's future. Time is measured
  33. * in main CPU clock cycles.
  34. *
  35. * To schedule an event, you first have to register its type. This is where you pass in the
  36. * callback. You then schedule events using the type ID you get back.
  37. *
  38. * The s64 ns_late that the callbacks get is how many ns late it was.
  39. * So to schedule a new event on a regular basis:
  40. * inside callback:
  41. * ScheduleEvent(period_in_ns - ns_late, callback, "whatever")
  42. */
  43. class CoreTiming {
  44. public:
  45. CoreTiming();
  46. ~CoreTiming();
  47. CoreTiming(const CoreTiming&) = delete;
  48. CoreTiming(CoreTiming&&) = delete;
  49. CoreTiming& operator=(const CoreTiming&) = delete;
  50. CoreTiming& operator=(CoreTiming&&) = delete;
  51. /// CoreTiming begins at the boundary of timing slice -1. An initial call to Advance() is
  52. /// required to end slice - 1 and start slice 0 before the first cycle of code is executed.
  53. void Initialize(std::function<void()>&& on_thread_init_);
  54. /// Tears down all timing related functionality.
  55. void Shutdown();
  56. /// Sets if emulation is multicore or single core, must be set before Initialize
  57. void SetMulticore(bool is_multicore_) {
  58. is_multicore = is_multicore_;
  59. }
  60. /// Check if it's using host timing.
  61. bool IsHostTiming() const {
  62. return is_multicore;
  63. }
  64. /// Pauses/Unpauses the execution of the timer thread.
  65. void Pause(bool is_paused);
  66. /// Pauses/Unpauses the execution of the timer thread and waits until paused.
  67. void SyncPause(bool is_paused);
  68. /// Checks if core timing is running.
  69. bool IsRunning() const;
  70. /// Checks if the timer thread has started.
  71. bool HasStarted() const {
  72. return has_started;
  73. }
  74. /// Checks if there are any pending time events.
  75. bool HasPendingEvents() const;
  76. /// Schedules an event in core timing
  77. void ScheduleEvent(std::chrono::nanoseconds ns_into_future,
  78. const std::shared_ptr<EventType>& event_type, std::uintptr_t user_data = 0);
  79. void UnscheduleEvent(const std::shared_ptr<EventType>& event_type, std::uintptr_t user_data);
  80. /// We only permit one event of each type in the queue at a time.
  81. void RemoveEvent(const std::shared_ptr<EventType>& event_type);
  82. void AddTicks(u64 ticks_to_add);
  83. void ResetTicks();
  84. void Idle();
  85. s64 GetDowncount() const {
  86. return downcount;
  87. }
  88. /// Returns current time in emulated CPU cycles
  89. u64 GetCPUTicks() const;
  90. /// Returns current time in emulated in Clock cycles
  91. u64 GetClockTicks() const;
  92. /// Returns current time in microseconds.
  93. std::chrono::microseconds GetGlobalTimeUs() const;
  94. /// Returns current time in nanoseconds.
  95. std::chrono::nanoseconds GetGlobalTimeNs() const;
  96. /// Checks for events manually and returns time in nanoseconds for next event, threadsafe.
  97. std::optional<s64> Advance();
  98. private:
  99. struct Event;
  100. /// Clear all pending events. This should ONLY be done on exit.
  101. void ClearPendingEvents();
  102. static void ThreadEntry(CoreTiming& instance);
  103. void ThreadLoop();
  104. std::unique_ptr<Common::WallClock> clock;
  105. u64 global_timer = 0;
  106. // The queue is a min-heap using std::make_heap/push_heap/pop_heap.
  107. // We don't use std::priority_queue because we need to be able to serialize, unserialize and
  108. // erase arbitrary events (RemoveEvent()) regardless of the queue order. These aren't
  109. // accomodated by the standard adaptor class.
  110. std::vector<Event> event_queue;
  111. u64 event_fifo_id = 0;
  112. std::shared_ptr<EventType> ev_lost;
  113. Common::Event event{};
  114. Common::Event pause_event{};
  115. Common::SpinLock basic_lock{};
  116. Common::SpinLock advance_lock{};
  117. std::unique_ptr<std::thread> timer_thread;
  118. std::atomic<bool> paused{};
  119. std::atomic<bool> paused_set{};
  120. std::atomic<bool> wait_set{};
  121. std::atomic<bool> shutting_down{};
  122. std::atomic<bool> has_started{};
  123. std::function<void()> on_thread_init{};
  124. bool is_multicore{};
  125. /// Cycle timing
  126. u64 ticks{};
  127. s64 downcount{};
  128. };
  129. /// Creates a core timing event with the given name and callback.
  130. ///
  131. /// @param name The name of the core timing event to create.
  132. /// @param callback The callback to execute for the event.
  133. ///
  134. /// @returns An EventType instance representing the created event.
  135. ///
  136. std::shared_ptr<EventType> CreateEvent(std::string name, TimedCallback&& callback);
  137. } // namespace Core::Timing