core.cpp 15 KB

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