query_cache.h 17 KB

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