buffer_cache.h 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947
  1. // SPDX-FileCopyrightText: Copyright 2019 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #pragma once
  4. #include <algorithm>
  5. #include <array>
  6. #include <memory>
  7. #include <mutex>
  8. #include <numeric>
  9. #include <span>
  10. #include <vector>
  11. #include <boost/container/small_vector.hpp>
  12. #include <boost/icl/interval_set.hpp>
  13. #include "common/common_types.h"
  14. #include "common/div_ceil.h"
  15. #include "common/literals.h"
  16. #include "common/lru_cache.h"
  17. #include "common/microprofile.h"
  18. #include "common/polyfill_ranges.h"
  19. #include "common/settings.h"
  20. #include "core/memory.h"
  21. #include "video_core/buffer_cache/buffer_base.h"
  22. #include "video_core/control/channel_state_cache.h"
  23. #include "video_core/delayed_destruction_ring.h"
  24. #include "video_core/dirty_flags.h"
  25. #include "video_core/engines/draw_manager.h"
  26. #include "video_core/engines/kepler_compute.h"
  27. #include "video_core/engines/maxwell_3d.h"
  28. #include "video_core/memory_manager.h"
  29. #include "video_core/rasterizer_interface.h"
  30. #include "video_core/surface.h"
  31. #include "video_core/texture_cache/slot_vector.h"
  32. #include "video_core/texture_cache/types.h"
  33. namespace VideoCommon {
  34. MICROPROFILE_DECLARE(GPU_PrepareBuffers);
  35. MICROPROFILE_DECLARE(GPU_BindUploadBuffers);
  36. MICROPROFILE_DECLARE(GPU_DownloadMemory);
  37. using BufferId = SlotId;
  38. using VideoCore::Surface::PixelFormat;
  39. using namespace Common::Literals;
  40. constexpr u32 NUM_VERTEX_BUFFERS = 32;
  41. constexpr u32 NUM_TRANSFORM_FEEDBACK_BUFFERS = 4;
  42. constexpr u32 NUM_GRAPHICS_UNIFORM_BUFFERS = 18;
  43. constexpr u32 NUM_COMPUTE_UNIFORM_BUFFERS = 8;
  44. constexpr u32 NUM_STORAGE_BUFFERS = 16;
  45. constexpr u32 NUM_TEXTURE_BUFFERS = 16;
  46. constexpr u32 NUM_STAGES = 5;
  47. using UniformBufferSizes = std::array<std::array<u32, NUM_GRAPHICS_UNIFORM_BUFFERS>, NUM_STAGES>;
  48. using ComputeUniformBufferSizes = std::array<u32, NUM_COMPUTE_UNIFORM_BUFFERS>;
  49. template <typename P>
  50. class BufferCache : public VideoCommon::ChannelSetupCaches<VideoCommon::ChannelInfo> {
  51. // Page size for caching purposes.
  52. // This is unrelated to the CPU page size and it can be changed as it seems optimal.
  53. static constexpr u32 YUZU_PAGEBITS = 16;
  54. static constexpr u64 YUZU_PAGESIZE = u64{1} << YUZU_PAGEBITS;
  55. static constexpr bool IS_OPENGL = P::IS_OPENGL;
  56. static constexpr bool HAS_PERSISTENT_UNIFORM_BUFFER_BINDINGS =
  57. P::HAS_PERSISTENT_UNIFORM_BUFFER_BINDINGS;
  58. static constexpr bool HAS_FULL_INDEX_AND_PRIMITIVE_SUPPORT =
  59. P::HAS_FULL_INDEX_AND_PRIMITIVE_SUPPORT;
  60. static constexpr bool NEEDS_BIND_UNIFORM_INDEX = P::NEEDS_BIND_UNIFORM_INDEX;
  61. static constexpr bool NEEDS_BIND_STORAGE_INDEX = P::NEEDS_BIND_STORAGE_INDEX;
  62. static constexpr bool USE_MEMORY_MAPS = P::USE_MEMORY_MAPS;
  63. static constexpr bool SEPARATE_IMAGE_BUFFERS_BINDINGS = P::SEPARATE_IMAGE_BUFFER_BINDINGS;
  64. static constexpr BufferId NULL_BUFFER_ID{0};
  65. static constexpr s64 DEFAULT_EXPECTED_MEMORY = 512_MiB;
  66. static constexpr s64 DEFAULT_CRITICAL_MEMORY = 1_GiB;
  67. static constexpr s64 TARGET_THRESHOLD = 4_GiB;
  68. using Maxwell = Tegra::Engines::Maxwell3D::Regs;
  69. using Runtime = typename P::Runtime;
  70. using Buffer = typename P::Buffer;
  71. using IntervalSet = boost::icl::interval_set<VAddr>;
  72. using IntervalType = typename IntervalSet::interval_type;
  73. struct Empty {};
  74. struct OverlapResult {
  75. std::vector<BufferId> ids;
  76. VAddr begin;
  77. VAddr end;
  78. bool has_stream_leap = false;
  79. };
  80. struct Binding {
  81. VAddr cpu_addr{};
  82. u32 size{};
  83. BufferId buffer_id;
  84. };
  85. struct TextureBufferBinding : Binding {
  86. PixelFormat format;
  87. };
  88. static constexpr Binding NULL_BINDING{
  89. .cpu_addr = 0,
  90. .size = 0,
  91. .buffer_id = NULL_BUFFER_ID,
  92. };
  93. public:
  94. static constexpr u32 DEFAULT_SKIP_CACHE_SIZE = static_cast<u32>(4_KiB);
  95. explicit BufferCache(VideoCore::RasterizerInterface& rasterizer_,
  96. Core::Memory::Memory& cpu_memory_, Runtime& runtime_);
  97. void TickFrame();
  98. void WriteMemory(VAddr cpu_addr, u64 size);
  99. void CachedWriteMemory(VAddr cpu_addr, u64 size);
  100. void DownloadMemory(VAddr cpu_addr, u64 size);
  101. bool InlineMemory(VAddr dest_address, size_t copy_size, std::span<const u8> inlined_buffer);
  102. void BindGraphicsUniformBuffer(size_t stage, u32 index, GPUVAddr gpu_addr, u32 size);
  103. void DisableGraphicsUniformBuffer(size_t stage, u32 index);
  104. void UpdateGraphicsBuffers(bool is_indexed);
  105. void UpdateComputeBuffers();
  106. void BindHostGeometryBuffers(bool is_indexed);
  107. void BindHostStageBuffers(size_t stage);
  108. void BindHostComputeBuffers();
  109. void SetUniformBuffersState(const std::array<u32, NUM_STAGES>& mask,
  110. const UniformBufferSizes* sizes);
  111. void SetComputeUniformBufferState(u32 mask, const ComputeUniformBufferSizes* sizes);
  112. void UnbindGraphicsStorageBuffers(size_t stage);
  113. void BindGraphicsStorageBuffer(size_t stage, size_t ssbo_index, u32 cbuf_index, u32 cbuf_offset,
  114. bool is_written);
  115. void UnbindGraphicsTextureBuffers(size_t stage);
  116. void BindGraphicsTextureBuffer(size_t stage, size_t tbo_index, GPUVAddr gpu_addr, u32 size,
  117. PixelFormat format, bool is_written, bool is_image);
  118. void UnbindComputeStorageBuffers();
  119. void BindComputeStorageBuffer(size_t ssbo_index, u32 cbuf_index, u32 cbuf_offset,
  120. bool is_written);
  121. void UnbindComputeTextureBuffers();
  122. void BindComputeTextureBuffer(size_t tbo_index, GPUVAddr gpu_addr, u32 size, PixelFormat format,
  123. bool is_written, bool is_image);
  124. void FlushCachedWrites();
  125. /// Return true when there are uncommitted buffers to be downloaded
  126. [[nodiscard]] bool HasUncommittedFlushes() const noexcept;
  127. void AccumulateFlushes();
  128. /// Return true when the caller should wait for async downloads
  129. [[nodiscard]] bool ShouldWaitAsyncFlushes() const noexcept;
  130. /// Commit asynchronous downloads
  131. void CommitAsyncFlushes();
  132. void CommitAsyncFlushesHigh();
  133. /// Pop asynchronous downloads
  134. void PopAsyncFlushes();
  135. bool DMACopy(GPUVAddr src_address, GPUVAddr dest_address, u64 amount);
  136. bool DMAClear(GPUVAddr src_address, u64 amount, u32 value);
  137. /// Return true when a CPU region is modified from the GPU
  138. [[nodiscard]] bool IsRegionGpuModified(VAddr addr, size_t size);
  139. /// Return true when a region is registered on the cache
  140. [[nodiscard]] bool IsRegionRegistered(VAddr addr, size_t size);
  141. /// Return true when a CPU region is modified from the CPU
  142. [[nodiscard]] bool IsRegionCpuModified(VAddr addr, size_t size);
  143. std::mutex mutex;
  144. Runtime& runtime;
  145. private:
  146. template <typename Func>
  147. static void ForEachEnabledBit(u32 enabled_mask, Func&& func) {
  148. for (u32 index = 0; enabled_mask != 0; ++index, enabled_mask >>= 1) {
  149. const int disabled_bits = std::countr_zero(enabled_mask);
  150. index += disabled_bits;
  151. enabled_mask >>= disabled_bits;
  152. func(index);
  153. }
  154. }
  155. template <typename Func>
  156. void ForEachBufferInRange(VAddr cpu_addr, u64 size, Func&& func) {
  157. const u64 page_end = Common::DivCeil(cpu_addr + size, YUZU_PAGESIZE);
  158. for (u64 page = cpu_addr >> YUZU_PAGEBITS; page < page_end;) {
  159. const BufferId buffer_id = page_table[page];
  160. if (!buffer_id) {
  161. ++page;
  162. continue;
  163. }
  164. Buffer& buffer = slot_buffers[buffer_id];
  165. func(buffer_id, buffer);
  166. const VAddr end_addr = buffer.CpuAddr() + buffer.SizeBytes();
  167. page = Common::DivCeil(end_addr, YUZU_PAGESIZE);
  168. }
  169. }
  170. template <typename Func>
  171. void ForEachWrittenRange(VAddr cpu_addr, u64 size, Func&& func) {
  172. const VAddr start_address = cpu_addr;
  173. const VAddr end_address = start_address + size;
  174. const VAddr search_base =
  175. static_cast<VAddr>(std::min<s64>(0LL, static_cast<s64>(start_address - size)));
  176. const IntervalType search_interval{search_base, search_base + 1};
  177. auto it = common_ranges.lower_bound(search_interval);
  178. if (it == common_ranges.end()) {
  179. it = common_ranges.begin();
  180. }
  181. for (; it != common_ranges.end(); it++) {
  182. VAddr inter_addr_end = it->upper();
  183. VAddr inter_addr = it->lower();
  184. if (inter_addr >= end_address) {
  185. break;
  186. }
  187. if (inter_addr_end <= start_address) {
  188. continue;
  189. }
  190. if (inter_addr_end > end_address) {
  191. inter_addr_end = end_address;
  192. }
  193. if (inter_addr < start_address) {
  194. inter_addr = start_address;
  195. }
  196. func(inter_addr, inter_addr_end);
  197. }
  198. }
  199. static bool IsRangeGranular(VAddr cpu_addr, size_t size) {
  200. return (cpu_addr & ~Core::Memory::YUZU_PAGEMASK) ==
  201. ((cpu_addr + size) & ~Core::Memory::YUZU_PAGEMASK);
  202. }
  203. void RunGarbageCollector();
  204. void BindHostIndexBuffer();
  205. void BindHostVertexBuffers();
  206. void BindHostGraphicsUniformBuffers(size_t stage);
  207. void BindHostGraphicsUniformBuffer(size_t stage, u32 index, u32 binding_index, bool needs_bind);
  208. void BindHostGraphicsStorageBuffers(size_t stage);
  209. void BindHostGraphicsTextureBuffers(size_t stage);
  210. void BindHostTransformFeedbackBuffers();
  211. void BindHostComputeUniformBuffers();
  212. void BindHostComputeStorageBuffers();
  213. void BindHostComputeTextureBuffers();
  214. void DoUpdateGraphicsBuffers(bool is_indexed);
  215. void DoUpdateComputeBuffers();
  216. void UpdateIndexBuffer();
  217. void UpdateVertexBuffers();
  218. void UpdateVertexBuffer(u32 index);
  219. void UpdateUniformBuffers(size_t stage);
  220. void UpdateStorageBuffers(size_t stage);
  221. void UpdateTextureBuffers(size_t stage);
  222. void UpdateTransformFeedbackBuffers();
  223. void UpdateTransformFeedbackBuffer(u32 index);
  224. void UpdateComputeUniformBuffers();
  225. void UpdateComputeStorageBuffers();
  226. void UpdateComputeTextureBuffers();
  227. void MarkWrittenBuffer(BufferId buffer_id, VAddr cpu_addr, u32 size);
  228. [[nodiscard]] BufferId FindBuffer(VAddr cpu_addr, u32 size);
  229. [[nodiscard]] OverlapResult ResolveOverlaps(VAddr cpu_addr, u32 wanted_size);
  230. void JoinOverlap(BufferId new_buffer_id, BufferId overlap_id, bool accumulate_stream_score);
  231. [[nodiscard]] BufferId CreateBuffer(VAddr cpu_addr, u32 wanted_size);
  232. void Register(BufferId buffer_id);
  233. void Unregister(BufferId buffer_id);
  234. template <bool insert>
  235. void ChangeRegister(BufferId buffer_id);
  236. void TouchBuffer(Buffer& buffer, BufferId buffer_id) noexcept;
  237. bool SynchronizeBuffer(Buffer& buffer, VAddr cpu_addr, u32 size);
  238. bool SynchronizeBufferImpl(Buffer& buffer, VAddr cpu_addr, u32 size);
  239. void UploadMemory(Buffer& buffer, u64 total_size_bytes, u64 largest_copy,
  240. std::span<BufferCopy> copies);
  241. void ImmediateUploadMemory(Buffer& buffer, u64 largest_copy,
  242. std::span<const BufferCopy> copies);
  243. void MappedUploadMemory(Buffer& buffer, u64 total_size_bytes, std::span<BufferCopy> copies);
  244. void DownloadBufferMemory(Buffer& buffer_id);
  245. void DownloadBufferMemory(Buffer& buffer_id, VAddr cpu_addr, u64 size);
  246. void DeleteBuffer(BufferId buffer_id);
  247. void NotifyBufferDeletion();
  248. [[nodiscard]] Binding StorageBufferBinding(GPUVAddr ssbo_addr, bool is_written = false) const;
  249. [[nodiscard]] TextureBufferBinding GetTextureBufferBinding(GPUVAddr gpu_addr, u32 size,
  250. PixelFormat format);
  251. [[nodiscard]] std::span<const u8> ImmediateBufferWithData(VAddr cpu_addr, size_t size);
  252. [[nodiscard]] std::span<u8> ImmediateBuffer(size_t wanted_capacity);
  253. [[nodiscard]] bool HasFastUniformBufferBound(size_t stage, u32 binding_index) const noexcept;
  254. void ClearDownload(IntervalType subtract_interval);
  255. VideoCore::RasterizerInterface& rasterizer;
  256. Core::Memory::Memory& cpu_memory;
  257. SlotVector<Buffer> slot_buffers;
  258. DelayedDestructionRing<Buffer, 8> delayed_destruction_ring;
  259. u32 last_index_count = 0;
  260. Binding index_buffer;
  261. std::array<Binding, NUM_VERTEX_BUFFERS> vertex_buffers;
  262. std::array<std::array<Binding, NUM_GRAPHICS_UNIFORM_BUFFERS>, NUM_STAGES> uniform_buffers;
  263. std::array<std::array<Binding, NUM_STORAGE_BUFFERS>, NUM_STAGES> storage_buffers;
  264. std::array<std::array<TextureBufferBinding, NUM_TEXTURE_BUFFERS>, NUM_STAGES> texture_buffers;
  265. std::array<Binding, NUM_TRANSFORM_FEEDBACK_BUFFERS> transform_feedback_buffers;
  266. std::array<Binding, NUM_COMPUTE_UNIFORM_BUFFERS> compute_uniform_buffers;
  267. std::array<Binding, NUM_STORAGE_BUFFERS> compute_storage_buffers;
  268. std::array<TextureBufferBinding, NUM_TEXTURE_BUFFERS> compute_texture_buffers;
  269. std::array<u32, NUM_STAGES> enabled_uniform_buffer_masks{};
  270. u32 enabled_compute_uniform_buffer_mask = 0;
  271. const UniformBufferSizes* uniform_buffer_sizes{};
  272. const ComputeUniformBufferSizes* compute_uniform_buffer_sizes{};
  273. std::array<u32, NUM_STAGES> enabled_storage_buffers{};
  274. std::array<u32, NUM_STAGES> written_storage_buffers{};
  275. u32 enabled_compute_storage_buffers = 0;
  276. u32 written_compute_storage_buffers = 0;
  277. std::array<u32, NUM_STAGES> enabled_texture_buffers{};
  278. std::array<u32, NUM_STAGES> written_texture_buffers{};
  279. std::array<u32, NUM_STAGES> image_texture_buffers{};
  280. u32 enabled_compute_texture_buffers = 0;
  281. u32 written_compute_texture_buffers = 0;
  282. u32 image_compute_texture_buffers = 0;
  283. std::array<u32, 16> uniform_cache_hits{};
  284. std::array<u32, 16> uniform_cache_shots{};
  285. u32 uniform_buffer_skip_cache_size = DEFAULT_SKIP_CACHE_SIZE;
  286. bool has_deleted_buffers = false;
  287. std::conditional_t<HAS_PERSISTENT_UNIFORM_BUFFER_BINDINGS, std::array<u32, NUM_STAGES>, Empty>
  288. dirty_uniform_buffers{};
  289. std::conditional_t<IS_OPENGL, std::array<u32, NUM_STAGES>, Empty> fast_bound_uniform_buffers{};
  290. std::conditional_t<HAS_PERSISTENT_UNIFORM_BUFFER_BINDINGS,
  291. std::array<std::array<u32, NUM_GRAPHICS_UNIFORM_BUFFERS>, NUM_STAGES>, Empty>
  292. uniform_buffer_binding_sizes{};
  293. std::vector<BufferId> cached_write_buffer_ids;
  294. IntervalSet uncommitted_ranges;
  295. IntervalSet common_ranges;
  296. std::deque<IntervalSet> committed_ranges;
  297. size_t immediate_buffer_capacity = 0;
  298. std::unique_ptr<u8[]> immediate_buffer_alloc;
  299. struct LRUItemParams {
  300. using ObjectType = BufferId;
  301. using TickType = u64;
  302. };
  303. Common::LeastRecentlyUsedCache<LRUItemParams> lru_cache;
  304. u64 frame_tick = 0;
  305. u64 total_used_memory = 0;
  306. u64 minimum_memory = 0;
  307. u64 critical_memory = 0;
  308. std::array<BufferId, ((1ULL << 39) >> YUZU_PAGEBITS)> page_table;
  309. };
  310. template <class P>
  311. BufferCache<P>::BufferCache(VideoCore::RasterizerInterface& rasterizer_,
  312. Core::Memory::Memory& cpu_memory_, Runtime& runtime_)
  313. : runtime{runtime_}, rasterizer{rasterizer_}, cpu_memory{cpu_memory_} {
  314. // Ensure the first slot is used for the null buffer
  315. void(slot_buffers.insert(runtime, NullBufferParams{}));
  316. common_ranges.clear();
  317. if (!runtime.CanReportMemoryUsage()) {
  318. minimum_memory = DEFAULT_EXPECTED_MEMORY;
  319. critical_memory = DEFAULT_CRITICAL_MEMORY;
  320. return;
  321. }
  322. const s64 device_memory = static_cast<s64>(runtime.GetDeviceLocalMemory());
  323. const s64 min_spacing_expected = device_memory - 1_GiB - 512_MiB;
  324. const s64 min_spacing_critical = device_memory - 1_GiB;
  325. const s64 mem_threshold = std::min(device_memory, TARGET_THRESHOLD);
  326. const s64 min_vacancy_expected = (6 * mem_threshold) / 10;
  327. const s64 min_vacancy_critical = (3 * mem_threshold) / 10;
  328. minimum_memory = static_cast<u64>(
  329. std::max(std::min(device_memory - min_vacancy_expected, min_spacing_expected),
  330. DEFAULT_EXPECTED_MEMORY));
  331. critical_memory = static_cast<u64>(
  332. std::max(std::min(device_memory - min_vacancy_critical, min_spacing_critical),
  333. DEFAULT_CRITICAL_MEMORY));
  334. }
  335. template <class P>
  336. void BufferCache<P>::RunGarbageCollector() {
  337. const bool aggressive_gc = total_used_memory >= critical_memory;
  338. const u64 ticks_to_destroy = aggressive_gc ? 60 : 120;
  339. int num_iterations = aggressive_gc ? 64 : 32;
  340. const auto clean_up = [this, &num_iterations](BufferId buffer_id) {
  341. if (num_iterations == 0) {
  342. return true;
  343. }
  344. --num_iterations;
  345. auto& buffer = slot_buffers[buffer_id];
  346. DownloadBufferMemory(buffer);
  347. DeleteBuffer(buffer_id);
  348. return false;
  349. };
  350. lru_cache.ForEachItemBelow(frame_tick - ticks_to_destroy, clean_up);
  351. }
  352. template <class P>
  353. void BufferCache<P>::TickFrame() {
  354. // Calculate hits and shots and move hit bits to the right
  355. const u32 hits = std::reduce(uniform_cache_hits.begin(), uniform_cache_hits.end());
  356. const u32 shots = std::reduce(uniform_cache_shots.begin(), uniform_cache_shots.end());
  357. std::copy_n(uniform_cache_hits.begin(), uniform_cache_hits.size() - 1,
  358. uniform_cache_hits.begin() + 1);
  359. std::copy_n(uniform_cache_shots.begin(), uniform_cache_shots.size() - 1,
  360. uniform_cache_shots.begin() + 1);
  361. uniform_cache_hits[0] = 0;
  362. uniform_cache_shots[0] = 0;
  363. const bool skip_preferred = hits * 256 < shots * 251;
  364. uniform_buffer_skip_cache_size = skip_preferred ? DEFAULT_SKIP_CACHE_SIZE : 0;
  365. // If we can obtain the memory info, use it instead of the estimate.
  366. if (runtime.CanReportMemoryUsage()) {
  367. total_used_memory = runtime.GetDeviceMemoryUsage();
  368. }
  369. if (total_used_memory >= minimum_memory) {
  370. RunGarbageCollector();
  371. }
  372. ++frame_tick;
  373. delayed_destruction_ring.Tick();
  374. }
  375. template <class P>
  376. void BufferCache<P>::WriteMemory(VAddr cpu_addr, u64 size) {
  377. ForEachBufferInRange(cpu_addr, size, [&](BufferId, Buffer& buffer) {
  378. buffer.MarkRegionAsCpuModified(cpu_addr, size);
  379. });
  380. }
  381. template <class P>
  382. void BufferCache<P>::CachedWriteMemory(VAddr cpu_addr, u64 size) {
  383. ForEachBufferInRange(cpu_addr, size, [&](BufferId buffer_id, Buffer& buffer) {
  384. if (!buffer.HasCachedWrites()) {
  385. cached_write_buffer_ids.push_back(buffer_id);
  386. }
  387. buffer.CachedCpuWrite(cpu_addr, size);
  388. });
  389. }
  390. template <class P>
  391. void BufferCache<P>::DownloadMemory(VAddr cpu_addr, u64 size) {
  392. ForEachBufferInRange(cpu_addr, size, [&](BufferId, Buffer& buffer) {
  393. DownloadBufferMemory(buffer, cpu_addr, size);
  394. });
  395. }
  396. template <class P>
  397. void BufferCache<P>::ClearDownload(IntervalType subtract_interval) {
  398. uncommitted_ranges.subtract(subtract_interval);
  399. for (auto& interval_set : committed_ranges) {
  400. interval_set.subtract(subtract_interval);
  401. }
  402. }
  403. template <class P>
  404. bool BufferCache<P>::DMACopy(GPUVAddr src_address, GPUVAddr dest_address, u64 amount) {
  405. const std::optional<VAddr> cpu_src_address = gpu_memory->GpuToCpuAddress(src_address);
  406. const std::optional<VAddr> cpu_dest_address = gpu_memory->GpuToCpuAddress(dest_address);
  407. if (!cpu_src_address || !cpu_dest_address) {
  408. return false;
  409. }
  410. const bool source_dirty = IsRegionRegistered(*cpu_src_address, amount);
  411. const bool dest_dirty = IsRegionRegistered(*cpu_dest_address, amount);
  412. if (!source_dirty && !dest_dirty) {
  413. return false;
  414. }
  415. const IntervalType subtract_interval{*cpu_dest_address, *cpu_dest_address + amount};
  416. ClearDownload(subtract_interval);
  417. BufferId buffer_a;
  418. BufferId buffer_b;
  419. do {
  420. has_deleted_buffers = false;
  421. buffer_a = FindBuffer(*cpu_src_address, static_cast<u32>(amount));
  422. buffer_b = FindBuffer(*cpu_dest_address, static_cast<u32>(amount));
  423. } while (has_deleted_buffers);
  424. auto& src_buffer = slot_buffers[buffer_a];
  425. auto& dest_buffer = slot_buffers[buffer_b];
  426. SynchronizeBuffer(src_buffer, *cpu_src_address, static_cast<u32>(amount));
  427. SynchronizeBuffer(dest_buffer, *cpu_dest_address, static_cast<u32>(amount));
  428. std::array copies{BufferCopy{
  429. .src_offset = src_buffer.Offset(*cpu_src_address),
  430. .dst_offset = dest_buffer.Offset(*cpu_dest_address),
  431. .size = amount,
  432. }};
  433. boost::container::small_vector<IntervalType, 4> tmp_intervals;
  434. auto mirror = [&](VAddr base_address, VAddr base_address_end) {
  435. const u64 size = base_address_end - base_address;
  436. const VAddr diff = base_address - *cpu_src_address;
  437. const VAddr new_base_address = *cpu_dest_address + diff;
  438. const IntervalType add_interval{new_base_address, new_base_address + size};
  439. uncommitted_ranges.add(add_interval);
  440. tmp_intervals.push_back(add_interval);
  441. };
  442. ForEachWrittenRange(*cpu_src_address, amount, mirror);
  443. // This subtraction in this order is important for overlapping copies.
  444. common_ranges.subtract(subtract_interval);
  445. const bool has_new_downloads = tmp_intervals.size() != 0;
  446. for (const IntervalType& add_interval : tmp_intervals) {
  447. common_ranges.add(add_interval);
  448. }
  449. runtime.CopyBuffer(dest_buffer, src_buffer, copies);
  450. if (has_new_downloads) {
  451. dest_buffer.MarkRegionAsGpuModified(*cpu_dest_address, amount);
  452. }
  453. std::vector<u8> tmp_buffer(amount);
  454. cpu_memory.ReadBlockUnsafe(*cpu_src_address, tmp_buffer.data(), amount);
  455. cpu_memory.WriteBlockUnsafe(*cpu_dest_address, tmp_buffer.data(), amount);
  456. return true;
  457. }
  458. template <class P>
  459. bool BufferCache<P>::DMAClear(GPUVAddr dst_address, u64 amount, u32 value) {
  460. const std::optional<VAddr> cpu_dst_address = gpu_memory->GpuToCpuAddress(dst_address);
  461. if (!cpu_dst_address) {
  462. return false;
  463. }
  464. const bool dest_dirty = IsRegionRegistered(*cpu_dst_address, amount);
  465. if (!dest_dirty) {
  466. return false;
  467. }
  468. const size_t size = amount * sizeof(u32);
  469. const IntervalType subtract_interval{*cpu_dst_address, *cpu_dst_address + size};
  470. ClearDownload(subtract_interval);
  471. common_ranges.subtract(subtract_interval);
  472. const BufferId buffer = FindBuffer(*cpu_dst_address, static_cast<u32>(size));
  473. auto& dest_buffer = slot_buffers[buffer];
  474. const u32 offset = dest_buffer.Offset(*cpu_dst_address);
  475. runtime.ClearBuffer(dest_buffer, offset, size, value);
  476. return true;
  477. }
  478. template <class P>
  479. void BufferCache<P>::BindGraphicsUniformBuffer(size_t stage, u32 index, GPUVAddr gpu_addr,
  480. u32 size) {
  481. const std::optional<VAddr> cpu_addr = gpu_memory->GpuToCpuAddress(gpu_addr);
  482. const Binding binding{
  483. .cpu_addr = *cpu_addr,
  484. .size = size,
  485. .buffer_id = BufferId{},
  486. };
  487. uniform_buffers[stage][index] = binding;
  488. }
  489. template <class P>
  490. void BufferCache<P>::DisableGraphicsUniformBuffer(size_t stage, u32 index) {
  491. uniform_buffers[stage][index] = NULL_BINDING;
  492. }
  493. template <class P>
  494. void BufferCache<P>::UpdateGraphicsBuffers(bool is_indexed) {
  495. MICROPROFILE_SCOPE(GPU_PrepareBuffers);
  496. do {
  497. has_deleted_buffers = false;
  498. DoUpdateGraphicsBuffers(is_indexed);
  499. } while (has_deleted_buffers);
  500. }
  501. template <class P>
  502. void BufferCache<P>::UpdateComputeBuffers() {
  503. MICROPROFILE_SCOPE(GPU_PrepareBuffers);
  504. do {
  505. has_deleted_buffers = false;
  506. DoUpdateComputeBuffers();
  507. } while (has_deleted_buffers);
  508. }
  509. template <class P>
  510. void BufferCache<P>::BindHostGeometryBuffers(bool is_indexed) {
  511. MICROPROFILE_SCOPE(GPU_BindUploadBuffers);
  512. if (is_indexed) {
  513. BindHostIndexBuffer();
  514. } else if constexpr (!HAS_FULL_INDEX_AND_PRIMITIVE_SUPPORT) {
  515. const auto& draw_state = maxwell3d->draw_manager->GetDrawState();
  516. if (draw_state.topology == Maxwell::PrimitiveTopology::Quads ||
  517. draw_state.topology == Maxwell::PrimitiveTopology::QuadStrip) {
  518. runtime.BindQuadIndexBuffer(draw_state.topology, draw_state.vertex_buffer.first,
  519. draw_state.vertex_buffer.count);
  520. }
  521. }
  522. BindHostVertexBuffers();
  523. BindHostTransformFeedbackBuffers();
  524. }
  525. template <class P>
  526. void BufferCache<P>::BindHostStageBuffers(size_t stage) {
  527. MICROPROFILE_SCOPE(GPU_BindUploadBuffers);
  528. BindHostGraphicsUniformBuffers(stage);
  529. BindHostGraphicsStorageBuffers(stage);
  530. BindHostGraphicsTextureBuffers(stage);
  531. }
  532. template <class P>
  533. void BufferCache<P>::BindHostComputeBuffers() {
  534. MICROPROFILE_SCOPE(GPU_BindUploadBuffers);
  535. BindHostComputeUniformBuffers();
  536. BindHostComputeStorageBuffers();
  537. BindHostComputeTextureBuffers();
  538. }
  539. template <class P>
  540. void BufferCache<P>::SetUniformBuffersState(const std::array<u32, NUM_STAGES>& mask,
  541. const UniformBufferSizes* sizes) {
  542. if constexpr (HAS_PERSISTENT_UNIFORM_BUFFER_BINDINGS) {
  543. if (enabled_uniform_buffer_masks != mask) {
  544. if constexpr (IS_OPENGL) {
  545. fast_bound_uniform_buffers.fill(0);
  546. }
  547. dirty_uniform_buffers.fill(~u32{0});
  548. uniform_buffer_binding_sizes.fill({});
  549. }
  550. }
  551. enabled_uniform_buffer_masks = mask;
  552. uniform_buffer_sizes = sizes;
  553. }
  554. template <class P>
  555. void BufferCache<P>::SetComputeUniformBufferState(u32 mask,
  556. const ComputeUniformBufferSizes* sizes) {
  557. enabled_compute_uniform_buffer_mask = mask;
  558. compute_uniform_buffer_sizes = sizes;
  559. }
  560. template <class P>
  561. void BufferCache<P>::UnbindGraphicsStorageBuffers(size_t stage) {
  562. enabled_storage_buffers[stage] = 0;
  563. written_storage_buffers[stage] = 0;
  564. }
  565. template <class P>
  566. void BufferCache<P>::BindGraphicsStorageBuffer(size_t stage, size_t ssbo_index, u32 cbuf_index,
  567. u32 cbuf_offset, bool is_written) {
  568. enabled_storage_buffers[stage] |= 1U << ssbo_index;
  569. written_storage_buffers[stage] |= (is_written ? 1U : 0U) << ssbo_index;
  570. const auto& cbufs = maxwell3d->state.shader_stages[stage];
  571. const GPUVAddr ssbo_addr = cbufs.const_buffers[cbuf_index].address + cbuf_offset;
  572. storage_buffers[stage][ssbo_index] = StorageBufferBinding(ssbo_addr, is_written);
  573. }
  574. template <class P>
  575. void BufferCache<P>::UnbindGraphicsTextureBuffers(size_t stage) {
  576. enabled_texture_buffers[stage] = 0;
  577. written_texture_buffers[stage] = 0;
  578. image_texture_buffers[stage] = 0;
  579. }
  580. template <class P>
  581. void BufferCache<P>::BindGraphicsTextureBuffer(size_t stage, size_t tbo_index, GPUVAddr gpu_addr,
  582. u32 size, PixelFormat format, bool is_written,
  583. bool is_image) {
  584. enabled_texture_buffers[stage] |= 1U << tbo_index;
  585. written_texture_buffers[stage] |= (is_written ? 1U : 0U) << tbo_index;
  586. if constexpr (SEPARATE_IMAGE_BUFFERS_BINDINGS) {
  587. image_texture_buffers[stage] |= (is_image ? 1U : 0U) << tbo_index;
  588. }
  589. texture_buffers[stage][tbo_index] = GetTextureBufferBinding(gpu_addr, size, format);
  590. }
  591. template <class P>
  592. void BufferCache<P>::UnbindComputeStorageBuffers() {
  593. enabled_compute_storage_buffers = 0;
  594. written_compute_storage_buffers = 0;
  595. image_compute_texture_buffers = 0;
  596. }
  597. template <class P>
  598. void BufferCache<P>::BindComputeStorageBuffer(size_t ssbo_index, u32 cbuf_index, u32 cbuf_offset,
  599. bool is_written) {
  600. enabled_compute_storage_buffers |= 1U << ssbo_index;
  601. written_compute_storage_buffers |= (is_written ? 1U : 0U) << ssbo_index;
  602. const auto& launch_desc = kepler_compute->launch_description;
  603. ASSERT(((launch_desc.const_buffer_enable_mask >> cbuf_index) & 1) != 0);
  604. const auto& cbufs = launch_desc.const_buffer_config;
  605. const GPUVAddr ssbo_addr = cbufs[cbuf_index].Address() + cbuf_offset;
  606. compute_storage_buffers[ssbo_index] = StorageBufferBinding(ssbo_addr, is_written);
  607. }
  608. template <class P>
  609. void BufferCache<P>::UnbindComputeTextureBuffers() {
  610. enabled_compute_texture_buffers = 0;
  611. written_compute_texture_buffers = 0;
  612. image_compute_texture_buffers = 0;
  613. }
  614. template <class P>
  615. void BufferCache<P>::BindComputeTextureBuffer(size_t tbo_index, GPUVAddr gpu_addr, u32 size,
  616. PixelFormat format, bool is_written, bool is_image) {
  617. enabled_compute_texture_buffers |= 1U << tbo_index;
  618. written_compute_texture_buffers |= (is_written ? 1U : 0U) << tbo_index;
  619. if constexpr (SEPARATE_IMAGE_BUFFERS_BINDINGS) {
  620. image_compute_texture_buffers |= (is_image ? 1U : 0U) << tbo_index;
  621. }
  622. compute_texture_buffers[tbo_index] = GetTextureBufferBinding(gpu_addr, size, format);
  623. }
  624. template <class P>
  625. void BufferCache<P>::FlushCachedWrites() {
  626. for (const BufferId buffer_id : cached_write_buffer_ids) {
  627. slot_buffers[buffer_id].FlushCachedWrites();
  628. }
  629. cached_write_buffer_ids.clear();
  630. }
  631. template <class P>
  632. bool BufferCache<P>::HasUncommittedFlushes() const noexcept {
  633. return !uncommitted_ranges.empty() || !committed_ranges.empty();
  634. }
  635. template <class P>
  636. void BufferCache<P>::AccumulateFlushes() {
  637. if (Settings::values.gpu_accuracy.GetValue() != Settings::GPUAccuracy::High) {
  638. uncommitted_ranges.clear();
  639. return;
  640. }
  641. if (uncommitted_ranges.empty()) {
  642. return;
  643. }
  644. committed_ranges.emplace_back(std::move(uncommitted_ranges));
  645. }
  646. template <class P>
  647. bool BufferCache<P>::ShouldWaitAsyncFlushes() const noexcept {
  648. return false;
  649. }
  650. template <class P>
  651. void BufferCache<P>::CommitAsyncFlushesHigh() {
  652. AccumulateFlushes();
  653. if (committed_ranges.empty()) {
  654. return;
  655. }
  656. MICROPROFILE_SCOPE(GPU_DownloadMemory);
  657. const bool is_accuracy_normal =
  658. Settings::values.gpu_accuracy.GetValue() == Settings::GPUAccuracy::Normal;
  659. auto it = committed_ranges.begin();
  660. while (it != committed_ranges.end()) {
  661. auto& current_intervals = *it;
  662. auto next_it = std::next(it);
  663. while (next_it != committed_ranges.end()) {
  664. for (auto& interval : *next_it) {
  665. current_intervals.subtract(interval);
  666. }
  667. next_it++;
  668. }
  669. it++;
  670. }
  671. boost::container::small_vector<std::pair<BufferCopy, BufferId>, 1> downloads;
  672. u64 total_size_bytes = 0;
  673. u64 largest_copy = 0;
  674. for (const IntervalSet& intervals : committed_ranges) {
  675. for (auto& interval : intervals) {
  676. const std::size_t size = interval.upper() - interval.lower();
  677. const VAddr cpu_addr = interval.lower();
  678. ForEachBufferInRange(cpu_addr, size, [&](BufferId buffer_id, Buffer& buffer) {
  679. buffer.ForEachDownloadRangeAndClear(
  680. cpu_addr, size, [&](u64 range_offset, u64 range_size) {
  681. if (is_accuracy_normal) {
  682. return;
  683. }
  684. const VAddr buffer_addr = buffer.CpuAddr();
  685. const auto add_download = [&](VAddr start, VAddr end) {
  686. const u64 new_offset = start - buffer_addr;
  687. const u64 new_size = end - start;
  688. downloads.push_back({
  689. BufferCopy{
  690. .src_offset = new_offset,
  691. .dst_offset = total_size_bytes,
  692. .size = new_size,
  693. },
  694. buffer_id,
  695. });
  696. // Align up to avoid cache conflicts
  697. constexpr u64 align = 256ULL;
  698. constexpr u64 mask = ~(align - 1ULL);
  699. total_size_bytes += (new_size + align - 1) & mask;
  700. largest_copy = std::max(largest_copy, new_size);
  701. };
  702. const VAddr start_address = buffer_addr + range_offset;
  703. const VAddr end_address = start_address + range_size;
  704. ForEachWrittenRange(start_address, range_size, add_download);
  705. const IntervalType subtract_interval{start_address, end_address};
  706. common_ranges.subtract(subtract_interval);
  707. });
  708. });
  709. }
  710. }
  711. committed_ranges.clear();
  712. if (downloads.empty()) {
  713. return;
  714. }
  715. if constexpr (USE_MEMORY_MAPS) {
  716. auto download_staging = runtime.DownloadStagingBuffer(total_size_bytes);
  717. runtime.PreCopyBarrier();
  718. for (auto& [copy, buffer_id] : downloads) {
  719. // Have in mind the staging buffer offset for the copy
  720. copy.dst_offset += download_staging.offset;
  721. const std::array copies{copy};
  722. runtime.CopyBuffer(download_staging.buffer, slot_buffers[buffer_id], copies, false);
  723. }
  724. runtime.PostCopyBarrier();
  725. runtime.Finish();
  726. for (const auto& [copy, buffer_id] : downloads) {
  727. const Buffer& buffer = slot_buffers[buffer_id];
  728. const VAddr cpu_addr = buffer.CpuAddr() + copy.src_offset;
  729. // Undo the modified offset
  730. const u64 dst_offset = copy.dst_offset - download_staging.offset;
  731. const u8* read_mapped_memory = download_staging.mapped_span.data() + dst_offset;
  732. cpu_memory.WriteBlockUnsafe(cpu_addr, read_mapped_memory, copy.size);
  733. }
  734. } else {
  735. const std::span<u8> immediate_buffer = ImmediateBuffer(largest_copy);
  736. for (const auto& [copy, buffer_id] : downloads) {
  737. Buffer& buffer = slot_buffers[buffer_id];
  738. buffer.ImmediateDownload(copy.src_offset, immediate_buffer.subspan(0, copy.size));
  739. const VAddr cpu_addr = buffer.CpuAddr() + copy.src_offset;
  740. cpu_memory.WriteBlockUnsafe(cpu_addr, immediate_buffer.data(), copy.size);
  741. }
  742. }
  743. }
  744. template <class P>
  745. void BufferCache<P>::CommitAsyncFlushes() {
  746. if (Settings::values.gpu_accuracy.GetValue() == Settings::GPUAccuracy::High) {
  747. CommitAsyncFlushesHigh();
  748. } else {
  749. uncommitted_ranges.clear();
  750. committed_ranges.clear();
  751. }
  752. }
  753. template <class P>
  754. void BufferCache<P>::PopAsyncFlushes() {}
  755. template <class P>
  756. bool BufferCache<P>::IsRegionGpuModified(VAddr addr, size_t size) {
  757. const u64 page_end = Common::DivCeil(addr + size, YUZU_PAGESIZE);
  758. for (u64 page = addr >> YUZU_PAGEBITS; page < page_end;) {
  759. const BufferId image_id = page_table[page];
  760. if (!image_id) {
  761. ++page;
  762. continue;
  763. }
  764. Buffer& buffer = slot_buffers[image_id];
  765. if (buffer.IsRegionGpuModified(addr, size)) {
  766. return true;
  767. }
  768. const VAddr end_addr = buffer.CpuAddr() + buffer.SizeBytes();
  769. page = Common::DivCeil(end_addr, YUZU_PAGESIZE);
  770. }
  771. return false;
  772. }
  773. template <class P>
  774. bool BufferCache<P>::IsRegionRegistered(VAddr addr, size_t size) {
  775. const VAddr end_addr = addr + size;
  776. const u64 page_end = Common::DivCeil(end_addr, YUZU_PAGESIZE);
  777. for (u64 page = addr >> YUZU_PAGEBITS; page < page_end;) {
  778. const BufferId buffer_id = page_table[page];
  779. if (!buffer_id) {
  780. ++page;
  781. continue;
  782. }
  783. Buffer& buffer = slot_buffers[buffer_id];
  784. const VAddr buf_start_addr = buffer.CpuAddr();
  785. const VAddr buf_end_addr = buf_start_addr + buffer.SizeBytes();
  786. if (buf_start_addr < end_addr && addr < buf_end_addr) {
  787. return true;
  788. }
  789. page = Common::DivCeil(end_addr, YUZU_PAGESIZE);
  790. }
  791. return false;
  792. }
  793. template <class P>
  794. bool BufferCache<P>::IsRegionCpuModified(VAddr addr, size_t size) {
  795. const u64 page_end = Common::DivCeil(addr + size, YUZU_PAGESIZE);
  796. for (u64 page = addr >> YUZU_PAGEBITS; page < page_end;) {
  797. const BufferId image_id = page_table[page];
  798. if (!image_id) {
  799. ++page;
  800. continue;
  801. }
  802. Buffer& buffer = slot_buffers[image_id];
  803. if (buffer.IsRegionCpuModified(addr, size)) {
  804. return true;
  805. }
  806. const VAddr end_addr = buffer.CpuAddr() + buffer.SizeBytes();
  807. page = Common::DivCeil(end_addr, YUZU_PAGESIZE);
  808. }
  809. return false;
  810. }
  811. template <class P>
  812. void BufferCache<P>::BindHostIndexBuffer() {
  813. Buffer& buffer = slot_buffers[index_buffer.buffer_id];
  814. TouchBuffer(buffer, index_buffer.buffer_id);
  815. const u32 offset = buffer.Offset(index_buffer.cpu_addr);
  816. const u32 size = index_buffer.size;
  817. const auto& draw_state = maxwell3d->draw_manager->GetDrawState();
  818. if (!draw_state.inline_index_draw_indexes.empty()) {
  819. if constexpr (USE_MEMORY_MAPS) {
  820. auto upload_staging = runtime.UploadStagingBuffer(size);
  821. std::array<BufferCopy, 1> copies{
  822. {BufferCopy{.src_offset = upload_staging.offset, .dst_offset = 0, .size = size}}};
  823. std::memcpy(upload_staging.mapped_span.data(),
  824. draw_state.inline_index_draw_indexes.data(), size);
  825. runtime.CopyBuffer(buffer, upload_staging.buffer, copies);
  826. } else {
  827. buffer.ImmediateUpload(0, draw_state.inline_index_draw_indexes);
  828. }
  829. } else {
  830. SynchronizeBuffer(buffer, index_buffer.cpu_addr, size);
  831. }
  832. if constexpr (HAS_FULL_INDEX_AND_PRIMITIVE_SUPPORT) {
  833. const u32 new_offset =
  834. offset + draw_state.index_buffer.first * draw_state.index_buffer.FormatSizeInBytes();
  835. runtime.BindIndexBuffer(buffer, new_offset, size);
  836. } else {
  837. runtime.BindIndexBuffer(draw_state.topology, draw_state.index_buffer.format,
  838. draw_state.index_buffer.first, draw_state.index_buffer.count,
  839. buffer, offset, size);
  840. }
  841. }
  842. template <class P>
  843. void BufferCache<P>::BindHostVertexBuffers() {
  844. auto& flags = maxwell3d->dirty.flags;
  845. for (u32 index = 0; index < NUM_VERTEX_BUFFERS; ++index) {
  846. const Binding& binding = vertex_buffers[index];
  847. Buffer& buffer = slot_buffers[binding.buffer_id];
  848. TouchBuffer(buffer, binding.buffer_id);
  849. SynchronizeBuffer(buffer, binding.cpu_addr, binding.size);
  850. if (!flags[Dirty::VertexBuffer0 + index]) {
  851. continue;
  852. }
  853. flags[Dirty::VertexBuffer0 + index] = false;
  854. const u32 stride = maxwell3d->regs.vertex_streams[index].stride;
  855. const u32 offset = buffer.Offset(binding.cpu_addr);
  856. runtime.BindVertexBuffer(index, buffer, offset, binding.size, stride);
  857. }
  858. }
  859. template <class P>
  860. void BufferCache<P>::BindHostGraphicsUniformBuffers(size_t stage) {
  861. u32 dirty = ~0U;
  862. if constexpr (HAS_PERSISTENT_UNIFORM_BUFFER_BINDINGS) {
  863. dirty = std::exchange(dirty_uniform_buffers[stage], 0);
  864. }
  865. u32 binding_index = 0;
  866. ForEachEnabledBit(enabled_uniform_buffer_masks[stage], [&](u32 index) {
  867. const bool needs_bind = ((dirty >> index) & 1) != 0;
  868. BindHostGraphicsUniformBuffer(stage, index, binding_index, needs_bind);
  869. if constexpr (NEEDS_BIND_UNIFORM_INDEX) {
  870. ++binding_index;
  871. }
  872. });
  873. }
  874. template <class P>
  875. void BufferCache<P>::BindHostGraphicsUniformBuffer(size_t stage, u32 index, u32 binding_index,
  876. bool needs_bind) {
  877. const Binding& binding = uniform_buffers[stage][index];
  878. const VAddr cpu_addr = binding.cpu_addr;
  879. const u32 size = std::min(binding.size, (*uniform_buffer_sizes)[stage][index]);
  880. Buffer& buffer = slot_buffers[binding.buffer_id];
  881. TouchBuffer(buffer, binding.buffer_id);
  882. const bool use_fast_buffer = binding.buffer_id != NULL_BUFFER_ID &&
  883. size <= uniform_buffer_skip_cache_size &&
  884. !buffer.IsRegionGpuModified(cpu_addr, size);
  885. if (use_fast_buffer) {
  886. if constexpr (IS_OPENGL) {
  887. if (runtime.HasFastBufferSubData()) {
  888. // Fast path for Nvidia
  889. const bool should_fast_bind =
  890. !HasFastUniformBufferBound(stage, binding_index) ||
  891. uniform_buffer_binding_sizes[stage][binding_index] != size;
  892. if (should_fast_bind) {
  893. // We only have to bind when the currently bound buffer is not the fast version
  894. fast_bound_uniform_buffers[stage] |= 1U << binding_index;
  895. uniform_buffer_binding_sizes[stage][binding_index] = size;
  896. runtime.BindFastUniformBuffer(stage, binding_index, size);
  897. }
  898. const auto span = ImmediateBufferWithData(cpu_addr, size);
  899. runtime.PushFastUniformBuffer(stage, binding_index, span);
  900. return;
  901. }
  902. }
  903. if constexpr (IS_OPENGL) {
  904. fast_bound_uniform_buffers[stage] |= 1U << binding_index;
  905. uniform_buffer_binding_sizes[stage][binding_index] = size;
  906. }
  907. // Stream buffer path to avoid stalling on non-Nvidia drivers or Vulkan
  908. const std::span<u8> span = runtime.BindMappedUniformBuffer(stage, binding_index, size);
  909. cpu_memory.ReadBlockUnsafe(cpu_addr, span.data(), size);
  910. return;
  911. }
  912. // Classic cached path
  913. const bool sync_cached = SynchronizeBuffer(buffer, cpu_addr, size);
  914. if (sync_cached) {
  915. ++uniform_cache_hits[0];
  916. }
  917. ++uniform_cache_shots[0];
  918. // Skip binding if it's not needed and if the bound buffer is not the fast version
  919. // This exists to avoid instances where the fast buffer is bound and a GPU write happens
  920. needs_bind |= HasFastUniformBufferBound(stage, binding_index);
  921. if constexpr (HAS_PERSISTENT_UNIFORM_BUFFER_BINDINGS) {
  922. needs_bind |= uniform_buffer_binding_sizes[stage][binding_index] != size;
  923. }
  924. if (!needs_bind) {
  925. return;
  926. }
  927. const u32 offset = buffer.Offset(cpu_addr);
  928. if constexpr (IS_OPENGL) {
  929. // Fast buffer will be unbound
  930. fast_bound_uniform_buffers[stage] &= ~(1U << binding_index);
  931. // Mark the index as dirty if offset doesn't match
  932. const bool is_copy_bind = offset != 0 && !runtime.SupportsNonZeroUniformOffset();
  933. dirty_uniform_buffers[stage] |= (is_copy_bind ? 1U : 0U) << index;
  934. }
  935. if constexpr (HAS_PERSISTENT_UNIFORM_BUFFER_BINDINGS) {
  936. uniform_buffer_binding_sizes[stage][binding_index] = size;
  937. }
  938. if constexpr (NEEDS_BIND_UNIFORM_INDEX) {
  939. runtime.BindUniformBuffer(stage, binding_index, buffer, offset, size);
  940. } else {
  941. runtime.BindUniformBuffer(buffer, offset, size);
  942. }
  943. }
  944. template <class P>
  945. void BufferCache<P>::BindHostGraphicsStorageBuffers(size_t stage) {
  946. u32 binding_index = 0;
  947. ForEachEnabledBit(enabled_storage_buffers[stage], [&](u32 index) {
  948. const Binding& binding = storage_buffers[stage][index];
  949. Buffer& buffer = slot_buffers[binding.buffer_id];
  950. TouchBuffer(buffer, binding.buffer_id);
  951. const u32 size = binding.size;
  952. SynchronizeBuffer(buffer, binding.cpu_addr, size);
  953. const u32 offset = buffer.Offset(binding.cpu_addr);
  954. const bool is_written = ((written_storage_buffers[stage] >> index) & 1) != 0;
  955. if constexpr (NEEDS_BIND_STORAGE_INDEX) {
  956. runtime.BindStorageBuffer(stage, binding_index, buffer, offset, size, is_written);
  957. ++binding_index;
  958. } else {
  959. runtime.BindStorageBuffer(buffer, offset, size, is_written);
  960. }
  961. });
  962. }
  963. template <class P>
  964. void BufferCache<P>::BindHostGraphicsTextureBuffers(size_t stage) {
  965. ForEachEnabledBit(enabled_texture_buffers[stage], [&](u32 index) {
  966. const TextureBufferBinding& binding = texture_buffers[stage][index];
  967. Buffer& buffer = slot_buffers[binding.buffer_id];
  968. const u32 size = binding.size;
  969. SynchronizeBuffer(buffer, binding.cpu_addr, size);
  970. const u32 offset = buffer.Offset(binding.cpu_addr);
  971. const PixelFormat format = binding.format;
  972. if constexpr (SEPARATE_IMAGE_BUFFERS_BINDINGS) {
  973. if (((image_texture_buffers[stage] >> index) & 1) != 0) {
  974. runtime.BindImageBuffer(buffer, offset, size, format);
  975. } else {
  976. runtime.BindTextureBuffer(buffer, offset, size, format);
  977. }
  978. } else {
  979. runtime.BindTextureBuffer(buffer, offset, size, format);
  980. }
  981. });
  982. }
  983. template <class P>
  984. void BufferCache<P>::BindHostTransformFeedbackBuffers() {
  985. if (maxwell3d->regs.transform_feedback_enabled == 0) {
  986. return;
  987. }
  988. for (u32 index = 0; index < NUM_TRANSFORM_FEEDBACK_BUFFERS; ++index) {
  989. const Binding& binding = transform_feedback_buffers[index];
  990. Buffer& buffer = slot_buffers[binding.buffer_id];
  991. TouchBuffer(buffer, binding.buffer_id);
  992. const u32 size = binding.size;
  993. SynchronizeBuffer(buffer, binding.cpu_addr, size);
  994. const u32 offset = buffer.Offset(binding.cpu_addr);
  995. runtime.BindTransformFeedbackBuffer(index, buffer, offset, size);
  996. }
  997. }
  998. template <class P>
  999. void BufferCache<P>::BindHostComputeUniformBuffers() {
  1000. if constexpr (HAS_PERSISTENT_UNIFORM_BUFFER_BINDINGS) {
  1001. // Mark all uniform buffers as dirty
  1002. dirty_uniform_buffers.fill(~u32{0});
  1003. fast_bound_uniform_buffers.fill(0);
  1004. }
  1005. u32 binding_index = 0;
  1006. ForEachEnabledBit(enabled_compute_uniform_buffer_mask, [&](u32 index) {
  1007. const Binding& binding = compute_uniform_buffers[index];
  1008. Buffer& buffer = slot_buffers[binding.buffer_id];
  1009. TouchBuffer(buffer, binding.buffer_id);
  1010. const u32 size = std::min(binding.size, (*compute_uniform_buffer_sizes)[index]);
  1011. SynchronizeBuffer(buffer, binding.cpu_addr, size);
  1012. const u32 offset = buffer.Offset(binding.cpu_addr);
  1013. if constexpr (NEEDS_BIND_UNIFORM_INDEX) {
  1014. runtime.BindComputeUniformBuffer(binding_index, buffer, offset, size);
  1015. ++binding_index;
  1016. } else {
  1017. runtime.BindUniformBuffer(buffer, offset, size);
  1018. }
  1019. });
  1020. }
  1021. template <class P>
  1022. void BufferCache<P>::BindHostComputeStorageBuffers() {
  1023. u32 binding_index = 0;
  1024. ForEachEnabledBit(enabled_compute_storage_buffers, [&](u32 index) {
  1025. const Binding& binding = compute_storage_buffers[index];
  1026. Buffer& buffer = slot_buffers[binding.buffer_id];
  1027. TouchBuffer(buffer, binding.buffer_id);
  1028. const u32 size = binding.size;
  1029. SynchronizeBuffer(buffer, binding.cpu_addr, size);
  1030. const u32 offset = buffer.Offset(binding.cpu_addr);
  1031. const bool is_written = ((written_compute_storage_buffers >> index) & 1) != 0;
  1032. if constexpr (NEEDS_BIND_STORAGE_INDEX) {
  1033. runtime.BindComputeStorageBuffer(binding_index, buffer, offset, size, is_written);
  1034. ++binding_index;
  1035. } else {
  1036. runtime.BindStorageBuffer(buffer, offset, size, is_written);
  1037. }
  1038. });
  1039. }
  1040. template <class P>
  1041. void BufferCache<P>::BindHostComputeTextureBuffers() {
  1042. ForEachEnabledBit(enabled_compute_texture_buffers, [&](u32 index) {
  1043. const TextureBufferBinding& binding = compute_texture_buffers[index];
  1044. Buffer& buffer = slot_buffers[binding.buffer_id];
  1045. const u32 size = binding.size;
  1046. SynchronizeBuffer(buffer, binding.cpu_addr, size);
  1047. const u32 offset = buffer.Offset(binding.cpu_addr);
  1048. const PixelFormat format = binding.format;
  1049. if constexpr (SEPARATE_IMAGE_BUFFERS_BINDINGS) {
  1050. if (((image_compute_texture_buffers >> index) & 1) != 0) {
  1051. runtime.BindImageBuffer(buffer, offset, size, format);
  1052. } else {
  1053. runtime.BindTextureBuffer(buffer, offset, size, format);
  1054. }
  1055. } else {
  1056. runtime.BindTextureBuffer(buffer, offset, size, format);
  1057. }
  1058. });
  1059. }
  1060. template <class P>
  1061. void BufferCache<P>::DoUpdateGraphicsBuffers(bool is_indexed) {
  1062. do {
  1063. has_deleted_buffers = false;
  1064. if (is_indexed) {
  1065. UpdateIndexBuffer();
  1066. }
  1067. UpdateVertexBuffers();
  1068. UpdateTransformFeedbackBuffers();
  1069. for (size_t stage = 0; stage < NUM_STAGES; ++stage) {
  1070. UpdateUniformBuffers(stage);
  1071. UpdateStorageBuffers(stage);
  1072. UpdateTextureBuffers(stage);
  1073. }
  1074. } while (has_deleted_buffers);
  1075. }
  1076. template <class P>
  1077. void BufferCache<P>::DoUpdateComputeBuffers() {
  1078. UpdateComputeUniformBuffers();
  1079. UpdateComputeStorageBuffers();
  1080. UpdateComputeTextureBuffers();
  1081. }
  1082. template <class P>
  1083. void BufferCache<P>::UpdateIndexBuffer() {
  1084. // We have to check for the dirty flags and index count
  1085. // The index count is currently changed without updating the dirty flags
  1086. const auto& draw_state = maxwell3d->draw_manager->GetDrawState();
  1087. const auto& index_array = draw_state.index_buffer;
  1088. auto& flags = maxwell3d->dirty.flags;
  1089. if (!flags[Dirty::IndexBuffer] && last_index_count == index_array.count) {
  1090. return;
  1091. }
  1092. flags[Dirty::IndexBuffer] = false;
  1093. last_index_count = index_array.count;
  1094. if (!draw_state.inline_index_draw_indexes.empty()) {
  1095. auto inline_index_size = static_cast<u32>(draw_state.inline_index_draw_indexes.size());
  1096. index_buffer = Binding{
  1097. .cpu_addr = 0,
  1098. .size = inline_index_size,
  1099. .buffer_id = CreateBuffer(0, inline_index_size),
  1100. };
  1101. return;
  1102. }
  1103. const GPUVAddr gpu_addr_begin = index_array.StartAddress();
  1104. const GPUVAddr gpu_addr_end = index_array.EndAddress();
  1105. const std::optional<VAddr> cpu_addr = gpu_memory->GpuToCpuAddress(gpu_addr_begin);
  1106. const u32 address_size = static_cast<u32>(gpu_addr_end - gpu_addr_begin);
  1107. const u32 draw_size = (index_array.count + index_array.first) * index_array.FormatSizeInBytes();
  1108. const u32 size = std::min(address_size, draw_size);
  1109. if (size == 0 || !cpu_addr) {
  1110. index_buffer = NULL_BINDING;
  1111. return;
  1112. }
  1113. index_buffer = Binding{
  1114. .cpu_addr = *cpu_addr,
  1115. .size = size,
  1116. .buffer_id = FindBuffer(*cpu_addr, size),
  1117. };
  1118. }
  1119. template <class P>
  1120. void BufferCache<P>::UpdateVertexBuffers() {
  1121. auto& flags = maxwell3d->dirty.flags;
  1122. if (!maxwell3d->dirty.flags[Dirty::VertexBuffers]) {
  1123. return;
  1124. }
  1125. flags[Dirty::VertexBuffers] = false;
  1126. for (u32 index = 0; index < NUM_VERTEX_BUFFERS; ++index) {
  1127. UpdateVertexBuffer(index);
  1128. }
  1129. }
  1130. template <class P>
  1131. void BufferCache<P>::UpdateVertexBuffer(u32 index) {
  1132. if (!maxwell3d->dirty.flags[Dirty::VertexBuffer0 + index]) {
  1133. return;
  1134. }
  1135. const auto& array = maxwell3d->regs.vertex_streams[index];
  1136. const auto& limit = maxwell3d->regs.vertex_stream_limits[index];
  1137. const GPUVAddr gpu_addr_begin = array.Address();
  1138. const GPUVAddr gpu_addr_end = limit.Address() + 1;
  1139. const std::optional<VAddr> cpu_addr = gpu_memory->GpuToCpuAddress(gpu_addr_begin);
  1140. u32 address_size = static_cast<u32>(
  1141. std::min(gpu_addr_end - gpu_addr_begin, static_cast<u64>(std::numeric_limits<u32>::max())));
  1142. if (array.enable == 0 || address_size == 0 || !cpu_addr) {
  1143. vertex_buffers[index] = NULL_BINDING;
  1144. return;
  1145. }
  1146. if (!gpu_memory->IsWithinGPUAddressRange(gpu_addr_end)) {
  1147. address_size =
  1148. static_cast<u32>(gpu_memory->MaxContinousRange(gpu_addr_begin, address_size));
  1149. }
  1150. const u32 size = address_size; // TODO: Analyze stride and number of vertices
  1151. vertex_buffers[index] = Binding{
  1152. .cpu_addr = *cpu_addr,
  1153. .size = size,
  1154. .buffer_id = FindBuffer(*cpu_addr, size),
  1155. };
  1156. }
  1157. template <class P>
  1158. void BufferCache<P>::UpdateUniformBuffers(size_t stage) {
  1159. ForEachEnabledBit(enabled_uniform_buffer_masks[stage], [&](u32 index) {
  1160. Binding& binding = uniform_buffers[stage][index];
  1161. if (binding.buffer_id) {
  1162. // Already updated
  1163. return;
  1164. }
  1165. // Mark as dirty
  1166. if constexpr (HAS_PERSISTENT_UNIFORM_BUFFER_BINDINGS) {
  1167. dirty_uniform_buffers[stage] |= 1U << index;
  1168. }
  1169. // Resolve buffer
  1170. binding.buffer_id = FindBuffer(binding.cpu_addr, binding.size);
  1171. });
  1172. }
  1173. template <class P>
  1174. void BufferCache<P>::UpdateStorageBuffers(size_t stage) {
  1175. const u32 written_mask = written_storage_buffers[stage];
  1176. ForEachEnabledBit(enabled_storage_buffers[stage], [&](u32 index) {
  1177. // Resolve buffer
  1178. Binding& binding = storage_buffers[stage][index];
  1179. const BufferId buffer_id = FindBuffer(binding.cpu_addr, binding.size);
  1180. binding.buffer_id = buffer_id;
  1181. // Mark buffer as written if needed
  1182. if (((written_mask >> index) & 1) != 0) {
  1183. MarkWrittenBuffer(buffer_id, binding.cpu_addr, binding.size);
  1184. }
  1185. });
  1186. }
  1187. template <class P>
  1188. void BufferCache<P>::UpdateTextureBuffers(size_t stage) {
  1189. ForEachEnabledBit(enabled_texture_buffers[stage], [&](u32 index) {
  1190. Binding& binding = texture_buffers[stage][index];
  1191. binding.buffer_id = FindBuffer(binding.cpu_addr, binding.size);
  1192. // Mark buffer as written if needed
  1193. if (((written_texture_buffers[stage] >> index) & 1) != 0) {
  1194. MarkWrittenBuffer(binding.buffer_id, binding.cpu_addr, binding.size);
  1195. }
  1196. });
  1197. }
  1198. template <class P>
  1199. void BufferCache<P>::UpdateTransformFeedbackBuffers() {
  1200. if (maxwell3d->regs.transform_feedback_enabled == 0) {
  1201. return;
  1202. }
  1203. for (u32 index = 0; index < NUM_TRANSFORM_FEEDBACK_BUFFERS; ++index) {
  1204. UpdateTransformFeedbackBuffer(index);
  1205. }
  1206. }
  1207. template <class P>
  1208. void BufferCache<P>::UpdateTransformFeedbackBuffer(u32 index) {
  1209. const auto& binding = maxwell3d->regs.transform_feedback.buffers[index];
  1210. const GPUVAddr gpu_addr = binding.Address() + binding.start_offset;
  1211. const u32 size = binding.size;
  1212. const std::optional<VAddr> cpu_addr = gpu_memory->GpuToCpuAddress(gpu_addr);
  1213. if (binding.enable == 0 || size == 0 || !cpu_addr) {
  1214. transform_feedback_buffers[index] = NULL_BINDING;
  1215. return;
  1216. }
  1217. const BufferId buffer_id = FindBuffer(*cpu_addr, size);
  1218. transform_feedback_buffers[index] = Binding{
  1219. .cpu_addr = *cpu_addr,
  1220. .size = size,
  1221. .buffer_id = buffer_id,
  1222. };
  1223. MarkWrittenBuffer(buffer_id, *cpu_addr, size);
  1224. }
  1225. template <class P>
  1226. void BufferCache<P>::UpdateComputeUniformBuffers() {
  1227. ForEachEnabledBit(enabled_compute_uniform_buffer_mask, [&](u32 index) {
  1228. Binding& binding = compute_uniform_buffers[index];
  1229. binding = NULL_BINDING;
  1230. const auto& launch_desc = kepler_compute->launch_description;
  1231. if (((launch_desc.const_buffer_enable_mask >> index) & 1) != 0) {
  1232. const auto& cbuf = launch_desc.const_buffer_config[index];
  1233. const std::optional<VAddr> cpu_addr = gpu_memory->GpuToCpuAddress(cbuf.Address());
  1234. if (cpu_addr) {
  1235. binding.cpu_addr = *cpu_addr;
  1236. binding.size = cbuf.size;
  1237. }
  1238. }
  1239. binding.buffer_id = FindBuffer(binding.cpu_addr, binding.size);
  1240. });
  1241. }
  1242. template <class P>
  1243. void BufferCache<P>::UpdateComputeStorageBuffers() {
  1244. ForEachEnabledBit(enabled_compute_storage_buffers, [&](u32 index) {
  1245. // Resolve buffer
  1246. Binding& binding = compute_storage_buffers[index];
  1247. binding.buffer_id = FindBuffer(binding.cpu_addr, binding.size);
  1248. // Mark as written if needed
  1249. if (((written_compute_storage_buffers >> index) & 1) != 0) {
  1250. MarkWrittenBuffer(binding.buffer_id, binding.cpu_addr, binding.size);
  1251. }
  1252. });
  1253. }
  1254. template <class P>
  1255. void BufferCache<P>::UpdateComputeTextureBuffers() {
  1256. ForEachEnabledBit(enabled_compute_texture_buffers, [&](u32 index) {
  1257. Binding& binding = compute_texture_buffers[index];
  1258. binding.buffer_id = FindBuffer(binding.cpu_addr, binding.size);
  1259. // Mark as written if needed
  1260. if (((written_compute_texture_buffers >> index) & 1) != 0) {
  1261. MarkWrittenBuffer(binding.buffer_id, binding.cpu_addr, binding.size);
  1262. }
  1263. });
  1264. }
  1265. template <class P>
  1266. void BufferCache<P>::MarkWrittenBuffer(BufferId buffer_id, VAddr cpu_addr, u32 size) {
  1267. Buffer& buffer = slot_buffers[buffer_id];
  1268. buffer.MarkRegionAsGpuModified(cpu_addr, size);
  1269. const IntervalType base_interval{cpu_addr, cpu_addr + size};
  1270. common_ranges.add(base_interval);
  1271. const bool is_async = Settings::values.use_asynchronous_gpu_emulation.GetValue();
  1272. if (!is_async) {
  1273. return;
  1274. }
  1275. uncommitted_ranges.add(base_interval);
  1276. }
  1277. template <class P>
  1278. BufferId BufferCache<P>::FindBuffer(VAddr cpu_addr, u32 size) {
  1279. if (cpu_addr == 0) {
  1280. return NULL_BUFFER_ID;
  1281. }
  1282. const u64 page = cpu_addr >> YUZU_PAGEBITS;
  1283. const BufferId buffer_id = page_table[page];
  1284. if (!buffer_id) {
  1285. return CreateBuffer(cpu_addr, size);
  1286. }
  1287. const Buffer& buffer = slot_buffers[buffer_id];
  1288. if (buffer.IsInBounds(cpu_addr, size)) {
  1289. return buffer_id;
  1290. }
  1291. return CreateBuffer(cpu_addr, size);
  1292. }
  1293. template <class P>
  1294. typename BufferCache<P>::OverlapResult BufferCache<P>::ResolveOverlaps(VAddr cpu_addr,
  1295. u32 wanted_size) {
  1296. static constexpr int STREAM_LEAP_THRESHOLD = 16;
  1297. std::vector<BufferId> overlap_ids;
  1298. VAddr begin = cpu_addr;
  1299. VAddr end = cpu_addr + wanted_size;
  1300. int stream_score = 0;
  1301. bool has_stream_leap = false;
  1302. if (begin == 0) {
  1303. return OverlapResult{
  1304. .ids = std::move(overlap_ids),
  1305. .begin = begin,
  1306. .end = end,
  1307. .has_stream_leap = has_stream_leap,
  1308. };
  1309. }
  1310. for (; cpu_addr >> YUZU_PAGEBITS < Common::DivCeil(end, YUZU_PAGESIZE);
  1311. cpu_addr += YUZU_PAGESIZE) {
  1312. const BufferId overlap_id = page_table[cpu_addr >> YUZU_PAGEBITS];
  1313. if (!overlap_id) {
  1314. continue;
  1315. }
  1316. Buffer& overlap = slot_buffers[overlap_id];
  1317. if (overlap.IsPicked()) {
  1318. continue;
  1319. }
  1320. overlap_ids.push_back(overlap_id);
  1321. overlap.Pick();
  1322. const VAddr overlap_cpu_addr = overlap.CpuAddr();
  1323. const bool expands_left = overlap_cpu_addr < begin;
  1324. if (expands_left) {
  1325. cpu_addr = begin = overlap_cpu_addr;
  1326. }
  1327. const VAddr overlap_end = overlap_cpu_addr + overlap.SizeBytes();
  1328. const bool expands_right = overlap_end > end;
  1329. if (overlap_end > end) {
  1330. end = overlap_end;
  1331. }
  1332. stream_score += overlap.StreamScore();
  1333. if (stream_score > STREAM_LEAP_THRESHOLD && !has_stream_leap) {
  1334. // When this memory region has been joined a bunch of times, we assume it's being used
  1335. // as a stream buffer. Increase the size to skip constantly recreating buffers.
  1336. has_stream_leap = true;
  1337. if (expands_right) {
  1338. begin -= YUZU_PAGESIZE * 256;
  1339. cpu_addr = begin;
  1340. }
  1341. if (expands_left) {
  1342. end += YUZU_PAGESIZE * 256;
  1343. }
  1344. }
  1345. }
  1346. return OverlapResult{
  1347. .ids = std::move(overlap_ids),
  1348. .begin = begin,
  1349. .end = end,
  1350. .has_stream_leap = has_stream_leap,
  1351. };
  1352. }
  1353. template <class P>
  1354. void BufferCache<P>::JoinOverlap(BufferId new_buffer_id, BufferId overlap_id,
  1355. bool accumulate_stream_score) {
  1356. Buffer& new_buffer = slot_buffers[new_buffer_id];
  1357. Buffer& overlap = slot_buffers[overlap_id];
  1358. if (accumulate_stream_score) {
  1359. new_buffer.IncreaseStreamScore(overlap.StreamScore() + 1);
  1360. }
  1361. std::vector<BufferCopy> copies;
  1362. const size_t dst_base_offset = overlap.CpuAddr() - new_buffer.CpuAddr();
  1363. overlap.ForEachDownloadRange([&](u64 begin, u64 range_size) {
  1364. copies.push_back(BufferCopy{
  1365. .src_offset = begin,
  1366. .dst_offset = dst_base_offset + begin,
  1367. .size = range_size,
  1368. });
  1369. new_buffer.UnmarkRegionAsCpuModified(begin, range_size);
  1370. new_buffer.MarkRegionAsGpuModified(begin, range_size);
  1371. });
  1372. if (!copies.empty()) {
  1373. runtime.CopyBuffer(slot_buffers[new_buffer_id], overlap, copies);
  1374. }
  1375. DeleteBuffer(overlap_id);
  1376. }
  1377. template <class P>
  1378. BufferId BufferCache<P>::CreateBuffer(VAddr cpu_addr, u32 wanted_size) {
  1379. const OverlapResult overlap = ResolveOverlaps(cpu_addr, wanted_size);
  1380. const u32 size = static_cast<u32>(overlap.end - overlap.begin);
  1381. const BufferId new_buffer_id = slot_buffers.insert(runtime, rasterizer, overlap.begin, size);
  1382. auto& new_buffer = slot_buffers[new_buffer_id];
  1383. runtime.ClearBuffer(new_buffer, 0, new_buffer.SizeBytes(), 0);
  1384. for (const BufferId overlap_id : overlap.ids) {
  1385. JoinOverlap(new_buffer_id, overlap_id, !overlap.has_stream_leap);
  1386. }
  1387. Register(new_buffer_id);
  1388. TouchBuffer(slot_buffers[new_buffer_id], new_buffer_id);
  1389. return new_buffer_id;
  1390. }
  1391. template <class P>
  1392. void BufferCache<P>::Register(BufferId buffer_id) {
  1393. ChangeRegister<true>(buffer_id);
  1394. }
  1395. template <class P>
  1396. void BufferCache<P>::Unregister(BufferId buffer_id) {
  1397. ChangeRegister<false>(buffer_id);
  1398. }
  1399. template <class P>
  1400. template <bool insert>
  1401. void BufferCache<P>::ChangeRegister(BufferId buffer_id) {
  1402. Buffer& buffer = slot_buffers[buffer_id];
  1403. const auto size = buffer.SizeBytes();
  1404. if (insert) {
  1405. total_used_memory += Common::AlignUp(size, 1024);
  1406. buffer.setLRUID(lru_cache.Insert(buffer_id, frame_tick));
  1407. } else {
  1408. total_used_memory -= Common::AlignUp(size, 1024);
  1409. lru_cache.Free(buffer.getLRUID());
  1410. }
  1411. const VAddr cpu_addr_begin = buffer.CpuAddr();
  1412. const VAddr cpu_addr_end = cpu_addr_begin + size;
  1413. const u64 page_begin = cpu_addr_begin / YUZU_PAGESIZE;
  1414. const u64 page_end = Common::DivCeil(cpu_addr_end, YUZU_PAGESIZE);
  1415. for (u64 page = page_begin; page != page_end; ++page) {
  1416. if constexpr (insert) {
  1417. page_table[page] = buffer_id;
  1418. } else {
  1419. page_table[page] = BufferId{};
  1420. }
  1421. }
  1422. }
  1423. template <class P>
  1424. void BufferCache<P>::TouchBuffer(Buffer& buffer, BufferId buffer_id) noexcept {
  1425. if (buffer_id != NULL_BUFFER_ID) {
  1426. lru_cache.Touch(buffer.getLRUID(), frame_tick);
  1427. }
  1428. }
  1429. template <class P>
  1430. bool BufferCache<P>::SynchronizeBuffer(Buffer& buffer, VAddr cpu_addr, u32 size) {
  1431. if (buffer.CpuAddr() == 0) {
  1432. return true;
  1433. }
  1434. return SynchronizeBufferImpl(buffer, cpu_addr, size);
  1435. }
  1436. template <class P>
  1437. bool BufferCache<P>::SynchronizeBufferImpl(Buffer& buffer, VAddr cpu_addr, u32 size) {
  1438. boost::container::small_vector<BufferCopy, 4> copies;
  1439. u64 total_size_bytes = 0;
  1440. u64 largest_copy = 0;
  1441. buffer.ForEachUploadRange(cpu_addr, size, [&](u64 range_offset, u64 range_size) {
  1442. copies.push_back(BufferCopy{
  1443. .src_offset = total_size_bytes,
  1444. .dst_offset = range_offset,
  1445. .size = range_size,
  1446. });
  1447. total_size_bytes += range_size;
  1448. largest_copy = std::max(largest_copy, range_size);
  1449. });
  1450. if (total_size_bytes == 0) {
  1451. return true;
  1452. }
  1453. const std::span<BufferCopy> copies_span(copies.data(), copies.size());
  1454. UploadMemory(buffer, total_size_bytes, largest_copy, copies_span);
  1455. return false;
  1456. }
  1457. template <class P>
  1458. void BufferCache<P>::UploadMemory(Buffer& buffer, u64 total_size_bytes, u64 largest_copy,
  1459. std::span<BufferCopy> copies) {
  1460. if constexpr (USE_MEMORY_MAPS) {
  1461. MappedUploadMemory(buffer, total_size_bytes, copies);
  1462. } else {
  1463. ImmediateUploadMemory(buffer, largest_copy, copies);
  1464. }
  1465. }
  1466. template <class P>
  1467. void BufferCache<P>::ImmediateUploadMemory(Buffer& buffer, u64 largest_copy,
  1468. std::span<const BufferCopy> copies) {
  1469. std::span<u8> immediate_buffer;
  1470. for (const BufferCopy& copy : copies) {
  1471. std::span<const u8> upload_span;
  1472. const VAddr cpu_addr = buffer.CpuAddr() + copy.dst_offset;
  1473. if (IsRangeGranular(cpu_addr, copy.size)) {
  1474. upload_span = std::span(cpu_memory.GetPointer(cpu_addr), copy.size);
  1475. } else {
  1476. if (immediate_buffer.empty()) {
  1477. immediate_buffer = ImmediateBuffer(largest_copy);
  1478. }
  1479. cpu_memory.ReadBlockUnsafe(cpu_addr, immediate_buffer.data(), copy.size);
  1480. upload_span = immediate_buffer.subspan(0, copy.size);
  1481. }
  1482. buffer.ImmediateUpload(copy.dst_offset, upload_span);
  1483. }
  1484. }
  1485. template <class P>
  1486. void BufferCache<P>::MappedUploadMemory(Buffer& buffer, u64 total_size_bytes,
  1487. std::span<BufferCopy> copies) {
  1488. auto upload_staging = runtime.UploadStagingBuffer(total_size_bytes);
  1489. const std::span<u8> staging_pointer = upload_staging.mapped_span;
  1490. for (BufferCopy& copy : copies) {
  1491. u8* const src_pointer = staging_pointer.data() + copy.src_offset;
  1492. const VAddr cpu_addr = buffer.CpuAddr() + copy.dst_offset;
  1493. cpu_memory.ReadBlockUnsafe(cpu_addr, src_pointer, copy.size);
  1494. // Apply the staging offset
  1495. copy.src_offset += upload_staging.offset;
  1496. }
  1497. runtime.CopyBuffer(buffer, upload_staging.buffer, copies);
  1498. }
  1499. template <class P>
  1500. bool BufferCache<P>::InlineMemory(VAddr dest_address, size_t copy_size,
  1501. std::span<const u8> inlined_buffer) {
  1502. const bool is_dirty = IsRegionRegistered(dest_address, copy_size);
  1503. if (!is_dirty) {
  1504. return false;
  1505. }
  1506. if (!IsRegionGpuModified(dest_address, copy_size)) {
  1507. return false;
  1508. }
  1509. const IntervalType subtract_interval{dest_address, dest_address + copy_size};
  1510. ClearDownload(subtract_interval);
  1511. common_ranges.subtract(subtract_interval);
  1512. BufferId buffer_id = FindBuffer(dest_address, static_cast<u32>(copy_size));
  1513. auto& buffer = slot_buffers[buffer_id];
  1514. SynchronizeBuffer(buffer, dest_address, static_cast<u32>(copy_size));
  1515. if constexpr (USE_MEMORY_MAPS) {
  1516. auto upload_staging = runtime.UploadStagingBuffer(copy_size);
  1517. std::array copies{BufferCopy{
  1518. .src_offset = upload_staging.offset,
  1519. .dst_offset = buffer.Offset(dest_address),
  1520. .size = copy_size,
  1521. }};
  1522. u8* const src_pointer = upload_staging.mapped_span.data();
  1523. std::memcpy(src_pointer, inlined_buffer.data(), copy_size);
  1524. runtime.CopyBuffer(buffer, upload_staging.buffer, copies);
  1525. } else {
  1526. buffer.ImmediateUpload(buffer.Offset(dest_address), inlined_buffer.first(copy_size));
  1527. }
  1528. return true;
  1529. }
  1530. template <class P>
  1531. void BufferCache<P>::DownloadBufferMemory(Buffer& buffer) {
  1532. DownloadBufferMemory(buffer, buffer.CpuAddr(), buffer.SizeBytes());
  1533. }
  1534. template <class P>
  1535. void BufferCache<P>::DownloadBufferMemory(Buffer& buffer, VAddr cpu_addr, u64 size) {
  1536. boost::container::small_vector<BufferCopy, 1> copies;
  1537. u64 total_size_bytes = 0;
  1538. u64 largest_copy = 0;
  1539. buffer.ForEachDownloadRangeAndClear(cpu_addr, size, [&](u64 range_offset, u64 range_size) {
  1540. const VAddr buffer_addr = buffer.CpuAddr();
  1541. const auto add_download = [&](VAddr start, VAddr end) {
  1542. const u64 new_offset = start - buffer_addr;
  1543. const u64 new_size = end - start;
  1544. copies.push_back(BufferCopy{
  1545. .src_offset = new_offset,
  1546. .dst_offset = total_size_bytes,
  1547. .size = new_size,
  1548. });
  1549. // Align up to avoid cache conflicts
  1550. constexpr u64 align = 256ULL;
  1551. constexpr u64 mask = ~(align - 1ULL);
  1552. total_size_bytes += (new_size + align - 1) & mask;
  1553. largest_copy = std::max(largest_copy, new_size);
  1554. };
  1555. const VAddr start_address = buffer_addr + range_offset;
  1556. const VAddr end_address = start_address + range_size;
  1557. ForEachWrittenRange(start_address, range_size, add_download);
  1558. const IntervalType subtract_interval{start_address, end_address};
  1559. ClearDownload(subtract_interval);
  1560. common_ranges.subtract(subtract_interval);
  1561. });
  1562. if (total_size_bytes == 0) {
  1563. return;
  1564. }
  1565. MICROPROFILE_SCOPE(GPU_DownloadMemory);
  1566. if constexpr (USE_MEMORY_MAPS) {
  1567. auto download_staging = runtime.DownloadStagingBuffer(total_size_bytes);
  1568. const u8* const mapped_memory = download_staging.mapped_span.data();
  1569. const std::span<BufferCopy> copies_span(copies.data(), copies.data() + copies.size());
  1570. for (BufferCopy& copy : copies) {
  1571. // Modify copies to have the staging offset in mind
  1572. copy.dst_offset += download_staging.offset;
  1573. }
  1574. runtime.CopyBuffer(download_staging.buffer, buffer, copies_span);
  1575. runtime.Finish();
  1576. for (const BufferCopy& copy : copies) {
  1577. const VAddr copy_cpu_addr = buffer.CpuAddr() + copy.src_offset;
  1578. // Undo the modified offset
  1579. const u64 dst_offset = copy.dst_offset - download_staging.offset;
  1580. const u8* copy_mapped_memory = mapped_memory + dst_offset;
  1581. cpu_memory.WriteBlockUnsafe(copy_cpu_addr, copy_mapped_memory, copy.size);
  1582. }
  1583. } else {
  1584. const std::span<u8> immediate_buffer = ImmediateBuffer(largest_copy);
  1585. for (const BufferCopy& copy : copies) {
  1586. buffer.ImmediateDownload(copy.src_offset, immediate_buffer.subspan(0, copy.size));
  1587. const VAddr copy_cpu_addr = buffer.CpuAddr() + copy.src_offset;
  1588. cpu_memory.WriteBlockUnsafe(copy_cpu_addr, immediate_buffer.data(), copy.size);
  1589. }
  1590. }
  1591. }
  1592. template <class P>
  1593. void BufferCache<P>::DeleteBuffer(BufferId buffer_id) {
  1594. const auto scalar_replace = [buffer_id](Binding& binding) {
  1595. if (binding.buffer_id == buffer_id) {
  1596. binding.buffer_id = BufferId{};
  1597. }
  1598. };
  1599. const auto replace = [scalar_replace](std::span<Binding> bindings) {
  1600. std::ranges::for_each(bindings, scalar_replace);
  1601. };
  1602. scalar_replace(index_buffer);
  1603. replace(vertex_buffers);
  1604. std::ranges::for_each(uniform_buffers, replace);
  1605. std::ranges::for_each(storage_buffers, replace);
  1606. replace(transform_feedback_buffers);
  1607. replace(compute_uniform_buffers);
  1608. replace(compute_storage_buffers);
  1609. std::erase(cached_write_buffer_ids, buffer_id);
  1610. // Mark the whole buffer as CPU written to stop tracking CPU writes
  1611. Buffer& buffer = slot_buffers[buffer_id];
  1612. buffer.MarkRegionAsCpuModified(buffer.CpuAddr(), buffer.SizeBytes());
  1613. Unregister(buffer_id);
  1614. delayed_destruction_ring.Push(std::move(slot_buffers[buffer_id]));
  1615. slot_buffers.erase(buffer_id);
  1616. NotifyBufferDeletion();
  1617. }
  1618. template <class P>
  1619. void BufferCache<P>::NotifyBufferDeletion() {
  1620. if constexpr (HAS_PERSISTENT_UNIFORM_BUFFER_BINDINGS) {
  1621. dirty_uniform_buffers.fill(~u32{0});
  1622. uniform_buffer_binding_sizes.fill({});
  1623. }
  1624. auto& flags = maxwell3d->dirty.flags;
  1625. flags[Dirty::IndexBuffer] = true;
  1626. flags[Dirty::VertexBuffers] = true;
  1627. for (u32 index = 0; index < NUM_VERTEX_BUFFERS; ++index) {
  1628. flags[Dirty::VertexBuffer0 + index] = true;
  1629. }
  1630. has_deleted_buffers = true;
  1631. }
  1632. template <class P>
  1633. typename BufferCache<P>::Binding BufferCache<P>::StorageBufferBinding(GPUVAddr ssbo_addr,
  1634. bool is_written) const {
  1635. const GPUVAddr gpu_addr = gpu_memory->Read<u64>(ssbo_addr);
  1636. const u32 size = gpu_memory->Read<u32>(ssbo_addr + 8);
  1637. const std::optional<VAddr> cpu_addr = gpu_memory->GpuToCpuAddress(gpu_addr);
  1638. if (!cpu_addr || size == 0) {
  1639. return NULL_BINDING;
  1640. }
  1641. const VAddr cpu_end = Common::AlignUp(*cpu_addr + size, Core::Memory::YUZU_PAGESIZE);
  1642. const Binding binding{
  1643. .cpu_addr = *cpu_addr,
  1644. .size = is_written ? size : static_cast<u32>(cpu_end - *cpu_addr),
  1645. .buffer_id = BufferId{},
  1646. };
  1647. return binding;
  1648. }
  1649. template <class P>
  1650. typename BufferCache<P>::TextureBufferBinding BufferCache<P>::GetTextureBufferBinding(
  1651. GPUVAddr gpu_addr, u32 size, PixelFormat format) {
  1652. const std::optional<VAddr> cpu_addr = gpu_memory->GpuToCpuAddress(gpu_addr);
  1653. TextureBufferBinding binding;
  1654. if (!cpu_addr || size == 0) {
  1655. binding.cpu_addr = 0;
  1656. binding.size = 0;
  1657. binding.buffer_id = NULL_BUFFER_ID;
  1658. binding.format = PixelFormat::Invalid;
  1659. } else {
  1660. binding.cpu_addr = *cpu_addr;
  1661. binding.size = size;
  1662. binding.buffer_id = BufferId{};
  1663. binding.format = format;
  1664. }
  1665. return binding;
  1666. }
  1667. template <class P>
  1668. std::span<const u8> BufferCache<P>::ImmediateBufferWithData(VAddr cpu_addr, size_t size) {
  1669. u8* const base_pointer = cpu_memory.GetPointer(cpu_addr);
  1670. if (IsRangeGranular(cpu_addr, size) ||
  1671. base_pointer + size == cpu_memory.GetPointer(cpu_addr + size)) {
  1672. return std::span(base_pointer, size);
  1673. } else {
  1674. const std::span<u8> span = ImmediateBuffer(size);
  1675. cpu_memory.ReadBlockUnsafe(cpu_addr, span.data(), size);
  1676. return span;
  1677. }
  1678. }
  1679. template <class P>
  1680. std::span<u8> BufferCache<P>::ImmediateBuffer(size_t wanted_capacity) {
  1681. if (wanted_capacity > immediate_buffer_capacity) {
  1682. immediate_buffer_capacity = wanted_capacity;
  1683. immediate_buffer_alloc = std::make_unique<u8[]>(wanted_capacity);
  1684. }
  1685. return std::span<u8>(immediate_buffer_alloc.get(), wanted_capacity);
  1686. }
  1687. template <class P>
  1688. bool BufferCache<P>::HasFastUniformBufferBound(size_t stage, u32 binding_index) const noexcept {
  1689. if constexpr (IS_OPENGL) {
  1690. return ((fast_bound_uniform_buffers[stage] >> binding_index) & 1) != 0;
  1691. } else {
  1692. // Only OpenGL has fast uniform buffers
  1693. return false;
  1694. }
  1695. }
  1696. } // namespace VideoCommon