buffer_cache.h 72 KB

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