texture_cache.h 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928
  1. // Copyright 2019 yuzu Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #pragma once
  5. #include <algorithm>
  6. #include <array>
  7. #include <bit>
  8. #include <memory>
  9. #include <mutex>
  10. #include <optional>
  11. #include <span>
  12. #include <type_traits>
  13. #include <unordered_map>
  14. #include <unordered_set>
  15. #include <utility>
  16. #include <vector>
  17. #include <boost/container/small_vector.hpp>
  18. #include "common/alignment.h"
  19. #include "common/common_types.h"
  20. #include "common/literals.h"
  21. #include "common/logging/log.h"
  22. #include "common/settings.h"
  23. #include "video_core/compatible_formats.h"
  24. #include "video_core/delayed_destruction_ring.h"
  25. #include "video_core/dirty_flags.h"
  26. #include "video_core/engines/fermi_2d.h"
  27. #include "video_core/engines/kepler_compute.h"
  28. #include "video_core/engines/maxwell_3d.h"
  29. #include "video_core/memory_manager.h"
  30. #include "video_core/rasterizer_interface.h"
  31. #include "video_core/surface.h"
  32. #include "video_core/texture_cache/descriptor_table.h"
  33. #include "video_core/texture_cache/format_lookup_table.h"
  34. #include "video_core/texture_cache/formatter.h"
  35. #include "video_core/texture_cache/image_base.h"
  36. #include "video_core/texture_cache/image_info.h"
  37. #include "video_core/texture_cache/image_view_base.h"
  38. #include "video_core/texture_cache/image_view_info.h"
  39. #include "video_core/texture_cache/render_targets.h"
  40. #include "video_core/texture_cache/samples_helper.h"
  41. #include "video_core/texture_cache/slot_vector.h"
  42. #include "video_core/texture_cache/types.h"
  43. #include "video_core/texture_cache/util.h"
  44. #include "video_core/textures/texture.h"
  45. namespace VideoCommon {
  46. using Tegra::Texture::SwizzleSource;
  47. using Tegra::Texture::TextureType;
  48. using Tegra::Texture::TICEntry;
  49. using Tegra::Texture::TSCEntry;
  50. using VideoCore::Surface::GetFormatType;
  51. using VideoCore::Surface::IsCopyCompatible;
  52. using VideoCore::Surface::PixelFormat;
  53. using VideoCore::Surface::PixelFormatFromDepthFormat;
  54. using VideoCore::Surface::PixelFormatFromRenderTargetFormat;
  55. using VideoCore::Surface::SurfaceType;
  56. using namespace Common::Literals;
  57. template <class P>
  58. class TextureCache {
  59. /// Address shift for caching images into a hash table
  60. static constexpr u64 PAGE_BITS = 20;
  61. /// Enables debugging features to the texture cache
  62. static constexpr bool ENABLE_VALIDATION = P::ENABLE_VALIDATION;
  63. /// Implement blits as copies between framebuffers
  64. static constexpr bool FRAMEBUFFER_BLITS = P::FRAMEBUFFER_BLITS;
  65. /// True when some copies have to be emulated
  66. static constexpr bool HAS_EMULATED_COPIES = P::HAS_EMULATED_COPIES;
  67. /// True when the API can provide info about the memory of the device.
  68. static constexpr bool HAS_DEVICE_MEMORY_INFO = P::HAS_DEVICE_MEMORY_INFO;
  69. /// Image view ID for null descriptors
  70. static constexpr ImageViewId NULL_IMAGE_VIEW_ID{0};
  71. /// Sampler ID for bugged sampler ids
  72. static constexpr SamplerId NULL_SAMPLER_ID{0};
  73. static constexpr u64 DEFAULT_EXPECTED_MEMORY = 1_GiB;
  74. static constexpr u64 DEFAULT_CRITICAL_MEMORY = 2_GiB;
  75. using Runtime = typename P::Runtime;
  76. using Image = typename P::Image;
  77. using ImageAlloc = typename P::ImageAlloc;
  78. using ImageView = typename P::ImageView;
  79. using Sampler = typename P::Sampler;
  80. using Framebuffer = typename P::Framebuffer;
  81. struct BlitImages {
  82. ImageId dst_id;
  83. ImageId src_id;
  84. PixelFormat dst_format;
  85. PixelFormat src_format;
  86. };
  87. template <typename T>
  88. struct IdentityHash {
  89. [[nodiscard]] size_t operator()(T value) const noexcept {
  90. return static_cast<size_t>(value);
  91. }
  92. };
  93. public:
  94. explicit TextureCache(Runtime&, VideoCore::RasterizerInterface&, Tegra::Engines::Maxwell3D&,
  95. Tegra::Engines::KeplerCompute&, Tegra::MemoryManager&);
  96. /// Notify the cache that a new frame has been queued
  97. void TickFrame();
  98. /// Return a constant reference to the given image view id
  99. [[nodiscard]] const ImageView& GetImageView(ImageViewId id) const noexcept;
  100. /// Return a reference to the given image view id
  101. [[nodiscard]] ImageView& GetImageView(ImageViewId id) noexcept;
  102. /// Mark an image as modified from the GPU
  103. void MarkModification(ImageId id) noexcept;
  104. /// Fill image_view_ids with the graphics images in indices
  105. void FillGraphicsImageViews(std::span<const u32> indices,
  106. std::span<ImageViewId> image_view_ids);
  107. /// Fill image_view_ids with the compute images in indices
  108. void FillComputeImageViews(std::span<const u32> indices, std::span<ImageViewId> image_view_ids);
  109. /// Get the sampler from the graphics descriptor table in the specified index
  110. Sampler* GetGraphicsSampler(u32 index);
  111. /// Get the sampler from the compute descriptor table in the specified index
  112. Sampler* GetComputeSampler(u32 index);
  113. /// Refresh the state for graphics image view and sampler descriptors
  114. void SynchronizeGraphicsDescriptors();
  115. /// Refresh the state for compute image view and sampler descriptors
  116. void SynchronizeComputeDescriptors();
  117. /// Update bound render targets and upload memory if necessary
  118. /// @param is_clear True when the render targets are being used for clears
  119. void UpdateRenderTargets(bool is_clear);
  120. /// Find a framebuffer with the currently bound render targets
  121. /// UpdateRenderTargets should be called before this
  122. Framebuffer* GetFramebuffer();
  123. /// Mark images in a range as modified from the CPU
  124. void WriteMemory(VAddr cpu_addr, size_t size);
  125. /// Download contents of host images to guest memory in a region
  126. void DownloadMemory(VAddr cpu_addr, size_t size);
  127. /// Remove images in a region
  128. void UnmapMemory(VAddr cpu_addr, size_t size);
  129. /// Remove images in a region
  130. void UnmapGPUMemory(GPUVAddr gpu_addr, size_t size);
  131. /// Blit an image with the given parameters
  132. void BlitImage(const Tegra::Engines::Fermi2D::Surface& dst,
  133. const Tegra::Engines::Fermi2D::Surface& src,
  134. const Tegra::Engines::Fermi2D::Config& copy);
  135. /// Invalidate the contents of the color buffer index
  136. /// These contents become unspecified, the cache can assume aggressive optimizations.
  137. void InvalidateColorBuffer(size_t index);
  138. /// Invalidate the contents of the depth buffer
  139. /// These contents become unspecified, the cache can assume aggressive optimizations.
  140. void InvalidateDepthBuffer();
  141. /// Try to find a cached image view in the given CPU address
  142. [[nodiscard]] ImageView* TryFindFramebufferImageView(VAddr cpu_addr);
  143. /// Return true when there are uncommitted images to be downloaded
  144. [[nodiscard]] bool HasUncommittedFlushes() const noexcept;
  145. /// Return true when the caller should wait for async downloads
  146. [[nodiscard]] bool ShouldWaitAsyncFlushes() const noexcept;
  147. /// Commit asynchronous downloads
  148. void CommitAsyncFlushes();
  149. /// Pop asynchronous downloads
  150. void PopAsyncFlushes();
  151. /// Return true when a CPU region is modified from the GPU
  152. [[nodiscard]] bool IsRegionGpuModified(VAddr addr, size_t size);
  153. std::mutex mutex;
  154. private:
  155. /// Iterate over all page indices in a range
  156. template <typename Func>
  157. static void ForEachCPUPage(VAddr addr, size_t size, Func&& func) {
  158. static constexpr bool RETURNS_BOOL = std::is_same_v<std::invoke_result<Func, u64>, bool>;
  159. const u64 page_end = (addr + size - 1) >> PAGE_BITS;
  160. for (u64 page = addr >> PAGE_BITS; page <= page_end; ++page) {
  161. if constexpr (RETURNS_BOOL) {
  162. if (func(page)) {
  163. break;
  164. }
  165. } else {
  166. func(page);
  167. }
  168. }
  169. }
  170. template <typename Func>
  171. static void ForEachGPUPage(GPUVAddr addr, size_t size, Func&& func) {
  172. static constexpr bool RETURNS_BOOL = std::is_same_v<std::invoke_result<Func, u64>, bool>;
  173. const u64 page_end = (addr + size - 1) >> PAGE_BITS;
  174. for (u64 page = addr >> PAGE_BITS; page <= page_end; ++page) {
  175. if constexpr (RETURNS_BOOL) {
  176. if (func(page)) {
  177. break;
  178. }
  179. } else {
  180. func(page);
  181. }
  182. }
  183. }
  184. /// Runs the Garbage Collector.
  185. void RunGarbageCollector();
  186. /// Fills image_view_ids in the image views in indices
  187. void FillImageViews(DescriptorTable<TICEntry>& table,
  188. std::span<ImageViewId> cached_image_view_ids, std::span<const u32> indices,
  189. std::span<ImageViewId> image_view_ids);
  190. /// Find or create an image view in the guest descriptor table
  191. ImageViewId VisitImageView(DescriptorTable<TICEntry>& table,
  192. std::span<ImageViewId> cached_image_view_ids, u32 index);
  193. /// Find or create a framebuffer with the given render target parameters
  194. FramebufferId GetFramebufferId(const RenderTargets& key);
  195. /// Refresh the contents (pixel data) of an image
  196. void RefreshContents(Image& image, ImageId image_id);
  197. /// Upload data from guest to an image
  198. template <typename StagingBuffer>
  199. void UploadImageContents(Image& image, StagingBuffer& staging_buffer);
  200. /// Find or create an image view from a guest descriptor
  201. [[nodiscard]] ImageViewId FindImageView(const TICEntry& config);
  202. /// Create a new image view from a guest descriptor
  203. [[nodiscard]] ImageViewId CreateImageView(const TICEntry& config);
  204. /// Find or create an image from the given parameters
  205. [[nodiscard]] ImageId FindOrInsertImage(const ImageInfo& info, GPUVAddr gpu_addr,
  206. RelaxedOptions options = RelaxedOptions{});
  207. /// Find an image from the given parameters
  208. [[nodiscard]] ImageId FindImage(const ImageInfo& info, GPUVAddr gpu_addr,
  209. RelaxedOptions options);
  210. /// Create an image from the given parameters
  211. [[nodiscard]] ImageId InsertImage(const ImageInfo& info, GPUVAddr gpu_addr,
  212. RelaxedOptions options);
  213. /// Create a new image and join perfectly matching existing images
  214. /// Remove joined images from the cache
  215. [[nodiscard]] ImageId JoinImages(const ImageInfo& info, GPUVAddr gpu_addr, VAddr cpu_addr);
  216. /// Return a blit image pair from the given guest blit parameters
  217. [[nodiscard]] BlitImages GetBlitImages(const Tegra::Engines::Fermi2D::Surface& dst,
  218. const Tegra::Engines::Fermi2D::Surface& src);
  219. /// Find or create a sampler from a guest descriptor sampler
  220. [[nodiscard]] SamplerId FindSampler(const TSCEntry& config);
  221. /// Find or create an image view for the given color buffer index
  222. [[nodiscard]] ImageViewId FindColorBuffer(size_t index, bool is_clear);
  223. /// Find or create an image view for the depth buffer
  224. [[nodiscard]] ImageViewId FindDepthBuffer(bool is_clear);
  225. /// Find or create a view for a render target with the given image parameters
  226. [[nodiscard]] ImageViewId FindRenderTargetView(const ImageInfo& info, GPUVAddr gpu_addr,
  227. bool is_clear);
  228. /// Iterates over all the images in a region calling func
  229. template <typename Func>
  230. void ForEachImageInRegion(VAddr cpu_addr, size_t size, Func&& func);
  231. template <typename Func>
  232. void ForEachImageInRegionGPU(GPUVAddr gpu_addr, size_t size, Func&& func);
  233. template <typename Func>
  234. void ForEachSparseImageInRegion(GPUVAddr gpu_addr, size_t size, Func&& func);
  235. /// Iterates over all the images in a region calling func
  236. template <typename Func>
  237. void ForEachSparseSegment(ImageBase& image, Func&& func);
  238. /// Find or create an image view in the given image with the passed parameters
  239. [[nodiscard]] ImageViewId FindOrEmplaceImageView(ImageId image_id, const ImageViewInfo& info);
  240. /// Register image in the page table
  241. void RegisterImage(ImageId image);
  242. /// Unregister image from the page table
  243. void UnregisterImage(ImageId image);
  244. /// Track CPU reads and writes for image
  245. void TrackImage(ImageBase& image, ImageId image_id);
  246. /// Stop tracking CPU reads and writes for image
  247. void UntrackImage(ImageBase& image, ImageId image_id);
  248. /// Delete image from the cache
  249. void DeleteImage(ImageId image);
  250. /// Remove image views references from the cache
  251. void RemoveImageViewReferences(std::span<const ImageViewId> removed_views);
  252. /// Remove framebuffers using the given image views from the cache
  253. void RemoveFramebuffers(std::span<const ImageViewId> removed_views);
  254. /// Mark an image as modified from the GPU
  255. void MarkModification(ImageBase& image) noexcept;
  256. /// Synchronize image aliases, copying data if needed
  257. void SynchronizeAliases(ImageId image_id);
  258. /// Prepare an image to be used
  259. void PrepareImage(ImageId image_id, bool is_modification, bool invalidate);
  260. /// Prepare an image view to be used
  261. void PrepareImageView(ImageViewId image_view_id, bool is_modification, bool invalidate);
  262. /// Execute copies from one image to the other, even if they are incompatible
  263. void CopyImage(ImageId dst_id, ImageId src_id, std::span<const ImageCopy> copies);
  264. /// Bind an image view as render target, downloading resources preemtively if needed
  265. void BindRenderTarget(ImageViewId* old_id, ImageViewId new_id);
  266. /// Create a render target from a given image and image view parameters
  267. [[nodiscard]] std::pair<FramebufferId, ImageViewId> RenderTargetFromImage(
  268. ImageId, const ImageViewInfo& view_info);
  269. /// Returns true if the current clear parameters clear the whole image of a given image view
  270. [[nodiscard]] bool IsFullClear(ImageViewId id);
  271. Runtime& runtime;
  272. VideoCore::RasterizerInterface& rasterizer;
  273. Tegra::Engines::Maxwell3D& maxwell3d;
  274. Tegra::Engines::KeplerCompute& kepler_compute;
  275. Tegra::MemoryManager& gpu_memory;
  276. DescriptorTable<TICEntry> graphics_image_table{gpu_memory};
  277. DescriptorTable<TSCEntry> graphics_sampler_table{gpu_memory};
  278. std::vector<SamplerId> graphics_sampler_ids;
  279. std::vector<ImageViewId> graphics_image_view_ids;
  280. DescriptorTable<TICEntry> compute_image_table{gpu_memory};
  281. DescriptorTable<TSCEntry> compute_sampler_table{gpu_memory};
  282. std::vector<SamplerId> compute_sampler_ids;
  283. std::vector<ImageViewId> compute_image_view_ids;
  284. RenderTargets render_targets;
  285. std::unordered_map<TICEntry, ImageViewId> image_views;
  286. std::unordered_map<TSCEntry, SamplerId> samplers;
  287. std::unordered_map<RenderTargets, FramebufferId> framebuffers;
  288. std::unordered_map<u64, std::vector<ImageMapId>, IdentityHash<u64>> page_table;
  289. std::unordered_map<u64, std::vector<ImageId>, IdentityHash<u64>> gpu_page_table;
  290. std::unordered_map<u64, std::vector<ImageId>, IdentityHash<u64>> sparse_page_table;
  291. std::unordered_map<ImageId, std::vector<ImageViewId>> sparse_views;
  292. VAddr virtual_invalid_space{};
  293. bool has_deleted_images = false;
  294. u64 total_used_memory = 0;
  295. u64 minimum_memory;
  296. u64 expected_memory;
  297. u64 critical_memory;
  298. SlotVector<Image> slot_images;
  299. SlotVector<ImageMapView> slot_map_views;
  300. SlotVector<ImageView> slot_image_views;
  301. SlotVector<ImageAlloc> slot_image_allocs;
  302. SlotVector<Sampler> slot_samplers;
  303. SlotVector<Framebuffer> slot_framebuffers;
  304. // TODO: This data structure is not optimal and it should be reworked
  305. std::vector<ImageId> uncommitted_downloads;
  306. std::queue<std::vector<ImageId>> committed_downloads;
  307. static constexpr size_t TICKS_TO_DESTROY = 6;
  308. DelayedDestructionRing<Image, TICKS_TO_DESTROY> sentenced_images;
  309. DelayedDestructionRing<ImageView, TICKS_TO_DESTROY> sentenced_image_view;
  310. DelayedDestructionRing<Framebuffer, TICKS_TO_DESTROY> sentenced_framebuffers;
  311. std::unordered_map<GPUVAddr, ImageAllocId> image_allocs_table;
  312. u64 modification_tick = 0;
  313. u64 frame_tick = 0;
  314. typename SlotVector<Image>::Iterator deletion_iterator;
  315. };
  316. template <class P>
  317. TextureCache<P>::TextureCache(Runtime& runtime_, VideoCore::RasterizerInterface& rasterizer_,
  318. Tegra::Engines::Maxwell3D& maxwell3d_,
  319. Tegra::Engines::KeplerCompute& kepler_compute_,
  320. Tegra::MemoryManager& gpu_memory_)
  321. : runtime{runtime_}, rasterizer{rasterizer_}, maxwell3d{maxwell3d_},
  322. kepler_compute{kepler_compute_}, gpu_memory{gpu_memory_} {
  323. // Configure null sampler
  324. TSCEntry sampler_descriptor{};
  325. sampler_descriptor.min_filter.Assign(Tegra::Texture::TextureFilter::Linear);
  326. sampler_descriptor.mag_filter.Assign(Tegra::Texture::TextureFilter::Linear);
  327. sampler_descriptor.mipmap_filter.Assign(Tegra::Texture::TextureMipmapFilter::Linear);
  328. sampler_descriptor.cubemap_anisotropy.Assign(1);
  329. // Make sure the first index is reserved for the null resources
  330. // This way the null resource becomes a compile time constant
  331. void(slot_image_views.insert(runtime, NullImageParams{}));
  332. void(slot_samplers.insert(runtime, sampler_descriptor));
  333. deletion_iterator = slot_images.begin();
  334. if constexpr (HAS_DEVICE_MEMORY_INFO) {
  335. const auto device_memory = runtime.GetDeviceLocalMemory();
  336. const u64 possible_expected_memory = (device_memory * 3) / 10;
  337. const u64 possible_critical_memory = (device_memory * 6) / 10;
  338. expected_memory = std::max(possible_expected_memory, DEFAULT_EXPECTED_MEMORY);
  339. critical_memory = std::max(possible_critical_memory, DEFAULT_CRITICAL_MEMORY);
  340. minimum_memory = 0;
  341. } else {
  342. // on OGL we can be more conservatives as the driver takes care.
  343. expected_memory = DEFAULT_EXPECTED_MEMORY + 512_MiB;
  344. critical_memory = DEFAULT_CRITICAL_MEMORY + 1_GiB;
  345. minimum_memory = expected_memory;
  346. }
  347. }
  348. template <class P>
  349. void TextureCache<P>::RunGarbageCollector() {
  350. const bool high_priority_mode = total_used_memory >= expected_memory;
  351. const bool aggressive_mode = total_used_memory >= critical_memory;
  352. const u64 ticks_to_destroy = high_priority_mode ? 60 : 100;
  353. int num_iterations = aggressive_mode ? 256 : (high_priority_mode ? 128 : 64);
  354. for (; num_iterations > 0; --num_iterations) {
  355. if (deletion_iterator == slot_images.end()) {
  356. deletion_iterator = slot_images.begin();
  357. if (deletion_iterator == slot_images.end()) {
  358. break;
  359. }
  360. }
  361. auto [image_id, image_tmp] = *deletion_iterator;
  362. Image* image = image_tmp; // fix clang error.
  363. const bool is_alias = True(image->flags & ImageFlagBits::Alias);
  364. const bool is_bad_overlap = True(image->flags & ImageFlagBits::BadOverlap);
  365. const bool must_download = image->IsSafeDownload();
  366. bool should_care = is_bad_overlap || is_alias || (high_priority_mode && !must_download);
  367. const u64 ticks_needed =
  368. is_bad_overlap
  369. ? ticks_to_destroy >> 4
  370. : ((should_care && aggressive_mode) ? ticks_to_destroy >> 1 : ticks_to_destroy);
  371. should_care |= aggressive_mode;
  372. if (should_care && image->frame_tick + ticks_needed < frame_tick) {
  373. if (is_bad_overlap) {
  374. const bool overlap_check = std::ranges::all_of(
  375. image->overlapping_images, [&, image](const ImageId& overlap_id) {
  376. auto& overlap = slot_images[overlap_id];
  377. return overlap.frame_tick >= image->frame_tick;
  378. });
  379. if (!overlap_check) {
  380. ++deletion_iterator;
  381. continue;
  382. }
  383. }
  384. if (!is_bad_overlap && must_download) {
  385. const bool alias_check = std::ranges::none_of(
  386. image->aliased_images, [&, image](const AliasedImage& alias) {
  387. auto& alias_image = slot_images[alias.id];
  388. return (alias_image.frame_tick < image->frame_tick) ||
  389. (alias_image.modification_tick < image->modification_tick);
  390. });
  391. if (alias_check) {
  392. auto map = runtime.DownloadStagingBuffer(image->unswizzled_size_bytes);
  393. const auto copies = FullDownloadCopies(image->info);
  394. image->DownloadMemory(map, copies);
  395. runtime.Finish();
  396. SwizzleImage(gpu_memory, image->gpu_addr, image->info, copies, map.mapped_span);
  397. }
  398. }
  399. if (True(image->flags & ImageFlagBits::Tracked)) {
  400. UntrackImage(*image, image_id);
  401. }
  402. UnregisterImage(image_id);
  403. DeleteImage(image_id);
  404. if (is_bad_overlap) {
  405. ++num_iterations;
  406. }
  407. }
  408. ++deletion_iterator;
  409. }
  410. }
  411. template <class P>
  412. void TextureCache<P>::TickFrame() {
  413. if (Settings::values.use_caches_gc.GetValue() && total_used_memory > minimum_memory) {
  414. RunGarbageCollector();
  415. }
  416. sentenced_images.Tick();
  417. sentenced_framebuffers.Tick();
  418. sentenced_image_view.Tick();
  419. ++frame_tick;
  420. }
  421. template <class P>
  422. const typename P::ImageView& TextureCache<P>::GetImageView(ImageViewId id) const noexcept {
  423. return slot_image_views[id];
  424. }
  425. template <class P>
  426. typename P::ImageView& TextureCache<P>::GetImageView(ImageViewId id) noexcept {
  427. return slot_image_views[id];
  428. }
  429. template <class P>
  430. void TextureCache<P>::MarkModification(ImageId id) noexcept {
  431. MarkModification(slot_images[id]);
  432. }
  433. template <class P>
  434. void TextureCache<P>::FillGraphicsImageViews(std::span<const u32> indices,
  435. std::span<ImageViewId> image_view_ids) {
  436. FillImageViews(graphics_image_table, graphics_image_view_ids, indices, image_view_ids);
  437. }
  438. template <class P>
  439. void TextureCache<P>::FillComputeImageViews(std::span<const u32> indices,
  440. std::span<ImageViewId> image_view_ids) {
  441. FillImageViews(compute_image_table, compute_image_view_ids, indices, image_view_ids);
  442. }
  443. template <class P>
  444. typename P::Sampler* TextureCache<P>::GetGraphicsSampler(u32 index) {
  445. if (index > graphics_sampler_table.Limit()) {
  446. LOG_DEBUG(HW_GPU, "Invalid sampler index={}", index);
  447. return &slot_samplers[NULL_SAMPLER_ID];
  448. }
  449. const auto [descriptor, is_new] = graphics_sampler_table.Read(index);
  450. SamplerId& id = graphics_sampler_ids[index];
  451. if (is_new) {
  452. id = FindSampler(descriptor);
  453. }
  454. return &slot_samplers[id];
  455. }
  456. template <class P>
  457. typename P::Sampler* TextureCache<P>::GetComputeSampler(u32 index) {
  458. if (index > compute_sampler_table.Limit()) {
  459. LOG_DEBUG(HW_GPU, "Invalid sampler index={}", index);
  460. return &slot_samplers[NULL_SAMPLER_ID];
  461. }
  462. const auto [descriptor, is_new] = compute_sampler_table.Read(index);
  463. SamplerId& id = compute_sampler_ids[index];
  464. if (is_new) {
  465. id = FindSampler(descriptor);
  466. }
  467. return &slot_samplers[id];
  468. }
  469. template <class P>
  470. void TextureCache<P>::SynchronizeGraphicsDescriptors() {
  471. using SamplerIndex = Tegra::Engines::Maxwell3D::Regs::SamplerIndex;
  472. const bool linked_tsc = maxwell3d.regs.sampler_index == SamplerIndex::ViaHeaderIndex;
  473. const u32 tic_limit = maxwell3d.regs.tic.limit;
  474. const u32 tsc_limit = linked_tsc ? tic_limit : maxwell3d.regs.tsc.limit;
  475. if (graphics_sampler_table.Synchornize(maxwell3d.regs.tsc.Address(), tsc_limit)) {
  476. graphics_sampler_ids.resize(tsc_limit + 1, CORRUPT_ID);
  477. }
  478. if (graphics_image_table.Synchornize(maxwell3d.regs.tic.Address(), tic_limit)) {
  479. graphics_image_view_ids.resize(tic_limit + 1, CORRUPT_ID);
  480. }
  481. }
  482. template <class P>
  483. void TextureCache<P>::SynchronizeComputeDescriptors() {
  484. const bool linked_tsc = kepler_compute.launch_description.linked_tsc;
  485. const u32 tic_limit = kepler_compute.regs.tic.limit;
  486. const u32 tsc_limit = linked_tsc ? tic_limit : kepler_compute.regs.tsc.limit;
  487. const GPUVAddr tsc_gpu_addr = kepler_compute.regs.tsc.Address();
  488. if (compute_sampler_table.Synchornize(tsc_gpu_addr, tsc_limit)) {
  489. compute_sampler_ids.resize(tsc_limit + 1, CORRUPT_ID);
  490. }
  491. if (compute_image_table.Synchornize(kepler_compute.regs.tic.Address(), tic_limit)) {
  492. compute_image_view_ids.resize(tic_limit + 1, CORRUPT_ID);
  493. }
  494. }
  495. template <class P>
  496. void TextureCache<P>::UpdateRenderTargets(bool is_clear) {
  497. using namespace VideoCommon::Dirty;
  498. auto& flags = maxwell3d.dirty.flags;
  499. if (!flags[Dirty::RenderTargets]) {
  500. for (size_t index = 0; index < NUM_RT; ++index) {
  501. ImageViewId& color_buffer_id = render_targets.color_buffer_ids[index];
  502. PrepareImageView(color_buffer_id, true, is_clear && IsFullClear(color_buffer_id));
  503. }
  504. const ImageViewId depth_buffer_id = render_targets.depth_buffer_id;
  505. PrepareImageView(depth_buffer_id, true, is_clear && IsFullClear(depth_buffer_id));
  506. return;
  507. }
  508. flags[Dirty::RenderTargets] = false;
  509. // Render target control is used on all render targets, so force look ups when this one is up
  510. const bool force = flags[Dirty::RenderTargetControl];
  511. flags[Dirty::RenderTargetControl] = false;
  512. for (size_t index = 0; index < NUM_RT; ++index) {
  513. ImageViewId& color_buffer_id = render_targets.color_buffer_ids[index];
  514. if (flags[Dirty::ColorBuffer0 + index] || force) {
  515. flags[Dirty::ColorBuffer0 + index] = false;
  516. BindRenderTarget(&color_buffer_id, FindColorBuffer(index, is_clear));
  517. }
  518. PrepareImageView(color_buffer_id, true, is_clear && IsFullClear(color_buffer_id));
  519. }
  520. if (flags[Dirty::ZetaBuffer] || force) {
  521. flags[Dirty::ZetaBuffer] = false;
  522. BindRenderTarget(&render_targets.depth_buffer_id, FindDepthBuffer(is_clear));
  523. }
  524. const ImageViewId depth_buffer_id = render_targets.depth_buffer_id;
  525. PrepareImageView(depth_buffer_id, true, is_clear && IsFullClear(depth_buffer_id));
  526. for (size_t index = 0; index < NUM_RT; ++index) {
  527. render_targets.draw_buffers[index] = static_cast<u8>(maxwell3d.regs.rt_control.Map(index));
  528. }
  529. render_targets.size = Extent2D{
  530. maxwell3d.regs.render_area.width,
  531. maxwell3d.regs.render_area.height,
  532. };
  533. }
  534. template <class P>
  535. typename P::Framebuffer* TextureCache<P>::GetFramebuffer() {
  536. return &slot_framebuffers[GetFramebufferId(render_targets)];
  537. }
  538. template <class P>
  539. void TextureCache<P>::FillImageViews(DescriptorTable<TICEntry>& table,
  540. std::span<ImageViewId> cached_image_view_ids,
  541. std::span<const u32> indices,
  542. std::span<ImageViewId> image_view_ids) {
  543. ASSERT(indices.size() <= image_view_ids.size());
  544. do {
  545. has_deleted_images = false;
  546. std::ranges::transform(indices, image_view_ids.begin(), [&](u32 index) {
  547. return VisitImageView(table, cached_image_view_ids, index);
  548. });
  549. } while (has_deleted_images);
  550. }
  551. template <class P>
  552. ImageViewId TextureCache<P>::VisitImageView(DescriptorTable<TICEntry>& table,
  553. std::span<ImageViewId> cached_image_view_ids,
  554. u32 index) {
  555. if (index > table.Limit()) {
  556. LOG_DEBUG(HW_GPU, "Invalid image view index={}", index);
  557. return NULL_IMAGE_VIEW_ID;
  558. }
  559. const auto [descriptor, is_new] = table.Read(index);
  560. ImageViewId& image_view_id = cached_image_view_ids[index];
  561. if (is_new) {
  562. image_view_id = FindImageView(descriptor);
  563. }
  564. if (image_view_id != NULL_IMAGE_VIEW_ID) {
  565. PrepareImageView(image_view_id, false, false);
  566. }
  567. return image_view_id;
  568. }
  569. template <class P>
  570. FramebufferId TextureCache<P>::GetFramebufferId(const RenderTargets& key) {
  571. const auto [pair, is_new] = framebuffers.try_emplace(key);
  572. FramebufferId& framebuffer_id = pair->second;
  573. if (!is_new) {
  574. return framebuffer_id;
  575. }
  576. std::array<ImageView*, NUM_RT> color_buffers;
  577. std::ranges::transform(key.color_buffer_ids, color_buffers.begin(),
  578. [this](ImageViewId id) { return id ? &slot_image_views[id] : nullptr; });
  579. ImageView* const depth_buffer =
  580. key.depth_buffer_id ? &slot_image_views[key.depth_buffer_id] : nullptr;
  581. framebuffer_id = slot_framebuffers.insert(runtime, color_buffers, depth_buffer, key);
  582. return framebuffer_id;
  583. }
  584. template <class P>
  585. void TextureCache<P>::WriteMemory(VAddr cpu_addr, size_t size) {
  586. ForEachImageInRegion(cpu_addr, size, [this](ImageId image_id, Image& image) {
  587. if (True(image.flags & ImageFlagBits::CpuModified)) {
  588. return;
  589. }
  590. image.flags |= ImageFlagBits::CpuModified;
  591. if (True(image.flags & ImageFlagBits::Tracked)) {
  592. UntrackImage(image, image_id);
  593. }
  594. });
  595. }
  596. template <class P>
  597. void TextureCache<P>::DownloadMemory(VAddr cpu_addr, size_t size) {
  598. std::vector<ImageId> images;
  599. ForEachImageInRegion(cpu_addr, size, [this, &images](ImageId image_id, ImageBase& image) {
  600. if (!image.IsSafeDownload()) {
  601. return;
  602. }
  603. image.flags &= ~ImageFlagBits::GpuModified;
  604. images.push_back(image_id);
  605. });
  606. if (images.empty()) {
  607. return;
  608. }
  609. std::ranges::sort(images, [this](ImageId lhs, ImageId rhs) {
  610. return slot_images[lhs].modification_tick < slot_images[rhs].modification_tick;
  611. });
  612. for (const ImageId image_id : images) {
  613. Image& image = slot_images[image_id];
  614. auto map = runtime.DownloadStagingBuffer(image.unswizzled_size_bytes);
  615. const auto copies = FullDownloadCopies(image.info);
  616. image.DownloadMemory(map, copies);
  617. runtime.Finish();
  618. SwizzleImage(gpu_memory, image.gpu_addr, image.info, copies, map.mapped_span);
  619. }
  620. }
  621. template <class P>
  622. void TextureCache<P>::UnmapMemory(VAddr cpu_addr, size_t size) {
  623. std::vector<ImageId> deleted_images;
  624. ForEachImageInRegion(cpu_addr, size, [&](ImageId id, Image&) { deleted_images.push_back(id); });
  625. for (const ImageId id : deleted_images) {
  626. Image& image = slot_images[id];
  627. if (True(image.flags & ImageFlagBits::Tracked)) {
  628. UntrackImage(image, id);
  629. }
  630. UnregisterImage(id);
  631. DeleteImage(id);
  632. }
  633. }
  634. template <class P>
  635. void TextureCache<P>::UnmapGPUMemory(GPUVAddr gpu_addr, size_t size) {
  636. std::vector<ImageId> deleted_images;
  637. ForEachImageInRegionGPU(gpu_addr, size,
  638. [&](ImageId id, Image&) { deleted_images.push_back(id); });
  639. for (const ImageId id : deleted_images) {
  640. Image& image = slot_images[id];
  641. if (True(image.flags & ImageFlagBits::Remapped)) {
  642. continue;
  643. }
  644. image.flags |= ImageFlagBits::Remapped;
  645. if (True(image.flags & ImageFlagBits::Tracked)) {
  646. UntrackImage(image, id);
  647. }
  648. }
  649. }
  650. template <class P>
  651. void TextureCache<P>::BlitImage(const Tegra::Engines::Fermi2D::Surface& dst,
  652. const Tegra::Engines::Fermi2D::Surface& src,
  653. const Tegra::Engines::Fermi2D::Config& copy) {
  654. const BlitImages images = GetBlitImages(dst, src);
  655. const ImageId dst_id = images.dst_id;
  656. const ImageId src_id = images.src_id;
  657. PrepareImage(src_id, false, false);
  658. PrepareImage(dst_id, true, false);
  659. ImageBase& dst_image = slot_images[dst_id];
  660. const ImageBase& src_image = slot_images[src_id];
  661. // TODO: Deduplicate
  662. const std::optional src_base = src_image.TryFindBase(src.Address());
  663. const SubresourceRange src_range{.base = src_base.value(), .extent = {1, 1}};
  664. const ImageViewInfo src_view_info(ImageViewType::e2D, images.src_format, src_range);
  665. const auto [src_framebuffer_id, src_view_id] = RenderTargetFromImage(src_id, src_view_info);
  666. const auto [src_samples_x, src_samples_y] = SamplesLog2(src_image.info.num_samples);
  667. const Region2D src_region{
  668. Offset2D{.x = copy.src_x0 >> src_samples_x, .y = copy.src_y0 >> src_samples_y},
  669. Offset2D{.x = copy.src_x1 >> src_samples_x, .y = copy.src_y1 >> src_samples_y},
  670. };
  671. const std::optional dst_base = dst_image.TryFindBase(dst.Address());
  672. const SubresourceRange dst_range{.base = dst_base.value(), .extent = {1, 1}};
  673. const ImageViewInfo dst_view_info(ImageViewType::e2D, images.dst_format, dst_range);
  674. const auto [dst_framebuffer_id, dst_view_id] = RenderTargetFromImage(dst_id, dst_view_info);
  675. const auto [dst_samples_x, dst_samples_y] = SamplesLog2(dst_image.info.num_samples);
  676. const Region2D dst_region{
  677. Offset2D{.x = copy.dst_x0 >> dst_samples_x, .y = copy.dst_y0 >> dst_samples_y},
  678. Offset2D{.x = copy.dst_x1 >> dst_samples_x, .y = copy.dst_y1 >> dst_samples_y},
  679. };
  680. // Always call this after src_framebuffer_id was queried, as the address might be invalidated.
  681. Framebuffer* const dst_framebuffer = &slot_framebuffers[dst_framebuffer_id];
  682. if constexpr (FRAMEBUFFER_BLITS) {
  683. // OpenGL blits from framebuffers, not images
  684. Framebuffer* const src_framebuffer = &slot_framebuffers[src_framebuffer_id];
  685. runtime.BlitFramebuffer(dst_framebuffer, src_framebuffer, dst_region, src_region,
  686. copy.filter, copy.operation);
  687. } else {
  688. // Vulkan can blit images, but it lacks format reinterpretations
  689. // Provide a framebuffer in case it's necessary
  690. ImageView& dst_view = slot_image_views[dst_view_id];
  691. ImageView& src_view = slot_image_views[src_view_id];
  692. runtime.BlitImage(dst_framebuffer, dst_view, src_view, dst_region, src_region, copy.filter,
  693. copy.operation);
  694. }
  695. }
  696. template <class P>
  697. void TextureCache<P>::InvalidateColorBuffer(size_t index) {
  698. ImageViewId& color_buffer_id = render_targets.color_buffer_ids[index];
  699. color_buffer_id = FindColorBuffer(index, false);
  700. if (!color_buffer_id) {
  701. LOG_ERROR(HW_GPU, "Invalidating invalid color buffer in index={}", index);
  702. return;
  703. }
  704. // When invalidating a color buffer, the old contents are no longer relevant
  705. ImageView& color_buffer = slot_image_views[color_buffer_id];
  706. Image& image = slot_images[color_buffer.image_id];
  707. image.flags &= ~ImageFlagBits::CpuModified;
  708. image.flags &= ~ImageFlagBits::GpuModified;
  709. runtime.InvalidateColorBuffer(color_buffer, index);
  710. }
  711. template <class P>
  712. void TextureCache<P>::InvalidateDepthBuffer() {
  713. ImageViewId& depth_buffer_id = render_targets.depth_buffer_id;
  714. depth_buffer_id = FindDepthBuffer(false);
  715. if (!depth_buffer_id) {
  716. LOG_ERROR(HW_GPU, "Invalidating invalid depth buffer");
  717. return;
  718. }
  719. // When invalidating the depth buffer, the old contents are no longer relevant
  720. ImageBase& image = slot_images[slot_image_views[depth_buffer_id].image_id];
  721. image.flags &= ~ImageFlagBits::CpuModified;
  722. image.flags &= ~ImageFlagBits::GpuModified;
  723. ImageView& depth_buffer = slot_image_views[depth_buffer_id];
  724. runtime.InvalidateDepthBuffer(depth_buffer);
  725. }
  726. template <class P>
  727. typename P::ImageView* TextureCache<P>::TryFindFramebufferImageView(VAddr cpu_addr) {
  728. // TODO: Properly implement this
  729. const auto it = page_table.find(cpu_addr >> PAGE_BITS);
  730. if (it == page_table.end()) {
  731. return nullptr;
  732. }
  733. const auto& image_map_ids = it->second;
  734. for (const ImageMapId map_id : image_map_ids) {
  735. const ImageMapView& map = slot_map_views[map_id];
  736. const ImageBase& image = slot_images[map.image_id];
  737. if (image.cpu_addr != cpu_addr) {
  738. continue;
  739. }
  740. if (image.image_view_ids.empty()) {
  741. continue;
  742. }
  743. return &slot_image_views[image.image_view_ids.at(0)];
  744. }
  745. return nullptr;
  746. }
  747. template <class P>
  748. bool TextureCache<P>::HasUncommittedFlushes() const noexcept {
  749. return !uncommitted_downloads.empty();
  750. }
  751. template <class P>
  752. bool TextureCache<P>::ShouldWaitAsyncFlushes() const noexcept {
  753. return !committed_downloads.empty() && !committed_downloads.front().empty();
  754. }
  755. template <class P>
  756. void TextureCache<P>::CommitAsyncFlushes() {
  757. // This is intentionally passing the value by copy
  758. committed_downloads.push(uncommitted_downloads);
  759. uncommitted_downloads.clear();
  760. }
  761. template <class P>
  762. void TextureCache<P>::PopAsyncFlushes() {
  763. if (committed_downloads.empty()) {
  764. return;
  765. }
  766. const std::span<const ImageId> download_ids = committed_downloads.front();
  767. if (download_ids.empty()) {
  768. committed_downloads.pop();
  769. return;
  770. }
  771. size_t total_size_bytes = 0;
  772. for (const ImageId image_id : download_ids) {
  773. total_size_bytes += slot_images[image_id].unswizzled_size_bytes;
  774. }
  775. auto download_map = runtime.DownloadStagingBuffer(total_size_bytes);
  776. const size_t original_offset = download_map.offset;
  777. for (const ImageId image_id : download_ids) {
  778. Image& image = slot_images[image_id];
  779. const auto copies = FullDownloadCopies(image.info);
  780. image.DownloadMemory(download_map, copies);
  781. download_map.offset += image.unswizzled_size_bytes;
  782. }
  783. // Wait for downloads to finish
  784. runtime.Finish();
  785. download_map.offset = original_offset;
  786. std::span<u8> download_span = download_map.mapped_span;
  787. for (const ImageId image_id : download_ids) {
  788. const ImageBase& image = slot_images[image_id];
  789. const auto copies = FullDownloadCopies(image.info);
  790. SwizzleImage(gpu_memory, image.gpu_addr, image.info, copies, download_span);
  791. download_map.offset += image.unswizzled_size_bytes;
  792. download_span = download_span.subspan(image.unswizzled_size_bytes);
  793. }
  794. committed_downloads.pop();
  795. }
  796. template <class P>
  797. bool TextureCache<P>::IsRegionGpuModified(VAddr addr, size_t size) {
  798. bool is_modified = false;
  799. ForEachImageInRegion(addr, size, [&is_modified](ImageId, ImageBase& image) {
  800. if (False(image.flags & ImageFlagBits::GpuModified)) {
  801. return false;
  802. }
  803. is_modified = true;
  804. return true;
  805. });
  806. return is_modified;
  807. }
  808. template <class P>
  809. void TextureCache<P>::RefreshContents(Image& image, ImageId image_id) {
  810. if (False(image.flags & ImageFlagBits::CpuModified)) {
  811. // Only upload modified images
  812. return;
  813. }
  814. image.flags &= ~ImageFlagBits::CpuModified;
  815. TrackImage(image, image_id);
  816. if (image.info.num_samples > 1) {
  817. LOG_WARNING(HW_GPU, "MSAA image uploads are not implemented");
  818. return;
  819. }
  820. auto staging = runtime.UploadStagingBuffer(MapSizeBytes(image));
  821. UploadImageContents(image, staging);
  822. runtime.InsertUploadMemoryBarrier();
  823. }
  824. template <class P>
  825. template <typename StagingBuffer>
  826. void TextureCache<P>::UploadImageContents(Image& image, StagingBuffer& staging) {
  827. const std::span<u8> mapped_span = staging.mapped_span;
  828. const GPUVAddr gpu_addr = image.gpu_addr;
  829. if (True(image.flags & ImageFlagBits::AcceleratedUpload)) {
  830. gpu_memory.ReadBlockUnsafe(gpu_addr, mapped_span.data(), mapped_span.size_bytes());
  831. const auto uploads = FullUploadSwizzles(image.info);
  832. runtime.AccelerateImageUpload(image, staging, uploads);
  833. } else if (True(image.flags & ImageFlagBits::Converted)) {
  834. std::vector<u8> unswizzled_data(image.unswizzled_size_bytes);
  835. auto copies = UnswizzleImage(gpu_memory, gpu_addr, image.info, unswizzled_data);
  836. ConvertImage(unswizzled_data, image.info, mapped_span, copies);
  837. image.UploadMemory(staging, copies);
  838. } else {
  839. const auto copies = UnswizzleImage(gpu_memory, gpu_addr, image.info, mapped_span);
  840. image.UploadMemory(staging, copies);
  841. }
  842. }
  843. template <class P>
  844. ImageViewId TextureCache<P>::FindImageView(const TICEntry& config) {
  845. if (!IsValidEntry(gpu_memory, config)) {
  846. return NULL_IMAGE_VIEW_ID;
  847. }
  848. const auto [pair, is_new] = image_views.try_emplace(config);
  849. ImageViewId& image_view_id = pair->second;
  850. if (is_new) {
  851. image_view_id = CreateImageView(config);
  852. }
  853. return image_view_id;
  854. }
  855. template <class P>
  856. ImageViewId TextureCache<P>::CreateImageView(const TICEntry& config) {
  857. const ImageInfo info(config);
  858. if (info.type == ImageType::Buffer) {
  859. const ImageViewInfo view_info(config, 0);
  860. return slot_image_views.insert(runtime, info, view_info, config.Address());
  861. }
  862. const u32 layer_offset = config.BaseLayer() * info.layer_stride;
  863. const GPUVAddr image_gpu_addr = config.Address() - layer_offset;
  864. const ImageId image_id = FindOrInsertImage(info, image_gpu_addr);
  865. if (!image_id) {
  866. return NULL_IMAGE_VIEW_ID;
  867. }
  868. ImageBase& image = slot_images[image_id];
  869. const SubresourceBase base = image.TryFindBase(config.Address()).value();
  870. ASSERT(base.level == 0);
  871. const ImageViewInfo view_info(config, base.layer);
  872. const ImageViewId image_view_id = FindOrEmplaceImageView(image_id, view_info);
  873. ImageViewBase& image_view = slot_image_views[image_view_id];
  874. image_view.flags |= ImageViewFlagBits::Strong;
  875. image.flags |= ImageFlagBits::Strong;
  876. return image_view_id;
  877. }
  878. template <class P>
  879. ImageId TextureCache<P>::FindOrInsertImage(const ImageInfo& info, GPUVAddr gpu_addr,
  880. RelaxedOptions options) {
  881. if (const ImageId image_id = FindImage(info, gpu_addr, options); image_id) {
  882. return image_id;
  883. }
  884. return InsertImage(info, gpu_addr, options);
  885. }
  886. template <class P>
  887. ImageId TextureCache<P>::FindImage(const ImageInfo& info, GPUVAddr gpu_addr,
  888. RelaxedOptions options) {
  889. std::optional<VAddr> cpu_addr = gpu_memory.GpuToCpuAddress(gpu_addr);
  890. if (!cpu_addr) {
  891. cpu_addr = gpu_memory.GpuToCpuAddress(gpu_addr, CalculateGuestSizeInBytes(info));
  892. if (!cpu_addr) {
  893. return ImageId{};
  894. }
  895. }
  896. const bool broken_views = runtime.HasBrokenTextureViewFormats();
  897. const bool native_bgr = runtime.HasNativeBgr();
  898. ImageId image_id;
  899. const auto lambda = [&](ImageId existing_image_id, ImageBase& existing_image) {
  900. if (True(existing_image.flags & ImageFlagBits::Remapped)) {
  901. return false;
  902. }
  903. if (info.type == ImageType::Linear || existing_image.info.type == ImageType::Linear) {
  904. const bool strict_size = False(options & RelaxedOptions::Size) &&
  905. True(existing_image.flags & ImageFlagBits::Strong);
  906. const ImageInfo& existing = existing_image.info;
  907. if (existing_image.gpu_addr == gpu_addr && existing.type == info.type &&
  908. existing.pitch == info.pitch &&
  909. IsPitchLinearSameSize(existing, info, strict_size) &&
  910. IsViewCompatible(existing.format, info.format, broken_views, native_bgr)) {
  911. image_id = existing_image_id;
  912. return true;
  913. }
  914. } else if (IsSubresource(info, existing_image, gpu_addr, options, broken_views,
  915. native_bgr)) {
  916. image_id = existing_image_id;
  917. return true;
  918. }
  919. return false;
  920. };
  921. ForEachImageInRegion(*cpu_addr, CalculateGuestSizeInBytes(info), lambda);
  922. return image_id;
  923. }
  924. template <class P>
  925. ImageId TextureCache<P>::InsertImage(const ImageInfo& info, GPUVAddr gpu_addr,
  926. RelaxedOptions options) {
  927. std::optional<VAddr> cpu_addr = gpu_memory.GpuToCpuAddress(gpu_addr);
  928. if (!cpu_addr) {
  929. const auto size = CalculateGuestSizeInBytes(info);
  930. cpu_addr = gpu_memory.GpuToCpuAddress(gpu_addr, size);
  931. if (!cpu_addr) {
  932. const VAddr fake_addr = ~(1ULL << 40ULL) + virtual_invalid_space;
  933. virtual_invalid_space += Common::AlignUp(size, 32);
  934. cpu_addr = std::optional<VAddr>(fake_addr);
  935. }
  936. }
  937. ASSERT_MSG(cpu_addr, "Tried to insert an image to an invalid gpu_addr=0x{:x}", gpu_addr);
  938. const ImageId image_id = JoinImages(info, gpu_addr, *cpu_addr);
  939. const Image& image = slot_images[image_id];
  940. // Using "image.gpu_addr" instead of "gpu_addr" is important because it might be different
  941. const auto [it, is_new] = image_allocs_table.try_emplace(image.gpu_addr);
  942. if (is_new) {
  943. it->second = slot_image_allocs.insert();
  944. }
  945. slot_image_allocs[it->second].images.push_back(image_id);
  946. return image_id;
  947. }
  948. template <class P>
  949. ImageId TextureCache<P>::JoinImages(const ImageInfo& info, GPUVAddr gpu_addr, VAddr cpu_addr) {
  950. ImageInfo new_info = info;
  951. const size_t size_bytes = CalculateGuestSizeInBytes(new_info);
  952. const bool broken_views = runtime.HasBrokenTextureViewFormats();
  953. const bool native_bgr = runtime.HasNativeBgr();
  954. std::vector<ImageId> overlap_ids;
  955. std::unordered_set<ImageId> overlaps_found;
  956. std::vector<ImageId> left_aliased_ids;
  957. std::vector<ImageId> right_aliased_ids;
  958. std::unordered_set<ImageId> ignore_textures;
  959. std::vector<ImageId> bad_overlap_ids;
  960. const auto region_check = [&](ImageId overlap_id, ImageBase& overlap) {
  961. if (True(overlap.flags & ImageFlagBits::Remapped)) {
  962. ignore_textures.insert(overlap_id);
  963. return;
  964. }
  965. if (info.type == ImageType::Linear) {
  966. if (info.pitch == overlap.info.pitch && gpu_addr == overlap.gpu_addr) {
  967. // Alias linear images with the same pitch
  968. left_aliased_ids.push_back(overlap_id);
  969. }
  970. return;
  971. }
  972. overlaps_found.insert(overlap_id);
  973. static constexpr bool strict_size = true;
  974. const std::optional<OverlapResult> solution = ResolveOverlap(
  975. new_info, gpu_addr, cpu_addr, overlap, strict_size, broken_views, native_bgr);
  976. if (solution) {
  977. gpu_addr = solution->gpu_addr;
  978. cpu_addr = solution->cpu_addr;
  979. new_info.resources = solution->resources;
  980. overlap_ids.push_back(overlap_id);
  981. return;
  982. }
  983. static constexpr auto options = RelaxedOptions::Size | RelaxedOptions::Format;
  984. const ImageBase new_image_base(new_info, gpu_addr, cpu_addr);
  985. if (IsSubresource(new_info, overlap, gpu_addr, options, broken_views, native_bgr)) {
  986. left_aliased_ids.push_back(overlap_id);
  987. overlap.flags |= ImageFlagBits::Alias;
  988. } else if (IsSubresource(overlap.info, new_image_base, overlap.gpu_addr, options,
  989. broken_views, native_bgr)) {
  990. right_aliased_ids.push_back(overlap_id);
  991. overlap.flags |= ImageFlagBits::Alias;
  992. } else {
  993. bad_overlap_ids.push_back(overlap_id);
  994. overlap.flags |= ImageFlagBits::BadOverlap;
  995. }
  996. };
  997. ForEachImageInRegion(cpu_addr, size_bytes, region_check);
  998. const auto region_check_gpu = [&](ImageId overlap_id, ImageBase& overlap) {
  999. if (!overlaps_found.contains(overlap_id)) {
  1000. if (True(overlap.flags & ImageFlagBits::Remapped)) {
  1001. ignore_textures.insert(overlap_id);
  1002. }
  1003. if (overlap.gpu_addr == gpu_addr && overlap.guest_size_bytes == size_bytes) {
  1004. ignore_textures.insert(overlap_id);
  1005. }
  1006. }
  1007. };
  1008. ForEachSparseImageInRegion(gpu_addr, size_bytes, region_check_gpu);
  1009. const ImageId new_image_id = slot_images.insert(runtime, new_info, gpu_addr, cpu_addr);
  1010. Image& new_image = slot_images[new_image_id];
  1011. if (!gpu_memory.IsContinousRange(new_image.gpu_addr, new_image.guest_size_bytes)) {
  1012. new_image.flags |= ImageFlagBits::Sparse;
  1013. }
  1014. for (const ImageId overlap_id : ignore_textures) {
  1015. Image& overlap = slot_images[overlap_id];
  1016. if (True(overlap.flags & ImageFlagBits::GpuModified)) {
  1017. UNIMPLEMENTED();
  1018. }
  1019. if (True(overlap.flags & ImageFlagBits::Tracked)) {
  1020. UntrackImage(overlap, overlap_id);
  1021. }
  1022. UnregisterImage(overlap_id);
  1023. DeleteImage(overlap_id);
  1024. }
  1025. // TODO: Only upload what we need
  1026. RefreshContents(new_image, new_image_id);
  1027. for (const ImageId overlap_id : overlap_ids) {
  1028. Image& overlap = slot_images[overlap_id];
  1029. if (overlap.info.num_samples != new_image.info.num_samples) {
  1030. LOG_WARNING(HW_GPU, "Copying between images with different samples is not implemented");
  1031. } else {
  1032. const SubresourceBase base = new_image.TryFindBase(overlap.gpu_addr).value();
  1033. const auto copies = MakeShrinkImageCopies(new_info, overlap.info, base);
  1034. runtime.CopyImage(new_image, overlap, copies);
  1035. }
  1036. if (True(overlap.flags & ImageFlagBits::Tracked)) {
  1037. UntrackImage(overlap, overlap_id);
  1038. }
  1039. UnregisterImage(overlap_id);
  1040. DeleteImage(overlap_id);
  1041. }
  1042. ImageBase& new_image_base = new_image;
  1043. for (const ImageId aliased_id : right_aliased_ids) {
  1044. ImageBase& aliased = slot_images[aliased_id];
  1045. AddImageAlias(new_image_base, aliased, new_image_id, aliased_id);
  1046. new_image.flags |= ImageFlagBits::Alias;
  1047. }
  1048. for (const ImageId aliased_id : left_aliased_ids) {
  1049. ImageBase& aliased = slot_images[aliased_id];
  1050. AddImageAlias(aliased, new_image_base, aliased_id, new_image_id);
  1051. new_image.flags |= ImageFlagBits::Alias;
  1052. }
  1053. for (const ImageId aliased_id : bad_overlap_ids) {
  1054. ImageBase& aliased = slot_images[aliased_id];
  1055. aliased.overlapping_images.push_back(new_image_id);
  1056. new_image.overlapping_images.push_back(aliased_id);
  1057. new_image.flags |= ImageFlagBits::BadOverlap;
  1058. }
  1059. RegisterImage(new_image_id);
  1060. return new_image_id;
  1061. }
  1062. template <class P>
  1063. typename TextureCache<P>::BlitImages TextureCache<P>::GetBlitImages(
  1064. const Tegra::Engines::Fermi2D::Surface& dst, const Tegra::Engines::Fermi2D::Surface& src) {
  1065. static constexpr auto FIND_OPTIONS = RelaxedOptions::Format | RelaxedOptions::Samples;
  1066. const GPUVAddr dst_addr = dst.Address();
  1067. const GPUVAddr src_addr = src.Address();
  1068. ImageInfo dst_info(dst);
  1069. ImageInfo src_info(src);
  1070. ImageId dst_id;
  1071. ImageId src_id;
  1072. do {
  1073. has_deleted_images = false;
  1074. dst_id = FindImage(dst_info, dst_addr, FIND_OPTIONS);
  1075. src_id = FindImage(src_info, src_addr, FIND_OPTIONS);
  1076. const ImageBase* const dst_image = dst_id ? &slot_images[dst_id] : nullptr;
  1077. const ImageBase* const src_image = src_id ? &slot_images[src_id] : nullptr;
  1078. DeduceBlitImages(dst_info, src_info, dst_image, src_image);
  1079. if (GetFormatType(dst_info.format) != GetFormatType(src_info.format)) {
  1080. continue;
  1081. }
  1082. if (!dst_id) {
  1083. dst_id = InsertImage(dst_info, dst_addr, RelaxedOptions{});
  1084. }
  1085. if (!src_id) {
  1086. src_id = InsertImage(src_info, src_addr, RelaxedOptions{});
  1087. }
  1088. } while (has_deleted_images);
  1089. return BlitImages{
  1090. .dst_id = dst_id,
  1091. .src_id = src_id,
  1092. .dst_format = dst_info.format,
  1093. .src_format = src_info.format,
  1094. };
  1095. }
  1096. template <class P>
  1097. SamplerId TextureCache<P>::FindSampler(const TSCEntry& config) {
  1098. if (std::ranges::all_of(config.raw, [](u64 value) { return value == 0; })) {
  1099. return NULL_SAMPLER_ID;
  1100. }
  1101. const auto [pair, is_new] = samplers.try_emplace(config);
  1102. if (is_new) {
  1103. pair->second = slot_samplers.insert(runtime, config);
  1104. }
  1105. return pair->second;
  1106. }
  1107. template <class P>
  1108. ImageViewId TextureCache<P>::FindColorBuffer(size_t index, bool is_clear) {
  1109. const auto& regs = maxwell3d.regs;
  1110. if (index >= regs.rt_control.count) {
  1111. return ImageViewId{};
  1112. }
  1113. const auto& rt = regs.rt[index];
  1114. const GPUVAddr gpu_addr = rt.Address();
  1115. if (gpu_addr == 0) {
  1116. return ImageViewId{};
  1117. }
  1118. if (rt.format == Tegra::RenderTargetFormat::NONE) {
  1119. return ImageViewId{};
  1120. }
  1121. const ImageInfo info(regs, index);
  1122. return FindRenderTargetView(info, gpu_addr, is_clear);
  1123. }
  1124. template <class P>
  1125. ImageViewId TextureCache<P>::FindDepthBuffer(bool is_clear) {
  1126. const auto& regs = maxwell3d.regs;
  1127. if (!regs.zeta_enable) {
  1128. return ImageViewId{};
  1129. }
  1130. const GPUVAddr gpu_addr = regs.zeta.Address();
  1131. if (gpu_addr == 0) {
  1132. return ImageViewId{};
  1133. }
  1134. const ImageInfo info(regs);
  1135. return FindRenderTargetView(info, gpu_addr, is_clear);
  1136. }
  1137. template <class P>
  1138. ImageViewId TextureCache<P>::FindRenderTargetView(const ImageInfo& info, GPUVAddr gpu_addr,
  1139. bool is_clear) {
  1140. const auto options = is_clear ? RelaxedOptions::Samples : RelaxedOptions{};
  1141. const ImageId image_id = FindOrInsertImage(info, gpu_addr, options);
  1142. if (!image_id) {
  1143. return NULL_IMAGE_VIEW_ID;
  1144. }
  1145. Image& image = slot_images[image_id];
  1146. const ImageViewType view_type = RenderTargetImageViewType(info);
  1147. SubresourceBase base;
  1148. if (image.info.type == ImageType::Linear) {
  1149. base = SubresourceBase{.level = 0, .layer = 0};
  1150. } else {
  1151. base = image.TryFindBase(gpu_addr).value();
  1152. }
  1153. const s32 layers = image.info.type == ImageType::e3D ? info.size.depth : info.resources.layers;
  1154. const SubresourceRange range{
  1155. .base = base,
  1156. .extent = {.levels = 1, .layers = layers},
  1157. };
  1158. return FindOrEmplaceImageView(image_id, ImageViewInfo(view_type, info.format, range));
  1159. }
  1160. template <class P>
  1161. template <typename Func>
  1162. void TextureCache<P>::ForEachImageInRegion(VAddr cpu_addr, size_t size, Func&& func) {
  1163. using FuncReturn = typename std::invoke_result<Func, ImageId, Image&>::type;
  1164. static constexpr bool BOOL_BREAK = std::is_same_v<FuncReturn, bool>;
  1165. boost::container::small_vector<ImageId, 32> images;
  1166. boost::container::small_vector<ImageMapId, 32> maps;
  1167. ForEachCPUPage(cpu_addr, size, [this, &images, &maps, cpu_addr, size, func](u64 page) {
  1168. const auto it = page_table.find(page);
  1169. if (it == page_table.end()) {
  1170. if constexpr (BOOL_BREAK) {
  1171. return false;
  1172. } else {
  1173. return;
  1174. }
  1175. }
  1176. for (const ImageMapId map_id : it->second) {
  1177. ImageMapView& map = slot_map_views[map_id];
  1178. if (map.picked) {
  1179. continue;
  1180. }
  1181. if (!map.Overlaps(cpu_addr, size)) {
  1182. continue;
  1183. }
  1184. map.picked = true;
  1185. maps.push_back(map_id);
  1186. Image& image = slot_images[map.image_id];
  1187. if (True(image.flags & ImageFlagBits::Picked)) {
  1188. continue;
  1189. }
  1190. image.flags |= ImageFlagBits::Picked;
  1191. images.push_back(map.image_id);
  1192. if constexpr (BOOL_BREAK) {
  1193. if (func(map.image_id, image)) {
  1194. return true;
  1195. }
  1196. } else {
  1197. func(map.image_id, image);
  1198. }
  1199. }
  1200. if constexpr (BOOL_BREAK) {
  1201. return false;
  1202. }
  1203. });
  1204. for (const ImageId image_id : images) {
  1205. slot_images[image_id].flags &= ~ImageFlagBits::Picked;
  1206. }
  1207. for (const ImageMapId map_id : maps) {
  1208. slot_map_views[map_id].picked = false;
  1209. }
  1210. }
  1211. template <class P>
  1212. template <typename Func>
  1213. void TextureCache<P>::ForEachImageInRegionGPU(GPUVAddr gpu_addr, size_t size, Func&& func) {
  1214. using FuncReturn = typename std::invoke_result<Func, ImageId, Image&>::type;
  1215. static constexpr bool BOOL_BREAK = std::is_same_v<FuncReturn, bool>;
  1216. boost::container::small_vector<ImageId, 8> images;
  1217. ForEachGPUPage(gpu_addr, size, [this, &images, gpu_addr, size, func](u64 page) {
  1218. const auto it = gpu_page_table.find(page);
  1219. if (it == gpu_page_table.end()) {
  1220. if constexpr (BOOL_BREAK) {
  1221. return false;
  1222. } else {
  1223. return;
  1224. }
  1225. }
  1226. for (const ImageId image_id : it->second) {
  1227. Image& image = slot_images[image_id];
  1228. if (True(image.flags & ImageFlagBits::Picked)) {
  1229. continue;
  1230. }
  1231. if (!image.OverlapsGPU(gpu_addr, size)) {
  1232. continue;
  1233. }
  1234. image.flags |= ImageFlagBits::Picked;
  1235. images.push_back(image_id);
  1236. if constexpr (BOOL_BREAK) {
  1237. if (func(image_id, image)) {
  1238. return true;
  1239. }
  1240. } else {
  1241. func(image_id, image);
  1242. }
  1243. }
  1244. if constexpr (BOOL_BREAK) {
  1245. return false;
  1246. }
  1247. });
  1248. for (const ImageId image_id : images) {
  1249. slot_images[image_id].flags &= ~ImageFlagBits::Picked;
  1250. }
  1251. }
  1252. template <class P>
  1253. template <typename Func>
  1254. void TextureCache<P>::ForEachSparseImageInRegion(GPUVAddr gpu_addr, size_t size, Func&& func) {
  1255. using FuncReturn = typename std::invoke_result<Func, ImageId, Image&>::type;
  1256. static constexpr bool BOOL_BREAK = std::is_same_v<FuncReturn, bool>;
  1257. boost::container::small_vector<ImageId, 8> images;
  1258. ForEachGPUPage(gpu_addr, size, [this, &images, gpu_addr, size, func](u64 page) {
  1259. const auto it = sparse_page_table.find(page);
  1260. if (it == sparse_page_table.end()) {
  1261. if constexpr (BOOL_BREAK) {
  1262. return false;
  1263. } else {
  1264. return;
  1265. }
  1266. }
  1267. for (const ImageId image_id : it->second) {
  1268. Image& image = slot_images[image_id];
  1269. if (True(image.flags & ImageFlagBits::Picked)) {
  1270. continue;
  1271. }
  1272. if (!image.OverlapsGPU(gpu_addr, size)) {
  1273. continue;
  1274. }
  1275. image.flags |= ImageFlagBits::Picked;
  1276. images.push_back(image_id);
  1277. if constexpr (BOOL_BREAK) {
  1278. if (func(image_id, image)) {
  1279. return true;
  1280. }
  1281. } else {
  1282. func(image_id, image);
  1283. }
  1284. }
  1285. if constexpr (BOOL_BREAK) {
  1286. return false;
  1287. }
  1288. });
  1289. for (const ImageId image_id : images) {
  1290. slot_images[image_id].flags &= ~ImageFlagBits::Picked;
  1291. }
  1292. }
  1293. template <class P>
  1294. template <typename Func>
  1295. void TextureCache<P>::ForEachSparseSegment(ImageBase& image, Func&& func) {
  1296. using FuncReturn = typename std::invoke_result<Func, GPUVAddr, VAddr, size_t>::type;
  1297. static constexpr bool RETURNS_BOOL = std::is_same_v<FuncReturn, bool>;
  1298. const auto segments = gpu_memory.GetSubmappedRange(image.gpu_addr, image.guest_size_bytes);
  1299. for (auto& segment : segments) {
  1300. const auto gpu_addr = segment.first;
  1301. const auto size = segment.second;
  1302. std::optional<VAddr> cpu_addr = gpu_memory.GpuToCpuAddress(gpu_addr);
  1303. ASSERT(cpu_addr);
  1304. if constexpr (RETURNS_BOOL) {
  1305. if (func(gpu_addr, *cpu_addr, size)) {
  1306. break;
  1307. }
  1308. } else {
  1309. func(gpu_addr, *cpu_addr, size);
  1310. }
  1311. }
  1312. }
  1313. template <class P>
  1314. ImageViewId TextureCache<P>::FindOrEmplaceImageView(ImageId image_id, const ImageViewInfo& info) {
  1315. Image& image = slot_images[image_id];
  1316. if (const ImageViewId image_view_id = image.FindView(info); image_view_id) {
  1317. return image_view_id;
  1318. }
  1319. const ImageViewId image_view_id = slot_image_views.insert(runtime, info, image_id, image);
  1320. image.InsertView(info, image_view_id);
  1321. return image_view_id;
  1322. }
  1323. template <class P>
  1324. void TextureCache<P>::RegisterImage(ImageId image_id) {
  1325. ImageBase& image = slot_images[image_id];
  1326. ASSERT_MSG(False(image.flags & ImageFlagBits::Registered),
  1327. "Trying to register an already registered image");
  1328. image.flags |= ImageFlagBits::Registered;
  1329. u64 tentative_size = std::max(image.guest_size_bytes, image.unswizzled_size_bytes);
  1330. if ((IsPixelFormatASTC(image.info.format) &&
  1331. True(image.flags & ImageFlagBits::AcceleratedUpload)) ||
  1332. True(image.flags & ImageFlagBits::Converted)) {
  1333. tentative_size = EstimatedDecompressedSize(tentative_size, image.info.format);
  1334. }
  1335. total_used_memory += Common::AlignUp(tentative_size, 1024);
  1336. ForEachGPUPage(image.gpu_addr, image.guest_size_bytes,
  1337. [this, image_id](u64 page) { gpu_page_table[page].push_back(image_id); });
  1338. if (False(image.flags & ImageFlagBits::Sparse)) {
  1339. auto map_id =
  1340. slot_map_views.insert(image.gpu_addr, image.cpu_addr, image.guest_size_bytes, image_id);
  1341. ForEachCPUPage(image.cpu_addr, image.guest_size_bytes,
  1342. [this, map_id](u64 page) { page_table[page].push_back(map_id); });
  1343. image.map_view_id = map_id;
  1344. return;
  1345. }
  1346. std::vector<ImageViewId> sparse_maps{};
  1347. ForEachSparseSegment(
  1348. image, [this, image_id, &sparse_maps](GPUVAddr gpu_addr, VAddr cpu_addr, size_t size) {
  1349. auto map_id = slot_map_views.insert(gpu_addr, cpu_addr, size, image_id);
  1350. ForEachCPUPage(cpu_addr, size,
  1351. [this, map_id](u64 page) { page_table[page].push_back(map_id); });
  1352. sparse_maps.push_back(map_id);
  1353. });
  1354. sparse_views.emplace(image_id, std::move(sparse_maps));
  1355. ForEachGPUPage(image.gpu_addr, image.guest_size_bytes,
  1356. [this, image_id](u64 page) { sparse_page_table[page].push_back(image_id); });
  1357. }
  1358. template <class P>
  1359. void TextureCache<P>::UnregisterImage(ImageId image_id) {
  1360. Image& image = slot_images[image_id];
  1361. ASSERT_MSG(True(image.flags & ImageFlagBits::Registered),
  1362. "Trying to unregister an already registered image");
  1363. image.flags &= ~ImageFlagBits::Registered;
  1364. image.flags &= ~ImageFlagBits::BadOverlap;
  1365. u64 tentative_size = std::max(image.guest_size_bytes, image.unswizzled_size_bytes);
  1366. if ((IsPixelFormatASTC(image.info.format) &&
  1367. True(image.flags & ImageFlagBits::AcceleratedUpload)) ||
  1368. True(image.flags & ImageFlagBits::Converted)) {
  1369. tentative_size = EstimatedDecompressedSize(tentative_size, image.info.format);
  1370. }
  1371. total_used_memory -= Common::AlignUp(tentative_size, 1024);
  1372. const auto& clear_page_table =
  1373. [this, image_id](
  1374. u64 page,
  1375. std::unordered_map<u64, std::vector<ImageId>, IdentityHash<u64>>& selected_page_table) {
  1376. const auto page_it = selected_page_table.find(page);
  1377. if (page_it == selected_page_table.end()) {
  1378. UNREACHABLE_MSG("Unregistering unregistered page=0x{:x}", page << PAGE_BITS);
  1379. return;
  1380. }
  1381. std::vector<ImageId>& image_ids = page_it->second;
  1382. const auto vector_it = std::ranges::find(image_ids, image_id);
  1383. if (vector_it == image_ids.end()) {
  1384. UNREACHABLE_MSG("Unregistering unregistered image in page=0x{:x}",
  1385. page << PAGE_BITS);
  1386. return;
  1387. }
  1388. image_ids.erase(vector_it);
  1389. };
  1390. ForEachGPUPage(image.gpu_addr, image.guest_size_bytes,
  1391. [this, &clear_page_table](u64 page) { clear_page_table(page, gpu_page_table); });
  1392. if (False(image.flags & ImageFlagBits::Sparse)) {
  1393. const auto map_id = image.map_view_id;
  1394. ForEachCPUPage(image.cpu_addr, image.guest_size_bytes, [this, map_id](u64 page) {
  1395. const auto page_it = page_table.find(page);
  1396. if (page_it == page_table.end()) {
  1397. UNREACHABLE_MSG("Unregistering unregistered page=0x{:x}", page << PAGE_BITS);
  1398. return;
  1399. }
  1400. std::vector<ImageMapId>& image_map_ids = page_it->second;
  1401. const auto vector_it = std::ranges::find(image_map_ids, map_id);
  1402. if (vector_it == image_map_ids.end()) {
  1403. UNREACHABLE_MSG("Unregistering unregistered image in page=0x{:x}",
  1404. page << PAGE_BITS);
  1405. return;
  1406. }
  1407. image_map_ids.erase(vector_it);
  1408. });
  1409. slot_map_views.erase(map_id);
  1410. return;
  1411. }
  1412. ForEachGPUPage(image.gpu_addr, image.guest_size_bytes, [this, &clear_page_table](u64 page) {
  1413. clear_page_table(page, sparse_page_table);
  1414. });
  1415. auto it = sparse_views.find(image_id);
  1416. ASSERT(it != sparse_views.end());
  1417. auto& sparse_maps = it->second;
  1418. for (auto& map_view_id : sparse_maps) {
  1419. const auto& map_range = slot_map_views[map_view_id];
  1420. const VAddr cpu_addr = map_range.cpu_addr;
  1421. const std::size_t size = map_range.size;
  1422. ForEachCPUPage(cpu_addr, size, [this, image_id](u64 page) {
  1423. const auto page_it = page_table.find(page);
  1424. if (page_it == page_table.end()) {
  1425. UNREACHABLE_MSG("Unregistering unregistered page=0x{:x}", page << PAGE_BITS);
  1426. return;
  1427. }
  1428. std::vector<ImageMapId>& image_map_ids = page_it->second;
  1429. auto vector_it = image_map_ids.begin();
  1430. while (vector_it != image_map_ids.end()) {
  1431. ImageMapView& map = slot_map_views[*vector_it];
  1432. if (map.image_id != image_id) {
  1433. vector_it++;
  1434. continue;
  1435. }
  1436. if (!map.picked) {
  1437. map.picked = true;
  1438. }
  1439. vector_it = image_map_ids.erase(vector_it);
  1440. }
  1441. });
  1442. slot_map_views.erase(map_view_id);
  1443. }
  1444. sparse_views.erase(it);
  1445. }
  1446. template <class P>
  1447. void TextureCache<P>::TrackImage(ImageBase& image, ImageId image_id) {
  1448. ASSERT(False(image.flags & ImageFlagBits::Tracked));
  1449. image.flags |= ImageFlagBits::Tracked;
  1450. if (False(image.flags & ImageFlagBits::Sparse)) {
  1451. rasterizer.UpdatePagesCachedCount(image.cpu_addr, image.guest_size_bytes, 1);
  1452. return;
  1453. }
  1454. if (True(image.flags & ImageFlagBits::Registered)) {
  1455. auto it = sparse_views.find(image_id);
  1456. ASSERT(it != sparse_views.end());
  1457. auto& sparse_maps = it->second;
  1458. for (auto& map_view_id : sparse_maps) {
  1459. const auto& map = slot_map_views[map_view_id];
  1460. const VAddr cpu_addr = map.cpu_addr;
  1461. const std::size_t size = map.size;
  1462. rasterizer.UpdatePagesCachedCount(cpu_addr, size, 1);
  1463. }
  1464. return;
  1465. }
  1466. ForEachSparseSegment(image,
  1467. [this]([[maybe_unused]] GPUVAddr gpu_addr, VAddr cpu_addr, size_t size) {
  1468. rasterizer.UpdatePagesCachedCount(cpu_addr, size, 1);
  1469. });
  1470. }
  1471. template <class P>
  1472. void TextureCache<P>::UntrackImage(ImageBase& image, ImageId image_id) {
  1473. ASSERT(True(image.flags & ImageFlagBits::Tracked));
  1474. image.flags &= ~ImageFlagBits::Tracked;
  1475. if (False(image.flags & ImageFlagBits::Sparse)) {
  1476. rasterizer.UpdatePagesCachedCount(image.cpu_addr, image.guest_size_bytes, -1);
  1477. return;
  1478. }
  1479. ASSERT(True(image.flags & ImageFlagBits::Registered));
  1480. auto it = sparse_views.find(image_id);
  1481. ASSERT(it != sparse_views.end());
  1482. auto& sparse_maps = it->second;
  1483. for (auto& map_view_id : sparse_maps) {
  1484. const auto& map = slot_map_views[map_view_id];
  1485. const VAddr cpu_addr = map.cpu_addr;
  1486. const std::size_t size = map.size;
  1487. rasterizer.UpdatePagesCachedCount(cpu_addr, size, -1);
  1488. }
  1489. }
  1490. template <class P>
  1491. void TextureCache<P>::DeleteImage(ImageId image_id) {
  1492. ImageBase& image = slot_images[image_id];
  1493. const GPUVAddr gpu_addr = image.gpu_addr;
  1494. const auto alloc_it = image_allocs_table.find(gpu_addr);
  1495. if (alloc_it == image_allocs_table.end()) {
  1496. UNREACHABLE_MSG("Trying to delete an image alloc that does not exist in address 0x{:x}",
  1497. gpu_addr);
  1498. return;
  1499. }
  1500. const ImageAllocId alloc_id = alloc_it->second;
  1501. std::vector<ImageId>& alloc_images = slot_image_allocs[alloc_id].images;
  1502. const auto alloc_image_it = std::ranges::find(alloc_images, image_id);
  1503. if (alloc_image_it == alloc_images.end()) {
  1504. UNREACHABLE_MSG("Trying to delete an image that does not exist");
  1505. return;
  1506. }
  1507. ASSERT_MSG(False(image.flags & ImageFlagBits::Tracked), "Image was not untracked");
  1508. ASSERT_MSG(False(image.flags & ImageFlagBits::Registered), "Image was not unregistered");
  1509. // Mark render targets as dirty
  1510. auto& dirty = maxwell3d.dirty.flags;
  1511. dirty[Dirty::RenderTargets] = true;
  1512. dirty[Dirty::ZetaBuffer] = true;
  1513. for (size_t rt = 0; rt < NUM_RT; ++rt) {
  1514. dirty[Dirty::ColorBuffer0 + rt] = true;
  1515. }
  1516. const std::span<const ImageViewId> image_view_ids = image.image_view_ids;
  1517. for (const ImageViewId image_view_id : image_view_ids) {
  1518. std::ranges::replace(render_targets.color_buffer_ids, image_view_id, ImageViewId{});
  1519. if (render_targets.depth_buffer_id == image_view_id) {
  1520. render_targets.depth_buffer_id = ImageViewId{};
  1521. }
  1522. }
  1523. RemoveImageViewReferences(image_view_ids);
  1524. RemoveFramebuffers(image_view_ids);
  1525. for (const AliasedImage& alias : image.aliased_images) {
  1526. ImageBase& other_image = slot_images[alias.id];
  1527. [[maybe_unused]] const size_t num_removed_aliases =
  1528. std::erase_if(other_image.aliased_images, [image_id](const AliasedImage& other_alias) {
  1529. return other_alias.id == image_id;
  1530. });
  1531. other_image.CheckAliasState();
  1532. ASSERT_MSG(num_removed_aliases == 1, "Invalid number of removed aliases: {}",
  1533. num_removed_aliases);
  1534. }
  1535. for (const ImageId overlap_id : image.overlapping_images) {
  1536. ImageBase& other_image = slot_images[overlap_id];
  1537. [[maybe_unused]] const size_t num_removed_overlaps = std::erase_if(
  1538. other_image.overlapping_images,
  1539. [image_id](const ImageId other_overlap_id) { return other_overlap_id == image_id; });
  1540. other_image.CheckBadOverlapState();
  1541. ASSERT_MSG(num_removed_overlaps == 1, "Invalid number of removed overlapps: {}",
  1542. num_removed_overlaps);
  1543. }
  1544. for (const ImageViewId image_view_id : image_view_ids) {
  1545. sentenced_image_view.Push(std::move(slot_image_views[image_view_id]));
  1546. slot_image_views.erase(image_view_id);
  1547. }
  1548. sentenced_images.Push(std::move(slot_images[image_id]));
  1549. slot_images.erase(image_id);
  1550. alloc_images.erase(alloc_image_it);
  1551. if (alloc_images.empty()) {
  1552. image_allocs_table.erase(alloc_it);
  1553. }
  1554. if constexpr (ENABLE_VALIDATION) {
  1555. std::ranges::fill(graphics_image_view_ids, CORRUPT_ID);
  1556. std::ranges::fill(compute_image_view_ids, CORRUPT_ID);
  1557. }
  1558. graphics_image_table.Invalidate();
  1559. compute_image_table.Invalidate();
  1560. has_deleted_images = true;
  1561. }
  1562. template <class P>
  1563. void TextureCache<P>::RemoveImageViewReferences(std::span<const ImageViewId> removed_views) {
  1564. auto it = image_views.begin();
  1565. while (it != image_views.end()) {
  1566. const auto found = std::ranges::find(removed_views, it->second);
  1567. if (found != removed_views.end()) {
  1568. it = image_views.erase(it);
  1569. } else {
  1570. ++it;
  1571. }
  1572. }
  1573. }
  1574. template <class P>
  1575. void TextureCache<P>::RemoveFramebuffers(std::span<const ImageViewId> removed_views) {
  1576. auto it = framebuffers.begin();
  1577. while (it != framebuffers.end()) {
  1578. if (it->first.Contains(removed_views)) {
  1579. it = framebuffers.erase(it);
  1580. } else {
  1581. ++it;
  1582. }
  1583. }
  1584. }
  1585. template <class P>
  1586. void TextureCache<P>::MarkModification(ImageBase& image) noexcept {
  1587. image.flags |= ImageFlagBits::GpuModified;
  1588. image.modification_tick = ++modification_tick;
  1589. }
  1590. template <class P>
  1591. void TextureCache<P>::SynchronizeAliases(ImageId image_id) {
  1592. boost::container::small_vector<const AliasedImage*, 1> aliased_images;
  1593. ImageBase& image = slot_images[image_id];
  1594. u64 most_recent_tick = image.modification_tick;
  1595. for (const AliasedImage& aliased : image.aliased_images) {
  1596. ImageBase& aliased_image = slot_images[aliased.id];
  1597. if (image.modification_tick < aliased_image.modification_tick) {
  1598. most_recent_tick = std::max(most_recent_tick, aliased_image.modification_tick);
  1599. aliased_images.push_back(&aliased);
  1600. }
  1601. }
  1602. if (aliased_images.empty()) {
  1603. return;
  1604. }
  1605. image.modification_tick = most_recent_tick;
  1606. std::ranges::sort(aliased_images, [this](const AliasedImage* lhs, const AliasedImage* rhs) {
  1607. const ImageBase& lhs_image = slot_images[lhs->id];
  1608. const ImageBase& rhs_image = slot_images[rhs->id];
  1609. return lhs_image.modification_tick < rhs_image.modification_tick;
  1610. });
  1611. for (const AliasedImage* const aliased : aliased_images) {
  1612. CopyImage(image_id, aliased->id, aliased->copies);
  1613. }
  1614. }
  1615. template <class P>
  1616. void TextureCache<P>::PrepareImage(ImageId image_id, bool is_modification, bool invalidate) {
  1617. Image& image = slot_images[image_id];
  1618. if (invalidate) {
  1619. image.flags &= ~(ImageFlagBits::CpuModified | ImageFlagBits::GpuModified);
  1620. if (False(image.flags & ImageFlagBits::Tracked)) {
  1621. TrackImage(image, image_id);
  1622. }
  1623. } else {
  1624. RefreshContents(image, image_id);
  1625. SynchronizeAliases(image_id);
  1626. }
  1627. if (is_modification) {
  1628. MarkModification(image);
  1629. }
  1630. image.frame_tick = frame_tick;
  1631. }
  1632. template <class P>
  1633. void TextureCache<P>::PrepareImageView(ImageViewId image_view_id, bool is_modification,
  1634. bool invalidate) {
  1635. if (!image_view_id) {
  1636. return;
  1637. }
  1638. const ImageViewBase& image_view = slot_image_views[image_view_id];
  1639. if (image_view.IsBuffer()) {
  1640. return;
  1641. }
  1642. PrepareImage(image_view.image_id, is_modification, invalidate);
  1643. }
  1644. template <class P>
  1645. void TextureCache<P>::CopyImage(ImageId dst_id, ImageId src_id, std::span<const ImageCopy> copies) {
  1646. Image& dst = slot_images[dst_id];
  1647. Image& src = slot_images[src_id];
  1648. const auto dst_format_type = GetFormatType(dst.info.format);
  1649. const auto src_format_type = GetFormatType(src.info.format);
  1650. if (src_format_type == dst_format_type) {
  1651. if constexpr (HAS_EMULATED_COPIES) {
  1652. if (!runtime.CanImageBeCopied(dst, src)) {
  1653. return runtime.EmulateCopyImage(dst, src, copies);
  1654. }
  1655. }
  1656. return runtime.CopyImage(dst, src, copies);
  1657. }
  1658. UNIMPLEMENTED_IF(dst.info.type != ImageType::e2D);
  1659. UNIMPLEMENTED_IF(src.info.type != ImageType::e2D);
  1660. for (const ImageCopy& copy : copies) {
  1661. UNIMPLEMENTED_IF(copy.dst_subresource.num_layers != 1);
  1662. UNIMPLEMENTED_IF(copy.src_subresource.num_layers != 1);
  1663. UNIMPLEMENTED_IF(copy.src_offset != Offset3D{});
  1664. UNIMPLEMENTED_IF(copy.dst_offset != Offset3D{});
  1665. const SubresourceBase dst_base{
  1666. .level = copy.dst_subresource.base_level,
  1667. .layer = copy.dst_subresource.base_layer,
  1668. };
  1669. const SubresourceBase src_base{
  1670. .level = copy.src_subresource.base_level,
  1671. .layer = copy.src_subresource.base_layer,
  1672. };
  1673. const SubresourceExtent dst_extent{.levels = 1, .layers = 1};
  1674. const SubresourceExtent src_extent{.levels = 1, .layers = 1};
  1675. const SubresourceRange dst_range{.base = dst_base, .extent = dst_extent};
  1676. const SubresourceRange src_range{.base = src_base, .extent = src_extent};
  1677. const ImageViewInfo dst_view_info(ImageViewType::e2D, dst.info.format, dst_range);
  1678. const ImageViewInfo src_view_info(ImageViewType::e2D, src.info.format, src_range);
  1679. const auto [dst_framebuffer_id, dst_view_id] = RenderTargetFromImage(dst_id, dst_view_info);
  1680. Framebuffer* const dst_framebuffer = &slot_framebuffers[dst_framebuffer_id];
  1681. const ImageViewId src_view_id = FindOrEmplaceImageView(src_id, src_view_info);
  1682. ImageView& dst_view = slot_image_views[dst_view_id];
  1683. ImageView& src_view = slot_image_views[src_view_id];
  1684. [[maybe_unused]] const Extent3D expected_size{
  1685. .width = std::min(dst_view.size.width, src_view.size.width),
  1686. .height = std::min(dst_view.size.height, src_view.size.height),
  1687. .depth = std::min(dst_view.size.depth, src_view.size.depth),
  1688. };
  1689. UNIMPLEMENTED_IF(copy.extent != expected_size);
  1690. runtime.ConvertImage(dst_framebuffer, dst_view, src_view);
  1691. }
  1692. }
  1693. template <class P>
  1694. void TextureCache<P>::BindRenderTarget(ImageViewId* old_id, ImageViewId new_id) {
  1695. if (*old_id == new_id) {
  1696. return;
  1697. }
  1698. if (*old_id) {
  1699. const ImageViewBase& old_view = slot_image_views[*old_id];
  1700. if (True(old_view.flags & ImageViewFlagBits::PreemtiveDownload)) {
  1701. uncommitted_downloads.push_back(old_view.image_id);
  1702. }
  1703. }
  1704. *old_id = new_id;
  1705. }
  1706. template <class P>
  1707. std::pair<FramebufferId, ImageViewId> TextureCache<P>::RenderTargetFromImage(
  1708. ImageId image_id, const ImageViewInfo& view_info) {
  1709. const ImageViewId view_id = FindOrEmplaceImageView(image_id, view_info);
  1710. const ImageBase& image = slot_images[image_id];
  1711. const bool is_color = GetFormatType(image.info.format) == SurfaceType::ColorTexture;
  1712. const ImageViewId color_view_id = is_color ? view_id : ImageViewId{};
  1713. const ImageViewId depth_view_id = is_color ? ImageViewId{} : view_id;
  1714. const Extent3D extent = MipSize(image.info.size, view_info.range.base.level);
  1715. const u32 num_samples = image.info.num_samples;
  1716. const auto [samples_x, samples_y] = SamplesLog2(num_samples);
  1717. const FramebufferId framebuffer_id = GetFramebufferId(RenderTargets{
  1718. .color_buffer_ids = {color_view_id},
  1719. .depth_buffer_id = depth_view_id,
  1720. .size = {extent.width >> samples_x, extent.height >> samples_y},
  1721. });
  1722. return {framebuffer_id, view_id};
  1723. }
  1724. template <class P>
  1725. bool TextureCache<P>::IsFullClear(ImageViewId id) {
  1726. if (!id) {
  1727. return true;
  1728. }
  1729. const ImageViewBase& image_view = slot_image_views[id];
  1730. const ImageBase& image = slot_images[image_view.image_id];
  1731. const Extent3D size = image_view.size;
  1732. const auto& regs = maxwell3d.regs;
  1733. const auto& scissor = regs.scissor_test[0];
  1734. if (image.info.resources.levels > 1 || image.info.resources.layers > 1) {
  1735. // Images with multiple resources can't be cleared in a single call
  1736. return false;
  1737. }
  1738. if (regs.clear_flags.scissor == 0) {
  1739. // If scissor testing is disabled, the clear is always full
  1740. return true;
  1741. }
  1742. // Make sure the clear covers all texels in the subresource
  1743. return scissor.min_x == 0 && scissor.min_y == 0 && scissor.max_x >= size.width &&
  1744. scissor.max_y >= size.height;
  1745. }
  1746. } // namespace VideoCommon