query_cache.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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 "core/core.h"
  17. #include "core/settings.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 QueryPool>
  81. class QueryCacheBase {
  82. public:
  83. explicit QueryCacheBase(Core::System& system, VideoCore::RasterizerInterface& rasterizer)
  84. : system{system}, rasterizer{rasterizer}, streams{{CounterStream{
  85. 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. auto& memory_manager = system.GPU().MemoryManager();
  104. const std::optional<VAddr> cpu_addr_opt = memory_manager.GpuToCpuAddress(gpu_addr);
  105. ASSERT(cpu_addr_opt);
  106. VAddr cpu_addr = *cpu_addr_opt;
  107. CachedQuery* query = TryGet(cpu_addr);
  108. if (!query) {
  109. ASSERT_OR_EXECUTE(cpu_addr_opt, return;);
  110. const auto host_ptr = memory_manager.GetPointer(gpu_addr);
  111. query = Register(type, cpu_addr, host_ptr, timestamp.has_value());
  112. }
  113. query->BindCounter(Stream(type).Current(), timestamp);
  114. if (Settings::values.use_asynchronous_gpu_emulation) {
  115. AsyncFlushQuery(cpu_addr);
  116. }
  117. }
  118. /// Updates counters from GPU state. Expected to be called once per draw, clear or dispatch.
  119. void UpdateCounters() {
  120. std::unique_lock lock{mutex};
  121. const auto& regs = system.GPU().Maxwell3D().regs;
  122. Stream(VideoCore::QueryType::SamplesPassed).Update(regs.samplecnt_enable);
  123. }
  124. /// Resets a counter to zero. It doesn't disable the query after resetting.
  125. void ResetCounter(VideoCore::QueryType type) {
  126. std::unique_lock lock{mutex};
  127. Stream(type).Reset();
  128. }
  129. /// Disable all active streams. Expected to be called at the end of a command buffer.
  130. void DisableStreams() {
  131. std::unique_lock lock{mutex};
  132. for (auto& stream : streams) {
  133. stream.Update(false);
  134. }
  135. }
  136. /// Returns a new host counter.
  137. std::shared_ptr<HostCounter> Counter(std::shared_ptr<HostCounter> dependency,
  138. VideoCore::QueryType type) {
  139. return std::make_shared<HostCounter>(static_cast<QueryCache&>(*this), std::move(dependency),
  140. type);
  141. }
  142. /// Returns the counter stream of the specified type.
  143. CounterStream& Stream(VideoCore::QueryType type) {
  144. return streams[static_cast<std::size_t>(type)];
  145. }
  146. /// Returns the counter stream of the specified type.
  147. const CounterStream& Stream(VideoCore::QueryType type) const {
  148. return streams[static_cast<std::size_t>(type)];
  149. }
  150. void CommitAsyncFlushes() {
  151. committed_flushes.push_back(uncommitted_flushes);
  152. uncommitted_flushes.reset();
  153. }
  154. bool HasUncommittedFlushes() const {
  155. return uncommitted_flushes != nullptr;
  156. }
  157. bool ShouldWaitAsyncFlushes() const {
  158. if (committed_flushes.empty()) {
  159. return false;
  160. }
  161. return committed_flushes.front() != nullptr;
  162. }
  163. void PopAsyncFlushes() {
  164. if (committed_flushes.empty()) {
  165. return;
  166. }
  167. auto& flush_list = committed_flushes.front();
  168. if (!flush_list) {
  169. committed_flushes.pop_front();
  170. return;
  171. }
  172. for (VAddr query_address : *flush_list) {
  173. FlushAndRemoveRegion(query_address, 4);
  174. }
  175. committed_flushes.pop_front();
  176. }
  177. protected:
  178. std::array<QueryPool, VideoCore::NumQueryTypes> query_pools;
  179. private:
  180. /// Flushes a memory range to guest memory and removes it from the cache.
  181. void FlushAndRemoveRegion(VAddr addr, std::size_t size) {
  182. const u64 addr_begin = static_cast<u64>(addr);
  183. const u64 addr_end = addr_begin + static_cast<u64>(size);
  184. const auto in_range = [addr_begin, addr_end](CachedQuery& query) {
  185. const u64 cache_begin = query.GetCpuAddr();
  186. const u64 cache_end = cache_begin + query.SizeInBytes();
  187. return cache_begin < addr_end && addr_begin < cache_end;
  188. };
  189. const u64 page_end = addr_end >> PAGE_SHIFT;
  190. for (u64 page = addr_begin >> PAGE_SHIFT; page <= page_end; ++page) {
  191. const auto& it = cached_queries.find(page);
  192. if (it == std::end(cached_queries)) {
  193. continue;
  194. }
  195. auto& contents = it->second;
  196. for (auto& query : contents) {
  197. if (!in_range(query)) {
  198. continue;
  199. }
  200. rasterizer.UpdatePagesCachedCount(query.GetCpuAddr(), query.SizeInBytes(), -1);
  201. query.Flush();
  202. }
  203. contents.erase(std::remove_if(std::begin(contents), std::end(contents), in_range),
  204. std::end(contents));
  205. }
  206. }
  207. /// Registers the passed parameters as cached and returns a pointer to the stored cached query.
  208. CachedQuery* Register(VideoCore::QueryType type, VAddr cpu_addr, u8* host_ptr, bool timestamp) {
  209. rasterizer.UpdatePagesCachedCount(cpu_addr, CachedQuery::SizeInBytes(timestamp), 1);
  210. const u64 page = static_cast<u64>(cpu_addr) >> PAGE_SHIFT;
  211. return &cached_queries[page].emplace_back(static_cast<QueryCache&>(*this), type, cpu_addr,
  212. host_ptr);
  213. }
  214. /// Tries to a get a cached query. Returns nullptr on failure.
  215. CachedQuery* TryGet(VAddr addr) {
  216. const u64 page = static_cast<u64>(addr) >> PAGE_SHIFT;
  217. const auto it = cached_queries.find(page);
  218. if (it == std::end(cached_queries)) {
  219. return nullptr;
  220. }
  221. auto& contents = it->second;
  222. const auto found = std::find_if(std::begin(contents), std::end(contents),
  223. [addr](auto& query) { return query.GetCpuAddr() == addr; });
  224. return found != std::end(contents) ? &*found : nullptr;
  225. }
  226. void AsyncFlushQuery(VAddr addr) {
  227. if (!uncommitted_flushes) {
  228. uncommitted_flushes = std::make_shared<std::unordered_set<VAddr>>();
  229. }
  230. uncommitted_flushes->insert(addr);
  231. }
  232. static constexpr std::uintptr_t PAGE_SIZE = 4096;
  233. static constexpr unsigned PAGE_SHIFT = 12;
  234. Core::System& system;
  235. VideoCore::RasterizerInterface& rasterizer;
  236. std::recursive_mutex mutex;
  237. std::unordered_map<u64, std::vector<CachedQuery>> cached_queries;
  238. std::array<CounterStream, VideoCore::NumQueryTypes> streams;
  239. std::shared_ptr<std::unordered_set<VAddr>> uncommitted_flushes{};
  240. std::list<std::shared_ptr<std::unordered_set<VAddr>>> committed_flushes;
  241. };
  242. template <class QueryCache, class HostCounter>
  243. class HostCounterBase {
  244. public:
  245. explicit HostCounterBase(std::shared_ptr<HostCounter> dependency_)
  246. : dependency{std::move(dependency_)}, depth{dependency ? (dependency->Depth() + 1) : 0} {
  247. // Avoid nesting too many dependencies to avoid a stack overflow when these are deleted.
  248. constexpr u64 depth_threshold = 96;
  249. if (depth > depth_threshold) {
  250. depth = 0;
  251. base_result = dependency->Query();
  252. dependency = nullptr;
  253. }
  254. }
  255. virtual ~HostCounterBase() = default;
  256. /// Returns the current value of the query.
  257. u64 Query() {
  258. if (result) {
  259. return *result;
  260. }
  261. u64 value = BlockingQuery() + base_result;
  262. if (dependency) {
  263. value += dependency->Query();
  264. dependency = nullptr;
  265. }
  266. result = value;
  267. return *result;
  268. }
  269. /// Returns true when flushing this query will potentially wait.
  270. bool WaitPending() const noexcept {
  271. return result.has_value();
  272. }
  273. u64 Depth() const noexcept {
  274. return depth;
  275. }
  276. protected:
  277. /// Returns the value of query from the backend API blocking as needed.
  278. virtual u64 BlockingQuery() const = 0;
  279. private:
  280. std::shared_ptr<HostCounter> dependency; ///< Counter to add to this value.
  281. std::optional<u64> result; ///< Filled with the already returned value.
  282. u64 depth; ///< Number of nested dependencies.
  283. u64 base_result = 0; ///< Equivalent to nested dependencies value.
  284. };
  285. template <class HostCounter>
  286. class CachedQueryBase {
  287. public:
  288. explicit CachedQueryBase(VAddr cpu_addr, u8* host_ptr)
  289. : cpu_addr{cpu_addr}, host_ptr{host_ptr} {}
  290. virtual ~CachedQueryBase() = default;
  291. CachedQueryBase(CachedQueryBase&&) noexcept = default;
  292. CachedQueryBase(const CachedQueryBase&) = delete;
  293. CachedQueryBase& operator=(CachedQueryBase&&) noexcept = default;
  294. CachedQueryBase& operator=(const CachedQueryBase&) = delete;
  295. /// Flushes the query to guest memory.
  296. virtual void Flush() {
  297. // When counter is nullptr it means that it's just been reseted. We are supposed to write a
  298. // zero in these cases.
  299. const u64 value = counter ? counter->Query() : 0;
  300. std::memcpy(host_ptr, &value, sizeof(u64));
  301. if (timestamp) {
  302. std::memcpy(host_ptr + TIMESTAMP_OFFSET, &*timestamp, sizeof(u64));
  303. }
  304. }
  305. /// Binds a counter to this query.
  306. void BindCounter(std::shared_ptr<HostCounter> counter_, std::optional<u64> timestamp_) {
  307. if (counter) {
  308. // If there's an old counter set it means the query is being rewritten by the game.
  309. // To avoid losing the data forever, flush here.
  310. Flush();
  311. }
  312. counter = std::move(counter_);
  313. timestamp = timestamp_;
  314. }
  315. VAddr GetCpuAddr() const noexcept {
  316. return cpu_addr;
  317. }
  318. u64 SizeInBytes() const noexcept {
  319. return SizeInBytes(timestamp.has_value());
  320. }
  321. static constexpr u64 SizeInBytes(bool with_timestamp) noexcept {
  322. return with_timestamp ? LARGE_QUERY_SIZE : SMALL_QUERY_SIZE;
  323. }
  324. protected:
  325. /// Returns true when querying the counter may potentially block.
  326. bool WaitPending() const noexcept {
  327. return counter && counter->WaitPending();
  328. }
  329. private:
  330. static constexpr std::size_t SMALL_QUERY_SIZE = 8; // Query size without timestamp.
  331. static constexpr std::size_t LARGE_QUERY_SIZE = 16; // Query size with timestamp.
  332. static constexpr std::intptr_t TIMESTAMP_OFFSET = 8; // Timestamp offset in a large query.
  333. VAddr cpu_addr; ///< Guest CPU address.
  334. u8* host_ptr; ///< Writable host pointer.
  335. std::shared_ptr<HostCounter> counter; ///< Host counter to query, owns the dependency tree.
  336. std::optional<u64> timestamp; ///< Timestamp to flush to guest memory.
  337. };
  338. } // namespace VideoCommon