query_cache.h 13 KB

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