query_cache.h 13 KB

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