buffer_cache.h 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912
  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. SynchronizeBuffer(buffer, index_buffer.cpu_addr, size);
  814. if constexpr (HAS_FULL_INDEX_AND_PRIMITIVE_SUPPORT) {
  815. const u32 new_offset = offset + maxwell3d->regs.index_array.first *
  816. maxwell3d->regs.index_array.FormatSizeInBytes();
  817. runtime.BindIndexBuffer(buffer, new_offset, size);
  818. } else {
  819. runtime.BindIndexBuffer(maxwell3d->regs.draw.topology, maxwell3d->regs.index_array.format,
  820. maxwell3d->regs.index_array.first,
  821. maxwell3d->regs.index_array.count, buffer, offset, size);
  822. }
  823. }
  824. template <class P>
  825. void BufferCache<P>::BindHostVertexBuffers() {
  826. auto& flags = maxwell3d->dirty.flags;
  827. for (u32 index = 0; index < NUM_VERTEX_BUFFERS; ++index) {
  828. const Binding& binding = vertex_buffers[index];
  829. Buffer& buffer = slot_buffers[binding.buffer_id];
  830. TouchBuffer(buffer, binding.buffer_id);
  831. SynchronizeBuffer(buffer, binding.cpu_addr, binding.size);
  832. if (!flags[Dirty::VertexBuffer0 + index]) {
  833. continue;
  834. }
  835. flags[Dirty::VertexBuffer0 + index] = false;
  836. const u32 stride = maxwell3d->regs.vertex_array[index].stride;
  837. const u32 offset = buffer.Offset(binding.cpu_addr);
  838. runtime.BindVertexBuffer(index, buffer, offset, binding.size, stride);
  839. }
  840. }
  841. template <class P>
  842. void BufferCache<P>::BindHostGraphicsUniformBuffers(size_t stage) {
  843. u32 dirty = ~0U;
  844. if constexpr (HAS_PERSISTENT_UNIFORM_BUFFER_BINDINGS) {
  845. dirty = std::exchange(dirty_uniform_buffers[stage], 0);
  846. }
  847. u32 binding_index = 0;
  848. ForEachEnabledBit(enabled_uniform_buffer_masks[stage], [&](u32 index) {
  849. const bool needs_bind = ((dirty >> index) & 1) != 0;
  850. BindHostGraphicsUniformBuffer(stage, index, binding_index, needs_bind);
  851. if constexpr (NEEDS_BIND_UNIFORM_INDEX) {
  852. ++binding_index;
  853. }
  854. });
  855. }
  856. template <class P>
  857. void BufferCache<P>::BindHostGraphicsUniformBuffer(size_t stage, u32 index, u32 binding_index,
  858. bool needs_bind) {
  859. const Binding& binding = uniform_buffers[stage][index];
  860. const VAddr cpu_addr = binding.cpu_addr;
  861. const u32 size = std::min(binding.size, (*uniform_buffer_sizes)[stage][index]);
  862. Buffer& buffer = slot_buffers[binding.buffer_id];
  863. TouchBuffer(buffer, binding.buffer_id);
  864. const bool use_fast_buffer = binding.buffer_id != NULL_BUFFER_ID &&
  865. size <= uniform_buffer_skip_cache_size &&
  866. !buffer.IsRegionGpuModified(cpu_addr, size);
  867. if (use_fast_buffer) {
  868. if constexpr (IS_OPENGL) {
  869. if (runtime.HasFastBufferSubData()) {
  870. // Fast path for Nvidia
  871. const bool should_fast_bind =
  872. !HasFastUniformBufferBound(stage, binding_index) ||
  873. uniform_buffer_binding_sizes[stage][binding_index] != size;
  874. if (should_fast_bind) {
  875. // We only have to bind when the currently bound buffer is not the fast version
  876. fast_bound_uniform_buffers[stage] |= 1U << binding_index;
  877. uniform_buffer_binding_sizes[stage][binding_index] = size;
  878. runtime.BindFastUniformBuffer(stage, binding_index, size);
  879. }
  880. const auto span = ImmediateBufferWithData(cpu_addr, size);
  881. runtime.PushFastUniformBuffer(stage, binding_index, span);
  882. return;
  883. }
  884. }
  885. if constexpr (IS_OPENGL) {
  886. fast_bound_uniform_buffers[stage] |= 1U << binding_index;
  887. uniform_buffer_binding_sizes[stage][binding_index] = size;
  888. }
  889. // Stream buffer path to avoid stalling on non-Nvidia drivers or Vulkan
  890. const std::span<u8> span = runtime.BindMappedUniformBuffer(stage, binding_index, size);
  891. cpu_memory.ReadBlockUnsafe(cpu_addr, span.data(), size);
  892. return;
  893. }
  894. // Classic cached path
  895. const bool sync_cached = SynchronizeBuffer(buffer, cpu_addr, size);
  896. if (sync_cached) {
  897. ++uniform_cache_hits[0];
  898. }
  899. ++uniform_cache_shots[0];
  900. // Skip binding if it's not needed and if the bound buffer is not the fast version
  901. // This exists to avoid instances where the fast buffer is bound and a GPU write happens
  902. needs_bind |= HasFastUniformBufferBound(stage, binding_index);
  903. if constexpr (HAS_PERSISTENT_UNIFORM_BUFFER_BINDINGS) {
  904. needs_bind |= uniform_buffer_binding_sizes[stage][binding_index] != size;
  905. }
  906. if (!needs_bind) {
  907. return;
  908. }
  909. const u32 offset = buffer.Offset(cpu_addr);
  910. if constexpr (IS_OPENGL) {
  911. // Fast buffer will be unbound
  912. fast_bound_uniform_buffers[stage] &= ~(1U << binding_index);
  913. // Mark the index as dirty if offset doesn't match
  914. const bool is_copy_bind = offset != 0 && !runtime.SupportsNonZeroUniformOffset();
  915. dirty_uniform_buffers[stage] |= (is_copy_bind ? 1U : 0U) << index;
  916. }
  917. if constexpr (HAS_PERSISTENT_UNIFORM_BUFFER_BINDINGS) {
  918. uniform_buffer_binding_sizes[stage][binding_index] = size;
  919. }
  920. if constexpr (NEEDS_BIND_UNIFORM_INDEX) {
  921. runtime.BindUniformBuffer(stage, binding_index, buffer, offset, size);
  922. } else {
  923. runtime.BindUniformBuffer(buffer, offset, size);
  924. }
  925. }
  926. template <class P>
  927. void BufferCache<P>::BindHostGraphicsStorageBuffers(size_t stage) {
  928. u32 binding_index = 0;
  929. ForEachEnabledBit(enabled_storage_buffers[stage], [&](u32 index) {
  930. const Binding& binding = storage_buffers[stage][index];
  931. Buffer& buffer = slot_buffers[binding.buffer_id];
  932. TouchBuffer(buffer, binding.buffer_id);
  933. const u32 size = binding.size;
  934. SynchronizeBuffer(buffer, binding.cpu_addr, size);
  935. const u32 offset = buffer.Offset(binding.cpu_addr);
  936. const bool is_written = ((written_storage_buffers[stage] >> index) & 1) != 0;
  937. if constexpr (NEEDS_BIND_STORAGE_INDEX) {
  938. runtime.BindStorageBuffer(stage, binding_index, buffer, offset, size, is_written);
  939. ++binding_index;
  940. } else {
  941. runtime.BindStorageBuffer(buffer, offset, size, is_written);
  942. }
  943. });
  944. }
  945. template <class P>
  946. void BufferCache<P>::BindHostGraphicsTextureBuffers(size_t stage) {
  947. ForEachEnabledBit(enabled_texture_buffers[stage], [&](u32 index) {
  948. const TextureBufferBinding& binding = texture_buffers[stage][index];
  949. Buffer& buffer = slot_buffers[binding.buffer_id];
  950. const u32 size = binding.size;
  951. SynchronizeBuffer(buffer, binding.cpu_addr, size);
  952. const u32 offset = buffer.Offset(binding.cpu_addr);
  953. const PixelFormat format = binding.format;
  954. if constexpr (SEPARATE_IMAGE_BUFFERS_BINDINGS) {
  955. if (((image_texture_buffers[stage] >> index) & 1) != 0) {
  956. runtime.BindImageBuffer(buffer, offset, size, format);
  957. } else {
  958. runtime.BindTextureBuffer(buffer, offset, size, format);
  959. }
  960. } else {
  961. runtime.BindTextureBuffer(buffer, offset, size, format);
  962. }
  963. });
  964. }
  965. template <class P>
  966. void BufferCache<P>::BindHostTransformFeedbackBuffers() {
  967. if (maxwell3d->regs.tfb_enabled == 0) {
  968. return;
  969. }
  970. for (u32 index = 0; index < NUM_TRANSFORM_FEEDBACK_BUFFERS; ++index) {
  971. const Binding& binding = transform_feedback_buffers[index];
  972. Buffer& buffer = slot_buffers[binding.buffer_id];
  973. TouchBuffer(buffer, binding.buffer_id);
  974. const u32 size = binding.size;
  975. SynchronizeBuffer(buffer, binding.cpu_addr, size);
  976. const u32 offset = buffer.Offset(binding.cpu_addr);
  977. runtime.BindTransformFeedbackBuffer(index, buffer, offset, size);
  978. }
  979. }
  980. template <class P>
  981. void BufferCache<P>::BindHostComputeUniformBuffers() {
  982. if constexpr (HAS_PERSISTENT_UNIFORM_BUFFER_BINDINGS) {
  983. // Mark all uniform buffers as dirty
  984. dirty_uniform_buffers.fill(~u32{0});
  985. fast_bound_uniform_buffers.fill(0);
  986. }
  987. u32 binding_index = 0;
  988. ForEachEnabledBit(enabled_compute_uniform_buffer_mask, [&](u32 index) {
  989. const Binding& binding = compute_uniform_buffers[index];
  990. Buffer& buffer = slot_buffers[binding.buffer_id];
  991. TouchBuffer(buffer, binding.buffer_id);
  992. const u32 size = std::min(binding.size, (*compute_uniform_buffer_sizes)[index]);
  993. SynchronizeBuffer(buffer, binding.cpu_addr, size);
  994. const u32 offset = buffer.Offset(binding.cpu_addr);
  995. if constexpr (NEEDS_BIND_UNIFORM_INDEX) {
  996. runtime.BindComputeUniformBuffer(binding_index, buffer, offset, size);
  997. ++binding_index;
  998. } else {
  999. runtime.BindUniformBuffer(buffer, offset, size);
  1000. }
  1001. });
  1002. }
  1003. template <class P>
  1004. void BufferCache<P>::BindHostComputeStorageBuffers() {
  1005. u32 binding_index = 0;
  1006. ForEachEnabledBit(enabled_compute_storage_buffers, [&](u32 index) {
  1007. const Binding& binding = compute_storage_buffers[index];
  1008. Buffer& buffer = slot_buffers[binding.buffer_id];
  1009. TouchBuffer(buffer, binding.buffer_id);
  1010. const u32 size = binding.size;
  1011. SynchronizeBuffer(buffer, binding.cpu_addr, size);
  1012. const u32 offset = buffer.Offset(binding.cpu_addr);
  1013. const bool is_written = ((written_compute_storage_buffers >> index) & 1) != 0;
  1014. if constexpr (NEEDS_BIND_STORAGE_INDEX) {
  1015. runtime.BindComputeStorageBuffer(binding_index, buffer, offset, size, is_written);
  1016. ++binding_index;
  1017. } else {
  1018. runtime.BindStorageBuffer(buffer, offset, size, is_written);
  1019. }
  1020. });
  1021. }
  1022. template <class P>
  1023. void BufferCache<P>::BindHostComputeTextureBuffers() {
  1024. ForEachEnabledBit(enabled_compute_texture_buffers, [&](u32 index) {
  1025. const TextureBufferBinding& binding = compute_texture_buffers[index];
  1026. Buffer& buffer = slot_buffers[binding.buffer_id];
  1027. const u32 size = binding.size;
  1028. SynchronizeBuffer(buffer, binding.cpu_addr, size);
  1029. const u32 offset = buffer.Offset(binding.cpu_addr);
  1030. const PixelFormat format = binding.format;
  1031. if constexpr (SEPARATE_IMAGE_BUFFERS_BINDINGS) {
  1032. if (((image_compute_texture_buffers >> index) & 1) != 0) {
  1033. runtime.BindImageBuffer(buffer, offset, size, format);
  1034. } else {
  1035. runtime.BindTextureBuffer(buffer, offset, size, format);
  1036. }
  1037. } else {
  1038. runtime.BindTextureBuffer(buffer, offset, size, format);
  1039. }
  1040. });
  1041. }
  1042. template <class P>
  1043. void BufferCache<P>::DoUpdateGraphicsBuffers(bool is_indexed) {
  1044. do {
  1045. has_deleted_buffers = false;
  1046. if (is_indexed) {
  1047. UpdateIndexBuffer();
  1048. }
  1049. UpdateVertexBuffers();
  1050. UpdateTransformFeedbackBuffers();
  1051. for (size_t stage = 0; stage < NUM_STAGES; ++stage) {
  1052. UpdateUniformBuffers(stage);
  1053. UpdateStorageBuffers(stage);
  1054. UpdateTextureBuffers(stage);
  1055. }
  1056. } while (has_deleted_buffers);
  1057. }
  1058. template <class P>
  1059. void BufferCache<P>::DoUpdateComputeBuffers() {
  1060. UpdateComputeUniformBuffers();
  1061. UpdateComputeStorageBuffers();
  1062. UpdateComputeTextureBuffers();
  1063. }
  1064. template <class P>
  1065. void BufferCache<P>::UpdateIndexBuffer() {
  1066. // We have to check for the dirty flags and index count
  1067. // The index count is currently changed without updating the dirty flags
  1068. const auto& index_array = maxwell3d->regs.index_array;
  1069. auto& flags = maxwell3d->dirty.flags;
  1070. if (!flags[Dirty::IndexBuffer] && last_index_count == index_array.count) {
  1071. return;
  1072. }
  1073. flags[Dirty::IndexBuffer] = false;
  1074. last_index_count = index_array.count;
  1075. const GPUVAddr gpu_addr_begin = index_array.StartAddress();
  1076. const GPUVAddr gpu_addr_end = index_array.EndAddress();
  1077. const std::optional<VAddr> cpu_addr = gpu_memory->GpuToCpuAddress(gpu_addr_begin);
  1078. const u32 address_size = static_cast<u32>(gpu_addr_end - gpu_addr_begin);
  1079. const u32 draw_size = (index_array.count + index_array.first) * index_array.FormatSizeInBytes();
  1080. const u32 size = std::min(address_size, draw_size);
  1081. if (size == 0 || !cpu_addr) {
  1082. index_buffer = NULL_BINDING;
  1083. return;
  1084. }
  1085. index_buffer = Binding{
  1086. .cpu_addr = *cpu_addr,
  1087. .size = size,
  1088. .buffer_id = FindBuffer(*cpu_addr, size),
  1089. };
  1090. }
  1091. template <class P>
  1092. void BufferCache<P>::UpdateVertexBuffers() {
  1093. auto& flags = maxwell3d->dirty.flags;
  1094. if (!maxwell3d->dirty.flags[Dirty::VertexBuffers]) {
  1095. return;
  1096. }
  1097. flags[Dirty::VertexBuffers] = false;
  1098. for (u32 index = 0; index < NUM_VERTEX_BUFFERS; ++index) {
  1099. UpdateVertexBuffer(index);
  1100. }
  1101. }
  1102. template <class P>
  1103. void BufferCache<P>::UpdateVertexBuffer(u32 index) {
  1104. if (!maxwell3d->dirty.flags[Dirty::VertexBuffer0 + index]) {
  1105. return;
  1106. }
  1107. const auto& array = maxwell3d->regs.vertex_array[index];
  1108. const auto& limit = maxwell3d->regs.vertex_array_limit[index];
  1109. const GPUVAddr gpu_addr_begin = array.StartAddress();
  1110. const GPUVAddr gpu_addr_end = limit.LimitAddress() + 1;
  1111. const std::optional<VAddr> cpu_addr = gpu_memory->GpuToCpuAddress(gpu_addr_begin);
  1112. u32 address_size = static_cast<u32>(
  1113. std::min(gpu_addr_end - gpu_addr_begin, static_cast<u64>(std::numeric_limits<u32>::max())));
  1114. if (array.enable == 0 || address_size == 0 || !cpu_addr) {
  1115. vertex_buffers[index] = NULL_BINDING;
  1116. return;
  1117. }
  1118. if (!gpu_memory->IsWithinGPUAddressRange(gpu_addr_end)) {
  1119. address_size =
  1120. static_cast<u32>(gpu_memory->MaxContinousRange(gpu_addr_begin, address_size));
  1121. }
  1122. const u32 size = address_size; // TODO: Analyze stride and number of vertices
  1123. vertex_buffers[index] = Binding{
  1124. .cpu_addr = *cpu_addr,
  1125. .size = size,
  1126. .buffer_id = FindBuffer(*cpu_addr, size),
  1127. };
  1128. }
  1129. template <class P>
  1130. void BufferCache<P>::UpdateUniformBuffers(size_t stage) {
  1131. ForEachEnabledBit(enabled_uniform_buffer_masks[stage], [&](u32 index) {
  1132. Binding& binding = uniform_buffers[stage][index];
  1133. if (binding.buffer_id) {
  1134. // Already updated
  1135. return;
  1136. }
  1137. // Mark as dirty
  1138. if constexpr (HAS_PERSISTENT_UNIFORM_BUFFER_BINDINGS) {
  1139. dirty_uniform_buffers[stage] |= 1U << index;
  1140. }
  1141. // Resolve buffer
  1142. binding.buffer_id = FindBuffer(binding.cpu_addr, binding.size);
  1143. });
  1144. }
  1145. template <class P>
  1146. void BufferCache<P>::UpdateStorageBuffers(size_t stage) {
  1147. const u32 written_mask = written_storage_buffers[stage];
  1148. ForEachEnabledBit(enabled_storage_buffers[stage], [&](u32 index) {
  1149. // Resolve buffer
  1150. Binding& binding = storage_buffers[stage][index];
  1151. const BufferId buffer_id = FindBuffer(binding.cpu_addr, binding.size);
  1152. binding.buffer_id = buffer_id;
  1153. // Mark buffer as written if needed
  1154. if (((written_mask >> index) & 1) != 0) {
  1155. MarkWrittenBuffer(buffer_id, binding.cpu_addr, binding.size);
  1156. }
  1157. });
  1158. }
  1159. template <class P>
  1160. void BufferCache<P>::UpdateTextureBuffers(size_t stage) {
  1161. ForEachEnabledBit(enabled_texture_buffers[stage], [&](u32 index) {
  1162. Binding& binding = texture_buffers[stage][index];
  1163. binding.buffer_id = FindBuffer(binding.cpu_addr, binding.size);
  1164. // Mark buffer as written if needed
  1165. if (((written_texture_buffers[stage] >> index) & 1) != 0) {
  1166. MarkWrittenBuffer(binding.buffer_id, binding.cpu_addr, binding.size);
  1167. }
  1168. });
  1169. }
  1170. template <class P>
  1171. void BufferCache<P>::UpdateTransformFeedbackBuffers() {
  1172. if (maxwell3d->regs.tfb_enabled == 0) {
  1173. return;
  1174. }
  1175. for (u32 index = 0; index < NUM_TRANSFORM_FEEDBACK_BUFFERS; ++index) {
  1176. UpdateTransformFeedbackBuffer(index);
  1177. }
  1178. }
  1179. template <class P>
  1180. void BufferCache<P>::UpdateTransformFeedbackBuffer(u32 index) {
  1181. const auto& binding = maxwell3d->regs.tfb_bindings[index];
  1182. const GPUVAddr gpu_addr = binding.Address() + binding.buffer_offset;
  1183. const u32 size = binding.buffer_size;
  1184. const std::optional<VAddr> cpu_addr = gpu_memory->GpuToCpuAddress(gpu_addr);
  1185. if (binding.buffer_enable == 0 || size == 0 || !cpu_addr) {
  1186. transform_feedback_buffers[index] = NULL_BINDING;
  1187. return;
  1188. }
  1189. const BufferId buffer_id = FindBuffer(*cpu_addr, size);
  1190. transform_feedback_buffers[index] = Binding{
  1191. .cpu_addr = *cpu_addr,
  1192. .size = size,
  1193. .buffer_id = buffer_id,
  1194. };
  1195. MarkWrittenBuffer(buffer_id, *cpu_addr, size);
  1196. }
  1197. template <class P>
  1198. void BufferCache<P>::UpdateComputeUniformBuffers() {
  1199. ForEachEnabledBit(enabled_compute_uniform_buffer_mask, [&](u32 index) {
  1200. Binding& binding = compute_uniform_buffers[index];
  1201. binding = NULL_BINDING;
  1202. const auto& launch_desc = kepler_compute->launch_description;
  1203. if (((launch_desc.const_buffer_enable_mask >> index) & 1) != 0) {
  1204. const auto& cbuf = launch_desc.const_buffer_config[index];
  1205. const std::optional<VAddr> cpu_addr = gpu_memory->GpuToCpuAddress(cbuf.Address());
  1206. if (cpu_addr) {
  1207. binding.cpu_addr = *cpu_addr;
  1208. binding.size = cbuf.size;
  1209. }
  1210. }
  1211. binding.buffer_id = FindBuffer(binding.cpu_addr, binding.size);
  1212. });
  1213. }
  1214. template <class P>
  1215. void BufferCache<P>::UpdateComputeStorageBuffers() {
  1216. ForEachEnabledBit(enabled_compute_storage_buffers, [&](u32 index) {
  1217. // Resolve buffer
  1218. Binding& binding = compute_storage_buffers[index];
  1219. binding.buffer_id = FindBuffer(binding.cpu_addr, binding.size);
  1220. // Mark as written if needed
  1221. if (((written_compute_storage_buffers >> index) & 1) != 0) {
  1222. MarkWrittenBuffer(binding.buffer_id, binding.cpu_addr, binding.size);
  1223. }
  1224. });
  1225. }
  1226. template <class P>
  1227. void BufferCache<P>::UpdateComputeTextureBuffers() {
  1228. ForEachEnabledBit(enabled_compute_texture_buffers, [&](u32 index) {
  1229. Binding& binding = compute_texture_buffers[index];
  1230. binding.buffer_id = FindBuffer(binding.cpu_addr, binding.size);
  1231. // Mark as written if needed
  1232. if (((written_compute_texture_buffers >> index) & 1) != 0) {
  1233. MarkWrittenBuffer(binding.buffer_id, binding.cpu_addr, binding.size);
  1234. }
  1235. });
  1236. }
  1237. template <class P>
  1238. void BufferCache<P>::MarkWrittenBuffer(BufferId buffer_id, VAddr cpu_addr, u32 size) {
  1239. Buffer& buffer = slot_buffers[buffer_id];
  1240. buffer.MarkRegionAsGpuModified(cpu_addr, size);
  1241. const IntervalType base_interval{cpu_addr, cpu_addr + size};
  1242. common_ranges.add(base_interval);
  1243. const bool is_async = Settings::values.use_asynchronous_gpu_emulation.GetValue();
  1244. if (!is_async) {
  1245. return;
  1246. }
  1247. uncommitted_ranges.add(base_interval);
  1248. }
  1249. template <class P>
  1250. BufferId BufferCache<P>::FindBuffer(VAddr cpu_addr, u32 size) {
  1251. if (cpu_addr == 0) {
  1252. return NULL_BUFFER_ID;
  1253. }
  1254. const u64 page = cpu_addr >> YUZU_PAGEBITS;
  1255. const BufferId buffer_id = page_table[page];
  1256. if (!buffer_id) {
  1257. return CreateBuffer(cpu_addr, size);
  1258. }
  1259. const Buffer& buffer = slot_buffers[buffer_id];
  1260. if (buffer.IsInBounds(cpu_addr, size)) {
  1261. return buffer_id;
  1262. }
  1263. return CreateBuffer(cpu_addr, size);
  1264. }
  1265. template <class P>
  1266. typename BufferCache<P>::OverlapResult BufferCache<P>::ResolveOverlaps(VAddr cpu_addr,
  1267. u32 wanted_size) {
  1268. static constexpr int STREAM_LEAP_THRESHOLD = 16;
  1269. std::vector<BufferId> overlap_ids;
  1270. VAddr begin = cpu_addr;
  1271. VAddr end = cpu_addr + wanted_size;
  1272. int stream_score = 0;
  1273. bool has_stream_leap = false;
  1274. for (; cpu_addr >> YUZU_PAGEBITS < Common::DivCeil(end, YUZU_PAGESIZE);
  1275. cpu_addr += YUZU_PAGESIZE) {
  1276. const BufferId overlap_id = page_table[cpu_addr >> YUZU_PAGEBITS];
  1277. if (!overlap_id) {
  1278. continue;
  1279. }
  1280. Buffer& overlap = slot_buffers[overlap_id];
  1281. if (overlap.IsPicked()) {
  1282. continue;
  1283. }
  1284. overlap_ids.push_back(overlap_id);
  1285. overlap.Pick();
  1286. const VAddr overlap_cpu_addr = overlap.CpuAddr();
  1287. const bool expands_left = overlap_cpu_addr < begin;
  1288. if (expands_left) {
  1289. cpu_addr = begin = overlap_cpu_addr;
  1290. }
  1291. const VAddr overlap_end = overlap_cpu_addr + overlap.SizeBytes();
  1292. const bool expands_right = overlap_end > end;
  1293. if (overlap_end > end) {
  1294. end = overlap_end;
  1295. }
  1296. stream_score += overlap.StreamScore();
  1297. if (stream_score > STREAM_LEAP_THRESHOLD && !has_stream_leap) {
  1298. // When this memory region has been joined a bunch of times, we assume it's being used
  1299. // as a stream buffer. Increase the size to skip constantly recreating buffers.
  1300. has_stream_leap = true;
  1301. if (expands_right) {
  1302. begin -= YUZU_PAGESIZE * 256;
  1303. cpu_addr = begin;
  1304. }
  1305. if (expands_left) {
  1306. end += YUZU_PAGESIZE * 256;
  1307. }
  1308. }
  1309. }
  1310. return OverlapResult{
  1311. .ids = std::move(overlap_ids),
  1312. .begin = begin,
  1313. .end = end,
  1314. .has_stream_leap = has_stream_leap,
  1315. };
  1316. }
  1317. template <class P>
  1318. void BufferCache<P>::JoinOverlap(BufferId new_buffer_id, BufferId overlap_id,
  1319. bool accumulate_stream_score) {
  1320. Buffer& new_buffer = slot_buffers[new_buffer_id];
  1321. Buffer& overlap = slot_buffers[overlap_id];
  1322. if (accumulate_stream_score) {
  1323. new_buffer.IncreaseStreamScore(overlap.StreamScore() + 1);
  1324. }
  1325. std::vector<BufferCopy> copies;
  1326. const size_t dst_base_offset = overlap.CpuAddr() - new_buffer.CpuAddr();
  1327. overlap.ForEachDownloadRange([&](u64 begin, u64 range_size) {
  1328. copies.push_back(BufferCopy{
  1329. .src_offset = begin,
  1330. .dst_offset = dst_base_offset + begin,
  1331. .size = range_size,
  1332. });
  1333. new_buffer.UnmarkRegionAsCpuModified(begin, range_size);
  1334. new_buffer.MarkRegionAsGpuModified(begin, range_size);
  1335. });
  1336. if (!copies.empty()) {
  1337. runtime.CopyBuffer(slot_buffers[new_buffer_id], overlap, copies);
  1338. }
  1339. DeleteBuffer(overlap_id);
  1340. }
  1341. template <class P>
  1342. BufferId BufferCache<P>::CreateBuffer(VAddr cpu_addr, u32 wanted_size) {
  1343. const OverlapResult overlap = ResolveOverlaps(cpu_addr, wanted_size);
  1344. const u32 size = static_cast<u32>(overlap.end - overlap.begin);
  1345. const BufferId new_buffer_id = slot_buffers.insert(runtime, rasterizer, overlap.begin, size);
  1346. auto& new_buffer = slot_buffers[new_buffer_id];
  1347. runtime.ClearBuffer(new_buffer, 0, new_buffer.SizeBytes(), 0);
  1348. for (const BufferId overlap_id : overlap.ids) {
  1349. JoinOverlap(new_buffer_id, overlap_id, !overlap.has_stream_leap);
  1350. }
  1351. Register(new_buffer_id);
  1352. TouchBuffer(slot_buffers[new_buffer_id], new_buffer_id);
  1353. return new_buffer_id;
  1354. }
  1355. template <class P>
  1356. void BufferCache<P>::Register(BufferId buffer_id) {
  1357. ChangeRegister<true>(buffer_id);
  1358. }
  1359. template <class P>
  1360. void BufferCache<P>::Unregister(BufferId buffer_id) {
  1361. ChangeRegister<false>(buffer_id);
  1362. }
  1363. template <class P>
  1364. template <bool insert>
  1365. void BufferCache<P>::ChangeRegister(BufferId buffer_id) {
  1366. Buffer& buffer = slot_buffers[buffer_id];
  1367. const auto size = buffer.SizeBytes();
  1368. if (insert) {
  1369. total_used_memory += Common::AlignUp(size, 1024);
  1370. buffer.setLRUID(lru_cache.Insert(buffer_id, frame_tick));
  1371. } else {
  1372. total_used_memory -= Common::AlignUp(size, 1024);
  1373. lru_cache.Free(buffer.getLRUID());
  1374. }
  1375. const VAddr cpu_addr_begin = buffer.CpuAddr();
  1376. const VAddr cpu_addr_end = cpu_addr_begin + size;
  1377. const u64 page_begin = cpu_addr_begin / YUZU_PAGESIZE;
  1378. const u64 page_end = Common::DivCeil(cpu_addr_end, YUZU_PAGESIZE);
  1379. for (u64 page = page_begin; page != page_end; ++page) {
  1380. if constexpr (insert) {
  1381. page_table[page] = buffer_id;
  1382. } else {
  1383. page_table[page] = BufferId{};
  1384. }
  1385. }
  1386. }
  1387. template <class P>
  1388. void BufferCache<P>::TouchBuffer(Buffer& buffer, BufferId buffer_id) noexcept {
  1389. if (buffer_id != NULL_BUFFER_ID) {
  1390. lru_cache.Touch(buffer.getLRUID(), frame_tick);
  1391. }
  1392. }
  1393. template <class P>
  1394. bool BufferCache<P>::SynchronizeBuffer(Buffer& buffer, VAddr cpu_addr, u32 size) {
  1395. if (buffer.CpuAddr() == 0) {
  1396. return true;
  1397. }
  1398. return SynchronizeBufferImpl(buffer, cpu_addr, size);
  1399. }
  1400. template <class P>
  1401. bool BufferCache<P>::SynchronizeBufferImpl(Buffer& buffer, VAddr cpu_addr, u32 size) {
  1402. boost::container::small_vector<BufferCopy, 4> copies;
  1403. u64 total_size_bytes = 0;
  1404. u64 largest_copy = 0;
  1405. buffer.ForEachUploadRange(cpu_addr, size, [&](u64 range_offset, u64 range_size) {
  1406. copies.push_back(BufferCopy{
  1407. .src_offset = total_size_bytes,
  1408. .dst_offset = range_offset,
  1409. .size = range_size,
  1410. });
  1411. total_size_bytes += range_size;
  1412. largest_copy = std::max(largest_copy, range_size);
  1413. });
  1414. if (total_size_bytes == 0) {
  1415. return true;
  1416. }
  1417. const std::span<BufferCopy> copies_span(copies.data(), copies.size());
  1418. UploadMemory(buffer, total_size_bytes, largest_copy, copies_span);
  1419. return false;
  1420. }
  1421. template <class P>
  1422. void BufferCache<P>::UploadMemory(Buffer& buffer, u64 total_size_bytes, u64 largest_copy,
  1423. std::span<BufferCopy> copies) {
  1424. if constexpr (USE_MEMORY_MAPS) {
  1425. MappedUploadMemory(buffer, total_size_bytes, copies);
  1426. } else {
  1427. ImmediateUploadMemory(buffer, largest_copy, copies);
  1428. }
  1429. }
  1430. template <class P>
  1431. void BufferCache<P>::ImmediateUploadMemory(Buffer& buffer, u64 largest_copy,
  1432. std::span<const BufferCopy> copies) {
  1433. std::span<u8> immediate_buffer;
  1434. for (const BufferCopy& copy : copies) {
  1435. std::span<const u8> upload_span;
  1436. const VAddr cpu_addr = buffer.CpuAddr() + copy.dst_offset;
  1437. if (IsRangeGranular(cpu_addr, copy.size)) {
  1438. upload_span = std::span(cpu_memory.GetPointer(cpu_addr), copy.size);
  1439. } else {
  1440. if (immediate_buffer.empty()) {
  1441. immediate_buffer = ImmediateBuffer(largest_copy);
  1442. }
  1443. cpu_memory.ReadBlockUnsafe(cpu_addr, immediate_buffer.data(), copy.size);
  1444. upload_span = immediate_buffer.subspan(0, copy.size);
  1445. }
  1446. buffer.ImmediateUpload(copy.dst_offset, upload_span);
  1447. }
  1448. }
  1449. template <class P>
  1450. void BufferCache<P>::MappedUploadMemory(Buffer& buffer, u64 total_size_bytes,
  1451. std::span<BufferCopy> copies) {
  1452. auto upload_staging = runtime.UploadStagingBuffer(total_size_bytes);
  1453. const std::span<u8> staging_pointer = upload_staging.mapped_span;
  1454. for (BufferCopy& copy : copies) {
  1455. u8* const src_pointer = staging_pointer.data() + copy.src_offset;
  1456. const VAddr cpu_addr = buffer.CpuAddr() + copy.dst_offset;
  1457. cpu_memory.ReadBlockUnsafe(cpu_addr, src_pointer, copy.size);
  1458. // Apply the staging offset
  1459. copy.src_offset += upload_staging.offset;
  1460. }
  1461. runtime.CopyBuffer(buffer, upload_staging.buffer, copies);
  1462. }
  1463. template <class P>
  1464. bool BufferCache<P>::InlineMemory(VAddr dest_address, size_t copy_size,
  1465. std::span<const u8> inlined_buffer) {
  1466. const bool is_dirty = IsRegionRegistered(dest_address, copy_size);
  1467. if (!is_dirty) {
  1468. return false;
  1469. }
  1470. if (!IsRegionGpuModified(dest_address, copy_size)) {
  1471. return false;
  1472. }
  1473. const IntervalType subtract_interval{dest_address, dest_address + copy_size};
  1474. ClearDownload(subtract_interval);
  1475. common_ranges.subtract(subtract_interval);
  1476. BufferId buffer_id = FindBuffer(dest_address, static_cast<u32>(copy_size));
  1477. auto& buffer = slot_buffers[buffer_id];
  1478. SynchronizeBuffer(buffer, dest_address, static_cast<u32>(copy_size));
  1479. if constexpr (USE_MEMORY_MAPS) {
  1480. std::array copies{BufferCopy{
  1481. .src_offset = 0,
  1482. .dst_offset = buffer.Offset(dest_address),
  1483. .size = copy_size,
  1484. }};
  1485. auto upload_staging = runtime.UploadStagingBuffer(copy_size);
  1486. u8* const src_pointer = upload_staging.mapped_span.data();
  1487. std::memcpy(src_pointer, inlined_buffer.data(), copy_size);
  1488. runtime.CopyBuffer(buffer, upload_staging.buffer, copies);
  1489. } else {
  1490. buffer.ImmediateUpload(buffer.Offset(dest_address), inlined_buffer.first(copy_size));
  1491. }
  1492. return true;
  1493. }
  1494. template <class P>
  1495. void BufferCache<P>::DownloadBufferMemory(Buffer& buffer) {
  1496. DownloadBufferMemory(buffer, buffer.CpuAddr(), buffer.SizeBytes());
  1497. }
  1498. template <class P>
  1499. void BufferCache<P>::DownloadBufferMemory(Buffer& buffer, VAddr cpu_addr, u64 size) {
  1500. boost::container::small_vector<BufferCopy, 1> copies;
  1501. u64 total_size_bytes = 0;
  1502. u64 largest_copy = 0;
  1503. buffer.ForEachDownloadRangeAndClear(cpu_addr, size, [&](u64 range_offset, u64 range_size) {
  1504. const VAddr buffer_addr = buffer.CpuAddr();
  1505. const auto add_download = [&](VAddr start, VAddr end) {
  1506. const u64 new_offset = start - buffer_addr;
  1507. const u64 new_size = end - start;
  1508. copies.push_back(BufferCopy{
  1509. .src_offset = new_offset,
  1510. .dst_offset = total_size_bytes,
  1511. .size = new_size,
  1512. });
  1513. // Align up to avoid cache conflicts
  1514. constexpr u64 align = 256ULL;
  1515. constexpr u64 mask = ~(align - 1ULL);
  1516. total_size_bytes += (new_size + align - 1) & mask;
  1517. largest_copy = std::max(largest_copy, new_size);
  1518. };
  1519. const VAddr start_address = buffer_addr + range_offset;
  1520. const VAddr end_address = start_address + range_size;
  1521. ForEachWrittenRange(start_address, range_size, add_download);
  1522. const IntervalType subtract_interval{start_address, end_address};
  1523. ClearDownload(subtract_interval);
  1524. common_ranges.subtract(subtract_interval);
  1525. });
  1526. if (total_size_bytes == 0) {
  1527. return;
  1528. }
  1529. MICROPROFILE_SCOPE(GPU_DownloadMemory);
  1530. if constexpr (USE_MEMORY_MAPS) {
  1531. auto download_staging = runtime.DownloadStagingBuffer(total_size_bytes);
  1532. const u8* const mapped_memory = download_staging.mapped_span.data();
  1533. const std::span<BufferCopy> copies_span(copies.data(), copies.data() + copies.size());
  1534. for (BufferCopy& copy : copies) {
  1535. // Modify copies to have the staging offset in mind
  1536. copy.dst_offset += download_staging.offset;
  1537. }
  1538. runtime.CopyBuffer(download_staging.buffer, buffer, copies_span);
  1539. runtime.Finish();
  1540. for (const BufferCopy& copy : copies) {
  1541. const VAddr copy_cpu_addr = buffer.CpuAddr() + copy.src_offset;
  1542. // Undo the modified offset
  1543. const u64 dst_offset = copy.dst_offset - download_staging.offset;
  1544. const u8* copy_mapped_memory = mapped_memory + dst_offset;
  1545. cpu_memory.WriteBlockUnsafe(copy_cpu_addr, copy_mapped_memory, copy.size);
  1546. }
  1547. } else {
  1548. const std::span<u8> immediate_buffer = ImmediateBuffer(largest_copy);
  1549. for (const BufferCopy& copy : copies) {
  1550. buffer.ImmediateDownload(copy.src_offset, immediate_buffer.subspan(0, copy.size));
  1551. const VAddr copy_cpu_addr = buffer.CpuAddr() + copy.src_offset;
  1552. cpu_memory.WriteBlockUnsafe(copy_cpu_addr, immediate_buffer.data(), copy.size);
  1553. }
  1554. }
  1555. }
  1556. template <class P>
  1557. void BufferCache<P>::DeleteBuffer(BufferId buffer_id) {
  1558. const auto scalar_replace = [buffer_id](Binding& binding) {
  1559. if (binding.buffer_id == buffer_id) {
  1560. binding.buffer_id = BufferId{};
  1561. }
  1562. };
  1563. const auto replace = [scalar_replace](std::span<Binding> bindings) {
  1564. std::ranges::for_each(bindings, scalar_replace);
  1565. };
  1566. scalar_replace(index_buffer);
  1567. replace(vertex_buffers);
  1568. std::ranges::for_each(uniform_buffers, replace);
  1569. std::ranges::for_each(storage_buffers, replace);
  1570. replace(transform_feedback_buffers);
  1571. replace(compute_uniform_buffers);
  1572. replace(compute_storage_buffers);
  1573. std::erase(cached_write_buffer_ids, buffer_id);
  1574. // Mark the whole buffer as CPU written to stop tracking CPU writes
  1575. Buffer& buffer = slot_buffers[buffer_id];
  1576. buffer.MarkRegionAsCpuModified(buffer.CpuAddr(), buffer.SizeBytes());
  1577. Unregister(buffer_id);
  1578. delayed_destruction_ring.Push(std::move(slot_buffers[buffer_id]));
  1579. slot_buffers.erase(buffer_id);
  1580. NotifyBufferDeletion();
  1581. }
  1582. template <class P>
  1583. void BufferCache<P>::NotifyBufferDeletion() {
  1584. if constexpr (HAS_PERSISTENT_UNIFORM_BUFFER_BINDINGS) {
  1585. dirty_uniform_buffers.fill(~u32{0});
  1586. uniform_buffer_binding_sizes.fill({});
  1587. }
  1588. auto& flags = maxwell3d->dirty.flags;
  1589. flags[Dirty::IndexBuffer] = true;
  1590. flags[Dirty::VertexBuffers] = true;
  1591. for (u32 index = 0; index < NUM_VERTEX_BUFFERS; ++index) {
  1592. flags[Dirty::VertexBuffer0 + index] = true;
  1593. }
  1594. has_deleted_buffers = true;
  1595. }
  1596. template <class P>
  1597. typename BufferCache<P>::Binding BufferCache<P>::StorageBufferBinding(GPUVAddr ssbo_addr,
  1598. bool is_written) const {
  1599. const GPUVAddr gpu_addr = gpu_memory->Read<u64>(ssbo_addr);
  1600. const u32 size = gpu_memory->Read<u32>(ssbo_addr + 8);
  1601. const std::optional<VAddr> cpu_addr = gpu_memory->GpuToCpuAddress(gpu_addr);
  1602. if (!cpu_addr || size == 0) {
  1603. return NULL_BINDING;
  1604. }
  1605. const VAddr cpu_end = Common::AlignUp(*cpu_addr + size, Core::Memory::YUZU_PAGESIZE);
  1606. const Binding binding{
  1607. .cpu_addr = *cpu_addr,
  1608. .size = is_written ? size : static_cast<u32>(cpu_end - *cpu_addr),
  1609. .buffer_id = BufferId{},
  1610. };
  1611. return binding;
  1612. }
  1613. template <class P>
  1614. typename BufferCache<P>::TextureBufferBinding BufferCache<P>::GetTextureBufferBinding(
  1615. GPUVAddr gpu_addr, u32 size, PixelFormat format) {
  1616. const std::optional<VAddr> cpu_addr = gpu_memory->GpuToCpuAddress(gpu_addr);
  1617. TextureBufferBinding binding;
  1618. if (!cpu_addr || size == 0) {
  1619. binding.cpu_addr = 0;
  1620. binding.size = 0;
  1621. binding.buffer_id = NULL_BUFFER_ID;
  1622. binding.format = PixelFormat::Invalid;
  1623. } else {
  1624. binding.cpu_addr = *cpu_addr;
  1625. binding.size = size;
  1626. binding.buffer_id = BufferId{};
  1627. binding.format = format;
  1628. }
  1629. return binding;
  1630. }
  1631. template <class P>
  1632. std::span<const u8> BufferCache<P>::ImmediateBufferWithData(VAddr cpu_addr, size_t size) {
  1633. u8* const base_pointer = cpu_memory.GetPointer(cpu_addr);
  1634. if (IsRangeGranular(cpu_addr, size) ||
  1635. base_pointer + size == cpu_memory.GetPointer(cpu_addr + size)) {
  1636. return std::span(base_pointer, size);
  1637. } else {
  1638. const std::span<u8> span = ImmediateBuffer(size);
  1639. cpu_memory.ReadBlockUnsafe(cpu_addr, span.data(), size);
  1640. return span;
  1641. }
  1642. }
  1643. template <class P>
  1644. std::span<u8> BufferCache<P>::ImmediateBuffer(size_t wanted_capacity) {
  1645. if (wanted_capacity > immediate_buffer_capacity) {
  1646. immediate_buffer_capacity = wanted_capacity;
  1647. immediate_buffer_alloc = std::make_unique<u8[]>(wanted_capacity);
  1648. }
  1649. return std::span<u8>(immediate_buffer_alloc.get(), wanted_capacity);
  1650. }
  1651. template <class P>
  1652. bool BufferCache<P>::HasFastUniformBufferBound(size_t stage, u32 binding_index) const noexcept {
  1653. if constexpr (IS_OPENGL) {
  1654. return ((fast_bound_uniform_buffers[stage] >> binding_index) & 1) != 0;
  1655. } else {
  1656. // Only OpenGL has fast uniform buffers
  1657. return false;
  1658. }
  1659. }
  1660. } // namespace VideoCommon