core_timing.h 6.1 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 <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. using PauseCallback = std::function<void(bool paused)>;
  21. /// Contains the characteristics of a particular event.
  22. struct EventType {
  23. explicit EventType(TimedCallback&& callback_, std::string&& name_)
  24. : callback{std::move(callback_)}, name{std::move(name_)} {}
  25. /// The event's callback function.
  26. TimedCallback callback;
  27. /// A pointer to the name of the event.
  28. const std::string name;
  29. };
  30. /**
  31. * This is a system to schedule events into the emulated machine's future. Time is measured
  32. * in main CPU clock cycles.
  33. *
  34. * To schedule an event, you first have to register its type. This is where you pass in the
  35. * callback. You then schedule events using the type ID you get back.
  36. *
  37. * The s64 ns_late that the callbacks get is how many ns late it was.
  38. * So to schedule a new event on a regular basis:
  39. * inside callback:
  40. * ScheduleEvent(period_in_ns - ns_late, callback, "whatever")
  41. */
  42. class CoreTiming {
  43. public:
  44. CoreTiming();
  45. ~CoreTiming();
  46. CoreTiming(const CoreTiming&) = delete;
  47. CoreTiming(CoreTiming&&) = delete;
  48. CoreTiming& operator=(const CoreTiming&) = delete;
  49. CoreTiming& operator=(CoreTiming&&) = delete;
  50. /// CoreTiming begins at the boundary of timing slice -1. An initial call to Advance() is
  51. /// required to end slice - 1 and start slice 0 before the first cycle of code is executed.
  52. void Initialize(std::function<void()>&& on_thread_init_);
  53. /// Tears down all timing related functionality.
  54. void Shutdown();
  55. /// Sets if emulation is multicore or single core, must be set before Initialize
  56. void SetMulticore(bool is_multicore_) {
  57. is_multicore = is_multicore_;
  58. }
  59. /// Check if it's using host timing.
  60. bool IsHostTiming() const {
  61. return is_multicore;
  62. }
  63. /// Pauses/Unpauses the execution of the timer thread.
  64. void Pause(bool is_paused);
  65. /// Pauses/Unpauses the execution of the timer thread and waits until paused.
  66. void SyncPause(bool is_paused);
  67. /// Checks if core timing is running.
  68. bool IsRunning() const;
  69. /// Checks if the timer thread has started.
  70. bool HasStarted() const {
  71. return has_started;
  72. }
  73. /// Checks if there are any pending time events.
  74. bool HasPendingEvents() const;
  75. /// Schedules an event in core timing
  76. void ScheduleEvent(std::chrono::nanoseconds ns_into_future,
  77. const std::shared_ptr<EventType>& event_type, std::uintptr_t user_data = 0,
  78. bool absolute_time = false);
  79. /// Schedules an event which will automatically re-schedule itself with the given time, until
  80. /// unscheduled
  81. void ScheduleLoopingEvent(std::chrono::nanoseconds start_time,
  82. std::chrono::nanoseconds resched_time,
  83. const std::shared_ptr<EventType>& event_type,
  84. std::uintptr_t user_data = 0, bool absolute_time = false);
  85. void UnscheduleEvent(const std::shared_ptr<EventType>& event_type, std::uintptr_t user_data);
  86. /// We only permit one event of each type in the queue at a time.
  87. void RemoveEvent(const std::shared_ptr<EventType>& event_type);
  88. void AddTicks(u64 ticks_to_add);
  89. void ResetTicks();
  90. void Idle();
  91. s64 GetDowncount() const {
  92. return downcount;
  93. }
  94. /// Returns current time in emulated CPU cycles
  95. u64 GetCPUTicks() const;
  96. /// Returns current time in emulated in Clock cycles
  97. u64 GetClockTicks() 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. /// Register a callback function to be called when coretiming pauses.
  105. void RegisterPauseCallback(PauseCallback&& callback);
  106. private:
  107. struct Event;
  108. /// Clear all pending events. This should ONLY be done on exit.
  109. void ClearPendingEvents();
  110. static void ThreadEntry(CoreTiming& instance);
  111. void ThreadLoop();
  112. std::unique_ptr<Common::WallClock> clock;
  113. s64 global_timer = 0;
  114. // The queue is a min-heap using std::make_heap/push_heap/pop_heap.
  115. // We don't use std::priority_queue because we need to be able to serialize, unserialize and
  116. // erase arbitrary events (RemoveEvent()) regardless of the queue order. These aren't
  117. // accomodated by the standard adaptor class.
  118. std::vector<Event> event_queue;
  119. u64 event_fifo_id = 0;
  120. std::shared_ptr<EventType> ev_lost;
  121. Common::Event event{};
  122. Common::Event pause_event{};
  123. std::mutex basic_lock;
  124. std::mutex advance_lock;
  125. std::unique_ptr<std::thread> 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 ticks{};
  136. s64 downcount{};
  137. std::vector<PauseCallback> pause_callbacks{};
  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