texture_cache.h 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998
  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 <memory>
  8. #include <mutex>
  9. #include <set>
  10. #include <tuple>
  11. #include <unordered_map>
  12. #include <vector>
  13. #include <boost/icl/interval_map.hpp>
  14. #include <boost/range/iterator_range.hpp>
  15. #include "common/assert.h"
  16. #include "common/common_types.h"
  17. #include "common/math_util.h"
  18. #include "core/core.h"
  19. #include "core/memory.h"
  20. #include "core/settings.h"
  21. #include "video_core/engines/fermi_2d.h"
  22. #include "video_core/engines/maxwell_3d.h"
  23. #include "video_core/gpu.h"
  24. #include "video_core/memory_manager.h"
  25. #include "video_core/rasterizer_interface.h"
  26. #include "video_core/surface.h"
  27. #include "video_core/texture_cache/copy_params.h"
  28. #include "video_core/texture_cache/format_lookup_table.h"
  29. #include "video_core/texture_cache/surface_base.h"
  30. #include "video_core/texture_cache/surface_params.h"
  31. #include "video_core/texture_cache/surface_view.h"
  32. namespace Tegra::Texture {
  33. struct FullTextureInfo;
  34. }
  35. namespace VideoCore {
  36. class RasterizerInterface;
  37. }
  38. namespace VideoCommon {
  39. using VideoCore::Surface::PixelFormat;
  40. using VideoCore::Surface::SurfaceTarget;
  41. using RenderTargetConfig = Tegra::Engines::Maxwell3D::Regs::RenderTargetConfig;
  42. template <typename TSurface, typename TView>
  43. class TextureCache {
  44. using IntervalMap = boost::icl::interval_map<CacheAddr, std::set<TSurface>>;
  45. using IntervalType = typename IntervalMap::interval_type;
  46. public:
  47. void InvalidateRegion(CacheAddr 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. /**
  54. * Guarantees that rendertargets don't unregister themselves if the
  55. * collide. Protection is currently only done on 3D slices.
  56. */
  57. void GuardRenderTargets(bool new_guard) {
  58. guard_render_targets = new_guard;
  59. }
  60. void GuardSamplers(bool new_guard) {
  61. guard_samplers = new_guard;
  62. }
  63. void FlushRegion(CacheAddr addr, std::size_t size) {
  64. std::lock_guard lock{mutex};
  65. auto surfaces = GetSurfacesInRegion(addr, size);
  66. if (surfaces.empty()) {
  67. return;
  68. }
  69. std::sort(surfaces.begin(), surfaces.end(), [](const TSurface& a, const TSurface& b) {
  70. return a->GetModificationTick() < b->GetModificationTick();
  71. });
  72. for (const auto& surface : surfaces) {
  73. FlushSurface(surface);
  74. }
  75. }
  76. TView GetTextureSurface(const Tegra::Texture::TICEntry& tic,
  77. const VideoCommon::Shader::Sampler& entry) {
  78. std::lock_guard lock{mutex};
  79. const auto gpu_addr{tic.Address()};
  80. if (!gpu_addr) {
  81. return {};
  82. }
  83. const auto params{SurfaceParams::CreateForTexture(format_lookup_table, tic, entry)};
  84. const auto [surface, view] = GetSurface(gpu_addr, params, true, false);
  85. if (guard_samplers) {
  86. sampled_textures.push_back(surface);
  87. }
  88. return view;
  89. }
  90. TView GetImageSurface(const Tegra::Texture::TICEntry& tic,
  91. const VideoCommon::Shader::Image& entry) {
  92. std::lock_guard lock{mutex};
  93. const auto gpu_addr{tic.Address()};
  94. if (!gpu_addr) {
  95. return {};
  96. }
  97. const auto params{SurfaceParams::CreateForImage(format_lookup_table, tic, entry)};
  98. const auto [surface, view] = GetSurface(gpu_addr, params, true, false);
  99. if (guard_samplers) {
  100. sampled_textures.push_back(surface);
  101. }
  102. return view;
  103. }
  104. bool TextureBarrier() {
  105. const bool any_rt =
  106. std::any_of(sampled_textures.begin(), sampled_textures.end(),
  107. [](const auto& surface) { return surface->IsRenderTarget(); });
  108. sampled_textures.clear();
  109. return any_rt;
  110. }
  111. TView GetDepthBufferSurface(bool preserve_contents) {
  112. std::lock_guard lock{mutex};
  113. auto& maxwell3d = system.GPU().Maxwell3D();
  114. if (!maxwell3d.dirty.depth_buffer) {
  115. return depth_buffer.view;
  116. }
  117. maxwell3d.dirty.depth_buffer = false;
  118. const auto& regs{maxwell3d.regs};
  119. const auto gpu_addr{regs.zeta.Address()};
  120. if (!gpu_addr || !regs.zeta_enable) {
  121. SetEmptyDepthBuffer();
  122. return {};
  123. }
  124. const auto depth_params{SurfaceParams::CreateForDepthBuffer(
  125. system, regs.zeta_width, regs.zeta_height, regs.zeta.format,
  126. regs.zeta.memory_layout.block_width, regs.zeta.memory_layout.block_height,
  127. regs.zeta.memory_layout.block_depth, regs.zeta.memory_layout.type)};
  128. auto surface_view = GetSurface(gpu_addr, depth_params, preserve_contents, true);
  129. if (depth_buffer.target)
  130. depth_buffer.target->MarkAsRenderTarget(false, NO_RT);
  131. depth_buffer.target = surface_view.first;
  132. depth_buffer.view = surface_view.second;
  133. if (depth_buffer.target)
  134. depth_buffer.target->MarkAsRenderTarget(true, DEPTH_RT);
  135. return surface_view.second;
  136. }
  137. TView GetColorBufferSurface(std::size_t index, bool preserve_contents) {
  138. std::lock_guard lock{mutex};
  139. ASSERT(index < Tegra::Engines::Maxwell3D::Regs::NumRenderTargets);
  140. auto& maxwell3d = system.GPU().Maxwell3D();
  141. if (!maxwell3d.dirty.render_target[index]) {
  142. return render_targets[index].view;
  143. }
  144. maxwell3d.dirty.render_target[index] = false;
  145. const auto& regs{maxwell3d.regs};
  146. if (index >= regs.rt_control.count || regs.rt[index].Address() == 0 ||
  147. regs.rt[index].format == Tegra::RenderTargetFormat::NONE) {
  148. SetEmptyColorBuffer(index);
  149. return {};
  150. }
  151. const auto& config{regs.rt[index]};
  152. const auto gpu_addr{config.Address()};
  153. if (!gpu_addr) {
  154. SetEmptyColorBuffer(index);
  155. return {};
  156. }
  157. auto surface_view = GetSurface(gpu_addr, SurfaceParams::CreateForFramebuffer(system, index),
  158. preserve_contents, true);
  159. if (render_targets[index].target)
  160. render_targets[index].target->MarkAsRenderTarget(false, NO_RT);
  161. render_targets[index].target = surface_view.first;
  162. render_targets[index].view = surface_view.second;
  163. if (render_targets[index].target)
  164. render_targets[index].target->MarkAsRenderTarget(true, static_cast<u32>(index));
  165. return surface_view.second;
  166. }
  167. void MarkColorBufferInUse(std::size_t index) {
  168. if (auto& render_target = render_targets[index].target) {
  169. render_target->MarkAsModified(true, Tick());
  170. }
  171. }
  172. void MarkDepthBufferInUse() {
  173. if (depth_buffer.target) {
  174. depth_buffer.target->MarkAsModified(true, Tick());
  175. }
  176. }
  177. void SetEmptyDepthBuffer() {
  178. if (depth_buffer.target == nullptr) {
  179. return;
  180. }
  181. depth_buffer.target->MarkAsRenderTarget(false, NO_RT);
  182. depth_buffer.target = nullptr;
  183. depth_buffer.view = nullptr;
  184. }
  185. void SetEmptyColorBuffer(std::size_t index) {
  186. if (render_targets[index].target == nullptr) {
  187. return;
  188. }
  189. render_targets[index].target->MarkAsRenderTarget(false, NO_RT);
  190. render_targets[index].target = nullptr;
  191. render_targets[index].view = nullptr;
  192. }
  193. void DoFermiCopy(const Tegra::Engines::Fermi2D::Regs::Surface& src_config,
  194. const Tegra::Engines::Fermi2D::Regs::Surface& dst_config,
  195. const Tegra::Engines::Fermi2D::Config& copy_config) {
  196. std::lock_guard lock{mutex};
  197. SurfaceParams src_params = SurfaceParams::CreateForFermiCopySurface(src_config);
  198. SurfaceParams dst_params = SurfaceParams::CreateForFermiCopySurface(dst_config);
  199. const GPUVAddr src_gpu_addr = src_config.Address();
  200. const GPUVAddr dst_gpu_addr = dst_config.Address();
  201. DeduceBestBlit(src_params, dst_params, src_gpu_addr, dst_gpu_addr);
  202. std::pair<TSurface, TView> dst_surface = GetSurface(dst_gpu_addr, dst_params, true, false);
  203. std::pair<TSurface, TView> src_surface = GetSurface(src_gpu_addr, src_params, true, false);
  204. ImageBlit(src_surface.second, dst_surface.second, copy_config);
  205. dst_surface.first->MarkAsModified(true, Tick());
  206. }
  207. TSurface TryFindFramebufferSurface(const u8* host_ptr) {
  208. const CacheAddr cache_addr = ToCacheAddr(host_ptr);
  209. if (!cache_addr) {
  210. return nullptr;
  211. }
  212. const CacheAddr page = cache_addr >> registry_page_bits;
  213. std::vector<TSurface>& list = registry[page];
  214. for (auto& surface : list) {
  215. if (surface->GetCacheAddr() == cache_addr) {
  216. return surface;
  217. }
  218. }
  219. return nullptr;
  220. }
  221. u64 Tick() {
  222. return ++ticks;
  223. }
  224. protected:
  225. TextureCache(Core::System& system, VideoCore::RasterizerInterface& rasterizer)
  226. : system{system}, rasterizer{rasterizer} {
  227. for (std::size_t i = 0; i < Tegra::Engines::Maxwell3D::Regs::NumRenderTargets; i++) {
  228. SetEmptyColorBuffer(i);
  229. }
  230. SetEmptyDepthBuffer();
  231. staging_cache.SetSize(2);
  232. const auto make_siblings = [this](PixelFormat a, PixelFormat b) {
  233. siblings_table[static_cast<std::size_t>(a)] = b;
  234. siblings_table[static_cast<std::size_t>(b)] = a;
  235. };
  236. std::fill(siblings_table.begin(), siblings_table.end(), PixelFormat::Invalid);
  237. make_siblings(PixelFormat::Z16, PixelFormat::R16U);
  238. make_siblings(PixelFormat::Z32F, PixelFormat::R32F);
  239. make_siblings(PixelFormat::Z32FS8, PixelFormat::RG32F);
  240. sampled_textures.reserve(64);
  241. }
  242. ~TextureCache() = default;
  243. virtual TSurface CreateSurface(GPUVAddr gpu_addr, const SurfaceParams& params) = 0;
  244. virtual void ImageCopy(TSurface& src_surface, TSurface& dst_surface,
  245. const CopyParams& copy_params) = 0;
  246. virtual void ImageBlit(TView& src_view, TView& dst_view,
  247. const Tegra::Engines::Fermi2D::Config& copy_config) = 0;
  248. // Depending on the backend, a buffer copy can be slow as it means deoptimizing the texture
  249. // and reading it from a separate buffer.
  250. virtual void BufferCopy(TSurface& src_surface, TSurface& dst_surface) = 0;
  251. void ManageRenderTargetUnregister(TSurface& surface) {
  252. auto& maxwell3d = system.GPU().Maxwell3D();
  253. const u32 index = surface->GetRenderTarget();
  254. if (index == DEPTH_RT) {
  255. maxwell3d.dirty.depth_buffer = true;
  256. } else {
  257. maxwell3d.dirty.render_target[index] = true;
  258. }
  259. maxwell3d.dirty.render_settings = true;
  260. }
  261. void Register(TSurface surface) {
  262. const GPUVAddr gpu_addr = surface->GetGpuAddr();
  263. const CacheAddr cache_ptr = ToCacheAddr(system.GPU().MemoryManager().GetPointer(gpu_addr));
  264. const std::size_t size = surface->GetSizeInBytes();
  265. const std::optional<VAddr> cpu_addr =
  266. system.GPU().MemoryManager().GpuToCpuAddress(gpu_addr);
  267. if (!cache_ptr || !cpu_addr) {
  268. LOG_CRITICAL(HW_GPU, "Failed to register surface with unmapped gpu_address 0x{:016x}",
  269. gpu_addr);
  270. return;
  271. }
  272. const bool continuous = system.GPU().MemoryManager().IsBlockContinuous(gpu_addr, size);
  273. surface->MarkAsContinuous(continuous);
  274. surface->SetCacheAddr(cache_ptr);
  275. surface->SetCpuAddr(*cpu_addr);
  276. RegisterInnerCache(surface);
  277. surface->MarkAsRegistered(true);
  278. rasterizer.UpdatePagesCachedCount(*cpu_addr, size, 1);
  279. }
  280. void Unregister(TSurface surface) {
  281. if (guard_render_targets && surface->IsProtected()) {
  282. return;
  283. }
  284. if (!guard_render_targets && surface->IsRenderTarget()) {
  285. ManageRenderTargetUnregister(surface);
  286. }
  287. const std::size_t size = surface->GetSizeInBytes();
  288. const VAddr cpu_addr = surface->GetCpuAddr();
  289. rasterizer.UpdatePagesCachedCount(cpu_addr, size, -1);
  290. UnregisterInnerCache(surface);
  291. surface->MarkAsRegistered(false);
  292. ReserveSurface(surface->GetSurfaceParams(), surface);
  293. }
  294. TSurface GetUncachedSurface(const GPUVAddr gpu_addr, const SurfaceParams& params) {
  295. if (const auto surface = TryGetReservedSurface(params); surface) {
  296. surface->SetGpuAddr(gpu_addr);
  297. return surface;
  298. }
  299. // No reserved surface available, create a new one and reserve it
  300. auto new_surface{CreateSurface(gpu_addr, params)};
  301. return new_surface;
  302. }
  303. std::pair<TSurface, TView> GetFermiSurface(
  304. const Tegra::Engines::Fermi2D::Regs::Surface& config) {
  305. SurfaceParams params = SurfaceParams::CreateForFermiCopySurface(config);
  306. const GPUVAddr gpu_addr = config.Address();
  307. return GetSurface(gpu_addr, params, true, false);
  308. }
  309. Core::System& system;
  310. private:
  311. enum class RecycleStrategy : u32 {
  312. Ignore = 0,
  313. Flush = 1,
  314. BufferCopy = 3,
  315. };
  316. enum class DeductionType : u32 {
  317. DeductionComplete,
  318. DeductionIncomplete,
  319. DeductionFailed,
  320. };
  321. struct Deduction {
  322. DeductionType type{DeductionType::DeductionFailed};
  323. TSurface surface{};
  324. bool Failed() const {
  325. return type == DeductionType::DeductionFailed;
  326. }
  327. bool Incomplete() const {
  328. return type == DeductionType::DeductionIncomplete;
  329. }
  330. bool IsDepth() const {
  331. return surface->GetSurfaceParams().IsPixelFormatZeta();
  332. }
  333. };
  334. /**
  335. * Takes care of selecting a proper strategy to deal with a texture recycle.
  336. *
  337. * @param overlaps The overlapping surfaces registered in the cache.
  338. * @param params The parameters on the new surface.
  339. * @param gpu_addr The starting address of the new surface.
  340. * @param untopological Indicates to the recycler that the texture has no way
  341. * to match the overlaps due to topological reasons.
  342. **/
  343. RecycleStrategy PickStrategy(std::vector<TSurface>& overlaps, const SurfaceParams& params,
  344. const GPUVAddr gpu_addr, const MatchTopologyResult untopological) {
  345. if (Settings::values.use_accurate_gpu_emulation) {
  346. return RecycleStrategy::Flush;
  347. }
  348. // 3D Textures decision
  349. if (params.block_depth > 1 || params.target == SurfaceTarget::Texture3D) {
  350. return RecycleStrategy::Flush;
  351. }
  352. for (const auto& s : overlaps) {
  353. const auto& s_params = s->GetSurfaceParams();
  354. if (s_params.block_depth > 1 || s_params.target == SurfaceTarget::Texture3D) {
  355. return RecycleStrategy::Flush;
  356. }
  357. }
  358. // Untopological decision
  359. if (untopological == MatchTopologyResult::CompressUnmatch) {
  360. return RecycleStrategy::Flush;
  361. }
  362. if (untopological == MatchTopologyResult::FullMatch && !params.is_tiled) {
  363. return RecycleStrategy::Flush;
  364. }
  365. return RecycleStrategy::Ignore;
  366. }
  367. /**
  368. * Used to decide what to do with textures we can't resolve in the cache It has 2 implemented
  369. * strategies: Ignore and Flush.
  370. *
  371. * - Ignore: Just unregisters all the overlaps and loads the new texture.
  372. * - Flush: Flushes all the overlaps into memory and loads the new surface from that data.
  373. *
  374. * @param overlaps The overlapping surfaces registered in the cache.
  375. * @param params The parameters for the new surface.
  376. * @param gpu_addr The starting address of the new surface.
  377. * @param preserve_contents Indicates that the new surface should be loaded from memory or left
  378. * blank.
  379. * @param untopological Indicates to the recycler that the texture has no way to match the
  380. * overlaps due to topological reasons.
  381. **/
  382. std::pair<TSurface, TView> RecycleSurface(std::vector<TSurface>& overlaps,
  383. const SurfaceParams& params, const GPUVAddr gpu_addr,
  384. const bool preserve_contents,
  385. const MatchTopologyResult untopological) {
  386. const bool do_load = preserve_contents && Settings::values.use_accurate_gpu_emulation;
  387. for (auto& surface : overlaps) {
  388. Unregister(surface);
  389. }
  390. switch (PickStrategy(overlaps, params, gpu_addr, untopological)) {
  391. case RecycleStrategy::Ignore: {
  392. return InitializeSurface(gpu_addr, params, do_load);
  393. }
  394. case RecycleStrategy::Flush: {
  395. std::sort(overlaps.begin(), overlaps.end(),
  396. [](const TSurface& a, const TSurface& b) -> bool {
  397. return a->GetModificationTick() < b->GetModificationTick();
  398. });
  399. for (auto& surface : overlaps) {
  400. FlushSurface(surface);
  401. }
  402. return InitializeSurface(gpu_addr, params, preserve_contents);
  403. }
  404. case RecycleStrategy::BufferCopy: {
  405. auto new_surface = GetUncachedSurface(gpu_addr, params);
  406. BufferCopy(overlaps[0], new_surface);
  407. return {new_surface, new_surface->GetMainView()};
  408. }
  409. default: {
  410. UNIMPLEMENTED_MSG("Unimplemented Texture Cache Recycling Strategy!");
  411. return InitializeSurface(gpu_addr, params, do_load);
  412. }
  413. }
  414. }
  415. /**
  416. * Takes a single surface and recreates into another that may differ in
  417. * format, target or width alignment.
  418. *
  419. * @param current_surface The registered surface in the cache which we want to convert.
  420. * @param params The new surface params which we'll use to recreate the surface.
  421. * @param is_render Whether or not the surface is a render target.
  422. **/
  423. std::pair<TSurface, TView> RebuildSurface(TSurface current_surface, const SurfaceParams& params,
  424. bool is_render) {
  425. const auto gpu_addr = current_surface->GetGpuAddr();
  426. const auto& cr_params = current_surface->GetSurfaceParams();
  427. TSurface new_surface;
  428. if (cr_params.pixel_format != params.pixel_format && !is_render &&
  429. GetSiblingFormat(cr_params.pixel_format) == params.pixel_format) {
  430. SurfaceParams new_params = params;
  431. new_params.pixel_format = cr_params.pixel_format;
  432. new_params.type = cr_params.type;
  433. new_surface = GetUncachedSurface(gpu_addr, new_params);
  434. } else {
  435. new_surface = GetUncachedSurface(gpu_addr, params);
  436. }
  437. const auto& final_params = new_surface->GetSurfaceParams();
  438. if (cr_params.type != final_params.type) {
  439. BufferCopy(current_surface, new_surface);
  440. } else {
  441. std::vector<CopyParams> bricks = current_surface->BreakDown(final_params);
  442. for (auto& brick : bricks) {
  443. ImageCopy(current_surface, new_surface, brick);
  444. }
  445. }
  446. Unregister(current_surface);
  447. Register(new_surface);
  448. new_surface->MarkAsModified(current_surface->IsModified(), Tick());
  449. return {new_surface, new_surface->GetMainView()};
  450. }
  451. /**
  452. * Takes a single surface and checks with the new surface's params if it's an exact
  453. * match, we return the main view of the registered surface. If its formats don't
  454. * match, we rebuild the surface. We call this last method a `Mirage`. If formats
  455. * match but the targets don't, we create an overview View of the registered surface.
  456. *
  457. * @param current_surface The registered surface in the cache which we want to convert.
  458. * @param params The new surface params which we want to check.
  459. * @param is_render Whether or not the surface is a render target.
  460. **/
  461. std::pair<TSurface, TView> ManageStructuralMatch(TSurface current_surface,
  462. const SurfaceParams& params, bool is_render) {
  463. const bool is_mirage = !current_surface->MatchFormat(params.pixel_format);
  464. const bool matches_target = current_surface->MatchTarget(params.target);
  465. const auto match_check = [&]() -> std::pair<TSurface, TView> {
  466. if (matches_target) {
  467. return {current_surface, current_surface->GetMainView()};
  468. }
  469. return {current_surface, current_surface->EmplaceOverview(params)};
  470. };
  471. if (!is_mirage) {
  472. return match_check();
  473. }
  474. if (!is_render && GetSiblingFormat(current_surface->GetFormat()) == params.pixel_format) {
  475. return match_check();
  476. }
  477. return RebuildSurface(current_surface, params, is_render);
  478. }
  479. /**
  480. * Unlike RebuildSurface where we know whether or not registered surfaces match the candidate
  481. * in some way, we have no guarantees here. We try to see if the overlaps are sublayers/mipmaps
  482. * of the new surface, if they all match we end up recreating a surface for them,
  483. * else we return nothing.
  484. *
  485. * @param overlaps The overlapping surfaces registered in the cache.
  486. * @param params The parameters on the new surface.
  487. * @param gpu_addr The starting address of the new surface.
  488. **/
  489. std::optional<std::pair<TSurface, TView>> TryReconstructSurface(std::vector<TSurface>& overlaps,
  490. const SurfaceParams& params,
  491. const GPUVAddr gpu_addr) {
  492. if (params.target == SurfaceTarget::Texture3D) {
  493. return {};
  494. }
  495. bool modified = false;
  496. TSurface new_surface = GetUncachedSurface(gpu_addr, params);
  497. u32 passed_tests = 0;
  498. for (auto& surface : overlaps) {
  499. const SurfaceParams& src_params = surface->GetSurfaceParams();
  500. if (src_params.is_layered || src_params.num_levels > 1) {
  501. // We send this cases to recycle as they are more complex to handle
  502. return {};
  503. }
  504. const std::size_t candidate_size = surface->GetSizeInBytes();
  505. auto mipmap_layer{new_surface->GetLayerMipmap(surface->GetGpuAddr())};
  506. if (!mipmap_layer) {
  507. continue;
  508. }
  509. const auto [layer, mipmap] = *mipmap_layer;
  510. if (new_surface->GetMipmapSize(mipmap) != candidate_size) {
  511. continue;
  512. }
  513. modified |= surface->IsModified();
  514. // Now we got all the data set up
  515. const u32 width = SurfaceParams::IntersectWidth(src_params, params, 0, mipmap);
  516. const u32 height = SurfaceParams::IntersectHeight(src_params, params, 0, mipmap);
  517. const CopyParams copy_params(0, 0, 0, 0, 0, layer, 0, mipmap, width, height, 1);
  518. passed_tests++;
  519. ImageCopy(surface, new_surface, copy_params);
  520. }
  521. if (passed_tests == 0) {
  522. return {};
  523. // In Accurate GPU all tests should pass, else we recycle
  524. } else if (Settings::values.use_accurate_gpu_emulation && passed_tests != overlaps.size()) {
  525. return {};
  526. }
  527. for (const auto& surface : overlaps) {
  528. Unregister(surface);
  529. }
  530. new_surface->MarkAsModified(modified, Tick());
  531. Register(new_surface);
  532. return {{new_surface, new_surface->GetMainView()}};
  533. }
  534. /**
  535. * Gets the starting address and parameters of a candidate surface and tries
  536. * to find a matching surface within the cache. This is done in 3 big steps:
  537. *
  538. * 1. Check the 1st Level Cache in order to find an exact match, if we fail, we move to step 2.
  539. *
  540. * 2. Check if there are any overlaps at all, if there are none, we just load the texture from
  541. * memory else we move to step 3.
  542. *
  543. * 3. Consists of figuring out the relationship between the candidate texture and the
  544. * overlaps. We divide the scenarios depending if there's 1 or many overlaps. If
  545. * there's many, we just try to reconstruct a new surface out of them based on the
  546. * candidate's parameters, if we fail, we recycle. When there's only 1 overlap then we
  547. * have to check if the candidate is a view (layer/mipmap) of the overlap or if the
  548. * registered surface is a mipmap/layer of the candidate. In this last case we reconstruct
  549. * a new surface.
  550. *
  551. * @param gpu_addr The starting address of the candidate surface.
  552. * @param params The parameters on the candidate surface.
  553. * @param preserve_contents Indicates that the new surface should be loaded from memory or
  554. * left blank.
  555. * @param is_render Whether or not the surface is a render target.
  556. **/
  557. std::pair<TSurface, TView> GetSurface(const GPUVAddr gpu_addr, const SurfaceParams& params,
  558. bool preserve_contents, bool is_render) {
  559. const auto host_ptr{system.GPU().MemoryManager().GetPointer(gpu_addr)};
  560. const auto cache_addr{ToCacheAddr(host_ptr)};
  561. // Step 0: guarantee a valid surface
  562. if (!cache_addr) {
  563. // Return a null surface if it's invalid
  564. SurfaceParams new_params = params;
  565. new_params.width = 1;
  566. new_params.height = 1;
  567. new_params.depth = 1;
  568. new_params.block_height = 0;
  569. new_params.block_depth = 0;
  570. return InitializeSurface(gpu_addr, new_params, false);
  571. }
  572. // Step 1
  573. // Check Level 1 Cache for a fast structural match. If candidate surface
  574. // matches at certain level we are pretty much done.
  575. if (const auto iter = l1_cache.find(cache_addr); iter != l1_cache.end()) {
  576. TSurface& current_surface = iter->second;
  577. const auto topological_result = current_surface->MatchesTopology(params);
  578. if (topological_result != MatchTopologyResult::FullMatch) {
  579. std::vector<TSurface> overlaps{current_surface};
  580. return RecycleSurface(overlaps, params, gpu_addr, preserve_contents,
  581. topological_result);
  582. }
  583. const auto struct_result = current_surface->MatchesStructure(params);
  584. if (struct_result != MatchStructureResult::None &&
  585. (params.target != SurfaceTarget::Texture3D ||
  586. current_surface->MatchTarget(params.target))) {
  587. if (struct_result == MatchStructureResult::FullMatch) {
  588. return ManageStructuralMatch(current_surface, params, is_render);
  589. } else {
  590. return RebuildSurface(current_surface, params, is_render);
  591. }
  592. }
  593. }
  594. // Step 2
  595. // Obtain all possible overlaps in the memory region
  596. const std::size_t candidate_size = params.GetGuestSizeInBytes();
  597. auto overlaps{GetSurfacesInRegion(cache_addr, candidate_size)};
  598. // If none are found, we are done. we just load the surface and create it.
  599. if (overlaps.empty()) {
  600. return InitializeSurface(gpu_addr, params, preserve_contents);
  601. }
  602. // Step 3
  603. // Now we need to figure the relationship between the texture and its overlaps
  604. // we do a topological test to ensure we can find some relationship. If it fails
  605. // immediately recycle the texture
  606. for (const auto& surface : overlaps) {
  607. const auto topological_result = surface->MatchesTopology(params);
  608. if (topological_result != MatchTopologyResult::FullMatch) {
  609. return RecycleSurface(overlaps, params, gpu_addr, preserve_contents,
  610. topological_result);
  611. }
  612. }
  613. // Split cases between 1 overlap or many.
  614. if (overlaps.size() == 1) {
  615. TSurface current_surface = overlaps[0];
  616. // First check if the surface is within the overlap. If not, it means
  617. // two things either the candidate surface is a supertexture of the overlap
  618. // or they don't match in any known way.
  619. if (!current_surface->IsInside(gpu_addr, gpu_addr + candidate_size)) {
  620. if (current_surface->GetGpuAddr() == gpu_addr) {
  621. std::optional<std::pair<TSurface, TView>> view =
  622. TryReconstructSurface(overlaps, params, gpu_addr);
  623. if (view) {
  624. return *view;
  625. }
  626. }
  627. return RecycleSurface(overlaps, params, gpu_addr, preserve_contents,
  628. MatchTopologyResult::FullMatch);
  629. }
  630. // Now we check if the candidate is a mipmap/layer of the overlap
  631. std::optional<TView> view =
  632. current_surface->EmplaceView(params, gpu_addr, candidate_size);
  633. if (view) {
  634. const bool is_mirage = !current_surface->MatchFormat(params.pixel_format);
  635. if (is_mirage) {
  636. // On a mirage view, we need to recreate the surface under this new view
  637. // and then obtain a view again.
  638. SurfaceParams new_params = current_surface->GetSurfaceParams();
  639. const u32 wh = SurfaceParams::ConvertWidth(
  640. new_params.width, new_params.pixel_format, params.pixel_format);
  641. const u32 hh = SurfaceParams::ConvertHeight(
  642. new_params.height, new_params.pixel_format, params.pixel_format);
  643. new_params.width = wh;
  644. new_params.height = hh;
  645. new_params.pixel_format = params.pixel_format;
  646. std::pair<TSurface, TView> pair =
  647. RebuildSurface(current_surface, new_params, is_render);
  648. std::optional<TView> mirage_view =
  649. pair.first->EmplaceView(params, gpu_addr, candidate_size);
  650. if (mirage_view)
  651. return {pair.first, *mirage_view};
  652. return RecycleSurface(overlaps, params, gpu_addr, preserve_contents,
  653. MatchTopologyResult::FullMatch);
  654. }
  655. return {current_surface, *view};
  656. }
  657. } else {
  658. // If there are many overlaps, odds are they are subtextures of the candidate
  659. // surface. We try to construct a new surface based on the candidate parameters,
  660. // using the overlaps. If a single overlap fails, this will fail.
  661. std::optional<std::pair<TSurface, TView>> view =
  662. TryReconstructSurface(overlaps, params, gpu_addr);
  663. if (view) {
  664. return *view;
  665. }
  666. }
  667. // We failed all the tests, recycle the overlaps into a new texture.
  668. return RecycleSurface(overlaps, params, gpu_addr, preserve_contents,
  669. MatchTopologyResult::FullMatch);
  670. }
  671. /**
  672. * Gets the starting address and parameters of a candidate surface and tries to find a
  673. * matching surface within the cache that's similar to it. If there are many textures
  674. * or the texture found if entirely incompatible, it will fail. If no texture is found, the
  675. * blit will be unsuccessful.
  676. *
  677. * @param gpu_addr The starting address of the candidate surface.
  678. * @param params The parameters on the candidate surface.
  679. **/
  680. Deduction DeduceSurface(const GPUVAddr gpu_addr, const SurfaceParams& params) {
  681. const auto host_ptr{system.GPU().MemoryManager().GetPointer(gpu_addr)};
  682. const auto cache_addr{ToCacheAddr(host_ptr)};
  683. if (!cache_addr) {
  684. Deduction result{};
  685. result.type = DeductionType::DeductionFailed;
  686. return result;
  687. }
  688. if (const auto iter = l1_cache.find(cache_addr); iter != l1_cache.end()) {
  689. TSurface& current_surface = iter->second;
  690. const auto topological_result = current_surface->MatchesTopology(params);
  691. if (topological_result != MatchTopologyResult::FullMatch) {
  692. Deduction result{};
  693. result.type = DeductionType::DeductionFailed;
  694. return result;
  695. }
  696. const auto struct_result = current_surface->MatchesStructure(params);
  697. if (struct_result != MatchStructureResult::None &&
  698. current_surface->MatchTarget(params.target)) {
  699. Deduction result{};
  700. result.type = DeductionType::DeductionComplete;
  701. result.surface = current_surface;
  702. return result;
  703. }
  704. }
  705. const std::size_t candidate_size = params.GetGuestSizeInBytes();
  706. auto overlaps{GetSurfacesInRegion(cache_addr, candidate_size)};
  707. if (overlaps.empty()) {
  708. Deduction result{};
  709. result.type = DeductionType::DeductionIncomplete;
  710. return result;
  711. }
  712. if (overlaps.size() > 1) {
  713. Deduction result{};
  714. result.type = DeductionType::DeductionFailed;
  715. return result;
  716. } else {
  717. Deduction result{};
  718. result.type = DeductionType::DeductionComplete;
  719. result.surface = overlaps[0];
  720. return result;
  721. }
  722. }
  723. /**
  724. * Gets the a source and destination starting address and parameters,
  725. * and tries to deduce if they are supposed to be depth textures. If so, their
  726. * parameters are modified and fixed into so.
  727. *
  728. * @param src_params The parameters of the candidate surface.
  729. * @param dst_params The parameters of the destination surface.
  730. * @param src_gpu_addr The starting address of the candidate surface.
  731. * @param dst_gpu_addr The starting address of the destination surface.
  732. **/
  733. void DeduceBestBlit(SurfaceParams& src_params, SurfaceParams& dst_params,
  734. const GPUVAddr src_gpu_addr, const GPUVAddr dst_gpu_addr) {
  735. auto deduced_src = DeduceSurface(src_gpu_addr, src_params);
  736. auto deduced_dst = DeduceSurface(src_gpu_addr, src_params);
  737. if (deduced_src.Failed() || deduced_dst.Failed()) {
  738. return;
  739. }
  740. const bool incomplete_src = deduced_src.Incomplete();
  741. const bool incomplete_dst = deduced_dst.Incomplete();
  742. if (incomplete_src && incomplete_dst) {
  743. return;
  744. }
  745. const bool any_incomplete = incomplete_src || incomplete_dst;
  746. if (!any_incomplete) {
  747. if (!(deduced_src.IsDepth() && deduced_dst.IsDepth())) {
  748. return;
  749. }
  750. } else {
  751. if (incomplete_src && !(deduced_dst.IsDepth())) {
  752. return;
  753. }
  754. if (incomplete_dst && !(deduced_src.IsDepth())) {
  755. return;
  756. }
  757. }
  758. const auto inherit_format = [](SurfaceParams& to, TSurface from) {
  759. const SurfaceParams& params = from->GetSurfaceParams();
  760. to.pixel_format = params.pixel_format;
  761. to.type = params.type;
  762. };
  763. // Now we got the cases where one or both is Depth and the other is not known
  764. if (!incomplete_src) {
  765. inherit_format(src_params, deduced_src.surface);
  766. } else {
  767. inherit_format(src_params, deduced_dst.surface);
  768. }
  769. if (!incomplete_dst) {
  770. inherit_format(dst_params, deduced_dst.surface);
  771. } else {
  772. inherit_format(dst_params, deduced_src.surface);
  773. }
  774. }
  775. std::pair<TSurface, TView> InitializeSurface(GPUVAddr gpu_addr, const SurfaceParams& params,
  776. bool preserve_contents) {
  777. auto new_surface{GetUncachedSurface(gpu_addr, params)};
  778. Register(new_surface);
  779. if (preserve_contents) {
  780. LoadSurface(new_surface);
  781. }
  782. return {new_surface, new_surface->GetMainView()};
  783. }
  784. void LoadSurface(const TSurface& surface) {
  785. staging_cache.GetBuffer(0).resize(surface->GetHostSizeInBytes());
  786. surface->LoadBuffer(system.GPU().MemoryManager(), staging_cache);
  787. surface->UploadTexture(staging_cache.GetBuffer(0));
  788. surface->MarkAsModified(false, Tick());
  789. }
  790. void FlushSurface(const TSurface& surface) {
  791. if (!surface->IsModified()) {
  792. return;
  793. }
  794. staging_cache.GetBuffer(0).resize(surface->GetHostSizeInBytes());
  795. surface->DownloadTexture(staging_cache.GetBuffer(0));
  796. surface->FlushBuffer(system.GPU().MemoryManager(), staging_cache);
  797. surface->MarkAsModified(false, Tick());
  798. }
  799. void RegisterInnerCache(TSurface& surface) {
  800. const CacheAddr cache_addr = surface->GetCacheAddr();
  801. CacheAddr start = cache_addr >> registry_page_bits;
  802. const CacheAddr end = (surface->GetCacheAddrEnd() - 1) >> registry_page_bits;
  803. l1_cache[cache_addr] = surface;
  804. while (start <= end) {
  805. registry[start].push_back(surface);
  806. start++;
  807. }
  808. }
  809. void UnregisterInnerCache(TSurface& surface) {
  810. const CacheAddr cache_addr = surface->GetCacheAddr();
  811. CacheAddr start = cache_addr >> registry_page_bits;
  812. const CacheAddr end = (surface->GetCacheAddrEnd() - 1) >> registry_page_bits;
  813. l1_cache.erase(cache_addr);
  814. while (start <= end) {
  815. auto& reg{registry[start]};
  816. reg.erase(std::find(reg.begin(), reg.end(), surface));
  817. start++;
  818. }
  819. }
  820. std::vector<TSurface> GetSurfacesInRegion(const CacheAddr cache_addr, const std::size_t size) {
  821. if (size == 0) {
  822. return {};
  823. }
  824. const CacheAddr cache_addr_end = cache_addr + size;
  825. CacheAddr start = cache_addr >> registry_page_bits;
  826. const CacheAddr end = (cache_addr_end - 1) >> registry_page_bits;
  827. std::vector<TSurface> surfaces;
  828. while (start <= end) {
  829. std::vector<TSurface>& list = registry[start];
  830. for (auto& surface : list) {
  831. if (!surface->IsPicked() && surface->Overlaps(cache_addr, cache_addr_end)) {
  832. surface->MarkAsPicked(true);
  833. surfaces.push_back(surface);
  834. }
  835. }
  836. start++;
  837. }
  838. for (auto& surface : surfaces) {
  839. surface->MarkAsPicked(false);
  840. }
  841. return surfaces;
  842. }
  843. void ReserveSurface(const SurfaceParams& params, TSurface surface) {
  844. surface_reserve[params].push_back(std::move(surface));
  845. }
  846. TSurface TryGetReservedSurface(const SurfaceParams& params) {
  847. auto search{surface_reserve.find(params)};
  848. if (search == surface_reserve.end()) {
  849. return {};
  850. }
  851. for (auto& surface : search->second) {
  852. if (!surface->IsRegistered()) {
  853. return surface;
  854. }
  855. }
  856. return {};
  857. }
  858. constexpr PixelFormat GetSiblingFormat(PixelFormat format) const {
  859. return siblings_table[static_cast<std::size_t>(format)];
  860. }
  861. struct FramebufferTargetInfo {
  862. TSurface target;
  863. TView view;
  864. };
  865. VideoCore::RasterizerInterface& rasterizer;
  866. FormatLookupTable format_lookup_table;
  867. u64 ticks{};
  868. // Guards the cache for protection conflicts.
  869. bool guard_render_targets{};
  870. bool guard_samplers{};
  871. // The siblings table is for formats that can inter exchange with one another
  872. // without causing issues. This is only valid when a conflict occurs on a non
  873. // rendering use.
  874. std::array<PixelFormat, static_cast<std::size_t>(PixelFormat::Max)> siblings_table;
  875. // The internal Cache is different for the Texture Cache. It's based on buckets
  876. // of 1MB. This fits better for the purpose of this cache as textures are normaly
  877. // large in size.
  878. static constexpr u64 registry_page_bits{20};
  879. static constexpr u64 registry_page_size{1 << registry_page_bits};
  880. std::unordered_map<CacheAddr, std::vector<TSurface>> registry;
  881. static constexpr u32 DEPTH_RT = 8;
  882. static constexpr u32 NO_RT = 0xFFFFFFFF;
  883. // The L1 Cache is used for fast texture lookup before checking the overlaps
  884. // This avoids calculating size and other stuffs.
  885. std::unordered_map<CacheAddr, TSurface> l1_cache;
  886. /// The surface reserve is a "backup" cache, this is where we put unique surfaces that have
  887. /// previously been used. This is to prevent surfaces from being constantly created and
  888. /// destroyed when used with different surface parameters.
  889. std::unordered_map<SurfaceParams, std::vector<TSurface>> surface_reserve;
  890. std::array<FramebufferTargetInfo, Tegra::Engines::Maxwell3D::Regs::NumRenderTargets>
  891. render_targets;
  892. FramebufferTargetInfo depth_buffer;
  893. std::vector<TSurface> sampled_textures;
  894. StagingCache staging_cache;
  895. std::recursive_mutex mutex;
  896. };
  897. } // namespace VideoCommon