core.cpp 32 KB

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