query_cache.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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 <algorithm>
  6. #include <array>
  7. #include <cstring>
  8. #include <iterator>
  9. #include <memory>
  10. #include <mutex>
  11. #include <optional>
  12. #include <unordered_map>
  13. #include <unordered_set>
  14. #include <vector>
  15. #include "common/assert.h"
  16. #include "common/settings.h"
  17. #include "core/core.h"
  18. #include "video_core/engines/maxwell_3d.h"
  19. #include "video_core/gpu.h"
  20. #include "video_core/memory_manager.h"
  21. #include "video_core/rasterizer_interface.h"
  22. namespace VideoCommon {
  23. template <class QueryCache, class HostCounter>
  24. class CounterStreamBase {
  25. public:
  26. explicit CounterStreamBase(QueryCache& cache_, VideoCore::QueryType type_)
  27. : cache{cache_}, type{type_} {}
  28. /// Updates the state of the stream, enabling or disabling as needed.
  29. void Update(bool enabled) {
  30. if (enabled) {
  31. Enable();
  32. } else {
  33. Disable();
  34. }
  35. }
  36. /// Resets the stream to zero. It doesn't disable the query after resetting.
  37. void Reset() {
  38. if (current) {
  39. current->EndQuery();
  40. // Immediately start a new query to avoid disabling its state.
  41. current = cache.Counter(nullptr, type);
  42. }
  43. last = nullptr;
  44. }
  45. /// Returns the current counter slicing as needed.
  46. std::shared_ptr<HostCounter> Current() {
  47. if (!current) {
  48. return nullptr;
  49. }
  50. current->EndQuery();
  51. last = std::move(current);
  52. current = cache.Counter(last, type);
  53. return last;
  54. }
  55. /// Returns true when the counter stream is enabled.
  56. bool IsEnabled() const {
  57. return current != nullptr;
  58. }
  59. private:
  60. /// Enables the stream.
  61. void Enable() {
  62. if (current) {
  63. return;
  64. }
  65. current = cache.Counter(last, type);
  66. }
  67. // Disables the stream.
  68. void Disable() {
  69. if (current) {
  70. current->EndQuery();
  71. }
  72. last = std::exchange(current, nullptr);
  73. }
  74. QueryCache& cache;
  75. const VideoCore::QueryType type;
  76. std::shared_ptr<HostCounter> current;
  77. std::shared_ptr<HostCounter> last;
  78. };
  79. template <class QueryCache, class CachedQuery, class CounterStream, class HostCounter>
  80. class QueryCacheBase {
  81. public:
  82. explicit QueryCacheBase(VideoCore::RasterizerInterface& rasterizer_,
  83. Tegra::Engines::Maxwell3D& maxwell3d_,
  84. Tegra::MemoryManager& gpu_memory_)
  85. : rasterizer{rasterizer_}, maxwell3d{maxwell3d_},
  86. gpu_memory{gpu_memory_}, streams{{CounterStream{static_cast<QueryCache&>(*this),
  87. VideoCore::QueryType::SamplesPassed}}} {}
  88. void InvalidateRegion(VAddr addr, std::size_t size) {
  89. std::unique_lock lock{mutex};
  90. FlushAndRemoveRegion(addr, size);
  91. }
  92. void FlushRegion(VAddr addr, std::size_t size) {
  93. std::unique_lock lock{mutex};
  94. FlushAndRemoveRegion(addr, size);
  95. }
  96. /**
  97. * Records a query in GPU mapped memory, potentially marked with a timestamp.
  98. * @param gpu_addr GPU address to flush to when the mapped memory is read.
  99. * @param type Query type, e.g. SamplesPassed.
  100. * @param timestamp Timestamp, when empty the flushed query is assumed to be short.
  101. */
  102. void Query(GPUVAddr gpu_addr, VideoCore::QueryType type, std::optional<u64> timestamp) {
  103. std::unique_lock lock{mutex};
  104. const std::optional<VAddr> cpu_addr = gpu_memory.GpuToCpuAddress(gpu_addr);
  105. ASSERT(cpu_addr);
  106. CachedQuery* query = TryGet(*cpu_addr);
  107. if (!query) {
  108. ASSERT_OR_EXECUTE(cpu_addr, return;);
  109. u8* const host_ptr = gpu_memory.GetPointer(gpu_addr);
  110. query = Register(type, *cpu_addr, host_ptr, timestamp.has_value());
  111. }
  112. query->BindCounter(Stream(type).Current(), timestamp);
  113. if (Settings::values.use_asynchronous_gpu_emulation.GetValue()) {
  114. AsyncFlushQuery(*cpu_addr);
  115. }
  116. }
  117. /// Updates counters from GPU state. Expected to be called once per draw, clear or dispatch.
  118. void UpdateCounters() {
  119. std::unique_lock lock{mutex};
  120. const auto& regs = maxwell3d.regs;
  121. Stream(VideoCore::QueryType::SamplesPassed).Update(regs.samplecnt_enable);
  122. }
  123. /// Resets a counter to zero. It doesn't disable the query after resetting.
  124. void ResetCounter(VideoCore::QueryType type) {
  125. std::unique_lock lock{mutex};
  126. Stream(type).Reset();
  127. }
  128. /// Disable all active streams. Expected to be called at the end of a command buffer.
  129. void DisableStreams() {
  130. std::unique_lock lock{mutex};
  131. for (auto& stream : streams) {
  132. stream.Update(false);
  133. }
  134. }
  135. /// Returns a new host counter.
  136. std::shared_ptr<HostCounter> Counter(std::shared_ptr<HostCounter> dependency,
  137. VideoCore::QueryType type) {
  138. return std::make_shared<HostCounter>(static_cast<QueryCache&>(*this), std::move(dependency),
  139. type);
  140. }
  141. /// Returns the counter stream of the specified type.
  142. CounterStream& Stream(VideoCore::QueryType type) {
  143. return streams[static_cast<std::size_t>(type)];
  144. }
  145. /// Returns the counter stream of the specified type.
  146. const CounterStream& Stream(VideoCore::QueryType type) const {
  147. return streams[static_cast<std::size_t>(type)];
  148. }
  149. void CommitAsyncFlushes() {
  150. committed_flushes.push_back(uncommitted_flushes);
  151. uncommitted_flushes.reset();
  152. }
  153. bool HasUncommittedFlushes() const {
  154. return uncommitted_flushes != nullptr;
  155. }
  156. bool ShouldWaitAsyncFlushes() const {
  157. if (committed_flushes.empty()) {
  158. return false;
  159. }
  160. return committed_flushes.front() != nullptr;
  161. }
  162. void PopAsyncFlushes() {
  163. if (committed_flushes.empty()) {
  164. return;
  165. }
  166. auto& flush_list = committed_flushes.front();
  167. if (!flush_list) {
  168. committed_flushes.pop_front();
  169. return;
  170. }
  171. for (VAddr query_address : *flush_list) {
  172. FlushAndRemoveRegion(query_address, 4);
  173. }
  174. committed_flushes.pop_front();
  175. }
  176. private:
  177. /// Flushes a memory range to guest memory and removes it from the cache.
  178. void FlushAndRemoveRegion(VAddr addr, std::size_t size) {
  179. const u64 addr_begin = addr;
  180. const u64 addr_end = addr_begin + size;
  181. const auto in_range = [addr_begin, addr_end](const CachedQuery& query) {
  182. const u64 cache_begin = query.GetCpuAddr();
  183. const u64 cache_end = cache_begin + query.SizeInBytes();
  184. return cache_begin < addr_end && addr_begin < cache_end;
  185. };
  186. const u64 page_end = addr_end >> PAGE_BITS;
  187. for (u64 page = addr_begin >> PAGE_BITS; page <= page_end; ++page) {
  188. const auto& it = cached_queries.find(page);
  189. if (it == std::end(cached_queries)) {
  190. continue;
  191. }
  192. auto& contents = it->second;
  193. for (auto& query : contents) {
  194. if (!in_range(query)) {
  195. continue;
  196. }
  197. rasterizer.UpdatePagesCachedCount(query.GetCpuAddr(), query.SizeInBytes(), -1);
  198. query.Flush();
  199. }
  200. std::erase_if(contents, in_range);
  201. }
  202. }
  203. /// Registers the passed parameters as cached and returns a pointer to the stored cached query.
  204. CachedQuery* Register(VideoCore::QueryType type, VAddr cpu_addr, u8* host_ptr, bool timestamp) {
  205. rasterizer.UpdatePagesCachedCount(cpu_addr, CachedQuery::SizeInBytes(timestamp), 1);
  206. const u64 page = static_cast<u64>(cpu_addr) >> PAGE_BITS;
  207. return &cached_queries[page].emplace_back(static_cast<QueryCache&>(*this), type, cpu_addr,
  208. host_ptr);
  209. }
  210. /// Tries to a get a cached query. Returns nullptr on failure.
  211. CachedQuery* TryGet(VAddr addr) {
  212. const u64 page = static_cast<u64>(addr) >> PAGE_BITS;
  213. const auto it = cached_queries.find(page);
  214. if (it == std::end(cached_queries)) {
  215. return nullptr;
  216. }
  217. auto& contents = it->second;
  218. const auto found = std::find_if(std::begin(contents), std::end(contents),
  219. [addr](auto& query) { return query.GetCpuAddr() == addr; });
  220. return found != std::end(contents) ? &*found : nullptr;
  221. }
  222. void AsyncFlushQuery(VAddr addr) {
  223. if (!uncommitted_flushes) {
  224. uncommitted_flushes = std::make_shared<std::unordered_set<VAddr>>();
  225. }
  226. uncommitted_flushes->insert(addr);
  227. }
  228. static constexpr std::uintptr_t PAGE_SIZE = 4096;
  229. static constexpr unsigned PAGE_BITS = 12;
  230. VideoCore::RasterizerInterface& rasterizer;
  231. Tegra::Engines::Maxwell3D& maxwell3d;
  232. Tegra::MemoryManager& gpu_memory;
  233. std::recursive_mutex mutex;
  234. std::unordered_map<u64, std::vector<CachedQuery>> cached_queries;
  235. std::array<CounterStream, VideoCore::NumQueryTypes> streams;
  236. std::shared_ptr<std::unordered_set<VAddr>> uncommitted_flushes{};
  237. std::list<std::shared_ptr<std::unordered_set<VAddr>>> committed_flushes;
  238. };
  239. template <class QueryCache, class HostCounter>
  240. class HostCounterBase {
  241. public:
  242. explicit HostCounterBase(std::shared_ptr<HostCounter> dependency_)
  243. : dependency{std::move(dependency_)}, depth{dependency ? (dependency->Depth() + 1) : 0} {
  244. // Avoid nesting too many dependencies to avoid a stack overflow when these are deleted.
  245. constexpr u64 depth_threshold = 96;
  246. if (depth > depth_threshold) {
  247. depth = 0;
  248. base_result = dependency->Query();
  249. dependency = nullptr;
  250. }
  251. }
  252. virtual ~HostCounterBase() = default;
  253. /// Returns the current value of the query.
  254. u64 Query() {
  255. if (result) {
  256. return *result;
  257. }
  258. u64 value = BlockingQuery() + base_result;
  259. if (dependency) {
  260. value += dependency->Query();
  261. dependency = nullptr;
  262. }
  263. result = value;
  264. return *result;
  265. }
  266. /// Returns true when flushing this query will potentially wait.
  267. bool WaitPending() const noexcept {
  268. return result.has_value();
  269. }
  270. u64 Depth() const noexcept {
  271. return depth;
  272. }
  273. protected:
  274. /// Returns the value of query from the backend API blocking as needed.
  275. virtual u64 BlockingQuery() const = 0;
  276. private:
  277. std::shared_ptr<HostCounter> dependency; ///< Counter to add to this value.
  278. std::optional<u64> result; ///< Filled with the already returned value.
  279. u64 depth; ///< Number of nested dependencies.
  280. u64 base_result = 0; ///< Equivalent to nested dependencies value.
  281. };
  282. template <class HostCounter>
  283. class CachedQueryBase {
  284. public:
  285. explicit CachedQueryBase(VAddr cpu_addr_, u8* host_ptr_)
  286. : cpu_addr{cpu_addr_}, host_ptr{host_ptr_} {}
  287. virtual ~CachedQueryBase() = default;
  288. CachedQueryBase(CachedQueryBase&&) noexcept = default;
  289. CachedQueryBase(const CachedQueryBase&) = delete;
  290. CachedQueryBase& operator=(CachedQueryBase&&) noexcept = default;
  291. CachedQueryBase& operator=(const CachedQueryBase&) = delete;
  292. /// Flushes the query to guest memory.
  293. virtual void Flush() {
  294. // When counter is nullptr it means that it's just been reseted. We are supposed to write a
  295. // zero in these cases.
  296. const u64 value = counter ? counter->Query() : 0;
  297. std::memcpy(host_ptr, &value, sizeof(u64));
  298. if (timestamp) {
  299. std::memcpy(host_ptr + TIMESTAMP_OFFSET, &*timestamp, sizeof(u64));
  300. }
  301. }
  302. /// Binds a counter to this query.
  303. void BindCounter(std::shared_ptr<HostCounter> counter_, std::optional<u64> timestamp_) {
  304. if (counter) {
  305. // If there's an old counter set it means the query is being rewritten by the game.
  306. // To avoid losing the data forever, flush here.
  307. Flush();
  308. }
  309. counter = std::move(counter_);
  310. timestamp = timestamp_;
  311. }
  312. VAddr GetCpuAddr() const noexcept {
  313. return cpu_addr;
  314. }
  315. u64 SizeInBytes() const noexcept {
  316. return SizeInBytes(timestamp.has_value());
  317. }
  318. static constexpr u64 SizeInBytes(bool with_timestamp) noexcept {
  319. return with_timestamp ? LARGE_QUERY_SIZE : SMALL_QUERY_SIZE;
  320. }
  321. protected:
  322. /// Returns true when querying the counter may potentially block.
  323. bool WaitPending() const noexcept {
  324. return counter && counter->WaitPending();
  325. }
  326. private:
  327. static constexpr std::size_t SMALL_QUERY_SIZE = 8; // Query size without timestamp.
  328. static constexpr std::size_t LARGE_QUERY_SIZE = 16; // Query size with timestamp.
  329. static constexpr std::intptr_t TIMESTAMP_OFFSET = 8; // Timestamp offset in a large query.
  330. VAddr cpu_addr; ///< Guest CPU address.
  331. u8* host_ptr; ///< Writable host pointer.
  332. std::shared_ptr<HostCounter> counter; ///< Host counter to query, owns the dependency tree.
  333. std::optional<u64> timestamp; ///< Timestamp to flush to guest memory.
  334. };
  335. } // namespace VideoCommon