shader_environment.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. // Copyright 2021 yuzu Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <algorithm>
  5. #include <filesystem>
  6. #include <fstream>
  7. #include <memory>
  8. #include <optional>
  9. #include <utility>
  10. #include "common/assert.h"
  11. #include "common/cityhash.h"
  12. #include "common/common_types.h"
  13. #include "common/div_ceil.h"
  14. #include "common/fs/fs.h"
  15. #include "common/logging/log.h"
  16. #include "shader_recompiler/environment.h"
  17. #include "video_core/engines/kepler_compute.h"
  18. #include "video_core/memory_manager.h"
  19. #include "video_core/shader_environment.h"
  20. #include "video_core/textures/texture.h"
  21. namespace VideoCommon {
  22. constexpr std::array<char, 8> MAGIC_NUMBER{'y', 'u', 'z', 'u', 'c', 'a', 'c', 'h'};
  23. constexpr size_t INST_SIZE = sizeof(u64);
  24. using Maxwell = Tegra::Engines::Maxwell3D::Regs;
  25. static u64 MakeCbufKey(u32 index, u32 offset) {
  26. return (static_cast<u64>(index) << 32) | offset;
  27. }
  28. static Shader::TextureType ConvertType(const Tegra::Texture::TICEntry& entry) {
  29. switch (entry.texture_type) {
  30. case Tegra::Texture::TextureType::Texture1D:
  31. return Shader::TextureType::Color1D;
  32. case Tegra::Texture::TextureType::Texture2D:
  33. case Tegra::Texture::TextureType::Texture2DNoMipmap:
  34. return Shader::TextureType::Color2D;
  35. case Tegra::Texture::TextureType::Texture3D:
  36. return Shader::TextureType::Color3D;
  37. case Tegra::Texture::TextureType::TextureCubemap:
  38. return Shader::TextureType::ColorCube;
  39. case Tegra::Texture::TextureType::Texture1DArray:
  40. return Shader::TextureType::ColorArray1D;
  41. case Tegra::Texture::TextureType::Texture2DArray:
  42. return Shader::TextureType::ColorArray2D;
  43. case Tegra::Texture::TextureType::Texture1DBuffer:
  44. return Shader::TextureType::Buffer;
  45. case Tegra::Texture::TextureType::TextureCubeArray:
  46. return Shader::TextureType::ColorArrayCube;
  47. default:
  48. throw Shader::NotImplementedException("Unknown texture type");
  49. }
  50. }
  51. GenericEnvironment::GenericEnvironment(Tegra::MemoryManager& gpu_memory_, GPUVAddr program_base_,
  52. u32 start_address_)
  53. : gpu_memory{&gpu_memory_}, program_base{program_base_} {
  54. start_address = start_address_;
  55. }
  56. GenericEnvironment::~GenericEnvironment() = default;
  57. u32 GenericEnvironment::TextureBoundBuffer() const {
  58. return texture_bound;
  59. }
  60. u32 GenericEnvironment::LocalMemorySize() const {
  61. return local_memory_size;
  62. }
  63. u32 GenericEnvironment::SharedMemorySize() const {
  64. return shared_memory_size;
  65. }
  66. std::array<u32, 3> GenericEnvironment::WorkgroupSize() const {
  67. return workgroup_size;
  68. }
  69. u64 GenericEnvironment::ReadInstruction(u32 address) {
  70. read_lowest = std::min(read_lowest, address);
  71. read_highest = std::max(read_highest, address);
  72. if (address >= cached_lowest && address < cached_highest) {
  73. return code[(address - cached_lowest) / INST_SIZE];
  74. }
  75. has_unbound_instructions = true;
  76. return gpu_memory->Read<u64>(program_base + address);
  77. }
  78. std::optional<u64> GenericEnvironment::Analyze() {
  79. const std::optional<u64> size{TryFindSize()};
  80. if (!size) {
  81. return std::nullopt;
  82. }
  83. cached_lowest = start_address;
  84. cached_highest = start_address + static_cast<u32>(*size);
  85. return Common::CityHash64(reinterpret_cast<const char*>(code.data()), *size);
  86. }
  87. void GenericEnvironment::SetCachedSize(size_t size_bytes) {
  88. cached_lowest = start_address;
  89. cached_highest = start_address + static_cast<u32>(size_bytes);
  90. code.resize(CachedSize());
  91. gpu_memory->ReadBlock(program_base + cached_lowest, code.data(), code.size() * sizeof(u64));
  92. }
  93. size_t GenericEnvironment::CachedSize() const noexcept {
  94. return cached_highest - cached_lowest + INST_SIZE;
  95. }
  96. size_t GenericEnvironment::ReadSize() const noexcept {
  97. return read_highest - read_lowest + INST_SIZE;
  98. }
  99. bool GenericEnvironment::CanBeSerialized() const noexcept {
  100. return !has_unbound_instructions;
  101. }
  102. u64 GenericEnvironment::CalculateHash() const {
  103. const size_t size{ReadSize()};
  104. const auto data{std::make_unique<char[]>(size)};
  105. gpu_memory->ReadBlock(program_base + read_lowest, data.get(), size);
  106. return Common::CityHash64(data.get(), size);
  107. }
  108. void GenericEnvironment::Serialize(std::ofstream& file) const {
  109. const u64 code_size{static_cast<u64>(CachedSize())};
  110. const u64 num_texture_types{static_cast<u64>(texture_types.size())};
  111. const u64 num_cbuf_values{static_cast<u64>(cbuf_values.size())};
  112. file.write(reinterpret_cast<const char*>(&code_size), sizeof(code_size))
  113. .write(reinterpret_cast<const char*>(&num_texture_types), sizeof(num_texture_types))
  114. .write(reinterpret_cast<const char*>(&num_cbuf_values), sizeof(num_cbuf_values))
  115. .write(reinterpret_cast<const char*>(&local_memory_size), sizeof(local_memory_size))
  116. .write(reinterpret_cast<const char*>(&texture_bound), sizeof(texture_bound))
  117. .write(reinterpret_cast<const char*>(&start_address), sizeof(start_address))
  118. .write(reinterpret_cast<const char*>(&cached_lowest), sizeof(cached_lowest))
  119. .write(reinterpret_cast<const char*>(&cached_highest), sizeof(cached_highest))
  120. .write(reinterpret_cast<const char*>(&stage), sizeof(stage))
  121. .write(reinterpret_cast<const char*>(code.data()), code_size);
  122. for (const auto [key, type] : texture_types) {
  123. file.write(reinterpret_cast<const char*>(&key), sizeof(key))
  124. .write(reinterpret_cast<const char*>(&type), sizeof(type));
  125. }
  126. for (const auto [key, type] : cbuf_values) {
  127. file.write(reinterpret_cast<const char*>(&key), sizeof(key))
  128. .write(reinterpret_cast<const char*>(&type), sizeof(type));
  129. }
  130. if (stage == Shader::Stage::Compute) {
  131. file.write(reinterpret_cast<const char*>(&workgroup_size), sizeof(workgroup_size))
  132. .write(reinterpret_cast<const char*>(&shared_memory_size), sizeof(shared_memory_size));
  133. } else {
  134. file.write(reinterpret_cast<const char*>(&sph), sizeof(sph));
  135. if (stage == Shader::Stage::Geometry) {
  136. file.write(reinterpret_cast<const char*>(&gp_passthrough_mask),
  137. sizeof(gp_passthrough_mask));
  138. }
  139. }
  140. }
  141. std::optional<u64> GenericEnvironment::TryFindSize() {
  142. static constexpr size_t BLOCK_SIZE = 0x1000;
  143. static constexpr size_t MAXIMUM_SIZE = 0x100000;
  144. static constexpr u64 SELF_BRANCH_A = 0xE2400FFFFF87000FULL;
  145. static constexpr u64 SELF_BRANCH_B = 0xE2400FFFFF07000FULL;
  146. GPUVAddr guest_addr{program_base + start_address};
  147. size_t offset{0};
  148. size_t size{BLOCK_SIZE};
  149. while (size <= MAXIMUM_SIZE) {
  150. code.resize(size / INST_SIZE);
  151. u64* const data = code.data() + offset / INST_SIZE;
  152. gpu_memory->ReadBlock(guest_addr, data, BLOCK_SIZE);
  153. for (size_t index = 0; index < BLOCK_SIZE; index += INST_SIZE) {
  154. const u64 inst = data[index / INST_SIZE];
  155. if (inst == SELF_BRANCH_A || inst == SELF_BRANCH_B) {
  156. return offset + index;
  157. }
  158. }
  159. guest_addr += BLOCK_SIZE;
  160. size += BLOCK_SIZE;
  161. offset += BLOCK_SIZE;
  162. }
  163. return std::nullopt;
  164. }
  165. Shader::TextureType GenericEnvironment::ReadTextureTypeImpl(GPUVAddr tic_addr, u32 tic_limit,
  166. bool via_header_index, u32 raw) {
  167. const auto handle{Tegra::Texture::TexturePair(raw, via_header_index)};
  168. const GPUVAddr descriptor_addr{tic_addr + handle.first * sizeof(Tegra::Texture::TICEntry)};
  169. Tegra::Texture::TICEntry entry;
  170. gpu_memory->ReadBlock(descriptor_addr, &entry, sizeof(entry));
  171. const Shader::TextureType result{ConvertType(entry)};
  172. texture_types.emplace(raw, result);
  173. return result;
  174. }
  175. GraphicsEnvironment::GraphicsEnvironment(Tegra::Engines::Maxwell3D& maxwell3d_,
  176. Tegra::MemoryManager& gpu_memory_,
  177. Maxwell::ShaderProgram program, GPUVAddr program_base_,
  178. u32 start_address_)
  179. : GenericEnvironment{gpu_memory_, program_base_, start_address_}, maxwell3d{&maxwell3d_} {
  180. gpu_memory->ReadBlock(program_base + start_address, &sph, sizeof(sph));
  181. gp_passthrough_mask = maxwell3d->regs.gp_passthrough_mask;
  182. switch (program) {
  183. case Maxwell::ShaderProgram::VertexA:
  184. stage = Shader::Stage::VertexA;
  185. stage_index = 0;
  186. break;
  187. case Maxwell::ShaderProgram::VertexB:
  188. stage = Shader::Stage::VertexB;
  189. stage_index = 0;
  190. break;
  191. case Maxwell::ShaderProgram::TesselationControl:
  192. stage = Shader::Stage::TessellationControl;
  193. stage_index = 1;
  194. break;
  195. case Maxwell::ShaderProgram::TesselationEval:
  196. stage = Shader::Stage::TessellationEval;
  197. stage_index = 2;
  198. break;
  199. case Maxwell::ShaderProgram::Geometry:
  200. stage = Shader::Stage::Geometry;
  201. stage_index = 3;
  202. break;
  203. case Maxwell::ShaderProgram::Fragment:
  204. stage = Shader::Stage::Fragment;
  205. stage_index = 4;
  206. break;
  207. default:
  208. UNREACHABLE_MSG("Invalid program={}", program);
  209. break;
  210. }
  211. const u64 local_size{sph.LocalMemorySize()};
  212. ASSERT(local_size <= std::numeric_limits<u32>::max());
  213. local_memory_size = static_cast<u32>(local_size) + sph.common3.shader_local_memory_crs_size;
  214. texture_bound = maxwell3d->regs.tex_cb_index;
  215. }
  216. u32 GraphicsEnvironment::ReadCbufValue(u32 cbuf_index, u32 cbuf_offset) {
  217. const auto& cbuf{maxwell3d->state.shader_stages[stage_index].const_buffers[cbuf_index]};
  218. ASSERT(cbuf.enabled);
  219. u32 value{};
  220. if (cbuf_offset < cbuf.size) {
  221. value = gpu_memory->Read<u32>(cbuf.address + cbuf_offset);
  222. }
  223. cbuf_values.emplace(MakeCbufKey(cbuf_index, cbuf_offset), value);
  224. return value;
  225. }
  226. Shader::TextureType GraphicsEnvironment::ReadTextureType(u32 handle) {
  227. const auto& regs{maxwell3d->regs};
  228. const bool via_header_index{regs.sampler_index == Maxwell::SamplerIndex::ViaHeaderIndex};
  229. return ReadTextureTypeImpl(regs.tic.Address(), regs.tic.limit, via_header_index, handle);
  230. }
  231. ComputeEnvironment::ComputeEnvironment(Tegra::Engines::KeplerCompute& kepler_compute_,
  232. Tegra::MemoryManager& gpu_memory_, GPUVAddr program_base_,
  233. u32 start_address_)
  234. : GenericEnvironment{gpu_memory_, program_base_, start_address_}, kepler_compute{
  235. &kepler_compute_} {
  236. const auto& qmd{kepler_compute->launch_description};
  237. stage = Shader::Stage::Compute;
  238. local_memory_size = qmd.local_pos_alloc + qmd.local_crs_alloc;
  239. texture_bound = kepler_compute->regs.tex_cb_index;
  240. shared_memory_size = qmd.shared_alloc;
  241. workgroup_size = {qmd.block_dim_x, qmd.block_dim_y, qmd.block_dim_z};
  242. }
  243. u32 ComputeEnvironment::ReadCbufValue(u32 cbuf_index, u32 cbuf_offset) {
  244. const auto& qmd{kepler_compute->launch_description};
  245. ASSERT(((qmd.const_buffer_enable_mask.Value() >> cbuf_index) & 1) != 0);
  246. const auto& cbuf{qmd.const_buffer_config[cbuf_index]};
  247. u32 value{};
  248. if (cbuf_offset < cbuf.size) {
  249. value = gpu_memory->Read<u32>(cbuf.Address() + cbuf_offset);
  250. }
  251. cbuf_values.emplace(MakeCbufKey(cbuf_index, cbuf_offset), value);
  252. return value;
  253. }
  254. Shader::TextureType ComputeEnvironment::ReadTextureType(u32 handle) {
  255. const auto& regs{kepler_compute->regs};
  256. const auto& qmd{kepler_compute->launch_description};
  257. return ReadTextureTypeImpl(regs.tic.Address(), regs.tic.limit, qmd.linked_tsc != 0, handle);
  258. }
  259. void FileEnvironment::Deserialize(std::ifstream& file) {
  260. u64 code_size{};
  261. u64 num_texture_types{};
  262. u64 num_cbuf_values{};
  263. file.read(reinterpret_cast<char*>(&code_size), sizeof(code_size))
  264. .read(reinterpret_cast<char*>(&num_texture_types), sizeof(num_texture_types))
  265. .read(reinterpret_cast<char*>(&num_cbuf_values), sizeof(num_cbuf_values))
  266. .read(reinterpret_cast<char*>(&local_memory_size), sizeof(local_memory_size))
  267. .read(reinterpret_cast<char*>(&texture_bound), sizeof(texture_bound))
  268. .read(reinterpret_cast<char*>(&start_address), sizeof(start_address))
  269. .read(reinterpret_cast<char*>(&read_lowest), sizeof(read_lowest))
  270. .read(reinterpret_cast<char*>(&read_highest), sizeof(read_highest))
  271. .read(reinterpret_cast<char*>(&stage), sizeof(stage));
  272. code = std::make_unique<u64[]>(Common::DivCeil(code_size, sizeof(u64)));
  273. file.read(reinterpret_cast<char*>(code.get()), code_size);
  274. for (size_t i = 0; i < num_texture_types; ++i) {
  275. u32 key;
  276. Shader::TextureType type;
  277. file.read(reinterpret_cast<char*>(&key), sizeof(key))
  278. .read(reinterpret_cast<char*>(&type), sizeof(type));
  279. texture_types.emplace(key, type);
  280. }
  281. for (size_t i = 0; i < num_cbuf_values; ++i) {
  282. u64 key;
  283. u32 value;
  284. file.read(reinterpret_cast<char*>(&key), sizeof(key))
  285. .read(reinterpret_cast<char*>(&value), sizeof(value));
  286. cbuf_values.emplace(key, value);
  287. }
  288. if (stage == Shader::Stage::Compute) {
  289. file.read(reinterpret_cast<char*>(&workgroup_size), sizeof(workgroup_size))
  290. .read(reinterpret_cast<char*>(&shared_memory_size), sizeof(shared_memory_size));
  291. } else {
  292. file.read(reinterpret_cast<char*>(&sph), sizeof(sph));
  293. if (stage == Shader::Stage::Geometry) {
  294. file.read(reinterpret_cast<char*>(&gp_passthrough_mask), sizeof(gp_passthrough_mask));
  295. }
  296. }
  297. }
  298. u64 FileEnvironment::ReadInstruction(u32 address) {
  299. if (address < read_lowest || address > read_highest) {
  300. throw Shader::LogicError("Out of bounds address {}", address);
  301. }
  302. return code[(address - read_lowest) / sizeof(u64)];
  303. }
  304. u32 FileEnvironment::ReadCbufValue(u32 cbuf_index, u32 cbuf_offset) {
  305. const auto it{cbuf_values.find(MakeCbufKey(cbuf_index, cbuf_offset))};
  306. if (it == cbuf_values.end()) {
  307. throw Shader::LogicError("Uncached read texture type");
  308. }
  309. return it->second;
  310. }
  311. Shader::TextureType FileEnvironment::ReadTextureType(u32 handle) {
  312. const auto it{texture_types.find(handle)};
  313. if (it == texture_types.end()) {
  314. throw Shader::LogicError("Uncached read texture type");
  315. }
  316. return it->second;
  317. }
  318. u32 FileEnvironment::LocalMemorySize() const {
  319. return local_memory_size;
  320. }
  321. u32 FileEnvironment::SharedMemorySize() const {
  322. return shared_memory_size;
  323. }
  324. u32 FileEnvironment::TextureBoundBuffer() const {
  325. return texture_bound;
  326. }
  327. std::array<u32, 3> FileEnvironment::WorkgroupSize() const {
  328. return workgroup_size;
  329. }
  330. void SerializePipeline(std::span<const char> key, std::span<const GenericEnvironment* const> envs,
  331. const std::filesystem::path& filename, u32 cache_version) try {
  332. std::ofstream file(filename, std::ios::binary | std::ios::ate | std::ios::app);
  333. file.exceptions(std::ifstream::failbit);
  334. if (!file.is_open()) {
  335. LOG_ERROR(Common_Filesystem, "Failed to open pipeline cache file {}",
  336. Common::FS::PathToUTF8String(filename));
  337. return;
  338. }
  339. if (file.tellp() == 0) {
  340. // Write header
  341. file.write(MAGIC_NUMBER.data(), MAGIC_NUMBER.size())
  342. .write(reinterpret_cast<const char*>(&cache_version), sizeof(cache_version));
  343. }
  344. if (!std::ranges::all_of(envs, &GenericEnvironment::CanBeSerialized)) {
  345. return;
  346. }
  347. const u32 num_envs{static_cast<u32>(envs.size())};
  348. file.write(reinterpret_cast<const char*>(&num_envs), sizeof(num_envs));
  349. for (const GenericEnvironment* const env : envs) {
  350. env->Serialize(file);
  351. }
  352. file.write(key.data(), key.size_bytes());
  353. } catch (const std::ios_base::failure& e) {
  354. LOG_ERROR(Common_Filesystem, "{}", e.what());
  355. if (!Common::FS::RemoveFile(filename)) {
  356. LOG_ERROR(Common_Filesystem, "Failed to delete pipeline cache file {}",
  357. Common::FS::PathToUTF8String(filename));
  358. }
  359. }
  360. void LoadPipelines(
  361. std::stop_token stop_loading, const std::filesystem::path& filename, u32 expected_cache_version,
  362. Common::UniqueFunction<void, std::ifstream&, FileEnvironment> load_compute,
  363. Common::UniqueFunction<void, std::ifstream&, std::vector<FileEnvironment>> load_graphics) try {
  364. std::ifstream file(filename, std::ios::binary | std::ios::ate);
  365. if (!file.is_open()) {
  366. return;
  367. }
  368. file.exceptions(std::ifstream::failbit);
  369. const auto end{file.tellg()};
  370. file.seekg(0, std::ios::beg);
  371. std::array<char, 8> magic_number;
  372. u32 cache_version;
  373. file.read(magic_number.data(), magic_number.size())
  374. .read(reinterpret_cast<char*>(&cache_version), sizeof(cache_version));
  375. if (magic_number != MAGIC_NUMBER || cache_version != expected_cache_version) {
  376. file.close();
  377. if (Common::FS::RemoveFile(filename)) {
  378. if (magic_number != MAGIC_NUMBER) {
  379. LOG_ERROR(Common_Filesystem, "Invalid pipeline cache file");
  380. }
  381. if (cache_version != expected_cache_version) {
  382. LOG_INFO(Common_Filesystem, "Deleting old pipeline cache");
  383. }
  384. } else {
  385. LOG_ERROR(Common_Filesystem,
  386. "Invalid pipeline cache file and failed to delete it in \"{}\"",
  387. Common::FS::PathToUTF8String(filename));
  388. }
  389. return;
  390. }
  391. while (file.tellg() != end) {
  392. if (stop_loading.stop_requested()) {
  393. return;
  394. }
  395. u32 num_envs{};
  396. file.read(reinterpret_cast<char*>(&num_envs), sizeof(num_envs));
  397. std::vector<FileEnvironment> envs(num_envs);
  398. for (FileEnvironment& env : envs) {
  399. env.Deserialize(file);
  400. }
  401. if (envs.front().ShaderStage() == Shader::Stage::Compute) {
  402. load_compute(file, std::move(envs.front()));
  403. } else {
  404. load_graphics(file, std::move(envs));
  405. }
  406. }
  407. } catch (const std::ios_base::failure& e) {
  408. LOG_ERROR(Common_Filesystem, "{}", e.what());
  409. if (!Common::FS::RemoveFile(filename)) {
  410. LOG_ERROR(Common_Filesystem, "Failed to delete pipeline cache file {}",
  411. Common::FS::PathToUTF8String(filename));
  412. }
  413. }
  414. } // namespace VideoCommon