core.cpp 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079
  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 the process.
  251. auto main_process = Kernel::KProcess::Create(system.Kernel());
  252. Kernel::KProcess::Register(system.Kernel(), main_process);
  253. kernel.AppendNewProcess(main_process);
  254. kernel.MakeApplicationProcess(main_process);
  255. const auto [load_result, load_parameters] = app_loader->Load(*main_process, system);
  256. if (load_result != Loader::ResultStatus::Success) {
  257. LOG_CRITICAL(Core, "Failed to load ROM (Error {})!", load_result);
  258. ShutdownMainProcess();
  259. return static_cast<SystemResultStatus>(
  260. static_cast<u32>(SystemResultStatus::ErrorLoader) + static_cast<u32>(load_result));
  261. }
  262. AddGlueRegistrationForProcess(*app_loader, *main_process);
  263. kernel.InitializeCores();
  264. // Initialize cheat engine
  265. if (cheat_engine) {
  266. cheat_engine->Initialize();
  267. }
  268. // All threads are started, begin main process execution, now that we're in the clear.
  269. main_process->Run(load_parameters->main_thread_priority,
  270. load_parameters->main_thread_stack_size);
  271. if (Settings::values.gamecard_inserted) {
  272. if (Settings::values.gamecard_current_game) {
  273. fs_controller.SetGameCard(GetGameFileFromPath(virtual_filesystem, filepath));
  274. } else if (!Settings::values.gamecard_path.GetValue().empty()) {
  275. const auto& gamecard_path = Settings::values.gamecard_path.GetValue();
  276. fs_controller.SetGameCard(GetGameFileFromPath(virtual_filesystem, gamecard_path));
  277. }
  278. }
  279. if (app_loader->ReadProgramId(program_id) != Loader::ResultStatus::Success) {
  280. LOG_ERROR(Core, "Failed to find title id for ROM (Error {})", load_result);
  281. }
  282. perf_stats = std::make_unique<PerfStats>(program_id);
  283. // Reset counters and set time origin to current frame
  284. GetAndResetPerfStats();
  285. perf_stats->BeginSystemFrame();
  286. std::string name = "Unknown Game";
  287. if (app_loader->ReadTitle(name) != Loader::ResultStatus::Success) {
  288. LOG_ERROR(Core, "Failed to read title for ROM (Error {})", load_result);
  289. }
  290. std::string title_version;
  291. const FileSys::PatchManager pm(program_id, system.GetFileSystemController(),
  292. system.GetContentProvider());
  293. const auto metadata = pm.GetControlMetadata();
  294. if (metadata.first != nullptr) {
  295. title_version = metadata.first->GetVersionString();
  296. }
  297. if (auto room_member = room_network.GetRoomMember().lock()) {
  298. Network::GameInfo game_info;
  299. game_info.name = name;
  300. game_info.id = program_id;
  301. game_info.version = title_version;
  302. room_member->SendGameInfo(game_info);
  303. }
  304. // Workarounds:
  305. // Activate this in Super Smash Brothers Ultimate, it only affects AMD cards using AMDVLK
  306. Settings::values.renderer_amdvlk_depth_bias_workaround = program_id == 0x1006A800016E000ULL;
  307. status = SystemResultStatus::Success;
  308. return status;
  309. }
  310. void ShutdownMainProcess() {
  311. SetShuttingDown(true);
  312. // Log last frame performance stats if game was loaded
  313. if (perf_stats) {
  314. const auto perf_results = GetAndResetPerfStats();
  315. constexpr auto performance = Common::Telemetry::FieldType::Performance;
  316. telemetry_session->AddField(performance, "Shutdown_EmulationSpeed",
  317. perf_results.emulation_speed * 100.0);
  318. telemetry_session->AddField(performance, "Shutdown_Framerate",
  319. perf_results.average_game_fps);
  320. telemetry_session->AddField(performance, "Shutdown_Frametime",
  321. perf_results.frametime * 1000.0);
  322. telemetry_session->AddField(performance, "Mean_Frametime_MS",
  323. perf_stats->GetMeanFrametime());
  324. }
  325. is_powered_on = false;
  326. exit_locked = false;
  327. exit_requested = false;
  328. if (gpu_core != nullptr) {
  329. gpu_core->NotifyShutdown();
  330. }
  331. Network::CancelPendingSocketOperations();
  332. kernel.SuspendApplication(true);
  333. if (services) {
  334. services->KillNVNFlinger();
  335. }
  336. kernel.CloseServices();
  337. kernel.ShutdownCores();
  338. services.reset();
  339. service_manager.reset();
  340. cheat_engine.reset();
  341. telemetry_session.reset();
  342. time_manager.Shutdown();
  343. core_timing.ClearPendingEvents();
  344. app_loader.reset();
  345. audio_core.reset();
  346. gpu_core.reset();
  347. host1x_core.reset();
  348. perf_stats.reset();
  349. cpu_manager.Shutdown();
  350. debugger.reset();
  351. kernel.Shutdown();
  352. memory.Reset();
  353. Network::RestartSocketOperations();
  354. if (auto room_member = room_network.GetRoomMember().lock()) {
  355. Network::GameInfo game_info{};
  356. room_member->SendGameInfo(game_info);
  357. }
  358. // Workarounds
  359. Settings::values.renderer_amdvlk_depth_bias_workaround = false;
  360. LOG_DEBUG(Core, "Shutdown OK");
  361. }
  362. bool IsShuttingDown() const {
  363. return is_shutting_down;
  364. }
  365. void SetShuttingDown(bool shutting_down) {
  366. is_shutting_down = shutting_down;
  367. }
  368. Loader::ResultStatus GetGameName(std::string& out) const {
  369. if (app_loader == nullptr)
  370. return Loader::ResultStatus::ErrorNotInitialized;
  371. return app_loader->ReadTitle(out);
  372. }
  373. void AddGlueRegistrationForProcess(Loader::AppLoader& loader, Kernel::KProcess& process) {
  374. std::vector<u8> nacp_data;
  375. FileSys::NACP nacp;
  376. if (loader.ReadControlData(nacp) == Loader::ResultStatus::Success) {
  377. nacp_data = nacp.GetRawBytes();
  378. } else {
  379. nacp_data.resize(sizeof(FileSys::RawNACP));
  380. }
  381. Service::Glue::ApplicationLaunchProperty launch{};
  382. launch.title_id = process.GetProgramId();
  383. FileSys::PatchManager pm{launch.title_id, fs_controller, *content_provider};
  384. launch.version = pm.GetGameVersion().value_or(0);
  385. // TODO(DarkLordZach): When FSController/Game Card Support is added, if
  386. // current_process_game_card use correct StorageId
  387. launch.base_game_storage_id = GetStorageIdForFrontendSlot(content_provider->GetSlotForEntry(
  388. launch.title_id, FileSys::ContentRecordType::Program));
  389. launch.update_storage_id = GetStorageIdForFrontendSlot(content_provider->GetSlotForEntry(
  390. FileSys::GetUpdateTitleID(launch.title_id), FileSys::ContentRecordType::Program));
  391. arp_manager.Register(launch.title_id, launch, std::move(nacp_data));
  392. }
  393. void SetStatus(SystemResultStatus new_status, const char* details = nullptr) {
  394. status = new_status;
  395. if (details) {
  396. status_details = details;
  397. }
  398. }
  399. PerfStatsResults GetAndResetPerfStats() {
  400. return perf_stats->GetAndResetStats(core_timing.GetGlobalTimeUs());
  401. }
  402. mutable std::mutex suspend_guard;
  403. std::atomic_bool is_paused{};
  404. std::atomic<bool> is_shutting_down{};
  405. Timing::CoreTiming core_timing;
  406. Kernel::KernelCore kernel;
  407. /// RealVfsFilesystem instance
  408. FileSys::VirtualFilesystem virtual_filesystem;
  409. /// ContentProviderUnion instance
  410. std::unique_ptr<FileSys::ContentProviderUnion> content_provider;
  411. Service::FileSystem::FileSystemController fs_controller;
  412. /// AppLoader used to load the current executing application
  413. std::unique_ptr<Loader::AppLoader> app_loader;
  414. std::unique_ptr<Tegra::GPU> gpu_core;
  415. std::unique_ptr<Tegra::Host1x::Host1x> host1x_core;
  416. std::unique_ptr<Core::DeviceMemory> device_memory;
  417. std::unique_ptr<AudioCore::AudioCore> audio_core;
  418. Core::Memory::Memory memory;
  419. Core::HID::HIDCore hid_core;
  420. Network::RoomNetwork room_network;
  421. CpuManager cpu_manager;
  422. std::atomic_bool is_powered_on{};
  423. bool exit_locked = false;
  424. bool exit_requested = false;
  425. bool nvdec_active{};
  426. Reporter reporter;
  427. std::unique_ptr<Memory::CheatEngine> cheat_engine;
  428. std::unique_ptr<Tools::Freezer> memory_freezer;
  429. std::array<u8, 0x20> build_id{};
  430. std::unique_ptr<Tools::RenderdocAPI> renderdoc_api;
  431. /// Frontend applets
  432. Service::AM::Applets::AppletManager applet_manager;
  433. /// APM (Performance) services
  434. Service::APM::Controller apm_controller{core_timing};
  435. /// Service State
  436. Service::Glue::ARPManager arp_manager;
  437. Service::Time::TimeManager time_manager;
  438. /// Service manager
  439. std::shared_ptr<Service::SM::ServiceManager> service_manager;
  440. /// Services
  441. std::unique_ptr<Service::Services> services;
  442. /// Telemetry session for this emulation session
  443. std::unique_ptr<Core::TelemetrySession> telemetry_session;
  444. /// Network instance
  445. Network::NetworkInstance network_instance;
  446. /// Debugger
  447. std::unique_ptr<Core::Debugger> debugger;
  448. SystemResultStatus status = SystemResultStatus::Success;
  449. std::string status_details = "";
  450. std::unique_ptr<Core::PerfStats> perf_stats;
  451. Core::SpeedLimiter speed_limiter;
  452. bool is_multicore{};
  453. bool is_async_gpu{};
  454. bool extended_memory_layout{};
  455. ExecuteProgramCallback execute_program_callback;
  456. ExitCallback exit_callback;
  457. std::array<u64, Core::Hardware::NUM_CPU_CORES> dynarmic_ticks{};
  458. std::array<MicroProfileToken, Core::Hardware::NUM_CPU_CORES> microprofile_cpu{};
  459. std::array<Core::GPUDirtyMemoryManager, Core::Hardware::NUM_CPU_CORES>
  460. gpu_dirty_memory_write_manager{};
  461. std::deque<std::vector<u8>> user_channel;
  462. };
  463. System::System() : impl{std::make_unique<Impl>(*this)} {}
  464. System::~System() = default;
  465. CpuManager& System::GetCpuManager() {
  466. return impl->cpu_manager;
  467. }
  468. const CpuManager& System::GetCpuManager() const {
  469. return impl->cpu_manager;
  470. }
  471. void System::Initialize() {
  472. impl->Initialize(*this);
  473. }
  474. void System::Run() {
  475. impl->Run();
  476. }
  477. void System::Pause() {
  478. impl->Pause();
  479. }
  480. bool System::IsPaused() const {
  481. return impl->IsPaused();
  482. }
  483. void System::InvalidateCpuInstructionCaches() {
  484. impl->kernel.InvalidateAllInstructionCaches();
  485. }
  486. void System::InvalidateCpuInstructionCacheRange(u64 addr, std::size_t size) {
  487. impl->kernel.InvalidateCpuInstructionCacheRange(addr, size);
  488. }
  489. void System::ShutdownMainProcess() {
  490. impl->ShutdownMainProcess();
  491. }
  492. bool System::IsShuttingDown() const {
  493. return impl->IsShuttingDown();
  494. }
  495. void System::SetShuttingDown(bool shutting_down) {
  496. impl->SetShuttingDown(shutting_down);
  497. }
  498. void System::DetachDebugger() {
  499. if (impl->debugger) {
  500. impl->debugger->NotifyShutdown();
  501. }
  502. }
  503. std::unique_lock<std::mutex> System::StallApplication() {
  504. return impl->StallApplication();
  505. }
  506. void System::UnstallApplication() {
  507. impl->UnstallApplication();
  508. }
  509. void System::SetNVDECActive(bool is_nvdec_active) {
  510. impl->SetNVDECActive(is_nvdec_active);
  511. }
  512. bool System::GetNVDECActive() {
  513. return impl->GetNVDECActive();
  514. }
  515. void System::InitializeDebugger() {
  516. impl->InitializeDebugger(*this, Settings::values.gdbstub_port.GetValue());
  517. }
  518. SystemResultStatus System::Load(Frontend::EmuWindow& emu_window, const std::string& filepath,
  519. u64 program_id, std::size_t program_index) {
  520. return impl->Load(*this, emu_window, filepath, program_id, program_index);
  521. }
  522. bool System::IsPoweredOn() const {
  523. return impl->is_powered_on.load(std::memory_order::relaxed);
  524. }
  525. void System::PrepareReschedule(const u32 core_index) {
  526. impl->kernel.PrepareReschedule(core_index);
  527. }
  528. Core::GPUDirtyMemoryManager& System::CurrentGPUDirtyMemoryManager() {
  529. const std::size_t core = impl->kernel.GetCurrentHostThreadID();
  530. return impl->gpu_dirty_memory_write_manager[core < Core::Hardware::NUM_CPU_CORES
  531. ? core
  532. : Core::Hardware::NUM_CPU_CORES - 1];
  533. }
  534. /// Provides a constant reference to the current gou dirty memory manager.
  535. const Core::GPUDirtyMemoryManager& System::CurrentGPUDirtyMemoryManager() const {
  536. const std::size_t core = impl->kernel.GetCurrentHostThreadID();
  537. return impl->gpu_dirty_memory_write_manager[core < Core::Hardware::NUM_CPU_CORES
  538. ? core
  539. : Core::Hardware::NUM_CPU_CORES - 1];
  540. }
  541. size_t System::GetCurrentHostThreadID() const {
  542. return impl->kernel.GetCurrentHostThreadID();
  543. }
  544. void System::GatherGPUDirtyMemory(std::function<void(VAddr, size_t)>& callback) {
  545. for (auto& manager : impl->gpu_dirty_memory_write_manager) {
  546. manager.Gather(callback);
  547. }
  548. }
  549. PerfStatsResults System::GetAndResetPerfStats() {
  550. return impl->GetAndResetPerfStats();
  551. }
  552. TelemetrySession& System::TelemetrySession() {
  553. return *impl->telemetry_session;
  554. }
  555. const TelemetrySession& System::TelemetrySession() const {
  556. return *impl->telemetry_session;
  557. }
  558. ARM_Interface& System::CurrentArmInterface() {
  559. return impl->kernel.CurrentPhysicalCore().ArmInterface();
  560. }
  561. const ARM_Interface& System::CurrentArmInterface() const {
  562. return impl->kernel.CurrentPhysicalCore().ArmInterface();
  563. }
  564. Kernel::PhysicalCore& System::CurrentPhysicalCore() {
  565. return impl->kernel.CurrentPhysicalCore();
  566. }
  567. const Kernel::PhysicalCore& System::CurrentPhysicalCore() const {
  568. return impl->kernel.CurrentPhysicalCore();
  569. }
  570. /// Gets the global scheduler
  571. Kernel::GlobalSchedulerContext& System::GlobalSchedulerContext() {
  572. return impl->kernel.GlobalSchedulerContext();
  573. }
  574. /// Gets the global scheduler
  575. const Kernel::GlobalSchedulerContext& System::GlobalSchedulerContext() const {
  576. return impl->kernel.GlobalSchedulerContext();
  577. }
  578. Kernel::KProcess* System::ApplicationProcess() {
  579. return impl->kernel.ApplicationProcess();
  580. }
  581. Core::DeviceMemory& System::DeviceMemory() {
  582. return *impl->device_memory;
  583. }
  584. const Core::DeviceMemory& System::DeviceMemory() const {
  585. return *impl->device_memory;
  586. }
  587. const Kernel::KProcess* System::ApplicationProcess() const {
  588. return impl->kernel.ApplicationProcess();
  589. }
  590. ARM_Interface& System::ArmInterface(std::size_t core_index) {
  591. return impl->kernel.PhysicalCore(core_index).ArmInterface();
  592. }
  593. const ARM_Interface& System::ArmInterface(std::size_t core_index) const {
  594. return impl->kernel.PhysicalCore(core_index).ArmInterface();
  595. }
  596. ExclusiveMonitor& System::Monitor() {
  597. return impl->kernel.GetExclusiveMonitor();
  598. }
  599. const ExclusiveMonitor& System::Monitor() const {
  600. return impl->kernel.GetExclusiveMonitor();
  601. }
  602. Memory::Memory& System::ApplicationMemory() {
  603. return impl->memory;
  604. }
  605. const Core::Memory::Memory& System::ApplicationMemory() const {
  606. return impl->memory;
  607. }
  608. Tegra::GPU& System::GPU() {
  609. return *impl->gpu_core;
  610. }
  611. const Tegra::GPU& System::GPU() const {
  612. return *impl->gpu_core;
  613. }
  614. Tegra::Host1x::Host1x& System::Host1x() {
  615. return *impl->host1x_core;
  616. }
  617. const Tegra::Host1x::Host1x& System::Host1x() const {
  618. return *impl->host1x_core;
  619. }
  620. VideoCore::RendererBase& System::Renderer() {
  621. return impl->gpu_core->Renderer();
  622. }
  623. const VideoCore::RendererBase& System::Renderer() const {
  624. return impl->gpu_core->Renderer();
  625. }
  626. Kernel::KernelCore& System::Kernel() {
  627. return impl->kernel;
  628. }
  629. const Kernel::KernelCore& System::Kernel() const {
  630. return impl->kernel;
  631. }
  632. HID::HIDCore& System::HIDCore() {
  633. return impl->hid_core;
  634. }
  635. const HID::HIDCore& System::HIDCore() const {
  636. return impl->hid_core;
  637. }
  638. AudioCore::AudioCore& System::AudioCore() {
  639. return *impl->audio_core;
  640. }
  641. const AudioCore::AudioCore& System::AudioCore() const {
  642. return *impl->audio_core;
  643. }
  644. Timing::CoreTiming& System::CoreTiming() {
  645. return impl->core_timing;
  646. }
  647. const Timing::CoreTiming& System::CoreTiming() const {
  648. return impl->core_timing;
  649. }
  650. Core::PerfStats& System::GetPerfStats() {
  651. return *impl->perf_stats;
  652. }
  653. const Core::PerfStats& System::GetPerfStats() const {
  654. return *impl->perf_stats;
  655. }
  656. Core::SpeedLimiter& System::SpeedLimiter() {
  657. return impl->speed_limiter;
  658. }
  659. const Core::SpeedLimiter& System::SpeedLimiter() const {
  660. return impl->speed_limiter;
  661. }
  662. u64 System::GetApplicationProcessProgramID() const {
  663. return impl->kernel.ApplicationProcess()->GetProgramId();
  664. }
  665. Loader::ResultStatus System::GetGameName(std::string& out) const {
  666. return impl->GetGameName(out);
  667. }
  668. void System::SetStatus(SystemResultStatus new_status, const char* details) {
  669. impl->SetStatus(new_status, details);
  670. }
  671. const std::string& System::GetStatusDetails() const {
  672. return impl->status_details;
  673. }
  674. Loader::AppLoader& System::GetAppLoader() {
  675. return *impl->app_loader;
  676. }
  677. const Loader::AppLoader& System::GetAppLoader() const {
  678. return *impl->app_loader;
  679. }
  680. void System::SetFilesystem(FileSys::VirtualFilesystem vfs) {
  681. impl->virtual_filesystem = std::move(vfs);
  682. }
  683. FileSys::VirtualFilesystem System::GetFilesystem() const {
  684. return impl->virtual_filesystem;
  685. }
  686. void System::RegisterCheatList(const std::vector<Memory::CheatEntry>& list,
  687. const std::array<u8, 32>& build_id, u64 main_region_begin,
  688. u64 main_region_size) {
  689. impl->cheat_engine = std::make_unique<Memory::CheatEngine>(*this, list, build_id);
  690. impl->cheat_engine->SetMainMemoryParameters(main_region_begin, main_region_size);
  691. }
  692. void System::SetAppletFrontendSet(Service::AM::Applets::AppletFrontendSet&& set) {
  693. impl->applet_manager.SetAppletFrontendSet(std::move(set));
  694. }
  695. void System::SetDefaultAppletFrontendSet() {
  696. impl->applet_manager.SetDefaultAppletFrontendSet();
  697. }
  698. Service::AM::Applets::AppletManager& System::GetAppletManager() {
  699. return impl->applet_manager;
  700. }
  701. const Service::AM::Applets::AppletManager& System::GetAppletManager() const {
  702. return impl->applet_manager;
  703. }
  704. void System::SetContentProvider(std::unique_ptr<FileSys::ContentProviderUnion> provider) {
  705. impl->content_provider = std::move(provider);
  706. }
  707. FileSys::ContentProvider& System::GetContentProvider() {
  708. return *impl->content_provider;
  709. }
  710. const FileSys::ContentProvider& System::GetContentProvider() const {
  711. return *impl->content_provider;
  712. }
  713. FileSys::ContentProviderUnion& System::GetContentProviderUnion() {
  714. return *impl->content_provider;
  715. }
  716. const FileSys::ContentProviderUnion& System::GetContentProviderUnion() const {
  717. return *impl->content_provider;
  718. }
  719. Service::FileSystem::FileSystemController& System::GetFileSystemController() {
  720. return impl->fs_controller;
  721. }
  722. const Service::FileSystem::FileSystemController& System::GetFileSystemController() const {
  723. return impl->fs_controller;
  724. }
  725. void System::RegisterContentProvider(FileSys::ContentProviderUnionSlot slot,
  726. FileSys::ContentProvider* provider) {
  727. impl->content_provider->SetSlot(slot, provider);
  728. }
  729. void System::ClearContentProvider(FileSys::ContentProviderUnionSlot slot) {
  730. impl->content_provider->ClearSlot(slot);
  731. }
  732. const Reporter& System::GetReporter() const {
  733. return impl->reporter;
  734. }
  735. Service::Glue::ARPManager& System::GetARPManager() {
  736. return impl->arp_manager;
  737. }
  738. const Service::Glue::ARPManager& System::GetARPManager() const {
  739. return impl->arp_manager;
  740. }
  741. Service::APM::Controller& System::GetAPMController() {
  742. return impl->apm_controller;
  743. }
  744. const Service::APM::Controller& System::GetAPMController() const {
  745. return impl->apm_controller;
  746. }
  747. Service::Time::TimeManager& System::GetTimeManager() {
  748. return impl->time_manager;
  749. }
  750. const Service::Time::TimeManager& System::GetTimeManager() const {
  751. return impl->time_manager;
  752. }
  753. void System::SetExitLocked(bool locked) {
  754. impl->exit_locked = locked;
  755. }
  756. bool System::GetExitLocked() const {
  757. return impl->exit_locked;
  758. }
  759. void System::SetExitRequested(bool requested) {
  760. impl->exit_requested = requested;
  761. }
  762. bool System::GetExitRequested() const {
  763. return impl->exit_requested;
  764. }
  765. void System::SetApplicationProcessBuildID(const CurrentBuildProcessID& id) {
  766. impl->build_id = id;
  767. }
  768. const System::CurrentBuildProcessID& System::GetApplicationProcessBuildID() const {
  769. return impl->build_id;
  770. }
  771. Service::SM::ServiceManager& System::ServiceManager() {
  772. return *impl->service_manager;
  773. }
  774. const Service::SM::ServiceManager& System::ServiceManager() const {
  775. return *impl->service_manager;
  776. }
  777. void System::RegisterCoreThread(std::size_t id) {
  778. impl->kernel.RegisterCoreThread(id);
  779. }
  780. void System::RegisterHostThread() {
  781. impl->kernel.RegisterHostThread();
  782. }
  783. void System::EnterCPUProfile() {
  784. std::size_t core = impl->kernel.GetCurrentHostThreadID();
  785. impl->dynarmic_ticks[core] = MicroProfileEnter(impl->microprofile_cpu[core]);
  786. }
  787. void System::ExitCPUProfile() {
  788. std::size_t core = impl->kernel.GetCurrentHostThreadID();
  789. MicroProfileLeave(impl->microprofile_cpu[core], impl->dynarmic_ticks[core]);
  790. }
  791. bool System::IsMulticore() const {
  792. return impl->is_multicore;
  793. }
  794. bool System::DebuggerEnabled() const {
  795. return Settings::values.use_gdbstub.GetValue();
  796. }
  797. Core::Debugger& System::GetDebugger() {
  798. return *impl->debugger;
  799. }
  800. const Core::Debugger& System::GetDebugger() const {
  801. return *impl->debugger;
  802. }
  803. Network::RoomNetwork& System::GetRoomNetwork() {
  804. return impl->room_network;
  805. }
  806. const Network::RoomNetwork& System::GetRoomNetwork() const {
  807. return impl->room_network;
  808. }
  809. Tools::RenderdocAPI& System::GetRenderdocAPI() {
  810. return *impl->renderdoc_api;
  811. }
  812. void System::RunServer(std::unique_ptr<Service::ServerManager>&& server_manager) {
  813. return impl->kernel.RunServer(std::move(server_manager));
  814. }
  815. void System::RegisterExecuteProgramCallback(ExecuteProgramCallback&& callback) {
  816. impl->execute_program_callback = std::move(callback);
  817. }
  818. void System::ExecuteProgram(std::size_t program_index) {
  819. if (impl->execute_program_callback) {
  820. impl->execute_program_callback(program_index);
  821. } else {
  822. LOG_CRITICAL(Core, "execute_program_callback must be initialized by the frontend");
  823. }
  824. }
  825. std::deque<std::vector<u8>>& System::GetUserChannel() {
  826. return impl->user_channel;
  827. }
  828. void System::RegisterExitCallback(ExitCallback&& callback) {
  829. impl->exit_callback = std::move(callback);
  830. }
  831. void System::Exit() {
  832. if (impl->exit_callback) {
  833. impl->exit_callback();
  834. } else {
  835. LOG_CRITICAL(Core, "exit_callback must be initialized by the frontend");
  836. }
  837. }
  838. void System::ApplySettings() {
  839. impl->RefreshTime();
  840. if (IsPoweredOn()) {
  841. if (Settings::values.custom_rtc_enabled) {
  842. const s64 posix_time{Settings::values.custom_rtc.GetValue()};
  843. GetTimeManager().UpdateLocalSystemClockTime(posix_time);
  844. }
  845. Renderer().RefreshBaseSettings();
  846. }
  847. }
  848. } // namespace Core