core.cpp 33 KB

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