summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/audio_core/audio_in_manager.cpp2
-rw-r--r--src/audio_core/audio_manager.cpp4
-rw-r--r--src/audio_core/audio_out_manager.cpp2
-rw-r--r--src/audio_core/audio_render_manager.cpp2
-rw-r--r--src/audio_core/in/audio_in.cpp2
-rw-r--r--src/audio_core/in/audio_in_system.cpp6
-rw-r--r--src/audio_core/out/audio_out.cpp2
-rw-r--r--src/audio_core/out/audio_out_system.cpp8
-rw-r--r--src/audio_core/renderer/audio_renderer.cpp2
-rw-r--r--src/audio_core/renderer/behavior/info_updater.cpp38
-rw-r--r--src/audio_core/renderer/command/effect/reverb.cpp3
-rw-r--r--src/audio_core/renderer/effect/i3dl2.h3
-rw-r--r--src/audio_core/renderer/effect/reverb.h8
-rw-r--r--src/audio_core/renderer/memory/pool_mapper.cpp2
-rw-r--r--src/audio_core/renderer/system.cpp50
-rw-r--r--src/audio_core/renderer/voice/voice_info.cpp8
-rw-r--r--src/common/CMakeLists.txt11
-rw-r--r--src/common/bit_cast.h20
-rw-r--r--src/common/input.h2
-rw-r--r--src/common/overflow.h22
-rw-r--r--src/common/settings.h8
-rw-r--r--src/common/steady_clock.cpp56
-rw-r--r--src/common/steady_clock.h23
-rw-r--r--src/common/wall_clock.cpp39
-rw-r--r--src/common/wall_clock.h3
-rw-r--r--src/common/windows/timer_resolution.cpp109
-rw-r--r--src/common/windows/timer_resolution.h38
-rw-r--r--src/common/x64/native_clock.cpp17
-rw-r--r--src/core/CMakeLists.txt1
-rw-r--r--src/core/constants.cpp27
-rw-r--r--src/core/constants.h2
-rw-r--r--src/core/core_timing.cpp55
-rw-r--r--src/core/core_timing.h6
-rw-r--r--src/core/hardware_properties.h8
-rw-r--r--src/core/hle/kernel/k_address_space_info.cpp4
-rw-r--r--src/core/hle/kernel/k_address_space_info.h2
-rw-r--r--src/core/hle/kernel/k_device_address_space.h4
-rw-r--r--src/core/hle/kernel/k_process.h4
-rw-r--r--src/core/hle/kernel/k_resource_limit.cpp3
-rw-r--r--src/core/hle/kernel/k_scoped_lock.h1
-rw-r--r--src/core/hle/kernel/svc/svc_synchronization.cpp45
-rw-r--r--src/core/hle/service/acc/acc.cpp26
-rw-r--r--src/core/hle/service/acc/errors.h10
-rw-r--r--src/core/hle/service/am/am.cpp20
-rw-r--r--src/core/hle/service/am/applets/applet_controller.cpp7
-rw-r--r--src/core/hle/service/am/applets/applet_profile_select.cpp7
-rw-r--r--src/core/hle/service/audio/audren_u.cpp6
-rw-r--r--src/core/hle/service/audio/errors.h24
-rw-r--r--src/core/hle/service/friend/errors.h11
-rw-r--r--src/core/hle/service/friend/friend.cpp4
-rw-r--r--src/core/hle/service/glue/arp.cpp18
-rw-r--r--src/core/hle/service/glue/errors.h7
-rw-r--r--src/core/hle/service/glue/glue_manager.cpp16
-rw-r--r--src/core/hle/service/glue/glue_manager.h16
-rw-r--r--src/core/hle/service/ipc_helpers.h2
-rw-r--r--src/core/hle/service/ns/errors.h5
-rw-r--r--src/core/hle/service/ns/ns.cpp8
-rw-r--r--src/core/hle/service/psc/psc.cpp18
-rw-r--r--src/core/hle/service/server_manager.cpp2
-rw-r--r--src/core/hle/service/service.cpp2
-rw-r--r--src/core/hle/service/set/set.cpp4
-rw-r--r--src/core/hle/service/sm/sm.cpp24
-rw-r--r--src/core/hle/service/ssl/ssl.cpp76
-rw-r--r--src/core/hle/service/usb/usb.cpp70
-rw-r--r--src/input_common/drivers/joycon.cpp4
-rw-r--r--src/input_common/drivers/virtual_amiibo.h2
-rw-r--r--src/input_common/helpers/joycon_driver.cpp2
-rw-r--r--src/input_common/helpers/joycon_driver.h2
-rw-r--r--src/input_common/helpers/joycon_protocol/joycon_types.h14
-rw-r--r--src/input_common/helpers/joycon_protocol/poller.cpp107
-rw-r--r--src/input_common/helpers/joycon_protocol/poller.h15
-rw-r--r--src/video_core/gpu.cpp2
-rw-r--r--src/video_core/renderer_opengl/gl_texture_cache.cpp13
-rw-r--r--src/video_core/renderer_vulkan/vk_buffer_cache.cpp4
-rw-r--r--src/video_core/renderer_vulkan/vk_rasterizer.cpp2
-rw-r--r--src/video_core/renderer_vulkan/vk_texture_cache.cpp11
-rw-r--r--src/yuzu/main.cpp9
-rw-r--r--src/yuzu_cmd/yuzu.cpp4
78 files changed, 814 insertions, 412 deletions
diff --git a/src/audio_core/audio_in_manager.cpp b/src/audio_core/audio_in_manager.cpp
index f39fb4002..3dfb613cb 100644
--- a/src/audio_core/audio_in_manager.cpp
+++ b/src/audio_core/audio_in_manager.cpp
@@ -20,7 +20,7 @@ Manager::Manager(Core::System& system_) : system{system_} {
20Result Manager::AcquireSessionId(size_t& session_id) { 20Result Manager::AcquireSessionId(size_t& session_id) {
21 if (num_free_sessions == 0) { 21 if (num_free_sessions == 0) {
22 LOG_ERROR(Service_Audio, "All 4 AudioIn sessions are in use, cannot create any more"); 22 LOG_ERROR(Service_Audio, "All 4 AudioIn sessions are in use, cannot create any more");
23 return Service::Audio::ERR_MAXIMUM_SESSIONS_REACHED; 23 return Service::Audio::ResultOutOfSessions;
24 } 24 }
25 session_id = session_ids[next_session_id]; 25 session_id = session_ids[next_session_id];
26 next_session_id = (next_session_id + 1) % MaxInSessions; 26 next_session_id = (next_session_id + 1) % MaxInSessions;
diff --git a/src/audio_core/audio_manager.cpp b/src/audio_core/audio_manager.cpp
index 2acde668e..10b56f214 100644
--- a/src/audio_core/audio_manager.cpp
+++ b/src/audio_core/audio_manager.cpp
@@ -19,7 +19,7 @@ void AudioManager::Shutdown() {
19 19
20Result AudioManager::SetOutManager(BufferEventFunc buffer_func) { 20Result AudioManager::SetOutManager(BufferEventFunc buffer_func) {
21 if (!running) { 21 if (!running) {
22 return Service::Audio::ERR_OPERATION_FAILED; 22 return Service::Audio::ResultOperationFailed;
23 } 23 }
24 24
25 std::scoped_lock l{lock}; 25 std::scoped_lock l{lock};
@@ -35,7 +35,7 @@ Result AudioManager::SetOutManager(BufferEventFunc buffer_func) {
35 35
36Result AudioManager::SetInManager(BufferEventFunc buffer_func) { 36Result AudioManager::SetInManager(BufferEventFunc buffer_func) {
37 if (!running) { 37 if (!running) {
38 return Service::Audio::ERR_OPERATION_FAILED; 38 return Service::Audio::ResultOperationFailed;
39 } 39 }
40 40
41 std::scoped_lock l{lock}; 41 std::scoped_lock l{lock};
diff --git a/src/audio_core/audio_out_manager.cpp b/src/audio_core/audio_out_manager.cpp
index 1766efde1..f22821360 100644
--- a/src/audio_core/audio_out_manager.cpp
+++ b/src/audio_core/audio_out_manager.cpp
@@ -19,7 +19,7 @@ Manager::Manager(Core::System& system_) : system{system_} {
19Result Manager::AcquireSessionId(size_t& session_id) { 19Result Manager::AcquireSessionId(size_t& session_id) {
20 if (num_free_sessions == 0) { 20 if (num_free_sessions == 0) {
21 LOG_ERROR(Service_Audio, "All 12 Audio Out sessions are in use, cannot create any more"); 21 LOG_ERROR(Service_Audio, "All 12 Audio Out sessions are in use, cannot create any more");
22 return Service::Audio::ERR_MAXIMUM_SESSIONS_REACHED; 22 return Service::Audio::ResultOutOfSessions;
23 } 23 }
24 session_id = session_ids[next_session_id]; 24 session_id = session_ids[next_session_id];
25 next_session_id = (next_session_id + 1) % MaxOutSessions; 25 next_session_id = (next_session_id + 1) % MaxOutSessions;
diff --git a/src/audio_core/audio_render_manager.cpp b/src/audio_core/audio_render_manager.cpp
index 7aba2b423..320715727 100644
--- a/src/audio_core/audio_render_manager.cpp
+++ b/src/audio_core/audio_render_manager.cpp
@@ -28,7 +28,7 @@ SystemManager& Manager::GetSystemManager() {
28Result Manager::GetWorkBufferSize(const AudioRendererParameterInternal& params, 28Result Manager::GetWorkBufferSize(const AudioRendererParameterInternal& params,
29 u64& out_count) const { 29 u64& out_count) const {
30 if (!CheckValidRevision(params.revision)) { 30 if (!CheckValidRevision(params.revision)) {
31 return Service::Audio::ERR_INVALID_REVISION; 31 return Service::Audio::ResultInvalidRevision;
32 } 32 }
33 33
34 out_count = System::GetWorkBufferSize(params); 34 out_count = System::GetWorkBufferSize(params);
diff --git a/src/audio_core/in/audio_in.cpp b/src/audio_core/in/audio_in.cpp
index 91ccd5ad7..df8c44d1f 100644
--- a/src/audio_core/in/audio_in.cpp
+++ b/src/audio_core/in/audio_in.cpp
@@ -46,7 +46,7 @@ Result In::AppendBuffer(const AudioInBuffer& buffer, u64 tag) {
46 if (system.AppendBuffer(buffer, tag)) { 46 if (system.AppendBuffer(buffer, tag)) {
47 return ResultSuccess; 47 return ResultSuccess;
48 } 48 }
49 return Service::Audio::ERR_BUFFER_COUNT_EXCEEDED; 49 return Service::Audio::ResultBufferCountReached;
50} 50}
51 51
52void In::ReleaseAndRegisterBuffers() { 52void In::ReleaseAndRegisterBuffers() {
diff --git a/src/audio_core/in/audio_in_system.cpp b/src/audio_core/in/audio_in_system.cpp
index 934ef8c1c..e23e51758 100644
--- a/src/audio_core/in/audio_in_system.cpp
+++ b/src/audio_core/in/audio_in_system.cpp
@@ -45,11 +45,11 @@ Result System::IsConfigValid(const std::string_view device_name,
45 const AudioInParameter& in_params) const { 45 const AudioInParameter& in_params) const {
46 if ((device_name.size() > 0) && 46 if ((device_name.size() > 0) &&
47 (device_name != GetDefaultDeviceName() && device_name != GetDefaultUacDeviceName())) { 47 (device_name != GetDefaultDeviceName() && device_name != GetDefaultUacDeviceName())) {
48 return Service::Audio::ERR_INVALID_DEVICE_NAME; 48 return Service::Audio::ResultNotFound;
49 } 49 }
50 50
51 if (in_params.sample_rate != TargetSampleRate && in_params.sample_rate > 0) { 51 if (in_params.sample_rate != TargetSampleRate && in_params.sample_rate > 0) {
52 return Service::Audio::ERR_INVALID_SAMPLE_RATE; 52 return Service::Audio::ResultInvalidSampleRate;
53 } 53 }
54 54
55 return ResultSuccess; 55 return ResultSuccess;
@@ -80,7 +80,7 @@ Result System::Initialize(std::string device_name, const AudioInParameter& in_pa
80 80
81Result System::Start() { 81Result System::Start() {
82 if (state != State::Stopped) { 82 if (state != State::Stopped) {
83 return Service::Audio::ERR_OPERATION_FAILED; 83 return Service::Audio::ResultOperationFailed;
84 } 84 }
85 85
86 session->Initialize(name, sample_format, channel_count, session_id, handle, 86 session->Initialize(name, sample_format, channel_count, session_id, handle,
diff --git a/src/audio_core/out/audio_out.cpp b/src/audio_core/out/audio_out.cpp
index d3ee4f0eb..b7ea13405 100644
--- a/src/audio_core/out/audio_out.cpp
+++ b/src/audio_core/out/audio_out.cpp
@@ -46,7 +46,7 @@ Result Out::AppendBuffer(const AudioOutBuffer& buffer, const u64 tag) {
46 if (system.AppendBuffer(buffer, tag)) { 46 if (system.AppendBuffer(buffer, tag)) {
47 return ResultSuccess; 47 return ResultSuccess;
48 } 48 }
49 return Service::Audio::ERR_BUFFER_COUNT_EXCEEDED; 49 return Service::Audio::ResultBufferCountReached;
50} 50}
51 51
52void Out::ReleaseAndRegisterBuffers() { 52void Out::ReleaseAndRegisterBuffers() {
diff --git a/src/audio_core/out/audio_out_system.cpp b/src/audio_core/out/audio_out_system.cpp
index e096a1dac..bd13f7219 100644
--- a/src/audio_core/out/audio_out_system.cpp
+++ b/src/audio_core/out/audio_out_system.cpp
@@ -33,11 +33,11 @@ std::string_view System::GetDefaultOutputDeviceName() const {
33Result System::IsConfigValid(std::string_view device_name, 33Result System::IsConfigValid(std::string_view device_name,
34 const AudioOutParameter& in_params) const { 34 const AudioOutParameter& in_params) const {
35 if ((device_name.size() > 0) && (device_name != GetDefaultOutputDeviceName())) { 35 if ((device_name.size() > 0) && (device_name != GetDefaultOutputDeviceName())) {
36 return Service::Audio::ERR_INVALID_DEVICE_NAME; 36 return Service::Audio::ResultNotFound;
37 } 37 }
38 38
39 if (in_params.sample_rate != TargetSampleRate && in_params.sample_rate > 0) { 39 if (in_params.sample_rate != TargetSampleRate && in_params.sample_rate > 0) {
40 return Service::Audio::ERR_INVALID_SAMPLE_RATE; 40 return Service::Audio::ResultInvalidSampleRate;
41 } 41 }
42 42
43 if (in_params.channel_count == 0 || in_params.channel_count == 2 || 43 if (in_params.channel_count == 0 || in_params.channel_count == 2 ||
@@ -45,7 +45,7 @@ Result System::IsConfigValid(std::string_view device_name,
45 return ResultSuccess; 45 return ResultSuccess;
46 } 46 }
47 47
48 return Service::Audio::ERR_INVALID_CHANNEL_COUNT; 48 return Service::Audio::ResultInvalidChannelCount;
49} 49}
50 50
51Result System::Initialize(std::string device_name, const AudioOutParameter& in_params, u32 handle_, 51Result System::Initialize(std::string device_name, const AudioOutParameter& in_params, u32 handle_,
@@ -80,7 +80,7 @@ size_t System::GetSessionId() const {
80 80
81Result System::Start() { 81Result System::Start() {
82 if (state != State::Stopped) { 82 if (state != State::Stopped) {
83 return Service::Audio::ERR_OPERATION_FAILED; 83 return Service::Audio::ResultOperationFailed;
84 } 84 }
85 85
86 session->Initialize(name, sample_format, channel_count, session_id, handle, 86 session->Initialize(name, sample_format, channel_count, session_id, handle,
diff --git a/src/audio_core/renderer/audio_renderer.cpp b/src/audio_core/renderer/audio_renderer.cpp
index 51aa17599..a8257eb2e 100644
--- a/src/audio_core/renderer/audio_renderer.cpp
+++ b/src/audio_core/renderer/audio_renderer.cpp
@@ -22,7 +22,7 @@ Result Renderer::Initialize(const AudioRendererParameterInternal& params,
22 if (!manager.AddSystem(system)) { 22 if (!manager.AddSystem(system)) {
23 LOG_ERROR(Service_Audio, 23 LOG_ERROR(Service_Audio,
24 "Both Audio Render sessions are in use, cannot create any more"); 24 "Both Audio Render sessions are in use, cannot create any more");
25 return Service::Audio::ERR_MAXIMUM_SESSIONS_REACHED; 25 return Service::Audio::ResultOutOfSessions;
26 } 26 }
27 system_registered = true; 27 system_registered = true;
28 } 28 }
diff --git a/src/audio_core/renderer/behavior/info_updater.cpp b/src/audio_core/renderer/behavior/info_updater.cpp
index 574cf0982..e312eb166 100644
--- a/src/audio_core/renderer/behavior/info_updater.cpp
+++ b/src/audio_core/renderer/behavior/info_updater.cpp
@@ -48,7 +48,7 @@ Result InfoUpdater::UpdateVoiceChannelResources(VoiceContext& voice_context) {
48 LOG_ERROR(Service_Audio, 48 LOG_ERROR(Service_Audio,
49 "Consumed an incorrect voice resource size, header size={}, consumed={}", 49 "Consumed an incorrect voice resource size, header size={}, consumed={}",
50 in_header->voice_resources_size, consumed_input_size); 50 in_header->voice_resources_size, consumed_input_size);
51 return Service::Audio::ERR_INVALID_UPDATE_DATA; 51 return Service::Audio::ResultInvalidUpdateInfo;
52 } 52 }
53 53
54 input += consumed_input_size; 54 input += consumed_input_size;
@@ -123,7 +123,7 @@ Result InfoUpdater::UpdateVoices(VoiceContext& voice_context,
123 if (consumed_input_size != in_header->voices_size) { 123 if (consumed_input_size != in_header->voices_size) {
124 LOG_ERROR(Service_Audio, "Consumed an incorrect voices size, header size={}, consumed={}", 124 LOG_ERROR(Service_Audio, "Consumed an incorrect voices size, header size={}, consumed={}",
125 in_header->voices_size, consumed_input_size); 125 in_header->voices_size, consumed_input_size);
126 return Service::Audio::ERR_INVALID_UPDATE_DATA; 126 return Service::Audio::ResultInvalidUpdateInfo;
127 } 127 }
128 128
129 out_header->voices_size = consumed_output_size; 129 out_header->voices_size = consumed_output_size;
@@ -184,7 +184,7 @@ Result InfoUpdater::UpdateEffectsVersion1(EffectContext& effect_context, const b
184 if (consumed_input_size != in_header->effects_size) { 184 if (consumed_input_size != in_header->effects_size) {
185 LOG_ERROR(Service_Audio, "Consumed an incorrect effects size, header size={}, consumed={}", 185 LOG_ERROR(Service_Audio, "Consumed an incorrect effects size, header size={}, consumed={}",
186 in_header->effects_size, consumed_input_size); 186 in_header->effects_size, consumed_input_size);
187 return Service::Audio::ERR_INVALID_UPDATE_DATA; 187 return Service::Audio::ResultInvalidUpdateInfo;
188 } 188 }
189 189
190 out_header->effects_size = consumed_output_size; 190 out_header->effects_size = consumed_output_size;
@@ -239,7 +239,7 @@ Result InfoUpdater::UpdateEffectsVersion2(EffectContext& effect_context, const b
239 if (consumed_input_size != in_header->effects_size) { 239 if (consumed_input_size != in_header->effects_size) {
240 LOG_ERROR(Service_Audio, "Consumed an incorrect effects size, header size={}, consumed={}", 240 LOG_ERROR(Service_Audio, "Consumed an incorrect effects size, header size={}, consumed={}",
241 in_header->effects_size, consumed_input_size); 241 in_header->effects_size, consumed_input_size);
242 return Service::Audio::ERR_INVALID_UPDATE_DATA; 242 return Service::Audio::ResultInvalidUpdateInfo;
243 } 243 }
244 244
245 out_header->effects_size = consumed_output_size; 245 out_header->effects_size = consumed_output_size;
@@ -267,7 +267,7 @@ Result InfoUpdater::UpdateMixes(MixContext& mix_context, const u32 mix_buffer_co
267 } 267 }
268 268
269 if (mix_buffer_count == 0) { 269 if (mix_buffer_count == 0) {
270 return Service::Audio::ERR_INVALID_UPDATE_DATA; 270 return Service::Audio::ResultInvalidUpdateInfo;
271 } 271 }
272 272
273 std::span<const MixInfo::InParameter> in_params{ 273 std::span<const MixInfo::InParameter> in_params{
@@ -281,13 +281,13 @@ Result InfoUpdater::UpdateMixes(MixContext& mix_context, const u32 mix_buffer_co
281 total_buffer_count += params.buffer_count; 281 total_buffer_count += params.buffer_count;
282 if (params.dest_mix_id > static_cast<s32>(mix_context.GetCount()) && 282 if (params.dest_mix_id > static_cast<s32>(mix_context.GetCount()) &&
283 params.dest_mix_id != UnusedMixId && params.mix_id != FinalMixId) { 283 params.dest_mix_id != UnusedMixId && params.mix_id != FinalMixId) {
284 return Service::Audio::ERR_INVALID_UPDATE_DATA; 284 return Service::Audio::ResultInvalidUpdateInfo;
285 } 285 }
286 } 286 }
287 } 287 }
288 288
289 if (total_buffer_count > mix_buffer_count) { 289 if (total_buffer_count > mix_buffer_count) {
290 return Service::Audio::ERR_INVALID_UPDATE_DATA; 290 return Service::Audio::ResultInvalidUpdateInfo;
291 } 291 }
292 292
293 bool mix_dirty{false}; 293 bool mix_dirty{false};
@@ -317,7 +317,7 @@ Result InfoUpdater::UpdateMixes(MixContext& mix_context, const u32 mix_buffer_co
317 if (mix_dirty) { 317 if (mix_dirty) {
318 if (behaviour.IsSplitterSupported() && splitter_context.UsingSplitter()) { 318 if (behaviour.IsSplitterSupported() && splitter_context.UsingSplitter()) {
319 if (!mix_context.TSortInfo(splitter_context)) { 319 if (!mix_context.TSortInfo(splitter_context)) {
320 return Service::Audio::ERR_INVALID_UPDATE_DATA; 320 return Service::Audio::ResultInvalidUpdateInfo;
321 } 321 }
322 } else { 322 } else {
323 mix_context.SortInfo(); 323 mix_context.SortInfo();
@@ -327,7 +327,7 @@ Result InfoUpdater::UpdateMixes(MixContext& mix_context, const u32 mix_buffer_co
327 if (consumed_input_size != in_header->mix_size) { 327 if (consumed_input_size != in_header->mix_size) {
328 LOG_ERROR(Service_Audio, "Consumed an incorrect mixes size, header size={}, consumed={}", 328 LOG_ERROR(Service_Audio, "Consumed an incorrect mixes size, header size={}, consumed={}",
329 in_header->mix_size, consumed_input_size); 329 in_header->mix_size, consumed_input_size);
330 return Service::Audio::ERR_INVALID_UPDATE_DATA; 330 return Service::Audio::ResultInvalidUpdateInfo;
331 } 331 }
332 332
333 input += mix_count * sizeof(MixInfo::InParameter); 333 input += mix_count * sizeof(MixInfo::InParameter);
@@ -384,7 +384,7 @@ Result InfoUpdater::UpdateSinks(SinkContext& sink_context, std::span<MemoryPoolI
384 if (consumed_input_size != in_header->sinks_size) { 384 if (consumed_input_size != in_header->sinks_size) {
385 LOG_ERROR(Service_Audio, "Consumed an incorrect sinks size, header size={}, consumed={}", 385 LOG_ERROR(Service_Audio, "Consumed an incorrect sinks size, header size={}, consumed={}",
386 in_header->sinks_size, consumed_input_size); 386 in_header->sinks_size, consumed_input_size);
387 return Service::Audio::ERR_INVALID_UPDATE_DATA; 387 return Service::Audio::ResultInvalidUpdateInfo;
388 } 388 }
389 389
390 input += consumed_input_size; 390 input += consumed_input_size;
@@ -411,7 +411,7 @@ Result InfoUpdater::UpdateMemoryPools(std::span<MemoryPoolInfo> memory_pools,
411 state != MemoryPoolInfo::ResultState::MapFailed && 411 state != MemoryPoolInfo::ResultState::MapFailed &&
412 state != MemoryPoolInfo::ResultState::InUse) { 412 state != MemoryPoolInfo::ResultState::InUse) {
413 LOG_WARNING(Service_Audio, "Invalid ResultState from updating memory pools"); 413 LOG_WARNING(Service_Audio, "Invalid ResultState from updating memory pools");
414 return Service::Audio::ERR_INVALID_UPDATE_DATA; 414 return Service::Audio::ResultInvalidUpdateInfo;
415 } 415 }
416 } 416 }
417 417
@@ -423,7 +423,7 @@ Result InfoUpdater::UpdateMemoryPools(std::span<MemoryPoolInfo> memory_pools,
423 LOG_ERROR(Service_Audio, 423 LOG_ERROR(Service_Audio,
424 "Consumed an incorrect memory pool size, header size={}, consumed={}", 424 "Consumed an incorrect memory pool size, header size={}, consumed={}",
425 in_header->memory_pool_size, consumed_input_size); 425 in_header->memory_pool_size, consumed_input_size);
426 return Service::Audio::ERR_INVALID_UPDATE_DATA; 426 return Service::Audio::ResultInvalidUpdateInfo;
427 } 427 }
428 428
429 input += consumed_input_size; 429 input += consumed_input_size;
@@ -453,7 +453,7 @@ Result InfoUpdater::UpdatePerformanceBuffer(std::span<u8> performance_output,
453 LOG_ERROR(Service_Audio, 453 LOG_ERROR(Service_Audio,
454 "Consumed an incorrect performance size, header size={}, consumed={}", 454 "Consumed an incorrect performance size, header size={}, consumed={}",
455 in_header->performance_buffer_size, consumed_input_size); 455 in_header->performance_buffer_size, consumed_input_size);
456 return Service::Audio::ERR_INVALID_UPDATE_DATA; 456 return Service::Audio::ResultInvalidUpdateInfo;
457 } 457 }
458 458
459 input += consumed_input_size; 459 input += consumed_input_size;
@@ -467,18 +467,18 @@ Result InfoUpdater::UpdateBehaviorInfo(BehaviorInfo& behaviour_) {
467 const auto in_params{reinterpret_cast<const BehaviorInfo::InParameter*>(input)}; 467 const auto in_params{reinterpret_cast<const BehaviorInfo::InParameter*>(input)};
468 468
469 if (!CheckValidRevision(in_params->revision)) { 469 if (!CheckValidRevision(in_params->revision)) {
470 return Service::Audio::ERR_INVALID_UPDATE_DATA; 470 return Service::Audio::ResultInvalidUpdateInfo;
471 } 471 }
472 472
473 if (in_params->revision != behaviour_.GetUserRevision()) { 473 if (in_params->revision != behaviour_.GetUserRevision()) {
474 return Service::Audio::ERR_INVALID_UPDATE_DATA; 474 return Service::Audio::ResultInvalidUpdateInfo;
475 } 475 }
476 476
477 behaviour_.ClearError(); 477 behaviour_.ClearError();
478 behaviour_.UpdateFlags(in_params->flags); 478 behaviour_.UpdateFlags(in_params->flags);
479 479
480 if (in_header->behaviour_size != sizeof(BehaviorInfo::InParameter)) { 480 if (in_header->behaviour_size != sizeof(BehaviorInfo::InParameter)) {
481 return Service::Audio::ERR_INVALID_UPDATE_DATA; 481 return Service::Audio::ResultInvalidUpdateInfo;
482 } 482 }
483 483
484 input += sizeof(BehaviorInfo::InParameter); 484 input += sizeof(BehaviorInfo::InParameter);
@@ -500,7 +500,7 @@ Result InfoUpdater::UpdateErrorInfo(const BehaviorInfo& behaviour_) {
500Result InfoUpdater::UpdateSplitterInfo(SplitterContext& splitter_context) { 500Result InfoUpdater::UpdateSplitterInfo(SplitterContext& splitter_context) {
501 u32 consumed_size{0}; 501 u32 consumed_size{0};
502 if (!splitter_context.Update(input, consumed_size)) { 502 if (!splitter_context.Update(input, consumed_size)) {
503 return Service::Audio::ERR_INVALID_UPDATE_DATA; 503 return Service::Audio::ResultInvalidUpdateInfo;
504 } 504 }
505 505
506 input += consumed_size; 506 input += consumed_size;
@@ -529,9 +529,9 @@ Result InfoUpdater::UpdateRendererInfo(const u64 elapsed_frames) {
529 529
530Result InfoUpdater::CheckConsumedSize() { 530Result InfoUpdater::CheckConsumedSize() {
531 if (CpuAddr(input) - CpuAddr(input_origin.data()) != expected_input_size) { 531 if (CpuAddr(input) - CpuAddr(input_origin.data()) != expected_input_size) {
532 return Service::Audio::ERR_INVALID_UPDATE_DATA; 532 return Service::Audio::ResultInvalidUpdateInfo;
533 } else if (CpuAddr(output) - CpuAddr(output_origin.data()) != expected_output_size) { 533 } else if (CpuAddr(output) - CpuAddr(output_origin.data()) != expected_output_size) {
534 return Service::Audio::ERR_INVALID_UPDATE_DATA; 534 return Service::Audio::ResultInvalidUpdateInfo;
535 } 535 }
536 return ResultSuccess; 536 return ResultSuccess;
537} 537}
diff --git a/src/audio_core/renderer/command/effect/reverb.cpp b/src/audio_core/renderer/command/effect/reverb.cpp
index 6fe844ff0..8b9b65214 100644
--- a/src/audio_core/renderer/command/effect/reverb.cpp
+++ b/src/audio_core/renderer/command/effect/reverb.cpp
@@ -308,7 +308,8 @@ static void ApplyReverbEffect(const ReverbInfo::ParameterVersion2& params, Rever
308 } 308 }
309 309
310 Common::FixedPoint<50, 14> pre_delay_sample{ 310 Common::FixedPoint<50, 14> pre_delay_sample{
311 state.pre_delay_line.Read() * Common::FixedPoint<50, 14>::from_base(params.late_gain)}; 311 state.pre_delay_line.TapOut(state.pre_delay_time) *
312 Common::FixedPoint<50, 14>::from_base(params.late_gain)};
312 313
313 std::array<Common::FixedPoint<50, 14>, ReverbInfo::MaxDelayLines> mix_matrix{ 314 std::array<Common::FixedPoint<50, 14>, ReverbInfo::MaxDelayLines> mix_matrix{
314 state.prev_feedback_output[2] + state.prev_feedback_output[1] + pre_delay_sample, 315 state.prev_feedback_output[2] + state.prev_feedback_output[1] + pre_delay_sample,
diff --git a/src/audio_core/renderer/effect/i3dl2.h b/src/audio_core/renderer/effect/i3dl2.h
index 1ebbc5c4c..6e3ffd1d4 100644
--- a/src/audio_core/renderer/effect/i3dl2.h
+++ b/src/audio_core/renderer/effect/i3dl2.h
@@ -104,7 +104,8 @@ public:
104 } 104 }
105 105
106 void Write(const Common::FixedPoint<50, 14> sample) { 106 void Write(const Common::FixedPoint<50, 14> sample) {
107 *(input++) = sample; 107 *input = sample;
108 input++;
108 if (input >= buffer_end) { 109 if (input >= buffer_end) {
109 input = buffer.data(); 110 input = buffer.data();
110 } 111 }
diff --git a/src/audio_core/renderer/effect/reverb.h b/src/audio_core/renderer/effect/reverb.h
index a72475c3c..6cc345ef6 100644
--- a/src/audio_core/renderer/effect/reverb.h
+++ b/src/audio_core/renderer/effect/reverb.h
@@ -79,12 +79,10 @@ public:
79 return; 79 return;
80 } 80 }
81 sample_count = delay_time; 81 sample_count = delay_time;
82 input = &buffer[(output - buffer.data() + sample_count) % (sample_count_max + 1)]; 82 input = &buffer[0];
83 } 83 }
84 84
85 Common::FixedPoint<50, 14> Tick(const Common::FixedPoint<50, 14> sample) { 85 Common::FixedPoint<50, 14> Tick(const Common::FixedPoint<50, 14> sample) {
86 Write(sample);
87
88 auto out_sample{Read()}; 86 auto out_sample{Read()};
89 87
90 output++; 88 output++;
@@ -92,6 +90,7 @@ public:
92 output = buffer.data(); 90 output = buffer.data();
93 } 91 }
94 92
93 Write(sample);
95 return out_sample; 94 return out_sample;
96 } 95 }
97 96
@@ -100,7 +99,8 @@ public:
100 } 99 }
101 100
102 void Write(const Common::FixedPoint<50, 14> sample) { 101 void Write(const Common::FixedPoint<50, 14> sample) {
103 *(input++) = sample; 102 *input = sample;
103 input++;
104 if (input >= buffer_end) { 104 if (input >= buffer_end) {
105 input = buffer.data(); 105 input = buffer.data();
106 } 106 }
diff --git a/src/audio_core/renderer/memory/pool_mapper.cpp b/src/audio_core/renderer/memory/pool_mapper.cpp
index 2baf2ce08..7fd2b5f47 100644
--- a/src/audio_core/renderer/memory/pool_mapper.cpp
+++ b/src/audio_core/renderer/memory/pool_mapper.cpp
@@ -92,7 +92,7 @@ bool PoolMapper::TryAttachBuffer(BehaviorInfo::ErrorInfo& error_info, AddressInf
92 address_info.Setup(address, size); 92 address_info.Setup(address, size);
93 93
94 if (!FillDspAddr(address_info)) { 94 if (!FillDspAddr(address_info)) {
95 error_info.error_code = Service::Audio::ERR_POOL_MAPPING_FAILED; 95 error_info.error_code = Service::Audio::ResultInvalidAddressInfo;
96 error_info.address = address; 96 error_info.address = address;
97 return force_map; 97 return force_map;
98 } 98 }
diff --git a/src/audio_core/renderer/system.cpp b/src/audio_core/renderer/system.cpp
index 31cbee282..28f063641 100644
--- a/src/audio_core/renderer/system.cpp
+++ b/src/audio_core/renderer/system.cpp
@@ -101,15 +101,15 @@ Result System::Initialize(const AudioRendererParameterInternal& params,
101 Kernel::KTransferMemory* transfer_memory, u64 transfer_memory_size, 101 Kernel::KTransferMemory* transfer_memory, u64 transfer_memory_size,
102 u32 process_handle_, u64 applet_resource_user_id_, s32 session_id_) { 102 u32 process_handle_, u64 applet_resource_user_id_, s32 session_id_) {
103 if (!CheckValidRevision(params.revision)) { 103 if (!CheckValidRevision(params.revision)) {
104 return Service::Audio::ERR_INVALID_REVISION; 104 return Service::Audio::ResultInvalidRevision;
105 } 105 }
106 106
107 if (GetWorkBufferSize(params) > transfer_memory_size) { 107 if (GetWorkBufferSize(params) > transfer_memory_size) {
108 return Service::Audio::ERR_INSUFFICIENT_BUFFER_SIZE; 108 return Service::Audio::ResultInsufficientBuffer;
109 } 109 }
110 110
111 if (process_handle_ == 0) { 111 if (process_handle_ == 0) {
112 return Service::Audio::ERR_INVALID_PROCESS_HANDLE; 112 return Service::Audio::ResultInvalidHandle;
113 } 113 }
114 114
115 behavior.SetUserLibRevision(params.revision); 115 behavior.SetUserLibRevision(params.revision);
@@ -143,19 +143,19 @@ Result System::Initialize(const AudioRendererParameterInternal& params,
143 samples_workbuffer = 143 samples_workbuffer =
144 allocator.Allocate<s32>((voice_channels + mix_buffer_count) * sample_count, 0x10); 144 allocator.Allocate<s32>((voice_channels + mix_buffer_count) * sample_count, 0x10);
145 if (samples_workbuffer.empty()) { 145 if (samples_workbuffer.empty()) {
146 return Service::Audio::ERR_INSUFFICIENT_BUFFER_SIZE; 146 return Service::Audio::ResultInsufficientBuffer;
147 } 147 }
148 148
149 auto upsampler_workbuffer{allocator.Allocate<s32>( 149 auto upsampler_workbuffer{allocator.Allocate<s32>(
150 (voice_channels + mix_buffer_count) * TargetSampleCount * upsampler_count, 0x10)}; 150 (voice_channels + mix_buffer_count) * TargetSampleCount * upsampler_count, 0x10)};
151 if (upsampler_workbuffer.empty()) { 151 if (upsampler_workbuffer.empty()) {
152 return Service::Audio::ERR_INSUFFICIENT_BUFFER_SIZE; 152 return Service::Audio::ResultInsufficientBuffer;
153 } 153 }
154 154
155 depop_buffer = 155 depop_buffer =
156 allocator.Allocate<s32>(Common::AlignUp(static_cast<u32>(mix_buffer_count), 0x40), 0x40); 156 allocator.Allocate<s32>(Common::AlignUp(static_cast<u32>(mix_buffer_count), 0x40), 0x40);
157 if (depop_buffer.empty()) { 157 if (depop_buffer.empty()) {
158 return Service::Audio::ERR_INSUFFICIENT_BUFFER_SIZE; 158 return Service::Audio::ResultInsufficientBuffer;
159 } 159 }
160 160
161 // invalidate samples_workbuffer DSP cache 161 // invalidate samples_workbuffer DSP cache
@@ -166,12 +166,12 @@ Result System::Initialize(const AudioRendererParameterInternal& params,
166 } 166 }
167 167
168 if (voice_infos.empty()) { 168 if (voice_infos.empty()) {
169 return Service::Audio::ERR_INSUFFICIENT_BUFFER_SIZE; 169 return Service::Audio::ResultInsufficientBuffer;
170 } 170 }
171 171
172 auto sorted_voice_infos{allocator.Allocate<VoiceInfo*>(params.voices, 0x10)}; 172 auto sorted_voice_infos{allocator.Allocate<VoiceInfo*>(params.voices, 0x10)};
173 if (sorted_voice_infos.empty()) { 173 if (sorted_voice_infos.empty()) {
174 return Service::Audio::ERR_INSUFFICIENT_BUFFER_SIZE; 174 return Service::Audio::ResultInsufficientBuffer;
175 } 175 }
176 176
177 std::memset(sorted_voice_infos.data(), 0, sorted_voice_infos.size_bytes()); 177 std::memset(sorted_voice_infos.data(), 0, sorted_voice_infos.size_bytes());
@@ -183,12 +183,12 @@ Result System::Initialize(const AudioRendererParameterInternal& params,
183 } 183 }
184 184
185 if (voice_channel_resources.empty()) { 185 if (voice_channel_resources.empty()) {
186 return Service::Audio::ERR_INSUFFICIENT_BUFFER_SIZE; 186 return Service::Audio::ResultInsufficientBuffer;
187 } 187 }
188 188
189 auto voice_cpu_states{allocator.Allocate<VoiceState>(params.voices, 0x10)}; 189 auto voice_cpu_states{allocator.Allocate<VoiceState>(params.voices, 0x10)};
190 if (voice_cpu_states.empty()) { 190 if (voice_cpu_states.empty()) {
191 return Service::Audio::ERR_INSUFFICIENT_BUFFER_SIZE; 191 return Service::Audio::ResultInsufficientBuffer;
192 } 192 }
193 193
194 for (auto& voice_state : voice_cpu_states) { 194 for (auto& voice_state : voice_cpu_states) {
@@ -198,7 +198,7 @@ Result System::Initialize(const AudioRendererParameterInternal& params,
198 auto mix_infos{allocator.Allocate<MixInfo>(params.sub_mixes + 1, 0x10)}; 198 auto mix_infos{allocator.Allocate<MixInfo>(params.sub_mixes + 1, 0x10)};
199 199
200 if (mix_infos.empty()) { 200 if (mix_infos.empty()) {
201 return Service::Audio::ERR_INSUFFICIENT_BUFFER_SIZE; 201 return Service::Audio::ResultInsufficientBuffer;
202 } 202 }
203 203
204 u32 effect_process_order_count{0}; 204 u32 effect_process_order_count{0};
@@ -208,7 +208,7 @@ Result System::Initialize(const AudioRendererParameterInternal& params,
208 effect_process_order_count = params.effects * (params.sub_mixes + 1); 208 effect_process_order_count = params.effects * (params.sub_mixes + 1);
209 effect_process_order_buffer = allocator.Allocate<s32>(effect_process_order_count, 0x10); 209 effect_process_order_buffer = allocator.Allocate<s32>(effect_process_order_count, 0x10);
210 if (effect_process_order_buffer.empty()) { 210 if (effect_process_order_buffer.empty()) {
211 return Service::Audio::ERR_INSUFFICIENT_BUFFER_SIZE; 211 return Service::Audio::ResultInsufficientBuffer;
212 } 212 }
213 } 213 }
214 214
@@ -222,7 +222,7 @@ Result System::Initialize(const AudioRendererParameterInternal& params,
222 222
223 auto sorted_mix_infos{allocator.Allocate<MixInfo*>(params.sub_mixes + 1, 0x10)}; 223 auto sorted_mix_infos{allocator.Allocate<MixInfo*>(params.sub_mixes + 1, 0x10)};
224 if (sorted_mix_infos.empty()) { 224 if (sorted_mix_infos.empty()) {
225 return Service::Audio::ERR_INSUFFICIENT_BUFFER_SIZE; 225 return Service::Audio::ResultInsufficientBuffer;
226 } 226 }
227 227
228 std::memset(sorted_mix_infos.data(), 0, sorted_mix_infos.size_bytes()); 228 std::memset(sorted_mix_infos.data(), 0, sorted_mix_infos.size_bytes());
@@ -235,7 +235,7 @@ Result System::Initialize(const AudioRendererParameterInternal& params,
235 auto edge_matrix_workbuffer{allocator.Allocate<u8>(edge_matrix_size, 1)}; 235 auto edge_matrix_workbuffer{allocator.Allocate<u8>(edge_matrix_size, 1)};
236 236
237 if (node_states_workbuffer.empty() || edge_matrix_workbuffer.size() == 0) { 237 if (node_states_workbuffer.empty() || edge_matrix_workbuffer.size() == 0) {
238 return Service::Audio::ERR_INSUFFICIENT_BUFFER_SIZE; 238 return Service::Audio::ResultInsufficientBuffer;
239 } 239 }
240 240
241 mix_context.Initialize(sorted_mix_infos, mix_infos, params.sub_mixes + 1, 241 mix_context.Initialize(sorted_mix_infos, mix_infos, params.sub_mixes + 1,
@@ -250,7 +250,7 @@ Result System::Initialize(const AudioRendererParameterInternal& params,
250 250
251 upsampler_manager = allocator.Allocate<UpsamplerManager>(1, 0x10).data(); 251 upsampler_manager = allocator.Allocate<UpsamplerManager>(1, 0x10).data();
252 if (upsampler_manager == nullptr) { 252 if (upsampler_manager == nullptr) {
253 return Service::Audio::ERR_INSUFFICIENT_BUFFER_SIZE; 253 return Service::Audio::ResultInsufficientBuffer;
254 } 254 }
255 255
256 memory_pool_workbuffer = allocator.Allocate<MemoryPoolInfo>(memory_pool_count, 0x10); 256 memory_pool_workbuffer = allocator.Allocate<MemoryPoolInfo>(memory_pool_count, 0x10);
@@ -259,18 +259,18 @@ Result System::Initialize(const AudioRendererParameterInternal& params,
259 } 259 }
260 260
261 if (memory_pool_workbuffer.empty() && memory_pool_count > 0) { 261 if (memory_pool_workbuffer.empty() && memory_pool_count > 0) {
262 return Service::Audio::ERR_INSUFFICIENT_BUFFER_SIZE; 262 return Service::Audio::ResultInsufficientBuffer;
263 } 263 }
264 264
265 if (!splitter_context.Initialize(behavior, params, allocator)) { 265 if (!splitter_context.Initialize(behavior, params, allocator)) {
266 return Service::Audio::ERR_INSUFFICIENT_BUFFER_SIZE; 266 return Service::Audio::ResultInsufficientBuffer;
267 } 267 }
268 268
269 std::span<EffectResultState> effect_result_states_cpu{}; 269 std::span<EffectResultState> effect_result_states_cpu{};
270 if (behavior.IsEffectInfoVersion2Supported() && params.effects > 0) { 270 if (behavior.IsEffectInfoVersion2Supported() && params.effects > 0) {
271 effect_result_states_cpu = allocator.Allocate<EffectResultState>(params.effects, 0x10); 271 effect_result_states_cpu = allocator.Allocate<EffectResultState>(params.effects, 0x10);
272 if (effect_result_states_cpu.empty()) { 272 if (effect_result_states_cpu.empty()) {
273 return Service::Audio::ERR_INSUFFICIENT_BUFFER_SIZE; 273 return Service::Audio::ResultInsufficientBuffer;
274 } 274 }
275 std::memset(effect_result_states_cpu.data(), 0, effect_result_states_cpu.size_bytes()); 275 std::memset(effect_result_states_cpu.data(), 0, effect_result_states_cpu.size_bytes());
276 } 276 }
@@ -289,7 +289,7 @@ Result System::Initialize(const AudioRendererParameterInternal& params,
289 upsampler_workbuffer); 289 upsampler_workbuffer);
290 290
291 if (upsampler_infos.empty()) { 291 if (upsampler_infos.empty()) {
292 return Service::Audio::ERR_INSUFFICIENT_BUFFER_SIZE; 292 return Service::Audio::ResultInsufficientBuffer;
293 } 293 }
294 294
295 auto effect_infos{allocator.Allocate<EffectInfoBase>(params.effects, 0x40)}; 295 auto effect_infos{allocator.Allocate<EffectInfoBase>(params.effects, 0x40)};
@@ -298,14 +298,14 @@ Result System::Initialize(const AudioRendererParameterInternal& params,
298 } 298 }
299 299
300 if (effect_infos.empty() && params.effects > 0) { 300 if (effect_infos.empty() && params.effects > 0) {
301 return Service::Audio::ERR_INSUFFICIENT_BUFFER_SIZE; 301 return Service::Audio::ResultInsufficientBuffer;
302 } 302 }
303 303
304 std::span<EffectResultState> effect_result_states_dsp{}; 304 std::span<EffectResultState> effect_result_states_dsp{};
305 if (behavior.IsEffectInfoVersion2Supported() && params.effects > 0) { 305 if (behavior.IsEffectInfoVersion2Supported() && params.effects > 0) {
306 effect_result_states_dsp = allocator.Allocate<EffectResultState>(params.effects, 0x40); 306 effect_result_states_dsp = allocator.Allocate<EffectResultState>(params.effects, 0x40);
307 if (effect_result_states_dsp.empty()) { 307 if (effect_result_states_dsp.empty()) {
308 return Service::Audio::ERR_INSUFFICIENT_BUFFER_SIZE; 308 return Service::Audio::ResultInsufficientBuffer;
309 } 309 }
310 std::memset(effect_result_states_dsp.data(), 0, effect_result_states_dsp.size_bytes()); 310 std::memset(effect_result_states_dsp.data(), 0, effect_result_states_dsp.size_bytes());
311 } 311 }
@@ -319,14 +319,14 @@ Result System::Initialize(const AudioRendererParameterInternal& params,
319 } 319 }
320 320
321 if (sinks.empty()) { 321 if (sinks.empty()) {
322 return Service::Audio::ERR_INSUFFICIENT_BUFFER_SIZE; 322 return Service::Audio::ResultInsufficientBuffer;
323 } 323 }
324 324
325 sink_context.Initialize(sinks, params.sinks); 325 sink_context.Initialize(sinks, params.sinks);
326 326
327 auto voice_dsp_states{allocator.Allocate<VoiceState>(params.voices, 0x40)}; 327 auto voice_dsp_states{allocator.Allocate<VoiceState>(params.voices, 0x40)};
328 if (voice_dsp_states.empty()) { 328 if (voice_dsp_states.empty()) {
329 return Service::Audio::ERR_INSUFFICIENT_BUFFER_SIZE; 329 return Service::Audio::ResultInsufficientBuffer;
330 } 330 }
331 331
332 for (auto& voice_state : voice_dsp_states) { 332 for (auto& voice_state : voice_dsp_states) {
@@ -344,7 +344,7 @@ Result System::Initialize(const AudioRendererParameterInternal& params,
344 0xC}; 344 0xC};
345 performance_workbuffer = allocator.Allocate<u8>(perf_workbuffer_size, 0x40); 345 performance_workbuffer = allocator.Allocate<u8>(perf_workbuffer_size, 0x40);
346 if (performance_workbuffer.empty()) { 346 if (performance_workbuffer.empty()) {
347 return Service::Audio::ERR_INSUFFICIENT_BUFFER_SIZE; 347 return Service::Audio::ResultInsufficientBuffer;
348 } 348 }
349 std::memset(performance_workbuffer.data(), 0, performance_workbuffer.size_bytes()); 349 std::memset(performance_workbuffer.data(), 0, performance_workbuffer.size_bytes());
350 performance_manager.Initialize(performance_workbuffer, performance_workbuffer.size_bytes(), 350 performance_manager.Initialize(performance_workbuffer, performance_workbuffer.size_bytes(),
@@ -360,7 +360,7 @@ Result System::Initialize(const AudioRendererParameterInternal& params,
360 command_workbuffer_size = allocator.GetRemainingSize(); 360 command_workbuffer_size = allocator.GetRemainingSize();
361 command_workbuffer = allocator.Allocate<u8>(command_workbuffer_size, 0x40); 361 command_workbuffer = allocator.Allocate<u8>(command_workbuffer_size, 0x40);
362 if (command_workbuffer.empty()) { 362 if (command_workbuffer.empty()) {
363 return Service::Audio::ERR_INSUFFICIENT_BUFFER_SIZE; 363 return Service::Audio::ResultInsufficientBuffer;
364 } 364 }
365 365
366 command_buffer_size = 0; 366 command_buffer_size = 0;
diff --git a/src/audio_core/renderer/voice/voice_info.cpp b/src/audio_core/renderer/voice/voice_info.cpp
index 1849eeb57..c0bfb23fc 100644
--- a/src/audio_core/renderer/voice/voice_info.cpp
+++ b/src/audio_core/renderer/voice/voice_info.cpp
@@ -181,7 +181,7 @@ void VoiceInfo::UpdateWaveBuffer(std::span<BehaviorInfo::ErrorInfo> error_info,
181 if (wave_buffer_internal.start_offset * byte_size > wave_buffer_internal.size || 181 if (wave_buffer_internal.start_offset * byte_size > wave_buffer_internal.size ||
182 wave_buffer_internal.end_offset * byte_size > wave_buffer_internal.size) { 182 wave_buffer_internal.end_offset * byte_size > wave_buffer_internal.size) {
183 LOG_ERROR(Service_Audio, "Invalid PCM16 start/end wavebuffer sizes!"); 183 LOG_ERROR(Service_Audio, "Invalid PCM16 start/end wavebuffer sizes!");
184 error_info[0].error_code = Service::Audio::ERR_INVALID_UPDATE_DATA; 184 error_info[0].error_code = Service::Audio::ResultInvalidUpdateInfo;
185 error_info[0].address = wave_buffer_internal.address; 185 error_info[0].address = wave_buffer_internal.address;
186 return; 186 return;
187 } 187 }
@@ -192,7 +192,7 @@ void VoiceInfo::UpdateWaveBuffer(std::span<BehaviorInfo::ErrorInfo> error_info,
192 if (wave_buffer_internal.start_offset * byte_size > wave_buffer_internal.size || 192 if (wave_buffer_internal.start_offset * byte_size > wave_buffer_internal.size ||
193 wave_buffer_internal.end_offset * byte_size > wave_buffer_internal.size) { 193 wave_buffer_internal.end_offset * byte_size > wave_buffer_internal.size) {
194 LOG_ERROR(Service_Audio, "Invalid PCMFloat start/end wavebuffer sizes!"); 194 LOG_ERROR(Service_Audio, "Invalid PCMFloat start/end wavebuffer sizes!");
195 error_info[0].error_code = Service::Audio::ERR_INVALID_UPDATE_DATA; 195 error_info[0].error_code = Service::Audio::ResultInvalidUpdateInfo;
196 error_info[0].address = wave_buffer_internal.address; 196 error_info[0].address = wave_buffer_internal.address;
197 return; 197 return;
198 } 198 }
@@ -216,7 +216,7 @@ void VoiceInfo::UpdateWaveBuffer(std::span<BehaviorInfo::ErrorInfo> error_info,
216 if (start > static_cast<s64>(wave_buffer_internal.size) || 216 if (start > static_cast<s64>(wave_buffer_internal.size) ||
217 end > static_cast<s64>(wave_buffer_internal.size)) { 217 end > static_cast<s64>(wave_buffer_internal.size)) {
218 LOG_ERROR(Service_Audio, "Invalid ADPCM start/end wavebuffer sizes!"); 218 LOG_ERROR(Service_Audio, "Invalid ADPCM start/end wavebuffer sizes!");
219 error_info[0].error_code = Service::Audio::ERR_INVALID_UPDATE_DATA; 219 error_info[0].error_code = Service::Audio::ResultInvalidUpdateInfo;
220 error_info[0].address = wave_buffer_internal.address; 220 error_info[0].address = wave_buffer_internal.address;
221 return; 221 return;
222 } 222 }
@@ -228,7 +228,7 @@ void VoiceInfo::UpdateWaveBuffer(std::span<BehaviorInfo::ErrorInfo> error_info,
228 228
229 if (wave_buffer_internal.start_offset < 0 || wave_buffer_internal.end_offset < 0) { 229 if (wave_buffer_internal.start_offset < 0 || wave_buffer_internal.end_offset < 0) {
230 LOG_ERROR(Service_Audio, "Invalid input start/end wavebuffer sizes!"); 230 LOG_ERROR(Service_Audio, "Invalid input start/end wavebuffer sizes!");
231 error_info[0].error_code = Service::Audio::ERR_INVALID_UPDATE_DATA; 231 error_info[0].error_code = Service::Audio::ResultInvalidUpdateInfo;
232 error_info[0].address = wave_buffer_internal.address; 232 error_info[0].address = wave_buffer_internal.address;
233 return; 233 return;
234 } 234 }
diff --git a/src/common/CMakeLists.txt b/src/common/CMakeLists.txt
index 56b247ac4..61ab68864 100644
--- a/src/common/CMakeLists.txt
+++ b/src/common/CMakeLists.txt
@@ -91,6 +91,7 @@ add_library(common STATIC
91 multi_level_page_table.h 91 multi_level_page_table.h
92 nvidia_flags.cpp 92 nvidia_flags.cpp
93 nvidia_flags.h 93 nvidia_flags.h
94 overflow.h
94 page_table.cpp 95 page_table.cpp
95 page_table.h 96 page_table.h
96 param_package.cpp 97 param_package.cpp
@@ -113,6 +114,8 @@ add_library(common STATIC
113 socket_types.h 114 socket_types.h
114 spin_lock.cpp 115 spin_lock.cpp
115 spin_lock.h 116 spin_lock.h
117 steady_clock.cpp
118 steady_clock.h
116 stream.cpp 119 stream.cpp
117 stream.h 120 stream.h
118 string_util.cpp 121 string_util.cpp
@@ -142,6 +145,14 @@ add_library(common STATIC
142 zstd_compression.h 145 zstd_compression.h
143) 146)
144 147
148if (WIN32)
149 target_sources(common PRIVATE
150 windows/timer_resolution.cpp
151 windows/timer_resolution.h
152 )
153 target_link_libraries(common PRIVATE ntdll)
154endif()
155
145if(ARCHITECTURE_x86_64) 156if(ARCHITECTURE_x86_64)
146 target_sources(common 157 target_sources(common
147 PRIVATE 158 PRIVATE
diff --git a/src/common/bit_cast.h b/src/common/bit_cast.h
index 535148b4d..c6110c542 100644
--- a/src/common/bit_cast.h
+++ b/src/common/bit_cast.h
@@ -3,19 +3,21 @@
3 3
4#pragma once 4#pragma once
5 5
6#include <cstring> 6#include <version>
7#include <type_traits> 7
8#ifdef __cpp_lib_bit_cast
9#include <bit>
10#endif
8 11
9namespace Common { 12namespace Common {
10 13
11template <typename To, typename From> 14template <typename To, typename From>
12[[nodiscard]] std::enable_if_t<sizeof(To) == sizeof(From) && std::is_trivially_copyable_v<From> && 15constexpr inline To BitCast(const From& from) {
13 std::is_trivially_copyable_v<To>, 16#ifdef __cpp_lib_bit_cast
14 To> 17 return std::bit_cast<To>(from);
15BitCast(const From& src) noexcept { 18#else
16 To dst; 19 return __builtin_bit_cast(To, from);
17 std::memcpy(&dst, &src, sizeof(To)); 20#endif
18 return dst;
19} 21}
20 22
21} // namespace Common 23} // namespace Common
diff --git a/src/common/input.h b/src/common/input.h
index b5748a6c8..98e934685 100644
--- a/src/common/input.h
+++ b/src/common/input.h
@@ -46,7 +46,7 @@ enum class PollingMode {
46 // Constant polling of buttons, analogs and motion data 46 // Constant polling of buttons, analogs and motion data
47 Active, 47 Active,
48 // Only update on button change, digital analogs 48 // Only update on button change, digital analogs
49 Pasive, 49 Passive,
50 // Enable near field communication polling 50 // Enable near field communication polling
51 NFC, 51 NFC,
52 // Enable infrared camera polling 52 // Enable infrared camera polling
diff --git a/src/common/overflow.h b/src/common/overflow.h
new file mode 100644
index 000000000..44d8e7e73
--- /dev/null
+++ b/src/common/overflow.h
@@ -0,0 +1,22 @@
1// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4#pragma once
5
6#include <type_traits>
7#include "bit_cast.h"
8
9namespace Common {
10
11template <typename T>
12 requires(std::is_integral_v<T> && std::is_signed_v<T>)
13inline T WrappingAdd(T lhs, T rhs) {
14 using U = std::make_unsigned_t<T>;
15
16 U lhs_u = BitCast<U>(lhs);
17 U rhs_u = BitCast<U>(rhs);
18
19 return BitCast<T>(lhs_u + rhs_u);
20}
21
22} // namespace Common
diff --git a/src/common/settings.h b/src/common/settings.h
index 56ee4e28d..b77a1580a 100644
--- a/src/common/settings.h
+++ b/src/common/settings.h
@@ -128,7 +128,7 @@ public:
128 /** 128 /**
129 * Sets a default value, label, and setting value. 129 * Sets a default value, label, and setting value.
130 * 130 *
131 * @param default_val Intial value of the setting, and default value of the setting 131 * @param default_val Initial value of the setting, and default value of the setting
132 * @param name Label for the setting 132 * @param name Label for the setting
133 */ 133 */
134 explicit Setting(const Type& default_val, const std::string& name) 134 explicit Setting(const Type& default_val, const std::string& name)
@@ -139,7 +139,7 @@ public:
139 /** 139 /**
140 * Sets a default value, minimum value, maximum value, and label. 140 * Sets a default value, minimum value, maximum value, and label.
141 * 141 *
142 * @param default_val Intial value of the setting, and default value of the setting 142 * @param default_val Initial value of the setting, and default value of the setting
143 * @param min_val Sets the minimum allowed value of the setting 143 * @param min_val Sets the minimum allowed value of the setting
144 * @param max_val Sets the maximum allowed value of the setting 144 * @param max_val Sets the maximum allowed value of the setting
145 * @param name Label for the setting 145 * @param name Label for the setting
@@ -231,7 +231,7 @@ public:
231 /** 231 /**
232 * Sets a default value, label, and setting value. 232 * Sets a default value, label, and setting value.
233 * 233 *
234 * @param default_val Intial value of the setting, and default value of the setting 234 * @param default_val Initial value of the setting, and default value of the setting
235 * @param name Label for the setting 235 * @param name Label for the setting
236 */ 236 */
237 explicit SwitchableSetting(const Type& default_val, const std::string& name) 237 explicit SwitchableSetting(const Type& default_val, const std::string& name)
@@ -242,7 +242,7 @@ public:
242 /** 242 /**
243 * Sets a default value, minimum value, maximum value, and label. 243 * Sets a default value, minimum value, maximum value, and label.
244 * 244 *
245 * @param default_val Intial value of the setting, and default value of the setting 245 * @param default_val Initial value of the setting, and default value of the setting
246 * @param min_val Sets the minimum allowed value of the setting 246 * @param min_val Sets the minimum allowed value of the setting
247 * @param max_val Sets the maximum allowed value of the setting 247 * @param max_val Sets the maximum allowed value of the setting
248 * @param name Label for the setting 248 * @param name Label for the setting
diff --git a/src/common/steady_clock.cpp b/src/common/steady_clock.cpp
new file mode 100644
index 000000000..0d5908aa7
--- /dev/null
+++ b/src/common/steady_clock.cpp
@@ -0,0 +1,56 @@
1// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4#if defined(_WIN32)
5#include <windows.h>
6#else
7#include <time.h>
8#endif
9
10#include "common/steady_clock.h"
11
12namespace Common {
13
14#ifdef _WIN32
15static s64 WindowsQueryPerformanceFrequency() {
16 LARGE_INTEGER frequency;
17 QueryPerformanceFrequency(&frequency);
18 return frequency.QuadPart;
19}
20
21static s64 WindowsQueryPerformanceCounter() {
22 LARGE_INTEGER counter;
23 QueryPerformanceCounter(&counter);
24 return counter.QuadPart;
25}
26#endif
27
28SteadyClock::time_point SteadyClock::Now() noexcept {
29#if defined(_WIN32)
30 static const auto freq = WindowsQueryPerformanceFrequency();
31 const auto counter = WindowsQueryPerformanceCounter();
32
33 // 10 MHz is a very common QPC frequency on modern PCs.
34 // Optimizing for this specific frequency can double the performance of
35 // this function by avoiding the expensive frequency conversion path.
36 static constexpr s64 TenMHz = 10'000'000;
37
38 if (freq == TenMHz) [[likely]] {
39 static_assert(period::den % TenMHz == 0);
40 static constexpr s64 Multiplier = period::den / TenMHz;
41 return time_point{duration{counter * Multiplier}};
42 }
43
44 const auto whole = (counter / freq) * period::den;
45 const auto part = (counter % freq) * period::den / freq;
46 return time_point{duration{whole + part}};
47#elif defined(__APPLE__)
48 return time_point{duration{clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW)}};
49#else
50 timespec ts;
51 clock_gettime(CLOCK_MONOTONIC, &ts);
52 return time_point{std::chrono::seconds{ts.tv_sec} + std::chrono::nanoseconds{ts.tv_nsec}};
53#endif
54}
55
56}; // namespace Common
diff --git a/src/common/steady_clock.h b/src/common/steady_clock.h
new file mode 100644
index 000000000..9497cf865
--- /dev/null
+++ b/src/common/steady_clock.h
@@ -0,0 +1,23 @@
1// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4#pragma once
5
6#include <chrono>
7
8#include "common/common_types.h"
9
10namespace Common {
11
12struct SteadyClock {
13 using rep = s64;
14 using period = std::nano;
15 using duration = std::chrono::nanoseconds;
16 using time_point = std::chrono::time_point<SteadyClock>;
17
18 static constexpr bool is_steady = true;
19
20 [[nodiscard]] static time_point Now() noexcept;
21};
22
23} // namespace Common
diff --git a/src/common/wall_clock.cpp b/src/common/wall_clock.cpp
index ae07f2811..817e71d52 100644
--- a/src/common/wall_clock.cpp
+++ b/src/common/wall_clock.cpp
@@ -1,6 +1,7 @@
1// SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project 1// SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later 2// SPDX-License-Identifier: GPL-2.0-or-later
3 3
4#include "common/steady_clock.h"
4#include "common/uint128.h" 5#include "common/uint128.h"
5#include "common/wall_clock.h" 6#include "common/wall_clock.h"
6 7
@@ -11,45 +12,32 @@
11 12
12namespace Common { 13namespace Common {
13 14
14using base_timer = std::chrono::steady_clock;
15using base_time_point = std::chrono::time_point<base_timer>;
16
17class StandardWallClock final : public WallClock { 15class StandardWallClock final : public WallClock {
18public: 16public:
19 explicit StandardWallClock(u64 emulated_cpu_frequency_, u64 emulated_clock_frequency_) 17 explicit StandardWallClock(u64 emulated_cpu_frequency_, u64 emulated_clock_frequency_)
20 : WallClock(emulated_cpu_frequency_, emulated_clock_frequency_, false) { 18 : WallClock{emulated_cpu_frequency_, emulated_clock_frequency_, false},
21 start_time = base_timer::now(); 19 start_time{SteadyClock::Now()} {}
22 }
23 20
24 std::chrono::nanoseconds GetTimeNS() override { 21 std::chrono::nanoseconds GetTimeNS() override {
25 base_time_point current = base_timer::now(); 22 return SteadyClock::Now() - start_time;
26 auto elapsed = current - start_time;
27 return std::chrono::duration_cast<std::chrono::nanoseconds>(elapsed);
28 } 23 }
29 24
30 std::chrono::microseconds GetTimeUS() override { 25 std::chrono::microseconds GetTimeUS() override {
31 base_time_point current = base_timer::now(); 26 return std::chrono::duration_cast<std::chrono::microseconds>(GetTimeNS());
32 auto elapsed = current - start_time;
33 return std::chrono::duration_cast<std::chrono::microseconds>(elapsed);
34 } 27 }
35 28
36 std::chrono::milliseconds GetTimeMS() override { 29 std::chrono::milliseconds GetTimeMS() override {
37 base_time_point current = base_timer::now(); 30 return std::chrono::duration_cast<std::chrono::milliseconds>(GetTimeNS());
38 auto elapsed = current - start_time;
39 return std::chrono::duration_cast<std::chrono::milliseconds>(elapsed);
40 } 31 }
41 32
42 u64 GetClockCycles() override { 33 u64 GetClockCycles() override {
43 std::chrono::nanoseconds time_now = GetTimeNS(); 34 const u128 temp = Common::Multiply64Into128(GetTimeNS().count(), emulated_clock_frequency);
44 const u128 temporary = 35 return Common::Divide128On32(temp, NS_RATIO).first;
45 Common::Multiply64Into128(time_now.count(), emulated_clock_frequency);
46 return Common::Divide128On32(temporary, 1000000000).first;
47 } 36 }
48 37
49 u64 GetCPUCycles() override { 38 u64 GetCPUCycles() override {
50 std::chrono::nanoseconds time_now = GetTimeNS(); 39 const u128 temp = Common::Multiply64Into128(GetTimeNS().count(), emulated_cpu_frequency);
51 const u128 temporary = Common::Multiply64Into128(time_now.count(), emulated_cpu_frequency); 40 return Common::Divide128On32(temp, NS_RATIO).first;
52 return Common::Divide128On32(temporary, 1000000000).first;
53 } 41 }
54 42
55 void Pause([[maybe_unused]] bool is_paused) override { 43 void Pause([[maybe_unused]] bool is_paused) override {
@@ -57,7 +45,7 @@ public:
57 } 45 }
58 46
59private: 47private:
60 base_time_point start_time; 48 SteadyClock::time_point start_time;
61}; 49};
62 50
63#ifdef ARCHITECTURE_x86_64 51#ifdef ARCHITECTURE_x86_64
@@ -93,4 +81,9 @@ std::unique_ptr<WallClock> CreateBestMatchingClock(u64 emulated_cpu_frequency,
93 81
94#endif 82#endif
95 83
84std::unique_ptr<WallClock> CreateStandardWallClock(u64 emulated_cpu_frequency,
85 u64 emulated_clock_frequency) {
86 return std::make_unique<StandardWallClock>(emulated_cpu_frequency, emulated_clock_frequency);
87}
88
96} // namespace Common 89} // namespace Common
diff --git a/src/common/wall_clock.h b/src/common/wall_clock.h
index 828a523a8..157ec5eae 100644
--- a/src/common/wall_clock.h
+++ b/src/common/wall_clock.h
@@ -55,4 +55,7 @@ private:
55[[nodiscard]] std::unique_ptr<WallClock> CreateBestMatchingClock(u64 emulated_cpu_frequency, 55[[nodiscard]] std::unique_ptr<WallClock> CreateBestMatchingClock(u64 emulated_cpu_frequency,
56 u64 emulated_clock_frequency); 56 u64 emulated_clock_frequency);
57 57
58[[nodiscard]] std::unique_ptr<WallClock> CreateStandardWallClock(u64 emulated_cpu_frequency,
59 u64 emulated_clock_frequency);
60
58} // namespace Common 61} // namespace Common
diff --git a/src/common/windows/timer_resolution.cpp b/src/common/windows/timer_resolution.cpp
new file mode 100644
index 000000000..29c6e5c7e
--- /dev/null
+++ b/src/common/windows/timer_resolution.cpp
@@ -0,0 +1,109 @@
1// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4#include <windows.h>
5
6#include "common/windows/timer_resolution.h"
7
8extern "C" {
9// http://undocumented.ntinternals.net/index.html?page=UserMode%2FUndocumented%20Functions%2FTime%2FNtQueryTimerResolution.html
10NTSYSAPI LONG NTAPI NtQueryTimerResolution(PULONG MinimumResolution, PULONG MaximumResolution,
11 PULONG CurrentResolution);
12
13// http://undocumented.ntinternals.net/index.html?page=UserMode%2FUndocumented%20Functions%2FTime%2FNtSetTimerResolution.html
14NTSYSAPI LONG NTAPI NtSetTimerResolution(ULONG DesiredResolution, BOOLEAN SetResolution,
15 PULONG CurrentResolution);
16
17// http://undocumented.ntinternals.net/index.html?page=UserMode%2FUndocumented%20Functions%2FNT%20Objects%2FThread%2FNtDelayExecution.html
18NTSYSAPI LONG NTAPI NtDelayExecution(BOOLEAN Alertable, PLARGE_INTEGER DelayInterval);
19}
20
21// Defines for compatibility with older Windows 10 SDKs.
22
23#ifndef PROCESS_POWER_THROTTLING_EXECUTION_SPEED
24#define PROCESS_POWER_THROTTLING_EXECUTION_SPEED 0x1
25#endif
26#ifndef PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION
27#define PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION 0x4
28#endif
29
30namespace Common::Windows {
31
32namespace {
33
34using namespace std::chrono;
35
36constexpr nanoseconds ToNS(ULONG hundred_ns) {
37 return nanoseconds{hundred_ns * 100};
38}
39
40constexpr ULONG ToHundredNS(nanoseconds ns) {
41 return static_cast<ULONG>(ns.count()) / 100;
42}
43
44struct TimerResolution {
45 std::chrono::nanoseconds minimum;
46 std::chrono::nanoseconds maximum;
47 std::chrono::nanoseconds current;
48};
49
50TimerResolution GetTimerResolution() {
51 ULONG MinimumTimerResolution;
52 ULONG MaximumTimerResolution;
53 ULONG CurrentTimerResolution;
54 NtQueryTimerResolution(&MinimumTimerResolution, &MaximumTimerResolution,
55 &CurrentTimerResolution);
56 return {
57 .minimum{ToNS(MinimumTimerResolution)},
58 .maximum{ToNS(MaximumTimerResolution)},
59 .current{ToNS(CurrentTimerResolution)},
60 };
61}
62
63void SetHighQoS() {
64 // https://learn.microsoft.com/en-us/windows/win32/procthread/quality-of-service
65 PROCESS_POWER_THROTTLING_STATE PowerThrottling{
66 .Version{PROCESS_POWER_THROTTLING_CURRENT_VERSION},
67 .ControlMask{PROCESS_POWER_THROTTLING_EXECUTION_SPEED |
68 PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION},
69 .StateMask{},
70 };
71 SetProcessInformation(GetCurrentProcess(), ProcessPowerThrottling, &PowerThrottling,
72 sizeof(PROCESS_POWER_THROTTLING_STATE));
73}
74
75} // Anonymous namespace
76
77nanoseconds GetMinimumTimerResolution() {
78 return GetTimerResolution().minimum;
79}
80
81nanoseconds GetMaximumTimerResolution() {
82 return GetTimerResolution().maximum;
83}
84
85nanoseconds GetCurrentTimerResolution() {
86 return GetTimerResolution().current;
87}
88
89nanoseconds SetCurrentTimerResolution(nanoseconds timer_resolution) {
90 // Set the timer resolution, and return the current timer resolution.
91 const auto DesiredTimerResolution = ToHundredNS(timer_resolution);
92 ULONG CurrentTimerResolution;
93 NtSetTimerResolution(DesiredTimerResolution, TRUE, &CurrentTimerResolution);
94 return ToNS(CurrentTimerResolution);
95}
96
97nanoseconds SetCurrentTimerResolutionToMaximum() {
98 SetHighQoS();
99 return SetCurrentTimerResolution(GetMaximumTimerResolution());
100}
101
102void SleepForOneTick() {
103 LARGE_INTEGER DelayInterval{
104 .QuadPart{-1},
105 };
106 NtDelayExecution(FALSE, &DelayInterval);
107}
108
109} // namespace Common::Windows
diff --git a/src/common/windows/timer_resolution.h b/src/common/windows/timer_resolution.h
new file mode 100644
index 000000000..e1e50a62d
--- /dev/null
+++ b/src/common/windows/timer_resolution.h
@@ -0,0 +1,38 @@
1// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4#pragma once
5
6#include <chrono>
7
8namespace Common::Windows {
9
10/// Returns the minimum (least precise) supported timer resolution in nanoseconds.
11std::chrono::nanoseconds GetMinimumTimerResolution();
12
13/// Returns the maximum (most precise) supported timer resolution in nanoseconds.
14std::chrono::nanoseconds GetMaximumTimerResolution();
15
16/// Returns the current timer resolution in nanoseconds.
17std::chrono::nanoseconds GetCurrentTimerResolution();
18
19/**
20 * Sets the current timer resolution.
21 *
22 * @param timer_resolution Timer resolution in nanoseconds.
23 *
24 * @returns The current timer resolution.
25 */
26std::chrono::nanoseconds SetCurrentTimerResolution(std::chrono::nanoseconds timer_resolution);
27
28/**
29 * Sets the current timer resolution to the maximum supported timer resolution.
30 *
31 * @returns The current timer resolution.
32 */
33std::chrono::nanoseconds SetCurrentTimerResolutionToMaximum();
34
35/// Sleep for one tick of the current timer resolution.
36void SleepForOneTick();
37
38} // namespace Common::Windows
diff --git a/src/common/x64/native_clock.cpp b/src/common/x64/native_clock.cpp
index 8b08332ab..bc1a973b0 100644
--- a/src/common/x64/native_clock.cpp
+++ b/src/common/x64/native_clock.cpp
@@ -6,6 +6,7 @@
6#include <thread> 6#include <thread>
7 7
8#include "common/atomic_ops.h" 8#include "common/atomic_ops.h"
9#include "common/steady_clock.h"
9#include "common/uint128.h" 10#include "common/uint128.h"
10#include "common/x64/native_clock.h" 11#include "common/x64/native_clock.h"
11 12
@@ -39,6 +40,12 @@ static u64 FencedRDTSC() {
39} 40}
40#endif 41#endif
41 42
43template <u64 Nearest>
44static u64 RoundToNearest(u64 value) {
45 const auto mod = value % Nearest;
46 return mod >= (Nearest / 2) ? (value - mod + Nearest) : (value - mod);
47}
48
42u64 EstimateRDTSCFrequency() { 49u64 EstimateRDTSCFrequency() {
43 // Discard the first result measuring the rdtsc. 50 // Discard the first result measuring the rdtsc.
44 FencedRDTSC(); 51 FencedRDTSC();
@@ -46,18 +53,18 @@ u64 EstimateRDTSCFrequency() {
46 FencedRDTSC(); 53 FencedRDTSC();
47 54
48 // Get the current time. 55 // Get the current time.
49 const auto start_time = std::chrono::steady_clock::now(); 56 const auto start_time = Common::SteadyClock::Now();
50 const u64 tsc_start = FencedRDTSC(); 57 const u64 tsc_start = FencedRDTSC();
51 // Wait for 200 milliseconds. 58 // Wait for 250 milliseconds.
52 std::this_thread::sleep_for(std::chrono::milliseconds{200}); 59 std::this_thread::sleep_for(std::chrono::milliseconds{250});
53 const auto end_time = std::chrono::steady_clock::now(); 60 const auto end_time = Common::SteadyClock::Now();
54 const u64 tsc_end = FencedRDTSC(); 61 const u64 tsc_end = FencedRDTSC();
55 // Calculate differences. 62 // Calculate differences.
56 const u64 timer_diff = static_cast<u64>( 63 const u64 timer_diff = static_cast<u64>(
57 std::chrono::duration_cast<std::chrono::nanoseconds>(end_time - start_time).count()); 64 std::chrono::duration_cast<std::chrono::nanoseconds>(end_time - start_time).count());
58 const u64 tsc_diff = tsc_end - tsc_start; 65 const u64 tsc_diff = tsc_end - tsc_start;
59 const u64 tsc_freq = MultiplyAndDivide64(tsc_diff, 1000000000ULL, timer_diff); 66 const u64 tsc_freq = MultiplyAndDivide64(tsc_diff, 1000000000ULL, timer_diff);
60 return tsc_freq; 67 return RoundToNearest<1000>(tsc_freq);
61} 68}
62 69
63namespace X64 { 70namespace X64 {
diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt
index 4a1a8bb43..75e0c4f38 100644
--- a/src/core/CMakeLists.txt
+++ b/src/core/CMakeLists.txt
@@ -454,7 +454,6 @@ add_library(core STATIC
454 hle/service/filesystem/fsp_srv.h 454 hle/service/filesystem/fsp_srv.h
455 hle/service/fgm/fgm.cpp 455 hle/service/fgm/fgm.cpp
456 hle/service/fgm/fgm.h 456 hle/service/fgm/fgm.h
457 hle/service/friend/errors.h
458 hle/service/friend/friend.cpp 457 hle/service/friend/friend.cpp
459 hle/service/friend/friend.h 458 hle/service/friend/friend.h
460 hle/service/friend/friend_interface.cpp 459 hle/service/friend/friend_interface.cpp
diff --git a/src/core/constants.cpp b/src/core/constants.cpp
index 4430173ef..760dc5f23 100644
--- a/src/core/constants.cpp
+++ b/src/core/constants.cpp
@@ -4,13 +4,24 @@
4#include "core/constants.h" 4#include "core/constants.h"
5 5
6namespace Core::Constants { 6namespace Core::Constants {
7const std::array<u8, 107> ACCOUNT_BACKUP_JPEG{{ 7const std::array<u8, 287> ACCOUNT_BACKUP_JPEG{{
8 0xff, 0xd8, 0xff, 0xdb, 0x00, 0x43, 0x00, 0x03, 0x02, 0x02, 0x02, 0x02, 0x02, 0x03, 0x02, 0x02, 8 0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, 0x01, 0x01, 0x01, 0x00, 0x48,
9 0x02, 0x03, 0x03, 0x03, 0x03, 0x04, 0x06, 0x04, 0x04, 0x04, 0x04, 0x04, 0x08, 0x06, 0x06, 0x05, 9 0x00, 0x48, 0x00, 0x00, 0xff, 0xdb, 0x00, 0x43, 0x00, 0x06, 0x04, 0x04, 0x04, 0x05, 0x04, 0x06,
10 0x06, 0x09, 0x08, 0x0a, 0x0a, 0x09, 0x08, 0x09, 0x09, 0x0a, 0x0c, 0x0f, 0x0c, 0x0a, 0x0b, 0x0e, 10 0x05, 0x05, 0x06, 0x09, 0x06, 0x05, 0x06, 0x09, 0x0b, 0x08, 0x06, 0x06, 0x08, 0x0b, 0x0c, 0x0a,
11 0x0b, 0x09, 0x09, 0x0d, 0x11, 0x0d, 0x0e, 0x0f, 0x10, 0x10, 0x11, 0x10, 0x0a, 0x0c, 0x12, 0x13, 11 0x0a, 0x0b, 0x0a, 0x0a, 0x0c, 0x10, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x10, 0x0c, 0x0e, 0x0f,
12 0x12, 0x10, 0x13, 0x0f, 0x10, 0x10, 0x10, 0xff, 0xc9, 0x00, 0x0b, 0x08, 0x00, 0x01, 0x00, 0x01, 12 0x10, 0x0f, 0x0e, 0x0c, 0x13, 0x13, 0x14, 0x14, 0x13, 0x13, 0x1c, 0x1b, 0x1b, 0x1b, 0x1c, 0x20,
13 0x01, 0x01, 0x11, 0x00, 0xff, 0xcc, 0x00, 0x06, 0x00, 0x10, 0x10, 0x05, 0xff, 0xda, 0x00, 0x08, 13 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0xff, 0xdb, 0x00, 0x43, 0x01, 0x07, 0x07,
14 0x01, 0x01, 0x00, 0x00, 0x3f, 0x00, 0xd2, 0xcf, 0x20, 0xff, 0xd9, 14 0x07, 0x0d, 0x0c, 0x0d, 0x18, 0x10, 0x10, 0x18, 0x1a, 0x15, 0x11, 0x15, 0x1a, 0x20, 0x20, 0x20,
15 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
16 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
17 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0xff, 0xc0,
18 0x00, 0x11, 0x08, 0x00, 0x20, 0x00, 0x20, 0x03, 0x01, 0x22, 0x00, 0x02, 0x11, 0x01, 0x03, 0x11,
19 0x01, 0xff, 0xc4, 0x00, 0x14, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
20 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xc4, 0x00, 0x14, 0x10, 0x01, 0x00, 0x00, 0x00,
21 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xc4, 0x00,
22 0x14, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
23 0x00, 0x00, 0x00, 0xff, 0xc4, 0x00, 0x14, 0x11, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
24 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xda, 0x00, 0x0c, 0x03, 0x01, 0x00,
25 0x02, 0x11, 0x03, 0x11, 0x00, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xd9,
15}}; 26}};
16} 27}
diff --git a/src/core/constants.h b/src/core/constants.h
index f916ce0b6..f1f67d3b8 100644
--- a/src/core/constants.h
+++ b/src/core/constants.h
@@ -12,6 +12,6 @@
12namespace Core::Constants { 12namespace Core::Constants {
13 13
14// ACC Service - Blank JPEG used as user icon in absentia of real one. 14// ACC Service - Blank JPEG used as user icon in absentia of real one.
15extern const std::array<u8, 107> ACCOUNT_BACKUP_JPEG; 15extern const std::array<u8, 287> ACCOUNT_BACKUP_JPEG;
16 16
17} // namespace Core::Constants 17} // namespace Core::Constants
diff --git a/src/core/core_timing.cpp b/src/core/core_timing.cpp
index 3a63b52e3..742cfb996 100644
--- a/src/core/core_timing.cpp
+++ b/src/core/core_timing.cpp
@@ -6,6 +6,10 @@
6#include <string> 6#include <string>
7#include <tuple> 7#include <tuple>
8 8
9#ifdef _WIN32
10#include "common/windows/timer_resolution.h"
11#endif
12
9#include "common/microprofile.h" 13#include "common/microprofile.h"
10#include "core/core_timing.h" 14#include "core/core_timing.h"
11#include "core/core_timing_util.h" 15#include "core/core_timing_util.h"
@@ -38,7 +42,8 @@ struct CoreTiming::Event {
38}; 42};
39 43
40CoreTiming::CoreTiming() 44CoreTiming::CoreTiming()
41 : clock{Common::CreateBestMatchingClock(Hardware::BASE_CLOCK_RATE, Hardware::CNTFREQ)} {} 45 : cpu_clock{Common::CreateBestMatchingClock(Hardware::BASE_CLOCK_RATE, Hardware::CNTFREQ)},
46 event_clock{Common::CreateStandardWallClock(Hardware::BASE_CLOCK_RATE, Hardware::CNTFREQ)} {}
42 47
43CoreTiming::~CoreTiming() { 48CoreTiming::~CoreTiming() {
44 Reset(); 49 Reset();
@@ -185,15 +190,15 @@ void CoreTiming::ResetTicks() {
185} 190}
186 191
187u64 CoreTiming::GetCPUTicks() const { 192u64 CoreTiming::GetCPUTicks() const {
188 if (is_multicore) { 193 if (is_multicore) [[likely]] {
189 return clock->GetCPUCycles(); 194 return cpu_clock->GetCPUCycles();
190 } 195 }
191 return ticks; 196 return ticks;
192} 197}
193 198
194u64 CoreTiming::GetClockTicks() const { 199u64 CoreTiming::GetClockTicks() const {
195 if (is_multicore) { 200 if (is_multicore) [[likely]] {
196 return clock->GetClockCycles(); 201 return cpu_clock->GetClockCycles();
197 } 202 }
198 return CpuCyclesToClockCycles(ticks); 203 return CpuCyclesToClockCycles(ticks);
199} 204}
@@ -252,21 +257,20 @@ void CoreTiming::ThreadLoop() {
252 const auto next_time = Advance(); 257 const auto next_time = Advance();
253 if (next_time) { 258 if (next_time) {
254 // There are more events left in the queue, wait until the next event. 259 // There are more events left in the queue, wait until the next event.
255 const auto wait_time = *next_time - GetGlobalTimeNs().count(); 260 auto wait_time = *next_time - GetGlobalTimeNs().count();
256 if (wait_time > 0) { 261 if (wait_time > 0) {
257#ifdef _WIN32 262#ifdef _WIN32
258 // Assume a timer resolution of 1ms. 263 const auto timer_resolution_ns =
259 static constexpr s64 TimerResolutionNS = 1000000; 264 Common::Windows::GetCurrentTimerResolution().count();
260 265
261 // Sleep in discrete intervals of the timer resolution, and spin the rest. 266 while (!paused && !event.IsSet() && wait_time > 0) {
262 const auto sleep_time = wait_time - (wait_time % TimerResolutionNS); 267 wait_time = *next_time - GetGlobalTimeNs().count();
263 if (sleep_time > 0) {
264 event.WaitFor(std::chrono::nanoseconds(sleep_time));
265 }
266 268
267 while (!paused && !event.IsSet() && GetGlobalTimeNs().count() < *next_time) { 269 if (wait_time >= timer_resolution_ns) {
268 // Yield to reduce thread starvation. 270 Common::Windows::SleepForOneTick();
269 std::this_thread::yield(); 271 } else {
272 std::this_thread::yield();
273 }
270 } 274 }
271 275
272 if (event.IsSet()) { 276 if (event.IsSet()) {
@@ -285,9 +289,9 @@ void CoreTiming::ThreadLoop() {
285 } 289 }
286 290
287 paused_set = true; 291 paused_set = true;
288 clock->Pause(true); 292 event_clock->Pause(true);
289 pause_event.Wait(); 293 pause_event.Wait();
290 clock->Pause(false); 294 event_clock->Pause(false);
291 } 295 }
292} 296}
293 297
@@ -303,16 +307,23 @@ void CoreTiming::Reset() {
303 has_started = false; 307 has_started = false;
304} 308}
305 309
310std::chrono::nanoseconds CoreTiming::GetCPUTimeNs() const {
311 if (is_multicore) [[likely]] {
312 return cpu_clock->GetTimeNS();
313 }
314 return CyclesToNs(ticks);
315}
316
306std::chrono::nanoseconds CoreTiming::GetGlobalTimeNs() const { 317std::chrono::nanoseconds CoreTiming::GetGlobalTimeNs() const {
307 if (is_multicore) { 318 if (is_multicore) [[likely]] {
308 return clock->GetTimeNS(); 319 return event_clock->GetTimeNS();
309 } 320 }
310 return CyclesToNs(ticks); 321 return CyclesToNs(ticks);
311} 322}
312 323
313std::chrono::microseconds CoreTiming::GetGlobalTimeUs() const { 324std::chrono::microseconds CoreTiming::GetGlobalTimeUs() const {
314 if (is_multicore) { 325 if (is_multicore) [[likely]] {
315 return clock->GetTimeUS(); 326 return event_clock->GetTimeUS();
316 } 327 }
317 return CyclesToUs(ticks); 328 return CyclesToUs(ticks);
318} 329}
diff --git a/src/core/core_timing.h b/src/core/core_timing.h
index da366637b..4b89c0c39 100644
--- a/src/core/core_timing.h
+++ b/src/core/core_timing.h
@@ -122,6 +122,9 @@ public:
122 /// Returns current time in emulated in Clock cycles 122 /// Returns current time in emulated in Clock cycles
123 u64 GetClockTicks() const; 123 u64 GetClockTicks() const;
124 124
125 /// Returns current time in nanoseconds.
126 std::chrono::nanoseconds GetCPUTimeNs() const;
127
125 /// Returns current time in microseconds. 128 /// Returns current time in microseconds.
126 std::chrono::microseconds GetGlobalTimeUs() const; 129 std::chrono::microseconds GetGlobalTimeUs() const;
127 130
@@ -139,7 +142,8 @@ private:
139 142
140 void Reset(); 143 void Reset();
141 144
142 std::unique_ptr<Common::WallClock> clock; 145 std::unique_ptr<Common::WallClock> cpu_clock;
146 std::unique_ptr<Common::WallClock> event_clock;
143 147
144 s64 global_timer = 0; 148 s64 global_timer = 0;
145 149
diff --git a/src/core/hardware_properties.h b/src/core/hardware_properties.h
index 45567b840..191c28bb4 100644
--- a/src/core/hardware_properties.h
+++ b/src/core/hardware_properties.h
@@ -13,11 +13,9 @@ namespace Core {
13 13
14namespace Hardware { 14namespace Hardware {
15 15
16// The below clock rate is based on Switch's clockspeed being widely known as 1.020GHz 16constexpr u64 BASE_CLOCK_RATE = 1'020'000'000; // Default CPU Frequency = 1020 MHz
17// The exact value used is of course unverified. 17constexpr u64 CNTFREQ = 19'200'000; // CNTPCT_EL0 Frequency = 19.2 MHz
18constexpr u64 BASE_CLOCK_RATE = 1019215872; // Switch cpu frequency is 1020MHz un/docked 18constexpr u32 NUM_CPU_CORES = 4; // Number of CPU Cores
19constexpr u64 CNTFREQ = 19200000; // Switch's hardware clock speed
20constexpr u32 NUM_CPU_CORES = 4; // Number of CPU Cores
21 19
22// Virtual to Physical core map. 20// Virtual to Physical core map.
23constexpr std::array<s32, Common::BitSize<u64>()> VirtualToPhysicalCoreMap{ 21constexpr std::array<s32, Common::BitSize<u64>()> VirtualToPhysicalCoreMap{
diff --git a/src/core/hle/kernel/k_address_space_info.cpp b/src/core/hle/kernel/k_address_space_info.cpp
index 97972ebae..c36eb5dc4 100644
--- a/src/core/hle/kernel/k_address_space_info.cpp
+++ b/src/core/hle/kernel/k_address_space_info.cpp
@@ -44,11 +44,11 @@ const KAddressSpaceInfo& GetAddressSpaceInfo(size_t width, KAddressSpaceInfo::Ty
44 44
45} // namespace 45} // namespace
46 46
47uintptr_t KAddressSpaceInfo::GetAddressSpaceStart(size_t width, KAddressSpaceInfo::Type type) { 47std::size_t KAddressSpaceInfo::GetAddressSpaceStart(size_t width, KAddressSpaceInfo::Type type) {
48 return GetAddressSpaceInfo(width, type).address; 48 return GetAddressSpaceInfo(width, type).address;
49} 49}
50 50
51size_t KAddressSpaceInfo::GetAddressSpaceSize(size_t width, KAddressSpaceInfo::Type type) { 51std::size_t KAddressSpaceInfo::GetAddressSpaceSize(size_t width, KAddressSpaceInfo::Type type) {
52 return GetAddressSpaceInfo(width, type).size; 52 return GetAddressSpaceInfo(width, type).size;
53} 53}
54 54
diff --git a/src/core/hle/kernel/k_address_space_info.h b/src/core/hle/kernel/k_address_space_info.h
index 69e9d77f2..9a26f6b90 100644
--- a/src/core/hle/kernel/k_address_space_info.h
+++ b/src/core/hle/kernel/k_address_space_info.h
@@ -18,7 +18,7 @@ struct KAddressSpaceInfo final {
18 Count, 18 Count,
19 }; 19 };
20 20
21 static u64 GetAddressSpaceStart(std::size_t width, Type type); 21 static std::size_t GetAddressSpaceStart(std::size_t width, Type type);
22 static std::size_t GetAddressSpaceSize(std::size_t width, Type type); 22 static std::size_t GetAddressSpaceSize(std::size_t width, Type type);
23 23
24 const std::size_t bit_width{}; 24 const std::size_t bit_width{};
diff --git a/src/core/hle/kernel/k_device_address_space.h b/src/core/hle/kernel/k_device_address_space.h
index 4709df995..b4a014c38 100644
--- a/src/core/hle/kernel/k_device_address_space.h
+++ b/src/core/hle/kernel/k_device_address_space.h
@@ -21,9 +21,9 @@ public:
21 ~KDeviceAddressSpace(); 21 ~KDeviceAddressSpace();
22 22
23 Result Initialize(u64 address, u64 size); 23 Result Initialize(u64 address, u64 size);
24 void Finalize(); 24 void Finalize() override;
25 25
26 bool IsInitialized() const { 26 bool IsInitialized() const override {
27 return m_is_initialized; 27 return m_is_initialized;
28 } 28 }
29 static void PostDestroy(uintptr_t arg) {} 29 static void PostDestroy(uintptr_t arg) {}
diff --git a/src/core/hle/kernel/k_process.h b/src/core/hle/kernel/k_process.h
index 09bf2f1d0..549809000 100644
--- a/src/core/hle/kernel/k_process.h
+++ b/src/core/hle/kernel/k_process.h
@@ -310,10 +310,10 @@ public:
310 /// Clears the signaled state of the process if and only if it's signaled. 310 /// Clears the signaled state of the process if and only if it's signaled.
311 /// 311 ///
312 /// @pre The process must not be already terminated. If this is called on a 312 /// @pre The process must not be already terminated. If this is called on a
313 /// terminated process, then ERR_INVALID_STATE will be returned. 313 /// terminated process, then ResultInvalidState will be returned.
314 /// 314 ///
315 /// @pre The process must be in a signaled state. If this is called on a 315 /// @pre The process must be in a signaled state. If this is called on a
316 /// process instance that is not signaled, ERR_INVALID_STATE will be 316 /// process instance that is not signaled, ResultInvalidState will be
317 /// returned. 317 /// returned.
318 Result Reset(); 318 Result Reset();
319 319
diff --git a/src/core/hle/kernel/k_resource_limit.cpp b/src/core/hle/kernel/k_resource_limit.cpp
index b9d22b414..626517619 100644
--- a/src/core/hle/kernel/k_resource_limit.cpp
+++ b/src/core/hle/kernel/k_resource_limit.cpp
@@ -2,6 +2,7 @@
2// SPDX-License-Identifier: GPL-2.0-or-later 2// SPDX-License-Identifier: GPL-2.0-or-later
3 3
4#include "common/assert.h" 4#include "common/assert.h"
5#include "common/overflow.h"
5#include "core/core.h" 6#include "core/core.h"
6#include "core/core_timing.h" 7#include "core/core_timing.h"
7#include "core/hle/kernel/k_resource_limit.h" 8#include "core/hle/kernel/k_resource_limit.h"
@@ -104,7 +105,7 @@ bool KResourceLimit::Reserve(LimitableResource which, s64 value, s64 timeout) {
104 ASSERT(current_hints[index] <= current_values[index]); 105 ASSERT(current_hints[index] <= current_values[index]);
105 106
106 // If we would overflow, don't allow to succeed. 107 // If we would overflow, don't allow to succeed.
107 if (current_values[index] + value <= current_values[index]) { 108 if (Common::WrappingAdd(current_values[index], value) <= current_values[index]) {
108 break; 109 break;
109 } 110 }
110 111
diff --git a/src/core/hle/kernel/k_scoped_lock.h b/src/core/hle/kernel/k_scoped_lock.h
index 59b3e32ae..a15640fd2 100644
--- a/src/core/hle/kernel/k_scoped_lock.h
+++ b/src/core/hle/kernel/k_scoped_lock.h
@@ -4,6 +4,7 @@
4#pragma once 4#pragma once
5 5
6#include <concepts> 6#include <concepts>
7#include <memory>
7#include <type_traits> 8#include <type_traits>
8 9
9namespace Kernel { 10namespace Kernel {
diff --git a/src/core/hle/kernel/svc/svc_synchronization.cpp b/src/core/hle/kernel/svc/svc_synchronization.cpp
index 1a8f7e191..9e7bf9530 100644
--- a/src/core/hle/kernel/svc/svc_synchronization.cpp
+++ b/src/core/hle/kernel/svc/svc_synchronization.cpp
@@ -48,19 +48,15 @@ Result ResetSignal(Core::System& system, Handle handle) {
48 return ResultInvalidHandle; 48 return ResultInvalidHandle;
49} 49}
50 50
51/// Wait for the given handles to synchronize, timeout after the specified nanoseconds 51static Result WaitSynchronization(Core::System& system, int32_t* out_index, const Handle* handles,
52Result WaitSynchronization(Core::System& system, s32* index, VAddr handles_address, s32 num_handles, 52 int32_t num_handles, int64_t timeout_ns) {
53 s64 nano_seconds) {
54 LOG_TRACE(Kernel_SVC, "called handles_address=0x{:X}, num_handles={}, nano_seconds={}",
55 handles_address, num_handles, nano_seconds);
56
57 // Ensure number of handles is valid. 53 // Ensure number of handles is valid.
58 R_UNLESS(0 <= num_handles && num_handles <= ArgumentHandleCountMax, ResultOutOfRange); 54 R_UNLESS(0 <= num_handles && num_handles <= Svc::ArgumentHandleCountMax, ResultOutOfRange);
59 55
56 // Get the synchronization context.
60 auto& kernel = system.Kernel(); 57 auto& kernel = system.Kernel();
58 auto& handle_table = GetCurrentProcess(kernel).GetHandleTable();
61 std::vector<KSynchronizationObject*> objs(num_handles); 59 std::vector<KSynchronizationObject*> objs(num_handles);
62 const auto& handle_table = GetCurrentProcess(kernel).GetHandleTable();
63 Handle* handles = system.Memory().GetPointer<Handle>(handles_address);
64 60
65 // Copy user handles. 61 // Copy user handles.
66 if (num_handles > 0) { 62 if (num_handles > 0) {
@@ -68,21 +64,38 @@ Result WaitSynchronization(Core::System& system, s32* index, VAddr handles_addre
68 R_UNLESS(handle_table.GetMultipleObjects<KSynchronizationObject>(objs.data(), handles, 64 R_UNLESS(handle_table.GetMultipleObjects<KSynchronizationObject>(objs.data(), handles,
69 num_handles), 65 num_handles),
70 ResultInvalidHandle); 66 ResultInvalidHandle);
71 for (const auto& obj : objs) {
72 kernel.RegisterInUseObject(obj);
73 }
74 } 67 }
75 68
76 // Ensure handles are closed when we're done. 69 // Ensure handles are closed when we're done.
77 SCOPE_EXIT({ 70 SCOPE_EXIT({
78 for (s32 i = 0; i < num_handles; ++i) { 71 for (auto i = 0; i < num_handles; ++i) {
79 kernel.UnregisterInUseObject(objs[i]);
80 objs[i]->Close(); 72 objs[i]->Close();
81 } 73 }
82 }); 74 });
83 75
84 return KSynchronizationObject::Wait(kernel, index, objs.data(), static_cast<s32>(objs.size()), 76 // Wait on the objects.
85 nano_seconds); 77 Result res = KSynchronizationObject::Wait(kernel, out_index, objs.data(),
78 static_cast<s32>(objs.size()), timeout_ns);
79
80 R_SUCCEED_IF(res == ResultSessionClosed);
81 R_RETURN(res);
82}
83
84/// Wait for the given handles to synchronize, timeout after the specified nanoseconds
85Result WaitSynchronization(Core::System& system, int32_t* out_index, VAddr user_handles,
86 int32_t num_handles, int64_t timeout_ns) {
87 LOG_TRACE(Kernel_SVC, "called user_handles={:#x}, num_handles={}, timeout_ns={}", user_handles,
88 num_handles, timeout_ns);
89
90 // Ensure number of handles is valid.
91 R_UNLESS(0 <= num_handles && num_handles <= Svc::ArgumentHandleCountMax, ResultOutOfRange);
92
93 std::vector<Handle> handles(num_handles);
94 if (num_handles > 0) {
95 system.Memory().ReadBlock(user_handles, handles.data(), num_handles * sizeof(Handle));
96 }
97
98 R_RETURN(WaitSynchronization(system, out_index, handles.data(), num_handles, timeout_ns));
86} 99}
87 100
88/// Resumes a thread waiting on WaitSynchronization 101/// Resumes a thread waiting on WaitSynchronization
diff --git a/src/core/hle/service/acc/acc.cpp b/src/core/hle/service/acc/acc.cpp
index ddc3a6dbe..120282aa4 100644
--- a/src/core/hle/service/acc/acc.cpp
+++ b/src/core/hle/service/acc/acc.cpp
@@ -30,12 +30,6 @@
30 30
31namespace Service::Account { 31namespace Service::Account {
32 32
33constexpr Result ERR_INVALID_USER_ID{ErrorModule::Account, 20};
34constexpr Result ERR_INVALID_APPLICATION_ID{ErrorModule::Account, 22};
35constexpr Result ERR_INVALID_BUFFER{ErrorModule::Account, 30};
36constexpr Result ERR_INVALID_BUFFER_SIZE{ErrorModule::Account, 31};
37constexpr Result ERR_FAILED_SAVE_DATA{ErrorModule::Account, 100};
38
39// Thumbnails are hard coded to be at least this size 33// Thumbnails are hard coded to be at least this size
40constexpr std::size_t THUMBNAIL_SIZE = 0x24000; 34constexpr std::size_t THUMBNAIL_SIZE = 0x24000;
41 35
@@ -384,7 +378,7 @@ protected:
384 if (user_data.size() < sizeof(UserData)) { 378 if (user_data.size() < sizeof(UserData)) {
385 LOG_ERROR(Service_ACC, "UserData buffer too small!"); 379 LOG_ERROR(Service_ACC, "UserData buffer too small!");
386 IPC::ResponseBuilder rb{ctx, 2}; 380 IPC::ResponseBuilder rb{ctx, 2};
387 rb.Push(ERR_INVALID_BUFFER); 381 rb.Push(Account::ResultInvalidArrayLength);
388 return; 382 return;
389 } 383 }
390 384
@@ -394,7 +388,7 @@ protected:
394 if (!profile_manager.SetProfileBaseAndData(user_id, base, data)) { 388 if (!profile_manager.SetProfileBaseAndData(user_id, base, data)) {
395 LOG_ERROR(Service_ACC, "Failed to update user data and base!"); 389 LOG_ERROR(Service_ACC, "Failed to update user data and base!");
396 IPC::ResponseBuilder rb{ctx, 2}; 390 IPC::ResponseBuilder rb{ctx, 2};
397 rb.Push(ERR_FAILED_SAVE_DATA); 391 rb.Push(Account::ResultAccountUpdateFailed);
398 return; 392 return;
399 } 393 }
400 394
@@ -417,7 +411,7 @@ protected:
417 if (user_data.size() < sizeof(UserData)) { 411 if (user_data.size() < sizeof(UserData)) {
418 LOG_ERROR(Service_ACC, "UserData buffer too small!"); 412 LOG_ERROR(Service_ACC, "UserData buffer too small!");
419 IPC::ResponseBuilder rb{ctx, 2}; 413 IPC::ResponseBuilder rb{ctx, 2};
420 rb.Push(ERR_INVALID_BUFFER); 414 rb.Push(Account::ResultInvalidArrayLength);
421 return; 415 return;
422 } 416 }
423 417
@@ -432,7 +426,7 @@ protected:
432 !profile_manager.SetProfileBaseAndData(user_id, base, data)) { 426 !profile_manager.SetProfileBaseAndData(user_id, base, data)) {
433 LOG_ERROR(Service_ACC, "Failed to update profile data, base, and image!"); 427 LOG_ERROR(Service_ACC, "Failed to update profile data, base, and image!");
434 IPC::ResponseBuilder rb{ctx, 2}; 428 IPC::ResponseBuilder rb{ctx, 2};
435 rb.Push(ERR_FAILED_SAVE_DATA); 429 rb.Push(Account::ResultAccountUpdateFailed);
436 return; 430 return;
437 } 431 }
438 432
@@ -764,7 +758,7 @@ void Module::Interface::InitializeApplicationInfoRestricted(HLERequestContext& c
764Result Module::Interface::InitializeApplicationInfoBase() { 758Result Module::Interface::InitializeApplicationInfoBase() {
765 if (application_info) { 759 if (application_info) {
766 LOG_ERROR(Service_ACC, "Application already initialized"); 760 LOG_ERROR(Service_ACC, "Application already initialized");
767 return ERR_ACCOUNTINFO_ALREADY_INITIALIZED; 761 return Account::ResultApplicationInfoAlreadyInitialized;
768 } 762 }
769 763
770 // TODO(ogniK): This should be changed to reflect the target process for when we have multiple 764 // TODO(ogniK): This should be changed to reflect the target process for when we have multiple
@@ -775,7 +769,7 @@ Result Module::Interface::InitializeApplicationInfoBase() {
775 769
776 if (launch_property.Failed()) { 770 if (launch_property.Failed()) {
777 LOG_ERROR(Service_ACC, "Failed to get launch property"); 771 LOG_ERROR(Service_ACC, "Failed to get launch property");
778 return ERR_ACCOUNTINFO_BAD_APPLICATION; 772 return Account::ResultInvalidApplication;
779 } 773 }
780 774
781 switch (launch_property->base_game_storage_id) { 775 switch (launch_property->base_game_storage_id) {
@@ -791,7 +785,7 @@ Result Module::Interface::InitializeApplicationInfoBase() {
791 default: 785 default:
792 LOG_ERROR(Service_ACC, "Invalid game storage ID! storage_id={}", 786 LOG_ERROR(Service_ACC, "Invalid game storage ID! storage_id={}",
793 launch_property->base_game_storage_id); 787 launch_property->base_game_storage_id);
794 return ERR_ACCOUNTINFO_BAD_APPLICATION; 788 return Account::ResultInvalidApplication;
795 } 789 }
796 790
797 LOG_WARNING(Service_ACC, "ApplicationInfo init required"); 791 LOG_WARNING(Service_ACC, "ApplicationInfo init required");
@@ -899,20 +893,20 @@ void Module::Interface::StoreSaveDataThumbnail(HLERequestContext& ctx, const Com
899 893
900 if (tid == 0) { 894 if (tid == 0) {
901 LOG_ERROR(Service_ACC, "TitleID is not valid!"); 895 LOG_ERROR(Service_ACC, "TitleID is not valid!");
902 rb.Push(ERR_INVALID_APPLICATION_ID); 896 rb.Push(Account::ResultInvalidApplication);
903 return; 897 return;
904 } 898 }
905 899
906 if (uuid.IsInvalid()) { 900 if (uuid.IsInvalid()) {
907 LOG_ERROR(Service_ACC, "User ID is not valid!"); 901 LOG_ERROR(Service_ACC, "User ID is not valid!");
908 rb.Push(ERR_INVALID_USER_ID); 902 rb.Push(Account::ResultInvalidUserId);
909 return; 903 return;
910 } 904 }
911 const auto thumbnail_size = ctx.GetReadBufferSize(); 905 const auto thumbnail_size = ctx.GetReadBufferSize();
912 if (thumbnail_size != THUMBNAIL_SIZE) { 906 if (thumbnail_size != THUMBNAIL_SIZE) {
913 LOG_ERROR(Service_ACC, "Buffer size is empty! size={:X} expecting {:X}", thumbnail_size, 907 LOG_ERROR(Service_ACC, "Buffer size is empty! size={:X} expecting {:X}", thumbnail_size,
914 THUMBNAIL_SIZE); 908 THUMBNAIL_SIZE);
915 rb.Push(ERR_INVALID_BUFFER_SIZE); 909 rb.Push(Account::ResultInvalidArrayLength);
916 return; 910 return;
917 } 911 }
918 912
diff --git a/src/core/hle/service/acc/errors.h b/src/core/hle/service/acc/errors.h
index e9c16b951..433ebfe9d 100644
--- a/src/core/hle/service/acc/errors.h
+++ b/src/core/hle/service/acc/errors.h
@@ -7,7 +7,13 @@
7 7
8namespace Service::Account { 8namespace Service::Account {
9 9
10constexpr Result ERR_ACCOUNTINFO_BAD_APPLICATION{ErrorModule::Account, 22}; 10constexpr Result ResultCancelledByUser{ErrorModule::Account, 1};
11constexpr Result ERR_ACCOUNTINFO_ALREADY_INITIALIZED{ErrorModule::Account, 41}; 11constexpr Result ResultNoNotifications{ErrorModule::Account, 15};
12constexpr Result ResultInvalidUserId{ErrorModule::Account, 20};
13constexpr Result ResultInvalidApplication{ErrorModule::Account, 22};
14constexpr Result ResultNullptr{ErrorModule::Account, 30};
15constexpr Result ResultInvalidArrayLength{ErrorModule::Account, 32};
16constexpr Result ResultApplicationInfoAlreadyInitialized{ErrorModule::Account, 41};
17constexpr Result ResultAccountUpdateFailed{ErrorModule::Account, 100};
12 18
13} // namespace Service::Account 19} // namespace Service::Account
diff --git a/src/core/hle/service/am/am.cpp b/src/core/hle/service/am/am.cpp
index f74c7b550..f17df5124 100644
--- a/src/core/hle/service/am/am.cpp
+++ b/src/core/hle/service/am/am.cpp
@@ -39,9 +39,9 @@
39 39
40namespace Service::AM { 40namespace Service::AM {
41 41
42constexpr Result ERR_NO_DATA_IN_CHANNEL{ErrorModule::AM, 2}; 42constexpr Result ResultNoDataInChannel{ErrorModule::AM, 2};
43constexpr Result ERR_NO_MESSAGES{ErrorModule::AM, 3}; 43constexpr Result ResultNoMessages{ErrorModule::AM, 3};
44constexpr Result ERR_SIZE_OUT_OF_BOUNDS{ErrorModule::AM, 503}; 44constexpr Result ResultInvalidOffset{ErrorModule::AM, 503};
45 45
46enum class LaunchParameterKind : u32 { 46enum class LaunchParameterKind : u32 {
47 ApplicationSpecific = 1, 47 ApplicationSpecific = 1,
@@ -758,7 +758,7 @@ void ICommonStateGetter::ReceiveMessage(HLERequestContext& ctx) {
758 758
759 if (message == AppletMessageQueue::AppletMessage::None) { 759 if (message == AppletMessageQueue::AppletMessage::None) {
760 LOG_ERROR(Service_AM, "Message queue is empty"); 760 LOG_ERROR(Service_AM, "Message queue is empty");
761 rb.Push(ERR_NO_MESSAGES); 761 rb.Push(AM::ResultNoMessages);
762 rb.PushEnum<AppletMessageQueue::AppletMessage>(message); 762 rb.PushEnum<AppletMessageQueue::AppletMessage>(message);
763 return; 763 return;
764 } 764 }
@@ -1028,7 +1028,7 @@ private:
1028 LOG_DEBUG(Service_AM, 1028 LOG_DEBUG(Service_AM,
1029 "storage is a nullptr. There is no data in the current normal channel"); 1029 "storage is a nullptr. There is no data in the current normal channel");
1030 IPC::ResponseBuilder rb{ctx, 2}; 1030 IPC::ResponseBuilder rb{ctx, 2};
1031 rb.Push(ERR_NO_DATA_IN_CHANNEL); 1031 rb.Push(AM::ResultNoDataInChannel);
1032 return; 1032 return;
1033 } 1033 }
1034 1034
@@ -1059,7 +1059,7 @@ private:
1059 LOG_DEBUG(Service_AM, 1059 LOG_DEBUG(Service_AM,
1060 "storage is a nullptr. There is no data in the current interactive channel"); 1060 "storage is a nullptr. There is no data in the current interactive channel");
1061 IPC::ResponseBuilder rb{ctx, 2}; 1061 IPC::ResponseBuilder rb{ctx, 2};
1062 rb.Push(ERR_NO_DATA_IN_CHANNEL); 1062 rb.Push(AM::ResultNoDataInChannel);
1063 return; 1063 return;
1064 } 1064 }
1065 1065
@@ -1138,7 +1138,7 @@ void IStorageAccessor::Write(HLERequestContext& ctx) {
1138 backing.GetSize(), size, offset); 1138 backing.GetSize(), size, offset);
1139 1139
1140 IPC::ResponseBuilder rb{ctx, 2}; 1140 IPC::ResponseBuilder rb{ctx, 2};
1141 rb.Push(ERR_SIZE_OUT_OF_BOUNDS); 1141 rb.Push(AM::ResultInvalidOffset);
1142 return; 1142 return;
1143 } 1143 }
1144 1144
@@ -1161,7 +1161,7 @@ void IStorageAccessor::Read(HLERequestContext& ctx) {
1161 backing.GetSize(), size, offset); 1161 backing.GetSize(), size, offset);
1162 1162
1163 IPC::ResponseBuilder rb{ctx, 2}; 1163 IPC::ResponseBuilder rb{ctx, 2};
1164 rb.Push(ERR_SIZE_OUT_OF_BOUNDS); 1164 rb.Push(AM::ResultInvalidOffset);
1165 return; 1165 return;
1166 } 1166 }
1167 1167
@@ -1502,7 +1502,7 @@ void IApplicationFunctions::PopLaunchParameter(HLERequestContext& ctx) {
1502 1502
1503 LOG_ERROR(Service_AM, "Attempted to load launch parameter but none was found!"); 1503 LOG_ERROR(Service_AM, "Attempted to load launch parameter but none was found!");
1504 IPC::ResponseBuilder rb{ctx, 2}; 1504 IPC::ResponseBuilder rb{ctx, 2};
1505 rb.Push(ERR_NO_DATA_IN_CHANNEL); 1505 rb.Push(AM::ResultNoDataInChannel);
1506} 1506}
1507 1507
1508void IApplicationFunctions::CreateApplicationAndRequestToStartForQuest(HLERequestContext& ctx) { 1508void IApplicationFunctions::CreateApplicationAndRequestToStartForQuest(HLERequestContext& ctx) {
@@ -1799,7 +1799,7 @@ void IApplicationFunctions::TryPopFromFriendInvitationStorageChannel(HLERequestC
1799 LOG_WARNING(Service_AM, "(STUBBED) called"); 1799 LOG_WARNING(Service_AM, "(STUBBED) called");
1800 1800
1801 IPC::ResponseBuilder rb{ctx, 2}; 1801 IPC::ResponseBuilder rb{ctx, 2};
1802 rb.Push(ERR_NO_DATA_IN_CHANNEL); 1802 rb.Push(AM::ResultNoDataInChannel);
1803} 1803}
1804 1804
1805void IApplicationFunctions::GetNotificationStorageChannelEvent(HLERequestContext& ctx) { 1805void IApplicationFunctions::GetNotificationStorageChannelEvent(HLERequestContext& ctx) {
diff --git a/src/core/hle/service/am/applets/applet_controller.cpp b/src/core/hle/service/am/applets/applet_controller.cpp
index b418031de..58484519b 100644
--- a/src/core/hle/service/am/applets/applet_controller.cpp
+++ b/src/core/hle/service/am/applets/applet_controller.cpp
@@ -19,10 +19,9 @@
19 19
20namespace Service::AM::Applets { 20namespace Service::AM::Applets {
21 21
22// This error code (0x183ACA) is thrown when the applet fails to initialize. 22[[maybe_unused]] constexpr Result ResultControllerSupportCanceled{ErrorModule::HID, 3101};
23[[maybe_unused]] constexpr Result ERR_CONTROLLER_APPLET_3101{ErrorModule::HID, 3101}; 23[[maybe_unused]] constexpr Result ResultControllerSupportNotSupportedNpadStyle{ErrorModule::HID,
24// This error code (0x183CCA) is thrown when the u32 result in ControllerSupportResultInfo is 2. 24 3102};
25[[maybe_unused]] constexpr Result ERR_CONTROLLER_APPLET_3102{ErrorModule::HID, 3102};
26 25
27static Core::Frontend::ControllerParameters ConvertToFrontendParameters( 26static Core::Frontend::ControllerParameters ConvertToFrontendParameters(
28 ControllerSupportArgPrivate private_arg, ControllerSupportArgHeader header, bool enable_text, 27 ControllerSupportArgPrivate private_arg, ControllerSupportArgHeader header, bool enable_text,
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 c738db028..1d69f5447 100644
--- a/src/core/hle/service/am/applets/applet_profile_select.cpp
+++ b/src/core/hle/service/am/applets/applet_profile_select.cpp
@@ -7,13 +7,12 @@
7#include "common/string_util.h" 7#include "common/string_util.h"
8#include "core/core.h" 8#include "core/core.h"
9#include "core/frontend/applets/profile_select.h" 9#include "core/frontend/applets/profile_select.h"
10#include "core/hle/service/acc/errors.h"
10#include "core/hle/service/am/am.h" 11#include "core/hle/service/am/am.h"
11#include "core/hle/service/am/applets/applet_profile_select.h" 12#include "core/hle/service/am/applets/applet_profile_select.h"
12 13
13namespace Service::AM::Applets { 14namespace Service::AM::Applets {
14 15
15constexpr Result ERR_USER_CANCELLED_SELECTION{ErrorModule::Account, 1};
16
17ProfileSelect::ProfileSelect(Core::System& system_, LibraryAppletMode applet_mode_, 16ProfileSelect::ProfileSelect(Core::System& system_, LibraryAppletMode applet_mode_,
18 const Core::Frontend::ProfileSelectApplet& frontend_) 17 const Core::Frontend::ProfileSelectApplet& frontend_)
19 : Applet{system_, applet_mode_}, frontend{frontend_}, system{system_} {} 18 : Applet{system_, applet_mode_}, frontend{frontend_}, system{system_} {}
@@ -63,8 +62,8 @@ void ProfileSelect::SelectionComplete(std::optional<Common::UUID> uuid) {
63 output.result = 0; 62 output.result = 0;
64 output.uuid_selected = *uuid; 63 output.uuid_selected = *uuid;
65 } else { 64 } else {
66 status = ERR_USER_CANCELLED_SELECTION; 65 status = Account::ResultCancelledByUser;
67 output.result = ERR_USER_CANCELLED_SELECTION.raw; 66 output.result = Account::ResultCancelledByUser.raw;
68 output.uuid_selected = Common::InvalidUUID; 67 output.uuid_selected = Common::InvalidUUID;
69 } 68 }
70 69
diff --git a/src/core/hle/service/audio/audren_u.cpp b/src/core/hle/service/audio/audren_u.cpp
index 0a6830ffa..7086d4750 100644
--- a/src/core/hle/service/audio/audren_u.cpp
+++ b/src/core/hle/service/audio/audren_u.cpp
@@ -170,7 +170,7 @@ private:
170 170
171 if (impl->GetSystem().GetExecutionMode() == AudioCore::ExecutionMode::Manual) { 171 if (impl->GetSystem().GetExecutionMode() == AudioCore::ExecutionMode::Manual) {
172 IPC::ResponseBuilder rb{ctx, 2}; 172 IPC::ResponseBuilder rb{ctx, 2};
173 rb.Push(ERR_NOT_SUPPORTED); 173 rb.Push(Audio::ResultNotSupported);
174 return; 174 return;
175 } 175 }
176 176
@@ -448,7 +448,7 @@ void AudRenU::OpenAudioRenderer(HLERequestContext& ctx) {
448 if (impl->GetSessionCount() + 1 > AudioCore::MaxRendererSessions) { 448 if (impl->GetSessionCount() + 1 > AudioCore::MaxRendererSessions) {
449 LOG_ERROR(Service_Audio, "Too many AudioRenderer sessions open!"); 449 LOG_ERROR(Service_Audio, "Too many AudioRenderer sessions open!");
450 IPC::ResponseBuilder rb{ctx, 2}; 450 IPC::ResponseBuilder rb{ctx, 2};
451 rb.Push(ERR_MAXIMUM_SESSIONS_REACHED); 451 rb.Push(Audio::ResultOutOfSessions);
452 return; 452 return;
453 } 453 }
454 454
@@ -461,7 +461,7 @@ void AudRenU::OpenAudioRenderer(HLERequestContext& ctx) {
461 if (session_id == -1) { 461 if (session_id == -1) {
462 LOG_ERROR(Service_Audio, "Tried to open a session that's already in use!"); 462 LOG_ERROR(Service_Audio, "Tried to open a session that's already in use!");
463 IPC::ResponseBuilder rb{ctx, 2}; 463 IPC::ResponseBuilder rb{ctx, 2};
464 rb.Push(ERR_MAXIMUM_SESSIONS_REACHED); 464 rb.Push(Audio::ResultOutOfSessions);
465 return; 465 return;
466 } 466 }
467 467
diff --git a/src/core/hle/service/audio/errors.h b/src/core/hle/service/audio/errors.h
index d706978cb..3d3d3d97a 100644
--- a/src/core/hle/service/audio/errors.h
+++ b/src/core/hle/service/audio/errors.h
@@ -7,17 +7,17 @@
7 7
8namespace Service::Audio { 8namespace Service::Audio {
9 9
10constexpr Result ERR_INVALID_DEVICE_NAME{ErrorModule::Audio, 1}; 10constexpr Result ResultNotFound{ErrorModule::Audio, 1};
11constexpr Result ERR_OPERATION_FAILED{ErrorModule::Audio, 2}; 11constexpr Result ResultOperationFailed{ErrorModule::Audio, 2};
12constexpr Result ERR_INVALID_SAMPLE_RATE{ErrorModule::Audio, 3}; 12constexpr Result ResultInvalidSampleRate{ErrorModule::Audio, 3};
13constexpr Result ERR_INSUFFICIENT_BUFFER_SIZE{ErrorModule::Audio, 4}; 13constexpr Result ResultInsufficientBuffer{ErrorModule::Audio, 4};
14constexpr Result ERR_MAXIMUM_SESSIONS_REACHED{ErrorModule::Audio, 5}; 14constexpr Result ResultOutOfSessions{ErrorModule::Audio, 5};
15constexpr Result ERR_BUFFER_COUNT_EXCEEDED{ErrorModule::Audio, 8}; 15constexpr Result ResultBufferCountReached{ErrorModule::Audio, 8};
16constexpr Result ERR_INVALID_CHANNEL_COUNT{ErrorModule::Audio, 10}; 16constexpr Result ResultInvalidChannelCount{ErrorModule::Audio, 10};
17constexpr Result ERR_INVALID_UPDATE_DATA{ErrorModule::Audio, 41}; 17constexpr Result ResultInvalidUpdateInfo{ErrorModule::Audio, 41};
18constexpr Result ERR_POOL_MAPPING_FAILED{ErrorModule::Audio, 42}; 18constexpr Result ResultInvalidAddressInfo{ErrorModule::Audio, 42};
19constexpr Result ERR_NOT_SUPPORTED{ErrorModule::Audio, 513}; 19constexpr Result ResultNotSupported{ErrorModule::Audio, 513};
20constexpr Result ERR_INVALID_PROCESS_HANDLE{ErrorModule::Audio, 1536}; 20constexpr Result ResultInvalidHandle{ErrorModule::Audio, 1536};
21constexpr Result ERR_INVALID_REVISION{ErrorModule::Audio, 1537}; 21constexpr Result ResultInvalidRevision{ErrorModule::Audio, 1537};
22 22
23} // namespace Service::Audio 23} // namespace Service::Audio
diff --git a/src/core/hle/service/friend/errors.h b/src/core/hle/service/friend/errors.h
deleted file mode 100644
index ff525d865..000000000
--- a/src/core/hle/service/friend/errors.h
+++ /dev/null
@@ -1,11 +0,0 @@
1// SPDX-FileCopyrightText: Copyright 2019 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4#pragma once
5
6#include "core/hle/result.h"
7
8namespace Service::Friend {
9
10constexpr Result ERR_NO_NOTIFICATIONS{ErrorModule::Account, 15};
11}
diff --git a/src/core/hle/service/friend/friend.cpp b/src/core/hle/service/friend/friend.cpp
index 447deab8b..9d05f9801 100644
--- a/src/core/hle/service/friend/friend.cpp
+++ b/src/core/hle/service/friend/friend.cpp
@@ -6,7 +6,7 @@
6#include "common/uuid.h" 6#include "common/uuid.h"
7#include "core/core.h" 7#include "core/core.h"
8#include "core/hle/kernel/k_event.h" 8#include "core/hle/kernel/k_event.h"
9#include "core/hle/service/friend/errors.h" 9#include "core/hle/service/acc/errors.h"
10#include "core/hle/service/friend/friend.h" 10#include "core/hle/service/friend/friend.h"
11#include "core/hle/service/friend/friend_interface.h" 11#include "core/hle/service/friend/friend_interface.h"
12#include "core/hle/service/ipc_helpers.h" 12#include "core/hle/service/ipc_helpers.h"
@@ -259,7 +259,7 @@ private:
259 if (notifications.empty()) { 259 if (notifications.empty()) {
260 LOG_ERROR(Service_Friend, "No notifications in queue!"); 260 LOG_ERROR(Service_Friend, "No notifications in queue!");
261 IPC::ResponseBuilder rb{ctx, 2}; 261 IPC::ResponseBuilder rb{ctx, 2};
262 rb.Push(ERR_NO_NOTIFICATIONS); 262 rb.Push(Account::ResultNoNotifications);
263 return; 263 return;
264 } 264 }
265 265
diff --git a/src/core/hle/service/glue/arp.cpp b/src/core/hle/service/glue/arp.cpp
index 9db136bac..929dcca0d 100644
--- a/src/core/hle/service/glue/arp.cpp
+++ b/src/core/hle/service/glue/arp.cpp
@@ -61,7 +61,7 @@ void ARP_R::GetApplicationLaunchProperty(HLERequestContext& ctx) {
61 if (!title_id.has_value()) { 61 if (!title_id.has_value()) {
62 LOG_ERROR(Service_ARP, "Failed to get title ID for process ID!"); 62 LOG_ERROR(Service_ARP, "Failed to get title ID for process ID!");
63 IPC::ResponseBuilder rb{ctx, 2}; 63 IPC::ResponseBuilder rb{ctx, 2};
64 rb.Push(ERR_NOT_REGISTERED); 64 rb.Push(Glue::ResultProcessIdNotRegistered);
65 return; 65 return;
66 } 66 }
67 67
@@ -109,7 +109,7 @@ void ARP_R::GetApplicationControlProperty(HLERequestContext& ctx) {
109 if (!title_id.has_value()) { 109 if (!title_id.has_value()) {
110 LOG_ERROR(Service_ARP, "Failed to get title ID for process ID!"); 110 LOG_ERROR(Service_ARP, "Failed to get title ID for process ID!");
111 IPC::ResponseBuilder rb{ctx, 2}; 111 IPC::ResponseBuilder rb{ctx, 2};
112 rb.Push(ERR_NOT_REGISTERED); 112 rb.Push(Glue::ResultProcessIdNotRegistered);
113 return; 113 return;
114 } 114 }
115 115
@@ -178,7 +178,7 @@ private:
178 if (process_id == 0) { 178 if (process_id == 0) {
179 LOG_ERROR(Service_ARP, "Must have non-zero process ID!"); 179 LOG_ERROR(Service_ARP, "Must have non-zero process ID!");
180 IPC::ResponseBuilder rb{ctx, 2}; 180 IPC::ResponseBuilder rb{ctx, 2};
181 rb.Push(ERR_INVALID_PROCESS_ID); 181 rb.Push(Glue::ResultInvalidProcessId);
182 return; 182 return;
183 } 183 }
184 184
@@ -186,7 +186,7 @@ private:
186 LOG_ERROR(Service_ARP, 186 LOG_ERROR(Service_ARP,
187 "Attempted to issue registrar, but registrar is already issued!"); 187 "Attempted to issue registrar, but registrar is already issued!");
188 IPC::ResponseBuilder rb{ctx, 2}; 188 IPC::ResponseBuilder rb{ctx, 2};
189 rb.Push(ERR_INVALID_ACCESS); 189 rb.Push(Glue::ResultAlreadyBound);
190 return; 190 return;
191 } 191 }
192 192
@@ -205,7 +205,7 @@ private:
205 Service_ARP, 205 Service_ARP,
206 "Attempted to set application launch property, but registrar is already issued!"); 206 "Attempted to set application launch property, but registrar is already issued!");
207 IPC::ResponseBuilder rb{ctx, 2}; 207 IPC::ResponseBuilder rb{ctx, 2};
208 rb.Push(ERR_INVALID_ACCESS); 208 rb.Push(Glue::ResultAlreadyBound);
209 return; 209 return;
210 } 210 }
211 211
@@ -224,7 +224,7 @@ private:
224 Service_ARP, 224 Service_ARP,
225 "Attempted to set application control property, but registrar is already issued!"); 225 "Attempted to set application control property, but registrar is already issued!");
226 IPC::ResponseBuilder rb{ctx, 2}; 226 IPC::ResponseBuilder rb{ctx, 2};
227 rb.Push(ERR_INVALID_ACCESS); 227 rb.Push(Glue::ResultAlreadyBound);
228 return; 228 return;
229 } 229 }
230 230
@@ -263,7 +263,7 @@ void ARP_W::AcquireRegistrar(HLERequestContext& ctx) {
263 system, [this](u64 process_id, ApplicationLaunchProperty launch, std::vector<u8> control) { 263 system, [this](u64 process_id, ApplicationLaunchProperty launch, std::vector<u8> control) {
264 const auto res = GetTitleIDForProcessID(system, process_id); 264 const auto res = GetTitleIDForProcessID(system, process_id);
265 if (!res.has_value()) { 265 if (!res.has_value()) {
266 return ERR_NOT_REGISTERED; 266 return Glue::ResultProcessIdNotRegistered;
267 } 267 }
268 268
269 return manager.Register(*res, launch, std::move(control)); 269 return manager.Register(*res, launch, std::move(control));
@@ -283,7 +283,7 @@ void ARP_W::UnregisterApplicationInstance(HLERequestContext& ctx) {
283 if (process_id == 0) { 283 if (process_id == 0) {
284 LOG_ERROR(Service_ARP, "Must have non-zero process ID!"); 284 LOG_ERROR(Service_ARP, "Must have non-zero process ID!");
285 IPC::ResponseBuilder rb{ctx, 2}; 285 IPC::ResponseBuilder rb{ctx, 2};
286 rb.Push(ERR_INVALID_PROCESS_ID); 286 rb.Push(Glue::ResultInvalidProcessId);
287 return; 287 return;
288 } 288 }
289 289
@@ -292,7 +292,7 @@ void ARP_W::UnregisterApplicationInstance(HLERequestContext& ctx) {
292 if (!title_id.has_value()) { 292 if (!title_id.has_value()) {
293 LOG_ERROR(Service_ARP, "No title ID for process ID!"); 293 LOG_ERROR(Service_ARP, "No title ID for process ID!");
294 IPC::ResponseBuilder rb{ctx, 2}; 294 IPC::ResponseBuilder rb{ctx, 2};
295 rb.Push(ERR_NOT_REGISTERED); 295 rb.Push(Glue::ResultProcessIdNotRegistered);
296 return; 296 return;
297 } 297 }
298 298
diff --git a/src/core/hle/service/glue/errors.h b/src/core/hle/service/glue/errors.h
index d4ce7f44e..30feaa5c0 100644
--- a/src/core/hle/service/glue/errors.h
+++ b/src/core/hle/service/glue/errors.h
@@ -7,9 +7,8 @@
7 7
8namespace Service::Glue { 8namespace Service::Glue {
9 9
10constexpr Result ERR_INVALID_RESOURCE{ErrorModule::ARP, 30}; 10constexpr Result ResultInvalidProcessId{ErrorModule::ARP, 31};
11constexpr Result ERR_INVALID_PROCESS_ID{ErrorModule::ARP, 31}; 11constexpr Result ResultAlreadyBound{ErrorModule::ARP, 42};
12constexpr Result ERR_INVALID_ACCESS{ErrorModule::ARP, 42}; 12constexpr Result ResultProcessIdNotRegistered{ErrorModule::ARP, 102};
13constexpr Result ERR_NOT_REGISTERED{ErrorModule::ARP, 102};
14 13
15} // namespace Service::Glue 14} // namespace Service::Glue
diff --git a/src/core/hle/service/glue/glue_manager.cpp b/src/core/hle/service/glue/glue_manager.cpp
index 8a654cdca..4bf67921b 100644
--- a/src/core/hle/service/glue/glue_manager.cpp
+++ b/src/core/hle/service/glue/glue_manager.cpp
@@ -17,12 +17,12 @@ ARPManager::~ARPManager() = default;
17 17
18ResultVal<ApplicationLaunchProperty> ARPManager::GetLaunchProperty(u64 title_id) const { 18ResultVal<ApplicationLaunchProperty> ARPManager::GetLaunchProperty(u64 title_id) const {
19 if (title_id == 0) { 19 if (title_id == 0) {
20 return ERR_INVALID_PROCESS_ID; 20 return Glue::ResultInvalidProcessId;
21 } 21 }
22 22
23 const auto iter = entries.find(title_id); 23 const auto iter = entries.find(title_id);
24 if (iter == entries.end()) { 24 if (iter == entries.end()) {
25 return ERR_NOT_REGISTERED; 25 return Glue::ResultProcessIdNotRegistered;
26 } 26 }
27 27
28 return iter->second.launch; 28 return iter->second.launch;
@@ -30,12 +30,12 @@ ResultVal<ApplicationLaunchProperty> ARPManager::GetLaunchProperty(u64 title_id)
30 30
31ResultVal<std::vector<u8>> ARPManager::GetControlProperty(u64 title_id) const { 31ResultVal<std::vector<u8>> ARPManager::GetControlProperty(u64 title_id) const {
32 if (title_id == 0) { 32 if (title_id == 0) {
33 return ERR_INVALID_PROCESS_ID; 33 return Glue::ResultInvalidProcessId;
34 } 34 }
35 35
36 const auto iter = entries.find(title_id); 36 const auto iter = entries.find(title_id);
37 if (iter == entries.end()) { 37 if (iter == entries.end()) {
38 return ERR_NOT_REGISTERED; 38 return Glue::ResultProcessIdNotRegistered;
39 } 39 }
40 40
41 return iter->second.control; 41 return iter->second.control;
@@ -44,12 +44,12 @@ ResultVal<std::vector<u8>> ARPManager::GetControlProperty(u64 title_id) const {
44Result 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 Glue::ResultInvalidProcessId;
48 } 48 }
49 49
50 const auto iter = entries.find(title_id); 50 const auto iter = entries.find(title_id);
51 if (iter != entries.end()) { 51 if (iter != entries.end()) {
52 return ERR_INVALID_ACCESS; 52 return Glue::ResultAlreadyBound;
53 } 53 }
54 54
55 entries.insert_or_assign(title_id, MapEntry{launch, std::move(control)}); 55 entries.insert_or_assign(title_id, MapEntry{launch, std::move(control)});
@@ -58,12 +58,12 @@ Result ARPManager::Register(u64 title_id, ApplicationLaunchProperty launch,
58 58
59Result 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 Glue::ResultInvalidProcessId;
62 } 62 }
63 63
64 const auto iter = entries.find(title_id); 64 const auto iter = entries.find(title_id);
65 if (iter == entries.end()) { 65 if (iter == entries.end()) {
66 return ERR_NOT_REGISTERED; 66 return Glue::ResultProcessIdNotRegistered;
67 } 67 }
68 68
69 entries.erase(iter); 69 entries.erase(iter);
diff --git a/src/core/hle/service/glue/glue_manager.h b/src/core/hle/service/glue/glue_manager.h
index cd0b092ac..1cf53d9d9 100644
--- a/src/core/hle/service/glue/glue_manager.h
+++ b/src/core/hle/service/glue/glue_manager.h
@@ -30,23 +30,23 @@ public:
30 ~ARPManager(); 30 ~ARPManager();
31 31
32 // Returns the ApplicationLaunchProperty corresponding to the provided title ID if it was 32 // Returns the ApplicationLaunchProperty corresponding to the provided title ID if it was
33 // previously registered, otherwise ERR_NOT_REGISTERED if it was never registered or 33 // previously registered, otherwise ResultProcessIdNotRegistered if it was never registered or
34 // ERR_INVALID_PROCESS_ID if the title ID is 0. 34 // ResultInvalidProcessId if the title ID is 0.
35 ResultVal<ApplicationLaunchProperty> GetLaunchProperty(u64 title_id) const; 35 ResultVal<ApplicationLaunchProperty> GetLaunchProperty(u64 title_id) const;
36 36
37 // Returns a vector of the raw bytes of NACP data (necessarily 0x4000 in size) corresponding to 37 // Returns a vector of the raw bytes of NACP data (necessarily 0x4000 in size) corresponding to
38 // the provided title ID if it was previously registered, otherwise ERR_NOT_REGISTERED if it was 38 // the provided title ID if it was previously registered, otherwise ResultProcessIdNotRegistered
39 // never registered or ERR_INVALID_PROCESS_ID if the title ID is 0. 39 // if it was never registered or ResultInvalidProcessId if the title ID is 0.
40 ResultVal<std::vector<u8>> GetControlProperty(u64 title_id) const; 40 ResultVal<std::vector<u8>> GetControlProperty(u64 title_id) const;
41 41
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 // ResultProcessIdNotRegistered if attempting to re-register a title ID without an intermediate
44 // step, and ERR_INVALID_PROCESS_ID if the title ID is 0. 44 // Unregister step, and ResultInvalidProcessId if the title ID is 0.
45 Result 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 // ResultProcessIdNotRegistered if it doesn't exist in the database and ResultInvalidProcessId
49 // title ID is 0. 49 // if the title ID is 0.
50 Result 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
diff --git a/src/core/hle/service/ipc_helpers.h b/src/core/hle/service/ipc_helpers.h
index 3e67123c7..8703b57ca 100644
--- a/src/core/hle/service/ipc_helpers.h
+++ b/src/core/hle/service/ipc_helpers.h
@@ -19,7 +19,7 @@
19 19
20namespace IPC { 20namespace IPC {
21 21
22constexpr Result ERR_REMOTE_PROCESS_DEAD{ErrorModule::HIPC, 301}; 22constexpr Result ResultSessionClosed{ErrorModule::HIPC, 301};
23 23
24class RequestHelperBase { 24class RequestHelperBase {
25protected: 25protected:
diff --git a/src/core/hle/service/ns/errors.h b/src/core/hle/service/ns/errors.h
index 8a7621798..16d2ea6f7 100644
--- a/src/core/hle/service/ns/errors.h
+++ b/src/core/hle/service/ns/errors.h
@@ -7,5 +7,6 @@
7 7
8namespace Service::NS { 8namespace Service::NS {
9 9
10constexpr Result ERR_APPLICATION_LANGUAGE_NOT_FOUND{ErrorModule::NS, 300}; 10constexpr Result ResultApplicationLanguageNotFound{ErrorModule::NS, 300};
11} \ No newline at end of file 11
12}
diff --git a/src/core/hle/service/ns/ns.cpp b/src/core/hle/service/ns/ns.cpp
index d6f0faea2..376067a95 100644
--- a/src/core/hle/service/ns/ns.cpp
+++ b/src/core/hle/service/ns/ns.cpp
@@ -416,14 +416,14 @@ ResultVal<u8> IApplicationManagerInterface::GetApplicationDesiredLanguage(
416 if (application_language == std::nullopt) { 416 if (application_language == std::nullopt) {
417 LOG_ERROR(Service_NS, "Could not convert application language! language_code={}", 417 LOG_ERROR(Service_NS, "Could not convert application language! language_code={}",
418 language_code); 418 language_code);
419 return ERR_APPLICATION_LANGUAGE_NOT_FOUND; 419 return Service::NS::ResultApplicationLanguageNotFound;
420 } 420 }
421 const auto priority_list = GetApplicationLanguagePriorityList(*application_language); 421 const auto priority_list = GetApplicationLanguagePriorityList(*application_language);
422 if (!priority_list) { 422 if (!priority_list) {
423 LOG_ERROR(Service_NS, 423 LOG_ERROR(Service_NS,
424 "Could not find application language priorities! application_language={}", 424 "Could not find application language priorities! application_language={}",
425 *application_language); 425 *application_language);
426 return ERR_APPLICATION_LANGUAGE_NOT_FOUND; 426 return Service::NS::ResultApplicationLanguageNotFound;
427 } 427 }
428 428
429 // Try to find a valid language. 429 // Try to find a valid language.
@@ -436,7 +436,7 @@ ResultVal<u8> IApplicationManagerInterface::GetApplicationDesiredLanguage(
436 436
437 LOG_ERROR(Service_NS, "Could not find a valid language! supported_languages={:08X}", 437 LOG_ERROR(Service_NS, "Could not find a valid language! supported_languages={:08X}",
438 supported_languages); 438 supported_languages);
439 return ERR_APPLICATION_LANGUAGE_NOT_FOUND; 439 return Service::NS::ResultApplicationLanguageNotFound;
440} 440}
441 441
442void IApplicationManagerInterface::ConvertApplicationLanguageToLanguageCode( 442void IApplicationManagerInterface::ConvertApplicationLanguageToLanguageCode(
@@ -461,7 +461,7 @@ ResultVal<u64> IApplicationManagerInterface::ConvertApplicationLanguageToLanguag
461 ConvertToLanguageCode(static_cast<ApplicationLanguage>(application_language)); 461 ConvertToLanguageCode(static_cast<ApplicationLanguage>(application_language));
462 if (language_code == std::nullopt) { 462 if (language_code == std::nullopt) {
463 LOG_ERROR(Service_NS, "Language not found! application_language={}", application_language); 463 LOG_ERROR(Service_NS, "Language not found! application_language={}", application_language);
464 return ERR_APPLICATION_LANGUAGE_NOT_FOUND; 464 return Service::NS::ResultApplicationLanguageNotFound;
465 } 465 }
466 466
467 return static_cast<u64>(*language_code); 467 return static_cast<u64>(*language_code);
diff --git a/src/core/hle/service/psc/psc.cpp b/src/core/hle/service/psc/psc.cpp
index 25702703e..cd0cc9287 100644
--- a/src/core/hle/service/psc/psc.cpp
+++ b/src/core/hle/service/psc/psc.cpp
@@ -11,9 +11,9 @@
11 11
12namespace Service::PSC { 12namespace Service::PSC {
13 13
14class PSC_C final : public ServiceFramework<PSC_C> { 14class IPmControl final : public ServiceFramework<IPmControl> {
15public: 15public:
16 explicit PSC_C(Core::System& system_) : ServiceFramework{system_, "psc:c"} { 16 explicit IPmControl(Core::System& system_) : ServiceFramework{system_, "psc:c"} {
17 // clang-format off 17 // clang-format off
18 static const FunctionInfo functions[] = { 18 static const FunctionInfo functions[] = {
19 {0, nullptr, "Initialize"}, 19 {0, nullptr, "Initialize"},
@@ -23,8 +23,8 @@ public:
23 {4, nullptr, "Cancel"}, 23 {4, nullptr, "Cancel"},
24 {5, nullptr, "PrintModuleInformation"}, 24 {5, nullptr, "PrintModuleInformation"},
25 {6, nullptr, "GetModuleInformation"}, 25 {6, nullptr, "GetModuleInformation"},
26 {10, nullptr, "Unknown10"}, 26 {10, nullptr, "AcquireStateLock"},
27 {11, nullptr, "Unknown11"}, 27 {11, nullptr, "HasStateLock"},
28 }; 28 };
29 // clang-format on 29 // clang-format on
30 30
@@ -49,12 +49,12 @@ public:
49 } 49 }
50}; 50};
51 51
52class PSC_M final : public ServiceFramework<PSC_M> { 52class IPmService final : public ServiceFramework<IPmService> {
53public: 53public:
54 explicit PSC_M(Core::System& system_) : ServiceFramework{system_, "psc:m"} { 54 explicit IPmService(Core::System& system_) : ServiceFramework{system_, "psc:m"} {
55 // clang-format off 55 // clang-format off
56 static const FunctionInfo functions[] = { 56 static const FunctionInfo functions[] = {
57 {0, &PSC_M::GetPmModule, "GetPmModule"}, 57 {0, &IPmService::GetPmModule, "GetPmModule"},
58 }; 58 };
59 // clang-format on 59 // clang-format on
60 60
@@ -74,8 +74,8 @@ private:
74void LoopProcess(Core::System& system) { 74void LoopProcess(Core::System& system) {
75 auto server_manager = std::make_unique<ServerManager>(system); 75 auto server_manager = std::make_unique<ServerManager>(system);
76 76
77 server_manager->RegisterNamedService("psc:c", std::make_shared<PSC_C>(system)); 77 server_manager->RegisterNamedService("psc:c", std::make_shared<IPmControl>(system));
78 server_manager->RegisterNamedService("psc:m", std::make_shared<PSC_M>(system)); 78 server_manager->RegisterNamedService("psc:m", std::make_shared<IPmService>(system));
79 ServerManager::RunServer(std::move(server_manager)); 79 ServerManager::RunServer(std::move(server_manager));
80} 80}
81 81
diff --git a/src/core/hle/service/server_manager.cpp b/src/core/hle/service/server_manager.cpp
index c91f6d880..bd04cd023 100644
--- a/src/core/hle/service/server_manager.cpp
+++ b/src/core/hle/service/server_manager.cpp
@@ -404,7 +404,7 @@ Result ServerManager::CompleteSyncRequest(RequestState&& request) {
404 rc = request.session->SendReplyHLE(); 404 rc = request.session->SendReplyHLE();
405 405
406 // If the session has been closed, we're done. 406 // If the session has been closed, we're done.
407 if (rc == Kernel::ResultSessionClosed || service_rc == IPC::ERR_REMOTE_PROCESS_DEAD) { 407 if (rc == Kernel::ResultSessionClosed || service_rc == IPC::ResultSessionClosed) {
408 // Close the session. 408 // Close the session.
409 request.session->Close(); 409 request.session->Close();
410 410
diff --git a/src/core/hle/service/service.cpp b/src/core/hle/service/service.cpp
index eed615377..69cdb5918 100644
--- a/src/core/hle/service/service.cpp
+++ b/src/core/hle/service/service.cpp
@@ -176,7 +176,7 @@ Result ServiceFrameworkBase::HandleSyncRequest(Kernel::KServerSession& session,
176 case IPC::CommandType::TIPC_Close: { 176 case IPC::CommandType::TIPC_Close: {
177 IPC::ResponseBuilder rb{ctx, 2}; 177 IPC::ResponseBuilder rb{ctx, 2};
178 rb.Push(ResultSuccess); 178 rb.Push(ResultSuccess);
179 result = IPC::ERR_REMOTE_PROCESS_DEAD; 179 result = IPC::ResultSessionClosed;
180 break; 180 break;
181 } 181 }
182 case IPC::CommandType::ControlWithContext: 182 case IPC::CommandType::ControlWithContext:
diff --git a/src/core/hle/service/set/set.cpp b/src/core/hle/service/set/set.cpp
index 88df52331..f5788b481 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 Result ERR_INVALID_LANGUAGE{ErrorModule::Settings, 625}; 77constexpr Result ResultInvalidLanguage{ErrorModule::Settings, 625};
78 78
79void PushResponseLanguageCode(HLERequestContext& ctx, std::size_t num_language_codes) { 79void PushResponseLanguageCode(HLERequestContext& ctx, std::size_t num_language_codes) {
80 IPC::ResponseBuilder rb{ctx, 3}; 80 IPC::ResponseBuilder rb{ctx, 3};
@@ -130,7 +130,7 @@ void SET::MakeLanguageCode(HLERequestContext& ctx) {
130 if (index >= available_language_codes.size()) { 130 if (index >= available_language_codes.size()) {
131 LOG_ERROR(Service_SET, "Invalid language code index! index={}", index); 131 LOG_ERROR(Service_SET, "Invalid language code index! index={}", index);
132 IPC::ResponseBuilder rb{ctx, 2}; 132 IPC::ResponseBuilder rb{ctx, 2};
133 rb.Push(ERR_INVALID_LANGUAGE); 133 rb.Push(Set::ResultInvalidLanguage);
134 return; 134 return;
135 } 135 }
136 136
diff --git a/src/core/hle/service/sm/sm.cpp b/src/core/hle/service/sm/sm.cpp
index a46f47d3e..b4046d3ce 100644
--- a/src/core/hle/service/sm/sm.cpp
+++ b/src/core/hle/service/sm/sm.cpp
@@ -18,10 +18,10 @@
18 18
19namespace Service::SM { 19namespace Service::SM {
20 20
21constexpr Result ERR_NOT_INITIALIZED(ErrorModule::SM, 2); 21constexpr Result ResultInvalidClient(ErrorModule::SM, 2);
22constexpr Result ERR_ALREADY_REGISTERED(ErrorModule::SM, 4); 22constexpr Result ResultAlreadyRegistered(ErrorModule::SM, 4);
23constexpr Result ERR_INVALID_NAME(ErrorModule::SM, 6); 23constexpr Result ResultInvalidServiceName(ErrorModule::SM, 6);
24constexpr Result ERR_SERVICE_NOT_REGISTERED(ErrorModule::SM, 7); 24constexpr Result ResultNotRegistered(ErrorModule::SM, 7);
25 25
26ServiceManager::ServiceManager(Kernel::KernelCore& kernel_) : kernel{kernel_} { 26ServiceManager::ServiceManager(Kernel::KernelCore& kernel_) : kernel{kernel_} {
27 controller_interface = std::make_unique<Controller>(kernel.System()); 27 controller_interface = std::make_unique<Controller>(kernel.System());
@@ -45,7 +45,7 @@ void ServiceManager::InvokeControlRequest(HLERequestContext& context) {
45static Result ValidateServiceName(const std::string& name) { 45static Result ValidateServiceName(const std::string& name) {
46 if (name.empty() || name.size() > 8) { 46 if (name.empty() || name.size() > 8) {
47 LOG_ERROR(Service_SM, "Invalid service name! service={}", name); 47 LOG_ERROR(Service_SM, "Invalid service name! service={}", name);
48 return ERR_INVALID_NAME; 48 return Service::SM::ResultInvalidServiceName;
49 } 49 }
50 return ResultSuccess; 50 return ResultSuccess;
51} 51}
@@ -58,7 +58,7 @@ Result ServiceManager::RegisterService(std::string name, u32 max_sessions,
58 std::scoped_lock lk{lock}; 58 std::scoped_lock lk{lock};
59 if (registered_services.find(name) != registered_services.end()) { 59 if (registered_services.find(name) != registered_services.end()) {
60 LOG_ERROR(Service_SM, "Service is already registered! service={}", name); 60 LOG_ERROR(Service_SM, "Service is already registered! service={}", name);
61 return ERR_ALREADY_REGISTERED; 61 return Service::SM::ResultAlreadyRegistered;
62 } 62 }
63 63
64 auto* port = Kernel::KPort::Create(kernel); 64 auto* port = Kernel::KPort::Create(kernel);
@@ -80,7 +80,7 @@ Result ServiceManager::UnregisterService(const std::string& name) {
80 const auto iter = registered_services.find(name); 80 const auto iter = registered_services.find(name);
81 if (iter == registered_services.end()) { 81 if (iter == registered_services.end()) {
82 LOG_ERROR(Service_SM, "Server is not registered! service={}", name); 82 LOG_ERROR(Service_SM, "Server is not registered! service={}", name);
83 return ERR_SERVICE_NOT_REGISTERED; 83 return Service::SM::ResultNotRegistered;
84 } 84 }
85 85
86 registered_services.erase(iter); 86 registered_services.erase(iter);
@@ -96,7 +96,7 @@ ResultVal<Kernel::KPort*> ServiceManager::GetServicePort(const std::string& name
96 auto it = service_ports.find(name); 96 auto it = service_ports.find(name);
97 if (it == service_ports.end()) { 97 if (it == service_ports.end()) {
98 LOG_WARNING(Service_SM, "Server is not registered! service={}", name); 98 LOG_WARNING(Service_SM, "Server is not registered! service={}", name);
99 return ERR_SERVICE_NOT_REGISTERED; 99 return Service::SM::ResultNotRegistered;
100 } 100 }
101 101
102 return it->second; 102 return it->second;
@@ -160,7 +160,7 @@ static std::string PopServiceName(IPC::RequestParser& rp) {
160 160
161ResultVal<Kernel::KClientSession*> SM::GetServiceImpl(HLERequestContext& ctx) { 161ResultVal<Kernel::KClientSession*> SM::GetServiceImpl(HLERequestContext& ctx) {
162 if (!ctx.GetManager()->GetIsInitializedForSm()) { 162 if (!ctx.GetManager()->GetIsInitializedForSm()) {
163 return ERR_NOT_INITIALIZED; 163 return Service::SM::ResultInvalidClient;
164 } 164 }
165 165
166 IPC::RequestParser rp{ctx}; 166 IPC::RequestParser rp{ctx};
@@ -168,15 +168,15 @@ ResultVal<Kernel::KClientSession*> SM::GetServiceImpl(HLERequestContext& ctx) {
168 168
169 // Find the named port. 169 // Find the named port.
170 auto port_result = service_manager.GetServicePort(name); 170 auto port_result = service_manager.GetServicePort(name);
171 if (port_result.Code() == ERR_INVALID_NAME) { 171 if (port_result.Code() == Service::SM::ResultInvalidServiceName) {
172 LOG_ERROR(Service_SM, "Invalid service name '{}'", name); 172 LOG_ERROR(Service_SM, "Invalid service name '{}'", name);
173 return ERR_INVALID_NAME; 173 return Service::SM::ResultInvalidServiceName;
174 } 174 }
175 175
176 if (port_result.Failed()) { 176 if (port_result.Failed()) {
177 LOG_INFO(Service_SM, "Waiting for service {} to become available", name); 177 LOG_INFO(Service_SM, "Waiting for service {} to become available", name);
178 ctx.SetIsDeferred(); 178 ctx.SetIsDeferred();
179 return ERR_SERVICE_NOT_REGISTERED; 179 return Service::SM::ResultNotRegistered;
180 } 180 }
181 auto& port = port_result.Unwrap(); 181 auto& port = port_result.Unwrap();
182 182
diff --git a/src/core/hle/service/ssl/ssl.cpp b/src/core/hle/service/ssl/ssl.cpp
index b19bc1b3e..2b99dd7ac 100644
--- a/src/core/hle/service/ssl/ssl.cpp
+++ b/src/core/hle/service/ssl/ssl.cpp
@@ -8,14 +8,36 @@
8 8
9namespace Service::SSL { 9namespace Service::SSL {
10 10
11// This is nn::ssl::sf::CertificateFormat
11enum class CertificateFormat : u32 { 12enum class CertificateFormat : u32 {
12 Pem = 1, 13 Pem = 1,
13 Der = 2, 14 Der = 2,
14}; 15};
15 16
17// This is nn::ssl::sf::ContextOption
18enum class ContextOption : u32 {
19 None = 0,
20 CrlImportDateCheckEnable = 1,
21};
22
23// This is nn::ssl::sf::SslVersion
24struct SslVersion {
25 union {
26 u32 raw{};
27
28 BitField<0, 1, u32> tls_auto;
29 BitField<3, 1, u32> tls_v10;
30 BitField<4, 1, u32> tls_v11;
31 BitField<5, 1, u32> tls_v12;
32 BitField<6, 1, u32> tls_v13;
33 BitField<24, 7, u32> api_version;
34 };
35};
36
16class ISslConnection final : public ServiceFramework<ISslConnection> { 37class ISslConnection final : public ServiceFramework<ISslConnection> {
17public: 38public:
18 explicit ISslConnection(Core::System& system_) : ServiceFramework{system_, "ISslConnection"} { 39 explicit ISslConnection(Core::System& system_, SslVersion version)
40 : ServiceFramework{system_, "ISslConnection"}, ssl_version{version} {
19 // clang-format off 41 // clang-format off
20 static const FunctionInfo functions[] = { 42 static const FunctionInfo functions[] = {
21 {0, nullptr, "SetSocketDescriptor"}, 43 {0, nullptr, "SetSocketDescriptor"},
@@ -59,11 +81,15 @@ public:
59 81
60 RegisterHandlers(functions); 82 RegisterHandlers(functions);
61 } 83 }
84
85private:
86 SslVersion ssl_version;
62}; 87};
63 88
64class ISslContext final : public ServiceFramework<ISslContext> { 89class ISslContext final : public ServiceFramework<ISslContext> {
65public: 90public:
66 explicit ISslContext(Core::System& system_) : ServiceFramework{system_, "ISslContext"} { 91 explicit ISslContext(Core::System& system_, SslVersion version)
92 : ServiceFramework{system_, "ISslContext"}, ssl_version{version} {
67 static const FunctionInfo functions[] = { 93 static const FunctionInfo functions[] = {
68 {0, &ISslContext::SetOption, "SetOption"}, 94 {0, &ISslContext::SetOption, "SetOption"},
69 {1, nullptr, "GetOption"}, 95 {1, nullptr, "GetOption"},
@@ -84,17 +110,20 @@ public:
84 } 110 }
85 111
86private: 112private:
113 SslVersion ssl_version;
114
87 void SetOption(HLERequestContext& ctx) { 115 void SetOption(HLERequestContext& ctx) {
88 struct Parameters { 116 struct Parameters {
89 u8 enable; 117 ContextOption option;
90 u32 option; 118 s32 value;
91 }; 119 };
120 static_assert(sizeof(Parameters) == 0x8, "Parameters is an invalid size");
92 121
93 IPC::RequestParser rp{ctx}; 122 IPC::RequestParser rp{ctx};
94 const auto parameters = rp.PopRaw<Parameters>(); 123 const auto parameters = rp.PopRaw<Parameters>();
95 124
96 LOG_WARNING(Service_SSL, "(STUBBED) called. enable={}, option={}", parameters.enable, 125 LOG_WARNING(Service_SSL, "(STUBBED) called. option={}, value={}", parameters.option,
97 parameters.option); 126 parameters.value);
98 127
99 IPC::ResponseBuilder rb{ctx, 2}; 128 IPC::ResponseBuilder rb{ctx, 2};
100 rb.Push(ResultSuccess); 129 rb.Push(ResultSuccess);
@@ -105,7 +134,7 @@ private:
105 134
106 IPC::ResponseBuilder rb{ctx, 2, 0, 1}; 135 IPC::ResponseBuilder rb{ctx, 2, 0, 1};
107 rb.Push(ResultSuccess); 136 rb.Push(ResultSuccess);
108 rb.PushIpcInterface<ISslConnection>(system); 137 rb.PushIpcInterface<ISslConnection>(system, ssl_version);
109 } 138 }
110 139
111 void ImportServerPki(HLERequestContext& ctx) { 140 void ImportServerPki(HLERequestContext& ctx) {
@@ -142,20 +171,21 @@ private:
142 } 171 }
143}; 172};
144 173
145class SSL final : public ServiceFramework<SSL> { 174class ISslService final : public ServiceFramework<ISslService> {
146public: 175public:
147 explicit SSL(Core::System& system_) : ServiceFramework{system_, "ssl"} { 176 explicit ISslService(Core::System& system_) : ServiceFramework{system_, "ssl"} {
148 // clang-format off 177 // clang-format off
149 static const FunctionInfo functions[] = { 178 static const FunctionInfo functions[] = {
150 {0, &SSL::CreateContext, "CreateContext"}, 179 {0, &ISslService::CreateContext, "CreateContext"},
151 {1, nullptr, "GetContextCount"}, 180 {1, nullptr, "GetContextCount"},
152 {2, nullptr, "GetCertificates"}, 181 {2, nullptr, "GetCertificates"},
153 {3, nullptr, "GetCertificateBufSize"}, 182 {3, nullptr, "GetCertificateBufSize"},
154 {4, nullptr, "DebugIoctl"}, 183 {4, nullptr, "DebugIoctl"},
155 {5, &SSL::SetInterfaceVersion, "SetInterfaceVersion"}, 184 {5, &ISslService::SetInterfaceVersion, "SetInterfaceVersion"},
156 {6, nullptr, "FlushSessionCache"}, 185 {6, nullptr, "FlushSessionCache"},
157 {7, nullptr, "SetDebugOption"}, 186 {7, nullptr, "SetDebugOption"},
158 {8, nullptr, "GetDebugOption"}, 187 {8, nullptr, "GetDebugOption"},
188 {8, nullptr, "ClearTls12FallbackFlag"},
159 }; 189 };
160 // clang-format on 190 // clang-format on
161 191
@@ -163,20 +193,30 @@ public:
163 } 193 }
164 194
165private: 195private:
166 u32 ssl_version{};
167 void CreateContext(HLERequestContext& ctx) { 196 void CreateContext(HLERequestContext& ctx) {
168 LOG_WARNING(Service_SSL, "(STUBBED) called"); 197 struct Parameters {
198 SslVersion ssl_version;
199 INSERT_PADDING_BYTES(0x4);
200 u64 pid_placeholder;
201 };
202 static_assert(sizeof(Parameters) == 0x10, "Parameters is an invalid size");
203
204 IPC::RequestParser rp{ctx};
205 const auto parameters = rp.PopRaw<Parameters>();
206
207 LOG_WARNING(Service_SSL, "(STUBBED) called, api_version={}, pid_placeholder={}",
208 parameters.ssl_version.api_version, parameters.pid_placeholder);
169 209
170 IPC::ResponseBuilder rb{ctx, 2, 0, 1}; 210 IPC::ResponseBuilder rb{ctx, 2, 0, 1};
171 rb.Push(ResultSuccess); 211 rb.Push(ResultSuccess);
172 rb.PushIpcInterface<ISslContext>(system); 212 rb.PushIpcInterface<ISslContext>(system, parameters.ssl_version);
173 } 213 }
174 214
175 void SetInterfaceVersion(HLERequestContext& ctx) { 215 void SetInterfaceVersion(HLERequestContext& ctx) {
176 LOG_DEBUG(Service_SSL, "called");
177
178 IPC::RequestParser rp{ctx}; 216 IPC::RequestParser rp{ctx};
179 ssl_version = rp.Pop<u32>(); 217 u32 ssl_version = rp.Pop<u32>();
218
219 LOG_DEBUG(Service_SSL, "called, ssl_version={}", ssl_version);
180 220
181 IPC::ResponseBuilder rb{ctx, 2}; 221 IPC::ResponseBuilder rb{ctx, 2};
182 rb.Push(ResultSuccess); 222 rb.Push(ResultSuccess);
@@ -186,7 +226,7 @@ private:
186void LoopProcess(Core::System& system) { 226void LoopProcess(Core::System& system) {
187 auto server_manager = std::make_unique<ServerManager>(system); 227 auto server_manager = std::make_unique<ServerManager>(system);
188 228
189 server_manager->RegisterNamedService("ssl", std::make_shared<SSL>(system)); 229 server_manager->RegisterNamedService("ssl", std::make_shared<ISslService>(system));
190 ServerManager::RunServer(std::move(server_manager)); 230 ServerManager::RunServer(std::move(server_manager));
191} 231}
192 232
diff --git a/src/core/hle/service/usb/usb.cpp b/src/core/hle/service/usb/usb.cpp
index a2855e783..f29fff1dd 100644
--- a/src/core/hle/service/usb/usb.cpp
+++ b/src/core/hle/service/usb/usb.cpp
@@ -16,19 +16,19 @@ public:
16 explicit IDsInterface(Core::System& system_) : ServiceFramework{system_, "IDsInterface"} { 16 explicit IDsInterface(Core::System& system_) : ServiceFramework{system_, "IDsInterface"} {
17 // clang-format off 17 // clang-format off
18 static const FunctionInfo functions[] = { 18 static const FunctionInfo functions[] = {
19 {0, nullptr, "BindDevice"}, 19 {0, nullptr, "AddEndpoint"},
20 {1, nullptr, "BindClientProcess"}, 20 {1, nullptr, "GetSetupEvent"},
21 {2, nullptr, "AddInterface"}, 21 {2, nullptr, "GetSetupPacket"},
22 {3, nullptr, "GetStateChangeEvent"}, 22 {3, nullptr, "Enable"},
23 {4, nullptr, "GetState"}, 23 {4, nullptr, "Disable"},
24 {5, nullptr, "ClearDeviceData"}, 24 {5, nullptr, "CtrlIn"},
25 {6, nullptr, "AddUsbStringDescriptor"}, 25 {6, nullptr, "CtrlOut"},
26 {7, nullptr, "DeleteUsbStringDescriptor"}, 26 {7, nullptr, "GetCtrlInCompletionEvent"},
27 {8, nullptr, "SetUsbDeviceDescriptor"}, 27 {8, nullptr, "GetCtrlInUrbReport"},
28 {9, nullptr, "SetBinaryObjectStore"}, 28 {9, nullptr, "GetCtrlOutCompletionEvent"},
29 {10, nullptr, "Enable"}, 29 {10, nullptr, "GetCtrlOutUrbReport"},
30 {11, nullptr, "Disable"}, 30 {11, nullptr, "CtrlStall"},
31 {12, nullptr, "Unknown12"}, 31 {12, nullptr, "AppendConfigurationData"},
32 }; 32 };
33 // clang-format on 33 // clang-format on
34 34
@@ -36,9 +36,9 @@ public:
36 } 36 }
37}; 37};
38 38
39class USB_DS final : public ServiceFramework<USB_DS> { 39class IDsRootSession final : public ServiceFramework<IDsRootSession> {
40public: 40public:
41 explicit USB_DS(Core::System& system_) : ServiceFramework{system_, "usb:ds"} { 41 explicit IDsRootSession(Core::System& system_) : ServiceFramework{system_, "usb:ds"} {
42 // clang-format off 42 // clang-format off
43 static const FunctionInfo functions[] = { 43 static const FunctionInfo functions[] = {
44 {0, nullptr, "OpenDsService"}, 44 {0, nullptr, "OpenDsService"},
@@ -94,9 +94,9 @@ public:
94 } 94 }
95}; 95};
96 96
97class USB_HS final : public ServiceFramework<USB_HS> { 97class IClientRootSession final : public ServiceFramework<IClientRootSession> {
98public: 98public:
99 explicit USB_HS(Core::System& system_) : ServiceFramework{system_, "usb:hs"} { 99 explicit IClientRootSession(Core::System& system_) : ServiceFramework{system_, "usb:hs"} {
100 // clang-format off 100 // clang-format off
101 static const FunctionInfo functions[] = { 101 static const FunctionInfo functions[] = {
102 {0, nullptr, "BindClientProcess"}, 102 {0, nullptr, "BindClientProcess"},
@@ -107,7 +107,7 @@ public:
107 {5, nullptr, "DestroyInterfaceAvailableEvent"}, 107 {5, nullptr, "DestroyInterfaceAvailableEvent"},
108 {6, nullptr, "GetInterfaceStateChangeEvent"}, 108 {6, nullptr, "GetInterfaceStateChangeEvent"},
109 {7, nullptr, "AcquireUsbIf"}, 109 {7, nullptr, "AcquireUsbIf"},
110 {8, nullptr, "ResetDevice"}, 110 {8, nullptr, "SetTestMode"},
111 }; 111 };
112 // clang-format on 112 // clang-format on
113 113
@@ -134,12 +134,12 @@ public:
134 } 134 }
135}; 135};
136 136
137class USB_PD final : public ServiceFramework<USB_PD> { 137class IPdManager final : public ServiceFramework<IPdManager> {
138public: 138public:
139 explicit USB_PD(Core::System& system_) : ServiceFramework{system_, "usb:pd"} { 139 explicit IPdManager(Core::System& system_) : ServiceFramework{system_, "usb:pd"} {
140 // clang-format off 140 // clang-format off
141 static const FunctionInfo functions[] = { 141 static const FunctionInfo functions[] = {
142 {0, &USB_PD::GetPdSession, "GetPdSession"}, 142 {0, &IPdManager::OpenSession, "OpenSession"},
143 }; 143 };
144 // clang-format on 144 // clang-format on
145 145
@@ -147,7 +147,7 @@ public:
147 } 147 }
148 148
149private: 149private:
150 void GetPdSession(HLERequestContext& ctx) { 150 void OpenSession(HLERequestContext& ctx) {
151 LOG_DEBUG(Service_USB, "called"); 151 LOG_DEBUG(Service_USB, "called");
152 152
153 IPC::ResponseBuilder rb{ctx, 2, 0, 1}; 153 IPC::ResponseBuilder rb{ctx, 2, 0, 1};
@@ -178,12 +178,12 @@ public:
178 } 178 }
179}; 179};
180 180
181class USB_PD_C final : public ServiceFramework<USB_PD_C> { 181class IPdCradleManager final : public ServiceFramework<IPdCradleManager> {
182public: 182public:
183 explicit USB_PD_C(Core::System& system_) : ServiceFramework{system_, "usb:pd:c"} { 183 explicit IPdCradleManager(Core::System& system_) : ServiceFramework{system_, "usb:pd:c"} {
184 // clang-format off 184 // clang-format off
185 static const FunctionInfo functions[] = { 185 static const FunctionInfo functions[] = {
186 {0, &USB_PD_C::GetPdCradleSession, "GetPdCradleSession"}, 186 {0, &IPdCradleManager::OpenCradleSession, "OpenCradleSession"},
187 }; 187 };
188 // clang-format on 188 // clang-format on
189 189
@@ -191,18 +191,18 @@ public:
191 } 191 }
192 192
193private: 193private:
194 void GetPdCradleSession(HLERequestContext& ctx) { 194 void OpenCradleSession(HLERequestContext& ctx) {
195 LOG_DEBUG(Service_USB, "called");
196
195 IPC::ResponseBuilder rb{ctx, 2, 0, 1}; 197 IPC::ResponseBuilder rb{ctx, 2, 0, 1};
196 rb.Push(ResultSuccess); 198 rb.Push(ResultSuccess);
197 rb.PushIpcInterface<IPdCradleSession>(system); 199 rb.PushIpcInterface<IPdCradleSession>(system);
198
199 LOG_DEBUG(Service_USB, "called");
200 } 200 }
201}; 201};
202 202
203class USB_PM final : public ServiceFramework<USB_PM> { 203class IPmMainService final : public ServiceFramework<IPmMainService> {
204public: 204public:
205 explicit USB_PM(Core::System& system_) : ServiceFramework{system_, "usb:pm"} { 205 explicit IPmMainService(Core::System& system_) : ServiceFramework{system_, "usb:pm"} {
206 // clang-format off 206 // clang-format off
207 static const FunctionInfo functions[] = { 207 static const FunctionInfo functions[] = {
208 {0, nullptr, "GetPowerEvent"}, 208 {0, nullptr, "GetPowerEvent"},
@@ -221,11 +221,11 @@ public:
221void LoopProcess(Core::System& system) { 221void LoopProcess(Core::System& system) {
222 auto server_manager = std::make_unique<ServerManager>(system); 222 auto server_manager = std::make_unique<ServerManager>(system);
223 223
224 server_manager->RegisterNamedService("usb:ds", std::make_shared<USB_DS>(system)); 224 server_manager->RegisterNamedService("usb:ds", std::make_shared<IDsRootSession>(system));
225 server_manager->RegisterNamedService("usb:hs", std::make_shared<USB_HS>(system)); 225 server_manager->RegisterNamedService("usb:hs", std::make_shared<IClientRootSession>(system));
226 server_manager->RegisterNamedService("usb:pd", std::make_shared<USB_PD>(system)); 226 server_manager->RegisterNamedService("usb:pd", std::make_shared<IPdManager>(system));
227 server_manager->RegisterNamedService("usb:pd:c", std::make_shared<USB_PD_C>(system)); 227 server_manager->RegisterNamedService("usb:pd:c", std::make_shared<IPdCradleManager>(system));
228 server_manager->RegisterNamedService("usb:pm", std::make_shared<USB_PM>(system)); 228 server_manager->RegisterNamedService("usb:pm", std::make_shared<IPmMainService>(system));
229 ServerManager::RunServer(std::move(server_manager)); 229 ServerManager::RunServer(std::move(server_manager));
230} 230}
231 231
diff --git a/src/input_common/drivers/joycon.cpp b/src/input_common/drivers/joycon.cpp
index b4cd39a20..8b57ebe07 100644
--- a/src/input_common/drivers/joycon.cpp
+++ b/src/input_common/drivers/joycon.cpp
@@ -307,8 +307,8 @@ Common::Input::DriverResult Joycons::SetPollingMode(const PadIdentifier& identif
307 switch (polling_mode) { 307 switch (polling_mode) {
308 case Common::Input::PollingMode::Active: 308 case Common::Input::PollingMode::Active:
309 return static_cast<Common::Input::DriverResult>(handle->SetActiveMode()); 309 return static_cast<Common::Input::DriverResult>(handle->SetActiveMode());
310 case Common::Input::PollingMode::Pasive: 310 case Common::Input::PollingMode::Passive:
311 return static_cast<Common::Input::DriverResult>(handle->SetPasiveMode()); 311 return static_cast<Common::Input::DriverResult>(handle->SetPassiveMode());
312 case Common::Input::PollingMode::IR: 312 case Common::Input::PollingMode::IR:
313 return static_cast<Common::Input::DriverResult>(handle->SetIrMode()); 313 return static_cast<Common::Input::DriverResult>(handle->SetIrMode());
314 case Common::Input::PollingMode::NFC: 314 case Common::Input::PollingMode::NFC:
diff --git a/src/input_common/drivers/virtual_amiibo.h b/src/input_common/drivers/virtual_amiibo.h
index 13cacfc0a..488d00b31 100644
--- a/src/input_common/drivers/virtual_amiibo.h
+++ b/src/input_common/drivers/virtual_amiibo.h
@@ -60,6 +60,6 @@ private:
60 std::string file_path{}; 60 std::string file_path{};
61 State state{State::Initialized}; 61 State state{State::Initialized};
62 std::vector<u8> nfc_data; 62 std::vector<u8> nfc_data;
63 Common::Input::PollingMode polling_mode{Common::Input::PollingMode::Pasive}; 63 Common::Input::PollingMode polling_mode{Common::Input::PollingMode::Passive};
64}; 64};
65} // namespace InputCommon 65} // namespace InputCommon
diff --git a/src/input_common/helpers/joycon_driver.cpp b/src/input_common/helpers/joycon_driver.cpp
index e65b6b845..78cc5893c 100644
--- a/src/input_common/helpers/joycon_driver.cpp
+++ b/src/input_common/helpers/joycon_driver.cpp
@@ -410,7 +410,7 @@ DriverResult JoyconDriver::SetIrsConfig(IrsMode mode_, IrsResolution format_) {
410 return result; 410 return result;
411} 411}
412 412
413DriverResult JoyconDriver::SetPasiveMode() { 413DriverResult JoyconDriver::SetPassiveMode() {
414 std::scoped_lock lock{mutex}; 414 std::scoped_lock lock{mutex};
415 motion_enabled = false; 415 motion_enabled = false;
416 hidbus_enabled = false; 416 hidbus_enabled = false;
diff --git a/src/input_common/helpers/joycon_driver.h b/src/input_common/helpers/joycon_driver.h
index c1e189fa5..b52a13ecf 100644
--- a/src/input_common/helpers/joycon_driver.h
+++ b/src/input_common/helpers/joycon_driver.h
@@ -44,7 +44,7 @@ public:
44 DriverResult SetVibration(const VibrationValue& vibration); 44 DriverResult SetVibration(const VibrationValue& vibration);
45 DriverResult SetLedConfig(u8 led_pattern); 45 DriverResult SetLedConfig(u8 led_pattern);
46 DriverResult SetIrsConfig(IrsMode mode_, IrsResolution format_); 46 DriverResult SetIrsConfig(IrsMode mode_, IrsResolution format_);
47 DriverResult SetPasiveMode(); 47 DriverResult SetPassiveMode();
48 DriverResult SetActiveMode(); 48 DriverResult SetActiveMode();
49 DriverResult SetIrMode(); 49 DriverResult SetIrMode();
50 DriverResult SetNfcMode(); 50 DriverResult SetNfcMode();
diff --git a/src/input_common/helpers/joycon_protocol/joycon_types.h b/src/input_common/helpers/joycon_protocol/joycon_types.h
index b91934990..dcac0e422 100644
--- a/src/input_common/helpers/joycon_protocol/joycon_types.h
+++ b/src/input_common/helpers/joycon_protocol/joycon_types.h
@@ -78,7 +78,7 @@ enum class PadButton : u32 {
78 Capture = 0x200000, 78 Capture = 0x200000,
79}; 79};
80 80
81enum class PasivePadButton : u32 { 81enum class PassivePadButton : u32 {
82 Down_A = 0x0001, 82 Down_A = 0x0001,
83 Right_X = 0x0002, 83 Right_X = 0x0002,
84 Left_B = 0x0004, 84 Left_B = 0x0004,
@@ -95,6 +95,18 @@ enum class PasivePadButton : u32 {
95 ZL_ZR = 0x8000, 95 ZL_ZR = 0x8000,
96}; 96};
97 97
98enum class PassivePadStick : u8 {
99 Right = 0x00,
100 RightDown = 0x01,
101 Down = 0x02,
102 DownLeft = 0x03,
103 Left = 0x04,
104 LeftUp = 0x05,
105 Up = 0x06,
106 UpRight = 0x07,
107 Neutral = 0x08,
108};
109
98enum class OutputReport : u8 { 110enum class OutputReport : u8 {
99 RUMBLE_AND_SUBCMD = 0x01, 111 RUMBLE_AND_SUBCMD = 0x01,
100 FW_UPDATE_PKT = 0x03, 112 FW_UPDATE_PKT = 0x03,
diff --git a/src/input_common/helpers/joycon_protocol/poller.cpp b/src/input_common/helpers/joycon_protocol/poller.cpp
index 9bb15e935..dca797f7a 100644
--- a/src/input_common/helpers/joycon_protocol/poller.cpp
+++ b/src/input_common/helpers/joycon_protocol/poller.cpp
@@ -12,7 +12,7 @@ JoyconPoller::JoyconPoller(ControllerType device_type_, JoyStickCalibration left
12 : device_type{device_type_}, left_stick_calibration{left_stick_calibration_}, 12 : device_type{device_type_}, left_stick_calibration{left_stick_calibration_},
13 right_stick_calibration{right_stick_calibration_}, motion_calibration{motion_calibration_} {} 13 right_stick_calibration{right_stick_calibration_}, motion_calibration{motion_calibration_} {}
14 14
15void JoyconPoller::SetCallbacks(const Joycon::JoyconCallbacks& callbacks_) { 15void JoyconPoller::SetCallbacks(const JoyconCallbacks& callbacks_) {
16 callbacks = std::move(callbacks_); 16 callbacks = std::move(callbacks_);
17} 17}
18 18
@@ -22,13 +22,13 @@ void JoyconPoller::ReadActiveMode(std::span<u8> buffer, const MotionStatus& moti
22 memcpy(&data, buffer.data(), sizeof(InputReportActive)); 22 memcpy(&data, buffer.data(), sizeof(InputReportActive));
23 23
24 switch (device_type) { 24 switch (device_type) {
25 case Joycon::ControllerType::Left: 25 case ControllerType::Left:
26 UpdateActiveLeftPadInput(data, motion_status); 26 UpdateActiveLeftPadInput(data, motion_status);
27 break; 27 break;
28 case Joycon::ControllerType::Right: 28 case ControllerType::Right:
29 UpdateActiveRightPadInput(data, motion_status); 29 UpdateActiveRightPadInput(data, motion_status);
30 break; 30 break;
31 case Joycon::ControllerType::Pro: 31 case ControllerType::Pro:
32 UpdateActiveProPadInput(data, motion_status); 32 UpdateActiveProPadInput(data, motion_status);
33 break; 33 break;
34 default: 34 default:
@@ -47,14 +47,14 @@ void JoyconPoller::ReadPassiveMode(std::span<u8> buffer) {
47 memcpy(&data, buffer.data(), sizeof(InputReportPassive)); 47 memcpy(&data, buffer.data(), sizeof(InputReportPassive));
48 48
49 switch (device_type) { 49 switch (device_type) {
50 case Joycon::ControllerType::Left: 50 case ControllerType::Left:
51 UpdatePasiveLeftPadInput(data); 51 UpdatePassiveLeftPadInput(data);
52 break; 52 break;
53 case Joycon::ControllerType::Right: 53 case ControllerType::Right:
54 UpdatePasiveRightPadInput(data); 54 UpdatePassiveRightPadInput(data);
55 break; 55 break;
56 case Joycon::ControllerType::Pro: 56 case ControllerType::Pro:
57 UpdatePasiveProPadInput(data); 57 UpdatePassiveProPadInput(data);
58 break; 58 break;
59 default: 59 default:
60 break; 60 break;
@@ -210,14 +210,12 @@ void JoyconPoller::UpdateActiveProPadInput(const InputReportActive& input,
210 } 210 }
211} 211}
212 212
213void JoyconPoller::UpdatePasiveLeftPadInput(const InputReportPassive& input) { 213void JoyconPoller::UpdatePassiveLeftPadInput(const InputReportPassive& input) {
214 static constexpr std::array<Joycon::PasivePadButton, 11> left_buttons{ 214 static constexpr std::array<PassivePadButton, 11> left_buttons{
215 Joycon::PasivePadButton::Down_A, Joycon::PasivePadButton::Right_X, 215 PassivePadButton::Down_A, PassivePadButton::Right_X, PassivePadButton::Left_B,
216 Joycon::PasivePadButton::Left_B, Joycon::PasivePadButton::Up_Y, 216 PassivePadButton::Up_Y, PassivePadButton::SL, PassivePadButton::SR,
217 Joycon::PasivePadButton::SL, Joycon::PasivePadButton::SR, 217 PassivePadButton::L_R, PassivePadButton::ZL_ZR, PassivePadButton::Minus,
218 Joycon::PasivePadButton::L_R, Joycon::PasivePadButton::ZL_ZR, 218 PassivePadButton::Capture, PassivePadButton::StickL,
219 Joycon::PasivePadButton::Minus, Joycon::PasivePadButton::Capture,
220 Joycon::PasivePadButton::StickL,
221 }; 219 };
222 220
223 for (auto left_button : left_buttons) { 221 for (auto left_button : left_buttons) {
@@ -225,16 +223,19 @@ void JoyconPoller::UpdatePasiveLeftPadInput(const InputReportPassive& input) {
225 const int button = static_cast<int>(left_button); 223 const int button = static_cast<int>(left_button);
226 callbacks.on_button_data(button, button_status); 224 callbacks.on_button_data(button, button_status);
227 } 225 }
226
227 const auto [left_axis_x, left_axis_y] =
228 GetPassiveAxisValue(static_cast<PassivePadStick>(input.stick_state));
229 callbacks.on_stick_data(static_cast<int>(PadAxes::LeftStickX), left_axis_x);
230 callbacks.on_stick_data(static_cast<int>(PadAxes::LeftStickY), left_axis_y);
228} 231}
229 232
230void JoyconPoller::UpdatePasiveRightPadInput(const InputReportPassive& input) { 233void JoyconPoller::UpdatePassiveRightPadInput(const InputReportPassive& input) {
231 static constexpr std::array<Joycon::PasivePadButton, 11> right_buttons{ 234 static constexpr std::array<PassivePadButton, 11> right_buttons{
232 Joycon::PasivePadButton::Down_A, Joycon::PasivePadButton::Right_X, 235 PassivePadButton::Down_A, PassivePadButton::Right_X, PassivePadButton::Left_B,
233 Joycon::PasivePadButton::Left_B, Joycon::PasivePadButton::Up_Y, 236 PassivePadButton::Up_Y, PassivePadButton::SL, PassivePadButton::SR,
234 Joycon::PasivePadButton::SL, Joycon::PasivePadButton::SR, 237 PassivePadButton::L_R, PassivePadButton::ZL_ZR, PassivePadButton::Plus,
235 Joycon::PasivePadButton::L_R, Joycon::PasivePadButton::ZL_ZR, 238 PassivePadButton::Home, PassivePadButton::StickR,
236 Joycon::PasivePadButton::Plus, Joycon::PasivePadButton::Home,
237 Joycon::PasivePadButton::StickR,
238 }; 239 };
239 240
240 for (auto right_button : right_buttons) { 241 for (auto right_button : right_buttons) {
@@ -242,17 +243,20 @@ void JoyconPoller::UpdatePasiveRightPadInput(const InputReportPassive& input) {
242 const int button = static_cast<int>(right_button); 243 const int button = static_cast<int>(right_button);
243 callbacks.on_button_data(button, button_status); 244 callbacks.on_button_data(button, button_status);
244 } 245 }
246
247 const auto [right_axis_x, right_axis_y] =
248 GetPassiveAxisValue(static_cast<PassivePadStick>(input.stick_state));
249 callbacks.on_stick_data(static_cast<int>(PadAxes::RightStickX), right_axis_x);
250 callbacks.on_stick_data(static_cast<int>(PadAxes::RightStickY), right_axis_y);
245} 251}
246 252
247void JoyconPoller::UpdatePasiveProPadInput(const InputReportPassive& input) { 253void JoyconPoller::UpdatePassiveProPadInput(const InputReportPassive& input) {
248 static constexpr std::array<Joycon::PasivePadButton, 14> pro_buttons{ 254 static constexpr std::array<PassivePadButton, 14> pro_buttons{
249 Joycon::PasivePadButton::Down_A, Joycon::PasivePadButton::Right_X, 255 PassivePadButton::Down_A, PassivePadButton::Right_X, PassivePadButton::Left_B,
250 Joycon::PasivePadButton::Left_B, Joycon::PasivePadButton::Up_Y, 256 PassivePadButton::Up_Y, PassivePadButton::SL, PassivePadButton::SR,
251 Joycon::PasivePadButton::SL, Joycon::PasivePadButton::SR, 257 PassivePadButton::L_R, PassivePadButton::ZL_ZR, PassivePadButton::Minus,
252 Joycon::PasivePadButton::L_R, Joycon::PasivePadButton::ZL_ZR, 258 PassivePadButton::Plus, PassivePadButton::Capture, PassivePadButton::Home,
253 Joycon::PasivePadButton::Minus, Joycon::PasivePadButton::Plus, 259 PassivePadButton::StickL, PassivePadButton::StickR,
254 Joycon::PasivePadButton::Capture, Joycon::PasivePadButton::Home,
255 Joycon::PasivePadButton::StickL, Joycon::PasivePadButton::StickR,
256 }; 260 };
257 261
258 for (auto pro_button : pro_buttons) { 262 for (auto pro_button : pro_buttons) {
@@ -260,6 +264,15 @@ void JoyconPoller::UpdatePasiveProPadInput(const InputReportPassive& input) {
260 const int button = static_cast<int>(pro_button); 264 const int button = static_cast<int>(pro_button);
261 callbacks.on_button_data(button, button_status); 265 callbacks.on_button_data(button, button_status);
262 } 266 }
267
268 const auto [left_axis_x, left_axis_y] =
269 GetPassiveAxisValue(static_cast<PassivePadStick>(input.stick_state & 0xf));
270 const auto [right_axis_x, right_axis_y] =
271 GetPassiveAxisValue(static_cast<PassivePadStick>(input.stick_state >> 4));
272 callbacks.on_stick_data(static_cast<int>(PadAxes::LeftStickX), left_axis_x);
273 callbacks.on_stick_data(static_cast<int>(PadAxes::LeftStickY), left_axis_y);
274 callbacks.on_stick_data(static_cast<int>(PadAxes::RightStickX), right_axis_x);
275 callbacks.on_stick_data(static_cast<int>(PadAxes::RightStickY), right_axis_y);
263} 276}
264 277
265f32 JoyconPoller::GetAxisValue(u16 raw_value, Joycon::JoyStickAxisCalibration calibration) const { 278f32 JoyconPoller::GetAxisValue(u16 raw_value, Joycon::JoyStickAxisCalibration calibration) const {
@@ -270,6 +283,30 @@ f32 JoyconPoller::GetAxisValue(u16 raw_value, Joycon::JoyStickAxisCalibration ca
270 return value / calibration.min; 283 return value / calibration.min;
271} 284}
272 285
286std::pair<f32, f32> JoyconPoller::GetPassiveAxisValue(PassivePadStick raw_value) const {
287 switch (raw_value) {
288 case PassivePadStick::Right:
289 return {1.0f, 0.0f};
290 case PassivePadStick::RightDown:
291 return {1.0f, -1.0f};
292 case PassivePadStick::Down:
293 return {0.0f, -1.0f};
294 case PassivePadStick::DownLeft:
295 return {-1.0f, -1.0f};
296 case PassivePadStick::Left:
297 return {-1.0f, 0.0f};
298 case PassivePadStick::LeftUp:
299 return {-1.0f, 1.0f};
300 case PassivePadStick::Up:
301 return {0.0f, 1.0f};
302 case PassivePadStick::UpRight:
303 return {1.0f, 1.0f};
304 case PassivePadStick::Neutral:
305 default:
306 return {0.0f, 0.0f};
307 }
308}
309
273f32 JoyconPoller::GetAccelerometerValue(s16 raw, const MotionSensorCalibration& cal, 310f32 JoyconPoller::GetAccelerometerValue(s16 raw, const MotionSensorCalibration& cal,
274 AccelerometerSensitivity sensitivity) const { 311 AccelerometerSensitivity sensitivity) const {
275 const f32 value = raw * (1.0f / (cal.scale - cal.offset)) * 4; 312 const f32 value = raw * (1.0f / (cal.scale - cal.offset)) * 4;
diff --git a/src/input_common/helpers/joycon_protocol/poller.h b/src/input_common/helpers/joycon_protocol/poller.h
index 354d41dad..0fa72c6db 100644
--- a/src/input_common/helpers/joycon_protocol/poller.h
+++ b/src/input_common/helpers/joycon_protocol/poller.h
@@ -22,7 +22,7 @@ public:
22 JoyStickCalibration right_stick_calibration_, 22 JoyStickCalibration right_stick_calibration_,
23 MotionCalibration motion_calibration_); 23 MotionCalibration motion_calibration_);
24 24
25 void SetCallbacks(const Joycon::JoyconCallbacks& callbacks_); 25 void SetCallbacks(const JoyconCallbacks& callbacks_);
26 26
27 /// Handles data from passive packages 27 /// Handles data from passive packages
28 void ReadPassiveMode(std::span<u8> buffer); 28 void ReadPassiveMode(std::span<u8> buffer);
@@ -46,12 +46,15 @@ private:
46 const MotionStatus& motion_status); 46 const MotionStatus& motion_status);
47 void UpdateActiveProPadInput(const InputReportActive& input, const MotionStatus& motion_status); 47 void UpdateActiveProPadInput(const InputReportActive& input, const MotionStatus& motion_status);
48 48
49 void UpdatePasiveLeftPadInput(const InputReportPassive& buffer); 49 void UpdatePassiveLeftPadInput(const InputReportPassive& buffer);
50 void UpdatePasiveRightPadInput(const InputReportPassive& buffer); 50 void UpdatePassiveRightPadInput(const InputReportPassive& buffer);
51 void UpdatePasiveProPadInput(const InputReportPassive& buffer); 51 void UpdatePassiveProPadInput(const InputReportPassive& buffer);
52 52
53 /// Returns a calibrated joystick axis from raw axis data 53 /// Returns a calibrated joystick axis from raw axis data
54 f32 GetAxisValue(u16 raw_value, Joycon::JoyStickAxisCalibration calibration) const; 54 f32 GetAxisValue(u16 raw_value, JoyStickAxisCalibration calibration) const;
55
56 /// Returns a digital joystick axis from passive axis data
57 std::pair<f32, f32> GetPassiveAxisValue(PassivePadStick raw_value) const;
55 58
56 /// Returns a calibrated accelerometer axis from raw motion data 59 /// Returns a calibrated accelerometer axis from raw motion data
57 f32 GetAccelerometerValue(s16 raw, const MotionSensorCalibration& cal, 60 f32 GetAccelerometerValue(s16 raw, const MotionSensorCalibration& cal,
@@ -75,7 +78,7 @@ private:
75 JoyStickCalibration right_stick_calibration{}; 78 JoyStickCalibration right_stick_calibration{};
76 MotionCalibration motion_calibration{}; 79 MotionCalibration motion_calibration{};
77 80
78 Joycon::JoyconCallbacks callbacks{}; 81 JoyconCallbacks callbacks{};
79}; 82};
80 83
81} // namespace InputCommon::Joycon 84} // namespace InputCommon::Joycon
diff --git a/src/video_core/gpu.cpp b/src/video_core/gpu.cpp
index 7024a19cf..2e7f9c5ed 100644
--- a/src/video_core/gpu.cpp
+++ b/src/video_core/gpu.cpp
@@ -197,7 +197,7 @@ struct GPU::Impl {
197 constexpr u64 gpu_ticks_num = 384; 197 constexpr u64 gpu_ticks_num = 384;
198 constexpr u64 gpu_ticks_den = 625; 198 constexpr u64 gpu_ticks_den = 625;
199 199
200 u64 nanoseconds = system.CoreTiming().GetGlobalTimeNs().count(); 200 u64 nanoseconds = system.CoreTiming().GetCPUTimeNs().count();
201 if (Settings::values.use_fast_gpu_time.GetValue()) { 201 if (Settings::values.use_fast_gpu_time.GetValue()) {
202 nanoseconds /= 256; 202 nanoseconds /= 256;
203 } 203 }
diff --git a/src/video_core/renderer_opengl/gl_texture_cache.cpp b/src/video_core/renderer_opengl/gl_texture_cache.cpp
index b047e7b3d..d3eabd686 100644
--- a/src/video_core/renderer_opengl/gl_texture_cache.cpp
+++ b/src/video_core/renderer_opengl/gl_texture_cache.cpp
@@ -112,13 +112,17 @@ GLenum ImageTarget(Shader::TextureType type, int num_samples = 1) {
112 return GL_NONE; 112 return GL_NONE;
113} 113}
114 114
115GLenum TextureMode(PixelFormat format, bool is_first) { 115GLenum TextureMode(PixelFormat format, std::array<SwizzleSource, 4> swizzle) {
116 bool any_r =
117 std::ranges::any_of(swizzle, [](SwizzleSource s) { return s == SwizzleSource::R; });
116 switch (format) { 118 switch (format) {
117 case PixelFormat::D24_UNORM_S8_UINT: 119 case PixelFormat::D24_UNORM_S8_UINT:
118 case PixelFormat::D32_FLOAT_S8_UINT: 120 case PixelFormat::D32_FLOAT_S8_UINT:
119 return is_first ? GL_DEPTH_COMPONENT : GL_STENCIL_INDEX; 121 // R = depth, G = stencil
122 return any_r ? GL_DEPTH_COMPONENT : GL_STENCIL_INDEX;
120 case PixelFormat::S8_UINT_D24_UNORM: 123 case PixelFormat::S8_UINT_D24_UNORM:
121 return is_first ? GL_STENCIL_INDEX : GL_DEPTH_COMPONENT; 124 // R = stencil, G = depth
125 return any_r ? GL_STENCIL_INDEX : GL_DEPTH_COMPONENT;
122 default: 126 default:
123 ASSERT(false); 127 ASSERT(false);
124 return GL_DEPTH_COMPONENT; 128 return GL_DEPTH_COMPONENT;
@@ -208,8 +212,7 @@ void ApplySwizzle(GLuint handle, PixelFormat format, std::array<SwizzleSource, 4
208 case PixelFormat::D32_FLOAT_S8_UINT: 212 case PixelFormat::D32_FLOAT_S8_UINT:
209 case PixelFormat::S8_UINT_D24_UNORM: 213 case PixelFormat::S8_UINT_D24_UNORM:
210 UNIMPLEMENTED_IF(swizzle[0] != SwizzleSource::R && swizzle[0] != SwizzleSource::G); 214 UNIMPLEMENTED_IF(swizzle[0] != SwizzleSource::R && swizzle[0] != SwizzleSource::G);
211 glTextureParameteri(handle, GL_DEPTH_STENCIL_TEXTURE_MODE, 215 glTextureParameteri(handle, GL_DEPTH_STENCIL_TEXTURE_MODE, TextureMode(format, swizzle));
212 TextureMode(format, swizzle[0] == SwizzleSource::R));
213 std::ranges::transform(swizzle, swizzle.begin(), ConvertGreenRed); 216 std::ranges::transform(swizzle, swizzle.begin(), ConvertGreenRed);
214 break; 217 break;
215 case PixelFormat::A5B5G5R1_UNORM: { 218 case PixelFormat::A5B5G5R1_UNORM: {
diff --git a/src/video_core/renderer_vulkan/vk_buffer_cache.cpp b/src/video_core/renderer_vulkan/vk_buffer_cache.cpp
index b0153a502..9cbcb3c8f 100644
--- a/src/video_core/renderer_vulkan/vk_buffer_cache.cpp
+++ b/src/video_core/renderer_vulkan/vk_buffer_cache.cpp
@@ -238,7 +238,7 @@ private:
238 return indices; 238 return indices;
239 } 239 }
240 240
241 void MakeAndUpdateIndices(u8* staging_data, size_t quad_size, u32 quad, u32 first) { 241 void MakeAndUpdateIndices(u8* staging_data, size_t quad_size, u32 quad, u32 first) override {
242 switch (index_type) { 242 switch (index_type) {
243 case VK_INDEX_TYPE_UINT8_EXT: 243 case VK_INDEX_TYPE_UINT8_EXT:
244 std::memcpy(staging_data, MakeIndices<u8>(quad, first).data(), quad_size); 244 std::memcpy(staging_data, MakeIndices<u8>(quad, first).data(), quad_size);
@@ -278,7 +278,7 @@ private:
278 return indices; 278 return indices;
279 } 279 }
280 280
281 void MakeAndUpdateIndices(u8* staging_data, size_t quad_size, u32 quad, u32 first) { 281 void MakeAndUpdateIndices(u8* staging_data, size_t quad_size, u32 quad, u32 first) override {
282 switch (index_type) { 282 switch (index_type) {
283 case VK_INDEX_TYPE_UINT8_EXT: 283 case VK_INDEX_TYPE_UINT8_EXT:
284 std::memcpy(staging_data, MakeIndices<u8>(quad, first).data(), quad_size); 284 std::memcpy(staging_data, MakeIndices<u8>(quad, first).data(), quad_size);
diff --git a/src/video_core/renderer_vulkan/vk_rasterizer.cpp b/src/video_core/renderer_vulkan/vk_rasterizer.cpp
index f085d53a1..25965b684 100644
--- a/src/video_core/renderer_vulkan/vk_rasterizer.cpp
+++ b/src/video_core/renderer_vulkan/vk_rasterizer.cpp
@@ -1294,7 +1294,7 @@ void RasterizerVulkan::UpdateDepthBoundsTestEnable(Tegra::Engines::Maxwell3D::Re
1294 LOG_WARNING(Render_Vulkan, "Depth bounds is enabled but not supported"); 1294 LOG_WARNING(Render_Vulkan, "Depth bounds is enabled but not supported");
1295 enabled = false; 1295 enabled = false;
1296 } 1296 }
1297 scheduler.Record([enable = regs.depth_bounds_enable](vk::CommandBuffer cmdbuf) { 1297 scheduler.Record([enable = enabled](vk::CommandBuffer cmdbuf) {
1298 cmdbuf.SetDepthBoundsTestEnableEXT(enable); 1298 cmdbuf.SetDepthBoundsTestEnableEXT(enable);
1299 }); 1299 });
1300} 1300}
diff --git a/src/video_core/renderer_vulkan/vk_texture_cache.cpp b/src/video_core/renderer_vulkan/vk_texture_cache.cpp
index 8a204f93f..e013d1c60 100644
--- a/src/video_core/renderer_vulkan/vk_texture_cache.cpp
+++ b/src/video_core/renderer_vulkan/vk_texture_cache.cpp
@@ -189,13 +189,16 @@ constexpr VkBorderColor ConvertBorderColor(const std::array<float, 4>& color) {
189 if (info.IsRenderTarget()) { 189 if (info.IsRenderTarget()) {
190 return ImageAspectMask(info.format); 190 return ImageAspectMask(info.format);
191 } 191 }
192 const bool is_first = info.Swizzle()[0] == SwizzleSource::R; 192 bool any_r =
193 std::ranges::any_of(info.Swizzle(), [](SwizzleSource s) { return s == SwizzleSource::R; });
193 switch (info.format) { 194 switch (info.format) {
194 case PixelFormat::D24_UNORM_S8_UINT: 195 case PixelFormat::D24_UNORM_S8_UINT:
195 case PixelFormat::D32_FLOAT_S8_UINT: 196 case PixelFormat::D32_FLOAT_S8_UINT:
196 return is_first ? VK_IMAGE_ASPECT_DEPTH_BIT : VK_IMAGE_ASPECT_STENCIL_BIT; 197 // R = depth, G = stencil
198 return any_r ? VK_IMAGE_ASPECT_DEPTH_BIT : VK_IMAGE_ASPECT_STENCIL_BIT;
197 case PixelFormat::S8_UINT_D24_UNORM: 199 case PixelFormat::S8_UINT_D24_UNORM:
198 return is_first ? VK_IMAGE_ASPECT_STENCIL_BIT : VK_IMAGE_ASPECT_DEPTH_BIT; 200 // R = stencil, G = depth
201 return any_r ? VK_IMAGE_ASPECT_STENCIL_BIT : VK_IMAGE_ASPECT_DEPTH_BIT;
199 case PixelFormat::D16_UNORM: 202 case PixelFormat::D16_UNORM:
200 case PixelFormat::D32_FLOAT: 203 case PixelFormat::D32_FLOAT:
201 return VK_IMAGE_ASPECT_DEPTH_BIT; 204 return VK_IMAGE_ASPECT_DEPTH_BIT;
@@ -1769,7 +1772,7 @@ Sampler::Sampler(TextureCacheRuntime& runtime, const Tegra::Texture::TSCEntry& t
1769 .minLod = tsc.mipmap_filter == TextureMipmapFilter::None ? 0.0f : tsc.MinLod(), 1772 .minLod = tsc.mipmap_filter == TextureMipmapFilter::None ? 0.0f : tsc.MinLod(),
1770 .maxLod = tsc.mipmap_filter == TextureMipmapFilter::None ? 0.25f : tsc.MaxLod(), 1773 .maxLod = tsc.mipmap_filter == TextureMipmapFilter::None ? 0.25f : tsc.MaxLod(),
1771 .borderColor = 1774 .borderColor =
1772 arbitrary_borders ? VK_BORDER_COLOR_INT_CUSTOM_EXT : ConvertBorderColor(color), 1775 arbitrary_borders ? VK_BORDER_COLOR_FLOAT_CUSTOM_EXT : ConvertBorderColor(color),
1773 .unnormalizedCoordinates = VK_FALSE, 1776 .unnormalizedCoordinates = VK_FALSE,
1774 }); 1777 });
1775} 1778}
diff --git a/src/yuzu/main.cpp b/src/yuzu/main.cpp
index f233b065e..c092507f4 100644
--- a/src/yuzu/main.cpp
+++ b/src/yuzu/main.cpp
@@ -91,6 +91,9 @@ static FileSys::VirtualFile VfsDirectoryCreateFileWrapper(const FileSys::Virtual
91#include "common/microprofile.h" 91#include "common/microprofile.h"
92#include "common/scm_rev.h" 92#include "common/scm_rev.h"
93#include "common/scope_exit.h" 93#include "common/scope_exit.h"
94#ifdef _WIN32
95#include "common/windows/timer_resolution.h"
96#endif
94#ifdef ARCHITECTURE_x86_64 97#ifdef ARCHITECTURE_x86_64
95#include "common/x64/cpu_detect.h" 98#include "common/x64/cpu_detect.h"
96#endif 99#endif
@@ -377,6 +380,12 @@ GMainWindow::GMainWindow(std::unique_ptr<Config> config_, bool has_broken_vulkan
377 LOG_INFO(Frontend, "Host RAM: {:.2f} GiB", 380 LOG_INFO(Frontend, "Host RAM: {:.2f} GiB",
378 Common::GetMemInfo().TotalPhysicalMemory / f64{1_GiB}); 381 Common::GetMemInfo().TotalPhysicalMemory / f64{1_GiB});
379 LOG_INFO(Frontend, "Host Swap: {:.2f} GiB", Common::GetMemInfo().TotalSwapMemory / f64{1_GiB}); 382 LOG_INFO(Frontend, "Host Swap: {:.2f} GiB", Common::GetMemInfo().TotalSwapMemory / f64{1_GiB});
383#ifdef _WIN32
384 LOG_INFO(Frontend, "Host Timer Resolution: {:.4f} ms",
385 std::chrono::duration_cast<std::chrono::duration<f64, std::milli>>(
386 Common::Windows::SetCurrentTimerResolutionToMaximum())
387 .count());
388#endif
380 UpdateWindowTitle(); 389 UpdateWindowTitle();
381 390
382 show(); 391 show();
diff --git a/src/yuzu_cmd/yuzu.cpp b/src/yuzu_cmd/yuzu.cpp
index 77edd58ca..5f39ece32 100644
--- a/src/yuzu_cmd/yuzu.cpp
+++ b/src/yuzu_cmd/yuzu.cpp
@@ -42,6 +42,8 @@
42#include <windows.h> 42#include <windows.h>
43 43
44#include <shellapi.h> 44#include <shellapi.h>
45
46#include "common/windows/timer_resolution.h"
45#endif 47#endif
46 48
47#undef _UNICODE 49#undef _UNICODE
@@ -314,6 +316,8 @@ int main(int argc, char** argv) {
314 316
315#ifdef _WIN32 317#ifdef _WIN32
316 LocalFree(argv_w); 318 LocalFree(argv_w);
319
320 Common::Windows::SetCurrentTimerResolutionToMaximum();
317#endif 321#endif
318 322
319 MicroProfileOnThreadCreate("EmuThread"); 323 MicroProfileOnThreadCreate("EmuThread");