buffer_cache.h 72 KB

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