query_cache.h 13 KB

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