core.cpp 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028
  1. // SPDX-FileCopyrightText: 2014 Citra Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <array>
  4. #include <atomic>
  5. #include <exception>
  6. #include <memory>
  7. #include <utility>
  8. #include "audio_core/audio_core.h"
  9. #include "common/fs/fs.h"
  10. #include "common/logging/log.h"
  11. #include "common/microprofile.h"
  12. #include "common/settings.h"
  13. #include "common/string_util.h"
  14. #include "core/arm/exclusive_monitor.h"
  15. #include "core/core.h"
  16. #include "core/core_timing.h"
  17. #include "core/cpu_manager.h"
  18. #include "core/debugger/debugger.h"
  19. #include "core/device_memory.h"
  20. #include "core/file_sys/bis_factory.h"
  21. #include "core/file_sys/mode.h"
  22. #include "core/file_sys/patch_manager.h"
  23. #include "core/file_sys/registered_cache.h"
  24. #include "core/file_sys/romfs_factory.h"
  25. #include "core/file_sys/savedata_factory.h"
  26. #include "core/file_sys/vfs_concat.h"
  27. #include "core/file_sys/vfs_real.h"
  28. #include "core/gpu_dirty_memory_manager.h"
  29. #include "core/hid/hid_core.h"
  30. #include "core/hle/kernel/k_memory_manager.h"
  31. #include "core/hle/kernel/k_process.h"
  32. #include "core/hle/kernel/k_resource_limit.h"
  33. #include "core/hle/kernel/k_scheduler.h"
  34. #include "core/hle/kernel/kernel.h"
  35. #include "core/hle/kernel/physical_core.h"
  36. #include "core/hle/service/am/applets/applets.h"
  37. #include "core/hle/service/apm/apm_controller.h"
  38. #include "core/hle/service/filesystem/filesystem.h"
  39. #include "core/hle/service/glue/glue_manager.h"
  40. #include "core/hle/service/service.h"
  41. #include "core/hle/service/sm/sm.h"
  42. #include "core/hle/service/time/time_manager.h"
  43. #include "core/internal_network/network.h"
  44. #include "core/loader/loader.h"
  45. #include "core/memory.h"
  46. #include "core/memory/cheat_engine.h"
  47. #include "core/perf_stats.h"
  48. #include "core/reporter.h"
  49. #include "core/telemetry_session.h"
  50. #include "core/tools/freezer.h"
  51. #include "network/network.h"
  52. #include "video_core/host1x/host1x.h"
  53. #include "video_core/renderer_base.h"
  54. #include "video_core/video_core.h"
  55. MICROPROFILE_DEFINE(ARM_CPU0, "ARM", "CPU 0", MP_RGB(255, 64, 64));
  56. MICROPROFILE_DEFINE(ARM_CPU1, "ARM", "CPU 1", MP_RGB(255, 64, 64));
  57. MICROPROFILE_DEFINE(ARM_CPU2, "ARM", "CPU 2", MP_RGB(255, 64, 64));
  58. MICROPROFILE_DEFINE(ARM_CPU3, "ARM", "CPU 3", MP_RGB(255, 64, 64));
  59. namespace Core {
  60. namespace {
  61. FileSys::StorageId GetStorageIdForFrontendSlot(
  62. std::optional<FileSys::ContentProviderUnionSlot> slot) {
  63. if (!slot.has_value()) {
  64. return FileSys::StorageId::None;
  65. }
  66. switch (*slot) {
  67. case FileSys::ContentProviderUnionSlot::UserNAND:
  68. return FileSys::StorageId::NandUser;
  69. case FileSys::ContentProviderUnionSlot::SysNAND:
  70. return FileSys::StorageId::NandSystem;
  71. case FileSys::ContentProviderUnionSlot::SDMC:
  72. return FileSys::StorageId::SdCard;
  73. case FileSys::ContentProviderUnionSlot::FrontendManual:
  74. return FileSys::StorageId::Host;
  75. default:
  76. return FileSys::StorageId::None;
  77. }
  78. }
  79. } // Anonymous namespace
  80. FileSys::VirtualFile GetGameFileFromPath(const FileSys::VirtualFilesystem& vfs,
  81. const std::string& path) {
  82. // To account for split 00+01+etc files.
  83. std::string dir_name;
  84. std::string filename;
  85. Common::SplitPath(path, &dir_name, &filename, nullptr);
  86. if (filename == "00") {
  87. const auto dir = vfs->OpenDirectory(dir_name, FileSys::Mode::Read);
  88. std::vector<FileSys::VirtualFile> concat;
  89. for (u32 i = 0; i < 0x10; ++i) {
  90. const auto file_name = fmt::format("{:02X}", i);
  91. auto next = dir->GetFile(file_name);
  92. if (next != nullptr) {
  93. concat.push_back(std::move(next));
  94. } else {
  95. next = dir->GetFile(file_name);
  96. if (next == nullptr) {
  97. break;
  98. }
  99. concat.push_back(std::move(next));
  100. }
  101. }
  102. if (concat.empty()) {
  103. return nullptr;
  104. }
  105. return FileSys::ConcatenatedVfsFile::MakeConcatenatedFile(concat, dir->GetName());
  106. }
  107. if (Common::FS::IsDir(path)) {
  108. return vfs->OpenFile(path + "/main", FileSys::Mode::Read);
  109. }
  110. return vfs->OpenFile(path, FileSys::Mode::Read);
  111. }
  112. struct System::Impl {
  113. explicit Impl(System& system)
  114. : kernel{system}, fs_controller{system}, memory{system}, hid_core{}, room_network{},
  115. cpu_manager{system}, reporter{system}, applet_manager{system}, time_manager{system},
  116. gpu_dirty_memory_write_manager{} {
  117. memory.SetGPUDirtyManagers(gpu_dirty_memory_write_manager);
  118. }
  119. void Initialize(System& system) {
  120. device_memory = std::make_unique<Core::DeviceMemory>();
  121. is_multicore = Settings::values.use_multi_core.GetValue();
  122. extended_memory_layout = Settings::values.use_unsafe_extended_memory_layout.GetValue();
  123. core_timing.SetMulticore(is_multicore);
  124. core_timing.Initialize([&system]() { system.RegisterHostThread(); });
  125. const auto posix_time = std::chrono::system_clock::now().time_since_epoch();
  126. const auto current_time =
  127. std::chrono::duration_cast<std::chrono::seconds>(posix_time).count();
  128. Settings::values.custom_rtc_differential =
  129. Settings::values.custom_rtc.value_or(current_time) - current_time;
  130. // Create a default fs if one doesn't already exist.
  131. if (virtual_filesystem == nullptr) {
  132. virtual_filesystem = std::make_shared<FileSys::RealVfsFilesystem>();
  133. }
  134. if (content_provider == nullptr) {
  135. content_provider = std::make_unique<FileSys::ContentProviderUnion>();
  136. }
  137. // Create default implementations of applets if one is not provided.
  138. applet_manager.SetDefaultAppletsIfMissing();
  139. is_async_gpu = Settings::values.use_asynchronous_gpu_emulation.GetValue();
  140. kernel.SetMulticore(is_multicore);
  141. cpu_manager.SetMulticore(is_multicore);
  142. cpu_manager.SetAsyncGpu(is_async_gpu);
  143. }
  144. void ReinitializeIfNecessary(System& system) {
  145. const bool must_reinitialize =
  146. is_multicore != Settings::values.use_multi_core.GetValue() ||
  147. extended_memory_layout != Settings::values.use_unsafe_extended_memory_layout.GetValue();
  148. if (!must_reinitialize) {
  149. return;
  150. }
  151. LOG_DEBUG(Kernel, "Re-initializing");
  152. is_multicore = Settings::values.use_multi_core.GetValue();
  153. extended_memory_layout = Settings::values.use_unsafe_extended_memory_layout.GetValue();
  154. Initialize(system);
  155. }
  156. void Run() {
  157. std::unique_lock<std::mutex> lk(suspend_guard);
  158. kernel.SuspendApplication(false);
  159. core_timing.SyncPause(false);
  160. is_paused.store(false, std::memory_order_relaxed);
  161. }
  162. void Pause() {
  163. std::unique_lock<std::mutex> lk(suspend_guard);
  164. core_timing.SyncPause(true);
  165. kernel.SuspendApplication(true);
  166. is_paused.store(true, std::memory_order_relaxed);
  167. }
  168. bool IsPaused() const {
  169. return is_paused.load(std::memory_order_relaxed);
  170. }
  171. std::unique_lock<std::mutex> StallApplication() {
  172. std::unique_lock<std::mutex> lk(suspend_guard);
  173. kernel.SuspendApplication(true);
  174. core_timing.SyncPause(true);
  175. return lk;
  176. }
  177. void UnstallApplication() {
  178. if (!IsPaused()) {
  179. core_timing.SyncPause(false);
  180. kernel.SuspendApplication(false);
  181. }
  182. }
  183. void SetNVDECActive(bool is_nvdec_active) {
  184. nvdec_active = is_nvdec_active;
  185. }
  186. bool GetNVDECActive() {
  187. return nvdec_active;
  188. }
  189. void InitializeDebugger(System& system, u16 port) {
  190. debugger = std::make_unique<Debugger>(system, port);
  191. }
  192. SystemResultStatus SetupForApplicationProcess(System& system, Frontend::EmuWindow& emu_window) {
  193. LOG_DEBUG(Core, "initialized OK");
  194. // Setting changes may require a full system reinitialization (e.g., disabling multicore).
  195. ReinitializeIfNecessary(system);
  196. memory.SetGPUDirtyManagers(gpu_dirty_memory_write_manager);
  197. kernel.Initialize();
  198. cpu_manager.Initialize();
  199. /// Reset all glue registrations
  200. arp_manager.ResetAll();
  201. telemetry_session = std::make_unique<Core::TelemetrySession>();
  202. host1x_core = std::make_unique<Tegra::Host1x::Host1x>(system);
  203. gpu_core = VideoCore::CreateGPU(emu_window, system);
  204. if (!gpu_core) {
  205. return SystemResultStatus::ErrorVideoCore;
  206. }
  207. audio_core = std::make_unique<AudioCore::AudioCore>(system);
  208. service_manager = std::make_shared<Service::SM::ServiceManager>(kernel);
  209. services = std::make_unique<Service::Services>(service_manager, system);
  210. // Initialize time manager, which must happen after kernel is created
  211. time_manager.Initialize();
  212. is_powered_on = true;
  213. exit_lock = false;
  214. microprofile_cpu[0] = MICROPROFILE_TOKEN(ARM_CPU0);
  215. microprofile_cpu[1] = MICROPROFILE_TOKEN(ARM_CPU1);
  216. microprofile_cpu[2] = MICROPROFILE_TOKEN(ARM_CPU2);
  217. microprofile_cpu[3] = MICROPROFILE_TOKEN(ARM_CPU3);
  218. LOG_DEBUG(Core, "Initialized OK");
  219. return SystemResultStatus::Success;
  220. }
  221. SystemResultStatus Load(System& system, Frontend::EmuWindow& emu_window,
  222. const std::string& filepath, u64 program_id,
  223. std::size_t program_index) {
  224. app_loader = Loader::GetLoader(system, GetGameFileFromPath(virtual_filesystem, filepath),
  225. program_id, program_index);
  226. if (!app_loader) {
  227. LOG_CRITICAL(Core, "Failed to obtain loader for {}!", filepath);
  228. return SystemResultStatus::ErrorGetLoader;
  229. }
  230. SystemResultStatus init_result{SetupForApplicationProcess(system, emu_window)};
  231. if (init_result != SystemResultStatus::Success) {
  232. LOG_CRITICAL(Core, "Failed to initialize system (Error {})!",
  233. static_cast<int>(init_result));
  234. ShutdownMainProcess();
  235. return init_result;
  236. }
  237. telemetry_session->AddInitialInfo(*app_loader, fs_controller, *content_provider);
  238. // Create a resource limit for the process.
  239. const auto physical_memory_size =
  240. kernel.MemoryManager().GetSize(Kernel::KMemoryManager::Pool::Application);
  241. auto* resource_limit = Kernel::CreateResourceLimitForProcess(system, physical_memory_size);
  242. // Create the process.
  243. auto main_process = Kernel::KProcess::Create(system.Kernel());
  244. ASSERT(Kernel::KProcess::Initialize(main_process, system, "main",
  245. Kernel::KProcess::ProcessType::Userland, resource_limit)
  246. .IsSuccess());
  247. Kernel::KProcess::Register(system.Kernel(), main_process);
  248. kernel.MakeApplicationProcess(main_process);
  249. const auto [load_result, load_parameters] = app_loader->Load(*main_process, system);
  250. if (load_result != Loader::ResultStatus::Success) {
  251. LOG_CRITICAL(Core, "Failed to load ROM (Error {})!", load_result);
  252. ShutdownMainProcess();
  253. return static_cast<SystemResultStatus>(
  254. static_cast<u32>(SystemResultStatus::ErrorLoader) + static_cast<u32>(load_result));
  255. }
  256. AddGlueRegistrationForProcess(*app_loader, *main_process);
  257. kernel.InitializeCores();
  258. // Initialize cheat engine
  259. if (cheat_engine) {
  260. cheat_engine->Initialize();
  261. }
  262. // All threads are started, begin main process execution, now that we're in the clear.
  263. main_process->Run(load_parameters->main_thread_priority,
  264. load_parameters->main_thread_stack_size);
  265. if (Settings::values.gamecard_inserted) {
  266. if (Settings::values.gamecard_current_game) {
  267. fs_controller.SetGameCard(GetGameFileFromPath(virtual_filesystem, filepath));
  268. } else if (!Settings::values.gamecard_path.GetValue().empty()) {
  269. const auto& gamecard_path = Settings::values.gamecard_path.GetValue();
  270. fs_controller.SetGameCard(GetGameFileFromPath(virtual_filesystem, gamecard_path));
  271. }
  272. }
  273. if (app_loader->ReadProgramId(program_id) != Loader::ResultStatus::Success) {
  274. LOG_ERROR(Core, "Failed to find title id for ROM (Error {})", load_result);
  275. }
  276. perf_stats = std::make_unique<PerfStats>(program_id);
  277. // Reset counters and set time origin to current frame
  278. GetAndResetPerfStats();
  279. perf_stats->BeginSystemFrame();
  280. std::string name = "Unknown Game";
  281. if (app_loader->ReadTitle(name) != Loader::ResultStatus::Success) {
  282. LOG_ERROR(Core, "Failed to read title for ROM (Error {})", load_result);
  283. }
  284. std::string title_version;
  285. const FileSys::PatchManager pm(program_id, system.GetFileSystemController(),
  286. system.GetContentProvider());
  287. const auto metadata = pm.GetControlMetadata();
  288. if (metadata.first != nullptr) {
  289. title_version = metadata.first->GetVersionString();
  290. }
  291. if (auto room_member = room_network.GetRoomMember().lock()) {
  292. Network::GameInfo game_info;
  293. game_info.name = name;
  294. game_info.id = program_id;
  295. game_info.version = title_version;
  296. room_member->SendGameInfo(game_info);
  297. }
  298. status = SystemResultStatus::Success;
  299. return status;
  300. }
  301. void ShutdownMainProcess() {
  302. SetShuttingDown(true);
  303. // Log last frame performance stats if game was loaded
  304. if (perf_stats) {
  305. const auto perf_results = GetAndResetPerfStats();
  306. constexpr auto performance = Common::Telemetry::FieldType::Performance;
  307. telemetry_session->AddField(performance, "Shutdown_EmulationSpeed",
  308. perf_results.emulation_speed * 100.0);
  309. telemetry_session->AddField(performance, "Shutdown_Framerate",
  310. perf_results.average_game_fps);
  311. telemetry_session->AddField(performance, "Shutdown_Frametime",
  312. perf_results.frametime * 1000.0);
  313. telemetry_session->AddField(performance, "Mean_Frametime_MS",
  314. perf_stats->GetMeanFrametime());
  315. }
  316. is_powered_on = false;
  317. exit_lock = false;
  318. if (gpu_core != nullptr) {
  319. gpu_core->NotifyShutdown();
  320. }
  321. kernel.SuspendApplication(true);
  322. if (services) {
  323. services->KillNVNFlinger();
  324. }
  325. kernel.CloseServices();
  326. services.reset();
  327. service_manager.reset();
  328. cheat_engine.reset();
  329. telemetry_session.reset();
  330. time_manager.Shutdown();
  331. core_timing.ClearPendingEvents();
  332. app_loader.reset();
  333. audio_core.reset();
  334. gpu_core.reset();
  335. host1x_core.reset();
  336. perf_stats.reset();
  337. kernel.ShutdownCores();
  338. cpu_manager.Shutdown();
  339. debugger.reset();
  340. kernel.Shutdown();
  341. memory.Reset();
  342. if (auto room_member = room_network.GetRoomMember().lock()) {
  343. Network::GameInfo game_info{};
  344. room_member->SendGameInfo(game_info);
  345. }
  346. LOG_DEBUG(Core, "Shutdown OK");
  347. }
  348. bool IsShuttingDown() const {
  349. return is_shutting_down;
  350. }
  351. void SetShuttingDown(bool shutting_down) {
  352. is_shutting_down = shutting_down;
  353. }
  354. Loader::ResultStatus GetGameName(std::string& out) const {
  355. if (app_loader == nullptr)
  356. return Loader::ResultStatus::ErrorNotInitialized;
  357. return app_loader->ReadTitle(out);
  358. }
  359. void AddGlueRegistrationForProcess(Loader::AppLoader& loader, Kernel::KProcess& process) {
  360. std::vector<u8> nacp_data;
  361. FileSys::NACP nacp;
  362. if (loader.ReadControlData(nacp) == Loader::ResultStatus::Success) {
  363. nacp_data = nacp.GetRawBytes();
  364. } else {
  365. nacp_data.resize(sizeof(FileSys::RawNACP));
  366. }
  367. Service::Glue::ApplicationLaunchProperty launch{};
  368. launch.title_id = process.GetProgramId();
  369. FileSys::PatchManager pm{launch.title_id, fs_controller, *content_provider};
  370. launch.version = pm.GetGameVersion().value_or(0);
  371. // TODO(DarkLordZach): When FSController/Game Card Support is added, if
  372. // current_process_game_card use correct StorageId
  373. launch.base_game_storage_id = GetStorageIdForFrontendSlot(content_provider->GetSlotForEntry(
  374. launch.title_id, FileSys::ContentRecordType::Program));
  375. launch.update_storage_id = GetStorageIdForFrontendSlot(content_provider->GetSlotForEntry(
  376. FileSys::GetUpdateTitleID(launch.title_id), FileSys::ContentRecordType::Program));
  377. arp_manager.Register(launch.title_id, launch, std::move(nacp_data));
  378. }
  379. void SetStatus(SystemResultStatus new_status, const char* details = nullptr) {
  380. status = new_status;
  381. if (details) {
  382. status_details = details;
  383. }
  384. }
  385. PerfStatsResults GetAndResetPerfStats() {
  386. return perf_stats->GetAndResetStats(core_timing.GetGlobalTimeUs());
  387. }
  388. mutable std::mutex suspend_guard;
  389. std::atomic_bool is_paused{};
  390. std::atomic<bool> is_shutting_down{};
  391. Timing::CoreTiming core_timing;
  392. Kernel::KernelCore kernel;
  393. /// RealVfsFilesystem instance
  394. FileSys::VirtualFilesystem virtual_filesystem;
  395. /// ContentProviderUnion instance
  396. std::unique_ptr<FileSys::ContentProviderUnion> content_provider;
  397. Service::FileSystem::FileSystemController fs_controller;
  398. /// AppLoader used to load the current executing application
  399. std::unique_ptr<Loader::AppLoader> app_loader;
  400. std::unique_ptr<Tegra::GPU> gpu_core;
  401. std::unique_ptr<Tegra::Host1x::Host1x> host1x_core;
  402. std::unique_ptr<Core::DeviceMemory> device_memory;
  403. std::unique_ptr<AudioCore::AudioCore> audio_core;
  404. Core::Memory::Memory memory;
  405. Core::HID::HIDCore hid_core;
  406. Network::RoomNetwork room_network;
  407. CpuManager cpu_manager;
  408. std::atomic_bool is_powered_on{};
  409. bool exit_lock = false;
  410. bool nvdec_active{};
  411. Reporter reporter;
  412. std::unique_ptr<Memory::CheatEngine> cheat_engine;
  413. std::unique_ptr<Tools::Freezer> memory_freezer;
  414. std::array<u8, 0x20> build_id{};
  415. /// Frontend applets
  416. Service::AM::Applets::AppletManager applet_manager;
  417. /// APM (Performance) services
  418. Service::APM::Controller apm_controller{core_timing};
  419. /// Service State
  420. Service::Glue::ARPManager arp_manager;
  421. Service::Time::TimeManager time_manager;
  422. /// Service manager
  423. std::shared_ptr<Service::SM::ServiceManager> service_manager;
  424. /// Services
  425. std::unique_ptr<Service::Services> services;
  426. /// Telemetry session for this emulation session
  427. std::unique_ptr<Core::TelemetrySession> telemetry_session;
  428. /// Network instance
  429. Network::NetworkInstance network_instance;
  430. /// Debugger
  431. std::unique_ptr<Core::Debugger> debugger;
  432. SystemResultStatus status = SystemResultStatus::Success;
  433. std::string status_details = "";
  434. std::unique_ptr<Core::PerfStats> perf_stats;
  435. Core::SpeedLimiter speed_limiter;
  436. bool is_multicore{};
  437. bool is_async_gpu{};
  438. bool extended_memory_layout{};
  439. ExecuteProgramCallback execute_program_callback;
  440. ExitCallback exit_callback;
  441. std::array<u64, Core::Hardware::NUM_CPU_CORES> dynarmic_ticks{};
  442. std::array<MicroProfileToken, Core::Hardware::NUM_CPU_CORES> microprofile_cpu{};
  443. std::array<Core::GPUDirtyMemoryManager, Core::Hardware::NUM_CPU_CORES>
  444. gpu_dirty_memory_write_manager{};
  445. };
  446. System::System() : impl{std::make_unique<Impl>(*this)} {}
  447. System::~System() = default;
  448. CpuManager& System::GetCpuManager() {
  449. return impl->cpu_manager;
  450. }
  451. const CpuManager& System::GetCpuManager() const {
  452. return impl->cpu_manager;
  453. }
  454. void System::Initialize() {
  455. impl->Initialize(*this);
  456. }
  457. void System::Run() {
  458. impl->Run();
  459. }
  460. void System::Pause() {
  461. impl->Pause();
  462. }
  463. bool System::IsPaused() const {
  464. return impl->IsPaused();
  465. }
  466. void System::InvalidateCpuInstructionCaches() {
  467. impl->kernel.InvalidateAllInstructionCaches();
  468. }
  469. void System::InvalidateCpuInstructionCacheRange(u64 addr, std::size_t size) {
  470. impl->kernel.InvalidateCpuInstructionCacheRange(addr, size);
  471. }
  472. void System::ShutdownMainProcess() {
  473. impl->ShutdownMainProcess();
  474. }
  475. bool System::IsShuttingDown() const {
  476. return impl->IsShuttingDown();
  477. }
  478. void System::SetShuttingDown(bool shutting_down) {
  479. impl->SetShuttingDown(shutting_down);
  480. }
  481. void System::DetachDebugger() {
  482. if (impl->debugger) {
  483. impl->debugger->NotifyShutdown();
  484. }
  485. }
  486. std::unique_lock<std::mutex> System::StallApplication() {
  487. return impl->StallApplication();
  488. }
  489. void System::UnstallApplication() {
  490. impl->UnstallApplication();
  491. }
  492. void System::SetNVDECActive(bool is_nvdec_active) {
  493. impl->SetNVDECActive(is_nvdec_active);
  494. }
  495. bool System::GetNVDECActive() {
  496. return impl->GetNVDECActive();
  497. }
  498. void System::InitializeDebugger() {
  499. impl->InitializeDebugger(*this, Settings::values.gdbstub_port.GetValue());
  500. }
  501. SystemResultStatus System::Load(Frontend::EmuWindow& emu_window, const std::string& filepath,
  502. u64 program_id, std::size_t program_index) {
  503. return impl->Load(*this, emu_window, filepath, program_id, program_index);
  504. }
  505. bool System::IsPoweredOn() const {
  506. return impl->is_powered_on.load(std::memory_order::relaxed);
  507. }
  508. void System::PrepareReschedule(const u32 core_index) {
  509. impl->kernel.PrepareReschedule(core_index);
  510. }
  511. Core::GPUDirtyMemoryManager& System::CurrentGPUDirtyMemoryManager() {
  512. const std::size_t core = impl->kernel.GetCurrentHostThreadID();
  513. return impl->gpu_dirty_memory_write_manager[core < Core::Hardware::NUM_CPU_CORES
  514. ? core
  515. : Core::Hardware::NUM_CPU_CORES - 1];
  516. }
  517. /// Provides a constant reference to the current gou dirty memory manager.
  518. const Core::GPUDirtyMemoryManager& System::CurrentGPUDirtyMemoryManager() const {
  519. const std::size_t core = impl->kernel.GetCurrentHostThreadID();
  520. return impl->gpu_dirty_memory_write_manager[core < Core::Hardware::NUM_CPU_CORES
  521. ? core
  522. : Core::Hardware::NUM_CPU_CORES - 1];
  523. }
  524. size_t System::GetCurrentHostThreadID() const {
  525. return impl->kernel.GetCurrentHostThreadID();
  526. }
  527. void System::GatherGPUDirtyMemory(std::function<void(VAddr, size_t)>& callback) {
  528. for (auto& manager : impl->gpu_dirty_memory_write_manager) {
  529. manager.Gather(callback);
  530. }
  531. }
  532. PerfStatsResults System::GetAndResetPerfStats() {
  533. return impl->GetAndResetPerfStats();
  534. }
  535. TelemetrySession& System::TelemetrySession() {
  536. return *impl->telemetry_session;
  537. }
  538. const TelemetrySession& System::TelemetrySession() const {
  539. return *impl->telemetry_session;
  540. }
  541. ARM_Interface& System::CurrentArmInterface() {
  542. return impl->kernel.CurrentPhysicalCore().ArmInterface();
  543. }
  544. const ARM_Interface& System::CurrentArmInterface() const {
  545. return impl->kernel.CurrentPhysicalCore().ArmInterface();
  546. }
  547. Kernel::PhysicalCore& System::CurrentPhysicalCore() {
  548. return impl->kernel.CurrentPhysicalCore();
  549. }
  550. const Kernel::PhysicalCore& System::CurrentPhysicalCore() const {
  551. return impl->kernel.CurrentPhysicalCore();
  552. }
  553. /// Gets the global scheduler
  554. Kernel::GlobalSchedulerContext& System::GlobalSchedulerContext() {
  555. return impl->kernel.GlobalSchedulerContext();
  556. }
  557. /// Gets the global scheduler
  558. const Kernel::GlobalSchedulerContext& System::GlobalSchedulerContext() const {
  559. return impl->kernel.GlobalSchedulerContext();
  560. }
  561. Kernel::KProcess* System::ApplicationProcess() {
  562. return impl->kernel.ApplicationProcess();
  563. }
  564. Core::DeviceMemory& System::DeviceMemory() {
  565. return *impl->device_memory;
  566. }
  567. const Core::DeviceMemory& System::DeviceMemory() const {
  568. return *impl->device_memory;
  569. }
  570. const Kernel::KProcess* System::ApplicationProcess() const {
  571. return impl->kernel.ApplicationProcess();
  572. }
  573. ARM_Interface& System::ArmInterface(std::size_t core_index) {
  574. return impl->kernel.PhysicalCore(core_index).ArmInterface();
  575. }
  576. const ARM_Interface& System::ArmInterface(std::size_t core_index) const {
  577. return impl->kernel.PhysicalCore(core_index).ArmInterface();
  578. }
  579. ExclusiveMonitor& System::Monitor() {
  580. return impl->kernel.GetExclusiveMonitor();
  581. }
  582. const ExclusiveMonitor& System::Monitor() const {
  583. return impl->kernel.GetExclusiveMonitor();
  584. }
  585. Memory::Memory& System::ApplicationMemory() {
  586. return impl->memory;
  587. }
  588. const Core::Memory::Memory& System::ApplicationMemory() const {
  589. return impl->memory;
  590. }
  591. Tegra::GPU& System::GPU() {
  592. return *impl->gpu_core;
  593. }
  594. const Tegra::GPU& System::GPU() const {
  595. return *impl->gpu_core;
  596. }
  597. Tegra::Host1x::Host1x& System::Host1x() {
  598. return *impl->host1x_core;
  599. }
  600. const Tegra::Host1x::Host1x& System::Host1x() const {
  601. return *impl->host1x_core;
  602. }
  603. VideoCore::RendererBase& System::Renderer() {
  604. return impl->gpu_core->Renderer();
  605. }
  606. const VideoCore::RendererBase& System::Renderer() const {
  607. return impl->gpu_core->Renderer();
  608. }
  609. Kernel::KernelCore& System::Kernel() {
  610. return impl->kernel;
  611. }
  612. const Kernel::KernelCore& System::Kernel() const {
  613. return impl->kernel;
  614. }
  615. HID::HIDCore& System::HIDCore() {
  616. return impl->hid_core;
  617. }
  618. const HID::HIDCore& System::HIDCore() const {
  619. return impl->hid_core;
  620. }
  621. AudioCore::AudioCore& System::AudioCore() {
  622. return *impl->audio_core;
  623. }
  624. const AudioCore::AudioCore& System::AudioCore() const {
  625. return *impl->audio_core;
  626. }
  627. Timing::CoreTiming& System::CoreTiming() {
  628. return impl->core_timing;
  629. }
  630. const Timing::CoreTiming& System::CoreTiming() const {
  631. return impl->core_timing;
  632. }
  633. Core::PerfStats& System::GetPerfStats() {
  634. return *impl->perf_stats;
  635. }
  636. const Core::PerfStats& System::GetPerfStats() const {
  637. return *impl->perf_stats;
  638. }
  639. Core::SpeedLimiter& System::SpeedLimiter() {
  640. return impl->speed_limiter;
  641. }
  642. const Core::SpeedLimiter& System::SpeedLimiter() const {
  643. return impl->speed_limiter;
  644. }
  645. u64 System::GetApplicationProcessProgramID() const {
  646. return impl->kernel.ApplicationProcess()->GetProgramId();
  647. }
  648. Loader::ResultStatus System::GetGameName(std::string& out) const {
  649. return impl->GetGameName(out);
  650. }
  651. void System::SetStatus(SystemResultStatus new_status, const char* details) {
  652. impl->SetStatus(new_status, details);
  653. }
  654. const std::string& System::GetStatusDetails() const {
  655. return impl->status_details;
  656. }
  657. Loader::AppLoader& System::GetAppLoader() {
  658. return *impl->app_loader;
  659. }
  660. const Loader::AppLoader& System::GetAppLoader() const {
  661. return *impl->app_loader;
  662. }
  663. void System::SetFilesystem(FileSys::VirtualFilesystem vfs) {
  664. impl->virtual_filesystem = std::move(vfs);
  665. }
  666. FileSys::VirtualFilesystem System::GetFilesystem() const {
  667. return impl->virtual_filesystem;
  668. }
  669. void System::RegisterCheatList(const std::vector<Memory::CheatEntry>& list,
  670. const std::array<u8, 32>& build_id, u64 main_region_begin,
  671. u64 main_region_size) {
  672. impl->cheat_engine = std::make_unique<Memory::CheatEngine>(*this, list, build_id);
  673. impl->cheat_engine->SetMainMemoryParameters(main_region_begin, main_region_size);
  674. }
  675. void System::SetAppletFrontendSet(Service::AM::Applets::AppletFrontendSet&& set) {
  676. impl->applet_manager.SetAppletFrontendSet(std::move(set));
  677. }
  678. void System::SetDefaultAppletFrontendSet() {
  679. impl->applet_manager.SetDefaultAppletFrontendSet();
  680. }
  681. Service::AM::Applets::AppletManager& System::GetAppletManager() {
  682. return impl->applet_manager;
  683. }
  684. const Service::AM::Applets::AppletManager& System::GetAppletManager() const {
  685. return impl->applet_manager;
  686. }
  687. void System::SetContentProvider(std::unique_ptr<FileSys::ContentProviderUnion> provider) {
  688. impl->content_provider = std::move(provider);
  689. }
  690. FileSys::ContentProvider& System::GetContentProvider() {
  691. return *impl->content_provider;
  692. }
  693. const FileSys::ContentProvider& System::GetContentProvider() const {
  694. return *impl->content_provider;
  695. }
  696. Service::FileSystem::FileSystemController& System::GetFileSystemController() {
  697. return impl->fs_controller;
  698. }
  699. const Service::FileSystem::FileSystemController& System::GetFileSystemController() const {
  700. return impl->fs_controller;
  701. }
  702. void System::RegisterContentProvider(FileSys::ContentProviderUnionSlot slot,
  703. FileSys::ContentProvider* provider) {
  704. impl->content_provider->SetSlot(slot, provider);
  705. }
  706. void System::ClearContentProvider(FileSys::ContentProviderUnionSlot slot) {
  707. impl->content_provider->ClearSlot(slot);
  708. }
  709. const Reporter& System::GetReporter() const {
  710. return impl->reporter;
  711. }
  712. Service::Glue::ARPManager& System::GetARPManager() {
  713. return impl->arp_manager;
  714. }
  715. const Service::Glue::ARPManager& System::GetARPManager() const {
  716. return impl->arp_manager;
  717. }
  718. Service::APM::Controller& System::GetAPMController() {
  719. return impl->apm_controller;
  720. }
  721. const Service::APM::Controller& System::GetAPMController() const {
  722. return impl->apm_controller;
  723. }
  724. Service::Time::TimeManager& System::GetTimeManager() {
  725. return impl->time_manager;
  726. }
  727. const Service::Time::TimeManager& System::GetTimeManager() const {
  728. return impl->time_manager;
  729. }
  730. void System::SetExitLock(bool locked) {
  731. impl->exit_lock = locked;
  732. }
  733. bool System::GetExitLock() const {
  734. return impl->exit_lock;
  735. }
  736. void System::SetApplicationProcessBuildID(const CurrentBuildProcessID& id) {
  737. impl->build_id = id;
  738. }
  739. const System::CurrentBuildProcessID& System::GetApplicationProcessBuildID() const {
  740. return impl->build_id;
  741. }
  742. Service::SM::ServiceManager& System::ServiceManager() {
  743. return *impl->service_manager;
  744. }
  745. const Service::SM::ServiceManager& System::ServiceManager() const {
  746. return *impl->service_manager;
  747. }
  748. void System::RegisterCoreThread(std::size_t id) {
  749. impl->kernel.RegisterCoreThread(id);
  750. }
  751. void System::RegisterHostThread() {
  752. impl->kernel.RegisterHostThread();
  753. }
  754. void System::EnterCPUProfile() {
  755. std::size_t core = impl->kernel.GetCurrentHostThreadID();
  756. impl->dynarmic_ticks[core] = MicroProfileEnter(impl->microprofile_cpu[core]);
  757. }
  758. void System::ExitCPUProfile() {
  759. std::size_t core = impl->kernel.GetCurrentHostThreadID();
  760. MicroProfileLeave(impl->microprofile_cpu[core], impl->dynarmic_ticks[core]);
  761. }
  762. bool System::IsMulticore() const {
  763. return impl->is_multicore;
  764. }
  765. bool System::DebuggerEnabled() const {
  766. return Settings::values.use_gdbstub.GetValue();
  767. }
  768. Core::Debugger& System::GetDebugger() {
  769. return *impl->debugger;
  770. }
  771. const Core::Debugger& System::GetDebugger() const {
  772. return *impl->debugger;
  773. }
  774. Network::RoomNetwork& System::GetRoomNetwork() {
  775. return impl->room_network;
  776. }
  777. const Network::RoomNetwork& System::GetRoomNetwork() const {
  778. return impl->room_network;
  779. }
  780. void System::RunServer(std::unique_ptr<Service::ServerManager>&& server_manager) {
  781. return impl->kernel.RunServer(std::move(server_manager));
  782. }
  783. void System::RegisterExecuteProgramCallback(ExecuteProgramCallback&& callback) {
  784. impl->execute_program_callback = std::move(callback);
  785. }
  786. void System::ExecuteProgram(std::size_t program_index) {
  787. if (impl->execute_program_callback) {
  788. impl->execute_program_callback(program_index);
  789. } else {
  790. LOG_CRITICAL(Core, "execute_program_callback must be initialized by the frontend");
  791. }
  792. }
  793. void System::RegisterExitCallback(ExitCallback&& callback) {
  794. impl->exit_callback = std::move(callback);
  795. }
  796. void System::Exit() {
  797. if (impl->exit_callback) {
  798. impl->exit_callback();
  799. } else {
  800. LOG_CRITICAL(Core, "exit_callback must be initialized by the frontend");
  801. }
  802. }
  803. void System::ApplySettings() {
  804. if (IsPoweredOn()) {
  805. Renderer().RefreshBaseSettings();
  806. }
  807. }
  808. } // namespace Core