summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/CMakeLists.txt8
-rw-r--r--src/audio_core/audio_renderer.cpp8
-rw-r--r--src/audio_core/audio_renderer.h8
-rw-r--r--src/audio_core/common.h4
-rw-r--r--src/audio_core/info_updater.cpp5
-rw-r--r--src/audio_core/info_updater.h4
-rw-r--r--src/common/fiber.cpp21
-rw-r--r--src/common/fiber.h7
-rw-r--r--src/common/settings.h452
-rw-r--r--src/common/thread.cpp12
-rw-r--r--src/common/thread.h1
-rw-r--r--src/common/uint128.h5
-rw-r--r--src/common/x64/native_clock.cpp5
-rw-r--r--src/common/x64/native_clock.h6
-rw-r--r--src/core/CMakeLists.txt2
-rw-r--r--src/core/arm/arm_interface.cpp19
-rw-r--r--src/core/arm/arm_interface.h1
-rw-r--r--src/core/arm/dynarmic/arm_dynarmic_32.cpp42
-rw-r--r--src/core/arm/dynarmic/arm_dynarmic_64.cpp28
-rw-r--r--src/core/core_timing.cpp146
-rw-r--r--src/core/core_timing.h27
-rw-r--r--src/core/cpu_manager.cpp64
-rw-r--r--src/core/cpu_manager.h21
-rw-r--r--src/core/debugger/gdbstub.cpp1
-rw-r--r--src/core/debugger/gdbstub_arch.cpp8
-rw-r--r--src/core/file_sys/errors.h18
-rw-r--r--src/core/frontend/applets/error.cpp6
-rw-r--r--src/core/frontend/applets/error.h12
-rw-r--r--src/core/hid/hid_types.h1
-rw-r--r--src/core/hle/ipc_helpers.h10
-rw-r--r--src/core/hle/kernel/hle_ipc.cpp6
-rw-r--r--src/core/hle/kernel/hle_ipc.h13
-rw-r--r--src/core/hle/kernel/k_address_arbiter.cpp17
-rw-r--r--src/core/hle/kernel/k_address_arbiter.h19
-rw-r--r--src/core/hle/kernel/k_client_port.cpp4
-rw-r--r--src/core/hle/kernel/k_client_port.h4
-rw-r--r--src/core/hle/kernel/k_client_session.cpp4
-rw-r--r--src/core/hle/kernel/k_client_session.h6
-rw-r--r--src/core/hle/kernel/k_code_memory.cpp12
-rw-r--r--src/core/hle/kernel/k_code_memory.h14
-rw-r--r--src/core/hle/kernel/k_condition_variable.cpp18
-rw-r--r--src/core/hle/kernel/k_condition_variable.h6
-rw-r--r--src/core/hle/kernel/k_handle_table.cpp6
-rw-r--r--src/core/hle/kernel/k_handle_table.h8
-rw-r--r--src/core/hle/kernel/k_interrupt_manager.cpp5
-rw-r--r--src/core/hle/kernel/k_light_condition_variable.cpp3
-rw-r--r--src/core/hle/kernel/k_light_lock.cpp3
-rw-r--r--src/core/hle/kernel/k_memory_manager.cpp16
-rw-r--r--src/core/hle/kernel/k_memory_manager.h16
-rw-r--r--src/core/hle/kernel/k_page_group.h (renamed from src/core/hle/kernel/k_page_linked_list.h)10
-rw-r--r--src/core/hle/kernel/k_page_table.cpp177
-rw-r--r--src/core/hle/kernel/k_page_table.h173
-rw-r--r--src/core/hle/kernel/k_port.cpp2
-rw-r--r--src/core/hle/kernel/k_port.h2
-rw-r--r--src/core/hle/kernel/k_process.cpp45
-rw-r--r--src/core/hle/kernel/k_process.h31
-rw-r--r--src/core/hle/kernel/k_readable_event.cpp6
-rw-r--r--src/core/hle/kernel/k_readable_event.h6
-rw-r--r--src/core/hle/kernel/k_resource_limit.cpp2
-rw-r--r--src/core/hle/kernel/k_resource_limit.h4
-rw-r--r--src/core/hle/kernel/k_scheduler.cpp32
-rw-r--r--src/core/hle/kernel/k_scheduler.h10
-rw-r--r--src/core/hle/kernel/k_server_session.cpp12
-rw-r--r--src/core/hle/kernel/k_server_session.h12
-rw-r--r--src/core/hle/kernel/k_shared_memory.cpp16
-rw-r--r--src/core/hle/kernel/k_shared_memory.h18
-rw-r--r--src/core/hle/kernel/k_synchronization_object.cpp13
-rw-r--r--src/core/hle/kernel/k_synchronization_object.h8
-rw-r--r--src/core/hle/kernel/k_thread.cpp73
-rw-r--r--src/core/hle/kernel/k_thread.h61
-rw-r--r--src/core/hle/kernel/k_thread_local_page.cpp4
-rw-r--r--src/core/hle/kernel/k_thread_local_page.h4
-rw-r--r--src/core/hle/kernel/k_thread_queue.cpp9
-rw-r--r--src/core/hle/kernel/k_thread_queue.h9
-rw-r--r--src/core/hle/kernel/k_transfer_memory.cpp4
-rw-r--r--src/core/hle/kernel/k_transfer_memory.h4
-rw-r--r--src/core/hle/kernel/k_writable_event.cpp4
-rw-r--r--src/core/hle/kernel/k_writable_event.h4
-rw-r--r--src/core/hle/kernel/kernel.cpp13
-rw-r--r--src/core/hle/kernel/kernel.h3
-rw-r--r--src/core/hle/kernel/process_capability.cpp43
-rw-r--r--src/core/hle/kernel/process_capability.h38
-rw-r--r--src/core/hle/kernel/svc.cpp331
-rw-r--r--src/core/hle/kernel/svc_results.h58
-rw-r--r--src/core/hle/kernel/svc_wrap.h124
-rw-r--r--src/core/hle/result.h44
-rw-r--r--src/core/hle/service/acc/acc.cpp14
-rw-r--r--src/core/hle/service/acc/acc.h2
-rw-r--r--src/core/hle/service/acc/async_context.h2
-rw-r--r--src/core/hle/service/acc/errors.h4
-rw-r--r--src/core/hle/service/acc/profile_manager.cpp12
-rw-r--r--src/core/hle/service/acc/profile_manager.h6
-rw-r--r--src/core/hle/service/am/am.cpp8
-rw-r--r--src/core/hle/service/am/applets/applet_controller.cpp6
-rw-r--r--src/core/hle/service/am/applets/applet_controller.h4
-rw-r--r--src/core/hle/service/am/applets/applet_error.cpp18
-rw-r--r--src/core/hle/service/am/applets/applet_error.h4
-rw-r--r--src/core/hle/service/am/applets/applet_general_backend.cpp10
-rw-r--r--src/core/hle/service/am/applets/applet_general_backend.h6
-rw-r--r--src/core/hle/service/am/applets/applet_mii_edit.cpp2
-rw-r--r--src/core/hle/service/am/applets/applet_mii_edit.h2
-rw-r--r--src/core/hle/service/am/applets/applet_profile_select.cpp4
-rw-r--r--src/core/hle/service/am/applets/applet_profile_select.h4
-rw-r--r--src/core/hle/service/am/applets/applet_software_keyboard.cpp2
-rw-r--r--src/core/hle/service/am/applets/applet_software_keyboard.h4
-rw-r--r--src/core/hle/service/am/applets/applet_web_browser.cpp2
-rw-r--r--src/core/hle/service/am/applets/applet_web_browser.h4
-rw-r--r--src/core/hle/service/am/applets/applets.h4
-rw-r--r--src/core/hle/service/audio/errors.h6
-rw-r--r--src/core/hle/service/bcat/backend/backend.cpp2
-rw-r--r--src/core/hle/service/bcat/backend/backend.h4
-rw-r--r--src/core/hle/service/bcat/bcat_module.cpp10
-rw-r--r--src/core/hle/service/es/es.cpp4
-rw-r--r--src/core/hle/service/fatal/fatal.cpp11
-rw-r--r--src/core/hle/service/filesystem/filesystem.cpp29
-rw-r--r--src/core/hle/service/filesystem/filesystem.h26
-rw-r--r--src/core/hle/service/friend/errors.h2
-rw-r--r--src/core/hle/service/glue/arp.cpp2
-rw-r--r--src/core/hle/service/glue/errors.h8
-rw-r--r--src/core/hle/service/glue/glue_manager.cpp6
-rw-r--r--src/core/hle/service/glue/glue_manager.h4
-rw-r--r--src/core/hle/service/hid/controllers/npad.cpp94
-rw-r--r--src/core/hle/service/hid/controllers/npad.h72
-rw-r--r--src/core/hle/service/hid/errors.h17
-rw-r--r--src/core/hle/service/hid/hid.cpp75
-rw-r--r--src/core/hle/service/hid/hidbus.h2
-rw-r--r--src/core/hle/service/hid/hidbus/hidbus_base.h2
-rw-r--r--src/core/hle/service/ldn/errors.h2
-rw-r--r--src/core/hle/service/ldr/ldr.cpp41
-rw-r--r--src/core/hle/service/mii/mii.cpp2
-rw-r--r--src/core/hle/service/mii/mii_manager.cpp4
-rw-r--r--src/core/hle/service/mii/mii_manager.h2
-rw-r--r--src/core/hle/service/nfp/nfp.cpp32
-rw-r--r--src/core/hle/service/nfp/nfp.h28
-rw-r--r--src/core/hle/service/ns/errors.h2
-rw-r--r--src/core/hle/service/pctl/pctl_module.cpp8
-rw-r--r--src/core/hle/service/pm/pm.cpp12
-rw-r--r--src/core/hle/service/service.cpp4
-rw-r--r--src/core/hle/service/service.h4
-rw-r--r--src/core/hle/service/set/set.cpp2
-rw-r--r--src/core/hle/service/set/set_sys.cpp2
-rw-r--r--src/core/hle/service/sm/sm.cpp18
-rw-r--r--src/core/hle/service/sm/sm.h6
-rw-r--r--src/core/hle/service/sm/sm_controller.cpp2
-rw-r--r--src/core/hle/service/spl/spl_results.h32
-rw-r--r--src/core/hle/service/time/clock_types.h8
-rw-r--r--src/core/hle/service/time/errors.h20
-rw-r--r--src/core/hle/service/time/local_system_clock_context_writer.h2
-rw-r--r--src/core/hle/service/time/network_system_clock_context_writer.h2
-rw-r--r--src/core/hle/service/time/standard_user_system_clock_core.cpp22
-rw-r--r--src/core/hle/service/time/standard_user_system_clock_core.h10
-rw-r--r--src/core/hle/service/time/system_clock_context_update_callback.cpp6
-rw-r--r--src/core/hle/service/time/system_clock_context_update_callback.h4
-rw-r--r--src/core/hle/service/time/system_clock_core.cpp14
-rw-r--r--src/core/hle/service/time/system_clock_core.h14
-rw-r--r--src/core/hle/service/time/time.cpp25
-rw-r--r--src/core/hle/service/time/time.h2
-rw-r--r--src/core/hle/service/time/time_zone_content_manager.cpp10
-rw-r--r--src/core/hle/service/time/time_zone_content_manager.h6
-rw-r--r--src/core/hle/service/time/time_zone_manager.cpp46
-rw-r--r--src/core/hle/service/time/time_zone_manager.h20
-rw-r--r--src/core/hle/service/time/time_zone_service.cpp15
-rw-r--r--src/core/hle/service/vi/vi.cpp8
-rw-r--r--src/core/reporter.cpp8
-rw-r--r--src/core/reporter.h6
-rw-r--r--src/tests/common/fibers.cpp123
-rw-r--r--src/tests/core/core_timing.cpp4
-rw-r--r--src/video_core/renderer_vulkan/blit_image.cpp2
-rw-r--r--src/video_core/renderer_vulkan/blit_image.h6
-rw-r--r--src/video_core/renderer_vulkan/pipeline_helper.h2
-rw-r--r--src/video_core/renderer_vulkan/renderer_vulkan.h8
-rw-r--r--src/video_core/renderer_vulkan/vk_blit_screen.cpp87
-rw-r--r--src/video_core/renderer_vulkan/vk_blit_screen.h23
-rw-r--r--src/video_core/renderer_vulkan/vk_buffer_cache.cpp4
-rw-r--r--src/video_core/renderer_vulkan/vk_buffer_cache.h10
-rw-r--r--src/video_core/renderer_vulkan/vk_compute_pass.cpp14
-rw-r--r--src/video_core/renderer_vulkan/vk_compute_pass.h28
-rw-r--r--src/video_core/renderer_vulkan/vk_compute_pipeline.cpp4
-rw-r--r--src/video_core/renderer_vulkan/vk_compute_pipeline.h8
-rw-r--r--src/video_core/renderer_vulkan/vk_descriptor_pool.cpp2
-rw-r--r--src/video_core/renderer_vulkan/vk_descriptor_pool.h4
-rw-r--r--src/video_core/renderer_vulkan/vk_fence_manager.cpp21
-rw-r--r--src/video_core/renderer_vulkan/vk_fence_manager.h24
-rw-r--r--src/video_core/renderer_vulkan/vk_fsr.cpp2
-rw-r--r--src/video_core/renderer_vulkan/vk_fsr.h4
-rw-r--r--src/video_core/renderer_vulkan/vk_graphics_pipeline.cpp6
-rw-r--r--src/video_core/renderer_vulkan/vk_graphics_pipeline.h12
-rw-r--r--src/video_core/renderer_vulkan/vk_pipeline_cache.cpp4
-rw-r--r--src/video_core/renderer_vulkan/vk_pipeline_cache.h12
-rw-r--r--src/video_core/renderer_vulkan/vk_query_cache.cpp16
-rw-r--r--src/video_core/renderer_vulkan/vk_query_cache.h32
-rw-r--r--src/video_core/renderer_vulkan/vk_rasterizer.cpp4
-rw-r--r--src/video_core/renderer_vulkan/vk_rasterizer.h16
-rw-r--r--src/video_core/renderer_vulkan/vk_scheduler.cpp38
-rw-r--r--src/video_core/renderer_vulkan/vk_scheduler.h12
-rw-r--r--src/video_core/renderer_vulkan/vk_staging_buffer_pool.cpp2
-rw-r--r--src/video_core/renderer_vulkan/vk_staging_buffer_pool.h6
-rw-r--r--src/video_core/renderer_vulkan/vk_swapchain.cpp26
-rw-r--r--src/video_core/renderer_vulkan/vk_swapchain.h12
-rw-r--r--src/video_core/renderer_vulkan/vk_texture_cache.cpp4
-rw-r--r--src/video_core/renderer_vulkan/vk_texture_cache.h8
-rw-r--r--src/video_core/renderer_vulkan/vk_update_descriptor.cpp8
-rw-r--r--src/video_core/renderer_vulkan/vk_update_descriptor.h10
-rw-r--r--src/video_core/vulkan_common/vulkan_device.cpp11
-rw-r--r--src/yuzu/applets/qt_error.cpp6
-rw-r--r--src/yuzu/applets/qt_error.h6
-rw-r--r--src/yuzu/applets/qt_web_browser.cpp6
-rw-r--r--src/yuzu/configuration/config.cpp12
-rw-r--r--src/yuzu/configuration/config.h8
-rw-r--r--src/yuzu/configuration/configuration_shared.cpp6
-rw-r--r--src/yuzu/configuration/configuration_shared.h10
-rw-r--r--src/yuzu/uisettings.h54
-rw-r--r--src/yuzu_cmd/config.cpp6
-rw-r--r--src/yuzu_cmd/config.h4
214 files changed, 2094 insertions, 2135 deletions
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
index 39d038493..39ae573b2 100644
--- a/src/CMakeLists.txt
+++ b/src/CMakeLists.txt
@@ -36,7 +36,6 @@ if (MSVC)
36 # /GT - Supports fiber safety for data allocated using static thread-local storage 36 # /GT - Supports fiber safety for data allocated using static thread-local storage
37 add_compile_options( 37 add_compile_options(
38 /MP 38 /MP
39 /Zi
40 /Zm200 39 /Zm200
41 /Zo 40 /Zo
42 /permissive- 41 /permissive-
@@ -79,6 +78,13 @@ if (MSVC)
79 /we5245 # 'function': unreferenced function with internal linkage has been removed 78 /we5245 # 'function': unreferenced function with internal linkage has been removed
80 ) 79 )
81 80
81 if (USE_CCACHE)
82 # when caching, we need to use /Z7 to downgrade debug info to use an older but more cachable format
83 add_compile_options(/Z7)
84 else()
85 add_compile_options(/Zi)
86 endif()
87
82 if (ARCHITECTURE_x86_64) 88 if (ARCHITECTURE_x86_64)
83 add_compile_options(/QIntel-jcc-erratum) 89 add_compile_options(/QIntel-jcc-erratum)
84 endif() 90 endif()
diff --git a/src/audio_core/audio_renderer.cpp b/src/audio_core/audio_renderer.cpp
index e40ab16d2..2ee0a96ed 100644
--- a/src/audio_core/audio_renderer.cpp
+++ b/src/audio_core/audio_renderer.cpp
@@ -98,13 +98,13 @@ AudioRenderer::AudioRenderer(Core::Timing::CoreTiming& core_timing_, Core::Memor
98 98
99AudioRenderer::~AudioRenderer() = default; 99AudioRenderer::~AudioRenderer() = default;
100 100
101ResultCode AudioRenderer::Start() { 101Result AudioRenderer::Start() {
102 audio_out->StartStream(stream); 102 audio_out->StartStream(stream);
103 ReleaseAndQueueBuffers(); 103 ReleaseAndQueueBuffers();
104 return ResultSuccess; 104 return ResultSuccess;
105} 105}
106 106
107ResultCode AudioRenderer::Stop() { 107Result AudioRenderer::Stop() {
108 audio_out->StopStream(stream); 108 audio_out->StopStream(stream);
109 return ResultSuccess; 109 return ResultSuccess;
110} 110}
@@ -125,8 +125,8 @@ Stream::State AudioRenderer::GetStreamState() const {
125 return stream->GetState(); 125 return stream->GetState();
126} 126}
127 127
128ResultCode AudioRenderer::UpdateAudioRenderer(const std::vector<u8>& input_params, 128Result AudioRenderer::UpdateAudioRenderer(const std::vector<u8>& input_params,
129 std::vector<u8>& output_params) { 129 std::vector<u8>& output_params) {
130 std::scoped_lock lock{mutex}; 130 std::scoped_lock lock{mutex};
131 InfoUpdater info_updater{input_params, output_params, behavior_info}; 131 InfoUpdater info_updater{input_params, output_params, behavior_info};
132 132
diff --git a/src/audio_core/audio_renderer.h b/src/audio_core/audio_renderer.h
index 1f9f55ae2..a67ffd592 100644
--- a/src/audio_core/audio_renderer.h
+++ b/src/audio_core/audio_renderer.h
@@ -43,10 +43,10 @@ public:
43 Stream::ReleaseCallback&& release_callback, std::size_t instance_number); 43 Stream::ReleaseCallback&& release_callback, std::size_t instance_number);
44 ~AudioRenderer(); 44 ~AudioRenderer();
45 45
46 [[nodiscard]] ResultCode UpdateAudioRenderer(const std::vector<u8>& input_params, 46 [[nodiscard]] Result UpdateAudioRenderer(const std::vector<u8>& input_params,
47 std::vector<u8>& output_params); 47 std::vector<u8>& output_params);
48 [[nodiscard]] ResultCode Start(); 48 [[nodiscard]] Result Start();
49 [[nodiscard]] ResultCode Stop(); 49 [[nodiscard]] Result Stop();
50 void QueueMixedBuffer(Buffer::Tag tag); 50 void QueueMixedBuffer(Buffer::Tag tag);
51 void ReleaseAndQueueBuffers(); 51 void ReleaseAndQueueBuffers();
52 [[nodiscard]] u32 GetSampleRate() const; 52 [[nodiscard]] u32 GetSampleRate() const;
diff --git a/src/audio_core/common.h b/src/audio_core/common.h
index 46ef83113..056a0ac70 100644
--- a/src/audio_core/common.h
+++ b/src/audio_core/common.h
@@ -10,8 +10,8 @@
10 10
11namespace AudioCommon { 11namespace AudioCommon {
12namespace Audren { 12namespace Audren {
13constexpr ResultCode ERR_INVALID_PARAMETERS{ErrorModule::Audio, 41}; 13constexpr Result ERR_INVALID_PARAMETERS{ErrorModule::Audio, 41};
14constexpr ResultCode ERR_SPLITTER_SORT_FAILED{ErrorModule::Audio, 43}; 14constexpr Result ERR_SPLITTER_SORT_FAILED{ErrorModule::Audio, 43};
15} // namespace Audren 15} // namespace Audren
16 16
17constexpr u8 BASE_REVISION = '0'; 17constexpr u8 BASE_REVISION = '0';
diff --git a/src/audio_core/info_updater.cpp b/src/audio_core/info_updater.cpp
index 313a2eb6d..0065e6e53 100644
--- a/src/audio_core/info_updater.cpp
+++ b/src/audio_core/info_updater.cpp
@@ -285,9 +285,8 @@ bool InfoUpdater::UpdateSplitterInfo(SplitterContext& splitter_context) {
285 return true; 285 return true;
286} 286}
287 287
288ResultCode InfoUpdater::UpdateMixes(MixContext& mix_context, std::size_t mix_buffer_count, 288Result InfoUpdater::UpdateMixes(MixContext& mix_context, std::size_t mix_buffer_count,
289 SplitterContext& splitter_context, 289 SplitterContext& splitter_context, EffectContext& effect_context) {
290 EffectContext& effect_context) {
291 std::vector<MixInfo::InParams> mix_in_params; 290 std::vector<MixInfo::InParams> mix_in_params;
292 291
293 if (!behavior_info.IsMixInParameterDirtyOnlyUpdateSupported()) { 292 if (!behavior_info.IsMixInParameterDirtyOnlyUpdateSupported()) {
diff --git a/src/audio_core/info_updater.h b/src/audio_core/info_updater.h
index 6aab5beaf..17e66b036 100644
--- a/src/audio_core/info_updater.h
+++ b/src/audio_core/info_updater.h
@@ -32,8 +32,8 @@ public:
32 VAddr audio_codec_dsp_addr); 32 VAddr audio_codec_dsp_addr);
33 bool UpdateEffects(EffectContext& effect_context, bool is_active); 33 bool UpdateEffects(EffectContext& effect_context, bool is_active);
34 bool UpdateSplitterInfo(SplitterContext& splitter_context); 34 bool UpdateSplitterInfo(SplitterContext& splitter_context);
35 ResultCode UpdateMixes(MixContext& mix_context, std::size_t mix_buffer_count, 35 Result UpdateMixes(MixContext& mix_context, std::size_t mix_buffer_count,
36 SplitterContext& splitter_context, EffectContext& effect_context); 36 SplitterContext& splitter_context, EffectContext& effect_context);
37 bool UpdateSinks(SinkContext& sink_context); 37 bool UpdateSinks(SinkContext& sink_context);
38 bool UpdatePerformanceBuffer(); 38 bool UpdatePerformanceBuffer();
39 bool UpdateErrorInfo(BehaviorInfo& in_behavior_info); 39 bool UpdateErrorInfo(BehaviorInfo& in_behavior_info);
diff --git a/src/common/fiber.cpp b/src/common/fiber.cpp
index f9aeb692a..bc92b360b 100644
--- a/src/common/fiber.cpp
+++ b/src/common/fiber.cpp
@@ -20,10 +20,8 @@ struct Fiber::FiberImpl {
20 VirtualBuffer<u8> rewind_stack; 20 VirtualBuffer<u8> rewind_stack;
21 21
22 std::mutex guard; 22 std::mutex guard;
23 std::function<void(void*)> entry_point; 23 std::function<void()> entry_point;
24 std::function<void(void*)> rewind_point; 24 std::function<void()> rewind_point;
25 void* rewind_parameter{};
26 void* start_parameter{};
27 std::shared_ptr<Fiber> previous_fiber; 25 std::shared_ptr<Fiber> previous_fiber;
28 bool is_thread_fiber{}; 26 bool is_thread_fiber{};
29 bool released{}; 27 bool released{};
@@ -34,13 +32,8 @@ struct Fiber::FiberImpl {
34 boost::context::detail::fcontext_t rewind_context{}; 32 boost::context::detail::fcontext_t rewind_context{};
35}; 33};
36 34
37void Fiber::SetStartParameter(void* new_parameter) { 35void Fiber::SetRewindPoint(std::function<void()>&& rewind_func) {
38 impl->start_parameter = new_parameter;
39}
40
41void Fiber::SetRewindPoint(std::function<void(void*)>&& rewind_func, void* rewind_param) {
42 impl->rewind_point = std::move(rewind_func); 36 impl->rewind_point = std::move(rewind_func);
43 impl->rewind_parameter = rewind_param;
44} 37}
45 38
46void Fiber::Start(boost::context::detail::transfer_t& transfer) { 39void Fiber::Start(boost::context::detail::transfer_t& transfer) {
@@ -48,7 +41,7 @@ void Fiber::Start(boost::context::detail::transfer_t& transfer) {
48 impl->previous_fiber->impl->context = transfer.fctx; 41 impl->previous_fiber->impl->context = transfer.fctx;
49 impl->previous_fiber->impl->guard.unlock(); 42 impl->previous_fiber->impl->guard.unlock();
50 impl->previous_fiber.reset(); 43 impl->previous_fiber.reset();
51 impl->entry_point(impl->start_parameter); 44 impl->entry_point();
52 UNREACHABLE(); 45 UNREACHABLE();
53} 46}
54 47
@@ -59,7 +52,7 @@ void Fiber::OnRewind([[maybe_unused]] boost::context::detail::transfer_t& transf
59 u8* tmp = impl->stack_limit; 52 u8* tmp = impl->stack_limit;
60 impl->stack_limit = impl->rewind_stack_limit; 53 impl->stack_limit = impl->rewind_stack_limit;
61 impl->rewind_stack_limit = tmp; 54 impl->rewind_stack_limit = tmp;
62 impl->rewind_point(impl->rewind_parameter); 55 impl->rewind_point();
63 UNREACHABLE(); 56 UNREACHABLE();
64} 57}
65 58
@@ -73,10 +66,8 @@ void Fiber::RewindStartFunc(boost::context::detail::transfer_t transfer) {
73 fiber->OnRewind(transfer); 66 fiber->OnRewind(transfer);
74} 67}
75 68
76Fiber::Fiber(std::function<void(void*)>&& entry_point_func, void* start_parameter) 69Fiber::Fiber(std::function<void()>&& entry_point_func) : impl{std::make_unique<FiberImpl>()} {
77 : impl{std::make_unique<FiberImpl>()} {
78 impl->entry_point = std::move(entry_point_func); 70 impl->entry_point = std::move(entry_point_func);
79 impl->start_parameter = start_parameter;
80 impl->stack_limit = impl->stack.data(); 71 impl->stack_limit = impl->stack.data();
81 impl->rewind_stack_limit = impl->rewind_stack.data(); 72 impl->rewind_stack_limit = impl->rewind_stack.data();
82 u8* stack_base = impl->stack_limit + default_stack_size; 73 u8* stack_base = impl->stack_limit + default_stack_size;
diff --git a/src/common/fiber.h b/src/common/fiber.h
index 873604bc6..f24d333a3 100644
--- a/src/common/fiber.h
+++ b/src/common/fiber.h
@@ -29,7 +29,7 @@ namespace Common {
29 */ 29 */
30class Fiber { 30class Fiber {
31public: 31public:
32 Fiber(std::function<void(void*)>&& entry_point_func, void* start_parameter); 32 Fiber(std::function<void()>&& entry_point_func);
33 ~Fiber(); 33 ~Fiber();
34 34
35 Fiber(const Fiber&) = delete; 35 Fiber(const Fiber&) = delete;
@@ -43,16 +43,13 @@ public:
43 static void YieldTo(std::weak_ptr<Fiber> weak_from, Fiber& to); 43 static void YieldTo(std::weak_ptr<Fiber> weak_from, Fiber& to);
44 [[nodiscard]] static std::shared_ptr<Fiber> ThreadToFiber(); 44 [[nodiscard]] static std::shared_ptr<Fiber> ThreadToFiber();
45 45
46 void SetRewindPoint(std::function<void(void*)>&& rewind_func, void* rewind_param); 46 void SetRewindPoint(std::function<void()>&& rewind_func);
47 47
48 void Rewind(); 48 void Rewind();
49 49
50 /// Only call from main thread's fiber 50 /// Only call from main thread's fiber
51 void Exit(); 51 void Exit();
52 52
53 /// Changes the start parameter of the fiber. Has no effect if the fiber already started
54 void SetStartParameter(void* new_parameter);
55
56private: 53private:
57 Fiber(); 54 Fiber();
58 55
diff --git a/src/common/settings.h b/src/common/settings.h
index a507744a2..3583a2e70 100644
--- a/src/common/settings.h
+++ b/src/common/settings.h
@@ -101,15 +101,15 @@ struct ResolutionScalingInfo {
101 } 101 }
102}; 102};
103 103
104/** The BasicSetting class is a simple resource manager. It defines a label and default value 104/** The Setting class is a simple resource manager. It defines a label and default value alongside
105 * alongside the actual value of the setting for simpler and less-error prone use with frontend 105 * the actual value of the setting for simpler and less-error prone use with frontend
106 * configurations. Setting a default value and label is required, though subclasses may deviate from 106 * configurations. Specifying a default value and label is required. A minimum and maximum range can
107 * this requirement. 107 * be specified for sanitization.
108 */ 108 */
109template <typename Type> 109template <typename Type>
110class BasicSetting { 110class Setting {
111protected: 111protected:
112 BasicSetting() = default; 112 Setting() = default;
113 113
114 /** 114 /**
115 * Only sets the setting to the given initializer, leaving the other members to their default 115 * Only sets the setting to the given initializer, leaving the other members to their default
@@ -117,7 +117,7 @@ protected:
117 * 117 *
118 * @param global_val Initial value of the setting 118 * @param global_val Initial value of the setting
119 */ 119 */
120 explicit BasicSetting(const Type& global_val) : global{global_val} {} 120 explicit Setting(const Type& val) : value{val} {}
121 121
122public: 122public:
123 /** 123 /**
@@ -126,9 +126,22 @@ public:
126 * @param default_val Intial value of the setting, and default value of the setting 126 * @param default_val Intial value of the setting, and default value of the setting
127 * @param name Label for the setting 127 * @param name Label for the setting
128 */ 128 */
129 explicit BasicSetting(const Type& default_val, const std::string& name) 129 explicit Setting(const Type& default_val, const std::string& name)
130 : default_value{default_val}, global{default_val}, label{name} {} 130 : value{default_val}, default_value{default_val}, ranged{false}, label{name} {}
131 virtual ~BasicSetting() = default; 131 virtual ~Setting() = default;
132
133 /**
134 * Sets a default value, minimum value, maximum value, and label.
135 *
136 * @param default_val Intial value of the setting, and default value of the setting
137 * @param min_val Sets the minimum allowed value of the setting
138 * @param max_val Sets the maximum allowed value of the setting
139 * @param name Label for the setting
140 */
141 explicit Setting(const Type& default_val, const Type& min_val, const Type& max_val,
142 const std::string& name)
143 : value{default_val}, default_value{default_val}, maximum{max_val}, minimum{min_val},
144 ranged{true}, label{name} {}
132 145
133 /** 146 /**
134 * Returns a reference to the setting's value. 147 * Returns a reference to the setting's value.
@@ -136,17 +149,17 @@ public:
136 * @returns A reference to the setting 149 * @returns A reference to the setting
137 */ 150 */
138 [[nodiscard]] virtual const Type& GetValue() const { 151 [[nodiscard]] virtual const Type& GetValue() const {
139 return global; 152 return value;
140 } 153 }
141 154
142 /** 155 /**
143 * Sets the setting to the given value. 156 * Sets the setting to the given value.
144 * 157 *
145 * @param value The desired value 158 * @param val The desired value
146 */ 159 */
147 virtual void SetValue(const Type& value) { 160 virtual void SetValue(const Type& val) {
148 Type temp{value}; 161 Type temp{(ranged) ? std::clamp(val, minimum, maximum) : val};
149 std::swap(global, temp); 162 std::swap(value, temp);
150 } 163 }
151 164
152 /** 165 /**
@@ -170,14 +183,14 @@ public:
170 /** 183 /**
171 * Assigns a value to the setting. 184 * Assigns a value to the setting.
172 * 185 *
173 * @param value The desired setting value 186 * @param val The desired setting value
174 * 187 *
175 * @returns A reference to the setting 188 * @returns A reference to the setting
176 */ 189 */
177 virtual const Type& operator=(const Type& value) { 190 virtual const Type& operator=(const Type& val) {
178 Type temp{value}; 191 Type temp{(ranged) ? std::clamp(val, minimum, maximum) : val};
179 std::swap(global, temp); 192 std::swap(value, temp);
180 return global; 193 return value;
181 } 194 }
182 195
183 /** 196 /**
@@ -186,72 +199,28 @@ public:
186 * @returns A reference to the setting 199 * @returns A reference to the setting
187 */ 200 */
188 explicit virtual operator const Type&() const { 201 explicit virtual operator const Type&() const {
189 return global; 202 return value;
190 } 203 }
191 204
192protected: 205protected:
206 Type value{}; ///< The setting
193 const Type default_value{}; ///< The default value 207 const Type default_value{}; ///< The default value
194 Type global{}; ///< The setting 208 const Type maximum{}; ///< Maximum allowed value of the setting
209 const Type minimum{}; ///< Minimum allowed value of the setting
210 const bool ranged; ///< The setting has sanitization ranges
195 const std::string label{}; ///< The setting's label 211 const std::string label{}; ///< The setting's label
196}; 212};
197 213
198/** 214/**
199 * BasicRangedSetting class is intended for use with quantifiable settings that need a more 215 * The SwitchableSetting class is a slightly more complex version of the Setting class. This adds a
200 * restrictive range than implicitly defined by its type. Implements a minimum and maximum that is
201 * simply used to sanitize SetValue and the assignment overload.
202 */
203template <typename Type>
204class BasicRangedSetting : virtual public BasicSetting<Type> {
205public:
206 /**
207 * Sets a default value, minimum value, maximum value, and label.
208 *
209 * @param default_val Intial value of the setting, and default value of the setting
210 * @param min_val Sets the minimum allowed value of the setting
211 * @param max_val Sets the maximum allowed value of the setting
212 * @param name Label for the setting
213 */
214 explicit BasicRangedSetting(const Type& default_val, const Type& min_val, const Type& max_val,
215 const std::string& name)
216 : BasicSetting<Type>{default_val, name}, minimum{min_val}, maximum{max_val} {}
217 virtual ~BasicRangedSetting() = default;
218
219 /**
220 * Like BasicSetting's SetValue, except value is clamped to the range of the setting.
221 *
222 * @param value The desired value
223 */
224 void SetValue(const Type& value) override {
225 this->global = std::clamp(value, minimum, maximum);
226 }
227
228 /**
229 * Like BasicSetting's assignment overload, except value is clamped to the range of the setting.
230 *
231 * @param value The desired value
232 * @returns A reference to the setting's value
233 */
234 const Type& operator=(const Type& value) override {
235 this->global = std::clamp(value, minimum, maximum);
236 return this->global;
237 }
238
239 const Type minimum; ///< Minimum allowed value of the setting
240 const Type maximum; ///< Maximum allowed value of the setting
241};
242
243/**
244 * The Setting class is a slightly more complex version of the BasicSetting class. This adds a
245 * custom setting to switch to when a guest application specifically requires it. The effect is that 216 * custom setting to switch to when a guest application specifically requires it. The effect is that
246 * other components of the emulator can access the setting's intended value without any need for the 217 * other components of the emulator can access the setting's intended value without any need for the
247 * component to ask whether the custom or global setting is needed at the moment. 218 * component to ask whether the custom or global setting is needed at the moment.
248 * 219 *
249 * By default, the global setting is used. 220 * By default, the global setting is used.
250 *
251 * Like the BasicSetting, this requires setting a default value and label to use.
252 */ 221 */
253template <typename Type> 222template <typename Type>
254class Setting : virtual public BasicSetting<Type> { 223class SwitchableSetting : virtual public Setting<Type> {
255public: 224public:
256 /** 225 /**
257 * Sets a default value, label, and setting value. 226 * Sets a default value, label, and setting value.
@@ -259,9 +228,21 @@ public:
259 * @param default_val Intial value of the setting, and default value of the setting 228 * @param default_val Intial value of the setting, and default value of the setting
260 * @param name Label for the setting 229 * @param name Label for the setting
261 */ 230 */
262 explicit Setting(const Type& default_val, const std::string& name) 231 explicit SwitchableSetting(const Type& default_val, const std::string& name)
263 : BasicSetting<Type>(default_val, name) {} 232 : Setting<Type>{default_val, name} {}
264 virtual ~Setting() = default; 233 virtual ~SwitchableSetting() = default;
234
235 /**
236 * Sets a default value, minimum value, maximum value, and label.
237 *
238 * @param default_val Intial value of the setting, and default value of the setting
239 * @param min_val Sets the minimum allowed value of the setting
240 * @param max_val Sets the maximum allowed value of the setting
241 * @param name Label for the setting
242 */
243 explicit SwitchableSetting(const Type& default_val, const Type& min_val, const Type& max_val,
244 const std::string& name)
245 : Setting<Type>{default_val, min_val, max_val, name} {}
265 246
266 /** 247 /**
267 * Tells this setting to represent either the global or custom setting when other member 248 * Tells this setting to represent either the global or custom setting when other member
@@ -292,13 +273,13 @@ public:
292 */ 273 */
293 [[nodiscard]] virtual const Type& GetValue() const override { 274 [[nodiscard]] virtual const Type& GetValue() const override {
294 if (use_global) { 275 if (use_global) {
295 return this->global; 276 return this->value;
296 } 277 }
297 return custom; 278 return custom;
298 } 279 }
299 [[nodiscard]] virtual const Type& GetValue(bool need_global) const { 280 [[nodiscard]] virtual const Type& GetValue(bool need_global) const {
300 if (use_global || need_global) { 281 if (use_global || need_global) {
301 return this->global; 282 return this->value;
302 } 283 }
303 return custom; 284 return custom;
304 } 285 }
@@ -306,12 +287,12 @@ public:
306 /** 287 /**
307 * Sets the current setting value depending on the global state. 288 * Sets the current setting value depending on the global state.
308 * 289 *
309 * @param value The new value 290 * @param val The new value
310 */ 291 */
311 void SetValue(const Type& value) override { 292 void SetValue(const Type& val) override {
312 Type temp{value}; 293 Type temp{(this->ranged) ? std::clamp(val, this->minimum, this->maximum) : val};
313 if (use_global) { 294 if (use_global) {
314 std::swap(this->global, temp); 295 std::swap(this->value, temp);
315 } else { 296 } else {
316 std::swap(custom, temp); 297 std::swap(custom, temp);
317 } 298 }
@@ -320,15 +301,15 @@ public:
320 /** 301 /**
321 * Assigns the current setting value depending on the global state. 302 * Assigns the current setting value depending on the global state.
322 * 303 *
323 * @param value The new value 304 * @param val The new value
324 * 305 *
325 * @returns A reference to the current setting value 306 * @returns A reference to the current setting value
326 */ 307 */
327 const Type& operator=(const Type& value) override { 308 const Type& operator=(const Type& val) override {
328 Type temp{value}; 309 Type temp{(this->ranged) ? std::clamp(val, this->minimum, this->maximum) : val};
329 if (use_global) { 310 if (use_global) {
330 std::swap(this->global, temp); 311 std::swap(this->value, temp);
331 return this->global; 312 return this->value;
332 } 313 }
333 std::swap(custom, temp); 314 std::swap(custom, temp);
334 return custom; 315 return custom;
@@ -341,7 +322,7 @@ public:
341 */ 322 */
342 virtual explicit operator const Type&() const override { 323 virtual explicit operator const Type&() const override {
343 if (use_global) { 324 if (use_global) {
344 return this->global; 325 return this->value;
345 } 326 }
346 return custom; 327 return custom;
347 } 328 }
@@ -352,75 +333,6 @@ protected:
352}; 333};
353 334
354/** 335/**
355 * RangedSetting is a Setting that implements a maximum and minimum value for its setting. Intended
356 * for use with quantifiable settings.
357 */
358template <typename Type>
359class RangedSetting final : public BasicRangedSetting<Type>, public Setting<Type> {
360public:
361 /**
362 * Sets a default value, minimum value, maximum value, and label.
363 *
364 * @param default_val Intial value of the setting, and default value of the setting
365 * @param min_val Sets the minimum allowed value of the setting
366 * @param max_val Sets the maximum allowed value of the setting
367 * @param name Label for the setting
368 */
369 explicit RangedSetting(const Type& default_val, const Type& min_val, const Type& max_val,
370 const std::string& name)
371 : BasicSetting<Type>{default_val, name},
372 BasicRangedSetting<Type>{default_val, min_val, max_val, name}, Setting<Type>{default_val,
373 name} {}
374 virtual ~RangedSetting() = default;
375
376 // The following are needed to avoid a MSVC bug
377 // (source: https://stackoverflow.com/questions/469508)
378 [[nodiscard]] const Type& GetValue() const override {
379 return Setting<Type>::GetValue();
380 }
381 [[nodiscard]] const Type& GetValue(bool need_global) const override {
382 return Setting<Type>::GetValue(need_global);
383 }
384 explicit operator const Type&() const override {
385 if (this->use_global) {
386 return this->global;
387 }
388 return this->custom;
389 }
390
391 /**
392 * Like BasicSetting's SetValue, except value is clamped to the range of the setting. Sets the
393 * appropriate value depending on the global state.
394 *
395 * @param value The desired value
396 */
397 void SetValue(const Type& value) override {
398 const Type temp = std::clamp(value, this->minimum, this->maximum);
399 if (this->use_global) {
400 this->global = temp;
401 }
402 this->custom = temp;
403 }
404
405 /**
406 * Like BasicSetting's assignment overload, except value is clamped to the range of the setting.
407 * Uses the appropriate value depending on the global state.
408 *
409 * @param value The desired value
410 * @returns A reference to the setting's value
411 */
412 const Type& operator=(const Type& value) override {
413 const Type temp = std::clamp(value, this->minimum, this->maximum);
414 if (this->use_global) {
415 this->global = temp;
416 return this->global;
417 }
418 this->custom = temp;
419 return this->custom;
420 }
421};
422
423/**
424 * The InputSetting class allows for getting a reference to either the global or custom members. 336 * The InputSetting class allows for getting a reference to either the global or custom members.
425 * This is required as we cannot easily modify the values of user-defined types within containers 337 * This is required as we cannot easily modify the values of user-defined types within containers
426 * using the SetValue() member function found in the Setting class. The primary purpose of this 338 * using the SetValue() member function found in the Setting class. The primary purpose of this
@@ -431,7 +343,7 @@ template <typename Type>
431class InputSetting final { 343class InputSetting final {
432public: 344public:
433 InputSetting() = default; 345 InputSetting() = default;
434 explicit InputSetting(Type val) : BasicSetting<Type>(val) {} 346 explicit InputSetting(Type val) : Setting<Type>(val) {}
435 ~InputSetting() = default; 347 ~InputSetting() = default;
436 void SetGlobal(bool to_global) { 348 void SetGlobal(bool to_global) {
437 use_global = to_global; 349 use_global = to_global;
@@ -459,175 +371,175 @@ struct TouchFromButtonMap {
459 371
460struct Values { 372struct Values {
461 // Audio 373 // Audio
462 BasicSetting<std::string> audio_device_id{"auto", "output_device"}; 374 Setting<std::string> audio_device_id{"auto", "output_device"};
463 BasicSetting<std::string> sink_id{"auto", "output_engine"}; 375 Setting<std::string> sink_id{"auto", "output_engine"};
464 BasicSetting<bool> audio_muted{false, "audio_muted"}; 376 Setting<bool> audio_muted{false, "audio_muted"};
465 RangedSetting<u8> volume{100, 0, 100, "volume"}; 377 SwitchableSetting<u8> volume{100, 0, 100, "volume"};
466 378
467 // Core 379 // Core
468 Setting<bool> use_multi_core{true, "use_multi_core"}; 380 SwitchableSetting<bool> use_multi_core{true, "use_multi_core"};
469 Setting<bool> use_extended_memory_layout{false, "use_extended_memory_layout"}; 381 SwitchableSetting<bool> use_extended_memory_layout{false, "use_extended_memory_layout"};
470 382
471 // Cpu 383 // Cpu
472 RangedSetting<CPUAccuracy> cpu_accuracy{CPUAccuracy::Auto, CPUAccuracy::Auto, 384 SwitchableSetting<CPUAccuracy> cpu_accuracy{CPUAccuracy::Auto, CPUAccuracy::Auto,
473 CPUAccuracy::Paranoid, "cpu_accuracy"}; 385 CPUAccuracy::Paranoid, "cpu_accuracy"};
474 // TODO: remove cpu_accuracy_first_time, migration setting added 8 July 2021 386 // TODO: remove cpu_accuracy_first_time, migration setting added 8 July 2021
475 BasicSetting<bool> cpu_accuracy_first_time{true, "cpu_accuracy_first_time"}; 387 Setting<bool> cpu_accuracy_first_time{true, "cpu_accuracy_first_time"};
476 BasicSetting<bool> cpu_debug_mode{false, "cpu_debug_mode"}; 388 Setting<bool> cpu_debug_mode{false, "cpu_debug_mode"};
477 389
478 BasicSetting<bool> cpuopt_page_tables{true, "cpuopt_page_tables"}; 390 Setting<bool> cpuopt_page_tables{true, "cpuopt_page_tables"};
479 BasicSetting<bool> cpuopt_block_linking{true, "cpuopt_block_linking"}; 391 Setting<bool> cpuopt_block_linking{true, "cpuopt_block_linking"};
480 BasicSetting<bool> cpuopt_return_stack_buffer{true, "cpuopt_return_stack_buffer"}; 392 Setting<bool> cpuopt_return_stack_buffer{true, "cpuopt_return_stack_buffer"};
481 BasicSetting<bool> cpuopt_fast_dispatcher{true, "cpuopt_fast_dispatcher"}; 393 Setting<bool> cpuopt_fast_dispatcher{true, "cpuopt_fast_dispatcher"};
482 BasicSetting<bool> cpuopt_context_elimination{true, "cpuopt_context_elimination"}; 394 Setting<bool> cpuopt_context_elimination{true, "cpuopt_context_elimination"};
483 BasicSetting<bool> cpuopt_const_prop{true, "cpuopt_const_prop"}; 395 Setting<bool> cpuopt_const_prop{true, "cpuopt_const_prop"};
484 BasicSetting<bool> cpuopt_misc_ir{true, "cpuopt_misc_ir"}; 396 Setting<bool> cpuopt_misc_ir{true, "cpuopt_misc_ir"};
485 BasicSetting<bool> cpuopt_reduce_misalign_checks{true, "cpuopt_reduce_misalign_checks"}; 397 Setting<bool> cpuopt_reduce_misalign_checks{true, "cpuopt_reduce_misalign_checks"};
486 BasicSetting<bool> cpuopt_fastmem{true, "cpuopt_fastmem"}; 398 Setting<bool> cpuopt_fastmem{true, "cpuopt_fastmem"};
487 BasicSetting<bool> cpuopt_fastmem_exclusives{true, "cpuopt_fastmem_exclusives"}; 399 Setting<bool> cpuopt_fastmem_exclusives{true, "cpuopt_fastmem_exclusives"};
488 BasicSetting<bool> cpuopt_recompile_exclusives{true, "cpuopt_recompile_exclusives"}; 400 Setting<bool> cpuopt_recompile_exclusives{true, "cpuopt_recompile_exclusives"};
489 401
490 Setting<bool> cpuopt_unsafe_unfuse_fma{true, "cpuopt_unsafe_unfuse_fma"}; 402 SwitchableSetting<bool> cpuopt_unsafe_unfuse_fma{true, "cpuopt_unsafe_unfuse_fma"};
491 Setting<bool> cpuopt_unsafe_reduce_fp_error{true, "cpuopt_unsafe_reduce_fp_error"}; 403 SwitchableSetting<bool> cpuopt_unsafe_reduce_fp_error{true, "cpuopt_unsafe_reduce_fp_error"};
492 Setting<bool> cpuopt_unsafe_ignore_standard_fpcr{true, "cpuopt_unsafe_ignore_standard_fpcr"}; 404 SwitchableSetting<bool> cpuopt_unsafe_ignore_standard_fpcr{
493 Setting<bool> cpuopt_unsafe_inaccurate_nan{true, "cpuopt_unsafe_inaccurate_nan"}; 405 true, "cpuopt_unsafe_ignore_standard_fpcr"};
494 Setting<bool> cpuopt_unsafe_fastmem_check{true, "cpuopt_unsafe_fastmem_check"}; 406 SwitchableSetting<bool> cpuopt_unsafe_inaccurate_nan{true, "cpuopt_unsafe_inaccurate_nan"};
495 Setting<bool> cpuopt_unsafe_ignore_global_monitor{true, "cpuopt_unsafe_ignore_global_monitor"}; 407 SwitchableSetting<bool> cpuopt_unsafe_fastmem_check{true, "cpuopt_unsafe_fastmem_check"};
408 SwitchableSetting<bool> cpuopt_unsafe_ignore_global_monitor{
409 true, "cpuopt_unsafe_ignore_global_monitor"};
496 410
497 // Renderer 411 // Renderer
498 RangedSetting<RendererBackend> renderer_backend{ 412 SwitchableSetting<RendererBackend> renderer_backend{
499 RendererBackend::Vulkan, RendererBackend::OpenGL, RendererBackend::Vulkan, "backend"}; 413 RendererBackend::Vulkan, RendererBackend::OpenGL, RendererBackend::Vulkan, "backend"};
500 BasicSetting<bool> renderer_debug{false, "debug"}; 414 Setting<bool> renderer_debug{false, "debug"};
501 BasicSetting<bool> renderer_shader_feedback{false, "shader_feedback"}; 415 Setting<bool> renderer_shader_feedback{false, "shader_feedback"};
502 BasicSetting<bool> enable_nsight_aftermath{false, "nsight_aftermath"}; 416 Setting<bool> enable_nsight_aftermath{false, "nsight_aftermath"};
503 BasicSetting<bool> disable_shader_loop_safety_checks{false, 417 Setting<bool> disable_shader_loop_safety_checks{false, "disable_shader_loop_safety_checks"};
504 "disable_shader_loop_safety_checks"}; 418 SwitchableSetting<int> vulkan_device{0, "vulkan_device"};
505 Setting<int> vulkan_device{0, "vulkan_device"};
506 419
507 ResolutionScalingInfo resolution_info{}; 420 ResolutionScalingInfo resolution_info{};
508 Setting<ResolutionSetup> resolution_setup{ResolutionSetup::Res1X, "resolution_setup"}; 421 SwitchableSetting<ResolutionSetup> resolution_setup{ResolutionSetup::Res1X, "resolution_setup"};
509 Setting<ScalingFilter> scaling_filter{ScalingFilter::Bilinear, "scaling_filter"}; 422 SwitchableSetting<ScalingFilter> scaling_filter{ScalingFilter::Bilinear, "scaling_filter"};
510 Setting<AntiAliasing> anti_aliasing{AntiAliasing::None, "anti_aliasing"}; 423 SwitchableSetting<AntiAliasing> anti_aliasing{AntiAliasing::None, "anti_aliasing"};
511 // *nix platforms may have issues with the borderless windowed fullscreen mode. 424 // *nix platforms may have issues with the borderless windowed fullscreen mode.
512 // Default to exclusive fullscreen on these platforms for now. 425 // Default to exclusive fullscreen on these platforms for now.
513 RangedSetting<FullscreenMode> fullscreen_mode{ 426 SwitchableSetting<FullscreenMode> fullscreen_mode{
514#ifdef _WIN32 427#ifdef _WIN32
515 FullscreenMode::Borderless, 428 FullscreenMode::Borderless,
516#else 429#else
517 FullscreenMode::Exclusive, 430 FullscreenMode::Exclusive,
518#endif 431#endif
519 FullscreenMode::Borderless, FullscreenMode::Exclusive, "fullscreen_mode"}; 432 FullscreenMode::Borderless, FullscreenMode::Exclusive, "fullscreen_mode"};
520 RangedSetting<int> aspect_ratio{0, 0, 3, "aspect_ratio"}; 433 SwitchableSetting<int> aspect_ratio{0, 0, 3, "aspect_ratio"};
521 RangedSetting<int> max_anisotropy{0, 0, 5, "max_anisotropy"}; 434 SwitchableSetting<int> max_anisotropy{0, 0, 5, "max_anisotropy"};
522 Setting<bool> use_speed_limit{true, "use_speed_limit"}; 435 SwitchableSetting<bool> use_speed_limit{true, "use_speed_limit"};
523 RangedSetting<u16> speed_limit{100, 0, 9999, "speed_limit"}; 436 SwitchableSetting<u16> speed_limit{100, 0, 9999, "speed_limit"};
524 Setting<bool> use_disk_shader_cache{true, "use_disk_shader_cache"}; 437 SwitchableSetting<bool> use_disk_shader_cache{true, "use_disk_shader_cache"};
525 RangedSetting<GPUAccuracy> gpu_accuracy{GPUAccuracy::High, GPUAccuracy::Normal, 438 SwitchableSetting<GPUAccuracy> gpu_accuracy{GPUAccuracy::High, GPUAccuracy::Normal,
526 GPUAccuracy::Extreme, "gpu_accuracy"}; 439 GPUAccuracy::Extreme, "gpu_accuracy"};
527 Setting<bool> use_asynchronous_gpu_emulation{true, "use_asynchronous_gpu_emulation"}; 440 SwitchableSetting<bool> use_asynchronous_gpu_emulation{true, "use_asynchronous_gpu_emulation"};
528 Setting<NvdecEmulation> nvdec_emulation{NvdecEmulation::GPU, "nvdec_emulation"}; 441 SwitchableSetting<NvdecEmulation> nvdec_emulation{NvdecEmulation::GPU, "nvdec_emulation"};
529 Setting<bool> accelerate_astc{true, "accelerate_astc"}; 442 SwitchableSetting<bool> accelerate_astc{true, "accelerate_astc"};
530 Setting<bool> use_vsync{true, "use_vsync"}; 443 SwitchableSetting<bool> use_vsync{true, "use_vsync"};
531 RangedSetting<u16> fps_cap{1000, 1, 1000, "fps_cap"}; 444 SwitchableSetting<u16> fps_cap{1000, 1, 1000, "fps_cap"};
532 BasicSetting<bool> disable_fps_limit{false, "disable_fps_limit"}; 445 Setting<bool> disable_fps_limit{false, "disable_fps_limit"};
533 RangedSetting<ShaderBackend> shader_backend{ShaderBackend::GLASM, ShaderBackend::GLSL, 446 SwitchableSetting<ShaderBackend> shader_backend{ShaderBackend::GLASM, ShaderBackend::GLSL,
534 ShaderBackend::SPIRV, "shader_backend"}; 447 ShaderBackend::SPIRV, "shader_backend"};
535 Setting<bool> use_asynchronous_shaders{false, "use_asynchronous_shaders"}; 448 SwitchableSetting<bool> use_asynchronous_shaders{false, "use_asynchronous_shaders"};
536 Setting<bool> use_fast_gpu_time{true, "use_fast_gpu_time"}; 449 SwitchableSetting<bool> use_fast_gpu_time{true, "use_fast_gpu_time"};
537 450
538 Setting<u8> bg_red{0, "bg_red"}; 451 SwitchableSetting<u8> bg_red{0, "bg_red"};
539 Setting<u8> bg_green{0, "bg_green"}; 452 SwitchableSetting<u8> bg_green{0, "bg_green"};
540 Setting<u8> bg_blue{0, "bg_blue"}; 453 SwitchableSetting<u8> bg_blue{0, "bg_blue"};
541 454
542 // System 455 // System
543 Setting<std::optional<u32>> rng_seed{std::optional<u32>(), "rng_seed"}; 456 SwitchableSetting<std::optional<u32>> rng_seed{std::optional<u32>(), "rng_seed"};
544 // Measured in seconds since epoch 457 // Measured in seconds since epoch
545 std::optional<s64> custom_rtc; 458 std::optional<s64> custom_rtc;
546 // Set on game boot, reset on stop. Seconds difference between current time and `custom_rtc` 459 // Set on game boot, reset on stop. Seconds difference between current time and `custom_rtc`
547 s64 custom_rtc_differential; 460 s64 custom_rtc_differential;
548 461
549 BasicSetting<s32> current_user{0, "current_user"}; 462 Setting<s32> current_user{0, "current_user"};
550 RangedSetting<s32> language_index{1, 0, 17, "language_index"}; 463 SwitchableSetting<s32> language_index{1, 0, 17, "language_index"};
551 RangedSetting<s32> region_index{1, 0, 6, "region_index"}; 464 SwitchableSetting<s32> region_index{1, 0, 6, "region_index"};
552 RangedSetting<s32> time_zone_index{0, 0, 45, "time_zone_index"}; 465 SwitchableSetting<s32> time_zone_index{0, 0, 45, "time_zone_index"};
553 RangedSetting<s32> sound_index{1, 0, 2, "sound_index"}; 466 SwitchableSetting<s32> sound_index{1, 0, 2, "sound_index"};
554 467
555 // Controls 468 // Controls
556 InputSetting<std::array<PlayerInput, 10>> players; 469 InputSetting<std::array<PlayerInput, 10>> players;
557 470
558 Setting<bool> use_docked_mode{true, "use_docked_mode"}; 471 SwitchableSetting<bool> use_docked_mode{true, "use_docked_mode"};
559 472
560 BasicSetting<bool> enable_raw_input{false, "enable_raw_input"}; 473 Setting<bool> enable_raw_input{false, "enable_raw_input"};
561 BasicSetting<bool> controller_navigation{true, "controller_navigation"}; 474 Setting<bool> controller_navigation{true, "controller_navigation"};
562 475
563 Setting<bool> vibration_enabled{true, "vibration_enabled"}; 476 SwitchableSetting<bool> vibration_enabled{true, "vibration_enabled"};
564 Setting<bool> enable_accurate_vibrations{false, "enable_accurate_vibrations"}; 477 SwitchableSetting<bool> enable_accurate_vibrations{false, "enable_accurate_vibrations"};
565 478
566 Setting<bool> motion_enabled{true, "motion_enabled"}; 479 SwitchableSetting<bool> motion_enabled{true, "motion_enabled"};
567 BasicSetting<std::string> udp_input_servers{"127.0.0.1:26760", "udp_input_servers"}; 480 Setting<std::string> udp_input_servers{"127.0.0.1:26760", "udp_input_servers"};
568 BasicSetting<bool> enable_udp_controller{false, "enable_udp_controller"}; 481 Setting<bool> enable_udp_controller{false, "enable_udp_controller"};
569 482
570 BasicSetting<bool> pause_tas_on_load{true, "pause_tas_on_load"}; 483 Setting<bool> pause_tas_on_load{true, "pause_tas_on_load"};
571 BasicSetting<bool> tas_enable{false, "tas_enable"}; 484 Setting<bool> tas_enable{false, "tas_enable"};
572 BasicSetting<bool> tas_loop{false, "tas_loop"}; 485 Setting<bool> tas_loop{false, "tas_loop"};
573 486
574 BasicSetting<bool> mouse_panning{false, "mouse_panning"}; 487 Setting<bool> mouse_panning{false, "mouse_panning"};
575 BasicRangedSetting<u8> mouse_panning_sensitivity{10, 1, 100, "mouse_panning_sensitivity"}; 488 Setting<u8> mouse_panning_sensitivity{10, 1, 100, "mouse_panning_sensitivity"};
576 BasicSetting<bool> mouse_enabled{false, "mouse_enabled"}; 489 Setting<bool> mouse_enabled{false, "mouse_enabled"};
577 490
578 BasicSetting<bool> emulate_analog_keyboard{false, "emulate_analog_keyboard"}; 491 Setting<bool> emulate_analog_keyboard{false, "emulate_analog_keyboard"};
579 BasicSetting<bool> keyboard_enabled{false, "keyboard_enabled"}; 492 Setting<bool> keyboard_enabled{false, "keyboard_enabled"};
580 493
581 BasicSetting<bool> debug_pad_enabled{false, "debug_pad_enabled"}; 494 Setting<bool> debug_pad_enabled{false, "debug_pad_enabled"};
582 ButtonsRaw debug_pad_buttons; 495 ButtonsRaw debug_pad_buttons;
583 AnalogsRaw debug_pad_analogs; 496 AnalogsRaw debug_pad_analogs;
584 497
585 TouchscreenInput touchscreen; 498 TouchscreenInput touchscreen;
586 499
587 BasicSetting<std::string> touch_device{"min_x:100,min_y:50,max_x:1800,max_y:850", 500 Setting<std::string> touch_device{"min_x:100,min_y:50,max_x:1800,max_y:850", "touch_device"};
588 "touch_device"}; 501 Setting<int> touch_from_button_map_index{0, "touch_from_button_map"};
589 BasicSetting<int> touch_from_button_map_index{0, "touch_from_button_map"};
590 std::vector<TouchFromButtonMap> touch_from_button_maps; 502 std::vector<TouchFromButtonMap> touch_from_button_maps;
591 503
592 BasicSetting<bool> enable_ring_controller{true, "enable_ring_controller"}; 504 Setting<bool> enable_ring_controller{true, "enable_ring_controller"};
593 RingconRaw ringcon_analogs; 505 RingconRaw ringcon_analogs;
594 506
595 // Data Storage 507 // Data Storage
596 BasicSetting<bool> use_virtual_sd{true, "use_virtual_sd"}; 508 Setting<bool> use_virtual_sd{true, "use_virtual_sd"};
597 BasicSetting<bool> gamecard_inserted{false, "gamecard_inserted"}; 509 Setting<bool> gamecard_inserted{false, "gamecard_inserted"};
598 BasicSetting<bool> gamecard_current_game{false, "gamecard_current_game"}; 510 Setting<bool> gamecard_current_game{false, "gamecard_current_game"};
599 BasicSetting<std::string> gamecard_path{std::string(), "gamecard_path"}; 511 Setting<std::string> gamecard_path{std::string(), "gamecard_path"};
600 512
601 // Debugging 513 // Debugging
602 bool record_frame_times; 514 bool record_frame_times;
603 BasicSetting<bool> use_gdbstub{false, "use_gdbstub"}; 515 Setting<bool> use_gdbstub{false, "use_gdbstub"};
604 BasicSetting<u16> gdbstub_port{6543, "gdbstub_port"}; 516 Setting<u16> gdbstub_port{6543, "gdbstub_port"};
605 BasicSetting<std::string> program_args{std::string(), "program_args"}; 517 Setting<std::string> program_args{std::string(), "program_args"};
606 BasicSetting<bool> dump_exefs{false, "dump_exefs"}; 518 Setting<bool> dump_exefs{false, "dump_exefs"};
607 BasicSetting<bool> dump_nso{false, "dump_nso"}; 519 Setting<bool> dump_nso{false, "dump_nso"};
608 BasicSetting<bool> dump_shaders{false, "dump_shaders"}; 520 Setting<bool> dump_shaders{false, "dump_shaders"};
609 BasicSetting<bool> dump_macros{false, "dump_macros"}; 521 Setting<bool> dump_macros{false, "dump_macros"};
610 BasicSetting<bool> enable_fs_access_log{false, "enable_fs_access_log"}; 522 Setting<bool> enable_fs_access_log{false, "enable_fs_access_log"};
611 BasicSetting<bool> reporting_services{false, "reporting_services"}; 523 Setting<bool> reporting_services{false, "reporting_services"};
612 BasicSetting<bool> quest_flag{false, "quest_flag"}; 524 Setting<bool> quest_flag{false, "quest_flag"};
613 BasicSetting<bool> disable_macro_jit{false, "disable_macro_jit"}; 525 Setting<bool> disable_macro_jit{false, "disable_macro_jit"};
614 BasicSetting<bool> extended_logging{false, "extended_logging"}; 526 Setting<bool> extended_logging{false, "extended_logging"};
615 BasicSetting<bool> use_debug_asserts{false, "use_debug_asserts"}; 527 Setting<bool> use_debug_asserts{false, "use_debug_asserts"};
616 BasicSetting<bool> use_auto_stub{false, "use_auto_stub"}; 528 Setting<bool> use_auto_stub{false, "use_auto_stub"};
617 BasicSetting<bool> enable_all_controllers{false, "enable_all_controllers"}; 529 Setting<bool> enable_all_controllers{false, "enable_all_controllers"};
618 530
619 // Miscellaneous 531 // Miscellaneous
620 BasicSetting<std::string> log_filter{"*:Info", "log_filter"}; 532 Setting<std::string> log_filter{"*:Info", "log_filter"};
621 BasicSetting<bool> use_dev_keys{false, "use_dev_keys"}; 533 Setting<bool> use_dev_keys{false, "use_dev_keys"};
622 534
623 // Network 535 // Network
624 BasicSetting<std::string> network_interface{std::string(), "network_interface"}; 536 Setting<std::string> network_interface{std::string(), "network_interface"};
625 537
626 // WebService 538 // WebService
627 BasicSetting<bool> enable_telemetry{true, "enable_telemetry"}; 539 Setting<bool> enable_telemetry{true, "enable_telemetry"};
628 BasicSetting<std::string> web_api_url{"https://api.yuzu-emu.org", "web_api_url"}; 540 Setting<std::string> web_api_url{"https://api.yuzu-emu.org", "web_api_url"};
629 BasicSetting<std::string> yuzu_username{std::string(), "yuzu_username"}; 541 Setting<std::string> yuzu_username{std::string(), "yuzu_username"};
630 BasicSetting<std::string> yuzu_token{std::string(), "yuzu_token"}; 542 Setting<std::string> yuzu_token{std::string(), "yuzu_token"};
631 543
632 // Add-Ons 544 // Add-Ons
633 std::map<u64, std::vector<std::string>> disabled_addons; 545 std::map<u64, std::vector<std::string>> disabled_addons;
diff --git a/src/common/thread.cpp b/src/common/thread.cpp
index f932a7290..919e33af9 100644
--- a/src/common/thread.cpp
+++ b/src/common/thread.cpp
@@ -47,6 +47,9 @@ void SetCurrentThreadPriority(ThreadPriority new_priority) {
47 case ThreadPriority::VeryHigh: 47 case ThreadPriority::VeryHigh:
48 windows_priority = THREAD_PRIORITY_HIGHEST; 48 windows_priority = THREAD_PRIORITY_HIGHEST;
49 break; 49 break;
50 case ThreadPriority::Critical:
51 windows_priority = THREAD_PRIORITY_TIME_CRITICAL;
52 break;
50 default: 53 default:
51 windows_priority = THREAD_PRIORITY_NORMAL; 54 windows_priority = THREAD_PRIORITY_NORMAL;
52 break; 55 break;
@@ -59,9 +62,10 @@ void SetCurrentThreadPriority(ThreadPriority new_priority) {
59void SetCurrentThreadPriority(ThreadPriority new_priority) { 62void SetCurrentThreadPriority(ThreadPriority new_priority) {
60 pthread_t this_thread = pthread_self(); 63 pthread_t this_thread = pthread_self();
61 64
62 s32 max_prio = sched_get_priority_max(SCHED_OTHER); 65 const auto scheduling_type = SCHED_OTHER;
63 s32 min_prio = sched_get_priority_min(SCHED_OTHER); 66 s32 max_prio = sched_get_priority_max(scheduling_type);
64 u32 level = static_cast<u32>(new_priority) + 1; 67 s32 min_prio = sched_get_priority_min(scheduling_type);
68 u32 level = std::max(static_cast<u32>(new_priority) + 1, 4U);
65 69
66 struct sched_param params; 70 struct sched_param params;
67 if (max_prio > min_prio) { 71 if (max_prio > min_prio) {
@@ -70,7 +74,7 @@ void SetCurrentThreadPriority(ThreadPriority new_priority) {
70 params.sched_priority = min_prio - ((min_prio - max_prio) * level) / 4; 74 params.sched_priority = min_prio - ((min_prio - max_prio) * level) / 4;
71 } 75 }
72 76
73 pthread_setschedparam(this_thread, SCHED_OTHER, &params); 77 pthread_setschedparam(this_thread, scheduling_type, &params);
74} 78}
75 79
76#endif 80#endif
diff --git a/src/common/thread.h b/src/common/thread.h
index a63122516..1552f58e0 100644
--- a/src/common/thread.h
+++ b/src/common/thread.h
@@ -92,6 +92,7 @@ enum class ThreadPriority : u32 {
92 Normal = 1, 92 Normal = 1,
93 High = 2, 93 High = 2,
94 VeryHigh = 3, 94 VeryHigh = 3,
95 Critical = 4,
95}; 96};
96 97
97void SetCurrentThreadPriority(ThreadPriority new_priority); 98void SetCurrentThreadPriority(ThreadPriority new_priority);
diff --git a/src/common/uint128.h b/src/common/uint128.h
index f890ffec2..199d0f55e 100644
--- a/src/common/uint128.h
+++ b/src/common/uint128.h
@@ -31,12 +31,17 @@ namespace Common {
31 return _udiv128(r[1], r[0], d, &remainder); 31 return _udiv128(r[1], r[0], d, &remainder);
32#endif 32#endif
33#else 33#else
34#ifdef __SIZEOF_INT128__
35 const auto product = static_cast<unsigned __int128>(a) * static_cast<unsigned __int128>(b);
36 return static_cast<u64>(product / d);
37#else
34 const u64 diva = a / d; 38 const u64 diva = a / d;
35 const u64 moda = a % d; 39 const u64 moda = a % d;
36 const u64 divb = b / d; 40 const u64 divb = b / d;
37 const u64 modb = b % d; 41 const u64 modb = b % d;
38 return diva * b + moda * divb + moda * modb / d; 42 return diva * b + moda * divb + moda * modb / d;
39#endif 43#endif
44#endif
40} 45}
41 46
42// This function multiplies 2 u64 values and produces a u128 value; 47// This function multiplies 2 u64 values and produces a u128 value;
diff --git a/src/common/x64/native_clock.cpp b/src/common/x64/native_clock.cpp
index 1b7194503..6aaa8cdf9 100644
--- a/src/common/x64/native_clock.cpp
+++ b/src/common/x64/native_clock.cpp
@@ -75,8 +75,8 @@ NativeClock::NativeClock(u64 emulated_cpu_frequency_, u64 emulated_clock_frequen
75} 75}
76 76
77u64 NativeClock::GetRTSC() { 77u64 NativeClock::GetRTSC() {
78 TimePoint new_time_point{};
79 TimePoint current_time_point{}; 78 TimePoint current_time_point{};
79 TimePoint new_time_point{};
80 80
81 current_time_point.pack = Common::AtomicLoad128(time_point.pack.data()); 81 current_time_point.pack = Common::AtomicLoad128(time_point.pack.data());
82 do { 82 do {
@@ -89,8 +89,7 @@ u64 NativeClock::GetRTSC() {
89 new_time_point.inner.accumulated_ticks = current_time_point.inner.accumulated_ticks + diff; 89 new_time_point.inner.accumulated_ticks = current_time_point.inner.accumulated_ticks + diff;
90 } while (!Common::AtomicCompareAndSwap(time_point.pack.data(), new_time_point.pack, 90 } while (!Common::AtomicCompareAndSwap(time_point.pack.data(), new_time_point.pack,
91 current_time_point.pack, current_time_point.pack)); 91 current_time_point.pack, current_time_point.pack));
92 /// The clock cannot be more precise than the guest timer, remove the lower bits 92 return new_time_point.inner.accumulated_ticks;
93 return new_time_point.inner.accumulated_ticks & inaccuracy_mask;
94} 93}
95 94
96void NativeClock::Pause(bool is_paused) { 95void NativeClock::Pause(bool is_paused) {
diff --git a/src/common/x64/native_clock.h b/src/common/x64/native_clock.h
index 30d2ba2e9..38ae7a462 100644
--- a/src/common/x64/native_clock.h
+++ b/src/common/x64/native_clock.h
@@ -37,12 +37,8 @@ private:
37 } inner; 37 } inner;
38 }; 38 };
39 39
40 /// value used to reduce the native clocks accuracy as some apss rely on
41 /// undefined behavior where the level of accuracy in the clock shouldn't
42 /// be higher.
43 static constexpr u64 inaccuracy_mask = ~(UINT64_C(0x400) - 1);
44
45 TimePoint time_point; 40 TimePoint time_point;
41
46 // factors 42 // factors
47 u64 clock_rtsc_factor{}; 43 u64 clock_rtsc_factor{};
48 u64 cpu_rtsc_factor{}; 44 u64 cpu_rtsc_factor{};
diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt
index 670410e75..d9357138f 100644
--- a/src/core/CMakeLists.txt
+++ b/src/core/CMakeLists.txt
@@ -222,7 +222,7 @@ add_library(core STATIC
222 hle/kernel/k_page_buffer.h 222 hle/kernel/k_page_buffer.h
223 hle/kernel/k_page_heap.cpp 223 hle/kernel/k_page_heap.cpp
224 hle/kernel/k_page_heap.h 224 hle/kernel/k_page_heap.h
225 hle/kernel/k_page_linked_list.h 225 hle/kernel/k_page_group.h
226 hle/kernel/k_page_table.cpp 226 hle/kernel/k_page_table.cpp
227 hle/kernel/k_page_table.h 227 hle/kernel/k_page_table.h
228 hle/kernel/k_port.cpp 228 hle/kernel/k_port.cpp
diff --git a/src/core/arm/arm_interface.cpp b/src/core/arm/arm_interface.cpp
index 6425e131f..0efc3732f 100644
--- a/src/core/arm/arm_interface.cpp
+++ b/src/core/arm/arm_interface.cpp
@@ -95,7 +95,7 @@ void ARM_Interface::Run() {
95 using Kernel::SuspendType; 95 using Kernel::SuspendType;
96 96
97 while (true) { 97 while (true) {
98 Kernel::KThread* current_thread{system.Kernel().CurrentScheduler()->GetCurrentThread()}; 98 Kernel::KThread* current_thread{Kernel::GetCurrentThreadPointer(system.Kernel())};
99 Dynarmic::HaltReason hr{}; 99 Dynarmic::HaltReason hr{};
100 100
101 // Notify the debugger and go to sleep if a step was performed 101 // Notify the debugger and go to sleep if a step was performed
@@ -119,16 +119,23 @@ void ARM_Interface::Run() {
119 } 119 }
120 system.ExitDynarmicProfile(); 120 system.ExitDynarmicProfile();
121 121
122 // Notify the debugger and go to sleep if a breakpoint was hit. 122 // Notify the debugger and go to sleep if a breakpoint was hit,
123 if (Has(hr, breakpoint)) { 123 // or if the thread is unable to continue for any reason.
124 if (Has(hr, breakpoint) || Has(hr, no_execute)) {
124 RewindBreakpointInstruction(); 125 RewindBreakpointInstruction();
125 system.GetDebugger().NotifyThreadStopped(current_thread); 126 if (system.DebuggerEnabled()) {
126 current_thread->RequestSuspend(SuspendType::Debug); 127 system.GetDebugger().NotifyThreadStopped(current_thread);
128 }
129 current_thread->RequestSuspend(Kernel::SuspendType::Debug);
127 break; 130 break;
128 } 131 }
132
133 // Notify the debugger and go to sleep if a watchpoint was hit.
129 if (Has(hr, watchpoint)) { 134 if (Has(hr, watchpoint)) {
130 RewindBreakpointInstruction(); 135 RewindBreakpointInstruction();
131 system.GetDebugger().NotifyThreadWatchpoint(current_thread, *HaltedWatchpoint()); 136 if (system.DebuggerEnabled()) {
137 system.GetDebugger().NotifyThreadWatchpoint(current_thread, *HaltedWatchpoint());
138 }
132 current_thread->RequestSuspend(SuspendType::Debug); 139 current_thread->RequestSuspend(SuspendType::Debug);
133 break; 140 break;
134 } 141 }
diff --git a/src/core/arm/arm_interface.h b/src/core/arm/arm_interface.h
index 4e431e27a..8a066ed91 100644
--- a/src/core/arm/arm_interface.h
+++ b/src/core/arm/arm_interface.h
@@ -204,6 +204,7 @@ public:
204 static constexpr Dynarmic::HaltReason svc_call = Dynarmic::HaltReason::UserDefined3; 204 static constexpr Dynarmic::HaltReason svc_call = Dynarmic::HaltReason::UserDefined3;
205 static constexpr Dynarmic::HaltReason breakpoint = Dynarmic::HaltReason::UserDefined4; 205 static constexpr Dynarmic::HaltReason breakpoint = Dynarmic::HaltReason::UserDefined4;
206 static constexpr Dynarmic::HaltReason watchpoint = Dynarmic::HaltReason::UserDefined5; 206 static constexpr Dynarmic::HaltReason watchpoint = Dynarmic::HaltReason::UserDefined5;
207 static constexpr Dynarmic::HaltReason no_execute = Dynarmic::HaltReason::UserDefined6;
207 208
208protected: 209protected:
209 /// System context that this ARM interface is running under. 210 /// System context that this ARM interface is running under.
diff --git a/src/core/arm/dynarmic/arm_dynarmic_32.cpp b/src/core/arm/dynarmic/arm_dynarmic_32.cpp
index 8c90c8be0..10cf72a45 100644
--- a/src/core/arm/dynarmic/arm_dynarmic_32.cpp
+++ b/src/core/arm/dynarmic/arm_dynarmic_32.cpp
@@ -48,6 +48,12 @@ public:
48 CheckMemoryAccess(vaddr, 8, Kernel::DebugWatchpointType::Read); 48 CheckMemoryAccess(vaddr, 8, Kernel::DebugWatchpointType::Read);
49 return memory.Read64(vaddr); 49 return memory.Read64(vaddr);
50 } 50 }
51 std::optional<u32> MemoryReadCode(u32 vaddr) override {
52 if (!memory.IsValidVirtualAddressRange(vaddr, sizeof(u32))) {
53 return std::nullopt;
54 }
55 return MemoryRead32(vaddr);
56 }
51 57
52 void MemoryWrite8(u32 vaddr, u8 value) override { 58 void MemoryWrite8(u32 vaddr, u8 value) override {
53 if (CheckMemoryAccess(vaddr, 1, Kernel::DebugWatchpointType::Write)) { 59 if (CheckMemoryAccess(vaddr, 1, Kernel::DebugWatchpointType::Write)) {
@@ -89,21 +95,28 @@ public:
89 95
90 void InterpreterFallback(u32 pc, std::size_t num_instructions) override { 96 void InterpreterFallback(u32 pc, std::size_t num_instructions) override {
91 parent.LogBacktrace(); 97 parent.LogBacktrace();
92 UNIMPLEMENTED_MSG("This should never happen, pc = {:08X}, code = {:08X}", pc, 98 LOG_ERROR(Core_ARM,
93 MemoryReadCode(pc)); 99 "Unimplemented instruction @ 0x{:X} for {} instructions (instr = {:08X})", pc,
100 num_instructions, MemoryRead32(pc));
94 } 101 }
95 102
96 void ExceptionRaised(u32 pc, Dynarmic::A32::Exception exception) override { 103 void ExceptionRaised(u32 pc, Dynarmic::A32::Exception exception) override {
97 if (debugger_enabled) { 104 switch (exception) {
98 parent.SaveContext(parent.breakpoint_context); 105 case Dynarmic::A32::Exception::NoExecuteFault:
99 parent.jit.load()->HaltExecution(ARM_Interface::breakpoint); 106 LOG_CRITICAL(Core_ARM, "Cannot execute instruction at unmapped address {:#08x}", pc);
107 ReturnException(pc, ARM_Interface::no_execute);
100 return; 108 return;
101 } 109 default:
110 if (debugger_enabled) {
111 ReturnException(pc, ARM_Interface::breakpoint);
112 return;
113 }
102 114
103 parent.LogBacktrace(); 115 parent.LogBacktrace();
104 LOG_CRITICAL(Core_ARM, 116 LOG_CRITICAL(Core_ARM,
105 "ExceptionRaised(exception = {}, pc = {:08X}, code = {:08X}, thumb = {})", 117 "ExceptionRaised(exception = {}, pc = {:08X}, code = {:08X}, thumb = {})",
106 exception, pc, MemoryReadCode(pc), parent.IsInThumbMode()); 118 exception, pc, MemoryRead32(pc), parent.IsInThumbMode());
119 }
107 } 120 }
108 121
109 void CallSVC(u32 swi) override { 122 void CallSVC(u32 swi) override {
@@ -141,15 +154,20 @@ public:
141 154
142 const auto match{parent.MatchingWatchpoint(addr, size, type)}; 155 const auto match{parent.MatchingWatchpoint(addr, size, type)};
143 if (match) { 156 if (match) {
144 parent.SaveContext(parent.breakpoint_context);
145 parent.jit.load()->HaltExecution(ARM_Interface::watchpoint);
146 parent.halted_watchpoint = match; 157 parent.halted_watchpoint = match;
158 ReturnException(parent.jit.load()->Regs()[15], ARM_Interface::watchpoint);
147 return false; 159 return false;
148 } 160 }
149 161
150 return true; 162 return true;
151 } 163 }
152 164
165 void ReturnException(u32 pc, Dynarmic::HaltReason hr) {
166 parent.SaveContext(parent.breakpoint_context);
167 parent.breakpoint_context.cpu_registers[15] = pc;
168 parent.jit.load()->HaltExecution(hr);
169 }
170
153 ARM_Dynarmic_32& parent; 171 ARM_Dynarmic_32& parent;
154 Core::Memory::Memory& memory; 172 Core::Memory::Memory& memory;
155 std::size_t num_interpreted_instructions{}; 173 std::size_t num_interpreted_instructions{};
diff --git a/src/core/arm/dynarmic/arm_dynarmic_64.cpp b/src/core/arm/dynarmic/arm_dynarmic_64.cpp
index 4370ca294..92266aa9e 100644
--- a/src/core/arm/dynarmic/arm_dynarmic_64.cpp
+++ b/src/core/arm/dynarmic/arm_dynarmic_64.cpp
@@ -52,6 +52,12 @@ public:
52 CheckMemoryAccess(vaddr, 16, Kernel::DebugWatchpointType::Read); 52 CheckMemoryAccess(vaddr, 16, Kernel::DebugWatchpointType::Read);
53 return {memory.Read64(vaddr), memory.Read64(vaddr + 8)}; 53 return {memory.Read64(vaddr), memory.Read64(vaddr + 8)};
54 } 54 }
55 std::optional<u32> MemoryReadCode(u64 vaddr) override {
56 if (!memory.IsValidVirtualAddressRange(vaddr, sizeof(u32))) {
57 return std::nullopt;
58 }
59 return MemoryRead32(vaddr);
60 }
55 61
56 void MemoryWrite8(u64 vaddr, u8 value) override { 62 void MemoryWrite8(u64 vaddr, u8 value) override {
57 if (CheckMemoryAccess(vaddr, 1, Kernel::DebugWatchpointType::Write)) { 63 if (CheckMemoryAccess(vaddr, 1, Kernel::DebugWatchpointType::Write)) {
@@ -105,7 +111,7 @@ public:
105 parent.LogBacktrace(); 111 parent.LogBacktrace();
106 LOG_ERROR(Core_ARM, 112 LOG_ERROR(Core_ARM,
107 "Unimplemented instruction @ 0x{:X} for {} instructions (instr = {:08X})", pc, 113 "Unimplemented instruction @ 0x{:X} for {} instructions (instr = {:08X})", pc,
108 num_instructions, MemoryReadCode(pc)); 114 num_instructions, MemoryRead32(pc));
109 } 115 }
110 116
111 void InstructionCacheOperationRaised(Dynarmic::A64::InstructionCacheOperation op, 117 void InstructionCacheOperationRaised(Dynarmic::A64::InstructionCacheOperation op,
@@ -138,16 +144,19 @@ public:
138 case Dynarmic::A64::Exception::SendEventLocal: 144 case Dynarmic::A64::Exception::SendEventLocal:
139 case Dynarmic::A64::Exception::Yield: 145 case Dynarmic::A64::Exception::Yield:
140 return; 146 return;
147 case Dynarmic::A64::Exception::NoExecuteFault:
148 LOG_CRITICAL(Core_ARM, "Cannot execute instruction at unmapped address {:#016x}", pc);
149 ReturnException(pc, ARM_Interface::no_execute);
150 return;
141 default: 151 default:
142 if (debugger_enabled) { 152 if (debugger_enabled) {
143 parent.SaveContext(parent.breakpoint_context); 153 ReturnException(pc, ARM_Interface::breakpoint);
144 parent.jit.load()->HaltExecution(ARM_Interface::breakpoint);
145 return; 154 return;
146 } 155 }
147 156
148 parent.LogBacktrace(); 157 parent.LogBacktrace();
149 ASSERT_MSG(false, "ExceptionRaised(exception = {}, pc = {:08X}, code = {:08X})", 158 LOG_CRITICAL(Core_ARM, "ExceptionRaised(exception = {}, pc = {:08X}, code = {:08X})",
150 static_cast<std::size_t>(exception), pc, MemoryReadCode(pc)); 159 static_cast<std::size_t>(exception), pc, MemoryRead32(pc));
151 } 160 }
152 } 161 }
153 162
@@ -188,15 +197,20 @@ public:
188 197
189 const auto match{parent.MatchingWatchpoint(addr, size, type)}; 198 const auto match{parent.MatchingWatchpoint(addr, size, type)};
190 if (match) { 199 if (match) {
191 parent.SaveContext(parent.breakpoint_context);
192 parent.jit.load()->HaltExecution(ARM_Interface::watchpoint);
193 parent.halted_watchpoint = match; 200 parent.halted_watchpoint = match;
201 ReturnException(parent.jit.load()->GetPC(), ARM_Interface::watchpoint);
194 return false; 202 return false;
195 } 203 }
196 204
197 return true; 205 return true;
198 } 206 }
199 207
208 void ReturnException(u64 pc, Dynarmic::HaltReason hr) {
209 parent.SaveContext(parent.breakpoint_context);
210 parent.breakpoint_context.pc = pc;
211 parent.jit.load()->HaltExecution(hr);
212 }
213
200 ARM_Dynarmic_64& parent; 214 ARM_Dynarmic_64& parent;
201 Core::Memory::Memory& memory; 215 Core::Memory::Memory& memory;
202 u64 tpidrro_el0 = 0; 216 u64 tpidrro_el0 = 0;
diff --git a/src/core/core_timing.cpp b/src/core/core_timing.cpp
index 29e7dba9b..140578069 100644
--- a/src/core/core_timing.cpp
+++ b/src/core/core_timing.cpp
@@ -6,7 +6,9 @@
6#include <string> 6#include <string>
7#include <tuple> 7#include <tuple>
8 8
9#include "common/logging/log.h"
9#include "common/microprofile.h" 10#include "common/microprofile.h"
11#include "common/thread.h"
10#include "core/core_timing.h" 12#include "core/core_timing.h"
11#include "core/core_timing_util.h" 13#include "core/core_timing_util.h"
12#include "core/hardware_properties.h" 14#include "core/hardware_properties.h"
@@ -41,11 +43,11 @@ CoreTiming::CoreTiming()
41 43
42CoreTiming::~CoreTiming() = default; 44CoreTiming::~CoreTiming() = default;
43 45
44void CoreTiming::ThreadEntry(CoreTiming& instance) { 46void CoreTiming::ThreadEntry(CoreTiming& instance, size_t id) {
45 constexpr char name[] = "yuzu:HostTiming"; 47 const std::string name = "yuzu:HostTiming_" + std::to_string(id);
46 MicroProfileOnThreadCreate(name); 48 MicroProfileOnThreadCreate(name.c_str());
47 Common::SetCurrentThreadName(name); 49 Common::SetCurrentThreadName(name.c_str());
48 Common::SetCurrentThreadPriority(Common::ThreadPriority::VeryHigh); 50 Common::SetCurrentThreadPriority(Common::ThreadPriority::Critical);
49 instance.on_thread_init(); 51 instance.on_thread_init();
50 instance.ThreadLoop(); 52 instance.ThreadLoop();
51 MicroProfileOnThreadExit(); 53 MicroProfileOnThreadExit();
@@ -59,68 +61,97 @@ void CoreTiming::Initialize(std::function<void()>&& on_thread_init_) {
59 const auto empty_timed_callback = [](std::uintptr_t, std::chrono::nanoseconds) {}; 61 const auto empty_timed_callback = [](std::uintptr_t, std::chrono::nanoseconds) {};
60 ev_lost = CreateEvent("_lost_event", empty_timed_callback); 62 ev_lost = CreateEvent("_lost_event", empty_timed_callback);
61 if (is_multicore) { 63 if (is_multicore) {
62 timer_thread = std::make_unique<std::thread>(ThreadEntry, std::ref(*this)); 64 const auto hardware_concurrency = std::thread::hardware_concurrency();
65 size_t id = 0;
66 worker_threads.emplace_back(ThreadEntry, std::ref(*this), id++);
67 if (hardware_concurrency > 8) {
68 worker_threads.emplace_back(ThreadEntry, std::ref(*this), id++);
69 }
63 } 70 }
64} 71}
65 72
66void CoreTiming::Shutdown() { 73void CoreTiming::Shutdown() {
67 paused = true; 74 is_paused = true;
68 shutting_down = true; 75 shutting_down = true;
69 pause_event.Set(); 76 std::atomic_thread_fence(std::memory_order_release);
70 event.Set(); 77
71 if (timer_thread) { 78 event_cv.notify_all();
72 timer_thread->join(); 79 wait_pause_cv.notify_all();
80 for (auto& thread : worker_threads) {
81 thread.join();
73 } 82 }
83 worker_threads.clear();
74 ClearPendingEvents(); 84 ClearPendingEvents();
75 timer_thread.reset();
76 has_started = false; 85 has_started = false;
77} 86}
78 87
79void CoreTiming::Pause(bool is_paused) { 88void CoreTiming::Pause(bool is_paused_) {
80 paused = is_paused; 89 std::unique_lock main_lock(event_mutex);
81 pause_event.Set(); 90 if (is_paused_ == paused_state.load(std::memory_order_relaxed)) {
91 return;
92 }
93 if (is_multicore) {
94 is_paused = is_paused_;
95 event_cv.notify_all();
96 if (!is_paused_) {
97 wait_pause_cv.notify_all();
98 }
99 }
100 paused_state.store(is_paused_, std::memory_order_relaxed);
82} 101}
83 102
84void CoreTiming::SyncPause(bool is_paused) { 103void CoreTiming::SyncPause(bool is_paused_) {
85 if (is_paused == paused && paused_set == paused) { 104 std::unique_lock main_lock(event_mutex);
105 if (is_paused_ == paused_state.load(std::memory_order_relaxed)) {
86 return; 106 return;
87 } 107 }
88 Pause(is_paused); 108
89 if (timer_thread) { 109 if (is_multicore) {
90 if (!is_paused) { 110 is_paused = is_paused_;
91 pause_event.Set(); 111 event_cv.notify_all();
112 if (!is_paused_) {
113 wait_pause_cv.notify_all();
114 }
115 }
116 paused_state.store(is_paused_, std::memory_order_relaxed);
117 if (is_multicore) {
118 if (is_paused_) {
119 wait_signal_cv.wait(main_lock, [this] { return pause_count == worker_threads.size(); });
120 } else {
121 wait_signal_cv.wait(main_lock, [this] { return pause_count == 0; });
92 } 122 }
93 event.Set();
94 while (paused_set != is_paused)
95 ;
96 } 123 }
97} 124}
98 125
99bool CoreTiming::IsRunning() const { 126bool CoreTiming::IsRunning() const {
100 return !paused_set; 127 return !paused_state.load(std::memory_order_acquire);
101} 128}
102 129
103bool CoreTiming::HasPendingEvents() const { 130bool CoreTiming::HasPendingEvents() const {
104 return !(wait_set && event_queue.empty()); 131 std::unique_lock main_lock(event_mutex);
132 return !event_queue.empty() || pending_events.load(std::memory_order_relaxed) != 0;
105} 133}
106 134
107void CoreTiming::ScheduleEvent(std::chrono::nanoseconds ns_into_future, 135void CoreTiming::ScheduleEvent(std::chrono::nanoseconds ns_into_future,
108 const std::shared_ptr<EventType>& event_type, 136 const std::shared_ptr<EventType>& event_type,
109 std::uintptr_t user_data) { 137 std::uintptr_t user_data) {
110 {
111 std::scoped_lock scope{basic_lock};
112 const u64 timeout = static_cast<u64>((GetGlobalTimeNs() + ns_into_future).count());
113 138
114 event_queue.emplace_back(Event{timeout, event_fifo_id++, user_data, event_type}); 139 std::unique_lock main_lock(event_mutex);
140 const u64 timeout = static_cast<u64>((GetGlobalTimeNs() + ns_into_future).count());
141
142 event_queue.emplace_back(Event{timeout, event_fifo_id++, user_data, event_type});
143 pending_events.fetch_add(1, std::memory_order_relaxed);
115 144
116 std::push_heap(event_queue.begin(), event_queue.end(), std::greater<>()); 145 std::push_heap(event_queue.begin(), event_queue.end(), std::greater<>());
146
147 if (is_multicore) {
148 event_cv.notify_one();
117 } 149 }
118 event.Set();
119} 150}
120 151
121void CoreTiming::UnscheduleEvent(const std::shared_ptr<EventType>& event_type, 152void CoreTiming::UnscheduleEvent(const std::shared_ptr<EventType>& event_type,
122 std::uintptr_t user_data) { 153 std::uintptr_t user_data) {
123 std::scoped_lock scope{basic_lock}; 154 std::unique_lock main_lock(event_mutex);
124 const auto itr = std::remove_if(event_queue.begin(), event_queue.end(), [&](const Event& e) { 155 const auto itr = std::remove_if(event_queue.begin(), event_queue.end(), [&](const Event& e) {
125 return e.type.lock().get() == event_type.get() && e.user_data == user_data; 156 return e.type.lock().get() == event_type.get() && e.user_data == user_data;
126 }); 157 });
@@ -129,6 +160,7 @@ void CoreTiming::UnscheduleEvent(const std::shared_ptr<EventType>& event_type,
129 if (itr != event_queue.end()) { 160 if (itr != event_queue.end()) {
130 event_queue.erase(itr, event_queue.end()); 161 event_queue.erase(itr, event_queue.end());
131 std::make_heap(event_queue.begin(), event_queue.end(), std::greater<>()); 162 std::make_heap(event_queue.begin(), event_queue.end(), std::greater<>());
163 pending_events.fetch_sub(1, std::memory_order_relaxed);
132 } 164 }
133} 165}
134 166
@@ -168,11 +200,12 @@ u64 CoreTiming::GetClockTicks() const {
168} 200}
169 201
170void CoreTiming::ClearPendingEvents() { 202void CoreTiming::ClearPendingEvents() {
203 std::unique_lock main_lock(event_mutex);
171 event_queue.clear(); 204 event_queue.clear();
172} 205}
173 206
174void CoreTiming::RemoveEvent(const std::shared_ptr<EventType>& event_type) { 207void CoreTiming::RemoveEvent(const std::shared_ptr<EventType>& event_type) {
175 std::scoped_lock lock{basic_lock}; 208 std::unique_lock main_lock(event_mutex);
176 209
177 const auto itr = std::remove_if(event_queue.begin(), event_queue.end(), [&](const Event& e) { 210 const auto itr = std::remove_if(event_queue.begin(), event_queue.end(), [&](const Event& e) {
178 return e.type.lock().get() == event_type.get(); 211 return e.type.lock().get() == event_type.get();
@@ -186,21 +219,28 @@ void CoreTiming::RemoveEvent(const std::shared_ptr<EventType>& event_type) {
186} 219}
187 220
188std::optional<s64> CoreTiming::Advance() { 221std::optional<s64> CoreTiming::Advance() {
189 std::scoped_lock lock{advance_lock, basic_lock};
190 global_timer = GetGlobalTimeNs().count(); 222 global_timer = GetGlobalTimeNs().count();
191 223
224 std::unique_lock main_lock(event_mutex);
192 while (!event_queue.empty() && event_queue.front().time <= global_timer) { 225 while (!event_queue.empty() && event_queue.front().time <= global_timer) {
193 Event evt = std::move(event_queue.front()); 226 Event evt = std::move(event_queue.front());
194 std::pop_heap(event_queue.begin(), event_queue.end(), std::greater<>()); 227 std::pop_heap(event_queue.begin(), event_queue.end(), std::greater<>());
195 event_queue.pop_back(); 228 event_queue.pop_back();
196 basic_lock.unlock();
197 229
198 if (const auto event_type{evt.type.lock()}) { 230 if (const auto event_type{evt.type.lock()}) {
199 event_type->callback( 231 sequence_mutex.lock();
200 evt.user_data, std::chrono::nanoseconds{static_cast<s64>(global_timer - evt.time)}); 232 event_mutex.unlock();
233
234 event_type->guard.lock();
235 sequence_mutex.unlock();
236 const s64 delay = static_cast<s64>(GetGlobalTimeNs().count() - evt.time);
237 event_type->callback(evt.user_data, std::chrono::nanoseconds{delay});
238 event_type->guard.unlock();
239
240 event_mutex.lock();
241 pending_events.fetch_sub(1, std::memory_order_relaxed);
201 } 242 }
202 243
203 basic_lock.lock();
204 global_timer = GetGlobalTimeNs().count(); 244 global_timer = GetGlobalTimeNs().count();
205 } 245 }
206 246
@@ -213,26 +253,34 @@ std::optional<s64> CoreTiming::Advance() {
213} 253}
214 254
215void CoreTiming::ThreadLoop() { 255void CoreTiming::ThreadLoop() {
256 const auto predicate = [this] { return !event_queue.empty() || is_paused; };
216 has_started = true; 257 has_started = true;
217 while (!shutting_down) { 258 while (!shutting_down) {
218 while (!paused) { 259 while (!is_paused && !shutting_down) {
219 paused_set = false;
220 const auto next_time = Advance(); 260 const auto next_time = Advance();
221 if (next_time) { 261 if (next_time) {
222 if (*next_time > 0) { 262 if (*next_time > 0) {
223 std::chrono::nanoseconds next_time_ns = std::chrono::nanoseconds(*next_time); 263 std::chrono::nanoseconds next_time_ns = std::chrono::nanoseconds(*next_time);
224 event.WaitFor(next_time_ns); 264 std::unique_lock main_lock(event_mutex);
265 event_cv.wait_for(main_lock, next_time_ns, predicate);
225 } 266 }
226 } else { 267 } else {
227 wait_set = true; 268 std::unique_lock main_lock(event_mutex);
228 event.Wait(); 269 event_cv.wait(main_lock, predicate);
229 } 270 }
230 wait_set = false;
231 } 271 }
232 paused_set = true; 272 std::unique_lock main_lock(event_mutex);
233 clock->Pause(true); 273 pause_count++;
234 pause_event.Wait(); 274 if (pause_count == worker_threads.size()) {
235 clock->Pause(false); 275 clock->Pause(true);
276 wait_signal_cv.notify_all();
277 }
278 wait_pause_cv.wait(main_lock, [this] { return !is_paused || shutting_down; });
279 pause_count--;
280 if (pause_count == 0) {
281 clock->Pause(false);
282 wait_signal_cv.notify_all();
283 }
236 } 284 }
237} 285}
238 286
diff --git a/src/core/core_timing.h b/src/core/core_timing.h
index d27773009..a86553e08 100644
--- a/src/core/core_timing.h
+++ b/src/core/core_timing.h
@@ -5,6 +5,7 @@
5 5
6#include <atomic> 6#include <atomic>
7#include <chrono> 7#include <chrono>
8#include <condition_variable>
8#include <functional> 9#include <functional>
9#include <memory> 10#include <memory>
10#include <mutex> 11#include <mutex>
@@ -14,7 +15,6 @@
14#include <vector> 15#include <vector>
15 16
16#include "common/common_types.h" 17#include "common/common_types.h"
17#include "common/thread.h"
18#include "common/wall_clock.h" 18#include "common/wall_clock.h"
19 19
20namespace Core::Timing { 20namespace Core::Timing {
@@ -32,6 +32,7 @@ struct EventType {
32 TimedCallback callback; 32 TimedCallback callback;
33 /// A pointer to the name of the event. 33 /// A pointer to the name of the event.
34 const std::string name; 34 const std::string name;
35 mutable std::mutex guard;
35}; 36};
36 37
37/** 38/**
@@ -131,7 +132,7 @@ private:
131 /// Clear all pending events. This should ONLY be done on exit. 132 /// Clear all pending events. This should ONLY be done on exit.
132 void ClearPendingEvents(); 133 void ClearPendingEvents();
133 134
134 static void ThreadEntry(CoreTiming& instance); 135 static void ThreadEntry(CoreTiming& instance, size_t id);
135 void ThreadLoop(); 136 void ThreadLoop();
136 137
137 std::unique_ptr<Common::WallClock> clock; 138 std::unique_ptr<Common::WallClock> clock;
@@ -144,21 +145,25 @@ private:
144 // accomodated by the standard adaptor class. 145 // accomodated by the standard adaptor class.
145 std::vector<Event> event_queue; 146 std::vector<Event> event_queue;
146 u64 event_fifo_id = 0; 147 u64 event_fifo_id = 0;
148 std::atomic<size_t> pending_events{};
147 149
148 std::shared_ptr<EventType> ev_lost; 150 std::shared_ptr<EventType> ev_lost;
149 Common::Event event{};
150 Common::Event pause_event{};
151 std::mutex basic_lock;
152 std::mutex advance_lock;
153 std::unique_ptr<std::thread> timer_thread;
154 std::atomic<bool> paused{};
155 std::atomic<bool> paused_set{};
156 std::atomic<bool> wait_set{};
157 std::atomic<bool> shutting_down{};
158 std::atomic<bool> has_started{}; 151 std::atomic<bool> has_started{};
159 std::function<void()> on_thread_init{}; 152 std::function<void()> on_thread_init{};
160 153
154 std::vector<std::thread> worker_threads;
155
156 std::condition_variable event_cv;
157 std::condition_variable wait_pause_cv;
158 std::condition_variable wait_signal_cv;
159 mutable std::mutex event_mutex;
160 mutable std::mutex sequence_mutex;
161
162 std::atomic<bool> paused_state{};
163 bool is_paused{};
164 bool shutting_down{};
161 bool is_multicore{}; 165 bool is_multicore{};
166 size_t pause_count{};
162 167
163 /// Cycle timing 168 /// Cycle timing
164 u64 ticks{}; 169 u64 ticks{};
diff --git a/src/core/cpu_manager.cpp b/src/core/cpu_manager.cpp
index d69b2602a..37d3d83b9 100644
--- a/src/core/cpu_manager.cpp
+++ b/src/core/cpu_manager.cpp
@@ -41,51 +41,32 @@ void CpuManager::Shutdown() {
41 } 41 }
42} 42}
43 43
44std::function<void(void*)> CpuManager::GetGuestThreadStartFunc() { 44void CpuManager::GuestThreadFunction() {
45 return GuestThreadFunction; 45 if (is_multicore) {
46} 46 MultiCoreRunGuestThread();
47
48std::function<void(void*)> CpuManager::GetIdleThreadStartFunc() {
49 return IdleThreadFunction;
50}
51
52std::function<void(void*)> CpuManager::GetShutdownThreadStartFunc() {
53 return ShutdownThreadFunction;
54}
55
56void CpuManager::GuestThreadFunction(void* cpu_manager_) {
57 CpuManager* cpu_manager = static_cast<CpuManager*>(cpu_manager_);
58 if (cpu_manager->is_multicore) {
59 cpu_manager->MultiCoreRunGuestThread();
60 } else { 47 } else {
61 cpu_manager->SingleCoreRunGuestThread(); 48 SingleCoreRunGuestThread();
62 } 49 }
63} 50}
64 51
65void CpuManager::GuestRewindFunction(void* cpu_manager_) { 52void CpuManager::GuestRewindFunction() {
66 CpuManager* cpu_manager = static_cast<CpuManager*>(cpu_manager_); 53 if (is_multicore) {
67 if (cpu_manager->is_multicore) { 54 MultiCoreRunGuestLoop();
68 cpu_manager->MultiCoreRunGuestLoop();
69 } else { 55 } else {
70 cpu_manager->SingleCoreRunGuestLoop(); 56 SingleCoreRunGuestLoop();
71 } 57 }
72} 58}
73 59
74void CpuManager::IdleThreadFunction(void* cpu_manager_) { 60void CpuManager::IdleThreadFunction() {
75 CpuManager* cpu_manager = static_cast<CpuManager*>(cpu_manager_); 61 if (is_multicore) {
76 if (cpu_manager->is_multicore) { 62 MultiCoreRunIdleThread();
77 cpu_manager->MultiCoreRunIdleThread();
78 } else { 63 } else {
79 cpu_manager->SingleCoreRunIdleThread(); 64 SingleCoreRunIdleThread();
80 } 65 }
81} 66}
82 67
83void CpuManager::ShutdownThreadFunction(void* cpu_manager) { 68void CpuManager::ShutdownThreadFunction() {
84 static_cast<CpuManager*>(cpu_manager)->ShutdownThread(); 69 ShutdownThread();
85}
86
87void* CpuManager::GetStartFuncParameter() {
88 return this;
89} 70}
90 71
91/////////////////////////////////////////////////////////////////////////////// 72///////////////////////////////////////////////////////////////////////////////
@@ -95,9 +76,9 @@ void* CpuManager::GetStartFuncParameter() {
95void CpuManager::MultiCoreRunGuestThread() { 76void CpuManager::MultiCoreRunGuestThread() {
96 auto& kernel = system.Kernel(); 77 auto& kernel = system.Kernel();
97 kernel.CurrentScheduler()->OnThreadStart(); 78 kernel.CurrentScheduler()->OnThreadStart();
98 auto* thread = kernel.CurrentScheduler()->GetCurrentThread(); 79 auto* thread = kernel.CurrentScheduler()->GetSchedulerCurrentThread();
99 auto& host_context = thread->GetHostContext(); 80 auto& host_context = thread->GetHostContext();
100 host_context->SetRewindPoint(GuestRewindFunction, this); 81 host_context->SetRewindPoint([this] { GuestRewindFunction(); });
101 MultiCoreRunGuestLoop(); 82 MultiCoreRunGuestLoop();
102} 83}
103 84
@@ -132,9 +113,9 @@ void CpuManager::MultiCoreRunIdleThread() {
132void CpuManager::SingleCoreRunGuestThread() { 113void CpuManager::SingleCoreRunGuestThread() {
133 auto& kernel = system.Kernel(); 114 auto& kernel = system.Kernel();
134 kernel.CurrentScheduler()->OnThreadStart(); 115 kernel.CurrentScheduler()->OnThreadStart();
135 auto* thread = kernel.CurrentScheduler()->GetCurrentThread(); 116 auto* thread = kernel.CurrentScheduler()->GetSchedulerCurrentThread();
136 auto& host_context = thread->GetHostContext(); 117 auto& host_context = thread->GetHostContext();
137 host_context->SetRewindPoint(GuestRewindFunction, this); 118 host_context->SetRewindPoint([this] { GuestRewindFunction(); });
138 SingleCoreRunGuestLoop(); 119 SingleCoreRunGuestLoop();
139} 120}
140 121
@@ -172,7 +153,7 @@ void CpuManager::PreemptSingleCore(bool from_running_enviroment) {
172 { 153 {
173 auto& kernel = system.Kernel(); 154 auto& kernel = system.Kernel();
174 auto& scheduler = kernel.Scheduler(current_core); 155 auto& scheduler = kernel.Scheduler(current_core);
175 Kernel::KThread* current_thread = scheduler.GetCurrentThread(); 156 Kernel::KThread* current_thread = scheduler.GetSchedulerCurrentThread();
176 if (idle_count >= 4 || from_running_enviroment) { 157 if (idle_count >= 4 || from_running_enviroment) {
177 if (!from_running_enviroment) { 158 if (!from_running_enviroment) {
178 system.CoreTiming().Idle(); 159 system.CoreTiming().Idle();
@@ -184,7 +165,7 @@ void CpuManager::PreemptSingleCore(bool from_running_enviroment) {
184 } 165 }
185 current_core.store((current_core + 1) % Core::Hardware::NUM_CPU_CORES); 166 current_core.store((current_core + 1) % Core::Hardware::NUM_CPU_CORES);
186 system.CoreTiming().ResetTicks(); 167 system.CoreTiming().ResetTicks();
187 scheduler.Unload(scheduler.GetCurrentThread()); 168 scheduler.Unload(scheduler.GetSchedulerCurrentThread());
188 169
189 auto& next_scheduler = kernel.Scheduler(current_core); 170 auto& next_scheduler = kernel.Scheduler(current_core);
190 Common::Fiber::YieldTo(current_thread->GetHostContext(), *next_scheduler.ControlContext()); 171 Common::Fiber::YieldTo(current_thread->GetHostContext(), *next_scheduler.ControlContext());
@@ -193,7 +174,7 @@ void CpuManager::PreemptSingleCore(bool from_running_enviroment) {
193 // May have changed scheduler 174 // May have changed scheduler
194 { 175 {
195 auto& scheduler = system.Kernel().Scheduler(current_core); 176 auto& scheduler = system.Kernel().Scheduler(current_core);
196 scheduler.Reload(scheduler.GetCurrentThread()); 177 scheduler.Reload(scheduler.GetSchedulerCurrentThread());
197 if (!scheduler.IsIdle()) { 178 if (!scheduler.IsIdle()) {
198 idle_count = 0; 179 idle_count = 0;
199 } 180 }
@@ -237,7 +218,8 @@ void CpuManager::RunThread(std::size_t core) {
237 system.GPU().ObtainContext(); 218 system.GPU().ObtainContext();
238 } 219 }
239 220
240 auto current_thread = system.Kernel().CurrentScheduler()->GetCurrentThread(); 221 auto* current_thread = system.Kernel().CurrentScheduler()->GetIdleThread();
222 Kernel::SetCurrentThread(system.Kernel(), current_thread);
241 Common::Fiber::YieldTo(data.host_context, *current_thread->GetHostContext()); 223 Common::Fiber::YieldTo(data.host_context, *current_thread->GetHostContext());
242} 224}
243 225
diff --git a/src/core/cpu_manager.h b/src/core/cpu_manager.h
index f0751fc58..76dc58ee1 100644
--- a/src/core/cpu_manager.h
+++ b/src/core/cpu_manager.h
@@ -50,10 +50,15 @@ public:
50 void Initialize(); 50 void Initialize();
51 void Shutdown(); 51 void Shutdown();
52 52
53 static std::function<void(void*)> GetGuestThreadStartFunc(); 53 std::function<void()> GetGuestThreadStartFunc() {
54 static std::function<void(void*)> GetIdleThreadStartFunc(); 54 return [this] { GuestThreadFunction(); };
55 static std::function<void(void*)> GetShutdownThreadStartFunc(); 55 }
56 void* GetStartFuncParameter(); 56 std::function<void()> GetIdleThreadStartFunc() {
57 return [this] { IdleThreadFunction(); };
58 }
59 std::function<void()> GetShutdownThreadStartFunc() {
60 return [this] { ShutdownThreadFunction(); };
61 }
57 62
58 void PreemptSingleCore(bool from_running_enviroment = true); 63 void PreemptSingleCore(bool from_running_enviroment = true);
59 64
@@ -62,10 +67,10 @@ public:
62 } 67 }
63 68
64private: 69private:
65 static void GuestThreadFunction(void* cpu_manager); 70 void GuestThreadFunction();
66 static void GuestRewindFunction(void* cpu_manager); 71 void GuestRewindFunction();
67 static void IdleThreadFunction(void* cpu_manager); 72 void IdleThreadFunction();
68 static void ShutdownThreadFunction(void* cpu_manager); 73 void ShutdownThreadFunction();
69 74
70 void MultiCoreRunGuestThread(); 75 void MultiCoreRunGuestThread();
71 void MultiCoreRunGuestLoop(); 76 void MultiCoreRunGuestLoop();
diff --git a/src/core/debugger/gdbstub.cpp b/src/core/debugger/gdbstub.cpp
index f5e9a303d..884229c77 100644
--- a/src/core/debugger/gdbstub.cpp
+++ b/src/core/debugger/gdbstub.cpp
@@ -252,6 +252,7 @@ void GDBStub::ExecuteCommand(std::string_view packet, std::vector<DebuggerAction
252 const auto sep{std::find(command.begin(), command.end(), '=') - command.begin() + 1}; 252 const auto sep{std::find(command.begin(), command.end(), '=') - command.begin() + 1};
253 const size_t reg{static_cast<size_t>(strtoll(command.data(), nullptr, 16))}; 253 const size_t reg{static_cast<size_t>(strtoll(command.data(), nullptr, 16))};
254 arch->RegWrite(backend.GetActiveThread(), reg, std::string_view(command).substr(sep)); 254 arch->RegWrite(backend.GetActiveThread(), reg, std::string_view(command).substr(sep));
255 SendReply(GDB_STUB_REPLY_OK);
255 break; 256 break;
256 } 257 }
257 case 'm': { 258 case 'm': {
diff --git a/src/core/debugger/gdbstub_arch.cpp b/src/core/debugger/gdbstub_arch.cpp
index 750c353b9..4bef09bd7 100644
--- a/src/core/debugger/gdbstub_arch.cpp
+++ b/src/core/debugger/gdbstub_arch.cpp
@@ -191,8 +191,10 @@ std::string GDBStubA64::RegRead(const Kernel::KThread* thread, size_t id) const
191 const auto& gprs{context.cpu_registers}; 191 const auto& gprs{context.cpu_registers};
192 const auto& fprs{context.vector_registers}; 192 const auto& fprs{context.vector_registers};
193 193
194 if (id <= SP_REGISTER) { 194 if (id < SP_REGISTER) {
195 return ValueToHex(gprs[id]); 195 return ValueToHex(gprs[id]);
196 } else if (id == SP_REGISTER) {
197 return ValueToHex(context.sp);
196 } else if (id == PC_REGISTER) { 198 } else if (id == PC_REGISTER) {
197 return ValueToHex(context.pc); 199 return ValueToHex(context.pc);
198 } else if (id == PSTATE_REGISTER) { 200 } else if (id == PSTATE_REGISTER) {
@@ -215,8 +217,10 @@ void GDBStubA64::RegWrite(Kernel::KThread* thread, size_t id, std::string_view v
215 217
216 auto& context{thread->GetContext64()}; 218 auto& context{thread->GetContext64()};
217 219
218 if (id <= SP_REGISTER) { 220 if (id < SP_REGISTER) {
219 context.cpu_registers[id] = HexToValue<u64>(value); 221 context.cpu_registers[id] = HexToValue<u64>(value);
222 } else if (id == SP_REGISTER) {
223 context.sp = HexToValue<u64>(value);
220 } else if (id == PC_REGISTER) { 224 } else if (id == PC_REGISTER) {
221 context.pc = HexToValue<u64>(value); 225 context.pc = HexToValue<u64>(value);
222 } else if (id == PSTATE_REGISTER) { 226 } else if (id == PSTATE_REGISTER) {
diff --git a/src/core/file_sys/errors.h b/src/core/file_sys/errors.h
index 1a920b45d..ff15b3e23 100644
--- a/src/core/file_sys/errors.h
+++ b/src/core/file_sys/errors.h
@@ -8,14 +8,14 @@
8 8
9namespace FileSys { 9namespace FileSys {
10 10
11constexpr ResultCode ERROR_PATH_NOT_FOUND{ErrorModule::FS, 1}; 11constexpr Result ERROR_PATH_NOT_FOUND{ErrorModule::FS, 1};
12constexpr ResultCode ERROR_PATH_ALREADY_EXISTS{ErrorModule::FS, 2}; 12constexpr Result ERROR_PATH_ALREADY_EXISTS{ErrorModule::FS, 2};
13constexpr ResultCode ERROR_ENTITY_NOT_FOUND{ErrorModule::FS, 1002}; 13constexpr Result ERROR_ENTITY_NOT_FOUND{ErrorModule::FS, 1002};
14constexpr ResultCode ERROR_SD_CARD_NOT_FOUND{ErrorModule::FS, 2001}; 14constexpr Result ERROR_SD_CARD_NOT_FOUND{ErrorModule::FS, 2001};
15constexpr ResultCode ERROR_OUT_OF_BOUNDS{ErrorModule::FS, 3005}; 15constexpr Result ERROR_OUT_OF_BOUNDS{ErrorModule::FS, 3005};
16constexpr ResultCode ERROR_FAILED_MOUNT_ARCHIVE{ErrorModule::FS, 3223}; 16constexpr Result ERROR_FAILED_MOUNT_ARCHIVE{ErrorModule::FS, 3223};
17constexpr ResultCode ERROR_INVALID_ARGUMENT{ErrorModule::FS, 6001}; 17constexpr Result ERROR_INVALID_ARGUMENT{ErrorModule::FS, 6001};
18constexpr ResultCode ERROR_INVALID_OFFSET{ErrorModule::FS, 6061}; 18constexpr Result ERROR_INVALID_OFFSET{ErrorModule::FS, 6061};
19constexpr ResultCode ERROR_INVALID_SIZE{ErrorModule::FS, 6062}; 19constexpr Result ERROR_INVALID_SIZE{ErrorModule::FS, 6062};
20 20
21} // namespace FileSys 21} // namespace FileSys
diff --git a/src/core/frontend/applets/error.cpp b/src/core/frontend/applets/error.cpp
index f2ec4b10e..f8b961098 100644
--- a/src/core/frontend/applets/error.cpp
+++ b/src/core/frontend/applets/error.cpp
@@ -8,12 +8,12 @@ namespace Core::Frontend {
8 8
9ErrorApplet::~ErrorApplet() = default; 9ErrorApplet::~ErrorApplet() = default;
10 10
11void DefaultErrorApplet::ShowError(ResultCode error, std::function<void()> finished) const { 11void DefaultErrorApplet::ShowError(Result error, std::function<void()> finished) const {
12 LOG_CRITICAL(Service_Fatal, "Application requested error display: {:04}-{:04} (raw={:08X})", 12 LOG_CRITICAL(Service_Fatal, "Application requested error display: {:04}-{:04} (raw={:08X})",
13 error.module.Value(), error.description.Value(), error.raw); 13 error.module.Value(), error.description.Value(), error.raw);
14} 14}
15 15
16void DefaultErrorApplet::ShowErrorWithTimestamp(ResultCode error, std::chrono::seconds time, 16void DefaultErrorApplet::ShowErrorWithTimestamp(Result error, std::chrono::seconds time,
17 std::function<void()> finished) const { 17 std::function<void()> finished) const {
18 LOG_CRITICAL( 18 LOG_CRITICAL(
19 Service_Fatal, 19 Service_Fatal,
@@ -21,7 +21,7 @@ void DefaultErrorApplet::ShowErrorWithTimestamp(ResultCode error, std::chrono::s
21 error.module.Value(), error.description.Value(), error.raw, time.count()); 21 error.module.Value(), error.description.Value(), error.raw, time.count());
22} 22}
23 23
24void DefaultErrorApplet::ShowCustomErrorText(ResultCode error, std::string main_text, 24void DefaultErrorApplet::ShowCustomErrorText(Result error, std::string main_text,
25 std::string detail_text, 25 std::string detail_text,
26 std::function<void()> finished) const { 26 std::function<void()> finished) const {
27 LOG_CRITICAL(Service_Fatal, 27 LOG_CRITICAL(Service_Fatal,
diff --git a/src/core/frontend/applets/error.h b/src/core/frontend/applets/error.h
index 8a1134561..f378f8805 100644
--- a/src/core/frontend/applets/error.h
+++ b/src/core/frontend/applets/error.h
@@ -14,22 +14,22 @@ class ErrorApplet {
14public: 14public:
15 virtual ~ErrorApplet(); 15 virtual ~ErrorApplet();
16 16
17 virtual void ShowError(ResultCode error, std::function<void()> finished) const = 0; 17 virtual void ShowError(Result error, std::function<void()> finished) const = 0;
18 18
19 virtual void ShowErrorWithTimestamp(ResultCode error, std::chrono::seconds time, 19 virtual void ShowErrorWithTimestamp(Result error, std::chrono::seconds time,
20 std::function<void()> finished) const = 0; 20 std::function<void()> finished) const = 0;
21 21
22 virtual void ShowCustomErrorText(ResultCode error, std::string dialog_text, 22 virtual void ShowCustomErrorText(Result error, std::string dialog_text,
23 std::string fullscreen_text, 23 std::string fullscreen_text,
24 std::function<void()> finished) const = 0; 24 std::function<void()> finished) const = 0;
25}; 25};
26 26
27class DefaultErrorApplet final : public ErrorApplet { 27class DefaultErrorApplet final : public ErrorApplet {
28public: 28public:
29 void ShowError(ResultCode error, std::function<void()> finished) const override; 29 void ShowError(Result error, std::function<void()> finished) const override;
30 void ShowErrorWithTimestamp(ResultCode error, std::chrono::seconds time, 30 void ShowErrorWithTimestamp(Result error, std::chrono::seconds time,
31 std::function<void()> finished) const override; 31 std::function<void()> finished) const override;
32 void ShowCustomErrorText(ResultCode error, std::string main_text, std::string detail_text, 32 void ShowCustomErrorText(Result error, std::string main_text, std::string detail_text,
33 std::function<void()> finished) const override; 33 std::function<void()> finished) const override;
34}; 34};
35 35
diff --git a/src/core/hid/hid_types.h b/src/core/hid/hid_types.h
index 9f76f9bcb..e49223016 100644
--- a/src/core/hid/hid_types.h
+++ b/src/core/hid/hid_types.h
@@ -272,6 +272,7 @@ enum class VibrationDeviceType : u32 {
272 Unknown = 0, 272 Unknown = 0,
273 LinearResonantActuator = 1, 273 LinearResonantActuator = 1,
274 GcErm = 2, 274 GcErm = 2,
275 N64 = 3,
275}; 276};
276 277
277// This is nn::hid::VibrationGcErmCommand 278// This is nn::hid::VibrationGcErmCommand
diff --git a/src/core/hle/ipc_helpers.h b/src/core/hle/ipc_helpers.h
index 3c4e45fcd..004bb2005 100644
--- a/src/core/hle/ipc_helpers.h
+++ b/src/core/hle/ipc_helpers.h
@@ -19,7 +19,7 @@
19 19
20namespace IPC { 20namespace IPC {
21 21
22constexpr ResultCode ERR_REMOTE_PROCESS_DEAD{ErrorModule::HIPC, 301}; 22constexpr Result ERR_REMOTE_PROCESS_DEAD{ErrorModule::HIPC, 301};
23 23
24class RequestHelperBase { 24class RequestHelperBase {
25protected: 25protected:
@@ -176,7 +176,7 @@ public:
176 void PushImpl(float value); 176 void PushImpl(float value);
177 void PushImpl(double value); 177 void PushImpl(double value);
178 void PushImpl(bool value); 178 void PushImpl(bool value);
179 void PushImpl(ResultCode value); 179 void PushImpl(Result value);
180 180
181 template <typename T> 181 template <typename T>
182 void Push(T value) { 182 void Push(T value) {
@@ -251,7 +251,7 @@ void ResponseBuilder::PushRaw(const T& value) {
251 index += (sizeof(T) + 3) / 4; // round up to word length 251 index += (sizeof(T) + 3) / 4; // round up to word length
252} 252}
253 253
254inline void ResponseBuilder::PushImpl(ResultCode value) { 254inline void ResponseBuilder::PushImpl(Result value) {
255 // Result codes are actually 64-bit in the IPC buffer, but only the high part is discarded. 255 // Result codes are actually 64-bit in the IPC buffer, but only the high part is discarded.
256 Push(value.raw); 256 Push(value.raw);
257 Push<u32>(0); 257 Push<u32>(0);
@@ -481,8 +481,8 @@ inline bool RequestParser::Pop() {
481} 481}
482 482
483template <> 483template <>
484inline ResultCode RequestParser::Pop() { 484inline Result RequestParser::Pop() {
485 return ResultCode{Pop<u32>()}; 485 return Result{Pop<u32>()};
486} 486}
487 487
488template <typename T> 488template <typename T>
diff --git a/src/core/hle/kernel/hle_ipc.cpp b/src/core/hle/kernel/hle_ipc.cpp
index 4650d25b0..45135a07f 100644
--- a/src/core/hle/kernel/hle_ipc.cpp
+++ b/src/core/hle/kernel/hle_ipc.cpp
@@ -188,8 +188,8 @@ void HLERequestContext::ParseCommandBuffer(const KHandleTable& handle_table, u32
188 rp.Skip(1, false); // The command is actually an u64, but we don't use the high part. 188 rp.Skip(1, false); // The command is actually an u64, but we don't use the high part.
189} 189}
190 190
191ResultCode HLERequestContext::PopulateFromIncomingCommandBuffer(const KHandleTable& handle_table, 191Result HLERequestContext::PopulateFromIncomingCommandBuffer(const KHandleTable& handle_table,
192 u32_le* src_cmdbuf) { 192 u32_le* src_cmdbuf) {
193 ParseCommandBuffer(handle_table, src_cmdbuf, true); 193 ParseCommandBuffer(handle_table, src_cmdbuf, true);
194 194
195 if (command_header->IsCloseCommand()) { 195 if (command_header->IsCloseCommand()) {
@@ -202,7 +202,7 @@ ResultCode HLERequestContext::PopulateFromIncomingCommandBuffer(const KHandleTab
202 return ResultSuccess; 202 return ResultSuccess;
203} 203}
204 204
205ResultCode HLERequestContext::WriteToOutgoingCommandBuffer(KThread& requesting_thread) { 205Result HLERequestContext::WriteToOutgoingCommandBuffer(KThread& requesting_thread) {
206 auto current_offset = handles_offset; 206 auto current_offset = handles_offset;
207 auto& owner_process = *requesting_thread.GetOwnerProcess(); 207 auto& owner_process = *requesting_thread.GetOwnerProcess();
208 auto& handle_table = owner_process.GetHandleTable(); 208 auto& handle_table = owner_process.GetHandleTable();
diff --git a/src/core/hle/kernel/hle_ipc.h b/src/core/hle/kernel/hle_ipc.h
index 0ddc8df9e..d3abeee85 100644
--- a/src/core/hle/kernel/hle_ipc.h
+++ b/src/core/hle/kernel/hle_ipc.h
@@ -18,7 +18,7 @@
18#include "core/hle/ipc.h" 18#include "core/hle/ipc.h"
19#include "core/hle/kernel/svc_common.h" 19#include "core/hle/kernel/svc_common.h"
20 20
21union ResultCode; 21union Result;
22 22
23namespace Core::Memory { 23namespace Core::Memory {
24class Memory; 24class Memory;
@@ -71,10 +71,10 @@ public:
71 * it should be used to differentiate which client (As in ClientSession) we're answering to. 71 * it should be used to differentiate which client (As in ClientSession) we're answering to.
72 * TODO(Subv): Use a wrapper structure to hold all the information relevant to 72 * TODO(Subv): Use a wrapper structure to hold all the information relevant to
73 * this request (ServerSession, Originator thread, Translated command buffer, etc). 73 * this request (ServerSession, Originator thread, Translated command buffer, etc).
74 * @returns ResultCode the result code of the translate operation. 74 * @returns Result the result code of the translate operation.
75 */ 75 */
76 virtual ResultCode HandleSyncRequest(Kernel::KServerSession& session, 76 virtual Result HandleSyncRequest(Kernel::KServerSession& session,
77 Kernel::HLERequestContext& context) = 0; 77 Kernel::HLERequestContext& context) = 0;
78 78
79 /** 79 /**
80 * Signals that a client has just connected to this HLE handler and keeps the 80 * Signals that a client has just connected to this HLE handler and keeps the
@@ -212,11 +212,10 @@ public:
212 } 212 }
213 213
214 /// Populates this context with data from the requesting process/thread. 214 /// Populates this context with data from the requesting process/thread.
215 ResultCode PopulateFromIncomingCommandBuffer(const KHandleTable& handle_table, 215 Result PopulateFromIncomingCommandBuffer(const KHandleTable& handle_table, u32_le* src_cmdbuf);
216 u32_le* src_cmdbuf);
217 216
218 /// Writes data from this context back to the requesting process/thread. 217 /// Writes data from this context back to the requesting process/thread.
219 ResultCode WriteToOutgoingCommandBuffer(KThread& requesting_thread); 218 Result WriteToOutgoingCommandBuffer(KThread& requesting_thread);
220 219
221 u32_le GetHipcCommand() const { 220 u32_le GetHipcCommand() const {
222 return command; 221 return command;
diff --git a/src/core/hle/kernel/k_address_arbiter.cpp b/src/core/hle/kernel/k_address_arbiter.cpp
index 04cf86d52..f85b11557 100644
--- a/src/core/hle/kernel/k_address_arbiter.cpp
+++ b/src/core/hle/kernel/k_address_arbiter.cpp
@@ -90,8 +90,7 @@ public:
90 explicit ThreadQueueImplForKAddressArbiter(KernelCore& kernel_, KAddressArbiter::ThreadTree* t) 90 explicit ThreadQueueImplForKAddressArbiter(KernelCore& kernel_, KAddressArbiter::ThreadTree* t)
91 : KThreadQueue(kernel_), m_tree(t) {} 91 : KThreadQueue(kernel_), m_tree(t) {}
92 92
93 void CancelWait(KThread* waiting_thread, ResultCode wait_result, 93 void CancelWait(KThread* waiting_thread, Result wait_result, bool cancel_timer_task) override {
94 bool cancel_timer_task) override {
95 // If the thread is waiting on an address arbiter, remove it from the tree. 94 // If the thread is waiting on an address arbiter, remove it from the tree.
96 if (waiting_thread->IsWaitingForAddressArbiter()) { 95 if (waiting_thread->IsWaitingForAddressArbiter()) {
97 m_tree->erase(m_tree->iterator_to(*waiting_thread)); 96 m_tree->erase(m_tree->iterator_to(*waiting_thread));
@@ -108,7 +107,7 @@ private:
108 107
109} // namespace 108} // namespace
110 109
111ResultCode KAddressArbiter::Signal(VAddr addr, s32 count) { 110Result KAddressArbiter::Signal(VAddr addr, s32 count) {
112 // Perform signaling. 111 // Perform signaling.
113 s32 num_waiters{}; 112 s32 num_waiters{};
114 { 113 {
@@ -131,7 +130,7 @@ ResultCode KAddressArbiter::Signal(VAddr addr, s32 count) {
131 return ResultSuccess; 130 return ResultSuccess;
132} 131}
133 132
134ResultCode KAddressArbiter::SignalAndIncrementIfEqual(VAddr addr, s32 value, s32 count) { 133Result KAddressArbiter::SignalAndIncrementIfEqual(VAddr addr, s32 value, s32 count) {
135 // Perform signaling. 134 // Perform signaling.
136 s32 num_waiters{}; 135 s32 num_waiters{};
137 { 136 {
@@ -164,7 +163,7 @@ ResultCode KAddressArbiter::SignalAndIncrementIfEqual(VAddr addr, s32 value, s32
164 return ResultSuccess; 163 return ResultSuccess;
165} 164}
166 165
167ResultCode KAddressArbiter::SignalAndModifyByWaitingCountIfEqual(VAddr addr, s32 value, s32 count) { 166Result KAddressArbiter::SignalAndModifyByWaitingCountIfEqual(VAddr addr, s32 value, s32 count) {
168 // Perform signaling. 167 // Perform signaling.
169 s32 num_waiters{}; 168 s32 num_waiters{};
170 { 169 {
@@ -232,9 +231,9 @@ ResultCode KAddressArbiter::SignalAndModifyByWaitingCountIfEqual(VAddr addr, s32
232 return ResultSuccess; 231 return ResultSuccess;
233} 232}
234 233
235ResultCode KAddressArbiter::WaitIfLessThan(VAddr addr, s32 value, bool decrement, s64 timeout) { 234Result KAddressArbiter::WaitIfLessThan(VAddr addr, s32 value, bool decrement, s64 timeout) {
236 // Prepare to wait. 235 // Prepare to wait.
237 KThread* cur_thread = kernel.CurrentScheduler()->GetCurrentThread(); 236 KThread* cur_thread = GetCurrentThreadPointer(kernel);
238 ThreadQueueImplForKAddressArbiter wait_queue(kernel, std::addressof(thread_tree)); 237 ThreadQueueImplForKAddressArbiter wait_queue(kernel, std::addressof(thread_tree));
239 238
240 { 239 {
@@ -285,9 +284,9 @@ ResultCode KAddressArbiter::WaitIfLessThan(VAddr addr, s32 value, bool decrement
285 return cur_thread->GetWaitResult(); 284 return cur_thread->GetWaitResult();
286} 285}
287 286
288ResultCode KAddressArbiter::WaitIfEqual(VAddr addr, s32 value, s64 timeout) { 287Result KAddressArbiter::WaitIfEqual(VAddr addr, s32 value, s64 timeout) {
289 // Prepare to wait. 288 // Prepare to wait.
290 KThread* cur_thread = kernel.CurrentScheduler()->GetCurrentThread(); 289 KThread* cur_thread = GetCurrentThreadPointer(kernel);
291 ThreadQueueImplForKAddressArbiter wait_queue(kernel, std::addressof(thread_tree)); 290 ThreadQueueImplForKAddressArbiter wait_queue(kernel, std::addressof(thread_tree));
292 291
293 { 292 {
diff --git a/src/core/hle/kernel/k_address_arbiter.h b/src/core/hle/kernel/k_address_arbiter.h
index 5fa19d386..e4085ae22 100644
--- a/src/core/hle/kernel/k_address_arbiter.h
+++ b/src/core/hle/kernel/k_address_arbiter.h
@@ -8,7 +8,7 @@
8#include "core/hle/kernel/k_condition_variable.h" 8#include "core/hle/kernel/k_condition_variable.h"
9#include "core/hle/kernel/svc_types.h" 9#include "core/hle/kernel/svc_types.h"
10 10
11union ResultCode; 11union Result;
12 12
13namespace Core { 13namespace Core {
14class System; 14class System;
@@ -25,8 +25,7 @@ public:
25 explicit KAddressArbiter(Core::System& system_); 25 explicit KAddressArbiter(Core::System& system_);
26 ~KAddressArbiter(); 26 ~KAddressArbiter();
27 27
28 [[nodiscard]] ResultCode SignalToAddress(VAddr addr, Svc::SignalType type, s32 value, 28 [[nodiscard]] Result SignalToAddress(VAddr addr, Svc::SignalType type, s32 value, s32 count) {
29 s32 count) {
30 switch (type) { 29 switch (type) {
31 case Svc::SignalType::Signal: 30 case Svc::SignalType::Signal:
32 return Signal(addr, count); 31 return Signal(addr, count);
@@ -39,8 +38,8 @@ public:
39 return ResultUnknown; 38 return ResultUnknown;
40 } 39 }
41 40
42 [[nodiscard]] ResultCode WaitForAddress(VAddr addr, Svc::ArbitrationType type, s32 value, 41 [[nodiscard]] Result WaitForAddress(VAddr addr, Svc::ArbitrationType type, s32 value,
43 s64 timeout) { 42 s64 timeout) {
44 switch (type) { 43 switch (type) {
45 case Svc::ArbitrationType::WaitIfLessThan: 44 case Svc::ArbitrationType::WaitIfLessThan:
46 return WaitIfLessThan(addr, value, false, timeout); 45 return WaitIfLessThan(addr, value, false, timeout);
@@ -54,11 +53,11 @@ public:
54 } 53 }
55 54
56private: 55private:
57 [[nodiscard]] ResultCode Signal(VAddr addr, s32 count); 56 [[nodiscard]] Result Signal(VAddr addr, s32 count);
58 [[nodiscard]] ResultCode SignalAndIncrementIfEqual(VAddr addr, s32 value, s32 count); 57 [[nodiscard]] Result SignalAndIncrementIfEqual(VAddr addr, s32 value, s32 count);
59 [[nodiscard]] ResultCode SignalAndModifyByWaitingCountIfEqual(VAddr addr, s32 value, s32 count); 58 [[nodiscard]] Result SignalAndModifyByWaitingCountIfEqual(VAddr addr, s32 value, s32 count);
60 [[nodiscard]] ResultCode WaitIfLessThan(VAddr addr, s32 value, bool decrement, s64 timeout); 59 [[nodiscard]] Result WaitIfLessThan(VAddr addr, s32 value, bool decrement, s64 timeout);
61 [[nodiscard]] ResultCode WaitIfEqual(VAddr addr, s32 value, s64 timeout); 60 [[nodiscard]] Result WaitIfEqual(VAddr addr, s32 value, s64 timeout);
62 61
63 ThreadTree thread_tree; 62 ThreadTree thread_tree;
64 63
diff --git a/src/core/hle/kernel/k_client_port.cpp b/src/core/hle/kernel/k_client_port.cpp
index ef168fe87..d63e77d15 100644
--- a/src/core/hle/kernel/k_client_port.cpp
+++ b/src/core/hle/kernel/k_client_port.cpp
@@ -59,8 +59,8 @@ bool KClientPort::IsSignaled() const {
59 return num_sessions < max_sessions; 59 return num_sessions < max_sessions;
60} 60}
61 61
62ResultCode KClientPort::CreateSession(KClientSession** out, 62Result KClientPort::CreateSession(KClientSession** out,
63 std::shared_ptr<SessionRequestManager> session_manager) { 63 std::shared_ptr<SessionRequestManager> session_manager) {
64 // Reserve a new session from the resource limit. 64 // Reserve a new session from the resource limit.
65 KScopedResourceReservation session_reservation(kernel.CurrentProcess()->GetResourceLimit(), 65 KScopedResourceReservation session_reservation(kernel.CurrentProcess()->GetResourceLimit(),
66 LimitableResource::Sessions); 66 LimitableResource::Sessions);
diff --git a/src/core/hle/kernel/k_client_port.h b/src/core/hle/kernel/k_client_port.h
index 54bb05e20..ef8583efc 100644
--- a/src/core/hle/kernel/k_client_port.h
+++ b/src/core/hle/kernel/k_client_port.h
@@ -53,8 +53,8 @@ public:
53 void Destroy() override; 53 void Destroy() override;
54 bool IsSignaled() const override; 54 bool IsSignaled() const override;
55 55
56 ResultCode CreateSession(KClientSession** out, 56 Result CreateSession(KClientSession** out,
57 std::shared_ptr<SessionRequestManager> session_manager = nullptr); 57 std::shared_ptr<SessionRequestManager> session_manager = nullptr);
58 58
59private: 59private:
60 std::atomic<s32> num_sessions{}; 60 std::atomic<s32> num_sessions{};
diff --git a/src/core/hle/kernel/k_client_session.cpp b/src/core/hle/kernel/k_client_session.cpp
index 731af079c..b2a887b14 100644
--- a/src/core/hle/kernel/k_client_session.cpp
+++ b/src/core/hle/kernel/k_client_session.cpp
@@ -21,8 +21,8 @@ void KClientSession::Destroy() {
21 21
22void KClientSession::OnServerClosed() {} 22void KClientSession::OnServerClosed() {}
23 23
24ResultCode KClientSession::SendSyncRequest(KThread* thread, Core::Memory::Memory& memory, 24Result KClientSession::SendSyncRequest(KThread* thread, Core::Memory::Memory& memory,
25 Core::Timing::CoreTiming& core_timing) { 25 Core::Timing::CoreTiming& core_timing) {
26 // Signal the server session that new data is available 26 // Signal the server session that new data is available
27 return parent->GetServerSession().HandleSyncRequest(thread, memory, core_timing); 27 return parent->GetServerSession().HandleSyncRequest(thread, memory, core_timing);
28} 28}
diff --git a/src/core/hle/kernel/k_client_session.h b/src/core/hle/kernel/k_client_session.h
index 7a7ec8450..0c750d756 100644
--- a/src/core/hle/kernel/k_client_session.h
+++ b/src/core/hle/kernel/k_client_session.h
@@ -9,7 +9,7 @@
9#include "core/hle/kernel/slab_helpers.h" 9#include "core/hle/kernel/slab_helpers.h"
10#include "core/hle/result.h" 10#include "core/hle/result.h"
11 11
12union ResultCode; 12union Result;
13 13
14namespace Core::Memory { 14namespace Core::Memory {
15class Memory; 15class Memory;
@@ -46,8 +46,8 @@ public:
46 return parent; 46 return parent;
47 } 47 }
48 48
49 ResultCode SendSyncRequest(KThread* thread, Core::Memory::Memory& memory, 49 Result SendSyncRequest(KThread* thread, Core::Memory::Memory& memory,
50 Core::Timing::CoreTiming& core_timing); 50 Core::Timing::CoreTiming& core_timing);
51 51
52 void OnServerClosed(); 52 void OnServerClosed();
53 53
diff --git a/src/core/hle/kernel/k_code_memory.cpp b/src/core/hle/kernel/k_code_memory.cpp
index 4ae40ec8e..da57ceb21 100644
--- a/src/core/hle/kernel/k_code_memory.cpp
+++ b/src/core/hle/kernel/k_code_memory.cpp
@@ -7,7 +7,7 @@
7#include "core/hle/kernel/k_code_memory.h" 7#include "core/hle/kernel/k_code_memory.h"
8#include "core/hle/kernel/k_light_lock.h" 8#include "core/hle/kernel/k_light_lock.h"
9#include "core/hle/kernel/k_memory_block.h" 9#include "core/hle/kernel/k_memory_block.h"
10#include "core/hle/kernel/k_page_linked_list.h" 10#include "core/hle/kernel/k_page_group.h"
11#include "core/hle/kernel/k_page_table.h" 11#include "core/hle/kernel/k_page_table.h"
12#include "core/hle/kernel/k_process.h" 12#include "core/hle/kernel/k_process.h"
13#include "core/hle/kernel/slab_helpers.h" 13#include "core/hle/kernel/slab_helpers.h"
@@ -19,7 +19,7 @@ namespace Kernel {
19KCodeMemory::KCodeMemory(KernelCore& kernel_) 19KCodeMemory::KCodeMemory(KernelCore& kernel_)
20 : KAutoObjectWithSlabHeapAndContainer{kernel_}, m_lock(kernel_) {} 20 : KAutoObjectWithSlabHeapAndContainer{kernel_}, m_lock(kernel_) {}
21 21
22ResultCode KCodeMemory::Initialize(Core::DeviceMemory& device_memory, VAddr addr, size_t size) { 22Result KCodeMemory::Initialize(Core::DeviceMemory& device_memory, VAddr addr, size_t size) {
23 // Set members. 23 // Set members.
24 m_owner = kernel.CurrentProcess(); 24 m_owner = kernel.CurrentProcess();
25 25
@@ -62,7 +62,7 @@ void KCodeMemory::Finalize() {
62 m_owner->Close(); 62 m_owner->Close();
63} 63}
64 64
65ResultCode KCodeMemory::Map(VAddr address, size_t size) { 65Result KCodeMemory::Map(VAddr address, size_t size) {
66 // Validate the size. 66 // Validate the size.
67 R_UNLESS(m_page_group.GetNumPages() == Common::DivideUp(size, PageSize), ResultInvalidSize); 67 R_UNLESS(m_page_group.GetNumPages() == Common::DivideUp(size, PageSize), ResultInvalidSize);
68 68
@@ -82,7 +82,7 @@ ResultCode KCodeMemory::Map(VAddr address, size_t size) {
82 return ResultSuccess; 82 return ResultSuccess;
83} 83}
84 84
85ResultCode KCodeMemory::Unmap(VAddr address, size_t size) { 85Result KCodeMemory::Unmap(VAddr address, size_t size) {
86 // Validate the size. 86 // Validate the size.
87 R_UNLESS(m_page_group.GetNumPages() == Common::DivideUp(size, PageSize), ResultInvalidSize); 87 R_UNLESS(m_page_group.GetNumPages() == Common::DivideUp(size, PageSize), ResultInvalidSize);
88 88
@@ -99,7 +99,7 @@ ResultCode KCodeMemory::Unmap(VAddr address, size_t size) {
99 return ResultSuccess; 99 return ResultSuccess;
100} 100}
101 101
102ResultCode KCodeMemory::MapToOwner(VAddr address, size_t size, Svc::MemoryPermission perm) { 102Result KCodeMemory::MapToOwner(VAddr address, size_t size, Svc::MemoryPermission perm) {
103 // Validate the size. 103 // Validate the size.
104 R_UNLESS(m_page_group.GetNumPages() == Common::DivideUp(size, PageSize), ResultInvalidSize); 104 R_UNLESS(m_page_group.GetNumPages() == Common::DivideUp(size, PageSize), ResultInvalidSize);
105 105
@@ -133,7 +133,7 @@ ResultCode KCodeMemory::MapToOwner(VAddr address, size_t size, Svc::MemoryPermis
133 return ResultSuccess; 133 return ResultSuccess;
134} 134}
135 135
136ResultCode KCodeMemory::UnmapFromOwner(VAddr address, size_t size) { 136Result KCodeMemory::UnmapFromOwner(VAddr address, size_t size) {
137 // Validate the size. 137 // Validate the size.
138 R_UNLESS(m_page_group.GetNumPages() == Common::DivideUp(size, PageSize), ResultInvalidSize); 138 R_UNLESS(m_page_group.GetNumPages() == Common::DivideUp(size, PageSize), ResultInvalidSize);
139 139
diff --git a/src/core/hle/kernel/k_code_memory.h b/src/core/hle/kernel/k_code_memory.h
index ab06b6f29..2410f74a3 100644
--- a/src/core/hle/kernel/k_code_memory.h
+++ b/src/core/hle/kernel/k_code_memory.h
@@ -7,7 +7,7 @@
7#include "core/device_memory.h" 7#include "core/device_memory.h"
8#include "core/hle/kernel/k_auto_object.h" 8#include "core/hle/kernel/k_auto_object.h"
9#include "core/hle/kernel/k_light_lock.h" 9#include "core/hle/kernel/k_light_lock.h"
10#include "core/hle/kernel/k_page_linked_list.h" 10#include "core/hle/kernel/k_page_group.h"
11#include "core/hle/kernel/k_process.h" 11#include "core/hle/kernel/k_process.h"
12#include "core/hle/kernel/slab_helpers.h" 12#include "core/hle/kernel/slab_helpers.h"
13#include "core/hle/kernel/svc_types.h" 13#include "core/hle/kernel/svc_types.h"
@@ -29,13 +29,13 @@ class KCodeMemory final
29public: 29public:
30 explicit KCodeMemory(KernelCore& kernel_); 30 explicit KCodeMemory(KernelCore& kernel_);
31 31
32 ResultCode Initialize(Core::DeviceMemory& device_memory, VAddr address, size_t size); 32 Result Initialize(Core::DeviceMemory& device_memory, VAddr address, size_t size);
33 void Finalize(); 33 void Finalize();
34 34
35 ResultCode Map(VAddr address, size_t size); 35 Result Map(VAddr address, size_t size);
36 ResultCode Unmap(VAddr address, size_t size); 36 Result Unmap(VAddr address, size_t size);
37 ResultCode MapToOwner(VAddr address, size_t size, Svc::MemoryPermission perm); 37 Result MapToOwner(VAddr address, size_t size, Svc::MemoryPermission perm);
38 ResultCode UnmapFromOwner(VAddr address, size_t size); 38 Result UnmapFromOwner(VAddr address, size_t size);
39 39
40 bool IsInitialized() const { 40 bool IsInitialized() const {
41 return m_is_initialized; 41 return m_is_initialized;
@@ -53,7 +53,7 @@ public:
53 } 53 }
54 54
55private: 55private:
56 KPageLinkedList m_page_group{}; 56 KPageGroup m_page_group{};
57 KProcess* m_owner{}; 57 KProcess* m_owner{};
58 VAddr m_address{}; 58 VAddr m_address{};
59 KLightLock m_lock; 59 KLightLock m_lock;
diff --git a/src/core/hle/kernel/k_condition_variable.cpp b/src/core/hle/kernel/k_condition_variable.cpp
index 43bcd253d..124149697 100644
--- a/src/core/hle/kernel/k_condition_variable.cpp
+++ b/src/core/hle/kernel/k_condition_variable.cpp
@@ -61,8 +61,7 @@ public:
61 explicit ThreadQueueImplForKConditionVariableWaitForAddress(KernelCore& kernel_) 61 explicit ThreadQueueImplForKConditionVariableWaitForAddress(KernelCore& kernel_)
62 : KThreadQueue(kernel_) {} 62 : KThreadQueue(kernel_) {}
63 63
64 void CancelWait(KThread* waiting_thread, ResultCode wait_result, 64 void CancelWait(KThread* waiting_thread, Result wait_result, bool cancel_timer_task) override {
65 bool cancel_timer_task) override {
66 // Remove the thread as a waiter from its owner. 65 // Remove the thread as a waiter from its owner.
67 waiting_thread->GetLockOwner()->RemoveWaiter(waiting_thread); 66 waiting_thread->GetLockOwner()->RemoveWaiter(waiting_thread);
68 67
@@ -80,8 +79,7 @@ public:
80 KernelCore& kernel_, KConditionVariable::ThreadTree* t) 79 KernelCore& kernel_, KConditionVariable::ThreadTree* t)
81 : KThreadQueue(kernel_), m_tree(t) {} 80 : KThreadQueue(kernel_), m_tree(t) {}
82 81
83 void CancelWait(KThread* waiting_thread, ResultCode wait_result, 82 void CancelWait(KThread* waiting_thread, Result wait_result, bool cancel_timer_task) override {
84 bool cancel_timer_task) override {
85 // Remove the thread as a waiter from its owner. 83 // Remove the thread as a waiter from its owner.
86 if (KThread* owner = waiting_thread->GetLockOwner(); owner != nullptr) { 84 if (KThread* owner = waiting_thread->GetLockOwner(); owner != nullptr) {
87 owner->RemoveWaiter(waiting_thread); 85 owner->RemoveWaiter(waiting_thread);
@@ -105,8 +103,8 @@ KConditionVariable::KConditionVariable(Core::System& system_)
105 103
106KConditionVariable::~KConditionVariable() = default; 104KConditionVariable::~KConditionVariable() = default;
107 105
108ResultCode KConditionVariable::SignalToAddress(VAddr addr) { 106Result KConditionVariable::SignalToAddress(VAddr addr) {
109 KThread* owner_thread = kernel.CurrentScheduler()->GetCurrentThread(); 107 KThread* owner_thread = GetCurrentThreadPointer(kernel);
110 108
111 // Signal the address. 109 // Signal the address.
112 { 110 {
@@ -126,7 +124,7 @@ ResultCode KConditionVariable::SignalToAddress(VAddr addr) {
126 } 124 }
127 125
128 // Write the value to userspace. 126 // Write the value to userspace.
129 ResultCode result{ResultSuccess}; 127 Result result{ResultSuccess};
130 if (WriteToUser(system, addr, std::addressof(next_value))) [[likely]] { 128 if (WriteToUser(system, addr, std::addressof(next_value))) [[likely]] {
131 result = ResultSuccess; 129 result = ResultSuccess;
132 } else { 130 } else {
@@ -146,8 +144,8 @@ ResultCode KConditionVariable::SignalToAddress(VAddr addr) {
146 } 144 }
147} 145}
148 146
149ResultCode KConditionVariable::WaitForAddress(Handle handle, VAddr addr, u32 value) { 147Result KConditionVariable::WaitForAddress(Handle handle, VAddr addr, u32 value) {
150 KThread* cur_thread = kernel.CurrentScheduler()->GetCurrentThread(); 148 KThread* cur_thread = GetCurrentThreadPointer(kernel);
151 ThreadQueueImplForKConditionVariableWaitForAddress wait_queue(kernel); 149 ThreadQueueImplForKConditionVariableWaitForAddress wait_queue(kernel);
152 150
153 // Wait for the address. 151 // Wait for the address.
@@ -261,7 +259,7 @@ void KConditionVariable::Signal(u64 cv_key, s32 count) {
261 } 259 }
262} 260}
263 261
264ResultCode KConditionVariable::Wait(VAddr addr, u64 key, u32 value, s64 timeout) { 262Result KConditionVariable::Wait(VAddr addr, u64 key, u32 value, s64 timeout) {
265 // Prepare to wait. 263 // Prepare to wait.
266 KThread* cur_thread = GetCurrentThreadPointer(kernel); 264 KThread* cur_thread = GetCurrentThreadPointer(kernel);
267 ThreadQueueImplForKConditionVariableWaitConditionVariable wait_queue( 265 ThreadQueueImplForKConditionVariableWaitConditionVariable wait_queue(
diff --git a/src/core/hle/kernel/k_condition_variable.h b/src/core/hle/kernel/k_condition_variable.h
index 7bc749d98..fad4ed011 100644
--- a/src/core/hle/kernel/k_condition_variable.h
+++ b/src/core/hle/kernel/k_condition_variable.h
@@ -25,12 +25,12 @@ public:
25 ~KConditionVariable(); 25 ~KConditionVariable();
26 26
27 // Arbitration 27 // Arbitration
28 [[nodiscard]] ResultCode SignalToAddress(VAddr addr); 28 [[nodiscard]] Result SignalToAddress(VAddr addr);
29 [[nodiscard]] ResultCode WaitForAddress(Handle handle, VAddr addr, u32 value); 29 [[nodiscard]] Result WaitForAddress(Handle handle, VAddr addr, u32 value);
30 30
31 // Condition variable 31 // Condition variable
32 void Signal(u64 cv_key, s32 count); 32 void Signal(u64 cv_key, s32 count);
33 [[nodiscard]] ResultCode Wait(VAddr addr, u64 key, u32 value, s64 timeout); 33 [[nodiscard]] Result Wait(VAddr addr, u64 key, u32 value, s64 timeout);
34 34
35private: 35private:
36 void SignalImpl(KThread* thread); 36 void SignalImpl(KThread* thread);
diff --git a/src/core/hle/kernel/k_handle_table.cpp b/src/core/hle/kernel/k_handle_table.cpp
index c453927ad..e830ca46e 100644
--- a/src/core/hle/kernel/k_handle_table.cpp
+++ b/src/core/hle/kernel/k_handle_table.cpp
@@ -8,7 +8,7 @@ namespace Kernel {
8KHandleTable::KHandleTable(KernelCore& kernel_) : kernel{kernel_} {} 8KHandleTable::KHandleTable(KernelCore& kernel_) : kernel{kernel_} {}
9KHandleTable::~KHandleTable() = default; 9KHandleTable::~KHandleTable() = default;
10 10
11ResultCode KHandleTable::Finalize() { 11Result KHandleTable::Finalize() {
12 // Get the table and clear our record of it. 12 // Get the table and clear our record of it.
13 u16 saved_table_size = 0; 13 u16 saved_table_size = 0;
14 { 14 {
@@ -62,7 +62,7 @@ bool KHandleTable::Remove(Handle handle) {
62 return true; 62 return true;
63} 63}
64 64
65ResultCode KHandleTable::Add(Handle* out_handle, KAutoObject* obj) { 65Result KHandleTable::Add(Handle* out_handle, KAutoObject* obj) {
66 KScopedDisableDispatch dd(kernel); 66 KScopedDisableDispatch dd(kernel);
67 KScopedSpinLock lk(m_lock); 67 KScopedSpinLock lk(m_lock);
68 68
@@ -85,7 +85,7 @@ ResultCode KHandleTable::Add(Handle* out_handle, KAutoObject* obj) {
85 return ResultSuccess; 85 return ResultSuccess;
86} 86}
87 87
88ResultCode KHandleTable::Reserve(Handle* out_handle) { 88Result KHandleTable::Reserve(Handle* out_handle) {
89 KScopedDisableDispatch dd(kernel); 89 KScopedDisableDispatch dd(kernel);
90 KScopedSpinLock lk(m_lock); 90 KScopedSpinLock lk(m_lock);
91 91
diff --git a/src/core/hle/kernel/k_handle_table.h b/src/core/hle/kernel/k_handle_table.h
index befdb2ec9..0864a737c 100644
--- a/src/core/hle/kernel/k_handle_table.h
+++ b/src/core/hle/kernel/k_handle_table.h
@@ -30,7 +30,7 @@ public:
30 explicit KHandleTable(KernelCore& kernel_); 30 explicit KHandleTable(KernelCore& kernel_);
31 ~KHandleTable(); 31 ~KHandleTable();
32 32
33 ResultCode Initialize(s32 size) { 33 Result Initialize(s32 size) {
34 R_UNLESS(size <= static_cast<s32>(MaxTableSize), ResultOutOfMemory); 34 R_UNLESS(size <= static_cast<s32>(MaxTableSize), ResultOutOfMemory);
35 35
36 // Initialize all fields. 36 // Initialize all fields.
@@ -60,7 +60,7 @@ public:
60 return m_max_count; 60 return m_max_count;
61 } 61 }
62 62
63 ResultCode Finalize(); 63 Result Finalize();
64 bool Remove(Handle handle); 64 bool Remove(Handle handle);
65 65
66 template <typename T = KAutoObject> 66 template <typename T = KAutoObject>
@@ -100,10 +100,10 @@ public:
100 return this->template GetObjectWithoutPseudoHandle<T>(handle); 100 return this->template GetObjectWithoutPseudoHandle<T>(handle);
101 } 101 }
102 102
103 ResultCode Reserve(Handle* out_handle); 103 Result Reserve(Handle* out_handle);
104 void Unreserve(Handle handle); 104 void Unreserve(Handle handle);
105 105
106 ResultCode Add(Handle* out_handle, KAutoObject* obj); 106 Result Add(Handle* out_handle, KAutoObject* obj);
107 void Register(Handle handle, KAutoObject* obj); 107 void Register(Handle handle, KAutoObject* obj);
108 108
109 template <typename T> 109 template <typename T>
diff --git a/src/core/hle/kernel/k_interrupt_manager.cpp b/src/core/hle/kernel/k_interrupt_manager.cpp
index cf9ed80d0..d606a7f86 100644
--- a/src/core/hle/kernel/k_interrupt_manager.cpp
+++ b/src/core/hle/kernel/k_interrupt_manager.cpp
@@ -15,8 +15,7 @@ void HandleInterrupt(KernelCore& kernel, s32 core_id) {
15 return; 15 return;
16 } 16 }
17 17
18 auto& scheduler = kernel.Scheduler(core_id); 18 auto& current_thread = GetCurrentThread(kernel);
19 auto& current_thread = *scheduler.GetCurrentThread();
20 19
21 // If the user disable count is set, we may need to pin the current thread. 20 // If the user disable count is set, we may need to pin the current thread.
22 if (current_thread.GetUserDisableCount() && !process->GetPinnedThread(core_id)) { 21 if (current_thread.GetUserDisableCount() && !process->GetPinnedThread(core_id)) {
@@ -26,7 +25,7 @@ void HandleInterrupt(KernelCore& kernel, s32 core_id) {
26 process->PinCurrentThread(core_id); 25 process->PinCurrentThread(core_id);
27 26
28 // Set the interrupt flag for the thread. 27 // Set the interrupt flag for the thread.
29 scheduler.GetCurrentThread()->SetInterruptFlag(); 28 GetCurrentThread(kernel).SetInterruptFlag();
30 } 29 }
31} 30}
32 31
diff --git a/src/core/hle/kernel/k_light_condition_variable.cpp b/src/core/hle/kernel/k_light_condition_variable.cpp
index a40f35f45..cade99cfd 100644
--- a/src/core/hle/kernel/k_light_condition_variable.cpp
+++ b/src/core/hle/kernel/k_light_condition_variable.cpp
@@ -17,8 +17,7 @@ public:
17 bool term) 17 bool term)
18 : KThreadQueue(kernel_), m_wait_list(wl), m_allow_terminating_thread(term) {} 18 : KThreadQueue(kernel_), m_wait_list(wl), m_allow_terminating_thread(term) {}
19 19
20 void CancelWait(KThread* waiting_thread, ResultCode wait_result, 20 void CancelWait(KThread* waiting_thread, Result wait_result, bool cancel_timer_task) override {
21 bool cancel_timer_task) override {
22 // Only process waits if we're allowed to. 21 // Only process waits if we're allowed to.
23 if (ResultTerminationRequested == wait_result && m_allow_terminating_thread) { 22 if (ResultTerminationRequested == wait_result && m_allow_terminating_thread) {
24 return; 23 return;
diff --git a/src/core/hle/kernel/k_light_lock.cpp b/src/core/hle/kernel/k_light_lock.cpp
index 0225734b4..43185320d 100644
--- a/src/core/hle/kernel/k_light_lock.cpp
+++ b/src/core/hle/kernel/k_light_lock.cpp
@@ -15,8 +15,7 @@ class ThreadQueueImplForKLightLock final : public KThreadQueue {
15public: 15public:
16 explicit ThreadQueueImplForKLightLock(KernelCore& kernel_) : KThreadQueue(kernel_) {} 16 explicit ThreadQueueImplForKLightLock(KernelCore& kernel_) : KThreadQueue(kernel_) {}
17 17
18 void CancelWait(KThread* waiting_thread, ResultCode wait_result, 18 void CancelWait(KThread* waiting_thread, Result wait_result, bool cancel_timer_task) override {
19 bool cancel_timer_task) override {
20 // Remove the thread as a waiter from its owner. 19 // Remove the thread as a waiter from its owner.
21 if (KThread* owner = waiting_thread->GetLockOwner(); owner != nullptr) { 20 if (KThread* owner = waiting_thread->GetLockOwner(); owner != nullptr) {
22 owner->RemoveWaiter(waiting_thread); 21 owner->RemoveWaiter(waiting_thread);
diff --git a/src/core/hle/kernel/k_memory_manager.cpp b/src/core/hle/kernel/k_memory_manager.cpp
index 58e540f31..5b0a9963a 100644
--- a/src/core/hle/kernel/k_memory_manager.cpp
+++ b/src/core/hle/kernel/k_memory_manager.cpp
@@ -11,7 +11,7 @@
11#include "core/device_memory.h" 11#include "core/device_memory.h"
12#include "core/hle/kernel/initial_process.h" 12#include "core/hle/kernel/initial_process.h"
13#include "core/hle/kernel/k_memory_manager.h" 13#include "core/hle/kernel/k_memory_manager.h"
14#include "core/hle/kernel/k_page_linked_list.h" 14#include "core/hle/kernel/k_page_group.h"
15#include "core/hle/kernel/kernel.h" 15#include "core/hle/kernel/kernel.h"
16#include "core/hle/kernel/svc_results.h" 16#include "core/hle/kernel/svc_results.h"
17 17
@@ -208,8 +208,8 @@ PAddr KMemoryManager::AllocateAndOpenContinuous(size_t num_pages, size_t align_p
208 return allocated_block; 208 return allocated_block;
209} 209}
210 210
211ResultCode KMemoryManager::AllocatePageGroupImpl(KPageLinkedList* out, size_t num_pages, Pool pool, 211Result KMemoryManager::AllocatePageGroupImpl(KPageGroup* out, size_t num_pages, Pool pool,
212 Direction dir, bool random) { 212 Direction dir, bool random) {
213 // Choose a heap based on our page size request. 213 // Choose a heap based on our page size request.
214 const s32 heap_index = KPageHeap::GetBlockIndex(num_pages); 214 const s32 heap_index = KPageHeap::GetBlockIndex(num_pages);
215 R_UNLESS(0 <= heap_index, ResultOutOfMemory); 215 R_UNLESS(0 <= heap_index, ResultOutOfMemory);
@@ -257,7 +257,7 @@ ResultCode KMemoryManager::AllocatePageGroupImpl(KPageLinkedList* out, size_t nu
257 return ResultSuccess; 257 return ResultSuccess;
258} 258}
259 259
260ResultCode KMemoryManager::AllocateAndOpen(KPageLinkedList* out, size_t num_pages, u32 option) { 260Result KMemoryManager::AllocateAndOpen(KPageGroup* out, size_t num_pages, u32 option) {
261 ASSERT(out != nullptr); 261 ASSERT(out != nullptr);
262 ASSERT(out->GetNumPages() == 0); 262 ASSERT(out->GetNumPages() == 0);
263 263
@@ -293,8 +293,8 @@ ResultCode KMemoryManager::AllocateAndOpen(KPageLinkedList* out, size_t num_page
293 return ResultSuccess; 293 return ResultSuccess;
294} 294}
295 295
296ResultCode KMemoryManager::AllocateAndOpenForProcess(KPageLinkedList* out, size_t num_pages, 296Result KMemoryManager::AllocateAndOpenForProcess(KPageGroup* out, size_t num_pages, u32 option,
297 u32 option, u64 process_id, u8 fill_pattern) { 297 u64 process_id, u8 fill_pattern) {
298 ASSERT(out != nullptr); 298 ASSERT(out != nullptr);
299 ASSERT(out->GetNumPages() == 0); 299 ASSERT(out->GetNumPages() == 0);
300 300
@@ -370,12 +370,12 @@ void KMemoryManager::Close(PAddr address, size_t num_pages) {
370 } 370 }
371} 371}
372 372
373void KMemoryManager::Close(const KPageLinkedList& pg) { 373void KMemoryManager::Close(const KPageGroup& pg) {
374 for (const auto& node : pg.Nodes()) { 374 for (const auto& node : pg.Nodes()) {
375 Close(node.GetAddress(), node.GetNumPages()); 375 Close(node.GetAddress(), node.GetNumPages());
376 } 376 }
377} 377}
378void KMemoryManager::Open(const KPageLinkedList& pg) { 378void KMemoryManager::Open(const KPageGroup& pg) {
379 for (const auto& node : pg.Nodes()) { 379 for (const auto& node : pg.Nodes()) {
380 Open(node.GetAddress(), node.GetNumPages()); 380 Open(node.GetAddress(), node.GetNumPages());
381 } 381 }
diff --git a/src/core/hle/kernel/k_memory_manager.h b/src/core/hle/kernel/k_memory_manager.h
index c7923cb82..dcb9b6348 100644
--- a/src/core/hle/kernel/k_memory_manager.h
+++ b/src/core/hle/kernel/k_memory_manager.h
@@ -19,7 +19,7 @@ class System;
19 19
20namespace Kernel { 20namespace Kernel {
21 21
22class KPageLinkedList; 22class KPageGroup;
23 23
24class KMemoryManager final { 24class KMemoryManager final {
25public: 25public:
@@ -65,17 +65,17 @@ public:
65 } 65 }
66 66
67 PAddr AllocateAndOpenContinuous(size_t num_pages, size_t align_pages, u32 option); 67 PAddr AllocateAndOpenContinuous(size_t num_pages, size_t align_pages, u32 option);
68 ResultCode AllocateAndOpen(KPageLinkedList* out, size_t num_pages, u32 option); 68 Result AllocateAndOpen(KPageGroup* out, size_t num_pages, u32 option);
69 ResultCode AllocateAndOpenForProcess(KPageLinkedList* out, size_t num_pages, u32 option, 69 Result AllocateAndOpenForProcess(KPageGroup* out, size_t num_pages, u32 option, u64 process_id,
70 u64 process_id, u8 fill_pattern); 70 u8 fill_pattern);
71 71
72 static constexpr size_t MaxManagerCount = 10; 72 static constexpr size_t MaxManagerCount = 10;
73 73
74 void Close(PAddr address, size_t num_pages); 74 void Close(PAddr address, size_t num_pages);
75 void Close(const KPageLinkedList& pg); 75 void Close(const KPageGroup& pg);
76 76
77 void Open(PAddr address, size_t num_pages); 77 void Open(PAddr address, size_t num_pages);
78 void Open(const KPageLinkedList& pg); 78 void Open(const KPageGroup& pg);
79 79
80public: 80public:
81 static size_t CalculateManagementOverheadSize(size_t region_size) { 81 static size_t CalculateManagementOverheadSize(size_t region_size) {
@@ -262,8 +262,8 @@ private:
262 } 262 }
263 } 263 }
264 264
265 ResultCode AllocatePageGroupImpl(KPageLinkedList* out, size_t num_pages, Pool pool, 265 Result AllocatePageGroupImpl(KPageGroup* out, size_t num_pages, Pool pool, Direction dir,
266 Direction dir, bool random); 266 bool random);
267 267
268private: 268private:
269 Core::System& system; 269 Core::System& system;
diff --git a/src/core/hle/kernel/k_page_linked_list.h b/src/core/hle/kernel/k_page_group.h
index 1f79c8330..968753992 100644
--- a/src/core/hle/kernel/k_page_linked_list.h
+++ b/src/core/hle/kernel/k_page_group.h
@@ -12,7 +12,7 @@
12 12
13namespace Kernel { 13namespace Kernel {
14 14
15class KPageLinkedList final { 15class KPageGroup final {
16public: 16public:
17 class Node final { 17 class Node final {
18 public: 18 public:
@@ -36,8 +36,8 @@ public:
36 }; 36 };
37 37
38public: 38public:
39 KPageLinkedList() = default; 39 KPageGroup() = default;
40 KPageLinkedList(u64 address, u64 num_pages) { 40 KPageGroup(u64 address, u64 num_pages) {
41 ASSERT(AddBlock(address, num_pages).IsSuccess()); 41 ASSERT(AddBlock(address, num_pages).IsSuccess());
42 } 42 }
43 43
@@ -57,7 +57,7 @@ public:
57 return num_pages; 57 return num_pages;
58 } 58 }
59 59
60 bool IsEqual(KPageLinkedList& other) const { 60 bool IsEqual(KPageGroup& other) const {
61 auto this_node = nodes.begin(); 61 auto this_node = nodes.begin();
62 auto other_node = other.nodes.begin(); 62 auto other_node = other.nodes.begin();
63 while (this_node != nodes.end() && other_node != other.nodes.end()) { 63 while (this_node != nodes.end() && other_node != other.nodes.end()) {
@@ -72,7 +72,7 @@ public:
72 return this_node == nodes.end() && other_node == other.nodes.end(); 72 return this_node == nodes.end() && other_node == other.nodes.end();
73 } 73 }
74 74
75 ResultCode AddBlock(u64 address, u64 num_pages) { 75 Result AddBlock(u64 address, u64 num_pages) {
76 if (!num_pages) { 76 if (!num_pages) {
77 return ResultSuccess; 77 return ResultSuccess;
78 } 78 }
diff --git a/src/core/hle/kernel/k_page_table.cpp b/src/core/hle/kernel/k_page_table.cpp
index 39b89da53..d975de844 100644
--- a/src/core/hle/kernel/k_page_table.cpp
+++ b/src/core/hle/kernel/k_page_table.cpp
@@ -9,7 +9,7 @@
9#include "core/hle/kernel/k_address_space_info.h" 9#include "core/hle/kernel/k_address_space_info.h"
10#include "core/hle/kernel/k_memory_block.h" 10#include "core/hle/kernel/k_memory_block.h"
11#include "core/hle/kernel/k_memory_block_manager.h" 11#include "core/hle/kernel/k_memory_block_manager.h"
12#include "core/hle/kernel/k_page_linked_list.h" 12#include "core/hle/kernel/k_page_group.h"
13#include "core/hle/kernel/k_page_table.h" 13#include "core/hle/kernel/k_page_table.h"
14#include "core/hle/kernel/k_process.h" 14#include "core/hle/kernel/k_process.h"
15#include "core/hle/kernel/k_resource_limit.h" 15#include "core/hle/kernel/k_resource_limit.h"
@@ -47,9 +47,9 @@ KPageTable::KPageTable(Core::System& system_)
47 47
48KPageTable::~KPageTable() = default; 48KPageTable::~KPageTable() = default;
49 49
50ResultCode KPageTable::InitializeForProcess(FileSys::ProgramAddressSpaceType as_type, 50Result KPageTable::InitializeForProcess(FileSys::ProgramAddressSpaceType as_type, bool enable_aslr,
51 bool enable_aslr, VAddr code_addr, 51 VAddr code_addr, std::size_t code_size,
52 std::size_t code_size, KMemoryManager::Pool pool) { 52 KMemoryManager::Pool pool) {
53 53
54 const auto GetSpaceStart = [this](KAddressSpaceInfo::Type type) { 54 const auto GetSpaceStart = [this](KAddressSpaceInfo::Type type) {
55 return KAddressSpaceInfo::GetAddressSpaceStart(address_space_width, type); 55 return KAddressSpaceInfo::GetAddressSpaceStart(address_space_width, type);
@@ -257,8 +257,8 @@ ResultCode KPageTable::InitializeForProcess(FileSys::ProgramAddressSpaceType as_
257 return InitializeMemoryLayout(start, end); 257 return InitializeMemoryLayout(start, end);
258} 258}
259 259
260ResultCode KPageTable::MapProcessCode(VAddr addr, std::size_t num_pages, KMemoryState state, 260Result KPageTable::MapProcessCode(VAddr addr, std::size_t num_pages, KMemoryState state,
261 KMemoryPermission perm) { 261 KMemoryPermission perm) {
262 const u64 size{num_pages * PageSize}; 262 const u64 size{num_pages * PageSize};
263 263
264 // Validate the mapping request. 264 // Validate the mapping request.
@@ -271,7 +271,7 @@ ResultCode KPageTable::MapProcessCode(VAddr addr, std::size_t num_pages, KMemory
271 R_TRY(this->CheckMemoryState(addr, size, KMemoryState::All, KMemoryState::Free, 271 R_TRY(this->CheckMemoryState(addr, size, KMemoryState::All, KMemoryState::Free,
272 KMemoryPermission::None, KMemoryPermission::None, 272 KMemoryPermission::None, KMemoryPermission::None,
273 KMemoryAttribute::None, KMemoryAttribute::None)); 273 KMemoryAttribute::None, KMemoryAttribute::None));
274 KPageLinkedList pg; 274 KPageGroup pg;
275 R_TRY(system.Kernel().MemoryManager().AllocateAndOpen( 275 R_TRY(system.Kernel().MemoryManager().AllocateAndOpen(
276 &pg, num_pages, 276 &pg, num_pages,
277 KMemoryManager::EncodeOption(KMemoryManager::Pool::Application, allocation_option))); 277 KMemoryManager::EncodeOption(KMemoryManager::Pool::Application, allocation_option)));
@@ -283,7 +283,7 @@ ResultCode KPageTable::MapProcessCode(VAddr addr, std::size_t num_pages, KMemory
283 return ResultSuccess; 283 return ResultSuccess;
284} 284}
285 285
286ResultCode KPageTable::MapCodeMemory(VAddr dst_address, VAddr src_address, std::size_t size) { 286Result KPageTable::MapCodeMemory(VAddr dst_address, VAddr src_address, std::size_t size) {
287 // Validate the mapping request. 287 // Validate the mapping request.
288 R_UNLESS(this->CanContain(dst_address, size, KMemoryState::AliasCode), 288 R_UNLESS(this->CanContain(dst_address, size, KMemoryState::AliasCode),
289 ResultInvalidMemoryRegion); 289 ResultInvalidMemoryRegion);
@@ -313,7 +313,7 @@ ResultCode KPageTable::MapCodeMemory(VAddr dst_address, VAddr src_address, std::
313 const std::size_t num_pages = size / PageSize; 313 const std::size_t num_pages = size / PageSize;
314 314
315 // Create page groups for the memory being mapped. 315 // Create page groups for the memory being mapped.
316 KPageLinkedList pg; 316 KPageGroup pg;
317 AddRegionToPages(src_address, num_pages, pg); 317 AddRegionToPages(src_address, num_pages, pg);
318 318
319 // Reprotect the source as kernel-read/not mapped. 319 // Reprotect the source as kernel-read/not mapped.
@@ -344,8 +344,8 @@ ResultCode KPageTable::MapCodeMemory(VAddr dst_address, VAddr src_address, std::
344 return ResultSuccess; 344 return ResultSuccess;
345} 345}
346 346
347ResultCode KPageTable::UnmapCodeMemory(VAddr dst_address, VAddr src_address, std::size_t size, 347Result KPageTable::UnmapCodeMemory(VAddr dst_address, VAddr src_address, std::size_t size,
348 ICacheInvalidationStrategy icache_invalidation_strategy) { 348 ICacheInvalidationStrategy icache_invalidation_strategy) {
349 // Validate the mapping request. 349 // Validate the mapping request.
350 R_UNLESS(this->CanContain(dst_address, size, KMemoryState::AliasCode), 350 R_UNLESS(this->CanContain(dst_address, size, KMemoryState::AliasCode),
351 ResultInvalidMemoryRegion); 351 ResultInvalidMemoryRegion);
@@ -489,7 +489,7 @@ VAddr KPageTable::FindFreeArea(VAddr region_start, std::size_t region_num_pages,
489 return address; 489 return address;
490} 490}
491 491
492ResultCode KPageTable::MakePageGroup(KPageLinkedList& pg, VAddr addr, size_t num_pages) { 492Result KPageTable::MakePageGroup(KPageGroup& pg, VAddr addr, size_t num_pages) {
493 ASSERT(this->IsLockedByCurrentThread()); 493 ASSERT(this->IsLockedByCurrentThread());
494 494
495 const size_t size = num_pages * PageSize; 495 const size_t size = num_pages * PageSize;
@@ -541,7 +541,7 @@ ResultCode KPageTable::MakePageGroup(KPageLinkedList& pg, VAddr addr, size_t num
541 return ResultSuccess; 541 return ResultSuccess;
542} 542}
543 543
544bool KPageTable::IsValidPageGroup(const KPageLinkedList& pg_ll, VAddr addr, size_t num_pages) { 544bool KPageTable::IsValidPageGroup(const KPageGroup& pg_ll, VAddr addr, size_t num_pages) {
545 ASSERT(this->IsLockedByCurrentThread()); 545 ASSERT(this->IsLockedByCurrentThread());
546 546
547 const size_t size = num_pages * PageSize; 547 const size_t size = num_pages * PageSize;
@@ -630,8 +630,8 @@ bool KPageTable::IsValidPageGroup(const KPageLinkedList& pg_ll, VAddr addr, size
630 return cur_block_address == cur_addr && cur_block_pages == (cur_size / PageSize); 630 return cur_block_address == cur_addr && cur_block_pages == (cur_size / PageSize);
631} 631}
632 632
633ResultCode KPageTable::UnmapProcessMemory(VAddr dst_addr, std::size_t size, 633Result KPageTable::UnmapProcessMemory(VAddr dst_addr, std::size_t size, KPageTable& src_page_table,
634 KPageTable& src_page_table, VAddr src_addr) { 634 VAddr src_addr) {
635 KScopedLightLock lk(general_lock); 635 KScopedLightLock lk(general_lock);
636 636
637 const std::size_t num_pages{size / PageSize}; 637 const std::size_t num_pages{size / PageSize};
@@ -660,7 +660,7 @@ ResultCode KPageTable::UnmapProcessMemory(VAddr dst_addr, std::size_t size,
660 return ResultSuccess; 660 return ResultSuccess;
661} 661}
662 662
663ResultCode KPageTable::MapPhysicalMemory(VAddr address, std::size_t size) { 663Result KPageTable::MapPhysicalMemory(VAddr address, std::size_t size) {
664 // Lock the physical memory lock. 664 // Lock the physical memory lock.
665 KScopedLightLock map_phys_mem_lk(map_physical_memory_lock); 665 KScopedLightLock map_phys_mem_lk(map_physical_memory_lock);
666 666
@@ -721,7 +721,7 @@ ResultCode KPageTable::MapPhysicalMemory(VAddr address, std::size_t size) {
721 R_UNLESS(memory_reservation.Succeeded(), ResultLimitReached); 721 R_UNLESS(memory_reservation.Succeeded(), ResultLimitReached);
722 722
723 // Allocate pages for the new memory. 723 // Allocate pages for the new memory.
724 KPageLinkedList pg; 724 KPageGroup pg;
725 R_TRY(system.Kernel().MemoryManager().AllocateAndOpenForProcess( 725 R_TRY(system.Kernel().MemoryManager().AllocateAndOpenForProcess(
726 &pg, (size - mapped_size) / PageSize, 726 &pg, (size - mapped_size) / PageSize,
727 KMemoryManager::EncodeOption(memory_pool, allocation_option), 0, 0)); 727 KMemoryManager::EncodeOption(memory_pool, allocation_option), 0, 0));
@@ -903,7 +903,7 @@ ResultCode KPageTable::MapPhysicalMemory(VAddr address, std::size_t size) {
903 } 903 }
904} 904}
905 905
906ResultCode KPageTable::UnmapPhysicalMemory(VAddr address, std::size_t size) { 906Result KPageTable::UnmapPhysicalMemory(VAddr address, std::size_t size) {
907 // Lock the physical memory lock. 907 // Lock the physical memory lock.
908 KScopedLightLock map_phys_mem_lk(map_physical_memory_lock); 908 KScopedLightLock map_phys_mem_lk(map_physical_memory_lock);
909 909
@@ -972,7 +972,7 @@ ResultCode KPageTable::UnmapPhysicalMemory(VAddr address, std::size_t size) {
972 } 972 }
973 973
974 // Make a page group for the unmap region. 974 // Make a page group for the unmap region.
975 KPageLinkedList pg; 975 KPageGroup pg;
976 { 976 {
977 auto& impl = this->PageTableImpl(); 977 auto& impl = this->PageTableImpl();
978 978
@@ -1134,7 +1134,7 @@ ResultCode KPageTable::UnmapPhysicalMemory(VAddr address, std::size_t size) {
1134 return ResultSuccess; 1134 return ResultSuccess;
1135} 1135}
1136 1136
1137ResultCode KPageTable::MapMemory(VAddr dst_addr, VAddr src_addr, std::size_t size) { 1137Result KPageTable::MapMemory(VAddr dst_addr, VAddr src_addr, std::size_t size) {
1138 KScopedLightLock lk(general_lock); 1138 KScopedLightLock lk(general_lock);
1139 1139
1140 KMemoryState src_state{}; 1140 KMemoryState src_state{};
@@ -1147,7 +1147,7 @@ ResultCode KPageTable::MapMemory(VAddr dst_addr, VAddr src_addr, std::size_t siz
1147 return ResultInvalidCurrentMemory; 1147 return ResultInvalidCurrentMemory;
1148 } 1148 }
1149 1149
1150 KPageLinkedList page_linked_list; 1150 KPageGroup page_linked_list;
1151 const std::size_t num_pages{size / PageSize}; 1151 const std::size_t num_pages{size / PageSize};
1152 1152
1153 AddRegionToPages(src_addr, num_pages, page_linked_list); 1153 AddRegionToPages(src_addr, num_pages, page_linked_list);
@@ -1173,7 +1173,7 @@ ResultCode KPageTable::MapMemory(VAddr dst_addr, VAddr src_addr, std::size_t siz
1173 return ResultSuccess; 1173 return ResultSuccess;
1174} 1174}
1175 1175
1176ResultCode KPageTable::UnmapMemory(VAddr dst_addr, VAddr src_addr, std::size_t size) { 1176Result KPageTable::UnmapMemory(VAddr dst_addr, VAddr src_addr, std::size_t size) {
1177 KScopedLightLock lk(general_lock); 1177 KScopedLightLock lk(general_lock);
1178 1178
1179 KMemoryState src_state{}; 1179 KMemoryState src_state{};
@@ -1188,8 +1188,8 @@ ResultCode KPageTable::UnmapMemory(VAddr dst_addr, VAddr src_addr, std::size_t s
1188 KMemoryPermission::None, KMemoryAttribute::Mask, 1188 KMemoryPermission::None, KMemoryAttribute::Mask,
1189 KMemoryAttribute::None, KMemoryAttribute::IpcAndDeviceMapped)); 1189 KMemoryAttribute::None, KMemoryAttribute::IpcAndDeviceMapped));
1190 1190
1191 KPageLinkedList src_pages; 1191 KPageGroup src_pages;
1192 KPageLinkedList dst_pages; 1192 KPageGroup dst_pages;
1193 const std::size_t num_pages{size / PageSize}; 1193 const std::size_t num_pages{size / PageSize};
1194 1194
1195 AddRegionToPages(src_addr, num_pages, src_pages); 1195 AddRegionToPages(src_addr, num_pages, src_pages);
@@ -1215,8 +1215,8 @@ ResultCode KPageTable::UnmapMemory(VAddr dst_addr, VAddr src_addr, std::size_t s
1215 return ResultSuccess; 1215 return ResultSuccess;
1216} 1216}
1217 1217
1218ResultCode KPageTable::MapPages(VAddr addr, const KPageLinkedList& page_linked_list, 1218Result KPageTable::MapPages(VAddr addr, const KPageGroup& page_linked_list,
1219 KMemoryPermission perm) { 1219 KMemoryPermission perm) {
1220 ASSERT(this->IsLockedByCurrentThread()); 1220 ASSERT(this->IsLockedByCurrentThread());
1221 1221
1222 VAddr cur_addr{addr}; 1222 VAddr cur_addr{addr};
@@ -1239,8 +1239,8 @@ ResultCode KPageTable::MapPages(VAddr addr, const KPageLinkedList& page_linked_l
1239 return ResultSuccess; 1239 return ResultSuccess;
1240} 1240}
1241 1241
1242ResultCode KPageTable::MapPages(VAddr address, KPageLinkedList& page_linked_list, 1242Result KPageTable::MapPages(VAddr address, KPageGroup& page_linked_list, KMemoryState state,
1243 KMemoryState state, KMemoryPermission perm) { 1243 KMemoryPermission perm) {
1244 // Check that the map is in range. 1244 // Check that the map is in range.
1245 const std::size_t num_pages{page_linked_list.GetNumPages()}; 1245 const std::size_t num_pages{page_linked_list.GetNumPages()};
1246 const std::size_t size{num_pages * PageSize}; 1246 const std::size_t size{num_pages * PageSize};
@@ -1263,10 +1263,10 @@ ResultCode KPageTable::MapPages(VAddr address, KPageLinkedList& page_linked_list
1263 return ResultSuccess; 1263 return ResultSuccess;
1264} 1264}
1265 1265
1266ResultCode KPageTable::MapPages(VAddr* out_addr, std::size_t num_pages, std::size_t alignment, 1266Result KPageTable::MapPages(VAddr* out_addr, std::size_t num_pages, std::size_t alignment,
1267 PAddr phys_addr, bool is_pa_valid, VAddr region_start, 1267 PAddr phys_addr, bool is_pa_valid, VAddr region_start,
1268 std::size_t region_num_pages, KMemoryState state, 1268 std::size_t region_num_pages, KMemoryState state,
1269 KMemoryPermission perm) { 1269 KMemoryPermission perm) {
1270 ASSERT(Common::IsAligned(alignment, PageSize) && alignment >= PageSize); 1270 ASSERT(Common::IsAligned(alignment, PageSize) && alignment >= PageSize);
1271 1271
1272 // Ensure this is a valid map request. 1272 // Ensure this is a valid map request.
@@ -1303,7 +1303,7 @@ ResultCode KPageTable::MapPages(VAddr* out_addr, std::size_t num_pages, std::siz
1303 return ResultSuccess; 1303 return ResultSuccess;
1304} 1304}
1305 1305
1306ResultCode KPageTable::UnmapPages(VAddr addr, const KPageLinkedList& page_linked_list) { 1306Result KPageTable::UnmapPages(VAddr addr, const KPageGroup& page_linked_list) {
1307 ASSERT(this->IsLockedByCurrentThread()); 1307 ASSERT(this->IsLockedByCurrentThread());
1308 1308
1309 VAddr cur_addr{addr}; 1309 VAddr cur_addr{addr};
@@ -1321,8 +1321,7 @@ ResultCode KPageTable::UnmapPages(VAddr addr, const KPageLinkedList& page_linked
1321 return ResultSuccess; 1321 return ResultSuccess;
1322} 1322}
1323 1323
1324ResultCode KPageTable::UnmapPages(VAddr addr, KPageLinkedList& page_linked_list, 1324Result KPageTable::UnmapPages(VAddr addr, KPageGroup& page_linked_list, KMemoryState state) {
1325 KMemoryState state) {
1326 // Check that the unmap is in range. 1325 // Check that the unmap is in range.
1327 const std::size_t num_pages{page_linked_list.GetNumPages()}; 1326 const std::size_t num_pages{page_linked_list.GetNumPages()};
1328 const std::size_t size{num_pages * PageSize}; 1327 const std::size_t size{num_pages * PageSize};
@@ -1345,7 +1344,7 @@ ResultCode KPageTable::UnmapPages(VAddr addr, KPageLinkedList& page_linked_list,
1345 return ResultSuccess; 1344 return ResultSuccess;
1346} 1345}
1347 1346
1348ResultCode KPageTable::UnmapPages(VAddr address, std::size_t num_pages, KMemoryState state) { 1347Result KPageTable::UnmapPages(VAddr address, std::size_t num_pages, KMemoryState state) {
1349 // Check that the unmap is in range. 1348 // Check that the unmap is in range.
1350 const std::size_t size = num_pages * PageSize; 1349 const std::size_t size = num_pages * PageSize;
1351 R_UNLESS(this->Contains(address, size), ResultInvalidCurrentMemory); 1350 R_UNLESS(this->Contains(address, size), ResultInvalidCurrentMemory);
@@ -1369,10 +1368,10 @@ ResultCode KPageTable::UnmapPages(VAddr address, std::size_t num_pages, KMemoryS
1369 return ResultSuccess; 1368 return ResultSuccess;
1370} 1369}
1371 1370
1372ResultCode KPageTable::MakeAndOpenPageGroup(KPageLinkedList* out, VAddr address, size_t num_pages, 1371Result KPageTable::MakeAndOpenPageGroup(KPageGroup* out, VAddr address, size_t num_pages,
1373 KMemoryState state_mask, KMemoryState state, 1372 KMemoryState state_mask, KMemoryState state,
1374 KMemoryPermission perm_mask, KMemoryPermission perm, 1373 KMemoryPermission perm_mask, KMemoryPermission perm,
1375 KMemoryAttribute attr_mask, KMemoryAttribute attr) { 1374 KMemoryAttribute attr_mask, KMemoryAttribute attr) {
1376 // Ensure that the page group isn't null. 1375 // Ensure that the page group isn't null.
1377 ASSERT(out != nullptr); 1376 ASSERT(out != nullptr);
1378 1377
@@ -1394,8 +1393,8 @@ ResultCode KPageTable::MakeAndOpenPageGroup(KPageLinkedList* out, VAddr address,
1394 return ResultSuccess; 1393 return ResultSuccess;
1395} 1394}
1396 1395
1397ResultCode KPageTable::SetProcessMemoryPermission(VAddr addr, std::size_t size, 1396Result KPageTable::SetProcessMemoryPermission(VAddr addr, std::size_t size,
1398 Svc::MemoryPermission svc_perm) { 1397 Svc::MemoryPermission svc_perm) {
1399 const size_t num_pages = size / PageSize; 1398 const size_t num_pages = size / PageSize;
1400 1399
1401 // Lock the table. 1400 // Lock the table.
@@ -1467,7 +1466,7 @@ KMemoryInfo KPageTable::QueryInfo(VAddr addr) {
1467 return QueryInfoImpl(addr); 1466 return QueryInfoImpl(addr);
1468} 1467}
1469 1468
1470ResultCode KPageTable::ReserveTransferMemory(VAddr addr, std::size_t size, KMemoryPermission perm) { 1469Result KPageTable::ReserveTransferMemory(VAddr addr, std::size_t size, KMemoryPermission perm) {
1471 KScopedLightLock lk(general_lock); 1470 KScopedLightLock lk(general_lock);
1472 1471
1473 KMemoryState state{}; 1472 KMemoryState state{};
@@ -1485,7 +1484,7 @@ ResultCode KPageTable::ReserveTransferMemory(VAddr addr, std::size_t size, KMemo
1485 return ResultSuccess; 1484 return ResultSuccess;
1486} 1485}
1487 1486
1488ResultCode KPageTable::ResetTransferMemory(VAddr addr, std::size_t size) { 1487Result KPageTable::ResetTransferMemory(VAddr addr, std::size_t size) {
1489 KScopedLightLock lk(general_lock); 1488 KScopedLightLock lk(general_lock);
1490 1489
1491 KMemoryState state{}; 1490 KMemoryState state{};
@@ -1500,8 +1499,8 @@ ResultCode KPageTable::ResetTransferMemory(VAddr addr, std::size_t size) {
1500 return ResultSuccess; 1499 return ResultSuccess;
1501} 1500}
1502 1501
1503ResultCode KPageTable::SetMemoryPermission(VAddr addr, std::size_t size, 1502Result KPageTable::SetMemoryPermission(VAddr addr, std::size_t size,
1504 Svc::MemoryPermission svc_perm) { 1503 Svc::MemoryPermission svc_perm) {
1505 const size_t num_pages = size / PageSize; 1504 const size_t num_pages = size / PageSize;
1506 1505
1507 // Lock the table. 1506 // Lock the table.
@@ -1528,7 +1527,7 @@ ResultCode KPageTable::SetMemoryPermission(VAddr addr, std::size_t size,
1528 return ResultSuccess; 1527 return ResultSuccess;
1529} 1528}
1530 1529
1531ResultCode KPageTable::SetMemoryAttribute(VAddr addr, std::size_t size, u32 mask, u32 attr) { 1530Result KPageTable::SetMemoryAttribute(VAddr addr, std::size_t size, u32 mask, u32 attr) {
1532 const size_t num_pages = size / PageSize; 1531 const size_t num_pages = size / PageSize;
1533 ASSERT((static_cast<KMemoryAttribute>(mask) | KMemoryAttribute::SetMask) == 1532 ASSERT((static_cast<KMemoryAttribute>(mask) | KMemoryAttribute::SetMask) ==
1534 KMemoryAttribute::SetMask); 1533 KMemoryAttribute::SetMask);
@@ -1563,7 +1562,7 @@ ResultCode KPageTable::SetMemoryAttribute(VAddr addr, std::size_t size, u32 mask
1563 return ResultSuccess; 1562 return ResultSuccess;
1564} 1563}
1565 1564
1566ResultCode KPageTable::SetMaxHeapSize(std::size_t size) { 1565Result KPageTable::SetMaxHeapSize(std::size_t size) {
1567 // Lock the table. 1566 // Lock the table.
1568 KScopedLightLock lk(general_lock); 1567 KScopedLightLock lk(general_lock);
1569 1568
@@ -1575,7 +1574,7 @@ ResultCode KPageTable::SetMaxHeapSize(std::size_t size) {
1575 return ResultSuccess; 1574 return ResultSuccess;
1576} 1575}
1577 1576
1578ResultCode KPageTable::SetHeapSize(VAddr* out, std::size_t size) { 1577Result KPageTable::SetHeapSize(VAddr* out, std::size_t size) {
1579 // Lock the physical memory mutex. 1578 // Lock the physical memory mutex.
1580 KScopedLightLock map_phys_mem_lk(map_physical_memory_lock); 1579 KScopedLightLock map_phys_mem_lk(map_physical_memory_lock);
1581 1580
@@ -1642,7 +1641,7 @@ ResultCode KPageTable::SetHeapSize(VAddr* out, std::size_t size) {
1642 R_UNLESS(memory_reservation.Succeeded(), ResultLimitReached); 1641 R_UNLESS(memory_reservation.Succeeded(), ResultLimitReached);
1643 1642
1644 // Allocate pages for the heap extension. 1643 // Allocate pages for the heap extension.
1645 KPageLinkedList pg; 1644 KPageGroup pg;
1646 R_TRY(system.Kernel().MemoryManager().AllocateAndOpen( 1645 R_TRY(system.Kernel().MemoryManager().AllocateAndOpen(
1647 &pg, allocation_size / PageSize, 1646 &pg, allocation_size / PageSize,
1648 KMemoryManager::EncodeOption(memory_pool, allocation_option))); 1647 KMemoryManager::EncodeOption(memory_pool, allocation_option)));
@@ -1717,7 +1716,7 @@ ResultVal<VAddr> KPageTable::AllocateAndMapMemory(std::size_t needed_num_pages,
1717 if (is_map_only) { 1716 if (is_map_only) {
1718 R_TRY(Operate(addr, needed_num_pages, perm, OperationType::Map, map_addr)); 1717 R_TRY(Operate(addr, needed_num_pages, perm, OperationType::Map, map_addr));
1719 } else { 1718 } else {
1720 KPageLinkedList page_group; 1719 KPageGroup page_group;
1721 R_TRY(system.Kernel().MemoryManager().AllocateAndOpenForProcess( 1720 R_TRY(system.Kernel().MemoryManager().AllocateAndOpenForProcess(
1722 &page_group, needed_num_pages, 1721 &page_group, needed_num_pages,
1723 KMemoryManager::EncodeOption(memory_pool, allocation_option), 0, 0)); 1722 KMemoryManager::EncodeOption(memory_pool, allocation_option), 0, 0));
@@ -1729,11 +1728,11 @@ ResultVal<VAddr> KPageTable::AllocateAndMapMemory(std::size_t needed_num_pages,
1729 return addr; 1728 return addr;
1730} 1729}
1731 1730
1732ResultCode KPageTable::LockForDeviceAddressSpace(VAddr addr, std::size_t size) { 1731Result KPageTable::LockForDeviceAddressSpace(VAddr addr, std::size_t size) {
1733 KScopedLightLock lk(general_lock); 1732 KScopedLightLock lk(general_lock);
1734 1733
1735 KMemoryPermission perm{}; 1734 KMemoryPermission perm{};
1736 if (const ResultCode result{CheckMemoryState( 1735 if (const Result result{CheckMemoryState(
1737 nullptr, &perm, nullptr, nullptr, addr, size, KMemoryState::FlagCanChangeAttribute, 1736 nullptr, &perm, nullptr, nullptr, addr, size, KMemoryState::FlagCanChangeAttribute,
1738 KMemoryState::FlagCanChangeAttribute, KMemoryPermission::None, KMemoryPermission::None, 1737 KMemoryState::FlagCanChangeAttribute, KMemoryPermission::None, KMemoryPermission::None,
1739 KMemoryAttribute::LockedAndIpcLocked, KMemoryAttribute::None, 1738 KMemoryAttribute::LockedAndIpcLocked, KMemoryAttribute::None,
@@ -1752,11 +1751,11 @@ ResultCode KPageTable::LockForDeviceAddressSpace(VAddr addr, std::size_t size) {
1752 return ResultSuccess; 1751 return ResultSuccess;
1753} 1752}
1754 1753
1755ResultCode KPageTable::UnlockForDeviceAddressSpace(VAddr addr, std::size_t size) { 1754Result KPageTable::UnlockForDeviceAddressSpace(VAddr addr, std::size_t size) {
1756 KScopedLightLock lk(general_lock); 1755 KScopedLightLock lk(general_lock);
1757 1756
1758 KMemoryPermission perm{}; 1757 KMemoryPermission perm{};
1759 if (const ResultCode result{CheckMemoryState( 1758 if (const Result result{CheckMemoryState(
1760 nullptr, &perm, nullptr, nullptr, addr, size, KMemoryState::FlagCanChangeAttribute, 1759 nullptr, &perm, nullptr, nullptr, addr, size, KMemoryState::FlagCanChangeAttribute,
1761 KMemoryState::FlagCanChangeAttribute, KMemoryPermission::None, KMemoryPermission::None, 1760 KMemoryState::FlagCanChangeAttribute, KMemoryPermission::None, KMemoryPermission::None,
1762 KMemoryAttribute::LockedAndIpcLocked, KMemoryAttribute::None, 1761 KMemoryAttribute::LockedAndIpcLocked, KMemoryAttribute::None,
@@ -1775,7 +1774,7 @@ ResultCode KPageTable::UnlockForDeviceAddressSpace(VAddr addr, std::size_t size)
1775 return ResultSuccess; 1774 return ResultSuccess;
1776} 1775}
1777 1776
1778ResultCode KPageTable::LockForCodeMemory(KPageLinkedList* out, VAddr addr, std::size_t size) { 1777Result KPageTable::LockForCodeMemory(KPageGroup* out, VAddr addr, std::size_t size) {
1779 return this->LockMemoryAndOpen( 1778 return this->LockMemoryAndOpen(
1780 out, nullptr, addr, size, KMemoryState::FlagCanCodeMemory, KMemoryState::FlagCanCodeMemory, 1779 out, nullptr, addr, size, KMemoryState::FlagCanCodeMemory, KMemoryState::FlagCanCodeMemory,
1781 KMemoryPermission::All, KMemoryPermission::UserReadWrite, KMemoryAttribute::All, 1780 KMemoryPermission::All, KMemoryPermission::UserReadWrite, KMemoryAttribute::All,
@@ -1785,15 +1784,14 @@ ResultCode KPageTable::LockForCodeMemory(KPageLinkedList* out, VAddr addr, std::
1785 KMemoryAttribute::Locked); 1784 KMemoryAttribute::Locked);
1786} 1785}
1787 1786
1788ResultCode KPageTable::UnlockForCodeMemory(VAddr addr, std::size_t size, 1787Result KPageTable::UnlockForCodeMemory(VAddr addr, std::size_t size, const KPageGroup& pg) {
1789 const KPageLinkedList& pg) {
1790 return this->UnlockMemory( 1788 return this->UnlockMemory(
1791 addr, size, KMemoryState::FlagCanCodeMemory, KMemoryState::FlagCanCodeMemory, 1789 addr, size, KMemoryState::FlagCanCodeMemory, KMemoryState::FlagCanCodeMemory,
1792 KMemoryPermission::None, KMemoryPermission::None, KMemoryAttribute::All, 1790 KMemoryPermission::None, KMemoryPermission::None, KMemoryAttribute::All,
1793 KMemoryAttribute::Locked, KMemoryPermission::UserReadWrite, KMemoryAttribute::Locked, &pg); 1791 KMemoryAttribute::Locked, KMemoryPermission::UserReadWrite, KMemoryAttribute::Locked, &pg);
1794} 1792}
1795 1793
1796ResultCode KPageTable::InitializeMemoryLayout(VAddr start, VAddr end) { 1794Result KPageTable::InitializeMemoryLayout(VAddr start, VAddr end) {
1797 block_manager = std::make_unique<KMemoryBlockManager>(start, end); 1795 block_manager = std::make_unique<KMemoryBlockManager>(start, end);
1798 1796
1799 return ResultSuccess; 1797 return ResultSuccess;
@@ -1818,7 +1816,7 @@ bool KPageTable::IsRegionContiguous(VAddr addr, u64 size) const {
1818} 1816}
1819 1817
1820void KPageTable::AddRegionToPages(VAddr start, std::size_t num_pages, 1818void KPageTable::AddRegionToPages(VAddr start, std::size_t num_pages,
1821 KPageLinkedList& page_linked_list) { 1819 KPageGroup& page_linked_list) {
1822 VAddr addr{start}; 1820 VAddr addr{start};
1823 while (addr < start + (num_pages * PageSize)) { 1821 while (addr < start + (num_pages * PageSize)) {
1824 const PAddr paddr{GetPhysicalAddr(addr)}; 1822 const PAddr paddr{GetPhysicalAddr(addr)};
@@ -1837,8 +1835,8 @@ VAddr KPageTable::AllocateVirtualMemory(VAddr start, std::size_t region_num_page
1837 IsKernel() ? 1 : 4); 1835 IsKernel() ? 1 : 4);
1838} 1836}
1839 1837
1840ResultCode KPageTable::Operate(VAddr addr, std::size_t num_pages, const KPageLinkedList& page_group, 1838Result KPageTable::Operate(VAddr addr, std::size_t num_pages, const KPageGroup& page_group,
1841 OperationType operation) { 1839 OperationType operation) {
1842 ASSERT(this->IsLockedByCurrentThread()); 1840 ASSERT(this->IsLockedByCurrentThread());
1843 1841
1844 ASSERT(Common::IsAligned(addr, PageSize)); 1842 ASSERT(Common::IsAligned(addr, PageSize));
@@ -1862,8 +1860,8 @@ ResultCode KPageTable::Operate(VAddr addr, std::size_t num_pages, const KPageLin
1862 return ResultSuccess; 1860 return ResultSuccess;
1863} 1861}
1864 1862
1865ResultCode KPageTable::Operate(VAddr addr, std::size_t num_pages, KMemoryPermission perm, 1863Result KPageTable::Operate(VAddr addr, std::size_t num_pages, KMemoryPermission perm,
1866 OperationType operation, PAddr map_addr) { 1864 OperationType operation, PAddr map_addr) {
1867 ASSERT(this->IsLockedByCurrentThread()); 1865 ASSERT(this->IsLockedByCurrentThread());
1868 1866
1869 ASSERT(num_pages > 0); 1867 ASSERT(num_pages > 0);
@@ -2005,10 +2003,10 @@ bool KPageTable::CanContain(VAddr addr, std::size_t size, KMemoryState state) co
2005 } 2003 }
2006} 2004}
2007 2005
2008ResultCode KPageTable::CheckMemoryState(const KMemoryInfo& info, KMemoryState state_mask, 2006Result KPageTable::CheckMemoryState(const KMemoryInfo& info, KMemoryState state_mask,
2009 KMemoryState state, KMemoryPermission perm_mask, 2007 KMemoryState state, KMemoryPermission perm_mask,
2010 KMemoryPermission perm, KMemoryAttribute attr_mask, 2008 KMemoryPermission perm, KMemoryAttribute attr_mask,
2011 KMemoryAttribute attr) const { 2009 KMemoryAttribute attr) const {
2012 // Validate the states match expectation. 2010 // Validate the states match expectation.
2013 R_UNLESS((info.state & state_mask) == state, ResultInvalidCurrentMemory); 2011 R_UNLESS((info.state & state_mask) == state, ResultInvalidCurrentMemory);
2014 R_UNLESS((info.perm & perm_mask) == perm, ResultInvalidCurrentMemory); 2012 R_UNLESS((info.perm & perm_mask) == perm, ResultInvalidCurrentMemory);
@@ -2017,12 +2015,11 @@ ResultCode KPageTable::CheckMemoryState(const KMemoryInfo& info, KMemoryState st
2017 return ResultSuccess; 2015 return ResultSuccess;
2018} 2016}
2019 2017
2020ResultCode KPageTable::CheckMemoryStateContiguous(std::size_t* out_blocks_needed, VAddr addr, 2018Result KPageTable::CheckMemoryStateContiguous(std::size_t* out_blocks_needed, VAddr addr,
2021 std::size_t size, KMemoryState state_mask, 2019 std::size_t size, KMemoryState state_mask,
2022 KMemoryState state, KMemoryPermission perm_mask, 2020 KMemoryState state, KMemoryPermission perm_mask,
2023 KMemoryPermission perm, 2021 KMemoryPermission perm, KMemoryAttribute attr_mask,
2024 KMemoryAttribute attr_mask, 2022 KMemoryAttribute attr) const {
2025 KMemoryAttribute attr) const {
2026 ASSERT(this->IsLockedByCurrentThread()); 2023 ASSERT(this->IsLockedByCurrentThread());
2027 2024
2028 // Get information about the first block. 2025 // Get information about the first block.
@@ -2060,12 +2057,12 @@ ResultCode KPageTable::CheckMemoryStateContiguous(std::size_t* out_blocks_needed
2060 return ResultSuccess; 2057 return ResultSuccess;
2061} 2058}
2062 2059
2063ResultCode KPageTable::CheckMemoryState(KMemoryState* out_state, KMemoryPermission* out_perm, 2060Result KPageTable::CheckMemoryState(KMemoryState* out_state, KMemoryPermission* out_perm,
2064 KMemoryAttribute* out_attr, std::size_t* out_blocks_needed, 2061 KMemoryAttribute* out_attr, std::size_t* out_blocks_needed,
2065 VAddr addr, std::size_t size, KMemoryState state_mask, 2062 VAddr addr, std::size_t size, KMemoryState state_mask,
2066 KMemoryState state, KMemoryPermission perm_mask, 2063 KMemoryState state, KMemoryPermission perm_mask,
2067 KMemoryPermission perm, KMemoryAttribute attr_mask, 2064 KMemoryPermission perm, KMemoryAttribute attr_mask,
2068 KMemoryAttribute attr, KMemoryAttribute ignore_attr) const { 2065 KMemoryAttribute attr, KMemoryAttribute ignore_attr) const {
2069 ASSERT(this->IsLockedByCurrentThread()); 2066 ASSERT(this->IsLockedByCurrentThread());
2070 2067
2071 // Get information about the first block. 2068 // Get information about the first block.
@@ -2122,11 +2119,11 @@ ResultCode KPageTable::CheckMemoryState(KMemoryState* out_state, KMemoryPermissi
2122 return ResultSuccess; 2119 return ResultSuccess;
2123} 2120}
2124 2121
2125ResultCode KPageTable::LockMemoryAndOpen(KPageLinkedList* out_pg, PAddr* out_paddr, VAddr addr, 2122Result KPageTable::LockMemoryAndOpen(KPageGroup* out_pg, PAddr* out_paddr, VAddr addr, size_t size,
2126 size_t size, KMemoryState state_mask, KMemoryState state, 2123 KMemoryState state_mask, KMemoryState state,
2127 KMemoryPermission perm_mask, KMemoryPermission perm, 2124 KMemoryPermission perm_mask, KMemoryPermission perm,
2128 KMemoryAttribute attr_mask, KMemoryAttribute attr, 2125 KMemoryAttribute attr_mask, KMemoryAttribute attr,
2129 KMemoryPermission new_perm, KMemoryAttribute lock_attr) { 2126 KMemoryPermission new_perm, KMemoryAttribute lock_attr) {
2130 // Validate basic preconditions. 2127 // Validate basic preconditions.
2131 ASSERT((lock_attr & attr) == KMemoryAttribute::None); 2128 ASSERT((lock_attr & attr) == KMemoryAttribute::None);
2132 ASSERT((lock_attr & (KMemoryAttribute::IpcLocked | KMemoryAttribute::DeviceShared)) == 2129 ASSERT((lock_attr & (KMemoryAttribute::IpcLocked | KMemoryAttribute::DeviceShared)) ==
@@ -2180,11 +2177,11 @@ ResultCode KPageTable::LockMemoryAndOpen(KPageLinkedList* out_pg, PAddr* out_pad
2180 return ResultSuccess; 2177 return ResultSuccess;
2181} 2178}
2182 2179
2183ResultCode KPageTable::UnlockMemory(VAddr addr, size_t size, KMemoryState state_mask, 2180Result KPageTable::UnlockMemory(VAddr addr, size_t size, KMemoryState state_mask,
2184 KMemoryState state, KMemoryPermission perm_mask, 2181 KMemoryState state, KMemoryPermission perm_mask,
2185 KMemoryPermission perm, KMemoryAttribute attr_mask, 2182 KMemoryPermission perm, KMemoryAttribute attr_mask,
2186 KMemoryAttribute attr, KMemoryPermission new_perm, 2183 KMemoryAttribute attr, KMemoryPermission new_perm,
2187 KMemoryAttribute lock_attr, const KPageLinkedList* pg) { 2184 KMemoryAttribute lock_attr, const KPageGroup* pg) {
2188 // Validate basic preconditions. 2185 // Validate basic preconditions.
2189 ASSERT((attr_mask & lock_attr) == lock_attr); 2186 ASSERT((attr_mask & lock_attr) == lock_attr);
2190 ASSERT((attr & lock_attr) == lock_attr); 2187 ASSERT((attr & lock_attr) == lock_attr);
diff --git a/src/core/hle/kernel/k_page_table.h b/src/core/hle/kernel/k_page_table.h
index 6312eb682..25774f232 100644
--- a/src/core/hle/kernel/k_page_table.h
+++ b/src/core/hle/kernel/k_page_table.h
@@ -33,51 +33,49 @@ public:
33 explicit KPageTable(Core::System& system_); 33 explicit KPageTable(Core::System& system_);
34 ~KPageTable(); 34 ~KPageTable();
35 35
36 ResultCode InitializeForProcess(FileSys::ProgramAddressSpaceType as_type, bool enable_aslr, 36 Result InitializeForProcess(FileSys::ProgramAddressSpaceType as_type, bool enable_aslr,
37 VAddr code_addr, std::size_t code_size, 37 VAddr code_addr, std::size_t code_size, KMemoryManager::Pool pool);
38 KMemoryManager::Pool pool); 38 Result MapProcessCode(VAddr addr, std::size_t pages_count, KMemoryState state,
39 ResultCode MapProcessCode(VAddr addr, std::size_t pages_count, KMemoryState state, 39 KMemoryPermission perm);
40 KMemoryPermission perm); 40 Result MapCodeMemory(VAddr dst_address, VAddr src_address, std::size_t size);
41 ResultCode MapCodeMemory(VAddr dst_address, VAddr src_address, std::size_t size); 41 Result UnmapCodeMemory(VAddr dst_address, VAddr src_address, std::size_t size,
42 ResultCode UnmapCodeMemory(VAddr dst_address, VAddr src_address, std::size_t size, 42 ICacheInvalidationStrategy icache_invalidation_strategy);
43 ICacheInvalidationStrategy icache_invalidation_strategy); 43 Result UnmapProcessMemory(VAddr dst_addr, std::size_t size, KPageTable& src_page_table,
44 ResultCode UnmapProcessMemory(VAddr dst_addr, std::size_t size, KPageTable& src_page_table, 44 VAddr src_addr);
45 VAddr src_addr); 45 Result MapPhysicalMemory(VAddr addr, std::size_t size);
46 ResultCode MapPhysicalMemory(VAddr addr, std::size_t size); 46 Result UnmapPhysicalMemory(VAddr addr, std::size_t size);
47 ResultCode UnmapPhysicalMemory(VAddr addr, std::size_t size); 47 Result MapMemory(VAddr dst_addr, VAddr src_addr, std::size_t size);
48 ResultCode MapMemory(VAddr dst_addr, VAddr src_addr, std::size_t size); 48 Result UnmapMemory(VAddr dst_addr, VAddr src_addr, std::size_t size);
49 ResultCode UnmapMemory(VAddr dst_addr, VAddr src_addr, std::size_t size); 49 Result MapPages(VAddr addr, KPageGroup& page_linked_list, KMemoryState state,
50 ResultCode MapPages(VAddr addr, KPageLinkedList& page_linked_list, KMemoryState state, 50 KMemoryPermission perm);
51 KMemoryPermission perm); 51 Result MapPages(VAddr* out_addr, std::size_t num_pages, std::size_t alignment, PAddr phys_addr,
52 ResultCode MapPages(VAddr* out_addr, std::size_t num_pages, std::size_t alignment, 52 KMemoryState state, KMemoryPermission perm) {
53 PAddr phys_addr, KMemoryState state, KMemoryPermission perm) {
54 return this->MapPages(out_addr, num_pages, alignment, phys_addr, true, 53 return this->MapPages(out_addr, num_pages, alignment, phys_addr, true,
55 this->GetRegionAddress(state), this->GetRegionSize(state) / PageSize, 54 this->GetRegionAddress(state), this->GetRegionSize(state) / PageSize,
56 state, perm); 55 state, perm);
57 } 56 }
58 ResultCode UnmapPages(VAddr addr, KPageLinkedList& page_linked_list, KMemoryState state); 57 Result UnmapPages(VAddr addr, KPageGroup& page_linked_list, KMemoryState state);
59 ResultCode UnmapPages(VAddr address, std::size_t num_pages, KMemoryState state); 58 Result UnmapPages(VAddr address, std::size_t num_pages, KMemoryState state);
60 ResultCode SetProcessMemoryPermission(VAddr addr, std::size_t size, 59 Result SetProcessMemoryPermission(VAddr addr, std::size_t size, Svc::MemoryPermission svc_perm);
61 Svc::MemoryPermission svc_perm);
62 KMemoryInfo QueryInfo(VAddr addr); 60 KMemoryInfo QueryInfo(VAddr addr);
63 ResultCode ReserveTransferMemory(VAddr addr, std::size_t size, KMemoryPermission perm); 61 Result ReserveTransferMemory(VAddr addr, std::size_t size, KMemoryPermission perm);
64 ResultCode ResetTransferMemory(VAddr addr, std::size_t size); 62 Result ResetTransferMemory(VAddr addr, std::size_t size);
65 ResultCode SetMemoryPermission(VAddr addr, std::size_t size, Svc::MemoryPermission perm); 63 Result SetMemoryPermission(VAddr addr, std::size_t size, Svc::MemoryPermission perm);
66 ResultCode SetMemoryAttribute(VAddr addr, std::size_t size, u32 mask, u32 attr); 64 Result SetMemoryAttribute(VAddr addr, std::size_t size, u32 mask, u32 attr);
67 ResultCode SetMaxHeapSize(std::size_t size); 65 Result SetMaxHeapSize(std::size_t size);
68 ResultCode SetHeapSize(VAddr* out, std::size_t size); 66 Result SetHeapSize(VAddr* out, std::size_t size);
69 ResultVal<VAddr> AllocateAndMapMemory(std::size_t needed_num_pages, std::size_t align, 67 ResultVal<VAddr> AllocateAndMapMemory(std::size_t needed_num_pages, std::size_t align,
70 bool is_map_only, VAddr region_start, 68 bool is_map_only, VAddr region_start,
71 std::size_t region_num_pages, KMemoryState state, 69 std::size_t region_num_pages, KMemoryState state,
72 KMemoryPermission perm, PAddr map_addr = 0); 70 KMemoryPermission perm, PAddr map_addr = 0);
73 ResultCode LockForDeviceAddressSpace(VAddr addr, std::size_t size); 71 Result LockForDeviceAddressSpace(VAddr addr, std::size_t size);
74 ResultCode UnlockForDeviceAddressSpace(VAddr addr, std::size_t size); 72 Result UnlockForDeviceAddressSpace(VAddr addr, std::size_t size);
75 ResultCode LockForCodeMemory(KPageLinkedList* out, VAddr addr, std::size_t size); 73 Result LockForCodeMemory(KPageGroup* out, VAddr addr, std::size_t size);
76 ResultCode UnlockForCodeMemory(VAddr addr, std::size_t size, const KPageLinkedList& pg); 74 Result UnlockForCodeMemory(VAddr addr, std::size_t size, const KPageGroup& pg);
77 ResultCode MakeAndOpenPageGroup(KPageLinkedList* out, VAddr address, size_t num_pages, 75 Result MakeAndOpenPageGroup(KPageGroup* out, VAddr address, size_t num_pages,
78 KMemoryState state_mask, KMemoryState state, 76 KMemoryState state_mask, KMemoryState state,
79 KMemoryPermission perm_mask, KMemoryPermission perm, 77 KMemoryPermission perm_mask, KMemoryPermission perm,
80 KMemoryAttribute attr_mask, KMemoryAttribute attr); 78 KMemoryAttribute attr_mask, KMemoryAttribute attr);
81 79
82 Common::PageTable& PageTableImpl() { 80 Common::PageTable& PageTableImpl() {
83 return page_table_impl; 81 return page_table_impl;
@@ -102,83 +100,78 @@ private:
102 KMemoryAttribute::IpcLocked | 100 KMemoryAttribute::IpcLocked |
103 KMemoryAttribute::DeviceShared; 101 KMemoryAttribute::DeviceShared;
104 102
105 ResultCode InitializeMemoryLayout(VAddr start, VAddr end); 103 Result InitializeMemoryLayout(VAddr start, VAddr end);
106 ResultCode MapPages(VAddr addr, const KPageLinkedList& page_linked_list, 104 Result MapPages(VAddr addr, const KPageGroup& page_linked_list, KMemoryPermission perm);
107 KMemoryPermission perm); 105 Result MapPages(VAddr* out_addr, std::size_t num_pages, std::size_t alignment, PAddr phys_addr,
108 ResultCode MapPages(VAddr* out_addr, std::size_t num_pages, std::size_t alignment, 106 bool is_pa_valid, VAddr region_start, std::size_t region_num_pages,
109 PAddr phys_addr, bool is_pa_valid, VAddr region_start, 107 KMemoryState state, KMemoryPermission perm);
110 std::size_t region_num_pages, KMemoryState state, KMemoryPermission perm); 108 Result UnmapPages(VAddr addr, const KPageGroup& page_linked_list);
111 ResultCode UnmapPages(VAddr addr, const KPageLinkedList& page_linked_list);
112 bool IsRegionMapped(VAddr address, u64 size); 109 bool IsRegionMapped(VAddr address, u64 size);
113 bool IsRegionContiguous(VAddr addr, u64 size) const; 110 bool IsRegionContiguous(VAddr addr, u64 size) const;
114 void AddRegionToPages(VAddr start, std::size_t num_pages, KPageLinkedList& page_linked_list); 111 void AddRegionToPages(VAddr start, std::size_t num_pages, KPageGroup& page_linked_list);
115 KMemoryInfo QueryInfoImpl(VAddr addr); 112 KMemoryInfo QueryInfoImpl(VAddr addr);
116 VAddr AllocateVirtualMemory(VAddr start, std::size_t region_num_pages, u64 needed_num_pages, 113 VAddr AllocateVirtualMemory(VAddr start, std::size_t region_num_pages, u64 needed_num_pages,
117 std::size_t align); 114 std::size_t align);
118 ResultCode Operate(VAddr addr, std::size_t num_pages, const KPageLinkedList& page_group, 115 Result Operate(VAddr addr, std::size_t num_pages, const KPageGroup& page_group,
119 OperationType operation); 116 OperationType operation);
120 ResultCode Operate(VAddr addr, std::size_t num_pages, KMemoryPermission perm, 117 Result Operate(VAddr addr, std::size_t num_pages, KMemoryPermission perm,
121 OperationType operation, PAddr map_addr = 0); 118 OperationType operation, PAddr map_addr = 0);
122 VAddr GetRegionAddress(KMemoryState state) const; 119 VAddr GetRegionAddress(KMemoryState state) const;
123 std::size_t GetRegionSize(KMemoryState state) const; 120 std::size_t GetRegionSize(KMemoryState state) const;
124 121
125 VAddr FindFreeArea(VAddr region_start, std::size_t region_num_pages, std::size_t num_pages, 122 VAddr FindFreeArea(VAddr region_start, std::size_t region_num_pages, std::size_t num_pages,
126 std::size_t alignment, std::size_t offset, std::size_t guard_pages); 123 std::size_t alignment, std::size_t offset, std::size_t guard_pages);
127 124
128 ResultCode CheckMemoryStateContiguous(std::size_t* out_blocks_needed, VAddr addr, 125 Result CheckMemoryStateContiguous(std::size_t* out_blocks_needed, VAddr addr, std::size_t size,
129 std::size_t size, KMemoryState state_mask, 126 KMemoryState state_mask, KMemoryState state,
130 KMemoryState state, KMemoryPermission perm_mask, 127 KMemoryPermission perm_mask, KMemoryPermission perm,
131 KMemoryPermission perm, KMemoryAttribute attr_mask, 128 KMemoryAttribute attr_mask, KMemoryAttribute attr) const;
132 KMemoryAttribute attr) const; 129 Result CheckMemoryStateContiguous(VAddr addr, std::size_t size, KMemoryState state_mask,
133 ResultCode CheckMemoryStateContiguous(VAddr addr, std::size_t size, KMemoryState state_mask, 130 KMemoryState state, KMemoryPermission perm_mask,
134 KMemoryState state, KMemoryPermission perm_mask, 131 KMemoryPermission perm, KMemoryAttribute attr_mask,
135 KMemoryPermission perm, KMemoryAttribute attr_mask, 132 KMemoryAttribute attr) const {
136 KMemoryAttribute attr) const {
137 return this->CheckMemoryStateContiguous(nullptr, addr, size, state_mask, state, perm_mask, 133 return this->CheckMemoryStateContiguous(nullptr, addr, size, state_mask, state, perm_mask,
138 perm, attr_mask, attr); 134 perm, attr_mask, attr);
139 } 135 }
140 136
141 ResultCode CheckMemoryState(const KMemoryInfo& info, KMemoryState state_mask, 137 Result CheckMemoryState(const KMemoryInfo& info, KMemoryState state_mask, KMemoryState state,
142 KMemoryState state, KMemoryPermission perm_mask, 138 KMemoryPermission perm_mask, KMemoryPermission perm,
143 KMemoryPermission perm, KMemoryAttribute attr_mask, 139 KMemoryAttribute attr_mask, KMemoryAttribute attr) const;
144 KMemoryAttribute attr) const; 140 Result CheckMemoryState(KMemoryState* out_state, KMemoryPermission* out_perm,
145 ResultCode CheckMemoryState(KMemoryState* out_state, KMemoryPermission* out_perm, 141 KMemoryAttribute* out_attr, std::size_t* out_blocks_needed, VAddr addr,
146 KMemoryAttribute* out_attr, std::size_t* out_blocks_needed, 142 std::size_t size, KMemoryState state_mask, KMemoryState state,
147 VAddr addr, std::size_t size, KMemoryState state_mask, 143 KMemoryPermission perm_mask, KMemoryPermission perm,
148 KMemoryState state, KMemoryPermission perm_mask, 144 KMemoryAttribute attr_mask, KMemoryAttribute attr,
149 KMemoryPermission perm, KMemoryAttribute attr_mask, 145 KMemoryAttribute ignore_attr = DefaultMemoryIgnoreAttr) const;
150 KMemoryAttribute attr, 146 Result CheckMemoryState(std::size_t* out_blocks_needed, VAddr addr, std::size_t size,
151 KMemoryAttribute ignore_attr = DefaultMemoryIgnoreAttr) const; 147 KMemoryState state_mask, KMemoryState state,
152 ResultCode CheckMemoryState(std::size_t* out_blocks_needed, VAddr addr, std::size_t size, 148 KMemoryPermission perm_mask, KMemoryPermission perm,
153 KMemoryState state_mask, KMemoryState state, 149 KMemoryAttribute attr_mask, KMemoryAttribute attr,
154 KMemoryPermission perm_mask, KMemoryPermission perm, 150 KMemoryAttribute ignore_attr = DefaultMemoryIgnoreAttr) const {
155 KMemoryAttribute attr_mask, KMemoryAttribute attr,
156 KMemoryAttribute ignore_attr = DefaultMemoryIgnoreAttr) const {
157 return CheckMemoryState(nullptr, nullptr, nullptr, out_blocks_needed, addr, size, 151 return CheckMemoryState(nullptr, nullptr, nullptr, out_blocks_needed, addr, size,
158 state_mask, state, perm_mask, perm, attr_mask, attr, ignore_attr); 152 state_mask, state, perm_mask, perm, attr_mask, attr, ignore_attr);
159 } 153 }
160 ResultCode CheckMemoryState(VAddr addr, std::size_t size, KMemoryState state_mask, 154 Result CheckMemoryState(VAddr addr, std::size_t size, KMemoryState state_mask,
161 KMemoryState state, KMemoryPermission perm_mask, 155 KMemoryState state, KMemoryPermission perm_mask, KMemoryPermission perm,
162 KMemoryPermission perm, KMemoryAttribute attr_mask, 156 KMemoryAttribute attr_mask, KMemoryAttribute attr,
163 KMemoryAttribute attr, 157 KMemoryAttribute ignore_attr = DefaultMemoryIgnoreAttr) const {
164 KMemoryAttribute ignore_attr = DefaultMemoryIgnoreAttr) const {
165 return this->CheckMemoryState(nullptr, addr, size, state_mask, state, perm_mask, perm, 158 return this->CheckMemoryState(nullptr, addr, size, state_mask, state, perm_mask, perm,
166 attr_mask, attr, ignore_attr); 159 attr_mask, attr, ignore_attr);
167 } 160 }
168 161
169 ResultCode LockMemoryAndOpen(KPageLinkedList* out_pg, PAddr* out_paddr, VAddr addr, size_t size, 162 Result LockMemoryAndOpen(KPageGroup* out_pg, PAddr* out_paddr, VAddr addr, size_t size,
170 KMemoryState state_mask, KMemoryState state, 163 KMemoryState state_mask, KMemoryState state,
171 KMemoryPermission perm_mask, KMemoryPermission perm, 164 KMemoryPermission perm_mask, KMemoryPermission perm,
172 KMemoryAttribute attr_mask, KMemoryAttribute attr, 165 KMemoryAttribute attr_mask, KMemoryAttribute attr,
173 KMemoryPermission new_perm, KMemoryAttribute lock_attr); 166 KMemoryPermission new_perm, KMemoryAttribute lock_attr);
174 ResultCode UnlockMemory(VAddr addr, size_t size, KMemoryState state_mask, KMemoryState state, 167 Result UnlockMemory(VAddr addr, size_t size, KMemoryState state_mask, KMemoryState state,
175 KMemoryPermission perm_mask, KMemoryPermission perm, 168 KMemoryPermission perm_mask, KMemoryPermission perm,
176 KMemoryAttribute attr_mask, KMemoryAttribute attr, 169 KMemoryAttribute attr_mask, KMemoryAttribute attr,
177 KMemoryPermission new_perm, KMemoryAttribute lock_attr, 170 KMemoryPermission new_perm, KMemoryAttribute lock_attr,
178 const KPageLinkedList* pg); 171 const KPageGroup* pg);
179 172
180 ResultCode MakePageGroup(KPageLinkedList& pg, VAddr addr, size_t num_pages); 173 Result MakePageGroup(KPageGroup& pg, VAddr addr, size_t num_pages);
181 bool IsValidPageGroup(const KPageLinkedList& pg, VAddr addr, size_t num_pages); 174 bool IsValidPageGroup(const KPageGroup& pg, VAddr addr, size_t num_pages);
182 175
183 bool IsLockedByCurrentThread() const { 176 bool IsLockedByCurrentThread() const {
184 return general_lock.IsLockedByCurrentThread(); 177 return general_lock.IsLockedByCurrentThread();
diff --git a/src/core/hle/kernel/k_port.cpp b/src/core/hle/kernel/k_port.cpp
index 51c2cd1ef..7a5a9dc2a 100644
--- a/src/core/hle/kernel/k_port.cpp
+++ b/src/core/hle/kernel/k_port.cpp
@@ -50,7 +50,7 @@ bool KPort::IsServerClosed() const {
50 return state == State::ServerClosed; 50 return state == State::ServerClosed;
51} 51}
52 52
53ResultCode KPort::EnqueueSession(KServerSession* session) { 53Result KPort::EnqueueSession(KServerSession* session) {
54 KScopedSchedulerLock sl{kernel}; 54 KScopedSchedulerLock sl{kernel};
55 55
56 R_UNLESS(state == State::Normal, ResultPortClosed); 56 R_UNLESS(state == State::Normal, ResultPortClosed);
diff --git a/src/core/hle/kernel/k_port.h b/src/core/hle/kernel/k_port.h
index 1bfecf8c3..0cfc16dab 100644
--- a/src/core/hle/kernel/k_port.h
+++ b/src/core/hle/kernel/k_port.h
@@ -34,7 +34,7 @@ public:
34 34
35 bool IsServerClosed() const; 35 bool IsServerClosed() const;
36 36
37 ResultCode EnqueueSession(KServerSession* session); 37 Result EnqueueSession(KServerSession* session);
38 38
39 KClientPort& GetClientPort() { 39 KClientPort& GetClientPort() {
40 return client; 40 return client;
diff --git a/src/core/hle/kernel/k_process.cpp b/src/core/hle/kernel/k_process.cpp
index 77356e592..b662788b3 100644
--- a/src/core/hle/kernel/k_process.cpp
+++ b/src/core/hle/kernel/k_process.cpp
@@ -67,8 +67,8 @@ void SetupMainThread(Core::System& system, KProcess& owner_process, u32 priority
67} 67}
68} // Anonymous namespace 68} // Anonymous namespace
69 69
70ResultCode KProcess::Initialize(KProcess* process, Core::System& system, std::string process_name, 70Result KProcess::Initialize(KProcess* process, Core::System& system, std::string process_name,
71 ProcessType type, KResourceLimit* res_limit) { 71 ProcessType type, KResourceLimit* res_limit) {
72 auto& kernel = system.Kernel(); 72 auto& kernel = system.Kernel();
73 73
74 process->name = std::move(process_name); 74 process->name = std::move(process_name);
@@ -176,7 +176,8 @@ void KProcess::PinCurrentThread(s32 core_id) {
176 ASSERT(kernel.GlobalSchedulerContext().IsLocked()); 176 ASSERT(kernel.GlobalSchedulerContext().IsLocked());
177 177
178 // Get the current thread. 178 // Get the current thread.
179 KThread* cur_thread = kernel.Scheduler(static_cast<std::size_t>(core_id)).GetCurrentThread(); 179 KThread* cur_thread =
180 kernel.Scheduler(static_cast<std::size_t>(core_id)).GetSchedulerCurrentThread();
180 181
181 // If the thread isn't terminated, pin it. 182 // If the thread isn't terminated, pin it.
182 if (!cur_thread->IsTerminationRequested()) { 183 if (!cur_thread->IsTerminationRequested()) {
@@ -193,7 +194,8 @@ void KProcess::UnpinCurrentThread(s32 core_id) {
193 ASSERT(kernel.GlobalSchedulerContext().IsLocked()); 194 ASSERT(kernel.GlobalSchedulerContext().IsLocked());
194 195
195 // Get the current thread. 196 // Get the current thread.
196 KThread* cur_thread = kernel.Scheduler(static_cast<std::size_t>(core_id)).GetCurrentThread(); 197 KThread* cur_thread =
198 kernel.Scheduler(static_cast<std::size_t>(core_id)).GetSchedulerCurrentThread();
197 199
198 // Unpin it. 200 // Unpin it.
199 cur_thread->Unpin(); 201 cur_thread->Unpin();
@@ -217,8 +219,8 @@ void KProcess::UnpinThread(KThread* thread) {
217 KScheduler::SetSchedulerUpdateNeeded(kernel); 219 KScheduler::SetSchedulerUpdateNeeded(kernel);
218} 220}
219 221
220ResultCode KProcess::AddSharedMemory(KSharedMemory* shmem, [[maybe_unused]] VAddr address, 222Result KProcess::AddSharedMemory(KSharedMemory* shmem, [[maybe_unused]] VAddr address,
221 [[maybe_unused]] size_t size) { 223 [[maybe_unused]] size_t size) {
222 // Lock ourselves, to prevent concurrent access. 224 // Lock ourselves, to prevent concurrent access.
223 KScopedLightLock lk(state_lock); 225 KScopedLightLock lk(state_lock);
224 226
@@ -282,7 +284,7 @@ void KProcess::UnregisterThread(KThread* thread) {
282 thread_list.remove(thread); 284 thread_list.remove(thread);
283} 285}
284 286
285ResultCode KProcess::Reset() { 287Result KProcess::Reset() {
286 // Lock the process and the scheduler. 288 // Lock the process and the scheduler.
287 KScopedLightLock lk(state_lock); 289 KScopedLightLock lk(state_lock);
288 KScopedSchedulerLock sl{kernel}; 290 KScopedSchedulerLock sl{kernel};
@@ -296,7 +298,7 @@ ResultCode KProcess::Reset() {
296 return ResultSuccess; 298 return ResultSuccess;
297} 299}
298 300
299ResultCode KProcess::SetActivity(ProcessActivity activity) { 301Result KProcess::SetActivity(ProcessActivity activity) {
300 // Lock ourselves and the scheduler. 302 // Lock ourselves and the scheduler.
301 KScopedLightLock lk{state_lock}; 303 KScopedLightLock lk{state_lock};
302 KScopedLightLock list_lk{list_lock}; 304 KScopedLightLock list_lk{list_lock};
@@ -340,8 +342,7 @@ ResultCode KProcess::SetActivity(ProcessActivity activity) {
340 return ResultSuccess; 342 return ResultSuccess;
341} 343}
342 344
343ResultCode KProcess::LoadFromMetadata(const FileSys::ProgramMetadata& metadata, 345Result KProcess::LoadFromMetadata(const FileSys::ProgramMetadata& metadata, std::size_t code_size) {
344 std::size_t code_size) {
345 program_id = metadata.GetTitleID(); 346 program_id = metadata.GetTitleID();
346 ideal_core = metadata.GetMainThreadCore(); 347 ideal_core = metadata.GetMainThreadCore();
347 is_64bit_process = metadata.Is64BitProgram(); 348 is_64bit_process = metadata.Is64BitProgram();
@@ -356,24 +357,24 @@ ResultCode KProcess::LoadFromMetadata(const FileSys::ProgramMetadata& metadata,
356 return ResultLimitReached; 357 return ResultLimitReached;
357 } 358 }
358 // Initialize proces address space 359 // Initialize proces address space
359 if (const ResultCode result{ 360 if (const Result result{page_table->InitializeForProcess(metadata.GetAddressSpaceType(), false,
360 page_table->InitializeForProcess(metadata.GetAddressSpaceType(), false, 0x8000000, 361 0x8000000, code_size,
361 code_size, KMemoryManager::Pool::Application)}; 362 KMemoryManager::Pool::Application)};
362 result.IsError()) { 363 result.IsError()) {
363 return result; 364 return result;
364 } 365 }
365 366
366 // Map process code region 367 // Map process code region
367 if (const ResultCode result{page_table->MapProcessCode(page_table->GetCodeRegionStart(), 368 if (const Result result{page_table->MapProcessCode(page_table->GetCodeRegionStart(),
368 code_size / PageSize, KMemoryState::Code, 369 code_size / PageSize, KMemoryState::Code,
369 KMemoryPermission::None)}; 370 KMemoryPermission::None)};
370 result.IsError()) { 371 result.IsError()) {
371 return result; 372 return result;
372 } 373 }
373 374
374 // Initialize process capabilities 375 // Initialize process capabilities
375 const auto& caps{metadata.GetKernelCapabilities()}; 376 const auto& caps{metadata.GetKernelCapabilities()};
376 if (const ResultCode result{ 377 if (const Result result{
377 capabilities.InitializeForUserProcess(caps.data(), caps.size(), *page_table)}; 378 capabilities.InitializeForUserProcess(caps.data(), caps.size(), *page_table)};
378 result.IsError()) { 379 result.IsError()) {
379 return result; 380 return result;
@@ -420,11 +421,11 @@ void KProcess::PrepareForTermination() {
420 ChangeStatus(ProcessStatus::Exiting); 421 ChangeStatus(ProcessStatus::Exiting);
421 422
422 const auto stop_threads = [this](const std::vector<KThread*>& in_thread_list) { 423 const auto stop_threads = [this](const std::vector<KThread*>& in_thread_list) {
423 for (auto& thread : in_thread_list) { 424 for (auto* thread : in_thread_list) {
424 if (thread->GetOwnerProcess() != this) 425 if (thread->GetOwnerProcess() != this)
425 continue; 426 continue;
426 427
427 if (thread == kernel.CurrentScheduler()->GetCurrentThread()) 428 if (thread == GetCurrentThreadPointer(kernel))
428 continue; 429 continue;
429 430
430 // TODO(Subv): When are the other running/ready threads terminated? 431 // TODO(Subv): When are the other running/ready threads terminated?
@@ -480,7 +481,7 @@ void KProcess::Finalize() {
480 KAutoObjectWithSlabHeapAndContainer<KProcess, KWorkerTask>::Finalize(); 481 KAutoObjectWithSlabHeapAndContainer<KProcess, KWorkerTask>::Finalize();
481} 482}
482 483
483ResultCode KProcess::CreateThreadLocalRegion(VAddr* out) { 484Result KProcess::CreateThreadLocalRegion(VAddr* out) {
484 KThreadLocalPage* tlp = nullptr; 485 KThreadLocalPage* tlp = nullptr;
485 VAddr tlr = 0; 486 VAddr tlr = 0;
486 487
@@ -531,7 +532,7 @@ ResultCode KProcess::CreateThreadLocalRegion(VAddr* out) {
531 return ResultSuccess; 532 return ResultSuccess;
532} 533}
533 534
534ResultCode KProcess::DeleteThreadLocalRegion(VAddr addr) { 535Result KProcess::DeleteThreadLocalRegion(VAddr addr) {
535 KThreadLocalPage* page_to_free = nullptr; 536 KThreadLocalPage* page_to_free = nullptr;
536 537
537 // Release the region. 538 // Release the region.
@@ -662,7 +663,7 @@ void KProcess::ChangeStatus(ProcessStatus new_status) {
662 NotifyAvailable(); 663 NotifyAvailable();
663} 664}
664 665
665ResultCode KProcess::AllocateMainThreadStack(std::size_t stack_size) { 666Result KProcess::AllocateMainThreadStack(std::size_t stack_size) {
666 ASSERT(stack_size); 667 ASSERT(stack_size);
667 668
668 // The kernel always ensures that the given stack size is page aligned. 669 // The kernel always ensures that the given stack size is page aligned.
diff --git a/src/core/hle/kernel/k_process.h b/src/core/hle/kernel/k_process.h
index c2086e5ba..5e3e22ad8 100644
--- a/src/core/hle/kernel/k_process.h
+++ b/src/core/hle/kernel/k_process.h
@@ -110,8 +110,8 @@ public:
110 110
111 static constexpr std::size_t RANDOM_ENTROPY_SIZE = 4; 111 static constexpr std::size_t RANDOM_ENTROPY_SIZE = 4;
112 112
113 static ResultCode Initialize(KProcess* process, Core::System& system, std::string process_name, 113 static Result Initialize(KProcess* process, Core::System& system, std::string process_name,
114 ProcessType type, KResourceLimit* res_limit); 114 ProcessType type, KResourceLimit* res_limit);
115 115
116 /// Gets a reference to the process' page table. 116 /// Gets a reference to the process' page table.
117 KPageTable& PageTable() { 117 KPageTable& PageTable() {
@@ -133,11 +133,11 @@ public:
133 return handle_table; 133 return handle_table;
134 } 134 }
135 135
136 ResultCode SignalToAddress(VAddr address) { 136 Result SignalToAddress(VAddr address) {
137 return condition_var.SignalToAddress(address); 137 return condition_var.SignalToAddress(address);
138 } 138 }
139 139
140 ResultCode WaitForAddress(Handle handle, VAddr address, u32 tag) { 140 Result WaitForAddress(Handle handle, VAddr address, u32 tag) {
141 return condition_var.WaitForAddress(handle, address, tag); 141 return condition_var.WaitForAddress(handle, address, tag);
142 } 142 }
143 143
@@ -145,17 +145,16 @@ public:
145 return condition_var.Signal(cv_key, count); 145 return condition_var.Signal(cv_key, count);
146 } 146 }
147 147
148 ResultCode WaitConditionVariable(VAddr address, u64 cv_key, u32 tag, s64 ns) { 148 Result WaitConditionVariable(VAddr address, u64 cv_key, u32 tag, s64 ns) {
149 return condition_var.Wait(address, cv_key, tag, ns); 149 return condition_var.Wait(address, cv_key, tag, ns);
150 } 150 }
151 151
152 ResultCode SignalAddressArbiter(VAddr address, Svc::SignalType signal_type, s32 value, 152 Result SignalAddressArbiter(VAddr address, Svc::SignalType signal_type, s32 value, s32 count) {
153 s32 count) {
154 return address_arbiter.SignalToAddress(address, signal_type, value, count); 153 return address_arbiter.SignalToAddress(address, signal_type, value, count);
155 } 154 }
156 155
157 ResultCode WaitAddressArbiter(VAddr address, Svc::ArbitrationType arb_type, s32 value, 156 Result WaitAddressArbiter(VAddr address, Svc::ArbitrationType arb_type, s32 value,
158 s64 timeout) { 157 s64 timeout) {
159 return address_arbiter.WaitForAddress(address, arb_type, value, timeout); 158 return address_arbiter.WaitForAddress(address, arb_type, value, timeout);
160 } 159 }
161 160
@@ -322,7 +321,7 @@ public:
322 /// @pre The process must be in a signaled state. If this is called on a 321 /// @pre The process must be in a signaled state. If this is called on a
323 /// process instance that is not signaled, ERR_INVALID_STATE will be 322 /// process instance that is not signaled, ERR_INVALID_STATE will be
324 /// returned. 323 /// returned.
325 ResultCode Reset(); 324 Result Reset();
326 325
327 /** 326 /**
328 * Loads process-specifics configuration info with metadata provided 327 * Loads process-specifics configuration info with metadata provided
@@ -333,7 +332,7 @@ public:
333 * @returns ResultSuccess if all relevant metadata was able to be 332 * @returns ResultSuccess if all relevant metadata was able to be
334 * loaded and parsed. Otherwise, an error code is returned. 333 * loaded and parsed. Otherwise, an error code is returned.
335 */ 334 */
336 ResultCode LoadFromMetadata(const FileSys::ProgramMetadata& metadata, std::size_t code_size); 335 Result LoadFromMetadata(const FileSys::ProgramMetadata& metadata, std::size_t code_size);
337 336
338 /** 337 /**
339 * Starts the main application thread for this process. 338 * Starts the main application thread for this process.
@@ -367,7 +366,7 @@ public:
367 366
368 void DoWorkerTaskImpl(); 367 void DoWorkerTaskImpl();
369 368
370 ResultCode SetActivity(ProcessActivity activity); 369 Result SetActivity(ProcessActivity activity);
371 370
372 void PinCurrentThread(s32 core_id); 371 void PinCurrentThread(s32 core_id);
373 void UnpinCurrentThread(s32 core_id); 372 void UnpinCurrentThread(s32 core_id);
@@ -377,17 +376,17 @@ public:
377 return state_lock; 376 return state_lock;
378 } 377 }
379 378
380 ResultCode AddSharedMemory(KSharedMemory* shmem, VAddr address, size_t size); 379 Result AddSharedMemory(KSharedMemory* shmem, VAddr address, size_t size);
381 void RemoveSharedMemory(KSharedMemory* shmem, VAddr address, size_t size); 380 void RemoveSharedMemory(KSharedMemory* shmem, VAddr address, size_t size);
382 381
383 /////////////////////////////////////////////////////////////////////////////////////////////// 382 ///////////////////////////////////////////////////////////////////////////////////////////////
384 // Thread-local storage management 383 // Thread-local storage management
385 384
386 // Marks the next available region as used and returns the address of the slot. 385 // Marks the next available region as used and returns the address of the slot.
387 [[nodiscard]] ResultCode CreateThreadLocalRegion(VAddr* out); 386 [[nodiscard]] Result CreateThreadLocalRegion(VAddr* out);
388 387
389 // Frees a used TLS slot identified by the given address 388 // Frees a used TLS slot identified by the given address
390 ResultCode DeleteThreadLocalRegion(VAddr addr); 389 Result DeleteThreadLocalRegion(VAddr addr);
391 390
392 /////////////////////////////////////////////////////////////////////////////////////////////// 391 ///////////////////////////////////////////////////////////////////////////////////////////////
393 // Debug watchpoint management 392 // Debug watchpoint management
@@ -423,7 +422,7 @@ private:
423 void ChangeStatus(ProcessStatus new_status); 422 void ChangeStatus(ProcessStatus new_status);
424 423
425 /// Allocates the main thread stack for the process, given the stack size in bytes. 424 /// Allocates the main thread stack for the process, given the stack size in bytes.
426 ResultCode AllocateMainThreadStack(std::size_t stack_size); 425 Result AllocateMainThreadStack(std::size_t stack_size);
427 426
428 /// Memory manager for this process 427 /// Memory manager for this process
429 std::unique_ptr<KPageTable> page_table; 428 std::unique_ptr<KPageTable> page_table;
diff --git a/src/core/hle/kernel/k_readable_event.cpp b/src/core/hle/kernel/k_readable_event.cpp
index dddba554d..94c5464fe 100644
--- a/src/core/hle/kernel/k_readable_event.cpp
+++ b/src/core/hle/kernel/k_readable_event.cpp
@@ -27,7 +27,7 @@ void KReadableEvent::Destroy() {
27 } 27 }
28} 28}
29 29
30ResultCode KReadableEvent::Signal() { 30Result KReadableEvent::Signal() {
31 KScopedSchedulerLock lk{kernel}; 31 KScopedSchedulerLock lk{kernel};
32 32
33 if (!is_signaled) { 33 if (!is_signaled) {
@@ -38,13 +38,13 @@ ResultCode KReadableEvent::Signal() {
38 return ResultSuccess; 38 return ResultSuccess;
39} 39}
40 40
41ResultCode KReadableEvent::Clear() { 41Result KReadableEvent::Clear() {
42 Reset(); 42 Reset();
43 43
44 return ResultSuccess; 44 return ResultSuccess;
45} 45}
46 46
47ResultCode KReadableEvent::Reset() { 47Result KReadableEvent::Reset() {
48 KScopedSchedulerLock lk{kernel}; 48 KScopedSchedulerLock lk{kernel};
49 49
50 if (!is_signaled) { 50 if (!is_signaled) {
diff --git a/src/core/hle/kernel/k_readable_event.h b/src/core/hle/kernel/k_readable_event.h
index 5065c7cc0..18dcad289 100644
--- a/src/core/hle/kernel/k_readable_event.h
+++ b/src/core/hle/kernel/k_readable_event.h
@@ -33,9 +33,9 @@ public:
33 bool IsSignaled() const override; 33 bool IsSignaled() const override;
34 void Destroy() override; 34 void Destroy() override;
35 35
36 ResultCode Signal(); 36 Result Signal();
37 ResultCode Clear(); 37 Result Clear();
38 ResultCode Reset(); 38 Result Reset();
39 39
40private: 40private:
41 bool is_signaled{}; 41 bool is_signaled{};
diff --git a/src/core/hle/kernel/k_resource_limit.cpp b/src/core/hle/kernel/k_resource_limit.cpp
index 3e0ecffdb..010dcf99e 100644
--- a/src/core/hle/kernel/k_resource_limit.cpp
+++ b/src/core/hle/kernel/k_resource_limit.cpp
@@ -73,7 +73,7 @@ s64 KResourceLimit::GetFreeValue(LimitableResource which) const {
73 return value; 73 return value;
74} 74}
75 75
76ResultCode KResourceLimit::SetLimitValue(LimitableResource which, s64 value) { 76Result KResourceLimit::SetLimitValue(LimitableResource which, s64 value) {
77 const auto index = static_cast<std::size_t>(which); 77 const auto index = static_cast<std::size_t>(which);
78 KScopedLightLock lk(lock); 78 KScopedLightLock lk(lock);
79 R_UNLESS(current_values[index] <= value, ResultInvalidState); 79 R_UNLESS(current_values[index] <= value, ResultInvalidState);
diff --git a/src/core/hle/kernel/k_resource_limit.h b/src/core/hle/kernel/k_resource_limit.h
index 43bf74b8d..65c98c979 100644
--- a/src/core/hle/kernel/k_resource_limit.h
+++ b/src/core/hle/kernel/k_resource_limit.h
@@ -8,7 +8,7 @@
8#include "core/hle/kernel/k_light_condition_variable.h" 8#include "core/hle/kernel/k_light_condition_variable.h"
9#include "core/hle/kernel/k_light_lock.h" 9#include "core/hle/kernel/k_light_lock.h"
10 10
11union ResultCode; 11union Result;
12 12
13namespace Core::Timing { 13namespace Core::Timing {
14class CoreTiming; 14class CoreTiming;
@@ -46,7 +46,7 @@ public:
46 s64 GetPeakValue(LimitableResource which) const; 46 s64 GetPeakValue(LimitableResource which) const;
47 s64 GetFreeValue(LimitableResource which) const; 47 s64 GetFreeValue(LimitableResource which) const;
48 48
49 ResultCode SetLimitValue(LimitableResource which, s64 value); 49 Result SetLimitValue(LimitableResource which, s64 value);
50 50
51 bool Reserve(LimitableResource which, s64 value); 51 bool Reserve(LimitableResource which, s64 value);
52 bool Reserve(LimitableResource which, s64 value, s64 timeout); 52 bool Reserve(LimitableResource which, s64 value, s64 timeout);
diff --git a/src/core/hle/kernel/k_scheduler.cpp b/src/core/hle/kernel/k_scheduler.cpp
index fb3b84f3d..d599d2bcb 100644
--- a/src/core/hle/kernel/k_scheduler.cpp
+++ b/src/core/hle/kernel/k_scheduler.cpp
@@ -317,7 +317,7 @@ void KScheduler::RotateScheduledQueue(s32 cpu_core_id, s32 priority) {
317 317
318 { 318 {
319 KThread* best_thread = priority_queue.GetScheduledFront(cpu_core_id); 319 KThread* best_thread = priority_queue.GetScheduledFront(cpu_core_id);
320 if (best_thread == GetCurrentThread()) { 320 if (best_thread == GetCurrentThreadPointer(kernel)) {
321 best_thread = priority_queue.GetScheduledNext(cpu_core_id, best_thread); 321 best_thread = priority_queue.GetScheduledNext(cpu_core_id, best_thread);
322 } 322 }
323 323
@@ -424,7 +424,7 @@ void KScheduler::YieldWithoutCoreMigration(KernelCore& kernel) {
424 ASSERT(kernel.CurrentProcess() != nullptr); 424 ASSERT(kernel.CurrentProcess() != nullptr);
425 425
426 // Get the current thread and process. 426 // Get the current thread and process.
427 KThread& cur_thread = Kernel::GetCurrentThread(kernel); 427 KThread& cur_thread = GetCurrentThread(kernel);
428 KProcess& cur_process = *kernel.CurrentProcess(); 428 KProcess& cur_process = *kernel.CurrentProcess();
429 429
430 // If the thread's yield count matches, there's nothing for us to do. 430 // If the thread's yield count matches, there's nothing for us to do.
@@ -463,7 +463,7 @@ void KScheduler::YieldWithCoreMigration(KernelCore& kernel) {
463 ASSERT(kernel.CurrentProcess() != nullptr); 463 ASSERT(kernel.CurrentProcess() != nullptr);
464 464
465 // Get the current thread and process. 465 // Get the current thread and process.
466 KThread& cur_thread = Kernel::GetCurrentThread(kernel); 466 KThread& cur_thread = GetCurrentThread(kernel);
467 KProcess& cur_process = *kernel.CurrentProcess(); 467 KProcess& cur_process = *kernel.CurrentProcess();
468 468
469 // If the thread's yield count matches, there's nothing for us to do. 469 // If the thread's yield count matches, there's nothing for us to do.
@@ -551,7 +551,7 @@ void KScheduler::YieldToAnyThread(KernelCore& kernel) {
551 ASSERT(kernel.CurrentProcess() != nullptr); 551 ASSERT(kernel.CurrentProcess() != nullptr);
552 552
553 // Get the current thread and process. 553 // Get the current thread and process.
554 KThread& cur_thread = Kernel::GetCurrentThread(kernel); 554 KThread& cur_thread = GetCurrentThread(kernel);
555 KProcess& cur_process = *kernel.CurrentProcess(); 555 KProcess& cur_process = *kernel.CurrentProcess();
556 556
557 // If the thread's yield count matches, there's nothing for us to do. 557 // If the thread's yield count matches, there's nothing for us to do.
@@ -622,7 +622,7 @@ void KScheduler::YieldToAnyThread(KernelCore& kernel) {
622} 622}
623 623
624KScheduler::KScheduler(Core::System& system_, s32 core_id_) : system{system_}, core_id{core_id_} { 624KScheduler::KScheduler(Core::System& system_, s32 core_id_) : system{system_}, core_id{core_id_} {
625 switch_fiber = std::make_shared<Common::Fiber>(OnSwitch, this); 625 switch_fiber = std::make_shared<Common::Fiber>([this] { SwitchToCurrent(); });
626 state.needs_scheduling.store(true); 626 state.needs_scheduling.store(true);
627 state.interrupt_task_thread_runnable = false; 627 state.interrupt_task_thread_runnable = false;
628 state.should_count_idle = false; 628 state.should_count_idle = false;
@@ -642,7 +642,7 @@ KScheduler::~KScheduler() {
642 ASSERT(!idle_thread); 642 ASSERT(!idle_thread);
643} 643}
644 644
645KThread* KScheduler::GetCurrentThread() const { 645KThread* KScheduler::GetSchedulerCurrentThread() const {
646 if (auto result = current_thread.load(); result) { 646 if (auto result = current_thread.load(); result) {
647 return result; 647 return result;
648 } 648 }
@@ -654,7 +654,7 @@ u64 KScheduler::GetLastContextSwitchTicks() const {
654} 654}
655 655
656void KScheduler::RescheduleCurrentCore() { 656void KScheduler::RescheduleCurrentCore() {
657 ASSERT(GetCurrentThread()->GetDisableDispatchCount() == 1); 657 ASSERT(GetCurrentThread(system.Kernel()).GetDisableDispatchCount() == 1);
658 658
659 auto& phys_core = system.Kernel().PhysicalCore(core_id); 659 auto& phys_core = system.Kernel().PhysicalCore(core_id);
660 if (phys_core.IsInterrupted()) { 660 if (phys_core.IsInterrupted()) {
@@ -665,7 +665,7 @@ void KScheduler::RescheduleCurrentCore() {
665 if (state.needs_scheduling.load()) { 665 if (state.needs_scheduling.load()) {
666 Schedule(); 666 Schedule();
667 } else { 667 } else {
668 GetCurrentThread()->EnableDispatch(); 668 GetCurrentThread(system.Kernel()).EnableDispatch();
669 guard.Unlock(); 669 guard.Unlock();
670 } 670 }
671} 671}
@@ -718,13 +718,18 @@ void KScheduler::Reload(KThread* thread) {
718 718
719void KScheduler::SwitchContextStep2() { 719void KScheduler::SwitchContextStep2() {
720 // Load context of new thread 720 // Load context of new thread
721 Reload(GetCurrentThread()); 721 Reload(GetCurrentThreadPointer(system.Kernel()));
722 722
723 RescheduleCurrentCore(); 723 RescheduleCurrentCore();
724} 724}
725 725
726void KScheduler::Schedule() {
727 ASSERT(GetCurrentThread(system.Kernel()).GetDisableDispatchCount() == 1);
728 this->ScheduleImpl();
729}
730
726void KScheduler::ScheduleImpl() { 731void KScheduler::ScheduleImpl() {
727 KThread* previous_thread = GetCurrentThread(); 732 KThread* previous_thread = GetCurrentThreadPointer(system.Kernel());
728 KThread* next_thread = state.highest_priority_thread; 733 KThread* next_thread = state.highest_priority_thread;
729 734
730 state.needs_scheduling.store(false); 735 state.needs_scheduling.store(false);
@@ -762,6 +767,7 @@ void KScheduler::ScheduleImpl() {
762 old_context = &previous_thread->GetHostContext(); 767 old_context = &previous_thread->GetHostContext();
763 768
764 // Set the new thread. 769 // Set the new thread.
770 SetCurrentThread(system.Kernel(), next_thread);
765 current_thread.store(next_thread); 771 current_thread.store(next_thread);
766 772
767 guard.Unlock(); 773 guard.Unlock();
@@ -772,11 +778,6 @@ void KScheduler::ScheduleImpl() {
772 next_scheduler.SwitchContextStep2(); 778 next_scheduler.SwitchContextStep2();
773} 779}
774 780
775void KScheduler::OnSwitch(void* this_scheduler) {
776 KScheduler* sched = static_cast<KScheduler*>(this_scheduler);
777 sched->SwitchToCurrent();
778}
779
780void KScheduler::SwitchToCurrent() { 781void KScheduler::SwitchToCurrent() {
781 while (true) { 782 while (true) {
782 { 783 {
@@ -805,6 +806,7 @@ void KScheduler::SwitchToCurrent() {
805 } 806 }
806 } 807 }
807 auto thread = next_thread ? next_thread : idle_thread; 808 auto thread = next_thread ? next_thread : idle_thread;
809 SetCurrentThread(system.Kernel(), thread);
808 Common::Fiber::YieldTo(switch_fiber, *thread->GetHostContext()); 810 Common::Fiber::YieldTo(switch_fiber, *thread->GetHostContext());
809 } while (!is_switch_pending()); 811 } while (!is_switch_pending());
810 } 812 }
diff --git a/src/core/hle/kernel/k_scheduler.h b/src/core/hle/kernel/k_scheduler.h
index 729e006f2..6a4760eca 100644
--- a/src/core/hle/kernel/k_scheduler.h
+++ b/src/core/hle/kernel/k_scheduler.h
@@ -48,7 +48,7 @@ public:
48 void Reload(KThread* thread); 48 void Reload(KThread* thread);
49 49
50 /// Gets the current running thread 50 /// Gets the current running thread
51 [[nodiscard]] KThread* GetCurrentThread() const; 51 [[nodiscard]] KThread* GetSchedulerCurrentThread() const;
52 52
53 /// Gets the idle thread 53 /// Gets the idle thread
54 [[nodiscard]] KThread* GetIdleThread() const { 54 [[nodiscard]] KThread* GetIdleThread() const {
@@ -57,7 +57,7 @@ public:
57 57
58 /// Returns true if the scheduler is idle 58 /// Returns true if the scheduler is idle
59 [[nodiscard]] bool IsIdle() const { 59 [[nodiscard]] bool IsIdle() const {
60 return GetCurrentThread() == idle_thread; 60 return GetSchedulerCurrentThread() == idle_thread;
61 } 61 }
62 62
63 /// Gets the timestamp for the last context switch in ticks. 63 /// Gets the timestamp for the last context switch in ticks.
@@ -149,10 +149,7 @@ private:
149 149
150 void RotateScheduledQueue(s32 cpu_core_id, s32 priority); 150 void RotateScheduledQueue(s32 cpu_core_id, s32 priority);
151 151
152 void Schedule() { 152 void Schedule();
153 ASSERT(GetCurrentThread()->GetDisableDispatchCount() == 1);
154 this->ScheduleImpl();
155 }
156 153
157 /// Switches the CPU's active thread context to that of the specified thread 154 /// Switches the CPU's active thread context to that of the specified thread
158 void ScheduleImpl(); 155 void ScheduleImpl();
@@ -173,7 +170,6 @@ private:
173 */ 170 */
174 void UpdateLastContextSwitchTime(KThread* thread, KProcess* process); 171 void UpdateLastContextSwitchTime(KThread* thread, KProcess* process);
175 172
176 static void OnSwitch(void* this_scheduler);
177 void SwitchToCurrent(); 173 void SwitchToCurrent();
178 174
179 KThread* prev_thread{}; 175 KThread* prev_thread{};
diff --git a/src/core/hle/kernel/k_server_session.cpp b/src/core/hle/kernel/k_server_session.cpp
index 60f8ed470..802c646a6 100644
--- a/src/core/hle/kernel/k_server_session.cpp
+++ b/src/core/hle/kernel/k_server_session.cpp
@@ -79,7 +79,7 @@ std::size_t KServerSession::NumDomainRequestHandlers() const {
79 return manager->DomainHandlerCount(); 79 return manager->DomainHandlerCount();
80} 80}
81 81
82ResultCode KServerSession::HandleDomainSyncRequest(Kernel::HLERequestContext& context) { 82Result KServerSession::HandleDomainSyncRequest(Kernel::HLERequestContext& context) {
83 if (!context.HasDomainMessageHeader()) { 83 if (!context.HasDomainMessageHeader()) {
84 return ResultSuccess; 84 return ResultSuccess;
85 } 85 }
@@ -123,7 +123,7 @@ ResultCode KServerSession::HandleDomainSyncRequest(Kernel::HLERequestContext& co
123 return ResultSuccess; 123 return ResultSuccess;
124} 124}
125 125
126ResultCode KServerSession::QueueSyncRequest(KThread* thread, Core::Memory::Memory& memory) { 126Result KServerSession::QueueSyncRequest(KThread* thread, Core::Memory::Memory& memory) {
127 u32* cmd_buf{reinterpret_cast<u32*>(memory.GetPointer(thread->GetTLSAddress()))}; 127 u32* cmd_buf{reinterpret_cast<u32*>(memory.GetPointer(thread->GetTLSAddress()))};
128 auto context = std::make_shared<HLERequestContext>(kernel, memory, this, thread); 128 auto context = std::make_shared<HLERequestContext>(kernel, memory, this, thread);
129 129
@@ -143,8 +143,8 @@ ResultCode KServerSession::QueueSyncRequest(KThread* thread, Core::Memory::Memor
143 return ResultSuccess; 143 return ResultSuccess;
144} 144}
145 145
146ResultCode KServerSession::CompleteSyncRequest(HLERequestContext& context) { 146Result KServerSession::CompleteSyncRequest(HLERequestContext& context) {
147 ResultCode result = ResultSuccess; 147 Result result = ResultSuccess;
148 148
149 // If the session has been converted to a domain, handle the domain request 149 // If the session has been converted to a domain, handle the domain request
150 if (manager->HasSessionRequestHandler(context)) { 150 if (manager->HasSessionRequestHandler(context)) {
@@ -173,8 +173,8 @@ ResultCode KServerSession::CompleteSyncRequest(HLERequestContext& context) {
173 return result; 173 return result;
174} 174}
175 175
176ResultCode KServerSession::HandleSyncRequest(KThread* thread, Core::Memory::Memory& memory, 176Result KServerSession::HandleSyncRequest(KThread* thread, Core::Memory::Memory& memory,
177 Core::Timing::CoreTiming& core_timing) { 177 Core::Timing::CoreTiming& core_timing) {
178 return QueueSyncRequest(thread, memory); 178 return QueueSyncRequest(thread, memory);
179} 179}
180 180
diff --git a/src/core/hle/kernel/k_server_session.h b/src/core/hle/kernel/k_server_session.h
index b628a843f..6d0821945 100644
--- a/src/core/hle/kernel/k_server_session.h
+++ b/src/core/hle/kernel/k_server_session.h
@@ -73,10 +73,10 @@ public:
73 * @param memory Memory context to handle the sync request under. 73 * @param memory Memory context to handle the sync request under.
74 * @param core_timing Core timing context to schedule the request event under. 74 * @param core_timing Core timing context to schedule the request event under.
75 * 75 *
76 * @returns ResultCode from the operation. 76 * @returns Result from the operation.
77 */ 77 */
78 ResultCode HandleSyncRequest(KThread* thread, Core::Memory::Memory& memory, 78 Result HandleSyncRequest(KThread* thread, Core::Memory::Memory& memory,
79 Core::Timing::CoreTiming& core_timing); 79 Core::Timing::CoreTiming& core_timing);
80 80
81 /// Adds a new domain request handler to the collection of request handlers within 81 /// Adds a new domain request handler to the collection of request handlers within
82 /// this ServerSession instance. 82 /// this ServerSession instance.
@@ -103,14 +103,14 @@ public:
103 103
104private: 104private:
105 /// Queues a sync request from the emulated application. 105 /// Queues a sync request from the emulated application.
106 ResultCode QueueSyncRequest(KThread* thread, Core::Memory::Memory& memory); 106 Result QueueSyncRequest(KThread* thread, Core::Memory::Memory& memory);
107 107
108 /// Completes a sync request from the emulated application. 108 /// Completes a sync request from the emulated application.
109 ResultCode CompleteSyncRequest(HLERequestContext& context); 109 Result CompleteSyncRequest(HLERequestContext& context);
110 110
111 /// Handles a SyncRequest to a domain, forwarding the request to the proper object or closing an 111 /// Handles a SyncRequest to a domain, forwarding the request to the proper object or closing an
112 /// object handle. 112 /// object handle.
113 ResultCode HandleDomainSyncRequest(Kernel::HLERequestContext& context); 113 Result HandleDomainSyncRequest(Kernel::HLERequestContext& context);
114 114
115 /// This session's HLE request handlers 115 /// This session's HLE request handlers
116 std::shared_ptr<SessionRequestManager> manager; 116 std::shared_ptr<SessionRequestManager> manager;
diff --git a/src/core/hle/kernel/k_shared_memory.cpp b/src/core/hle/kernel/k_shared_memory.cpp
index 51d7538ca..b77735736 100644
--- a/src/core/hle/kernel/k_shared_memory.cpp
+++ b/src/core/hle/kernel/k_shared_memory.cpp
@@ -18,12 +18,10 @@ KSharedMemory::~KSharedMemory() {
18 kernel.GetSystemResourceLimit()->Release(LimitableResource::PhysicalMemory, size); 18 kernel.GetSystemResourceLimit()->Release(LimitableResource::PhysicalMemory, size);
19} 19}
20 20
21ResultCode KSharedMemory::Initialize(Core::DeviceMemory& device_memory_, KProcess* owner_process_, 21Result KSharedMemory::Initialize(Core::DeviceMemory& device_memory_, KProcess* owner_process_,
22 KPageLinkedList&& page_list_, 22 KPageGroup&& page_list_, Svc::MemoryPermission owner_permission_,
23 Svc::MemoryPermission owner_permission_, 23 Svc::MemoryPermission user_permission_, PAddr physical_address_,
24 Svc::MemoryPermission user_permission_, 24 std::size_t size_, std::string name_) {
25 PAddr physical_address_, std::size_t size_,
26 std::string name_) {
27 // Set members. 25 // Set members.
28 owner_process = owner_process_; 26 owner_process = owner_process_;
29 device_memory = &device_memory_; 27 device_memory = &device_memory_;
@@ -67,8 +65,8 @@ void KSharedMemory::Finalize() {
67 KAutoObjectWithSlabHeapAndContainer<KSharedMemory, KAutoObjectWithList>::Finalize(); 65 KAutoObjectWithSlabHeapAndContainer<KSharedMemory, KAutoObjectWithList>::Finalize();
68} 66}
69 67
70ResultCode KSharedMemory::Map(KProcess& target_process, VAddr address, std::size_t map_size, 68Result KSharedMemory::Map(KProcess& target_process, VAddr address, std::size_t map_size,
71 Svc::MemoryPermission permissions) { 69 Svc::MemoryPermission permissions) {
72 const u64 page_count{(map_size + PageSize - 1) / PageSize}; 70 const u64 page_count{(map_size + PageSize - 1) / PageSize};
73 71
74 if (page_list.GetNumPages() != page_count) { 72 if (page_list.GetNumPages() != page_count) {
@@ -86,7 +84,7 @@ ResultCode KSharedMemory::Map(KProcess& target_process, VAddr address, std::size
86 ConvertToKMemoryPermission(permissions)); 84 ConvertToKMemoryPermission(permissions));
87} 85}
88 86
89ResultCode KSharedMemory::Unmap(KProcess& target_process, VAddr address, std::size_t unmap_size) { 87Result KSharedMemory::Unmap(KProcess& target_process, VAddr address, std::size_t unmap_size) {
90 const u64 page_count{(unmap_size + PageSize - 1) / PageSize}; 88 const u64 page_count{(unmap_size + PageSize - 1) / PageSize};
91 89
92 if (page_list.GetNumPages() != page_count) { 90 if (page_list.GetNumPages() != page_count) {
diff --git a/src/core/hle/kernel/k_shared_memory.h b/src/core/hle/kernel/k_shared_memory.h
index 81de36136..2c1db0e70 100644
--- a/src/core/hle/kernel/k_shared_memory.h
+++ b/src/core/hle/kernel/k_shared_memory.h
@@ -9,7 +9,7 @@
9#include "common/common_types.h" 9#include "common/common_types.h"
10#include "core/device_memory.h" 10#include "core/device_memory.h"
11#include "core/hle/kernel/k_memory_block.h" 11#include "core/hle/kernel/k_memory_block.h"
12#include "core/hle/kernel/k_page_linked_list.h" 12#include "core/hle/kernel/k_page_group.h"
13#include "core/hle/kernel/k_process.h" 13#include "core/hle/kernel/k_process.h"
14#include "core/hle/kernel/slab_helpers.h" 14#include "core/hle/kernel/slab_helpers.h"
15#include "core/hle/result.h" 15#include "core/hle/result.h"
@@ -26,10 +26,10 @@ public:
26 explicit KSharedMemory(KernelCore& kernel_); 26 explicit KSharedMemory(KernelCore& kernel_);
27 ~KSharedMemory() override; 27 ~KSharedMemory() override;
28 28
29 ResultCode Initialize(Core::DeviceMemory& device_memory_, KProcess* owner_process_, 29 Result Initialize(Core::DeviceMemory& device_memory_, KProcess* owner_process_,
30 KPageLinkedList&& page_list_, Svc::MemoryPermission owner_permission_, 30 KPageGroup&& page_list_, Svc::MemoryPermission owner_permission_,
31 Svc::MemoryPermission user_permission_, PAddr physical_address_, 31 Svc::MemoryPermission user_permission_, PAddr physical_address_,
32 std::size_t size_, std::string name_); 32 std::size_t size_, std::string name_);
33 33
34 /** 34 /**
35 * Maps a shared memory block to an address in the target process' address space 35 * Maps a shared memory block to an address in the target process' address space
@@ -38,8 +38,8 @@ public:
38 * @param map_size Size of the shared memory block to map 38 * @param map_size Size of the shared memory block to map
39 * @param permissions Memory block map permissions (specified by SVC field) 39 * @param permissions Memory block map permissions (specified by SVC field)
40 */ 40 */
41 ResultCode Map(KProcess& target_process, VAddr address, std::size_t map_size, 41 Result Map(KProcess& target_process, VAddr address, std::size_t map_size,
42 Svc::MemoryPermission permissions); 42 Svc::MemoryPermission permissions);
43 43
44 /** 44 /**
45 * Unmaps a shared memory block from an address in the target process' address space 45 * Unmaps a shared memory block from an address in the target process' address space
@@ -47,7 +47,7 @@ public:
47 * @param address Address in system memory to unmap shared memory block 47 * @param address Address in system memory to unmap shared memory block
48 * @param unmap_size Size of the shared memory block to unmap 48 * @param unmap_size Size of the shared memory block to unmap
49 */ 49 */
50 ResultCode Unmap(KProcess& target_process, VAddr address, std::size_t unmap_size); 50 Result Unmap(KProcess& target_process, VAddr address, std::size_t unmap_size);
51 51
52 /** 52 /**
53 * Gets a pointer to the shared memory block 53 * Gets a pointer to the shared memory block
@@ -77,7 +77,7 @@ public:
77private: 77private:
78 Core::DeviceMemory* device_memory; 78 Core::DeviceMemory* device_memory;
79 KProcess* owner_process{}; 79 KProcess* owner_process{};
80 KPageLinkedList page_list; 80 KPageGroup page_list;
81 Svc::MemoryPermission owner_permission{}; 81 Svc::MemoryPermission owner_permission{};
82 Svc::MemoryPermission user_permission{}; 82 Svc::MemoryPermission user_permission{};
83 PAddr physical_address{}; 83 PAddr physical_address{};
diff --git a/src/core/hle/kernel/k_synchronization_object.cpp b/src/core/hle/kernel/k_synchronization_object.cpp
index 8554144d5..802dca046 100644
--- a/src/core/hle/kernel/k_synchronization_object.cpp
+++ b/src/core/hle/kernel/k_synchronization_object.cpp
@@ -22,7 +22,7 @@ public:
22 : KThreadQueueWithoutEndWait(kernel_), m_objects(o), m_nodes(n), m_count(c) {} 22 : KThreadQueueWithoutEndWait(kernel_), m_objects(o), m_nodes(n), m_count(c) {}
23 23
24 void NotifyAvailable(KThread* waiting_thread, KSynchronizationObject* signaled_object, 24 void NotifyAvailable(KThread* waiting_thread, KSynchronizationObject* signaled_object,
25 ResultCode wait_result) override { 25 Result wait_result) override {
26 // Determine the sync index, and unlink all nodes. 26 // Determine the sync index, and unlink all nodes.
27 s32 sync_index = -1; 27 s32 sync_index = -1;
28 for (auto i = 0; i < m_count; ++i) { 28 for (auto i = 0; i < m_count; ++i) {
@@ -45,8 +45,7 @@ public:
45 KThreadQueue::EndWait(waiting_thread, wait_result); 45 KThreadQueue::EndWait(waiting_thread, wait_result);
46 } 46 }
47 47
48 void CancelWait(KThread* waiting_thread, ResultCode wait_result, 48 void CancelWait(KThread* waiting_thread, Result wait_result, bool cancel_timer_task) override {
49 bool cancel_timer_task) override {
50 // Remove all nodes from our list. 49 // Remove all nodes from our list.
51 for (auto i = 0; i < m_count; ++i) { 50 for (auto i = 0; i < m_count; ++i) {
52 m_objects[i]->UnlinkNode(std::addressof(m_nodes[i])); 51 m_objects[i]->UnlinkNode(std::addressof(m_nodes[i]));
@@ -72,9 +71,9 @@ void KSynchronizationObject::Finalize() {
72 KAutoObject::Finalize(); 71 KAutoObject::Finalize();
73} 72}
74 73
75ResultCode KSynchronizationObject::Wait(KernelCore& kernel_ctx, s32* out_index, 74Result KSynchronizationObject::Wait(KernelCore& kernel_ctx, s32* out_index,
76 KSynchronizationObject** objects, const s32 num_objects, 75 KSynchronizationObject** objects, const s32 num_objects,
77 s64 timeout) { 76 s64 timeout) {
78 // Allocate space on stack for thread nodes. 77 // Allocate space on stack for thread nodes.
79 std::vector<ThreadListNode> thread_nodes(num_objects); 78 std::vector<ThreadListNode> thread_nodes(num_objects);
80 79
@@ -148,7 +147,7 @@ KSynchronizationObject::KSynchronizationObject(KernelCore& kernel_)
148 147
149KSynchronizationObject::~KSynchronizationObject() = default; 148KSynchronizationObject::~KSynchronizationObject() = default;
150 149
151void KSynchronizationObject::NotifyAvailable(ResultCode result) { 150void KSynchronizationObject::NotifyAvailable(Result result) {
152 KScopedSchedulerLock sl(kernel); 151 KScopedSchedulerLock sl(kernel);
153 152
154 // If we're not signaled, we've nothing to notify. 153 // If we're not signaled, we've nothing to notify.
diff --git a/src/core/hle/kernel/k_synchronization_object.h b/src/core/hle/kernel/k_synchronization_object.h
index d7540d6c7..8d8122ab7 100644
--- a/src/core/hle/kernel/k_synchronization_object.h
+++ b/src/core/hle/kernel/k_synchronization_object.h
@@ -24,9 +24,9 @@ public:
24 KThread* thread{}; 24 KThread* thread{};
25 }; 25 };
26 26
27 [[nodiscard]] static ResultCode Wait(KernelCore& kernel, s32* out_index, 27 [[nodiscard]] static Result Wait(KernelCore& kernel, s32* out_index,
28 KSynchronizationObject** objects, const s32 num_objects, 28 KSynchronizationObject** objects, const s32 num_objects,
29 s64 timeout); 29 s64 timeout);
30 30
31 void Finalize() override; 31 void Finalize() override;
32 32
@@ -72,7 +72,7 @@ protected:
72 72
73 virtual void OnFinalizeSynchronizationObject() {} 73 virtual void OnFinalizeSynchronizationObject() {}
74 74
75 void NotifyAvailable(ResultCode result); 75 void NotifyAvailable(Result result);
76 void NotifyAvailable() { 76 void NotifyAvailable() {
77 return this->NotifyAvailable(ResultSuccess); 77 return this->NotifyAvailable(ResultSuccess);
78 } 78 }
diff --git a/src/core/hle/kernel/k_thread.cpp b/src/core/hle/kernel/k_thread.cpp
index e1bdd6c2c..50cb5fc90 100644
--- a/src/core/hle/kernel/k_thread.cpp
+++ b/src/core/hle/kernel/k_thread.cpp
@@ -80,8 +80,7 @@ public:
80 explicit ThreadQueueImplForKThreadSetProperty(KernelCore& kernel_, KThread::WaiterList* wl) 80 explicit ThreadQueueImplForKThreadSetProperty(KernelCore& kernel_, KThread::WaiterList* wl)
81 : KThreadQueue(kernel_), m_wait_list(wl) {} 81 : KThreadQueue(kernel_), m_wait_list(wl) {}
82 82
83 void CancelWait(KThread* waiting_thread, ResultCode wait_result, 83 void CancelWait(KThread* waiting_thread, Result wait_result, bool cancel_timer_task) override {
84 bool cancel_timer_task) override {
85 // Remove the thread from the wait list. 84 // Remove the thread from the wait list.
86 m_wait_list->erase(m_wait_list->iterator_to(*waiting_thread)); 85 m_wait_list->erase(m_wait_list->iterator_to(*waiting_thread));
87 86
@@ -99,8 +98,8 @@ KThread::KThread(KernelCore& kernel_)
99 : KAutoObjectWithSlabHeapAndContainer{kernel_}, activity_pause_lock{kernel_} {} 98 : KAutoObjectWithSlabHeapAndContainer{kernel_}, activity_pause_lock{kernel_} {}
100KThread::~KThread() = default; 99KThread::~KThread() = default;
101 100
102ResultCode KThread::Initialize(KThreadFunction func, uintptr_t arg, VAddr user_stack_top, s32 prio, 101Result KThread::Initialize(KThreadFunction func, uintptr_t arg, VAddr user_stack_top, s32 prio,
103 s32 virt_core, KProcess* owner, ThreadType type) { 102 s32 virt_core, KProcess* owner, ThreadType type) {
104 // Assert parameters are valid. 103 // Assert parameters are valid.
105 ASSERT((type == ThreadType::Main) || (type == ThreadType::Dummy) || 104 ASSERT((type == ThreadType::Main) || (type == ThreadType::Dummy) ||
106 (Svc::HighestThreadPriority <= prio && prio <= Svc::LowestThreadPriority)); 105 (Svc::HighestThreadPriority <= prio && prio <= Svc::LowestThreadPriority));
@@ -245,46 +244,40 @@ ResultCode KThread::Initialize(KThreadFunction func, uintptr_t arg, VAddr user_s
245 return ResultSuccess; 244 return ResultSuccess;
246} 245}
247 246
248ResultCode KThread::InitializeThread(KThread* thread, KThreadFunction func, uintptr_t arg, 247Result KThread::InitializeThread(KThread* thread, KThreadFunction func, uintptr_t arg,
249 VAddr user_stack_top, s32 prio, s32 core, KProcess* owner, 248 VAddr user_stack_top, s32 prio, s32 core, KProcess* owner,
250 ThreadType type, std::function<void(void*)>&& init_func, 249 ThreadType type, std::function<void()>&& init_func) {
251 void* init_func_parameter) {
252 // Initialize the thread. 250 // Initialize the thread.
253 R_TRY(thread->Initialize(func, arg, user_stack_top, prio, core, owner, type)); 251 R_TRY(thread->Initialize(func, arg, user_stack_top, prio, core, owner, type));
254 252
255 // Initialize emulation parameters. 253 // Initialize emulation parameters.
256 thread->host_context = 254 thread->host_context = std::make_shared<Common::Fiber>(std::move(init_func));
257 std::make_shared<Common::Fiber>(std::move(init_func), init_func_parameter);
258 thread->is_single_core = !Settings::values.use_multi_core.GetValue(); 255 thread->is_single_core = !Settings::values.use_multi_core.GetValue();
259 256
260 return ResultSuccess; 257 return ResultSuccess;
261} 258}
262 259
263ResultCode KThread::InitializeDummyThread(KThread* thread) { 260Result KThread::InitializeDummyThread(KThread* thread) {
264 return thread->Initialize({}, {}, {}, DummyThreadPriority, 3, {}, ThreadType::Dummy); 261 return thread->Initialize({}, {}, {}, DummyThreadPriority, 3, {}, ThreadType::Dummy);
265} 262}
266 263
267ResultCode KThread::InitializeIdleThread(Core::System& system, KThread* thread, s32 virt_core) { 264Result KThread::InitializeIdleThread(Core::System& system, KThread* thread, s32 virt_core) {
268 return InitializeThread(thread, {}, {}, {}, IdleThreadPriority, virt_core, {}, ThreadType::Main, 265 return InitializeThread(thread, {}, {}, {}, IdleThreadPriority, virt_core, {}, ThreadType::Main,
269 Core::CpuManager::GetIdleThreadStartFunc(), 266 system.GetCpuManager().GetIdleThreadStartFunc());
270 system.GetCpuManager().GetStartFuncParameter());
271} 267}
272 268
273ResultCode KThread::InitializeHighPriorityThread(Core::System& system, KThread* thread, 269Result KThread::InitializeHighPriorityThread(Core::System& system, KThread* thread,
274 KThreadFunction func, uintptr_t arg, 270 KThreadFunction func, uintptr_t arg, s32 virt_core) {
275 s32 virt_core) {
276 return InitializeThread(thread, func, arg, {}, {}, virt_core, nullptr, ThreadType::HighPriority, 271 return InitializeThread(thread, func, arg, {}, {}, virt_core, nullptr, ThreadType::HighPriority,
277 Core::CpuManager::GetShutdownThreadStartFunc(), 272 system.GetCpuManager().GetShutdownThreadStartFunc());
278 system.GetCpuManager().GetStartFuncParameter());
279} 273}
280 274
281ResultCode KThread::InitializeUserThread(Core::System& system, KThread* thread, 275Result KThread::InitializeUserThread(Core::System& system, KThread* thread, KThreadFunction func,
282 KThreadFunction func, uintptr_t arg, VAddr user_stack_top, 276 uintptr_t arg, VAddr user_stack_top, s32 prio, s32 virt_core,
283 s32 prio, s32 virt_core, KProcess* owner) { 277 KProcess* owner) {
284 system.Kernel().GlobalSchedulerContext().AddThread(thread); 278 system.Kernel().GlobalSchedulerContext().AddThread(thread);
285 return InitializeThread(thread, func, arg, user_stack_top, prio, virt_core, owner, 279 return InitializeThread(thread, func, arg, user_stack_top, prio, virt_core, owner,
286 ThreadType::User, Core::CpuManager::GetGuestThreadStartFunc(), 280 ThreadType::User, system.GetCpuManager().GetGuestThreadStartFunc());
287 system.GetCpuManager().GetStartFuncParameter());
288} 281}
289 282
290void KThread::PostDestroy(uintptr_t arg) { 283void KThread::PostDestroy(uintptr_t arg) {
@@ -382,7 +375,7 @@ void KThread::FinishTermination() {
382 for (std::size_t i = 0; i < static_cast<std::size_t>(Core::Hardware::NUM_CPU_CORES); ++i) { 375 for (std::size_t i = 0; i < static_cast<std::size_t>(Core::Hardware::NUM_CPU_CORES); ++i) {
383 KThread* core_thread{}; 376 KThread* core_thread{};
384 do { 377 do {
385 core_thread = kernel.Scheduler(i).GetCurrentThread(); 378 core_thread = kernel.Scheduler(i).GetSchedulerCurrentThread();
386 } while (core_thread == this); 379 } while (core_thread == this);
387 } 380 }
388 } 381 }
@@ -521,7 +514,7 @@ void KThread::ClearInterruptFlag() {
521 memory.Write16(tls_address + offsetof(ThreadLocalRegion, interrupt_flag), 0); 514 memory.Write16(tls_address + offsetof(ThreadLocalRegion, interrupt_flag), 0);
522} 515}
523 516
524ResultCode KThread::GetCoreMask(s32* out_ideal_core, u64* out_affinity_mask) { 517Result KThread::GetCoreMask(s32* out_ideal_core, u64* out_affinity_mask) {
525 KScopedSchedulerLock sl{kernel}; 518 KScopedSchedulerLock sl{kernel};
526 519
527 // Get the virtual mask. 520 // Get the virtual mask.
@@ -531,7 +524,7 @@ ResultCode KThread::GetCoreMask(s32* out_ideal_core, u64* out_affinity_mask) {
531 return ResultSuccess; 524 return ResultSuccess;
532} 525}
533 526
534ResultCode KThread::GetPhysicalCoreMask(s32* out_ideal_core, u64* out_affinity_mask) { 527Result KThread::GetPhysicalCoreMask(s32* out_ideal_core, u64* out_affinity_mask) {
535 KScopedSchedulerLock sl{kernel}; 528 KScopedSchedulerLock sl{kernel};
536 ASSERT(num_core_migration_disables >= 0); 529 ASSERT(num_core_migration_disables >= 0);
537 530
@@ -547,7 +540,7 @@ ResultCode KThread::GetPhysicalCoreMask(s32* out_ideal_core, u64* out_affinity_m
547 return ResultSuccess; 540 return ResultSuccess;
548} 541}
549 542
550ResultCode KThread::SetCoreMask(s32 core_id_, u64 v_affinity_mask) { 543Result KThread::SetCoreMask(s32 core_id_, u64 v_affinity_mask) {
551 ASSERT(parent != nullptr); 544 ASSERT(parent != nullptr);
552 ASSERT(v_affinity_mask != 0); 545 ASSERT(v_affinity_mask != 0);
553 KScopedLightLock lk(activity_pause_lock); 546 KScopedLightLock lk(activity_pause_lock);
@@ -629,7 +622,7 @@ ResultCode KThread::SetCoreMask(s32 core_id_, u64 v_affinity_mask) {
629 s32 thread_core; 622 s32 thread_core;
630 for (thread_core = 0; thread_core < static_cast<s32>(Core::Hardware::NUM_CPU_CORES); 623 for (thread_core = 0; thread_core < static_cast<s32>(Core::Hardware::NUM_CPU_CORES);
631 ++thread_core) { 624 ++thread_core) {
632 if (kernel.Scheduler(thread_core).GetCurrentThread() == this) { 625 if (kernel.Scheduler(thread_core).GetSchedulerCurrentThread() == this) {
633 thread_is_current = true; 626 thread_is_current = true;
634 break; 627 break;
635 } 628 }
@@ -754,12 +747,12 @@ void KThread::WaitUntilSuspended() {
754 for (std::size_t i = 0; i < static_cast<std::size_t>(Core::Hardware::NUM_CPU_CORES); ++i) { 747 for (std::size_t i = 0; i < static_cast<std::size_t>(Core::Hardware::NUM_CPU_CORES); ++i) {
755 KThread* core_thread{}; 748 KThread* core_thread{};
756 do { 749 do {
757 core_thread = kernel.Scheduler(i).GetCurrentThread(); 750 core_thread = kernel.Scheduler(i).GetSchedulerCurrentThread();
758 } while (core_thread == this); 751 } while (core_thread == this);
759 } 752 }
760} 753}
761 754
762ResultCode KThread::SetActivity(Svc::ThreadActivity activity) { 755Result KThread::SetActivity(Svc::ThreadActivity activity) {
763 // Lock ourselves. 756 // Lock ourselves.
764 KScopedLightLock lk(activity_pause_lock); 757 KScopedLightLock lk(activity_pause_lock);
765 758
@@ -820,7 +813,7 @@ ResultCode KThread::SetActivity(Svc::ThreadActivity activity) {
820 // Check if the thread is currently running. 813 // Check if the thread is currently running.
821 // If it is, we'll need to retry. 814 // If it is, we'll need to retry.
822 for (auto i = 0; i < static_cast<s32>(Core::Hardware::NUM_CPU_CORES); ++i) { 815 for (auto i = 0; i < static_cast<s32>(Core::Hardware::NUM_CPU_CORES); ++i) {
823 if (kernel.Scheduler(i).GetCurrentThread() == this) { 816 if (kernel.Scheduler(i).GetSchedulerCurrentThread() == this) {
824 thread_is_current = true; 817 thread_is_current = true;
825 break; 818 break;
826 } 819 }
@@ -832,7 +825,7 @@ ResultCode KThread::SetActivity(Svc::ThreadActivity activity) {
832 return ResultSuccess; 825 return ResultSuccess;
833} 826}
834 827
835ResultCode KThread::GetThreadContext3(std::vector<u8>& out) { 828Result KThread::GetThreadContext3(std::vector<u8>& out) {
836 // Lock ourselves. 829 // Lock ourselves.
837 KScopedLightLock lk{activity_pause_lock}; 830 KScopedLightLock lk{activity_pause_lock};
838 831
@@ -1000,7 +993,7 @@ KThread* KThread::RemoveWaiterByKey(s32* out_num_waiters, VAddr key) {
1000 return next_lock_owner; 993 return next_lock_owner;
1001} 994}
1002 995
1003ResultCode KThread::Run() { 996Result KThread::Run() {
1004 while (true) { 997 while (true) {
1005 KScopedSchedulerLock lk{kernel}; 998 KScopedSchedulerLock lk{kernel};
1006 999
@@ -1061,7 +1054,7 @@ void KThread::Exit() {
1061 } 1054 }
1062} 1055}
1063 1056
1064ResultCode KThread::Sleep(s64 timeout) { 1057Result KThread::Sleep(s64 timeout) {
1065 ASSERT(!kernel.GlobalSchedulerContext().IsLocked()); 1058 ASSERT(!kernel.GlobalSchedulerContext().IsLocked());
1066 ASSERT(this == GetCurrentThreadPointer(kernel)); 1059 ASSERT(this == GetCurrentThreadPointer(kernel));
1067 ASSERT(timeout > 0); 1060 ASSERT(timeout > 0);
@@ -1117,7 +1110,7 @@ void KThread::BeginWait(KThreadQueue* queue) {
1117 wait_queue = queue; 1110 wait_queue = queue;
1118} 1111}
1119 1112
1120void KThread::NotifyAvailable(KSynchronizationObject* signaled_object, ResultCode wait_result_) { 1113void KThread::NotifyAvailable(KSynchronizationObject* signaled_object, Result wait_result_) {
1121 // Lock the scheduler. 1114 // Lock the scheduler.
1122 KScopedSchedulerLock sl(kernel); 1115 KScopedSchedulerLock sl(kernel);
1123 1116
@@ -1127,7 +1120,7 @@ void KThread::NotifyAvailable(KSynchronizationObject* signaled_object, ResultCod
1127 } 1120 }
1128} 1121}
1129 1122
1130void KThread::EndWait(ResultCode wait_result_) { 1123void KThread::EndWait(Result wait_result_) {
1131 // Lock the scheduler. 1124 // Lock the scheduler.
1132 KScopedSchedulerLock sl(kernel); 1125 KScopedSchedulerLock sl(kernel);
1133 1126
@@ -1146,7 +1139,7 @@ void KThread::EndWait(ResultCode wait_result_) {
1146 } 1139 }
1147} 1140}
1148 1141
1149void KThread::CancelWait(ResultCode wait_result_, bool cancel_timer_task) { 1142void KThread::CancelWait(Result wait_result_, bool cancel_timer_task) {
1150 // Lock the scheduler. 1143 // Lock the scheduler.
1151 KScopedSchedulerLock sl(kernel); 1144 KScopedSchedulerLock sl(kernel);
1152 1145
@@ -1176,6 +1169,10 @@ std::shared_ptr<Common::Fiber>& KThread::GetHostContext() {
1176 return host_context; 1169 return host_context;
1177} 1170}
1178 1171
1172void SetCurrentThread(KernelCore& kernel, KThread* thread) {
1173 kernel.SetCurrentEmuThread(thread);
1174}
1175
1179KThread* GetCurrentThreadPointer(KernelCore& kernel) { 1176KThread* GetCurrentThreadPointer(KernelCore& kernel) {
1180 return kernel.GetCurrentEmuThread(); 1177 return kernel.GetCurrentEmuThread();
1181} 1178}
diff --git a/src/core/hle/kernel/k_thread.h b/src/core/hle/kernel/k_thread.h
index 8c1f8a344..28cd7ecb0 100644
--- a/src/core/hle/kernel/k_thread.h
+++ b/src/core/hle/kernel/k_thread.h
@@ -106,6 +106,7 @@ enum class StepState : u32 {
106 StepPerformed, ///< Thread has stepped, waiting to be scheduled again 106 StepPerformed, ///< Thread has stepped, waiting to be scheduled again
107}; 107};
108 108
109void SetCurrentThread(KernelCore& kernel, KThread* thread);
109[[nodiscard]] KThread* GetCurrentThreadPointer(KernelCore& kernel); 110[[nodiscard]] KThread* GetCurrentThreadPointer(KernelCore& kernel);
110[[nodiscard]] KThread& GetCurrentThread(KernelCore& kernel); 111[[nodiscard]] KThread& GetCurrentThread(KernelCore& kernel);
111[[nodiscard]] s32 GetCurrentCoreId(KernelCore& kernel); 112[[nodiscard]] s32 GetCurrentCoreId(KernelCore& kernel);
@@ -175,7 +176,7 @@ public:
175 176
176 void SetBasePriority(s32 value); 177 void SetBasePriority(s32 value);
177 178
178 [[nodiscard]] ResultCode Run(); 179 [[nodiscard]] Result Run();
179 180
180 void Exit(); 181 void Exit();
181 182
@@ -217,11 +218,11 @@ public:
217 return synced_index; 218 return synced_index;
218 } 219 }
219 220
220 constexpr void SetWaitResult(ResultCode wait_res) { 221 constexpr void SetWaitResult(Result wait_res) {
221 wait_result = wait_res; 222 wait_result = wait_res;
222 } 223 }
223 224
224 [[nodiscard]] constexpr ResultCode GetWaitResult() const { 225 [[nodiscard]] constexpr Result GetWaitResult() const {
225 return wait_result; 226 return wait_result;
226 } 227 }
227 228
@@ -344,15 +345,15 @@ public:
344 return physical_affinity_mask; 345 return physical_affinity_mask;
345 } 346 }
346 347
347 [[nodiscard]] ResultCode GetCoreMask(s32* out_ideal_core, u64* out_affinity_mask); 348 [[nodiscard]] Result GetCoreMask(s32* out_ideal_core, u64* out_affinity_mask);
348 349
349 [[nodiscard]] ResultCode GetPhysicalCoreMask(s32* out_ideal_core, u64* out_affinity_mask); 350 [[nodiscard]] Result GetPhysicalCoreMask(s32* out_ideal_core, u64* out_affinity_mask);
350 351
351 [[nodiscard]] ResultCode SetCoreMask(s32 cpu_core_id, u64 v_affinity_mask); 352 [[nodiscard]] Result SetCoreMask(s32 cpu_core_id, u64 v_affinity_mask);
352 353
353 [[nodiscard]] ResultCode SetActivity(Svc::ThreadActivity activity); 354 [[nodiscard]] Result SetActivity(Svc::ThreadActivity activity);
354 355
355 [[nodiscard]] ResultCode Sleep(s64 timeout); 356 [[nodiscard]] Result Sleep(s64 timeout);
356 357
357 [[nodiscard]] s64 GetYieldScheduleCount() const { 358 [[nodiscard]] s64 GetYieldScheduleCount() const {
358 return schedule_count; 359 return schedule_count;
@@ -410,20 +411,19 @@ public:
410 411
411 static void PostDestroy(uintptr_t arg); 412 static void PostDestroy(uintptr_t arg);
412 413
413 [[nodiscard]] static ResultCode InitializeDummyThread(KThread* thread); 414 [[nodiscard]] static Result InitializeDummyThread(KThread* thread);
414 415
415 [[nodiscard]] static ResultCode InitializeIdleThread(Core::System& system, KThread* thread, 416 [[nodiscard]] static Result InitializeIdleThread(Core::System& system, KThread* thread,
416 s32 virt_core); 417 s32 virt_core);
417 418
418 [[nodiscard]] static ResultCode InitializeHighPriorityThread(Core::System& system, 419 [[nodiscard]] static Result InitializeHighPriorityThread(Core::System& system, KThread* thread,
419 KThread* thread, 420 KThreadFunction func, uintptr_t arg,
420 KThreadFunction func, 421 s32 virt_core);
421 uintptr_t arg, s32 virt_core);
422 422
423 [[nodiscard]] static ResultCode InitializeUserThread(Core::System& system, KThread* thread, 423 [[nodiscard]] static Result InitializeUserThread(Core::System& system, KThread* thread,
424 KThreadFunction func, uintptr_t arg, 424 KThreadFunction func, uintptr_t arg,
425 VAddr user_stack_top, s32 prio, 425 VAddr user_stack_top, s32 prio, s32 virt_core,
426 s32 virt_core, KProcess* owner); 426 KProcess* owner);
427 427
428public: 428public:
429 struct StackParameters { 429 struct StackParameters {
@@ -609,7 +609,7 @@ public:
609 609
610 void RemoveWaiter(KThread* thread); 610 void RemoveWaiter(KThread* thread);
611 611
612 [[nodiscard]] ResultCode GetThreadContext3(std::vector<u8>& out); 612 [[nodiscard]] Result GetThreadContext3(std::vector<u8>& out);
613 613
614 [[nodiscard]] KThread* RemoveWaiterByKey(s32* out_num_waiters, VAddr key); 614 [[nodiscard]] KThread* RemoveWaiterByKey(s32* out_num_waiters, VAddr key);
615 615
@@ -635,9 +635,9 @@ public:
635 } 635 }
636 636
637 void BeginWait(KThreadQueue* queue); 637 void BeginWait(KThreadQueue* queue);
638 void NotifyAvailable(KSynchronizationObject* signaled_object, ResultCode wait_result_); 638 void NotifyAvailable(KSynchronizationObject* signaled_object, Result wait_result_);
639 void EndWait(ResultCode wait_result_); 639 void EndWait(Result wait_result_);
640 void CancelWait(ResultCode wait_result_, bool cancel_timer_task); 640 void CancelWait(Result wait_result_, bool cancel_timer_task);
641 641
642 [[nodiscard]] bool HasWaiters() const { 642 [[nodiscard]] bool HasWaiters() const {
643 return !waiter_list.empty(); 643 return !waiter_list.empty();
@@ -723,14 +723,13 @@ private:
723 723
724 void FinishTermination(); 724 void FinishTermination();
725 725
726 [[nodiscard]] ResultCode Initialize(KThreadFunction func, uintptr_t arg, VAddr user_stack_top, 726 [[nodiscard]] Result Initialize(KThreadFunction func, uintptr_t arg, VAddr user_stack_top,
727 s32 prio, s32 virt_core, KProcess* owner, ThreadType type); 727 s32 prio, s32 virt_core, KProcess* owner, ThreadType type);
728 728
729 [[nodiscard]] static ResultCode InitializeThread(KThread* thread, KThreadFunction func, 729 [[nodiscard]] static Result InitializeThread(KThread* thread, KThreadFunction func,
730 uintptr_t arg, VAddr user_stack_top, s32 prio, 730 uintptr_t arg, VAddr user_stack_top, s32 prio,
731 s32 core, KProcess* owner, ThreadType type, 731 s32 core, KProcess* owner, ThreadType type,
732 std::function<void(void*)>&& init_func, 732 std::function<void()>&& init_func);
733 void* init_func_parameter);
734 733
735 static void RestorePriority(KernelCore& kernel_ctx, KThread* thread); 734 static void RestorePriority(KernelCore& kernel_ctx, KThread* thread);
736 735
@@ -767,7 +766,7 @@ private:
767 u32 suspend_request_flags{}; 766 u32 suspend_request_flags{};
768 u32 suspend_allowed_flags{}; 767 u32 suspend_allowed_flags{};
769 s32 synced_index{}; 768 s32 synced_index{};
770 ResultCode wait_result{ResultSuccess}; 769 Result wait_result{ResultSuccess};
771 s32 base_priority{}; 770 s32 base_priority{};
772 s32 physical_ideal_core_id{}; 771 s32 physical_ideal_core_id{};
773 s32 virtual_ideal_core_id{}; 772 s32 virtual_ideal_core_id{};
diff --git a/src/core/hle/kernel/k_thread_local_page.cpp b/src/core/hle/kernel/k_thread_local_page.cpp
index fbdc40b3a..563560114 100644
--- a/src/core/hle/kernel/k_thread_local_page.cpp
+++ b/src/core/hle/kernel/k_thread_local_page.cpp
@@ -13,7 +13,7 @@
13 13
14namespace Kernel { 14namespace Kernel {
15 15
16ResultCode KThreadLocalPage::Initialize(KernelCore& kernel, KProcess* process) { 16Result KThreadLocalPage::Initialize(KernelCore& kernel, KProcess* process) {
17 // Set that this process owns us. 17 // Set that this process owns us.
18 m_owner = process; 18 m_owner = process;
19 m_kernel = &kernel; 19 m_kernel = &kernel;
@@ -35,7 +35,7 @@ ResultCode KThreadLocalPage::Initialize(KernelCore& kernel, KProcess* process) {
35 return ResultSuccess; 35 return ResultSuccess;
36} 36}
37 37
38ResultCode KThreadLocalPage::Finalize() { 38Result KThreadLocalPage::Finalize() {
39 // Get the physical address of the page. 39 // Get the physical address of the page.
40 const PAddr phys_addr = m_owner->PageTable().GetPhysicalAddr(m_virt_addr); 40 const PAddr phys_addr = m_owner->PageTable().GetPhysicalAddr(m_virt_addr);
41 ASSERT(phys_addr); 41 ASSERT(phys_addr);
diff --git a/src/core/hle/kernel/k_thread_local_page.h b/src/core/hle/kernel/k_thread_local_page.h
index a4fe43ee5..0a7f22680 100644
--- a/src/core/hle/kernel/k_thread_local_page.h
+++ b/src/core/hle/kernel/k_thread_local_page.h
@@ -34,8 +34,8 @@ public:
34 return m_virt_addr; 34 return m_virt_addr;
35 } 35 }
36 36
37 ResultCode Initialize(KernelCore& kernel, KProcess* process); 37 Result Initialize(KernelCore& kernel, KProcess* process);
38 ResultCode Finalize(); 38 Result Finalize();
39 39
40 VAddr Reserve(); 40 VAddr Reserve();
41 void Release(VAddr addr); 41 void Release(VAddr addr);
diff --git a/src/core/hle/kernel/k_thread_queue.cpp b/src/core/hle/kernel/k_thread_queue.cpp
index 1c338904a..9f4e081ba 100644
--- a/src/core/hle/kernel/k_thread_queue.cpp
+++ b/src/core/hle/kernel/k_thread_queue.cpp
@@ -9,9 +9,9 @@ namespace Kernel {
9 9
10void KThreadQueue::NotifyAvailable([[maybe_unused]] KThread* waiting_thread, 10void KThreadQueue::NotifyAvailable([[maybe_unused]] KThread* waiting_thread,
11 [[maybe_unused]] KSynchronizationObject* signaled_object, 11 [[maybe_unused]] KSynchronizationObject* signaled_object,
12 [[maybe_unused]] ResultCode wait_result) {} 12 [[maybe_unused]] Result wait_result) {}
13 13
14void KThreadQueue::EndWait(KThread* waiting_thread, ResultCode wait_result) { 14void KThreadQueue::EndWait(KThread* waiting_thread, Result wait_result) {
15 // Set the thread's wait result. 15 // Set the thread's wait result.
16 waiting_thread->SetWaitResult(wait_result); 16 waiting_thread->SetWaitResult(wait_result);
17 17
@@ -25,8 +25,7 @@ void KThreadQueue::EndWait(KThread* waiting_thread, ResultCode wait_result) {
25 kernel.TimeManager().UnscheduleTimeEvent(waiting_thread); 25 kernel.TimeManager().UnscheduleTimeEvent(waiting_thread);
26} 26}
27 27
28void KThreadQueue::CancelWait(KThread* waiting_thread, ResultCode wait_result, 28void KThreadQueue::CancelWait(KThread* waiting_thread, Result wait_result, bool cancel_timer_task) {
29 bool cancel_timer_task) {
30 // Set the thread's wait result. 29 // Set the thread's wait result.
31 waiting_thread->SetWaitResult(wait_result); 30 waiting_thread->SetWaitResult(wait_result);
32 31
@@ -43,6 +42,6 @@ void KThreadQueue::CancelWait(KThread* waiting_thread, ResultCode wait_result,
43} 42}
44 43
45void KThreadQueueWithoutEndWait::EndWait([[maybe_unused]] KThread* waiting_thread, 44void KThreadQueueWithoutEndWait::EndWait([[maybe_unused]] KThread* waiting_thread,
46 [[maybe_unused]] ResultCode wait_result) {} 45 [[maybe_unused]] Result wait_result) {}
47 46
48} // namespace Kernel 47} // namespace Kernel
diff --git a/src/core/hle/kernel/k_thread_queue.h b/src/core/hle/kernel/k_thread_queue.h
index 4a7dbdd47..8d76ece81 100644
--- a/src/core/hle/kernel/k_thread_queue.h
+++ b/src/core/hle/kernel/k_thread_queue.h
@@ -14,10 +14,9 @@ public:
14 virtual ~KThreadQueue() = default; 14 virtual ~KThreadQueue() = default;
15 15
16 virtual void NotifyAvailable(KThread* waiting_thread, KSynchronizationObject* signaled_object, 16 virtual void NotifyAvailable(KThread* waiting_thread, KSynchronizationObject* signaled_object,
17 ResultCode wait_result); 17 Result wait_result);
18 virtual void EndWait(KThread* waiting_thread, ResultCode wait_result); 18 virtual void EndWait(KThread* waiting_thread, Result wait_result);
19 virtual void CancelWait(KThread* waiting_thread, ResultCode wait_result, 19 virtual void CancelWait(KThread* waiting_thread, Result wait_result, bool cancel_timer_task);
20 bool cancel_timer_task);
21 20
22private: 21private:
23 KernelCore& kernel; 22 KernelCore& kernel;
@@ -28,7 +27,7 @@ class KThreadQueueWithoutEndWait : public KThreadQueue {
28public: 27public:
29 explicit KThreadQueueWithoutEndWait(KernelCore& kernel_) : KThreadQueue(kernel_) {} 28 explicit KThreadQueueWithoutEndWait(KernelCore& kernel_) : KThreadQueue(kernel_) {}
30 29
31 void EndWait(KThread* waiting_thread, ResultCode wait_result) override final; 30 void EndWait(KThread* waiting_thread, Result wait_result) override final;
32}; 31};
33 32
34} // namespace Kernel 33} // namespace Kernel
diff --git a/src/core/hle/kernel/k_transfer_memory.cpp b/src/core/hle/kernel/k_transfer_memory.cpp
index 1ed4b0f6f..b0320eb73 100644
--- a/src/core/hle/kernel/k_transfer_memory.cpp
+++ b/src/core/hle/kernel/k_transfer_memory.cpp
@@ -13,8 +13,8 @@ KTransferMemory::KTransferMemory(KernelCore& kernel_)
13 13
14KTransferMemory::~KTransferMemory() = default; 14KTransferMemory::~KTransferMemory() = default;
15 15
16ResultCode KTransferMemory::Initialize(VAddr address_, std::size_t size_, 16Result KTransferMemory::Initialize(VAddr address_, std::size_t size_,
17 Svc::MemoryPermission owner_perm_) { 17 Svc::MemoryPermission owner_perm_) {
18 // Set members. 18 // Set members.
19 owner = kernel.CurrentProcess(); 19 owner = kernel.CurrentProcess();
20 20
diff --git a/src/core/hle/kernel/k_transfer_memory.h b/src/core/hle/kernel/k_transfer_memory.h
index 9ad80ba30..85d508ee7 100644
--- a/src/core/hle/kernel/k_transfer_memory.h
+++ b/src/core/hle/kernel/k_transfer_memory.h
@@ -7,7 +7,7 @@
7#include "core/hle/kernel/svc_types.h" 7#include "core/hle/kernel/svc_types.h"
8#include "core/hle/result.h" 8#include "core/hle/result.h"
9 9
10union ResultCode; 10union Result;
11 11
12namespace Core::Memory { 12namespace Core::Memory {
13class Memory; 13class Memory;
@@ -26,7 +26,7 @@ public:
26 explicit KTransferMemory(KernelCore& kernel_); 26 explicit KTransferMemory(KernelCore& kernel_);
27 ~KTransferMemory() override; 27 ~KTransferMemory() override;
28 28
29 ResultCode Initialize(VAddr address_, std::size_t size_, Svc::MemoryPermission owner_perm_); 29 Result Initialize(VAddr address_, std::size_t size_, Svc::MemoryPermission owner_perm_);
30 30
31 void Finalize() override; 31 void Finalize() override;
32 32
diff --git a/src/core/hle/kernel/k_writable_event.cpp b/src/core/hle/kernel/k_writable_event.cpp
index 26c8489ad..ff88c5acd 100644
--- a/src/core/hle/kernel/k_writable_event.cpp
+++ b/src/core/hle/kernel/k_writable_event.cpp
@@ -18,11 +18,11 @@ void KWritableEvent::Initialize(KEvent* parent_event_, std::string&& name_) {
18 parent->GetReadableEvent().Open(); 18 parent->GetReadableEvent().Open();
19} 19}
20 20
21ResultCode KWritableEvent::Signal() { 21Result KWritableEvent::Signal() {
22 return parent->GetReadableEvent().Signal(); 22 return parent->GetReadableEvent().Signal();
23} 23}
24 24
25ResultCode KWritableEvent::Clear() { 25Result KWritableEvent::Clear() {
26 return parent->GetReadableEvent().Clear(); 26 return parent->GetReadableEvent().Clear();
27} 27}
28 28
diff --git a/src/core/hle/kernel/k_writable_event.h b/src/core/hle/kernel/k_writable_event.h
index e289e80c4..3fd0c7d0a 100644
--- a/src/core/hle/kernel/k_writable_event.h
+++ b/src/core/hle/kernel/k_writable_event.h
@@ -25,8 +25,8 @@ public:
25 static void PostDestroy([[maybe_unused]] uintptr_t arg) {} 25 static void PostDestroy([[maybe_unused]] uintptr_t arg) {}
26 26
27 void Initialize(KEvent* parent_, std::string&& name_); 27 void Initialize(KEvent* parent_, std::string&& name_);
28 ResultCode Signal(); 28 Result Signal();
29 ResultCode Clear(); 29 Result Clear();
30 30
31 KEvent* GetParent() const { 31 KEvent* GetParent() const {
32 return parent; 32 return parent;
diff --git a/src/core/hle/kernel/kernel.cpp b/src/core/hle/kernel/kernel.cpp
index 94953e257..0009193be 100644
--- a/src/core/hle/kernel/kernel.cpp
+++ b/src/core/hle/kernel/kernel.cpp
@@ -331,6 +331,8 @@ struct KernelCore::Impl {
331 return is_shutting_down.load(std::memory_order_relaxed); 331 return is_shutting_down.load(std::memory_order_relaxed);
332 } 332 }
333 333
334 static inline thread_local KThread* current_thread{nullptr};
335
334 KThread* GetCurrentEmuThread() { 336 KThread* GetCurrentEmuThread() {
335 // If we are shutting down the kernel, none of this is relevant anymore. 337 // If we are shutting down the kernel, none of this is relevant anymore.
336 if (IsShuttingDown()) { 338 if (IsShuttingDown()) {
@@ -341,7 +343,12 @@ struct KernelCore::Impl {
341 if (thread_id >= Core::Hardware::NUM_CPU_CORES) { 343 if (thread_id >= Core::Hardware::NUM_CPU_CORES) {
342 return GetHostDummyThread(); 344 return GetHostDummyThread();
343 } 345 }
344 return schedulers[thread_id]->GetCurrentThread(); 346
347 return current_thread;
348 }
349
350 void SetCurrentEmuThread(KThread* thread) {
351 current_thread = thread;
345 } 352 }
346 353
347 void DeriveInitialMemoryLayout() { 354 void DeriveInitialMemoryLayout() {
@@ -1024,6 +1031,10 @@ KThread* KernelCore::GetCurrentEmuThread() const {
1024 return impl->GetCurrentEmuThread(); 1031 return impl->GetCurrentEmuThread();
1025} 1032}
1026 1033
1034void KernelCore::SetCurrentEmuThread(KThread* thread) {
1035 impl->SetCurrentEmuThread(thread);
1036}
1037
1027KMemoryManager& KernelCore::MemoryManager() { 1038KMemoryManager& KernelCore::MemoryManager() {
1028 return *impl->memory_manager; 1039 return *impl->memory_manager;
1029} 1040}
diff --git a/src/core/hle/kernel/kernel.h b/src/core/hle/kernel/kernel.h
index 4e7beab0e..aa0ebaa02 100644
--- a/src/core/hle/kernel/kernel.h
+++ b/src/core/hle/kernel/kernel.h
@@ -226,6 +226,9 @@ public:
226 /// Gets the current host_thread/guest_thread pointer. 226 /// Gets the current host_thread/guest_thread pointer.
227 KThread* GetCurrentEmuThread() const; 227 KThread* GetCurrentEmuThread() const;
228 228
229 /// Sets the current guest_thread pointer.
230 void SetCurrentEmuThread(KThread* thread);
231
229 /// Gets the current host_thread handle. 232 /// Gets the current host_thread handle.
230 u32 GetCurrentHostThreadID() const; 233 u32 GetCurrentHostThreadID() const;
231 234
diff --git a/src/core/hle/kernel/process_capability.cpp b/src/core/hle/kernel/process_capability.cpp
index 54872626e..773319ad8 100644
--- a/src/core/hle/kernel/process_capability.cpp
+++ b/src/core/hle/kernel/process_capability.cpp
@@ -68,9 +68,9 @@ u32 GetFlagBitOffset(CapabilityType type) {
68 68
69} // Anonymous namespace 69} // Anonymous namespace
70 70
71ResultCode ProcessCapabilities::InitializeForKernelProcess(const u32* capabilities, 71Result ProcessCapabilities::InitializeForKernelProcess(const u32* capabilities,
72 std::size_t num_capabilities, 72 std::size_t num_capabilities,
73 KPageTable& page_table) { 73 KPageTable& page_table) {
74 Clear(); 74 Clear();
75 75
76 // Allow all cores and priorities. 76 // Allow all cores and priorities.
@@ -81,9 +81,9 @@ ResultCode ProcessCapabilities::InitializeForKernelProcess(const u32* capabiliti
81 return ParseCapabilities(capabilities, num_capabilities, page_table); 81 return ParseCapabilities(capabilities, num_capabilities, page_table);
82} 82}
83 83
84ResultCode ProcessCapabilities::InitializeForUserProcess(const u32* capabilities, 84Result ProcessCapabilities::InitializeForUserProcess(const u32* capabilities,
85 std::size_t num_capabilities, 85 std::size_t num_capabilities,
86 KPageTable& page_table) { 86 KPageTable& page_table) {
87 Clear(); 87 Clear();
88 88
89 return ParseCapabilities(capabilities, num_capabilities, page_table); 89 return ParseCapabilities(capabilities, num_capabilities, page_table);
@@ -107,9 +107,8 @@ void ProcessCapabilities::InitializeForMetadatalessProcess() {
107 can_force_debug = true; 107 can_force_debug = true;
108} 108}
109 109
110ResultCode ProcessCapabilities::ParseCapabilities(const u32* capabilities, 110Result ProcessCapabilities::ParseCapabilities(const u32* capabilities, std::size_t num_capabilities,
111 std::size_t num_capabilities, 111 KPageTable& page_table) {
112 KPageTable& page_table) {
113 u32 set_flags = 0; 112 u32 set_flags = 0;
114 u32 set_svc_bits = 0; 113 u32 set_svc_bits = 0;
115 114
@@ -155,8 +154,8 @@ ResultCode ProcessCapabilities::ParseCapabilities(const u32* capabilities,
155 return ResultSuccess; 154 return ResultSuccess;
156} 155}
157 156
158ResultCode ProcessCapabilities::ParseSingleFlagCapability(u32& set_flags, u32& set_svc_bits, 157Result ProcessCapabilities::ParseSingleFlagCapability(u32& set_flags, u32& set_svc_bits, u32 flag,
159 u32 flag, KPageTable& page_table) { 158 KPageTable& page_table) {
160 const auto type = GetCapabilityType(flag); 159 const auto type = GetCapabilityType(flag);
161 160
162 if (type == CapabilityType::Unset) { 161 if (type == CapabilityType::Unset) {
@@ -224,7 +223,7 @@ void ProcessCapabilities::Clear() {
224 can_force_debug = false; 223 can_force_debug = false;
225} 224}
226 225
227ResultCode ProcessCapabilities::HandlePriorityCoreNumFlags(u32 flags) { 226Result ProcessCapabilities::HandlePriorityCoreNumFlags(u32 flags) {
228 if (priority_mask != 0 || core_mask != 0) { 227 if (priority_mask != 0 || core_mask != 0) {
229 LOG_ERROR(Kernel, "Core or priority mask are not zero! priority_mask={}, core_mask={}", 228 LOG_ERROR(Kernel, "Core or priority mask are not zero! priority_mask={}, core_mask={}",
230 priority_mask, core_mask); 229 priority_mask, core_mask);
@@ -266,7 +265,7 @@ ResultCode ProcessCapabilities::HandlePriorityCoreNumFlags(u32 flags) {
266 return ResultSuccess; 265 return ResultSuccess;
267} 266}
268 267
269ResultCode ProcessCapabilities::HandleSyscallFlags(u32& set_svc_bits, u32 flags) { 268Result ProcessCapabilities::HandleSyscallFlags(u32& set_svc_bits, u32 flags) {
270 const u32 index = flags >> 29; 269 const u32 index = flags >> 29;
271 const u32 svc_bit = 1U << index; 270 const u32 svc_bit = 1U << index;
272 271
@@ -290,23 +289,23 @@ ResultCode ProcessCapabilities::HandleSyscallFlags(u32& set_svc_bits, u32 flags)
290 return ResultSuccess; 289 return ResultSuccess;
291} 290}
292 291
293ResultCode ProcessCapabilities::HandleMapPhysicalFlags(u32 flags, u32 size_flags, 292Result ProcessCapabilities::HandleMapPhysicalFlags(u32 flags, u32 size_flags,
294 KPageTable& page_table) { 293 KPageTable& page_table) {
295 // TODO(Lioncache): Implement once the memory manager can handle this. 294 // TODO(Lioncache): Implement once the memory manager can handle this.
296 return ResultSuccess; 295 return ResultSuccess;
297} 296}
298 297
299ResultCode ProcessCapabilities::HandleMapIOFlags(u32 flags, KPageTable& page_table) { 298Result ProcessCapabilities::HandleMapIOFlags(u32 flags, KPageTable& page_table) {
300 // TODO(Lioncache): Implement once the memory manager can handle this. 299 // TODO(Lioncache): Implement once the memory manager can handle this.
301 return ResultSuccess; 300 return ResultSuccess;
302} 301}
303 302
304ResultCode ProcessCapabilities::HandleMapRegionFlags(u32 flags, KPageTable& page_table) { 303Result ProcessCapabilities::HandleMapRegionFlags(u32 flags, KPageTable& page_table) {
305 // TODO(Lioncache): Implement once the memory manager can handle this. 304 // TODO(Lioncache): Implement once the memory manager can handle this.
306 return ResultSuccess; 305 return ResultSuccess;
307} 306}
308 307
309ResultCode ProcessCapabilities::HandleInterruptFlags(u32 flags) { 308Result ProcessCapabilities::HandleInterruptFlags(u32 flags) {
310 constexpr u32 interrupt_ignore_value = 0x3FF; 309 constexpr u32 interrupt_ignore_value = 0x3FF;
311 const u32 interrupt0 = (flags >> 12) & 0x3FF; 310 const u32 interrupt0 = (flags >> 12) & 0x3FF;
312 const u32 interrupt1 = (flags >> 22) & 0x3FF; 311 const u32 interrupt1 = (flags >> 22) & 0x3FF;
@@ -333,7 +332,7 @@ ResultCode ProcessCapabilities::HandleInterruptFlags(u32 flags) {
333 return ResultSuccess; 332 return ResultSuccess;
334} 333}
335 334
336ResultCode ProcessCapabilities::HandleProgramTypeFlags(u32 flags) { 335Result ProcessCapabilities::HandleProgramTypeFlags(u32 flags) {
337 const u32 reserved = flags >> 17; 336 const u32 reserved = flags >> 17;
338 if (reserved != 0) { 337 if (reserved != 0) {
339 LOG_ERROR(Kernel, "Reserved value is non-zero! reserved={}", reserved); 338 LOG_ERROR(Kernel, "Reserved value is non-zero! reserved={}", reserved);
@@ -344,7 +343,7 @@ ResultCode ProcessCapabilities::HandleProgramTypeFlags(u32 flags) {
344 return ResultSuccess; 343 return ResultSuccess;
345} 344}
346 345
347ResultCode ProcessCapabilities::HandleKernelVersionFlags(u32 flags) { 346Result ProcessCapabilities::HandleKernelVersionFlags(u32 flags) {
348 // Yes, the internal member variable is checked in the actual kernel here. 347 // Yes, the internal member variable is checked in the actual kernel here.
349 // This might look odd for options that are only allowed to be initialized 348 // This might look odd for options that are only allowed to be initialized
350 // just once, however the kernel has a separate initialization function for 349 // just once, however the kernel has a separate initialization function for
@@ -364,7 +363,7 @@ ResultCode ProcessCapabilities::HandleKernelVersionFlags(u32 flags) {
364 return ResultSuccess; 363 return ResultSuccess;
365} 364}
366 365
367ResultCode ProcessCapabilities::HandleHandleTableFlags(u32 flags) { 366Result ProcessCapabilities::HandleHandleTableFlags(u32 flags) {
368 const u32 reserved = flags >> 26; 367 const u32 reserved = flags >> 26;
369 if (reserved != 0) { 368 if (reserved != 0) {
370 LOG_ERROR(Kernel, "Reserved value is non-zero! reserved={}", reserved); 369 LOG_ERROR(Kernel, "Reserved value is non-zero! reserved={}", reserved);
@@ -375,7 +374,7 @@ ResultCode ProcessCapabilities::HandleHandleTableFlags(u32 flags) {
375 return ResultSuccess; 374 return ResultSuccess;
376} 375}
377 376
378ResultCode ProcessCapabilities::HandleDebugFlags(u32 flags) { 377Result ProcessCapabilities::HandleDebugFlags(u32 flags) {
379 const u32 reserved = flags >> 19; 378 const u32 reserved = flags >> 19;
380 if (reserved != 0) { 379 if (reserved != 0) {
381 LOG_ERROR(Kernel, "Reserved value is non-zero! reserved={}", reserved); 380 LOG_ERROR(Kernel, "Reserved value is non-zero! reserved={}", reserved);
diff --git a/src/core/hle/kernel/process_capability.h b/src/core/hle/kernel/process_capability.h
index 7f3a2339d..ff05dc5ff 100644
--- a/src/core/hle/kernel/process_capability.h
+++ b/src/core/hle/kernel/process_capability.h
@@ -7,7 +7,7 @@
7 7
8#include "common/common_types.h" 8#include "common/common_types.h"
9 9
10union ResultCode; 10union Result;
11 11
12namespace Kernel { 12namespace Kernel {
13 13
@@ -86,8 +86,8 @@ public:
86 /// @returns ResultSuccess if this capabilities instance was able to be initialized, 86 /// @returns ResultSuccess if this capabilities instance was able to be initialized,
87 /// otherwise, an error code upon failure. 87 /// otherwise, an error code upon failure.
88 /// 88 ///
89 ResultCode InitializeForKernelProcess(const u32* capabilities, std::size_t num_capabilities, 89 Result InitializeForKernelProcess(const u32* capabilities, std::size_t num_capabilities,
90 KPageTable& page_table); 90 KPageTable& page_table);
91 91
92 /// Initializes this process capabilities instance for a userland process. 92 /// Initializes this process capabilities instance for a userland process.
93 /// 93 ///
@@ -99,8 +99,8 @@ public:
99 /// @returns ResultSuccess if this capabilities instance was able to be initialized, 99 /// @returns ResultSuccess if this capabilities instance was able to be initialized,
100 /// otherwise, an error code upon failure. 100 /// otherwise, an error code upon failure.
101 /// 101 ///
102 ResultCode InitializeForUserProcess(const u32* capabilities, std::size_t num_capabilities, 102 Result InitializeForUserProcess(const u32* capabilities, std::size_t num_capabilities,
103 KPageTable& page_table); 103 KPageTable& page_table);
104 104
105 /// Initializes this process capabilities instance for a process that does not 105 /// Initializes this process capabilities instance for a process that does not
106 /// have any metadata to parse. 106 /// have any metadata to parse.
@@ -185,8 +185,8 @@ private:
185 /// 185 ///
186 /// @return ResultSuccess if no errors occur, otherwise an error code. 186 /// @return ResultSuccess if no errors occur, otherwise an error code.
187 /// 187 ///
188 ResultCode ParseCapabilities(const u32* capabilities, std::size_t num_capabilities, 188 Result ParseCapabilities(const u32* capabilities, std::size_t num_capabilities,
189 KPageTable& page_table); 189 KPageTable& page_table);
190 190
191 /// Attempts to parse a capability descriptor that is only represented by a 191 /// Attempts to parse a capability descriptor that is only represented by a
192 /// single flag set. 192 /// single flag set.
@@ -200,8 +200,8 @@ private:
200 /// 200 ///
201 /// @return ResultSuccess if no errors occurred, otherwise an error code. 201 /// @return ResultSuccess if no errors occurred, otherwise an error code.
202 /// 202 ///
203 ResultCode ParseSingleFlagCapability(u32& set_flags, u32& set_svc_bits, u32 flag, 203 Result ParseSingleFlagCapability(u32& set_flags, u32& set_svc_bits, u32 flag,
204 KPageTable& page_table); 204 KPageTable& page_table);
205 205
206 /// Clears the internal state of this process capability instance. Necessary, 206 /// Clears the internal state of this process capability instance. Necessary,
207 /// to have a sane starting point due to us allowing running executables without 207 /// to have a sane starting point due to us allowing running executables without
@@ -219,34 +219,34 @@ private:
219 void Clear(); 219 void Clear();
220 220
221 /// Handles flags related to the priority and core number capability flags. 221 /// Handles flags related to the priority and core number capability flags.
222 ResultCode HandlePriorityCoreNumFlags(u32 flags); 222 Result HandlePriorityCoreNumFlags(u32 flags);
223 223
224 /// Handles flags related to determining the allowable SVC mask. 224 /// Handles flags related to determining the allowable SVC mask.
225 ResultCode HandleSyscallFlags(u32& set_svc_bits, u32 flags); 225 Result HandleSyscallFlags(u32& set_svc_bits, u32 flags);
226 226
227 /// Handles flags related to mapping physical memory pages. 227 /// Handles flags related to mapping physical memory pages.
228 ResultCode HandleMapPhysicalFlags(u32 flags, u32 size_flags, KPageTable& page_table); 228 Result HandleMapPhysicalFlags(u32 flags, u32 size_flags, KPageTable& page_table);
229 229
230 /// Handles flags related to mapping IO pages. 230 /// Handles flags related to mapping IO pages.
231 ResultCode HandleMapIOFlags(u32 flags, KPageTable& page_table); 231 Result HandleMapIOFlags(u32 flags, KPageTable& page_table);
232 232
233 /// Handles flags related to mapping physical memory regions. 233 /// Handles flags related to mapping physical memory regions.
234 ResultCode HandleMapRegionFlags(u32 flags, KPageTable& page_table); 234 Result HandleMapRegionFlags(u32 flags, KPageTable& page_table);
235 235
236 /// Handles flags related to the interrupt capability flags. 236 /// Handles flags related to the interrupt capability flags.
237 ResultCode HandleInterruptFlags(u32 flags); 237 Result HandleInterruptFlags(u32 flags);
238 238
239 /// Handles flags related to the program type. 239 /// Handles flags related to the program type.
240 ResultCode HandleProgramTypeFlags(u32 flags); 240 Result HandleProgramTypeFlags(u32 flags);
241 241
242 /// Handles flags related to the handle table size. 242 /// Handles flags related to the handle table size.
243 ResultCode HandleHandleTableFlags(u32 flags); 243 Result HandleHandleTableFlags(u32 flags);
244 244
245 /// Handles flags related to the kernel version capability flags. 245 /// Handles flags related to the kernel version capability flags.
246 ResultCode HandleKernelVersionFlags(u32 flags); 246 Result HandleKernelVersionFlags(u32 flags);
247 247
248 /// Handles flags related to debug-specific capabilities. 248 /// Handles flags related to debug-specific capabilities.
249 ResultCode HandleDebugFlags(u32 flags); 249 Result HandleDebugFlags(u32 flags);
250 250
251 SyscallCapabilities svc_capabilities; 251 SyscallCapabilities svc_capabilities;
252 InterruptCapabilities interrupt_capabilities; 252 InterruptCapabilities interrupt_capabilities;
diff --git a/src/core/hle/kernel/svc.cpp b/src/core/hle/kernel/svc.cpp
index 2ff6d5fa6..8655506b0 100644
--- a/src/core/hle/kernel/svc.cpp
+++ b/src/core/hle/kernel/svc.cpp
@@ -58,8 +58,8 @@ constexpr bool IsValidAddressRange(VAddr address, u64 size) {
58// Helper function that performs the common sanity checks for svcMapMemory 58// Helper function that performs the common sanity checks for svcMapMemory
59// and svcUnmapMemory. This is doable, as both functions perform their sanitizing 59// and svcUnmapMemory. This is doable, as both functions perform their sanitizing
60// in the same order. 60// in the same order.
61ResultCode MapUnmapMemorySanityChecks(const KPageTable& manager, VAddr dst_addr, VAddr src_addr, 61Result MapUnmapMemorySanityChecks(const KPageTable& manager, VAddr dst_addr, VAddr src_addr,
62 u64 size) { 62 u64 size) {
63 if (!Common::Is4KBAligned(dst_addr)) { 63 if (!Common::Is4KBAligned(dst_addr)) {
64 LOG_ERROR(Kernel_SVC, "Destination address is not aligned to 4KB, 0x{:016X}", dst_addr); 64 LOG_ERROR(Kernel_SVC, "Destination address is not aligned to 4KB, 0x{:016X}", dst_addr);
65 return ResultInvalidAddress; 65 return ResultInvalidAddress;
@@ -135,7 +135,7 @@ enum class ResourceLimitValueType {
135} // Anonymous namespace 135} // Anonymous namespace
136 136
137/// Set the process heap to a given Size. It can both extend and shrink the heap. 137/// Set the process heap to a given Size. It can both extend and shrink the heap.
138static ResultCode SetHeapSize(Core::System& system, VAddr* out_address, u64 size) { 138static Result SetHeapSize(Core::System& system, VAddr* out_address, u64 size) {
139 LOG_TRACE(Kernel_SVC, "called, heap_size=0x{:X}", size); 139 LOG_TRACE(Kernel_SVC, "called, heap_size=0x{:X}", size);
140 140
141 // Validate size. 141 // Validate size.
@@ -148,9 +148,9 @@ static ResultCode SetHeapSize(Core::System& system, VAddr* out_address, u64 size
148 return ResultSuccess; 148 return ResultSuccess;
149} 149}
150 150
151static ResultCode SetHeapSize32(Core::System& system, u32* heap_addr, u32 heap_size) { 151static Result SetHeapSize32(Core::System& system, u32* heap_addr, u32 heap_size) {
152 VAddr temp_heap_addr{}; 152 VAddr temp_heap_addr{};
153 const ResultCode result{SetHeapSize(system, &temp_heap_addr, heap_size)}; 153 const Result result{SetHeapSize(system, &temp_heap_addr, heap_size)};
154 *heap_addr = static_cast<u32>(temp_heap_addr); 154 *heap_addr = static_cast<u32>(temp_heap_addr);
155 return result; 155 return result;
156} 156}
@@ -166,8 +166,8 @@ constexpr bool IsValidSetMemoryPermission(MemoryPermission perm) {
166 } 166 }
167} 167}
168 168
169static ResultCode SetMemoryPermission(Core::System& system, VAddr address, u64 size, 169static Result SetMemoryPermission(Core::System& system, VAddr address, u64 size,
170 MemoryPermission perm) { 170 MemoryPermission perm) {
171 LOG_DEBUG(Kernel_SVC, "called, address=0x{:016X}, size=0x{:X}, perm=0x{:08X", address, size, 171 LOG_DEBUG(Kernel_SVC, "called, address=0x{:016X}, size=0x{:X}, perm=0x{:08X", address, size,
172 perm); 172 perm);
173 173
@@ -188,8 +188,8 @@ static ResultCode SetMemoryPermission(Core::System& system, VAddr address, u64 s
188 return page_table.SetMemoryPermission(address, size, perm); 188 return page_table.SetMemoryPermission(address, size, perm);
189} 189}
190 190
191static ResultCode SetMemoryAttribute(Core::System& system, VAddr address, u64 size, u32 mask, 191static Result SetMemoryAttribute(Core::System& system, VAddr address, u64 size, u32 mask,
192 u32 attr) { 192 u32 attr) {
193 LOG_DEBUG(Kernel_SVC, 193 LOG_DEBUG(Kernel_SVC,
194 "called, address=0x{:016X}, size=0x{:X}, mask=0x{:08X}, attribute=0x{:08X}", address, 194 "called, address=0x{:016X}, size=0x{:X}, mask=0x{:08X}, attribute=0x{:08X}", address,
195 size, mask, attr); 195 size, mask, attr);
@@ -213,19 +213,19 @@ static ResultCode SetMemoryAttribute(Core::System& system, VAddr address, u64 si
213 return page_table.SetMemoryAttribute(address, size, mask, attr); 213 return page_table.SetMemoryAttribute(address, size, mask, attr);
214} 214}
215 215
216static ResultCode SetMemoryAttribute32(Core::System& system, u32 address, u32 size, u32 mask, 216static Result SetMemoryAttribute32(Core::System& system, u32 address, u32 size, u32 mask,
217 u32 attr) { 217 u32 attr) {
218 return SetMemoryAttribute(system, address, size, mask, attr); 218 return SetMemoryAttribute(system, address, size, mask, attr);
219} 219}
220 220
221/// Maps a memory range into a different range. 221/// Maps a memory range into a different range.
222static ResultCode MapMemory(Core::System& system, VAddr dst_addr, VAddr src_addr, u64 size) { 222static Result MapMemory(Core::System& system, VAddr dst_addr, VAddr src_addr, u64 size) {
223 LOG_TRACE(Kernel_SVC, "called, dst_addr=0x{:X}, src_addr=0x{:X}, size=0x{:X}", dst_addr, 223 LOG_TRACE(Kernel_SVC, "called, dst_addr=0x{:X}, src_addr=0x{:X}, size=0x{:X}", dst_addr,
224 src_addr, size); 224 src_addr, size);
225 225
226 auto& page_table{system.Kernel().CurrentProcess()->PageTable()}; 226 auto& page_table{system.Kernel().CurrentProcess()->PageTable()};
227 227
228 if (const ResultCode result{MapUnmapMemorySanityChecks(page_table, dst_addr, src_addr, size)}; 228 if (const Result result{MapUnmapMemorySanityChecks(page_table, dst_addr, src_addr, size)};
229 result.IsError()) { 229 result.IsError()) {
230 return result; 230 return result;
231 } 231 }
@@ -233,18 +233,18 @@ static ResultCode MapMemory(Core::System& system, VAddr dst_addr, VAddr src_addr
233 return page_table.MapMemory(dst_addr, src_addr, size); 233 return page_table.MapMemory(dst_addr, src_addr, size);
234} 234}
235 235
236static ResultCode MapMemory32(Core::System& system, u32 dst_addr, u32 src_addr, u32 size) { 236static Result MapMemory32(Core::System& system, u32 dst_addr, u32 src_addr, u32 size) {
237 return MapMemory(system, dst_addr, src_addr, size); 237 return MapMemory(system, dst_addr, src_addr, size);
238} 238}
239 239
240/// Unmaps a region that was previously mapped with svcMapMemory 240/// Unmaps a region that was previously mapped with svcMapMemory
241static ResultCode UnmapMemory(Core::System& system, VAddr dst_addr, VAddr src_addr, u64 size) { 241static Result UnmapMemory(Core::System& system, VAddr dst_addr, VAddr src_addr, u64 size) {
242 LOG_TRACE(Kernel_SVC, "called, dst_addr=0x{:X}, src_addr=0x{:X}, size=0x{:X}", dst_addr, 242 LOG_TRACE(Kernel_SVC, "called, dst_addr=0x{:X}, src_addr=0x{:X}, size=0x{:X}", dst_addr,
243 src_addr, size); 243 src_addr, size);
244 244
245 auto& page_table{system.Kernel().CurrentProcess()->PageTable()}; 245 auto& page_table{system.Kernel().CurrentProcess()->PageTable()};
246 246
247 if (const ResultCode result{MapUnmapMemorySanityChecks(page_table, dst_addr, src_addr, size)}; 247 if (const Result result{MapUnmapMemorySanityChecks(page_table, dst_addr, src_addr, size)};
248 result.IsError()) { 248 result.IsError()) {
249 return result; 249 return result;
250 } 250 }
@@ -252,12 +252,12 @@ static ResultCode UnmapMemory(Core::System& system, VAddr dst_addr, VAddr src_ad
252 return page_table.UnmapMemory(dst_addr, src_addr, size); 252 return page_table.UnmapMemory(dst_addr, src_addr, size);
253} 253}
254 254
255static ResultCode UnmapMemory32(Core::System& system, u32 dst_addr, u32 src_addr, u32 size) { 255static Result UnmapMemory32(Core::System& system, u32 dst_addr, u32 src_addr, u32 size) {
256 return UnmapMemory(system, dst_addr, src_addr, size); 256 return UnmapMemory(system, dst_addr, src_addr, size);
257} 257}
258 258
259/// Connect to an OS service given the port name, returns the handle to the port to out 259/// Connect to an OS service given the port name, returns the handle to the port to out
260static ResultCode ConnectToNamedPort(Core::System& system, Handle* out, VAddr port_name_address) { 260static Result ConnectToNamedPort(Core::System& system, Handle* out, VAddr port_name_address) {
261 auto& memory = system.Memory(); 261 auto& memory = system.Memory();
262 if (!memory.IsValidVirtualAddress(port_name_address)) { 262 if (!memory.IsValidVirtualAddress(port_name_address)) {
263 LOG_ERROR(Kernel_SVC, 263 LOG_ERROR(Kernel_SVC,
@@ -307,14 +307,14 @@ static ResultCode ConnectToNamedPort(Core::System& system, Handle* out, VAddr po
307 return ResultSuccess; 307 return ResultSuccess;
308} 308}
309 309
310static ResultCode ConnectToNamedPort32(Core::System& system, Handle* out_handle, 310static Result ConnectToNamedPort32(Core::System& system, Handle* out_handle,
311 u32 port_name_address) { 311 u32 port_name_address) {
312 312
313 return ConnectToNamedPort(system, out_handle, port_name_address); 313 return ConnectToNamedPort(system, out_handle, port_name_address);
314} 314}
315 315
316/// Makes a blocking IPC call to an OS service. 316/// Makes a blocking IPC call to an OS service.
317static ResultCode SendSyncRequest(Core::System& system, Handle handle) { 317static Result SendSyncRequest(Core::System& system, Handle handle) {
318 auto& kernel = system.Kernel(); 318 auto& kernel = system.Kernel();
319 319
320 // Create the wait queue. 320 // Create the wait queue.
@@ -327,7 +327,6 @@ static ResultCode SendSyncRequest(Core::System& system, Handle handle) {
327 327
328 LOG_TRACE(Kernel_SVC, "called handle=0x{:08X}({})", handle, session->GetName()); 328 LOG_TRACE(Kernel_SVC, "called handle=0x{:08X}({})", handle, session->GetName());
329 329
330 auto thread = kernel.CurrentScheduler()->GetCurrentThread();
331 { 330 {
332 KScopedSchedulerLock lock(kernel); 331 KScopedSchedulerLock lock(kernel);
333 332
@@ -337,15 +336,15 @@ static ResultCode SendSyncRequest(Core::System& system, Handle handle) {
337 session->SendSyncRequest(&GetCurrentThread(kernel), system.Memory(), system.CoreTiming()); 336 session->SendSyncRequest(&GetCurrentThread(kernel), system.Memory(), system.CoreTiming());
338 } 337 }
339 338
340 return thread->GetWaitResult(); 339 return GetCurrentThread(kernel).GetWaitResult();
341} 340}
342 341
343static ResultCode SendSyncRequest32(Core::System& system, Handle handle) { 342static Result SendSyncRequest32(Core::System& system, Handle handle) {
344 return SendSyncRequest(system, handle); 343 return SendSyncRequest(system, handle);
345} 344}
346 345
347/// Get the ID for the specified thread. 346/// Get the ID for the specified thread.
348static ResultCode GetThreadId(Core::System& system, u64* out_thread_id, Handle thread_handle) { 347static Result GetThreadId(Core::System& system, u64* out_thread_id, Handle thread_handle) {
349 // Get the thread from its handle. 348 // Get the thread from its handle.
350 KScopedAutoObject thread = 349 KScopedAutoObject thread =
351 system.Kernel().CurrentProcess()->GetHandleTable().GetObject<KThread>(thread_handle); 350 system.Kernel().CurrentProcess()->GetHandleTable().GetObject<KThread>(thread_handle);
@@ -356,10 +355,10 @@ static ResultCode GetThreadId(Core::System& system, u64* out_thread_id, Handle t
356 return ResultSuccess; 355 return ResultSuccess;
357} 356}
358 357
359static ResultCode GetThreadId32(Core::System& system, u32* out_thread_id_low, 358static Result GetThreadId32(Core::System& system, u32* out_thread_id_low, u32* out_thread_id_high,
360 u32* out_thread_id_high, Handle thread_handle) { 359 Handle thread_handle) {
361 u64 out_thread_id{}; 360 u64 out_thread_id{};
362 const ResultCode result{GetThreadId(system, &out_thread_id, thread_handle)}; 361 const Result result{GetThreadId(system, &out_thread_id, thread_handle)};
363 362
364 *out_thread_id_low = static_cast<u32>(out_thread_id >> 32); 363 *out_thread_id_low = static_cast<u32>(out_thread_id >> 32);
365 *out_thread_id_high = static_cast<u32>(out_thread_id & std::numeric_limits<u32>::max()); 364 *out_thread_id_high = static_cast<u32>(out_thread_id & std::numeric_limits<u32>::max());
@@ -368,7 +367,7 @@ static ResultCode GetThreadId32(Core::System& system, u32* out_thread_id_low,
368} 367}
369 368
370/// Gets the ID of the specified process or a specified thread's owning process. 369/// Gets the ID of the specified process or a specified thread's owning process.
371static ResultCode GetProcessId(Core::System& system, u64* out_process_id, Handle handle) { 370static Result GetProcessId(Core::System& system, u64* out_process_id, Handle handle) {
372 LOG_DEBUG(Kernel_SVC, "called handle=0x{:08X}", handle); 371 LOG_DEBUG(Kernel_SVC, "called handle=0x{:08X}", handle);
373 372
374 // Get the object from the handle table. 373 // Get the object from the handle table.
@@ -399,8 +398,8 @@ static ResultCode GetProcessId(Core::System& system, u64* out_process_id, Handle
399 return ResultSuccess; 398 return ResultSuccess;
400} 399}
401 400
402static ResultCode GetProcessId32(Core::System& system, u32* out_process_id_low, 401static Result GetProcessId32(Core::System& system, u32* out_process_id_low,
403 u32* out_process_id_high, Handle handle) { 402 u32* out_process_id_high, Handle handle) {
404 u64 out_process_id{}; 403 u64 out_process_id{};
405 const auto result = GetProcessId(system, &out_process_id, handle); 404 const auto result = GetProcessId(system, &out_process_id, handle);
406 *out_process_id_low = static_cast<u32>(out_process_id); 405 *out_process_id_low = static_cast<u32>(out_process_id);
@@ -409,8 +408,8 @@ static ResultCode GetProcessId32(Core::System& system, u32* out_process_id_low,
409} 408}
410 409
411/// Wait for the given handles to synchronize, timeout after the specified nanoseconds 410/// Wait for the given handles to synchronize, timeout after the specified nanoseconds
412static ResultCode WaitSynchronization(Core::System& system, s32* index, VAddr handles_address, 411static Result WaitSynchronization(Core::System& system, s32* index, VAddr handles_address,
413 s32 num_handles, s64 nano_seconds) { 412 s32 num_handles, s64 nano_seconds) {
414 LOG_TRACE(Kernel_SVC, "called handles_address=0x{:X}, num_handles={}, nano_seconds={}", 413 LOG_TRACE(Kernel_SVC, "called handles_address=0x{:X}, num_handles={}, nano_seconds={}",
415 handles_address, num_handles, nano_seconds); 414 handles_address, num_handles, nano_seconds);
416 415
@@ -445,14 +444,14 @@ static ResultCode WaitSynchronization(Core::System& system, s32* index, VAddr ha
445 nano_seconds); 444 nano_seconds);
446} 445}
447 446
448static ResultCode WaitSynchronization32(Core::System& system, u32 timeout_low, u32 handles_address, 447static Result WaitSynchronization32(Core::System& system, u32 timeout_low, u32 handles_address,
449 s32 num_handles, u32 timeout_high, s32* index) { 448 s32 num_handles, u32 timeout_high, s32* index) {
450 const s64 nano_seconds{(static_cast<s64>(timeout_high) << 32) | static_cast<s64>(timeout_low)}; 449 const s64 nano_seconds{(static_cast<s64>(timeout_high) << 32) | static_cast<s64>(timeout_low)};
451 return WaitSynchronization(system, index, handles_address, num_handles, nano_seconds); 450 return WaitSynchronization(system, index, handles_address, num_handles, nano_seconds);
452} 451}
453 452
454/// Resumes a thread waiting on WaitSynchronization 453/// Resumes a thread waiting on WaitSynchronization
455static ResultCode CancelSynchronization(Core::System& system, Handle handle) { 454static Result CancelSynchronization(Core::System& system, Handle handle) {
456 LOG_TRACE(Kernel_SVC, "called handle=0x{:X}", handle); 455 LOG_TRACE(Kernel_SVC, "called handle=0x{:X}", handle);
457 456
458 // Get the thread from its handle. 457 // Get the thread from its handle.
@@ -465,13 +464,12 @@ static ResultCode CancelSynchronization(Core::System& system, Handle handle) {
465 return ResultSuccess; 464 return ResultSuccess;
466} 465}
467 466
468static ResultCode CancelSynchronization32(Core::System& system, Handle handle) { 467static Result CancelSynchronization32(Core::System& system, Handle handle) {
469 return CancelSynchronization(system, handle); 468 return CancelSynchronization(system, handle);
470} 469}
471 470
472/// Attempts to locks a mutex 471/// Attempts to locks a mutex
473static ResultCode ArbitrateLock(Core::System& system, Handle thread_handle, VAddr address, 472static Result ArbitrateLock(Core::System& system, Handle thread_handle, VAddr address, u32 tag) {
474 u32 tag) {
475 LOG_TRACE(Kernel_SVC, "called thread_handle=0x{:08X}, address=0x{:X}, tag=0x{:08X}", 473 LOG_TRACE(Kernel_SVC, "called thread_handle=0x{:08X}, address=0x{:X}, tag=0x{:08X}",
476 thread_handle, address, tag); 474 thread_handle, address, tag);
477 475
@@ -489,13 +487,12 @@ static ResultCode ArbitrateLock(Core::System& system, Handle thread_handle, VAdd
489 return system.Kernel().CurrentProcess()->WaitForAddress(thread_handle, address, tag); 487 return system.Kernel().CurrentProcess()->WaitForAddress(thread_handle, address, tag);
490} 488}
491 489
492static ResultCode ArbitrateLock32(Core::System& system, Handle thread_handle, u32 address, 490static Result ArbitrateLock32(Core::System& system, Handle thread_handle, u32 address, u32 tag) {
493 u32 tag) {
494 return ArbitrateLock(system, thread_handle, address, tag); 491 return ArbitrateLock(system, thread_handle, address, tag);
495} 492}
496 493
497/// Unlock a mutex 494/// Unlock a mutex
498static ResultCode ArbitrateUnlock(Core::System& system, VAddr address) { 495static Result ArbitrateUnlock(Core::System& system, VAddr address) {
499 LOG_TRACE(Kernel_SVC, "called address=0x{:X}", address); 496 LOG_TRACE(Kernel_SVC, "called address=0x{:X}", address);
500 497
501 // Validate the input address. 498 // Validate the input address.
@@ -513,7 +510,7 @@ static ResultCode ArbitrateUnlock(Core::System& system, VAddr address) {
513 return system.Kernel().CurrentProcess()->SignalToAddress(address); 510 return system.Kernel().CurrentProcess()->SignalToAddress(address);
514} 511}
515 512
516static ResultCode ArbitrateUnlock32(Core::System& system, u32 address) { 513static Result ArbitrateUnlock32(Core::System& system, u32 address) {
517 return ArbitrateUnlock(system, address); 514 return ArbitrateUnlock(system, address);
518} 515}
519 516
@@ -624,7 +621,7 @@ static void Break(Core::System& system, u32 reason, u64 info1, u64 info2) {
624 621
625 handle_debug_buffer(info1, info2); 622 handle_debug_buffer(info1, info2);
626 623
627 auto* const current_thread = system.Kernel().CurrentScheduler()->GetCurrentThread(); 624 auto* const current_thread = GetCurrentThreadPointer(system.Kernel());
628 const auto thread_processor_id = current_thread->GetActiveCore(); 625 const auto thread_processor_id = current_thread->GetActiveCore();
629 system.ArmInterface(static_cast<std::size_t>(thread_processor_id)).LogBacktrace(); 626 system.ArmInterface(static_cast<std::size_t>(thread_processor_id)).LogBacktrace();
630 } 627 }
@@ -656,8 +653,8 @@ static void OutputDebugString32(Core::System& system, u32 address, u32 len) {
656} 653}
657 654
658/// Gets system/memory information for the current process 655/// Gets system/memory information for the current process
659static ResultCode GetInfo(Core::System& system, u64* result, u64 info_id, Handle handle, 656static Result GetInfo(Core::System& system, u64* result, u64 info_id, Handle handle,
660 u64 info_sub_id) { 657 u64 info_sub_id) {
661 LOG_TRACE(Kernel_SVC, "called info_id=0x{:X}, info_sub_id=0x{:X}, handle=0x{:08X}", info_id, 658 LOG_TRACE(Kernel_SVC, "called info_id=0x{:X}, info_sub_id=0x{:X}, handle=0x{:08X}", info_id,
662 info_sub_id, handle); 659 info_sub_id, handle);
663 660
@@ -692,6 +689,9 @@ static ResultCode GetInfo(Core::System& system, u64* result, u64 info_id, Handle
692 // 6.0.0+ 689 // 6.0.0+
693 TotalPhysicalMemoryAvailableWithoutSystemResource = 21, 690 TotalPhysicalMemoryAvailableWithoutSystemResource = 21,
694 TotalPhysicalMemoryUsedWithoutSystemResource = 22, 691 TotalPhysicalMemoryUsedWithoutSystemResource = 22,
692
693 // Homebrew only
694 MesosphereCurrentProcess = 65001,
695 }; 695 };
696 696
697 const auto info_id_type = static_cast<GetInfoType>(info_id); 697 const auto info_id_type = static_cast<GetInfoType>(info_id);
@@ -884,7 +884,7 @@ static ResultCode GetInfo(Core::System& system, u64* result, u64 info_id, Handle
884 884
885 const auto& core_timing = system.CoreTiming(); 885 const auto& core_timing = system.CoreTiming();
886 const auto& scheduler = *system.Kernel().CurrentScheduler(); 886 const auto& scheduler = *system.Kernel().CurrentScheduler();
887 const auto* const current_thread = scheduler.GetCurrentThread(); 887 const auto* const current_thread = GetCurrentThreadPointer(system.Kernel());
888 const bool same_thread = current_thread == thread.GetPointerUnsafe(); 888 const bool same_thread = current_thread == thread.GetPointerUnsafe();
889 889
890 const u64 prev_ctx_ticks = scheduler.GetLastContextSwitchTicks(); 890 const u64 prev_ctx_ticks = scheduler.GetLastContextSwitchTicks();
@@ -914,18 +914,39 @@ static ResultCode GetInfo(Core::System& system, u64* result, u64 info_id, Handle
914 *result = system.Kernel().CurrentScheduler()->GetIdleThread()->GetCpuTime(); 914 *result = system.Kernel().CurrentScheduler()->GetIdleThread()->GetCpuTime();
915 return ResultSuccess; 915 return ResultSuccess;
916 } 916 }
917 case GetInfoType::MesosphereCurrentProcess: {
918 // Verify the input handle is invalid.
919 R_UNLESS(handle == InvalidHandle, ResultInvalidHandle);
920
921 // Verify the sub-type is valid.
922 R_UNLESS(info_sub_id == 0, ResultInvalidCombination);
923
924 // Get the handle table.
925 KProcess* current_process = system.Kernel().CurrentProcess();
926 KHandleTable& handle_table = current_process->GetHandleTable();
927
928 // Get a new handle for the current process.
929 Handle tmp;
930 R_TRY(handle_table.Add(&tmp, current_process));
931
932 // Set the output.
933 *result = tmp;
934
935 // We succeeded.
936 return ResultSuccess;
937 }
917 default: 938 default:
918 LOG_ERROR(Kernel_SVC, "Unimplemented svcGetInfo id=0x{:016X}", info_id); 939 LOG_ERROR(Kernel_SVC, "Unimplemented svcGetInfo id=0x{:016X}", info_id);
919 return ResultInvalidEnumValue; 940 return ResultInvalidEnumValue;
920 } 941 }
921} 942}
922 943
923static ResultCode GetInfo32(Core::System& system, u32* result_low, u32* result_high, u32 sub_id_low, 944static Result GetInfo32(Core::System& system, u32* result_low, u32* result_high, u32 sub_id_low,
924 u32 info_id, u32 handle, u32 sub_id_high) { 945 u32 info_id, u32 handle, u32 sub_id_high) {
925 const u64 sub_id{u64{sub_id_low} | (u64{sub_id_high} << 32)}; 946 const u64 sub_id{u64{sub_id_low} | (u64{sub_id_high} << 32)};
926 u64 res_value{}; 947 u64 res_value{};
927 948
928 const ResultCode result{GetInfo(system, &res_value, info_id, handle, sub_id)}; 949 const Result result{GetInfo(system, &res_value, info_id, handle, sub_id)};
929 *result_high = static_cast<u32>(res_value >> 32); 950 *result_high = static_cast<u32>(res_value >> 32);
930 *result_low = static_cast<u32>(res_value & std::numeric_limits<u32>::max()); 951 *result_low = static_cast<u32>(res_value & std::numeric_limits<u32>::max());
931 952
@@ -933,7 +954,7 @@ static ResultCode GetInfo32(Core::System& system, u32* result_low, u32* result_h
933} 954}
934 955
935/// Maps memory at a desired address 956/// Maps memory at a desired address
936static ResultCode MapPhysicalMemory(Core::System& system, VAddr addr, u64 size) { 957static Result MapPhysicalMemory(Core::System& system, VAddr addr, u64 size) {
937 LOG_DEBUG(Kernel_SVC, "called, addr=0x{:016X}, size=0x{:X}", addr, size); 958 LOG_DEBUG(Kernel_SVC, "called, addr=0x{:016X}, size=0x{:X}", addr, size);
938 959
939 if (!Common::Is4KBAligned(addr)) { 960 if (!Common::Is4KBAligned(addr)) {
@@ -981,12 +1002,12 @@ static ResultCode MapPhysicalMemory(Core::System& system, VAddr addr, u64 size)
981 return page_table.MapPhysicalMemory(addr, size); 1002 return page_table.MapPhysicalMemory(addr, size);
982} 1003}
983 1004
984static ResultCode MapPhysicalMemory32(Core::System& system, u32 addr, u32 size) { 1005static Result MapPhysicalMemory32(Core::System& system, u32 addr, u32 size) {
985 return MapPhysicalMemory(system, addr, size); 1006 return MapPhysicalMemory(system, addr, size);
986} 1007}
987 1008
988/// Unmaps memory previously mapped via MapPhysicalMemory 1009/// Unmaps memory previously mapped via MapPhysicalMemory
989static ResultCode UnmapPhysicalMemory(Core::System& system, VAddr addr, u64 size) { 1010static Result UnmapPhysicalMemory(Core::System& system, VAddr addr, u64 size) {
990 LOG_DEBUG(Kernel_SVC, "called, addr=0x{:016X}, size=0x{:X}", addr, size); 1011 LOG_DEBUG(Kernel_SVC, "called, addr=0x{:016X}, size=0x{:X}", addr, size);
991 1012
992 if (!Common::Is4KBAligned(addr)) { 1013 if (!Common::Is4KBAligned(addr)) {
@@ -1034,13 +1055,13 @@ static ResultCode UnmapPhysicalMemory(Core::System& system, VAddr addr, u64 size
1034 return page_table.UnmapPhysicalMemory(addr, size); 1055 return page_table.UnmapPhysicalMemory(addr, size);
1035} 1056}
1036 1057
1037static ResultCode UnmapPhysicalMemory32(Core::System& system, u32 addr, u32 size) { 1058static Result UnmapPhysicalMemory32(Core::System& system, u32 addr, u32 size) {
1038 return UnmapPhysicalMemory(system, addr, size); 1059 return UnmapPhysicalMemory(system, addr, size);
1039} 1060}
1040 1061
1041/// Sets the thread activity 1062/// Sets the thread activity
1042static ResultCode SetThreadActivity(Core::System& system, Handle thread_handle, 1063static Result SetThreadActivity(Core::System& system, Handle thread_handle,
1043 ThreadActivity thread_activity) { 1064 ThreadActivity thread_activity) {
1044 LOG_DEBUG(Kernel_SVC, "called, handle=0x{:08X}, activity=0x{:08X}", thread_handle, 1065 LOG_DEBUG(Kernel_SVC, "called, handle=0x{:08X}, activity=0x{:08X}", thread_handle,
1045 thread_activity); 1066 thread_activity);
1046 1067
@@ -1065,13 +1086,13 @@ static ResultCode SetThreadActivity(Core::System& system, Handle thread_handle,
1065 return ResultSuccess; 1086 return ResultSuccess;
1066} 1087}
1067 1088
1068static ResultCode SetThreadActivity32(Core::System& system, Handle thread_handle, 1089static Result SetThreadActivity32(Core::System& system, Handle thread_handle,
1069 Svc::ThreadActivity thread_activity) { 1090 Svc::ThreadActivity thread_activity) {
1070 return SetThreadActivity(system, thread_handle, thread_activity); 1091 return SetThreadActivity(system, thread_handle, thread_activity);
1071} 1092}
1072 1093
1073/// Gets the thread context 1094/// Gets the thread context
1074static ResultCode GetThreadContext(Core::System& system, VAddr out_context, Handle thread_handle) { 1095static Result GetThreadContext(Core::System& system, VAddr out_context, Handle thread_handle) {
1075 LOG_DEBUG(Kernel_SVC, "called, out_context=0x{:08X}, thread_handle=0x{:X}", out_context, 1096 LOG_DEBUG(Kernel_SVC, "called, out_context=0x{:08X}, thread_handle=0x{:X}", out_context,
1076 thread_handle); 1097 thread_handle);
1077 1098
@@ -1103,7 +1124,7 @@ static ResultCode GetThreadContext(Core::System& system, VAddr out_context, Hand
1103 if (thread->GetRawState() != ThreadState::Runnable) { 1124 if (thread->GetRawState() != ThreadState::Runnable) {
1104 bool current = false; 1125 bool current = false;
1105 for (auto i = 0; i < static_cast<s32>(Core::Hardware::NUM_CPU_CORES); ++i) { 1126 for (auto i = 0; i < static_cast<s32>(Core::Hardware::NUM_CPU_CORES); ++i) {
1106 if (thread.GetPointerUnsafe() == kernel.Scheduler(i).GetCurrentThread()) { 1127 if (thread.GetPointerUnsafe() == kernel.Scheduler(i).GetSchedulerCurrentThread()) {
1107 current = true; 1128 current = true;
1108 break; 1129 break;
1109 } 1130 }
@@ -1128,12 +1149,12 @@ static ResultCode GetThreadContext(Core::System& system, VAddr out_context, Hand
1128 return ResultSuccess; 1149 return ResultSuccess;
1129} 1150}
1130 1151
1131static ResultCode GetThreadContext32(Core::System& system, u32 out_context, Handle thread_handle) { 1152static Result GetThreadContext32(Core::System& system, u32 out_context, Handle thread_handle) {
1132 return GetThreadContext(system, out_context, thread_handle); 1153 return GetThreadContext(system, out_context, thread_handle);
1133} 1154}
1134 1155
1135/// Gets the priority for the specified thread 1156/// Gets the priority for the specified thread
1136static ResultCode GetThreadPriority(Core::System& system, u32* out_priority, Handle handle) { 1157static Result GetThreadPriority(Core::System& system, u32* out_priority, Handle handle) {
1137 LOG_TRACE(Kernel_SVC, "called"); 1158 LOG_TRACE(Kernel_SVC, "called");
1138 1159
1139 // Get the thread from its handle. 1160 // Get the thread from its handle.
@@ -1146,12 +1167,12 @@ static ResultCode GetThreadPriority(Core::System& system, u32* out_priority, Han
1146 return ResultSuccess; 1167 return ResultSuccess;
1147} 1168}
1148 1169
1149static ResultCode GetThreadPriority32(Core::System& system, u32* out_priority, Handle handle) { 1170static Result GetThreadPriority32(Core::System& system, u32* out_priority, Handle handle) {
1150 return GetThreadPriority(system, out_priority, handle); 1171 return GetThreadPriority(system, out_priority, handle);
1151} 1172}
1152 1173
1153/// Sets the priority for the specified thread 1174/// Sets the priority for the specified thread
1154static ResultCode SetThreadPriority(Core::System& system, Handle thread_handle, u32 priority) { 1175static Result SetThreadPriority(Core::System& system, Handle thread_handle, u32 priority) {
1155 // Get the current process. 1176 // Get the current process.
1156 KProcess& process = *system.Kernel().CurrentProcess(); 1177 KProcess& process = *system.Kernel().CurrentProcess();
1157 1178
@@ -1169,7 +1190,7 @@ static ResultCode SetThreadPriority(Core::System& system, Handle thread_handle,
1169 return ResultSuccess; 1190 return ResultSuccess;
1170} 1191}
1171 1192
1172static ResultCode SetThreadPriority32(Core::System& system, Handle thread_handle, u32 priority) { 1193static Result SetThreadPriority32(Core::System& system, Handle thread_handle, u32 priority) {
1173 return SetThreadPriority(system, thread_handle, priority); 1194 return SetThreadPriority(system, thread_handle, priority);
1174} 1195}
1175 1196
@@ -1229,8 +1250,8 @@ constexpr bool IsValidUnmapFromOwnerCodeMemoryPermission(Svc::MemoryPermission p
1229 1250
1230} // Anonymous namespace 1251} // Anonymous namespace
1231 1252
1232static ResultCode MapSharedMemory(Core::System& system, Handle shmem_handle, VAddr address, 1253static Result MapSharedMemory(Core::System& system, Handle shmem_handle, VAddr address, u64 size,
1233 u64 size, Svc::MemoryPermission map_perm) { 1254 Svc::MemoryPermission map_perm) {
1234 LOG_TRACE(Kernel_SVC, 1255 LOG_TRACE(Kernel_SVC,
1235 "called, shared_memory_handle=0x{:X}, addr=0x{:X}, size=0x{:X}, permissions=0x{:08X}", 1256 "called, shared_memory_handle=0x{:X}, addr=0x{:X}, size=0x{:X}, permissions=0x{:08X}",
1236 shmem_handle, address, size, map_perm); 1257 shmem_handle, address, size, map_perm);
@@ -1270,13 +1291,13 @@ static ResultCode MapSharedMemory(Core::System& system, Handle shmem_handle, VAd
1270 return ResultSuccess; 1291 return ResultSuccess;
1271} 1292}
1272 1293
1273static ResultCode MapSharedMemory32(Core::System& system, Handle shmem_handle, u32 address, 1294static Result MapSharedMemory32(Core::System& system, Handle shmem_handle, u32 address, u32 size,
1274 u32 size, Svc::MemoryPermission map_perm) { 1295 Svc::MemoryPermission map_perm) {
1275 return MapSharedMemory(system, shmem_handle, address, size, map_perm); 1296 return MapSharedMemory(system, shmem_handle, address, size, map_perm);
1276} 1297}
1277 1298
1278static ResultCode UnmapSharedMemory(Core::System& system, Handle shmem_handle, VAddr address, 1299static Result UnmapSharedMemory(Core::System& system, Handle shmem_handle, VAddr address,
1279 u64 size) { 1300 u64 size) {
1280 // Validate the address/size. 1301 // Validate the address/size.
1281 R_UNLESS(Common::IsAligned(address, PageSize), ResultInvalidAddress); 1302 R_UNLESS(Common::IsAligned(address, PageSize), ResultInvalidAddress);
1282 R_UNLESS(Common::IsAligned(size, PageSize), ResultInvalidSize); 1303 R_UNLESS(Common::IsAligned(size, PageSize), ResultInvalidSize);
@@ -1303,13 +1324,13 @@ static ResultCode UnmapSharedMemory(Core::System& system, Handle shmem_handle, V
1303 return ResultSuccess; 1324 return ResultSuccess;
1304} 1325}
1305 1326
1306static ResultCode UnmapSharedMemory32(Core::System& system, Handle shmem_handle, u32 address, 1327static Result UnmapSharedMemory32(Core::System& system, Handle shmem_handle, u32 address,
1307 u32 size) { 1328 u32 size) {
1308 return UnmapSharedMemory(system, shmem_handle, address, size); 1329 return UnmapSharedMemory(system, shmem_handle, address, size);
1309} 1330}
1310 1331
1311static ResultCode SetProcessMemoryPermission(Core::System& system, Handle process_handle, 1332static Result SetProcessMemoryPermission(Core::System& system, Handle process_handle, VAddr address,
1312 VAddr address, u64 size, Svc::MemoryPermission perm) { 1333 u64 size, Svc::MemoryPermission perm) {
1313 LOG_TRACE(Kernel_SVC, 1334 LOG_TRACE(Kernel_SVC,
1314 "called, process_handle=0x{:X}, addr=0x{:X}, size=0x{:X}, permissions=0x{:08X}", 1335 "called, process_handle=0x{:X}, addr=0x{:X}, size=0x{:X}, permissions=0x{:08X}",
1315 process_handle, address, size, perm); 1336 process_handle, address, size, perm);
@@ -1338,8 +1359,8 @@ static ResultCode SetProcessMemoryPermission(Core::System& system, Handle proces
1338 return page_table.SetProcessMemoryPermission(address, size, perm); 1359 return page_table.SetProcessMemoryPermission(address, size, perm);
1339} 1360}
1340 1361
1341static ResultCode MapProcessMemory(Core::System& system, VAddr dst_address, Handle process_handle, 1362static Result MapProcessMemory(Core::System& system, VAddr dst_address, Handle process_handle,
1342 VAddr src_address, u64 size) { 1363 VAddr src_address, u64 size) {
1343 LOG_TRACE(Kernel_SVC, 1364 LOG_TRACE(Kernel_SVC,
1344 "called, dst_address=0x{:X}, process_handle=0x{:X}, src_address=0x{:X}, size=0x{:X}", 1365 "called, dst_address=0x{:X}, process_handle=0x{:X}, src_address=0x{:X}, size=0x{:X}",
1345 dst_address, process_handle, src_address, size); 1366 dst_address, process_handle, src_address, size);
@@ -1368,7 +1389,7 @@ static ResultCode MapProcessMemory(Core::System& system, VAddr dst_address, Hand
1368 ResultInvalidMemoryRegion); 1389 ResultInvalidMemoryRegion);
1369 1390
1370 // Create a new page group. 1391 // Create a new page group.
1371 KPageLinkedList pg; 1392 KPageGroup pg;
1372 R_TRY(src_pt.MakeAndOpenPageGroup( 1393 R_TRY(src_pt.MakeAndOpenPageGroup(
1373 std::addressof(pg), src_address, size / PageSize, KMemoryState::FlagCanMapProcess, 1394 std::addressof(pg), src_address, size / PageSize, KMemoryState::FlagCanMapProcess,
1374 KMemoryState::FlagCanMapProcess, KMemoryPermission::None, KMemoryPermission::None, 1395 KMemoryState::FlagCanMapProcess, KMemoryPermission::None, KMemoryPermission::None,
@@ -1381,8 +1402,8 @@ static ResultCode MapProcessMemory(Core::System& system, VAddr dst_address, Hand
1381 return ResultSuccess; 1402 return ResultSuccess;
1382} 1403}
1383 1404
1384static ResultCode UnmapProcessMemory(Core::System& system, VAddr dst_address, Handle process_handle, 1405static Result UnmapProcessMemory(Core::System& system, VAddr dst_address, Handle process_handle,
1385 VAddr src_address, u64 size) { 1406 VAddr src_address, u64 size) {
1386 LOG_TRACE(Kernel_SVC, 1407 LOG_TRACE(Kernel_SVC,
1387 "called, dst_address=0x{:X}, process_handle=0x{:X}, src_address=0x{:X}, size=0x{:X}", 1408 "called, dst_address=0x{:X}, process_handle=0x{:X}, src_address=0x{:X}, size=0x{:X}",
1388 dst_address, process_handle, src_address, size); 1409 dst_address, process_handle, src_address, size);
@@ -1416,7 +1437,7 @@ static ResultCode UnmapProcessMemory(Core::System& system, VAddr dst_address, Ha
1416 return ResultSuccess; 1437 return ResultSuccess;
1417} 1438}
1418 1439
1419static ResultCode CreateCodeMemory(Core::System& system, Handle* out, VAddr address, size_t size) { 1440static Result CreateCodeMemory(Core::System& system, Handle* out, VAddr address, size_t size) {
1420 LOG_TRACE(Kernel_SVC, "called, address=0x{:X}, size=0x{:X}", address, size); 1441 LOG_TRACE(Kernel_SVC, "called, address=0x{:X}, size=0x{:X}", address, size);
1421 1442
1422 // Get kernel instance. 1443 // Get kernel instance.
@@ -1451,12 +1472,12 @@ static ResultCode CreateCodeMemory(Core::System& system, Handle* out, VAddr addr
1451 return ResultSuccess; 1472 return ResultSuccess;
1452} 1473}
1453 1474
1454static ResultCode CreateCodeMemory32(Core::System& system, Handle* out, u32 address, u32 size) { 1475static Result CreateCodeMemory32(Core::System& system, Handle* out, u32 address, u32 size) {
1455 return CreateCodeMemory(system, out, address, size); 1476 return CreateCodeMemory(system, out, address, size);
1456} 1477}
1457 1478
1458static ResultCode ControlCodeMemory(Core::System& system, Handle code_memory_handle, u32 operation, 1479static Result ControlCodeMemory(Core::System& system, Handle code_memory_handle, u32 operation,
1459 VAddr address, size_t size, Svc::MemoryPermission perm) { 1480 VAddr address, size_t size, Svc::MemoryPermission perm) {
1460 1481
1461 LOG_TRACE(Kernel_SVC, 1482 LOG_TRACE(Kernel_SVC,
1462 "called, code_memory_handle=0x{:X}, operation=0x{:X}, address=0x{:X}, size=0x{:X}, " 1483 "called, code_memory_handle=0x{:X}, operation=0x{:X}, address=0x{:X}, size=0x{:X}, "
@@ -1534,15 +1555,13 @@ static ResultCode ControlCodeMemory(Core::System& system, Handle code_memory_han
1534 return ResultSuccess; 1555 return ResultSuccess;
1535} 1556}
1536 1557
1537static ResultCode ControlCodeMemory32(Core::System& system, Handle code_memory_handle, 1558static Result ControlCodeMemory32(Core::System& system, Handle code_memory_handle, u32 operation,
1538 u32 operation, u64 address, u64 size, 1559 u64 address, u64 size, Svc::MemoryPermission perm) {
1539 Svc::MemoryPermission perm) {
1540 return ControlCodeMemory(system, code_memory_handle, operation, address, size, perm); 1560 return ControlCodeMemory(system, code_memory_handle, operation, address, size, perm);
1541} 1561}
1542 1562
1543static ResultCode QueryProcessMemory(Core::System& system, VAddr memory_info_address, 1563static Result QueryProcessMemory(Core::System& system, VAddr memory_info_address,
1544 VAddr page_info_address, Handle process_handle, 1564 VAddr page_info_address, Handle process_handle, VAddr address) {
1545 VAddr address) {
1546 LOG_TRACE(Kernel_SVC, "called process=0x{:08X} address={:X}", process_handle, address); 1565 LOG_TRACE(Kernel_SVC, "called process=0x{:08X} address={:X}", process_handle, address);
1547 const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable(); 1566 const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
1548 KScopedAutoObject process = handle_table.GetObject<KProcess>(process_handle); 1567 KScopedAutoObject process = handle_table.GetObject<KProcess>(process_handle);
@@ -1570,8 +1589,8 @@ static ResultCode QueryProcessMemory(Core::System& system, VAddr memory_info_add
1570 return ResultSuccess; 1589 return ResultSuccess;
1571} 1590}
1572 1591
1573static ResultCode QueryMemory(Core::System& system, VAddr memory_info_address, 1592static Result QueryMemory(Core::System& system, VAddr memory_info_address, VAddr page_info_address,
1574 VAddr page_info_address, VAddr query_address) { 1593 VAddr query_address) {
1575 LOG_TRACE(Kernel_SVC, 1594 LOG_TRACE(Kernel_SVC,
1576 "called, memory_info_address=0x{:016X}, page_info_address=0x{:016X}, " 1595 "called, memory_info_address=0x{:016X}, page_info_address=0x{:016X}, "
1577 "query_address=0x{:016X}", 1596 "query_address=0x{:016X}",
@@ -1581,13 +1600,13 @@ static ResultCode QueryMemory(Core::System& system, VAddr memory_info_address,
1581 query_address); 1600 query_address);
1582} 1601}
1583 1602
1584static ResultCode QueryMemory32(Core::System& system, u32 memory_info_address, 1603static Result QueryMemory32(Core::System& system, u32 memory_info_address, u32 page_info_address,
1585 u32 page_info_address, u32 query_address) { 1604 u32 query_address) {
1586 return QueryMemory(system, memory_info_address, page_info_address, query_address); 1605 return QueryMemory(system, memory_info_address, page_info_address, query_address);
1587} 1606}
1588 1607
1589static ResultCode MapProcessCodeMemory(Core::System& system, Handle process_handle, u64 dst_address, 1608static Result MapProcessCodeMemory(Core::System& system, Handle process_handle, u64 dst_address,
1590 u64 src_address, u64 size) { 1609 u64 src_address, u64 size) {
1591 LOG_DEBUG(Kernel_SVC, 1610 LOG_DEBUG(Kernel_SVC,
1592 "called. process_handle=0x{:08X}, dst_address=0x{:016X}, " 1611 "called. process_handle=0x{:08X}, dst_address=0x{:016X}, "
1593 "src_address=0x{:016X}, size=0x{:016X}", 1612 "src_address=0x{:016X}, size=0x{:016X}",
@@ -1654,8 +1673,8 @@ static ResultCode MapProcessCodeMemory(Core::System& system, Handle process_hand
1654 return page_table.MapCodeMemory(dst_address, src_address, size); 1673 return page_table.MapCodeMemory(dst_address, src_address, size);
1655} 1674}
1656 1675
1657static ResultCode UnmapProcessCodeMemory(Core::System& system, Handle process_handle, 1676static Result UnmapProcessCodeMemory(Core::System& system, Handle process_handle, u64 dst_address,
1658 u64 dst_address, u64 src_address, u64 size) { 1677 u64 src_address, u64 size) {
1659 LOG_DEBUG(Kernel_SVC, 1678 LOG_DEBUG(Kernel_SVC,
1660 "called. process_handle=0x{:08X}, dst_address=0x{:016X}, src_address=0x{:016X}, " 1679 "called. process_handle=0x{:08X}, dst_address=0x{:016X}, src_address=0x{:016X}, "
1661 "size=0x{:016X}", 1680 "size=0x{:016X}",
@@ -1747,8 +1766,8 @@ constexpr bool IsValidVirtualCoreId(int32_t core_id) {
1747} // Anonymous namespace 1766} // Anonymous namespace
1748 1767
1749/// Creates a new thread 1768/// Creates a new thread
1750static ResultCode CreateThread(Core::System& system, Handle* out_handle, VAddr entry_point, u64 arg, 1769static Result CreateThread(Core::System& system, Handle* out_handle, VAddr entry_point, u64 arg,
1751 VAddr stack_bottom, u32 priority, s32 core_id) { 1770 VAddr stack_bottom, u32 priority, s32 core_id) {
1752 LOG_DEBUG(Kernel_SVC, 1771 LOG_DEBUG(Kernel_SVC,
1753 "called entry_point=0x{:08X}, arg=0x{:08X}, stack_bottom=0x{:08X}, " 1772 "called entry_point=0x{:08X}, arg=0x{:08X}, stack_bottom=0x{:08X}, "
1754 "priority=0x{:08X}, core_id=0x{:08X}", 1773 "priority=0x{:08X}, core_id=0x{:08X}",
@@ -1819,13 +1838,13 @@ static ResultCode CreateThread(Core::System& system, Handle* out_handle, VAddr e
1819 return ResultSuccess; 1838 return ResultSuccess;
1820} 1839}
1821 1840
1822static ResultCode CreateThread32(Core::System& system, Handle* out_handle, u32 priority, 1841static Result CreateThread32(Core::System& system, Handle* out_handle, u32 priority,
1823 u32 entry_point, u32 arg, u32 stack_top, s32 processor_id) { 1842 u32 entry_point, u32 arg, u32 stack_top, s32 processor_id) {
1824 return CreateThread(system, out_handle, entry_point, arg, stack_top, priority, processor_id); 1843 return CreateThread(system, out_handle, entry_point, arg, stack_top, priority, processor_id);
1825} 1844}
1826 1845
1827/// Starts the thread for the provided handle 1846/// Starts the thread for the provided handle
1828static ResultCode StartThread(Core::System& system, Handle thread_handle) { 1847static Result StartThread(Core::System& system, Handle thread_handle) {
1829 LOG_DEBUG(Kernel_SVC, "called thread=0x{:08X}", thread_handle); 1848 LOG_DEBUG(Kernel_SVC, "called thread=0x{:08X}", thread_handle);
1830 1849
1831 // Get the thread from its handle. 1850 // Get the thread from its handle.
@@ -1843,7 +1862,7 @@ static ResultCode StartThread(Core::System& system, Handle thread_handle) {
1843 return ResultSuccess; 1862 return ResultSuccess;
1844} 1863}
1845 1864
1846static ResultCode StartThread32(Core::System& system, Handle thread_handle) { 1865static Result StartThread32(Core::System& system, Handle thread_handle) {
1847 return StartThread(system, thread_handle); 1866 return StartThread(system, thread_handle);
1848} 1867}
1849 1868
@@ -1851,7 +1870,7 @@ static ResultCode StartThread32(Core::System& system, Handle thread_handle) {
1851static void ExitThread(Core::System& system) { 1870static void ExitThread(Core::System& system) {
1852 LOG_DEBUG(Kernel_SVC, "called, pc=0x{:08X}", system.CurrentArmInterface().GetPC()); 1871 LOG_DEBUG(Kernel_SVC, "called, pc=0x{:08X}", system.CurrentArmInterface().GetPC());
1853 1872
1854 auto* const current_thread = system.Kernel().CurrentScheduler()->GetCurrentThread(); 1873 auto* const current_thread = GetCurrentThreadPointer(system.Kernel());
1855 system.GlobalSchedulerContext().RemoveThread(current_thread); 1874 system.GlobalSchedulerContext().RemoveThread(current_thread);
1856 current_thread->Exit(); 1875 current_thread->Exit();
1857 system.Kernel().UnregisterInUseObject(current_thread); 1876 system.Kernel().UnregisterInUseObject(current_thread);
@@ -1894,8 +1913,8 @@ static void SleepThread32(Core::System& system, u32 nanoseconds_low, u32 nanosec
1894} 1913}
1895 1914
1896/// Wait process wide key atomic 1915/// Wait process wide key atomic
1897static ResultCode WaitProcessWideKeyAtomic(Core::System& system, VAddr address, VAddr cv_key, 1916static Result WaitProcessWideKeyAtomic(Core::System& system, VAddr address, VAddr cv_key, u32 tag,
1898 u32 tag, s64 timeout_ns) { 1917 s64 timeout_ns) {
1899 LOG_TRACE(Kernel_SVC, "called address={:X}, cv_key={:X}, tag=0x{:08X}, timeout_ns={}", address, 1918 LOG_TRACE(Kernel_SVC, "called address={:X}, cv_key={:X}, tag=0x{:08X}, timeout_ns={}", address,
1900 cv_key, tag, timeout_ns); 1919 cv_key, tag, timeout_ns);
1901 1920
@@ -1930,8 +1949,8 @@ static ResultCode WaitProcessWideKeyAtomic(Core::System& system, VAddr address,
1930 address, Common::AlignDown(cv_key, sizeof(u32)), tag, timeout); 1949 address, Common::AlignDown(cv_key, sizeof(u32)), tag, timeout);
1931} 1950}
1932 1951
1933static ResultCode WaitProcessWideKeyAtomic32(Core::System& system, u32 address, u32 cv_key, u32 tag, 1952static Result WaitProcessWideKeyAtomic32(Core::System& system, u32 address, u32 cv_key, u32 tag,
1934 u32 timeout_ns_low, u32 timeout_ns_high) { 1953 u32 timeout_ns_low, u32 timeout_ns_high) {
1935 const auto timeout_ns = static_cast<s64>(timeout_ns_low | (u64{timeout_ns_high} << 32)); 1954 const auto timeout_ns = static_cast<s64>(timeout_ns_low | (u64{timeout_ns_high} << 32));
1936 return WaitProcessWideKeyAtomic(system, address, cv_key, tag, timeout_ns); 1955 return WaitProcessWideKeyAtomic(system, address, cv_key, tag, timeout_ns);
1937} 1956}
@@ -1976,8 +1995,8 @@ constexpr bool IsValidArbitrationType(Svc::ArbitrationType type) {
1976} // namespace 1995} // namespace
1977 1996
1978// Wait for an address (via Address Arbiter) 1997// Wait for an address (via Address Arbiter)
1979static ResultCode WaitForAddress(Core::System& system, VAddr address, Svc::ArbitrationType arb_type, 1998static Result WaitForAddress(Core::System& system, VAddr address, Svc::ArbitrationType arb_type,
1980 s32 value, s64 timeout_ns) { 1999 s32 value, s64 timeout_ns) {
1981 LOG_TRACE(Kernel_SVC, "called, address=0x{:X}, arb_type=0x{:X}, value=0x{:X}, timeout_ns={}", 2000 LOG_TRACE(Kernel_SVC, "called, address=0x{:X}, arb_type=0x{:X}, value=0x{:X}, timeout_ns={}",
1982 address, arb_type, value, timeout_ns); 2001 address, arb_type, value, timeout_ns);
1983 2002
@@ -2014,15 +2033,15 @@ static ResultCode WaitForAddress(Core::System& system, VAddr address, Svc::Arbit
2014 return system.Kernel().CurrentProcess()->WaitAddressArbiter(address, arb_type, value, timeout); 2033 return system.Kernel().CurrentProcess()->WaitAddressArbiter(address, arb_type, value, timeout);
2015} 2034}
2016 2035
2017static ResultCode WaitForAddress32(Core::System& system, u32 address, Svc::ArbitrationType arb_type, 2036static Result WaitForAddress32(Core::System& system, u32 address, Svc::ArbitrationType arb_type,
2018 s32 value, u32 timeout_ns_low, u32 timeout_ns_high) { 2037 s32 value, u32 timeout_ns_low, u32 timeout_ns_high) {
2019 const auto timeout = static_cast<s64>(timeout_ns_low | (u64{timeout_ns_high} << 32)); 2038 const auto timeout = static_cast<s64>(timeout_ns_low | (u64{timeout_ns_high} << 32));
2020 return WaitForAddress(system, address, arb_type, value, timeout); 2039 return WaitForAddress(system, address, arb_type, value, timeout);
2021} 2040}
2022 2041
2023// Signals to an address (via Address Arbiter) 2042// Signals to an address (via Address Arbiter)
2024static ResultCode SignalToAddress(Core::System& system, VAddr address, Svc::SignalType signal_type, 2043static Result SignalToAddress(Core::System& system, VAddr address, Svc::SignalType signal_type,
2025 s32 value, s32 count) { 2044 s32 value, s32 count) {
2026 LOG_TRACE(Kernel_SVC, "called, address=0x{:X}, signal_type=0x{:X}, value=0x{:X}, count=0x{:X}", 2045 LOG_TRACE(Kernel_SVC, "called, address=0x{:X}, signal_type=0x{:X}, value=0x{:X}, count=0x{:X}",
2027 address, signal_type, value, count); 2046 address, signal_type, value, count);
2028 2047
@@ -2063,8 +2082,8 @@ static void SynchronizePreemptionState(Core::System& system) {
2063 } 2082 }
2064} 2083}
2065 2084
2066static ResultCode SignalToAddress32(Core::System& system, u32 address, Svc::SignalType signal_type, 2085static Result SignalToAddress32(Core::System& system, u32 address, Svc::SignalType signal_type,
2067 s32 value, s32 count) { 2086 s32 value, s32 count) {
2068 return SignalToAddress(system, address, signal_type, value, count); 2087 return SignalToAddress(system, address, signal_type, value, count);
2069} 2088}
2070 2089
@@ -2102,7 +2121,7 @@ static void GetSystemTick32(Core::System& system, u32* time_low, u32* time_high)
2102} 2121}
2103 2122
2104/// Close a handle 2123/// Close a handle
2105static ResultCode CloseHandle(Core::System& system, Handle handle) { 2124static Result CloseHandle(Core::System& system, Handle handle) {
2106 LOG_TRACE(Kernel_SVC, "Closing handle 0x{:08X}", handle); 2125 LOG_TRACE(Kernel_SVC, "Closing handle 0x{:08X}", handle);
2107 2126
2108 // Remove the handle. 2127 // Remove the handle.
@@ -2112,12 +2131,12 @@ static ResultCode CloseHandle(Core::System& system, Handle handle) {
2112 return ResultSuccess; 2131 return ResultSuccess;
2113} 2132}
2114 2133
2115static ResultCode CloseHandle32(Core::System& system, Handle handle) { 2134static Result CloseHandle32(Core::System& system, Handle handle) {
2116 return CloseHandle(system, handle); 2135 return CloseHandle(system, handle);
2117} 2136}
2118 2137
2119/// Clears the signaled state of an event or process. 2138/// Clears the signaled state of an event or process.
2120static ResultCode ResetSignal(Core::System& system, Handle handle) { 2139static Result ResetSignal(Core::System& system, Handle handle) {
2121 LOG_DEBUG(Kernel_SVC, "called handle 0x{:08X}", handle); 2140 LOG_DEBUG(Kernel_SVC, "called handle 0x{:08X}", handle);
2122 2141
2123 // Get the current handle table. 2142 // Get the current handle table.
@@ -2144,7 +2163,7 @@ static ResultCode ResetSignal(Core::System& system, Handle handle) {
2144 return ResultInvalidHandle; 2163 return ResultInvalidHandle;
2145} 2164}
2146 2165
2147static ResultCode ResetSignal32(Core::System& system, Handle handle) { 2166static Result ResetSignal32(Core::System& system, Handle handle) {
2148 return ResetSignal(system, handle); 2167 return ResetSignal(system, handle);
2149} 2168}
2150 2169
@@ -2164,8 +2183,8 @@ constexpr bool IsValidTransferMemoryPermission(MemoryPermission perm) {
2164} // Anonymous namespace 2183} // Anonymous namespace
2165 2184
2166/// Creates a TransferMemory object 2185/// Creates a TransferMemory object
2167static ResultCode CreateTransferMemory(Core::System& system, Handle* out, VAddr address, u64 size, 2186static Result CreateTransferMemory(Core::System& system, Handle* out, VAddr address, u64 size,
2168 MemoryPermission map_perm) { 2187 MemoryPermission map_perm) {
2169 auto& kernel = system.Kernel(); 2188 auto& kernel = system.Kernel();
2170 2189
2171 // Validate the size. 2190 // Validate the size.
@@ -2211,13 +2230,13 @@ static ResultCode CreateTransferMemory(Core::System& system, Handle* out, VAddr
2211 return ResultSuccess; 2230 return ResultSuccess;
2212} 2231}
2213 2232
2214static ResultCode CreateTransferMemory32(Core::System& system, Handle* out, u32 address, u32 size, 2233static Result CreateTransferMemory32(Core::System& system, Handle* out, u32 address, u32 size,
2215 MemoryPermission map_perm) { 2234 MemoryPermission map_perm) {
2216 return CreateTransferMemory(system, out, address, size, map_perm); 2235 return CreateTransferMemory(system, out, address, size, map_perm);
2217} 2236}
2218 2237
2219static ResultCode GetThreadCoreMask(Core::System& system, Handle thread_handle, s32* out_core_id, 2238static Result GetThreadCoreMask(Core::System& system, Handle thread_handle, s32* out_core_id,
2220 u64* out_affinity_mask) { 2239 u64* out_affinity_mask) {
2221 LOG_TRACE(Kernel_SVC, "called, handle=0x{:08X}", thread_handle); 2240 LOG_TRACE(Kernel_SVC, "called, handle=0x{:08X}", thread_handle);
2222 2241
2223 // Get the thread from its handle. 2242 // Get the thread from its handle.
@@ -2231,8 +2250,8 @@ static ResultCode GetThreadCoreMask(Core::System& system, Handle thread_handle,
2231 return ResultSuccess; 2250 return ResultSuccess;
2232} 2251}
2233 2252
2234static ResultCode GetThreadCoreMask32(Core::System& system, Handle thread_handle, s32* out_core_id, 2253static Result GetThreadCoreMask32(Core::System& system, Handle thread_handle, s32* out_core_id,
2235 u32* out_affinity_mask_low, u32* out_affinity_mask_high) { 2254 u32* out_affinity_mask_low, u32* out_affinity_mask_high) {
2236 u64 out_affinity_mask{}; 2255 u64 out_affinity_mask{};
2237 const auto result = GetThreadCoreMask(system, thread_handle, out_core_id, &out_affinity_mask); 2256 const auto result = GetThreadCoreMask(system, thread_handle, out_core_id, &out_affinity_mask);
2238 *out_affinity_mask_high = static_cast<u32>(out_affinity_mask >> 32); 2257 *out_affinity_mask_high = static_cast<u32>(out_affinity_mask >> 32);
@@ -2240,8 +2259,8 @@ static ResultCode GetThreadCoreMask32(Core::System& system, Handle thread_handle
2240 return result; 2259 return result;
2241} 2260}
2242 2261
2243static ResultCode SetThreadCoreMask(Core::System& system, Handle thread_handle, s32 core_id, 2262static Result SetThreadCoreMask(Core::System& system, Handle thread_handle, s32 core_id,
2244 u64 affinity_mask) { 2263 u64 affinity_mask) {
2245 // Determine the core id/affinity mask. 2264 // Determine the core id/affinity mask.
2246 if (core_id == IdealCoreUseProcessValue) { 2265 if (core_id == IdealCoreUseProcessValue) {
2247 core_id = system.Kernel().CurrentProcess()->GetIdealCoreId(); 2266 core_id = system.Kernel().CurrentProcess()->GetIdealCoreId();
@@ -2272,13 +2291,13 @@ static ResultCode SetThreadCoreMask(Core::System& system, Handle thread_handle,
2272 return ResultSuccess; 2291 return ResultSuccess;
2273} 2292}
2274 2293
2275static ResultCode SetThreadCoreMask32(Core::System& system, Handle thread_handle, s32 core_id, 2294static Result SetThreadCoreMask32(Core::System& system, Handle thread_handle, s32 core_id,
2276 u32 affinity_mask_low, u32 affinity_mask_high) { 2295 u32 affinity_mask_low, u32 affinity_mask_high) {
2277 const auto affinity_mask = u64{affinity_mask_low} | (u64{affinity_mask_high} << 32); 2296 const auto affinity_mask = u64{affinity_mask_low} | (u64{affinity_mask_high} << 32);
2278 return SetThreadCoreMask(system, thread_handle, core_id, affinity_mask); 2297 return SetThreadCoreMask(system, thread_handle, core_id, affinity_mask);
2279} 2298}
2280 2299
2281static ResultCode SignalEvent(Core::System& system, Handle event_handle) { 2300static Result SignalEvent(Core::System& system, Handle event_handle) {
2282 LOG_DEBUG(Kernel_SVC, "called, event_handle=0x{:08X}", event_handle); 2301 LOG_DEBUG(Kernel_SVC, "called, event_handle=0x{:08X}", event_handle);
2283 2302
2284 // Get the current handle table. 2303 // Get the current handle table.
@@ -2291,11 +2310,11 @@ static ResultCode SignalEvent(Core::System& system, Handle event_handle) {
2291 return writable_event->Signal(); 2310 return writable_event->Signal();
2292} 2311}
2293 2312
2294static ResultCode SignalEvent32(Core::System& system, Handle event_handle) { 2313static Result SignalEvent32(Core::System& system, Handle event_handle) {
2295 return SignalEvent(system, event_handle); 2314 return SignalEvent(system, event_handle);
2296} 2315}
2297 2316
2298static ResultCode ClearEvent(Core::System& system, Handle event_handle) { 2317static Result ClearEvent(Core::System& system, Handle event_handle) {
2299 LOG_TRACE(Kernel_SVC, "called, event_handle=0x{:08X}", event_handle); 2318 LOG_TRACE(Kernel_SVC, "called, event_handle=0x{:08X}", event_handle);
2300 2319
2301 // Get the current handle table. 2320 // Get the current handle table.
@@ -2322,11 +2341,11 @@ static ResultCode ClearEvent(Core::System& system, Handle event_handle) {
2322 return ResultInvalidHandle; 2341 return ResultInvalidHandle;
2323} 2342}
2324 2343
2325static ResultCode ClearEvent32(Core::System& system, Handle event_handle) { 2344static Result ClearEvent32(Core::System& system, Handle event_handle) {
2326 return ClearEvent(system, event_handle); 2345 return ClearEvent(system, event_handle);
2327} 2346}
2328 2347
2329static ResultCode CreateEvent(Core::System& system, Handle* out_write, Handle* out_read) { 2348static Result CreateEvent(Core::System& system, Handle* out_write, Handle* out_read) {
2330 LOG_DEBUG(Kernel_SVC, "called"); 2349 LOG_DEBUG(Kernel_SVC, "called");
2331 2350
2332 // Get the kernel reference and handle table. 2351 // Get the kernel reference and handle table.
@@ -2371,11 +2390,11 @@ static ResultCode CreateEvent(Core::System& system, Handle* out_write, Handle* o
2371 return ResultSuccess; 2390 return ResultSuccess;
2372} 2391}
2373 2392
2374static ResultCode CreateEvent32(Core::System& system, Handle* out_write, Handle* out_read) { 2393static Result CreateEvent32(Core::System& system, Handle* out_write, Handle* out_read) {
2375 return CreateEvent(system, out_write, out_read); 2394 return CreateEvent(system, out_write, out_read);
2376} 2395}
2377 2396
2378static ResultCode GetProcessInfo(Core::System& system, u64* out, Handle process_handle, u32 type) { 2397static Result GetProcessInfo(Core::System& system, u64* out, Handle process_handle, u32 type) {
2379 LOG_DEBUG(Kernel_SVC, "called, handle=0x{:08X}, type=0x{:X}", process_handle, type); 2398 LOG_DEBUG(Kernel_SVC, "called, handle=0x{:08X}, type=0x{:X}", process_handle, type);
2380 2399
2381 // This function currently only allows retrieving a process' status. 2400 // This function currently only allows retrieving a process' status.
@@ -2401,7 +2420,7 @@ static ResultCode GetProcessInfo(Core::System& system, u64* out, Handle process_
2401 return ResultSuccess; 2420 return ResultSuccess;
2402} 2421}
2403 2422
2404static ResultCode CreateResourceLimit(Core::System& system, Handle* out_handle) { 2423static Result CreateResourceLimit(Core::System& system, Handle* out_handle) {
2405 LOG_DEBUG(Kernel_SVC, "called"); 2424 LOG_DEBUG(Kernel_SVC, "called");
2406 2425
2407 // Create a new resource limit. 2426 // Create a new resource limit.
@@ -2424,9 +2443,8 @@ static ResultCode CreateResourceLimit(Core::System& system, Handle* out_handle)
2424 return ResultSuccess; 2443 return ResultSuccess;
2425} 2444}
2426 2445
2427static ResultCode GetResourceLimitLimitValue(Core::System& system, u64* out_limit_value, 2446static Result GetResourceLimitLimitValue(Core::System& system, u64* out_limit_value,
2428 Handle resource_limit_handle, 2447 Handle resource_limit_handle, LimitableResource which) {
2429 LimitableResource which) {
2430 LOG_DEBUG(Kernel_SVC, "called, resource_limit_handle={:08X}, which={}", resource_limit_handle, 2448 LOG_DEBUG(Kernel_SVC, "called, resource_limit_handle={:08X}, which={}", resource_limit_handle,
2431 which); 2449 which);
2432 2450
@@ -2445,9 +2463,8 @@ static ResultCode GetResourceLimitLimitValue(Core::System& system, u64* out_limi
2445 return ResultSuccess; 2463 return ResultSuccess;
2446} 2464}
2447 2465
2448static ResultCode GetResourceLimitCurrentValue(Core::System& system, u64* out_current_value, 2466static Result GetResourceLimitCurrentValue(Core::System& system, u64* out_current_value,
2449 Handle resource_limit_handle, 2467 Handle resource_limit_handle, LimitableResource which) {
2450 LimitableResource which) {
2451 LOG_DEBUG(Kernel_SVC, "called, resource_limit_handle={:08X}, which={}", resource_limit_handle, 2468 LOG_DEBUG(Kernel_SVC, "called, resource_limit_handle={:08X}, which={}", resource_limit_handle,
2452 which); 2469 which);
2453 2470
@@ -2466,8 +2483,8 @@ static ResultCode GetResourceLimitCurrentValue(Core::System& system, u64* out_cu
2466 return ResultSuccess; 2483 return ResultSuccess;
2467} 2484}
2468 2485
2469static ResultCode SetResourceLimitLimitValue(Core::System& system, Handle resource_limit_handle, 2486static Result SetResourceLimitLimitValue(Core::System& system, Handle resource_limit_handle,
2470 LimitableResource which, u64 limit_value) { 2487 LimitableResource which, u64 limit_value) {
2471 LOG_DEBUG(Kernel_SVC, "called, resource_limit_handle={:08X}, which={}, limit_value={}", 2488 LOG_DEBUG(Kernel_SVC, "called, resource_limit_handle={:08X}, which={}, limit_value={}",
2472 resource_limit_handle, which, limit_value); 2489 resource_limit_handle, which, limit_value);
2473 2490
@@ -2486,8 +2503,8 @@ static ResultCode SetResourceLimitLimitValue(Core::System& system, Handle resour
2486 return ResultSuccess; 2503 return ResultSuccess;
2487} 2504}
2488 2505
2489static ResultCode GetProcessList(Core::System& system, u32* out_num_processes, 2506static Result GetProcessList(Core::System& system, u32* out_num_processes, VAddr out_process_ids,
2490 VAddr out_process_ids, u32 out_process_ids_size) { 2507 u32 out_process_ids_size) {
2491 LOG_DEBUG(Kernel_SVC, "called. out_process_ids=0x{:016X}, out_process_ids_size={}", 2508 LOG_DEBUG(Kernel_SVC, "called. out_process_ids=0x{:016X}, out_process_ids_size={}",
2492 out_process_ids, out_process_ids_size); 2509 out_process_ids, out_process_ids_size);
2493 2510
@@ -2523,8 +2540,8 @@ static ResultCode GetProcessList(Core::System& system, u32* out_num_processes,
2523 return ResultSuccess; 2540 return ResultSuccess;
2524} 2541}
2525 2542
2526static ResultCode GetThreadList(Core::System& system, u32* out_num_threads, VAddr out_thread_ids, 2543static Result GetThreadList(Core::System& system, u32* out_num_threads, VAddr out_thread_ids,
2527 u32 out_thread_ids_size, Handle debug_handle) { 2544 u32 out_thread_ids_size, Handle debug_handle) {
2528 // TODO: Handle this case when debug events are supported. 2545 // TODO: Handle this case when debug events are supported.
2529 UNIMPLEMENTED_IF(debug_handle != InvalidHandle); 2546 UNIMPLEMENTED_IF(debug_handle != InvalidHandle);
2530 2547
@@ -2563,9 +2580,9 @@ static ResultCode GetThreadList(Core::System& system, u32* out_num_threads, VAdd
2563 return ResultSuccess; 2580 return ResultSuccess;
2564} 2581}
2565 2582
2566static ResultCode FlushProcessDataCache32([[maybe_unused]] Core::System& system, 2583static Result FlushProcessDataCache32([[maybe_unused]] Core::System& system,
2567 [[maybe_unused]] Handle handle, 2584 [[maybe_unused]] Handle handle, [[maybe_unused]] u32 address,
2568 [[maybe_unused]] u32 address, [[maybe_unused]] u32 size) { 2585 [[maybe_unused]] u32 size) {
2569 // Note(Blinkhawk): For emulation purposes of the data cache this is mostly a no-op, 2586 // Note(Blinkhawk): For emulation purposes of the data cache this is mostly a no-op,
2570 // as all emulation is done in the same cache level in host architecture, thus data cache 2587 // as all emulation is done in the same cache level in host architecture, thus data cache
2571 // does not need flushing. 2588 // does not need flushing.
@@ -2993,7 +3010,7 @@ void Call(Core::System& system, u32 immediate) {
2993 auto& kernel = system.Kernel(); 3010 auto& kernel = system.Kernel();
2994 kernel.EnterSVCProfile(); 3011 kernel.EnterSVCProfile();
2995 3012
2996 auto* thread = kernel.CurrentScheduler()->GetCurrentThread(); 3013 auto* thread = GetCurrentThreadPointer(kernel);
2997 thread->SetIsCallingSvc(); 3014 thread->SetIsCallingSvc();
2998 3015
2999 const FunctionDef* info = system.CurrentProcess()->Is64BitProcess() ? GetSVCInfo64(immediate) 3016 const FunctionDef* info = system.CurrentProcess()->Is64BitProcess() ? GetSVCInfo64(immediate)
diff --git a/src/core/hle/kernel/svc_results.h b/src/core/hle/kernel/svc_results.h
index fab12d070..f27cade33 100644
--- a/src/core/hle/kernel/svc_results.h
+++ b/src/core/hle/kernel/svc_results.h
@@ -9,34 +9,34 @@ namespace Kernel {
9 9
10// Confirmed Switch kernel error codes 10// Confirmed Switch kernel error codes
11 11
12constexpr ResultCode ResultOutOfSessions{ErrorModule::Kernel, 7}; 12constexpr Result ResultOutOfSessions{ErrorModule::Kernel, 7};
13constexpr ResultCode ResultInvalidArgument{ErrorModule::Kernel, 14}; 13constexpr Result ResultInvalidArgument{ErrorModule::Kernel, 14};
14constexpr ResultCode ResultNoSynchronizationObject{ErrorModule::Kernel, 57}; 14constexpr Result ResultNoSynchronizationObject{ErrorModule::Kernel, 57};
15constexpr ResultCode ResultTerminationRequested{ErrorModule::Kernel, 59}; 15constexpr Result ResultTerminationRequested{ErrorModule::Kernel, 59};
16constexpr ResultCode ResultInvalidSize{ErrorModule::Kernel, 101}; 16constexpr Result ResultInvalidSize{ErrorModule::Kernel, 101};
17constexpr ResultCode ResultInvalidAddress{ErrorModule::Kernel, 102}; 17constexpr Result ResultInvalidAddress{ErrorModule::Kernel, 102};
18constexpr ResultCode ResultOutOfResource{ErrorModule::Kernel, 103}; 18constexpr Result ResultOutOfResource{ErrorModule::Kernel, 103};
19constexpr ResultCode ResultOutOfMemory{ErrorModule::Kernel, 104}; 19constexpr Result ResultOutOfMemory{ErrorModule::Kernel, 104};
20constexpr ResultCode ResultOutOfHandles{ErrorModule::Kernel, 105}; 20constexpr Result ResultOutOfHandles{ErrorModule::Kernel, 105};
21constexpr ResultCode ResultInvalidCurrentMemory{ErrorModule::Kernel, 106}; 21constexpr Result ResultInvalidCurrentMemory{ErrorModule::Kernel, 106};
22constexpr ResultCode ResultInvalidNewMemoryPermission{ErrorModule::Kernel, 108}; 22constexpr Result ResultInvalidNewMemoryPermission{ErrorModule::Kernel, 108};
23constexpr ResultCode ResultInvalidMemoryRegion{ErrorModule::Kernel, 110}; 23constexpr Result ResultInvalidMemoryRegion{ErrorModule::Kernel, 110};
24constexpr ResultCode ResultInvalidPriority{ErrorModule::Kernel, 112}; 24constexpr Result ResultInvalidPriority{ErrorModule::Kernel, 112};
25constexpr ResultCode ResultInvalidCoreId{ErrorModule::Kernel, 113}; 25constexpr Result ResultInvalidCoreId{ErrorModule::Kernel, 113};
26constexpr ResultCode ResultInvalidHandle{ErrorModule::Kernel, 114}; 26constexpr Result ResultInvalidHandle{ErrorModule::Kernel, 114};
27constexpr ResultCode ResultInvalidPointer{ErrorModule::Kernel, 115}; 27constexpr Result ResultInvalidPointer{ErrorModule::Kernel, 115};
28constexpr ResultCode ResultInvalidCombination{ErrorModule::Kernel, 116}; 28constexpr Result ResultInvalidCombination{ErrorModule::Kernel, 116};
29constexpr ResultCode ResultTimedOut{ErrorModule::Kernel, 117}; 29constexpr Result ResultTimedOut{ErrorModule::Kernel, 117};
30constexpr ResultCode ResultCancelled{ErrorModule::Kernel, 118}; 30constexpr Result ResultCancelled{ErrorModule::Kernel, 118};
31constexpr ResultCode ResultOutOfRange{ErrorModule::Kernel, 119}; 31constexpr Result ResultOutOfRange{ErrorModule::Kernel, 119};
32constexpr ResultCode ResultInvalidEnumValue{ErrorModule::Kernel, 120}; 32constexpr Result ResultInvalidEnumValue{ErrorModule::Kernel, 120};
33constexpr ResultCode ResultNotFound{ErrorModule::Kernel, 121}; 33constexpr Result ResultNotFound{ErrorModule::Kernel, 121};
34constexpr ResultCode ResultBusy{ErrorModule::Kernel, 122}; 34constexpr Result ResultBusy{ErrorModule::Kernel, 122};
35constexpr ResultCode ResultSessionClosed{ErrorModule::Kernel, 123}; 35constexpr Result ResultSessionClosed{ErrorModule::Kernel, 123};
36constexpr ResultCode ResultInvalidState{ErrorModule::Kernel, 125}; 36constexpr Result ResultInvalidState{ErrorModule::Kernel, 125};
37constexpr ResultCode ResultReservedUsed{ErrorModule::Kernel, 126}; 37constexpr Result ResultReservedUsed{ErrorModule::Kernel, 126};
38constexpr ResultCode ResultPortClosed{ErrorModule::Kernel, 131}; 38constexpr Result ResultPortClosed{ErrorModule::Kernel, 131};
39constexpr ResultCode ResultLimitReached{ErrorModule::Kernel, 132}; 39constexpr Result ResultLimitReached{ErrorModule::Kernel, 132};
40constexpr ResultCode ResultInvalidId{ErrorModule::Kernel, 519}; 40constexpr Result ResultInvalidId{ErrorModule::Kernel, 519};
41 41
42} // namespace Kernel 42} // namespace Kernel
diff --git a/src/core/hle/kernel/svc_wrap.h b/src/core/hle/kernel/svc_wrap.h
index 2271bb80c..4bc49087e 100644
--- a/src/core/hle/kernel/svc_wrap.h
+++ b/src/core/hle/kernel/svc_wrap.h
@@ -33,24 +33,24 @@ static inline void FuncReturn32(Core::System& system, u32 result) {
33} 33}
34 34
35//////////////////////////////////////////////////////////////////////////////////////////////////// 35////////////////////////////////////////////////////////////////////////////////////////////////////
36// Function wrappers that return type ResultCode 36// Function wrappers that return type Result
37 37
38template <ResultCode func(Core::System&, u64)> 38template <Result func(Core::System&, u64)>
39void SvcWrap64(Core::System& system) { 39void SvcWrap64(Core::System& system) {
40 FuncReturn(system, func(system, Param(system, 0)).raw); 40 FuncReturn(system, func(system, Param(system, 0)).raw);
41} 41}
42 42
43template <ResultCode func(Core::System&, u64, u64)> 43template <Result func(Core::System&, u64, u64)>
44void SvcWrap64(Core::System& system) { 44void SvcWrap64(Core::System& system) {
45 FuncReturn(system, func(system, Param(system, 0), Param(system, 1)).raw); 45 FuncReturn(system, func(system, Param(system, 0), Param(system, 1)).raw);
46} 46}
47 47
48template <ResultCode func(Core::System&, u32)> 48template <Result func(Core::System&, u32)>
49void SvcWrap64(Core::System& system) { 49void SvcWrap64(Core::System& system) {
50 FuncReturn(system, func(system, static_cast<u32>(Param(system, 0))).raw); 50 FuncReturn(system, func(system, static_cast<u32>(Param(system, 0))).raw);
51} 51}
52 52
53template <ResultCode func(Core::System&, u32, u32)> 53template <Result func(Core::System&, u32, u32)>
54void SvcWrap64(Core::System& system) { 54void SvcWrap64(Core::System& system) {
55 FuncReturn( 55 FuncReturn(
56 system, 56 system,
@@ -58,14 +58,14 @@ void SvcWrap64(Core::System& system) {
58} 58}
59 59
60// Used by SetThreadActivity 60// Used by SetThreadActivity
61template <ResultCode func(Core::System&, Handle, Svc::ThreadActivity)> 61template <Result func(Core::System&, Handle, Svc::ThreadActivity)>
62void SvcWrap64(Core::System& system) { 62void SvcWrap64(Core::System& system) {
63 FuncReturn(system, func(system, static_cast<u32>(Param(system, 0)), 63 FuncReturn(system, func(system, static_cast<u32>(Param(system, 0)),
64 static_cast<Svc::ThreadActivity>(Param(system, 1))) 64 static_cast<Svc::ThreadActivity>(Param(system, 1)))
65 .raw); 65 .raw);
66} 66}
67 67
68template <ResultCode func(Core::System&, u32, u64, u64, u64)> 68template <Result func(Core::System&, u32, u64, u64, u64)>
69void SvcWrap64(Core::System& system) { 69void SvcWrap64(Core::System& system) {
70 FuncReturn(system, func(system, static_cast<u32>(Param(system, 0)), Param(system, 1), 70 FuncReturn(system, func(system, static_cast<u32>(Param(system, 0)), Param(system, 1),
71 Param(system, 2), Param(system, 3)) 71 Param(system, 2), Param(system, 3))
@@ -73,7 +73,7 @@ void SvcWrap64(Core::System& system) {
73} 73}
74 74
75// Used by MapProcessMemory and UnmapProcessMemory 75// Used by MapProcessMemory and UnmapProcessMemory
76template <ResultCode func(Core::System&, u64, u32, u64, u64)> 76template <Result func(Core::System&, u64, u32, u64, u64)>
77void SvcWrap64(Core::System& system) { 77void SvcWrap64(Core::System& system) {
78 FuncReturn(system, func(system, Param(system, 0), static_cast<u32>(Param(system, 1)), 78 FuncReturn(system, func(system, Param(system, 0), static_cast<u32>(Param(system, 1)),
79 Param(system, 2), Param(system, 3)) 79 Param(system, 2), Param(system, 3))
@@ -81,7 +81,7 @@ void SvcWrap64(Core::System& system) {
81} 81}
82 82
83// Used by ControlCodeMemory 83// Used by ControlCodeMemory
84template <ResultCode func(Core::System&, Handle, u32, u64, u64, Svc::MemoryPermission)> 84template <Result func(Core::System&, Handle, u32, u64, u64, Svc::MemoryPermission)>
85void SvcWrap64(Core::System& system) { 85void SvcWrap64(Core::System& system) {
86 FuncReturn(system, func(system, static_cast<Handle>(Param(system, 0)), 86 FuncReturn(system, func(system, static_cast<Handle>(Param(system, 0)),
87 static_cast<u32>(Param(system, 1)), Param(system, 2), Param(system, 3), 87 static_cast<u32>(Param(system, 1)), Param(system, 2), Param(system, 3),
@@ -89,7 +89,7 @@ void SvcWrap64(Core::System& system) {
89 .raw); 89 .raw);
90} 90}
91 91
92template <ResultCode func(Core::System&, u32*)> 92template <Result func(Core::System&, u32*)>
93void SvcWrap64(Core::System& system) { 93void SvcWrap64(Core::System& system) {
94 u32 param = 0; 94 u32 param = 0;
95 const u32 retval = func(system, &param).raw; 95 const u32 retval = func(system, &param).raw;
@@ -97,7 +97,7 @@ void SvcWrap64(Core::System& system) {
97 FuncReturn(system, retval); 97 FuncReturn(system, retval);
98} 98}
99 99
100template <ResultCode func(Core::System&, u32*, u32)> 100template <Result func(Core::System&, u32*, u32)>
101void SvcWrap64(Core::System& system) { 101void SvcWrap64(Core::System& system) {
102 u32 param_1 = 0; 102 u32 param_1 = 0;
103 const u32 retval = func(system, &param_1, static_cast<u32>(Param(system, 1))).raw; 103 const u32 retval = func(system, &param_1, static_cast<u32>(Param(system, 1))).raw;
@@ -105,7 +105,7 @@ void SvcWrap64(Core::System& system) {
105 FuncReturn(system, retval); 105 FuncReturn(system, retval);
106} 106}
107 107
108template <ResultCode func(Core::System&, u32*, u32*)> 108template <Result func(Core::System&, u32*, u32*)>
109void SvcWrap64(Core::System& system) { 109void SvcWrap64(Core::System& system) {
110 u32 param_1 = 0; 110 u32 param_1 = 0;
111 u32 param_2 = 0; 111 u32 param_2 = 0;
@@ -118,7 +118,7 @@ void SvcWrap64(Core::System& system) {
118 FuncReturn(system, retval); 118 FuncReturn(system, retval);
119} 119}
120 120
121template <ResultCode func(Core::System&, u32*, u64)> 121template <Result func(Core::System&, u32*, u64)>
122void SvcWrap64(Core::System& system) { 122void SvcWrap64(Core::System& system) {
123 u32 param_1 = 0; 123 u32 param_1 = 0;
124 const u32 retval = func(system, &param_1, Param(system, 1)).raw; 124 const u32 retval = func(system, &param_1, Param(system, 1)).raw;
@@ -126,7 +126,7 @@ void SvcWrap64(Core::System& system) {
126 FuncReturn(system, retval); 126 FuncReturn(system, retval);
127} 127}
128 128
129template <ResultCode func(Core::System&, u32*, u64, u32)> 129template <Result func(Core::System&, u32*, u64, u32)>
130void SvcWrap64(Core::System& system) { 130void SvcWrap64(Core::System& system) {
131 u32 param_1 = 0; 131 u32 param_1 = 0;
132 const u32 retval = 132 const u32 retval =
@@ -136,7 +136,7 @@ void SvcWrap64(Core::System& system) {
136 FuncReturn(system, retval); 136 FuncReturn(system, retval);
137} 137}
138 138
139template <ResultCode func(Core::System&, u64*, u32)> 139template <Result func(Core::System&, u64*, u32)>
140void SvcWrap64(Core::System& system) { 140void SvcWrap64(Core::System& system) {
141 u64 param_1 = 0; 141 u64 param_1 = 0;
142 const u32 retval = func(system, &param_1, static_cast<u32>(Param(system, 1))).raw; 142 const u32 retval = func(system, &param_1, static_cast<u32>(Param(system, 1))).raw;
@@ -145,12 +145,12 @@ void SvcWrap64(Core::System& system) {
145 FuncReturn(system, retval); 145 FuncReturn(system, retval);
146} 146}
147 147
148template <ResultCode func(Core::System&, u64, u32)> 148template <Result func(Core::System&, u64, u32)>
149void SvcWrap64(Core::System& system) { 149void SvcWrap64(Core::System& system) {
150 FuncReturn(system, func(system, Param(system, 0), static_cast<u32>(Param(system, 1))).raw); 150 FuncReturn(system, func(system, Param(system, 0), static_cast<u32>(Param(system, 1))).raw);
151} 151}
152 152
153template <ResultCode func(Core::System&, u64*, u64)> 153template <Result func(Core::System&, u64*, u64)>
154void SvcWrap64(Core::System& system) { 154void SvcWrap64(Core::System& system) {
155 u64 param_1 = 0; 155 u64 param_1 = 0;
156 const u32 retval = func(system, &param_1, Param(system, 1)).raw; 156 const u32 retval = func(system, &param_1, Param(system, 1)).raw;
@@ -159,7 +159,7 @@ void SvcWrap64(Core::System& system) {
159 FuncReturn(system, retval); 159 FuncReturn(system, retval);
160} 160}
161 161
162template <ResultCode func(Core::System&, u64*, u32, u32)> 162template <Result func(Core::System&, u64*, u32, u32)>
163void SvcWrap64(Core::System& system) { 163void SvcWrap64(Core::System& system) {
164 u64 param_1 = 0; 164 u64 param_1 = 0;
165 const u32 retval = func(system, &param_1, static_cast<u32>(Param(system, 1)), 165 const u32 retval = func(system, &param_1, static_cast<u32>(Param(system, 1)),
@@ -171,7 +171,7 @@ void SvcWrap64(Core::System& system) {
171} 171}
172 172
173// Used by GetResourceLimitLimitValue. 173// Used by GetResourceLimitLimitValue.
174template <ResultCode func(Core::System&, u64*, Handle, LimitableResource)> 174template <Result func(Core::System&, u64*, Handle, LimitableResource)>
175void SvcWrap64(Core::System& system) { 175void SvcWrap64(Core::System& system) {
176 u64 param_1 = 0; 176 u64 param_1 = 0;
177 const u32 retval = func(system, &param_1, static_cast<Handle>(Param(system, 1)), 177 const u32 retval = func(system, &param_1, static_cast<Handle>(Param(system, 1)),
@@ -182,13 +182,13 @@ void SvcWrap64(Core::System& system) {
182 FuncReturn(system, retval); 182 FuncReturn(system, retval);
183} 183}
184 184
185template <ResultCode func(Core::System&, u32, u64)> 185template <Result func(Core::System&, u32, u64)>
186void SvcWrap64(Core::System& system) { 186void SvcWrap64(Core::System& system) {
187 FuncReturn(system, func(system, static_cast<u32>(Param(system, 0)), Param(system, 1)).raw); 187 FuncReturn(system, func(system, static_cast<u32>(Param(system, 0)), Param(system, 1)).raw);
188} 188}
189 189
190// Used by SetResourceLimitLimitValue 190// Used by SetResourceLimitLimitValue
191template <ResultCode func(Core::System&, Handle, LimitableResource, u64)> 191template <Result func(Core::System&, Handle, LimitableResource, u64)>
192void SvcWrap64(Core::System& system) { 192void SvcWrap64(Core::System& system) {
193 FuncReturn(system, func(system, static_cast<Handle>(Param(system, 0)), 193 FuncReturn(system, func(system, static_cast<Handle>(Param(system, 0)),
194 static_cast<LimitableResource>(Param(system, 1)), Param(system, 2)) 194 static_cast<LimitableResource>(Param(system, 1)), Param(system, 2))
@@ -196,7 +196,7 @@ void SvcWrap64(Core::System& system) {
196} 196}
197 197
198// Used by SetThreadCoreMask 198// Used by SetThreadCoreMask
199template <ResultCode func(Core::System&, Handle, s32, u64)> 199template <Result func(Core::System&, Handle, s32, u64)>
200void SvcWrap64(Core::System& system) { 200void SvcWrap64(Core::System& system) {
201 FuncReturn(system, func(system, static_cast<u32>(Param(system, 0)), 201 FuncReturn(system, func(system, static_cast<u32>(Param(system, 0)),
202 static_cast<s32>(Param(system, 1)), Param(system, 2)) 202 static_cast<s32>(Param(system, 1)), Param(system, 2))
@@ -204,44 +204,44 @@ void SvcWrap64(Core::System& system) {
204} 204}
205 205
206// Used by GetThreadCoreMask 206// Used by GetThreadCoreMask
207template <ResultCode func(Core::System&, Handle, s32*, u64*)> 207template <Result func(Core::System&, Handle, s32*, u64*)>
208void SvcWrap64(Core::System& system) { 208void SvcWrap64(Core::System& system) {
209 s32 param_1 = 0; 209 s32 param_1 = 0;
210 u64 param_2 = 0; 210 u64 param_2 = 0;
211 const ResultCode retval = func(system, static_cast<u32>(Param(system, 2)), &param_1, &param_2); 211 const Result retval = func(system, static_cast<u32>(Param(system, 2)), &param_1, &param_2);
212 212
213 system.CurrentArmInterface().SetReg(1, param_1); 213 system.CurrentArmInterface().SetReg(1, param_1);
214 system.CurrentArmInterface().SetReg(2, param_2); 214 system.CurrentArmInterface().SetReg(2, param_2);
215 FuncReturn(system, retval.raw); 215 FuncReturn(system, retval.raw);
216} 216}
217 217
218template <ResultCode func(Core::System&, u64, u64, u32, u32)> 218template <Result func(Core::System&, u64, u64, u32, u32)>
219void SvcWrap64(Core::System& system) { 219void SvcWrap64(Core::System& system) {
220 FuncReturn(system, func(system, Param(system, 0), Param(system, 1), 220 FuncReturn(system, func(system, Param(system, 0), Param(system, 1),
221 static_cast<u32>(Param(system, 2)), static_cast<u32>(Param(system, 3))) 221 static_cast<u32>(Param(system, 2)), static_cast<u32>(Param(system, 3)))
222 .raw); 222 .raw);
223} 223}
224 224
225template <ResultCode func(Core::System&, u64, u64, u32, u64)> 225template <Result func(Core::System&, u64, u64, u32, u64)>
226void SvcWrap64(Core::System& system) { 226void SvcWrap64(Core::System& system) {
227 FuncReturn(system, func(system, Param(system, 0), Param(system, 1), 227 FuncReturn(system, func(system, Param(system, 0), Param(system, 1),
228 static_cast<u32>(Param(system, 2)), Param(system, 3)) 228 static_cast<u32>(Param(system, 2)), Param(system, 3))
229 .raw); 229 .raw);
230} 230}
231 231
232template <ResultCode func(Core::System&, u32, u64, u32)> 232template <Result func(Core::System&, u32, u64, u32)>
233void SvcWrap64(Core::System& system) { 233void SvcWrap64(Core::System& system) {
234 FuncReturn(system, func(system, static_cast<u32>(Param(system, 0)), Param(system, 1), 234 FuncReturn(system, func(system, static_cast<u32>(Param(system, 0)), Param(system, 1),
235 static_cast<u32>(Param(system, 2))) 235 static_cast<u32>(Param(system, 2)))
236 .raw); 236 .raw);
237} 237}
238 238
239template <ResultCode func(Core::System&, u64, u64, u64)> 239template <Result func(Core::System&, u64, u64, u64)>
240void SvcWrap64(Core::System& system) { 240void SvcWrap64(Core::System& system) {
241 FuncReturn(system, func(system, Param(system, 0), Param(system, 1), Param(system, 2)).raw); 241 FuncReturn(system, func(system, Param(system, 0), Param(system, 1), Param(system, 2)).raw);
242} 242}
243 243
244template <ResultCode func(Core::System&, u64, u64, u32)> 244template <Result func(Core::System&, u64, u64, u32)>
245void SvcWrap64(Core::System& system) { 245void SvcWrap64(Core::System& system) {
246 FuncReturn( 246 FuncReturn(
247 system, 247 system,
@@ -249,7 +249,7 @@ void SvcWrap64(Core::System& system) {
249} 249}
250 250
251// Used by SetMemoryPermission 251// Used by SetMemoryPermission
252template <ResultCode func(Core::System&, u64, u64, Svc::MemoryPermission)> 252template <Result func(Core::System&, u64, u64, Svc::MemoryPermission)>
253void SvcWrap64(Core::System& system) { 253void SvcWrap64(Core::System& system) {
254 FuncReturn(system, func(system, Param(system, 0), Param(system, 1), 254 FuncReturn(system, func(system, Param(system, 0), Param(system, 1),
255 static_cast<Svc::MemoryPermission>(Param(system, 2))) 255 static_cast<Svc::MemoryPermission>(Param(system, 2)))
@@ -257,14 +257,14 @@ void SvcWrap64(Core::System& system) {
257} 257}
258 258
259// Used by MapSharedMemory 259// Used by MapSharedMemory
260template <ResultCode func(Core::System&, Handle, u64, u64, Svc::MemoryPermission)> 260template <Result func(Core::System&, Handle, u64, u64, Svc::MemoryPermission)>
261void SvcWrap64(Core::System& system) { 261void SvcWrap64(Core::System& system) {
262 FuncReturn(system, func(system, static_cast<Handle>(Param(system, 0)), Param(system, 1), 262 FuncReturn(system, func(system, static_cast<Handle>(Param(system, 0)), Param(system, 1),
263 Param(system, 2), static_cast<Svc::MemoryPermission>(Param(system, 3))) 263 Param(system, 2), static_cast<Svc::MemoryPermission>(Param(system, 3)))
264 .raw); 264 .raw);
265} 265}
266 266
267template <ResultCode func(Core::System&, u32, u64, u64)> 267template <Result func(Core::System&, u32, u64, u64)>
268void SvcWrap64(Core::System& system) { 268void SvcWrap64(Core::System& system) {
269 FuncReturn( 269 FuncReturn(
270 system, 270 system,
@@ -272,7 +272,7 @@ void SvcWrap64(Core::System& system) {
272} 272}
273 273
274// Used by WaitSynchronization 274// Used by WaitSynchronization
275template <ResultCode func(Core::System&, s32*, u64, s32, s64)> 275template <Result func(Core::System&, s32*, u64, s32, s64)>
276void SvcWrap64(Core::System& system) { 276void SvcWrap64(Core::System& system) {
277 s32 param_1 = 0; 277 s32 param_1 = 0;
278 const u32 retval = func(system, &param_1, Param(system, 1), static_cast<s32>(Param(system, 2)), 278 const u32 retval = func(system, &param_1, Param(system, 1), static_cast<s32>(Param(system, 2)),
@@ -283,7 +283,7 @@ void SvcWrap64(Core::System& system) {
283 FuncReturn(system, retval); 283 FuncReturn(system, retval);
284} 284}
285 285
286template <ResultCode func(Core::System&, u64, u64, u32, s64)> 286template <Result func(Core::System&, u64, u64, u32, s64)>
287void SvcWrap64(Core::System& system) { 287void SvcWrap64(Core::System& system) {
288 FuncReturn(system, func(system, Param(system, 0), Param(system, 1), 288 FuncReturn(system, func(system, Param(system, 0), Param(system, 1),
289 static_cast<u32>(Param(system, 2)), static_cast<s64>(Param(system, 3))) 289 static_cast<u32>(Param(system, 2)), static_cast<s64>(Param(system, 3)))
@@ -291,7 +291,7 @@ void SvcWrap64(Core::System& system) {
291} 291}
292 292
293// Used by GetInfo 293// Used by GetInfo
294template <ResultCode func(Core::System&, u64*, u64, Handle, u64)> 294template <Result func(Core::System&, u64*, u64, Handle, u64)>
295void SvcWrap64(Core::System& system) { 295void SvcWrap64(Core::System& system) {
296 u64 param_1 = 0; 296 u64 param_1 = 0;
297 const u32 retval = func(system, &param_1, Param(system, 1), 297 const u32 retval = func(system, &param_1, Param(system, 1),
@@ -302,7 +302,7 @@ void SvcWrap64(Core::System& system) {
302 FuncReturn(system, retval); 302 FuncReturn(system, retval);
303} 303}
304 304
305template <ResultCode func(Core::System&, u32*, u64, u64, u64, u32, s32)> 305template <Result func(Core::System&, u32*, u64, u64, u64, u32, s32)>
306void SvcWrap64(Core::System& system) { 306void SvcWrap64(Core::System& system) {
307 u32 param_1 = 0; 307 u32 param_1 = 0;
308 const u32 retval = func(system, &param_1, Param(system, 1), Param(system, 2), Param(system, 3), 308 const u32 retval = func(system, &param_1, Param(system, 1), Param(system, 2), Param(system, 3),
@@ -314,7 +314,7 @@ void SvcWrap64(Core::System& system) {
314} 314}
315 315
316// Used by CreateTransferMemory 316// Used by CreateTransferMemory
317template <ResultCode func(Core::System&, Handle*, u64, u64, Svc::MemoryPermission)> 317template <Result func(Core::System&, Handle*, u64, u64, Svc::MemoryPermission)>
318void SvcWrap64(Core::System& system) { 318void SvcWrap64(Core::System& system) {
319 u32 param_1 = 0; 319 u32 param_1 = 0;
320 const u32 retval = func(system, &param_1, Param(system, 1), Param(system, 2), 320 const u32 retval = func(system, &param_1, Param(system, 1), Param(system, 2),
@@ -326,7 +326,7 @@ void SvcWrap64(Core::System& system) {
326} 326}
327 327
328// Used by CreateCodeMemory 328// Used by CreateCodeMemory
329template <ResultCode func(Core::System&, Handle*, u64, u64)> 329template <Result func(Core::System&, Handle*, u64, u64)>
330void SvcWrap64(Core::System& system) { 330void SvcWrap64(Core::System& system) {
331 u32 param_1 = 0; 331 u32 param_1 = 0;
332 const u32 retval = func(system, &param_1, Param(system, 1), Param(system, 2)).raw; 332 const u32 retval = func(system, &param_1, Param(system, 1), Param(system, 2)).raw;
@@ -335,7 +335,7 @@ void SvcWrap64(Core::System& system) {
335 FuncReturn(system, retval); 335 FuncReturn(system, retval);
336} 336}
337 337
338template <ResultCode func(Core::System&, Handle*, u64, u32, u32)> 338template <Result func(Core::System&, Handle*, u64, u32, u32)>
339void SvcWrap64(Core::System& system) { 339void SvcWrap64(Core::System& system) {
340 u32 param_1 = 0; 340 u32 param_1 = 0;
341 const u32 retval = func(system, &param_1, Param(system, 1), static_cast<u32>(Param(system, 2)), 341 const u32 retval = func(system, &param_1, Param(system, 1), static_cast<u32>(Param(system, 2)),
@@ -347,7 +347,7 @@ void SvcWrap64(Core::System& system) {
347} 347}
348 348
349// Used by WaitForAddress 349// Used by WaitForAddress
350template <ResultCode func(Core::System&, u64, Svc::ArbitrationType, s32, s64)> 350template <Result func(Core::System&, u64, Svc::ArbitrationType, s32, s64)>
351void SvcWrap64(Core::System& system) { 351void SvcWrap64(Core::System& system) {
352 FuncReturn(system, 352 FuncReturn(system,
353 func(system, Param(system, 0), static_cast<Svc::ArbitrationType>(Param(system, 1)), 353 func(system, Param(system, 0), static_cast<Svc::ArbitrationType>(Param(system, 1)),
@@ -356,7 +356,7 @@ void SvcWrap64(Core::System& system) {
356} 356}
357 357
358// Used by SignalToAddress 358// Used by SignalToAddress
359template <ResultCode func(Core::System&, u64, Svc::SignalType, s32, s32)> 359template <Result func(Core::System&, u64, Svc::SignalType, s32, s32)>
360void SvcWrap64(Core::System& system) { 360void SvcWrap64(Core::System& system) {
361 FuncReturn(system, 361 FuncReturn(system,
362 func(system, Param(system, 0), static_cast<Svc::SignalType>(Param(system, 1)), 362 func(system, Param(system, 0), static_cast<Svc::SignalType>(Param(system, 1)),
@@ -425,7 +425,7 @@ void SvcWrap64(Core::System& system) {
425} 425}
426 426
427// Used by QueryMemory32, ArbitrateLock32 427// Used by QueryMemory32, ArbitrateLock32
428template <ResultCode func(Core::System&, u32, u32, u32)> 428template <Result func(Core::System&, u32, u32, u32)>
429void SvcWrap32(Core::System& system) { 429void SvcWrap32(Core::System& system) {
430 FuncReturn32(system, 430 FuncReturn32(system,
431 func(system, Param32(system, 0), Param32(system, 1), Param32(system, 2)).raw); 431 func(system, Param32(system, 0), Param32(system, 1), Param32(system, 2)).raw);
@@ -456,7 +456,7 @@ void SvcWrap32(Core::System& system) {
456} 456}
457 457
458// Used by CreateThread32 458// Used by CreateThread32
459template <ResultCode func(Core::System&, Handle*, u32, u32, u32, u32, s32)> 459template <Result func(Core::System&, Handle*, u32, u32, u32, u32, s32)>
460void SvcWrap32(Core::System& system) { 460void SvcWrap32(Core::System& system) {
461 Handle param_1 = 0; 461 Handle param_1 = 0;
462 462
@@ -469,7 +469,7 @@ void SvcWrap32(Core::System& system) {
469} 469}
470 470
471// Used by GetInfo32 471// Used by GetInfo32
472template <ResultCode func(Core::System&, u32*, u32*, u32, u32, u32, u32)> 472template <Result func(Core::System&, u32*, u32*, u32, u32, u32, u32)>
473void SvcWrap32(Core::System& system) { 473void SvcWrap32(Core::System& system) {
474 u32 param_1 = 0; 474 u32 param_1 = 0;
475 u32 param_2 = 0; 475 u32 param_2 = 0;
@@ -484,7 +484,7 @@ void SvcWrap32(Core::System& system) {
484} 484}
485 485
486// Used by GetThreadPriority32, ConnectToNamedPort32 486// Used by GetThreadPriority32, ConnectToNamedPort32
487template <ResultCode func(Core::System&, u32*, u32)> 487template <Result func(Core::System&, u32*, u32)>
488void SvcWrap32(Core::System& system) { 488void SvcWrap32(Core::System& system) {
489 u32 param_1 = 0; 489 u32 param_1 = 0;
490 const u32 retval = func(system, &param_1, Param32(system, 1)).raw; 490 const u32 retval = func(system, &param_1, Param32(system, 1)).raw;
@@ -493,7 +493,7 @@ void SvcWrap32(Core::System& system) {
493} 493}
494 494
495// Used by GetThreadId32 495// Used by GetThreadId32
496template <ResultCode func(Core::System&, u32*, u32*, u32)> 496template <Result func(Core::System&, u32*, u32*, u32)>
497void SvcWrap32(Core::System& system) { 497void SvcWrap32(Core::System& system) {
498 u32 param_1 = 0; 498 u32 param_1 = 0;
499 u32 param_2 = 0; 499 u32 param_2 = 0;
@@ -516,7 +516,7 @@ void SvcWrap32(Core::System& system) {
516} 516}
517 517
518// Used by CreateEvent32 518// Used by CreateEvent32
519template <ResultCode func(Core::System&, Handle*, Handle*)> 519template <Result func(Core::System&, Handle*, Handle*)>
520void SvcWrap32(Core::System& system) { 520void SvcWrap32(Core::System& system) {
521 Handle param_1 = 0; 521 Handle param_1 = 0;
522 Handle param_2 = 0; 522 Handle param_2 = 0;
@@ -528,7 +528,7 @@ void SvcWrap32(Core::System& system) {
528} 528}
529 529
530// Used by GetThreadId32 530// Used by GetThreadId32
531template <ResultCode func(Core::System&, Handle, u32*, u32*, u32*)> 531template <Result func(Core::System&, Handle, u32*, u32*, u32*)>
532void SvcWrap32(Core::System& system) { 532void SvcWrap32(Core::System& system) {
533 u32 param_1 = 0; 533 u32 param_1 = 0;
534 u32 param_2 = 0; 534 u32 param_2 = 0;
@@ -542,7 +542,7 @@ void SvcWrap32(Core::System& system) {
542} 542}
543 543
544// Used by GetThreadCoreMask32 544// Used by GetThreadCoreMask32
545template <ResultCode func(Core::System&, Handle, s32*, u32*, u32*)> 545template <Result func(Core::System&, Handle, s32*, u32*, u32*)>
546void SvcWrap32(Core::System& system) { 546void SvcWrap32(Core::System& system) {
547 s32 param_1 = 0; 547 s32 param_1 = 0;
548 u32 param_2 = 0; 548 u32 param_2 = 0;
@@ -562,7 +562,7 @@ void SvcWrap32(Core::System& system) {
562} 562}
563 563
564// Used by SetThreadActivity32 564// Used by SetThreadActivity32
565template <ResultCode func(Core::System&, Handle, Svc::ThreadActivity)> 565template <Result func(Core::System&, Handle, Svc::ThreadActivity)>
566void SvcWrap32(Core::System& system) { 566void SvcWrap32(Core::System& system) {
567 const u32 retval = func(system, static_cast<Handle>(Param(system, 0)), 567 const u32 retval = func(system, static_cast<Handle>(Param(system, 0)),
568 static_cast<Svc::ThreadActivity>(Param(system, 1))) 568 static_cast<Svc::ThreadActivity>(Param(system, 1)))
@@ -571,7 +571,7 @@ void SvcWrap32(Core::System& system) {
571} 571}
572 572
573// Used by SetThreadPriority32 573// Used by SetThreadPriority32
574template <ResultCode func(Core::System&, Handle, u32)> 574template <Result func(Core::System&, Handle, u32)>
575void SvcWrap32(Core::System& system) { 575void SvcWrap32(Core::System& system) {
576 const u32 retval = 576 const u32 retval =
577 func(system, static_cast<Handle>(Param(system, 0)), static_cast<u32>(Param(system, 1))).raw; 577 func(system, static_cast<Handle>(Param(system, 0)), static_cast<u32>(Param(system, 1))).raw;
@@ -579,7 +579,7 @@ void SvcWrap32(Core::System& system) {
579} 579}
580 580
581// Used by SetMemoryAttribute32 581// Used by SetMemoryAttribute32
582template <ResultCode func(Core::System&, Handle, u32, u32, u32)> 582template <Result func(Core::System&, Handle, u32, u32, u32)>
583void SvcWrap32(Core::System& system) { 583void SvcWrap32(Core::System& system) {
584 const u32 retval = 584 const u32 retval =
585 func(system, static_cast<Handle>(Param(system, 0)), static_cast<u32>(Param(system, 1)), 585 func(system, static_cast<Handle>(Param(system, 0)), static_cast<u32>(Param(system, 1)),
@@ -589,7 +589,7 @@ void SvcWrap32(Core::System& system) {
589} 589}
590 590
591// Used by MapSharedMemory32 591// Used by MapSharedMemory32
592template <ResultCode func(Core::System&, Handle, u32, u32, Svc::MemoryPermission)> 592template <Result func(Core::System&, Handle, u32, u32, Svc::MemoryPermission)>
593void SvcWrap32(Core::System& system) { 593void SvcWrap32(Core::System& system) {
594 const u32 retval = func(system, static_cast<Handle>(Param(system, 0)), 594 const u32 retval = func(system, static_cast<Handle>(Param(system, 0)),
595 static_cast<u32>(Param(system, 1)), static_cast<u32>(Param(system, 2)), 595 static_cast<u32>(Param(system, 1)), static_cast<u32>(Param(system, 2)),
@@ -599,7 +599,7 @@ void SvcWrap32(Core::System& system) {
599} 599}
600 600
601// Used by SetThreadCoreMask32 601// Used by SetThreadCoreMask32
602template <ResultCode func(Core::System&, Handle, s32, u32, u32)> 602template <Result func(Core::System&, Handle, s32, u32, u32)>
603void SvcWrap32(Core::System& system) { 603void SvcWrap32(Core::System& system) {
604 const u32 retval = 604 const u32 retval =
605 func(system, static_cast<Handle>(Param(system, 0)), static_cast<s32>(Param(system, 1)), 605 func(system, static_cast<Handle>(Param(system, 0)), static_cast<s32>(Param(system, 1)),
@@ -609,7 +609,7 @@ void SvcWrap32(Core::System& system) {
609} 609}
610 610
611// Used by WaitProcessWideKeyAtomic32 611// Used by WaitProcessWideKeyAtomic32
612template <ResultCode func(Core::System&, u32, u32, Handle, u32, u32)> 612template <Result func(Core::System&, u32, u32, Handle, u32, u32)>
613void SvcWrap32(Core::System& system) { 613void SvcWrap32(Core::System& system) {
614 const u32 retval = 614 const u32 retval =
615 func(system, static_cast<u32>(Param(system, 0)), static_cast<u32>(Param(system, 1)), 615 func(system, static_cast<u32>(Param(system, 0)), static_cast<u32>(Param(system, 1)),
@@ -620,7 +620,7 @@ void SvcWrap32(Core::System& system) {
620} 620}
621 621
622// Used by WaitForAddress32 622// Used by WaitForAddress32
623template <ResultCode func(Core::System&, u32, Svc::ArbitrationType, s32, u32, u32)> 623template <Result func(Core::System&, u32, Svc::ArbitrationType, s32, u32, u32)>
624void SvcWrap32(Core::System& system) { 624void SvcWrap32(Core::System& system) {
625 const u32 retval = func(system, static_cast<u32>(Param(system, 0)), 625 const u32 retval = func(system, static_cast<u32>(Param(system, 0)),
626 static_cast<Svc::ArbitrationType>(Param(system, 1)), 626 static_cast<Svc::ArbitrationType>(Param(system, 1)),
@@ -631,7 +631,7 @@ void SvcWrap32(Core::System& system) {
631} 631}
632 632
633// Used by SignalToAddress32 633// Used by SignalToAddress32
634template <ResultCode func(Core::System&, u32, Svc::SignalType, s32, s32)> 634template <Result func(Core::System&, u32, Svc::SignalType, s32, s32)>
635void SvcWrap32(Core::System& system) { 635void SvcWrap32(Core::System& system) {
636 const u32 retval = func(system, static_cast<u32>(Param(system, 0)), 636 const u32 retval = func(system, static_cast<u32>(Param(system, 0)),
637 static_cast<Svc::SignalType>(Param(system, 1)), 637 static_cast<Svc::SignalType>(Param(system, 1)),
@@ -641,13 +641,13 @@ void SvcWrap32(Core::System& system) {
641} 641}
642 642
643// Used by SendSyncRequest32, ArbitrateUnlock32 643// Used by SendSyncRequest32, ArbitrateUnlock32
644template <ResultCode func(Core::System&, u32)> 644template <Result func(Core::System&, u32)>
645void SvcWrap32(Core::System& system) { 645void SvcWrap32(Core::System& system) {
646 FuncReturn(system, func(system, static_cast<u32>(Param(system, 0))).raw); 646 FuncReturn(system, func(system, static_cast<u32>(Param(system, 0))).raw);
647} 647}
648 648
649// Used by CreateTransferMemory32 649// Used by CreateTransferMemory32
650template <ResultCode func(Core::System&, Handle*, u32, u32, Svc::MemoryPermission)> 650template <Result func(Core::System&, Handle*, u32, u32, Svc::MemoryPermission)>
651void SvcWrap32(Core::System& system) { 651void SvcWrap32(Core::System& system) {
652 Handle handle = 0; 652 Handle handle = 0;
653 const u32 retval = func(system, &handle, Param32(system, 1), Param32(system, 2), 653 const u32 retval = func(system, &handle, Param32(system, 1), Param32(system, 2),
@@ -658,7 +658,7 @@ void SvcWrap32(Core::System& system) {
658} 658}
659 659
660// Used by WaitSynchronization32 660// Used by WaitSynchronization32
661template <ResultCode func(Core::System&, u32, u32, s32, u32, s32*)> 661template <Result func(Core::System&, u32, u32, s32, u32, s32*)>
662void SvcWrap32(Core::System& system) { 662void SvcWrap32(Core::System& system) {
663 s32 param_1 = 0; 663 s32 param_1 = 0;
664 const u32 retval = func(system, Param32(system, 0), Param32(system, 1), Param32(system, 2), 664 const u32 retval = func(system, Param32(system, 0), Param32(system, 1), Param32(system, 2),
@@ -669,7 +669,7 @@ void SvcWrap32(Core::System& system) {
669} 669}
670 670
671// Used by CreateCodeMemory32 671// Used by CreateCodeMemory32
672template <ResultCode func(Core::System&, Handle*, u32, u32)> 672template <Result func(Core::System&, Handle*, u32, u32)>
673void SvcWrap32(Core::System& system) { 673void SvcWrap32(Core::System& system) {
674 Handle handle = 0; 674 Handle handle = 0;
675 675
@@ -680,7 +680,7 @@ void SvcWrap32(Core::System& system) {
680} 680}
681 681
682// Used by ControlCodeMemory32 682// Used by ControlCodeMemory32
683template <ResultCode func(Core::System&, Handle, u32, u64, u64, Svc::MemoryPermission)> 683template <Result func(Core::System&, Handle, u32, u64, u64, Svc::MemoryPermission)>
684void SvcWrap32(Core::System& system) { 684void SvcWrap32(Core::System& system) {
685 const u32 retval = 685 const u32 retval =
686 func(system, Param32(system, 0), Param32(system, 1), Param(system, 2), Param(system, 4), 686 func(system, Param32(system, 0), Param32(system, 1), Param(system, 2), Param(system, 4),
diff --git a/src/core/hle/result.h b/src/core/hle/result.h
index 569dd9f38..aa9e5b89d 100644
--- a/src/core/hle/result.h
+++ b/src/core/hle/result.h
@@ -112,15 +112,15 @@ enum class ErrorModule : u32 {
112}; 112};
113 113
114/// Encapsulates a Horizon OS error code, allowing it to be separated into its constituent fields. 114/// Encapsulates a Horizon OS error code, allowing it to be separated into its constituent fields.
115union ResultCode { 115union Result {
116 u32 raw; 116 u32 raw;
117 117
118 BitField<0, 9, ErrorModule> module; 118 BitField<0, 9, ErrorModule> module;
119 BitField<9, 13, u32> description; 119 BitField<9, 13, u32> description;
120 120
121 constexpr explicit ResultCode(u32 raw_) : raw(raw_) {} 121 constexpr explicit Result(u32 raw_) : raw(raw_) {}
122 122
123 constexpr ResultCode(ErrorModule module_, u32 description_) 123 constexpr Result(ErrorModule module_, u32 description_)
124 : raw(module.FormatValue(module_) | description.FormatValue(description_)) {} 124 : raw(module.FormatValue(module_) | description.FormatValue(description_)) {}
125 125
126 [[nodiscard]] constexpr bool IsSuccess() const { 126 [[nodiscard]] constexpr bool IsSuccess() const {
@@ -132,18 +132,18 @@ union ResultCode {
132 } 132 }
133}; 133};
134 134
135[[nodiscard]] constexpr bool operator==(const ResultCode& a, const ResultCode& b) { 135[[nodiscard]] constexpr bool operator==(const Result& a, const Result& b) {
136 return a.raw == b.raw; 136 return a.raw == b.raw;
137} 137}
138 138
139[[nodiscard]] constexpr bool operator!=(const ResultCode& a, const ResultCode& b) { 139[[nodiscard]] constexpr bool operator!=(const Result& a, const Result& b) {
140 return !operator==(a, b); 140 return !operator==(a, b);
141} 141}
142 142
143// Convenience functions for creating some common kinds of errors: 143// Convenience functions for creating some common kinds of errors:
144 144
145/// The default success `ResultCode`. 145/// The default success `Result`.
146constexpr ResultCode ResultSuccess(0); 146constexpr Result ResultSuccess(0);
147 147
148/** 148/**
149 * Placeholder result code used for unknown error codes. 149 * Placeholder result code used for unknown error codes.
@@ -151,24 +151,24 @@ constexpr ResultCode ResultSuccess(0);
151 * @note This should only be used when a particular error code 151 * @note This should only be used when a particular error code
152 * is not known yet. 152 * is not known yet.
153 */ 153 */
154constexpr ResultCode ResultUnknown(UINT32_MAX); 154constexpr Result ResultUnknown(UINT32_MAX);
155 155
156/** 156/**
157 * A ResultRange defines an inclusive range of error descriptions within an error module. 157 * A ResultRange defines an inclusive range of error descriptions within an error module.
158 * This can be used to check whether the description of a given ResultCode falls within the range. 158 * This can be used to check whether the description of a given Result falls within the range.
159 * The conversion function returns a ResultCode with its description set to description_start. 159 * The conversion function returns a Result with its description set to description_start.
160 * 160 *
161 * An example of how it could be used: 161 * An example of how it could be used:
162 * \code 162 * \code
163 * constexpr ResultRange ResultCommonError{ErrorModule::Common, 0, 9999}; 163 * constexpr ResultRange ResultCommonError{ErrorModule::Common, 0, 9999};
164 * 164 *
165 * ResultCode Example(int value) { 165 * Result Example(int value) {
166 * const ResultCode result = OtherExample(value); 166 * const Result result = OtherExample(value);
167 * 167 *
168 * // This will only evaluate to true if result.module is ErrorModule::Common and 168 * // This will only evaluate to true if result.module is ErrorModule::Common and
169 * // result.description is in between 0 and 9999 inclusive. 169 * // result.description is in between 0 and 9999 inclusive.
170 * if (ResultCommonError.Includes(result)) { 170 * if (ResultCommonError.Includes(result)) {
171 * // This returns ResultCode{ErrorModule::Common, 0}; 171 * // This returns Result{ErrorModule::Common, 0};
172 * return ResultCommonError; 172 * return ResultCommonError;
173 * } 173 * }
174 * 174 *
@@ -181,22 +181,22 @@ public:
181 consteval ResultRange(ErrorModule module, u32 description_start, u32 description_end_) 181 consteval ResultRange(ErrorModule module, u32 description_start, u32 description_end_)
182 : code{module, description_start}, description_end{description_end_} {} 182 : code{module, description_start}, description_end{description_end_} {}
183 183
184 [[nodiscard]] constexpr operator ResultCode() const { 184 [[nodiscard]] constexpr operator Result() const {
185 return code; 185 return code;
186 } 186 }
187 187
188 [[nodiscard]] constexpr bool Includes(ResultCode other) const { 188 [[nodiscard]] constexpr bool Includes(Result other) const {
189 return code.module == other.module && code.description <= other.description && 189 return code.module == other.module && code.description <= other.description &&
190 other.description <= description_end; 190 other.description <= description_end;
191 } 191 }
192 192
193private: 193private:
194 ResultCode code; 194 Result code;
195 u32 description_end; 195 u32 description_end;
196}; 196};
197 197
198/** 198/**
199 * This is an optional value type. It holds a `ResultCode` and, if that code is ResultSuccess, it 199 * This is an optional value type. It holds a `Result` and, if that code is ResultSuccess, it
200 * also holds a result of type `T`. If the code is an error code (not ResultSuccess), then trying 200 * also holds a result of type `T`. If the code is an error code (not ResultSuccess), then trying
201 * to access the inner value with operator* is undefined behavior and will assert with Unwrap(). 201 * to access the inner value with operator* is undefined behavior and will assert with Unwrap().
202 * Users of this class must be cognizant to check the status of the ResultVal with operator bool(), 202 * Users of this class must be cognizant to check the status of the ResultVal with operator bool(),
@@ -207,7 +207,7 @@ private:
207 * ResultVal<int> Frobnicate(float strength) { 207 * ResultVal<int> Frobnicate(float strength) {
208 * if (strength < 0.f || strength > 1.0f) { 208 * if (strength < 0.f || strength > 1.0f) {
209 * // Can't frobnicate too weakly or too strongly 209 * // Can't frobnicate too weakly or too strongly
210 * return ResultCode{ErrorModule::Common, 1}; 210 * return Result{ErrorModule::Common, 1};
211 * } else { 211 * } else {
212 * // Frobnicated! Give caller a cookie 212 * // Frobnicated! Give caller a cookie
213 * return 42; 213 * return 42;
@@ -230,7 +230,7 @@ class ResultVal {
230public: 230public:
231 constexpr ResultVal() : expected{} {} 231 constexpr ResultVal() : expected{} {}
232 232
233 constexpr ResultVal(ResultCode code) : expected{Common::Unexpected(code)} {} 233 constexpr ResultVal(Result code) : expected{Common::Unexpected(code)} {}
234 234
235 constexpr ResultVal(ResultRange range) : expected{Common::Unexpected(range)} {} 235 constexpr ResultVal(ResultRange range) : expected{Common::Unexpected(range)} {}
236 236
@@ -252,7 +252,7 @@ public:
252 return expected.has_value(); 252 return expected.has_value();
253 } 253 }
254 254
255 [[nodiscard]] constexpr ResultCode Code() const { 255 [[nodiscard]] constexpr Result Code() const {
256 return expected.has_value() ? ResultSuccess : expected.error(); 256 return expected.has_value() ? ResultSuccess : expected.error();
257 } 257 }
258 258
@@ -320,7 +320,7 @@ public:
320 320
321private: 321private:
322 // TODO (Morph): Replace this with C++23 std::expected. 322 // TODO (Morph): Replace this with C++23 std::expected.
323 Common::Expected<T, ResultCode> expected; 323 Common::Expected<T, Result> expected;
324}; 324};
325 325
326/** 326/**
@@ -337,7 +337,7 @@ private:
337 target = std::move(*CONCAT2(check_result_L, __LINE__)) 337 target = std::move(*CONCAT2(check_result_L, __LINE__))
338 338
339/** 339/**
340 * Analogous to CASCADE_RESULT, but for a bare ResultCode. The code will be propagated if 340 * Analogous to CASCADE_RESULT, but for a bare Result. The code will be propagated if
341 * non-success, or discarded otherwise. 341 * non-success, or discarded otherwise.
342 */ 342 */
343#define CASCADE_CODE(source) \ 343#define CASCADE_CODE(source) \
diff --git a/src/core/hle/service/acc/acc.cpp b/src/core/hle/service/acc/acc.cpp
index 88b74cbb0..b726ac27a 100644
--- a/src/core/hle/service/acc/acc.cpp
+++ b/src/core/hle/service/acc/acc.cpp
@@ -28,11 +28,11 @@
28 28
29namespace Service::Account { 29namespace Service::Account {
30 30
31constexpr ResultCode ERR_INVALID_USER_ID{ErrorModule::Account, 20}; 31constexpr Result ERR_INVALID_USER_ID{ErrorModule::Account, 20};
32constexpr ResultCode ERR_INVALID_APPLICATION_ID{ErrorModule::Account, 22}; 32constexpr Result ERR_INVALID_APPLICATION_ID{ErrorModule::Account, 22};
33constexpr ResultCode ERR_INVALID_BUFFER{ErrorModule::Account, 30}; 33constexpr Result ERR_INVALID_BUFFER{ErrorModule::Account, 30};
34constexpr ResultCode ERR_INVALID_BUFFER_SIZE{ErrorModule::Account, 31}; 34constexpr Result ERR_INVALID_BUFFER_SIZE{ErrorModule::Account, 31};
35constexpr ResultCode ERR_FAILED_SAVE_DATA{ErrorModule::Account, 100}; 35constexpr Result ERR_FAILED_SAVE_DATA{ErrorModule::Account, 100};
36 36
37// Thumbnails are hard coded to be at least this size 37// Thumbnails are hard coded to be at least this size
38constexpr std::size_t THUMBNAIL_SIZE = 0x24000; 38constexpr std::size_t THUMBNAIL_SIZE = 0x24000;
@@ -505,7 +505,7 @@ protected:
505 505
506 void Cancel() override {} 506 void Cancel() override {}
507 507
508 ResultCode GetResult() const override { 508 Result GetResult() const override {
509 return ResultSuccess; 509 return ResultSuccess;
510 } 510 }
511}; 511};
@@ -747,7 +747,7 @@ void Module::Interface::InitializeApplicationInfoRestricted(Kernel::HLERequestCo
747 rb.Push(InitializeApplicationInfoBase()); 747 rb.Push(InitializeApplicationInfoBase());
748} 748}
749 749
750ResultCode Module::Interface::InitializeApplicationInfoBase() { 750Result Module::Interface::InitializeApplicationInfoBase() {
751 if (application_info) { 751 if (application_info) {
752 LOG_ERROR(Service_ACC, "Application already initialized"); 752 LOG_ERROR(Service_ACC, "Application already initialized");
753 return ERR_ACCOUNTINFO_ALREADY_INITIALIZED; 753 return ERR_ACCOUNTINFO_ALREADY_INITIALIZED;
diff --git a/src/core/hle/service/acc/acc.h b/src/core/hle/service/acc/acc.h
index fff447fc3..1621e7c0a 100644
--- a/src/core/hle/service/acc/acc.h
+++ b/src/core/hle/service/acc/acc.h
@@ -41,7 +41,7 @@ public:
41 void StoreSaveDataThumbnailSystem(Kernel::HLERequestContext& ctx); 41 void StoreSaveDataThumbnailSystem(Kernel::HLERequestContext& ctx);
42 42
43 private: 43 private:
44 ResultCode InitializeApplicationInfoBase(); 44 Result InitializeApplicationInfoBase();
45 void StoreSaveDataThumbnail(Kernel::HLERequestContext& ctx, const Common::UUID& uuid, 45 void StoreSaveDataThumbnail(Kernel::HLERequestContext& ctx, const Common::UUID& uuid,
46 const u64 tid); 46 const u64 tid);
47 47
diff --git a/src/core/hle/service/acc/async_context.h b/src/core/hle/service/acc/async_context.h
index e4929f7f0..26332d241 100644
--- a/src/core/hle/service/acc/async_context.h
+++ b/src/core/hle/service/acc/async_context.h
@@ -26,7 +26,7 @@ public:
26protected: 26protected:
27 virtual bool IsComplete() const = 0; 27 virtual bool IsComplete() const = 0;
28 virtual void Cancel() = 0; 28 virtual void Cancel() = 0;
29 virtual ResultCode GetResult() const = 0; 29 virtual Result GetResult() const = 0;
30 30
31 void MarkComplete(); 31 void MarkComplete();
32 32
diff --git a/src/core/hle/service/acc/errors.h b/src/core/hle/service/acc/errors.h
index eafb75713..e9c16b951 100644
--- a/src/core/hle/service/acc/errors.h
+++ b/src/core/hle/service/acc/errors.h
@@ -7,7 +7,7 @@
7 7
8namespace Service::Account { 8namespace Service::Account {
9 9
10constexpr ResultCode ERR_ACCOUNTINFO_BAD_APPLICATION{ErrorModule::Account, 22}; 10constexpr Result ERR_ACCOUNTINFO_BAD_APPLICATION{ErrorModule::Account, 22};
11constexpr ResultCode ERR_ACCOUNTINFO_ALREADY_INITIALIZED{ErrorModule::Account, 41}; 11constexpr Result ERR_ACCOUNTINFO_ALREADY_INITIALIZED{ErrorModule::Account, 41};
12 12
13} // namespace Service::Account 13} // namespace Service::Account
diff --git a/src/core/hle/service/acc/profile_manager.cpp b/src/core/hle/service/acc/profile_manager.cpp
index 0ef298180..8118ead33 100644
--- a/src/core/hle/service/acc/profile_manager.cpp
+++ b/src/core/hle/service/acc/profile_manager.cpp
@@ -33,9 +33,9 @@ struct ProfileDataRaw {
33static_assert(sizeof(ProfileDataRaw) == 0x650, "ProfileDataRaw has incorrect size."); 33static_assert(sizeof(ProfileDataRaw) == 0x650, "ProfileDataRaw has incorrect size.");
34 34
35// TODO(ogniK): Get actual error codes 35// TODO(ogniK): Get actual error codes
36constexpr ResultCode ERROR_TOO_MANY_USERS(ErrorModule::Account, u32(-1)); 36constexpr Result ERROR_TOO_MANY_USERS(ErrorModule::Account, u32(-1));
37constexpr ResultCode ERROR_USER_ALREADY_EXISTS(ErrorModule::Account, u32(-2)); 37constexpr Result ERROR_USER_ALREADY_EXISTS(ErrorModule::Account, u32(-2));
38constexpr ResultCode ERROR_ARGUMENT_IS_NULL(ErrorModule::Account, 20); 38constexpr Result ERROR_ARGUMENT_IS_NULL(ErrorModule::Account, 20);
39 39
40constexpr char ACC_SAVE_AVATORS_BASE_PATH[] = "system/save/8000000000000010/su/avators"; 40constexpr char ACC_SAVE_AVATORS_BASE_PATH[] = "system/save/8000000000000010/su/avators";
41 41
@@ -87,7 +87,7 @@ bool ProfileManager::RemoveProfileAtIndex(std::size_t index) {
87} 87}
88 88
89/// Helper function to register a user to the system 89/// Helper function to register a user to the system
90ResultCode ProfileManager::AddUser(const ProfileInfo& user) { 90Result ProfileManager::AddUser(const ProfileInfo& user) {
91 if (!AddToProfiles(user)) { 91 if (!AddToProfiles(user)) {
92 return ERROR_TOO_MANY_USERS; 92 return ERROR_TOO_MANY_USERS;
93 } 93 }
@@ -96,7 +96,7 @@ ResultCode ProfileManager::AddUser(const ProfileInfo& user) {
96 96
97/// Create a new user on the system. If the uuid of the user already exists, the user is not 97/// Create a new user on the system. If the uuid of the user already exists, the user is not
98/// created. 98/// created.
99ResultCode ProfileManager::CreateNewUser(UUID uuid, const ProfileUsername& username) { 99Result ProfileManager::CreateNewUser(UUID uuid, const ProfileUsername& username) {
100 if (user_count == MAX_USERS) { 100 if (user_count == MAX_USERS) {
101 return ERROR_TOO_MANY_USERS; 101 return ERROR_TOO_MANY_USERS;
102 } 102 }
@@ -123,7 +123,7 @@ ResultCode ProfileManager::CreateNewUser(UUID uuid, const ProfileUsername& usern
123/// Creates a new user on the system. This function allows a much simpler method of registration 123/// Creates a new user on the system. This function allows a much simpler method of registration
124/// specifically by allowing an std::string for the username. This is required specifically since 124/// specifically by allowing an std::string for the username. This is required specifically since
125/// we're loading a string straight from the config 125/// we're loading a string straight from the config
126ResultCode ProfileManager::CreateNewUser(UUID uuid, const std::string& username) { 126Result ProfileManager::CreateNewUser(UUID uuid, const std::string& username) {
127 ProfileUsername username_output{}; 127 ProfileUsername username_output{};
128 128
129 if (username.size() > username_output.size()) { 129 if (username.size() > username_output.size()) {
diff --git a/src/core/hle/service/acc/profile_manager.h b/src/core/hle/service/acc/profile_manager.h
index 955dbd3d6..9940957f1 100644
--- a/src/core/hle/service/acc/profile_manager.h
+++ b/src/core/hle/service/acc/profile_manager.h
@@ -64,9 +64,9 @@ public:
64 ProfileManager(); 64 ProfileManager();
65 ~ProfileManager(); 65 ~ProfileManager();
66 66
67 ResultCode AddUser(const ProfileInfo& user); 67 Result AddUser(const ProfileInfo& user);
68 ResultCode CreateNewUser(Common::UUID uuid, const ProfileUsername& username); 68 Result CreateNewUser(Common::UUID uuid, const ProfileUsername& username);
69 ResultCode CreateNewUser(Common::UUID uuid, const std::string& username); 69 Result CreateNewUser(Common::UUID uuid, const std::string& username);
70 std::optional<Common::UUID> GetUser(std::size_t index) const; 70 std::optional<Common::UUID> GetUser(std::size_t index) const;
71 std::optional<std::size_t> GetUserIndex(const Common::UUID& uuid) const; 71 std::optional<std::size_t> GetUserIndex(const Common::UUID& uuid) const;
72 std::optional<std::size_t> GetUserIndex(const ProfileInfo& user) const; 72 std::optional<std::size_t> GetUserIndex(const ProfileInfo& user) const;
diff --git a/src/core/hle/service/am/am.cpp b/src/core/hle/service/am/am.cpp
index c4a93e524..d35644e73 100644
--- a/src/core/hle/service/am/am.cpp
+++ b/src/core/hle/service/am/am.cpp
@@ -40,9 +40,9 @@
40 40
41namespace Service::AM { 41namespace Service::AM {
42 42
43constexpr ResultCode ERR_NO_DATA_IN_CHANNEL{ErrorModule::AM, 2}; 43constexpr Result ERR_NO_DATA_IN_CHANNEL{ErrorModule::AM, 2};
44constexpr ResultCode ERR_NO_MESSAGES{ErrorModule::AM, 3}; 44constexpr Result ERR_NO_MESSAGES{ErrorModule::AM, 3};
45constexpr ResultCode ERR_SIZE_OUT_OF_BOUNDS{ErrorModule::AM, 503}; 45constexpr Result ERR_SIZE_OUT_OF_BOUNDS{ErrorModule::AM, 503};
46 46
47enum class LaunchParameterKind : u32 { 47enum class LaunchParameterKind : u32 {
48 ApplicationSpecific = 1, 48 ApplicationSpecific = 1,
@@ -365,7 +365,7 @@ void ISelfController::LeaveFatalSection(Kernel::HLERequestContext& ctx) {
365 // Entry and exit of fatal sections must be balanced. 365 // Entry and exit of fatal sections must be balanced.
366 if (num_fatal_sections_entered == 0) { 366 if (num_fatal_sections_entered == 0) {
367 IPC::ResponseBuilder rb{ctx, 2}; 367 IPC::ResponseBuilder rb{ctx, 2};
368 rb.Push(ResultCode{ErrorModule::AM, 512}); 368 rb.Push(Result{ErrorModule::AM, 512});
369 return; 369 return;
370 } 370 }
371 371
diff --git a/src/core/hle/service/am/applets/applet_controller.cpp b/src/core/hle/service/am/applets/applet_controller.cpp
index 0a5603d18..b418031de 100644
--- a/src/core/hle/service/am/applets/applet_controller.cpp
+++ b/src/core/hle/service/am/applets/applet_controller.cpp
@@ -20,9 +20,9 @@
20namespace Service::AM::Applets { 20namespace Service::AM::Applets {
21 21
22// This error code (0x183ACA) is thrown when the applet fails to initialize. 22// This error code (0x183ACA) is thrown when the applet fails to initialize.
23[[maybe_unused]] constexpr ResultCode ERR_CONTROLLER_APPLET_3101{ErrorModule::HID, 3101}; 23[[maybe_unused]] constexpr Result ERR_CONTROLLER_APPLET_3101{ErrorModule::HID, 3101};
24// This error code (0x183CCA) is thrown when the u32 result in ControllerSupportResultInfo is 2. 24// This error code (0x183CCA) is thrown when the u32 result in ControllerSupportResultInfo is 2.
25[[maybe_unused]] constexpr ResultCode ERR_CONTROLLER_APPLET_3102{ErrorModule::HID, 3102}; 25[[maybe_unused]] constexpr Result ERR_CONTROLLER_APPLET_3102{ErrorModule::HID, 3102};
26 26
27static Core::Frontend::ControllerParameters ConvertToFrontendParameters( 27static Core::Frontend::ControllerParameters ConvertToFrontendParameters(
28 ControllerSupportArgPrivate private_arg, ControllerSupportArgHeader header, bool enable_text, 28 ControllerSupportArgPrivate private_arg, ControllerSupportArgHeader header, bool enable_text,
@@ -173,7 +173,7 @@ bool Controller::TransactionComplete() const {
173 return complete; 173 return complete;
174} 174}
175 175
176ResultCode Controller::GetStatus() const { 176Result Controller::GetStatus() const {
177 return status; 177 return status;
178} 178}
179 179
diff --git a/src/core/hle/service/am/applets/applet_controller.h b/src/core/hle/service/am/applets/applet_controller.h
index e1a34853d..1f9adec65 100644
--- a/src/core/hle/service/am/applets/applet_controller.h
+++ b/src/core/hle/service/am/applets/applet_controller.h
@@ -126,7 +126,7 @@ public:
126 void Initialize() override; 126 void Initialize() override;
127 127
128 bool TransactionComplete() const override; 128 bool TransactionComplete() const override;
129 ResultCode GetStatus() const override; 129 Result GetStatus() const override;
130 void ExecuteInteractive() override; 130 void ExecuteInteractive() override;
131 void Execute() override; 131 void Execute() override;
132 132
@@ -143,7 +143,7 @@ private:
143 ControllerUpdateFirmwareArg controller_update_arg; 143 ControllerUpdateFirmwareArg controller_update_arg;
144 ControllerKeyRemappingArg controller_key_remapping_arg; 144 ControllerKeyRemappingArg controller_key_remapping_arg;
145 bool complete{false}; 145 bool complete{false};
146 ResultCode status{ResultSuccess}; 146 Result status{ResultSuccess};
147 bool is_single_mode{false}; 147 bool is_single_mode{false};
148 std::vector<u8> out_data; 148 std::vector<u8> out_data;
149}; 149};
diff --git a/src/core/hle/service/am/applets/applet_error.cpp b/src/core/hle/service/am/applets/applet_error.cpp
index 0b87c60b9..fcf34bf7e 100644
--- a/src/core/hle/service/am/applets/applet_error.cpp
+++ b/src/core/hle/service/am/applets/applet_error.cpp
@@ -25,15 +25,15 @@ struct ErrorCode {
25 }; 25 };
26 } 26 }
27 27
28 static constexpr ErrorCode FromResultCode(ResultCode result) { 28 static constexpr ErrorCode FromResult(Result result) {
29 return { 29 return {
30 .error_category{2000 + static_cast<u32>(result.module.Value())}, 30 .error_category{2000 + static_cast<u32>(result.module.Value())},
31 .error_number{result.description.Value()}, 31 .error_number{result.description.Value()},
32 }; 32 };
33 } 33 }
34 34
35 constexpr ResultCode ToResultCode() const { 35 constexpr Result ToResult() const {
36 return ResultCode{static_cast<ErrorModule>(error_category - 2000), error_number}; 36 return Result{static_cast<ErrorModule>(error_category - 2000), error_number};
37 } 37 }
38}; 38};
39static_assert(sizeof(ErrorCode) == 0x8, "ErrorCode has incorrect size."); 39static_assert(sizeof(ErrorCode) == 0x8, "ErrorCode has incorrect size.");
@@ -97,8 +97,8 @@ void CopyArgumentData(const std::vector<u8>& data, T& variable) {
97 std::memcpy(&variable, data.data(), sizeof(T)); 97 std::memcpy(&variable, data.data(), sizeof(T));
98} 98}
99 99
100ResultCode Decode64BitError(u64 error) { 100Result Decode64BitError(u64 error) {
101 return ErrorCode::FromU64(error).ToResultCode(); 101 return ErrorCode::FromU64(error).ToResult();
102} 102}
103 103
104} // Anonymous namespace 104} // Anonymous namespace
@@ -127,16 +127,16 @@ void Error::Initialize() {
127 if (args->error.use_64bit_error_code) { 127 if (args->error.use_64bit_error_code) {
128 error_code = Decode64BitError(args->error.error_code_64); 128 error_code = Decode64BitError(args->error.error_code_64);
129 } else { 129 } else {
130 error_code = ResultCode(args->error.error_code_32); 130 error_code = Result(args->error.error_code_32);
131 } 131 }
132 break; 132 break;
133 case ErrorAppletMode::ShowSystemError: 133 case ErrorAppletMode::ShowSystemError:
134 CopyArgumentData(data, args->system_error); 134 CopyArgumentData(data, args->system_error);
135 error_code = ResultCode(Decode64BitError(args->system_error.error_code_64)); 135 error_code = Result(Decode64BitError(args->system_error.error_code_64));
136 break; 136 break;
137 case ErrorAppletMode::ShowApplicationError: 137 case ErrorAppletMode::ShowApplicationError:
138 CopyArgumentData(data, args->application_error); 138 CopyArgumentData(data, args->application_error);
139 error_code = ResultCode(args->application_error.error_code); 139 error_code = Result(args->application_error.error_code);
140 break; 140 break;
141 case ErrorAppletMode::ShowErrorRecord: 141 case ErrorAppletMode::ShowErrorRecord:
142 CopyArgumentData(data, args->error_record); 142 CopyArgumentData(data, args->error_record);
@@ -151,7 +151,7 @@ bool Error::TransactionComplete() const {
151 return complete; 151 return complete;
152} 152}
153 153
154ResultCode Error::GetStatus() const { 154Result Error::GetStatus() const {
155 return ResultSuccess; 155 return ResultSuccess;
156} 156}
157 157
diff --git a/src/core/hle/service/am/applets/applet_error.h b/src/core/hle/service/am/applets/applet_error.h
index 43487f647..d78d6f1d1 100644
--- a/src/core/hle/service/am/applets/applet_error.h
+++ b/src/core/hle/service/am/applets/applet_error.h
@@ -31,7 +31,7 @@ public:
31 void Initialize() override; 31 void Initialize() override;
32 32
33 bool TransactionComplete() const override; 33 bool TransactionComplete() const override;
34 ResultCode GetStatus() const override; 34 Result GetStatus() const override;
35 void ExecuteInteractive() override; 35 void ExecuteInteractive() override;
36 void Execute() override; 36 void Execute() override;
37 37
@@ -41,7 +41,7 @@ private:
41 union ErrorArguments; 41 union ErrorArguments;
42 42
43 const Core::Frontend::ErrorApplet& frontend; 43 const Core::Frontend::ErrorApplet& frontend;
44 ResultCode error_code = ResultSuccess; 44 Result error_code = ResultSuccess;
45 ErrorAppletMode mode = ErrorAppletMode::ShowError; 45 ErrorAppletMode mode = ErrorAppletMode::ShowError;
46 std::unique_ptr<ErrorArguments> args; 46 std::unique_ptr<ErrorArguments> args;
47 47
diff --git a/src/core/hle/service/am/applets/applet_general_backend.cpp b/src/core/hle/service/am/applets/applet_general_backend.cpp
index 41c002ef2..c34ef08b3 100644
--- a/src/core/hle/service/am/applets/applet_general_backend.cpp
+++ b/src/core/hle/service/am/applets/applet_general_backend.cpp
@@ -13,7 +13,7 @@
13 13
14namespace Service::AM::Applets { 14namespace Service::AM::Applets {
15 15
16constexpr ResultCode ERROR_INVALID_PIN{ErrorModule::PCTL, 221}; 16constexpr Result ERROR_INVALID_PIN{ErrorModule::PCTL, 221};
17 17
18static void LogCurrentStorage(AppletDataBroker& broker, std::string_view prefix) { 18static void LogCurrentStorage(AppletDataBroker& broker, std::string_view prefix) {
19 std::shared_ptr<IStorage> storage = broker.PopNormalDataToApplet(); 19 std::shared_ptr<IStorage> storage = broker.PopNormalDataToApplet();
@@ -71,7 +71,7 @@ bool Auth::TransactionComplete() const {
71 return complete; 71 return complete;
72} 72}
73 73
74ResultCode Auth::GetStatus() const { 74Result Auth::GetStatus() const {
75 return successful ? ResultSuccess : ERROR_INVALID_PIN; 75 return successful ? ResultSuccess : ERROR_INVALID_PIN;
76} 76}
77 77
@@ -136,7 +136,7 @@ void Auth::AuthFinished(bool is_successful) {
136 successful = is_successful; 136 successful = is_successful;
137 137
138 struct Return { 138 struct Return {
139 ResultCode result_code; 139 Result result_code;
140 }; 140 };
141 static_assert(sizeof(Return) == 0x4, "Return (AuthApplet) has incorrect size."); 141 static_assert(sizeof(Return) == 0x4, "Return (AuthApplet) has incorrect size.");
142 142
@@ -170,7 +170,7 @@ bool PhotoViewer::TransactionComplete() const {
170 return complete; 170 return complete;
171} 171}
172 172
173ResultCode PhotoViewer::GetStatus() const { 173Result PhotoViewer::GetStatus() const {
174 return ResultSuccess; 174 return ResultSuccess;
175} 175}
176 176
@@ -223,7 +223,7 @@ bool StubApplet::TransactionComplete() const {
223 return true; 223 return true;
224} 224}
225 225
226ResultCode StubApplet::GetStatus() const { 226Result StubApplet::GetStatus() const {
227 LOG_WARNING(Service_AM, "called (STUBBED)"); 227 LOG_WARNING(Service_AM, "called (STUBBED)");
228 return ResultSuccess; 228 return ResultSuccess;
229} 229}
diff --git a/src/core/hle/service/am/applets/applet_general_backend.h b/src/core/hle/service/am/applets/applet_general_backend.h
index e647d0f41..a9f2535a2 100644
--- a/src/core/hle/service/am/applets/applet_general_backend.h
+++ b/src/core/hle/service/am/applets/applet_general_backend.h
@@ -25,7 +25,7 @@ public:
25 25
26 void Initialize() override; 26 void Initialize() override;
27 bool TransactionComplete() const override; 27 bool TransactionComplete() const override;
28 ResultCode GetStatus() const override; 28 Result GetStatus() const override;
29 void ExecuteInteractive() override; 29 void ExecuteInteractive() override;
30 void Execute() override; 30 void Execute() override;
31 31
@@ -56,7 +56,7 @@ public:
56 56
57 void Initialize() override; 57 void Initialize() override;
58 bool TransactionComplete() const override; 58 bool TransactionComplete() const override;
59 ResultCode GetStatus() const override; 59 Result GetStatus() const override;
60 void ExecuteInteractive() override; 60 void ExecuteInteractive() override;
61 void Execute() override; 61 void Execute() override;
62 62
@@ -77,7 +77,7 @@ public:
77 void Initialize() override; 77 void Initialize() override;
78 78
79 bool TransactionComplete() const override; 79 bool TransactionComplete() const override;
80 ResultCode GetStatus() const override; 80 Result GetStatus() const override;
81 void ExecuteInteractive() override; 81 void ExecuteInteractive() override;
82 void Execute() override; 82 void Execute() override;
83 83
diff --git a/src/core/hle/service/am/applets/applet_mii_edit.cpp b/src/core/hle/service/am/applets/applet_mii_edit.cpp
index 8d847c3f6..ae80ef506 100644
--- a/src/core/hle/service/am/applets/applet_mii_edit.cpp
+++ b/src/core/hle/service/am/applets/applet_mii_edit.cpp
@@ -62,7 +62,7 @@ bool MiiEdit::TransactionComplete() const {
62 return is_complete; 62 return is_complete;
63} 63}
64 64
65ResultCode MiiEdit::GetStatus() const { 65Result MiiEdit::GetStatus() const {
66 return ResultSuccess; 66 return ResultSuccess;
67} 67}
68 68
diff --git a/src/core/hle/service/am/applets/applet_mii_edit.h b/src/core/hle/service/am/applets/applet_mii_edit.h
index 900754e57..d18dd3cf5 100644
--- a/src/core/hle/service/am/applets/applet_mii_edit.h
+++ b/src/core/hle/service/am/applets/applet_mii_edit.h
@@ -22,7 +22,7 @@ public:
22 void Initialize() override; 22 void Initialize() override;
23 23
24 bool TransactionComplete() const override; 24 bool TransactionComplete() const override;
25 ResultCode GetStatus() const override; 25 Result GetStatus() const override;
26 void ExecuteInteractive() override; 26 void ExecuteInteractive() override;
27 void Execute() override; 27 void Execute() override;
28 28
diff --git a/src/core/hle/service/am/applets/applet_profile_select.cpp b/src/core/hle/service/am/applets/applet_profile_select.cpp
index 02049fd9f..c738db028 100644
--- a/src/core/hle/service/am/applets/applet_profile_select.cpp
+++ b/src/core/hle/service/am/applets/applet_profile_select.cpp
@@ -12,7 +12,7 @@
12 12
13namespace Service::AM::Applets { 13namespace Service::AM::Applets {
14 14
15constexpr ResultCode ERR_USER_CANCELLED_SELECTION{ErrorModule::Account, 1}; 15constexpr Result ERR_USER_CANCELLED_SELECTION{ErrorModule::Account, 1};
16 16
17ProfileSelect::ProfileSelect(Core::System& system_, LibraryAppletMode applet_mode_, 17ProfileSelect::ProfileSelect(Core::System& system_, LibraryAppletMode applet_mode_,
18 const Core::Frontend::ProfileSelectApplet& frontend_) 18 const Core::Frontend::ProfileSelectApplet& frontend_)
@@ -39,7 +39,7 @@ bool ProfileSelect::TransactionComplete() const {
39 return complete; 39 return complete;
40} 40}
41 41
42ResultCode ProfileSelect::GetStatus() const { 42Result ProfileSelect::GetStatus() const {
43 return status; 43 return status;
44} 44}
45 45
diff --git a/src/core/hle/service/am/applets/applet_profile_select.h b/src/core/hle/service/am/applets/applet_profile_select.h
index 3a6e50eaa..b77f1d205 100644
--- a/src/core/hle/service/am/applets/applet_profile_select.h
+++ b/src/core/hle/service/am/applets/applet_profile_select.h
@@ -39,7 +39,7 @@ public:
39 void Initialize() override; 39 void Initialize() override;
40 40
41 bool TransactionComplete() const override; 41 bool TransactionComplete() const override;
42 ResultCode GetStatus() const override; 42 Result GetStatus() const override;
43 void ExecuteInteractive() override; 43 void ExecuteInteractive() override;
44 void Execute() override; 44 void Execute() override;
45 45
@@ -50,7 +50,7 @@ private:
50 50
51 UserSelectionConfig config; 51 UserSelectionConfig config;
52 bool complete = false; 52 bool complete = false;
53 ResultCode status = ResultSuccess; 53 Result status = ResultSuccess;
54 std::vector<u8> final_data; 54 std::vector<u8> final_data;
55 Core::System& system; 55 Core::System& system;
56}; 56};
diff --git a/src/core/hle/service/am/applets/applet_software_keyboard.cpp b/src/core/hle/service/am/applets/applet_software_keyboard.cpp
index 4116fbaa7..faa092957 100644
--- a/src/core/hle/service/am/applets/applet_software_keyboard.cpp
+++ b/src/core/hle/service/am/applets/applet_software_keyboard.cpp
@@ -80,7 +80,7 @@ bool SoftwareKeyboard::TransactionComplete() const {
80 return complete; 80 return complete;
81} 81}
82 82
83ResultCode SoftwareKeyboard::GetStatus() const { 83Result SoftwareKeyboard::GetStatus() const {
84 return status; 84 return status;
85} 85}
86 86
diff --git a/src/core/hle/service/am/applets/applet_software_keyboard.h b/src/core/hle/service/am/applets/applet_software_keyboard.h
index c36806a72..b01b31c98 100644
--- a/src/core/hle/service/am/applets/applet_software_keyboard.h
+++ b/src/core/hle/service/am/applets/applet_software_keyboard.h
@@ -28,7 +28,7 @@ public:
28 void Initialize() override; 28 void Initialize() override;
29 29
30 bool TransactionComplete() const override; 30 bool TransactionComplete() const override;
31 ResultCode GetStatus() const override; 31 Result GetStatus() const override;
32 void ExecuteInteractive() override; 32 void ExecuteInteractive() override;
33 void Execute() override; 33 void Execute() override;
34 34
@@ -180,7 +180,7 @@ private:
180 bool is_background{false}; 180 bool is_background{false};
181 181
182 bool complete{false}; 182 bool complete{false};
183 ResultCode status{ResultSuccess}; 183 Result status{ResultSuccess};
184}; 184};
185 185
186} // namespace Service::AM::Applets 186} // namespace Service::AM::Applets
diff --git a/src/core/hle/service/am/applets/applet_web_browser.cpp b/src/core/hle/service/am/applets/applet_web_browser.cpp
index 7b3f77a51..4b804b78c 100644
--- a/src/core/hle/service/am/applets/applet_web_browser.cpp
+++ b/src/core/hle/service/am/applets/applet_web_browser.cpp
@@ -288,7 +288,7 @@ bool WebBrowser::TransactionComplete() const {
288 return complete; 288 return complete;
289} 289}
290 290
291ResultCode WebBrowser::GetStatus() const { 291Result WebBrowser::GetStatus() const {
292 return status; 292 return status;
293} 293}
294 294
diff --git a/src/core/hle/service/am/applets/applet_web_browser.h b/src/core/hle/service/am/applets/applet_web_browser.h
index 6b602769b..fd727fac8 100644
--- a/src/core/hle/service/am/applets/applet_web_browser.h
+++ b/src/core/hle/service/am/applets/applet_web_browser.h
@@ -32,7 +32,7 @@ public:
32 void Initialize() override; 32 void Initialize() override;
33 33
34 bool TransactionComplete() const override; 34 bool TransactionComplete() const override;
35 ResultCode GetStatus() const override; 35 Result GetStatus() const override;
36 void ExecuteInteractive() override; 36 void ExecuteInteractive() override;
37 void Execute() override; 37 void Execute() override;
38 38
@@ -66,7 +66,7 @@ private:
66 const Core::Frontend::WebBrowserApplet& frontend; 66 const Core::Frontend::WebBrowserApplet& frontend;
67 67
68 bool complete{false}; 68 bool complete{false};
69 ResultCode status{ResultSuccess}; 69 Result status{ResultSuccess};
70 70
71 WebAppletVersion web_applet_version{}; 71 WebAppletVersion web_applet_version{};
72 WebArgHeader web_arg_header{}; 72 WebArgHeader web_arg_header{};
diff --git a/src/core/hle/service/am/applets/applets.h b/src/core/hle/service/am/applets/applets.h
index 2861fed0e..e78a57657 100644
--- a/src/core/hle/service/am/applets/applets.h
+++ b/src/core/hle/service/am/applets/applets.h
@@ -9,7 +9,7 @@
9#include "common/swap.h" 9#include "common/swap.h"
10#include "core/hle/service/kernel_helpers.h" 10#include "core/hle/service/kernel_helpers.h"
11 11
12union ResultCode; 12union Result;
13 13
14namespace Core { 14namespace Core {
15class System; 15class System;
@@ -138,7 +138,7 @@ public:
138 virtual void Initialize(); 138 virtual void Initialize();
139 139
140 virtual bool TransactionComplete() const = 0; 140 virtual bool TransactionComplete() const = 0;
141 virtual ResultCode GetStatus() const = 0; 141 virtual Result GetStatus() const = 0;
142 virtual void ExecuteInteractive() = 0; 142 virtual void ExecuteInteractive() = 0;
143 virtual void Execute() = 0; 143 virtual void Execute() = 0;
144 144
diff --git a/src/core/hle/service/audio/errors.h b/src/core/hle/service/audio/errors.h
index 542fec899..ac6c514af 100644
--- a/src/core/hle/service/audio/errors.h
+++ b/src/core/hle/service/audio/errors.h
@@ -7,8 +7,8 @@
7 7
8namespace Service::Audio { 8namespace Service::Audio {
9 9
10constexpr ResultCode ERR_OPERATION_FAILED{ErrorModule::Audio, 2}; 10constexpr Result ERR_OPERATION_FAILED{ErrorModule::Audio, 2};
11constexpr ResultCode ERR_BUFFER_COUNT_EXCEEDED{ErrorModule::Audio, 8}; 11constexpr Result ERR_BUFFER_COUNT_EXCEEDED{ErrorModule::Audio, 8};
12constexpr ResultCode ERR_NOT_SUPPORTED{ErrorModule::Audio, 513}; 12constexpr Result ERR_NOT_SUPPORTED{ErrorModule::Audio, 513};
13 13
14} // namespace Service::Audio 14} // namespace Service::Audio
diff --git a/src/core/hle/service/bcat/backend/backend.cpp b/src/core/hle/service/bcat/backend/backend.cpp
index 7e6d16230..cd0b405ff 100644
--- a/src/core/hle/service/bcat/backend/backend.cpp
+++ b/src/core/hle/service/bcat/backend/backend.cpp
@@ -74,7 +74,7 @@ void ProgressServiceBackend::CommitDirectory(std::string_view dir_name) {
74 SignalUpdate(); 74 SignalUpdate();
75} 75}
76 76
77void ProgressServiceBackend::FinishDownload(ResultCode result) { 77void ProgressServiceBackend::FinishDownload(Result result) {
78 impl.total_downloaded_bytes = impl.total_bytes; 78 impl.total_downloaded_bytes = impl.total_bytes;
79 impl.status = DeliveryCacheProgressImpl::Status::Done; 79 impl.status = DeliveryCacheProgressImpl::Status::Done;
80 impl.result = result; 80 impl.result = result;
diff --git a/src/core/hle/service/bcat/backend/backend.h b/src/core/hle/service/bcat/backend/backend.h
index 7e8026c75..205ed0702 100644
--- a/src/core/hle/service/bcat/backend/backend.h
+++ b/src/core/hle/service/bcat/backend/backend.h
@@ -49,7 +49,7 @@ struct DeliveryCacheProgressImpl {
49 }; 49 };
50 50
51 Status status; 51 Status status;
52 ResultCode result = ResultSuccess; 52 Result result = ResultSuccess;
53 DirectoryName current_directory; 53 DirectoryName current_directory;
54 FileName current_file; 54 FileName current_file;
55 s64 current_downloaded_bytes; ///< Bytes downloaded on current file. 55 s64 current_downloaded_bytes; ///< Bytes downloaded on current file.
@@ -90,7 +90,7 @@ public:
90 void CommitDirectory(std::string_view dir_name); 90 void CommitDirectory(std::string_view dir_name);
91 91
92 // Notifies the application that the operation completed with result code result. 92 // Notifies the application that the operation completed with result code result.
93 void FinishDownload(ResultCode result); 93 void FinishDownload(Result result);
94 94
95private: 95private:
96 explicit ProgressServiceBackend(Core::System& system, std::string_view event_name); 96 explicit ProgressServiceBackend(Core::System& system, std::string_view event_name);
diff --git a/src/core/hle/service/bcat/bcat_module.cpp b/src/core/hle/service/bcat/bcat_module.cpp
index 076fd79e7..d928e37fb 100644
--- a/src/core/hle/service/bcat/bcat_module.cpp
+++ b/src/core/hle/service/bcat/bcat_module.cpp
@@ -18,15 +18,15 @@
18 18
19namespace Service::BCAT { 19namespace Service::BCAT {
20 20
21constexpr ResultCode ERROR_INVALID_ARGUMENT{ErrorModule::BCAT, 1}; 21constexpr Result ERROR_INVALID_ARGUMENT{ErrorModule::BCAT, 1};
22constexpr ResultCode ERROR_FAILED_OPEN_ENTITY{ErrorModule::BCAT, 2}; 22constexpr Result ERROR_FAILED_OPEN_ENTITY{ErrorModule::BCAT, 2};
23constexpr ResultCode ERROR_ENTITY_ALREADY_OPEN{ErrorModule::BCAT, 6}; 23constexpr Result ERROR_ENTITY_ALREADY_OPEN{ErrorModule::BCAT, 6};
24constexpr ResultCode ERROR_NO_OPEN_ENTITY{ErrorModule::BCAT, 7}; 24constexpr Result ERROR_NO_OPEN_ENTITY{ErrorModule::BCAT, 7};
25 25
26// The command to clear the delivery cache just calls fs IFileSystem DeleteFile on all of the files 26// The command to clear the delivery cache just calls fs IFileSystem DeleteFile on all of the files
27// and if any of them have a non-zero result it just forwards that result. This is the FS error code 27// and if any of them have a non-zero result it just forwards that result. This is the FS error code
28// for permission denied, which is the closest approximation of this scenario. 28// for permission denied, which is the closest approximation of this scenario.
29constexpr ResultCode ERROR_FAILED_CLEAR_CACHE{ErrorModule::FS, 6400}; 29constexpr Result ERROR_FAILED_CLEAR_CACHE{ErrorModule::FS, 6400};
30 30
31using BCATDigest = std::array<u8, 0x10>; 31using BCATDigest = std::array<u8, 0x10>;
32 32
diff --git a/src/core/hle/service/es/es.cpp b/src/core/hle/service/es/es.cpp
index cbe9d5f7c..ff9b0427c 100644
--- a/src/core/hle/service/es/es.cpp
+++ b/src/core/hle/service/es/es.cpp
@@ -8,8 +8,8 @@
8 8
9namespace Service::ES { 9namespace Service::ES {
10 10
11constexpr ResultCode ERROR_INVALID_ARGUMENT{ErrorModule::ETicket, 2}; 11constexpr Result ERROR_INVALID_ARGUMENT{ErrorModule::ETicket, 2};
12constexpr ResultCode ERROR_INVALID_RIGHTS_ID{ErrorModule::ETicket, 3}; 12constexpr Result ERROR_INVALID_RIGHTS_ID{ErrorModule::ETicket, 3};
13 13
14class ETicket final : public ServiceFramework<ETicket> { 14class ETicket final : public ServiceFramework<ETicket> {
15public: 15public:
diff --git a/src/core/hle/service/fatal/fatal.cpp b/src/core/hle/service/fatal/fatal.cpp
index a99c90479..27675615b 100644
--- a/src/core/hle/service/fatal/fatal.cpp
+++ b/src/core/hle/service/fatal/fatal.cpp
@@ -62,8 +62,7 @@ enum class FatalType : u32 {
62 ErrorScreen = 2, 62 ErrorScreen = 2,
63}; 63};
64 64
65static void GenerateErrorReport(Core::System& system, ResultCode error_code, 65static void GenerateErrorReport(Core::System& system, Result error_code, const FatalInfo& info) {
66 const FatalInfo& info) {
67 const auto title_id = system.GetCurrentProcessProgramID(); 66 const auto title_id = system.GetCurrentProcessProgramID();
68 std::string crash_report = fmt::format( 67 std::string crash_report = fmt::format(
69 "Yuzu {}-{} crash report\n" 68 "Yuzu {}-{} crash report\n"
@@ -106,7 +105,7 @@ static void GenerateErrorReport(Core::System& system, ResultCode error_code,
106 info.backtrace_size, info.ArchAsString(), info.unk10); 105 info.backtrace_size, info.ArchAsString(), info.unk10);
107} 106}
108 107
109static void ThrowFatalError(Core::System& system, ResultCode error_code, FatalType fatal_type, 108static void ThrowFatalError(Core::System& system, Result error_code, FatalType fatal_type,
110 const FatalInfo& info) { 109 const FatalInfo& info) {
111 LOG_ERROR(Service_Fatal, "Threw fatal error type {} with error code 0x{:X}", fatal_type, 110 LOG_ERROR(Service_Fatal, "Threw fatal error type {} with error code 0x{:X}", fatal_type,
112 error_code.raw); 111 error_code.raw);
@@ -129,7 +128,7 @@ static void ThrowFatalError(Core::System& system, ResultCode error_code, FatalTy
129void Module::Interface::ThrowFatal(Kernel::HLERequestContext& ctx) { 128void Module::Interface::ThrowFatal(Kernel::HLERequestContext& ctx) {
130 LOG_ERROR(Service_Fatal, "called"); 129 LOG_ERROR(Service_Fatal, "called");
131 IPC::RequestParser rp{ctx}; 130 IPC::RequestParser rp{ctx};
132 const auto error_code = rp.Pop<ResultCode>(); 131 const auto error_code = rp.Pop<Result>();
133 132
134 ThrowFatalError(system, error_code, FatalType::ErrorScreen, {}); 133 ThrowFatalError(system, error_code, FatalType::ErrorScreen, {});
135 IPC::ResponseBuilder rb{ctx, 2}; 134 IPC::ResponseBuilder rb{ctx, 2};
@@ -139,7 +138,7 @@ void Module::Interface::ThrowFatal(Kernel::HLERequestContext& ctx) {
139void Module::Interface::ThrowFatalWithPolicy(Kernel::HLERequestContext& ctx) { 138void Module::Interface::ThrowFatalWithPolicy(Kernel::HLERequestContext& ctx) {
140 LOG_ERROR(Service_Fatal, "called"); 139 LOG_ERROR(Service_Fatal, "called");
141 IPC::RequestParser rp(ctx); 140 IPC::RequestParser rp(ctx);
142 const auto error_code = rp.Pop<ResultCode>(); 141 const auto error_code = rp.Pop<Result>();
143 const auto fatal_type = rp.PopEnum<FatalType>(); 142 const auto fatal_type = rp.PopEnum<FatalType>();
144 143
145 ThrowFatalError(system, error_code, fatal_type, 144 ThrowFatalError(system, error_code, fatal_type,
@@ -151,7 +150,7 @@ void Module::Interface::ThrowFatalWithPolicy(Kernel::HLERequestContext& ctx) {
151void Module::Interface::ThrowFatalWithCpuContext(Kernel::HLERequestContext& ctx) { 150void Module::Interface::ThrowFatalWithCpuContext(Kernel::HLERequestContext& ctx) {
152 LOG_ERROR(Service_Fatal, "called"); 151 LOG_ERROR(Service_Fatal, "called");
153 IPC::RequestParser rp(ctx); 152 IPC::RequestParser rp(ctx);
154 const auto error_code = rp.Pop<ResultCode>(); 153 const auto error_code = rp.Pop<Result>();
155 const auto fatal_type = rp.PopEnum<FatalType>(); 154 const auto fatal_type = rp.PopEnum<FatalType>();
156 const auto fatal_info = ctx.ReadBuffer(); 155 const auto fatal_info = ctx.ReadBuffer();
157 FatalInfo info{}; 156 FatalInfo info{};
diff --git a/src/core/hle/service/filesystem/filesystem.cpp b/src/core/hle/service/filesystem/filesystem.cpp
index f8e7519ca..11c604a0f 100644
--- a/src/core/hle/service/filesystem/filesystem.cpp
+++ b/src/core/hle/service/filesystem/filesystem.cpp
@@ -49,7 +49,7 @@ std::string VfsDirectoryServiceWrapper::GetName() const {
49 return backing->GetName(); 49 return backing->GetName();
50} 50}
51 51
52ResultCode VfsDirectoryServiceWrapper::CreateFile(const std::string& path_, u64 size) const { 52Result VfsDirectoryServiceWrapper::CreateFile(const std::string& path_, u64 size) const {
53 std::string path(Common::FS::SanitizePath(path_)); 53 std::string path(Common::FS::SanitizePath(path_));
54 auto dir = GetDirectoryRelativeWrapped(backing, Common::FS::GetParentPath(path)); 54 auto dir = GetDirectoryRelativeWrapped(backing, Common::FS::GetParentPath(path));
55 if (dir == nullptr) { 55 if (dir == nullptr) {
@@ -73,7 +73,7 @@ ResultCode VfsDirectoryServiceWrapper::CreateFile(const std::string& path_, u64
73 return ResultSuccess; 73 return ResultSuccess;
74} 74}
75 75
76ResultCode VfsDirectoryServiceWrapper::DeleteFile(const std::string& path_) const { 76Result VfsDirectoryServiceWrapper::DeleteFile(const std::string& path_) const {
77 std::string path(Common::FS::SanitizePath(path_)); 77 std::string path(Common::FS::SanitizePath(path_));
78 if (path.empty()) { 78 if (path.empty()) {
79 // TODO(DarkLordZach): Why do games call this and what should it do? Works as is but... 79 // TODO(DarkLordZach): Why do games call this and what should it do? Works as is but...
@@ -92,7 +92,7 @@ ResultCode VfsDirectoryServiceWrapper::DeleteFile(const std::string& path_) cons
92 return ResultSuccess; 92 return ResultSuccess;
93} 93}
94 94
95ResultCode VfsDirectoryServiceWrapper::CreateDirectory(const std::string& path_) const { 95Result VfsDirectoryServiceWrapper::CreateDirectory(const std::string& path_) const {
96 std::string path(Common::FS::SanitizePath(path_)); 96 std::string path(Common::FS::SanitizePath(path_));
97 97
98 // NOTE: This is inaccurate behavior. CreateDirectory is not recursive. 98 // NOTE: This is inaccurate behavior. CreateDirectory is not recursive.
@@ -116,7 +116,7 @@ ResultCode VfsDirectoryServiceWrapper::CreateDirectory(const std::string& path_)
116 return ResultSuccess; 116 return ResultSuccess;
117} 117}
118 118
119ResultCode VfsDirectoryServiceWrapper::DeleteDirectory(const std::string& path_) const { 119Result VfsDirectoryServiceWrapper::DeleteDirectory(const std::string& path_) const {
120 std::string path(Common::FS::SanitizePath(path_)); 120 std::string path(Common::FS::SanitizePath(path_));
121 auto dir = GetDirectoryRelativeWrapped(backing, Common::FS::GetParentPath(path)); 121 auto dir = GetDirectoryRelativeWrapped(backing, Common::FS::GetParentPath(path));
122 if (!dir->DeleteSubdirectory(Common::FS::GetFilename(path))) { 122 if (!dir->DeleteSubdirectory(Common::FS::GetFilename(path))) {
@@ -126,7 +126,7 @@ ResultCode VfsDirectoryServiceWrapper::DeleteDirectory(const std::string& path_)
126 return ResultSuccess; 126 return ResultSuccess;
127} 127}
128 128
129ResultCode VfsDirectoryServiceWrapper::DeleteDirectoryRecursively(const std::string& path_) const { 129Result VfsDirectoryServiceWrapper::DeleteDirectoryRecursively(const std::string& path_) const {
130 std::string path(Common::FS::SanitizePath(path_)); 130 std::string path(Common::FS::SanitizePath(path_));
131 auto dir = GetDirectoryRelativeWrapped(backing, Common::FS::GetParentPath(path)); 131 auto dir = GetDirectoryRelativeWrapped(backing, Common::FS::GetParentPath(path));
132 if (!dir->DeleteSubdirectoryRecursive(Common::FS::GetFilename(path))) { 132 if (!dir->DeleteSubdirectoryRecursive(Common::FS::GetFilename(path))) {
@@ -136,7 +136,7 @@ ResultCode VfsDirectoryServiceWrapper::DeleteDirectoryRecursively(const std::str
136 return ResultSuccess; 136 return ResultSuccess;
137} 137}
138 138
139ResultCode VfsDirectoryServiceWrapper::CleanDirectoryRecursively(const std::string& path) const { 139Result VfsDirectoryServiceWrapper::CleanDirectoryRecursively(const std::string& path) const {
140 const std::string sanitized_path(Common::FS::SanitizePath(path)); 140 const std::string sanitized_path(Common::FS::SanitizePath(path));
141 auto dir = GetDirectoryRelativeWrapped(backing, Common::FS::GetParentPath(sanitized_path)); 141 auto dir = GetDirectoryRelativeWrapped(backing, Common::FS::GetParentPath(sanitized_path));
142 142
@@ -148,8 +148,8 @@ ResultCode VfsDirectoryServiceWrapper::CleanDirectoryRecursively(const std::stri
148 return ResultSuccess; 148 return ResultSuccess;
149} 149}
150 150
151ResultCode VfsDirectoryServiceWrapper::RenameFile(const std::string& src_path_, 151Result VfsDirectoryServiceWrapper::RenameFile(const std::string& src_path_,
152 const std::string& dest_path_) const { 152 const std::string& dest_path_) const {
153 std::string src_path(Common::FS::SanitizePath(src_path_)); 153 std::string src_path(Common::FS::SanitizePath(src_path_));
154 std::string dest_path(Common::FS::SanitizePath(dest_path_)); 154 std::string dest_path(Common::FS::SanitizePath(dest_path_));
155 auto src = backing->GetFileRelative(src_path); 155 auto src = backing->GetFileRelative(src_path);
@@ -183,8 +183,8 @@ ResultCode VfsDirectoryServiceWrapper::RenameFile(const std::string& src_path_,
183 return ResultSuccess; 183 return ResultSuccess;
184} 184}
185 185
186ResultCode VfsDirectoryServiceWrapper::RenameDirectory(const std::string& src_path_, 186Result VfsDirectoryServiceWrapper::RenameDirectory(const std::string& src_path_,
187 const std::string& dest_path_) const { 187 const std::string& dest_path_) const {
188 std::string src_path(Common::FS::SanitizePath(src_path_)); 188 std::string src_path(Common::FS::SanitizePath(src_path_));
189 std::string dest_path(Common::FS::SanitizePath(dest_path_)); 189 std::string dest_path(Common::FS::SanitizePath(dest_path_));
190 auto src = GetDirectoryRelativeWrapped(backing, src_path); 190 auto src = GetDirectoryRelativeWrapped(backing, src_path);
@@ -273,28 +273,27 @@ FileSystemController::FileSystemController(Core::System& system_) : system{syste
273 273
274FileSystemController::~FileSystemController() = default; 274FileSystemController::~FileSystemController() = default;
275 275
276ResultCode FileSystemController::RegisterRomFS(std::unique_ptr<FileSys::RomFSFactory>&& factory) { 276Result FileSystemController::RegisterRomFS(std::unique_ptr<FileSys::RomFSFactory>&& factory) {
277 romfs_factory = std::move(factory); 277 romfs_factory = std::move(factory);
278 LOG_DEBUG(Service_FS, "Registered RomFS"); 278 LOG_DEBUG(Service_FS, "Registered RomFS");
279 return ResultSuccess; 279 return ResultSuccess;
280} 280}
281 281
282ResultCode FileSystemController::RegisterSaveData( 282Result FileSystemController::RegisterSaveData(std::unique_ptr<FileSys::SaveDataFactory>&& factory) {
283 std::unique_ptr<FileSys::SaveDataFactory>&& factory) {
284 ASSERT_MSG(save_data_factory == nullptr, "Tried to register a second save data"); 283 ASSERT_MSG(save_data_factory == nullptr, "Tried to register a second save data");
285 save_data_factory = std::move(factory); 284 save_data_factory = std::move(factory);
286 LOG_DEBUG(Service_FS, "Registered save data"); 285 LOG_DEBUG(Service_FS, "Registered save data");
287 return ResultSuccess; 286 return ResultSuccess;
288} 287}
289 288
290ResultCode FileSystemController::RegisterSDMC(std::unique_ptr<FileSys::SDMCFactory>&& factory) { 289Result FileSystemController::RegisterSDMC(std::unique_ptr<FileSys::SDMCFactory>&& factory) {
291 ASSERT_MSG(sdmc_factory == nullptr, "Tried to register a second SDMC"); 290 ASSERT_MSG(sdmc_factory == nullptr, "Tried to register a second SDMC");
292 sdmc_factory = std::move(factory); 291 sdmc_factory = std::move(factory);
293 LOG_DEBUG(Service_FS, "Registered SDMC"); 292 LOG_DEBUG(Service_FS, "Registered SDMC");
294 return ResultSuccess; 293 return ResultSuccess;
295} 294}
296 295
297ResultCode FileSystemController::RegisterBIS(std::unique_ptr<FileSys::BISFactory>&& factory) { 296Result FileSystemController::RegisterBIS(std::unique_ptr<FileSys::BISFactory>&& factory) {
298 ASSERT_MSG(bis_factory == nullptr, "Tried to register a second BIS"); 297 ASSERT_MSG(bis_factory == nullptr, "Tried to register a second BIS");
299 bis_factory = std::move(factory); 298 bis_factory = std::move(factory);
300 LOG_DEBUG(Service_FS, "Registered BIS"); 299 LOG_DEBUG(Service_FS, "Registered BIS");
diff --git a/src/core/hle/service/filesystem/filesystem.h b/src/core/hle/service/filesystem/filesystem.h
index 8dd2652fe..5b27de9fa 100644
--- a/src/core/hle/service/filesystem/filesystem.h
+++ b/src/core/hle/service/filesystem/filesystem.h
@@ -58,10 +58,10 @@ public:
58 explicit FileSystemController(Core::System& system_); 58 explicit FileSystemController(Core::System& system_);
59 ~FileSystemController(); 59 ~FileSystemController();
60 60
61 ResultCode RegisterRomFS(std::unique_ptr<FileSys::RomFSFactory>&& factory); 61 Result RegisterRomFS(std::unique_ptr<FileSys::RomFSFactory>&& factory);
62 ResultCode RegisterSaveData(std::unique_ptr<FileSys::SaveDataFactory>&& factory); 62 Result RegisterSaveData(std::unique_ptr<FileSys::SaveDataFactory>&& factory);
63 ResultCode RegisterSDMC(std::unique_ptr<FileSys::SDMCFactory>&& factory); 63 Result RegisterSDMC(std::unique_ptr<FileSys::SDMCFactory>&& factory);
64 ResultCode RegisterBIS(std::unique_ptr<FileSys::BISFactory>&& factory); 64 Result RegisterBIS(std::unique_ptr<FileSys::BISFactory>&& factory);
65 65
66 void SetPackedUpdate(FileSys::VirtualFile update_raw); 66 void SetPackedUpdate(FileSys::VirtualFile update_raw);
67 ResultVal<FileSys::VirtualFile> OpenRomFSCurrentProcess() const; 67 ResultVal<FileSys::VirtualFile> OpenRomFSCurrentProcess() const;
@@ -141,7 +141,7 @@ private:
141 141
142void InstallInterfaces(Core::System& system); 142void InstallInterfaces(Core::System& system);
143 143
144// A class that wraps a VfsDirectory with methods that return ResultVal and ResultCode instead of 144// A class that wraps a VfsDirectory with methods that return ResultVal and Result instead of
145// pointers and booleans. This makes using a VfsDirectory with switch services much easier and 145// pointers and booleans. This makes using a VfsDirectory with switch services much easier and
146// avoids repetitive code. 146// avoids repetitive code.
147class VfsDirectoryServiceWrapper { 147class VfsDirectoryServiceWrapper {
@@ -160,35 +160,35 @@ public:
160 * @param size The size of the new file, filled with zeroes 160 * @param size The size of the new file, filled with zeroes
161 * @return Result of the operation 161 * @return Result of the operation
162 */ 162 */
163 ResultCode CreateFile(const std::string& path, u64 size) const; 163 Result CreateFile(const std::string& path, u64 size) const;
164 164
165 /** 165 /**
166 * Delete a file specified by its path 166 * Delete a file specified by its path
167 * @param path Path relative to the archive 167 * @param path Path relative to the archive
168 * @return Result of the operation 168 * @return Result of the operation
169 */ 169 */
170 ResultCode DeleteFile(const std::string& path) const; 170 Result DeleteFile(const std::string& path) const;
171 171
172 /** 172 /**
173 * Create a directory specified by its path 173 * Create a directory specified by its path
174 * @param path Path relative to the archive 174 * @param path Path relative to the archive
175 * @return Result of the operation 175 * @return Result of the operation
176 */ 176 */
177 ResultCode CreateDirectory(const std::string& path) const; 177 Result CreateDirectory(const std::string& path) const;
178 178
179 /** 179 /**
180 * Delete a directory specified by its path 180 * Delete a directory specified by its path
181 * @param path Path relative to the archive 181 * @param path Path relative to the archive
182 * @return Result of the operation 182 * @return Result of the operation
183 */ 183 */
184 ResultCode DeleteDirectory(const std::string& path) const; 184 Result DeleteDirectory(const std::string& path) const;
185 185
186 /** 186 /**
187 * Delete a directory specified by its path and anything under it 187 * Delete a directory specified by its path and anything under it
188 * @param path Path relative to the archive 188 * @param path Path relative to the archive
189 * @return Result of the operation 189 * @return Result of the operation
190 */ 190 */
191 ResultCode DeleteDirectoryRecursively(const std::string& path) const; 191 Result DeleteDirectoryRecursively(const std::string& path) const;
192 192
193 /** 193 /**
194 * Cleans the specified directory. This is similar to DeleteDirectoryRecursively, 194 * Cleans the specified directory. This is similar to DeleteDirectoryRecursively,
@@ -200,7 +200,7 @@ public:
200 * 200 *
201 * @return Result of the operation. 201 * @return Result of the operation.
202 */ 202 */
203 ResultCode CleanDirectoryRecursively(const std::string& path) const; 203 Result CleanDirectoryRecursively(const std::string& path) const;
204 204
205 /** 205 /**
206 * Rename a File specified by its path 206 * Rename a File specified by its path
@@ -208,7 +208,7 @@ public:
208 * @param dest_path Destination path relative to the archive 208 * @param dest_path Destination path relative to the archive
209 * @return Result of the operation 209 * @return Result of the operation
210 */ 210 */
211 ResultCode RenameFile(const std::string& src_path, const std::string& dest_path) const; 211 Result RenameFile(const std::string& src_path, const std::string& dest_path) const;
212 212
213 /** 213 /**
214 * Rename a Directory specified by its path 214 * Rename a Directory specified by its path
@@ -216,7 +216,7 @@ public:
216 * @param dest_path Destination path relative to the archive 216 * @param dest_path Destination path relative to the archive
217 * @return Result of the operation 217 * @return Result of the operation
218 */ 218 */
219 ResultCode RenameDirectory(const std::string& src_path, const std::string& dest_path) const; 219 Result RenameDirectory(const std::string& src_path, const std::string& dest_path) const;
220 220
221 /** 221 /**
222 * Open a file specified by its path, using the specified mode 222 * Open a file specified by its path, using the specified mode
diff --git a/src/core/hle/service/friend/errors.h b/src/core/hle/service/friend/errors.h
index bc9fe0aca..ff525d865 100644
--- a/src/core/hle/service/friend/errors.h
+++ b/src/core/hle/service/friend/errors.h
@@ -7,5 +7,5 @@
7 7
8namespace Service::Friend { 8namespace Service::Friend {
9 9
10constexpr ResultCode ERR_NO_NOTIFICATIONS{ErrorModule::Account, 15}; 10constexpr Result ERR_NO_NOTIFICATIONS{ErrorModule::Account, 15};
11} 11}
diff --git a/src/core/hle/service/glue/arp.cpp b/src/core/hle/service/glue/arp.cpp
index fec7787ab..49b6d45fe 100644
--- a/src/core/hle/service/glue/arp.cpp
+++ b/src/core/hle/service/glue/arp.cpp
@@ -153,7 +153,7 @@ class IRegistrar final : public ServiceFramework<IRegistrar> {
153 friend class ARP_W; 153 friend class ARP_W;
154 154
155public: 155public:
156 using IssuerFn = std::function<ResultCode(u64, ApplicationLaunchProperty, std::vector<u8>)>; 156 using IssuerFn = std::function<Result(u64, ApplicationLaunchProperty, std::vector<u8>)>;
157 157
158 explicit IRegistrar(Core::System& system_, IssuerFn&& issuer) 158 explicit IRegistrar(Core::System& system_, IssuerFn&& issuer)
159 : ServiceFramework{system_, "IRegistrar"}, issue_process_id{std::move(issuer)} { 159 : ServiceFramework{system_, "IRegistrar"}, issue_process_id{std::move(issuer)} {
diff --git a/src/core/hle/service/glue/errors.h b/src/core/hle/service/glue/errors.h
index aefbe1f3e..d4ce7f44e 100644
--- a/src/core/hle/service/glue/errors.h
+++ b/src/core/hle/service/glue/errors.h
@@ -7,9 +7,9 @@
7 7
8namespace Service::Glue { 8namespace Service::Glue {
9 9
10constexpr ResultCode ERR_INVALID_RESOURCE{ErrorModule::ARP, 30}; 10constexpr Result ERR_INVALID_RESOURCE{ErrorModule::ARP, 30};
11constexpr ResultCode ERR_INVALID_PROCESS_ID{ErrorModule::ARP, 31}; 11constexpr Result ERR_INVALID_PROCESS_ID{ErrorModule::ARP, 31};
12constexpr ResultCode ERR_INVALID_ACCESS{ErrorModule::ARP, 42}; 12constexpr Result ERR_INVALID_ACCESS{ErrorModule::ARP, 42};
13constexpr ResultCode ERR_NOT_REGISTERED{ErrorModule::ARP, 102}; 13constexpr Result ERR_NOT_REGISTERED{ErrorModule::ARP, 102};
14 14
15} // namespace Service::Glue 15} // namespace Service::Glue
diff --git a/src/core/hle/service/glue/glue_manager.cpp b/src/core/hle/service/glue/glue_manager.cpp
index f1655b33e..8a654cdca 100644
--- a/src/core/hle/service/glue/glue_manager.cpp
+++ b/src/core/hle/service/glue/glue_manager.cpp
@@ -41,8 +41,8 @@ ResultVal<std::vector<u8>> ARPManager::GetControlProperty(u64 title_id) const {
41 return iter->second.control; 41 return iter->second.control;
42} 42}
43 43
44ResultCode ARPManager::Register(u64 title_id, ApplicationLaunchProperty launch, 44Result ARPManager::Register(u64 title_id, ApplicationLaunchProperty launch,
45 std::vector<u8> control) { 45 std::vector<u8> control) {
46 if (title_id == 0) { 46 if (title_id == 0) {
47 return ERR_INVALID_PROCESS_ID; 47 return ERR_INVALID_PROCESS_ID;
48 } 48 }
@@ -56,7 +56,7 @@ ResultCode ARPManager::Register(u64 title_id, ApplicationLaunchProperty launch,
56 return ResultSuccess; 56 return ResultSuccess;
57} 57}
58 58
59ResultCode ARPManager::Unregister(u64 title_id) { 59Result ARPManager::Unregister(u64 title_id) {
60 if (title_id == 0) { 60 if (title_id == 0) {
61 return ERR_INVALID_PROCESS_ID; 61 return ERR_INVALID_PROCESS_ID;
62 } 62 }
diff --git a/src/core/hle/service/glue/glue_manager.h b/src/core/hle/service/glue/glue_manager.h
index 6246fd2ff..cd0b092ac 100644
--- a/src/core/hle/service/glue/glue_manager.h
+++ b/src/core/hle/service/glue/glue_manager.h
@@ -42,12 +42,12 @@ public:
42 // Adds a new entry to the internal database with the provided parameters, returning 42 // Adds a new entry to the internal database with the provided parameters, returning
43 // ERR_INVALID_ACCESS if attempting to re-register a title ID without an intermediate Unregister 43 // ERR_INVALID_ACCESS if attempting to re-register a title ID without an intermediate Unregister
44 // step, and ERR_INVALID_PROCESS_ID if the title ID is 0. 44 // step, and ERR_INVALID_PROCESS_ID if the title ID is 0.
45 ResultCode Register(u64 title_id, ApplicationLaunchProperty launch, std::vector<u8> control); 45 Result Register(u64 title_id, ApplicationLaunchProperty launch, std::vector<u8> control);
46 46
47 // Removes the registration for the provided title ID from the database, returning 47 // Removes the registration for the provided title ID from the database, returning
48 // ERR_NOT_REGISTERED if it doesn't exist in the database and ERR_INVALID_PROCESS_ID if the 48 // ERR_NOT_REGISTERED if it doesn't exist in the database and ERR_INVALID_PROCESS_ID if the
49 // title ID is 0. 49 // title ID is 0.
50 ResultCode Unregister(u64 title_id); 50 Result Unregister(u64 title_id);
51 51
52 // Removes all entries from the database, always succeeds. Should only be used when resetting 52 // Removes all entries from the database, always succeeds. Should only be used when resetting
53 // system state. 53 // system state.
diff --git a/src/core/hle/service/hid/controllers/npad.cpp b/src/core/hle/service/hid/controllers/npad.cpp
index ac5c38cc6..aa7189bda 100644
--- a/src/core/hle/service/hid/controllers/npad.cpp
+++ b/src/core/hle/service/hid/controllers/npad.cpp
@@ -49,28 +49,41 @@ bool Controller_NPad::IsNpadIdValid(Core::HID::NpadIdType npad_id) {
49 } 49 }
50} 50}
51 51
52bool Controller_NPad::IsDeviceHandleValid(const Core::HID::VibrationDeviceHandle& device_handle) { 52Result Controller_NPad::IsDeviceHandleValid(const Core::HID::VibrationDeviceHandle& device_handle) {
53 const auto npad_id = IsNpadIdValid(static_cast<Core::HID::NpadIdType>(device_handle.npad_id)); 53 const auto npad_id = IsNpadIdValid(static_cast<Core::HID::NpadIdType>(device_handle.npad_id));
54 const bool npad_type = device_handle.npad_type < Core::HID::NpadStyleIndex::MaxNpadType; 54 const bool npad_type = device_handle.npad_type < Core::HID::NpadStyleIndex::MaxNpadType;
55 const bool device_index = device_handle.device_index < Core::HID::DeviceIndex::MaxDeviceIndex; 55 const bool device_index = device_handle.device_index < Core::HID::DeviceIndex::MaxDeviceIndex;
56 return npad_id && npad_type && device_index; 56
57 if (!npad_type) {
58 return VibrationInvalidStyleIndex;
59 }
60 if (!npad_id) {
61 return VibrationInvalidNpadId;
62 }
63 if (!device_index) {
64 return VibrationDeviceIndexOutOfRange;
65 }
66
67 return ResultSuccess;
57} 68}
58 69
59ResultCode Controller_NPad::VerifyValidSixAxisSensorHandle( 70Result Controller_NPad::VerifyValidSixAxisSensorHandle(
60 const Core::HID::SixAxisSensorHandle& device_handle) { 71 const Core::HID::SixAxisSensorHandle& device_handle) {
61 const auto npad_id = IsNpadIdValid(static_cast<Core::HID::NpadIdType>(device_handle.npad_id)); 72 const auto npad_id = IsNpadIdValid(static_cast<Core::HID::NpadIdType>(device_handle.npad_id));
73 const bool device_index = device_handle.device_index < Core::HID::DeviceIndex::MaxDeviceIndex;
74 const bool npad_type = device_handle.npad_type < Core::HID::NpadStyleIndex::MaxNpadType;
75
62 if (!npad_id) { 76 if (!npad_id) {
63 return InvalidNpadId; 77 return InvalidNpadId;
64 } 78 }
65 const bool device_index = device_handle.device_index < Core::HID::DeviceIndex::MaxDeviceIndex;
66 if (!device_index) { 79 if (!device_index) {
67 return NpadDeviceIndexOutOfRange; 80 return NpadDeviceIndexOutOfRange;
68 } 81 }
69 // This doesn't get validated on nnsdk 82 // This doesn't get validated on nnsdk
70 const bool npad_type = device_handle.npad_type < Core::HID::NpadStyleIndex::MaxNpadType;
71 if (!npad_type) { 83 if (!npad_type) {
72 return NpadInvalidHandle; 84 return NpadInvalidHandle;
73 } 85 }
86
74 return ResultSuccess; 87 return ResultSuccess;
75} 88}
76 89
@@ -705,6 +718,11 @@ Controller_NPad::NpadJoyHoldType Controller_NPad::GetHoldType() const {
705} 718}
706 719
707void Controller_NPad::SetNpadHandheldActivationMode(NpadHandheldActivationMode activation_mode) { 720void Controller_NPad::SetNpadHandheldActivationMode(NpadHandheldActivationMode activation_mode) {
721 if (activation_mode >= NpadHandheldActivationMode::MaxActivationMode) {
722 ASSERT_MSG(false, "Activation mode should be always None, Single or Dual");
723 return;
724 }
725
708 handheld_activation_mode = activation_mode; 726 handheld_activation_mode = activation_mode;
709} 727}
710 728
@@ -720,9 +738,9 @@ Controller_NPad::NpadCommunicationMode Controller_NPad::GetNpadCommunicationMode
720 return communication_mode; 738 return communication_mode;
721} 739}
722 740
723ResultCode Controller_NPad::SetNpadMode(Core::HID::NpadIdType npad_id, 741Result Controller_NPad::SetNpadMode(Core::HID::NpadIdType npad_id,
724 NpadJoyDeviceType npad_device_type, 742 NpadJoyDeviceType npad_device_type,
725 NpadJoyAssignmentMode assignment_mode) { 743 NpadJoyAssignmentMode assignment_mode) {
726 if (!IsNpadIdValid(npad_id)) { 744 if (!IsNpadIdValid(npad_id)) {
727 LOG_ERROR(Service_HID, "Invalid NpadIdType npad_id:{}", npad_id); 745 LOG_ERROR(Service_HID, "Invalid NpadIdType npad_id:{}", npad_id);
728 return InvalidNpadId; 746 return InvalidNpadId;
@@ -840,7 +858,7 @@ bool Controller_NPad::VibrateControllerAtIndex(Core::HID::NpadIdType npad_id,
840void Controller_NPad::VibrateController( 858void Controller_NPad::VibrateController(
841 const Core::HID::VibrationDeviceHandle& vibration_device_handle, 859 const Core::HID::VibrationDeviceHandle& vibration_device_handle,
842 const Core::HID::VibrationValue& vibration_value) { 860 const Core::HID::VibrationValue& vibration_value) {
843 if (!IsDeviceHandleValid(vibration_device_handle)) { 861 if (IsDeviceHandleValid(vibration_device_handle).IsError()) {
844 return; 862 return;
845 } 863 }
846 864
@@ -903,7 +921,7 @@ void Controller_NPad::VibrateControllers(
903 921
904Core::HID::VibrationValue Controller_NPad::GetLastVibration( 922Core::HID::VibrationValue Controller_NPad::GetLastVibration(
905 const Core::HID::VibrationDeviceHandle& vibration_device_handle) const { 923 const Core::HID::VibrationDeviceHandle& vibration_device_handle) const {
906 if (!IsDeviceHandleValid(vibration_device_handle)) { 924 if (IsDeviceHandleValid(vibration_device_handle).IsError()) {
907 return {}; 925 return {};
908 } 926 }
909 927
@@ -914,7 +932,7 @@ Core::HID::VibrationValue Controller_NPad::GetLastVibration(
914 932
915void Controller_NPad::InitializeVibrationDevice( 933void Controller_NPad::InitializeVibrationDevice(
916 const Core::HID::VibrationDeviceHandle& vibration_device_handle) { 934 const Core::HID::VibrationDeviceHandle& vibration_device_handle) {
917 if (!IsDeviceHandleValid(vibration_device_handle)) { 935 if (IsDeviceHandleValid(vibration_device_handle).IsError()) {
918 return; 936 return;
919 } 937 }
920 938
@@ -941,7 +959,7 @@ void Controller_NPad::SetPermitVibrationSession(bool permit_vibration_session) {
941 959
942bool Controller_NPad::IsVibrationDeviceMounted( 960bool Controller_NPad::IsVibrationDeviceMounted(
943 const Core::HID::VibrationDeviceHandle& vibration_device_handle) const { 961 const Core::HID::VibrationDeviceHandle& vibration_device_handle) const {
944 if (!IsDeviceHandleValid(vibration_device_handle)) { 962 if (IsDeviceHandleValid(vibration_device_handle).IsError()) {
945 return false; 963 return false;
946 } 964 }
947 965
@@ -984,7 +1002,7 @@ void Controller_NPad::UpdateControllerAt(Core::HID::NpadStyleIndex type,
984 InitNewlyAddedController(npad_id); 1002 InitNewlyAddedController(npad_id);
985} 1003}
986 1004
987ResultCode Controller_NPad::DisconnectNpad(Core::HID::NpadIdType npad_id) { 1005Result Controller_NPad::DisconnectNpad(Core::HID::NpadIdType npad_id) {
988 if (!IsNpadIdValid(npad_id)) { 1006 if (!IsNpadIdValid(npad_id)) {
989 LOG_ERROR(Service_HID, "Invalid NpadIdType npad_id:{}", npad_id); 1007 LOG_ERROR(Service_HID, "Invalid NpadIdType npad_id:{}", npad_id);
990 return InvalidNpadId; 1008 return InvalidNpadId;
@@ -1032,7 +1050,7 @@ ResultCode Controller_NPad::DisconnectNpad(Core::HID::NpadIdType npad_id) {
1032 WriteEmptyEntry(shared_memory); 1050 WriteEmptyEntry(shared_memory);
1033 return ResultSuccess; 1051 return ResultSuccess;
1034} 1052}
1035ResultCode Controller_NPad::SetGyroscopeZeroDriftMode( 1053Result Controller_NPad::SetGyroscopeZeroDriftMode(
1036 const Core::HID::SixAxisSensorHandle& sixaxis_handle, GyroscopeZeroDriftMode drift_mode) { 1054 const Core::HID::SixAxisSensorHandle& sixaxis_handle, GyroscopeZeroDriftMode drift_mode) {
1037 const auto is_valid = VerifyValidSixAxisSensorHandle(sixaxis_handle); 1055 const auto is_valid = VerifyValidSixAxisSensorHandle(sixaxis_handle);
1038 if (is_valid.IsError()) { 1056 if (is_valid.IsError()) {
@@ -1046,7 +1064,7 @@ ResultCode Controller_NPad::SetGyroscopeZeroDriftMode(
1046 return ResultSuccess; 1064 return ResultSuccess;
1047} 1065}
1048 1066
1049ResultCode Controller_NPad::GetGyroscopeZeroDriftMode( 1067Result Controller_NPad::GetGyroscopeZeroDriftMode(
1050 const Core::HID::SixAxisSensorHandle& sixaxis_handle, 1068 const Core::HID::SixAxisSensorHandle& sixaxis_handle,
1051 GyroscopeZeroDriftMode& drift_mode) const { 1069 GyroscopeZeroDriftMode& drift_mode) const {
1052 const auto is_valid = VerifyValidSixAxisSensorHandle(sixaxis_handle); 1070 const auto is_valid = VerifyValidSixAxisSensorHandle(sixaxis_handle);
@@ -1061,8 +1079,8 @@ ResultCode Controller_NPad::GetGyroscopeZeroDriftMode(
1061 return ResultSuccess; 1079 return ResultSuccess;
1062} 1080}
1063 1081
1064ResultCode Controller_NPad::IsSixAxisSensorAtRest( 1082Result Controller_NPad::IsSixAxisSensorAtRest(const Core::HID::SixAxisSensorHandle& sixaxis_handle,
1065 const Core::HID::SixAxisSensorHandle& sixaxis_handle, bool& is_at_rest) const { 1083 bool& is_at_rest) const {
1066 const auto is_valid = VerifyValidSixAxisSensorHandle(sixaxis_handle); 1084 const auto is_valid = VerifyValidSixAxisSensorHandle(sixaxis_handle);
1067 if (is_valid.IsError()) { 1085 if (is_valid.IsError()) {
1068 LOG_ERROR(Service_HID, "Invalid handle, error_code={}", is_valid.raw); 1086 LOG_ERROR(Service_HID, "Invalid handle, error_code={}", is_valid.raw);
@@ -1074,7 +1092,7 @@ ResultCode Controller_NPad::IsSixAxisSensorAtRest(
1074 return ResultSuccess; 1092 return ResultSuccess;
1075} 1093}
1076 1094
1077ResultCode Controller_NPad::IsFirmwareUpdateAvailableForSixAxisSensor( 1095Result Controller_NPad::IsFirmwareUpdateAvailableForSixAxisSensor(
1078 const Core::HID::SixAxisSensorHandle& sixaxis_handle, bool& is_firmware_available) const { 1096 const Core::HID::SixAxisSensorHandle& sixaxis_handle, bool& is_firmware_available) const {
1079 const auto is_valid = VerifyValidSixAxisSensorHandle(sixaxis_handle); 1097 const auto is_valid = VerifyValidSixAxisSensorHandle(sixaxis_handle);
1080 if (is_valid.IsError()) { 1098 if (is_valid.IsError()) {
@@ -1087,7 +1105,7 @@ ResultCode Controller_NPad::IsFirmwareUpdateAvailableForSixAxisSensor(
1087 return ResultSuccess; 1105 return ResultSuccess;
1088} 1106}
1089 1107
1090ResultCode Controller_NPad::EnableSixAxisSensorUnalteredPassthrough( 1108Result Controller_NPad::EnableSixAxisSensorUnalteredPassthrough(
1091 const Core::HID::SixAxisSensorHandle& sixaxis_handle, bool is_enabled) { 1109 const Core::HID::SixAxisSensorHandle& sixaxis_handle, bool is_enabled) {
1092 const auto is_valid = VerifyValidSixAxisSensorHandle(sixaxis_handle); 1110 const auto is_valid = VerifyValidSixAxisSensorHandle(sixaxis_handle);
1093 if (is_valid.IsError()) { 1111 if (is_valid.IsError()) {
@@ -1100,7 +1118,7 @@ ResultCode Controller_NPad::EnableSixAxisSensorUnalteredPassthrough(
1100 return ResultSuccess; 1118 return ResultSuccess;
1101} 1119}
1102 1120
1103ResultCode Controller_NPad::IsSixAxisSensorUnalteredPassthroughEnabled( 1121Result Controller_NPad::IsSixAxisSensorUnalteredPassthroughEnabled(
1104 const Core::HID::SixAxisSensorHandle& sixaxis_handle, bool& is_enabled) const { 1122 const Core::HID::SixAxisSensorHandle& sixaxis_handle, bool& is_enabled) const {
1105 const auto is_valid = VerifyValidSixAxisSensorHandle(sixaxis_handle); 1123 const auto is_valid = VerifyValidSixAxisSensorHandle(sixaxis_handle);
1106 if (is_valid.IsError()) { 1124 if (is_valid.IsError()) {
@@ -1113,7 +1131,7 @@ ResultCode Controller_NPad::IsSixAxisSensorUnalteredPassthroughEnabled(
1113 return ResultSuccess; 1131 return ResultSuccess;
1114} 1132}
1115 1133
1116ResultCode Controller_NPad::LoadSixAxisSensorCalibrationParameter( 1134Result Controller_NPad::LoadSixAxisSensorCalibrationParameter(
1117 const Core::HID::SixAxisSensorHandle& sixaxis_handle, 1135 const Core::HID::SixAxisSensorHandle& sixaxis_handle,
1118 Core::HID::SixAxisSensorCalibrationParameter& calibration) const { 1136 Core::HID::SixAxisSensorCalibrationParameter& calibration) const {
1119 const auto is_valid = VerifyValidSixAxisSensorHandle(sixaxis_handle); 1137 const auto is_valid = VerifyValidSixAxisSensorHandle(sixaxis_handle);
@@ -1128,7 +1146,7 @@ ResultCode Controller_NPad::LoadSixAxisSensorCalibrationParameter(
1128 return ResultSuccess; 1146 return ResultSuccess;
1129} 1147}
1130 1148
1131ResultCode Controller_NPad::GetSixAxisSensorIcInformation( 1149Result Controller_NPad::GetSixAxisSensorIcInformation(
1132 const Core::HID::SixAxisSensorHandle& sixaxis_handle, 1150 const Core::HID::SixAxisSensorHandle& sixaxis_handle,
1133 Core::HID::SixAxisSensorIcInformation& ic_information) const { 1151 Core::HID::SixAxisSensorIcInformation& ic_information) const {
1134 const auto is_valid = VerifyValidSixAxisSensorHandle(sixaxis_handle); 1152 const auto is_valid = VerifyValidSixAxisSensorHandle(sixaxis_handle);
@@ -1143,7 +1161,7 @@ ResultCode Controller_NPad::GetSixAxisSensorIcInformation(
1143 return ResultSuccess; 1161 return ResultSuccess;
1144} 1162}
1145 1163
1146ResultCode Controller_NPad::ResetIsSixAxisSensorDeviceNewlyAssigned( 1164Result Controller_NPad::ResetIsSixAxisSensorDeviceNewlyAssigned(
1147 const Core::HID::SixAxisSensorHandle& sixaxis_handle) { 1165 const Core::HID::SixAxisSensorHandle& sixaxis_handle) {
1148 const auto is_valid = VerifyValidSixAxisSensorHandle(sixaxis_handle); 1166 const auto is_valid = VerifyValidSixAxisSensorHandle(sixaxis_handle);
1149 if (is_valid.IsError()) { 1167 if (is_valid.IsError()) {
@@ -1157,8 +1175,8 @@ ResultCode Controller_NPad::ResetIsSixAxisSensorDeviceNewlyAssigned(
1157 return ResultSuccess; 1175 return ResultSuccess;
1158} 1176}
1159 1177
1160ResultCode Controller_NPad::SetSixAxisEnabled(const Core::HID::SixAxisSensorHandle& sixaxis_handle, 1178Result Controller_NPad::SetSixAxisEnabled(const Core::HID::SixAxisSensorHandle& sixaxis_handle,
1161 bool sixaxis_status) { 1179 bool sixaxis_status) {
1162 const auto is_valid = VerifyValidSixAxisSensorHandle(sixaxis_handle); 1180 const auto is_valid = VerifyValidSixAxisSensorHandle(sixaxis_handle);
1163 if (is_valid.IsError()) { 1181 if (is_valid.IsError()) {
1164 LOG_ERROR(Service_HID, "Invalid handle, error_code={}", is_valid.raw); 1182 LOG_ERROR(Service_HID, "Invalid handle, error_code={}", is_valid.raw);
@@ -1170,7 +1188,7 @@ ResultCode Controller_NPad::SetSixAxisEnabled(const Core::HID::SixAxisSensorHand
1170 return ResultSuccess; 1188 return ResultSuccess;
1171} 1189}
1172 1190
1173ResultCode Controller_NPad::IsSixAxisSensorFusionEnabled( 1191Result Controller_NPad::IsSixAxisSensorFusionEnabled(
1174 const Core::HID::SixAxisSensorHandle& sixaxis_handle, bool& is_fusion_enabled) const { 1192 const Core::HID::SixAxisSensorHandle& sixaxis_handle, bool& is_fusion_enabled) const {
1175 const auto is_valid = VerifyValidSixAxisSensorHandle(sixaxis_handle); 1193 const auto is_valid = VerifyValidSixAxisSensorHandle(sixaxis_handle);
1176 if (is_valid.IsError()) { 1194 if (is_valid.IsError()) {
@@ -1183,7 +1201,7 @@ ResultCode Controller_NPad::IsSixAxisSensorFusionEnabled(
1183 1201
1184 return ResultSuccess; 1202 return ResultSuccess;
1185} 1203}
1186ResultCode Controller_NPad::SetSixAxisFusionEnabled( 1204Result Controller_NPad::SetSixAxisFusionEnabled(
1187 const Core::HID::SixAxisSensorHandle& sixaxis_handle, bool is_fusion_enabled) { 1205 const Core::HID::SixAxisSensorHandle& sixaxis_handle, bool is_fusion_enabled) {
1188 const auto is_valid = VerifyValidSixAxisSensorHandle(sixaxis_handle); 1206 const auto is_valid = VerifyValidSixAxisSensorHandle(sixaxis_handle);
1189 if (is_valid.IsError()) { 1207 if (is_valid.IsError()) {
@@ -1197,7 +1215,7 @@ ResultCode Controller_NPad::SetSixAxisFusionEnabled(
1197 return ResultSuccess; 1215 return ResultSuccess;
1198} 1216}
1199 1217
1200ResultCode Controller_NPad::SetSixAxisFusionParameters( 1218Result Controller_NPad::SetSixAxisFusionParameters(
1201 const Core::HID::SixAxisSensorHandle& sixaxis_handle, 1219 const Core::HID::SixAxisSensorHandle& sixaxis_handle,
1202 Core::HID::SixAxisSensorFusionParameters sixaxis_fusion_parameters) { 1220 Core::HID::SixAxisSensorFusionParameters sixaxis_fusion_parameters) {
1203 const auto is_valid = VerifyValidSixAxisSensorHandle(sixaxis_handle); 1221 const auto is_valid = VerifyValidSixAxisSensorHandle(sixaxis_handle);
@@ -1217,7 +1235,7 @@ ResultCode Controller_NPad::SetSixAxisFusionParameters(
1217 return ResultSuccess; 1235 return ResultSuccess;
1218} 1236}
1219 1237
1220ResultCode Controller_NPad::GetSixAxisFusionParameters( 1238Result Controller_NPad::GetSixAxisFusionParameters(
1221 const Core::HID::SixAxisSensorHandle& sixaxis_handle, 1239 const Core::HID::SixAxisSensorHandle& sixaxis_handle,
1222 Core::HID::SixAxisSensorFusionParameters& parameters) const { 1240 Core::HID::SixAxisSensorFusionParameters& parameters) const {
1223 const auto is_valid = VerifyValidSixAxisSensorHandle(sixaxis_handle); 1241 const auto is_valid = VerifyValidSixAxisSensorHandle(sixaxis_handle);
@@ -1232,8 +1250,8 @@ ResultCode Controller_NPad::GetSixAxisFusionParameters(
1232 return ResultSuccess; 1250 return ResultSuccess;
1233} 1251}
1234 1252
1235ResultCode Controller_NPad::MergeSingleJoyAsDualJoy(Core::HID::NpadIdType npad_id_1, 1253Result Controller_NPad::MergeSingleJoyAsDualJoy(Core::HID::NpadIdType npad_id_1,
1236 Core::HID::NpadIdType npad_id_2) { 1254 Core::HID::NpadIdType npad_id_2) {
1237 if (!IsNpadIdValid(npad_id_1) || !IsNpadIdValid(npad_id_2)) { 1255 if (!IsNpadIdValid(npad_id_1) || !IsNpadIdValid(npad_id_2)) {
1238 LOG_ERROR(Service_HID, "Invalid NpadIdType npad_id_1:{}, npad_id_2:{}", npad_id_1, 1256 LOG_ERROR(Service_HID, "Invalid NpadIdType npad_id_1:{}, npad_id_2:{}", npad_id_1,
1239 npad_id_2); 1257 npad_id_2);
@@ -1304,8 +1322,8 @@ void Controller_NPad::StopLRAssignmentMode() {
1304 is_in_lr_assignment_mode = false; 1322 is_in_lr_assignment_mode = false;
1305} 1323}
1306 1324
1307ResultCode Controller_NPad::SwapNpadAssignment(Core::HID::NpadIdType npad_id_1, 1325Result Controller_NPad::SwapNpadAssignment(Core::HID::NpadIdType npad_id_1,
1308 Core::HID::NpadIdType npad_id_2) { 1326 Core::HID::NpadIdType npad_id_2) {
1309 if (!IsNpadIdValid(npad_id_1) || !IsNpadIdValid(npad_id_2)) { 1327 if (!IsNpadIdValid(npad_id_1) || !IsNpadIdValid(npad_id_2)) {
1310 LOG_ERROR(Service_HID, "Invalid NpadIdType npad_id_1:{}, npad_id_2:{}", npad_id_1, 1328 LOG_ERROR(Service_HID, "Invalid NpadIdType npad_id_1:{}, npad_id_2:{}", npad_id_1,
1311 npad_id_2); 1329 npad_id_2);
@@ -1336,8 +1354,8 @@ ResultCode Controller_NPad::SwapNpadAssignment(Core::HID::NpadIdType npad_id_1,
1336 return ResultSuccess; 1354 return ResultSuccess;
1337} 1355}
1338 1356
1339ResultCode Controller_NPad::GetLedPattern(Core::HID::NpadIdType npad_id, 1357Result Controller_NPad::GetLedPattern(Core::HID::NpadIdType npad_id,
1340 Core::HID::LedPattern& pattern) const { 1358 Core::HID::LedPattern& pattern) const {
1341 if (!IsNpadIdValid(npad_id)) { 1359 if (!IsNpadIdValid(npad_id)) {
1342 LOG_ERROR(Service_HID, "Invalid NpadIdType npad_id:{}", npad_id); 1360 LOG_ERROR(Service_HID, "Invalid NpadIdType npad_id:{}", npad_id);
1343 return InvalidNpadId; 1361 return InvalidNpadId;
@@ -1347,8 +1365,8 @@ ResultCode Controller_NPad::GetLedPattern(Core::HID::NpadIdType npad_id,
1347 return ResultSuccess; 1365 return ResultSuccess;
1348} 1366}
1349 1367
1350ResultCode Controller_NPad::IsUnintendedHomeButtonInputProtectionEnabled( 1368Result Controller_NPad::IsUnintendedHomeButtonInputProtectionEnabled(Core::HID::NpadIdType npad_id,
1351 Core::HID::NpadIdType npad_id, bool& is_valid) const { 1369 bool& is_valid) const {
1352 if (!IsNpadIdValid(npad_id)) { 1370 if (!IsNpadIdValid(npad_id)) {
1353 LOG_ERROR(Service_HID, "Invalid NpadIdType npad_id:{}", npad_id); 1371 LOG_ERROR(Service_HID, "Invalid NpadIdType npad_id:{}", npad_id);
1354 return InvalidNpadId; 1372 return InvalidNpadId;
@@ -1358,7 +1376,7 @@ ResultCode Controller_NPad::IsUnintendedHomeButtonInputProtectionEnabled(
1358 return ResultSuccess; 1376 return ResultSuccess;
1359} 1377}
1360 1378
1361ResultCode Controller_NPad::SetUnintendedHomeButtonInputProtectionEnabled( 1379Result Controller_NPad::SetUnintendedHomeButtonInputProtectionEnabled(
1362 bool is_protection_enabled, Core::HID::NpadIdType npad_id) { 1380 bool is_protection_enabled, Core::HID::NpadIdType npad_id) {
1363 if (!IsNpadIdValid(npad_id)) { 1381 if (!IsNpadIdValid(npad_id)) {
1364 LOG_ERROR(Service_HID, "Invalid NpadIdType npad_id:{}", npad_id); 1382 LOG_ERROR(Service_HID, "Invalid NpadIdType npad_id:{}", npad_id);
diff --git a/src/core/hle/service/hid/controllers/npad.h b/src/core/hle/service/hid/controllers/npad.h
index 0b662b7f8..1a589cca2 100644
--- a/src/core/hle/service/hid/controllers/npad.h
+++ b/src/core/hle/service/hid/controllers/npad.h
@@ -29,7 +29,7 @@ namespace Service::KernelHelpers {
29class ServiceContext; 29class ServiceContext;
30} // namespace Service::KernelHelpers 30} // namespace Service::KernelHelpers
31 31
32union ResultCode; 32union Result;
33 33
34namespace Service::HID { 34namespace Service::HID {
35 35
@@ -81,6 +81,7 @@ public:
81 Dual = 0, 81 Dual = 0,
82 Single = 1, 82 Single = 1,
83 None = 2, 83 None = 2,
84 MaxActivationMode = 3,
84 }; 85 };
85 86
86 // This is nn::hid::NpadCommunicationMode 87 // This is nn::hid::NpadCommunicationMode
@@ -107,8 +108,8 @@ public:
107 void SetNpadCommunicationMode(NpadCommunicationMode communication_mode_); 108 void SetNpadCommunicationMode(NpadCommunicationMode communication_mode_);
108 NpadCommunicationMode GetNpadCommunicationMode() const; 109 NpadCommunicationMode GetNpadCommunicationMode() const;
109 110
110 ResultCode SetNpadMode(Core::HID::NpadIdType npad_id, NpadJoyDeviceType npad_device_type, 111 Result SetNpadMode(Core::HID::NpadIdType npad_id, NpadJoyDeviceType npad_device_type,
111 NpadJoyAssignmentMode assignment_mode); 112 NpadJoyAssignmentMode assignment_mode);
112 113
113 bool VibrateControllerAtIndex(Core::HID::NpadIdType npad_id, std::size_t device_index, 114 bool VibrateControllerAtIndex(Core::HID::NpadIdType npad_id, std::size_t device_index,
114 const Core::HID::VibrationValue& vibration_value); 115 const Core::HID::VibrationValue& vibration_value);
@@ -141,64 +142,63 @@ public:
141 void UpdateControllerAt(Core::HID::NpadStyleIndex controller, Core::HID::NpadIdType npad_id, 142 void UpdateControllerAt(Core::HID::NpadStyleIndex controller, Core::HID::NpadIdType npad_id,
142 bool connected); 143 bool connected);
143 144
144 ResultCode DisconnectNpad(Core::HID::NpadIdType npad_id); 145 Result DisconnectNpad(Core::HID::NpadIdType npad_id);
145 146
146 ResultCode SetGyroscopeZeroDriftMode(const Core::HID::SixAxisSensorHandle& sixaxis_handle, 147 Result SetGyroscopeZeroDriftMode(const Core::HID::SixAxisSensorHandle& sixaxis_handle,
147 GyroscopeZeroDriftMode drift_mode); 148 GyroscopeZeroDriftMode drift_mode);
148 ResultCode GetGyroscopeZeroDriftMode(const Core::HID::SixAxisSensorHandle& sixaxis_handle, 149 Result GetGyroscopeZeroDriftMode(const Core::HID::SixAxisSensorHandle& sixaxis_handle,
149 GyroscopeZeroDriftMode& drift_mode) const; 150 GyroscopeZeroDriftMode& drift_mode) const;
150 ResultCode IsSixAxisSensorAtRest(const Core::HID::SixAxisSensorHandle& sixaxis_handle, 151 Result IsSixAxisSensorAtRest(const Core::HID::SixAxisSensorHandle& sixaxis_handle,
151 bool& is_at_rest) const; 152 bool& is_at_rest) const;
152 ResultCode IsFirmwareUpdateAvailableForSixAxisSensor( 153 Result IsFirmwareUpdateAvailableForSixAxisSensor(
153 const Core::HID::SixAxisSensorHandle& sixaxis_handle, bool& is_firmware_available) const; 154 const Core::HID::SixAxisSensorHandle& sixaxis_handle, bool& is_firmware_available) const;
154 ResultCode EnableSixAxisSensorUnalteredPassthrough( 155 Result EnableSixAxisSensorUnalteredPassthrough(
155 const Core::HID::SixAxisSensorHandle& sixaxis_handle, bool is_enabled); 156 const Core::HID::SixAxisSensorHandle& sixaxis_handle, bool is_enabled);
156 ResultCode IsSixAxisSensorUnalteredPassthroughEnabled( 157 Result IsSixAxisSensorUnalteredPassthroughEnabled(
157 const Core::HID::SixAxisSensorHandle& sixaxis_handle, bool& is_enabled) const; 158 const Core::HID::SixAxisSensorHandle& sixaxis_handle, bool& is_enabled) const;
158 ResultCode LoadSixAxisSensorCalibrationParameter( 159 Result LoadSixAxisSensorCalibrationParameter(
159 const Core::HID::SixAxisSensorHandle& sixaxis_handle, 160 const Core::HID::SixAxisSensorHandle& sixaxis_handle,
160 Core::HID::SixAxisSensorCalibrationParameter& calibration) const; 161 Core::HID::SixAxisSensorCalibrationParameter& calibration) const;
161 ResultCode GetSixAxisSensorIcInformation( 162 Result GetSixAxisSensorIcInformation(
162 const Core::HID::SixAxisSensorHandle& sixaxis_handle, 163 const Core::HID::SixAxisSensorHandle& sixaxis_handle,
163 Core::HID::SixAxisSensorIcInformation& ic_information) const; 164 Core::HID::SixAxisSensorIcInformation& ic_information) const;
164 ResultCode ResetIsSixAxisSensorDeviceNewlyAssigned( 165 Result ResetIsSixAxisSensorDeviceNewlyAssigned(
165 const Core::HID::SixAxisSensorHandle& sixaxis_handle); 166 const Core::HID::SixAxisSensorHandle& sixaxis_handle);
166 ResultCode SetSixAxisEnabled(const Core::HID::SixAxisSensorHandle& sixaxis_handle, 167 Result SetSixAxisEnabled(const Core::HID::SixAxisSensorHandle& sixaxis_handle,
167 bool sixaxis_status); 168 bool sixaxis_status);
168 ResultCode IsSixAxisSensorFusionEnabled(const Core::HID::SixAxisSensorHandle& sixaxis_handle, 169 Result IsSixAxisSensorFusionEnabled(const Core::HID::SixAxisSensorHandle& sixaxis_handle,
169 bool& is_fusion_enabled) const; 170 bool& is_fusion_enabled) const;
170 ResultCode SetSixAxisFusionEnabled(const Core::HID::SixAxisSensorHandle& sixaxis_handle, 171 Result SetSixAxisFusionEnabled(const Core::HID::SixAxisSensorHandle& sixaxis_handle,
171 bool is_fusion_enabled); 172 bool is_fusion_enabled);
172 ResultCode SetSixAxisFusionParameters( 173 Result SetSixAxisFusionParameters(
173 const Core::HID::SixAxisSensorHandle& sixaxis_handle, 174 const Core::HID::SixAxisSensorHandle& sixaxis_handle,
174 Core::HID::SixAxisSensorFusionParameters sixaxis_fusion_parameters); 175 Core::HID::SixAxisSensorFusionParameters sixaxis_fusion_parameters);
175 ResultCode GetSixAxisFusionParameters( 176 Result GetSixAxisFusionParameters(const Core::HID::SixAxisSensorHandle& sixaxis_handle,
176 const Core::HID::SixAxisSensorHandle& sixaxis_handle, 177 Core::HID::SixAxisSensorFusionParameters& parameters) const;
177 Core::HID::SixAxisSensorFusionParameters& parameters) const; 178 Result GetLedPattern(Core::HID::NpadIdType npad_id, Core::HID::LedPattern& pattern) const;
178 ResultCode GetLedPattern(Core::HID::NpadIdType npad_id, Core::HID::LedPattern& pattern) const; 179 Result IsUnintendedHomeButtonInputProtectionEnabled(Core::HID::NpadIdType npad_id,
179 ResultCode IsUnintendedHomeButtonInputProtectionEnabled(Core::HID::NpadIdType npad_id, 180 bool& is_enabled) const;
180 bool& is_enabled) const; 181 Result SetUnintendedHomeButtonInputProtectionEnabled(bool is_protection_enabled,
181 ResultCode SetUnintendedHomeButtonInputProtectionEnabled(bool is_protection_enabled, 182 Core::HID::NpadIdType npad_id);
182 Core::HID::NpadIdType npad_id);
183 void SetAnalogStickUseCenterClamp(bool use_center_clamp); 183 void SetAnalogStickUseCenterClamp(bool use_center_clamp);
184 void ClearAllConnectedControllers(); 184 void ClearAllConnectedControllers();
185 void DisconnectAllConnectedControllers(); 185 void DisconnectAllConnectedControllers();
186 void ConnectAllDisconnectedControllers(); 186 void ConnectAllDisconnectedControllers();
187 void ClearAllControllers(); 187 void ClearAllControllers();
188 188
189 ResultCode MergeSingleJoyAsDualJoy(Core::HID::NpadIdType npad_id_1, 189 Result MergeSingleJoyAsDualJoy(Core::HID::NpadIdType npad_id_1,
190 Core::HID::NpadIdType npad_id_2); 190 Core::HID::NpadIdType npad_id_2);
191 void StartLRAssignmentMode(); 191 void StartLRAssignmentMode();
192 void StopLRAssignmentMode(); 192 void StopLRAssignmentMode();
193 ResultCode SwapNpadAssignment(Core::HID::NpadIdType npad_id_1, Core::HID::NpadIdType npad_id_2); 193 Result SwapNpadAssignment(Core::HID::NpadIdType npad_id_1, Core::HID::NpadIdType npad_id_2);
194 194
195 // Logical OR for all buttons presses on all controllers 195 // Logical OR for all buttons presses on all controllers
196 // Specifically for cheat engine and other features. 196 // Specifically for cheat engine and other features.
197 Core::HID::NpadButton GetAndResetPressState(); 197 Core::HID::NpadButton GetAndResetPressState();
198 198
199 static bool IsNpadIdValid(Core::HID::NpadIdType npad_id); 199 static bool IsNpadIdValid(Core::HID::NpadIdType npad_id);
200 static bool IsDeviceHandleValid(const Core::HID::VibrationDeviceHandle& device_handle); 200 static Result IsDeviceHandleValid(const Core::HID::VibrationDeviceHandle& device_handle);
201 static ResultCode VerifyValidSixAxisSensorHandle( 201 static Result VerifyValidSixAxisSensorHandle(
202 const Core::HID::SixAxisSensorHandle& device_handle); 202 const Core::HID::SixAxisSensorHandle& device_handle);
203 203
204private: 204private:
diff --git a/src/core/hle/service/hid/errors.h b/src/core/hle/service/hid/errors.h
index 6c8ad04af..46282f42e 100644
--- a/src/core/hle/service/hid/errors.h
+++ b/src/core/hle/service/hid/errors.h
@@ -7,12 +7,15 @@
7 7
8namespace Service::HID { 8namespace Service::HID {
9 9
10constexpr ResultCode NpadInvalidHandle{ErrorModule::HID, 100}; 10constexpr Result NpadInvalidHandle{ErrorModule::HID, 100};
11constexpr ResultCode NpadDeviceIndexOutOfRange{ErrorModule::HID, 107}; 11constexpr Result NpadDeviceIndexOutOfRange{ErrorModule::HID, 107};
12constexpr ResultCode InvalidSixAxisFusionRange{ErrorModule::HID, 423}; 12constexpr Result VibrationInvalidStyleIndex{ErrorModule::HID, 122};
13constexpr ResultCode NpadIsDualJoycon{ErrorModule::HID, 601}; 13constexpr Result VibrationInvalidNpadId{ErrorModule::HID, 123};
14constexpr ResultCode NpadIsSameType{ErrorModule::HID, 602}; 14constexpr Result VibrationDeviceIndexOutOfRange{ErrorModule::HID, 124};
15constexpr ResultCode InvalidNpadId{ErrorModule::HID, 709}; 15constexpr Result InvalidSixAxisFusionRange{ErrorModule::HID, 423};
16constexpr ResultCode NpadNotConnected{ErrorModule::HID, 710}; 16constexpr Result NpadIsDualJoycon{ErrorModule::HID, 601};
17constexpr Result NpadIsSameType{ErrorModule::HID, 602};
18constexpr Result InvalidNpadId{ErrorModule::HID, 709};
19constexpr Result NpadNotConnected{ErrorModule::HID, 710};
17 20
18} // namespace Service::HID 21} // namespace Service::HID
diff --git a/src/core/hle/service/hid/hid.cpp b/src/core/hle/service/hid/hid.cpp
index dc5d0366d..78efffc50 100644
--- a/src/core/hle/service/hid/hid.cpp
+++ b/src/core/hle/service/hid/hid.cpp
@@ -778,7 +778,7 @@ void Hid::IsSixAxisSensorAtRest(Kernel::HLERequestContext& ctx) {
778 778
779 bool is_at_rest{}; 779 bool is_at_rest{};
780 auto& controller = GetAppletResource()->GetController<Controller_NPad>(HidController::NPad); 780 auto& controller = GetAppletResource()->GetController<Controller_NPad>(HidController::NPad);
781 const auto result = controller.IsSixAxisSensorAtRest(parameters.sixaxis_handle, is_at_rest); 781 controller.IsSixAxisSensorAtRest(parameters.sixaxis_handle, is_at_rest);
782 782
783 LOG_DEBUG(Service_HID, 783 LOG_DEBUG(Service_HID,
784 "called, npad_type={}, npad_id={}, device_index={}, applet_resource_user_id={}", 784 "called, npad_type={}, npad_id={}, device_index={}, applet_resource_user_id={}",
@@ -786,7 +786,7 @@ void Hid::IsSixAxisSensorAtRest(Kernel::HLERequestContext& ctx) {
786 parameters.sixaxis_handle.device_index, parameters.applet_resource_user_id); 786 parameters.sixaxis_handle.device_index, parameters.applet_resource_user_id);
787 787
788 IPC::ResponseBuilder rb{ctx, 3}; 788 IPC::ResponseBuilder rb{ctx, 3};
789 rb.Push(result); 789 rb.Push(ResultSuccess);
790 rb.Push(is_at_rest); 790 rb.Push(is_at_rest);
791} 791}
792 792
@@ -803,8 +803,8 @@ void Hid::IsFirmwareUpdateAvailableForSixAxisSensor(Kernel::HLERequestContext& c
803 803
804 bool is_firmware_available{}; 804 bool is_firmware_available{};
805 auto& controller = GetAppletResource()->GetController<Controller_NPad>(HidController::NPad); 805 auto& controller = GetAppletResource()->GetController<Controller_NPad>(HidController::NPad);
806 const auto result = controller.IsFirmwareUpdateAvailableForSixAxisSensor( 806 controller.IsFirmwareUpdateAvailableForSixAxisSensor(parameters.sixaxis_handle,
807 parameters.sixaxis_handle, is_firmware_available); 807 is_firmware_available);
808 808
809 LOG_WARNING( 809 LOG_WARNING(
810 Service_HID, 810 Service_HID,
@@ -813,7 +813,7 @@ void Hid::IsFirmwareUpdateAvailableForSixAxisSensor(Kernel::HLERequestContext& c
813 parameters.sixaxis_handle.device_index, parameters.applet_resource_user_id); 813 parameters.sixaxis_handle.device_index, parameters.applet_resource_user_id);
814 814
815 IPC::ResponseBuilder rb{ctx, 3}; 815 IPC::ResponseBuilder rb{ctx, 3};
816 rb.Push(result); 816 rb.Push(ResultSuccess);
817 rb.Push(is_firmware_available); 817 rb.Push(is_firmware_available);
818} 818}
819 819
@@ -1083,13 +1083,13 @@ void Hid::DisconnectNpad(Kernel::HLERequestContext& ctx) {
1083 const auto parameters{rp.PopRaw<Parameters>()}; 1083 const auto parameters{rp.PopRaw<Parameters>()};
1084 1084
1085 auto& controller = GetAppletResource()->GetController<Controller_NPad>(HidController::NPad); 1085 auto& controller = GetAppletResource()->GetController<Controller_NPad>(HidController::NPad);
1086 const auto result = controller.DisconnectNpad(parameters.npad_id); 1086 controller.DisconnectNpad(parameters.npad_id);
1087 1087
1088 LOG_DEBUG(Service_HID, "called, npad_id={}, applet_resource_user_id={}", parameters.npad_id, 1088 LOG_DEBUG(Service_HID, "called, npad_id={}, applet_resource_user_id={}", parameters.npad_id,
1089 parameters.applet_resource_user_id); 1089 parameters.applet_resource_user_id);
1090 1090
1091 IPC::ResponseBuilder rb{ctx, 2}; 1091 IPC::ResponseBuilder rb{ctx, 2};
1092 rb.Push(result); 1092 rb.Push(ResultSuccess);
1093} 1093}
1094 1094
1095void Hid::GetPlayerLedPattern(Kernel::HLERequestContext& ctx) { 1095void Hid::GetPlayerLedPattern(Kernel::HLERequestContext& ctx) {
@@ -1165,15 +1165,14 @@ void Hid::SetNpadJoyAssignmentModeSingleByDefault(Kernel::HLERequestContext& ctx
1165 const auto parameters{rp.PopRaw<Parameters>()}; 1165 const auto parameters{rp.PopRaw<Parameters>()};
1166 1166
1167 auto& controller = GetAppletResource()->GetController<Controller_NPad>(HidController::NPad); 1167 auto& controller = GetAppletResource()->GetController<Controller_NPad>(HidController::NPad);
1168 const auto result = 1168 controller.SetNpadMode(parameters.npad_id, Controller_NPad::NpadJoyDeviceType::Left,
1169 controller.SetNpadMode(parameters.npad_id, Controller_NPad::NpadJoyDeviceType::Left, 1169 Controller_NPad::NpadJoyAssignmentMode::Single);
1170 Controller_NPad::NpadJoyAssignmentMode::Single);
1171 1170
1172 LOG_INFO(Service_HID, "called, npad_id={}, applet_resource_user_id={}", parameters.npad_id, 1171 LOG_INFO(Service_HID, "called, npad_id={}, applet_resource_user_id={}", parameters.npad_id,
1173 parameters.applet_resource_user_id); 1172 parameters.applet_resource_user_id);
1174 1173
1175 IPC::ResponseBuilder rb{ctx, 2}; 1174 IPC::ResponseBuilder rb{ctx, 2};
1176 rb.Push(result); 1175 rb.Push(ResultSuccess);
1177} 1176}
1178 1177
1179void Hid::SetNpadJoyAssignmentModeSingle(Kernel::HLERequestContext& ctx) { 1178void Hid::SetNpadJoyAssignmentModeSingle(Kernel::HLERequestContext& ctx) {
@@ -1189,15 +1188,15 @@ void Hid::SetNpadJoyAssignmentModeSingle(Kernel::HLERequestContext& ctx) {
1189 const auto parameters{rp.PopRaw<Parameters>()}; 1188 const auto parameters{rp.PopRaw<Parameters>()};
1190 1189
1191 auto& controller = GetAppletResource()->GetController<Controller_NPad>(HidController::NPad); 1190 auto& controller = GetAppletResource()->GetController<Controller_NPad>(HidController::NPad);
1192 const auto result = controller.SetNpadMode(parameters.npad_id, parameters.npad_joy_device_type, 1191 controller.SetNpadMode(parameters.npad_id, parameters.npad_joy_device_type,
1193 Controller_NPad::NpadJoyAssignmentMode::Single); 1192 Controller_NPad::NpadJoyAssignmentMode::Single);
1194 1193
1195 LOG_INFO(Service_HID, "called, npad_id={}, applet_resource_user_id={}, npad_joy_device_type={}", 1194 LOG_INFO(Service_HID, "called, npad_id={}, applet_resource_user_id={}, npad_joy_device_type={}",
1196 parameters.npad_id, parameters.applet_resource_user_id, 1195 parameters.npad_id, parameters.applet_resource_user_id,
1197 parameters.npad_joy_device_type); 1196 parameters.npad_joy_device_type);
1198 1197
1199 IPC::ResponseBuilder rb{ctx, 2}; 1198 IPC::ResponseBuilder rb{ctx, 2};
1200 rb.Push(result); 1199 rb.Push(ResultSuccess);
1201} 1200}
1202 1201
1203void Hid::SetNpadJoyAssignmentModeDual(Kernel::HLERequestContext& ctx) { 1202void Hid::SetNpadJoyAssignmentModeDual(Kernel::HLERequestContext& ctx) {
@@ -1212,14 +1211,13 @@ void Hid::SetNpadJoyAssignmentModeDual(Kernel::HLERequestContext& ctx) {
1212 const auto parameters{rp.PopRaw<Parameters>()}; 1211 const auto parameters{rp.PopRaw<Parameters>()};
1213 1212
1214 auto& controller = GetAppletResource()->GetController<Controller_NPad>(HidController::NPad); 1213 auto& controller = GetAppletResource()->GetController<Controller_NPad>(HidController::NPad);
1215 const auto result = controller.SetNpadMode(parameters.npad_id, {}, 1214 controller.SetNpadMode(parameters.npad_id, {}, Controller_NPad::NpadJoyAssignmentMode::Dual);
1216 Controller_NPad::NpadJoyAssignmentMode::Dual);
1217 1215
1218 LOG_INFO(Service_HID, "called, npad_id={}, applet_resource_user_id={}", parameters.npad_id, 1216 LOG_INFO(Service_HID, "called, npad_id={}, applet_resource_user_id={}", parameters.npad_id,
1219 parameters.applet_resource_user_id); 1217 parameters.applet_resource_user_id);
1220 1218
1221 IPC::ResponseBuilder rb{ctx, 2}; 1219 IPC::ResponseBuilder rb{ctx, 2};
1222 rb.Push(result); 1220 rb.Push(ResultSuccess);
1223} 1221}
1224 1222
1225void Hid::MergeSingleJoyAsDualJoy(Kernel::HLERequestContext& ctx) { 1223void Hid::MergeSingleJoyAsDualJoy(Kernel::HLERequestContext& ctx) {
@@ -1412,8 +1410,11 @@ void Hid::ClearNpadCaptureButtonAssignment(Kernel::HLERequestContext& ctx) {
1412void Hid::GetVibrationDeviceInfo(Kernel::HLERequestContext& ctx) { 1410void Hid::GetVibrationDeviceInfo(Kernel::HLERequestContext& ctx) {
1413 IPC::RequestParser rp{ctx}; 1411 IPC::RequestParser rp{ctx};
1414 const auto vibration_device_handle{rp.PopRaw<Core::HID::VibrationDeviceHandle>()}; 1412 const auto vibration_device_handle{rp.PopRaw<Core::HID::VibrationDeviceHandle>()};
1413 const auto& controller =
1414 GetAppletResource()->GetController<Controller_NPad>(HidController::NPad);
1415 1415
1416 Core::HID::VibrationDeviceInfo vibration_device_info; 1416 Core::HID::VibrationDeviceInfo vibration_device_info;
1417 bool check_device_index = false;
1417 1418
1418 switch (vibration_device_handle.npad_type) { 1419 switch (vibration_device_handle.npad_type) {
1419 case Core::HID::NpadStyleIndex::ProController: 1420 case Core::HID::NpadStyleIndex::ProController:
@@ -1421,34 +1422,46 @@ void Hid::GetVibrationDeviceInfo(Kernel::HLERequestContext& ctx) {
1421 case Core::HID::NpadStyleIndex::JoyconDual: 1422 case Core::HID::NpadStyleIndex::JoyconDual:
1422 case Core::HID::NpadStyleIndex::JoyconLeft: 1423 case Core::HID::NpadStyleIndex::JoyconLeft:
1423 case Core::HID::NpadStyleIndex::JoyconRight: 1424 case Core::HID::NpadStyleIndex::JoyconRight:
1424 default:
1425 vibration_device_info.type = Core::HID::VibrationDeviceType::LinearResonantActuator; 1425 vibration_device_info.type = Core::HID::VibrationDeviceType::LinearResonantActuator;
1426 check_device_index = true;
1426 break; 1427 break;
1427 case Core::HID::NpadStyleIndex::GameCube: 1428 case Core::HID::NpadStyleIndex::GameCube:
1428 vibration_device_info.type = Core::HID::VibrationDeviceType::GcErm; 1429 vibration_device_info.type = Core::HID::VibrationDeviceType::GcErm;
1429 break; 1430 break;
1430 case Core::HID::NpadStyleIndex::Pokeball: 1431 case Core::HID::NpadStyleIndex::N64:
1432 vibration_device_info.type = Core::HID::VibrationDeviceType::N64;
1433 break;
1434 default:
1431 vibration_device_info.type = Core::HID::VibrationDeviceType::Unknown; 1435 vibration_device_info.type = Core::HID::VibrationDeviceType::Unknown;
1432 break; 1436 break;
1433 } 1437 }
1434 1438
1435 switch (vibration_device_handle.device_index) { 1439 vibration_device_info.position = Core::HID::VibrationDevicePosition::None;
1436 case Core::HID::DeviceIndex::Left: 1440 if (check_device_index) {
1437 vibration_device_info.position = Core::HID::VibrationDevicePosition::Left; 1441 switch (vibration_device_handle.device_index) {
1438 break; 1442 case Core::HID::DeviceIndex::Left:
1439 case Core::HID::DeviceIndex::Right: 1443 vibration_device_info.position = Core::HID::VibrationDevicePosition::Left;
1440 vibration_device_info.position = Core::HID::VibrationDevicePosition::Right; 1444 break;
1441 break; 1445 case Core::HID::DeviceIndex::Right:
1442 case Core::HID::DeviceIndex::None: 1446 vibration_device_info.position = Core::HID::VibrationDevicePosition::Right;
1443 default: 1447 break;
1444 ASSERT_MSG(false, "DeviceIndex should never be None!"); 1448 case Core::HID::DeviceIndex::None:
1445 vibration_device_info.position = Core::HID::VibrationDevicePosition::None; 1449 default:
1446 break; 1450 ASSERT_MSG(false, "DeviceIndex should never be None!");
1451 break;
1452 }
1447 } 1453 }
1448 1454
1449 LOG_DEBUG(Service_HID, "called, vibration_device_type={}, vibration_device_position={}", 1455 LOG_DEBUG(Service_HID, "called, vibration_device_type={}, vibration_device_position={}",
1450 vibration_device_info.type, vibration_device_info.position); 1456 vibration_device_info.type, vibration_device_info.position);
1451 1457
1458 const auto result = controller.IsDeviceHandleValid(vibration_device_handle);
1459 if (result.IsError()) {
1460 IPC::ResponseBuilder rb{ctx, 2};
1461 rb.Push(result);
1462 return;
1463 }
1464
1452 IPC::ResponseBuilder rb{ctx, 4}; 1465 IPC::ResponseBuilder rb{ctx, 4};
1453 rb.Push(ResultSuccess); 1466 rb.Push(ResultSuccess);
1454 rb.PushRaw(vibration_device_info); 1467 rb.PushRaw(vibration_device_info);
diff --git a/src/core/hle/service/hid/hidbus.h b/src/core/hle/service/hid/hidbus.h
index 6b3015a0f..8c687f678 100644
--- a/src/core/hle/service/hid/hidbus.h
+++ b/src/core/hle/service/hid/hidbus.h
@@ -71,7 +71,7 @@ private:
71 struct HidbusStatusManagerEntry { 71 struct HidbusStatusManagerEntry {
72 u8 is_connected{}; 72 u8 is_connected{};
73 INSERT_PADDING_BYTES(0x3); 73 INSERT_PADDING_BYTES(0x3);
74 ResultCode is_connected_result{0}; 74 Result is_connected_result{0};
75 u8 is_enabled{}; 75 u8 is_enabled{};
76 u8 is_in_focus{}; 76 u8 is_in_focus{};
77 u8 is_polling_mode{}; 77 u8 is_polling_mode{};
diff --git a/src/core/hle/service/hid/hidbus/hidbus_base.h b/src/core/hle/service/hid/hidbus/hidbus_base.h
index 01c52051b..d3960f506 100644
--- a/src/core/hle/service/hid/hidbus/hidbus_base.h
+++ b/src/core/hle/service/hid/hidbus/hidbus_base.h
@@ -26,7 +26,7 @@ enum class JoyPollingMode : u32 {
26}; 26};
27 27
28struct DataAccessorHeader { 28struct DataAccessorHeader {
29 ResultCode result{ResultUnknown}; 29 Result result{ResultUnknown};
30 INSERT_PADDING_WORDS(0x1); 30 INSERT_PADDING_WORDS(0x1);
31 std::array<u8, 0x18> unused{}; 31 std::array<u8, 0x18> unused{};
32 u64 latest_entry{}; 32 u64 latest_entry{};
diff --git a/src/core/hle/service/ldn/errors.h b/src/core/hle/service/ldn/errors.h
index fb86b9402..972a74806 100644
--- a/src/core/hle/service/ldn/errors.h
+++ b/src/core/hle/service/ldn/errors.h
@@ -7,6 +7,6 @@
7 7
8namespace Service::LDN { 8namespace Service::LDN {
9 9
10constexpr ResultCode ERROR_DISABLED{ErrorModule::LDN, 22}; 10constexpr Result ERROR_DISABLED{ErrorModule::LDN, 22};
11 11
12} // namespace Service::LDN 12} // namespace Service::LDN
diff --git a/src/core/hle/service/ldr/ldr.cpp b/src/core/hle/service/ldr/ldr.cpp
index 72e4902cb..becd6d1b9 100644
--- a/src/core/hle/service/ldr/ldr.cpp
+++ b/src/core/hle/service/ldr/ldr.cpp
@@ -20,20 +20,20 @@
20 20
21namespace Service::LDR { 21namespace Service::LDR {
22 22
23constexpr ResultCode ERROR_INSUFFICIENT_ADDRESS_SPACE{ErrorModule::RO, 2}; 23constexpr Result ERROR_INSUFFICIENT_ADDRESS_SPACE{ErrorModule::RO, 2};
24 24
25[[maybe_unused]] constexpr ResultCode ERROR_INVALID_MEMORY_STATE{ErrorModule::Loader, 51}; 25[[maybe_unused]] constexpr Result ERROR_INVALID_MEMORY_STATE{ErrorModule::Loader, 51};
26constexpr ResultCode ERROR_INVALID_NRO{ErrorModule::Loader, 52}; 26constexpr Result ERROR_INVALID_NRO{ErrorModule::Loader, 52};
27constexpr ResultCode ERROR_INVALID_NRR{ErrorModule::Loader, 53}; 27constexpr Result ERROR_INVALID_NRR{ErrorModule::Loader, 53};
28constexpr ResultCode ERROR_MISSING_NRR_HASH{ErrorModule::Loader, 54}; 28constexpr Result ERROR_MISSING_NRR_HASH{ErrorModule::Loader, 54};
29constexpr ResultCode ERROR_MAXIMUM_NRO{ErrorModule::Loader, 55}; 29constexpr Result ERROR_MAXIMUM_NRO{ErrorModule::Loader, 55};
30constexpr ResultCode ERROR_MAXIMUM_NRR{ErrorModule::Loader, 56}; 30constexpr Result ERROR_MAXIMUM_NRR{ErrorModule::Loader, 56};
31constexpr ResultCode ERROR_ALREADY_LOADED{ErrorModule::Loader, 57}; 31constexpr Result ERROR_ALREADY_LOADED{ErrorModule::Loader, 57};
32constexpr ResultCode ERROR_INVALID_ALIGNMENT{ErrorModule::Loader, 81}; 32constexpr Result ERROR_INVALID_ALIGNMENT{ErrorModule::Loader, 81};
33constexpr ResultCode ERROR_INVALID_SIZE{ErrorModule::Loader, 82}; 33constexpr Result ERROR_INVALID_SIZE{ErrorModule::Loader, 82};
34constexpr ResultCode ERROR_INVALID_NRO_ADDRESS{ErrorModule::Loader, 84}; 34constexpr Result ERROR_INVALID_NRO_ADDRESS{ErrorModule::Loader, 84};
35[[maybe_unused]] constexpr ResultCode ERROR_INVALID_NRR_ADDRESS{ErrorModule::Loader, 85}; 35[[maybe_unused]] constexpr Result ERROR_INVALID_NRR_ADDRESS{ErrorModule::Loader, 85};
36constexpr ResultCode ERROR_NOT_INITIALIZED{ErrorModule::Loader, 87}; 36constexpr Result ERROR_NOT_INITIALIZED{ErrorModule::Loader, 87};
37 37
38constexpr std::size_t MAXIMUM_LOADED_RO{0x40}; 38constexpr std::size_t MAXIMUM_LOADED_RO{0x40};
39constexpr std::size_t MAXIMUM_MAP_RETRIES{0x200}; 39constexpr std::size_t MAXIMUM_MAP_RETRIES{0x200};
@@ -307,7 +307,7 @@ public:
307 return (start + size + padding_size) <= (end_info.GetAddress() + end_info.GetSize()); 307 return (start + size + padding_size) <= (end_info.GetAddress() + end_info.GetSize());
308 } 308 }
309 309
310 ResultCode GetAvailableMapRegion(Kernel::KPageTable& page_table, u64 size, VAddr& out_addr) { 310 Result GetAvailableMapRegion(Kernel::KPageTable& page_table, u64 size, VAddr& out_addr) {
311 size = Common::AlignUp(size, Kernel::PageSize); 311 size = Common::AlignUp(size, Kernel::PageSize);
312 size += page_table.GetNumGuardPages() * Kernel::PageSize * 4; 312 size += page_table.GetNumGuardPages() * Kernel::PageSize * 4;
313 313
@@ -364,7 +364,7 @@ public:
364 for (std::size_t retry = 0; retry < MAXIMUM_MAP_RETRIES; retry++) { 364 for (std::size_t retry = 0; retry < MAXIMUM_MAP_RETRIES; retry++) {
365 R_TRY(GetAvailableMapRegion(page_table, size, addr)); 365 R_TRY(GetAvailableMapRegion(page_table, size, addr));
366 366
367 const ResultCode result{page_table.MapCodeMemory(addr, base_addr, size)}; 367 const Result result{page_table.MapCodeMemory(addr, base_addr, size)};
368 if (result == Kernel::ResultInvalidCurrentMemory) { 368 if (result == Kernel::ResultInvalidCurrentMemory) {
369 continue; 369 continue;
370 } 370 }
@@ -397,8 +397,7 @@ public:
397 Kernel::KPageTable::ICacheInvalidationStrategy::InvalidateRange); 397 Kernel::KPageTable::ICacheInvalidationStrategy::InvalidateRange);
398 }); 398 });
399 399
400 const ResultCode result{ 400 const Result result{page_table.MapCodeMemory(addr + nro_size, bss_addr, bss_size)};
401 page_table.MapCodeMemory(addr + nro_size, bss_addr, bss_size)};
402 401
403 if (result == Kernel::ResultInvalidCurrentMemory) { 402 if (result == Kernel::ResultInvalidCurrentMemory) {
404 continue; 403 continue;
@@ -419,8 +418,8 @@ public:
419 return ERROR_INSUFFICIENT_ADDRESS_SPACE; 418 return ERROR_INSUFFICIENT_ADDRESS_SPACE;
420 } 419 }
421 420
422 ResultCode LoadNro(Kernel::KProcess* process, const NROHeader& nro_header, VAddr nro_addr, 421 Result LoadNro(Kernel::KProcess* process, const NROHeader& nro_header, VAddr nro_addr,
423 VAddr start) const { 422 VAddr start) const {
424 const VAddr text_start{start + nro_header.segment_headers[TEXT_INDEX].memory_offset}; 423 const VAddr text_start{start + nro_header.segment_headers[TEXT_INDEX].memory_offset};
425 const VAddr ro_start{start + nro_header.segment_headers[RO_INDEX].memory_offset}; 424 const VAddr ro_start{start + nro_header.segment_headers[RO_INDEX].memory_offset};
426 const VAddr data_start{start + nro_header.segment_headers[DATA_INDEX].memory_offset}; 425 const VAddr data_start{start + nro_header.segment_headers[DATA_INDEX].memory_offset};
@@ -569,7 +568,7 @@ public:
569 rb.Push(*map_result); 568 rb.Push(*map_result);
570 } 569 }
571 570
572 ResultCode UnmapNro(const NROInfo& info) { 571 Result UnmapNro(const NROInfo& info) {
573 // Each region must be unmapped separately to validate memory state 572 // Each region must be unmapped separately to validate memory state
574 auto& page_table{system.CurrentProcess()->PageTable()}; 573 auto& page_table{system.CurrentProcess()->PageTable()};
575 574
diff --git a/src/core/hle/service/mii/mii.cpp b/src/core/hle/service/mii/mii.cpp
index 41755bf0b..efb569993 100644
--- a/src/core/hle/service/mii/mii.cpp
+++ b/src/core/hle/service/mii/mii.cpp
@@ -12,7 +12,7 @@
12 12
13namespace Service::Mii { 13namespace Service::Mii {
14 14
15constexpr ResultCode ERROR_INVALID_ARGUMENT{ErrorModule::Mii, 1}; 15constexpr Result ERROR_INVALID_ARGUMENT{ErrorModule::Mii, 1};
16 16
17class IDatabaseService final : public ServiceFramework<IDatabaseService> { 17class IDatabaseService final : public ServiceFramework<IDatabaseService> {
18public: 18public:
diff --git a/src/core/hle/service/mii/mii_manager.cpp b/src/core/hle/service/mii/mii_manager.cpp
index 08300a1a6..544c92a00 100644
--- a/src/core/hle/service/mii/mii_manager.cpp
+++ b/src/core/hle/service/mii/mii_manager.cpp
@@ -16,7 +16,7 @@ namespace Service::Mii {
16 16
17namespace { 17namespace {
18 18
19constexpr ResultCode ERROR_CANNOT_FIND_ENTRY{ErrorModule::Mii, 4}; 19constexpr Result ERROR_CANNOT_FIND_ENTRY{ErrorModule::Mii, 4};
20 20
21constexpr std::size_t BaseMiiCount{2}; 21constexpr std::size_t BaseMiiCount{2};
22constexpr std::size_t DefaultMiiCount{RawData::DefaultMii.size()}; 22constexpr std::size_t DefaultMiiCount{RawData::DefaultMii.size()};
@@ -441,7 +441,7 @@ ResultVal<std::vector<MiiInfoElement>> MiiManager::GetDefault(SourceFlag source_
441 return result; 441 return result;
442} 442}
443 443
444ResultCode MiiManager::GetIndex([[maybe_unused]] const MiiInfo& info, u32& index) { 444Result MiiManager::GetIndex([[maybe_unused]] const MiiInfo& info, u32& index) {
445 constexpr u32 INVALID_INDEX{0xFFFFFFFF}; 445 constexpr u32 INVALID_INDEX{0xFFFFFFFF};
446 446
447 index = INVALID_INDEX; 447 index = INVALID_INDEX;
diff --git a/src/core/hle/service/mii/mii_manager.h b/src/core/hle/service/mii/mii_manager.h
index db217b9a5..6a286bd96 100644
--- a/src/core/hle/service/mii/mii_manager.h
+++ b/src/core/hle/service/mii/mii_manager.h
@@ -23,7 +23,7 @@ public:
23 MiiInfo BuildRandom(Age age, Gender gender, Race race); 23 MiiInfo BuildRandom(Age age, Gender gender, Race race);
24 MiiInfo BuildDefault(std::size_t index); 24 MiiInfo BuildDefault(std::size_t index);
25 ResultVal<std::vector<MiiInfoElement>> GetDefault(SourceFlag source_flag); 25 ResultVal<std::vector<MiiInfoElement>> GetDefault(SourceFlag source_flag);
26 ResultCode GetIndex(const MiiInfo& info, u32& index); 26 Result GetIndex(const MiiInfo& info, u32& index);
27 27
28private: 28private:
29 const Common::UUID user_id{}; 29 const Common::UUID user_id{};
diff --git a/src/core/hle/service/nfp/nfp.cpp b/src/core/hle/service/nfp/nfp.cpp
index 74891da57..6c5b41dd1 100644
--- a/src/core/hle/service/nfp/nfp.cpp
+++ b/src/core/hle/service/nfp/nfp.cpp
@@ -17,10 +17,10 @@
17 17
18namespace Service::NFP { 18namespace Service::NFP {
19namespace ErrCodes { 19namespace ErrCodes {
20constexpr ResultCode DeviceNotFound(ErrorModule::NFP, 64); 20constexpr Result DeviceNotFound(ErrorModule::NFP, 64);
21constexpr ResultCode WrongDeviceState(ErrorModule::NFP, 73); 21constexpr Result WrongDeviceState(ErrorModule::NFP, 73);
22constexpr ResultCode ApplicationAreaIsNotInitialized(ErrorModule::NFP, 128); 22constexpr Result ApplicationAreaIsNotInitialized(ErrorModule::NFP, 128);
23constexpr ResultCode ApplicationAreaExist(ErrorModule::NFP, 168); 23constexpr Result ApplicationAreaExist(ErrorModule::NFP, 168);
24} // namespace ErrCodes 24} // namespace ErrCodes
25 25
26constexpr u32 ApplicationAreaSize = 0xD8; 26constexpr u32 ApplicationAreaSize = 0xD8;
@@ -585,7 +585,7 @@ void Module::Interface::Finalize() {
585 application_area_data.clear(); 585 application_area_data.clear();
586} 586}
587 587
588ResultCode Module::Interface::StartDetection(s32 protocol_) { 588Result Module::Interface::StartDetection(s32 protocol_) {
589 auto npad_device = system.HIDCore().GetEmulatedController(npad_id); 589 auto npad_device = system.HIDCore().GetEmulatedController(npad_id);
590 590
591 // TODO(german77): Add callback for when nfc data is available 591 // TODO(german77): Add callback for when nfc data is available
@@ -601,7 +601,7 @@ ResultCode Module::Interface::StartDetection(s32 protocol_) {
601 return ErrCodes::WrongDeviceState; 601 return ErrCodes::WrongDeviceState;
602} 602}
603 603
604ResultCode Module::Interface::StopDetection() { 604Result Module::Interface::StopDetection() {
605 auto npad_device = system.HIDCore().GetEmulatedController(npad_id); 605 auto npad_device = system.HIDCore().GetEmulatedController(npad_id);
606 npad_device->SetPollingMode(Common::Input::PollingMode::Active); 606 npad_device->SetPollingMode(Common::Input::PollingMode::Active);
607 607
@@ -618,7 +618,7 @@ ResultCode Module::Interface::StopDetection() {
618 return ErrCodes::WrongDeviceState; 618 return ErrCodes::WrongDeviceState;
619} 619}
620 620
621ResultCode Module::Interface::Mount() { 621Result Module::Interface::Mount() {
622 if (device_state == DeviceState::TagFound) { 622 if (device_state == DeviceState::TagFound) {
623 device_state = DeviceState::TagMounted; 623 device_state = DeviceState::TagMounted;
624 return ResultSuccess; 624 return ResultSuccess;
@@ -628,7 +628,7 @@ ResultCode Module::Interface::Mount() {
628 return ErrCodes::WrongDeviceState; 628 return ErrCodes::WrongDeviceState;
629} 629}
630 630
631ResultCode Module::Interface::Unmount() { 631Result Module::Interface::Unmount() {
632 if (device_state == DeviceState::TagMounted) { 632 if (device_state == DeviceState::TagMounted) {
633 is_application_area_initialized = false; 633 is_application_area_initialized = false;
634 application_area_id = 0; 634 application_area_id = 0;
@@ -641,7 +641,7 @@ ResultCode Module::Interface::Unmount() {
641 return ErrCodes::WrongDeviceState; 641 return ErrCodes::WrongDeviceState;
642} 642}
643 643
644ResultCode Module::Interface::GetTagInfo(TagInfo& tag_info) const { 644Result Module::Interface::GetTagInfo(TagInfo& tag_info) const {
645 if (device_state == DeviceState::TagFound || device_state == DeviceState::TagMounted) { 645 if (device_state == DeviceState::TagFound || device_state == DeviceState::TagMounted) {
646 tag_info = { 646 tag_info = {
647 .uuid = tag_data.uuid, 647 .uuid = tag_data.uuid,
@@ -656,7 +656,7 @@ ResultCode Module::Interface::GetTagInfo(TagInfo& tag_info) const {
656 return ErrCodes::WrongDeviceState; 656 return ErrCodes::WrongDeviceState;
657} 657}
658 658
659ResultCode Module::Interface::GetCommonInfo(CommonInfo& common_info) const { 659Result Module::Interface::GetCommonInfo(CommonInfo& common_info) const {
660 if (device_state != DeviceState::TagMounted) { 660 if (device_state != DeviceState::TagMounted) {
661 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state); 661 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state);
662 return ErrCodes::WrongDeviceState; 662 return ErrCodes::WrongDeviceState;
@@ -674,7 +674,7 @@ ResultCode Module::Interface::GetCommonInfo(CommonInfo& common_info) const {
674 return ResultSuccess; 674 return ResultSuccess;
675} 675}
676 676
677ResultCode Module::Interface::GetModelInfo(ModelInfo& model_info) const { 677Result Module::Interface::GetModelInfo(ModelInfo& model_info) const {
678 if (device_state != DeviceState::TagMounted) { 678 if (device_state != DeviceState::TagMounted) {
679 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state); 679 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state);
680 return ErrCodes::WrongDeviceState; 680 return ErrCodes::WrongDeviceState;
@@ -684,7 +684,7 @@ ResultCode Module::Interface::GetModelInfo(ModelInfo& model_info) const {
684 return ResultSuccess; 684 return ResultSuccess;
685} 685}
686 686
687ResultCode Module::Interface::GetRegisterInfo(RegisterInfo& register_info) const { 687Result Module::Interface::GetRegisterInfo(RegisterInfo& register_info) const {
688 if (device_state != DeviceState::TagMounted) { 688 if (device_state != DeviceState::TagMounted) {
689 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state); 689 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state);
690 return ErrCodes::WrongDeviceState; 690 return ErrCodes::WrongDeviceState;
@@ -704,7 +704,7 @@ ResultCode Module::Interface::GetRegisterInfo(RegisterInfo& register_info) const
704 return ResultSuccess; 704 return ResultSuccess;
705} 705}
706 706
707ResultCode Module::Interface::OpenApplicationArea(u32 access_id) { 707Result Module::Interface::OpenApplicationArea(u32 access_id) {
708 if (device_state != DeviceState::TagMounted) { 708 if (device_state != DeviceState::TagMounted) {
709 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state); 709 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state);
710 return ErrCodes::WrongDeviceState; 710 return ErrCodes::WrongDeviceState;
@@ -721,7 +721,7 @@ ResultCode Module::Interface::OpenApplicationArea(u32 access_id) {
721 return ResultSuccess; 721 return ResultSuccess;
722} 722}
723 723
724ResultCode Module::Interface::GetApplicationArea(std::vector<u8>& data) const { 724Result Module::Interface::GetApplicationArea(std::vector<u8>& data) const {
725 if (device_state != DeviceState::TagMounted) { 725 if (device_state != DeviceState::TagMounted) {
726 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state); 726 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state);
727 return ErrCodes::WrongDeviceState; 727 return ErrCodes::WrongDeviceState;
@@ -736,7 +736,7 @@ ResultCode Module::Interface::GetApplicationArea(std::vector<u8>& data) const {
736 return ResultSuccess; 736 return ResultSuccess;
737} 737}
738 738
739ResultCode Module::Interface::SetApplicationArea(const std::vector<u8>& data) { 739Result Module::Interface::SetApplicationArea(const std::vector<u8>& data) {
740 if (device_state != DeviceState::TagMounted) { 740 if (device_state != DeviceState::TagMounted) {
741 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state); 741 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state);
742 return ErrCodes::WrongDeviceState; 742 return ErrCodes::WrongDeviceState;
@@ -750,7 +750,7 @@ ResultCode Module::Interface::SetApplicationArea(const std::vector<u8>& data) {
750 return ResultSuccess; 750 return ResultSuccess;
751} 751}
752 752
753ResultCode Module::Interface::CreateApplicationArea(u32 access_id, const std::vector<u8>& data) { 753Result Module::Interface::CreateApplicationArea(u32 access_id, const std::vector<u8>& data) {
754 if (device_state != DeviceState::TagMounted) { 754 if (device_state != DeviceState::TagMounted) {
755 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state); 755 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state);
756 return ErrCodes::WrongDeviceState; 756 return ErrCodes::WrongDeviceState;
diff --git a/src/core/hle/service/nfp/nfp.h b/src/core/hle/service/nfp/nfp.h
index d307c6a35..0fc808781 100644
--- a/src/core/hle/service/nfp/nfp.h
+++ b/src/core/hle/service/nfp/nfp.h
@@ -178,20 +178,20 @@ public:
178 void Initialize(); 178 void Initialize();
179 void Finalize(); 179 void Finalize();
180 180
181 ResultCode StartDetection(s32 protocol_); 181 Result StartDetection(s32 protocol_);
182 ResultCode StopDetection(); 182 Result StopDetection();
183 ResultCode Mount(); 183 Result Mount();
184 ResultCode Unmount(); 184 Result Unmount();
185 185
186 ResultCode GetTagInfo(TagInfo& tag_info) const; 186 Result GetTagInfo(TagInfo& tag_info) const;
187 ResultCode GetCommonInfo(CommonInfo& common_info) const; 187 Result GetCommonInfo(CommonInfo& common_info) const;
188 ResultCode GetModelInfo(ModelInfo& model_info) const; 188 Result GetModelInfo(ModelInfo& model_info) const;
189 ResultCode GetRegisterInfo(RegisterInfo& register_info) const; 189 Result GetRegisterInfo(RegisterInfo& register_info) const;
190 190
191 ResultCode OpenApplicationArea(u32 access_id); 191 Result OpenApplicationArea(u32 access_id);
192 ResultCode GetApplicationArea(std::vector<u8>& data) const; 192 Result GetApplicationArea(std::vector<u8>& data) const;
193 ResultCode SetApplicationArea(const std::vector<u8>& data); 193 Result SetApplicationArea(const std::vector<u8>& data);
194 ResultCode CreateApplicationArea(u32 access_id, const std::vector<u8>& data); 194 Result CreateApplicationArea(u32 access_id, const std::vector<u8>& data);
195 195
196 u64 GetHandle() const; 196 u64 GetHandle() const;
197 DeviceState GetCurrentState() const; 197 DeviceState GetCurrentState() const;
diff --git a/src/core/hle/service/ns/errors.h b/src/core/hle/service/ns/errors.h
index 3c50c66e0..8a7621798 100644
--- a/src/core/hle/service/ns/errors.h
+++ b/src/core/hle/service/ns/errors.h
@@ -7,5 +7,5 @@
7 7
8namespace Service::NS { 8namespace Service::NS {
9 9
10constexpr ResultCode ERR_APPLICATION_LANGUAGE_NOT_FOUND{ErrorModule::NS, 300}; 10constexpr Result ERR_APPLICATION_LANGUAGE_NOT_FOUND{ErrorModule::NS, 300};
11} \ No newline at end of file 11} \ No newline at end of file
diff --git a/src/core/hle/service/pctl/pctl_module.cpp b/src/core/hle/service/pctl/pctl_module.cpp
index 8d5729003..2a123b42d 100644
--- a/src/core/hle/service/pctl/pctl_module.cpp
+++ b/src/core/hle/service/pctl/pctl_module.cpp
@@ -13,10 +13,10 @@ namespace Service::PCTL {
13 13
14namespace Error { 14namespace Error {
15 15
16constexpr ResultCode ResultNoFreeCommunication{ErrorModule::PCTL, 101}; 16constexpr Result ResultNoFreeCommunication{ErrorModule::PCTL, 101};
17constexpr ResultCode ResultStereoVisionRestricted{ErrorModule::PCTL, 104}; 17constexpr Result ResultStereoVisionRestricted{ErrorModule::PCTL, 104};
18constexpr ResultCode ResultNoCapability{ErrorModule::PCTL, 131}; 18constexpr Result ResultNoCapability{ErrorModule::PCTL, 131};
19constexpr ResultCode ResultNoRestrictionEnabled{ErrorModule::PCTL, 181}; 19constexpr Result ResultNoRestrictionEnabled{ErrorModule::PCTL, 181};
20 20
21} // namespace Error 21} // namespace Error
22 22
diff --git a/src/core/hle/service/pm/pm.cpp b/src/core/hle/service/pm/pm.cpp
index a8e2a5cbd..b10e86c8f 100644
--- a/src/core/hle/service/pm/pm.cpp
+++ b/src/core/hle/service/pm/pm.cpp
@@ -12,12 +12,12 @@ namespace Service::PM {
12 12
13namespace { 13namespace {
14 14
15constexpr ResultCode ResultProcessNotFound{ErrorModule::PM, 1}; 15constexpr Result ResultProcessNotFound{ErrorModule::PM, 1};
16[[maybe_unused]] constexpr ResultCode ResultAlreadyStarted{ErrorModule::PM, 2}; 16[[maybe_unused]] constexpr Result ResultAlreadyStarted{ErrorModule::PM, 2};
17[[maybe_unused]] constexpr ResultCode ResultNotTerminated{ErrorModule::PM, 3}; 17[[maybe_unused]] constexpr Result ResultNotTerminated{ErrorModule::PM, 3};
18[[maybe_unused]] constexpr ResultCode ResultDebugHookInUse{ErrorModule::PM, 4}; 18[[maybe_unused]] constexpr Result ResultDebugHookInUse{ErrorModule::PM, 4};
19[[maybe_unused]] constexpr ResultCode ResultApplicationRunning{ErrorModule::PM, 5}; 19[[maybe_unused]] constexpr Result ResultApplicationRunning{ErrorModule::PM, 5};
20[[maybe_unused]] constexpr ResultCode ResultInvalidSize{ErrorModule::PM, 6}; 20[[maybe_unused]] constexpr Result ResultInvalidSize{ErrorModule::PM, 6};
21 21
22constexpr u64 NO_PROCESS_FOUND_PID{0}; 22constexpr u64 NO_PROCESS_FOUND_PID{0};
23 23
diff --git a/src/core/hle/service/service.cpp b/src/core/hle/service/service.cpp
index 574272b0c..318009e4f 100644
--- a/src/core/hle/service/service.cpp
+++ b/src/core/hle/service/service.cpp
@@ -190,8 +190,8 @@ void ServiceFrameworkBase::InvokeRequestTipc(Kernel::HLERequestContext& ctx) {
190 handler_invoker(this, info->handler_callback, ctx); 190 handler_invoker(this, info->handler_callback, ctx);
191} 191}
192 192
193ResultCode ServiceFrameworkBase::HandleSyncRequest(Kernel::KServerSession& session, 193Result ServiceFrameworkBase::HandleSyncRequest(Kernel::KServerSession& session,
194 Kernel::HLERequestContext& ctx) { 194 Kernel::HLERequestContext& ctx) {
195 const auto guard = LockService(); 195 const auto guard = LockService();
196 196
197 switch (ctx.GetCommandType()) { 197 switch (ctx.GetCommandType()) {
diff --git a/src/core/hle/service/service.h b/src/core/hle/service/service.h
index f23e0cd64..5bf197c51 100644
--- a/src/core/hle/service/service.h
+++ b/src/core/hle/service/service.h
@@ -79,8 +79,8 @@ public:
79 Kernel::KClientPort& CreatePort(); 79 Kernel::KClientPort& CreatePort();
80 80
81 /// Handles a synchronization request for the service. 81 /// Handles a synchronization request for the service.
82 ResultCode HandleSyncRequest(Kernel::KServerSession& session, 82 Result HandleSyncRequest(Kernel::KServerSession& session,
83 Kernel::HLERequestContext& context) override; 83 Kernel::HLERequestContext& context) override;
84 84
85protected: 85protected:
86 /// Member-function pointer type of SyncRequest handlers. 86 /// Member-function pointer type of SyncRequest handlers.
diff --git a/src/core/hle/service/set/set.cpp b/src/core/hle/service/set/set.cpp
index 2839cffcf..f761c2da4 100644
--- a/src/core/hle/service/set/set.cpp
+++ b/src/core/hle/service/set/set.cpp
@@ -74,7 +74,7 @@ constexpr std::array<std::pair<LanguageCode, KeyboardLayout>, 18> language_to_la
74constexpr std::size_t PRE_4_0_0_MAX_ENTRIES = 0xF; 74constexpr std::size_t PRE_4_0_0_MAX_ENTRIES = 0xF;
75constexpr std::size_t POST_4_0_0_MAX_ENTRIES = 0x40; 75constexpr std::size_t POST_4_0_0_MAX_ENTRIES = 0x40;
76 76
77constexpr ResultCode ERR_INVALID_LANGUAGE{ErrorModule::Settings, 625}; 77constexpr Result ERR_INVALID_LANGUAGE{ErrorModule::Settings, 625};
78 78
79void PushResponseLanguageCode(Kernel::HLERequestContext& ctx, std::size_t num_language_codes) { 79void PushResponseLanguageCode(Kernel::HLERequestContext& ctx, std::size_t num_language_codes) {
80 IPC::ResponseBuilder rb{ctx, 3}; 80 IPC::ResponseBuilder rb{ctx, 3};
diff --git a/src/core/hle/service/set/set_sys.cpp b/src/core/hle/service/set/set_sys.cpp
index 87c6f7f85..2a0b812c1 100644
--- a/src/core/hle/service/set/set_sys.cpp
+++ b/src/core/hle/service/set/set_sys.cpp
@@ -32,7 +32,7 @@ void GetFirmwareVersionImpl(Kernel::HLERequestContext& ctx, GetFirmwareVersionTy
32 // consistence (currently reports as 5.1.0-0.0) 32 // consistence (currently reports as 5.1.0-0.0)
33 const auto archive = FileSys::SystemArchive::SystemVersion(); 33 const auto archive = FileSys::SystemArchive::SystemVersion();
34 34
35 const auto early_exit_failure = [&ctx](std::string_view desc, ResultCode code) { 35 const auto early_exit_failure = [&ctx](std::string_view desc, Result code) {
36 LOG_ERROR(Service_SET, "General failure while attempting to resolve firmware version ({}).", 36 LOG_ERROR(Service_SET, "General failure while attempting to resolve firmware version ({}).",
37 desc); 37 desc);
38 IPC::ResponseBuilder rb{ctx, 2}; 38 IPC::ResponseBuilder rb{ctx, 2};
diff --git a/src/core/hle/service/sm/sm.cpp b/src/core/hle/service/sm/sm.cpp
index 925608875..246c94623 100644
--- a/src/core/hle/service/sm/sm.cpp
+++ b/src/core/hle/service/sm/sm.cpp
@@ -17,10 +17,10 @@
17 17
18namespace Service::SM { 18namespace Service::SM {
19 19
20constexpr ResultCode ERR_NOT_INITIALIZED(ErrorModule::SM, 2); 20constexpr Result ERR_NOT_INITIALIZED(ErrorModule::SM, 2);
21constexpr ResultCode ERR_ALREADY_REGISTERED(ErrorModule::SM, 4); 21constexpr Result ERR_ALREADY_REGISTERED(ErrorModule::SM, 4);
22constexpr ResultCode ERR_INVALID_NAME(ErrorModule::SM, 6); 22constexpr Result ERR_INVALID_NAME(ErrorModule::SM, 6);
23constexpr ResultCode ERR_SERVICE_NOT_REGISTERED(ErrorModule::SM, 7); 23constexpr Result ERR_SERVICE_NOT_REGISTERED(ErrorModule::SM, 7);
24 24
25ServiceManager::ServiceManager(Kernel::KernelCore& kernel_) : kernel{kernel_} {} 25ServiceManager::ServiceManager(Kernel::KernelCore& kernel_) : kernel{kernel_} {}
26ServiceManager::~ServiceManager() = default; 26ServiceManager::~ServiceManager() = default;
@@ -29,7 +29,7 @@ void ServiceManager::InvokeControlRequest(Kernel::HLERequestContext& context) {
29 controller_interface->InvokeRequest(context); 29 controller_interface->InvokeRequest(context);
30} 30}
31 31
32static ResultCode ValidateServiceName(const std::string& name) { 32static Result ValidateServiceName(const std::string& name) {
33 if (name.empty() || name.size() > 8) { 33 if (name.empty() || name.size() > 8) {
34 LOG_ERROR(Service_SM, "Invalid service name! service={}", name); 34 LOG_ERROR(Service_SM, "Invalid service name! service={}", name);
35 return ERR_INVALID_NAME; 35 return ERR_INVALID_NAME;
@@ -43,8 +43,8 @@ Kernel::KClientPort& ServiceManager::InterfaceFactory(ServiceManager& self, Core
43 return self.sm_interface->CreatePort(); 43 return self.sm_interface->CreatePort();
44} 44}
45 45
46ResultCode ServiceManager::RegisterService(std::string name, u32 max_sessions, 46Result ServiceManager::RegisterService(std::string name, u32 max_sessions,
47 Kernel::SessionRequestHandlerPtr handler) { 47 Kernel::SessionRequestHandlerPtr handler) {
48 48
49 CASCADE_CODE(ValidateServiceName(name)); 49 CASCADE_CODE(ValidateServiceName(name));
50 50
@@ -58,7 +58,7 @@ ResultCode ServiceManager::RegisterService(std::string name, u32 max_sessions,
58 return ResultSuccess; 58 return ResultSuccess;
59} 59}
60 60
61ResultCode ServiceManager::UnregisterService(const std::string& name) { 61Result ServiceManager::UnregisterService(const std::string& name) {
62 CASCADE_CODE(ValidateServiceName(name)); 62 CASCADE_CODE(ValidateServiceName(name));
63 63
64 const auto iter = registered_services.find(name); 64 const auto iter = registered_services.find(name);
@@ -94,7 +94,7 @@ ResultVal<Kernel::KPort*> ServiceManager::GetServicePort(const std::string& name
94 * Inputs: 94 * Inputs:
95 * 0: 0x00000000 95 * 0: 0x00000000
96 * Outputs: 96 * Outputs:
97 * 0: ResultCode 97 * 0: Result
98 */ 98 */
99void SM::Initialize(Kernel::HLERequestContext& ctx) { 99void SM::Initialize(Kernel::HLERequestContext& ctx) {
100 LOG_DEBUG(Service_SM, "called"); 100 LOG_DEBUG(Service_SM, "called");
diff --git a/src/core/hle/service/sm/sm.h b/src/core/hle/service/sm/sm.h
index 43d445e97..878decc6f 100644
--- a/src/core/hle/service/sm/sm.h
+++ b/src/core/hle/service/sm/sm.h
@@ -55,9 +55,9 @@ public:
55 explicit ServiceManager(Kernel::KernelCore& kernel_); 55 explicit ServiceManager(Kernel::KernelCore& kernel_);
56 ~ServiceManager(); 56 ~ServiceManager();
57 57
58 ResultCode RegisterService(std::string name, u32 max_sessions, 58 Result RegisterService(std::string name, u32 max_sessions,
59 Kernel::SessionRequestHandlerPtr handler); 59 Kernel::SessionRequestHandlerPtr handler);
60 ResultCode UnregisterService(const std::string& name); 60 Result UnregisterService(const std::string& name);
61 ResultVal<Kernel::KPort*> GetServicePort(const std::string& name); 61 ResultVal<Kernel::KPort*> GetServicePort(const std::string& name);
62 62
63 template <Common::DerivedFrom<Kernel::SessionRequestHandler> T> 63 template <Common::DerivedFrom<Kernel::SessionRequestHandler> T>
diff --git a/src/core/hle/service/sm/sm_controller.cpp b/src/core/hle/service/sm/sm_controller.cpp
index a4ed4193e..2a4bd64ab 100644
--- a/src/core/hle/service/sm/sm_controller.cpp
+++ b/src/core/hle/service/sm/sm_controller.cpp
@@ -33,7 +33,7 @@ void Controller::CloneCurrentObject(Kernel::HLERequestContext& ctx) {
33 33
34 // Create a session. 34 // Create a session.
35 Kernel::KClientSession* session{}; 35 Kernel::KClientSession* session{};
36 const ResultCode result = parent_port.CreateSession(std::addressof(session), session_manager); 36 const Result result = parent_port.CreateSession(std::addressof(session), session_manager);
37 if (result.IsError()) { 37 if (result.IsError()) {
38 LOG_CRITICAL(Service, "CreateSession failed with error 0x{:08X}", result.raw); 38 LOG_CRITICAL(Service, "CreateSession failed with error 0x{:08X}", result.raw);
39 IPC::ResponseBuilder rb{ctx, 2}; 39 IPC::ResponseBuilder rb{ctx, 2};
diff --git a/src/core/hle/service/spl/spl_results.h b/src/core/hle/service/spl/spl_results.h
index 17ef655a9..dd7ba11f3 100644
--- a/src/core/hle/service/spl/spl_results.h
+++ b/src/core/hle/service/spl/spl_results.h
@@ -8,23 +8,23 @@
8namespace Service::SPL { 8namespace Service::SPL {
9 9
10// Description 0 - 99 10// Description 0 - 99
11constexpr ResultCode ResultSecureMonitorError{ErrorModule::SPL, 0}; 11constexpr Result ResultSecureMonitorError{ErrorModule::SPL, 0};
12constexpr ResultCode ResultSecureMonitorNotImplemented{ErrorModule::SPL, 1}; 12constexpr Result ResultSecureMonitorNotImplemented{ErrorModule::SPL, 1};
13constexpr ResultCode ResultSecureMonitorInvalidArgument{ErrorModule::SPL, 2}; 13constexpr Result ResultSecureMonitorInvalidArgument{ErrorModule::SPL, 2};
14constexpr ResultCode ResultSecureMonitorBusy{ErrorModule::SPL, 3}; 14constexpr Result ResultSecureMonitorBusy{ErrorModule::SPL, 3};
15constexpr ResultCode ResultSecureMonitorNoAsyncOperation{ErrorModule::SPL, 4}; 15constexpr Result ResultSecureMonitorNoAsyncOperation{ErrorModule::SPL, 4};
16constexpr ResultCode ResultSecureMonitorInvalidAsyncOperation{ErrorModule::SPL, 5}; 16constexpr Result ResultSecureMonitorInvalidAsyncOperation{ErrorModule::SPL, 5};
17constexpr ResultCode ResultSecureMonitorNotPermitted{ErrorModule::SPL, 6}; 17constexpr Result ResultSecureMonitorNotPermitted{ErrorModule::SPL, 6};
18constexpr ResultCode ResultSecureMonitorNotInitialized{ErrorModule::SPL, 7}; 18constexpr Result ResultSecureMonitorNotInitialized{ErrorModule::SPL, 7};
19 19
20constexpr ResultCode ResultInvalidSize{ErrorModule::SPL, 100}; 20constexpr Result ResultInvalidSize{ErrorModule::SPL, 100};
21constexpr ResultCode ResultUnknownSecureMonitorError{ErrorModule::SPL, 101}; 21constexpr Result ResultUnknownSecureMonitorError{ErrorModule::SPL, 101};
22constexpr ResultCode ResultDecryptionFailed{ErrorModule::SPL, 102}; 22constexpr Result ResultDecryptionFailed{ErrorModule::SPL, 102};
23 23
24constexpr ResultCode ResultOutOfKeySlots{ErrorModule::SPL, 104}; 24constexpr Result ResultOutOfKeySlots{ErrorModule::SPL, 104};
25constexpr ResultCode ResultInvalidKeySlot{ErrorModule::SPL, 105}; 25constexpr Result ResultInvalidKeySlot{ErrorModule::SPL, 105};
26constexpr ResultCode ResultBootReasonAlreadySet{ErrorModule::SPL, 106}; 26constexpr Result ResultBootReasonAlreadySet{ErrorModule::SPL, 106};
27constexpr ResultCode ResultBootReasonNotSet{ErrorModule::SPL, 107}; 27constexpr Result ResultBootReasonNotSet{ErrorModule::SPL, 107};
28constexpr ResultCode ResultInvalidArgument{ErrorModule::SPL, 108}; 28constexpr Result ResultInvalidArgument{ErrorModule::SPL, 108};
29 29
30} // namespace Service::SPL 30} // namespace Service::SPL
diff --git a/src/core/hle/service/time/clock_types.h b/src/core/hle/service/time/clock_types.h
index d0af06d94..ef070f32f 100644
--- a/src/core/hle/service/time/clock_types.h
+++ b/src/core/hle/service/time/clock_types.h
@@ -22,7 +22,7 @@ struct SteadyClockTimePoint {
22 s64 time_point; 22 s64 time_point;
23 Common::UUID clock_source_id; 23 Common::UUID clock_source_id;
24 24
25 ResultCode GetSpanBetween(SteadyClockTimePoint other, s64& span) const { 25 Result GetSpanBetween(SteadyClockTimePoint other, s64& span) const {
26 span = 0; 26 span = 0;
27 27
28 if (clock_source_id != other.clock_source_id) { 28 if (clock_source_id != other.clock_source_id) {
@@ -92,9 +92,9 @@ struct ClockSnapshot {
92 TimeType type; 92 TimeType type;
93 INSERT_PADDING_BYTES_NOINIT(0x2); 93 INSERT_PADDING_BYTES_NOINIT(0x2);
94 94
95 static ResultCode GetCurrentTime(s64& current_time, 95 static Result GetCurrentTime(s64& current_time,
96 const SteadyClockTimePoint& steady_clock_time_point, 96 const SteadyClockTimePoint& steady_clock_time_point,
97 const SystemClockContext& context) { 97 const SystemClockContext& context) {
98 if (steady_clock_time_point.clock_source_id != context.steady_time_point.clock_source_id) { 98 if (steady_clock_time_point.clock_source_id != context.steady_time_point.clock_source_id) {
99 current_time = 0; 99 current_time = 0;
100 return ERROR_TIME_MISMATCH; 100 return ERROR_TIME_MISMATCH;
diff --git a/src/core/hle/service/time/errors.h b/src/core/hle/service/time/errors.h
index 592921f6b..6655d30e1 100644
--- a/src/core/hle/service/time/errors.h
+++ b/src/core/hle/service/time/errors.h
@@ -7,15 +7,15 @@
7 7
8namespace Service::Time { 8namespace Service::Time {
9 9
10constexpr ResultCode ERROR_PERMISSION_DENIED{ErrorModule::Time, 1}; 10constexpr Result ERROR_PERMISSION_DENIED{ErrorModule::Time, 1};
11constexpr ResultCode ERROR_TIME_MISMATCH{ErrorModule::Time, 102}; 11constexpr Result ERROR_TIME_MISMATCH{ErrorModule::Time, 102};
12constexpr ResultCode ERROR_UNINITIALIZED_CLOCK{ErrorModule::Time, 103}; 12constexpr Result ERROR_UNINITIALIZED_CLOCK{ErrorModule::Time, 103};
13constexpr ResultCode ERROR_TIME_NOT_FOUND{ErrorModule::Time, 200}; 13constexpr Result ERROR_TIME_NOT_FOUND{ErrorModule::Time, 200};
14constexpr ResultCode ERROR_OVERFLOW{ErrorModule::Time, 201}; 14constexpr Result ERROR_OVERFLOW{ErrorModule::Time, 201};
15constexpr ResultCode ERROR_LOCATION_NAME_TOO_LONG{ErrorModule::Time, 801}; 15constexpr Result ERROR_LOCATION_NAME_TOO_LONG{ErrorModule::Time, 801};
16constexpr ResultCode ERROR_OUT_OF_RANGE{ErrorModule::Time, 902}; 16constexpr Result ERROR_OUT_OF_RANGE{ErrorModule::Time, 902};
17constexpr ResultCode ERROR_TIME_ZONE_CONVERSION_FAILED{ErrorModule::Time, 903}; 17constexpr Result ERROR_TIME_ZONE_CONVERSION_FAILED{ErrorModule::Time, 903};
18constexpr ResultCode ERROR_TIME_ZONE_NOT_FOUND{ErrorModule::Time, 989}; 18constexpr Result ERROR_TIME_ZONE_NOT_FOUND{ErrorModule::Time, 989};
19constexpr ResultCode ERROR_NOT_IMPLEMENTED{ErrorModule::Time, 990}; 19constexpr Result ERROR_NOT_IMPLEMENTED{ErrorModule::Time, 990};
20 20
21} // namespace Service::Time 21} // namespace Service::Time
diff --git a/src/core/hle/service/time/local_system_clock_context_writer.h b/src/core/hle/service/time/local_system_clock_context_writer.h
index 0977806b3..1639ef2b9 100644
--- a/src/core/hle/service/time/local_system_clock_context_writer.h
+++ b/src/core/hle/service/time/local_system_clock_context_writer.h
@@ -14,7 +14,7 @@ public:
14 : SystemClockContextUpdateCallback{}, shared_memory{shared_memory_} {} 14 : SystemClockContextUpdateCallback{}, shared_memory{shared_memory_} {}
15 15
16protected: 16protected:
17 ResultCode Update() override { 17 Result Update() override {
18 shared_memory.UpdateLocalSystemClockContext(context); 18 shared_memory.UpdateLocalSystemClockContext(context);
19 return ResultSuccess; 19 return ResultSuccess;
20 } 20 }
diff --git a/src/core/hle/service/time/network_system_clock_context_writer.h b/src/core/hle/service/time/network_system_clock_context_writer.h
index 975089af8..655e4c06d 100644
--- a/src/core/hle/service/time/network_system_clock_context_writer.h
+++ b/src/core/hle/service/time/network_system_clock_context_writer.h
@@ -15,7 +15,7 @@ public:
15 : SystemClockContextUpdateCallback{}, shared_memory{shared_memory_} {} 15 : SystemClockContextUpdateCallback{}, shared_memory{shared_memory_} {}
16 16
17protected: 17protected:
18 ResultCode Update() override { 18 Result Update() override {
19 shared_memory.UpdateNetworkSystemClockContext(context); 19 shared_memory.UpdateNetworkSystemClockContext(context);
20 return ResultSuccess; 20 return ResultSuccess;
21 } 21 }
diff --git a/src/core/hle/service/time/standard_user_system_clock_core.cpp b/src/core/hle/service/time/standard_user_system_clock_core.cpp
index 508091dc2..b033757ed 100644
--- a/src/core/hle/service/time/standard_user_system_clock_core.cpp
+++ b/src/core/hle/service/time/standard_user_system_clock_core.cpp
@@ -27,9 +27,9 @@ StandardUserSystemClockCore::~StandardUserSystemClockCore() {
27 service_context.CloseEvent(auto_correction_event); 27 service_context.CloseEvent(auto_correction_event);
28} 28}
29 29
30ResultCode StandardUserSystemClockCore::SetAutomaticCorrectionEnabled(Core::System& system, 30Result StandardUserSystemClockCore::SetAutomaticCorrectionEnabled(Core::System& system,
31 bool value) { 31 bool value) {
32 if (const ResultCode result{ApplyAutomaticCorrection(system, value)}; result != ResultSuccess) { 32 if (const Result result{ApplyAutomaticCorrection(system, value)}; result != ResultSuccess) {
33 return result; 33 return result;
34 } 34 }
35 35
@@ -38,27 +38,27 @@ ResultCode StandardUserSystemClockCore::SetAutomaticCorrectionEnabled(Core::Syst
38 return ResultSuccess; 38 return ResultSuccess;
39} 39}
40 40
41ResultCode StandardUserSystemClockCore::GetClockContext(Core::System& system, 41Result StandardUserSystemClockCore::GetClockContext(Core::System& system,
42 SystemClockContext& ctx) const { 42 SystemClockContext& ctx) const {
43 if (const ResultCode result{ApplyAutomaticCorrection(system, false)}; result != ResultSuccess) { 43 if (const Result result{ApplyAutomaticCorrection(system, false)}; result != ResultSuccess) {
44 return result; 44 return result;
45 } 45 }
46 46
47 return local_system_clock_core.GetClockContext(system, ctx); 47 return local_system_clock_core.GetClockContext(system, ctx);
48} 48}
49 49
50ResultCode StandardUserSystemClockCore::Flush(const SystemClockContext&) { 50Result StandardUserSystemClockCore::Flush(const SystemClockContext&) {
51 UNIMPLEMENTED(); 51 UNIMPLEMENTED();
52 return ERROR_NOT_IMPLEMENTED; 52 return ERROR_NOT_IMPLEMENTED;
53} 53}
54 54
55ResultCode StandardUserSystemClockCore::SetClockContext(const SystemClockContext&) { 55Result StandardUserSystemClockCore::SetClockContext(const SystemClockContext&) {
56 UNIMPLEMENTED(); 56 UNIMPLEMENTED();
57 return ERROR_NOT_IMPLEMENTED; 57 return ERROR_NOT_IMPLEMENTED;
58} 58}
59 59
60ResultCode StandardUserSystemClockCore::ApplyAutomaticCorrection(Core::System& system, 60Result StandardUserSystemClockCore::ApplyAutomaticCorrection(Core::System& system,
61 bool value) const { 61 bool value) const {
62 if (auto_correction_enabled == value) { 62 if (auto_correction_enabled == value) {
63 return ResultSuccess; 63 return ResultSuccess;
64 } 64 }
@@ -68,7 +68,7 @@ ResultCode StandardUserSystemClockCore::ApplyAutomaticCorrection(Core::System& s
68 } 68 }
69 69
70 SystemClockContext ctx{}; 70 SystemClockContext ctx{};
71 if (const ResultCode result{network_system_clock_core.GetClockContext(system, ctx)}; 71 if (const Result result{network_system_clock_core.GetClockContext(system, ctx)};
72 result != ResultSuccess) { 72 result != ResultSuccess) {
73 return result; 73 return result;
74 } 74 }
diff --git a/src/core/hle/service/time/standard_user_system_clock_core.h b/src/core/hle/service/time/standard_user_system_clock_core.h
index 22df23b29..ee6e29487 100644
--- a/src/core/hle/service/time/standard_user_system_clock_core.h
+++ b/src/core/hle/service/time/standard_user_system_clock_core.h
@@ -28,9 +28,9 @@ public:
28 28
29 ~StandardUserSystemClockCore() override; 29 ~StandardUserSystemClockCore() override;
30 30
31 ResultCode SetAutomaticCorrectionEnabled(Core::System& system, bool value); 31 Result SetAutomaticCorrectionEnabled(Core::System& system, bool value);
32 32
33 ResultCode GetClockContext(Core::System& system, SystemClockContext& ctx) const override; 33 Result GetClockContext(Core::System& system, SystemClockContext& ctx) const override;
34 34
35 bool IsAutomaticCorrectionEnabled() const { 35 bool IsAutomaticCorrectionEnabled() const {
36 return auto_correction_enabled; 36 return auto_correction_enabled;
@@ -41,11 +41,11 @@ public:
41 } 41 }
42 42
43protected: 43protected:
44 ResultCode Flush(const SystemClockContext&) override; 44 Result Flush(const SystemClockContext&) override;
45 45
46 ResultCode SetClockContext(const SystemClockContext&) override; 46 Result SetClockContext(const SystemClockContext&) override;
47 47
48 ResultCode ApplyAutomaticCorrection(Core::System& system, bool value) const; 48 Result ApplyAutomaticCorrection(Core::System& system, bool value) const;
49 49
50 const SteadyClockTimePoint& GetAutomaticCorrectionUpdatedTime() const { 50 const SteadyClockTimePoint& GetAutomaticCorrectionUpdatedTime() const {
51 return auto_correction_time; 51 return auto_correction_time;
diff --git a/src/core/hle/service/time/system_clock_context_update_callback.cpp b/src/core/hle/service/time/system_clock_context_update_callback.cpp
index 37c140c6f..a649bed3a 100644
--- a/src/core/hle/service/time/system_clock_context_update_callback.cpp
+++ b/src/core/hle/service/time/system_clock_context_update_callback.cpp
@@ -30,8 +30,8 @@ void SystemClockContextUpdateCallback::BroadcastOperationEvent() {
30 } 30 }
31} 31}
32 32
33ResultCode SystemClockContextUpdateCallback::Update(const SystemClockContext& value) { 33Result SystemClockContextUpdateCallback::Update(const SystemClockContext& value) {
34 ResultCode result{ResultSuccess}; 34 Result result{ResultSuccess};
35 35
36 if (NeedUpdate(value)) { 36 if (NeedUpdate(value)) {
37 context = value; 37 context = value;
@@ -47,7 +47,7 @@ ResultCode SystemClockContextUpdateCallback::Update(const SystemClockContext& va
47 return result; 47 return result;
48} 48}
49 49
50ResultCode SystemClockContextUpdateCallback::Update() { 50Result SystemClockContextUpdateCallback::Update() {
51 return ResultSuccess; 51 return ResultSuccess;
52} 52}
53 53
diff --git a/src/core/hle/service/time/system_clock_context_update_callback.h b/src/core/hle/service/time/system_clock_context_update_callback.h
index bee90e329..9c6caf196 100644
--- a/src/core/hle/service/time/system_clock_context_update_callback.h
+++ b/src/core/hle/service/time/system_clock_context_update_callback.h
@@ -28,10 +28,10 @@ public:
28 28
29 void BroadcastOperationEvent(); 29 void BroadcastOperationEvent();
30 30
31 ResultCode Update(const SystemClockContext& value); 31 Result Update(const SystemClockContext& value);
32 32
33protected: 33protected:
34 virtual ResultCode Update(); 34 virtual Result Update();
35 35
36 SystemClockContext context{}; 36 SystemClockContext context{};
37 37
diff --git a/src/core/hle/service/time/system_clock_core.cpp b/src/core/hle/service/time/system_clock_core.cpp
index cb132239c..da078241f 100644
--- a/src/core/hle/service/time/system_clock_core.cpp
+++ b/src/core/hle/service/time/system_clock_core.cpp
@@ -14,13 +14,13 @@ SystemClockCore::SystemClockCore(SteadyClockCore& steady_clock_core_)
14 14
15SystemClockCore::~SystemClockCore() = default; 15SystemClockCore::~SystemClockCore() = default;
16 16
17ResultCode SystemClockCore::GetCurrentTime(Core::System& system, s64& posix_time) const { 17Result SystemClockCore::GetCurrentTime(Core::System& system, s64& posix_time) const {
18 posix_time = 0; 18 posix_time = 0;
19 19
20 const SteadyClockTimePoint current_time_point{steady_clock_core.GetCurrentTimePoint(system)}; 20 const SteadyClockTimePoint current_time_point{steady_clock_core.GetCurrentTimePoint(system)};
21 21
22 SystemClockContext clock_context{}; 22 SystemClockContext clock_context{};
23 if (const ResultCode result{GetClockContext(system, clock_context)}; result != ResultSuccess) { 23 if (const Result result{GetClockContext(system, clock_context)}; result != ResultSuccess) {
24 return result; 24 return result;
25 } 25 }
26 26
@@ -33,26 +33,26 @@ ResultCode SystemClockCore::GetCurrentTime(Core::System& system, s64& posix_time
33 return ResultSuccess; 33 return ResultSuccess;
34} 34}
35 35
36ResultCode SystemClockCore::SetCurrentTime(Core::System& system, s64 posix_time) { 36Result SystemClockCore::SetCurrentTime(Core::System& system, s64 posix_time) {
37 const SteadyClockTimePoint current_time_point{steady_clock_core.GetCurrentTimePoint(system)}; 37 const SteadyClockTimePoint current_time_point{steady_clock_core.GetCurrentTimePoint(system)};
38 const SystemClockContext clock_context{posix_time - current_time_point.time_point, 38 const SystemClockContext clock_context{posix_time - current_time_point.time_point,
39 current_time_point}; 39 current_time_point};
40 40
41 if (const ResultCode result{SetClockContext(clock_context)}; result != ResultSuccess) { 41 if (const Result result{SetClockContext(clock_context)}; result != ResultSuccess) {
42 return result; 42 return result;
43 } 43 }
44 return Flush(clock_context); 44 return Flush(clock_context);
45} 45}
46 46
47ResultCode SystemClockCore::Flush(const SystemClockContext& clock_context) { 47Result SystemClockCore::Flush(const SystemClockContext& clock_context) {
48 if (!system_clock_context_update_callback) { 48 if (!system_clock_context_update_callback) {
49 return ResultSuccess; 49 return ResultSuccess;
50 } 50 }
51 return system_clock_context_update_callback->Update(clock_context); 51 return system_clock_context_update_callback->Update(clock_context);
52} 52}
53 53
54ResultCode SystemClockCore::SetSystemClockContext(const SystemClockContext& clock_context) { 54Result SystemClockCore::SetSystemClockContext(const SystemClockContext& clock_context) {
55 if (const ResultCode result{SetClockContext(clock_context)}; result != ResultSuccess) { 55 if (const Result result{SetClockContext(clock_context)}; result != ResultSuccess) {
56 return result; 56 return result;
57 } 57 }
58 return Flush(clock_context); 58 return Flush(clock_context);
diff --git a/src/core/hle/service/time/system_clock_core.h b/src/core/hle/service/time/system_clock_core.h
index 76d82f976..8cb34126f 100644
--- a/src/core/hle/service/time/system_clock_core.h
+++ b/src/core/hle/service/time/system_clock_core.h
@@ -29,28 +29,28 @@ public:
29 return steady_clock_core; 29 return steady_clock_core;
30 } 30 }
31 31
32 ResultCode GetCurrentTime(Core::System& system, s64& posix_time) const; 32 Result GetCurrentTime(Core::System& system, s64& posix_time) const;
33 33
34 ResultCode SetCurrentTime(Core::System& system, s64 posix_time); 34 Result SetCurrentTime(Core::System& system, s64 posix_time);
35 35
36 virtual ResultCode GetClockContext([[maybe_unused]] Core::System& system, 36 virtual Result GetClockContext([[maybe_unused]] Core::System& system,
37 SystemClockContext& value) const { 37 SystemClockContext& value) const {
38 value = context; 38 value = context;
39 return ResultSuccess; 39 return ResultSuccess;
40 } 40 }
41 41
42 virtual ResultCode SetClockContext(const SystemClockContext& value) { 42 virtual Result SetClockContext(const SystemClockContext& value) {
43 context = value; 43 context = value;
44 return ResultSuccess; 44 return ResultSuccess;
45 } 45 }
46 46
47 virtual ResultCode Flush(const SystemClockContext& clock_context); 47 virtual Result Flush(const SystemClockContext& clock_context);
48 48
49 void SetUpdateCallbackInstance(std::shared_ptr<SystemClockContextUpdateCallback> callback) { 49 void SetUpdateCallbackInstance(std::shared_ptr<SystemClockContextUpdateCallback> callback) {
50 system_clock_context_update_callback = std::move(callback); 50 system_clock_context_update_callback = std::move(callback);
51 } 51 }
52 52
53 ResultCode SetSystemClockContext(const SystemClockContext& context); 53 Result SetSystemClockContext(const SystemClockContext& context);
54 54
55 bool IsInitialized() const { 55 bool IsInitialized() const {
56 return is_initialized; 56 return is_initialized;
diff --git a/src/core/hle/service/time/time.cpp b/src/core/hle/service/time/time.cpp
index 095fa021c..f77cdbb43 100644
--- a/src/core/hle/service/time/time.cpp
+++ b/src/core/hle/service/time/time.cpp
@@ -43,8 +43,7 @@ private:
43 } 43 }
44 44
45 s64 posix_time{}; 45 s64 posix_time{};
46 if (const ResultCode result{clock_core.GetCurrentTime(system, posix_time)}; 46 if (const Result result{clock_core.GetCurrentTime(system, posix_time)}; result.IsError()) {
47 result.IsError()) {
48 IPC::ResponseBuilder rb{ctx, 2}; 47 IPC::ResponseBuilder rb{ctx, 2};
49 rb.Push(result); 48 rb.Push(result);
50 return; 49 return;
@@ -65,7 +64,7 @@ private:
65 } 64 }
66 65
67 Clock::SystemClockContext system_clock_context{}; 66 Clock::SystemClockContext system_clock_context{};
68 if (const ResultCode result{clock_core.GetClockContext(system, system_clock_context)}; 67 if (const Result result{clock_core.GetClockContext(system, system_clock_context)};
69 result.IsError()) { 68 result.IsError()) {
70 IPC::ResponseBuilder rb{ctx, 2}; 69 IPC::ResponseBuilder rb{ctx, 2};
71 rb.Push(result); 70 rb.Push(result);
@@ -116,7 +115,7 @@ private:
116 Clock::SteadyClockCore& clock_core; 115 Clock::SteadyClockCore& clock_core;
117}; 116};
118 117
119ResultCode Module::Interface::GetClockSnapshotFromSystemClockContextInternal( 118Result Module::Interface::GetClockSnapshotFromSystemClockContextInternal(
120 Kernel::KThread* thread, Clock::SystemClockContext user_context, 119 Kernel::KThread* thread, Clock::SystemClockContext user_context,
121 Clock::SystemClockContext network_context, Clock::TimeType type, 120 Clock::SystemClockContext network_context, Clock::TimeType type,
122 Clock::ClockSnapshot& clock_snapshot) { 121 Clock::ClockSnapshot& clock_snapshot) {
@@ -129,7 +128,7 @@ ResultCode Module::Interface::GetClockSnapshotFromSystemClockContextInternal(
129 time_manager.GetStandardUserSystemClockCore().IsAutomaticCorrectionEnabled(); 128 time_manager.GetStandardUserSystemClockCore().IsAutomaticCorrectionEnabled();
130 clock_snapshot.type = type; 129 clock_snapshot.type = type;
131 130
132 if (const ResultCode result{ 131 if (const Result result{
133 time_manager.GetTimeZoneContentManager().GetTimeZoneManager().GetDeviceLocationName( 132 time_manager.GetTimeZoneContentManager().GetTimeZoneManager().GetDeviceLocationName(
134 clock_snapshot.location_name)}; 133 clock_snapshot.location_name)};
135 result != ResultSuccess) { 134 result != ResultSuccess) {
@@ -138,7 +137,7 @@ ResultCode Module::Interface::GetClockSnapshotFromSystemClockContextInternal(
138 137
139 clock_snapshot.user_context = user_context; 138 clock_snapshot.user_context = user_context;
140 139
141 if (const ResultCode result{Clock::ClockSnapshot::GetCurrentTime( 140 if (const Result result{Clock::ClockSnapshot::GetCurrentTime(
142 clock_snapshot.user_time, clock_snapshot.steady_clock_time_point, 141 clock_snapshot.user_time, clock_snapshot.steady_clock_time_point,
143 clock_snapshot.user_context)}; 142 clock_snapshot.user_context)};
144 result != ResultSuccess) { 143 result != ResultSuccess) {
@@ -146,7 +145,7 @@ ResultCode Module::Interface::GetClockSnapshotFromSystemClockContextInternal(
146 } 145 }
147 146
148 TimeZone::CalendarInfo userCalendarInfo{}; 147 TimeZone::CalendarInfo userCalendarInfo{};
149 if (const ResultCode result{ 148 if (const Result result{
150 time_manager.GetTimeZoneContentManager().GetTimeZoneManager().ToCalendarTimeWithMyRules( 149 time_manager.GetTimeZoneContentManager().GetTimeZoneManager().ToCalendarTimeWithMyRules(
151 clock_snapshot.user_time, userCalendarInfo)}; 150 clock_snapshot.user_time, userCalendarInfo)};
152 result != ResultSuccess) { 151 result != ResultSuccess) {
@@ -165,7 +164,7 @@ ResultCode Module::Interface::GetClockSnapshotFromSystemClockContextInternal(
165 } 164 }
166 165
167 TimeZone::CalendarInfo networkCalendarInfo{}; 166 TimeZone::CalendarInfo networkCalendarInfo{};
168 if (const ResultCode result{ 167 if (const Result result{
169 time_manager.GetTimeZoneContentManager().GetTimeZoneManager().ToCalendarTimeWithMyRules( 168 time_manager.GetTimeZoneContentManager().GetTimeZoneManager().ToCalendarTimeWithMyRules(
170 clock_snapshot.network_time, networkCalendarInfo)}; 169 clock_snapshot.network_time, networkCalendarInfo)};
171 result != ResultSuccess) { 170 result != ResultSuccess) {
@@ -262,7 +261,7 @@ void Module::Interface::GetClockSnapshot(Kernel::HLERequestContext& ctx) {
262 LOG_DEBUG(Service_Time, "called, type={}", type); 261 LOG_DEBUG(Service_Time, "called, type={}", type);
263 262
264 Clock::SystemClockContext user_context{}; 263 Clock::SystemClockContext user_context{};
265 if (const ResultCode result{ 264 if (const Result result{
266 system.GetTimeManager().GetStandardUserSystemClockCore().GetClockContext(system, 265 system.GetTimeManager().GetStandardUserSystemClockCore().GetClockContext(system,
267 user_context)}; 266 user_context)};
268 result.IsError()) { 267 result.IsError()) {
@@ -272,7 +271,7 @@ void Module::Interface::GetClockSnapshot(Kernel::HLERequestContext& ctx) {
272 } 271 }
273 272
274 Clock::SystemClockContext network_context{}; 273 Clock::SystemClockContext network_context{};
275 if (const ResultCode result{ 274 if (const Result result{
276 system.GetTimeManager().GetStandardNetworkSystemClockCore().GetClockContext( 275 system.GetTimeManager().GetStandardNetworkSystemClockCore().GetClockContext(
277 system, network_context)}; 276 system, network_context)};
278 result.IsError()) { 277 result.IsError()) {
@@ -282,7 +281,7 @@ void Module::Interface::GetClockSnapshot(Kernel::HLERequestContext& ctx) {
282 } 281 }
283 282
284 Clock::ClockSnapshot clock_snapshot{}; 283 Clock::ClockSnapshot clock_snapshot{};
285 if (const ResultCode result{GetClockSnapshotFromSystemClockContextInternal( 284 if (const Result result{GetClockSnapshotFromSystemClockContextInternal(
286 &ctx.GetThread(), user_context, network_context, type, clock_snapshot)}; 285 &ctx.GetThread(), user_context, network_context, type, clock_snapshot)};
287 result.IsError()) { 286 result.IsError()) {
288 IPC::ResponseBuilder rb{ctx, 2}; 287 IPC::ResponseBuilder rb{ctx, 2};
@@ -308,7 +307,7 @@ void Module::Interface::GetClockSnapshotFromSystemClockContext(Kernel::HLEReques
308 LOG_DEBUG(Service_Time, "called, type={}", type); 307 LOG_DEBUG(Service_Time, "called, type={}", type);
309 308
310 Clock::ClockSnapshot clock_snapshot{}; 309 Clock::ClockSnapshot clock_snapshot{};
311 if (const ResultCode result{GetClockSnapshotFromSystemClockContextInternal( 310 if (const Result result{GetClockSnapshotFromSystemClockContextInternal(
312 &ctx.GetThread(), user_context, network_context, type, clock_snapshot)}; 311 &ctx.GetThread(), user_context, network_context, type, clock_snapshot)};
313 result != ResultSuccess) { 312 result != ResultSuccess) {
314 IPC::ResponseBuilder rb{ctx, 2}; 313 IPC::ResponseBuilder rb{ctx, 2};
@@ -365,7 +364,7 @@ void Module::Interface::CalculateSpanBetween(Kernel::HLERequestContext& ctx) {
365 Clock::TimeSpanType time_span_type{}; 364 Clock::TimeSpanType time_span_type{};
366 s64 span{}; 365 s64 span{};
367 366
368 if (const ResultCode result{snapshot_a.steady_clock_time_point.GetSpanBetween( 367 if (const Result result{snapshot_a.steady_clock_time_point.GetSpanBetween(
369 snapshot_b.steady_clock_time_point, span)}; 368 snapshot_b.steady_clock_time_point, span)};
370 result != ResultSuccess) { 369 result != ResultSuccess) {
371 if (snapshot_a.network_time && snapshot_b.network_time) { 370 if (snapshot_a.network_time && snapshot_b.network_time) {
diff --git a/src/core/hle/service/time/time.h b/src/core/hle/service/time/time.h
index 017f20a23..76a46cfc7 100644
--- a/src/core/hle/service/time/time.h
+++ b/src/core/hle/service/time/time.h
@@ -36,7 +36,7 @@ public:
36 void GetSharedMemoryNativeHandle(Kernel::HLERequestContext& ctx); 36 void GetSharedMemoryNativeHandle(Kernel::HLERequestContext& ctx);
37 37
38 private: 38 private:
39 ResultCode GetClockSnapshotFromSystemClockContextInternal( 39 Result GetClockSnapshotFromSystemClockContextInternal(
40 Kernel::KThread* thread, Clock::SystemClockContext user_context, 40 Kernel::KThread* thread, Clock::SystemClockContext user_context,
41 Clock::SystemClockContext network_context, Clock::TimeType type, 41 Clock::SystemClockContext network_context, Clock::TimeType type,
42 Clock::ClockSnapshot& cloc_snapshot); 42 Clock::ClockSnapshot& cloc_snapshot);
diff --git a/src/core/hle/service/time/time_zone_content_manager.cpp b/src/core/hle/service/time/time_zone_content_manager.cpp
index 80818eb70..afbfe9715 100644
--- a/src/core/hle/service/time/time_zone_content_manager.cpp
+++ b/src/core/hle/service/time/time_zone_content_manager.cpp
@@ -90,10 +90,10 @@ void TimeZoneContentManager::Initialize(TimeManager& time_manager) {
90 } 90 }
91} 91}
92 92
93ResultCode TimeZoneContentManager::LoadTimeZoneRule(TimeZoneRule& rules, 93Result TimeZoneContentManager::LoadTimeZoneRule(TimeZoneRule& rules,
94 const std::string& location_name) const { 94 const std::string& location_name) const {
95 FileSys::VirtualFile vfs_file; 95 FileSys::VirtualFile vfs_file;
96 if (const ResultCode result{GetTimeZoneInfoFile(location_name, vfs_file)}; 96 if (const Result result{GetTimeZoneInfoFile(location_name, vfs_file)};
97 result != ResultSuccess) { 97 result != ResultSuccess) {
98 return result; 98 return result;
99 } 99 }
@@ -106,8 +106,8 @@ bool TimeZoneContentManager::IsLocationNameValid(const std::string& location_nam
106 location_name_cache.end(); 106 location_name_cache.end();
107} 107}
108 108
109ResultCode TimeZoneContentManager::GetTimeZoneInfoFile(const std::string& location_name, 109Result TimeZoneContentManager::GetTimeZoneInfoFile(const std::string& location_name,
110 FileSys::VirtualFile& vfs_file) const { 110 FileSys::VirtualFile& vfs_file) const {
111 if (!IsLocationNameValid(location_name)) { 111 if (!IsLocationNameValid(location_name)) {
112 return ERROR_TIME_NOT_FOUND; 112 return ERROR_TIME_NOT_FOUND;
113 } 113 }
diff --git a/src/core/hle/service/time/time_zone_content_manager.h b/src/core/hle/service/time/time_zone_content_manager.h
index c6c94bcc0..3d94b6428 100644
--- a/src/core/hle/service/time/time_zone_content_manager.h
+++ b/src/core/hle/service/time/time_zone_content_manager.h
@@ -32,12 +32,12 @@ public:
32 return time_zone_manager; 32 return time_zone_manager;
33 } 33 }
34 34
35 ResultCode LoadTimeZoneRule(TimeZoneRule& rules, const std::string& location_name) const; 35 Result LoadTimeZoneRule(TimeZoneRule& rules, const std::string& location_name) const;
36 36
37private: 37private:
38 bool IsLocationNameValid(const std::string& location_name) const; 38 bool IsLocationNameValid(const std::string& location_name) const;
39 ResultCode GetTimeZoneInfoFile(const std::string& location_name, 39 Result GetTimeZoneInfoFile(const std::string& location_name,
40 FileSys::VirtualFile& vfs_file) const; 40 FileSys::VirtualFile& vfs_file) const;
41 41
42 Core::System& system; 42 Core::System& system;
43 TimeZoneManager time_zone_manager; 43 TimeZoneManager time_zone_manager;
diff --git a/src/core/hle/service/time/time_zone_manager.cpp b/src/core/hle/service/time/time_zone_manager.cpp
index fee05ec7a..2aa675df9 100644
--- a/src/core/hle/service/time/time_zone_manager.cpp
+++ b/src/core/hle/service/time/time_zone_manager.cpp
@@ -666,8 +666,8 @@ static bool ParseTimeZoneBinary(TimeZoneRule& time_zone_rule, FileSys::VirtualFi
666 return true; 666 return true;
667} 667}
668 668
669static ResultCode CreateCalendarTime(s64 time, int gmt_offset, CalendarTimeInternal& calendar_time, 669static Result CreateCalendarTime(s64 time, int gmt_offset, CalendarTimeInternal& calendar_time,
670 CalendarAdditionalInfo& calendar_additional_info) { 670 CalendarAdditionalInfo& calendar_additional_info) {
671 s64 year{epoch_year}; 671 s64 year{epoch_year};
672 s64 time_days{time / seconds_per_day}; 672 s64 time_days{time / seconds_per_day};
673 s64 remaining_seconds{time % seconds_per_day}; 673 s64 remaining_seconds{time % seconds_per_day};
@@ -741,9 +741,9 @@ static ResultCode CreateCalendarTime(s64 time, int gmt_offset, CalendarTimeInter
741 return ResultSuccess; 741 return ResultSuccess;
742} 742}
743 743
744static ResultCode ToCalendarTimeInternal(const TimeZoneRule& rules, s64 time, 744static Result ToCalendarTimeInternal(const TimeZoneRule& rules, s64 time,
745 CalendarTimeInternal& calendar_time, 745 CalendarTimeInternal& calendar_time,
746 CalendarAdditionalInfo& calendar_additional_info) { 746 CalendarAdditionalInfo& calendar_additional_info) {
747 if ((rules.go_ahead && time < rules.ats[0]) || 747 if ((rules.go_ahead && time < rules.ats[0]) ||
748 (rules.go_back && time > rules.ats[rules.time_count - 1])) { 748 (rules.go_back && time > rules.ats[rules.time_count - 1])) {
749 s64 seconds{}; 749 s64 seconds{};
@@ -766,7 +766,7 @@ static ResultCode ToCalendarTimeInternal(const TimeZoneRule& rules, s64 time,
766 if (new_time < rules.ats[0] && new_time > rules.ats[rules.time_count - 1]) { 766 if (new_time < rules.ats[0] && new_time > rules.ats[rules.time_count - 1]) {
767 return ERROR_TIME_NOT_FOUND; 767 return ERROR_TIME_NOT_FOUND;
768 } 768 }
769 if (const ResultCode result{ 769 if (const Result result{
770 ToCalendarTimeInternal(rules, new_time, calendar_time, calendar_additional_info)}; 770 ToCalendarTimeInternal(rules, new_time, calendar_time, calendar_additional_info)};
771 result != ResultSuccess) { 771 result != ResultSuccess) {
772 return result; 772 return result;
@@ -797,8 +797,8 @@ static ResultCode ToCalendarTimeInternal(const TimeZoneRule& rules, s64 time,
797 tti_index = rules.types[low - 1]; 797 tti_index = rules.types[low - 1];
798 } 798 }
799 799
800 if (const ResultCode result{CreateCalendarTime(time, rules.ttis[tti_index].gmt_offset, 800 if (const Result result{CreateCalendarTime(time, rules.ttis[tti_index].gmt_offset,
801 calendar_time, calendar_additional_info)}; 801 calendar_time, calendar_additional_info)};
802 result != ResultSuccess) { 802 result != ResultSuccess) {
803 return result; 803 return result;
804 } 804 }
@@ -811,9 +811,9 @@ static ResultCode ToCalendarTimeInternal(const TimeZoneRule& rules, s64 time,
811 return ResultSuccess; 811 return ResultSuccess;
812} 812}
813 813
814static ResultCode ToCalendarTimeImpl(const TimeZoneRule& rules, s64 time, CalendarInfo& calendar) { 814static Result ToCalendarTimeImpl(const TimeZoneRule& rules, s64 time, CalendarInfo& calendar) {
815 CalendarTimeInternal calendar_time{}; 815 CalendarTimeInternal calendar_time{};
816 const ResultCode result{ 816 const Result result{
817 ToCalendarTimeInternal(rules, time, calendar_time, calendar.additional_info)}; 817 ToCalendarTimeInternal(rules, time, calendar_time, calendar.additional_info)};
818 calendar.time.year = static_cast<s16>(calendar_time.year); 818 calendar.time.year = static_cast<s16>(calendar_time.year);
819 819
@@ -830,13 +830,13 @@ static ResultCode ToCalendarTimeImpl(const TimeZoneRule& rules, s64 time, Calend
830TimeZoneManager::TimeZoneManager() = default; 830TimeZoneManager::TimeZoneManager() = default;
831TimeZoneManager::~TimeZoneManager() = default; 831TimeZoneManager::~TimeZoneManager() = default;
832 832
833ResultCode TimeZoneManager::ToCalendarTime(const TimeZoneRule& rules, s64 time, 833Result TimeZoneManager::ToCalendarTime(const TimeZoneRule& rules, s64 time,
834 CalendarInfo& calendar) const { 834 CalendarInfo& calendar) const {
835 return ToCalendarTimeImpl(rules, time, calendar); 835 return ToCalendarTimeImpl(rules, time, calendar);
836} 836}
837 837
838ResultCode TimeZoneManager::SetDeviceLocationNameWithTimeZoneRule(const std::string& location_name, 838Result TimeZoneManager::SetDeviceLocationNameWithTimeZoneRule(const std::string& location_name,
839 FileSys::VirtualFile& vfs_file) { 839 FileSys::VirtualFile& vfs_file) {
840 TimeZoneRule rule{}; 840 TimeZoneRule rule{};
841 if (ParseTimeZoneBinary(rule, vfs_file)) { 841 if (ParseTimeZoneBinary(rule, vfs_file)) {
842 device_location_name = location_name; 842 device_location_name = location_name;
@@ -846,12 +846,12 @@ ResultCode TimeZoneManager::SetDeviceLocationNameWithTimeZoneRule(const std::str
846 return ERROR_TIME_ZONE_CONVERSION_FAILED; 846 return ERROR_TIME_ZONE_CONVERSION_FAILED;
847} 847}
848 848
849ResultCode TimeZoneManager::SetUpdatedTime(const Clock::SteadyClockTimePoint& value) { 849Result TimeZoneManager::SetUpdatedTime(const Clock::SteadyClockTimePoint& value) {
850 time_zone_update_time_point = value; 850 time_zone_update_time_point = value;
851 return ResultSuccess; 851 return ResultSuccess;
852} 852}
853 853
854ResultCode TimeZoneManager::ToCalendarTimeWithMyRules(s64 time, CalendarInfo& calendar) const { 854Result TimeZoneManager::ToCalendarTimeWithMyRules(s64 time, CalendarInfo& calendar) const {
855 if (is_initialized) { 855 if (is_initialized) {
856 return ToCalendarTime(time_zone_rule, time, calendar); 856 return ToCalendarTime(time_zone_rule, time, calendar);
857 } else { 857 } else {
@@ -859,16 +859,16 @@ ResultCode TimeZoneManager::ToCalendarTimeWithMyRules(s64 time, CalendarInfo& ca
859 } 859 }
860} 860}
861 861
862ResultCode TimeZoneManager::ParseTimeZoneRuleBinary(TimeZoneRule& rules, 862Result TimeZoneManager::ParseTimeZoneRuleBinary(TimeZoneRule& rules,
863 FileSys::VirtualFile& vfs_file) const { 863 FileSys::VirtualFile& vfs_file) const {
864 if (!ParseTimeZoneBinary(rules, vfs_file)) { 864 if (!ParseTimeZoneBinary(rules, vfs_file)) {
865 return ERROR_TIME_ZONE_CONVERSION_FAILED; 865 return ERROR_TIME_ZONE_CONVERSION_FAILED;
866 } 866 }
867 return ResultSuccess; 867 return ResultSuccess;
868} 868}
869 869
870ResultCode TimeZoneManager::ToPosixTime(const TimeZoneRule& rules, 870Result TimeZoneManager::ToPosixTime(const TimeZoneRule& rules, const CalendarTime& calendar_time,
871 const CalendarTime& calendar_time, s64& posix_time) const { 871 s64& posix_time) const {
872 posix_time = 0; 872 posix_time = 0;
873 873
874 CalendarTimeInternal internal_time{ 874 CalendarTimeInternal internal_time{
@@ -1020,8 +1020,8 @@ ResultCode TimeZoneManager::ToPosixTime(const TimeZoneRule& rules,
1020 return ResultSuccess; 1020 return ResultSuccess;
1021} 1021}
1022 1022
1023ResultCode TimeZoneManager::ToPosixTimeWithMyRule(const CalendarTime& calendar_time, 1023Result TimeZoneManager::ToPosixTimeWithMyRule(const CalendarTime& calendar_time,
1024 s64& posix_time) const { 1024 s64& posix_time) const {
1025 if (is_initialized) { 1025 if (is_initialized) {
1026 return ToPosixTime(time_zone_rule, calendar_time, posix_time); 1026 return ToPosixTime(time_zone_rule, calendar_time, posix_time);
1027 } 1027 }
@@ -1029,7 +1029,7 @@ ResultCode TimeZoneManager::ToPosixTimeWithMyRule(const CalendarTime& calendar_t
1029 return ERROR_UNINITIALIZED_CLOCK; 1029 return ERROR_UNINITIALIZED_CLOCK;
1030} 1030}
1031 1031
1032ResultCode TimeZoneManager::GetDeviceLocationName(LocationName& value) const { 1032Result TimeZoneManager::GetDeviceLocationName(LocationName& value) const {
1033 if (!is_initialized) { 1033 if (!is_initialized) {
1034 return ERROR_UNINITIALIZED_CLOCK; 1034 return ERROR_UNINITIALIZED_CLOCK;
1035 } 1035 }
diff --git a/src/core/hle/service/time/time_zone_manager.h b/src/core/hle/service/time/time_zone_manager.h
index 8c1b19f81..5ebd4035e 100644
--- a/src/core/hle/service/time/time_zone_manager.h
+++ b/src/core/hle/service/time/time_zone_manager.h
@@ -29,16 +29,16 @@ public:
29 is_initialized = true; 29 is_initialized = true;
30 } 30 }
31 31
32 ResultCode SetDeviceLocationNameWithTimeZoneRule(const std::string& location_name, 32 Result SetDeviceLocationNameWithTimeZoneRule(const std::string& location_name,
33 FileSys::VirtualFile& vfs_file); 33 FileSys::VirtualFile& vfs_file);
34 ResultCode SetUpdatedTime(const Clock::SteadyClockTimePoint& value); 34 Result SetUpdatedTime(const Clock::SteadyClockTimePoint& value);
35 ResultCode GetDeviceLocationName(TimeZone::LocationName& value) const; 35 Result GetDeviceLocationName(TimeZone::LocationName& value) const;
36 ResultCode ToCalendarTime(const TimeZoneRule& rules, s64 time, CalendarInfo& calendar) const; 36 Result ToCalendarTime(const TimeZoneRule& rules, s64 time, CalendarInfo& calendar) const;
37 ResultCode ToCalendarTimeWithMyRules(s64 time, CalendarInfo& calendar) const; 37 Result ToCalendarTimeWithMyRules(s64 time, CalendarInfo& calendar) const;
38 ResultCode ParseTimeZoneRuleBinary(TimeZoneRule& rules, FileSys::VirtualFile& vfs_file) const; 38 Result ParseTimeZoneRuleBinary(TimeZoneRule& rules, FileSys::VirtualFile& vfs_file) const;
39 ResultCode ToPosixTime(const TimeZoneRule& rules, const CalendarTime& calendar_time, 39 Result ToPosixTime(const TimeZoneRule& rules, const CalendarTime& calendar_time,
40 s64& posix_time) const; 40 s64& posix_time) const;
41 ResultCode ToPosixTimeWithMyRule(const CalendarTime& calendar_time, s64& posix_time) const; 41 Result ToPosixTimeWithMyRule(const CalendarTime& calendar_time, s64& posix_time) const;
42 42
43private: 43private:
44 bool is_initialized{}; 44 bool is_initialized{};
diff --git a/src/core/hle/service/time/time_zone_service.cpp b/src/core/hle/service/time/time_zone_service.cpp
index cbf0ef6fa..961040bfc 100644
--- a/src/core/hle/service/time/time_zone_service.cpp
+++ b/src/core/hle/service/time/time_zone_service.cpp
@@ -32,7 +32,7 @@ void ITimeZoneService::GetDeviceLocationName(Kernel::HLERequestContext& ctx) {
32 LOG_DEBUG(Service_Time, "called"); 32 LOG_DEBUG(Service_Time, "called");
33 33
34 TimeZone::LocationName location_name{}; 34 TimeZone::LocationName location_name{};
35 if (const ResultCode result{ 35 if (const Result result{
36 time_zone_content_manager.GetTimeZoneManager().GetDeviceLocationName(location_name)}; 36 time_zone_content_manager.GetTimeZoneManager().GetDeviceLocationName(location_name)};
37 result != ResultSuccess) { 37 result != ResultSuccess) {
38 IPC::ResponseBuilder rb{ctx, 2}; 38 IPC::ResponseBuilder rb{ctx, 2};
@@ -61,7 +61,7 @@ void ITimeZoneService::LoadTimeZoneRule(Kernel::HLERequestContext& ctx) {
61 LOG_DEBUG(Service_Time, "called, location_name={}", location_name); 61 LOG_DEBUG(Service_Time, "called, location_name={}", location_name);
62 62
63 TimeZone::TimeZoneRule time_zone_rule{}; 63 TimeZone::TimeZoneRule time_zone_rule{};
64 if (const ResultCode result{ 64 if (const Result result{
65 time_zone_content_manager.LoadTimeZoneRule(time_zone_rule, location_name)}; 65 time_zone_content_manager.LoadTimeZoneRule(time_zone_rule, location_name)};
66 result != ResultSuccess) { 66 result != ResultSuccess) {
67 IPC::ResponseBuilder rb{ctx, 2}; 67 IPC::ResponseBuilder rb{ctx, 2};
@@ -88,7 +88,7 @@ void ITimeZoneService::ToCalendarTime(Kernel::HLERequestContext& ctx) {
88 std::memcpy(&time_zone_rule, buffer.data(), buffer.size()); 88 std::memcpy(&time_zone_rule, buffer.data(), buffer.size());
89 89
90 TimeZone::CalendarInfo calendar_info{}; 90 TimeZone::CalendarInfo calendar_info{};
91 if (const ResultCode result{time_zone_content_manager.GetTimeZoneManager().ToCalendarTime( 91 if (const Result result{time_zone_content_manager.GetTimeZoneManager().ToCalendarTime(
92 time_zone_rule, posix_time, calendar_info)}; 92 time_zone_rule, posix_time, calendar_info)};
93 result != ResultSuccess) { 93 result != ResultSuccess) {
94 IPC::ResponseBuilder rb{ctx, 2}; 94 IPC::ResponseBuilder rb{ctx, 2};
@@ -108,7 +108,7 @@ void ITimeZoneService::ToCalendarTimeWithMyRule(Kernel::HLERequestContext& ctx)
108 LOG_DEBUG(Service_Time, "called, posix_time=0x{:016X}", posix_time); 108 LOG_DEBUG(Service_Time, "called, posix_time=0x{:016X}", posix_time);
109 109
110 TimeZone::CalendarInfo calendar_info{}; 110 TimeZone::CalendarInfo calendar_info{};
111 if (const ResultCode result{ 111 if (const Result result{
112 time_zone_content_manager.GetTimeZoneManager().ToCalendarTimeWithMyRules( 112 time_zone_content_manager.GetTimeZoneManager().ToCalendarTimeWithMyRules(
113 posix_time, calendar_info)}; 113 posix_time, calendar_info)};
114 result != ResultSuccess) { 114 result != ResultSuccess) {
@@ -131,7 +131,7 @@ void ITimeZoneService::ToPosixTime(Kernel::HLERequestContext& ctx) {
131 std::memcpy(&time_zone_rule, ctx.ReadBuffer().data(), sizeof(TimeZone::TimeZoneRule)); 131 std::memcpy(&time_zone_rule, ctx.ReadBuffer().data(), sizeof(TimeZone::TimeZoneRule));
132 132
133 s64 posix_time{}; 133 s64 posix_time{};
134 if (const ResultCode result{time_zone_content_manager.GetTimeZoneManager().ToPosixTime( 134 if (const Result result{time_zone_content_manager.GetTimeZoneManager().ToPosixTime(
135 time_zone_rule, calendar_time, posix_time)}; 135 time_zone_rule, calendar_time, posix_time)};
136 result != ResultSuccess) { 136 result != ResultSuccess) {
137 IPC::ResponseBuilder rb{ctx, 2}; 137 IPC::ResponseBuilder rb{ctx, 2};
@@ -154,9 +154,8 @@ void ITimeZoneService::ToPosixTimeWithMyRule(Kernel::HLERequestContext& ctx) {
154 const auto calendar_time{rp.PopRaw<TimeZone::CalendarTime>()}; 154 const auto calendar_time{rp.PopRaw<TimeZone::CalendarTime>()};
155 155
156 s64 posix_time{}; 156 s64 posix_time{};
157 if (const ResultCode result{ 157 if (const Result result{time_zone_content_manager.GetTimeZoneManager().ToPosixTimeWithMyRule(
158 time_zone_content_manager.GetTimeZoneManager().ToPosixTimeWithMyRule(calendar_time, 158 calendar_time, posix_time)};
159 posix_time)};
160 result != ResultSuccess) { 159 result != ResultSuccess) {
161 IPC::ResponseBuilder rb{ctx, 2}; 160 IPC::ResponseBuilder rb{ctx, 2};
162 rb.Push(result); 161 rb.Push(result);
diff --git a/src/core/hle/service/vi/vi.cpp b/src/core/hle/service/vi/vi.cpp
index a7b53d7dc..546879648 100644
--- a/src/core/hle/service/vi/vi.cpp
+++ b/src/core/hle/service/vi/vi.cpp
@@ -34,10 +34,10 @@
34 34
35namespace Service::VI { 35namespace Service::VI {
36 36
37constexpr ResultCode ERR_OPERATION_FAILED{ErrorModule::VI, 1}; 37constexpr Result ERR_OPERATION_FAILED{ErrorModule::VI, 1};
38constexpr ResultCode ERR_PERMISSION_DENIED{ErrorModule::VI, 5}; 38constexpr Result ERR_PERMISSION_DENIED{ErrorModule::VI, 5};
39constexpr ResultCode ERR_UNSUPPORTED{ErrorModule::VI, 6}; 39constexpr Result ERR_UNSUPPORTED{ErrorModule::VI, 6};
40constexpr ResultCode ERR_NOT_FOUND{ErrorModule::VI, 7}; 40constexpr Result ERR_NOT_FOUND{ErrorModule::VI, 7};
41 41
42struct DisplayInfo { 42struct DisplayInfo {
43 /// The name of this particular display. 43 /// The name of this particular display.
diff --git a/src/core/reporter.cpp b/src/core/reporter.cpp
index fa2729f54..6e21296f6 100644
--- a/src/core/reporter.cpp
+++ b/src/core/reporter.cpp
@@ -63,7 +63,7 @@ json GetYuzuVersionData() {
63 }; 63 };
64} 64}
65 65
66json GetReportCommonData(u64 title_id, ResultCode result, const std::string& timestamp, 66json GetReportCommonData(u64 title_id, Result result, const std::string& timestamp,
67 std::optional<u128> user_id = {}) { 67 std::optional<u128> user_id = {}) {
68 auto out = json{ 68 auto out = json{
69 {"title_id", fmt::format("{:016X}", title_id)}, 69 {"title_id", fmt::format("{:016X}", title_id)},
@@ -198,8 +198,8 @@ Reporter::Reporter(System& system_) : system(system_) {
198 198
199Reporter::~Reporter() = default; 199Reporter::~Reporter() = default;
200 200
201void Reporter::SaveCrashReport(u64 title_id, ResultCode result, u64 set_flags, u64 entry_point, 201void Reporter::SaveCrashReport(u64 title_id, Result result, u64 set_flags, u64 entry_point, u64 sp,
202 u64 sp, u64 pc, u64 pstate, u64 afsr0, u64 afsr1, u64 esr, u64 far, 202 u64 pc, u64 pstate, u64 afsr0, u64 afsr1, u64 esr, u64 far,
203 const std::array<u64, 31>& registers, 203 const std::array<u64, 31>& registers,
204 const std::array<u64, 32>& backtrace, u32 backtrace_size, 204 const std::array<u64, 32>& backtrace, u32 backtrace_size,
205 const std::string& arch, u32 unk10) const { 205 const std::string& arch, u32 unk10) const {
@@ -338,7 +338,7 @@ void Reporter::SavePlayReport(PlayReportType type, u64 title_id, std::vector<std
338 SaveToFile(std::move(out), GetPath("play_report", title_id, timestamp)); 338 SaveToFile(std::move(out), GetPath("play_report", title_id, timestamp));
339} 339}
340 340
341void Reporter::SaveErrorReport(u64 title_id, ResultCode result, 341void Reporter::SaveErrorReport(u64 title_id, Result result,
342 std::optional<std::string> custom_text_main, 342 std::optional<std::string> custom_text_main,
343 std::optional<std::string> custom_text_detail) const { 343 std::optional<std::string> custom_text_detail) const {
344 if (!IsReportingEnabled()) { 344 if (!IsReportingEnabled()) {
diff --git a/src/core/reporter.h b/src/core/reporter.h
index a5386bc83..68755cbde 100644
--- a/src/core/reporter.h
+++ b/src/core/reporter.h
@@ -9,7 +9,7 @@
9#include <vector> 9#include <vector>
10#include "common/common_types.h" 10#include "common/common_types.h"
11 11
12union ResultCode; 12union Result;
13 13
14namespace Kernel { 14namespace Kernel {
15class HLERequestContext; 15class HLERequestContext;
@@ -29,7 +29,7 @@ public:
29 ~Reporter(); 29 ~Reporter();
30 30
31 // Used by fatal services 31 // Used by fatal services
32 void SaveCrashReport(u64 title_id, ResultCode result, u64 set_flags, u64 entry_point, u64 sp, 32 void SaveCrashReport(u64 title_id, Result result, u64 set_flags, u64 entry_point, u64 sp,
33 u64 pc, u64 pstate, u64 afsr0, u64 afsr1, u64 esr, u64 far, 33 u64 pc, u64 pstate, u64 afsr0, u64 afsr1, u64 esr, u64 far,
34 const std::array<u64, 31>& registers, const std::array<u64, 32>& backtrace, 34 const std::array<u64, 31>& registers, const std::array<u64, 32>& backtrace,
35 u32 backtrace_size, const std::string& arch, u32 unk10) const; 35 u32 backtrace_size, const std::string& arch, u32 unk10) const;
@@ -60,7 +60,7 @@ public:
60 std::optional<u64> process_id = {}, std::optional<u128> user_id = {}) const; 60 std::optional<u64> process_id = {}, std::optional<u128> user_id = {}) const;
61 61
62 // Used by error applet 62 // Used by error applet
63 void SaveErrorReport(u64 title_id, ResultCode result, 63 void SaveErrorReport(u64 title_id, Result result,
64 std::optional<std::string> custom_text_main = {}, 64 std::optional<std::string> custom_text_main = {},
65 std::optional<std::string> custom_text_detail = {}) const; 65 std::optional<std::string> custom_text_detail = {}) const;
66 66
diff --git a/src/tests/common/fibers.cpp b/src/tests/common/fibers.cpp
index cfc84d423..4e29f9199 100644
--- a/src/tests/common/fibers.cpp
+++ b/src/tests/common/fibers.cpp
@@ -43,7 +43,15 @@ class TestControl1 {
43public: 43public:
44 TestControl1() = default; 44 TestControl1() = default;
45 45
46 void DoWork(); 46 void DoWork() {
47 const u32 id = thread_ids.Get();
48 u32 value = items[id];
49 for (u32 i = 0; i < id; i++) {
50 value++;
51 }
52 results[id] = value;
53 Fiber::YieldTo(work_fibers[id], *thread_fibers[id]);
54 }
47 55
48 void ExecuteThread(u32 id); 56 void ExecuteThread(u32 id);
49 57
@@ -54,35 +62,16 @@ public:
54 std::vector<u32> results; 62 std::vector<u32> results;
55}; 63};
56 64
57static void WorkControl1(void* control) {
58 auto* test_control = static_cast<TestControl1*>(control);
59 test_control->DoWork();
60}
61
62void TestControl1::DoWork() {
63 const u32 id = thread_ids.Get();
64 u32 value = items[id];
65 for (u32 i = 0; i < id; i++) {
66 value++;
67 }
68 results[id] = value;
69 Fiber::YieldTo(work_fibers[id], *thread_fibers[id]);
70}
71
72void TestControl1::ExecuteThread(u32 id) { 65void TestControl1::ExecuteThread(u32 id) {
73 thread_ids.Register(id); 66 thread_ids.Register(id);
74 auto thread_fiber = Fiber::ThreadToFiber(); 67 auto thread_fiber = Fiber::ThreadToFiber();
75 thread_fibers[id] = thread_fiber; 68 thread_fibers[id] = thread_fiber;
76 work_fibers[id] = std::make_shared<Fiber>(std::function<void(void*)>{WorkControl1}, this); 69 work_fibers[id] = std::make_shared<Fiber>([this] { DoWork(); });
77 items[id] = rand() % 256; 70 items[id] = rand() % 256;
78 Fiber::YieldTo(thread_fibers[id], *work_fibers[id]); 71 Fiber::YieldTo(thread_fibers[id], *work_fibers[id]);
79 thread_fibers[id]->Exit(); 72 thread_fibers[id]->Exit();
80} 73}
81 74
82static void ThreadStart1(u32 id, TestControl1& test_control) {
83 test_control.ExecuteThread(id);
84}
85
86/** This test checks for fiber setup configuration and validates that fibers are 75/** This test checks for fiber setup configuration and validates that fibers are
87 * doing all the work required. 76 * doing all the work required.
88 */ 77 */
@@ -95,7 +84,7 @@ TEST_CASE("Fibers::Setup", "[common]") {
95 test_control.results.resize(num_threads, 0); 84 test_control.results.resize(num_threads, 0);
96 std::vector<std::thread> threads; 85 std::vector<std::thread> threads;
97 for (u32 i = 0; i < num_threads; i++) { 86 for (u32 i = 0; i < num_threads; i++) {
98 threads.emplace_back(ThreadStart1, i, std::ref(test_control)); 87 threads.emplace_back([&test_control, i] { test_control.ExecuteThread(i); });
99 } 88 }
100 for (u32 i = 0; i < num_threads; i++) { 89 for (u32 i = 0; i < num_threads; i++) {
101 threads[i].join(); 90 threads[i].join();
@@ -167,21 +156,6 @@ public:
167 std::shared_ptr<Common::Fiber> fiber3; 156 std::shared_ptr<Common::Fiber> fiber3;
168}; 157};
169 158
170static void WorkControl2_1(void* control) {
171 auto* test_control = static_cast<TestControl2*>(control);
172 test_control->DoWork1();
173}
174
175static void WorkControl2_2(void* control) {
176 auto* test_control = static_cast<TestControl2*>(control);
177 test_control->DoWork2();
178}
179
180static void WorkControl2_3(void* control) {
181 auto* test_control = static_cast<TestControl2*>(control);
182 test_control->DoWork3();
183}
184
185void TestControl2::ExecuteThread(u32 id) { 159void TestControl2::ExecuteThread(u32 id) {
186 thread_ids.Register(id); 160 thread_ids.Register(id);
187 auto thread_fiber = Fiber::ThreadToFiber(); 161 auto thread_fiber = Fiber::ThreadToFiber();
@@ -193,18 +167,6 @@ void TestControl2::Exit() {
193 thread_fibers[id]->Exit(); 167 thread_fibers[id]->Exit();
194} 168}
195 169
196static void ThreadStart2_1(u32 id, TestControl2& test_control) {
197 test_control.ExecuteThread(id);
198 test_control.CallFiber1();
199 test_control.Exit();
200}
201
202static void ThreadStart2_2(u32 id, TestControl2& test_control) {
203 test_control.ExecuteThread(id);
204 test_control.CallFiber2();
205 test_control.Exit();
206}
207
208/** This test checks for fiber thread exchange configuration and validates that fibers are 170/** This test checks for fiber thread exchange configuration and validates that fibers are
209 * that a fiber has been successfully transferred from one thread to another and that the TLS 171 * that a fiber has been successfully transferred from one thread to another and that the TLS
210 * region of the thread is kept while changing fibers. 172 * region of the thread is kept while changing fibers.
@@ -212,14 +174,19 @@ static void ThreadStart2_2(u32 id, TestControl2& test_control) {
212TEST_CASE("Fibers::InterExchange", "[common]") { 174TEST_CASE("Fibers::InterExchange", "[common]") {
213 TestControl2 test_control{}; 175 TestControl2 test_control{};
214 test_control.thread_fibers.resize(2); 176 test_control.thread_fibers.resize(2);
215 test_control.fiber1 = 177 test_control.fiber1 = std::make_shared<Fiber>([&test_control] { test_control.DoWork1(); });
216 std::make_shared<Fiber>(std::function<void(void*)>{WorkControl2_1}, &test_control); 178 test_control.fiber2 = std::make_shared<Fiber>([&test_control] { test_control.DoWork2(); });
217 test_control.fiber2 = 179 test_control.fiber3 = std::make_shared<Fiber>([&test_control] { test_control.DoWork3(); });
218 std::make_shared<Fiber>(std::function<void(void*)>{WorkControl2_2}, &test_control); 180 std::thread thread1{[&test_control] {
219 test_control.fiber3 = 181 test_control.ExecuteThread(0);
220 std::make_shared<Fiber>(std::function<void(void*)>{WorkControl2_3}, &test_control); 182 test_control.CallFiber1();
221 std::thread thread1(ThreadStart2_1, 0, std::ref(test_control)); 183 test_control.Exit();
222 std::thread thread2(ThreadStart2_2, 1, std::ref(test_control)); 184 }};
185 std::thread thread2{[&test_control] {
186 test_control.ExecuteThread(1);
187 test_control.CallFiber2();
188 test_control.Exit();
189 }};
223 thread1.join(); 190 thread1.join();
224 thread2.join(); 191 thread2.join();
225 REQUIRE(test_control.assert1); 192 REQUIRE(test_control.assert1);
@@ -270,16 +237,6 @@ public:
270 std::shared_ptr<Common::Fiber> fiber2; 237 std::shared_ptr<Common::Fiber> fiber2;
271}; 238};
272 239
273static void WorkControl3_1(void* control) {
274 auto* test_control = static_cast<TestControl3*>(control);
275 test_control->DoWork1();
276}
277
278static void WorkControl3_2(void* control) {
279 auto* test_control = static_cast<TestControl3*>(control);
280 test_control->DoWork2();
281}
282
283void TestControl3::ExecuteThread(u32 id) { 240void TestControl3::ExecuteThread(u32 id) {
284 thread_ids.Register(id); 241 thread_ids.Register(id);
285 auto thread_fiber = Fiber::ThreadToFiber(); 242 auto thread_fiber = Fiber::ThreadToFiber();
@@ -291,12 +248,6 @@ void TestControl3::Exit() {
291 thread_fibers[id]->Exit(); 248 thread_fibers[id]->Exit();
292} 249}
293 250
294static void ThreadStart3(u32 id, TestControl3& test_control) {
295 test_control.ExecuteThread(id);
296 test_control.CallFiber1();
297 test_control.Exit();
298}
299
300/** This test checks for one two threads racing for starting the same fiber. 251/** This test checks for one two threads racing for starting the same fiber.
301 * It checks execution occurred in an ordered manner and by no time there were 252 * It checks execution occurred in an ordered manner and by no time there were
302 * two contexts at the same time. 253 * two contexts at the same time.
@@ -304,12 +255,15 @@ static void ThreadStart3(u32 id, TestControl3& test_control) {
304TEST_CASE("Fibers::StartRace", "[common]") { 255TEST_CASE("Fibers::StartRace", "[common]") {
305 TestControl3 test_control{}; 256 TestControl3 test_control{};
306 test_control.thread_fibers.resize(2); 257 test_control.thread_fibers.resize(2);
307 test_control.fiber1 = 258 test_control.fiber1 = std::make_shared<Fiber>([&test_control] { test_control.DoWork1(); });
308 std::make_shared<Fiber>(std::function<void(void*)>{WorkControl3_1}, &test_control); 259 test_control.fiber2 = std::make_shared<Fiber>([&test_control] { test_control.DoWork2(); });
309 test_control.fiber2 = 260 const auto race_function{[&test_control](u32 id) {
310 std::make_shared<Fiber>(std::function<void(void*)>{WorkControl3_2}, &test_control); 261 test_control.ExecuteThread(id);
311 std::thread thread1(ThreadStart3, 0, std::ref(test_control)); 262 test_control.CallFiber1();
312 std::thread thread2(ThreadStart3, 1, std::ref(test_control)); 263 test_control.Exit();
264 }};
265 std::thread thread1([&] { race_function(0); });
266 std::thread thread2([&] { race_function(1); });
313 thread1.join(); 267 thread1.join();
314 thread2.join(); 268 thread2.join();
315 REQUIRE(test_control.value1 == 1); 269 REQUIRE(test_control.value1 == 1);
@@ -319,12 +273,10 @@ TEST_CASE("Fibers::StartRace", "[common]") {
319 273
320class TestControl4; 274class TestControl4;
321 275
322static void WorkControl4(void* control);
323
324class TestControl4 { 276class TestControl4 {
325public: 277public:
326 TestControl4() { 278 TestControl4() {
327 fiber1 = std::make_shared<Fiber>(std::function<void(void*)>{WorkControl4}, this); 279 fiber1 = std::make_shared<Fiber>([this] { DoWork(); });
328 goal_reached = false; 280 goal_reached = false;
329 rewinded = false; 281 rewinded = false;
330 } 282 }
@@ -336,7 +288,7 @@ public:
336 } 288 }
337 289
338 void DoWork() { 290 void DoWork() {
339 fiber1->SetRewindPoint(std::function<void(void*)>{WorkControl4}, this); 291 fiber1->SetRewindPoint([this] { DoWork(); });
340 if (rewinded) { 292 if (rewinded) {
341 goal_reached = true; 293 goal_reached = true;
342 Fiber::YieldTo(fiber1, *thread_fiber); 294 Fiber::YieldTo(fiber1, *thread_fiber);
@@ -351,11 +303,6 @@ public:
351 bool rewinded; 303 bool rewinded;
352}; 304};
353 305
354static void WorkControl4(void* control) {
355 auto* test_control = static_cast<TestControl4*>(control);
356 test_control->DoWork();
357}
358
359TEST_CASE("Fibers::Rewind", "[common]") { 306TEST_CASE("Fibers::Rewind", "[common]") {
360 TestControl4 test_control{}; 307 TestControl4 test_control{};
361 test_control.Execute(); 308 test_control.Execute();
diff --git a/src/tests/core/core_timing.cpp b/src/tests/core/core_timing.cpp
index 8358d36b5..e687416a8 100644
--- a/src/tests/core/core_timing.cpp
+++ b/src/tests/core/core_timing.cpp
@@ -8,6 +8,7 @@
8#include <chrono> 8#include <chrono>
9#include <cstdlib> 9#include <cstdlib>
10#include <memory> 10#include <memory>
11#include <mutex>
11#include <string> 12#include <string>
12 13
13#include "core/core.h" 14#include "core/core.h"
@@ -21,13 +22,14 @@ std::array<s64, 5> delays{};
21 22
22std::bitset<CB_IDS.size()> callbacks_ran_flags; 23std::bitset<CB_IDS.size()> callbacks_ran_flags;
23u64 expected_callback = 0; 24u64 expected_callback = 0;
25std::mutex control_mutex;
24 26
25template <unsigned int IDX> 27template <unsigned int IDX>
26void HostCallbackTemplate(std::uintptr_t user_data, std::chrono::nanoseconds ns_late) { 28void HostCallbackTemplate(std::uintptr_t user_data, std::chrono::nanoseconds ns_late) {
29 std::unique_lock<std::mutex> lk(control_mutex);
27 static_assert(IDX < CB_IDS.size(), "IDX out of range"); 30 static_assert(IDX < CB_IDS.size(), "IDX out of range");
28 callbacks_ran_flags.set(IDX); 31 callbacks_ran_flags.set(IDX);
29 REQUIRE(CB_IDS[IDX] == user_data); 32 REQUIRE(CB_IDS[IDX] == user_data);
30 REQUIRE(CB_IDS[IDX] == CB_IDS[calls_order[expected_callback]]);
31 delays[IDX] = ns_late.count(); 33 delays[IDX] = ns_late.count();
32 ++expected_callback; 34 ++expected_callback;
33} 35}
diff --git a/src/video_core/renderer_vulkan/blit_image.cpp b/src/video_core/renderer_vulkan/blit_image.cpp
index 5d35366f7..3f2b139e0 100644
--- a/src/video_core/renderer_vulkan/blit_image.cpp
+++ b/src/video_core/renderer_vulkan/blit_image.cpp
@@ -349,7 +349,7 @@ VkExtent2D GetConversionExtent(const ImageView& src_image_view) {
349} 349}
350} // Anonymous namespace 350} // Anonymous namespace
351 351
352BlitImageHelper::BlitImageHelper(const Device& device_, VKScheduler& scheduler_, 352BlitImageHelper::BlitImageHelper(const Device& device_, Scheduler& scheduler_,
353 StateTracker& state_tracker_, DescriptorPool& descriptor_pool) 353 StateTracker& state_tracker_, DescriptorPool& descriptor_pool)
354 : device{device_}, scheduler{scheduler_}, state_tracker{state_tracker_}, 354 : device{device_}, scheduler{scheduler_}, state_tracker{state_tracker_},
355 one_texture_set_layout(device.GetLogical().CreateDescriptorSetLayout( 355 one_texture_set_layout(device.GetLogical().CreateDescriptorSetLayout(
diff --git a/src/video_core/renderer_vulkan/blit_image.h b/src/video_core/renderer_vulkan/blit_image.h
index 21e9d7d69..5df679fb4 100644
--- a/src/video_core/renderer_vulkan/blit_image.h
+++ b/src/video_core/renderer_vulkan/blit_image.h
@@ -16,7 +16,7 @@ class Device;
16class Framebuffer; 16class Framebuffer;
17class ImageView; 17class ImageView;
18class StateTracker; 18class StateTracker;
19class VKScheduler; 19class Scheduler;
20 20
21struct BlitImagePipelineKey { 21struct BlitImagePipelineKey {
22 constexpr auto operator<=>(const BlitImagePipelineKey&) const noexcept = default; 22 constexpr auto operator<=>(const BlitImagePipelineKey&) const noexcept = default;
@@ -27,7 +27,7 @@ struct BlitImagePipelineKey {
27 27
28class BlitImageHelper { 28class BlitImageHelper {
29public: 29public:
30 explicit BlitImageHelper(const Device& device, VKScheduler& scheduler, 30 explicit BlitImageHelper(const Device& device, Scheduler& scheduler,
31 StateTracker& state_tracker, DescriptorPool& descriptor_pool); 31 StateTracker& state_tracker, DescriptorPool& descriptor_pool);
32 ~BlitImageHelper(); 32 ~BlitImageHelper();
33 33
@@ -82,7 +82,7 @@ private:
82 vk::ShaderModule& module); 82 vk::ShaderModule& module);
83 83
84 const Device& device; 84 const Device& device;
85 VKScheduler& scheduler; 85 Scheduler& scheduler;
86 StateTracker& state_tracker; 86 StateTracker& state_tracker;
87 87
88 vk::DescriptorSetLayout one_texture_set_layout; 88 vk::DescriptorSetLayout one_texture_set_layout;
diff --git a/src/video_core/renderer_vulkan/pipeline_helper.h b/src/video_core/renderer_vulkan/pipeline_helper.h
index 9d676612c..b24f3424a 100644
--- a/src/video_core/renderer_vulkan/pipeline_helper.h
+++ b/src/video_core/renderer_vulkan/pipeline_helper.h
@@ -168,7 +168,7 @@ private:
168}; 168};
169 169
170inline void PushImageDescriptors(TextureCache& texture_cache, 170inline void PushImageDescriptors(TextureCache& texture_cache,
171 VKUpdateDescriptorQueue& update_descriptor_queue, 171 UpdateDescriptorQueue& update_descriptor_queue,
172 const Shader::Info& info, RescalingPushConstant& rescaling, 172 const Shader::Info& info, RescalingPushConstant& rescaling,
173 const VkSampler*& samplers, 173 const VkSampler*& samplers,
174 const VideoCommon::ImageViewInOut*& views) { 174 const VideoCommon::ImageViewInOut*& views) {
diff --git a/src/video_core/renderer_vulkan/renderer_vulkan.h b/src/video_core/renderer_vulkan/renderer_vulkan.h
index 8a8cb347c..e7bfecb20 100644
--- a/src/video_core/renderer_vulkan/renderer_vulkan.h
+++ b/src/video_core/renderer_vulkan/renderer_vulkan.h
@@ -65,14 +65,14 @@ private:
65 vk::DebugUtilsMessenger debug_callback; 65 vk::DebugUtilsMessenger debug_callback;
66 vk::SurfaceKHR surface; 66 vk::SurfaceKHR surface;
67 67
68 VKScreenInfo screen_info; 68 ScreenInfo screen_info;
69 69
70 Device device; 70 Device device;
71 MemoryAllocator memory_allocator; 71 MemoryAllocator memory_allocator;
72 StateTracker state_tracker; 72 StateTracker state_tracker;
73 VKScheduler scheduler; 73 Scheduler scheduler;
74 VKSwapchain swapchain; 74 Swapchain swapchain;
75 VKBlitScreen blit_screen; 75 BlitScreen blit_screen;
76 RasterizerVulkan rasterizer; 76 RasterizerVulkan rasterizer;
77}; 77};
78 78
diff --git a/src/video_core/renderer_vulkan/vk_blit_screen.cpp b/src/video_core/renderer_vulkan/vk_blit_screen.cpp
index 289bfd7b6..1ec8392e1 100644
--- a/src/video_core/renderer_vulkan/vk_blit_screen.cpp
+++ b/src/video_core/renderer_vulkan/vk_blit_screen.cpp
@@ -108,7 +108,7 @@ VkFormat GetFormat(const Tegra::FramebufferConfig& framebuffer) {
108 108
109} // Anonymous namespace 109} // Anonymous namespace
110 110
111struct VKBlitScreen::BufferData { 111struct BlitScreen::BufferData {
112 struct { 112 struct {
113 std::array<f32, 4 * 4> modelview_matrix; 113 std::array<f32, 4 * 4> modelview_matrix;
114 } uniform; 114 } uniform;
@@ -118,10 +118,9 @@ struct VKBlitScreen::BufferData {
118 // Unaligned image data goes here 118 // Unaligned image data goes here
119}; 119};
120 120
121VKBlitScreen::VKBlitScreen(Core::Memory::Memory& cpu_memory_, 121BlitScreen::BlitScreen(Core::Memory::Memory& cpu_memory_, Core::Frontend::EmuWindow& render_window_,
122 Core::Frontend::EmuWindow& render_window_, const Device& device_, 122 const Device& device_, MemoryAllocator& memory_allocator_,
123 MemoryAllocator& memory_allocator_, VKSwapchain& swapchain_, 123 Swapchain& swapchain_, Scheduler& scheduler_, const ScreenInfo& screen_info_)
124 VKScheduler& scheduler_, const VKScreenInfo& screen_info_)
125 : cpu_memory{cpu_memory_}, render_window{render_window_}, device{device_}, 124 : cpu_memory{cpu_memory_}, render_window{render_window_}, device{device_},
126 memory_allocator{memory_allocator_}, swapchain{swapchain_}, scheduler{scheduler_}, 125 memory_allocator{memory_allocator_}, swapchain{swapchain_}, scheduler{scheduler_},
127 image_count{swapchain.GetImageCount()}, screen_info{screen_info_} { 126 image_count{swapchain.GetImageCount()}, screen_info{screen_info_} {
@@ -131,16 +130,16 @@ VKBlitScreen::VKBlitScreen(Core::Memory::Memory& cpu_memory_,
131 CreateDynamicResources(); 130 CreateDynamicResources();
132} 131}
133 132
134VKBlitScreen::~VKBlitScreen() = default; 133BlitScreen::~BlitScreen() = default;
135 134
136void VKBlitScreen::Recreate() { 135void BlitScreen::Recreate() {
137 CreateDynamicResources(); 136 CreateDynamicResources();
138} 137}
139 138
140VkSemaphore VKBlitScreen::Draw(const Tegra::FramebufferConfig& framebuffer, 139VkSemaphore BlitScreen::Draw(const Tegra::FramebufferConfig& framebuffer,
141 const VkFramebuffer& host_framebuffer, 140 const VkFramebuffer& host_framebuffer,
142 const Layout::FramebufferLayout layout, VkExtent2D render_area, 141 const Layout::FramebufferLayout layout, VkExtent2D render_area,
143 bool use_accelerated) { 142 bool use_accelerated) {
144 RefreshResources(framebuffer); 143 RefreshResources(framebuffer);
145 144
146 // Finish any pending renderpass 145 // Finish any pending renderpass
@@ -419,20 +418,20 @@ VkSemaphore VKBlitScreen::Draw(const Tegra::FramebufferConfig& framebuffer,
419 return *semaphores[image_index]; 418 return *semaphores[image_index];
420} 419}
421 420
422VkSemaphore VKBlitScreen::DrawToSwapchain(const Tegra::FramebufferConfig& framebuffer, 421VkSemaphore BlitScreen::DrawToSwapchain(const Tegra::FramebufferConfig& framebuffer,
423 bool use_accelerated) { 422 bool use_accelerated) {
424 const std::size_t image_index = swapchain.GetImageIndex(); 423 const std::size_t image_index = swapchain.GetImageIndex();
425 const VkExtent2D render_area = swapchain.GetSize(); 424 const VkExtent2D render_area = swapchain.GetSize();
426 const Layout::FramebufferLayout layout = render_window.GetFramebufferLayout(); 425 const Layout::FramebufferLayout layout = render_window.GetFramebufferLayout();
427 return Draw(framebuffer, *framebuffers[image_index], layout, render_area, use_accelerated); 426 return Draw(framebuffer, *framebuffers[image_index], layout, render_area, use_accelerated);
428} 427}
429 428
430vk::Framebuffer VKBlitScreen::CreateFramebuffer(const VkImageView& image_view, VkExtent2D extent) { 429vk::Framebuffer BlitScreen::CreateFramebuffer(const VkImageView& image_view, VkExtent2D extent) {
431 return CreateFramebuffer(image_view, extent, renderpass); 430 return CreateFramebuffer(image_view, extent, renderpass);
432} 431}
433 432
434vk::Framebuffer VKBlitScreen::CreateFramebuffer(const VkImageView& image_view, VkExtent2D extent, 433vk::Framebuffer BlitScreen::CreateFramebuffer(const VkImageView& image_view, VkExtent2D extent,
435 vk::RenderPass& rd) { 434 vk::RenderPass& rd) {
436 return device.GetLogical().CreateFramebuffer(VkFramebufferCreateInfo{ 435 return device.GetLogical().CreateFramebuffer(VkFramebufferCreateInfo{
437 .sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, 436 .sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,
438 .pNext = nullptr, 437 .pNext = nullptr,
@@ -446,7 +445,7 @@ vk::Framebuffer VKBlitScreen::CreateFramebuffer(const VkImageView& image_view, V
446 }); 445 });
447} 446}
448 447
449void VKBlitScreen::CreateStaticResources() { 448void BlitScreen::CreateStaticResources() {
450 CreateShaders(); 449 CreateShaders();
451 CreateSemaphores(); 450 CreateSemaphores();
452 CreateDescriptorPool(); 451 CreateDescriptorPool();
@@ -456,7 +455,7 @@ void VKBlitScreen::CreateStaticResources() {
456 CreateSampler(); 455 CreateSampler();
457} 456}
458 457
459void VKBlitScreen::CreateDynamicResources() { 458void BlitScreen::CreateDynamicResources() {
460 CreateRenderPass(); 459 CreateRenderPass();
461 CreateFramebuffers(); 460 CreateFramebuffers();
462 CreateGraphicsPipeline(); 461 CreateGraphicsPipeline();
@@ -466,7 +465,7 @@ void VKBlitScreen::CreateDynamicResources() {
466 } 465 }
467} 466}
468 467
469void VKBlitScreen::RefreshResources(const Tegra::FramebufferConfig& framebuffer) { 468void BlitScreen::RefreshResources(const Tegra::FramebufferConfig& framebuffer) {
470 if (Settings::values.scaling_filter.GetValue() == Settings::ScalingFilter::Fsr) { 469 if (Settings::values.scaling_filter.GetValue() == Settings::ScalingFilter::Fsr) {
471 if (!fsr) { 470 if (!fsr) {
472 CreateFSR(); 471 CreateFSR();
@@ -486,7 +485,7 @@ void VKBlitScreen::RefreshResources(const Tegra::FramebufferConfig& framebuffer)
486 CreateRawImages(framebuffer); 485 CreateRawImages(framebuffer);
487} 486}
488 487
489void VKBlitScreen::CreateShaders() { 488void BlitScreen::CreateShaders() {
490 vertex_shader = BuildShader(device, VULKAN_PRESENT_VERT_SPV); 489 vertex_shader = BuildShader(device, VULKAN_PRESENT_VERT_SPV);
491 fxaa_vertex_shader = BuildShader(device, FXAA_VERT_SPV); 490 fxaa_vertex_shader = BuildShader(device, FXAA_VERT_SPV);
492 fxaa_fragment_shader = BuildShader(device, FXAA_FRAG_SPV); 491 fxaa_fragment_shader = BuildShader(device, FXAA_FRAG_SPV);
@@ -500,12 +499,12 @@ void VKBlitScreen::CreateShaders() {
500 } 499 }
501} 500}
502 501
503void VKBlitScreen::CreateSemaphores() { 502void BlitScreen::CreateSemaphores() {
504 semaphores.resize(image_count); 503 semaphores.resize(image_count);
505 std::ranges::generate(semaphores, [this] { return device.GetLogical().CreateSemaphore(); }); 504 std::ranges::generate(semaphores, [this] { return device.GetLogical().CreateSemaphore(); });
506} 505}
507 506
508void VKBlitScreen::CreateDescriptorPool() { 507void BlitScreen::CreateDescriptorPool() {
509 const std::array<VkDescriptorPoolSize, 2> pool_sizes{{ 508 const std::array<VkDescriptorPoolSize, 2> pool_sizes{{
510 { 509 {
511 .type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 510 .type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
@@ -545,11 +544,11 @@ void VKBlitScreen::CreateDescriptorPool() {
545 aa_descriptor_pool = device.GetLogical().CreateDescriptorPool(ci_aa); 544 aa_descriptor_pool = device.GetLogical().CreateDescriptorPool(ci_aa);
546} 545}
547 546
548void VKBlitScreen::CreateRenderPass() { 547void BlitScreen::CreateRenderPass() {
549 renderpass = CreateRenderPassImpl(swapchain.GetImageViewFormat()); 548 renderpass = CreateRenderPassImpl(swapchain.GetImageViewFormat());
550} 549}
551 550
552vk::RenderPass VKBlitScreen::CreateRenderPassImpl(VkFormat format, bool is_present) { 551vk::RenderPass BlitScreen::CreateRenderPassImpl(VkFormat format, bool is_present) {
553 const VkAttachmentDescription color_attachment{ 552 const VkAttachmentDescription color_attachment{
554 .flags = 0, 553 .flags = 0,
555 .format = format, 554 .format = format,
@@ -605,7 +604,7 @@ vk::RenderPass VKBlitScreen::CreateRenderPassImpl(VkFormat format, bool is_prese
605 return device.GetLogical().CreateRenderPass(renderpass_ci); 604 return device.GetLogical().CreateRenderPass(renderpass_ci);
606} 605}
607 606
608void VKBlitScreen::CreateDescriptorSetLayout() { 607void BlitScreen::CreateDescriptorSetLayout() {
609 const std::array<VkDescriptorSetLayoutBinding, 2> layout_bindings{{ 608 const std::array<VkDescriptorSetLayoutBinding, 2> layout_bindings{{
610 { 609 {
611 .binding = 0, 610 .binding = 0,
@@ -660,7 +659,7 @@ void VKBlitScreen::CreateDescriptorSetLayout() {
660 aa_descriptor_set_layout = device.GetLogical().CreateDescriptorSetLayout(ci_aa); 659 aa_descriptor_set_layout = device.GetLogical().CreateDescriptorSetLayout(ci_aa);
661} 660}
662 661
663void VKBlitScreen::CreateDescriptorSets() { 662void BlitScreen::CreateDescriptorSets() {
664 const std::vector layouts(image_count, *descriptor_set_layout); 663 const std::vector layouts(image_count, *descriptor_set_layout);
665 const std::vector layouts_aa(image_count, *aa_descriptor_set_layout); 664 const std::vector layouts_aa(image_count, *aa_descriptor_set_layout);
666 665
@@ -684,7 +683,7 @@ void VKBlitScreen::CreateDescriptorSets() {
684 aa_descriptor_sets = aa_descriptor_pool.Allocate(ai_aa); 683 aa_descriptor_sets = aa_descriptor_pool.Allocate(ai_aa);
685} 684}
686 685
687void VKBlitScreen::CreatePipelineLayout() { 686void BlitScreen::CreatePipelineLayout() {
688 const VkPipelineLayoutCreateInfo ci{ 687 const VkPipelineLayoutCreateInfo ci{
689 .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, 688 .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
690 .pNext = nullptr, 689 .pNext = nullptr,
@@ -707,7 +706,7 @@ void VKBlitScreen::CreatePipelineLayout() {
707 aa_pipeline_layout = device.GetLogical().CreatePipelineLayout(ci_aa); 706 aa_pipeline_layout = device.GetLogical().CreatePipelineLayout(ci_aa);
708} 707}
709 708
710void VKBlitScreen::CreateGraphicsPipeline() { 709void BlitScreen::CreateGraphicsPipeline() {
711 const std::array<VkPipelineShaderStageCreateInfo, 2> bilinear_shader_stages{{ 710 const std::array<VkPipelineShaderStageCreateInfo, 2> bilinear_shader_stages{{
712 { 711 {
713 .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, 712 .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
@@ -980,7 +979,7 @@ void VKBlitScreen::CreateGraphicsPipeline() {
980 scaleforce_pipeline = device.GetLogical().CreateGraphicsPipeline(scaleforce_pipeline_ci); 979 scaleforce_pipeline = device.GetLogical().CreateGraphicsPipeline(scaleforce_pipeline_ci);
981} 980}
982 981
983void VKBlitScreen::CreateSampler() { 982void BlitScreen::CreateSampler() {
984 const VkSamplerCreateInfo ci{ 983 const VkSamplerCreateInfo ci{
985 .sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO, 984 .sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,
986 .pNext = nullptr, 985 .pNext = nullptr,
@@ -1027,7 +1026,7 @@ void VKBlitScreen::CreateSampler() {
1027 nn_sampler = device.GetLogical().CreateSampler(ci_nn); 1026 nn_sampler = device.GetLogical().CreateSampler(ci_nn);
1028} 1027}
1029 1028
1030void VKBlitScreen::CreateFramebuffers() { 1029void BlitScreen::CreateFramebuffers() {
1031 const VkExtent2D size{swapchain.GetSize()}; 1030 const VkExtent2D size{swapchain.GetSize()};
1032 framebuffers.resize(image_count); 1031 framebuffers.resize(image_count);
1033 1032
@@ -1037,7 +1036,7 @@ void VKBlitScreen::CreateFramebuffers() {
1037 } 1036 }
1038} 1037}
1039 1038
1040void VKBlitScreen::ReleaseRawImages() { 1039void BlitScreen::ReleaseRawImages() {
1041 for (const u64 tick : resource_ticks) { 1040 for (const u64 tick : resource_ticks) {
1042 scheduler.Wait(tick); 1041 scheduler.Wait(tick);
1043 } 1042 }
@@ -1052,7 +1051,7 @@ void VKBlitScreen::ReleaseRawImages() {
1052 buffer_commit = MemoryCommit{}; 1051 buffer_commit = MemoryCommit{};
1053} 1052}
1054 1053
1055void VKBlitScreen::CreateStagingBuffer(const Tegra::FramebufferConfig& framebuffer) { 1054void BlitScreen::CreateStagingBuffer(const Tegra::FramebufferConfig& framebuffer) {
1056 const VkBufferCreateInfo ci{ 1055 const VkBufferCreateInfo ci{
1057 .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, 1056 .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
1058 .pNext = nullptr, 1057 .pNext = nullptr,
@@ -1069,7 +1068,7 @@ void VKBlitScreen::CreateStagingBuffer(const Tegra::FramebufferConfig& framebuff
1069 buffer_commit = memory_allocator.Commit(buffer, MemoryUsage::Upload); 1068 buffer_commit = memory_allocator.Commit(buffer, MemoryUsage::Upload);
1070} 1069}
1071 1070
1072void VKBlitScreen::CreateRawImages(const Tegra::FramebufferConfig& framebuffer) { 1071void BlitScreen::CreateRawImages(const Tegra::FramebufferConfig& framebuffer) {
1073 raw_images.resize(image_count); 1072 raw_images.resize(image_count);
1074 raw_image_views.resize(image_count); 1073 raw_image_views.resize(image_count);
1075 raw_buffer_commits.resize(image_count); 1074 raw_buffer_commits.resize(image_count);
@@ -1294,8 +1293,8 @@ void VKBlitScreen::CreateRawImages(const Tegra::FramebufferConfig& framebuffer)
1294 aa_pipeline = device.GetLogical().CreateGraphicsPipeline(fxaa_pipeline_ci); 1293 aa_pipeline = device.GetLogical().CreateGraphicsPipeline(fxaa_pipeline_ci);
1295} 1294}
1296 1295
1297void VKBlitScreen::UpdateAADescriptorSet(std::size_t image_index, VkImageView image_view, 1296void BlitScreen::UpdateAADescriptorSet(std::size_t image_index, VkImageView image_view,
1298 bool nn) const { 1297 bool nn) const {
1299 const VkDescriptorImageInfo image_info{ 1298 const VkDescriptorImageInfo image_info{
1300 .sampler = nn ? *nn_sampler : *sampler, 1299 .sampler = nn ? *nn_sampler : *sampler,
1301 .imageView = image_view, 1300 .imageView = image_view,
@@ -1331,8 +1330,8 @@ void VKBlitScreen::UpdateAADescriptorSet(std::size_t image_index, VkImageView im
1331 device.GetLogical().UpdateDescriptorSets(std::array{sampler_write, sampler_write_2}, {}); 1330 device.GetLogical().UpdateDescriptorSets(std::array{sampler_write, sampler_write_2}, {});
1332} 1331}
1333 1332
1334void VKBlitScreen::UpdateDescriptorSet(std::size_t image_index, VkImageView image_view, 1333void BlitScreen::UpdateDescriptorSet(std::size_t image_index, VkImageView image_view,
1335 bool nn) const { 1334 bool nn) const {
1336 const VkDescriptorBufferInfo buffer_info{ 1335 const VkDescriptorBufferInfo buffer_info{
1337 .buffer = *buffer, 1336 .buffer = *buffer,
1338 .offset = offsetof(BufferData, uniform), 1337 .offset = offsetof(BufferData, uniform),
@@ -1374,13 +1373,13 @@ void VKBlitScreen::UpdateDescriptorSet(std::size_t image_index, VkImageView imag
1374 device.GetLogical().UpdateDescriptorSets(std::array{ubo_write, sampler_write}, {}); 1373 device.GetLogical().UpdateDescriptorSets(std::array{ubo_write, sampler_write}, {});
1375} 1374}
1376 1375
1377void VKBlitScreen::SetUniformData(BufferData& data, const Layout::FramebufferLayout layout) const { 1376void BlitScreen::SetUniformData(BufferData& data, const Layout::FramebufferLayout layout) const {
1378 data.uniform.modelview_matrix = 1377 data.uniform.modelview_matrix =
1379 MakeOrthographicMatrix(static_cast<f32>(layout.width), static_cast<f32>(layout.height)); 1378 MakeOrthographicMatrix(static_cast<f32>(layout.width), static_cast<f32>(layout.height));
1380} 1379}
1381 1380
1382void VKBlitScreen::SetVertexData(BufferData& data, const Tegra::FramebufferConfig& framebuffer, 1381void BlitScreen::SetVertexData(BufferData& data, const Tegra::FramebufferConfig& framebuffer,
1383 const Layout::FramebufferLayout layout) const { 1382 const Layout::FramebufferLayout layout) const {
1384 const auto& framebuffer_transform_flags = framebuffer.transform_flags; 1383 const auto& framebuffer_transform_flags = framebuffer.transform_flags;
1385 const auto& framebuffer_crop_rect = framebuffer.crop_rect; 1384 const auto& framebuffer_crop_rect = framebuffer.crop_rect;
1386 1385
@@ -1432,7 +1431,7 @@ void VKBlitScreen::SetVertexData(BufferData& data, const Tegra::FramebufferConfi
1432 data.vertices[3] = ScreenRectVertex(x + w, y + h, texcoords.bottom * scale_u, right * scale_v); 1431 data.vertices[3] = ScreenRectVertex(x + w, y + h, texcoords.bottom * scale_u, right * scale_v);
1433} 1432}
1434 1433
1435void VKBlitScreen::CreateFSR() { 1434void BlitScreen::CreateFSR() {
1436 const auto& layout = render_window.GetFramebufferLayout(); 1435 const auto& layout = render_window.GetFramebufferLayout();
1437 const VkExtent2D fsr_size{ 1436 const VkExtent2D fsr_size{
1438 .width = layout.screen.GetWidth(), 1437 .width = layout.screen.GetWidth(),
@@ -1441,12 +1440,12 @@ void VKBlitScreen::CreateFSR() {
1441 fsr = std::make_unique<FSR>(device, memory_allocator, image_count, fsr_size); 1440 fsr = std::make_unique<FSR>(device, memory_allocator, image_count, fsr_size);
1442} 1441}
1443 1442
1444u64 VKBlitScreen::CalculateBufferSize(const Tegra::FramebufferConfig& framebuffer) const { 1443u64 BlitScreen::CalculateBufferSize(const Tegra::FramebufferConfig& framebuffer) const {
1445 return sizeof(BufferData) + GetSizeInBytes(framebuffer) * image_count; 1444 return sizeof(BufferData) + GetSizeInBytes(framebuffer) * image_count;
1446} 1445}
1447 1446
1448u64 VKBlitScreen::GetRawImageOffset(const Tegra::FramebufferConfig& framebuffer, 1447u64 BlitScreen::GetRawImageOffset(const Tegra::FramebufferConfig& framebuffer,
1449 std::size_t image_index) const { 1448 std::size_t image_index) const {
1450 constexpr auto first_image_offset = static_cast<u64>(sizeof(BufferData)); 1449 constexpr auto first_image_offset = static_cast<u64>(sizeof(BufferData));
1451 return first_image_offset + GetSizeInBytes(framebuffer) * image_index; 1450 return first_image_offset + GetSizeInBytes(framebuffer) * image_index;
1452} 1451}
diff --git a/src/video_core/renderer_vulkan/vk_blit_screen.h b/src/video_core/renderer_vulkan/vk_blit_screen.h
index 1b4260f36..b8c67bef0 100644
--- a/src/video_core/renderer_vulkan/vk_blit_screen.h
+++ b/src/video_core/renderer_vulkan/vk_blit_screen.h
@@ -35,23 +35,22 @@ struct ScreenInfo;
35class Device; 35class Device;
36class FSR; 36class FSR;
37class RasterizerVulkan; 37class RasterizerVulkan;
38class VKScheduler; 38class Scheduler;
39class VKSwapchain; 39class Swapchain;
40 40
41struct VKScreenInfo { 41struct ScreenInfo {
42 VkImageView image_view{}; 42 VkImageView image_view{};
43 u32 width{}; 43 u32 width{};
44 u32 height{}; 44 u32 height{};
45 bool is_srgb{}; 45 bool is_srgb{};
46}; 46};
47 47
48class VKBlitScreen { 48class BlitScreen {
49public: 49public:
50 explicit VKBlitScreen(Core::Memory::Memory& cpu_memory, 50 explicit BlitScreen(Core::Memory::Memory& cpu_memory, Core::Frontend::EmuWindow& render_window,
51 Core::Frontend::EmuWindow& render_window, const Device& device, 51 const Device& device, MemoryAllocator& memory_manager, Swapchain& swapchain,
52 MemoryAllocator& memory_manager, VKSwapchain& swapchain, 52 Scheduler& scheduler, const ScreenInfo& screen_info);
53 VKScheduler& scheduler, const VKScreenInfo& screen_info); 53 ~BlitScreen();
54 ~VKBlitScreen();
55 54
56 void Recreate(); 55 void Recreate();
57 56
@@ -108,10 +107,10 @@ private:
108 Core::Frontend::EmuWindow& render_window; 107 Core::Frontend::EmuWindow& render_window;
109 const Device& device; 108 const Device& device;
110 MemoryAllocator& memory_allocator; 109 MemoryAllocator& memory_allocator;
111 VKSwapchain& swapchain; 110 Swapchain& swapchain;
112 VKScheduler& scheduler; 111 Scheduler& scheduler;
113 const std::size_t image_count; 112 const std::size_t image_count;
114 const VKScreenInfo& screen_info; 113 const ScreenInfo& screen_info;
115 114
116 vk::ShaderModule vertex_shader; 115 vk::ShaderModule vertex_shader;
117 vk::ShaderModule fxaa_vertex_shader; 116 vk::ShaderModule fxaa_vertex_shader;
diff --git a/src/video_core/renderer_vulkan/vk_buffer_cache.cpp b/src/video_core/renderer_vulkan/vk_buffer_cache.cpp
index 450905197..558b8db56 100644
--- a/src/video_core/renderer_vulkan/vk_buffer_cache.cpp
+++ b/src/video_core/renderer_vulkan/vk_buffer_cache.cpp
@@ -124,8 +124,8 @@ VkBufferView Buffer::View(u32 offset, u32 size, VideoCore::Surface::PixelFormat
124} 124}
125 125
126BufferCacheRuntime::BufferCacheRuntime(const Device& device_, MemoryAllocator& memory_allocator_, 126BufferCacheRuntime::BufferCacheRuntime(const Device& device_, MemoryAllocator& memory_allocator_,
127 VKScheduler& scheduler_, StagingBufferPool& staging_pool_, 127 Scheduler& scheduler_, StagingBufferPool& staging_pool_,
128 VKUpdateDescriptorQueue& update_descriptor_queue_, 128 UpdateDescriptorQueue& update_descriptor_queue_,
129 DescriptorPool& descriptor_pool) 129 DescriptorPool& descriptor_pool)
130 : device{device_}, memory_allocator{memory_allocator_}, scheduler{scheduler_}, 130 : device{device_}, memory_allocator{memory_allocator_}, scheduler{scheduler_},
131 staging_pool{staging_pool_}, update_descriptor_queue{update_descriptor_queue_}, 131 staging_pool{staging_pool_}, update_descriptor_queue{update_descriptor_queue_},
diff --git a/src/video_core/renderer_vulkan/vk_buffer_cache.h b/src/video_core/renderer_vulkan/vk_buffer_cache.h
index 6fa618f18..a15c8b39b 100644
--- a/src/video_core/renderer_vulkan/vk_buffer_cache.h
+++ b/src/video_core/renderer_vulkan/vk_buffer_cache.h
@@ -16,7 +16,7 @@ namespace Vulkan {
16 16
17class Device; 17class Device;
18class DescriptorPool; 18class DescriptorPool;
19class VKScheduler; 19class Scheduler;
20 20
21class BufferCacheRuntime; 21class BufferCacheRuntime;
22 22
@@ -58,8 +58,8 @@ class BufferCacheRuntime {
58 58
59public: 59public:
60 explicit BufferCacheRuntime(const Device& device_, MemoryAllocator& memory_manager_, 60 explicit BufferCacheRuntime(const Device& device_, MemoryAllocator& memory_manager_,
61 VKScheduler& scheduler_, StagingBufferPool& staging_pool_, 61 Scheduler& scheduler_, StagingBufferPool& staging_pool_,
62 VKUpdateDescriptorQueue& update_descriptor_queue_, 62 UpdateDescriptorQueue& update_descriptor_queue_,
63 DescriptorPool& descriptor_pool); 63 DescriptorPool& descriptor_pool);
64 64
65 void Finish(); 65 void Finish();
@@ -124,9 +124,9 @@ private:
124 124
125 const Device& device; 125 const Device& device;
126 MemoryAllocator& memory_allocator; 126 MemoryAllocator& memory_allocator;
127 VKScheduler& scheduler; 127 Scheduler& scheduler;
128 StagingBufferPool& staging_pool; 128 StagingBufferPool& staging_pool;
129 VKUpdateDescriptorQueue& update_descriptor_queue; 129 UpdateDescriptorQueue& update_descriptor_queue;
130 130
131 vk::Buffer quad_array_lut; 131 vk::Buffer quad_array_lut;
132 MemoryCommit quad_array_lut_commit; 132 MemoryCommit quad_array_lut_commit;
diff --git a/src/video_core/renderer_vulkan/vk_compute_pass.cpp b/src/video_core/renderer_vulkan/vk_compute_pass.cpp
index 4cba777e6..f17a5ccd6 100644
--- a/src/video_core/renderer_vulkan/vk_compute_pass.cpp
+++ b/src/video_core/renderer_vulkan/vk_compute_pass.cpp
@@ -200,9 +200,9 @@ ComputePass::ComputePass(const Device& device_, DescriptorPool& descriptor_pool,
200 200
201ComputePass::~ComputePass() = default; 201ComputePass::~ComputePass() = default;
202 202
203Uint8Pass::Uint8Pass(const Device& device_, VKScheduler& scheduler_, 203Uint8Pass::Uint8Pass(const Device& device_, Scheduler& scheduler_, DescriptorPool& descriptor_pool,
204 DescriptorPool& descriptor_pool, StagingBufferPool& staging_buffer_pool_, 204 StagingBufferPool& staging_buffer_pool_,
205 VKUpdateDescriptorQueue& update_descriptor_queue_) 205 UpdateDescriptorQueue& update_descriptor_queue_)
206 : ComputePass(device_, descriptor_pool, INPUT_OUTPUT_DESCRIPTOR_SET_BINDINGS, 206 : ComputePass(device_, descriptor_pool, INPUT_OUTPUT_DESCRIPTOR_SET_BINDINGS,
207 INPUT_OUTPUT_DESCRIPTOR_UPDATE_TEMPLATE, INPUT_OUTPUT_BANK_INFO, {}, 207 INPUT_OUTPUT_DESCRIPTOR_UPDATE_TEMPLATE, INPUT_OUTPUT_BANK_INFO, {},
208 VULKAN_UINT8_COMP_SPV), 208 VULKAN_UINT8_COMP_SPV),
@@ -241,10 +241,10 @@ std::pair<VkBuffer, VkDeviceSize> Uint8Pass::Assemble(u32 num_vertices, VkBuffer
241 return {staging.buffer, staging.offset}; 241 return {staging.buffer, staging.offset};
242} 242}
243 243
244QuadIndexedPass::QuadIndexedPass(const Device& device_, VKScheduler& scheduler_, 244QuadIndexedPass::QuadIndexedPass(const Device& device_, Scheduler& scheduler_,
245 DescriptorPool& descriptor_pool_, 245 DescriptorPool& descriptor_pool_,
246 StagingBufferPool& staging_buffer_pool_, 246 StagingBufferPool& staging_buffer_pool_,
247 VKUpdateDescriptorQueue& update_descriptor_queue_) 247 UpdateDescriptorQueue& update_descriptor_queue_)
248 : ComputePass(device_, descriptor_pool_, INPUT_OUTPUT_DESCRIPTOR_SET_BINDINGS, 248 : ComputePass(device_, descriptor_pool_, INPUT_OUTPUT_DESCRIPTOR_SET_BINDINGS,
249 INPUT_OUTPUT_DESCRIPTOR_UPDATE_TEMPLATE, INPUT_OUTPUT_BANK_INFO, 249 INPUT_OUTPUT_DESCRIPTOR_UPDATE_TEMPLATE, INPUT_OUTPUT_BANK_INFO,
250 COMPUTE_PUSH_CONSTANT_RANGE<sizeof(u32) * 2>, VULKAN_QUAD_INDEXED_COMP_SPV), 250 COMPUTE_PUSH_CONSTANT_RANGE<sizeof(u32) * 2>, VULKAN_QUAD_INDEXED_COMP_SPV),
@@ -303,10 +303,10 @@ std::pair<VkBuffer, VkDeviceSize> QuadIndexedPass::Assemble(
303 return {staging.buffer, staging.offset}; 303 return {staging.buffer, staging.offset};
304} 304}
305 305
306ASTCDecoderPass::ASTCDecoderPass(const Device& device_, VKScheduler& scheduler_, 306ASTCDecoderPass::ASTCDecoderPass(const Device& device_, Scheduler& scheduler_,
307 DescriptorPool& descriptor_pool_, 307 DescriptorPool& descriptor_pool_,
308 StagingBufferPool& staging_buffer_pool_, 308 StagingBufferPool& staging_buffer_pool_,
309 VKUpdateDescriptorQueue& update_descriptor_queue_, 309 UpdateDescriptorQueue& update_descriptor_queue_,
310 MemoryAllocator& memory_allocator_) 310 MemoryAllocator& memory_allocator_)
311 : ComputePass(device_, descriptor_pool_, ASTC_DESCRIPTOR_SET_BINDINGS, 311 : ComputePass(device_, descriptor_pool_, ASTC_DESCRIPTOR_SET_BINDINGS,
312 ASTC_PASS_DESCRIPTOR_UPDATE_TEMPLATE_ENTRY, ASTC_BANK_INFO, 312 ASTC_PASS_DESCRIPTOR_UPDATE_TEMPLATE_ENTRY, ASTC_BANK_INFO,
diff --git a/src/video_core/renderer_vulkan/vk_compute_pass.h b/src/video_core/renderer_vulkan/vk_compute_pass.h
index 1c6aa0805..dcc691a8e 100644
--- a/src/video_core/renderer_vulkan/vk_compute_pass.h
+++ b/src/video_core/renderer_vulkan/vk_compute_pass.h
@@ -20,8 +20,8 @@ namespace Vulkan {
20 20
21class Device; 21class Device;
22class StagingBufferPool; 22class StagingBufferPool;
23class VKScheduler; 23class Scheduler;
24class VKUpdateDescriptorQueue; 24class UpdateDescriptorQueue;
25class Image; 25class Image;
26struct StagingBufferRef; 26struct StagingBufferRef;
27 27
@@ -48,9 +48,9 @@ private:
48 48
49class Uint8Pass final : public ComputePass { 49class Uint8Pass final : public ComputePass {
50public: 50public:
51 explicit Uint8Pass(const Device& device_, VKScheduler& scheduler_, 51 explicit Uint8Pass(const Device& device_, Scheduler& scheduler_,
52 DescriptorPool& descriptor_pool_, StagingBufferPool& staging_buffer_pool_, 52 DescriptorPool& descriptor_pool_, StagingBufferPool& staging_buffer_pool_,
53 VKUpdateDescriptorQueue& update_descriptor_queue_); 53 UpdateDescriptorQueue& update_descriptor_queue_);
54 ~Uint8Pass(); 54 ~Uint8Pass();
55 55
56 /// Assemble uint8 indices into an uint16 index buffer 56 /// Assemble uint8 indices into an uint16 index buffer
@@ -59,17 +59,17 @@ public:
59 u32 src_offset); 59 u32 src_offset);
60 60
61private: 61private:
62 VKScheduler& scheduler; 62 Scheduler& scheduler;
63 StagingBufferPool& staging_buffer_pool; 63 StagingBufferPool& staging_buffer_pool;
64 VKUpdateDescriptorQueue& update_descriptor_queue; 64 UpdateDescriptorQueue& update_descriptor_queue;
65}; 65};
66 66
67class QuadIndexedPass final : public ComputePass { 67class QuadIndexedPass final : public ComputePass {
68public: 68public:
69 explicit QuadIndexedPass(const Device& device_, VKScheduler& scheduler_, 69 explicit QuadIndexedPass(const Device& device_, Scheduler& scheduler_,
70 DescriptorPool& descriptor_pool_, 70 DescriptorPool& descriptor_pool_,
71 StagingBufferPool& staging_buffer_pool_, 71 StagingBufferPool& staging_buffer_pool_,
72 VKUpdateDescriptorQueue& update_descriptor_queue_); 72 UpdateDescriptorQueue& update_descriptor_queue_);
73 ~QuadIndexedPass(); 73 ~QuadIndexedPass();
74 74
75 std::pair<VkBuffer, VkDeviceSize> Assemble( 75 std::pair<VkBuffer, VkDeviceSize> Assemble(
@@ -77,17 +77,17 @@ public:
77 u32 base_vertex, VkBuffer src_buffer, u32 src_offset); 77 u32 base_vertex, VkBuffer src_buffer, u32 src_offset);
78 78
79private: 79private:
80 VKScheduler& scheduler; 80 Scheduler& scheduler;
81 StagingBufferPool& staging_buffer_pool; 81 StagingBufferPool& staging_buffer_pool;
82 VKUpdateDescriptorQueue& update_descriptor_queue; 82 UpdateDescriptorQueue& update_descriptor_queue;
83}; 83};
84 84
85class ASTCDecoderPass final : public ComputePass { 85class ASTCDecoderPass final : public ComputePass {
86public: 86public:
87 explicit ASTCDecoderPass(const Device& device_, VKScheduler& scheduler_, 87 explicit ASTCDecoderPass(const Device& device_, Scheduler& scheduler_,
88 DescriptorPool& descriptor_pool_, 88 DescriptorPool& descriptor_pool_,
89 StagingBufferPool& staging_buffer_pool_, 89 StagingBufferPool& staging_buffer_pool_,
90 VKUpdateDescriptorQueue& update_descriptor_queue_, 90 UpdateDescriptorQueue& update_descriptor_queue_,
91 MemoryAllocator& memory_allocator_); 91 MemoryAllocator& memory_allocator_);
92 ~ASTCDecoderPass(); 92 ~ASTCDecoderPass();
93 93
@@ -95,9 +95,9 @@ public:
95 std::span<const VideoCommon::SwizzleParameters> swizzles); 95 std::span<const VideoCommon::SwizzleParameters> swizzles);
96 96
97private: 97private:
98 VKScheduler& scheduler; 98 Scheduler& scheduler;
99 StagingBufferPool& staging_buffer_pool; 99 StagingBufferPool& staging_buffer_pool;
100 VKUpdateDescriptorQueue& update_descriptor_queue; 100 UpdateDescriptorQueue& update_descriptor_queue;
101 MemoryAllocator& memory_allocator; 101 MemoryAllocator& memory_allocator;
102}; 102};
103 103
diff --git a/src/video_core/renderer_vulkan/vk_compute_pipeline.cpp b/src/video_core/renderer_vulkan/vk_compute_pipeline.cpp
index 6c497b5d4..6447210e2 100644
--- a/src/video_core/renderer_vulkan/vk_compute_pipeline.cpp
+++ b/src/video_core/renderer_vulkan/vk_compute_pipeline.cpp
@@ -25,7 +25,7 @@ using Shader::Backend::SPIRV::RESCALING_LAYOUT_WORDS_OFFSET;
25using Tegra::Texture::TexturePair; 25using Tegra::Texture::TexturePair;
26 26
27ComputePipeline::ComputePipeline(const Device& device_, DescriptorPool& descriptor_pool, 27ComputePipeline::ComputePipeline(const Device& device_, DescriptorPool& descriptor_pool,
28 VKUpdateDescriptorQueue& update_descriptor_queue_, 28 UpdateDescriptorQueue& update_descriptor_queue_,
29 Common::ThreadWorker* thread_worker, 29 Common::ThreadWorker* thread_worker,
30 PipelineStatistics* pipeline_statistics, 30 PipelineStatistics* pipeline_statistics,
31 VideoCore::ShaderNotify* shader_notify, const Shader::Info& info_, 31 VideoCore::ShaderNotify* shader_notify, const Shader::Info& info_,
@@ -91,7 +91,7 @@ ComputePipeline::ComputePipeline(const Device& device_, DescriptorPool& descript
91} 91}
92 92
93void ComputePipeline::Configure(Tegra::Engines::KeplerCompute& kepler_compute, 93void ComputePipeline::Configure(Tegra::Engines::KeplerCompute& kepler_compute,
94 Tegra::MemoryManager& gpu_memory, VKScheduler& scheduler, 94 Tegra::MemoryManager& gpu_memory, Scheduler& scheduler,
95 BufferCache& buffer_cache, TextureCache& texture_cache) { 95 BufferCache& buffer_cache, TextureCache& texture_cache) {
96 update_descriptor_queue.Acquire(); 96 update_descriptor_queue.Acquire();
97 97
diff --git a/src/video_core/renderer_vulkan/vk_compute_pipeline.h b/src/video_core/renderer_vulkan/vk_compute_pipeline.h
index d4c0e2015..9879735fe 100644
--- a/src/video_core/renderer_vulkan/vk_compute_pipeline.h
+++ b/src/video_core/renderer_vulkan/vk_compute_pipeline.h
@@ -24,12 +24,12 @@ namespace Vulkan {
24 24
25class Device; 25class Device;
26class PipelineStatistics; 26class PipelineStatistics;
27class VKScheduler; 27class Scheduler;
28 28
29class ComputePipeline { 29class ComputePipeline {
30public: 30public:
31 explicit ComputePipeline(const Device& device, DescriptorPool& descriptor_pool, 31 explicit ComputePipeline(const Device& device, DescriptorPool& descriptor_pool,
32 VKUpdateDescriptorQueue& update_descriptor_queue, 32 UpdateDescriptorQueue& update_descriptor_queue,
33 Common::ThreadWorker* thread_worker, 33 Common::ThreadWorker* thread_worker,
34 PipelineStatistics* pipeline_statistics, 34 PipelineStatistics* pipeline_statistics,
35 VideoCore::ShaderNotify* shader_notify, const Shader::Info& info, 35 VideoCore::ShaderNotify* shader_notify, const Shader::Info& info,
@@ -42,11 +42,11 @@ public:
42 ComputePipeline(const ComputePipeline&) = delete; 42 ComputePipeline(const ComputePipeline&) = delete;
43 43
44 void Configure(Tegra::Engines::KeplerCompute& kepler_compute, Tegra::MemoryManager& gpu_memory, 44 void Configure(Tegra::Engines::KeplerCompute& kepler_compute, Tegra::MemoryManager& gpu_memory,
45 VKScheduler& scheduler, BufferCache& buffer_cache, TextureCache& texture_cache); 45 Scheduler& scheduler, BufferCache& buffer_cache, TextureCache& texture_cache);
46 46
47private: 47private:
48 const Device& device; 48 const Device& device;
49 VKUpdateDescriptorQueue& update_descriptor_queue; 49 UpdateDescriptorQueue& update_descriptor_queue;
50 Shader::Info info; 50 Shader::Info info;
51 51
52 VideoCommon::ComputeUniformBufferSizes uniform_buffer_sizes{}; 52 VideoCommon::ComputeUniformBufferSizes uniform_buffer_sizes{};
diff --git a/src/video_core/renderer_vulkan/vk_descriptor_pool.cpp b/src/video_core/renderer_vulkan/vk_descriptor_pool.cpp
index 7073a874b..c7196b64e 100644
--- a/src/video_core/renderer_vulkan/vk_descriptor_pool.cpp
+++ b/src/video_core/renderer_vulkan/vk_descriptor_pool.cpp
@@ -121,7 +121,7 @@ vk::DescriptorSets DescriptorAllocator::AllocateDescriptors(size_t count) {
121 throw vk::Exception(VK_ERROR_OUT_OF_POOL_MEMORY); 121 throw vk::Exception(VK_ERROR_OUT_OF_POOL_MEMORY);
122} 122}
123 123
124DescriptorPool::DescriptorPool(const Device& device_, VKScheduler& scheduler) 124DescriptorPool::DescriptorPool(const Device& device_, Scheduler& scheduler)
125 : device{device_}, master_semaphore{scheduler.GetMasterSemaphore()} {} 125 : device{device_}, master_semaphore{scheduler.GetMasterSemaphore()} {}
126 126
127DescriptorPool::~DescriptorPool() = default; 127DescriptorPool::~DescriptorPool() = default;
diff --git a/src/video_core/renderer_vulkan/vk_descriptor_pool.h b/src/video_core/renderer_vulkan/vk_descriptor_pool.h
index 30895f259..bd6696b07 100644
--- a/src/video_core/renderer_vulkan/vk_descriptor_pool.h
+++ b/src/video_core/renderer_vulkan/vk_descriptor_pool.h
@@ -14,7 +14,7 @@
14namespace Vulkan { 14namespace Vulkan {
15 15
16class Device; 16class Device;
17class VKScheduler; 17class Scheduler;
18 18
19struct DescriptorBank; 19struct DescriptorBank;
20 20
@@ -62,7 +62,7 @@ private:
62 62
63class DescriptorPool { 63class DescriptorPool {
64public: 64public:
65 explicit DescriptorPool(const Device& device, VKScheduler& scheduler); 65 explicit DescriptorPool(const Device& device, Scheduler& scheduler);
66 ~DescriptorPool(); 66 ~DescriptorPool();
67 67
68 DescriptorPool& operator=(const DescriptorPool&) = delete; 68 DescriptorPool& operator=(const DescriptorPool&) = delete;
diff --git a/src/video_core/renderer_vulkan/vk_fence_manager.cpp b/src/video_core/renderer_vulkan/vk_fence_manager.cpp
index 96335f22c..c249b34d4 100644
--- a/src/video_core/renderer_vulkan/vk_fence_manager.cpp
+++ b/src/video_core/renderer_vulkan/vk_fence_manager.cpp
@@ -11,10 +11,10 @@
11 11
12namespace Vulkan { 12namespace Vulkan {
13 13
14InnerFence::InnerFence(VKScheduler& scheduler_, u32 payload_, bool is_stubbed_) 14InnerFence::InnerFence(Scheduler& scheduler_, u32 payload_, bool is_stubbed_)
15 : FenceBase{payload_, is_stubbed_}, scheduler{scheduler_} {} 15 : FenceBase{payload_, is_stubbed_}, scheduler{scheduler_} {}
16 16
17InnerFence::InnerFence(VKScheduler& scheduler_, GPUVAddr address_, u32 payload_, bool is_stubbed_) 17InnerFence::InnerFence(Scheduler& scheduler_, GPUVAddr address_, u32 payload_, bool is_stubbed_)
18 : FenceBase{address_, payload_, is_stubbed_}, scheduler{scheduler_} {} 18 : FenceBase{address_, payload_, is_stubbed_}, scheduler{scheduler_} {}
19 19
20InnerFence::~InnerFence() = default; 20InnerFence::~InnerFence() = default;
@@ -42,30 +42,29 @@ void InnerFence::Wait() {
42 scheduler.Wait(wait_tick); 42 scheduler.Wait(wait_tick);
43} 43}
44 44
45VKFenceManager::VKFenceManager(VideoCore::RasterizerInterface& rasterizer_, Tegra::GPU& gpu_, 45FenceManager::FenceManager(VideoCore::RasterizerInterface& rasterizer_, Tegra::GPU& gpu_,
46 TextureCache& texture_cache_, BufferCache& buffer_cache_, 46 TextureCache& texture_cache_, BufferCache& buffer_cache_,
47 VKQueryCache& query_cache_, const Device& device_, 47 QueryCache& query_cache_, const Device& device_, Scheduler& scheduler_)
48 VKScheduler& scheduler_)
49 : GenericFenceManager{rasterizer_, gpu_, texture_cache_, buffer_cache_, query_cache_}, 48 : GenericFenceManager{rasterizer_, gpu_, texture_cache_, buffer_cache_, query_cache_},
50 scheduler{scheduler_} {} 49 scheduler{scheduler_} {}
51 50
52Fence VKFenceManager::CreateFence(u32 value, bool is_stubbed) { 51Fence FenceManager::CreateFence(u32 value, bool is_stubbed) {
53 return std::make_shared<InnerFence>(scheduler, value, is_stubbed); 52 return std::make_shared<InnerFence>(scheduler, value, is_stubbed);
54} 53}
55 54
56Fence VKFenceManager::CreateFence(GPUVAddr addr, u32 value, bool is_stubbed) { 55Fence FenceManager::CreateFence(GPUVAddr addr, u32 value, bool is_stubbed) {
57 return std::make_shared<InnerFence>(scheduler, addr, value, is_stubbed); 56 return std::make_shared<InnerFence>(scheduler, addr, value, is_stubbed);
58} 57}
59 58
60void VKFenceManager::QueueFence(Fence& fence) { 59void FenceManager::QueueFence(Fence& fence) {
61 fence->Queue(); 60 fence->Queue();
62} 61}
63 62
64bool VKFenceManager::IsFenceSignaled(Fence& fence) const { 63bool FenceManager::IsFenceSignaled(Fence& fence) const {
65 return fence->IsSignaled(); 64 return fence->IsSignaled();
66} 65}
67 66
68void VKFenceManager::WaitFence(Fence& fence) { 67void FenceManager::WaitFence(Fence& fence) {
69 fence->Wait(); 68 fence->Wait();
70} 69}
71 70
diff --git a/src/video_core/renderer_vulkan/vk_fence_manager.h b/src/video_core/renderer_vulkan/vk_fence_manager.h
index 04eb575ce..7c0bbd80a 100644
--- a/src/video_core/renderer_vulkan/vk_fence_manager.h
+++ b/src/video_core/renderer_vulkan/vk_fence_manager.h
@@ -20,13 +20,13 @@ class RasterizerInterface;
20namespace Vulkan { 20namespace Vulkan {
21 21
22class Device; 22class Device;
23class VKQueryCache; 23class QueryCache;
24class VKScheduler; 24class Scheduler;
25 25
26class InnerFence : public VideoCommon::FenceBase { 26class InnerFence : public VideoCommon::FenceBase {
27public: 27public:
28 explicit InnerFence(VKScheduler& scheduler_, u32 payload_, bool is_stubbed_); 28 explicit InnerFence(Scheduler& scheduler_, u32 payload_, bool is_stubbed_);
29 explicit InnerFence(VKScheduler& scheduler_, GPUVAddr address_, u32 payload_, bool is_stubbed_); 29 explicit InnerFence(Scheduler& scheduler_, GPUVAddr address_, u32 payload_, bool is_stubbed_);
30 ~InnerFence(); 30 ~InnerFence();
31 31
32 void Queue(); 32 void Queue();
@@ -36,20 +36,18 @@ public:
36 void Wait(); 36 void Wait();
37 37
38private: 38private:
39 VKScheduler& scheduler; 39 Scheduler& scheduler;
40 u64 wait_tick = 0; 40 u64 wait_tick = 0;
41}; 41};
42using Fence = std::shared_ptr<InnerFence>; 42using Fence = std::shared_ptr<InnerFence>;
43 43
44using GenericFenceManager = 44using GenericFenceManager = VideoCommon::FenceManager<Fence, TextureCache, BufferCache, QueryCache>;
45 VideoCommon::FenceManager<Fence, TextureCache, BufferCache, VKQueryCache>;
46 45
47class VKFenceManager final : public GenericFenceManager { 46class FenceManager final : public GenericFenceManager {
48public: 47public:
49 explicit VKFenceManager(VideoCore::RasterizerInterface& rasterizer, Tegra::GPU& gpu, 48 explicit FenceManager(VideoCore::RasterizerInterface& rasterizer, Tegra::GPU& gpu,
50 TextureCache& texture_cache, BufferCache& buffer_cache, 49 TextureCache& texture_cache, BufferCache& buffer_cache,
51 VKQueryCache& query_cache, const Device& device, 50 QueryCache& query_cache, const Device& device, Scheduler& scheduler);
52 VKScheduler& scheduler);
53 51
54protected: 52protected:
55 Fence CreateFence(u32 value, bool is_stubbed) override; 53 Fence CreateFence(u32 value, bool is_stubbed) override;
@@ -59,7 +57,7 @@ protected:
59 void WaitFence(Fence& fence) override; 57 void WaitFence(Fence& fence) override;
60 58
61private: 59private:
62 VKScheduler& scheduler; 60 Scheduler& scheduler;
63}; 61};
64 62
65} // namespace Vulkan 63} // namespace Vulkan
diff --git a/src/video_core/renderer_vulkan/vk_fsr.cpp b/src/video_core/renderer_vulkan/vk_fsr.cpp
index b563bd51d..dd450169e 100644
--- a/src/video_core/renderer_vulkan/vk_fsr.cpp
+++ b/src/video_core/renderer_vulkan/vk_fsr.cpp
@@ -172,7 +172,7 @@ FSR::FSR(const Device& device_, MemoryAllocator& memory_allocator_, size_t image
172 CreatePipeline(); 172 CreatePipeline();
173} 173}
174 174
175VkImageView FSR::Draw(VKScheduler& scheduler, size_t image_index, VkImageView image_view, 175VkImageView FSR::Draw(Scheduler& scheduler, size_t image_index, VkImageView image_view,
176 VkExtent2D input_image_extent, const Common::Rectangle<int>& crop_rect) { 176 VkExtent2D input_image_extent, const Common::Rectangle<int>& crop_rect) {
177 177
178 UpdateDescriptorSet(image_index, image_view); 178 UpdateDescriptorSet(image_index, image_view);
diff --git a/src/video_core/renderer_vulkan/vk_fsr.h b/src/video_core/renderer_vulkan/vk_fsr.h
index 836592cb3..5d872861f 100644
--- a/src/video_core/renderer_vulkan/vk_fsr.h
+++ b/src/video_core/renderer_vulkan/vk_fsr.h
@@ -10,13 +10,13 @@
10namespace Vulkan { 10namespace Vulkan {
11 11
12class Device; 12class Device;
13class VKScheduler; 13class Scheduler;
14 14
15class FSR { 15class FSR {
16public: 16public:
17 explicit FSR(const Device& device, MemoryAllocator& memory_allocator, size_t image_count, 17 explicit FSR(const Device& device, MemoryAllocator& memory_allocator, size_t image_count,
18 VkExtent2D output_size); 18 VkExtent2D output_size);
19 VkImageView Draw(VKScheduler& scheduler, size_t image_index, VkImageView image_view, 19 VkImageView Draw(Scheduler& scheduler, size_t image_index, VkImageView image_view,
20 VkExtent2D input_image_extent, const Common::Rectangle<int>& crop_rect); 20 VkExtent2D input_image_extent, const Common::Rectangle<int>& crop_rect);
21 21
22private: 22private:
diff --git a/src/video_core/renderer_vulkan/vk_graphics_pipeline.cpp b/src/video_core/renderer_vulkan/vk_graphics_pipeline.cpp
index 0179679c8..682f05335 100644
--- a/src/video_core/renderer_vulkan/vk_graphics_pipeline.cpp
+++ b/src/video_core/renderer_vulkan/vk_graphics_pipeline.cpp
@@ -215,10 +215,10 @@ ConfigureFuncPtr ConfigureFunc(const std::array<vk::ShaderModule, NUM_STAGES>& m
215} // Anonymous namespace 215} // Anonymous namespace
216 216
217GraphicsPipeline::GraphicsPipeline( 217GraphicsPipeline::GraphicsPipeline(
218 Tegra::Engines::Maxwell3D& maxwell3d_, Tegra::MemoryManager& gpu_memory_, 218 Tegra::Engines::Maxwell3D& maxwell3d_, Tegra::MemoryManager& gpu_memory_, Scheduler& scheduler_,
219 VKScheduler& scheduler_, BufferCache& buffer_cache_, TextureCache& texture_cache_, 219 BufferCache& buffer_cache_, TextureCache& texture_cache_,
220 VideoCore::ShaderNotify* shader_notify, const Device& device_, DescriptorPool& descriptor_pool, 220 VideoCore::ShaderNotify* shader_notify, const Device& device_, DescriptorPool& descriptor_pool,
221 VKUpdateDescriptorQueue& update_descriptor_queue_, Common::ThreadWorker* worker_thread, 221 UpdateDescriptorQueue& update_descriptor_queue_, Common::ThreadWorker* worker_thread,
222 PipelineStatistics* pipeline_statistics, RenderPassCache& render_pass_cache, 222 PipelineStatistics* pipeline_statistics, RenderPassCache& render_pass_cache,
223 const GraphicsPipelineCacheKey& key_, std::array<vk::ShaderModule, NUM_STAGES> stages, 223 const GraphicsPipelineCacheKey& key_, std::array<vk::ShaderModule, NUM_STAGES> stages,
224 const std::array<const Shader::Info*, NUM_STAGES>& infos) 224 const std::array<const Shader::Info*, NUM_STAGES>& infos)
diff --git a/src/video_core/renderer_vulkan/vk_graphics_pipeline.h b/src/video_core/renderer_vulkan/vk_graphics_pipeline.h
index b3bcb0a2d..e8949a9ab 100644
--- a/src/video_core/renderer_vulkan/vk_graphics_pipeline.h
+++ b/src/video_core/renderer_vulkan/vk_graphics_pipeline.h
@@ -62,8 +62,8 @@ class Device;
62class PipelineStatistics; 62class PipelineStatistics;
63class RenderPassCache; 63class RenderPassCache;
64class RescalingPushConstant; 64class RescalingPushConstant;
65class VKScheduler; 65class Scheduler;
66class VKUpdateDescriptorQueue; 66class UpdateDescriptorQueue;
67 67
68class GraphicsPipeline { 68class GraphicsPipeline {
69 static constexpr size_t NUM_STAGES = Tegra::Engines::Maxwell3D::Regs::MaxShaderStage; 69 static constexpr size_t NUM_STAGES = Tegra::Engines::Maxwell3D::Regs::MaxShaderStage;
@@ -71,9 +71,9 @@ class GraphicsPipeline {
71public: 71public:
72 explicit GraphicsPipeline( 72 explicit GraphicsPipeline(
73 Tegra::Engines::Maxwell3D& maxwell3d, Tegra::MemoryManager& gpu_memory, 73 Tegra::Engines::Maxwell3D& maxwell3d, Tegra::MemoryManager& gpu_memory,
74 VKScheduler& scheduler, BufferCache& buffer_cache, TextureCache& texture_cache, 74 Scheduler& scheduler, BufferCache& buffer_cache, TextureCache& texture_cache,
75 VideoCore::ShaderNotify* shader_notify, const Device& device, 75 VideoCore::ShaderNotify* shader_notify, const Device& device,
76 DescriptorPool& descriptor_pool, VKUpdateDescriptorQueue& update_descriptor_queue, 76 DescriptorPool& descriptor_pool, UpdateDescriptorQueue& update_descriptor_queue,
77 Common::ThreadWorker* worker_thread, PipelineStatistics* pipeline_statistics, 77 Common::ThreadWorker* worker_thread, PipelineStatistics* pipeline_statistics,
78 RenderPassCache& render_pass_cache, const GraphicsPipelineCacheKey& key, 78 RenderPassCache& render_pass_cache, const GraphicsPipelineCacheKey& key,
79 std::array<vk::ShaderModule, NUM_STAGES> stages, 79 std::array<vk::ShaderModule, NUM_STAGES> stages,
@@ -125,8 +125,8 @@ private:
125 const Device& device; 125 const Device& device;
126 TextureCache& texture_cache; 126 TextureCache& texture_cache;
127 BufferCache& buffer_cache; 127 BufferCache& buffer_cache;
128 VKScheduler& scheduler; 128 Scheduler& scheduler;
129 VKUpdateDescriptorQueue& update_descriptor_queue; 129 UpdateDescriptorQueue& update_descriptor_queue;
130 130
131 void (*configure_func)(GraphicsPipeline*, bool){}; 131 void (*configure_func)(GraphicsPipeline*, bool){};
132 132
diff --git a/src/video_core/renderer_vulkan/vk_pipeline_cache.cpp b/src/video_core/renderer_vulkan/vk_pipeline_cache.cpp
index 978e827f5..09e035799 100644
--- a/src/video_core/renderer_vulkan/vk_pipeline_cache.cpp
+++ b/src/video_core/renderer_vulkan/vk_pipeline_cache.cpp
@@ -262,8 +262,8 @@ bool GraphicsPipelineCacheKey::operator==(const GraphicsPipelineCacheKey& rhs) c
262PipelineCache::PipelineCache(RasterizerVulkan& rasterizer_, Tegra::Engines::Maxwell3D& maxwell3d_, 262PipelineCache::PipelineCache(RasterizerVulkan& rasterizer_, Tegra::Engines::Maxwell3D& maxwell3d_,
263 Tegra::Engines::KeplerCompute& kepler_compute_, 263 Tegra::Engines::KeplerCompute& kepler_compute_,
264 Tegra::MemoryManager& gpu_memory_, const Device& device_, 264 Tegra::MemoryManager& gpu_memory_, const Device& device_,
265 VKScheduler& scheduler_, DescriptorPool& descriptor_pool_, 265 Scheduler& scheduler_, DescriptorPool& descriptor_pool_,
266 VKUpdateDescriptorQueue& update_descriptor_queue_, 266 UpdateDescriptorQueue& update_descriptor_queue_,
267 RenderPassCache& render_pass_cache_, BufferCache& buffer_cache_, 267 RenderPassCache& render_pass_cache_, BufferCache& buffer_cache_,
268 TextureCache& texture_cache_, VideoCore::ShaderNotify& shader_notify_) 268 TextureCache& texture_cache_, VideoCore::ShaderNotify& shader_notify_)
269 : VideoCommon::ShaderCache{rasterizer_, gpu_memory_, maxwell3d_, kepler_compute_}, 269 : VideoCommon::ShaderCache{rasterizer_, gpu_memory_, maxwell3d_, kepler_compute_},
diff --git a/src/video_core/renderer_vulkan/vk_pipeline_cache.h b/src/video_core/renderer_vulkan/vk_pipeline_cache.h
index 5d3a9e496..127957dbf 100644
--- a/src/video_core/renderer_vulkan/vk_pipeline_cache.h
+++ b/src/video_core/renderer_vulkan/vk_pipeline_cache.h
@@ -81,8 +81,8 @@ class Device;
81class PipelineStatistics; 81class PipelineStatistics;
82class RasterizerVulkan; 82class RasterizerVulkan;
83class RenderPassCache; 83class RenderPassCache;
84class VKScheduler; 84class Scheduler;
85class VKUpdateDescriptorQueue; 85class UpdateDescriptorQueue;
86 86
87using VideoCommon::ShaderInfo; 87using VideoCommon::ShaderInfo;
88 88
@@ -103,8 +103,8 @@ public:
103 explicit PipelineCache(RasterizerVulkan& rasterizer, Tegra::Engines::Maxwell3D& maxwell3d, 103 explicit PipelineCache(RasterizerVulkan& rasterizer, Tegra::Engines::Maxwell3D& maxwell3d,
104 Tegra::Engines::KeplerCompute& kepler_compute, 104 Tegra::Engines::KeplerCompute& kepler_compute,
105 Tegra::MemoryManager& gpu_memory, const Device& device, 105 Tegra::MemoryManager& gpu_memory, const Device& device,
106 VKScheduler& scheduler, DescriptorPool& descriptor_pool, 106 Scheduler& scheduler, DescriptorPool& descriptor_pool,
107 VKUpdateDescriptorQueue& update_descriptor_queue, 107 UpdateDescriptorQueue& update_descriptor_queue,
108 RenderPassCache& render_pass_cache, BufferCache& buffer_cache, 108 RenderPassCache& render_pass_cache, BufferCache& buffer_cache,
109 TextureCache& texture_cache, VideoCore::ShaderNotify& shader_notify_); 109 TextureCache& texture_cache, VideoCore::ShaderNotify& shader_notify_);
110 ~PipelineCache(); 110 ~PipelineCache();
@@ -138,9 +138,9 @@ private:
138 bool build_in_parallel); 138 bool build_in_parallel);
139 139
140 const Device& device; 140 const Device& device;
141 VKScheduler& scheduler; 141 Scheduler& scheduler;
142 DescriptorPool& descriptor_pool; 142 DescriptorPool& descriptor_pool;
143 VKUpdateDescriptorQueue& update_descriptor_queue; 143 UpdateDescriptorQueue& update_descriptor_queue;
144 RenderPassCache& render_pass_cache; 144 RenderPassCache& render_pass_cache;
145 BufferCache& buffer_cache; 145 BufferCache& buffer_cache;
146 TextureCache& texture_cache; 146 TextureCache& texture_cache;
diff --git a/src/video_core/renderer_vulkan/vk_query_cache.cpp b/src/video_core/renderer_vulkan/vk_query_cache.cpp
index ea989d3bc..2b859c6b8 100644
--- a/src/video_core/renderer_vulkan/vk_query_cache.cpp
+++ b/src/video_core/renderer_vulkan/vk_query_cache.cpp
@@ -26,7 +26,7 @@ constexpr VkQueryType GetTarget(QueryType type) {
26 26
27} // Anonymous namespace 27} // Anonymous namespace
28 28
29QueryPool::QueryPool(const Device& device_, VKScheduler& scheduler, QueryType type_) 29QueryPool::QueryPool(const Device& device_, Scheduler& scheduler, QueryType type_)
30 : ResourcePool{scheduler.GetMasterSemaphore(), GROW_STEP}, device{device_}, type{type_} {} 30 : ResourcePool{scheduler.GetMasterSemaphore(), GROW_STEP}, device{device_}, type{type_} {}
31 31
32QueryPool::~QueryPool() = default; 32QueryPool::~QueryPool() = default;
@@ -65,15 +65,15 @@ void QueryPool::Reserve(std::pair<VkQueryPool, u32> query) {
65 usage[pool_index * GROW_STEP + static_cast<std::ptrdiff_t>(query.second)] = false; 65 usage[pool_index * GROW_STEP + static_cast<std::ptrdiff_t>(query.second)] = false;
66} 66}
67 67
68VKQueryCache::VKQueryCache(VideoCore::RasterizerInterface& rasterizer_, 68QueryCache::QueryCache(VideoCore::RasterizerInterface& rasterizer_,
69 Tegra::Engines::Maxwell3D& maxwell3d_, Tegra::MemoryManager& gpu_memory_, 69 Tegra::Engines::Maxwell3D& maxwell3d_, Tegra::MemoryManager& gpu_memory_,
70 const Device& device_, VKScheduler& scheduler_) 70 const Device& device_, Scheduler& scheduler_)
71 : QueryCacheBase{rasterizer_, maxwell3d_, gpu_memory_}, device{device_}, scheduler{scheduler_}, 71 : QueryCacheBase{rasterizer_, maxwell3d_, gpu_memory_}, device{device_}, scheduler{scheduler_},
72 query_pools{ 72 query_pools{
73 QueryPool{device_, scheduler_, QueryType::SamplesPassed}, 73 QueryPool{device_, scheduler_, QueryType::SamplesPassed},
74 } {} 74 } {}
75 75
76VKQueryCache::~VKQueryCache() { 76QueryCache::~QueryCache() {
77 // TODO(Rodrigo): This is a hack to destroy all HostCounter instances before the base class 77 // TODO(Rodrigo): This is a hack to destroy all HostCounter instances before the base class
78 // destructor is called. The query cache should be redesigned to have a proper ownership model 78 // destructor is called. The query cache should be redesigned to have a proper ownership model
79 // instead of using shared pointers. 79 // instead of using shared pointers.
@@ -84,15 +84,15 @@ VKQueryCache::~VKQueryCache() {
84 } 84 }
85} 85}
86 86
87std::pair<VkQueryPool, u32> VKQueryCache::AllocateQuery(QueryType type) { 87std::pair<VkQueryPool, u32> QueryCache::AllocateQuery(QueryType type) {
88 return query_pools[static_cast<std::size_t>(type)].Commit(); 88 return query_pools[static_cast<std::size_t>(type)].Commit();
89} 89}
90 90
91void VKQueryCache::Reserve(QueryType type, std::pair<VkQueryPool, u32> query) { 91void QueryCache::Reserve(QueryType type, std::pair<VkQueryPool, u32> query) {
92 query_pools[static_cast<std::size_t>(type)].Reserve(query); 92 query_pools[static_cast<std::size_t>(type)].Reserve(query);
93} 93}
94 94
95HostCounter::HostCounter(VKQueryCache& cache_, std::shared_ptr<HostCounter> dependency_, 95HostCounter::HostCounter(QueryCache& cache_, std::shared_ptr<HostCounter> dependency_,
96 QueryType type_) 96 QueryType type_)
97 : HostCounterBase{std::move(dependency_)}, cache{cache_}, type{type_}, 97 : HostCounterBase{std::move(dependency_)}, cache{cache_}, type{type_},
98 query{cache_.AllocateQuery(type_)}, tick{cache_.GetScheduler().CurrentTick()} { 98 query{cache_.AllocateQuery(type_)}, tick{cache_.GetScheduler().CurrentTick()} {
diff --git a/src/video_core/renderer_vulkan/vk_query_cache.h b/src/video_core/renderer_vulkan/vk_query_cache.h
index fc176d907..b0d86c4f8 100644
--- a/src/video_core/renderer_vulkan/vk_query_cache.h
+++ b/src/video_core/renderer_vulkan/vk_query_cache.h
@@ -22,14 +22,14 @@ namespace Vulkan {
22class CachedQuery; 22class CachedQuery;
23class Device; 23class Device;
24class HostCounter; 24class HostCounter;
25class VKQueryCache; 25class QueryCache;
26class VKScheduler; 26class Scheduler;
27 27
28using CounterStream = VideoCommon::CounterStreamBase<VKQueryCache, HostCounter>; 28using CounterStream = VideoCommon::CounterStreamBase<QueryCache, HostCounter>;
29 29
30class QueryPool final : public ResourcePool { 30class QueryPool final : public ResourcePool {
31public: 31public:
32 explicit QueryPool(const Device& device, VKScheduler& scheduler, VideoCore::QueryType type); 32 explicit QueryPool(const Device& device, Scheduler& scheduler, VideoCore::QueryType type);
33 ~QueryPool() override; 33 ~QueryPool() override;
34 34
35 std::pair<VkQueryPool, u32> Commit(); 35 std::pair<VkQueryPool, u32> Commit();
@@ -49,13 +49,13 @@ private:
49 std::vector<bool> usage; 49 std::vector<bool> usage;
50}; 50};
51 51
52class VKQueryCache final 52class QueryCache final
53 : public VideoCommon::QueryCacheBase<VKQueryCache, CachedQuery, CounterStream, HostCounter> { 53 : public VideoCommon::QueryCacheBase<QueryCache, CachedQuery, CounterStream, HostCounter> {
54public: 54public:
55 explicit VKQueryCache(VideoCore::RasterizerInterface& rasterizer_, 55 explicit QueryCache(VideoCore::RasterizerInterface& rasterizer_,
56 Tegra::Engines::Maxwell3D& maxwell3d_, Tegra::MemoryManager& gpu_memory_, 56 Tegra::Engines::Maxwell3D& maxwell3d_, Tegra::MemoryManager& gpu_memory_,
57 const Device& device_, VKScheduler& scheduler_); 57 const Device& device_, Scheduler& scheduler_);
58 ~VKQueryCache(); 58 ~QueryCache();
59 59
60 std::pair<VkQueryPool, u32> AllocateQuery(VideoCore::QueryType type); 60 std::pair<VkQueryPool, u32> AllocateQuery(VideoCore::QueryType type);
61 61
@@ -65,19 +65,19 @@ public:
65 return device; 65 return device;
66 } 66 }
67 67
68 VKScheduler& GetScheduler() const noexcept { 68 Scheduler& GetScheduler() const noexcept {
69 return scheduler; 69 return scheduler;
70 } 70 }
71 71
72private: 72private:
73 const Device& device; 73 const Device& device;
74 VKScheduler& scheduler; 74 Scheduler& scheduler;
75 std::array<QueryPool, VideoCore::NumQueryTypes> query_pools; 75 std::array<QueryPool, VideoCore::NumQueryTypes> query_pools;
76}; 76};
77 77
78class HostCounter final : public VideoCommon::HostCounterBase<VKQueryCache, HostCounter> { 78class HostCounter final : public VideoCommon::HostCounterBase<QueryCache, HostCounter> {
79public: 79public:
80 explicit HostCounter(VKQueryCache& cache_, std::shared_ptr<HostCounter> dependency_, 80 explicit HostCounter(QueryCache& cache_, std::shared_ptr<HostCounter> dependency_,
81 VideoCore::QueryType type_); 81 VideoCore::QueryType type_);
82 ~HostCounter(); 82 ~HostCounter();
83 83
@@ -86,7 +86,7 @@ public:
86private: 86private:
87 u64 BlockingQuery() const override; 87 u64 BlockingQuery() const override;
88 88
89 VKQueryCache& cache; 89 QueryCache& cache;
90 const VideoCore::QueryType type; 90 const VideoCore::QueryType type;
91 const std::pair<VkQueryPool, u32> query; 91 const std::pair<VkQueryPool, u32> query;
92 const u64 tick; 92 const u64 tick;
@@ -94,7 +94,7 @@ private:
94 94
95class CachedQuery : public VideoCommon::CachedQueryBase<HostCounter> { 95class CachedQuery : public VideoCommon::CachedQueryBase<HostCounter> {
96public: 96public:
97 explicit CachedQuery(VKQueryCache&, VideoCore::QueryType, VAddr cpu_addr_, u8* host_ptr_) 97 explicit CachedQuery(QueryCache&, VideoCore::QueryType, VAddr cpu_addr_, u8* host_ptr_)
98 : CachedQueryBase{cpu_addr_, host_ptr_} {} 98 : CachedQueryBase{cpu_addr_, host_ptr_} {}
99}; 99};
100 100
diff --git a/src/video_core/renderer_vulkan/vk_rasterizer.cpp b/src/video_core/renderer_vulkan/vk_rasterizer.cpp
index ce6c853c1..10f9fe7fe 100644
--- a/src/video_core/renderer_vulkan/vk_rasterizer.cpp
+++ b/src/video_core/renderer_vulkan/vk_rasterizer.cpp
@@ -142,9 +142,9 @@ DrawParams MakeDrawParams(const Maxwell& regs, u32 num_instances, bool is_instan
142 142
143RasterizerVulkan::RasterizerVulkan(Core::Frontend::EmuWindow& emu_window_, Tegra::GPU& gpu_, 143RasterizerVulkan::RasterizerVulkan(Core::Frontend::EmuWindow& emu_window_, Tegra::GPU& gpu_,
144 Tegra::MemoryManager& gpu_memory_, 144 Tegra::MemoryManager& gpu_memory_,
145 Core::Memory::Memory& cpu_memory_, VKScreenInfo& screen_info_, 145 Core::Memory::Memory& cpu_memory_, ScreenInfo& screen_info_,
146 const Device& device_, MemoryAllocator& memory_allocator_, 146 const Device& device_, MemoryAllocator& memory_allocator_,
147 StateTracker& state_tracker_, VKScheduler& scheduler_) 147 StateTracker& state_tracker_, Scheduler& scheduler_)
148 : RasterizerAccelerated{cpu_memory_}, gpu{gpu_}, 148 : RasterizerAccelerated{cpu_memory_}, gpu{gpu_},
149 gpu_memory{gpu_memory_}, maxwell3d{gpu.Maxwell3D()}, kepler_compute{gpu.KeplerCompute()}, 149 gpu_memory{gpu_memory_}, maxwell3d{gpu.Maxwell3D()}, kepler_compute{gpu.KeplerCompute()},
150 screen_info{screen_info_}, device{device_}, memory_allocator{memory_allocator_}, 150 screen_info{screen_info_}, device{device_}, memory_allocator{memory_allocator_},
diff --git a/src/video_core/renderer_vulkan/vk_rasterizer.h b/src/video_core/renderer_vulkan/vk_rasterizer.h
index 97eeedd9e..0370ea39b 100644
--- a/src/video_core/renderer_vulkan/vk_rasterizer.h
+++ b/src/video_core/renderer_vulkan/vk_rasterizer.h
@@ -38,7 +38,7 @@ class Maxwell3D;
38 38
39namespace Vulkan { 39namespace Vulkan {
40 40
41struct VKScreenInfo; 41struct ScreenInfo;
42 42
43class StateTracker; 43class StateTracker;
44 44
@@ -58,9 +58,9 @@ class RasterizerVulkan final : public VideoCore::RasterizerAccelerated {
58public: 58public:
59 explicit RasterizerVulkan(Core::Frontend::EmuWindow& emu_window_, Tegra::GPU& gpu_, 59 explicit RasterizerVulkan(Core::Frontend::EmuWindow& emu_window_, Tegra::GPU& gpu_,
60 Tegra::MemoryManager& gpu_memory_, Core::Memory::Memory& cpu_memory_, 60 Tegra::MemoryManager& gpu_memory_, Core::Memory::Memory& cpu_memory_,
61 VKScreenInfo& screen_info_, const Device& device_, 61 ScreenInfo& screen_info_, const Device& device_,
62 MemoryAllocator& memory_allocator_, StateTracker& state_tracker_, 62 MemoryAllocator& memory_allocator_, StateTracker& state_tracker_,
63 VKScheduler& scheduler_); 63 Scheduler& scheduler_);
64 ~RasterizerVulkan() override; 64 ~RasterizerVulkan() override;
65 65
66 void Draw(bool is_indexed, bool is_instanced) override; 66 void Draw(bool is_indexed, bool is_instanced) override;
@@ -138,15 +138,15 @@ private:
138 Tegra::Engines::Maxwell3D& maxwell3d; 138 Tegra::Engines::Maxwell3D& maxwell3d;
139 Tegra::Engines::KeplerCompute& kepler_compute; 139 Tegra::Engines::KeplerCompute& kepler_compute;
140 140
141 VKScreenInfo& screen_info; 141 ScreenInfo& screen_info;
142 const Device& device; 142 const Device& device;
143 MemoryAllocator& memory_allocator; 143 MemoryAllocator& memory_allocator;
144 StateTracker& state_tracker; 144 StateTracker& state_tracker;
145 VKScheduler& scheduler; 145 Scheduler& scheduler;
146 146
147 StagingBufferPool staging_pool; 147 StagingBufferPool staging_pool;
148 DescriptorPool descriptor_pool; 148 DescriptorPool descriptor_pool;
149 VKUpdateDescriptorQueue update_descriptor_queue; 149 UpdateDescriptorQueue update_descriptor_queue;
150 BlitImageHelper blit_image; 150 BlitImageHelper blit_image;
151 ASTCDecoderPass astc_decoder_pass; 151 ASTCDecoderPass astc_decoder_pass;
152 RenderPassCache render_pass_cache; 152 RenderPassCache render_pass_cache;
@@ -156,9 +156,9 @@ private:
156 BufferCacheRuntime buffer_cache_runtime; 156 BufferCacheRuntime buffer_cache_runtime;
157 BufferCache buffer_cache; 157 BufferCache buffer_cache;
158 PipelineCache pipeline_cache; 158 PipelineCache pipeline_cache;
159 VKQueryCache query_cache; 159 QueryCache query_cache;
160 AccelerateDMA accelerate_dma; 160 AccelerateDMA accelerate_dma;
161 VKFenceManager fence_manager; 161 FenceManager fence_manager;
162 162
163 vk::Event wfi_event; 163 vk::Event wfi_event;
164 164
diff --git a/src/video_core/renderer_vulkan/vk_scheduler.cpp b/src/video_core/renderer_vulkan/vk_scheduler.cpp
index a7261cf97..a331ff37e 100644
--- a/src/video_core/renderer_vulkan/vk_scheduler.cpp
+++ b/src/video_core/renderer_vulkan/vk_scheduler.cpp
@@ -21,7 +21,7 @@ namespace Vulkan {
21 21
22MICROPROFILE_DECLARE(Vulkan_WaitForWorker); 22MICROPROFILE_DECLARE(Vulkan_WaitForWorker);
23 23
24void VKScheduler::CommandChunk::ExecuteAll(vk::CommandBuffer cmdbuf) { 24void Scheduler::CommandChunk::ExecuteAll(vk::CommandBuffer cmdbuf) {
25 auto command = first; 25 auto command = first;
26 while (command != nullptr) { 26 while (command != nullptr) {
27 auto next = command->GetNext(); 27 auto next = command->GetNext();
@@ -35,7 +35,7 @@ void VKScheduler::CommandChunk::ExecuteAll(vk::CommandBuffer cmdbuf) {
35 last = nullptr; 35 last = nullptr;
36} 36}
37 37
38VKScheduler::VKScheduler(const Device& device_, StateTracker& state_tracker_) 38Scheduler::Scheduler(const Device& device_, StateTracker& state_tracker_)
39 : device{device_}, state_tracker{state_tracker_}, 39 : device{device_}, state_tracker{state_tracker_},
40 master_semaphore{std::make_unique<MasterSemaphore>(device)}, 40 master_semaphore{std::make_unique<MasterSemaphore>(device)},
41 command_pool{std::make_unique<CommandPool>(*master_semaphore, device)} { 41 command_pool{std::make_unique<CommandPool>(*master_semaphore, device)} {
@@ -44,14 +44,14 @@ VKScheduler::VKScheduler(const Device& device_, StateTracker& state_tracker_)
44 worker_thread = std::jthread([this](std::stop_token token) { WorkerThread(token); }); 44 worker_thread = std::jthread([this](std::stop_token token) { WorkerThread(token); });
45} 45}
46 46
47VKScheduler::~VKScheduler() = default; 47Scheduler::~Scheduler() = default;
48 48
49void VKScheduler::Flush(VkSemaphore signal_semaphore, VkSemaphore wait_semaphore) { 49void Scheduler::Flush(VkSemaphore signal_semaphore, VkSemaphore wait_semaphore) {
50 SubmitExecution(signal_semaphore, wait_semaphore); 50 SubmitExecution(signal_semaphore, wait_semaphore);
51 AllocateNewContext(); 51 AllocateNewContext();
52} 52}
53 53
54void VKScheduler::Finish(VkSemaphore signal_semaphore, VkSemaphore wait_semaphore) { 54void Scheduler::Finish(VkSemaphore signal_semaphore, VkSemaphore wait_semaphore) {
55 const u64 presubmit_tick = CurrentTick(); 55 const u64 presubmit_tick = CurrentTick();
56 SubmitExecution(signal_semaphore, wait_semaphore); 56 SubmitExecution(signal_semaphore, wait_semaphore);
57 WaitWorker(); 57 WaitWorker();
@@ -59,7 +59,7 @@ void VKScheduler::Finish(VkSemaphore signal_semaphore, VkSemaphore wait_semaphor
59 AllocateNewContext(); 59 AllocateNewContext();
60} 60}
61 61
62void VKScheduler::WaitWorker() { 62void Scheduler::WaitWorker() {
63 MICROPROFILE_SCOPE(Vulkan_WaitForWorker); 63 MICROPROFILE_SCOPE(Vulkan_WaitForWorker);
64 DispatchWork(); 64 DispatchWork();
65 65
@@ -67,7 +67,7 @@ void VKScheduler::WaitWorker() {
67 wait_cv.wait(lock, [this] { return work_queue.empty(); }); 67 wait_cv.wait(lock, [this] { return work_queue.empty(); });
68} 68}
69 69
70void VKScheduler::DispatchWork() { 70void Scheduler::DispatchWork() {
71 if (chunk->Empty()) { 71 if (chunk->Empty()) {
72 return; 72 return;
73 } 73 }
@@ -79,7 +79,7 @@ void VKScheduler::DispatchWork() {
79 AcquireNewChunk(); 79 AcquireNewChunk();
80} 80}
81 81
82void VKScheduler::RequestRenderpass(const Framebuffer* framebuffer) { 82void Scheduler::RequestRenderpass(const Framebuffer* framebuffer) {
83 const VkRenderPass renderpass = framebuffer->RenderPass(); 83 const VkRenderPass renderpass = framebuffer->RenderPass();
84 const VkFramebuffer framebuffer_handle = framebuffer->Handle(); 84 const VkFramebuffer framebuffer_handle = framebuffer->Handle();
85 const VkExtent2D render_area = framebuffer->RenderArea(); 85 const VkExtent2D render_area = framebuffer->RenderArea();
@@ -114,11 +114,11 @@ void VKScheduler::RequestRenderpass(const Framebuffer* framebuffer) {
114 renderpass_image_ranges = framebuffer->ImageRanges(); 114 renderpass_image_ranges = framebuffer->ImageRanges();
115} 115}
116 116
117void VKScheduler::RequestOutsideRenderPassOperationContext() { 117void Scheduler::RequestOutsideRenderPassOperationContext() {
118 EndRenderPass(); 118 EndRenderPass();
119} 119}
120 120
121bool VKScheduler::UpdateGraphicsPipeline(GraphicsPipeline* pipeline) { 121bool Scheduler::UpdateGraphicsPipeline(GraphicsPipeline* pipeline) {
122 if (state.graphics_pipeline == pipeline) { 122 if (state.graphics_pipeline == pipeline) {
123 return false; 123 return false;
124 } 124 }
@@ -126,7 +126,7 @@ bool VKScheduler::UpdateGraphicsPipeline(GraphicsPipeline* pipeline) {
126 return true; 126 return true;
127} 127}
128 128
129bool VKScheduler::UpdateRescaling(bool is_rescaling) { 129bool Scheduler::UpdateRescaling(bool is_rescaling) {
130 if (state.rescaling_defined && is_rescaling == state.is_rescaling) { 130 if (state.rescaling_defined && is_rescaling == state.is_rescaling) {
131 return false; 131 return false;
132 } 132 }
@@ -135,7 +135,7 @@ bool VKScheduler::UpdateRescaling(bool is_rescaling) {
135 return true; 135 return true;
136} 136}
137 137
138void VKScheduler::WorkerThread(std::stop_token stop_token) { 138void Scheduler::WorkerThread(std::stop_token stop_token) {
139 Common::SetCurrentThreadName("yuzu:VulkanWorker"); 139 Common::SetCurrentThreadName("yuzu:VulkanWorker");
140 do { 140 do {
141 std::unique_ptr<CommandChunk> work; 141 std::unique_ptr<CommandChunk> work;
@@ -161,7 +161,7 @@ void VKScheduler::WorkerThread(std::stop_token stop_token) {
161 } while (!stop_token.stop_requested()); 161 } while (!stop_token.stop_requested());
162} 162}
163 163
164void VKScheduler::AllocateWorkerCommandBuffer() { 164void Scheduler::AllocateWorkerCommandBuffer() {
165 current_cmdbuf = vk::CommandBuffer(command_pool->Commit(), device.GetDispatchLoader()); 165 current_cmdbuf = vk::CommandBuffer(command_pool->Commit(), device.GetDispatchLoader());
166 current_cmdbuf.Begin({ 166 current_cmdbuf.Begin({
167 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, 167 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
@@ -171,7 +171,7 @@ void VKScheduler::AllocateWorkerCommandBuffer() {
171 }); 171 });
172} 172}
173 173
174void VKScheduler::SubmitExecution(VkSemaphore signal_semaphore, VkSemaphore wait_semaphore) { 174void Scheduler::SubmitExecution(VkSemaphore signal_semaphore, VkSemaphore wait_semaphore) {
175 EndPendingOperations(); 175 EndPendingOperations();
176 InvalidateState(); 176 InvalidateState();
177 177
@@ -225,25 +225,25 @@ void VKScheduler::SubmitExecution(VkSemaphore signal_semaphore, VkSemaphore wait
225 DispatchWork(); 225 DispatchWork();
226} 226}
227 227
228void VKScheduler::AllocateNewContext() { 228void Scheduler::AllocateNewContext() {
229 // Enable counters once again. These are disabled when a command buffer is finished. 229 // Enable counters once again. These are disabled when a command buffer is finished.
230 if (query_cache) { 230 if (query_cache) {
231 query_cache->UpdateCounters(); 231 query_cache->UpdateCounters();
232 } 232 }
233} 233}
234 234
235void VKScheduler::InvalidateState() { 235void Scheduler::InvalidateState() {
236 state.graphics_pipeline = nullptr; 236 state.graphics_pipeline = nullptr;
237 state.rescaling_defined = false; 237 state.rescaling_defined = false;
238 state_tracker.InvalidateCommandBufferState(); 238 state_tracker.InvalidateCommandBufferState();
239} 239}
240 240
241void VKScheduler::EndPendingOperations() { 241void Scheduler::EndPendingOperations() {
242 query_cache->DisableStreams(); 242 query_cache->DisableStreams();
243 EndRenderPass(); 243 EndRenderPass();
244} 244}
245 245
246void VKScheduler::EndRenderPass() { 246void Scheduler::EndRenderPass() {
247 if (!state.renderpass) { 247 if (!state.renderpass) {
248 return; 248 return;
249 } 249 }
@@ -280,7 +280,7 @@ void VKScheduler::EndRenderPass() {
280 num_renderpass_images = 0; 280 num_renderpass_images = 0;
281} 281}
282 282
283void VKScheduler::AcquireNewChunk() { 283void Scheduler::AcquireNewChunk() {
284 std::scoped_lock lock{reserve_mutex}; 284 std::scoped_lock lock{reserve_mutex};
285 if (chunk_reserve.empty()) { 285 if (chunk_reserve.empty()) {
286 chunk = std::make_unique<CommandChunk>(); 286 chunk = std::make_unique<CommandChunk>();
diff --git a/src/video_core/renderer_vulkan/vk_scheduler.h b/src/video_core/renderer_vulkan/vk_scheduler.h
index 7a2200474..c04aad08f 100644
--- a/src/video_core/renderer_vulkan/vk_scheduler.h
+++ b/src/video_core/renderer_vulkan/vk_scheduler.h
@@ -22,14 +22,14 @@ class Device;
22class Framebuffer; 22class Framebuffer;
23class GraphicsPipeline; 23class GraphicsPipeline;
24class StateTracker; 24class StateTracker;
25class VKQueryCache; 25class QueryCache;
26 26
27/// The scheduler abstracts command buffer and fence management with an interface that's able to do 27/// The scheduler abstracts command buffer and fence management with an interface that's able to do
28/// OpenGL-like operations on Vulkan command buffers. 28/// OpenGL-like operations on Vulkan command buffers.
29class VKScheduler { 29class Scheduler {
30public: 30public:
31 explicit VKScheduler(const Device& device, StateTracker& state_tracker); 31 explicit Scheduler(const Device& device, StateTracker& state_tracker);
32 ~VKScheduler(); 32 ~Scheduler();
33 33
34 /// Sends the current execution context to the GPU. 34 /// Sends the current execution context to the GPU.
35 void Flush(VkSemaphore signal_semaphore = nullptr, VkSemaphore wait_semaphore = nullptr); 35 void Flush(VkSemaphore signal_semaphore = nullptr, VkSemaphore wait_semaphore = nullptr);
@@ -61,7 +61,7 @@ public:
61 void InvalidateState(); 61 void InvalidateState();
62 62
63 /// Assigns the query cache. 63 /// Assigns the query cache.
64 void SetQueryCache(VKQueryCache& query_cache_) { 64 void SetQueryCache(QueryCache& query_cache_) {
65 query_cache = &query_cache_; 65 query_cache = &query_cache_;
66 } 66 }
67 67
@@ -212,7 +212,7 @@ private:
212 std::unique_ptr<MasterSemaphore> master_semaphore; 212 std::unique_ptr<MasterSemaphore> master_semaphore;
213 std::unique_ptr<CommandPool> command_pool; 213 std::unique_ptr<CommandPool> command_pool;
214 214
215 VKQueryCache* query_cache = nullptr; 215 QueryCache* query_cache = nullptr;
216 216
217 vk::CommandBuffer current_cmdbuf; 217 vk::CommandBuffer current_cmdbuf;
218 218
diff --git a/src/video_core/renderer_vulkan/vk_staging_buffer_pool.cpp b/src/video_core/renderer_vulkan/vk_staging_buffer_pool.cpp
index 9a6afaca6..06f68d09a 100644
--- a/src/video_core/renderer_vulkan/vk_staging_buffer_pool.cpp
+++ b/src/video_core/renderer_vulkan/vk_staging_buffer_pool.cpp
@@ -85,7 +85,7 @@ size_t Region(size_t iterator) noexcept {
85} // Anonymous namespace 85} // Anonymous namespace
86 86
87StagingBufferPool::StagingBufferPool(const Device& device_, MemoryAllocator& memory_allocator_, 87StagingBufferPool::StagingBufferPool(const Device& device_, MemoryAllocator& memory_allocator_,
88 VKScheduler& scheduler_) 88 Scheduler& scheduler_)
89 : device{device_}, memory_allocator{memory_allocator_}, scheduler{scheduler_} { 89 : device{device_}, memory_allocator{memory_allocator_}, scheduler{scheduler_} {
90 const vk::Device& dev = device.GetLogical(); 90 const vk::Device& dev = device.GetLogical();
91 stream_buffer = dev.CreateBuffer(VkBufferCreateInfo{ 91 stream_buffer = dev.CreateBuffer(VkBufferCreateInfo{
diff --git a/src/video_core/renderer_vulkan/vk_staging_buffer_pool.h b/src/video_core/renderer_vulkan/vk_staging_buffer_pool.h
index d4d7efa68..91dc84da8 100644
--- a/src/video_core/renderer_vulkan/vk_staging_buffer_pool.h
+++ b/src/video_core/renderer_vulkan/vk_staging_buffer_pool.h
@@ -14,7 +14,7 @@
14namespace Vulkan { 14namespace Vulkan {
15 15
16class Device; 16class Device;
17class VKScheduler; 17class Scheduler;
18 18
19struct StagingBufferRef { 19struct StagingBufferRef {
20 VkBuffer buffer; 20 VkBuffer buffer;
@@ -27,7 +27,7 @@ public:
27 static constexpr size_t NUM_SYNCS = 16; 27 static constexpr size_t NUM_SYNCS = 16;
28 28
29 explicit StagingBufferPool(const Device& device, MemoryAllocator& memory_allocator, 29 explicit StagingBufferPool(const Device& device, MemoryAllocator& memory_allocator,
30 VKScheduler& scheduler); 30 Scheduler& scheduler);
31 ~StagingBufferPool(); 31 ~StagingBufferPool();
32 32
33 StagingBufferRef Request(size_t size, MemoryUsage usage); 33 StagingBufferRef Request(size_t size, MemoryUsage usage);
@@ -82,7 +82,7 @@ private:
82 82
83 const Device& device; 83 const Device& device;
84 MemoryAllocator& memory_allocator; 84 MemoryAllocator& memory_allocator;
85 VKScheduler& scheduler; 85 Scheduler& scheduler;
86 86
87 vk::Buffer stream_buffer; 87 vk::Buffer stream_buffer;
88 vk::DeviceMemory stream_memory; 88 vk::DeviceMemory stream_memory;
diff --git a/src/video_core/renderer_vulkan/vk_swapchain.cpp b/src/video_core/renderer_vulkan/vk_swapchain.cpp
index 7da81551a..a0c26a72a 100644
--- a/src/video_core/renderer_vulkan/vk_swapchain.cpp
+++ b/src/video_core/renderer_vulkan/vk_swapchain.cpp
@@ -64,15 +64,15 @@ VkExtent2D ChooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, u32 wi
64 64
65} // Anonymous namespace 65} // Anonymous namespace
66 66
67VKSwapchain::VKSwapchain(VkSurfaceKHR surface_, const Device& device_, VKScheduler& scheduler_, 67Swapchain::Swapchain(VkSurfaceKHR surface_, const Device& device_, Scheduler& scheduler_, u32 width,
68 u32 width, u32 height, bool srgb) 68 u32 height, bool srgb)
69 : surface{surface_}, device{device_}, scheduler{scheduler_} { 69 : surface{surface_}, device{device_}, scheduler{scheduler_} {
70 Create(width, height, srgb); 70 Create(width, height, srgb);
71} 71}
72 72
73VKSwapchain::~VKSwapchain() = default; 73Swapchain::~Swapchain() = default;
74 74
75void VKSwapchain::Create(u32 width, u32 height, bool srgb) { 75void Swapchain::Create(u32 width, u32 height, bool srgb) {
76 is_outdated = false; 76 is_outdated = false;
77 is_suboptimal = false; 77 is_suboptimal = false;
78 78
@@ -93,7 +93,7 @@ void VKSwapchain::Create(u32 width, u32 height, bool srgb) {
93 resource_ticks.resize(image_count); 93 resource_ticks.resize(image_count);
94} 94}
95 95
96void VKSwapchain::AcquireNextImage() { 96void Swapchain::AcquireNextImage() {
97 const VkResult result = device.GetLogical().AcquireNextImageKHR( 97 const VkResult result = device.GetLogical().AcquireNextImageKHR(
98 *swapchain, std::numeric_limits<u64>::max(), *present_semaphores[frame_index], 98 *swapchain, std::numeric_limits<u64>::max(), *present_semaphores[frame_index],
99 VK_NULL_HANDLE, &image_index); 99 VK_NULL_HANDLE, &image_index);
@@ -114,7 +114,7 @@ void VKSwapchain::AcquireNextImage() {
114 resource_ticks[image_index] = scheduler.CurrentTick(); 114 resource_ticks[image_index] = scheduler.CurrentTick();
115} 115}
116 116
117void VKSwapchain::Present(VkSemaphore render_semaphore) { 117void Swapchain::Present(VkSemaphore render_semaphore) {
118 const auto present_queue{device.GetPresentQueue()}; 118 const auto present_queue{device.GetPresentQueue()};
119 const VkPresentInfoKHR present_info{ 119 const VkPresentInfoKHR present_info{
120 .sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR, 120 .sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
@@ -145,8 +145,8 @@ void VKSwapchain::Present(VkSemaphore render_semaphore) {
145 } 145 }
146} 146}
147 147
148void VKSwapchain::CreateSwapchain(const VkSurfaceCapabilitiesKHR& capabilities, u32 width, 148void Swapchain::CreateSwapchain(const VkSurfaceCapabilitiesKHR& capabilities, u32 width, u32 height,
149 u32 height, bool srgb) { 149 bool srgb) {
150 const auto physical_device{device.GetPhysical()}; 150 const auto physical_device{device.GetPhysical()};
151 const auto formats{physical_device.GetSurfaceFormatsKHR(surface)}; 151 const auto formats{physical_device.GetSurfaceFormatsKHR(surface)};
152 const auto present_modes{physical_device.GetSurfacePresentModesKHR(surface)}; 152 const auto present_modes{physical_device.GetSurfacePresentModesKHR(surface)};
@@ -212,13 +212,13 @@ void VKSwapchain::CreateSwapchain(const VkSurfaceCapabilitiesKHR& capabilities,
212 image_view_format = srgb ? VK_FORMAT_B8G8R8A8_SRGB : VK_FORMAT_B8G8R8A8_UNORM; 212 image_view_format = srgb ? VK_FORMAT_B8G8R8A8_SRGB : VK_FORMAT_B8G8R8A8_UNORM;
213} 213}
214 214
215void VKSwapchain::CreateSemaphores() { 215void Swapchain::CreateSemaphores() {
216 present_semaphores.resize(image_count); 216 present_semaphores.resize(image_count);
217 std::ranges::generate(present_semaphores, 217 std::ranges::generate(present_semaphores,
218 [this] { return device.GetLogical().CreateSemaphore(); }); 218 [this] { return device.GetLogical().CreateSemaphore(); });
219} 219}
220 220
221void VKSwapchain::CreateImageViews() { 221void Swapchain::CreateImageViews() {
222 VkImageViewCreateInfo ci{ 222 VkImageViewCreateInfo ci{
223 .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, 223 .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
224 .pNext = nullptr, 224 .pNext = nullptr,
@@ -250,7 +250,7 @@ void VKSwapchain::CreateImageViews() {
250 } 250 }
251} 251}
252 252
253void VKSwapchain::Destroy() { 253void Swapchain::Destroy() {
254 frame_index = 0; 254 frame_index = 0;
255 present_semaphores.clear(); 255 present_semaphores.clear();
256 framebuffers.clear(); 256 framebuffers.clear();
@@ -258,11 +258,11 @@ void VKSwapchain::Destroy() {
258 swapchain.reset(); 258 swapchain.reset();
259} 259}
260 260
261bool VKSwapchain::HasFpsUnlockChanged() const { 261bool Swapchain::HasFpsUnlockChanged() const {
262 return current_fps_unlocked != Settings::values.disable_fps_limit.GetValue(); 262 return current_fps_unlocked != Settings::values.disable_fps_limit.GetValue();
263} 263}
264 264
265bool VKSwapchain::NeedsPresentModeUpdate() const { 265bool Swapchain::NeedsPresentModeUpdate() const {
266 // Mailbox present mode is the ideal for all scenarios. If it is not available, 266 // Mailbox present mode is the ideal for all scenarios. If it is not available,
267 // A different present mode is needed to support unlocked FPS above the monitor's refresh rate. 267 // A different present mode is needed to support unlocked FPS above the monitor's refresh rate.
268 return present_mode != VK_PRESENT_MODE_MAILBOX_KHR && HasFpsUnlockChanged(); 268 return present_mode != VK_PRESENT_MODE_MAILBOX_KHR && HasFpsUnlockChanged();
diff --git a/src/video_core/renderer_vulkan/vk_swapchain.h b/src/video_core/renderer_vulkan/vk_swapchain.h
index 6d9d8fec9..111b3902d 100644
--- a/src/video_core/renderer_vulkan/vk_swapchain.h
+++ b/src/video_core/renderer_vulkan/vk_swapchain.h
@@ -15,13 +15,13 @@ struct FramebufferLayout;
15namespace Vulkan { 15namespace Vulkan {
16 16
17class Device; 17class Device;
18class VKScheduler; 18class Scheduler;
19 19
20class VKSwapchain { 20class Swapchain {
21public: 21public:
22 explicit VKSwapchain(VkSurfaceKHR surface, const Device& device, VKScheduler& scheduler, 22 explicit Swapchain(VkSurfaceKHR surface, const Device& device, Scheduler& scheduler, u32 width,
23 u32 width, u32 height, bool srgb); 23 u32 height, bool srgb);
24 ~VKSwapchain(); 24 ~Swapchain();
25 25
26 /// Creates (or recreates) the swapchain with a given size. 26 /// Creates (or recreates) the swapchain with a given size.
27 void Create(u32 width, u32 height, bool srgb); 27 void Create(u32 width, u32 height, bool srgb);
@@ -94,7 +94,7 @@ private:
94 94
95 const VkSurfaceKHR surface; 95 const VkSurfaceKHR surface;
96 const Device& device; 96 const Device& device;
97 VKScheduler& scheduler; 97 Scheduler& scheduler;
98 98
99 vk::SwapchainKHR swapchain; 99 vk::SwapchainKHR swapchain;
100 100
diff --git a/src/video_core/renderer_vulkan/vk_texture_cache.cpp b/src/video_core/renderer_vulkan/vk_texture_cache.cpp
index 43ecb9647..ba6d81420 100644
--- a/src/video_core/renderer_vulkan/vk_texture_cache.cpp
+++ b/src/video_core/renderer_vulkan/vk_texture_cache.cpp
@@ -648,7 +648,7 @@ struct RangedBarrierRange {
648 return VK_FORMAT_R32_UINT; 648 return VK_FORMAT_R32_UINT;
649} 649}
650 650
651void BlitScale(VKScheduler& scheduler, VkImage src_image, VkImage dst_image, const ImageInfo& info, 651void BlitScale(Scheduler& scheduler, VkImage src_image, VkImage dst_image, const ImageInfo& info,
652 VkImageAspectFlags aspect_mask, const Settings::ResolutionScalingInfo& resolution, 652 VkImageAspectFlags aspect_mask, const Settings::ResolutionScalingInfo& resolution,
653 bool up_scaling = true) { 653 bool up_scaling = true) {
654 const bool is_2d = info.type == ImageType::e2D; 654 const bool is_2d = info.type == ImageType::e2D;
@@ -788,7 +788,7 @@ void BlitScale(VKScheduler& scheduler, VkImage src_image, VkImage dst_image, con
788} 788}
789} // Anonymous namespace 789} // Anonymous namespace
790 790
791TextureCacheRuntime::TextureCacheRuntime(const Device& device_, VKScheduler& scheduler_, 791TextureCacheRuntime::TextureCacheRuntime(const Device& device_, Scheduler& scheduler_,
792 MemoryAllocator& memory_allocator_, 792 MemoryAllocator& memory_allocator_,
793 StagingBufferPool& staging_buffer_pool_, 793 StagingBufferPool& staging_buffer_pool_,
794 BlitImageHelper& blit_image_helper_, 794 BlitImageHelper& blit_image_helper_,
diff --git a/src/video_core/renderer_vulkan/vk_texture_cache.h b/src/video_core/renderer_vulkan/vk_texture_cache.h
index 356dcc703..69f06ee7b 100644
--- a/src/video_core/renderer_vulkan/vk_texture_cache.h
+++ b/src/video_core/renderer_vulkan/vk_texture_cache.h
@@ -33,11 +33,11 @@ class ImageView;
33class Framebuffer; 33class Framebuffer;
34class RenderPassCache; 34class RenderPassCache;
35class StagingBufferPool; 35class StagingBufferPool;
36class VKScheduler; 36class Scheduler;
37 37
38class TextureCacheRuntime { 38class TextureCacheRuntime {
39public: 39public:
40 explicit TextureCacheRuntime(const Device& device_, VKScheduler& scheduler_, 40 explicit TextureCacheRuntime(const Device& device_, Scheduler& scheduler_,
41 MemoryAllocator& memory_allocator_, 41 MemoryAllocator& memory_allocator_,
42 StagingBufferPool& staging_buffer_pool_, 42 StagingBufferPool& staging_buffer_pool_,
43 BlitImageHelper& blit_image_helper_, 43 BlitImageHelper& blit_image_helper_,
@@ -93,7 +93,7 @@ public:
93 [[nodiscard]] VkBuffer GetTemporaryBuffer(size_t needed_size); 93 [[nodiscard]] VkBuffer GetTemporaryBuffer(size_t needed_size);
94 94
95 const Device& device; 95 const Device& device;
96 VKScheduler& scheduler; 96 Scheduler& scheduler;
97 MemoryAllocator& memory_allocator; 97 MemoryAllocator& memory_allocator;
98 StagingBufferPool& staging_buffer_pool; 98 StagingBufferPool& staging_buffer_pool;
99 BlitImageHelper& blit_image_helper; 99 BlitImageHelper& blit_image_helper;
@@ -154,7 +154,7 @@ private:
154 154
155 bool NeedsScaleHelper() const; 155 bool NeedsScaleHelper() const;
156 156
157 VKScheduler* scheduler{}; 157 Scheduler* scheduler{};
158 TextureCacheRuntime* runtime{}; 158 TextureCacheRuntime* runtime{};
159 159
160 vk::Image original_image; 160 vk::Image original_image;
diff --git a/src/video_core/renderer_vulkan/vk_update_descriptor.cpp b/src/video_core/renderer_vulkan/vk_update_descriptor.cpp
index d29540fec..4d4a6753b 100644
--- a/src/video_core/renderer_vulkan/vk_update_descriptor.cpp
+++ b/src/video_core/renderer_vulkan/vk_update_descriptor.cpp
@@ -12,18 +12,18 @@
12 12
13namespace Vulkan { 13namespace Vulkan {
14 14
15VKUpdateDescriptorQueue::VKUpdateDescriptorQueue(const Device& device_, VKScheduler& scheduler_) 15UpdateDescriptorQueue::UpdateDescriptorQueue(const Device& device_, Scheduler& scheduler_)
16 : device{device_}, scheduler{scheduler_} { 16 : device{device_}, scheduler{scheduler_} {
17 payload_cursor = payload.data(); 17 payload_cursor = payload.data();
18} 18}
19 19
20VKUpdateDescriptorQueue::~VKUpdateDescriptorQueue() = default; 20UpdateDescriptorQueue::~UpdateDescriptorQueue() = default;
21 21
22void VKUpdateDescriptorQueue::TickFrame() { 22void UpdateDescriptorQueue::TickFrame() {
23 payload_cursor = payload.data(); 23 payload_cursor = payload.data();
24} 24}
25 25
26void VKUpdateDescriptorQueue::Acquire() { 26void UpdateDescriptorQueue::Acquire() {
27 // Minimum number of entries required. 27 // Minimum number of entries required.
28 // This is the maximum number of entries a single draw call migth use. 28 // This is the maximum number of entries a single draw call migth use.
29 static constexpr size_t MIN_ENTRIES = 0x400; 29 static constexpr size_t MIN_ENTRIES = 0x400;
diff --git a/src/video_core/renderer_vulkan/vk_update_descriptor.h b/src/video_core/renderer_vulkan/vk_update_descriptor.h
index d8a56b153..625bcc809 100644
--- a/src/video_core/renderer_vulkan/vk_update_descriptor.h
+++ b/src/video_core/renderer_vulkan/vk_update_descriptor.h
@@ -10,7 +10,7 @@
10namespace Vulkan { 10namespace Vulkan {
11 11
12class Device; 12class Device;
13class VKScheduler; 13class Scheduler;
14 14
15struct DescriptorUpdateEntry { 15struct DescriptorUpdateEntry {
16 struct Empty {}; 16 struct Empty {};
@@ -28,10 +28,10 @@ struct DescriptorUpdateEntry {
28 }; 28 };
29}; 29};
30 30
31class VKUpdateDescriptorQueue final { 31class UpdateDescriptorQueue final {
32public: 32public:
33 explicit VKUpdateDescriptorQueue(const Device& device_, VKScheduler& scheduler_); 33 explicit UpdateDescriptorQueue(const Device& device_, Scheduler& scheduler_);
34 ~VKUpdateDescriptorQueue(); 34 ~UpdateDescriptorQueue();
35 35
36 void TickFrame(); 36 void TickFrame();
37 37
@@ -71,7 +71,7 @@ public:
71 71
72private: 72private:
73 const Device& device; 73 const Device& device;
74 VKScheduler& scheduler; 74 Scheduler& scheduler;
75 75
76 DescriptorUpdateEntry* payload_cursor = nullptr; 76 DescriptorUpdateEntry* payload_cursor = nullptr;
77 const DescriptorUpdateEntry* upload_start = nullptr; 77 const DescriptorUpdateEntry* upload_start = nullptr;
diff --git a/src/video_core/vulkan_common/vulkan_device.cpp b/src/video_core/vulkan_common/vulkan_device.cpp
index 11ce865a7..743ac09f6 100644
--- a/src/video_core/vulkan_common/vulkan_device.cpp
+++ b/src/video_core/vulkan_common/vulkan_device.cpp
@@ -669,17 +669,6 @@ Device::Device(VkInstance instance_, vk::PhysicalDevice physical_, VkSurfaceKHR
669 const bool is_amd = 669 const bool is_amd =
670 driver_id == VK_DRIVER_ID_AMD_PROPRIETARY || driver_id == VK_DRIVER_ID_AMD_OPEN_SOURCE; 670 driver_id == VK_DRIVER_ID_AMD_PROPRIETARY || driver_id == VK_DRIVER_ID_AMD_OPEN_SOURCE;
671 if (is_amd) { 671 if (is_amd) {
672 // TODO(lat9nq): Add an upper bound when AMD fixes their VK_KHR_push_descriptor
673 const bool has_broken_push_descriptor = VK_VERSION_MAJOR(properties.driverVersion) == 2 &&
674 VK_VERSION_MINOR(properties.driverVersion) == 0 &&
675 VK_VERSION_PATCH(properties.driverVersion) >= 226;
676 if (khr_push_descriptor && has_broken_push_descriptor) {
677 LOG_WARNING(
678 Render_Vulkan,
679 "Disabling AMD driver 2.0.226 and later from broken VK_KHR_push_descriptor");
680 khr_push_descriptor = false;
681 }
682
683 // AMD drivers need a higher amount of Sets per Pool in certain circunstances like in XC2. 672 // AMD drivers need a higher amount of Sets per Pool in certain circunstances like in XC2.
684 sets_per_pool = 96; 673 sets_per_pool = 96;
685 // Disable VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT on AMD GCN4 and lower as it is broken. 674 // Disable VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT on AMD GCN4 and lower as it is broken.
diff --git a/src/yuzu/applets/qt_error.cpp b/src/yuzu/applets/qt_error.cpp
index 5bd8d85bb..367d5352d 100644
--- a/src/yuzu/applets/qt_error.cpp
+++ b/src/yuzu/applets/qt_error.cpp
@@ -14,7 +14,7 @@ QtErrorDisplay::QtErrorDisplay(GMainWindow& parent) {
14 14
15QtErrorDisplay::~QtErrorDisplay() = default; 15QtErrorDisplay::~QtErrorDisplay() = default;
16 16
17void QtErrorDisplay::ShowError(ResultCode error, std::function<void()> finished) const { 17void QtErrorDisplay::ShowError(Result error, std::function<void()> finished) const {
18 callback = std::move(finished); 18 callback = std::move(finished);
19 emit MainWindowDisplayError( 19 emit MainWindowDisplayError(
20 tr("Error Code: %1-%2 (0x%3)") 20 tr("Error Code: %1-%2 (0x%3)")
@@ -24,7 +24,7 @@ void QtErrorDisplay::ShowError(ResultCode error, std::function<void()> finished)
24 tr("An error has occurred.\nPlease try again or contact the developer of the software.")); 24 tr("An error has occurred.\nPlease try again or contact the developer of the software."));
25} 25}
26 26
27void QtErrorDisplay::ShowErrorWithTimestamp(ResultCode error, std::chrono::seconds time, 27void QtErrorDisplay::ShowErrorWithTimestamp(Result error, std::chrono::seconds time,
28 std::function<void()> finished) const { 28 std::function<void()> finished) const {
29 callback = std::move(finished); 29 callback = std::move(finished);
30 30
@@ -40,7 +40,7 @@ void QtErrorDisplay::ShowErrorWithTimestamp(ResultCode error, std::chrono::secon
40 .arg(date_time.toString(QStringLiteral("h:mm:ss A")))); 40 .arg(date_time.toString(QStringLiteral("h:mm:ss A"))));
41} 41}
42 42
43void QtErrorDisplay::ShowCustomErrorText(ResultCode error, std::string dialog_text, 43void QtErrorDisplay::ShowCustomErrorText(Result error, std::string dialog_text,
44 std::string fullscreen_text, 44 std::string fullscreen_text,
45 std::function<void()> finished) const { 45 std::function<void()> finished) const {
46 callback = std::move(finished); 46 callback = std::move(finished);
diff --git a/src/yuzu/applets/qt_error.h b/src/yuzu/applets/qt_error.h
index 2d045b4fc..eb4107c7e 100644
--- a/src/yuzu/applets/qt_error.h
+++ b/src/yuzu/applets/qt_error.h
@@ -16,10 +16,10 @@ public:
16 explicit QtErrorDisplay(GMainWindow& parent); 16 explicit QtErrorDisplay(GMainWindow& parent);
17 ~QtErrorDisplay() override; 17 ~QtErrorDisplay() override;
18 18
19 void ShowError(ResultCode error, std::function<void()> finished) const override; 19 void ShowError(Result error, std::function<void()> finished) const override;
20 void ShowErrorWithTimestamp(ResultCode error, std::chrono::seconds time, 20 void ShowErrorWithTimestamp(Result error, std::chrono::seconds time,
21 std::function<void()> finished) const override; 21 std::function<void()> finished) const override;
22 void ShowCustomErrorText(ResultCode error, std::string dialog_text, std::string fullscreen_text, 22 void ShowCustomErrorText(Result error, std::string dialog_text, std::string fullscreen_text,
23 std::function<void()> finished) const override; 23 std::function<void()> finished) const override;
24 24
25signals: 25signals:
diff --git a/src/yuzu/applets/qt_web_browser.cpp b/src/yuzu/applets/qt_web_browser.cpp
index 283c04cd5..790edbb2a 100644
--- a/src/yuzu/applets/qt_web_browser.cpp
+++ b/src/yuzu/applets/qt_web_browser.cpp
@@ -52,8 +52,8 @@ QtNXWebEngineView::QtNXWebEngineView(QWidget* parent, Core::System& system,
52 : QWebEngineView(parent), input_subsystem{input_subsystem_}, 52 : QWebEngineView(parent), input_subsystem{input_subsystem_},
53 url_interceptor(std::make_unique<UrlRequestInterceptor>()), 53 url_interceptor(std::make_unique<UrlRequestInterceptor>()),
54 input_interpreter(std::make_unique<InputInterpreter>(system)), 54 input_interpreter(std::make_unique<InputInterpreter>(system)),
55 default_profile{QWebEngineProfile::defaultProfile()}, 55 default_profile{QWebEngineProfile::defaultProfile()}, global_settings{
56 global_settings{QWebEngineSettings::globalSettings()} { 56 default_profile->settings()} {
57 default_profile->setPersistentStoragePath(QString::fromStdString(Common::FS::PathToUTF8String( 57 default_profile->setPersistentStoragePath(QString::fromStdString(Common::FS::PathToUTF8String(
58 Common::FS::GetYuzuPath(Common::FS::YuzuPath::YuzuDir) / "qtwebengine"))); 58 Common::FS::GetYuzuPath(Common::FS::YuzuPath::YuzuDir) / "qtwebengine")));
59 59
@@ -78,7 +78,7 @@ QtNXWebEngineView::QtNXWebEngineView(QWidget* parent, Core::System& system,
78 default_profile->scripts()->insert(gamepad); 78 default_profile->scripts()->insert(gamepad);
79 default_profile->scripts()->insert(window_nx); 79 default_profile->scripts()->insert(window_nx);
80 80
81 default_profile->setRequestInterceptor(url_interceptor.get()); 81 default_profile->setUrlRequestInterceptor(url_interceptor.get());
82 82
83 global_settings->setAttribute(QWebEngineSettings::LocalContentCanAccessRemoteUrls, true); 83 global_settings->setAttribute(QWebEngineSettings::LocalContentCanAccessRemoteUrls, true);
84 global_settings->setAttribute(QWebEngineSettings::FullScreenSupportEnabled, true); 84 global_settings->setAttribute(QWebEngineSettings::FullScreenSupportEnabled, true);
diff --git a/src/yuzu/configuration/config.cpp b/src/yuzu/configuration/config.cpp
index 9df4752be..9686412d0 100644
--- a/src/yuzu/configuration/config.cpp
+++ b/src/yuzu/configuration/config.cpp
@@ -133,7 +133,7 @@ void Config::Initialize(const std::string& config_name) {
133// Explicit std::string definition: Qt can't implicitly convert a std::string to a QVariant, nor 133// Explicit std::string definition: Qt can't implicitly convert a std::string to a QVariant, nor
134// can it implicitly convert a QVariant back to a {std::,Q}string 134// can it implicitly convert a QVariant back to a {std::,Q}string
135template <> 135template <>
136void Config::ReadBasicSetting(Settings::BasicSetting<std::string>& setting) { 136void Config::ReadBasicSetting(Settings::Setting<std::string>& setting) {
137 const QString name = QString::fromStdString(setting.GetLabel()); 137 const QString name = QString::fromStdString(setting.GetLabel());
138 const auto default_value = QString::fromStdString(setting.GetDefault()); 138 const auto default_value = QString::fromStdString(setting.GetDefault());
139 if (qt_config->value(name + QStringLiteral("/default"), false).toBool()) { 139 if (qt_config->value(name + QStringLiteral("/default"), false).toBool()) {
@@ -144,7 +144,7 @@ void Config::ReadBasicSetting(Settings::BasicSetting<std::string>& setting) {
144} 144}
145 145
146template <typename Type> 146template <typename Type>
147void Config::ReadBasicSetting(Settings::BasicSetting<Type>& setting) { 147void Config::ReadBasicSetting(Settings::Setting<Type>& setting) {
148 const QString name = QString::fromStdString(setting.GetLabel()); 148 const QString name = QString::fromStdString(setting.GetLabel());
149 const Type default_value = setting.GetDefault(); 149 const Type default_value = setting.GetDefault();
150 if (qt_config->value(name + QStringLiteral("/default"), false).toBool()) { 150 if (qt_config->value(name + QStringLiteral("/default"), false).toBool()) {
@@ -157,7 +157,7 @@ void Config::ReadBasicSetting(Settings::BasicSetting<Type>& setting) {
157 157
158// Explicit std::string definition: Qt can't implicitly convert a std::string to a QVariant 158// Explicit std::string definition: Qt can't implicitly convert a std::string to a QVariant
159template <> 159template <>
160void Config::WriteBasicSetting(const Settings::BasicSetting<std::string>& setting) { 160void Config::WriteBasicSetting(const Settings::Setting<std::string>& setting) {
161 const QString name = QString::fromStdString(setting.GetLabel()); 161 const QString name = QString::fromStdString(setting.GetLabel());
162 const std::string& value = setting.GetValue(); 162 const std::string& value = setting.GetValue();
163 qt_config->setValue(name + QStringLiteral("/default"), value == setting.GetDefault()); 163 qt_config->setValue(name + QStringLiteral("/default"), value == setting.GetDefault());
@@ -165,7 +165,7 @@ void Config::WriteBasicSetting(const Settings::BasicSetting<std::string>& settin
165} 165}
166 166
167template <typename Type> 167template <typename Type>
168void Config::WriteBasicSetting(const Settings::BasicSetting<Type>& setting) { 168void Config::WriteBasicSetting(const Settings::Setting<Type>& setting) {
169 const QString name = QString::fromStdString(setting.GetLabel()); 169 const QString name = QString::fromStdString(setting.GetLabel());
170 const Type value = setting.GetValue(); 170 const Type value = setting.GetValue();
171 qt_config->setValue(name + QStringLiteral("/default"), value == setting.GetDefault()); 171 qt_config->setValue(name + QStringLiteral("/default"), value == setting.GetDefault());
@@ -173,7 +173,7 @@ void Config::WriteBasicSetting(const Settings::BasicSetting<Type>& setting) {
173} 173}
174 174
175template <typename Type> 175template <typename Type>
176void Config::WriteGlobalSetting(const Settings::Setting<Type>& setting) { 176void Config::WriteGlobalSetting(const Settings::SwitchableSetting<Type>& setting) {
177 const QString name = QString::fromStdString(setting.GetLabel()); 177 const QString name = QString::fromStdString(setting.GetLabel());
178 const Type& value = setting.GetValue(global); 178 const Type& value = setting.GetValue(global);
179 if (!global) { 179 if (!global) {
@@ -1422,7 +1422,7 @@ QVariant Config::ReadSetting(const QString& name, const QVariant& default_value)
1422} 1422}
1423 1423
1424template <typename Type> 1424template <typename Type>
1425void Config::ReadGlobalSetting(Settings::Setting<Type>& setting) { 1425void Config::ReadGlobalSetting(Settings::SwitchableSetting<Type>& setting) {
1426 QString name = QString::fromStdString(setting.GetLabel()); 1426 QString name = QString::fromStdString(setting.GetLabel());
1427 const bool use_global = qt_config->value(name + QStringLiteral("/use_global"), true).toBool(); 1427 const bool use_global = qt_config->value(name + QStringLiteral("/use_global"), true).toBool();
1428 setting.SetGlobal(use_global); 1428 setting.SetGlobal(use_global);
diff --git a/src/yuzu/configuration/config.h b/src/yuzu/configuration/config.h
index f0ab6bdaa..9ca878d23 100644
--- a/src/yuzu/configuration/config.h
+++ b/src/yuzu/configuration/config.h
@@ -160,7 +160,7 @@ private:
160 * @param The setting 160 * @param The setting
161 */ 161 */
162 template <typename Type> 162 template <typename Type>
163 void ReadGlobalSetting(Settings::Setting<Type>& setting); 163 void ReadGlobalSetting(Settings::SwitchableSetting<Type>& setting);
164 164
165 /** 165 /**
166 * Sets a value to the qt_config using the setting's label and default value. If the config is a 166 * Sets a value to the qt_config using the setting's label and default value. If the config is a
@@ -169,7 +169,7 @@ private:
169 * @param The setting 169 * @param The setting
170 */ 170 */
171 template <typename Type> 171 template <typename Type>
172 void WriteGlobalSetting(const Settings::Setting<Type>& setting); 172 void WriteGlobalSetting(const Settings::SwitchableSetting<Type>& setting);
173 173
174 /** 174 /**
175 * Reads a value from the qt_config using the setting's label and default value and applies the 175 * Reads a value from the qt_config using the setting's label and default value and applies the
@@ -178,14 +178,14 @@ private:
178 * @param The setting 178 * @param The setting
179 */ 179 */
180 template <typename Type> 180 template <typename Type>
181 void ReadBasicSetting(Settings::BasicSetting<Type>& setting); 181 void ReadBasicSetting(Settings::Setting<Type>& setting);
182 182
183 /** Sets a value from the setting in the qt_config using the setting's label and default value. 183 /** Sets a value from the setting in the qt_config using the setting's label and default value.
184 * 184 *
185 * @param The setting 185 * @param The setting
186 */ 186 */
187 template <typename Type> 187 template <typename Type>
188 void WriteBasicSetting(const Settings::BasicSetting<Type>& setting); 188 void WriteBasicSetting(const Settings::Setting<Type>& setting);
189 189
190 ConfigType type; 190 ConfigType type;
191 std::unique_ptr<QSettings> qt_config; 191 std::unique_ptr<QSettings> qt_config;
diff --git a/src/yuzu/configuration/configuration_shared.cpp b/src/yuzu/configuration/configuration_shared.cpp
index 5190bd18b..dd4959417 100644
--- a/src/yuzu/configuration/configuration_shared.cpp
+++ b/src/yuzu/configuration/configuration_shared.cpp
@@ -9,7 +9,7 @@
9#include "yuzu/configuration/configuration_shared.h" 9#include "yuzu/configuration/configuration_shared.h"
10#include "yuzu/configuration/configure_per_game.h" 10#include "yuzu/configuration/configure_per_game.h"
11 11
12void ConfigurationShared::ApplyPerGameSetting(Settings::Setting<bool>* setting, 12void ConfigurationShared::ApplyPerGameSetting(Settings::SwitchableSetting<bool>* setting,
13 const QCheckBox* checkbox, 13 const QCheckBox* checkbox,
14 const CheckState& tracker) { 14 const CheckState& tracker) {
15 if (Settings::IsConfiguringGlobal() && setting->UsingGlobal()) { 15 if (Settings::IsConfiguringGlobal() && setting->UsingGlobal()) {
@@ -25,7 +25,7 @@ void ConfigurationShared::ApplyPerGameSetting(Settings::Setting<bool>* setting,
25} 25}
26 26
27void ConfigurationShared::SetPerGameSetting(QCheckBox* checkbox, 27void ConfigurationShared::SetPerGameSetting(QCheckBox* checkbox,
28 const Settings::Setting<bool>* setting) { 28 const Settings::SwitchableSetting<bool>* setting) {
29 if (setting->UsingGlobal()) { 29 if (setting->UsingGlobal()) {
30 checkbox->setCheckState(Qt::PartiallyChecked); 30 checkbox->setCheckState(Qt::PartiallyChecked);
31 } else { 31 } else {
@@ -45,7 +45,7 @@ void ConfigurationShared::SetHighlight(QWidget* widget, bool highlighted) {
45} 45}
46 46
47void ConfigurationShared::SetColoredTristate(QCheckBox* checkbox, 47void ConfigurationShared::SetColoredTristate(QCheckBox* checkbox,
48 const Settings::Setting<bool>& setting, 48 const Settings::SwitchableSetting<bool>& setting,
49 CheckState& tracker) { 49 CheckState& tracker) {
50 if (setting.UsingGlobal()) { 50 if (setting.UsingGlobal()) {
51 tracker = CheckState::Global; 51 tracker = CheckState::Global;
diff --git a/src/yuzu/configuration/configuration_shared.h b/src/yuzu/configuration/configuration_shared.h
index 903a9baae..77802a367 100644
--- a/src/yuzu/configuration/configuration_shared.h
+++ b/src/yuzu/configuration/configuration_shared.h
@@ -25,10 +25,10 @@ enum class CheckState {
25// Global-aware apply and set functions 25// Global-aware apply and set functions
26 26
27// ApplyPerGameSetting, given a Settings::Setting and a Qt UI element, properly applies a Setting 27// ApplyPerGameSetting, given a Settings::Setting and a Qt UI element, properly applies a Setting
28void ApplyPerGameSetting(Settings::Setting<bool>* setting, const QCheckBox* checkbox, 28void ApplyPerGameSetting(Settings::SwitchableSetting<bool>* setting, const QCheckBox* checkbox,
29 const CheckState& tracker); 29 const CheckState& tracker);
30template <typename Type> 30template <typename Type>
31void ApplyPerGameSetting(Settings::Setting<Type>* setting, const QComboBox* combobox) { 31void ApplyPerGameSetting(Settings::SwitchableSetting<Type>* setting, const QComboBox* combobox) {
32 if (Settings::IsConfiguringGlobal() && setting->UsingGlobal()) { 32 if (Settings::IsConfiguringGlobal() && setting->UsingGlobal()) {
33 setting->SetValue(static_cast<Type>(combobox->currentIndex())); 33 setting->SetValue(static_cast<Type>(combobox->currentIndex()));
34 } else if (!Settings::IsConfiguringGlobal()) { 34 } else if (!Settings::IsConfiguringGlobal()) {
@@ -43,10 +43,10 @@ void ApplyPerGameSetting(Settings::Setting<Type>* setting, const QComboBox* comb
43} 43}
44 44
45// Sets a Qt UI element given a Settings::Setting 45// Sets a Qt UI element given a Settings::Setting
46void SetPerGameSetting(QCheckBox* checkbox, const Settings::Setting<bool>* setting); 46void SetPerGameSetting(QCheckBox* checkbox, const Settings::SwitchableSetting<bool>* setting);
47 47
48template <typename Type> 48template <typename Type>
49void SetPerGameSetting(QComboBox* combobox, const Settings::Setting<Type>* setting) { 49void SetPerGameSetting(QComboBox* combobox, const Settings::SwitchableSetting<Type>* setting) {
50 combobox->setCurrentIndex(setting->UsingGlobal() ? ConfigurationShared::USE_GLOBAL_INDEX 50 combobox->setCurrentIndex(setting->UsingGlobal() ? ConfigurationShared::USE_GLOBAL_INDEX
51 : static_cast<int>(setting->GetValue()) + 51 : static_cast<int>(setting->GetValue()) +
52 ConfigurationShared::USE_GLOBAL_OFFSET); 52 ConfigurationShared::USE_GLOBAL_OFFSET);
@@ -56,7 +56,7 @@ void SetPerGameSetting(QComboBox* combobox, const Settings::Setting<Type>* setti
56void SetHighlight(QWidget* widget, bool highlighted); 56void SetHighlight(QWidget* widget, bool highlighted);
57 57
58// Sets up a QCheckBox like a tristate one, given a Setting 58// Sets up a QCheckBox like a tristate one, given a Setting
59void SetColoredTristate(QCheckBox* checkbox, const Settings::Setting<bool>& setting, 59void SetColoredTristate(QCheckBox* checkbox, const Settings::SwitchableSetting<bool>& setting,
60 CheckState& tracker); 60 CheckState& tracker);
61void SetColoredTristate(QCheckBox* checkbox, bool global, bool state, bool global_state, 61void SetColoredTristate(QCheckBox* checkbox, bool global, bool state, bool global_state,
62 CheckState& tracker); 62 CheckState& tracker);
diff --git a/src/yuzu/uisettings.h b/src/yuzu/uisettings.h
index c64d87ace..044d88ca6 100644
--- a/src/yuzu/uisettings.h
+++ b/src/yuzu/uisettings.h
@@ -64,28 +64,28 @@ struct Values {
64 QByteArray gamelist_header_state; 64 QByteArray gamelist_header_state;
65 65
66 QByteArray microprofile_geometry; 66 QByteArray microprofile_geometry;
67 Settings::BasicSetting<bool> microprofile_visible{false, "microProfileDialogVisible"}; 67 Settings::Setting<bool> microprofile_visible{false, "microProfileDialogVisible"};
68 68
69 Settings::BasicSetting<bool> single_window_mode{true, "singleWindowMode"}; 69 Settings::Setting<bool> single_window_mode{true, "singleWindowMode"};
70 Settings::BasicSetting<bool> fullscreen{false, "fullscreen"}; 70 Settings::Setting<bool> fullscreen{false, "fullscreen"};
71 Settings::BasicSetting<bool> display_titlebar{true, "displayTitleBars"}; 71 Settings::Setting<bool> display_titlebar{true, "displayTitleBars"};
72 Settings::BasicSetting<bool> show_filter_bar{true, "showFilterBar"}; 72 Settings::Setting<bool> show_filter_bar{true, "showFilterBar"};
73 Settings::BasicSetting<bool> show_status_bar{true, "showStatusBar"}; 73 Settings::Setting<bool> show_status_bar{true, "showStatusBar"};
74 74
75 Settings::BasicSetting<bool> confirm_before_closing{true, "confirmClose"}; 75 Settings::Setting<bool> confirm_before_closing{true, "confirmClose"};
76 Settings::BasicSetting<bool> first_start{true, "firstStart"}; 76 Settings::Setting<bool> first_start{true, "firstStart"};
77 Settings::BasicSetting<bool> pause_when_in_background{false, "pauseWhenInBackground"}; 77 Settings::Setting<bool> pause_when_in_background{false, "pauseWhenInBackground"};
78 Settings::BasicSetting<bool> mute_when_in_background{false, "muteWhenInBackground"}; 78 Settings::Setting<bool> mute_when_in_background{false, "muteWhenInBackground"};
79 Settings::BasicSetting<bool> hide_mouse{true, "hideInactiveMouse"}; 79 Settings::Setting<bool> hide_mouse{true, "hideInactiveMouse"};
80 // Set when Vulkan is known to crash the application 80 // Set when Vulkan is known to crash the application
81 Settings::BasicSetting<bool> has_broken_vulkan{false, "has_broken_vulkan"}; 81 Settings::Setting<bool> has_broken_vulkan{false, "has_broken_vulkan"};
82 82
83 Settings::BasicSetting<bool> select_user_on_boot{false, "select_user_on_boot"}; 83 Settings::Setting<bool> select_user_on_boot{false, "select_user_on_boot"};
84 84
85 // Discord RPC 85 // Discord RPC
86 Settings::BasicSetting<bool> enable_discord_presence{true, "enable_discord_presence"}; 86 Settings::Setting<bool> enable_discord_presence{true, "enable_discord_presence"};
87 87
88 Settings::BasicSetting<bool> enable_screenshot_save_as{true, "enable_screenshot_save_as"}; 88 Settings::Setting<bool> enable_screenshot_save_as{true, "enable_screenshot_save_as"};
89 89
90 QString roms_path; 90 QString roms_path;
91 QString symbols_path; 91 QString symbols_path;
@@ -100,25 +100,25 @@ struct Values {
100 // Shortcut name <Shortcut, context> 100 // Shortcut name <Shortcut, context>
101 std::vector<Shortcut> shortcuts; 101 std::vector<Shortcut> shortcuts;
102 102
103 Settings::BasicSetting<uint32_t> callout_flags{0, "calloutFlags"}; 103 Settings::Setting<uint32_t> callout_flags{0, "calloutFlags"};
104 104
105 // logging 105 // logging
106 Settings::BasicSetting<bool> show_console{false, "showConsole"}; 106 Settings::Setting<bool> show_console{false, "showConsole"};
107 107
108 // Game List 108 // Game List
109 Settings::BasicSetting<bool> show_add_ons{true, "show_add_ons"}; 109 Settings::Setting<bool> show_add_ons{true, "show_add_ons"};
110 Settings::BasicSetting<uint32_t> game_icon_size{64, "game_icon_size"}; 110 Settings::Setting<uint32_t> game_icon_size{64, "game_icon_size"};
111 Settings::BasicSetting<uint32_t> folder_icon_size{48, "folder_icon_size"}; 111 Settings::Setting<uint32_t> folder_icon_size{48, "folder_icon_size"};
112 Settings::BasicSetting<uint8_t> row_1_text_id{3, "row_1_text_id"}; 112 Settings::Setting<uint8_t> row_1_text_id{3, "row_1_text_id"};
113 Settings::BasicSetting<uint8_t> row_2_text_id{2, "row_2_text_id"}; 113 Settings::Setting<uint8_t> row_2_text_id{2, "row_2_text_id"};
114 std::atomic_bool is_game_list_reload_pending{false}; 114 std::atomic_bool is_game_list_reload_pending{false};
115 Settings::BasicSetting<bool> cache_game_list{true, "cache_game_list"}; 115 Settings::Setting<bool> cache_game_list{true, "cache_game_list"};
116 Settings::BasicSetting<bool> favorites_expanded{true, "favorites_expanded"}; 116 Settings::Setting<bool> favorites_expanded{true, "favorites_expanded"};
117 QVector<u64> favorited_ids; 117 QVector<u64> favorited_ids;
118 118
119 bool configuration_applied; 119 bool configuration_applied;
120 bool reset_to_defaults; 120 bool reset_to_defaults;
121 Settings::BasicSetting<bool> disable_web_applet{true, "disable_web_applet"}; 121 Settings::Setting<bool> disable_web_applet{true, "disable_web_applet"};
122}; 122};
123 123
124extern Values values; 124extern Values values;
diff --git a/src/yuzu_cmd/config.cpp b/src/yuzu_cmd/config.cpp
index fc4744fb0..903e02297 100644
--- a/src/yuzu_cmd/config.cpp
+++ b/src/yuzu_cmd/config.cpp
@@ -90,17 +90,17 @@ static const std::array<std::array<int, 5>, Settings::NativeAnalog::NumAnalogs>
90}}; 90}};
91 91
92template <> 92template <>
93void Config::ReadSetting(const std::string& group, Settings::BasicSetting<std::string>& setting) { 93void Config::ReadSetting(const std::string& group, Settings::Setting<std::string>& setting) {
94 setting = sdl2_config->Get(group, setting.GetLabel(), setting.GetDefault()); 94 setting = sdl2_config->Get(group, setting.GetLabel(), setting.GetDefault());
95} 95}
96 96
97template <> 97template <>
98void Config::ReadSetting(const std::string& group, Settings::BasicSetting<bool>& setting) { 98void Config::ReadSetting(const std::string& group, Settings::Setting<bool>& setting) {
99 setting = sdl2_config->GetBoolean(group, setting.GetLabel(), setting.GetDefault()); 99 setting = sdl2_config->GetBoolean(group, setting.GetLabel(), setting.GetDefault());
100} 100}
101 101
102template <typename Type> 102template <typename Type>
103void Config::ReadSetting(const std::string& group, Settings::BasicSetting<Type>& setting) { 103void Config::ReadSetting(const std::string& group, Settings::Setting<Type>& setting) {
104 setting = static_cast<Type>(sdl2_config->GetInteger(group, setting.GetLabel(), 104 setting = static_cast<Type>(sdl2_config->GetInteger(group, setting.GetLabel(),
105 static_cast<long>(setting.GetDefault()))); 105 static_cast<long>(setting.GetDefault())));
106} 106}
diff --git a/src/yuzu_cmd/config.h b/src/yuzu_cmd/config.h
index f61ba23ec..ccf77d668 100644
--- a/src/yuzu_cmd/config.h
+++ b/src/yuzu_cmd/config.h
@@ -28,11 +28,11 @@ public:
28 28
29private: 29private:
30 /** 30 /**
31 * Applies a value read from the sdl2_config to a BasicSetting. 31 * Applies a value read from the sdl2_config to a Setting.
32 * 32 *
33 * @param group The name of the INI group 33 * @param group The name of the INI group
34 * @param setting The yuzu setting to modify 34 * @param setting The yuzu setting to modify
35 */ 35 */
36 template <typename Type> 36 template <typename Type>
37 void ReadSetting(const std::string& group, Settings::BasicSetting<Type>& setting); 37 void ReadSetting(const std::string& group, Settings::Setting<Type>& setting);
38}; 38};