buffer_cache.h 76 KB

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