core_timing.h 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  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 <condition_variable>
  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/wall_clock.h"
  16. namespace Core::Timing {
  17. /// A callback that may be scheduled for a particular core timing event.
  18. using TimedCallback =
  19. std::function<void(std::uintptr_t user_data, 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. mutable std::mutex guard;
  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. void UnscheduleEvent(const std::shared_ptr<EventType>& event_type, std::uintptr_t user_data);
  79. /// We only permit one event of each type in the queue at a time.
  80. void RemoveEvent(const std::shared_ptr<EventType>& event_type);
  81. void AddTicks(u64 ticks_to_add);
  82. void ResetTicks();
  83. void Idle();
  84. s64 GetDowncount() const {
  85. return downcount;
  86. }
  87. /// Returns current time in emulated CPU cycles
  88. u64 GetCPUTicks() const;
  89. /// Returns current time in emulated in Clock cycles
  90. u64 GetClockTicks() const;
  91. /// Returns current time in microseconds.
  92. std::chrono::microseconds GetGlobalTimeUs() const;
  93. /// Returns current time in nanoseconds.
  94. std::chrono::nanoseconds GetGlobalTimeNs() const;
  95. /// Checks for events manually and returns time in nanoseconds for next event, threadsafe.
  96. std::optional<s64> Advance();
  97. private:
  98. struct Event;
  99. /// Clear all pending events. This should ONLY be done on exit.
  100. void ClearPendingEvents();
  101. static void ThreadEntry(CoreTiming& instance, size_t id);
  102. void ThreadLoop();
  103. std::unique_ptr<Common::WallClock> clock;
  104. u64 global_timer = 0;
  105. // The queue is a min-heap using std::make_heap/push_heap/pop_heap.
  106. // We don't use std::priority_queue because we need to be able to serialize, unserialize and
  107. // erase arbitrary events (RemoveEvent()) regardless of the queue order. These aren't
  108. // accomodated by the standard adaptor class.
  109. std::vector<Event> event_queue;
  110. u64 event_fifo_id = 0;
  111. std::atomic<size_t> pending_events{};
  112. std::shared_ptr<EventType> ev_lost;
  113. std::atomic<bool> has_started{};
  114. std::function<void()> on_thread_init{};
  115. std::vector<std::thread> worker_threads;
  116. std::condition_variable event_cv;
  117. std::condition_variable wait_pause_cv;
  118. std::condition_variable wait_signal_cv;
  119. mutable std::mutex event_mutex;
  120. mutable std::mutex sequence_mutex;
  121. std::atomic<bool> paused_state{};
  122. bool is_paused{};
  123. bool shutting_down{};
  124. bool is_multicore{};
  125. size_t pause_count{};
  126. /// Cycle timing
  127. u64 ticks{};
  128. s64 downcount{};
  129. };
  130. /// Creates a core timing event with the given name and callback.
  131. ///
  132. /// @param name The name of the core timing event to create.
  133. /// @param callback The callback to execute for the event.
  134. ///
  135. /// @returns An EventType instance representing the created event.
  136. ///
  137. std::shared_ptr<EventType> CreateEvent(std::string name, TimedCallback&& callback);
  138. } // namespace Core::Timing