buffer_cache.h 71 KB

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