core_timing.h 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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 <vector>
  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. std::uintptr_t user_data, 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_)} {}
  24. /// The event's callback function.
  25. TimedCallback callback;
  26. /// A pointer to the name of the event.
  27. const std::string name;
  28. };
  29. /**
  30. * This is a system to schedule events into the emulated machine's future. Time is measured
  31. * in main CPU clock cycles.
  32. *
  33. * To schedule an event, you first have to register its type. This is where you pass in the
  34. * callback. You then schedule events using the type ID you get back.
  35. *
  36. * The s64 ns_late that the callbacks get is how many ns late it was.
  37. * So to schedule a new event on a regular basis:
  38. * inside callback:
  39. * ScheduleEvent(period_in_ns - ns_late, callback, "whatever")
  40. */
  41. class CoreTiming {
  42. public:
  43. CoreTiming();
  44. ~CoreTiming();
  45. CoreTiming(const CoreTiming&) = delete;
  46. CoreTiming(CoreTiming&&) = delete;
  47. CoreTiming& operator=(const CoreTiming&) = delete;
  48. CoreTiming& operator=(CoreTiming&&) = delete;
  49. /// CoreTiming begins at the boundary of timing slice -1. An initial call to Advance() is
  50. /// required to end slice - 1 and start slice 0 before the first cycle of code is executed.
  51. void Initialize(std::function<void()>&& on_thread_init_);
  52. /// Clear all pending events. This should ONLY be done on exit.
  53. void ClearPendingEvents();
  54. /// Sets if emulation is multicore or single core, must be set before Initialize
  55. void SetMulticore(bool is_multicore_) {
  56. is_multicore = is_multicore_;
  57. }
  58. /// Pauses/Unpauses the execution of the timer thread.
  59. void Pause(bool is_paused);
  60. /// Pauses/Unpauses the execution of the timer thread and waits until paused.
  61. void SyncPause(bool is_paused);
  62. /// Checks if core timing is running.
  63. bool IsRunning() const;
  64. /// Checks if the timer thread has started.
  65. bool HasStarted() const {
  66. return has_started;
  67. }
  68. /// Checks if there are any pending time events.
  69. bool HasPendingEvents() const;
  70. /// Schedules an event in core timing
  71. void ScheduleEvent(std::chrono::nanoseconds ns_into_future,
  72. const std::shared_ptr<EventType>& event_type, std::uintptr_t user_data = 0,
  73. bool absolute_time = false);
  74. /// Schedules an event which will automatically re-schedule itself with the given time, until
  75. /// unscheduled
  76. void ScheduleLoopingEvent(std::chrono::nanoseconds start_time,
  77. std::chrono::nanoseconds resched_time,
  78. const std::shared_ptr<EventType>& event_type,
  79. std::uintptr_t user_data = 0, bool absolute_time = false);
  80. void UnscheduleEvent(const std::shared_ptr<EventType>& event_type, std::uintptr_t user_data,
  81. bool wait = true);
  82. void UnscheduleEventWithoutWait(const std::shared_ptr<EventType>& event_type,
  83. std::uintptr_t user_data) {
  84. UnscheduleEvent(event_type, user_data, false);
  85. }
  86. void AddTicks(u64 ticks_to_add);
  87. void ResetTicks();
  88. void Idle();
  89. s64 GetDowncount() const {
  90. return downcount;
  91. }
  92. /// Returns the current CNTPCT tick value.
  93. u64 GetClockTicks() const;
  94. /// Returns the current GPU tick value.
  95. u64 GetGPUTicks() const;
  96. /// Returns current time in microseconds.
  97. std::chrono::microseconds GetGlobalTimeUs() const;
  98. /// Returns current time in nanoseconds.
  99. std::chrono::nanoseconds GetGlobalTimeNs() const;
  100. /// Checks for events manually and returns time in nanoseconds for next event, threadsafe.
  101. std::optional<s64> Advance();
  102. #ifdef _WIN32
  103. void SetTimerResolutionNs(std::chrono::nanoseconds ns);
  104. #endif
  105. private:
  106. struct Event;
  107. static void ThreadEntry(CoreTiming& instance);
  108. void ThreadLoop();
  109. void Reset();
  110. std::unique_ptr<Common::WallClock> clock;
  111. s64 global_timer = 0;
  112. #ifdef _WIN32
  113. s64 timer_resolution_ns;
  114. #endif
  115. // The queue is a min-heap using std::make_heap/push_heap/pop_heap.
  116. // We don't use std::priority_queue because we need to be able to serialize, unserialize and
  117. // erase arbitrary events (RemoveEvent()) regardless of the queue order. These aren't
  118. // accommodated by the standard adaptor class.
  119. std::vector<Event> event_queue;
  120. u64 event_fifo_id = 0;
  121. std::shared_ptr<EventType> ev_lost;
  122. Common::Event event{};
  123. Common::Event pause_event{};
  124. std::mutex basic_lock;
  125. std::mutex advance_lock;
  126. std::unique_ptr<std::jthread> timer_thread;
  127. std::atomic<bool> paused{};
  128. std::atomic<bool> paused_set{};
  129. std::atomic<bool> wait_set{};
  130. std::atomic<bool> shutting_down{};
  131. std::atomic<bool> has_started{};
  132. std::function<void()> on_thread_init{};
  133. bool is_multicore{};
  134. s64 pause_end_time{};
  135. /// Cycle timing
  136. u64 cpu_ticks{};
  137. s64 downcount{};
  138. };
  139. /// Creates a core timing event with the given name and callback.
  140. ///
  141. /// @param name The name of the core timing event to create.
  142. /// @param callback The callback to execute for the event.
  143. ///
  144. /// @returns An EventType instance representing the created event.
  145. ///
  146. std::shared_ptr<EventType> CreateEvent(std::string name, TimedCallback&& callback);
  147. } // namespace Core::Timing