query_cache.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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 <optional>
  11. #include <unordered_map>
  12. #include <vector>
  13. #include "common/assert.h"
  14. #include "core/core.h"
  15. #include "video_core/engines/maxwell_3d.h"
  16. #include "video_core/gpu.h"
  17. #include "video_core/memory_manager.h"
  18. #include "video_core/rasterizer_interface.h"
  19. namespace VideoCommon {
  20. template <class QueryCache, class HostCounter>
  21. class CounterStreamBase {
  22. public:
  23. explicit CounterStreamBase(QueryCache& cache, VideoCore::QueryType type)
  24. : cache{cache}, type{type} {}
  25. /// Updates the state of the stream, enabling or disabling as needed.
  26. void Update(bool enabled) {
  27. if (enabled) {
  28. Enable();
  29. } else {
  30. Disable();
  31. }
  32. }
  33. /// Resets the stream to zero. It doesn't disable the query after resetting.
  34. void Reset() {
  35. if (current) {
  36. current->EndQuery();
  37. // Immediately start a new query to avoid disabling its state.
  38. current = cache.Counter(nullptr, type);
  39. }
  40. last = nullptr;
  41. }
  42. /// Returns the current counter slicing as needed.
  43. std::shared_ptr<HostCounter> Current() {
  44. if (!current) {
  45. return nullptr;
  46. }
  47. current->EndQuery();
  48. last = std::move(current);
  49. current = cache.Counter(last, type);
  50. return last;
  51. }
  52. /// Returns true when the counter stream is enabled.
  53. bool IsEnabled() const {
  54. return static_cast<bool>(current);
  55. }
  56. private:
  57. /// Enables the stream.
  58. void Enable() {
  59. if (current) {
  60. return;
  61. }
  62. current = cache.Counter(last, type);
  63. }
  64. // Disables the stream.
  65. void Disable() {
  66. if (current) {
  67. current->EndQuery();
  68. }
  69. last = std::exchange(current, nullptr);
  70. }
  71. QueryCache& cache;
  72. const VideoCore::QueryType type;
  73. std::shared_ptr<HostCounter> current;
  74. std::shared_ptr<HostCounter> last;
  75. };
  76. template <class QueryCache, class CachedQuery, class CounterStream, class HostCounter>
  77. class QueryCacheBase {
  78. public:
  79. explicit QueryCacheBase(Core::System& system, VideoCore::RasterizerInterface& rasterizer)
  80. : system{system}, rasterizer{rasterizer}, streams{{CounterStream{
  81. static_cast<QueryCache&>(*this),
  82. VideoCore::QueryType::SamplesPassed}}} {}
  83. void InvalidateRegion(CacheAddr addr, std::size_t size) {
  84. FlushAndRemoveRegion(addr, size);
  85. }
  86. void FlushRegion(CacheAddr addr, std::size_t size) {
  87. FlushAndRemoveRegion(addr, size);
  88. }
  89. /**
  90. * Records a query in GPU mapped memory, potentially marked with a timestamp.
  91. * @param gpu_addr GPU address to flush to when the mapped memory is read.
  92. * @param type Query type, e.g. SamplesPassed.
  93. * @param timestamp Timestamp, when empty the flushed query is assumed to be short.
  94. */
  95. void Query(GPUVAddr gpu_addr, VideoCore::QueryType type, std::optional<u64> timestamp) {
  96. auto& memory_manager = system.GPU().MemoryManager();
  97. const auto host_ptr = memory_manager.GetPointer(gpu_addr);
  98. CachedQuery* query = TryGet(ToCacheAddr(host_ptr));
  99. if (!query) {
  100. const auto cpu_addr = memory_manager.GpuToCpuAddress(gpu_addr);
  101. ASSERT_OR_EXECUTE(cpu_addr, return;);
  102. query = Register(type, *cpu_addr, host_ptr, timestamp.has_value());
  103. }
  104. query->BindCounter(Stream(type).Current(), timestamp);
  105. }
  106. /// Updates counters from GPU state. Expected to be called once per draw, clear or dispatch.
  107. void UpdateCounters() {
  108. const auto& regs = system.GPU().Maxwell3D().regs;
  109. Stream(VideoCore::QueryType::SamplesPassed).Update(regs.samplecnt_enable);
  110. }
  111. /// Resets a counter to zero. It doesn't disable the query after resetting.
  112. void ResetCounter(VideoCore::QueryType type) {
  113. Stream(type).Reset();
  114. }
  115. /// Returns a new host counter.
  116. std::shared_ptr<HostCounter> Counter(std::shared_ptr<HostCounter> dependency,
  117. VideoCore::QueryType type) {
  118. return std::make_shared<HostCounter>(static_cast<QueryCache&>(*this), std::move(dependency),
  119. type);
  120. }
  121. /// Returns the counter stream of the specified type.
  122. CounterStream& Stream(VideoCore::QueryType type) {
  123. return streams[static_cast<std::size_t>(type)];
  124. }
  125. private:
  126. /// Flushes a memory range to guest memory and removes it from the cache.
  127. void FlushAndRemoveRegion(CacheAddr addr, std::size_t size) {
  128. const u64 addr_begin = static_cast<u64>(addr);
  129. const u64 addr_end = addr_begin + static_cast<u64>(size);
  130. const auto in_range = [addr_begin, addr_end](CachedQuery& query) {
  131. const u64 cache_begin = query.CacheAddr();
  132. const u64 cache_end = cache_begin + query.SizeInBytes();
  133. return cache_begin < addr_end && addr_begin < cache_end;
  134. };
  135. const u64 page_end = addr_end >> PAGE_SHIFT;
  136. for (u64 page = addr_begin >> PAGE_SHIFT; page <= page_end; ++page) {
  137. const auto& it = cached_queries.find(page);
  138. if (it == std::end(cached_queries)) {
  139. continue;
  140. }
  141. auto& contents = it->second;
  142. for (auto& query : contents) {
  143. if (!in_range(query)) {
  144. continue;
  145. }
  146. rasterizer.UpdatePagesCachedCount(query.CpuAddr(), query.SizeInBytes(), -1);
  147. query.Flush();
  148. }
  149. contents.erase(std::remove_if(std::begin(contents), std::end(contents), in_range),
  150. std::end(contents));
  151. }
  152. }
  153. /// Registers the passed parameters as cached and returns a pointer to the stored cached query.
  154. CachedQuery* Register(VideoCore::QueryType type, VAddr cpu_addr, u8* host_ptr, bool timestamp) {
  155. rasterizer.UpdatePagesCachedCount(cpu_addr, CachedQuery::SizeInBytes(timestamp), 1);
  156. const u64 page = static_cast<u64>(ToCacheAddr(host_ptr)) >> PAGE_SHIFT;
  157. return &cached_queries[page].emplace_back(static_cast<QueryCache&>(*this), type, cpu_addr,
  158. host_ptr);
  159. }
  160. /// Tries to a get a cached query. Returns nullptr on failure.
  161. CachedQuery* TryGet(CacheAddr addr) {
  162. const u64 page = static_cast<u64>(addr) >> PAGE_SHIFT;
  163. const auto it = cached_queries.find(page);
  164. if (it == std::end(cached_queries)) {
  165. return nullptr;
  166. }
  167. auto& contents = it->second;
  168. const auto found = std::find_if(std::begin(contents), std::end(contents),
  169. [addr](auto& query) { return query.CacheAddr() == addr; });
  170. return found != std::end(contents) ? &*found : nullptr;
  171. }
  172. static constexpr std::uintptr_t PAGE_SIZE = 4096;
  173. static constexpr int PAGE_SHIFT = 12;
  174. Core::System& system;
  175. VideoCore::RasterizerInterface& rasterizer;
  176. std::unordered_map<u64, std::vector<CachedQuery>> cached_queries;
  177. std::array<CounterStream, VideoCore::NumQueryTypes> streams;
  178. };
  179. template <class QueryCache, class HostCounter>
  180. class HostCounterBase {
  181. public:
  182. explicit HostCounterBase(std::shared_ptr<HostCounter> dependency)
  183. : dependency{std::move(dependency)} {}
  184. /// Returns the current value of the query.
  185. u64 Query() {
  186. if (result) {
  187. return *result;
  188. }
  189. u64 value = BlockingQuery();
  190. if (dependency) {
  191. value += dependency->Query();
  192. }
  193. return *(result = value);
  194. }
  195. /// Returns true when flushing this query will potentially wait.
  196. bool WaitPending() const noexcept {
  197. return result.has_value();
  198. }
  199. protected:
  200. /// Returns the value of query from the backend API blocking as needed.
  201. virtual u64 BlockingQuery() const = 0;
  202. private:
  203. std::shared_ptr<HostCounter> dependency; ///< Counter to add to this value.
  204. std::optional<u64> result; ///< Filled with the already returned value.
  205. };
  206. template <class HostCounter>
  207. class CachedQueryBase {
  208. public:
  209. explicit CachedQueryBase(VAddr cpu_addr, u8* host_ptr)
  210. : cpu_addr{cpu_addr}, host_ptr{host_ptr} {}
  211. CachedQueryBase(CachedQueryBase&& rhs) noexcept
  212. : cpu_addr{rhs.cpu_addr}, host_ptr{rhs.host_ptr}, counter{std::move(rhs.counter)},
  213. timestamp{rhs.timestamp} {}
  214. CachedQueryBase(const CachedQueryBase&) = delete;
  215. CachedQueryBase& operator=(CachedQueryBase&& rhs) noexcept {
  216. cpu_addr = rhs.cpu_addr;
  217. host_ptr = rhs.host_ptr;
  218. counter = std::move(rhs.counter);
  219. timestamp = rhs.timestamp;
  220. return *this;
  221. }
  222. /// Flushes the query to guest memory.
  223. virtual void Flush() {
  224. // When counter is nullptr it means that it's just been reseted. We are supposed to write a
  225. // zero in these cases.
  226. const u64 value = counter ? counter->Query() : 0;
  227. std::memcpy(host_ptr, &value, sizeof(u64));
  228. if (timestamp) {
  229. std::memcpy(host_ptr + TIMESTAMP_OFFSET, &*timestamp, sizeof(u64));
  230. }
  231. }
  232. /// Binds a counter to this query.
  233. void BindCounter(std::shared_ptr<HostCounter> counter_, std::optional<u64> timestamp_) {
  234. if (counter) {
  235. // If there's an old counter set it means the query is being rewritten by the game.
  236. // To avoid losing the data forever, flush here.
  237. Flush();
  238. }
  239. counter = std::move(counter_);
  240. timestamp = timestamp_;
  241. }
  242. VAddr CpuAddr() const noexcept {
  243. return cpu_addr;
  244. }
  245. CacheAddr CacheAddr() const noexcept {
  246. return ToCacheAddr(host_ptr);
  247. }
  248. u64 SizeInBytes() const noexcept {
  249. return SizeInBytes(timestamp.has_value());
  250. }
  251. static u64 SizeInBytes(bool with_timestamp) {
  252. return with_timestamp ? LARGE_QUERY_SIZE : SMALL_QUERY_SIZE;
  253. }
  254. protected:
  255. /// Returns true when querying the counter may potentially block.
  256. bool WaitPending() const noexcept {
  257. return counter && counter->WaitPending();
  258. }
  259. private:
  260. static constexpr std::size_t SMALL_QUERY_SIZE = 8; // Query size without timestamp.
  261. static constexpr std::size_t LARGE_QUERY_SIZE = 16; // Query size with timestamp.
  262. static constexpr std::intptr_t TIMESTAMP_OFFSET = 8; // Timestamp offset in a large query.
  263. VAddr cpu_addr; ///< Guest CPU address.
  264. u8* host_ptr; ///< Writable host pointer.
  265. std::shared_ptr<HostCounter> counter; ///< Host counter to query, owns the dependency tree.
  266. std::optional<u64> timestamp; ///< Timestamp to flush to guest memory.
  267. };
  268. } // namespace VideoCommon