core.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. // Copyright 2014 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <array>
  5. #include <map>
  6. #include <memory>
  7. #include <thread>
  8. #include <utility>
  9. #include "common/logging/log.h"
  10. #include "common/string_util.h"
  11. #include "core/arm/exclusive_monitor.h"
  12. #include "core/core.h"
  13. #include "core/core_cpu.h"
  14. #include "core/core_timing.h"
  15. #include "core/file_sys/mode.h"
  16. #include "core/file_sys/vfs_concat.h"
  17. #include "core/file_sys/vfs_real.h"
  18. #include "core/gdbstub/gdbstub.h"
  19. #include "core/hle/kernel/client_port.h"
  20. #include "core/hle/kernel/kernel.h"
  21. #include "core/hle/kernel/process.h"
  22. #include "core/hle/kernel/scheduler.h"
  23. #include "core/hle/kernel/thread.h"
  24. #include "core/hle/service/am/applets/software_keyboard.h"
  25. #include "core/hle/service/service.h"
  26. #include "core/hle/service/sm/sm.h"
  27. #include "core/loader/loader.h"
  28. #include "core/perf_stats.h"
  29. #include "core/settings.h"
  30. #include "core/telemetry_session.h"
  31. #include "frontend/applets/software_keyboard.h"
  32. #include "video_core/debug_utils/debug_utils.h"
  33. #include "video_core/gpu.h"
  34. #include "video_core/renderer_base.h"
  35. #include "video_core/video_core.h"
  36. namespace Core {
  37. /*static*/ System System::s_instance;
  38. namespace {
  39. FileSys::VirtualFile GetGameFileFromPath(const FileSys::VirtualFilesystem& vfs,
  40. const std::string& path) {
  41. // To account for split 00+01+etc files.
  42. std::string dir_name;
  43. std::string filename;
  44. Common::SplitPath(path, &dir_name, &filename, nullptr);
  45. if (filename == "00") {
  46. const auto dir = vfs->OpenDirectory(dir_name, FileSys::Mode::Read);
  47. std::vector<FileSys::VirtualFile> concat;
  48. for (u8 i = 0; i < 0x10; ++i) {
  49. auto next = dir->GetFile(fmt::format("{:02X}", i));
  50. if (next != nullptr)
  51. concat.push_back(std::move(next));
  52. else {
  53. next = dir->GetFile(fmt::format("{:02x}", i));
  54. if (next != nullptr)
  55. concat.push_back(std::move(next));
  56. else
  57. break;
  58. }
  59. }
  60. if (concat.empty())
  61. return nullptr;
  62. return FileSys::ConcatenatedVfsFile::MakeConcatenatedFile(concat, dir->GetName());
  63. }
  64. return vfs->OpenFile(path, FileSys::Mode::Read);
  65. }
  66. /// Runs a CPU core while the system is powered on
  67. void RunCpuCore(Cpu& cpu_state) {
  68. while (Core::System::GetInstance().IsPoweredOn()) {
  69. cpu_state.RunLoop(true);
  70. }
  71. }
  72. } // Anonymous namespace
  73. struct System::Impl {
  74. Cpu& CurrentCpuCore() {
  75. if (Settings::values.use_multi_core) {
  76. const auto& search = thread_to_cpu.find(std::this_thread::get_id());
  77. ASSERT(search != thread_to_cpu.end());
  78. ASSERT(search->second);
  79. return *search->second;
  80. }
  81. // Otherwise, use single-threaded mode active_core variable
  82. return *cpu_cores[active_core];
  83. }
  84. ResultStatus RunLoop(bool tight_loop) {
  85. status = ResultStatus::Success;
  86. // Update thread_to_cpu in case Core 0 is run from a different host thread
  87. thread_to_cpu[std::this_thread::get_id()] = cpu_cores[0].get();
  88. if (GDBStub::IsServerEnabled()) {
  89. GDBStub::HandlePacket();
  90. // If the loop is halted and we want to step, use a tiny (1) number of instructions to
  91. // execute. Otherwise, get out of the loop function.
  92. if (GDBStub::GetCpuHaltFlag()) {
  93. if (GDBStub::GetCpuStepFlag()) {
  94. tight_loop = false;
  95. } else {
  96. return ResultStatus::Success;
  97. }
  98. }
  99. }
  100. for (active_core = 0; active_core < NUM_CPU_CORES; ++active_core) {
  101. cpu_cores[active_core]->RunLoop(tight_loop);
  102. if (Settings::values.use_multi_core) {
  103. // Cores 1-3 are run on other threads in this mode
  104. break;
  105. }
  106. }
  107. if (GDBStub::IsServerEnabled()) {
  108. GDBStub::SetCpuStepFlag(false);
  109. }
  110. return status;
  111. }
  112. ResultStatus Init(Frontend::EmuWindow& emu_window) {
  113. LOG_DEBUG(HW_Memory, "initialized OK");
  114. CoreTiming::Init();
  115. kernel.Initialize();
  116. // Create a default fs if one doesn't already exist.
  117. if (virtual_filesystem == nullptr)
  118. virtual_filesystem = std::make_shared<FileSys::RealVfsFilesystem>();
  119. /// Create default implementations of applets if one is not provided.
  120. if (software_keyboard == nullptr)
  121. software_keyboard = std::make_unique<Core::Frontend::DefaultSoftwareKeyboardApplet>();
  122. auto main_process = Kernel::Process::Create(kernel, "main");
  123. kernel.MakeCurrentProcess(main_process.get());
  124. cpu_barrier = std::make_unique<CpuBarrier>();
  125. cpu_exclusive_monitor = Cpu::MakeExclusiveMonitor(cpu_cores.size());
  126. for (std::size_t index = 0; index < cpu_cores.size(); ++index) {
  127. cpu_cores[index] = std::make_unique<Cpu>(*cpu_exclusive_monitor, *cpu_barrier, index);
  128. }
  129. telemetry_session = std::make_unique<Core::TelemetrySession>();
  130. service_manager = std::make_shared<Service::SM::ServiceManager>();
  131. Service::Init(service_manager, *virtual_filesystem);
  132. GDBStub::Init();
  133. renderer = VideoCore::CreateRenderer(emu_window);
  134. if (!renderer->Init()) {
  135. return ResultStatus::ErrorVideoCore;
  136. }
  137. gpu_core = std::make_unique<Tegra::GPU>(renderer->Rasterizer());
  138. // Create threads for CPU cores 1-3, and build thread_to_cpu map
  139. // CPU core 0 is run on the main thread
  140. thread_to_cpu[std::this_thread::get_id()] = cpu_cores[0].get();
  141. if (Settings::values.use_multi_core) {
  142. for (std::size_t index = 0; index < cpu_core_threads.size(); ++index) {
  143. cpu_core_threads[index] =
  144. std::make_unique<std::thread>(RunCpuCore, std::ref(*cpu_cores[index + 1]));
  145. thread_to_cpu[cpu_core_threads[index]->get_id()] = cpu_cores[index + 1].get();
  146. }
  147. }
  148. LOG_DEBUG(Core, "Initialized OK");
  149. // Reset counters and set time origin to current frame
  150. GetAndResetPerfStats();
  151. perf_stats.BeginSystemFrame();
  152. return ResultStatus::Success;
  153. }
  154. ResultStatus Load(Frontend::EmuWindow& emu_window, const std::string& filepath) {
  155. app_loader = Loader::GetLoader(GetGameFileFromPath(virtual_filesystem, filepath));
  156. if (!app_loader) {
  157. LOG_CRITICAL(Core, "Failed to obtain loader for {}!", filepath);
  158. return ResultStatus::ErrorGetLoader;
  159. }
  160. std::pair<std::optional<u32>, Loader::ResultStatus> system_mode =
  161. app_loader->LoadKernelSystemMode();
  162. if (system_mode.second != Loader::ResultStatus::Success) {
  163. LOG_CRITICAL(Core, "Failed to determine system mode (Error {})!",
  164. static_cast<int>(system_mode.second));
  165. return ResultStatus::ErrorSystemMode;
  166. }
  167. ResultStatus init_result{Init(emu_window)};
  168. if (init_result != ResultStatus::Success) {
  169. LOG_CRITICAL(Core, "Failed to initialize system (Error {})!",
  170. static_cast<int>(init_result));
  171. Shutdown();
  172. return init_result;
  173. }
  174. const Loader::ResultStatus load_result{app_loader->Load(*kernel.CurrentProcess())};
  175. if (load_result != Loader::ResultStatus::Success) {
  176. LOG_CRITICAL(Core, "Failed to load ROM (Error {})!", static_cast<int>(load_result));
  177. Shutdown();
  178. return static_cast<ResultStatus>(static_cast<u32>(ResultStatus::ErrorLoader) +
  179. static_cast<u32>(load_result));
  180. }
  181. status = ResultStatus::Success;
  182. return status;
  183. }
  184. void Shutdown() {
  185. // Log last frame performance stats
  186. auto perf_results = GetAndResetPerfStats();
  187. Telemetry().AddField(Telemetry::FieldType::Performance, "Shutdown_EmulationSpeed",
  188. perf_results.emulation_speed * 100.0);
  189. Telemetry().AddField(Telemetry::FieldType::Performance, "Shutdown_Framerate",
  190. perf_results.game_fps);
  191. Telemetry().AddField(Telemetry::FieldType::Performance, "Shutdown_Frametime",
  192. perf_results.frametime * 1000.0);
  193. // Shutdown emulation session
  194. renderer.reset();
  195. GDBStub::Shutdown();
  196. Service::Shutdown();
  197. service_manager.reset();
  198. telemetry_session.reset();
  199. gpu_core.reset();
  200. // Close all CPU/threading state
  201. cpu_barrier->NotifyEnd();
  202. if (Settings::values.use_multi_core) {
  203. for (auto& thread : cpu_core_threads) {
  204. thread->join();
  205. thread.reset();
  206. }
  207. }
  208. thread_to_cpu.clear();
  209. for (auto& cpu_core : cpu_cores) {
  210. cpu_core.reset();
  211. }
  212. cpu_exclusive_monitor.reset();
  213. cpu_barrier.reset();
  214. // Shutdown kernel and core timing
  215. kernel.Shutdown();
  216. CoreTiming::Shutdown();
  217. // Close app loader
  218. app_loader.reset();
  219. LOG_DEBUG(Core, "Shutdown OK");
  220. }
  221. Loader::ResultStatus GetGameName(std::string& out) const {
  222. if (app_loader == nullptr)
  223. return Loader::ResultStatus::ErrorNotInitialized;
  224. return app_loader->ReadTitle(out);
  225. }
  226. void SetStatus(ResultStatus new_status, const char* details = nullptr) {
  227. status = new_status;
  228. if (details) {
  229. status_details = details;
  230. }
  231. }
  232. PerfStatsResults GetAndResetPerfStats() {
  233. return perf_stats.GetAndResetStats(CoreTiming::GetGlobalTimeUs());
  234. }
  235. Kernel::KernelCore kernel;
  236. /// RealVfsFilesystem instance
  237. FileSys::VirtualFilesystem virtual_filesystem;
  238. /// AppLoader used to load the current executing application
  239. std::unique_ptr<Loader::AppLoader> app_loader;
  240. std::unique_ptr<VideoCore::RendererBase> renderer;
  241. std::unique_ptr<Tegra::GPU> gpu_core;
  242. std::shared_ptr<Tegra::DebugContext> debug_context;
  243. std::unique_ptr<ExclusiveMonitor> cpu_exclusive_monitor;
  244. std::unique_ptr<CpuBarrier> cpu_barrier;
  245. std::array<std::unique_ptr<Cpu>, NUM_CPU_CORES> cpu_cores;
  246. std::array<std::unique_ptr<std::thread>, NUM_CPU_CORES - 1> cpu_core_threads;
  247. std::size_t active_core{}; ///< Active core, only used in single thread mode
  248. /// Frontend applets
  249. std::unique_ptr<Core::Frontend::SoftwareKeyboardApplet> software_keyboard;
  250. /// Service manager
  251. std::shared_ptr<Service::SM::ServiceManager> service_manager;
  252. /// Telemetry session for this emulation session
  253. std::unique_ptr<Core::TelemetrySession> telemetry_session;
  254. ResultStatus status = ResultStatus::Success;
  255. std::string status_details = "";
  256. /// Map of guest threads to CPU cores
  257. std::map<std::thread::id, Cpu*> thread_to_cpu;
  258. Core::PerfStats perf_stats;
  259. Core::FrameLimiter frame_limiter;
  260. };
  261. System::System() : impl{std::make_unique<Impl>()} {}
  262. System::~System() = default;
  263. Cpu& System::CurrentCpuCore() {
  264. return impl->CurrentCpuCore();
  265. }
  266. const Cpu& System::CurrentCpuCore() const {
  267. return impl->CurrentCpuCore();
  268. }
  269. System::ResultStatus System::RunLoop(bool tight_loop) {
  270. return impl->RunLoop(tight_loop);
  271. }
  272. System::ResultStatus System::SingleStep() {
  273. return RunLoop(false);
  274. }
  275. void System::InvalidateCpuInstructionCaches() {
  276. for (auto& cpu : impl->cpu_cores) {
  277. cpu->ArmInterface().ClearInstructionCache();
  278. }
  279. }
  280. System::ResultStatus System::Load(Frontend::EmuWindow& emu_window, const std::string& filepath) {
  281. return impl->Load(emu_window, filepath);
  282. }
  283. bool System::IsPoweredOn() const {
  284. return impl->cpu_barrier && impl->cpu_barrier->IsAlive();
  285. }
  286. void System::PrepareReschedule() {
  287. CurrentCpuCore().PrepareReschedule();
  288. }
  289. PerfStatsResults System::GetAndResetPerfStats() {
  290. return impl->GetAndResetPerfStats();
  291. }
  292. TelemetrySession& System::TelemetrySession() {
  293. return *impl->telemetry_session;
  294. }
  295. const TelemetrySession& System::TelemetrySession() const {
  296. return *impl->telemetry_session;
  297. }
  298. ARM_Interface& System::CurrentArmInterface() {
  299. return CurrentCpuCore().ArmInterface();
  300. }
  301. const ARM_Interface& System::CurrentArmInterface() const {
  302. return CurrentCpuCore().ArmInterface();
  303. }
  304. std::size_t System::CurrentCoreIndex() const {
  305. return CurrentCpuCore().CoreIndex();
  306. }
  307. Kernel::Scheduler& System::CurrentScheduler() {
  308. return CurrentCpuCore().Scheduler();
  309. }
  310. const Kernel::Scheduler& System::CurrentScheduler() const {
  311. return CurrentCpuCore().Scheduler();
  312. }
  313. Kernel::Scheduler& System::Scheduler(std::size_t core_index) {
  314. return CpuCore(core_index).Scheduler();
  315. }
  316. const Kernel::Scheduler& System::Scheduler(std::size_t core_index) const {
  317. return CpuCore(core_index).Scheduler();
  318. }
  319. Kernel::Process* System::CurrentProcess() {
  320. return impl->kernel.CurrentProcess();
  321. }
  322. const Kernel::Process* System::CurrentProcess() const {
  323. return impl->kernel.CurrentProcess();
  324. }
  325. ARM_Interface& System::ArmInterface(std::size_t core_index) {
  326. return CpuCore(core_index).ArmInterface();
  327. }
  328. const ARM_Interface& System::ArmInterface(std::size_t core_index) const {
  329. return CpuCore(core_index).ArmInterface();
  330. }
  331. Cpu& System::CpuCore(std::size_t core_index) {
  332. ASSERT(core_index < NUM_CPU_CORES);
  333. return *impl->cpu_cores[core_index];
  334. }
  335. const Cpu& System::CpuCore(std::size_t core_index) const {
  336. ASSERT(core_index < NUM_CPU_CORES);
  337. return *impl->cpu_cores[core_index];
  338. }
  339. ExclusiveMonitor& System::Monitor() {
  340. return *impl->cpu_exclusive_monitor;
  341. }
  342. const ExclusiveMonitor& System::Monitor() const {
  343. return *impl->cpu_exclusive_monitor;
  344. }
  345. Tegra::GPU& System::GPU() {
  346. return *impl->gpu_core;
  347. }
  348. const Tegra::GPU& System::GPU() const {
  349. return *impl->gpu_core;
  350. }
  351. VideoCore::RendererBase& System::Renderer() {
  352. return *impl->renderer;
  353. }
  354. const VideoCore::RendererBase& System::Renderer() const {
  355. return *impl->renderer;
  356. }
  357. Kernel::KernelCore& System::Kernel() {
  358. return impl->kernel;
  359. }
  360. const Kernel::KernelCore& System::Kernel() const {
  361. return impl->kernel;
  362. }
  363. Core::PerfStats& System::GetPerfStats() {
  364. return impl->perf_stats;
  365. }
  366. const Core::PerfStats& System::GetPerfStats() const {
  367. return impl->perf_stats;
  368. }
  369. Core::FrameLimiter& System::FrameLimiter() {
  370. return impl->frame_limiter;
  371. }
  372. const Core::FrameLimiter& System::FrameLimiter() const {
  373. return impl->frame_limiter;
  374. }
  375. Loader::ResultStatus System::GetGameName(std::string& out) const {
  376. return impl->GetGameName(out);
  377. }
  378. void System::SetStatus(ResultStatus new_status, const char* details) {
  379. impl->SetStatus(new_status, details);
  380. }
  381. const std::string& System::GetStatusDetails() const {
  382. return impl->status_details;
  383. }
  384. Loader::AppLoader& System::GetAppLoader() const {
  385. return *impl->app_loader;
  386. }
  387. void System::SetGPUDebugContext(std::shared_ptr<Tegra::DebugContext> context) {
  388. impl->debug_context = std::move(context);
  389. }
  390. Tegra::DebugContext* System::GetGPUDebugContext() const {
  391. return impl->debug_context.get();
  392. }
  393. void System::SetFilesystem(std::shared_ptr<FileSys::VfsFilesystem> vfs) {
  394. impl->virtual_filesystem = std::move(vfs);
  395. }
  396. std::shared_ptr<FileSys::VfsFilesystem> System::GetFilesystem() const {
  397. return impl->virtual_filesystem;
  398. }
  399. void System::SetSoftwareKeyboard(std::unique_ptr<Core::Frontend::SoftwareKeyboardApplet> applet) {
  400. impl->software_keyboard = std::move(applet);
  401. }
  402. const Core::Frontend::SoftwareKeyboardApplet& System::GetSoftwareKeyboard() const {
  403. return *impl->software_keyboard;
  404. }
  405. System::ResultStatus System::Init(Frontend::EmuWindow& emu_window) {
  406. return impl->Init(emu_window);
  407. }
  408. void System::Shutdown() {
  409. impl->Shutdown();
  410. }
  411. Service::SM::ServiceManager& System::ServiceManager() {
  412. return *impl->service_manager;
  413. }
  414. const Service::SM::ServiceManager& System::ServiceManager() const {
  415. return *impl->service_manager;
  416. }
  417. } // namespace Core