core_timing.h 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. // SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #pragma once
  4. #include <atomic>
  5. #include <chrono>
  6. #include <functional>
  7. #include <memory>
  8. #include <mutex>
  9. #include <optional>
  10. #include <string>
  11. #include <thread>
  12. #include <boost/heap/fibonacci_heap.hpp>
  13. #include "common/common_types.h"
  14. #include "common/thread.h"
  15. #include "common/wall_clock.h"
  16. namespace Core::Timing {
  17. /// A callback that may be scheduled for a particular core timing event.
  18. using TimedCallback = std::function<std::optional<std::chrono::nanoseconds>(
  19. s64 time, std::chrono::nanoseconds ns_late)>;
  20. /// Contains the characteristics of a particular event.
  21. struct EventType {
  22. explicit EventType(TimedCallback&& callback_, std::string&& name_)
  23. : callback{std::move(callback_)}, name{std::move(name_)}, sequence_number{0} {}
  24. /// The event's callback function.
  25. TimedCallback callback;
  26. /// A pointer to the name of the event.
  27. const std::string name;
  28. /// A monotonic sequence number, incremented when this event is
  29. /// changed externally.
  30. size_t sequence_number;
  31. };
  32. enum class UnscheduleEventType {
  33. Wait,
  34. NoWait,
  35. };
  36. /**
  37. * This is a system to schedule events into the emulated machine's future. Time is measured
  38. * in main CPU clock cycles.
  39. *
  40. * To schedule an event, you first have to register its type. This is where you pass in the
  41. * callback. You then schedule events using the type ID you get back.
  42. *
  43. * The s64 ns_late that the callbacks get is how many ns late it was.
  44. * So to schedule a new event on a regular basis:
  45. * inside callback:
  46. * ScheduleEvent(period_in_ns - ns_late, callback, "whatever")
  47. */
  48. class CoreTiming {
  49. public:
  50. CoreTiming();
  51. ~CoreTiming();
  52. CoreTiming(const CoreTiming&) = delete;
  53. CoreTiming(CoreTiming&&) = delete;
  54. CoreTiming& operator=(const CoreTiming&) = delete;
  55. CoreTiming& operator=(CoreTiming&&) = delete;
  56. /// CoreTiming begins at the boundary of timing slice -1. An initial call to Advance() is
  57. /// required to end slice - 1 and start slice 0 before the first cycle of code is executed.
  58. void Initialize(std::function<void()>&& on_thread_init_);
  59. /// Clear all pending events. This should ONLY be done on exit.
  60. void ClearPendingEvents();
  61. /// Sets if emulation is multicore or single core, must be set before Initialize
  62. void SetMulticore(bool is_multicore_) {
  63. is_multicore = is_multicore_;
  64. }
  65. /// Pauses/Unpauses the execution of the timer thread.
  66. void Pause(bool is_paused);
  67. /// Pauses/Unpauses the execution of the timer thread and waits until paused.
  68. void SyncPause(bool is_paused);
  69. /// Checks if core timing is running.
  70. bool IsRunning() const;
  71. /// Checks if the timer thread has started.
  72. bool HasStarted() const {
  73. return has_started;
  74. }
  75. /// Checks if there are any pending time events.
  76. bool HasPendingEvents() const;
  77. /// Schedules an event in core timing
  78. void ScheduleEvent(std::chrono::nanoseconds ns_into_future,
  79. const std::shared_ptr<EventType>& event_type, bool absolute_time = false);
  80. /// Schedules an event which will automatically re-schedule itself with the given time, until
  81. /// unscheduled
  82. void ScheduleLoopingEvent(std::chrono::nanoseconds start_time,
  83. std::chrono::nanoseconds resched_time,
  84. const std::shared_ptr<EventType>& event_type,
  85. bool absolute_time = false);
  86. void UnscheduleEvent(const std::shared_ptr<EventType>& event_type,
  87. UnscheduleEventType type = UnscheduleEventType::Wait);
  88. void AddTicks(u64 ticks_to_add);
  89. void ResetTicks();
  90. void Idle();
  91. s64 GetDowncount() const {
  92. return downcount;
  93. }
  94. /// Returns the current CNTPCT tick value.
  95. u64 GetClockTicks() const;
  96. /// Returns the current GPU tick value.
  97. u64 GetGPUTicks() const;
  98. /// Returns current time in microseconds.
  99. std::chrono::microseconds GetGlobalTimeUs() const;
  100. /// Returns current time in nanoseconds.
  101. std::chrono::nanoseconds GetGlobalTimeNs() const;
  102. /// Checks for events manually and returns time in nanoseconds for next event, threadsafe.
  103. std::optional<s64> Advance();
  104. #ifdef _WIN32
  105. void SetTimerResolutionNs(std::chrono::nanoseconds ns);
  106. #endif
  107. private:
  108. struct Event;
  109. static void ThreadEntry(CoreTiming& instance);
  110. void ThreadLoop();
  111. void Reset();
  112. std::unique_ptr<Common::WallClock> clock;
  113. s64 global_timer = 0;
  114. #ifdef _WIN32
  115. s64 timer_resolution_ns;
  116. #endif
  117. using heap_t =
  118. boost::heap::fibonacci_heap<CoreTiming::Event, boost::heap::compare<std::greater<>>>;
  119. heap_t event_queue;
  120. u64 event_fifo_id = 0;
  121. Common::Event event{};
  122. Common::Event pause_event{};
  123. mutable std::mutex basic_lock;
  124. std::mutex advance_lock;
  125. std::unique_ptr<std::jthread> timer_thread;
  126. std::atomic<bool> paused{};
  127. std::atomic<bool> paused_set{};
  128. std::atomic<bool> wait_set{};
  129. std::atomic<bool> shutting_down{};
  130. std::atomic<bool> has_started{};
  131. std::function<void()> on_thread_init{};
  132. bool is_multicore{};
  133. s64 pause_end_time{};
  134. /// Cycle timing
  135. u64 cpu_ticks{};
  136. s64 downcount{};
  137. };
  138. /// Creates a core timing event with the given name and callback.
  139. ///
  140. /// @param name The name of the core timing event to create.
  141. /// @param callback The callback to execute for the event.
  142. ///
  143. /// @returns An EventType instance representing the created event.
  144. ///
  145. std::shared_ptr<EventType> CreateEvent(std::string name, TimedCallback&& callback);
  146. } // namespace Core::Timing