query_cache.h 17 KB

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