buffer_cache.h 78 KB

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