arm_dynarmic_64.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. // SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include "common/settings.h"
  4. #include "core/arm/dynarmic/arm_dynarmic.h"
  5. #include "core/arm/dynarmic/arm_dynarmic_64.h"
  6. #include "core/arm/dynarmic/dynarmic_exclusive_monitor.h"
  7. #include "core/core_timing.h"
  8. #include "core/hle/kernel/k_process.h"
  9. namespace Core {
  10. using Vector = Dynarmic::A64::Vector;
  11. using namespace Common::Literals;
  12. class DynarmicCallbacks64 : public Dynarmic::A64::UserCallbacks {
  13. public:
  14. explicit DynarmicCallbacks64(ArmDynarmic64& parent, Kernel::KProcess* process)
  15. : m_parent{parent}, m_memory(process->GetMemory()), m_process(process),
  16. m_debugger_enabled{parent.m_system.DebuggerEnabled()},
  17. m_check_memory_access{m_debugger_enabled ||
  18. !Settings::values.cpuopt_ignore_memory_aborts.GetValue()} {}
  19. u8 MemoryRead8(u64 vaddr) override {
  20. CheckMemoryAccess(vaddr, 1, Kernel::DebugWatchpointType::Read);
  21. return m_memory.Read8(vaddr);
  22. }
  23. u16 MemoryRead16(u64 vaddr) override {
  24. CheckMemoryAccess(vaddr, 2, Kernel::DebugWatchpointType::Read);
  25. return m_memory.Read16(vaddr);
  26. }
  27. u32 MemoryRead32(u64 vaddr) override {
  28. CheckMemoryAccess(vaddr, 4, Kernel::DebugWatchpointType::Read);
  29. return m_memory.Read32(vaddr);
  30. }
  31. u64 MemoryRead64(u64 vaddr) override {
  32. CheckMemoryAccess(vaddr, 8, Kernel::DebugWatchpointType::Read);
  33. return m_memory.Read64(vaddr);
  34. }
  35. Vector MemoryRead128(u64 vaddr) override {
  36. CheckMemoryAccess(vaddr, 16, Kernel::DebugWatchpointType::Read);
  37. return {m_memory.Read64(vaddr), m_memory.Read64(vaddr + 8)};
  38. }
  39. std::optional<u32> MemoryReadCode(u64 vaddr) override {
  40. if (!m_memory.IsValidVirtualAddressRange(vaddr, sizeof(u32))) {
  41. return std::nullopt;
  42. }
  43. return m_memory.Read32(vaddr);
  44. }
  45. void MemoryWrite8(u64 vaddr, u8 value) override {
  46. if (CheckMemoryAccess(vaddr, 1, Kernel::DebugWatchpointType::Write)) {
  47. m_memory.Write8(vaddr, value);
  48. }
  49. }
  50. void MemoryWrite16(u64 vaddr, u16 value) override {
  51. if (CheckMemoryAccess(vaddr, 2, Kernel::DebugWatchpointType::Write)) {
  52. m_memory.Write16(vaddr, value);
  53. }
  54. }
  55. void MemoryWrite32(u64 vaddr, u32 value) override {
  56. if (CheckMemoryAccess(vaddr, 4, Kernel::DebugWatchpointType::Write)) {
  57. m_memory.Write32(vaddr, value);
  58. }
  59. }
  60. void MemoryWrite64(u64 vaddr, u64 value) override {
  61. if (CheckMemoryAccess(vaddr, 8, Kernel::DebugWatchpointType::Write)) {
  62. m_memory.Write64(vaddr, value);
  63. }
  64. }
  65. void MemoryWrite128(u64 vaddr, Vector value) override {
  66. if (CheckMemoryAccess(vaddr, 16, Kernel::DebugWatchpointType::Write)) {
  67. m_memory.Write64(vaddr, value[0]);
  68. m_memory.Write64(vaddr + 8, value[1]);
  69. }
  70. }
  71. bool MemoryWriteExclusive8(u64 vaddr, std::uint8_t value, std::uint8_t expected) override {
  72. return CheckMemoryAccess(vaddr, 1, Kernel::DebugWatchpointType::Write) &&
  73. m_memory.WriteExclusive8(vaddr, value, expected);
  74. }
  75. bool MemoryWriteExclusive16(u64 vaddr, std::uint16_t value, std::uint16_t expected) override {
  76. return CheckMemoryAccess(vaddr, 2, Kernel::DebugWatchpointType::Write) &&
  77. m_memory.WriteExclusive16(vaddr, value, expected);
  78. }
  79. bool MemoryWriteExclusive32(u64 vaddr, std::uint32_t value, std::uint32_t expected) override {
  80. return CheckMemoryAccess(vaddr, 4, Kernel::DebugWatchpointType::Write) &&
  81. m_memory.WriteExclusive32(vaddr, value, expected);
  82. }
  83. bool MemoryWriteExclusive64(u64 vaddr, std::uint64_t value, std::uint64_t expected) override {
  84. return CheckMemoryAccess(vaddr, 8, Kernel::DebugWatchpointType::Write) &&
  85. m_memory.WriteExclusive64(vaddr, value, expected);
  86. }
  87. bool MemoryWriteExclusive128(u64 vaddr, Vector value, Vector expected) override {
  88. return CheckMemoryAccess(vaddr, 16, Kernel::DebugWatchpointType::Write) &&
  89. m_memory.WriteExclusive128(vaddr, value, expected);
  90. }
  91. void InterpreterFallback(u64 pc, std::size_t num_instructions) override {
  92. m_parent.LogBacktrace(m_process);
  93. LOG_ERROR(Core_ARM,
  94. "Unimplemented instruction @ 0x{:X} for {} instructions (instr = {:08X})", pc,
  95. num_instructions, m_memory.Read32(pc));
  96. ReturnException(pc, PrefetchAbort);
  97. }
  98. void InstructionCacheOperationRaised(Dynarmic::A64::InstructionCacheOperation op,
  99. u64 value) override {
  100. switch (op) {
  101. case Dynarmic::A64::InstructionCacheOperation::InvalidateByVAToPoU: {
  102. static constexpr u64 ICACHE_LINE_SIZE = 64;
  103. const u64 cache_line_start = value & ~(ICACHE_LINE_SIZE - 1);
  104. m_parent.InvalidateCacheRange(cache_line_start, ICACHE_LINE_SIZE);
  105. break;
  106. }
  107. case Dynarmic::A64::InstructionCacheOperation::InvalidateAllToPoU:
  108. m_parent.ClearInstructionCache();
  109. break;
  110. case Dynarmic::A64::InstructionCacheOperation::InvalidateAllToPoUInnerSharable:
  111. default:
  112. LOG_DEBUG(Core_ARM, "Unprocesseed instruction cache operation: {}", op);
  113. break;
  114. }
  115. m_parent.m_jit->HaltExecution(Dynarmic::HaltReason::CacheInvalidation);
  116. }
  117. void ExceptionRaised(u64 pc, Dynarmic::A64::Exception exception) override {
  118. switch (exception) {
  119. case Dynarmic::A64::Exception::WaitForInterrupt:
  120. case Dynarmic::A64::Exception::WaitForEvent:
  121. case Dynarmic::A64::Exception::SendEvent:
  122. case Dynarmic::A64::Exception::SendEventLocal:
  123. case Dynarmic::A64::Exception::Yield:
  124. return;
  125. case Dynarmic::A64::Exception::NoExecuteFault:
  126. LOG_CRITICAL(Core_ARM, "Cannot execute instruction at unmapped address {:#016x}", pc);
  127. ReturnException(pc, PrefetchAbort);
  128. return;
  129. default:
  130. if (m_debugger_enabled) {
  131. ReturnException(pc, InstructionBreakpoint);
  132. return;
  133. }
  134. m_parent.LogBacktrace(m_process);
  135. LOG_CRITICAL(Core_ARM, "ExceptionRaised(exception = {}, pc = {:08X}, code = {:08X})",
  136. static_cast<std::size_t>(exception), pc, m_memory.Read32(pc));
  137. }
  138. }
  139. void CallSVC(u32 svc) override {
  140. m_parent.m_svc = svc;
  141. m_parent.m_jit->HaltExecution(SupervisorCall);
  142. }
  143. void AddTicks(u64 ticks) override {
  144. ASSERT_MSG(!m_parent.m_uses_wall_clock, "Dynarmic ticking disabled");
  145. // Divide the number of ticks by the amount of CPU cores. TODO(Subv): This yields only a
  146. // rough approximation of the amount of executed ticks in the system, it may be thrown off
  147. // if not all cores are doing a similar amount of work. Instead of doing this, we should
  148. // device a way so that timing is consistent across all cores without increasing the ticks 4
  149. // times.
  150. u64 amortized_ticks = ticks / Core::Hardware::NUM_CPU_CORES;
  151. // Always execute at least one tick.
  152. amortized_ticks = std::max<u64>(amortized_ticks, 1);
  153. m_parent.m_system.CoreTiming().AddTicks(amortized_ticks);
  154. }
  155. u64 GetTicksRemaining() override {
  156. ASSERT_MSG(!m_parent.m_uses_wall_clock, "Dynarmic ticking disabled");
  157. return std::max<s64>(m_parent.m_system.CoreTiming().GetDowncount(), 0);
  158. }
  159. u64 GetCNTPCT() override {
  160. return m_parent.m_system.CoreTiming().GetClockTicks();
  161. }
  162. bool CheckMemoryAccess(u64 addr, u64 size, Kernel::DebugWatchpointType type) {
  163. if (!m_check_memory_access) {
  164. return true;
  165. }
  166. if (!m_memory.IsValidVirtualAddressRange(addr, size)) {
  167. LOG_CRITICAL(Core_ARM, "Stopping execution due to unmapped memory access at {:#x}",
  168. addr);
  169. m_parent.m_jit->HaltExecution(PrefetchAbort);
  170. return false;
  171. }
  172. if (!m_debugger_enabled) {
  173. return true;
  174. }
  175. const auto match{m_parent.MatchingWatchpoint(addr, size, type)};
  176. if (match) {
  177. m_parent.m_halted_watchpoint = match;
  178. m_parent.m_jit->HaltExecution(DataAbort);
  179. return false;
  180. }
  181. return true;
  182. }
  183. void ReturnException(u64 pc, Dynarmic::HaltReason hr) {
  184. m_parent.GetContext(m_parent.m_breakpoint_context);
  185. m_parent.m_breakpoint_context.pc = pc;
  186. m_parent.m_jit->HaltExecution(hr);
  187. }
  188. ArmDynarmic64& m_parent;
  189. Core::Memory::Memory& m_memory;
  190. u64 m_tpidrro_el0{};
  191. u64 m_tpidr_el0{};
  192. Kernel::KProcess* m_process{};
  193. const bool m_debugger_enabled{};
  194. const bool m_check_memory_access{};
  195. static constexpr u64 MinimumRunCycles = 10000U;
  196. };
  197. std::shared_ptr<Dynarmic::A64::Jit> ArmDynarmic64::MakeJit(Common::PageTable* page_table,
  198. std::size_t address_space_bits) const {
  199. Dynarmic::A64::UserConfig config;
  200. // Callbacks
  201. config.callbacks = m_cb.get();
  202. // Memory
  203. if (page_table) {
  204. config.page_table = reinterpret_cast<void**>(page_table->pointers.data());
  205. config.page_table_address_space_bits = address_space_bits;
  206. config.page_table_pointer_mask_bits = Common::PageTable::ATTRIBUTE_BITS;
  207. config.silently_mirror_page_table = false;
  208. config.absolute_offset_page_table = true;
  209. config.detect_misaligned_access_via_page_table = 16 | 32 | 64 | 128;
  210. config.only_detect_misalignment_via_page_table_on_page_boundary = true;
  211. config.fastmem_pointer = page_table->fastmem_arena;
  212. config.fastmem_address_space_bits = address_space_bits;
  213. config.silently_mirror_fastmem = false;
  214. config.fastmem_exclusive_access = config.fastmem_pointer != nullptr;
  215. config.recompile_on_exclusive_fastmem_failure = true;
  216. }
  217. // Multi-process state
  218. config.processor_id = m_core_index;
  219. config.global_monitor = &m_exclusive_monitor.monitor;
  220. // System registers
  221. config.tpidrro_el0 = &m_cb->m_tpidrro_el0;
  222. config.tpidr_el0 = &m_cb->m_tpidr_el0;
  223. config.dczid_el0 = 4;
  224. config.ctr_el0 = 0x8444c004;
  225. config.cntfrq_el0 = Hardware::CNTFREQ;
  226. // Unpredictable instructions
  227. config.define_unpredictable_behaviour = true;
  228. // Timing
  229. config.wall_clock_cntpct = m_uses_wall_clock;
  230. config.enable_cycle_counting = !m_uses_wall_clock;
  231. // Code cache size
  232. #ifdef ARCHITECTURE_arm64
  233. config.code_cache_size = 128_MiB;
  234. #else
  235. config.code_cache_size = 512_MiB;
  236. #endif
  237. // Allow memory fault handling to work
  238. if (m_system.DebuggerEnabled()) {
  239. config.check_halt_on_memory_access = true;
  240. }
  241. // null_jit
  242. if (!page_table) {
  243. // Don't waste too much memory on null_jit
  244. config.code_cache_size = 8_MiB;
  245. }
  246. // Safe optimizations
  247. if (Settings::values.cpu_debug_mode) {
  248. if (!Settings::values.cpuopt_page_tables) {
  249. config.page_table = nullptr;
  250. }
  251. if (!Settings::values.cpuopt_block_linking) {
  252. config.optimizations &= ~Dynarmic::OptimizationFlag::BlockLinking;
  253. }
  254. if (!Settings::values.cpuopt_return_stack_buffer) {
  255. config.optimizations &= ~Dynarmic::OptimizationFlag::ReturnStackBuffer;
  256. }
  257. if (!Settings::values.cpuopt_fast_dispatcher) {
  258. config.optimizations &= ~Dynarmic::OptimizationFlag::FastDispatch;
  259. }
  260. if (!Settings::values.cpuopt_context_elimination) {
  261. config.optimizations &= ~Dynarmic::OptimizationFlag::GetSetElimination;
  262. }
  263. if (!Settings::values.cpuopt_const_prop) {
  264. config.optimizations &= ~Dynarmic::OptimizationFlag::ConstProp;
  265. }
  266. if (!Settings::values.cpuopt_misc_ir) {
  267. config.optimizations &= ~Dynarmic::OptimizationFlag::MiscIROpt;
  268. }
  269. if (!Settings::values.cpuopt_reduce_misalign_checks) {
  270. config.only_detect_misalignment_via_page_table_on_page_boundary = false;
  271. }
  272. if (!Settings::values.cpuopt_fastmem) {
  273. config.fastmem_pointer = nullptr;
  274. config.fastmem_exclusive_access = false;
  275. }
  276. if (!Settings::values.cpuopt_fastmem_exclusives) {
  277. config.fastmem_exclusive_access = false;
  278. }
  279. if (!Settings::values.cpuopt_recompile_exclusives) {
  280. config.recompile_on_exclusive_fastmem_failure = false;
  281. }
  282. if (!Settings::values.cpuopt_ignore_memory_aborts) {
  283. config.check_halt_on_memory_access = true;
  284. }
  285. } else {
  286. // Unsafe optimizations
  287. if (Settings::values.cpu_accuracy.GetValue() == Settings::CpuAccuracy::Unsafe) {
  288. config.unsafe_optimizations = true;
  289. if (Settings::values.cpuopt_unsafe_unfuse_fma) {
  290. config.optimizations |= Dynarmic::OptimizationFlag::Unsafe_UnfuseFMA;
  291. }
  292. if (Settings::values.cpuopt_unsafe_reduce_fp_error) {
  293. config.optimizations |= Dynarmic::OptimizationFlag::Unsafe_ReducedErrorFP;
  294. }
  295. if (Settings::values.cpuopt_unsafe_inaccurate_nan) {
  296. config.optimizations |= Dynarmic::OptimizationFlag::Unsafe_InaccurateNaN;
  297. }
  298. if (Settings::values.cpuopt_unsafe_fastmem_check) {
  299. config.fastmem_address_space_bits = 64;
  300. }
  301. if (Settings::values.cpuopt_unsafe_ignore_global_monitor) {
  302. config.optimizations |= Dynarmic::OptimizationFlag::Unsafe_IgnoreGlobalMonitor;
  303. }
  304. }
  305. // Curated optimizations
  306. if (Settings::values.cpu_accuracy.GetValue() == Settings::CpuAccuracy::Auto) {
  307. config.unsafe_optimizations = true;
  308. config.optimizations |= Dynarmic::OptimizationFlag::Unsafe_UnfuseFMA;
  309. config.fastmem_address_space_bits = 64;
  310. config.optimizations |= Dynarmic::OptimizationFlag::Unsafe_IgnoreGlobalMonitor;
  311. }
  312. // Paranoia mode for debugging optimizations
  313. if (Settings::values.cpu_accuracy.GetValue() == Settings::CpuAccuracy::Paranoid) {
  314. config.unsafe_optimizations = false;
  315. config.optimizations = Dynarmic::no_optimizations;
  316. }
  317. }
  318. return std::make_shared<Dynarmic::A64::Jit>(config);
  319. }
  320. HaltReason ArmDynarmic64::RunThread(Kernel::KThread* thread) {
  321. ScopedJitExecution sj(thread->GetOwnerProcess());
  322. m_jit->ClearExclusiveState();
  323. return TranslateHaltReason(m_jit->Run());
  324. }
  325. HaltReason ArmDynarmic64::StepThread(Kernel::KThread* thread) {
  326. ScopedJitExecution sj(thread->GetOwnerProcess());
  327. m_jit->ClearExclusiveState();
  328. return TranslateHaltReason(m_jit->Step());
  329. }
  330. u32 ArmDynarmic64::GetSvcNumber() const {
  331. return m_svc;
  332. }
  333. void ArmDynarmic64::GetSvcArguments(std::span<uint64_t, 8> args) const {
  334. Dynarmic::A64::Jit& j = *m_jit;
  335. for (size_t i = 0; i < 8; i++) {
  336. args[i] = j.GetRegister(i);
  337. }
  338. }
  339. void ArmDynarmic64::SetSvcArguments(std::span<const uint64_t, 8> args) {
  340. Dynarmic::A64::Jit& j = *m_jit;
  341. for (size_t i = 0; i < 8; i++) {
  342. j.SetRegister(i, args[i]);
  343. }
  344. }
  345. const Kernel::DebugWatchpoint* ArmDynarmic64::HaltedWatchpoint() const {
  346. return m_halted_watchpoint;
  347. }
  348. void ArmDynarmic64::RewindBreakpointInstruction() {
  349. this->SetContext(m_breakpoint_context);
  350. }
  351. ArmDynarmic64::ArmDynarmic64(System& system, bool uses_wall_clock, Kernel::KProcess* process,
  352. DynarmicExclusiveMonitor& exclusive_monitor, std::size_t core_index)
  353. : ArmInterface{uses_wall_clock}, m_system{system}, m_exclusive_monitor{exclusive_monitor},
  354. m_cb(std::make_unique<DynarmicCallbacks64>(*this, process)), m_core_index{core_index} {
  355. auto& page_table = process->GetPageTable().GetBasePageTable();
  356. auto& page_table_impl = page_table.GetImpl();
  357. m_jit = MakeJit(&page_table_impl, page_table.GetAddressSpaceWidth());
  358. ScopedJitExecution::RegisterHandler();
  359. }
  360. ArmDynarmic64::~ArmDynarmic64() = default;
  361. void ArmDynarmic64::SetTpidrroEl0(u64 value) {
  362. m_cb->m_tpidrro_el0 = value;
  363. }
  364. void ArmDynarmic64::GetContext(Kernel::Svc::ThreadContext& ctx) const {
  365. Dynarmic::A64::Jit& j = *m_jit;
  366. auto gpr = j.GetRegisters();
  367. auto fpr = j.GetVectors();
  368. // TODO: this is inconvenient
  369. for (size_t i = 0; i < 29; i++) {
  370. ctx.r[i] = gpr[i];
  371. }
  372. ctx.fp = gpr[29];
  373. ctx.lr = gpr[30];
  374. ctx.sp = j.GetSP();
  375. ctx.pc = j.GetPC();
  376. ctx.pstate = j.GetPstate();
  377. ctx.v = fpr;
  378. ctx.fpcr = j.GetFpcr();
  379. ctx.fpsr = j.GetFpsr();
  380. ctx.tpidr = m_cb->m_tpidr_el0;
  381. }
  382. void ArmDynarmic64::SetContext(const Kernel::Svc::ThreadContext& ctx) {
  383. Dynarmic::A64::Jit& j = *m_jit;
  384. // TODO: this is inconvenient
  385. std::array<u64, 31> gpr;
  386. for (size_t i = 0; i < 29; i++) {
  387. gpr[i] = ctx.r[i];
  388. }
  389. gpr[29] = ctx.fp;
  390. gpr[30] = ctx.lr;
  391. j.SetRegisters(gpr);
  392. j.SetSP(ctx.sp);
  393. j.SetPC(ctx.pc);
  394. j.SetPstate(ctx.pstate);
  395. j.SetVectors(ctx.v);
  396. j.SetFpcr(ctx.fpcr);
  397. j.SetFpsr(ctx.fpsr);
  398. m_cb->m_tpidr_el0 = ctx.tpidr;
  399. }
  400. void ArmDynarmic64::SignalInterrupt(Kernel::KThread* thread) {
  401. m_jit->HaltExecution(BreakLoop);
  402. }
  403. void ArmDynarmic64::ClearInstructionCache() {
  404. m_jit->ClearCache();
  405. }
  406. void ArmDynarmic64::InvalidateCacheRange(u64 addr, std::size_t size) {
  407. m_jit->InvalidateCacheRange(addr, size);
  408. }
  409. } // namespace Core