core.cpp 33 KB

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