buffer_cache.h 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910
  1. // Copyright 2019 yuzu Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #pragma once
  5. #include <algorithm>
  6. #include <array>
  7. #include <deque>
  8. #include <memory>
  9. #include <mutex>
  10. #include <numeric>
  11. #include <span>
  12. #include <vector>
  13. #include <boost/container/small_vector.hpp>
  14. #include <boost/icl/interval_set.hpp>
  15. #include "common/common_types.h"
  16. #include "common/div_ceil.h"
  17. #include "common/literals.h"
  18. #include "common/lru_cache.h"
  19. #include "common/microprofile.h"
  20. #include "common/settings.h"
  21. #include "core/memory.h"
  22. #include "video_core/buffer_cache/buffer_base.h"
  23. #include "video_core/delayed_destruction_ring.h"
  24. #include "video_core/dirty_flags.h"
  25. #include "video_core/engines/kepler_compute.h"
  26. #include "video_core/engines/maxwell_3d.h"
  27. #include "video_core/memory_manager.h"
  28. #include "video_core/rasterizer_interface.h"
  29. #include "video_core/surface.h"
  30. #include "video_core/texture_cache/slot_vector.h"
  31. #include "video_core/texture_cache/types.h"
  32. namespace VideoCommon {
  33. MICROPROFILE_DECLARE(GPU_PrepareBuffers);
  34. MICROPROFILE_DECLARE(GPU_BindUploadBuffers);
  35. MICROPROFILE_DECLARE(GPU_DownloadMemory);
  36. using BufferId = SlotId;
  37. using VideoCore::Surface::PixelFormat;
  38. using namespace Common::Literals;
  39. constexpr u32 NUM_VERTEX_BUFFERS = 32;
  40. constexpr u32 NUM_TRANSFORM_FEEDBACK_BUFFERS = 4;
  41. constexpr u32 NUM_GRAPHICS_UNIFORM_BUFFERS = 18;
  42. constexpr u32 NUM_COMPUTE_UNIFORM_BUFFERS = 8;
  43. constexpr u32 NUM_STORAGE_BUFFERS = 16;
  44. constexpr u32 NUM_TEXTURE_BUFFERS = 16;
  45. constexpr u32 NUM_STAGES = 5;
  46. using UniformBufferSizes = std::array<std::array<u32, NUM_GRAPHICS_UNIFORM_BUFFERS>, NUM_STAGES>;
  47. using ComputeUniformBufferSizes = std::array<u32, NUM_COMPUTE_UNIFORM_BUFFERS>;
  48. template <typename P>
  49. class BufferCache {
  50. // Page size for caching purposes.
  51. // This is unrelated to the CPU page size and it can be changed as it seems optimal.
  52. static constexpr u32 PAGE_BITS = 16;
  53. static constexpr u64 PAGE_SIZE = u64{1} << PAGE_BITS;
  54. static constexpr bool IS_OPENGL = P::IS_OPENGL;
  55. static constexpr bool HAS_PERSISTENT_UNIFORM_BUFFER_BINDINGS =
  56. P::HAS_PERSISTENT_UNIFORM_BUFFER_BINDINGS;
  57. static constexpr bool HAS_FULL_INDEX_AND_PRIMITIVE_SUPPORT =
  58. P::HAS_FULL_INDEX_AND_PRIMITIVE_SUPPORT;
  59. static constexpr bool NEEDS_BIND_UNIFORM_INDEX = P::NEEDS_BIND_UNIFORM_INDEX;
  60. static constexpr bool NEEDS_BIND_STORAGE_INDEX = P::NEEDS_BIND_STORAGE_INDEX;
  61. static constexpr bool USE_MEMORY_MAPS = P::USE_MEMORY_MAPS;
  62. static constexpr bool SEPARATE_IMAGE_BUFFERS_BINDINGS = P::SEPARATE_IMAGE_BUFFER_BINDINGS;
  63. static constexpr BufferId NULL_BUFFER_ID{0};
  64. static constexpr s64 DEFAULT_EXPECTED_MEMORY = 512_MiB;
  65. static constexpr s64 DEFAULT_CRITICAL_MEMORY = 1_GiB;
  66. static constexpr s64 TARGET_THRESHOLD = 4_GiB;
  67. using Maxwell = Tegra::Engines::Maxwell3D::Regs;
  68. using Runtime = typename P::Runtime;
  69. using Buffer = typename P::Buffer;
  70. using IntervalSet = boost::icl::interval_set<VAddr>;
  71. using IntervalType = typename IntervalSet::interval_type;
  72. struct Empty {};
  73. struct OverlapResult {
  74. std::vector<BufferId> ids;
  75. VAddr begin;
  76. VAddr end;
  77. bool has_stream_leap = false;
  78. };
  79. struct Binding {
  80. VAddr cpu_addr{};
  81. u32 size{};
  82. BufferId buffer_id;
  83. };
  84. struct TextureBufferBinding : Binding {
  85. PixelFormat format;
  86. };
  87. static constexpr Binding NULL_BINDING{
  88. .cpu_addr = 0,
  89. .size = 0,
  90. .buffer_id = NULL_BUFFER_ID,
  91. };
  92. public:
  93. static constexpr u32 DEFAULT_SKIP_CACHE_SIZE = static_cast<u32>(4_KiB);
  94. explicit BufferCache(VideoCore::RasterizerInterface& rasterizer_,
  95. Tegra::Engines::Maxwell3D& maxwell3d_,
  96. Tegra::Engines::KeplerCompute& kepler_compute_,
  97. Tegra::MemoryManager& gpu_memory_, Core::Memory::Memory& cpu_memory_,
  98. Runtime& runtime_);
  99. void TickFrame();
  100. void WriteMemory(VAddr cpu_addr, u64 size);
  101. void CachedWriteMemory(VAddr cpu_addr, u64 size);
  102. void DownloadMemory(VAddr cpu_addr, u64 size);
  103. bool InlineMemory(VAddr dest_address, size_t copy_size, std::span<u8> inlined_buffer);
  104. void BindGraphicsUniformBuffer(size_t stage, u32 index, GPUVAddr gpu_addr, u32 size);
  105. void DisableGraphicsUniformBuffer(size_t stage, u32 index);
  106. void UpdateGraphicsBuffers(bool is_indexed);
  107. void UpdateComputeBuffers();
  108. void BindHostGeometryBuffers(bool is_indexed);
  109. void BindHostStageBuffers(size_t stage);
  110. void BindHostComputeBuffers();
  111. void SetUniformBuffersState(const std::array<u32, NUM_STAGES>& mask,
  112. const UniformBufferSizes* sizes);
  113. void SetComputeUniformBufferState(u32 mask, const ComputeUniformBufferSizes* sizes);
  114. void UnbindGraphicsStorageBuffers(size_t stage);
  115. void BindGraphicsStorageBuffer(size_t stage, size_t ssbo_index, u32 cbuf_index, u32 cbuf_offset,
  116. bool is_written);
  117. void UnbindGraphicsTextureBuffers(size_t stage);
  118. void BindGraphicsTextureBuffer(size_t stage, size_t tbo_index, GPUVAddr gpu_addr, u32 size,
  119. PixelFormat format, bool is_written, bool is_image);
  120. void UnbindComputeStorageBuffers();
  121. void BindComputeStorageBuffer(size_t ssbo_index, u32 cbuf_index, u32 cbuf_offset,
  122. bool is_written);
  123. void UnbindComputeTextureBuffers();
  124. void BindComputeTextureBuffer(size_t tbo_index, GPUVAddr gpu_addr, u32 size, PixelFormat format,
  125. bool is_written, bool is_image);
  126. void FlushCachedWrites();
  127. /// Return true when there are uncommitted buffers to be downloaded
  128. [[nodiscard]] bool HasUncommittedFlushes() const noexcept;
  129. void AccumulateFlushes();
  130. /// Return true when the caller should wait for async downloads
  131. [[nodiscard]] bool ShouldWaitAsyncFlushes() const noexcept;
  132. /// Commit asynchronous downloads
  133. void CommitAsyncFlushes();
  134. void CommitAsyncFlushesHigh();
  135. /// Pop asynchronous downloads
  136. void PopAsyncFlushes();
  137. bool DMACopy(GPUVAddr src_address, GPUVAddr dest_address, u64 amount);
  138. bool DMAClear(GPUVAddr src_address, u64 amount, u32 value);
  139. /// Return true when a CPU region is modified from the GPU
  140. [[nodiscard]] bool IsRegionGpuModified(VAddr addr, size_t size);
  141. /// Return true when a region is registered on the cache
  142. [[nodiscard]] bool IsRegionRegistered(VAddr addr, size_t size);
  143. /// Return true when a CPU region is modified from the CPU
  144. [[nodiscard]] bool IsRegionCpuModified(VAddr addr, size_t size);
  145. std::mutex mutex;
  146. Runtime& runtime;
  147. private:
  148. template <typename Func>
  149. static void ForEachEnabledBit(u32 enabled_mask, Func&& func) {
  150. for (u32 index = 0; enabled_mask != 0; ++index, enabled_mask >>= 1) {
  151. const int disabled_bits = std::countr_zero(enabled_mask);
  152. index += disabled_bits;
  153. enabled_mask >>= disabled_bits;
  154. func(index);
  155. }
  156. }
  157. template <typename Func>
  158. void ForEachBufferInRange(VAddr cpu_addr, u64 size, Func&& func) {
  159. const u64 page_end = Common::DivCeil(cpu_addr + size, PAGE_SIZE);
  160. for (u64 page = cpu_addr >> PAGE_BITS; page < page_end;) {
  161. const BufferId buffer_id = page_table[page];
  162. if (!buffer_id) {
  163. ++page;
  164. continue;
  165. }
  166. Buffer& buffer = slot_buffers[buffer_id];
  167. func(buffer_id, buffer);
  168. const VAddr end_addr = buffer.CpuAddr() + buffer.SizeBytes();
  169. page = Common::DivCeil(end_addr, PAGE_SIZE);
  170. }
  171. }
  172. template <typename Func>
  173. void ForEachWrittenRange(VAddr cpu_addr, u64 size, Func&& func) {
  174. const VAddr start_address = cpu_addr;
  175. const VAddr end_address = start_address + size;
  176. const VAddr search_base =
  177. static_cast<VAddr>(std::min<s64>(0LL, static_cast<s64>(start_address - size)));
  178. const IntervalType search_interval{search_base, search_base + 1};
  179. auto it = common_ranges.lower_bound(search_interval);
  180. if (it == common_ranges.end()) {
  181. it = common_ranges.begin();
  182. }
  183. for (; it != common_ranges.end(); it++) {
  184. VAddr inter_addr_end = it->upper();
  185. VAddr inter_addr = it->lower();
  186. if (inter_addr >= end_address) {
  187. break;
  188. }
  189. if (inter_addr_end <= start_address) {
  190. continue;
  191. }
  192. if (inter_addr_end > end_address) {
  193. inter_addr_end = end_address;
  194. }
  195. if (inter_addr < start_address) {
  196. inter_addr = start_address;
  197. }
  198. func(inter_addr, inter_addr_end);
  199. }
  200. }
  201. static bool IsRangeGranular(VAddr cpu_addr, size_t size) {
  202. return (cpu_addr & ~Core::Memory::PAGE_MASK) ==
  203. ((cpu_addr + size) & ~Core::Memory::PAGE_MASK);
  204. }
  205. void RunGarbageCollector();
  206. void BindHostIndexBuffer();
  207. void BindHostVertexBuffers();
  208. void BindHostGraphicsUniformBuffers(size_t stage);
  209. void BindHostGraphicsUniformBuffer(size_t stage, u32 index, u32 binding_index, bool needs_bind);
  210. void BindHostGraphicsStorageBuffers(size_t stage);
  211. void BindHostGraphicsTextureBuffers(size_t stage);
  212. void BindHostTransformFeedbackBuffers();
  213. void BindHostComputeUniformBuffers();
  214. void BindHostComputeStorageBuffers();
  215. void BindHostComputeTextureBuffers();
  216. void DoUpdateGraphicsBuffers(bool is_indexed);
  217. void DoUpdateComputeBuffers();
  218. void UpdateIndexBuffer();
  219. void UpdateVertexBuffers();
  220. void UpdateVertexBuffer(u32 index);
  221. void UpdateUniformBuffers(size_t stage);
  222. void UpdateStorageBuffers(size_t stage);
  223. void UpdateTextureBuffers(size_t stage);
  224. void UpdateTransformFeedbackBuffers();
  225. void UpdateTransformFeedbackBuffer(u32 index);
  226. void UpdateComputeUniformBuffers();
  227. void UpdateComputeStorageBuffers();
  228. void UpdateComputeTextureBuffers();
  229. void MarkWrittenBuffer(BufferId buffer_id, VAddr cpu_addr, u32 size);
  230. [[nodiscard]] BufferId FindBuffer(VAddr cpu_addr, u32 size);
  231. [[nodiscard]] OverlapResult ResolveOverlaps(VAddr cpu_addr, u32 wanted_size);
  232. void JoinOverlap(BufferId new_buffer_id, BufferId overlap_id, bool accumulate_stream_score);
  233. [[nodiscard]] BufferId CreateBuffer(VAddr cpu_addr, u32 wanted_size);
  234. void Register(BufferId buffer_id);
  235. void Unregister(BufferId buffer_id);
  236. template <bool insert>
  237. void ChangeRegister(BufferId buffer_id);
  238. void TouchBuffer(Buffer& buffer, BufferId buffer_id) noexcept;
  239. bool SynchronizeBuffer(Buffer& buffer, VAddr cpu_addr, u32 size);
  240. bool SynchronizeBufferImpl(Buffer& buffer, VAddr cpu_addr, u32 size);
  241. void UploadMemory(Buffer& buffer, u64 total_size_bytes, u64 largest_copy,
  242. std::span<BufferCopy> copies);
  243. void ImmediateUploadMemory(Buffer& buffer, u64 largest_copy,
  244. std::span<const BufferCopy> copies);
  245. void MappedUploadMemory(Buffer& buffer, u64 total_size_bytes, std::span<BufferCopy> copies);
  246. void DownloadBufferMemory(Buffer& buffer_id);
  247. void DownloadBufferMemory(Buffer& buffer_id, VAddr cpu_addr, u64 size);
  248. void DeleteBuffer(BufferId buffer_id);
  249. void NotifyBufferDeletion();
  250. [[nodiscard]] Binding StorageBufferBinding(GPUVAddr ssbo_addr) const;
  251. [[nodiscard]] TextureBufferBinding GetTextureBufferBinding(GPUVAddr gpu_addr, u32 size,
  252. PixelFormat format);
  253. [[nodiscard]] std::span<const u8> ImmediateBufferWithData(VAddr cpu_addr, size_t size);
  254. [[nodiscard]] std::span<u8> ImmediateBuffer(size_t wanted_capacity);
  255. [[nodiscard]] bool HasFastUniformBufferBound(size_t stage, u32 binding_index) const noexcept;
  256. void ClearDownload(IntervalType subtract_interval);
  257. VideoCore::RasterizerInterface& rasterizer;
  258. Tegra::Engines::Maxwell3D& maxwell3d;
  259. Tegra::Engines::KeplerCompute& kepler_compute;
  260. Tegra::MemoryManager& gpu_memory;
  261. Core::Memory::Memory& cpu_memory;
  262. SlotVector<Buffer> slot_buffers;
  263. DelayedDestructionRing<Buffer, 8> delayed_destruction_ring;
  264. u32 last_index_count = 0;
  265. Binding index_buffer;
  266. std::array<Binding, NUM_VERTEX_BUFFERS> vertex_buffers;
  267. std::array<std::array<Binding, NUM_GRAPHICS_UNIFORM_BUFFERS>, NUM_STAGES> uniform_buffers;
  268. std::array<std::array<Binding, NUM_STORAGE_BUFFERS>, NUM_STAGES> storage_buffers;
  269. std::array<std::array<TextureBufferBinding, NUM_TEXTURE_BUFFERS>, NUM_STAGES> texture_buffers;
  270. std::array<Binding, NUM_TRANSFORM_FEEDBACK_BUFFERS> transform_feedback_buffers;
  271. std::array<Binding, NUM_COMPUTE_UNIFORM_BUFFERS> compute_uniform_buffers;
  272. std::array<Binding, NUM_STORAGE_BUFFERS> compute_storage_buffers;
  273. std::array<TextureBufferBinding, NUM_TEXTURE_BUFFERS> compute_texture_buffers;
  274. std::array<u32, NUM_STAGES> enabled_uniform_buffer_masks{};
  275. u32 enabled_compute_uniform_buffer_mask = 0;
  276. const UniformBufferSizes* uniform_buffer_sizes{};
  277. const ComputeUniformBufferSizes* compute_uniform_buffer_sizes{};
  278. std::array<u32, NUM_STAGES> enabled_storage_buffers{};
  279. std::array<u32, NUM_STAGES> written_storage_buffers{};
  280. u32 enabled_compute_storage_buffers = 0;
  281. u32 written_compute_storage_buffers = 0;
  282. std::array<u32, NUM_STAGES> enabled_texture_buffers{};
  283. std::array<u32, NUM_STAGES> written_texture_buffers{};
  284. std::array<u32, NUM_STAGES> image_texture_buffers{};
  285. u32 enabled_compute_texture_buffers = 0;
  286. u32 written_compute_texture_buffers = 0;
  287. u32 image_compute_texture_buffers = 0;
  288. std::array<u32, 16> uniform_cache_hits{};
  289. std::array<u32, 16> uniform_cache_shots{};
  290. u32 uniform_buffer_skip_cache_size = DEFAULT_SKIP_CACHE_SIZE;
  291. bool has_deleted_buffers = false;
  292. std::conditional_t<HAS_PERSISTENT_UNIFORM_BUFFER_BINDINGS, std::array<u32, NUM_STAGES>, Empty>
  293. dirty_uniform_buffers{};
  294. std::conditional_t<IS_OPENGL, std::array<u32, NUM_STAGES>, Empty> fast_bound_uniform_buffers{};
  295. std::conditional_t<HAS_PERSISTENT_UNIFORM_BUFFER_BINDINGS,
  296. std::array<std::array<u32, NUM_GRAPHICS_UNIFORM_BUFFERS>, NUM_STAGES>, Empty>
  297. uniform_buffer_binding_sizes{};
  298. std::vector<BufferId> cached_write_buffer_ids;
  299. IntervalSet uncommitted_ranges;
  300. IntervalSet common_ranges;
  301. std::deque<IntervalSet> committed_ranges;
  302. size_t immediate_buffer_capacity = 0;
  303. std::unique_ptr<u8[]> immediate_buffer_alloc;
  304. struct LRUItemParams {
  305. using ObjectType = BufferId;
  306. using TickType = u64;
  307. };
  308. Common::LeastRecentlyUsedCache<LRUItemParams> lru_cache;
  309. u64 frame_tick = 0;
  310. u64 total_used_memory = 0;
  311. u64 minimum_memory = 0;
  312. u64 critical_memory = 0;
  313. std::array<BufferId, ((1ULL << 39) >> PAGE_BITS)> page_table;
  314. };
  315. template <class P>
  316. BufferCache<P>::BufferCache(VideoCore::RasterizerInterface& rasterizer_,
  317. Tegra::Engines::Maxwell3D& maxwell3d_,
  318. Tegra::Engines::KeplerCompute& kepler_compute_,
  319. Tegra::MemoryManager& gpu_memory_, Core::Memory::Memory& cpu_memory_,
  320. Runtime& runtime_)
  321. : runtime{runtime_}, rasterizer{rasterizer_}, maxwell3d{maxwell3d_},
  322. kepler_compute{kepler_compute_}, gpu_memory{gpu_memory_}, cpu_memory{cpu_memory_} {
  323. // Ensure the first slot is used for the null buffer
  324. void(slot_buffers.insert(runtime, NullBufferParams{}));
  325. common_ranges.clear();
  326. if (!runtime.CanReportMemoryUsage()) {
  327. minimum_memory = DEFAULT_EXPECTED_MEMORY;
  328. critical_memory = DEFAULT_CRITICAL_MEMORY;
  329. return;
  330. }
  331. const s64 device_memory = static_cast<s64>(runtime.GetDeviceLocalMemory());
  332. const s64 min_spacing_expected = device_memory - 1_GiB - 512_MiB;
  333. const s64 min_spacing_critical = device_memory - 1_GiB;
  334. const s64 mem_threshold = std::min(device_memory, TARGET_THRESHOLD);
  335. const s64 min_vacancy_expected = (6 * mem_threshold) / 10;
  336. const s64 min_vacancy_critical = (3 * mem_threshold) / 10;
  337. minimum_memory = static_cast<u64>(
  338. std::max(std::min(device_memory - min_vacancy_expected, min_spacing_expected),
  339. DEFAULT_EXPECTED_MEMORY));
  340. critical_memory = static_cast<u64>(
  341. std::max(std::min(device_memory - min_vacancy_critical, min_spacing_critical),
  342. DEFAULT_CRITICAL_MEMORY));
  343. }
  344. template <class P>
  345. void BufferCache<P>::RunGarbageCollector() {
  346. const bool aggressive_gc = total_used_memory >= critical_memory;
  347. const u64 ticks_to_destroy = aggressive_gc ? 60 : 120;
  348. int num_iterations = aggressive_gc ? 64 : 32;
  349. const auto clean_up = [this, &num_iterations](BufferId buffer_id) {
  350. if (num_iterations == 0) {
  351. return true;
  352. }
  353. --num_iterations;
  354. auto& buffer = slot_buffers[buffer_id];
  355. DownloadBufferMemory(buffer);
  356. DeleteBuffer(buffer_id);
  357. return false;
  358. };
  359. lru_cache.ForEachItemBelow(frame_tick - ticks_to_destroy, clean_up);
  360. }
  361. template <class P>
  362. void BufferCache<P>::TickFrame() {
  363. // Calculate hits and shots and move hit bits to the right
  364. const u32 hits = std::reduce(uniform_cache_hits.begin(), uniform_cache_hits.end());
  365. const u32 shots = std::reduce(uniform_cache_shots.begin(), uniform_cache_shots.end());
  366. std::copy_n(uniform_cache_hits.begin(), uniform_cache_hits.size() - 1,
  367. uniform_cache_hits.begin() + 1);
  368. std::copy_n(uniform_cache_shots.begin(), uniform_cache_shots.size() - 1,
  369. uniform_cache_shots.begin() + 1);
  370. uniform_cache_hits[0] = 0;
  371. uniform_cache_shots[0] = 0;
  372. const bool skip_preferred = hits * 256 < shots * 251;
  373. uniform_buffer_skip_cache_size = skip_preferred ? DEFAULT_SKIP_CACHE_SIZE : 0;
  374. // If we can obtain the memory info, use it instead of the estimate.
  375. if (runtime.CanReportMemoryUsage()) {
  376. total_used_memory = runtime.GetDeviceMemoryUsage();
  377. }
  378. if (total_used_memory >= minimum_memory) {
  379. RunGarbageCollector();
  380. }
  381. ++frame_tick;
  382. delayed_destruction_ring.Tick();
  383. }
  384. template <class P>
  385. void BufferCache<P>::WriteMemory(VAddr cpu_addr, u64 size) {
  386. ForEachBufferInRange(cpu_addr, size, [&](BufferId, Buffer& buffer) {
  387. buffer.MarkRegionAsCpuModified(cpu_addr, size);
  388. });
  389. }
  390. template <class P>
  391. void BufferCache<P>::CachedWriteMemory(VAddr cpu_addr, u64 size) {
  392. ForEachBufferInRange(cpu_addr, size, [&](BufferId buffer_id, Buffer& buffer) {
  393. if (!buffer.HasCachedWrites()) {
  394. cached_write_buffer_ids.push_back(buffer_id);
  395. }
  396. buffer.CachedCpuWrite(cpu_addr, size);
  397. });
  398. }
  399. template <class P>
  400. void BufferCache<P>::DownloadMemory(VAddr cpu_addr, u64 size) {
  401. ForEachBufferInRange(cpu_addr, size, [&](BufferId, Buffer& buffer) {
  402. DownloadBufferMemory(buffer, cpu_addr, size);
  403. });
  404. }
  405. template <class P>
  406. void BufferCache<P>::ClearDownload(IntervalType subtract_interval) {
  407. uncommitted_ranges.subtract(subtract_interval);
  408. for (auto& interval_set : committed_ranges) {
  409. interval_set.subtract(subtract_interval);
  410. }
  411. }
  412. template <class P>
  413. bool BufferCache<P>::DMACopy(GPUVAddr src_address, GPUVAddr dest_address, u64 amount) {
  414. const std::optional<VAddr> cpu_src_address = gpu_memory.GpuToCpuAddress(src_address);
  415. const std::optional<VAddr> cpu_dest_address = gpu_memory.GpuToCpuAddress(dest_address);
  416. if (!cpu_src_address || !cpu_dest_address) {
  417. return false;
  418. }
  419. const bool source_dirty = IsRegionRegistered(*cpu_src_address, amount);
  420. const bool dest_dirty = IsRegionRegistered(*cpu_dest_address, amount);
  421. if (!source_dirty && !dest_dirty) {
  422. return false;
  423. }
  424. const IntervalType subtract_interval{*cpu_dest_address, *cpu_dest_address + amount};
  425. ClearDownload(subtract_interval);
  426. BufferId buffer_a;
  427. BufferId buffer_b;
  428. do {
  429. has_deleted_buffers = false;
  430. buffer_a = FindBuffer(*cpu_src_address, static_cast<u32>(amount));
  431. buffer_b = FindBuffer(*cpu_dest_address, static_cast<u32>(amount));
  432. } while (has_deleted_buffers);
  433. auto& src_buffer = slot_buffers[buffer_a];
  434. auto& dest_buffer = slot_buffers[buffer_b];
  435. SynchronizeBuffer(src_buffer, *cpu_src_address, static_cast<u32>(amount));
  436. SynchronizeBuffer(dest_buffer, *cpu_dest_address, static_cast<u32>(amount));
  437. std::array copies{BufferCopy{
  438. .src_offset = src_buffer.Offset(*cpu_src_address),
  439. .dst_offset = dest_buffer.Offset(*cpu_dest_address),
  440. .size = amount,
  441. }};
  442. boost::container::small_vector<IntervalType, 4> tmp_intervals;
  443. auto mirror = [&](VAddr base_address, VAddr base_address_end) {
  444. const u64 size = base_address_end - base_address;
  445. const VAddr diff = base_address - *cpu_src_address;
  446. const VAddr new_base_address = *cpu_dest_address + diff;
  447. const IntervalType add_interval{new_base_address, new_base_address + size};
  448. uncommitted_ranges.add(add_interval);
  449. tmp_intervals.push_back(add_interval);
  450. };
  451. ForEachWrittenRange(*cpu_src_address, amount, mirror);
  452. // This subtraction in this order is important for overlapping copies.
  453. common_ranges.subtract(subtract_interval);
  454. const bool has_new_downloads = tmp_intervals.size() != 0;
  455. for (const IntervalType& add_interval : tmp_intervals) {
  456. common_ranges.add(add_interval);
  457. }
  458. runtime.CopyBuffer(dest_buffer, src_buffer, copies);
  459. if (has_new_downloads) {
  460. dest_buffer.MarkRegionAsGpuModified(*cpu_dest_address, amount);
  461. }
  462. std::vector<u8> tmp_buffer(amount);
  463. cpu_memory.ReadBlockUnsafe(*cpu_src_address, tmp_buffer.data(), amount);
  464. cpu_memory.WriteBlockUnsafe(*cpu_dest_address, tmp_buffer.data(), amount);
  465. return true;
  466. }
  467. template <class P>
  468. bool BufferCache<P>::DMAClear(GPUVAddr dst_address, u64 amount, u32 value) {
  469. const std::optional<VAddr> cpu_dst_address = gpu_memory.GpuToCpuAddress(dst_address);
  470. if (!cpu_dst_address) {
  471. return false;
  472. }
  473. const bool dest_dirty = IsRegionRegistered(*cpu_dst_address, amount);
  474. if (!dest_dirty) {
  475. return false;
  476. }
  477. const size_t size = amount * sizeof(u32);
  478. const IntervalType subtract_interval{*cpu_dst_address, *cpu_dst_address + size};
  479. ClearDownload(subtract_interval);
  480. common_ranges.subtract(subtract_interval);
  481. const BufferId buffer = FindBuffer(*cpu_dst_address, static_cast<u32>(size));
  482. auto& dest_buffer = slot_buffers[buffer];
  483. const u32 offset = dest_buffer.Offset(*cpu_dst_address);
  484. runtime.ClearBuffer(dest_buffer, offset, size, value);
  485. return true;
  486. }
  487. template <class P>
  488. void BufferCache<P>::BindGraphicsUniformBuffer(size_t stage, u32 index, GPUVAddr gpu_addr,
  489. u32 size) {
  490. const std::optional<VAddr> cpu_addr = gpu_memory.GpuToCpuAddress(gpu_addr);
  491. const Binding binding{
  492. .cpu_addr = *cpu_addr,
  493. .size = size,
  494. .buffer_id = BufferId{},
  495. };
  496. uniform_buffers[stage][index] = binding;
  497. }
  498. template <class P>
  499. void BufferCache<P>::DisableGraphicsUniformBuffer(size_t stage, u32 index) {
  500. uniform_buffers[stage][index] = NULL_BINDING;
  501. }
  502. template <class P>
  503. void BufferCache<P>::UpdateGraphicsBuffers(bool is_indexed) {
  504. MICROPROFILE_SCOPE(GPU_PrepareBuffers);
  505. do {
  506. has_deleted_buffers = false;
  507. DoUpdateGraphicsBuffers(is_indexed);
  508. } while (has_deleted_buffers);
  509. }
  510. template <class P>
  511. void BufferCache<P>::UpdateComputeBuffers() {
  512. MICROPROFILE_SCOPE(GPU_PrepareBuffers);
  513. do {
  514. has_deleted_buffers = false;
  515. DoUpdateComputeBuffers();
  516. } while (has_deleted_buffers);
  517. }
  518. template <class P>
  519. void BufferCache<P>::BindHostGeometryBuffers(bool is_indexed) {
  520. MICROPROFILE_SCOPE(GPU_BindUploadBuffers);
  521. if (is_indexed) {
  522. BindHostIndexBuffer();
  523. } else if constexpr (!HAS_FULL_INDEX_AND_PRIMITIVE_SUPPORT) {
  524. const auto& regs = maxwell3d.regs;
  525. if (regs.draw.topology == Maxwell::PrimitiveTopology::Quads) {
  526. runtime.BindQuadArrayIndexBuffer(regs.vertex_buffer.first, regs.vertex_buffer.count);
  527. }
  528. }
  529. BindHostVertexBuffers();
  530. BindHostTransformFeedbackBuffers();
  531. }
  532. template <class P>
  533. void BufferCache<P>::BindHostStageBuffers(size_t stage) {
  534. MICROPROFILE_SCOPE(GPU_BindUploadBuffers);
  535. BindHostGraphicsUniformBuffers(stage);
  536. BindHostGraphicsStorageBuffers(stage);
  537. BindHostGraphicsTextureBuffers(stage);
  538. }
  539. template <class P>
  540. void BufferCache<P>::BindHostComputeBuffers() {
  541. MICROPROFILE_SCOPE(GPU_BindUploadBuffers);
  542. BindHostComputeUniformBuffers();
  543. BindHostComputeStorageBuffers();
  544. BindHostComputeTextureBuffers();
  545. }
  546. template <class P>
  547. void BufferCache<P>::SetUniformBuffersState(const std::array<u32, NUM_STAGES>& mask,
  548. const UniformBufferSizes* sizes) {
  549. if constexpr (HAS_PERSISTENT_UNIFORM_BUFFER_BINDINGS) {
  550. if (enabled_uniform_buffer_masks != mask) {
  551. if constexpr (IS_OPENGL) {
  552. fast_bound_uniform_buffers.fill(0);
  553. }
  554. dirty_uniform_buffers.fill(~u32{0});
  555. uniform_buffer_binding_sizes.fill({});
  556. }
  557. }
  558. enabled_uniform_buffer_masks = mask;
  559. uniform_buffer_sizes = sizes;
  560. }
  561. template <class P>
  562. void BufferCache<P>::SetComputeUniformBufferState(u32 mask,
  563. const ComputeUniformBufferSizes* sizes) {
  564. enabled_compute_uniform_buffer_mask = mask;
  565. compute_uniform_buffer_sizes = sizes;
  566. }
  567. template <class P>
  568. void BufferCache<P>::UnbindGraphicsStorageBuffers(size_t stage) {
  569. enabled_storage_buffers[stage] = 0;
  570. written_storage_buffers[stage] = 0;
  571. }
  572. template <class P>
  573. void BufferCache<P>::BindGraphicsStorageBuffer(size_t stage, size_t ssbo_index, u32 cbuf_index,
  574. u32 cbuf_offset, bool is_written) {
  575. enabled_storage_buffers[stage] |= 1U << ssbo_index;
  576. written_storage_buffers[stage] |= (is_written ? 1U : 0U) << ssbo_index;
  577. const auto& cbufs = maxwell3d.state.shader_stages[stage];
  578. const GPUVAddr ssbo_addr = cbufs.const_buffers[cbuf_index].address + cbuf_offset;
  579. storage_buffers[stage][ssbo_index] = StorageBufferBinding(ssbo_addr);
  580. }
  581. template <class P>
  582. void BufferCache<P>::UnbindGraphicsTextureBuffers(size_t stage) {
  583. enabled_texture_buffers[stage] = 0;
  584. written_texture_buffers[stage] = 0;
  585. image_texture_buffers[stage] = 0;
  586. }
  587. template <class P>
  588. void BufferCache<P>::BindGraphicsTextureBuffer(size_t stage, size_t tbo_index, GPUVAddr gpu_addr,
  589. u32 size, PixelFormat format, bool is_written,
  590. bool is_image) {
  591. enabled_texture_buffers[stage] |= 1U << tbo_index;
  592. written_texture_buffers[stage] |= (is_written ? 1U : 0U) << tbo_index;
  593. if constexpr (SEPARATE_IMAGE_BUFFERS_BINDINGS) {
  594. image_texture_buffers[stage] |= (is_image ? 1U : 0U) << tbo_index;
  595. }
  596. texture_buffers[stage][tbo_index] = GetTextureBufferBinding(gpu_addr, size, format);
  597. }
  598. template <class P>
  599. void BufferCache<P>::UnbindComputeStorageBuffers() {
  600. enabled_compute_storage_buffers = 0;
  601. written_compute_storage_buffers = 0;
  602. image_compute_texture_buffers = 0;
  603. }
  604. template <class P>
  605. void BufferCache<P>::BindComputeStorageBuffer(size_t ssbo_index, u32 cbuf_index, u32 cbuf_offset,
  606. bool is_written) {
  607. enabled_compute_storage_buffers |= 1U << ssbo_index;
  608. written_compute_storage_buffers |= (is_written ? 1U : 0U) << ssbo_index;
  609. const auto& launch_desc = kepler_compute.launch_description;
  610. ASSERT(((launch_desc.const_buffer_enable_mask >> cbuf_index) & 1) != 0);
  611. const auto& cbufs = launch_desc.const_buffer_config;
  612. const GPUVAddr ssbo_addr = cbufs[cbuf_index].Address() + cbuf_offset;
  613. compute_storage_buffers[ssbo_index] = StorageBufferBinding(ssbo_addr);
  614. }
  615. template <class P>
  616. void BufferCache<P>::UnbindComputeTextureBuffers() {
  617. enabled_compute_texture_buffers = 0;
  618. written_compute_texture_buffers = 0;
  619. image_compute_texture_buffers = 0;
  620. }
  621. template <class P>
  622. void BufferCache<P>::BindComputeTextureBuffer(size_t tbo_index, GPUVAddr gpu_addr, u32 size,
  623. PixelFormat format, bool is_written, bool is_image) {
  624. enabled_compute_texture_buffers |= 1U << tbo_index;
  625. written_compute_texture_buffers |= (is_written ? 1U : 0U) << tbo_index;
  626. if constexpr (SEPARATE_IMAGE_BUFFERS_BINDINGS) {
  627. image_compute_texture_buffers |= (is_image ? 1U : 0U) << tbo_index;
  628. }
  629. compute_texture_buffers[tbo_index] = GetTextureBufferBinding(gpu_addr, size, format);
  630. }
  631. template <class P>
  632. void BufferCache<P>::FlushCachedWrites() {
  633. for (const BufferId buffer_id : cached_write_buffer_ids) {
  634. slot_buffers[buffer_id].FlushCachedWrites();
  635. }
  636. cached_write_buffer_ids.clear();
  637. }
  638. template <class P>
  639. bool BufferCache<P>::HasUncommittedFlushes() const noexcept {
  640. return !uncommitted_ranges.empty() || !committed_ranges.empty();
  641. }
  642. template <class P>
  643. void BufferCache<P>::AccumulateFlushes() {
  644. if (Settings::values.gpu_accuracy.GetValue() != Settings::GPUAccuracy::High) {
  645. uncommitted_ranges.clear();
  646. return;
  647. }
  648. if (uncommitted_ranges.empty()) {
  649. return;
  650. }
  651. committed_ranges.emplace_back(std::move(uncommitted_ranges));
  652. }
  653. template <class P>
  654. bool BufferCache<P>::ShouldWaitAsyncFlushes() const noexcept {
  655. return false;
  656. }
  657. template <class P>
  658. void BufferCache<P>::CommitAsyncFlushesHigh() {
  659. AccumulateFlushes();
  660. if (committed_ranges.empty()) {
  661. return;
  662. }
  663. MICROPROFILE_SCOPE(GPU_DownloadMemory);
  664. const bool is_accuracy_normal =
  665. Settings::values.gpu_accuracy.GetValue() == Settings::GPUAccuracy::Normal;
  666. boost::container::small_vector<std::pair<BufferCopy, BufferId>, 1> downloads;
  667. u64 total_size_bytes = 0;
  668. u64 largest_copy = 0;
  669. for (const IntervalSet& intervals : committed_ranges) {
  670. for (auto& interval : intervals) {
  671. const std::size_t size = interval.upper() - interval.lower();
  672. const VAddr cpu_addr = interval.lower();
  673. ForEachBufferInRange(cpu_addr, size, [&](BufferId buffer_id, Buffer& buffer) {
  674. buffer.ForEachDownloadRangeAndClear(
  675. cpu_addr, size, [&](u64 range_offset, u64 range_size) {
  676. if (is_accuracy_normal) {
  677. return;
  678. }
  679. const VAddr buffer_addr = buffer.CpuAddr();
  680. const auto add_download = [&](VAddr start, VAddr end) {
  681. const u64 new_offset = start - buffer_addr;
  682. const u64 new_size = end - start;
  683. downloads.push_back({
  684. BufferCopy{
  685. .src_offset = new_offset,
  686. .dst_offset = total_size_bytes,
  687. .size = new_size,
  688. },
  689. buffer_id,
  690. });
  691. // Align up to avoid cache conflicts
  692. constexpr u64 align = 256ULL;
  693. constexpr u64 mask = ~(align - 1ULL);
  694. total_size_bytes += (new_size + align - 1) & mask;
  695. largest_copy = std::max(largest_copy, new_size);
  696. };
  697. const VAddr start_address = buffer_addr + range_offset;
  698. const VAddr end_address = start_address + range_size;
  699. ForEachWrittenRange(start_address, range_size, add_download);
  700. const IntervalType subtract_interval{start_address, end_address};
  701. common_ranges.subtract(subtract_interval);
  702. });
  703. });
  704. }
  705. }
  706. committed_ranges.clear();
  707. if (downloads.empty()) {
  708. return;
  709. }
  710. if constexpr (USE_MEMORY_MAPS) {
  711. auto download_staging = runtime.DownloadStagingBuffer(total_size_bytes);
  712. runtime.PreCopyBarrier();
  713. for (auto& [copy, buffer_id] : downloads) {
  714. // Have in mind the staging buffer offset for the copy
  715. copy.dst_offset += download_staging.offset;
  716. const std::array copies{copy};
  717. runtime.CopyBuffer(download_staging.buffer, slot_buffers[buffer_id], copies, false);
  718. }
  719. runtime.PostCopyBarrier();
  720. runtime.Finish();
  721. for (const auto& [copy, buffer_id] : downloads) {
  722. const Buffer& buffer = slot_buffers[buffer_id];
  723. const VAddr cpu_addr = buffer.CpuAddr() + copy.src_offset;
  724. // Undo the modified offset
  725. const u64 dst_offset = copy.dst_offset - download_staging.offset;
  726. const u8* read_mapped_memory = download_staging.mapped_span.data() + dst_offset;
  727. cpu_memory.WriteBlockUnsafe(cpu_addr, read_mapped_memory, copy.size);
  728. }
  729. } else {
  730. const std::span<u8> immediate_buffer = ImmediateBuffer(largest_copy);
  731. for (const auto& [copy, buffer_id] : downloads) {
  732. Buffer& buffer = slot_buffers[buffer_id];
  733. buffer.ImmediateDownload(copy.src_offset, immediate_buffer.subspan(0, copy.size));
  734. const VAddr cpu_addr = buffer.CpuAddr() + copy.src_offset;
  735. cpu_memory.WriteBlockUnsafe(cpu_addr, immediate_buffer.data(), copy.size);
  736. }
  737. }
  738. }
  739. template <class P>
  740. void BufferCache<P>::CommitAsyncFlushes() {
  741. if (Settings::values.gpu_accuracy.GetValue() == Settings::GPUAccuracy::High) {
  742. CommitAsyncFlushesHigh();
  743. } else {
  744. uncommitted_ranges.clear();
  745. committed_ranges.clear();
  746. }
  747. }
  748. template <class P>
  749. void BufferCache<P>::PopAsyncFlushes() {}
  750. template <class P>
  751. bool BufferCache<P>::IsRegionGpuModified(VAddr addr, size_t size) {
  752. const u64 page_end = Common::DivCeil(addr + size, PAGE_SIZE);
  753. for (u64 page = addr >> PAGE_BITS; page < page_end;) {
  754. const BufferId image_id = page_table[page];
  755. if (!image_id) {
  756. ++page;
  757. continue;
  758. }
  759. Buffer& buffer = slot_buffers[image_id];
  760. if (buffer.IsRegionGpuModified(addr, size)) {
  761. return true;
  762. }
  763. const VAddr end_addr = buffer.CpuAddr() + buffer.SizeBytes();
  764. page = Common::DivCeil(end_addr, PAGE_SIZE);
  765. }
  766. return false;
  767. }
  768. template <class P>
  769. bool BufferCache<P>::IsRegionRegistered(VAddr addr, size_t size) {
  770. const VAddr end_addr = addr + size;
  771. const u64 page_end = Common::DivCeil(end_addr, PAGE_SIZE);
  772. for (u64 page = addr >> PAGE_BITS; page < page_end;) {
  773. const BufferId buffer_id = page_table[page];
  774. if (!buffer_id) {
  775. ++page;
  776. continue;
  777. }
  778. Buffer& buffer = slot_buffers[buffer_id];
  779. const VAddr buf_start_addr = buffer.CpuAddr();
  780. const VAddr buf_end_addr = buf_start_addr + buffer.SizeBytes();
  781. if (buf_start_addr < end_addr && addr < buf_end_addr) {
  782. return true;
  783. }
  784. page = Common::DivCeil(end_addr, PAGE_SIZE);
  785. }
  786. return false;
  787. }
  788. template <class P>
  789. bool BufferCache<P>::IsRegionCpuModified(VAddr addr, size_t size) {
  790. const u64 page_end = Common::DivCeil(addr + size, PAGE_SIZE);
  791. for (u64 page = addr >> PAGE_BITS; page < page_end;) {
  792. const BufferId image_id = page_table[page];
  793. if (!image_id) {
  794. ++page;
  795. continue;
  796. }
  797. Buffer& buffer = slot_buffers[image_id];
  798. if (buffer.IsRegionCpuModified(addr, size)) {
  799. return true;
  800. }
  801. const VAddr end_addr = buffer.CpuAddr() + buffer.SizeBytes();
  802. page = Common::DivCeil(end_addr, PAGE_SIZE);
  803. }
  804. return false;
  805. }
  806. template <class P>
  807. void BufferCache<P>::BindHostIndexBuffer() {
  808. Buffer& buffer = slot_buffers[index_buffer.buffer_id];
  809. TouchBuffer(buffer, index_buffer.buffer_id);
  810. const u32 offset = buffer.Offset(index_buffer.cpu_addr);
  811. const u32 size = index_buffer.size;
  812. SynchronizeBuffer(buffer, index_buffer.cpu_addr, size);
  813. if constexpr (HAS_FULL_INDEX_AND_PRIMITIVE_SUPPORT) {
  814. const u32 new_offset = offset + maxwell3d.regs.index_array.first *
  815. maxwell3d.regs.index_array.FormatSizeInBytes();
  816. runtime.BindIndexBuffer(buffer, new_offset, size);
  817. } else {
  818. runtime.BindIndexBuffer(maxwell3d.regs.draw.topology, maxwell3d.regs.index_array.format,
  819. maxwell3d.regs.index_array.first, maxwell3d.regs.index_array.count,
  820. buffer, offset, size);
  821. }
  822. }
  823. template <class P>
  824. void BufferCache<P>::BindHostVertexBuffers() {
  825. auto& flags = maxwell3d.dirty.flags;
  826. for (u32 index = 0; index < NUM_VERTEX_BUFFERS; ++index) {
  827. const Binding& binding = vertex_buffers[index];
  828. Buffer& buffer = slot_buffers[binding.buffer_id];
  829. TouchBuffer(buffer, binding.buffer_id);
  830. SynchronizeBuffer(buffer, binding.cpu_addr, binding.size);
  831. if (!flags[Dirty::VertexBuffer0 + index]) {
  832. continue;
  833. }
  834. flags[Dirty::VertexBuffer0 + index] = false;
  835. const u32 stride = maxwell3d.regs.vertex_array[index].stride;
  836. const u32 offset = buffer.Offset(binding.cpu_addr);
  837. runtime.BindVertexBuffer(index, buffer, offset, binding.size, stride);
  838. }
  839. }
  840. template <class P>
  841. void BufferCache<P>::BindHostGraphicsUniformBuffers(size_t stage) {
  842. u32 dirty = ~0U;
  843. if constexpr (HAS_PERSISTENT_UNIFORM_BUFFER_BINDINGS) {
  844. dirty = std::exchange(dirty_uniform_buffers[stage], 0);
  845. }
  846. u32 binding_index = 0;
  847. ForEachEnabledBit(enabled_uniform_buffer_masks[stage], [&](u32 index) {
  848. const bool needs_bind = ((dirty >> index) & 1) != 0;
  849. BindHostGraphicsUniformBuffer(stage, index, binding_index, needs_bind);
  850. if constexpr (NEEDS_BIND_UNIFORM_INDEX) {
  851. ++binding_index;
  852. }
  853. });
  854. }
  855. template <class P>
  856. void BufferCache<P>::BindHostGraphicsUniformBuffer(size_t stage, u32 index, u32 binding_index,
  857. bool needs_bind) {
  858. const Binding& binding = uniform_buffers[stage][index];
  859. const VAddr cpu_addr = binding.cpu_addr;
  860. const u32 size = std::min(binding.size, (*uniform_buffer_sizes)[stage][index]);
  861. Buffer& buffer = slot_buffers[binding.buffer_id];
  862. TouchBuffer(buffer, binding.buffer_id);
  863. const bool use_fast_buffer = binding.buffer_id != NULL_BUFFER_ID &&
  864. size <= uniform_buffer_skip_cache_size &&
  865. !buffer.IsRegionGpuModified(cpu_addr, size);
  866. if (use_fast_buffer) {
  867. if constexpr (IS_OPENGL) {
  868. if (runtime.HasFastBufferSubData()) {
  869. // Fast path for Nvidia
  870. const bool should_fast_bind =
  871. !HasFastUniformBufferBound(stage, binding_index) ||
  872. uniform_buffer_binding_sizes[stage][binding_index] != size;
  873. if (should_fast_bind) {
  874. // We only have to bind when the currently bound buffer is not the fast version
  875. fast_bound_uniform_buffers[stage] |= 1U << binding_index;
  876. uniform_buffer_binding_sizes[stage][binding_index] = size;
  877. runtime.BindFastUniformBuffer(stage, binding_index, size);
  878. }
  879. const auto span = ImmediateBufferWithData(cpu_addr, size);
  880. runtime.PushFastUniformBuffer(stage, binding_index, span);
  881. return;
  882. }
  883. }
  884. if constexpr (IS_OPENGL) {
  885. fast_bound_uniform_buffers[stage] |= 1U << binding_index;
  886. uniform_buffer_binding_sizes[stage][binding_index] = size;
  887. }
  888. // Stream buffer path to avoid stalling on non-Nvidia drivers or Vulkan
  889. const std::span<u8> span = runtime.BindMappedUniformBuffer(stage, binding_index, size);
  890. cpu_memory.ReadBlockUnsafe(cpu_addr, span.data(), size);
  891. return;
  892. }
  893. // Classic cached path
  894. const bool sync_cached = SynchronizeBuffer(buffer, cpu_addr, size);
  895. if (sync_cached) {
  896. ++uniform_cache_hits[0];
  897. }
  898. ++uniform_cache_shots[0];
  899. // Skip binding if it's not needed and if the bound buffer is not the fast version
  900. // This exists to avoid instances where the fast buffer is bound and a GPU write happens
  901. needs_bind |= HasFastUniformBufferBound(stage, binding_index);
  902. if constexpr (HAS_PERSISTENT_UNIFORM_BUFFER_BINDINGS) {
  903. needs_bind |= uniform_buffer_binding_sizes[stage][binding_index] != size;
  904. }
  905. if (!needs_bind) {
  906. return;
  907. }
  908. const u32 offset = buffer.Offset(cpu_addr);
  909. if constexpr (IS_OPENGL) {
  910. // Fast buffer will be unbound
  911. fast_bound_uniform_buffers[stage] &= ~(1U << binding_index);
  912. // Mark the index as dirty if offset doesn't match
  913. const bool is_copy_bind = offset != 0 && !runtime.SupportsNonZeroUniformOffset();
  914. dirty_uniform_buffers[stage] |= (is_copy_bind ? 1U : 0U) << index;
  915. }
  916. if constexpr (HAS_PERSISTENT_UNIFORM_BUFFER_BINDINGS) {
  917. uniform_buffer_binding_sizes[stage][binding_index] = size;
  918. }
  919. if constexpr (NEEDS_BIND_UNIFORM_INDEX) {
  920. runtime.BindUniformBuffer(stage, binding_index, buffer, offset, size);
  921. } else {
  922. runtime.BindUniformBuffer(buffer, offset, size);
  923. }
  924. }
  925. template <class P>
  926. void BufferCache<P>::BindHostGraphicsStorageBuffers(size_t stage) {
  927. u32 binding_index = 0;
  928. ForEachEnabledBit(enabled_storage_buffers[stage], [&](u32 index) {
  929. const Binding& binding = storage_buffers[stage][index];
  930. Buffer& buffer = slot_buffers[binding.buffer_id];
  931. TouchBuffer(buffer, binding.buffer_id);
  932. const u32 size = binding.size;
  933. SynchronizeBuffer(buffer, binding.cpu_addr, size);
  934. const u32 offset = buffer.Offset(binding.cpu_addr);
  935. const bool is_written = ((written_storage_buffers[stage] >> index) & 1) != 0;
  936. if constexpr (NEEDS_BIND_STORAGE_INDEX) {
  937. runtime.BindStorageBuffer(stage, binding_index, buffer, offset, size, is_written);
  938. ++binding_index;
  939. } else {
  940. runtime.BindStorageBuffer(buffer, offset, size, is_written);
  941. }
  942. });
  943. }
  944. template <class P>
  945. void BufferCache<P>::BindHostGraphicsTextureBuffers(size_t stage) {
  946. ForEachEnabledBit(enabled_texture_buffers[stage], [&](u32 index) {
  947. const TextureBufferBinding& binding = texture_buffers[stage][index];
  948. Buffer& buffer = slot_buffers[binding.buffer_id];
  949. const u32 size = binding.size;
  950. SynchronizeBuffer(buffer, binding.cpu_addr, size);
  951. const u32 offset = buffer.Offset(binding.cpu_addr);
  952. const PixelFormat format = binding.format;
  953. if constexpr (SEPARATE_IMAGE_BUFFERS_BINDINGS) {
  954. if (((image_texture_buffers[stage] >> index) & 1) != 0) {
  955. runtime.BindImageBuffer(buffer, offset, size, format);
  956. } else {
  957. runtime.BindTextureBuffer(buffer, offset, size, format);
  958. }
  959. } else {
  960. runtime.BindTextureBuffer(buffer, offset, size, format);
  961. }
  962. });
  963. }
  964. template <class P>
  965. void BufferCache<P>::BindHostTransformFeedbackBuffers() {
  966. if (maxwell3d.regs.tfb_enabled == 0) {
  967. return;
  968. }
  969. for (u32 index = 0; index < NUM_TRANSFORM_FEEDBACK_BUFFERS; ++index) {
  970. const Binding& binding = transform_feedback_buffers[index];
  971. Buffer& buffer = slot_buffers[binding.buffer_id];
  972. TouchBuffer(buffer, binding.buffer_id);
  973. const u32 size = binding.size;
  974. SynchronizeBuffer(buffer, binding.cpu_addr, size);
  975. const u32 offset = buffer.Offset(binding.cpu_addr);
  976. runtime.BindTransformFeedbackBuffer(index, buffer, offset, size);
  977. }
  978. }
  979. template <class P>
  980. void BufferCache<P>::BindHostComputeUniformBuffers() {
  981. if constexpr (HAS_PERSISTENT_UNIFORM_BUFFER_BINDINGS) {
  982. // Mark all uniform buffers as dirty
  983. dirty_uniform_buffers.fill(~u32{0});
  984. fast_bound_uniform_buffers.fill(0);
  985. }
  986. u32 binding_index = 0;
  987. ForEachEnabledBit(enabled_compute_uniform_buffer_mask, [&](u32 index) {
  988. const Binding& binding = compute_uniform_buffers[index];
  989. Buffer& buffer = slot_buffers[binding.buffer_id];
  990. TouchBuffer(buffer, binding.buffer_id);
  991. const u32 size = std::min(binding.size, (*compute_uniform_buffer_sizes)[index]);
  992. SynchronizeBuffer(buffer, binding.cpu_addr, size);
  993. const u32 offset = buffer.Offset(binding.cpu_addr);
  994. if constexpr (NEEDS_BIND_UNIFORM_INDEX) {
  995. runtime.BindComputeUniformBuffer(binding_index, buffer, offset, size);
  996. ++binding_index;
  997. } else {
  998. runtime.BindUniformBuffer(buffer, offset, size);
  999. }
  1000. });
  1001. }
  1002. template <class P>
  1003. void BufferCache<P>::BindHostComputeStorageBuffers() {
  1004. u32 binding_index = 0;
  1005. ForEachEnabledBit(enabled_compute_storage_buffers, [&](u32 index) {
  1006. const Binding& binding = compute_storage_buffers[index];
  1007. Buffer& buffer = slot_buffers[binding.buffer_id];
  1008. TouchBuffer(buffer, binding.buffer_id);
  1009. const u32 size = binding.size;
  1010. SynchronizeBuffer(buffer, binding.cpu_addr, size);
  1011. const u32 offset = buffer.Offset(binding.cpu_addr);
  1012. const bool is_written = ((written_compute_storage_buffers >> index) & 1) != 0;
  1013. if constexpr (NEEDS_BIND_STORAGE_INDEX) {
  1014. runtime.BindComputeStorageBuffer(binding_index, buffer, offset, size, is_written);
  1015. ++binding_index;
  1016. } else {
  1017. runtime.BindStorageBuffer(buffer, offset, size, is_written);
  1018. }
  1019. });
  1020. }
  1021. template <class P>
  1022. void BufferCache<P>::BindHostComputeTextureBuffers() {
  1023. ForEachEnabledBit(enabled_compute_texture_buffers, [&](u32 index) {
  1024. const TextureBufferBinding& binding = compute_texture_buffers[index];
  1025. Buffer& buffer = slot_buffers[binding.buffer_id];
  1026. const u32 size = binding.size;
  1027. SynchronizeBuffer(buffer, binding.cpu_addr, size);
  1028. const u32 offset = buffer.Offset(binding.cpu_addr);
  1029. const PixelFormat format = binding.format;
  1030. if constexpr (SEPARATE_IMAGE_BUFFERS_BINDINGS) {
  1031. if (((image_compute_texture_buffers >> index) & 1) != 0) {
  1032. runtime.BindImageBuffer(buffer, offset, size, format);
  1033. } else {
  1034. runtime.BindTextureBuffer(buffer, offset, size, format);
  1035. }
  1036. } else {
  1037. runtime.BindTextureBuffer(buffer, offset, size, format);
  1038. }
  1039. });
  1040. }
  1041. template <class P>
  1042. void BufferCache<P>::DoUpdateGraphicsBuffers(bool is_indexed) {
  1043. if (is_indexed) {
  1044. UpdateIndexBuffer();
  1045. }
  1046. UpdateVertexBuffers();
  1047. UpdateTransformFeedbackBuffers();
  1048. for (size_t stage = 0; stage < NUM_STAGES; ++stage) {
  1049. UpdateUniformBuffers(stage);
  1050. UpdateStorageBuffers(stage);
  1051. UpdateTextureBuffers(stage);
  1052. }
  1053. }
  1054. template <class P>
  1055. void BufferCache<P>::DoUpdateComputeBuffers() {
  1056. UpdateComputeUniformBuffers();
  1057. UpdateComputeStorageBuffers();
  1058. UpdateComputeTextureBuffers();
  1059. }
  1060. template <class P>
  1061. void BufferCache<P>::UpdateIndexBuffer() {
  1062. // We have to check for the dirty flags and index count
  1063. // The index count is currently changed without updating the dirty flags
  1064. const auto& index_array = maxwell3d.regs.index_array;
  1065. auto& flags = maxwell3d.dirty.flags;
  1066. if (!flags[Dirty::IndexBuffer] && last_index_count == index_array.count) {
  1067. return;
  1068. }
  1069. flags[Dirty::IndexBuffer] = false;
  1070. last_index_count = index_array.count;
  1071. const GPUVAddr gpu_addr_begin = index_array.StartAddress();
  1072. const GPUVAddr gpu_addr_end = index_array.EndAddress();
  1073. const std::optional<VAddr> cpu_addr = gpu_memory.GpuToCpuAddress(gpu_addr_begin);
  1074. const u32 address_size = static_cast<u32>(gpu_addr_end - gpu_addr_begin);
  1075. const u32 draw_size = (index_array.count + index_array.first) * index_array.FormatSizeInBytes();
  1076. const u32 size = std::min(address_size, draw_size);
  1077. if (size == 0 || !cpu_addr) {
  1078. index_buffer = NULL_BINDING;
  1079. return;
  1080. }
  1081. index_buffer = Binding{
  1082. .cpu_addr = *cpu_addr,
  1083. .size = size,
  1084. .buffer_id = FindBuffer(*cpu_addr, size),
  1085. };
  1086. }
  1087. template <class P>
  1088. void BufferCache<P>::UpdateVertexBuffers() {
  1089. auto& flags = maxwell3d.dirty.flags;
  1090. if (!maxwell3d.dirty.flags[Dirty::VertexBuffers]) {
  1091. return;
  1092. }
  1093. flags[Dirty::VertexBuffers] = false;
  1094. for (u32 index = 0; index < NUM_VERTEX_BUFFERS; ++index) {
  1095. UpdateVertexBuffer(index);
  1096. }
  1097. }
  1098. template <class P>
  1099. void BufferCache<P>::UpdateVertexBuffer(u32 index) {
  1100. if (!maxwell3d.dirty.flags[Dirty::VertexBuffer0 + index]) {
  1101. return;
  1102. }
  1103. const auto& array = maxwell3d.regs.vertex_array[index];
  1104. const auto& limit = maxwell3d.regs.vertex_array_limit[index];
  1105. const GPUVAddr gpu_addr_begin = array.StartAddress();
  1106. const GPUVAddr gpu_addr_end = limit.LimitAddress() + 1;
  1107. const std::optional<VAddr> cpu_addr = gpu_memory.GpuToCpuAddress(gpu_addr_begin);
  1108. u32 address_size = static_cast<u32>(gpu_addr_end - gpu_addr_begin);
  1109. if (address_size >= 64_MiB) {
  1110. // Reported vertex buffer size is very large, cap to mapped buffer size
  1111. GPUVAddr submapped_addr_end = gpu_addr_begin;
  1112. const auto ranges{gpu_memory.GetSubmappedRange(gpu_addr_begin, address_size)};
  1113. if (ranges.size() > 0) {
  1114. const auto& [addr, size] = *ranges.begin();
  1115. submapped_addr_end = addr + size;
  1116. }
  1117. address_size =
  1118. std::min(address_size, static_cast<u32>(submapped_addr_end - gpu_addr_begin));
  1119. }
  1120. const u32 size = address_size; // TODO: Analyze stride and number of vertices
  1121. if (array.enable == 0 || size == 0 || !cpu_addr) {
  1122. vertex_buffers[index] = NULL_BINDING;
  1123. return;
  1124. }
  1125. vertex_buffers[index] = Binding{
  1126. .cpu_addr = *cpu_addr,
  1127. .size = size,
  1128. .buffer_id = FindBuffer(*cpu_addr, size),
  1129. };
  1130. }
  1131. template <class P>
  1132. void BufferCache<P>::UpdateUniformBuffers(size_t stage) {
  1133. ForEachEnabledBit(enabled_uniform_buffer_masks[stage], [&](u32 index) {
  1134. Binding& binding = uniform_buffers[stage][index];
  1135. if (binding.buffer_id) {
  1136. // Already updated
  1137. return;
  1138. }
  1139. // Mark as dirty
  1140. if constexpr (HAS_PERSISTENT_UNIFORM_BUFFER_BINDINGS) {
  1141. dirty_uniform_buffers[stage] |= 1U << index;
  1142. }
  1143. // Resolve buffer
  1144. binding.buffer_id = FindBuffer(binding.cpu_addr, binding.size);
  1145. });
  1146. }
  1147. template <class P>
  1148. void BufferCache<P>::UpdateStorageBuffers(size_t stage) {
  1149. const u32 written_mask = written_storage_buffers[stage];
  1150. ForEachEnabledBit(enabled_storage_buffers[stage], [&](u32 index) {
  1151. // Resolve buffer
  1152. Binding& binding = storage_buffers[stage][index];
  1153. const BufferId buffer_id = FindBuffer(binding.cpu_addr, binding.size);
  1154. binding.buffer_id = buffer_id;
  1155. // Mark buffer as written if needed
  1156. if (((written_mask >> index) & 1) != 0) {
  1157. MarkWrittenBuffer(buffer_id, binding.cpu_addr, binding.size);
  1158. }
  1159. });
  1160. }
  1161. template <class P>
  1162. void BufferCache<P>::UpdateTextureBuffers(size_t stage) {
  1163. ForEachEnabledBit(enabled_texture_buffers[stage], [&](u32 index) {
  1164. Binding& binding = texture_buffers[stage][index];
  1165. binding.buffer_id = FindBuffer(binding.cpu_addr, binding.size);
  1166. // Mark buffer as written if needed
  1167. if (((written_texture_buffers[stage] >> index) & 1) != 0) {
  1168. MarkWrittenBuffer(binding.buffer_id, binding.cpu_addr, binding.size);
  1169. }
  1170. });
  1171. }
  1172. template <class P>
  1173. void BufferCache<P>::UpdateTransformFeedbackBuffers() {
  1174. if (maxwell3d.regs.tfb_enabled == 0) {
  1175. return;
  1176. }
  1177. for (u32 index = 0; index < NUM_TRANSFORM_FEEDBACK_BUFFERS; ++index) {
  1178. UpdateTransformFeedbackBuffer(index);
  1179. }
  1180. }
  1181. template <class P>
  1182. void BufferCache<P>::UpdateTransformFeedbackBuffer(u32 index) {
  1183. const auto& binding = maxwell3d.regs.tfb_bindings[index];
  1184. const GPUVAddr gpu_addr = binding.Address() + binding.buffer_offset;
  1185. const u32 size = binding.buffer_size;
  1186. const std::optional<VAddr> cpu_addr = gpu_memory.GpuToCpuAddress(gpu_addr);
  1187. if (binding.buffer_enable == 0 || size == 0 || !cpu_addr) {
  1188. transform_feedback_buffers[index] = NULL_BINDING;
  1189. return;
  1190. }
  1191. const BufferId buffer_id = FindBuffer(*cpu_addr, size);
  1192. transform_feedback_buffers[index] = Binding{
  1193. .cpu_addr = *cpu_addr,
  1194. .size = size,
  1195. .buffer_id = buffer_id,
  1196. };
  1197. MarkWrittenBuffer(buffer_id, *cpu_addr, size);
  1198. }
  1199. template <class P>
  1200. void BufferCache<P>::UpdateComputeUniformBuffers() {
  1201. ForEachEnabledBit(enabled_compute_uniform_buffer_mask, [&](u32 index) {
  1202. Binding& binding = compute_uniform_buffers[index];
  1203. binding = NULL_BINDING;
  1204. const auto& launch_desc = kepler_compute.launch_description;
  1205. if (((launch_desc.const_buffer_enable_mask >> index) & 1) != 0) {
  1206. const auto& cbuf = launch_desc.const_buffer_config[index];
  1207. const std::optional<VAddr> cpu_addr = gpu_memory.GpuToCpuAddress(cbuf.Address());
  1208. if (cpu_addr) {
  1209. binding.cpu_addr = *cpu_addr;
  1210. binding.size = cbuf.size;
  1211. }
  1212. }
  1213. binding.buffer_id = FindBuffer(binding.cpu_addr, binding.size);
  1214. });
  1215. }
  1216. template <class P>
  1217. void BufferCache<P>::UpdateComputeStorageBuffers() {
  1218. ForEachEnabledBit(enabled_compute_storage_buffers, [&](u32 index) {
  1219. // Resolve buffer
  1220. Binding& binding = compute_storage_buffers[index];
  1221. binding.buffer_id = FindBuffer(binding.cpu_addr, binding.size);
  1222. // Mark as written if needed
  1223. if (((written_compute_storage_buffers >> index) & 1) != 0) {
  1224. MarkWrittenBuffer(binding.buffer_id, binding.cpu_addr, binding.size);
  1225. }
  1226. });
  1227. }
  1228. template <class P>
  1229. void BufferCache<P>::UpdateComputeTextureBuffers() {
  1230. ForEachEnabledBit(enabled_compute_texture_buffers, [&](u32 index) {
  1231. Binding& binding = compute_texture_buffers[index];
  1232. binding.buffer_id = FindBuffer(binding.cpu_addr, binding.size);
  1233. // Mark as written if needed
  1234. if (((written_compute_texture_buffers >> index) & 1) != 0) {
  1235. MarkWrittenBuffer(binding.buffer_id, binding.cpu_addr, binding.size);
  1236. }
  1237. });
  1238. }
  1239. template <class P>
  1240. void BufferCache<P>::MarkWrittenBuffer(BufferId buffer_id, VAddr cpu_addr, u32 size) {
  1241. Buffer& buffer = slot_buffers[buffer_id];
  1242. buffer.MarkRegionAsGpuModified(cpu_addr, size);
  1243. const IntervalType base_interval{cpu_addr, cpu_addr + size};
  1244. common_ranges.add(base_interval);
  1245. const bool is_async = Settings::values.use_asynchronous_gpu_emulation.GetValue();
  1246. if (!is_async) {
  1247. return;
  1248. }
  1249. uncommitted_ranges.add(base_interval);
  1250. }
  1251. template <class P>
  1252. BufferId BufferCache<P>::FindBuffer(VAddr cpu_addr, u32 size) {
  1253. if (cpu_addr == 0) {
  1254. return NULL_BUFFER_ID;
  1255. }
  1256. const u64 page = cpu_addr >> PAGE_BITS;
  1257. const BufferId buffer_id = page_table[page];
  1258. if (!buffer_id) {
  1259. return CreateBuffer(cpu_addr, size);
  1260. }
  1261. const Buffer& buffer = slot_buffers[buffer_id];
  1262. if (buffer.IsInBounds(cpu_addr, size)) {
  1263. return buffer_id;
  1264. }
  1265. return CreateBuffer(cpu_addr, size);
  1266. }
  1267. template <class P>
  1268. typename BufferCache<P>::OverlapResult BufferCache<P>::ResolveOverlaps(VAddr cpu_addr,
  1269. u32 wanted_size) {
  1270. static constexpr int STREAM_LEAP_THRESHOLD = 16;
  1271. std::vector<BufferId> overlap_ids;
  1272. VAddr begin = cpu_addr;
  1273. VAddr end = cpu_addr + wanted_size;
  1274. int stream_score = 0;
  1275. bool has_stream_leap = false;
  1276. for (; cpu_addr >> PAGE_BITS < Common::DivCeil(end, PAGE_SIZE); cpu_addr += PAGE_SIZE) {
  1277. const BufferId overlap_id = page_table[cpu_addr >> PAGE_BITS];
  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 -= PAGE_SIZE * 256;
  1304. cpu_addr = begin;
  1305. }
  1306. if (expands_left) {
  1307. end += PAGE_SIZE * 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 / PAGE_SIZE;
  1377. const u64 page_end = Common::DivCeil(cpu_addr_end, PAGE_SIZE);
  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