query_cache.h 17 KB

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