query_cache.h 17 KB

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