core.cpp 14 KB

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