arm_dynarmic_64.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. // SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <cinttypes>
  4. #include <memory>
  5. #include <dynarmic/interface/A64/a64.h>
  6. #include <dynarmic/interface/A64/config.h>
  7. #include "common/assert.h"
  8. #include "common/literals.h"
  9. #include "common/logging/log.h"
  10. #include "common/page_table.h"
  11. #include "common/settings.h"
  12. #include "core/arm/cpu_interrupt_handler.h"
  13. #include "core/arm/dynarmic/arm_dynarmic_64.h"
  14. #include "core/arm/dynarmic/arm_exclusive_monitor.h"
  15. #include "core/core.h"
  16. #include "core/core_timing.h"
  17. #include "core/debugger/debugger.h"
  18. #include "core/hardware_properties.h"
  19. #include "core/hle/kernel/k_process.h"
  20. #include "core/hle/kernel/svc.h"
  21. #include "core/memory.h"
  22. namespace Core {
  23. using Vector = Dynarmic::A64::Vector;
  24. using namespace Common::Literals;
  25. constexpr Dynarmic::HaltReason break_loop = Dynarmic::HaltReason::UserDefined2;
  26. constexpr Dynarmic::HaltReason svc_call = Dynarmic::HaltReason::UserDefined3;
  27. constexpr Dynarmic::HaltReason breakpoint = Dynarmic::HaltReason::UserDefined4;
  28. class DynarmicCallbacks64 : public Dynarmic::A64::UserCallbacks {
  29. public:
  30. explicit DynarmicCallbacks64(ARM_Dynarmic_64& parent_)
  31. : parent{parent_}, memory(parent.system.Memory()) {}
  32. u8 MemoryRead8(u64 vaddr) override {
  33. return memory.Read8(vaddr);
  34. }
  35. u16 MemoryRead16(u64 vaddr) override {
  36. return memory.Read16(vaddr);
  37. }
  38. u32 MemoryRead32(u64 vaddr) override {
  39. return memory.Read32(vaddr);
  40. }
  41. u64 MemoryRead64(u64 vaddr) override {
  42. return memory.Read64(vaddr);
  43. }
  44. Vector MemoryRead128(u64 vaddr) override {
  45. return {memory.Read64(vaddr), memory.Read64(vaddr + 8)};
  46. }
  47. void MemoryWrite8(u64 vaddr, u8 value) override {
  48. memory.Write8(vaddr, value);
  49. }
  50. void MemoryWrite16(u64 vaddr, u16 value) override {
  51. memory.Write16(vaddr, value);
  52. }
  53. void MemoryWrite32(u64 vaddr, u32 value) override {
  54. memory.Write32(vaddr, value);
  55. }
  56. void MemoryWrite64(u64 vaddr, u64 value) override {
  57. memory.Write64(vaddr, value);
  58. }
  59. void MemoryWrite128(u64 vaddr, Vector value) override {
  60. memory.Write64(vaddr, value[0]);
  61. memory.Write64(vaddr + 8, value[1]);
  62. }
  63. bool MemoryWriteExclusive8(u64 vaddr, std::uint8_t value, std::uint8_t expected) override {
  64. return memory.WriteExclusive8(vaddr, value, expected);
  65. }
  66. bool MemoryWriteExclusive16(u64 vaddr, std::uint16_t value, std::uint16_t expected) override {
  67. return memory.WriteExclusive16(vaddr, value, expected);
  68. }
  69. bool MemoryWriteExclusive32(u64 vaddr, std::uint32_t value, std::uint32_t expected) override {
  70. return memory.WriteExclusive32(vaddr, value, expected);
  71. }
  72. bool MemoryWriteExclusive64(u64 vaddr, std::uint64_t value, std::uint64_t expected) override {
  73. return memory.WriteExclusive64(vaddr, value, expected);
  74. }
  75. bool MemoryWriteExclusive128(u64 vaddr, Vector value, Vector expected) override {
  76. return memory.WriteExclusive128(vaddr, value, expected);
  77. }
  78. void InterpreterFallback(u64 pc, std::size_t num_instructions) override {
  79. parent.LogBacktrace();
  80. LOG_ERROR(Core_ARM,
  81. "Unimplemented instruction @ 0x{:X} for {} instructions (instr = {:08X})", pc,
  82. num_instructions, MemoryReadCode(pc));
  83. }
  84. void InstructionCacheOperationRaised(Dynarmic::A64::InstructionCacheOperation op,
  85. VAddr value) override {
  86. switch (op) {
  87. case Dynarmic::A64::InstructionCacheOperation::InvalidateByVAToPoU: {
  88. static constexpr u64 ICACHE_LINE_SIZE = 64;
  89. const u64 cache_line_start = value & ~(ICACHE_LINE_SIZE - 1);
  90. parent.system.InvalidateCpuInstructionCacheRange(cache_line_start, ICACHE_LINE_SIZE);
  91. break;
  92. }
  93. case Dynarmic::A64::InstructionCacheOperation::InvalidateAllToPoU:
  94. parent.system.InvalidateCpuInstructionCaches();
  95. break;
  96. case Dynarmic::A64::InstructionCacheOperation::InvalidateAllToPoUInnerSharable:
  97. default:
  98. LOG_DEBUG(Core_ARM, "Unprocesseed instruction cache operation: {}", op);
  99. break;
  100. }
  101. parent.jit.load()->HaltExecution(Dynarmic::HaltReason::CacheInvalidation);
  102. }
  103. void ExceptionRaised(u64 pc, Dynarmic::A64::Exception exception) override {
  104. switch (exception) {
  105. case Dynarmic::A64::Exception::WaitForInterrupt:
  106. case Dynarmic::A64::Exception::WaitForEvent:
  107. case Dynarmic::A64::Exception::SendEvent:
  108. case Dynarmic::A64::Exception::SendEventLocal:
  109. case Dynarmic::A64::Exception::Yield:
  110. return;
  111. default:
  112. if (parent.system.DebuggerEnabled()) {
  113. parent.breakpoint_pc = pc;
  114. parent.jit.load()->HaltExecution(breakpoint);
  115. return;
  116. }
  117. parent.LogBacktrace();
  118. ASSERT_MSG(false, "ExceptionRaised(exception = {}, pc = {:08X}, code = {:08X})",
  119. static_cast<std::size_t>(exception), pc, MemoryReadCode(pc));
  120. }
  121. }
  122. void CallSVC(u32 swi) override {
  123. parent.svc_swi = swi;
  124. parent.jit.load()->HaltExecution(svc_call);
  125. }
  126. void AddTicks(u64 ticks) override {
  127. ASSERT_MSG(!parent.uses_wall_clock, "This should never happen - dynarmic ticking disabled");
  128. // Divide the number of ticks by the amount of CPU cores. TODO(Subv): This yields only a
  129. // rough approximation of the amount of executed ticks in the system, it may be thrown off
  130. // if not all cores are doing a similar amount of work. Instead of doing this, we should
  131. // device a way so that timing is consistent across all cores without increasing the ticks 4
  132. // times.
  133. u64 amortized_ticks = ticks / Core::Hardware::NUM_CPU_CORES;
  134. // Always execute at least one tick.
  135. amortized_ticks = std::max<u64>(amortized_ticks, 1);
  136. parent.system.CoreTiming().AddTicks(amortized_ticks);
  137. }
  138. u64 GetTicksRemaining() override {
  139. ASSERT_MSG(!parent.uses_wall_clock, "This should never happen - dynarmic ticking disabled");
  140. return std::max<s64>(parent.system.CoreTiming().GetDowncount(), 0);
  141. }
  142. u64 GetCNTPCT() override {
  143. return parent.system.CoreTiming().GetClockTicks();
  144. }
  145. ARM_Dynarmic_64& parent;
  146. Core::Memory::Memory& memory;
  147. u64 tpidrro_el0 = 0;
  148. u64 tpidr_el0 = 0;
  149. static constexpr u64 minimum_run_cycles = 1000U;
  150. };
  151. std::shared_ptr<Dynarmic::A64::Jit> ARM_Dynarmic_64::MakeJit(Common::PageTable* page_table,
  152. std::size_t address_space_bits) const {
  153. Dynarmic::A64::UserConfig config;
  154. // Callbacks
  155. config.callbacks = cb.get();
  156. // Memory
  157. if (page_table) {
  158. config.page_table = reinterpret_cast<void**>(page_table->pointers.data());
  159. config.page_table_address_space_bits = address_space_bits;
  160. config.page_table_pointer_mask_bits = Common::PageTable::ATTRIBUTE_BITS;
  161. config.silently_mirror_page_table = false;
  162. config.absolute_offset_page_table = true;
  163. config.detect_misaligned_access_via_page_table = 16 | 32 | 64 | 128;
  164. config.only_detect_misalignment_via_page_table_on_page_boundary = true;
  165. config.fastmem_pointer = page_table->fastmem_arena;
  166. config.fastmem_address_space_bits = address_space_bits;
  167. config.silently_mirror_fastmem = false;
  168. config.fastmem_exclusive_access = true;
  169. config.recompile_on_exclusive_fastmem_failure = true;
  170. }
  171. // Multi-process state
  172. config.processor_id = core_index;
  173. config.global_monitor = &exclusive_monitor.monitor;
  174. // System registers
  175. config.tpidrro_el0 = &cb->tpidrro_el0;
  176. config.tpidr_el0 = &cb->tpidr_el0;
  177. config.dczid_el0 = 4;
  178. config.ctr_el0 = 0x8444c004;
  179. config.cntfrq_el0 = Hardware::CNTFREQ;
  180. // Unpredictable instructions
  181. config.define_unpredictable_behaviour = true;
  182. // Timing
  183. config.wall_clock_cntpct = uses_wall_clock;
  184. config.enable_cycle_counting = !uses_wall_clock;
  185. // Code cache size
  186. config.code_cache_size = 512_MiB;
  187. config.far_code_offset = 400_MiB;
  188. // null_jit
  189. if (!page_table) {
  190. // Don't waste too much memory on null_jit
  191. config.code_cache_size = 8_MiB;
  192. config.far_code_offset = 4_MiB;
  193. }
  194. // Safe optimizations
  195. if (Settings::values.cpu_debug_mode) {
  196. if (!Settings::values.cpuopt_page_tables) {
  197. config.page_table = nullptr;
  198. }
  199. if (!Settings::values.cpuopt_block_linking) {
  200. config.optimizations &= ~Dynarmic::OptimizationFlag::BlockLinking;
  201. }
  202. if (!Settings::values.cpuopt_return_stack_buffer) {
  203. config.optimizations &= ~Dynarmic::OptimizationFlag::ReturnStackBuffer;
  204. }
  205. if (!Settings::values.cpuopt_fast_dispatcher) {
  206. config.optimizations &= ~Dynarmic::OptimizationFlag::FastDispatch;
  207. }
  208. if (!Settings::values.cpuopt_context_elimination) {
  209. config.optimizations &= ~Dynarmic::OptimizationFlag::GetSetElimination;
  210. }
  211. if (!Settings::values.cpuopt_const_prop) {
  212. config.optimizations &= ~Dynarmic::OptimizationFlag::ConstProp;
  213. }
  214. if (!Settings::values.cpuopt_misc_ir) {
  215. config.optimizations &= ~Dynarmic::OptimizationFlag::MiscIROpt;
  216. }
  217. if (!Settings::values.cpuopt_reduce_misalign_checks) {
  218. config.only_detect_misalignment_via_page_table_on_page_boundary = false;
  219. }
  220. if (!Settings::values.cpuopt_fastmem) {
  221. config.fastmem_pointer = nullptr;
  222. }
  223. if (!Settings::values.cpuopt_fastmem_exclusives) {
  224. config.fastmem_exclusive_access = false;
  225. }
  226. if (!Settings::values.cpuopt_recompile_exclusives) {
  227. config.recompile_on_exclusive_fastmem_failure = false;
  228. }
  229. } else {
  230. // Unsafe optimizations
  231. if (Settings::values.cpu_accuracy.GetValue() == Settings::CPUAccuracy::Unsafe) {
  232. config.unsafe_optimizations = true;
  233. if (Settings::values.cpuopt_unsafe_unfuse_fma) {
  234. config.optimizations |= Dynarmic::OptimizationFlag::Unsafe_UnfuseFMA;
  235. }
  236. if (Settings::values.cpuopt_unsafe_reduce_fp_error) {
  237. config.optimizations |= Dynarmic::OptimizationFlag::Unsafe_ReducedErrorFP;
  238. }
  239. if (Settings::values.cpuopt_unsafe_inaccurate_nan) {
  240. config.optimizations |= Dynarmic::OptimizationFlag::Unsafe_InaccurateNaN;
  241. }
  242. if (Settings::values.cpuopt_unsafe_fastmem_check) {
  243. config.fastmem_address_space_bits = 64;
  244. }
  245. if (Settings::values.cpuopt_unsafe_ignore_global_monitor) {
  246. config.optimizations |= Dynarmic::OptimizationFlag::Unsafe_IgnoreGlobalMonitor;
  247. }
  248. }
  249. // Curated optimizations
  250. if (Settings::values.cpu_accuracy.GetValue() == Settings::CPUAccuracy::Auto) {
  251. config.unsafe_optimizations = true;
  252. config.optimizations |= Dynarmic::OptimizationFlag::Unsafe_UnfuseFMA;
  253. config.optimizations |= Dynarmic::OptimizationFlag::Unsafe_InaccurateNaN;
  254. config.fastmem_address_space_bits = 64;
  255. config.optimizations |= Dynarmic::OptimizationFlag::Unsafe_IgnoreGlobalMonitor;
  256. }
  257. // Paranoia mode for debugging optimizations
  258. if (Settings::values.cpu_accuracy.GetValue() == Settings::CPUAccuracy::Paranoid) {
  259. config.unsafe_optimizations = false;
  260. config.optimizations = Dynarmic::no_optimizations;
  261. }
  262. }
  263. return std::make_shared<Dynarmic::A64::Jit>(config);
  264. }
  265. void ARM_Dynarmic_64::Run() {
  266. while (true) {
  267. const auto hr = jit.load()->Run();
  268. if (Has(hr, svc_call)) {
  269. Kernel::Svc::Call(system, svc_swi);
  270. }
  271. // Check to see if breakpoint is triggered.
  272. // Recheck step condition in case stop is no longer desired.
  273. Kernel::KThread* current_thread = system.Kernel().GetCurrentEmuThread();
  274. if (Has(hr, breakpoint)) {
  275. jit.load()->SetPC(breakpoint_pc);
  276. if (system.GetDebugger().NotifyThreadStopped(current_thread)) {
  277. current_thread->RequestSuspend(Kernel::SuspendType::Debug);
  278. }
  279. break;
  280. }
  281. if (ShouldStep()) {
  282. // When stepping, this should be the only thread running.
  283. ASSERT(system.GetDebugger().NotifyThreadStopped(current_thread));
  284. current_thread->RequestSuspend(Kernel::SuspendType::Debug);
  285. break;
  286. }
  287. if (Has(hr, break_loop) || !uses_wall_clock) {
  288. break;
  289. }
  290. }
  291. }
  292. ARM_Dynarmic_64::ARM_Dynarmic_64(System& system_, CPUInterrupts& interrupt_handlers_,
  293. bool uses_wall_clock_, ExclusiveMonitor& exclusive_monitor_,
  294. std::size_t core_index_)
  295. : ARM_Interface{system_, interrupt_handlers_, uses_wall_clock_},
  296. cb(std::make_unique<DynarmicCallbacks64>(*this)), core_index{core_index_},
  297. exclusive_monitor{dynamic_cast<DynarmicExclusiveMonitor&>(exclusive_monitor_)},
  298. null_jit{MakeJit(nullptr, 48)}, jit{null_jit.get()} {}
  299. ARM_Dynarmic_64::~ARM_Dynarmic_64() = default;
  300. void ARM_Dynarmic_64::SetPC(u64 pc) {
  301. jit.load()->SetPC(pc);
  302. }
  303. u64 ARM_Dynarmic_64::GetPC() const {
  304. return jit.load()->GetPC();
  305. }
  306. u64 ARM_Dynarmic_64::GetSP() const {
  307. return jit.load()->GetSP();
  308. }
  309. u64 ARM_Dynarmic_64::GetReg(int index) const {
  310. return jit.load()->GetRegister(index);
  311. }
  312. void ARM_Dynarmic_64::SetReg(int index, u64 value) {
  313. jit.load()->SetRegister(index, value);
  314. }
  315. u128 ARM_Dynarmic_64::GetVectorReg(int index) const {
  316. return jit.load()->GetVector(index);
  317. }
  318. void ARM_Dynarmic_64::SetVectorReg(int index, u128 value) {
  319. jit.load()->SetVector(index, value);
  320. }
  321. u32 ARM_Dynarmic_64::GetPSTATE() const {
  322. return jit.load()->GetPstate();
  323. }
  324. void ARM_Dynarmic_64::SetPSTATE(u32 pstate) {
  325. jit.load()->SetPstate(pstate);
  326. }
  327. u64 ARM_Dynarmic_64::GetTlsAddress() const {
  328. return cb->tpidrro_el0;
  329. }
  330. void ARM_Dynarmic_64::SetTlsAddress(VAddr address) {
  331. cb->tpidrro_el0 = address;
  332. }
  333. u64 ARM_Dynarmic_64::GetTPIDR_EL0() const {
  334. return cb->tpidr_el0;
  335. }
  336. void ARM_Dynarmic_64::SetTPIDR_EL0(u64 value) {
  337. cb->tpidr_el0 = value;
  338. }
  339. void ARM_Dynarmic_64::SaveContext(ThreadContext64& ctx) {
  340. Dynarmic::A64::Jit* j = jit.load();
  341. ctx.cpu_registers = j->GetRegisters();
  342. ctx.sp = j->GetSP();
  343. ctx.pc = j->GetPC();
  344. ctx.pstate = j->GetPstate();
  345. ctx.vector_registers = j->GetVectors();
  346. ctx.fpcr = j->GetFpcr();
  347. ctx.fpsr = j->GetFpsr();
  348. ctx.tpidr = cb->tpidr_el0;
  349. }
  350. void ARM_Dynarmic_64::LoadContext(const ThreadContext64& ctx) {
  351. Dynarmic::A64::Jit* j = jit.load();
  352. j->SetRegisters(ctx.cpu_registers);
  353. j->SetSP(ctx.sp);
  354. j->SetPC(ctx.pc);
  355. j->SetPstate(ctx.pstate);
  356. j->SetVectors(ctx.vector_registers);
  357. j->SetFpcr(ctx.fpcr);
  358. j->SetFpsr(ctx.fpsr);
  359. SetTPIDR_EL0(ctx.tpidr);
  360. }
  361. void ARM_Dynarmic_64::SignalInterrupt() {
  362. jit.load()->HaltExecution(break_loop);
  363. }
  364. void ARM_Dynarmic_64::ClearInstructionCache() {
  365. jit.load()->ClearCache();
  366. }
  367. void ARM_Dynarmic_64::InvalidateCacheRange(VAddr addr, std::size_t size) {
  368. jit.load()->InvalidateCacheRange(addr, size);
  369. }
  370. void ARM_Dynarmic_64::ClearExclusiveState() {
  371. jit.load()->ClearExclusiveState();
  372. }
  373. void ARM_Dynarmic_64::PageTableChanged(Common::PageTable& page_table,
  374. std::size_t new_address_space_size_in_bits) {
  375. ThreadContext64 ctx{};
  376. SaveContext(ctx);
  377. auto key = std::make_pair(&page_table, new_address_space_size_in_bits);
  378. auto iter = jit_cache.find(key);
  379. if (iter != jit_cache.end()) {
  380. jit.store(iter->second.get());
  381. LoadContext(ctx);
  382. return;
  383. }
  384. std::shared_ptr new_jit = MakeJit(&page_table, new_address_space_size_in_bits);
  385. jit.store(new_jit.get());
  386. LoadContext(ctx);
  387. jit_cache.emplace(key, std::move(new_jit));
  388. }
  389. std::vector<ARM_Interface::BacktraceEntry> ARM_Dynarmic_64::GetBacktrace(Core::System& system,
  390. u64 fp, u64 lr) {
  391. std::vector<BacktraceEntry> out;
  392. auto& memory = system.Memory();
  393. // fp (= r29) points to the last frame record.
  394. // Note that this is the frame record for the *previous* frame, not the current one.
  395. // Note we need to subtract 4 from our last read to get the proper address
  396. // Frame records are two words long:
  397. // fp+0 : pointer to previous frame record
  398. // fp+8 : value of lr for frame
  399. while (true) {
  400. out.push_back({"", 0, lr, 0, ""});
  401. if (!fp) {
  402. break;
  403. }
  404. lr = memory.Read64(fp + 8) - 4;
  405. fp = memory.Read64(fp);
  406. }
  407. SymbolicateBacktrace(system, out);
  408. return out;
  409. }
  410. std::vector<ARM_Interface::BacktraceEntry> ARM_Dynarmic_64::GetBacktraceFromContext(
  411. System& system, const ThreadContext64& ctx) {
  412. return GetBacktrace(system, ctx.cpu_registers[29], ctx.cpu_registers[30]);
  413. }
  414. std::vector<ARM_Interface::BacktraceEntry> ARM_Dynarmic_64::GetBacktrace() const {
  415. return GetBacktrace(system, GetReg(29), GetReg(30));
  416. }
  417. } // namespace Core