query_cache.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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/control/channel_state_cache.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 : public VideoCommon::ChannelSetupCaches<VideoCommon::ChannelInfo> {
  80. public:
  81. explicit QueryCacheBase(VideoCore::RasterizerInterface& rasterizer_)
  82. : rasterizer{rasterizer_}, streams{{CounterStream{static_cast<QueryCache&>(*this),
  83. VideoCore::QueryType::SamplesPassed}}} {}
  84. void InvalidateRegion(VAddr addr, std::size_t size) {
  85. std::unique_lock lock{mutex};
  86. FlushAndRemoveRegion(addr, size);
  87. }
  88. void FlushRegion(VAddr addr, std::size_t size) {
  89. std::unique_lock lock{mutex};
  90. FlushAndRemoveRegion(addr, size);
  91. }
  92. /**
  93. * Records a query in GPU mapped memory, potentially marked with a timestamp.
  94. * @param gpu_addr GPU address to flush to when the mapped memory is read.
  95. * @param type Query type, e.g. SamplesPassed.
  96. * @param timestamp Timestamp, when empty the flushed query is assumed to be short.
  97. */
  98. void Query(GPUVAddr gpu_addr, VideoCore::QueryType type, std::optional<u64> timestamp) {
  99. std::unique_lock lock{mutex};
  100. const std::optional<VAddr> cpu_addr = gpu_memory->GpuToCpuAddress(gpu_addr);
  101. ASSERT(cpu_addr);
  102. CachedQuery* query = TryGet(*cpu_addr);
  103. if (!query) {
  104. ASSERT_OR_EXECUTE(cpu_addr, return;);
  105. u8* const host_ptr = gpu_memory->GetPointer(gpu_addr);
  106. query = Register(type, *cpu_addr, host_ptr, timestamp.has_value());
  107. }
  108. query->BindCounter(Stream(type).Current(), timestamp);
  109. if (Settings::values.use_asynchronous_gpu_emulation.GetValue()) {
  110. AsyncFlushQuery(*cpu_addr);
  111. }
  112. }
  113. /// Updates counters from GPU state. Expected to be called once per draw, clear or dispatch.
  114. void UpdateCounters() {
  115. std::unique_lock lock{mutex};
  116. if (maxwell3d) {
  117. const auto& regs = maxwell3d->regs;
  118. Stream(VideoCore::QueryType::SamplesPassed).Update(regs.zpass_pixel_count_enable);
  119. }
  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 >> YUZU_PAGEBITS;
  185. for (u64 page = addr_begin >> YUZU_PAGEBITS; 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) >> YUZU_PAGEBITS;
  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) >> YUZU_PAGEBITS;
  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 YUZU_PAGESIZE = 4096;
  227. static constexpr unsigned YUZU_PAGEBITS = 12;
  228. VideoCore::RasterizerInterface& rasterizer;
  229. std::recursive_mutex mutex;
  230. std::unordered_map<u64, std::vector<CachedQuery>> cached_queries;
  231. std::array<CounterStream, VideoCore::NumQueryTypes> streams;
  232. std::shared_ptr<std::vector<VAddr>> uncommitted_flushes{};
  233. std::list<std::shared_ptr<std::vector<VAddr>>> committed_flushes;
  234. };
  235. template <class QueryCache, class HostCounter>
  236. class HostCounterBase {
  237. public:
  238. explicit HostCounterBase(std::shared_ptr<HostCounter> dependency_)
  239. : dependency{std::move(dependency_)}, depth{dependency ? (dependency->Depth() + 1) : 0} {
  240. // Avoid nesting too many dependencies to avoid a stack overflow when these are deleted.
  241. constexpr u64 depth_threshold = 96;
  242. if (depth > depth_threshold) {
  243. depth = 0;
  244. base_result = dependency->Query();
  245. dependency = nullptr;
  246. }
  247. }
  248. virtual ~HostCounterBase() = default;
  249. /// Returns the current value of the query.
  250. u64 Query() {
  251. if (result) {
  252. return *result;
  253. }
  254. u64 value = BlockingQuery() + base_result;
  255. if (dependency) {
  256. value += dependency->Query();
  257. dependency = nullptr;
  258. }
  259. result = value;
  260. return *result;
  261. }
  262. /// Returns true when flushing this query will potentially wait.
  263. bool WaitPending() const noexcept {
  264. return result.has_value();
  265. }
  266. u64 Depth() const noexcept {
  267. return depth;
  268. }
  269. protected:
  270. /// Returns the value of query from the backend API blocking as needed.
  271. virtual u64 BlockingQuery() const = 0;
  272. private:
  273. std::shared_ptr<HostCounter> dependency; ///< Counter to add to this value.
  274. std::optional<u64> result; ///< Filled with the already returned value.
  275. u64 depth; ///< Number of nested dependencies.
  276. u64 base_result = 0; ///< Equivalent to nested dependencies value.
  277. };
  278. template <class HostCounter>
  279. class CachedQueryBase {
  280. public:
  281. explicit CachedQueryBase(VAddr cpu_addr_, u8* host_ptr_)
  282. : cpu_addr{cpu_addr_}, host_ptr{host_ptr_} {}
  283. virtual ~CachedQueryBase() = default;
  284. CachedQueryBase(CachedQueryBase&&) noexcept = default;
  285. CachedQueryBase(const CachedQueryBase&) = delete;
  286. CachedQueryBase& operator=(CachedQueryBase&&) noexcept = default;
  287. CachedQueryBase& operator=(const CachedQueryBase&) = delete;
  288. /// Flushes the query to guest memory.
  289. virtual void Flush() {
  290. // When counter is nullptr it means that it's just been reseted. We are supposed to write a
  291. // zero in these cases.
  292. const u64 value = counter ? counter->Query() : 0;
  293. std::memcpy(host_ptr, &value, sizeof(u64));
  294. if (timestamp) {
  295. std::memcpy(host_ptr + TIMESTAMP_OFFSET, &*timestamp, sizeof(u64));
  296. }
  297. }
  298. /// Binds a counter to this query.
  299. void BindCounter(std::shared_ptr<HostCounter> counter_, std::optional<u64> timestamp_) {
  300. if (counter) {
  301. // If there's an old counter set it means the query is being rewritten by the game.
  302. // To avoid losing the data forever, flush here.
  303. Flush();
  304. }
  305. counter = std::move(counter_);
  306. timestamp = timestamp_;
  307. }
  308. VAddr GetCpuAddr() const noexcept {
  309. return cpu_addr;
  310. }
  311. u64 SizeInBytes() const noexcept {
  312. return SizeInBytes(timestamp.has_value());
  313. }
  314. static constexpr u64 SizeInBytes(bool with_timestamp) noexcept {
  315. return with_timestamp ? LARGE_QUERY_SIZE : SMALL_QUERY_SIZE;
  316. }
  317. protected:
  318. /// Returns true when querying the counter may potentially block.
  319. bool WaitPending() const noexcept {
  320. return counter && counter->WaitPending();
  321. }
  322. private:
  323. static constexpr std::size_t SMALL_QUERY_SIZE = 8; // Query size without timestamp.
  324. static constexpr std::size_t LARGE_QUERY_SIZE = 16; // Query size with timestamp.
  325. static constexpr std::intptr_t TIMESTAMP_OFFSET = 8; // Timestamp offset in a large query.
  326. VAddr cpu_addr; ///< Guest CPU address.
  327. u8* host_ptr; ///< Writable host pointer.
  328. std::shared_ptr<HostCounter> counter; ///< Host counter to query, owns the dependency tree.
  329. std::optional<u64> timestamp; ///< Timestamp to flush to guest memory.
  330. };
  331. } // namespace VideoCommon