texture_cache.h 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288
  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 <list>
  8. #include <memory>
  9. #include <mutex>
  10. #include <set>
  11. #include <tuple>
  12. #include <unordered_map>
  13. #include <vector>
  14. #include <boost/icl/interval_map.hpp>
  15. #include <boost/range/iterator_range.hpp>
  16. #include "common/assert.h"
  17. #include "common/common_types.h"
  18. #include "common/math_util.h"
  19. #include "core/core.h"
  20. #include "core/memory.h"
  21. #include "core/settings.h"
  22. #include "video_core/dirty_flags.h"
  23. #include "video_core/engines/fermi_2d.h"
  24. #include "video_core/engines/maxwell_3d.h"
  25. #include "video_core/gpu.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/copy_params.h"
  30. #include "video_core/texture_cache/format_lookup_table.h"
  31. #include "video_core/texture_cache/surface_base.h"
  32. #include "video_core/texture_cache/surface_params.h"
  33. #include "video_core/texture_cache/surface_view.h"
  34. namespace Tegra::Texture {
  35. struct FullTextureInfo;
  36. }
  37. namespace VideoCore {
  38. class RasterizerInterface;
  39. }
  40. namespace VideoCommon {
  41. using VideoCore::Surface::PixelFormat;
  42. using VideoCore::Surface::SurfaceTarget;
  43. using RenderTargetConfig = Tegra::Engines::Maxwell3D::Regs::RenderTargetConfig;
  44. template <typename TSurface, typename TView>
  45. class TextureCache {
  46. public:
  47. void InvalidateRegion(VAddr addr, std::size_t size) {
  48. std::lock_guard lock{mutex};
  49. for (const auto& surface : GetSurfacesInRegion(addr, size)) {
  50. Unregister(surface);
  51. }
  52. }
  53. void OnCPUWrite(VAddr addr, std::size_t size) {
  54. std::lock_guard lock{mutex};
  55. for (const auto& surface : GetSurfacesInRegion(addr, size)) {
  56. if (surface->IsMemoryMarked()) {
  57. UnmarkMemory(surface);
  58. surface->SetSyncPending(true);
  59. marked_for_unregister.emplace_back(surface);
  60. }
  61. }
  62. }
  63. void SyncGuestHost() {
  64. std::lock_guard lock{mutex};
  65. for (const auto& surface : marked_for_unregister) {
  66. if (surface->IsRegistered()) {
  67. surface->SetSyncPending(false);
  68. Unregister(surface);
  69. }
  70. }
  71. marked_for_unregister.clear();
  72. }
  73. /**
  74. * Guarantees that rendertargets don't unregister themselves if the
  75. * collide. Protection is currently only done on 3D slices.
  76. */
  77. void GuardRenderTargets(bool new_guard) {
  78. guard_render_targets = new_guard;
  79. }
  80. void GuardSamplers(bool new_guard) {
  81. guard_samplers = new_guard;
  82. }
  83. void FlushRegion(VAddr addr, std::size_t size) {
  84. std::lock_guard lock{mutex};
  85. auto surfaces = GetSurfacesInRegion(addr, size);
  86. if (surfaces.empty()) {
  87. return;
  88. }
  89. std::sort(surfaces.begin(), surfaces.end(), [](const TSurface& a, const TSurface& b) {
  90. return a->GetModificationTick() < b->GetModificationTick();
  91. });
  92. for (const auto& surface : surfaces) {
  93. mutex.unlock();
  94. FlushSurface(surface);
  95. mutex.lock();
  96. }
  97. }
  98. bool MustFlushRegion(VAddr addr, std::size_t size) {
  99. std::lock_guard lock{mutex};
  100. const auto surfaces = GetSurfacesInRegion(addr, size);
  101. return std::any_of(surfaces.cbegin(), surfaces.cend(),
  102. [](const TSurface& surface) { return surface->IsModified(); });
  103. }
  104. TView GetTextureSurface(const Tegra::Texture::TICEntry& tic,
  105. const VideoCommon::Shader::Sampler& entry) {
  106. std::lock_guard lock{mutex};
  107. const auto gpu_addr{tic.Address()};
  108. if (!gpu_addr) {
  109. return GetNullSurface(SurfaceParams::ExpectedTarget(entry));
  110. }
  111. const std::optional<VAddr> cpu_addr =
  112. system.GPU().MemoryManager().GpuToCpuAddress(gpu_addr);
  113. if (!cpu_addr) {
  114. return GetNullSurface(SurfaceParams::ExpectedTarget(entry));
  115. }
  116. if (!IsTypeCompatible(tic.texture_type, entry)) {
  117. return GetNullSurface(SurfaceParams::ExpectedTarget(entry));
  118. }
  119. const auto params{SurfaceParams::CreateForTexture(format_lookup_table, tic, entry)};
  120. const auto [surface, view] = GetSurface(gpu_addr, *cpu_addr, params, true, false);
  121. if (guard_samplers) {
  122. sampled_textures.push_back(surface);
  123. }
  124. return view;
  125. }
  126. TView GetImageSurface(const Tegra::Texture::TICEntry& tic,
  127. const VideoCommon::Shader::Image& entry) {
  128. std::lock_guard lock{mutex};
  129. const auto gpu_addr{tic.Address()};
  130. if (!gpu_addr) {
  131. return GetNullSurface(SurfaceParams::ExpectedTarget(entry));
  132. }
  133. const std::optional<VAddr> cpu_addr =
  134. system.GPU().MemoryManager().GpuToCpuAddress(gpu_addr);
  135. if (!cpu_addr) {
  136. return GetNullSurface(SurfaceParams::ExpectedTarget(entry));
  137. }
  138. const auto params{SurfaceParams::CreateForImage(format_lookup_table, tic, entry)};
  139. const auto [surface, view] = GetSurface(gpu_addr, *cpu_addr, params, true, false);
  140. if (guard_samplers) {
  141. sampled_textures.push_back(surface);
  142. }
  143. return view;
  144. }
  145. bool TextureBarrier() {
  146. const bool any_rt =
  147. std::any_of(sampled_textures.begin(), sampled_textures.end(),
  148. [](const auto& surface) { return surface->IsRenderTarget(); });
  149. sampled_textures.clear();
  150. return any_rt;
  151. }
  152. TView GetDepthBufferSurface(bool preserve_contents) {
  153. std::lock_guard lock{mutex};
  154. auto& maxwell3d = system.GPU().Maxwell3D();
  155. if (!maxwell3d.dirty.flags[VideoCommon::Dirty::ZetaBuffer]) {
  156. return depth_buffer.view;
  157. }
  158. maxwell3d.dirty.flags[VideoCommon::Dirty::ZetaBuffer] = false;
  159. const auto& regs{maxwell3d.regs};
  160. const auto gpu_addr{regs.zeta.Address()};
  161. if (!gpu_addr || !regs.zeta_enable) {
  162. SetEmptyDepthBuffer();
  163. return {};
  164. }
  165. const std::optional<VAddr> cpu_addr =
  166. system.GPU().MemoryManager().GpuToCpuAddress(gpu_addr);
  167. if (!cpu_addr) {
  168. SetEmptyDepthBuffer();
  169. return {};
  170. }
  171. const auto depth_params{SurfaceParams::CreateForDepthBuffer(system)};
  172. auto surface_view = GetSurface(gpu_addr, *cpu_addr, depth_params, preserve_contents, true);
  173. if (depth_buffer.target)
  174. depth_buffer.target->MarkAsRenderTarget(false, NO_RT);
  175. depth_buffer.target = surface_view.first;
  176. depth_buffer.view = surface_view.second;
  177. if (depth_buffer.target)
  178. depth_buffer.target->MarkAsRenderTarget(true, DEPTH_RT);
  179. return surface_view.second;
  180. }
  181. TView GetColorBufferSurface(std::size_t index, bool preserve_contents) {
  182. std::lock_guard lock{mutex};
  183. ASSERT(index < Tegra::Engines::Maxwell3D::Regs::NumRenderTargets);
  184. auto& maxwell3d = system.GPU().Maxwell3D();
  185. if (!maxwell3d.dirty.flags[VideoCommon::Dirty::ColorBuffer0 + index]) {
  186. return render_targets[index].view;
  187. }
  188. maxwell3d.dirty.flags[VideoCommon::Dirty::ColorBuffer0 + index] = false;
  189. const auto& regs{maxwell3d.regs};
  190. if (index >= regs.rt_control.count || regs.rt[index].Address() == 0 ||
  191. regs.rt[index].format == Tegra::RenderTargetFormat::NONE) {
  192. SetEmptyColorBuffer(index);
  193. return {};
  194. }
  195. const auto& config{regs.rt[index]};
  196. const auto gpu_addr{config.Address()};
  197. if (!gpu_addr) {
  198. SetEmptyColorBuffer(index);
  199. return {};
  200. }
  201. const std::optional<VAddr> cpu_addr =
  202. system.GPU().MemoryManager().GpuToCpuAddress(gpu_addr);
  203. if (!cpu_addr) {
  204. SetEmptyColorBuffer(index);
  205. return {};
  206. }
  207. auto surface_view =
  208. GetSurface(gpu_addr, *cpu_addr, SurfaceParams::CreateForFramebuffer(system, index),
  209. preserve_contents, true);
  210. if (render_targets[index].target) {
  211. auto& surface = render_targets[index].target;
  212. surface->MarkAsRenderTarget(false, NO_RT);
  213. const auto& cr_params = surface->GetSurfaceParams();
  214. if (!cr_params.is_tiled && Settings::values.use_asynchronous_gpu_emulation) {
  215. AsyncFlushSurface(surface);
  216. }
  217. }
  218. render_targets[index].target = surface_view.first;
  219. render_targets[index].view = surface_view.second;
  220. if (render_targets[index].target)
  221. render_targets[index].target->MarkAsRenderTarget(true, static_cast<u32>(index));
  222. return surface_view.second;
  223. }
  224. void MarkColorBufferInUse(std::size_t index) {
  225. if (auto& render_target = render_targets[index].target) {
  226. render_target->MarkAsModified(true, Tick());
  227. }
  228. }
  229. void MarkDepthBufferInUse() {
  230. if (depth_buffer.target) {
  231. depth_buffer.target->MarkAsModified(true, Tick());
  232. }
  233. }
  234. void SetEmptyDepthBuffer() {
  235. if (depth_buffer.target == nullptr) {
  236. return;
  237. }
  238. depth_buffer.target->MarkAsRenderTarget(false, NO_RT);
  239. depth_buffer.target = nullptr;
  240. depth_buffer.view = nullptr;
  241. }
  242. void SetEmptyColorBuffer(std::size_t index) {
  243. if (render_targets[index].target == nullptr) {
  244. return;
  245. }
  246. render_targets[index].target->MarkAsRenderTarget(false, NO_RT);
  247. render_targets[index].target = nullptr;
  248. render_targets[index].view = nullptr;
  249. }
  250. void DoFermiCopy(const Tegra::Engines::Fermi2D::Regs::Surface& src_config,
  251. const Tegra::Engines::Fermi2D::Regs::Surface& dst_config,
  252. const Tegra::Engines::Fermi2D::Config& copy_config) {
  253. std::lock_guard lock{mutex};
  254. SurfaceParams src_params = SurfaceParams::CreateForFermiCopySurface(src_config);
  255. SurfaceParams dst_params = SurfaceParams::CreateForFermiCopySurface(dst_config);
  256. const GPUVAddr src_gpu_addr = src_config.Address();
  257. const GPUVAddr dst_gpu_addr = dst_config.Address();
  258. DeduceBestBlit(src_params, dst_params, src_gpu_addr, dst_gpu_addr);
  259. const std::optional<VAddr> dst_cpu_addr =
  260. system.GPU().MemoryManager().GpuToCpuAddress(dst_gpu_addr);
  261. const std::optional<VAddr> src_cpu_addr =
  262. system.GPU().MemoryManager().GpuToCpuAddress(src_gpu_addr);
  263. std::pair<TSurface, TView> dst_surface =
  264. GetSurface(dst_gpu_addr, *dst_cpu_addr, dst_params, true, false);
  265. std::pair<TSurface, TView> src_surface =
  266. GetSurface(src_gpu_addr, *src_cpu_addr, src_params, true, false);
  267. ImageBlit(src_surface.second, dst_surface.second, copy_config);
  268. dst_surface.first->MarkAsModified(true, Tick());
  269. }
  270. TSurface TryFindFramebufferSurface(VAddr addr) {
  271. if (!addr) {
  272. return nullptr;
  273. }
  274. const VAddr page = addr >> registry_page_bits;
  275. std::vector<TSurface>& list = registry[page];
  276. for (auto& surface : list) {
  277. if (surface->GetCpuAddr() == addr) {
  278. return surface;
  279. }
  280. }
  281. return nullptr;
  282. }
  283. u64 Tick() {
  284. return ++ticks;
  285. }
  286. void CommitAsyncFlushes() {
  287. committed_flushes.push_back(uncommitted_flushes);
  288. uncommitted_flushes.reset();
  289. }
  290. bool HasUncommittedFlushes() const {
  291. return uncommitted_flushes != nullptr;
  292. }
  293. bool ShouldWaitAsyncFlushes() const {
  294. return !committed_flushes.empty() && committed_flushes.front() != nullptr;
  295. }
  296. void PopAsyncFlushes() {
  297. if (committed_flushes.empty()) {
  298. return;
  299. }
  300. auto& flush_list = committed_flushes.front();
  301. if (!flush_list) {
  302. committed_flushes.pop_front();
  303. return;
  304. }
  305. for (TSurface& surface : *flush_list) {
  306. FlushSurface(surface);
  307. }
  308. committed_flushes.pop_front();
  309. }
  310. protected:
  311. explicit TextureCache(Core::System& system, VideoCore::RasterizerInterface& rasterizer,
  312. bool is_astc_supported)
  313. : system{system}, is_astc_supported{is_astc_supported}, rasterizer{rasterizer} {
  314. for (std::size_t i = 0; i < Tegra::Engines::Maxwell3D::Regs::NumRenderTargets; i++) {
  315. SetEmptyColorBuffer(i);
  316. }
  317. SetEmptyDepthBuffer();
  318. staging_cache.SetSize(2);
  319. const auto make_siblings = [this](PixelFormat a, PixelFormat b) {
  320. siblings_table[static_cast<std::size_t>(a)] = b;
  321. siblings_table[static_cast<std::size_t>(b)] = a;
  322. };
  323. std::fill(siblings_table.begin(), siblings_table.end(), PixelFormat::Invalid);
  324. make_siblings(PixelFormat::Z16, PixelFormat::R16U);
  325. make_siblings(PixelFormat::Z32F, PixelFormat::R32F);
  326. make_siblings(PixelFormat::Z32FS8, PixelFormat::RG32F);
  327. sampled_textures.reserve(64);
  328. }
  329. ~TextureCache() = default;
  330. virtual TSurface CreateSurface(GPUVAddr gpu_addr, const SurfaceParams& params) = 0;
  331. virtual void ImageCopy(TSurface& src_surface, TSurface& dst_surface,
  332. const CopyParams& copy_params) = 0;
  333. virtual void ImageBlit(TView& src_view, TView& dst_view,
  334. const Tegra::Engines::Fermi2D::Config& copy_config) = 0;
  335. // Depending on the backend, a buffer copy can be slow as it means deoptimizing the texture
  336. // and reading it from a separate buffer.
  337. virtual void BufferCopy(TSurface& src_surface, TSurface& dst_surface) = 0;
  338. void ManageRenderTargetUnregister(TSurface& surface) {
  339. auto& dirty = system.GPU().Maxwell3D().dirty;
  340. const u32 index = surface->GetRenderTarget();
  341. if (index == DEPTH_RT) {
  342. dirty.flags[VideoCommon::Dirty::ZetaBuffer] = true;
  343. } else {
  344. dirty.flags[VideoCommon::Dirty::ColorBuffer0 + index] = true;
  345. }
  346. dirty.flags[VideoCommon::Dirty::RenderTargets] = true;
  347. }
  348. void Register(TSurface surface) {
  349. const GPUVAddr gpu_addr = surface->GetGpuAddr();
  350. const std::size_t size = surface->GetSizeInBytes();
  351. const std::optional<VAddr> cpu_addr =
  352. system.GPU().MemoryManager().GpuToCpuAddress(gpu_addr);
  353. if (!cpu_addr) {
  354. LOG_CRITICAL(HW_GPU, "Failed to register surface with unmapped gpu_address 0x{:016x}",
  355. gpu_addr);
  356. return;
  357. }
  358. surface->SetCpuAddr(*cpu_addr);
  359. RegisterInnerCache(surface);
  360. surface->MarkAsRegistered(true);
  361. surface->SetMemoryMarked(true);
  362. rasterizer.UpdatePagesCachedCount(*cpu_addr, size, 1);
  363. }
  364. void UnmarkMemory(TSurface surface) {
  365. if (!surface->IsMemoryMarked()) {
  366. return;
  367. }
  368. const std::size_t size = surface->GetSizeInBytes();
  369. const VAddr cpu_addr = surface->GetCpuAddr();
  370. rasterizer.UpdatePagesCachedCount(cpu_addr, size, -1);
  371. surface->SetMemoryMarked(false);
  372. }
  373. void Unregister(TSurface surface) {
  374. if (guard_render_targets && surface->IsProtected()) {
  375. return;
  376. }
  377. if (!guard_render_targets && surface->IsRenderTarget()) {
  378. ManageRenderTargetUnregister(surface);
  379. }
  380. UnmarkMemory(surface);
  381. if (surface->IsSyncPending()) {
  382. marked_for_unregister.remove(surface);
  383. surface->SetSyncPending(false);
  384. }
  385. UnregisterInnerCache(surface);
  386. surface->MarkAsRegistered(false);
  387. ReserveSurface(surface->GetSurfaceParams(), surface);
  388. }
  389. TSurface GetUncachedSurface(const GPUVAddr gpu_addr, const SurfaceParams& params) {
  390. if (const auto surface = TryGetReservedSurface(params); surface) {
  391. surface->SetGpuAddr(gpu_addr);
  392. return surface;
  393. }
  394. // No reserved surface available, create a new one and reserve it
  395. auto new_surface{CreateSurface(gpu_addr, params)};
  396. return new_surface;
  397. }
  398. Core::System& system;
  399. const bool is_astc_supported;
  400. private:
  401. enum class RecycleStrategy : u32 {
  402. Ignore = 0,
  403. Flush = 1,
  404. BufferCopy = 3,
  405. };
  406. enum class DeductionType : u32 {
  407. DeductionComplete,
  408. DeductionIncomplete,
  409. DeductionFailed,
  410. };
  411. struct Deduction {
  412. DeductionType type{DeductionType::DeductionFailed};
  413. TSurface surface{};
  414. bool Failed() const {
  415. return type == DeductionType::DeductionFailed;
  416. }
  417. bool Incomplete() const {
  418. return type == DeductionType::DeductionIncomplete;
  419. }
  420. bool IsDepth() const {
  421. return surface->GetSurfaceParams().IsPixelFormatZeta();
  422. }
  423. };
  424. /**
  425. * Takes care of selecting a proper strategy to deal with a texture recycle.
  426. *
  427. * @param overlaps The overlapping surfaces registered in the cache.
  428. * @param params The parameters on the new surface.
  429. * @param gpu_addr The starting address of the new surface.
  430. * @param untopological Indicates to the recycler that the texture has no way
  431. * to match the overlaps due to topological reasons.
  432. **/
  433. RecycleStrategy PickStrategy(std::vector<TSurface>& overlaps, const SurfaceParams& params,
  434. const GPUVAddr gpu_addr, const MatchTopologyResult untopological) {
  435. if (Settings::IsGPULevelExtreme()) {
  436. return RecycleStrategy::Flush;
  437. }
  438. // 3D Textures decision
  439. if (params.block_depth > 1 || params.target == SurfaceTarget::Texture3D) {
  440. return RecycleStrategy::Flush;
  441. }
  442. for (const auto& s : overlaps) {
  443. const auto& s_params = s->GetSurfaceParams();
  444. if (s_params.block_depth > 1 || s_params.target == SurfaceTarget::Texture3D) {
  445. return RecycleStrategy::Flush;
  446. }
  447. }
  448. // Untopological decision
  449. if (untopological == MatchTopologyResult::CompressUnmatch) {
  450. return RecycleStrategy::Flush;
  451. }
  452. if (untopological == MatchTopologyResult::FullMatch && !params.is_tiled) {
  453. return RecycleStrategy::Flush;
  454. }
  455. return RecycleStrategy::Ignore;
  456. }
  457. /**
  458. * Used to decide what to do with textures we can't resolve in the cache It has 2 implemented
  459. * strategies: Ignore and Flush.
  460. *
  461. * - Ignore: Just unregisters all the overlaps and loads the new texture.
  462. * - Flush: Flushes all the overlaps into memory and loads the new surface from that data.
  463. *
  464. * @param overlaps The overlapping surfaces registered in the cache.
  465. * @param params The parameters for the new surface.
  466. * @param gpu_addr The starting address of the new surface.
  467. * @param preserve_contents Indicates that the new surface should be loaded from memory or left
  468. * blank.
  469. * @param untopological Indicates to the recycler that the texture has no way to match the
  470. * overlaps due to topological reasons.
  471. **/
  472. std::pair<TSurface, TView> RecycleSurface(std::vector<TSurface>& overlaps,
  473. const SurfaceParams& params, const GPUVAddr gpu_addr,
  474. const bool preserve_contents,
  475. const MatchTopologyResult untopological) {
  476. const bool do_load = preserve_contents && Settings::IsGPULevelExtreme();
  477. for (auto& surface : overlaps) {
  478. Unregister(surface);
  479. }
  480. switch (PickStrategy(overlaps, params, gpu_addr, untopological)) {
  481. case RecycleStrategy::Ignore: {
  482. return InitializeSurface(gpu_addr, params, do_load);
  483. }
  484. case RecycleStrategy::Flush: {
  485. std::sort(overlaps.begin(), overlaps.end(),
  486. [](const TSurface& a, const TSurface& b) -> bool {
  487. return a->GetModificationTick() < b->GetModificationTick();
  488. });
  489. for (auto& surface : overlaps) {
  490. FlushSurface(surface);
  491. }
  492. return InitializeSurface(gpu_addr, params, preserve_contents);
  493. }
  494. case RecycleStrategy::BufferCopy: {
  495. auto new_surface = GetUncachedSurface(gpu_addr, params);
  496. BufferCopy(overlaps[0], new_surface);
  497. return {new_surface, new_surface->GetMainView()};
  498. }
  499. default: {
  500. UNIMPLEMENTED_MSG("Unimplemented Texture Cache Recycling Strategy!");
  501. return InitializeSurface(gpu_addr, params, do_load);
  502. }
  503. }
  504. }
  505. /**
  506. * Takes a single surface and recreates into another that may differ in
  507. * format, target or width alignment.
  508. *
  509. * @param current_surface The registered surface in the cache which we want to convert.
  510. * @param params The new surface params which we'll use to recreate the surface.
  511. * @param is_render Whether or not the surface is a render target.
  512. **/
  513. std::pair<TSurface, TView> RebuildSurface(TSurface current_surface, const SurfaceParams& params,
  514. bool is_render) {
  515. const auto gpu_addr = current_surface->GetGpuAddr();
  516. const auto& cr_params = current_surface->GetSurfaceParams();
  517. TSurface new_surface;
  518. if (cr_params.pixel_format != params.pixel_format && !is_render &&
  519. GetSiblingFormat(cr_params.pixel_format) == params.pixel_format) {
  520. SurfaceParams new_params = params;
  521. new_params.pixel_format = cr_params.pixel_format;
  522. new_params.type = cr_params.type;
  523. new_surface = GetUncachedSurface(gpu_addr, new_params);
  524. } else {
  525. new_surface = GetUncachedSurface(gpu_addr, params);
  526. }
  527. const auto& final_params = new_surface->GetSurfaceParams();
  528. if (cr_params.type != final_params.type) {
  529. if (Settings::IsGPULevelExtreme()) {
  530. BufferCopy(current_surface, new_surface);
  531. }
  532. } else {
  533. std::vector<CopyParams> bricks = current_surface->BreakDown(final_params);
  534. for (auto& brick : bricks) {
  535. ImageCopy(current_surface, new_surface, brick);
  536. }
  537. }
  538. Unregister(current_surface);
  539. Register(new_surface);
  540. new_surface->MarkAsModified(current_surface->IsModified(), Tick());
  541. return {new_surface, new_surface->GetMainView()};
  542. }
  543. /**
  544. * Takes a single surface and checks with the new surface's params if it's an exact
  545. * match, we return the main view of the registered surface. If its formats don't
  546. * match, we rebuild the surface. We call this last method a `Mirage`. If formats
  547. * match but the targets don't, we create an overview View of the registered surface.
  548. *
  549. * @param current_surface The registered surface in the cache which we want to convert.
  550. * @param params The new surface params which we want to check.
  551. * @param is_render Whether or not the surface is a render target.
  552. **/
  553. std::pair<TSurface, TView> ManageStructuralMatch(TSurface current_surface,
  554. const SurfaceParams& params, bool is_render) {
  555. const bool is_mirage = !current_surface->MatchFormat(params.pixel_format);
  556. const bool matches_target = current_surface->MatchTarget(params.target);
  557. const auto match_check = [&]() -> std::pair<TSurface, TView> {
  558. if (matches_target) {
  559. return {current_surface, current_surface->GetMainView()};
  560. }
  561. return {current_surface, current_surface->EmplaceOverview(params)};
  562. };
  563. if (!is_mirage) {
  564. return match_check();
  565. }
  566. if (!is_render && GetSiblingFormat(current_surface->GetFormat()) == params.pixel_format) {
  567. return match_check();
  568. }
  569. return RebuildSurface(current_surface, params, is_render);
  570. }
  571. /**
  572. * Unlike RebuildSurface where we know whether or not registered surfaces match the candidate
  573. * in some way, we have no guarantees here. We try to see if the overlaps are sublayers/mipmaps
  574. * of the new surface, if they all match we end up recreating a surface for them,
  575. * else we return nothing.
  576. *
  577. * @param overlaps The overlapping surfaces registered in the cache.
  578. * @param params The parameters on the new surface.
  579. * @param gpu_addr The starting address of the new surface.
  580. **/
  581. std::optional<std::pair<TSurface, TView>> TryReconstructSurface(std::vector<TSurface>& overlaps,
  582. const SurfaceParams& params,
  583. GPUVAddr gpu_addr) {
  584. if (params.target == SurfaceTarget::Texture3D) {
  585. return std::nullopt;
  586. }
  587. TSurface new_surface = GetUncachedSurface(gpu_addr, params);
  588. std::size_t passed_tests = 0;
  589. bool modified = false;
  590. u32 num_resources = 0;
  591. for (auto& surface : overlaps) {
  592. const SurfaceParams& src_params = surface->GetSurfaceParams();
  593. num_resources += src_params.depth * src_params.num_levels;
  594. }
  595. if (num_resources != params.depth * params.num_levels) {
  596. LoadSurface(new_surface);
  597. }
  598. for (auto& surface : overlaps) {
  599. const SurfaceParams& src_params = surface->GetSurfaceParams();
  600. const auto mipmap_layer{new_surface->GetLayerMipmap(surface->GetGpuAddr())};
  601. if (!mipmap_layer) {
  602. continue;
  603. }
  604. const auto [base_layer, base_mipmap] = *mipmap_layer;
  605. if (new_surface->GetMipmapSize(base_mipmap) != surface->GetMipmapSize(0)) {
  606. continue;
  607. }
  608. ++passed_tests;
  609. if (!surface->IsModified()) {
  610. continue;
  611. }
  612. modified = true;
  613. // Copy all mipmaps and layers
  614. const u32 block_width = params.GetDefaultBlockWidth();
  615. const u32 block_height = params.GetDefaultBlockHeight();
  616. for (u32 mipmap = base_mipmap; mipmap < base_mipmap + src_params.num_levels; ++mipmap) {
  617. const u32 width = SurfaceParams::IntersectWidth(src_params, params, 0, mipmap);
  618. const u32 height = SurfaceParams::IntersectHeight(src_params, params, 0, mipmap);
  619. if (width < block_width || height < block_height) {
  620. // Current APIs forbid copying small compressed textures, avoid errors
  621. break;
  622. }
  623. const CopyParams copy_params(0, 0, 0, 0, 0, base_layer, 0, mipmap, width, height,
  624. src_params.depth);
  625. ImageCopy(surface, new_surface, copy_params);
  626. }
  627. }
  628. if (passed_tests == 0) {
  629. return std::nullopt;
  630. }
  631. if (Settings::IsGPULevelExtreme() && passed_tests != overlaps.size()) {
  632. // In Accurate GPU all tests should pass, else we recycle
  633. return std::nullopt;
  634. }
  635. for (const auto& surface : overlaps) {
  636. Unregister(surface);
  637. }
  638. new_surface->MarkAsModified(modified, Tick());
  639. Register(new_surface);
  640. return {{new_surface, new_surface->GetMainView()}};
  641. }
  642. /**
  643. * Takes care of managing 3D textures and its slices. Does HLE methods for reconstructing the 3D
  644. * textures within the GPU if possible. Falls back to LLE when it isn't possible to use any of
  645. * the HLE methods.
  646. *
  647. * @param overlaps The overlapping surfaces registered in the cache.
  648. * @param params The parameters on the new surface.
  649. * @param gpu_addr The starting address of the new surface.
  650. * @param cpu_addr The starting address of the new surface on physical memory.
  651. * @param preserve_contents Indicates that the new surface should be loaded from memory or
  652. * left blank.
  653. */
  654. std::optional<std::pair<TSurface, TView>> Manage3DSurfaces(std::vector<TSurface>& overlaps,
  655. const SurfaceParams& params,
  656. const GPUVAddr gpu_addr,
  657. const VAddr cpu_addr,
  658. bool preserve_contents) {
  659. if (params.target == SurfaceTarget::Texture3D) {
  660. bool failed = false;
  661. if (params.num_levels > 1) {
  662. // We can't handle mipmaps in 3D textures yet, better fallback to LLE approach
  663. return std::nullopt;
  664. }
  665. TSurface new_surface = GetUncachedSurface(gpu_addr, params);
  666. bool modified = false;
  667. for (auto& surface : overlaps) {
  668. const SurfaceParams& src_params = surface->GetSurfaceParams();
  669. if (src_params.target != SurfaceTarget::Texture2D) {
  670. failed = true;
  671. break;
  672. }
  673. if (src_params.height != params.height) {
  674. failed = true;
  675. break;
  676. }
  677. if (src_params.block_depth != params.block_depth ||
  678. src_params.block_height != params.block_height) {
  679. failed = true;
  680. break;
  681. }
  682. const u32 offset = static_cast<u32>(surface->GetCpuAddr() - cpu_addr);
  683. const auto offsets = params.GetBlockOffsetXYZ(offset);
  684. const auto z = std::get<2>(offsets);
  685. modified |= surface->IsModified();
  686. const CopyParams copy_params(0, 0, 0, 0, 0, z, 0, 0, params.width, params.height,
  687. 1);
  688. ImageCopy(surface, new_surface, copy_params);
  689. }
  690. if (failed) {
  691. return std::nullopt;
  692. }
  693. for (const auto& surface : overlaps) {
  694. Unregister(surface);
  695. }
  696. new_surface->MarkAsModified(modified, Tick());
  697. Register(new_surface);
  698. auto view = new_surface->GetMainView();
  699. return {{std::move(new_surface), view}};
  700. } else {
  701. for (const auto& surface : overlaps) {
  702. if (!surface->MatchTarget(params.target)) {
  703. if (overlaps.size() == 1 && surface->GetCpuAddr() == cpu_addr) {
  704. if (Settings::IsGPULevelExtreme()) {
  705. return std::nullopt;
  706. }
  707. Unregister(surface);
  708. return InitializeSurface(gpu_addr, params, preserve_contents);
  709. }
  710. return std::nullopt;
  711. }
  712. if (surface->GetCpuAddr() != cpu_addr) {
  713. continue;
  714. }
  715. if (surface->MatchesStructure(params) == MatchStructureResult::FullMatch) {
  716. return {{surface, surface->GetMainView()}};
  717. }
  718. }
  719. return InitializeSurface(gpu_addr, params, preserve_contents);
  720. }
  721. }
  722. /**
  723. * Gets the starting address and parameters of a candidate surface and tries
  724. * to find a matching surface within the cache. This is done in 3 big steps:
  725. *
  726. * 1. Check the 1st Level Cache in order to find an exact match, if we fail, we move to step 2.
  727. *
  728. * 2. Check if there are any overlaps at all, if there are none, we just load the texture from
  729. * memory else we move to step 3.
  730. *
  731. * 3. Consists of figuring out the relationship between the candidate texture and the
  732. * overlaps. We divide the scenarios depending if there's 1 or many overlaps. If
  733. * there's many, we just try to reconstruct a new surface out of them based on the
  734. * candidate's parameters, if we fail, we recycle. When there's only 1 overlap then we
  735. * have to check if the candidate is a view (layer/mipmap) of the overlap or if the
  736. * registered surface is a mipmap/layer of the candidate. In this last case we reconstruct
  737. * a new surface.
  738. *
  739. * @param gpu_addr The starting address of the candidate surface.
  740. * @param params The parameters on the candidate surface.
  741. * @param preserve_contents Indicates that the new surface should be loaded from memory or
  742. * left blank.
  743. * @param is_render Whether or not the surface is a render target.
  744. **/
  745. std::pair<TSurface, TView> GetSurface(const GPUVAddr gpu_addr, const VAddr cpu_addr,
  746. const SurfaceParams& params, bool preserve_contents,
  747. bool is_render) {
  748. // Step 1
  749. // Check Level 1 Cache for a fast structural match. If candidate surface
  750. // matches at certain level we are pretty much done.
  751. if (const auto iter = l1_cache.find(cpu_addr); iter != l1_cache.end()) {
  752. TSurface& current_surface = iter->second;
  753. const auto topological_result = current_surface->MatchesTopology(params);
  754. if (topological_result != MatchTopologyResult::FullMatch) {
  755. std::vector<TSurface> overlaps{current_surface};
  756. return RecycleSurface(overlaps, params, gpu_addr, preserve_contents,
  757. topological_result);
  758. }
  759. const auto struct_result = current_surface->MatchesStructure(params);
  760. if (struct_result != MatchStructureResult::None) {
  761. const auto& old_params = current_surface->GetSurfaceParams();
  762. const bool not_3d = params.target != SurfaceTarget::Texture3D &&
  763. old_params.target != SurfaceTarget::Texture3D;
  764. if (not_3d || current_surface->MatchTarget(params.target)) {
  765. if (struct_result == MatchStructureResult::FullMatch) {
  766. return ManageStructuralMatch(current_surface, params, is_render);
  767. } else {
  768. return RebuildSurface(current_surface, params, is_render);
  769. }
  770. }
  771. }
  772. }
  773. // Step 2
  774. // Obtain all possible overlaps in the memory region
  775. const std::size_t candidate_size = params.GetGuestSizeInBytes();
  776. auto overlaps{GetSurfacesInRegion(cpu_addr, candidate_size)};
  777. // If none are found, we are done. we just load the surface and create it.
  778. if (overlaps.empty()) {
  779. return InitializeSurface(gpu_addr, params, preserve_contents);
  780. }
  781. // Step 3
  782. // Now we need to figure the relationship between the texture and its overlaps
  783. // we do a topological test to ensure we can find some relationship. If it fails
  784. // immediately recycle the texture
  785. for (const auto& surface : overlaps) {
  786. const auto topological_result = surface->MatchesTopology(params);
  787. if (topological_result != MatchTopologyResult::FullMatch) {
  788. return RecycleSurface(overlaps, params, gpu_addr, preserve_contents,
  789. topological_result);
  790. }
  791. }
  792. // Check if it's a 3D texture
  793. if (params.block_depth > 0) {
  794. auto surface =
  795. Manage3DSurfaces(overlaps, params, gpu_addr, cpu_addr, preserve_contents);
  796. if (surface) {
  797. return *surface;
  798. }
  799. }
  800. // Split cases between 1 overlap or many.
  801. if (overlaps.size() == 1) {
  802. TSurface current_surface = overlaps[0];
  803. // First check if the surface is within the overlap. If not, it means
  804. // two things either the candidate surface is a supertexture of the overlap
  805. // or they don't match in any known way.
  806. if (!current_surface->IsInside(gpu_addr, gpu_addr + candidate_size)) {
  807. const std::optional view = TryReconstructSurface(overlaps, params, gpu_addr);
  808. if (view) {
  809. return *view;
  810. }
  811. return RecycleSurface(overlaps, params, gpu_addr, preserve_contents,
  812. MatchTopologyResult::FullMatch);
  813. }
  814. // Now we check if the candidate is a mipmap/layer of the overlap
  815. std::optional<TView> view =
  816. current_surface->EmplaceView(params, gpu_addr, candidate_size);
  817. if (view) {
  818. const bool is_mirage = !current_surface->MatchFormat(params.pixel_format);
  819. if (is_mirage) {
  820. // On a mirage view, we need to recreate the surface under this new view
  821. // and then obtain a view again.
  822. SurfaceParams new_params = current_surface->GetSurfaceParams();
  823. const u32 wh = SurfaceParams::ConvertWidth(
  824. new_params.width, new_params.pixel_format, params.pixel_format);
  825. const u32 hh = SurfaceParams::ConvertHeight(
  826. new_params.height, new_params.pixel_format, params.pixel_format);
  827. new_params.width = wh;
  828. new_params.height = hh;
  829. new_params.pixel_format = params.pixel_format;
  830. std::pair<TSurface, TView> pair =
  831. RebuildSurface(current_surface, new_params, is_render);
  832. std::optional<TView> mirage_view =
  833. pair.first->EmplaceView(params, gpu_addr, candidate_size);
  834. if (mirage_view)
  835. return {pair.first, *mirage_view};
  836. return RecycleSurface(overlaps, params, gpu_addr, preserve_contents,
  837. MatchTopologyResult::FullMatch);
  838. }
  839. return {current_surface, *view};
  840. }
  841. } else {
  842. // If there are many overlaps, odds are they are subtextures of the candidate
  843. // surface. We try to construct a new surface based on the candidate parameters,
  844. // using the overlaps. If a single overlap fails, this will fail.
  845. std::optional<std::pair<TSurface, TView>> view =
  846. TryReconstructSurface(overlaps, params, gpu_addr);
  847. if (view) {
  848. return *view;
  849. }
  850. }
  851. // We failed all the tests, recycle the overlaps into a new texture.
  852. return RecycleSurface(overlaps, params, gpu_addr, preserve_contents,
  853. MatchTopologyResult::FullMatch);
  854. }
  855. /**
  856. * Gets the starting address and parameters of a candidate surface and tries to find a
  857. * matching surface within the cache that's similar to it. If there are many textures
  858. * or the texture found if entirely incompatible, it will fail. If no texture is found, the
  859. * blit will be unsuccessful.
  860. *
  861. * @param gpu_addr The starting address of the candidate surface.
  862. * @param params The parameters on the candidate surface.
  863. **/
  864. Deduction DeduceSurface(const GPUVAddr gpu_addr, const SurfaceParams& params) {
  865. const std::optional<VAddr> cpu_addr =
  866. system.GPU().MemoryManager().GpuToCpuAddress(gpu_addr);
  867. if (!cpu_addr) {
  868. Deduction result{};
  869. result.type = DeductionType::DeductionFailed;
  870. return result;
  871. }
  872. if (const auto iter = l1_cache.find(*cpu_addr); iter != l1_cache.end()) {
  873. TSurface& current_surface = iter->second;
  874. const auto topological_result = current_surface->MatchesTopology(params);
  875. if (topological_result != MatchTopologyResult::FullMatch) {
  876. Deduction result{};
  877. result.type = DeductionType::DeductionFailed;
  878. return result;
  879. }
  880. const auto struct_result = current_surface->MatchesStructure(params);
  881. if (struct_result != MatchStructureResult::None &&
  882. current_surface->MatchTarget(params.target)) {
  883. Deduction result{};
  884. result.type = DeductionType::DeductionComplete;
  885. result.surface = current_surface;
  886. return result;
  887. }
  888. }
  889. const std::size_t candidate_size = params.GetGuestSizeInBytes();
  890. auto overlaps{GetSurfacesInRegion(*cpu_addr, candidate_size)};
  891. if (overlaps.empty()) {
  892. Deduction result{};
  893. result.type = DeductionType::DeductionIncomplete;
  894. return result;
  895. }
  896. if (overlaps.size() > 1) {
  897. Deduction result{};
  898. result.type = DeductionType::DeductionFailed;
  899. return result;
  900. } else {
  901. Deduction result{};
  902. result.type = DeductionType::DeductionComplete;
  903. result.surface = overlaps[0];
  904. return result;
  905. }
  906. }
  907. /**
  908. * Gets a null surface based on a target texture.
  909. * @param target The target of the null surface.
  910. */
  911. TView GetNullSurface(SurfaceTarget target) {
  912. const u32 i_target = static_cast<u32>(target);
  913. if (const auto it = invalid_cache.find(i_target); it != invalid_cache.end()) {
  914. return it->second->GetMainView();
  915. }
  916. SurfaceParams params{};
  917. params.target = target;
  918. params.is_tiled = false;
  919. params.srgb_conversion = false;
  920. params.is_layered =
  921. target == SurfaceTarget::Texture1DArray || target == SurfaceTarget::Texture2DArray ||
  922. target == SurfaceTarget::TextureCubemap || target == SurfaceTarget::TextureCubeArray;
  923. params.block_width = 0;
  924. params.block_height = 0;
  925. params.block_depth = 0;
  926. params.tile_width_spacing = 1;
  927. params.width = 1;
  928. params.height = 1;
  929. params.depth = 1;
  930. if (target == SurfaceTarget::TextureCubemap || target == SurfaceTarget::TextureCubeArray) {
  931. params.depth = 6;
  932. }
  933. params.pitch = 4;
  934. params.num_levels = 1;
  935. params.emulated_levels = 1;
  936. params.pixel_format = VideoCore::Surface::PixelFormat::R8U;
  937. params.type = VideoCore::Surface::SurfaceType::ColorTexture;
  938. auto surface = CreateSurface(0ULL, params);
  939. invalid_memory.resize(surface->GetHostSizeInBytes(), 0U);
  940. surface->UploadTexture(invalid_memory);
  941. surface->MarkAsModified(false, Tick());
  942. invalid_cache.emplace(i_target, surface);
  943. return surface->GetMainView();
  944. }
  945. /**
  946. * Gets the a source and destination starting address and parameters,
  947. * and tries to deduce if they are supposed to be depth textures. If so, their
  948. * parameters are modified and fixed into so.
  949. *
  950. * @param src_params The parameters of the candidate surface.
  951. * @param dst_params The parameters of the destination surface.
  952. * @param src_gpu_addr The starting address of the candidate surface.
  953. * @param dst_gpu_addr The starting address of the destination surface.
  954. **/
  955. void DeduceBestBlit(SurfaceParams& src_params, SurfaceParams& dst_params,
  956. const GPUVAddr src_gpu_addr, const GPUVAddr dst_gpu_addr) {
  957. auto deduced_src = DeduceSurface(src_gpu_addr, src_params);
  958. auto deduced_dst = DeduceSurface(src_gpu_addr, src_params);
  959. if (deduced_src.Failed() || deduced_dst.Failed()) {
  960. return;
  961. }
  962. const bool incomplete_src = deduced_src.Incomplete();
  963. const bool incomplete_dst = deduced_dst.Incomplete();
  964. if (incomplete_src && incomplete_dst) {
  965. return;
  966. }
  967. const bool any_incomplete = incomplete_src || incomplete_dst;
  968. if (!any_incomplete) {
  969. if (!(deduced_src.IsDepth() && deduced_dst.IsDepth())) {
  970. return;
  971. }
  972. } else {
  973. if (incomplete_src && !(deduced_dst.IsDepth())) {
  974. return;
  975. }
  976. if (incomplete_dst && !(deduced_src.IsDepth())) {
  977. return;
  978. }
  979. }
  980. const auto inherit_format = [](SurfaceParams& to, TSurface from) {
  981. const SurfaceParams& params = from->GetSurfaceParams();
  982. to.pixel_format = params.pixel_format;
  983. to.type = params.type;
  984. };
  985. // Now we got the cases where one or both is Depth and the other is not known
  986. if (!incomplete_src) {
  987. inherit_format(src_params, deduced_src.surface);
  988. } else {
  989. inherit_format(src_params, deduced_dst.surface);
  990. }
  991. if (!incomplete_dst) {
  992. inherit_format(dst_params, deduced_dst.surface);
  993. } else {
  994. inherit_format(dst_params, deduced_src.surface);
  995. }
  996. }
  997. std::pair<TSurface, TView> InitializeSurface(GPUVAddr gpu_addr, const SurfaceParams& params,
  998. bool preserve_contents) {
  999. auto new_surface{GetUncachedSurface(gpu_addr, params)};
  1000. Register(new_surface);
  1001. if (preserve_contents) {
  1002. LoadSurface(new_surface);
  1003. }
  1004. return {new_surface, new_surface->GetMainView()};
  1005. }
  1006. void LoadSurface(const TSurface& surface) {
  1007. staging_cache.GetBuffer(0).resize(surface->GetHostSizeInBytes());
  1008. surface->LoadBuffer(system.GPU().MemoryManager(), staging_cache);
  1009. surface->UploadTexture(staging_cache.GetBuffer(0));
  1010. surface->MarkAsModified(false, Tick());
  1011. }
  1012. void FlushSurface(const TSurface& surface) {
  1013. if (!surface->IsModified()) {
  1014. return;
  1015. }
  1016. staging_cache.GetBuffer(0).resize(surface->GetHostSizeInBytes());
  1017. surface->DownloadTexture(staging_cache.GetBuffer(0));
  1018. surface->FlushBuffer(system.GPU().MemoryManager(), staging_cache);
  1019. surface->MarkAsModified(false, Tick());
  1020. }
  1021. void RegisterInnerCache(TSurface& surface) {
  1022. const VAddr cpu_addr = surface->GetCpuAddr();
  1023. VAddr start = cpu_addr >> registry_page_bits;
  1024. const VAddr end = (surface->GetCpuAddrEnd() - 1) >> registry_page_bits;
  1025. l1_cache[cpu_addr] = surface;
  1026. while (start <= end) {
  1027. registry[start].push_back(surface);
  1028. start++;
  1029. }
  1030. }
  1031. void UnregisterInnerCache(TSurface& surface) {
  1032. const VAddr cpu_addr = surface->GetCpuAddr();
  1033. VAddr start = cpu_addr >> registry_page_bits;
  1034. const VAddr end = (surface->GetCpuAddrEnd() - 1) >> registry_page_bits;
  1035. l1_cache.erase(cpu_addr);
  1036. while (start <= end) {
  1037. auto& reg{registry[start]};
  1038. reg.erase(std::find(reg.begin(), reg.end(), surface));
  1039. start++;
  1040. }
  1041. }
  1042. std::vector<TSurface> GetSurfacesInRegion(const VAddr cpu_addr, const std::size_t size) {
  1043. if (size == 0) {
  1044. return {};
  1045. }
  1046. const VAddr cpu_addr_end = cpu_addr + size;
  1047. VAddr start = cpu_addr >> registry_page_bits;
  1048. const VAddr end = (cpu_addr_end - 1) >> registry_page_bits;
  1049. std::vector<TSurface> surfaces;
  1050. while (start <= end) {
  1051. std::vector<TSurface>& list = registry[start];
  1052. for (auto& surface : list) {
  1053. if (!surface->IsPicked() && surface->Overlaps(cpu_addr, cpu_addr_end)) {
  1054. surface->MarkAsPicked(true);
  1055. surfaces.push_back(surface);
  1056. }
  1057. }
  1058. start++;
  1059. }
  1060. for (auto& surface : surfaces) {
  1061. surface->MarkAsPicked(false);
  1062. }
  1063. return surfaces;
  1064. }
  1065. void ReserveSurface(const SurfaceParams& params, TSurface surface) {
  1066. surface_reserve[params].push_back(std::move(surface));
  1067. }
  1068. TSurface TryGetReservedSurface(const SurfaceParams& params) {
  1069. auto search{surface_reserve.find(params)};
  1070. if (search == surface_reserve.end()) {
  1071. return {};
  1072. }
  1073. for (auto& surface : search->second) {
  1074. if (!surface->IsRegistered()) {
  1075. return surface;
  1076. }
  1077. }
  1078. return {};
  1079. }
  1080. constexpr PixelFormat GetSiblingFormat(PixelFormat format) const {
  1081. return siblings_table[static_cast<std::size_t>(format)];
  1082. }
  1083. /// Returns true the shader sampler entry is compatible with the TIC texture type.
  1084. static bool IsTypeCompatible(Tegra::Texture::TextureType tic_type,
  1085. const VideoCommon::Shader::Sampler& entry) {
  1086. const auto shader_type = entry.type;
  1087. switch (tic_type) {
  1088. case Tegra::Texture::TextureType::Texture1D:
  1089. case Tegra::Texture::TextureType::Texture1DArray:
  1090. return shader_type == Tegra::Shader::TextureType::Texture1D;
  1091. case Tegra::Texture::TextureType::Texture1DBuffer:
  1092. // TODO(Rodrigo): Assume as valid for now
  1093. return true;
  1094. case Tegra::Texture::TextureType::Texture2D:
  1095. case Tegra::Texture::TextureType::Texture2DNoMipmap:
  1096. return shader_type == Tegra::Shader::TextureType::Texture2D;
  1097. case Tegra::Texture::TextureType::Texture2DArray:
  1098. return shader_type == Tegra::Shader::TextureType::Texture2D ||
  1099. shader_type == Tegra::Shader::TextureType::TextureCube;
  1100. case Tegra::Texture::TextureType::Texture3D:
  1101. return shader_type == Tegra::Shader::TextureType::Texture3D;
  1102. case Tegra::Texture::TextureType::TextureCubeArray:
  1103. case Tegra::Texture::TextureType::TextureCubemap:
  1104. if (shader_type == Tegra::Shader::TextureType::TextureCube) {
  1105. return true;
  1106. }
  1107. return shader_type == Tegra::Shader::TextureType::Texture2D && entry.is_array;
  1108. }
  1109. UNREACHABLE();
  1110. return true;
  1111. }
  1112. struct FramebufferTargetInfo {
  1113. TSurface target;
  1114. TView view;
  1115. };
  1116. void AsyncFlushSurface(TSurface& surface) {
  1117. if (!uncommitted_flushes) {
  1118. uncommitted_flushes = std::make_shared<std::list<TSurface>>();
  1119. }
  1120. uncommitted_flushes->push_back(surface);
  1121. }
  1122. VideoCore::RasterizerInterface& rasterizer;
  1123. FormatLookupTable format_lookup_table;
  1124. u64 ticks{};
  1125. // Guards the cache for protection conflicts.
  1126. bool guard_render_targets{};
  1127. bool guard_samplers{};
  1128. // The siblings table is for formats that can inter exchange with one another
  1129. // without causing issues. This is only valid when a conflict occurs on a non
  1130. // rendering use.
  1131. std::array<PixelFormat, static_cast<std::size_t>(PixelFormat::Max)> siblings_table;
  1132. // The internal Cache is different for the Texture Cache. It's based on buckets
  1133. // of 1MB. This fits better for the purpose of this cache as textures are normaly
  1134. // large in size.
  1135. static constexpr u64 registry_page_bits{20};
  1136. static constexpr u64 registry_page_size{1 << registry_page_bits};
  1137. std::unordered_map<VAddr, std::vector<TSurface>> registry;
  1138. static constexpr u32 DEPTH_RT = 8;
  1139. static constexpr u32 NO_RT = 0xFFFFFFFF;
  1140. // The L1 Cache is used for fast texture lookup before checking the overlaps
  1141. // This avoids calculating size and other stuffs.
  1142. std::unordered_map<VAddr, TSurface> l1_cache;
  1143. /// The surface reserve is a "backup" cache, this is where we put unique surfaces that have
  1144. /// previously been used. This is to prevent surfaces from being constantly created and
  1145. /// destroyed when used with different surface parameters.
  1146. std::unordered_map<SurfaceParams, std::vector<TSurface>> surface_reserve;
  1147. std::array<FramebufferTargetInfo, Tegra::Engines::Maxwell3D::Regs::NumRenderTargets>
  1148. render_targets;
  1149. FramebufferTargetInfo depth_buffer;
  1150. std::vector<TSurface> sampled_textures;
  1151. /// This cache stores null surfaces in order to be used as a placeholder
  1152. /// for invalid texture calls.
  1153. std::unordered_map<u32, TSurface> invalid_cache;
  1154. std::vector<u8> invalid_memory;
  1155. std::list<TSurface> marked_for_unregister;
  1156. std::shared_ptr<std::list<TSurface>> uncommitted_flushes{};
  1157. std::list<std::shared_ptr<std::list<TSurface>>> committed_flushes;
  1158. StagingCache staging_cache;
  1159. std::recursive_mutex mutex;
  1160. };
  1161. } // namespace VideoCommon