summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
m---------externals/dynarmic0
-rw-r--r--src/common/settings.cpp2
-rw-r--r--src/common/settings.h1
-rw-r--r--src/core/CMakeLists.txt21
-rw-r--r--src/core/core.cpp4
-rw-r--r--src/core/core.h2
-rw-r--r--src/core/frontend/applets/cabinet.cpp2
-rw-r--r--src/core/frontend/applets/cabinet.h10
-rw-r--r--src/core/hid/emulated_controller.cpp35
-rw-r--r--src/core/hid/emulated_controller.h8
-rw-r--r--src/core/hid/input_converter.cpp2
-rw-r--r--src/core/hid/motion_input.cpp21
-rw-r--r--src/core/hid/motion_input.h11
-rw-r--r--src/core/hle/service/am/applets/applet_cabinet.cpp24
-rw-r--r--src/core/hle/service/am/applets/applet_cabinet.h6
-rw-r--r--src/core/hle/service/hid/controllers/npad.cpp4
-rw-r--r--src/core/hle/service/nfc/common/amiibo_crypto.cpp (renamed from src/core/hle/service/nfp/amiibo_crypto.cpp)4
-rw-r--r--src/core/hle/service/nfc/common/amiibo_crypto.h (renamed from src/core/hle/service/nfp/amiibo_crypto.h)4
-rw-r--r--src/core/hle/service/nfc/common/device.cpp (renamed from src/core/hle/service/nfp/nfp_device.cpp)672
-rw-r--r--src/core/hle/service/nfc/common/device.h138
-rw-r--r--src/core/hle/service/nfc/common/device_manager.cpp695
-rw-r--r--src/core/hle/service/nfc/common/device_manager.h100
-rw-r--r--src/core/hle/service/nfc/mifare_result.h17
-rw-r--r--src/core/hle/service/nfc/mifare_types.h63
-rw-r--r--src/core/hle/service/nfc/mifare_user.cpp400
-rw-r--r--src/core/hle/service/nfc/mifare_user.h52
-rw-r--r--src/core/hle/service/nfc/nfc.cpp159
-rw-r--r--src/core/hle/service/nfc/nfc_device.cpp288
-rw-r--r--src/core/hle/service/nfc/nfc_device.h78
-rw-r--r--src/core/hle/service/nfc/nfc_interface.cpp382
-rw-r--r--src/core/hle/service/nfc/nfc_interface.h (renamed from src/core/hle/service/nfc/nfc_user.h)33
-rw-r--r--src/core/hle/service/nfc/nfc_result.h33
-rw-r--r--src/core/hle/service/nfc/nfc_types.h90
-rw-r--r--src/core/hle/service/nfc/nfc_user.cpp365
-rw-r--r--src/core/hle/service/nfp/nfp.cpp36
-rw-r--r--src/core/hle/service/nfp/nfp_device.h120
-rw-r--r--src/core/hle/service/nfp/nfp_interface.cpp839
-rw-r--r--src/core/hle/service/nfp/nfp_interface.h37
-rw-r--r--src/core/hle/service/nfp/nfp_result.h29
-rw-r--r--src/core/hle/service/nfp/nfp_types.h129
-rw-r--r--src/core/hle/service/nifm/nifm.cpp6
-rw-r--r--src/core/hle/service/service.h20
-rw-r--r--src/core/internal_network/network.cpp2
-rw-r--r--src/core/internal_network/network_interface.cpp2
-rw-r--r--src/core/memory.cpp25
-rw-r--r--src/input_common/helpers/joycon_protocol/common_protocol.cpp7
-rw-r--r--src/input_common/helpers/joycon_protocol/common_protocol.h2
-rw-r--r--src/input_common/helpers/joycon_protocol/joycon_types.h7
-rw-r--r--src/input_common/helpers/joycon_protocol/nfc.cpp24
-rw-r--r--src/input_common/input_poller.cpp2
-rw-r--r--src/tests/video_core/memory_tracker.cpp4
-rw-r--r--src/video_core/buffer_cache/buffer_base.h9
-rw-r--r--src/video_core/buffer_cache/buffer_cache.h141
-rw-r--r--src/video_core/buffer_cache/buffer_cache_base.h7
-rw-r--r--src/video_core/buffer_cache/memory_tracker_base.h26
-rw-r--r--src/video_core/buffer_cache/word_manager.h27
-rw-r--r--src/video_core/engines/maxwell_dma.cpp8
-rw-r--r--src/video_core/fence_manager.h5
-rw-r--r--src/video_core/gpu.cpp19
-rw-r--r--src/video_core/gpu.h4
-rw-r--r--src/video_core/query_cache.h2
-rw-r--r--src/video_core/rasterizer_download_area.h16
-rw-r--r--src/video_core/rasterizer_interface.h3
-rw-r--r--src/video_core/renderer_null/null_rasterizer.cpp10
-rw-r--r--src/video_core/renderer_null/null_rasterizer.h1
-rw-r--r--src/video_core/renderer_opengl/gl_rasterizer.cpp25
-rw-r--r--src/video_core/renderer_opengl/gl_rasterizer.h1
-rw-r--r--src/video_core/renderer_opengl/gl_texture_cache.cpp2
-rw-r--r--src/video_core/renderer_vulkan/vk_rasterizer.cpp22
-rw-r--r--src/video_core/renderer_vulkan/vk_rasterizer.h1
-rw-r--r--src/video_core/renderer_vulkan/vk_texture_cache.cpp2
-rw-r--r--src/video_core/texture_cache/image_info.cpp12
-rw-r--r--src/video_core/texture_cache/image_info.h2
-rw-r--r--src/video_core/texture_cache/image_view_base.cpp4
-rw-r--r--src/video_core/texture_cache/texture_cache.h45
-rw-r--r--src/video_core/texture_cache/texture_cache_base.h4
-rw-r--r--src/video_core/texture_cache/util.cpp10
-rw-r--r--src/yuzu/applets/qt_amiibo_settings.cpp12
-rw-r--r--src/yuzu/applets/qt_amiibo_settings.h14
-rw-r--r--src/yuzu/bootmanager.h1
-rw-r--r--src/yuzu/configuration/config.cpp2
-rw-r--r--src/yuzu/configuration/configure_graphics_advanced.cpp7
-rw-r--r--src/yuzu/configuration/configure_graphics_advanced.h1
-rw-r--r--src/yuzu/configuration/configure_graphics_advanced.ui10
-rw-r--r--src/yuzu/configuration/configure_input_player.cpp3
-rw-r--r--src/yuzu/configuration/configure_input_player_widget.cpp20
-rw-r--r--src/yuzu/main.cpp6
-rw-r--r--src/yuzu/main.h8
-rw-r--r--src/yuzu/qt_common.cpp2
-rw-r--r--src/yuzu_cmd/config.cpp1
-rw-r--r--src/yuzu_cmd/default_ini.h4
91 files changed, 2719 insertions, 2797 deletions
diff --git a/externals/dynarmic b/externals/dynarmic
Subproject f9e6a3df5c84bcc74be46c289a74a78e5e28d62 Subproject 7da378033a7764f955516f75194856d87bbcd7a
diff --git a/src/common/settings.cpp b/src/common/settings.cpp
index f1ee42ab2..db1774c71 100644
--- a/src/common/settings.cpp
+++ b/src/common/settings.cpp
@@ -62,6 +62,7 @@ void LogSettings() {
62 log_setting("Renderer_AccelerateASTC", values.accelerate_astc.GetValue()); 62 log_setting("Renderer_AccelerateASTC", values.accelerate_astc.GetValue());
63 log_setting("Renderer_AsyncASTC", values.async_astc.GetValue()); 63 log_setting("Renderer_AsyncASTC", values.async_astc.GetValue());
64 log_setting("Renderer_UseVsync", values.vsync_mode.GetValue()); 64 log_setting("Renderer_UseVsync", values.vsync_mode.GetValue());
65 log_setting("Renderer_UseReactiveFlushing", values.use_reactive_flushing.GetValue());
65 log_setting("Renderer_ShaderBackend", values.shader_backend.GetValue()); 66 log_setting("Renderer_ShaderBackend", values.shader_backend.GetValue());
66 log_setting("Renderer_UseAsynchronousShaders", values.use_asynchronous_shaders.GetValue()); 67 log_setting("Renderer_UseAsynchronousShaders", values.use_asynchronous_shaders.GetValue());
67 log_setting("Renderer_AnisotropicFilteringLevel", values.max_anisotropy.GetValue()); 68 log_setting("Renderer_AnisotropicFilteringLevel", values.max_anisotropy.GetValue());
@@ -223,6 +224,7 @@ void RestoreGlobalState(bool is_powered_on) {
223 values.nvdec_emulation.SetGlobal(true); 224 values.nvdec_emulation.SetGlobal(true);
224 values.accelerate_astc.SetGlobal(true); 225 values.accelerate_astc.SetGlobal(true);
225 values.async_astc.SetGlobal(true); 226 values.async_astc.SetGlobal(true);
227 values.use_reactive_flushing.SetGlobal(true);
226 values.shader_backend.SetGlobal(true); 228 values.shader_backend.SetGlobal(true);
227 values.use_asynchronous_shaders.SetGlobal(true); 229 values.use_asynchronous_shaders.SetGlobal(true);
228 values.use_fast_gpu_time.SetGlobal(true); 230 values.use_fast_gpu_time.SetGlobal(true);
diff --git a/src/common/settings.h b/src/common/settings.h
index 2bf191cef..f4eb4e3cd 100644
--- a/src/common/settings.h
+++ b/src/common/settings.h
@@ -465,6 +465,7 @@ struct Values {
465 SwitchableSetting<bool> async_astc{false, "async_astc"}; 465 SwitchableSetting<bool> async_astc{false, "async_astc"};
466 Setting<VSyncMode, true> vsync_mode{VSyncMode::FIFO, VSyncMode::Immediate, 466 Setting<VSyncMode, true> vsync_mode{VSyncMode::FIFO, VSyncMode::Immediate,
467 VSyncMode::FIFORelaxed, "use_vsync"}; 467 VSyncMode::FIFORelaxed, "use_vsync"};
468 SwitchableSetting<bool> use_reactive_flushing{true, "use_reactive_flushing"};
468 SwitchableSetting<ShaderBackend, true> shader_backend{ShaderBackend::GLSL, ShaderBackend::GLSL, 469 SwitchableSetting<ShaderBackend, true> shader_backend{ShaderBackend::GLSL, ShaderBackend::GLSL,
469 ShaderBackend::SPIRV, "shader_backend"}; 470 ShaderBackend::SPIRV, "shader_backend"};
470 SwitchableSetting<bool> use_asynchronous_shaders{false, "use_asynchronous_shaders"}; 471 SwitchableSetting<bool> use_asynchronous_shaders{false, "use_asynchronous_shaders"};
diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt
index 8817a99c9..45328158f 100644
--- a/src/core/CMakeLists.txt
+++ b/src/core/CMakeLists.txt
@@ -555,21 +555,22 @@ add_library(core STATIC
555 hle/service/mnpp/mnpp_app.h 555 hle/service/mnpp/mnpp_app.h
556 hle/service/ncm/ncm.cpp 556 hle/service/ncm/ncm.cpp
557 hle/service/ncm/ncm.h 557 hle/service/ncm/ncm.h
558 hle/service/nfc/mifare_user.cpp 558 hle/service/nfc/common/amiibo_crypto.cpp
559 hle/service/nfc/mifare_user.h 559 hle/service/nfc/common/amiibo_crypto.h
560 hle/service/nfc/common/device.cpp
561 hle/service/nfc/common/device.h
562 hle/service/nfc/common/device_manager.cpp
563 hle/service/nfc/common/device_manager.h
564 hle/service/nfc/mifare_result.h
565 hle/service/nfc/mifare_types.h
560 hle/service/nfc/nfc.cpp 566 hle/service/nfc/nfc.cpp
561 hle/service/nfc/nfc.h 567 hle/service/nfc/nfc.h
562 hle/service/nfc/nfc_device.cpp 568 hle/service/nfc/nfc_interface.cpp
563 hle/service/nfc/nfc_device.h 569 hle/service/nfc/nfc_interface.h
564 hle/service/nfc/nfc_result.h 570 hle/service/nfc/nfc_result.h
565 hle/service/nfc/nfc_user.cpp 571 hle/service/nfc/nfc_types.h
566 hle/service/nfc/nfc_user.h
567 hle/service/nfp/amiibo_crypto.cpp
568 hle/service/nfp/amiibo_crypto.h
569 hle/service/nfp/nfp.cpp 572 hle/service/nfp/nfp.cpp
570 hle/service/nfp/nfp.h 573 hle/service/nfp/nfp.h
571 hle/service/nfp/nfp_device.cpp
572 hle/service/nfp/nfp_device.h
573 hle/service/nfp/nfp_interface.cpp 574 hle/service/nfp/nfp_interface.cpp
574 hle/service/nfp/nfp_interface.h 575 hle/service/nfp/nfp_interface.h
575 hle/service/nfp/nfp_result.h 576 hle/service/nfp/nfp_result.h
diff --git a/src/core/core.cpp b/src/core/core.cpp
index 06fba4ce5..b5f62690e 100644
--- a/src/core/core.cpp
+++ b/src/core/core.cpp
@@ -612,6 +612,10 @@ void System::PrepareReschedule(const u32 core_index) {
612 impl->kernel.PrepareReschedule(core_index); 612 impl->kernel.PrepareReschedule(core_index);
613} 613}
614 614
615size_t System::GetCurrentHostThreadID() const {
616 return impl->kernel.GetCurrentHostThreadID();
617}
618
615PerfStatsResults System::GetAndResetPerfStats() { 619PerfStatsResults System::GetAndResetPerfStats() {
616 return impl->GetAndResetPerfStats(); 620 return impl->GetAndResetPerfStats();
617} 621}
diff --git a/src/core/core.h b/src/core/core.h
index 4a5aba032..4f153154f 100644
--- a/src/core/core.h
+++ b/src/core/core.h
@@ -222,6 +222,8 @@ public:
222 /// Prepare the core emulation for a reschedule 222 /// Prepare the core emulation for a reschedule
223 void PrepareReschedule(u32 core_index); 223 void PrepareReschedule(u32 core_index);
224 224
225 [[nodiscard]] size_t GetCurrentHostThreadID() const;
226
225 /// Gets and resets core performance statistics 227 /// Gets and resets core performance statistics
226 [[nodiscard]] PerfStatsResults GetAndResetPerfStats(); 228 [[nodiscard]] PerfStatsResults GetAndResetPerfStats();
227 229
diff --git a/src/core/frontend/applets/cabinet.cpp b/src/core/frontend/applets/cabinet.cpp
index 2d501eeae..c33ce248b 100644
--- a/src/core/frontend/applets/cabinet.cpp
+++ b/src/core/frontend/applets/cabinet.cpp
@@ -14,7 +14,7 @@ void DefaultCabinetApplet::Close() const {}
14 14
15void DefaultCabinetApplet::ShowCabinetApplet( 15void DefaultCabinetApplet::ShowCabinetApplet(
16 const CabinetCallback& callback, const CabinetParameters& parameters, 16 const CabinetCallback& callback, const CabinetParameters& parameters,
17 std::shared_ptr<Service::NFP::NfpDevice> nfp_device) const { 17 std::shared_ptr<Service::NFC::NfcDevice> nfp_device) const {
18 LOG_WARNING(Service_AM, "(STUBBED) called"); 18 LOG_WARNING(Service_AM, "(STUBBED) called");
19 callback(false, {}); 19 callback(false, {});
20} 20}
diff --git a/src/core/frontend/applets/cabinet.h b/src/core/frontend/applets/cabinet.h
index 74dc5a4f6..af3fc6c3d 100644
--- a/src/core/frontend/applets/cabinet.h
+++ b/src/core/frontend/applets/cabinet.h
@@ -7,9 +7,9 @@
7#include "core/frontend/applets/applet.h" 7#include "core/frontend/applets/applet.h"
8#include "core/hle/service/nfp/nfp_types.h" 8#include "core/hle/service/nfp/nfp_types.h"
9 9
10namespace Service::NFP { 10namespace Service::NFC {
11class NfpDevice; 11class NfcDevice;
12} // namespace Service::NFP 12} // namespace Service::NFC
13 13
14namespace Core::Frontend { 14namespace Core::Frontend {
15 15
@@ -26,14 +26,14 @@ public:
26 virtual ~CabinetApplet(); 26 virtual ~CabinetApplet();
27 virtual void ShowCabinetApplet(const CabinetCallback& callback, 27 virtual void ShowCabinetApplet(const CabinetCallback& callback,
28 const CabinetParameters& parameters, 28 const CabinetParameters& parameters,
29 std::shared_ptr<Service::NFP::NfpDevice> nfp_device) const = 0; 29 std::shared_ptr<Service::NFC::NfcDevice> nfp_device) const = 0;
30}; 30};
31 31
32class DefaultCabinetApplet final : public CabinetApplet { 32class DefaultCabinetApplet final : public CabinetApplet {
33public: 33public:
34 void Close() const override; 34 void Close() const override;
35 void ShowCabinetApplet(const CabinetCallback& callback, const CabinetParameters& parameters, 35 void ShowCabinetApplet(const CabinetCallback& callback, const CabinetParameters& parameters,
36 std::shared_ptr<Service::NFP::NfpDevice> nfp_device) const override; 36 std::shared_ptr<Service::NFC::NfcDevice> nfp_device) const override;
37}; 37};
38 38
39} // namespace Core::Frontend 39} // namespace Core::Frontend
diff --git a/src/core/hid/emulated_controller.cpp b/src/core/hid/emulated_controller.cpp
index ecab85893..366880711 100644
--- a/src/core/hid/emulated_controller.cpp
+++ b/src/core/hid/emulated_controller.cpp
@@ -688,6 +688,12 @@ void EmulatedController::SetMotionParam(std::size_t index, Common::ParamPackage
688 ReloadInput(); 688 ReloadInput();
689} 689}
690 690
691void EmulatedController::StartMotionCalibration() {
692 for (ControllerMotionInfo& motion : controller.motion_values) {
693 motion.emulated.Calibrate();
694 }
695}
696
691void EmulatedController::SetButton(const Common::Input::CallbackStatus& callback, std::size_t index, 697void EmulatedController::SetButton(const Common::Input::CallbackStatus& callback, std::size_t index,
692 Common::UUID uuid) { 698 Common::UUID uuid) {
693 if (index >= controller.button_values.size()) { 699 if (index >= controller.button_values.size()) {
@@ -979,7 +985,6 @@ void EmulatedController::SetMotion(const Common::Input::CallbackStatus& callback
979 emulated.SetUserGyroThreshold(raw_status.gyro.x.properties.threshold); 985 emulated.SetUserGyroThreshold(raw_status.gyro.x.properties.threshold);
980 emulated.UpdateRotation(raw_status.delta_timestamp); 986 emulated.UpdateRotation(raw_status.delta_timestamp);
981 emulated.UpdateOrientation(raw_status.delta_timestamp); 987 emulated.UpdateOrientation(raw_status.delta_timestamp);
982 force_update_motion = raw_status.force_update;
983 988
984 auto& motion = controller.motion_state[index]; 989 auto& motion = controller.motion_state[index];
985 motion.accel = emulated.GetAcceleration(); 990 motion.accel = emulated.GetAcceleration();
@@ -1618,19 +1623,6 @@ NpadGcTriggerState EmulatedController::GetTriggers() const {
1618 1623
1619MotionState EmulatedController::GetMotions() const { 1624MotionState EmulatedController::GetMotions() const {
1620 std::unique_lock lock{mutex}; 1625 std::unique_lock lock{mutex};
1621
1622 // Some drivers like mouse motion need constant refreshing
1623 if (force_update_motion) {
1624 for (auto& device : motion_devices) {
1625 if (!device) {
1626 continue;
1627 }
1628 lock.unlock();
1629 device->ForceUpdate();
1630 lock.lock();
1631 }
1632 }
1633
1634 return controller.motion_state; 1626 return controller.motion_state;
1635} 1627}
1636 1628
@@ -1696,8 +1688,21 @@ void EmulatedController::DeleteCallback(int key) {
1696 callback_list.erase(iterator); 1688 callback_list.erase(iterator);
1697} 1689}
1698 1690
1699void EmulatedController::TurboButtonUpdate() { 1691void EmulatedController::StatusUpdate() {
1700 turbo_button_state = (turbo_button_state + 1) % (TURBO_BUTTON_DELAY * 2); 1692 turbo_button_state = (turbo_button_state + 1) % (TURBO_BUTTON_DELAY * 2);
1693
1694 // Some drivers like key motion need constant refreshing
1695 for (std::size_t index = 0; index < motion_devices.size(); ++index) {
1696 const auto& raw_status = controller.motion_values[index].raw_status;
1697 auto& device = motion_devices[index];
1698 if (!raw_status.force_update) {
1699 continue;
1700 }
1701 if (!device) {
1702 continue;
1703 }
1704 device->ForceUpdate();
1705 }
1701} 1706}
1702 1707
1703NpadButton EmulatedController::GetTurboButtonMask() const { 1708NpadButton EmulatedController::GetTurboButtonMask() const {
diff --git a/src/core/hid/emulated_controller.h b/src/core/hid/emulated_controller.h
index 6e01f4e12..88fad2f56 100644
--- a/src/core/hid/emulated_controller.h
+++ b/src/core/hid/emulated_controller.h
@@ -290,6 +290,9 @@ public:
290 */ 290 */
291 void SetMotionParam(std::size_t index, Common::ParamPackage param); 291 void SetMotionParam(std::size_t index, Common::ParamPackage param);
292 292
293 /// Auto calibrates the current motion devices
294 void StartMotionCalibration();
295
293 /// Returns the latest button status from the controller with parameters 296 /// Returns the latest button status from the controller with parameters
294 ButtonValues GetButtonsValues() const; 297 ButtonValues GetButtonsValues() const;
295 298
@@ -415,8 +418,8 @@ public:
415 */ 418 */
416 void DeleteCallback(int key); 419 void DeleteCallback(int key);
417 420
418 /// Swaps the state of the turbo buttons 421 /// Swaps the state of the turbo buttons and updates motion input
419 void TurboButtonUpdate(); 422 void StatusUpdate();
420 423
421private: 424private:
422 /// creates input devices from params 425 /// creates input devices from params
@@ -528,7 +531,6 @@ private:
528 bool is_configuring{false}; 531 bool is_configuring{false};
529 bool system_buttons_enabled{true}; 532 bool system_buttons_enabled{true};
530 f32 motion_sensitivity{Core::HID::MotionInput::IsAtRestStandard}; 533 f32 motion_sensitivity{Core::HID::MotionInput::IsAtRestStandard};
531 bool force_update_motion{false};
532 u32 turbo_button_state{0}; 534 u32 turbo_button_state{0};
533 535
534 // Temporary values to avoid doing changes while the controller is in configuring mode 536 // Temporary values to avoid doing changes while the controller is in configuring mode
diff --git a/src/core/hid/input_converter.cpp b/src/core/hid/input_converter.cpp
index 53b00b1f9..4ccb1c596 100644
--- a/src/core/hid/input_converter.cpp
+++ b/src/core/hid/input_converter.cpp
@@ -86,7 +86,7 @@ Common::Input::MotionStatus TransformToMotion(const Common::Input::CallbackStatu
86 .range = 1.0f, 86 .range = 1.0f,
87 .offset = 0.0f, 87 .offset = 0.0f,
88 }; 88 };
89 status.delta_timestamp = 5000; 89 status.delta_timestamp = 1000;
90 status.force_update = true; 90 status.force_update = true;
91 status.accel.x = { 91 status.accel.x = {
92 .value = 0.0f, 92 .value = 0.0f,
diff --git a/src/core/hid/motion_input.cpp b/src/core/hid/motion_input.cpp
index b60478dbb..f56f2ae1d 100644
--- a/src/core/hid/motion_input.cpp
+++ b/src/core/hid/motion_input.cpp
@@ -37,11 +37,17 @@ void MotionInput::SetGyroscope(const Common::Vec3f& gyroscope) {
37 gyro.y = std::clamp(gyro.y, -GyroMaxValue, GyroMaxValue); 37 gyro.y = std::clamp(gyro.y, -GyroMaxValue, GyroMaxValue);
38 gyro.z = std::clamp(gyro.z, -GyroMaxValue, GyroMaxValue); 38 gyro.z = std::clamp(gyro.z, -GyroMaxValue, GyroMaxValue);
39 39
40 // Auto adjust drift to minimize drift 40 // Auto adjust gyro_bias to minimize drift
41 if (!IsMoving(IsAtRestRelaxed)) { 41 if (!IsMoving(IsAtRestRelaxed)) {
42 gyro_bias = (gyro_bias * 0.9999f) + (gyroscope * 0.0001f); 42 gyro_bias = (gyro_bias * 0.9999f) + (gyroscope * 0.0001f);
43 } 43 }
44 44
45 // Adjust drift when calibration mode is enabled
46 if (calibration_mode) {
47 gyro_bias = (gyro_bias * 0.99f) + (gyroscope * 0.01f);
48 StopCalibration();
49 }
50
45 if (gyro.Length() < gyro_threshold * user_gyro_threshold) { 51 if (gyro.Length() < gyro_threshold * user_gyro_threshold) {
46 gyro = {}; 52 gyro = {};
47 } else { 53 } else {
@@ -107,6 +113,19 @@ void MotionInput::UpdateRotation(u64 elapsed_time) {
107 rotations += gyro * sample_period; 113 rotations += gyro * sample_period;
108} 114}
109 115
116void MotionInput::Calibrate() {
117 calibration_mode = true;
118 calibration_counter = 0;
119}
120
121void MotionInput::StopCalibration() {
122 if (calibration_counter++ > CalibrationSamples) {
123 calibration_mode = false;
124 ResetQuaternion();
125 ResetRotations();
126 }
127}
128
110// Based on Madgwick's implementation of Mayhony's AHRS algorithm. 129// Based on Madgwick's implementation of Mayhony's AHRS algorithm.
111// https://github.com/xioTechnologies/Open-Source-AHRS-With-x-IMU/blob/master/x-IMU%20IMU%20and%20AHRS%20Algorithms/x-IMU%20IMU%20and%20AHRS%20Algorithms/AHRS/MahonyAHRS.cs 130// https://github.com/xioTechnologies/Open-Source-AHRS-With-x-IMU/blob/master/x-IMU%20IMU%20and%20AHRS%20Algorithms/x-IMU%20IMU%20and%20AHRS%20Algorithms/AHRS/MahonyAHRS.cs
112void MotionInput::UpdateOrientation(u64 elapsed_time) { 131void MotionInput::UpdateOrientation(u64 elapsed_time) {
diff --git a/src/core/hid/motion_input.h b/src/core/hid/motion_input.h
index 482719359..11678983d 100644
--- a/src/core/hid/motion_input.h
+++ b/src/core/hid/motion_input.h
@@ -23,6 +23,8 @@ public:
23 static constexpr float GyroMaxValue = 5.0f; 23 static constexpr float GyroMaxValue = 5.0f;
24 static constexpr float AccelMaxValue = 7.0f; 24 static constexpr float AccelMaxValue = 7.0f;
25 25
26 static constexpr std::size_t CalibrationSamples = 300;
27
26 explicit MotionInput(); 28 explicit MotionInput();
27 29
28 MotionInput(const MotionInput&) = default; 30 MotionInput(const MotionInput&) = default;
@@ -49,6 +51,8 @@ public:
49 void UpdateRotation(u64 elapsed_time); 51 void UpdateRotation(u64 elapsed_time);
50 void UpdateOrientation(u64 elapsed_time); 52 void UpdateOrientation(u64 elapsed_time);
51 53
54 void Calibrate();
55
52 [[nodiscard]] std::array<Common::Vec3f, 3> GetOrientation() const; 56 [[nodiscard]] std::array<Common::Vec3f, 3> GetOrientation() const;
53 [[nodiscard]] Common::Vec3f GetAcceleration() const; 57 [[nodiscard]] Common::Vec3f GetAcceleration() const;
54 [[nodiscard]] Common::Vec3f GetGyroscope() const; 58 [[nodiscard]] Common::Vec3f GetGyroscope() const;
@@ -61,6 +65,7 @@ public:
61 [[nodiscard]] bool IsCalibrated(f32 sensitivity) const; 65 [[nodiscard]] bool IsCalibrated(f32 sensitivity) const;
62 66
63private: 67private:
68 void StopCalibration();
64 void ResetOrientation(); 69 void ResetOrientation();
65 void SetOrientationFromAccelerometer(); 70 void SetOrientationFromAccelerometer();
66 71
@@ -103,6 +108,12 @@ private:
103 108
104 // Use accelerometer values to calculate position 109 // Use accelerometer values to calculate position
105 bool only_accelerometer = true; 110 bool only_accelerometer = true;
111
112 // When enabled it will aggressively adjust for gyro drift
113 bool calibration_mode = false;
114
115 // Used to auto disable calibration mode
116 std::size_t calibration_counter = 0;
106}; 117};
107 118
108} // namespace Core::HID 119} // namespace Core::HID
diff --git a/src/core/hle/service/am/applets/applet_cabinet.cpp b/src/core/hle/service/am/applets/applet_cabinet.cpp
index 93c9f2a55..8b754e9d4 100644
--- a/src/core/hle/service/am/applets/applet_cabinet.cpp
+++ b/src/core/hle/service/am/applets/applet_cabinet.cpp
@@ -11,7 +11,7 @@
11#include "core/hle/service/am/am.h" 11#include "core/hle/service/am/am.h"
12#include "core/hle/service/am/applets/applet_cabinet.h" 12#include "core/hle/service/am/applets/applet_cabinet.h"
13#include "core/hle/service/mii/mii_manager.h" 13#include "core/hle/service/mii/mii_manager.h"
14#include "core/hle/service/nfp/nfp_device.h" 14#include "core/hle/service/nfc/common/device.h"
15 15
16namespace Service::AM::Applets { 16namespace Service::AM::Applets {
17 17
@@ -72,10 +72,10 @@ void Cabinet::Execute() {
72 72
73 // TODO: listen on all controllers 73 // TODO: listen on all controllers
74 if (nfp_device == nullptr) { 74 if (nfp_device == nullptr) {
75 nfp_device = std::make_shared<Service::NFP::NfpDevice>( 75 nfp_device = std::make_shared<Service::NFC::NfcDevice>(
76 system.HIDCore().GetFirstNpadId(), system, service_context, availability_change_event); 76 system.HIDCore().GetFirstNpadId(), system, service_context, availability_change_event);
77 nfp_device->Initialize(); 77 nfp_device->Initialize();
78 nfp_device->StartDetection(Service::NFP::TagProtocol::All); 78 nfp_device->StartDetection(Service::NFC::NfcProtocol::All);
79 } 79 }
80 80
81 const Core::Frontend::CabinetParameters parameters{ 81 const Core::Frontend::CabinetParameters parameters{
@@ -106,20 +106,22 @@ void Cabinet::DisplayCompleted(bool apply_changes, std::string_view amiibo_name)
106 Cancel(); 106 Cancel();
107 } 107 }
108 108
109 if (nfp_device->GetCurrentState() != Service::NFP::DeviceState::TagFound && 109 if (nfp_device->GetCurrentState() != Service::NFC::DeviceState::TagFound &&
110 nfp_device->GetCurrentState() != Service::NFP::DeviceState::TagMounted) { 110 nfp_device->GetCurrentState() != Service::NFC::DeviceState::TagMounted) {
111 Cancel(); 111 Cancel();
112 } 112 }
113 113
114 if (nfp_device->GetCurrentState() == Service::NFP::DeviceState::TagFound) { 114 if (nfp_device->GetCurrentState() == Service::NFC::DeviceState::TagFound) {
115 nfp_device->Mount(Service::NFP::MountTarget::All); 115 nfp_device->Mount(Service::NFP::ModelType::Amiibo, Service::NFP::MountTarget::All);
116 } 116 }
117 117
118 switch (applet_input_common.applet_mode) { 118 switch (applet_input_common.applet_mode) {
119 case Service::NFP::CabinetMode::StartNicknameAndOwnerSettings: { 119 case Service::NFP::CabinetMode::StartNicknameAndOwnerSettings: {
120 Service::NFP::AmiiboName name{}; 120 Service::NFP::RegisterInfoPrivate register_info{};
121 std::memcpy(name.data(), amiibo_name.data(), std::min(amiibo_name.size(), name.size() - 1)); 121 std::memcpy(register_info.amiibo_name.data(), amiibo_name.data(),
122 nfp_device->SetRegisterInfoPrivate(name); 122 std::min(amiibo_name.size(), register_info.amiibo_name.size() - 1));
123
124 nfp_device->SetRegisterInfoPrivate(register_info);
123 break; 125 break;
124 } 126 }
125 case Service::NFP::CabinetMode::StartGameDataEraser: 127 case Service::NFP::CabinetMode::StartGameDataEraser:
@@ -139,7 +141,7 @@ void Cabinet::DisplayCompleted(bool apply_changes, std::string_view amiibo_name)
139 applet_output.device_handle = applet_input_common.device_handle; 141 applet_output.device_handle = applet_input_common.device_handle;
140 applet_output.result = CabinetResult::Cancel; 142 applet_output.result = CabinetResult::Cancel;
141 const auto reg_result = nfp_device->GetRegisterInfo(applet_output.register_info); 143 const auto reg_result = nfp_device->GetRegisterInfo(applet_output.register_info);
142 const auto tag_result = nfp_device->GetTagInfo(applet_output.tag_info); 144 const auto tag_result = nfp_device->GetTagInfo(applet_output.tag_info, false);
143 nfp_device->Finalize(); 145 nfp_device->Finalize();
144 146
145 if (reg_result.IsSuccess()) { 147 if (reg_result.IsSuccess()) {
diff --git a/src/core/hle/service/am/applets/applet_cabinet.h b/src/core/hle/service/am/applets/applet_cabinet.h
index edd295a27..b56427021 100644
--- a/src/core/hle/service/am/applets/applet_cabinet.h
+++ b/src/core/hle/service/am/applets/applet_cabinet.h
@@ -19,8 +19,8 @@ namespace Core {
19class System; 19class System;
20} // namespace Core 20} // namespace Core
21 21
22namespace Service::NFP { 22namespace Service::NFC {
23class NfpDevice; 23class NfcDevice;
24} 24}
25 25
26namespace Service::AM::Applets { 26namespace Service::AM::Applets {
@@ -96,7 +96,7 @@ private:
96 Core::System& system; 96 Core::System& system;
97 97
98 bool is_complete{false}; 98 bool is_complete{false};
99 std::shared_ptr<Service::NFP::NfpDevice> nfp_device; 99 std::shared_ptr<Service::NFC::NfcDevice> nfp_device;
100 Kernel::KEvent* availability_change_event; 100 Kernel::KEvent* availability_change_event;
101 KernelHelpers::ServiceContext service_context; 101 KernelHelpers::ServiceContext service_context;
102 StartParamForAmiiboSettings applet_input_common{}; 102 StartParamForAmiiboSettings applet_input_common{};
diff --git a/src/core/hle/service/hid/controllers/npad.cpp b/src/core/hle/service/hid/controllers/npad.cpp
index 8abf71608..ef4aec4ea 100644
--- a/src/core/hle/service/hid/controllers/npad.cpp
+++ b/src/core/hle/service/hid/controllers/npad.cpp
@@ -423,8 +423,8 @@ void Controller_NPad::RequestPadStateUpdate(Core::HID::NpadIdType npad_id) {
423 return; 423 return;
424 } 424 }
425 425
426 // This function is unique to yuzu for the turbo buttons to work properly 426 // This function is unique to yuzu for the turbo buttons and motion to work properly
427 controller.device->TurboButtonUpdate(); 427 controller.device->StatusUpdate();
428 428
429 auto& pad_entry = controller.npad_pad_state; 429 auto& pad_entry = controller.npad_pad_state;
430 auto& trigger_entry = controller.npad_trigger_state; 430 auto& trigger_entry = controller.npad_trigger_state;
diff --git a/src/core/hle/service/nfp/amiibo_crypto.cpp b/src/core/hle/service/nfc/common/amiibo_crypto.cpp
index a3622e792..f3901ee8d 100644
--- a/src/core/hle/service/nfp/amiibo_crypto.cpp
+++ b/src/core/hle/service/nfc/common/amiibo_crypto.cpp
@@ -12,7 +12,7 @@
12#include "common/fs/fs.h" 12#include "common/fs/fs.h"
13#include "common/fs/path_util.h" 13#include "common/fs/path_util.h"
14#include "common/logging/log.h" 14#include "common/logging/log.h"
15#include "core/hle/service/nfp/amiibo_crypto.h" 15#include "core/hle/service/nfc/common/amiibo_crypto.h"
16 16
17namespace Service::NFP::AmiiboCrypto { 17namespace Service::NFP::AmiiboCrypto {
18 18
@@ -55,7 +55,7 @@ bool IsAmiiboValid(const EncryptedNTAG215File& ntag_file) {
55 if (amiibo_data.constant_value != 0xA5) { 55 if (amiibo_data.constant_value != 0xA5) {
56 return false; 56 return false;
57 } 57 }
58 if (amiibo_data.model_info.tag_type != PackedTagType::Type2) { 58 if (amiibo_data.model_info.tag_type != NFC::PackedTagType::Type2) {
59 return false; 59 return false;
60 } 60 }
61 if ((ntag_file.dynamic_lock & 0xFFFFFF) != 0x0F0001U) { 61 if ((ntag_file.dynamic_lock & 0xFFFFFF) != 0x0F0001U) {
diff --git a/src/core/hle/service/nfp/amiibo_crypto.h b/src/core/hle/service/nfc/common/amiibo_crypto.h
index f6208ee6b..bf3044ed9 100644
--- a/src/core/hle/service/nfp/amiibo_crypto.h
+++ b/src/core/hle/service/nfc/common/amiibo_crypto.h
@@ -24,9 +24,9 @@ using DrgbOutput = std::array<u8, 0x20>;
24struct HashSeed { 24struct HashSeed {
25 u16_be magic; 25 u16_be magic;
26 std::array<u8, 0xE> padding; 26 std::array<u8, 0xE> padding;
27 UniqueSerialNumber uid_1; 27 NFC::UniqueSerialNumber uid_1;
28 u8 nintendo_id_1; 28 u8 nintendo_id_1;
29 UniqueSerialNumber uid_2; 29 NFC::UniqueSerialNumber uid_2;
30 u8 nintendo_id_2; 30 u8 nintendo_id_2;
31 std::array<u8, 0x20> keygen_salt; 31 std::array<u8, 0x20> keygen_salt;
32}; 32};
diff --git a/src/core/hle/service/nfp/nfp_device.cpp b/src/core/hle/service/nfc/common/device.cpp
index 3f9af53c8..e5de65ce0 100644
--- a/src/core/hle/service/nfp/nfp_device.cpp
+++ b/src/core/hle/service/nfc/common/device.cpp
@@ -1,8 +1,6 @@
1// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project 1// SPDX-FileCopyrightText: Copyright 2022 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 <array>
5
6#ifdef _MSC_VER 4#ifdef _MSC_VER
7#pragma warning(push) 5#pragma warning(push)
8#pragma warning(disable : 4701) // Potentially uninitialized local variable 'result' used 6#pragma warning(disable : 4701) // Potentially uninitialized local variable 'result' used
@@ -26,21 +24,22 @@
26#include "core/hle/service/ipc_helpers.h" 24#include "core/hle/service/ipc_helpers.h"
27#include "core/hle/service/mii/mii_manager.h" 25#include "core/hle/service/mii/mii_manager.h"
28#include "core/hle/service/mii/types.h" 26#include "core/hle/service/mii/types.h"
29#include "core/hle/service/nfp/amiibo_crypto.h" 27#include "core/hle/service/nfc/common/amiibo_crypto.h"
30#include "core/hle/service/nfp/nfp_device.h" 28#include "core/hle/service/nfc/common/device.h"
31#include "core/hle/service/nfp/nfp_result.h" 29#include "core/hle/service/nfc/mifare_result.h"
30#include "core/hle/service/nfc/nfc_result.h"
32#include "core/hle/service/time/time_manager.h" 31#include "core/hle/service/time/time_manager.h"
33#include "core/hle/service/time/time_zone_content_manager.h" 32#include "core/hle/service/time/time_zone_content_manager.h"
34#include "core/hle/service/time/time_zone_types.h" 33#include "core/hle/service/time/time_zone_types.h"
35 34
36namespace Service::NFP { 35namespace Service::NFC {
37NfpDevice::NfpDevice(Core::HID::NpadIdType npad_id_, Core::System& system_, 36NfcDevice::NfcDevice(Core::HID::NpadIdType npad_id_, Core::System& system_,
38 KernelHelpers::ServiceContext& service_context_, 37 KernelHelpers::ServiceContext& service_context_,
39 Kernel::KEvent* availability_change_event_) 38 Kernel::KEvent* availability_change_event_)
40 : npad_id{npad_id_}, system{system_}, service_context{service_context_}, 39 : npad_id{npad_id_}, system{system_}, service_context{service_context_},
41 availability_change_event{availability_change_event_} { 40 availability_change_event{availability_change_event_} {
42 activate_event = service_context.CreateEvent("IUser:NFPActivateEvent"); 41 activate_event = service_context.CreateEvent("NFC:ActivateEvent");
43 deactivate_event = service_context.CreateEvent("IUser:NFPDeactivateEvent"); 42 deactivate_event = service_context.CreateEvent("NFC:DeactivateEvent");
44 npad_device = system.HIDCore().GetEmulatedController(npad_id); 43 npad_device = system.HIDCore().GetEmulatedController(npad_id);
45 44
46 Core::HID::ControllerUpdateCallback engine_callback{ 45 Core::HID::ControllerUpdateCallback engine_callback{
@@ -54,9 +53,9 @@ NfpDevice::NfpDevice(Core::HID::NpadIdType npad_id_, Core::System& system_,
54 current_posix_time = standard_steady_clock.GetCurrentTimePoint(system).time_point; 53 current_posix_time = standard_steady_clock.GetCurrentTimePoint(system).time_point;
55} 54}
56 55
57NfpDevice::~NfpDevice() { 56NfcDevice::~NfcDevice() {
58 activate_event->Close(); 57 service_context.CloseEvent(activate_event);
59 deactivate_event->Close(); 58 service_context.CloseEvent(deactivate_event);
60 if (!is_controller_set) { 59 if (!is_controller_set) {
61 return; 60 return;
62 } 61 }
@@ -64,7 +63,7 @@ NfpDevice::~NfpDevice() {
64 is_controller_set = false; 63 is_controller_set = false;
65}; 64};
66 65
67void NfpDevice::NpadUpdate(Core::HID::ControllerTriggerType type) { 66void NfcDevice::NpadUpdate(Core::HID::ControllerTriggerType type) {
68 if (!is_initalized) { 67 if (!is_initalized) {
69 return; 68 return;
70 } 69 }
@@ -92,14 +91,14 @@ void NfpDevice::NpadUpdate(Core::HID::ControllerTriggerType type) {
92 const auto nfc_status = npad_device->GetNfc(); 91 const auto nfc_status = npad_device->GetNfc();
93 switch (nfc_status.state) { 92 switch (nfc_status.state) {
94 case Common::Input::NfcState::NewAmiibo: 93 case Common::Input::NfcState::NewAmiibo:
95 LoadAmiibo(nfc_status.data); 94 LoadNfcTag(nfc_status.data);
96 break; 95 break;
97 case Common::Input::NfcState::AmiiboRemoved: 96 case Common::Input::NfcState::AmiiboRemoved:
98 if (device_state == DeviceState::Initialized || device_state == DeviceState::TagRemoved) { 97 if (device_state == DeviceState::Initialized || device_state == DeviceState::TagRemoved) {
99 break; 98 break;
100 } 99 }
101 if (device_state != DeviceState::SearchingForTag) { 100 if (device_state != DeviceState::SearchingForTag) {
102 CloseAmiibo(); 101 CloseNfcTag();
103 } 102 }
104 break; 103 break;
105 default: 104 default:
@@ -107,28 +106,29 @@ void NfpDevice::NpadUpdate(Core::HID::ControllerTriggerType type) {
107 } 106 }
108} 107}
109 108
110bool NfpDevice::LoadAmiibo(std::span<const u8> data) { 109bool NfcDevice::LoadNfcTag(std::span<const u8> data) {
111 if (device_state != DeviceState::SearchingForTag) { 110 if (device_state != DeviceState::SearchingForTag) {
112 LOG_ERROR(Service_NFP, "Game is not looking for amiibos, current state {}", device_state); 111 LOG_ERROR(Service_NFC, "Game is not looking for nfc tag, current state {}", device_state);
113 return false; 112 return false;
114 } 113 }
115 114
116 if (data.size() != sizeof(EncryptedNTAG215File)) { 115 if (data.size() < sizeof(NFP::EncryptedNTAG215File)) {
117 LOG_ERROR(Service_NFP, "Not an amiibo, size={}", data.size()); 116 LOG_ERROR(Service_NFC, "Not an amiibo, size={}", data.size());
118 return false; 117 return false;
119 } 118 }
120 119
121 // TODO: Filter by allowed_protocols here 120 mifare_data.resize(data.size());
121 memcpy(mifare_data.data(), data.data(), data.size());
122 122
123 memcpy(&tag_data, data.data(), sizeof(EncryptedNTAG215File)); 123 memcpy(&tag_data, data.data(), sizeof(NFP::EncryptedNTAG215File));
124 is_plain_amiibo = AmiiboCrypto::IsAmiiboValid(tag_data); 124 is_plain_amiibo = NFP::AmiiboCrypto::IsAmiiboValid(tag_data);
125 125
126 if (is_plain_amiibo) { 126 if (is_plain_amiibo) {
127 encrypted_tag_data = AmiiboCrypto::EncodedDataToNfcData(tag_data); 127 encrypted_tag_data = NFP::AmiiboCrypto::EncodedDataToNfcData(tag_data);
128 LOG_INFO(Service_NFP, "Using plain amiibo"); 128 LOG_INFO(Service_NFP, "Using plain amiibo");
129 } else { 129 } else {
130 tag_data = {}; 130 tag_data = {};
131 memcpy(&encrypted_tag_data, data.data(), sizeof(EncryptedNTAG215File)); 131 memcpy(&encrypted_tag_data, data.data(), sizeof(NFP::EncryptedNTAG215File));
132 } 132 }
133 133
134 device_state = DeviceState::TagFound; 134 device_state = DeviceState::TagFound;
@@ -137,8 +137,8 @@ bool NfpDevice::LoadAmiibo(std::span<const u8> data) {
137 return true; 137 return true;
138} 138}
139 139
140void NfpDevice::CloseAmiibo() { 140void NfcDevice::CloseNfcTag() {
141 LOG_INFO(Service_NFP, "Remove amiibo"); 141 LOG_INFO(Service_NFC, "Remove nfc tag");
142 142
143 if (device_state == DeviceState::TagMounted) { 143 if (device_state == DeviceState::TagMounted) {
144 Unmount(); 144 Unmount();
@@ -147,26 +147,28 @@ void NfpDevice::CloseAmiibo() {
147 device_state = DeviceState::TagRemoved; 147 device_state = DeviceState::TagRemoved;
148 encrypted_tag_data = {}; 148 encrypted_tag_data = {};
149 tag_data = {}; 149 tag_data = {};
150 mifare_data = {};
150 activate_event->GetReadableEvent().Clear(); 151 activate_event->GetReadableEvent().Clear();
151 deactivate_event->Signal(); 152 deactivate_event->Signal();
152} 153}
153 154
154Kernel::KReadableEvent& NfpDevice::GetActivateEvent() const { 155Kernel::KReadableEvent& NfcDevice::GetActivateEvent() const {
155 return activate_event->GetReadableEvent(); 156 return activate_event->GetReadableEvent();
156} 157}
157 158
158Kernel::KReadableEvent& NfpDevice::GetDeactivateEvent() const { 159Kernel::KReadableEvent& NfcDevice::GetDeactivateEvent() const {
159 return deactivate_event->GetReadableEvent(); 160 return deactivate_event->GetReadableEvent();
160} 161}
161 162
162void NfpDevice::Initialize() { 163void NfcDevice::Initialize() {
163 device_state = npad_device->HasNfc() ? DeviceState::Initialized : DeviceState::Unavailable; 164 device_state = npad_device->HasNfc() ? DeviceState::Initialized : DeviceState::Unavailable;
164 encrypted_tag_data = {}; 165 encrypted_tag_data = {};
165 tag_data = {}; 166 tag_data = {};
167 mifare_data = {};
166 is_initalized = true; 168 is_initalized = true;
167} 169}
168 170
169void NfpDevice::Finalize() { 171void NfcDevice::Finalize() {
170 if (device_state == DeviceState::TagMounted) { 172 if (device_state == DeviceState::TagMounted) {
171 Unmount(); 173 Unmount();
172 } 174 }
@@ -177,17 +179,17 @@ void NfpDevice::Finalize() {
177 is_initalized = false; 179 is_initalized = false;
178} 180}
179 181
180Result NfpDevice::StartDetection(TagProtocol allowed_protocol) { 182Result NfcDevice::StartDetection(NfcProtocol allowed_protocol) {
181 if (device_state != DeviceState::Initialized && device_state != DeviceState::TagRemoved) { 183 if (device_state != DeviceState::Initialized && device_state != DeviceState::TagRemoved) {
182 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state); 184 LOG_ERROR(Service_NFC, "Wrong device state {}", device_state);
183 return WrongDeviceState; 185 return ResultWrongDeviceState;
184 } 186 }
185 187
186 if (npad_device->SetPollingMode(Core::HID::EmulatedDeviceIndex::RightIndex, 188 if (npad_device->SetPollingMode(Core::HID::EmulatedDeviceIndex::RightIndex,
187 Common::Input::PollingMode::NFC) != 189 Common::Input::PollingMode::NFC) !=
188 Common::Input::DriverResult::Success) { 190 Common::Input::DriverResult::Success) {
189 LOG_ERROR(Service_NFP, "Nfc not supported"); 191 LOG_ERROR(Service_NFC, "Nfc not supported");
190 return NfcDisabled; 192 return ResultNfcDisabled;
191 } 193 }
192 194
193 device_state = DeviceState::SearchingForTag; 195 device_state = DeviceState::SearchingForTag;
@@ -195,7 +197,7 @@ Result NfpDevice::StartDetection(TagProtocol allowed_protocol) {
195 return ResultSuccess; 197 return ResultSuccess;
196} 198}
197 199
198Result NfpDevice::StopDetection() { 200Result NfcDevice::StopDetection() {
199 npad_device->SetPollingMode(Core::HID::EmulatedDeviceIndex::RightIndex, 201 npad_device->SetPollingMode(Core::HID::EmulatedDeviceIndex::RightIndex,
200 Common::Input::PollingMode::Active); 202 Common::Input::PollingMode::Active);
201 203
@@ -204,7 +206,7 @@ Result NfpDevice::StopDetection() {
204 } 206 }
205 207
206 if (device_state == DeviceState::TagFound || device_state == DeviceState::TagMounted) { 208 if (device_state == DeviceState::TagFound || device_state == DeviceState::TagMounted) {
207 CloseAmiibo(); 209 CloseNfcTag();
208 } 210 }
209 211
210 if (device_state == DeviceState::SearchingForTag || device_state == DeviceState::TagRemoved) { 212 if (device_state == DeviceState::SearchingForTag || device_state == DeviceState::TagRemoved) {
@@ -212,94 +214,129 @@ Result NfpDevice::StopDetection() {
212 return ResultSuccess; 214 return ResultSuccess;
213 } 215 }
214 216
215 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state); 217 LOG_ERROR(Service_NFC, "Wrong device state {}", device_state);
216 return WrongDeviceState; 218 return ResultWrongDeviceState;
217} 219}
218 220
219Result NfpDevice::Flush() { 221Result NfcDevice::GetTagInfo(NFP::TagInfo& tag_info, bool is_mifare) const {
220 if (device_state != DeviceState::TagMounted) { 222 if (device_state != DeviceState::TagFound && device_state != DeviceState::TagMounted) {
221 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state); 223 LOG_ERROR(Service_NFC, "Wrong device state {}", device_state);
222 if (device_state == DeviceState::TagRemoved) { 224 if (device_state == DeviceState::TagRemoved) {
223 return TagRemoved; 225 return ResultTagRemoved;
224 } 226 }
225 return WrongDeviceState; 227 return ResultWrongDeviceState;
226 } 228 }
227 229
228 if (mount_target == MountTarget::None || mount_target == MountTarget::Rom) { 230 if (is_mifare) {
229 LOG_ERROR(Service_NFP, "Amiibo is read only", device_state); 231 tag_info = {
230 return WrongDeviceState; 232 .uuid = encrypted_tag_data.uuid.uid,
233 .uuid_extension = {},
234 .uuid_length = static_cast<u8>(encrypted_tag_data.uuid.uid.size()),
235 .protocol = NfcProtocol::TypeA,
236 .tag_type = TagType::Type4,
237 };
238 return ResultSuccess;
231 } 239 }
232 240
233 auto& settings = tag_data.settings; 241 // Protocol and tag type may change here
234 242 tag_info = {
235 const auto& current_date = GetAmiiboDate(current_posix_time); 243 .uuid = encrypted_tag_data.uuid.uid,
236 if (settings.write_date.raw_date != current_date.raw_date) { 244 .uuid_extension = {},
237 settings.write_date = current_date; 245 .uuid_length = static_cast<u8>(encrypted_tag_data.uuid.uid.size()),
238 UpdateSettingsCrc(); 246 .protocol = NfcProtocol::TypeA,
239 } 247 .tag_type = TagType::Type2,
248 };
240 249
241 tag_data.write_counter++; 250 return ResultSuccess;
251}
242 252
243 FlushWithBreak(BreakType::Normal); 253Result NfcDevice::ReadMifare(std::span<const MifareReadBlockParameter> parameters,
254 std::span<MifareReadBlockData> read_block_data) const {
255 Result result = ResultSuccess;
244 256
245 is_data_moddified = false; 257 for (std::size_t i = 0; i < parameters.size(); i++) {
258 result = ReadMifare(parameters[i], read_block_data[i]);
259 if (result.IsError()) {
260 break;
261 }
262 }
246 263
247 return ResultSuccess; 264 return result;
248} 265}
249 266
250Result NfpDevice::FlushDebug() { 267Result NfcDevice::ReadMifare(const MifareReadBlockParameter& parameter,
251 if (device_state != DeviceState::TagMounted) { 268 MifareReadBlockData& read_block_data) const {
269 const std::size_t sector_index = parameter.sector_number * sizeof(DataBlock);
270 read_block_data.sector_number = parameter.sector_number;
271
272 if (device_state != DeviceState::TagFound && device_state != DeviceState::TagMounted) {
252 LOG_ERROR(Service_NFC, "Wrong device state {}", device_state); 273 LOG_ERROR(Service_NFC, "Wrong device state {}", device_state);
253 if (device_state == DeviceState::TagRemoved) { 274 if (device_state == DeviceState::TagRemoved) {
254 return TagRemoved; 275 return ResultTagRemoved;
255 } 276 }
256 return WrongDeviceState; 277 return ResultWrongDeviceState;
257 } 278 }
258 279
259 if (mount_target == MountTarget::None || mount_target == MountTarget::Rom) { 280 if (mifare_data.size() < sector_index + sizeof(DataBlock)) {
260 LOG_ERROR(Service_NFC, "Amiibo is read only", device_state); 281 return Mifare::ResultReadError;
261 return WrongDeviceState;
262 } 282 }
263 283
264 tag_data.write_counter++; 284 // TODO: Use parameter.sector_key to read encrypted data
265 285 memcpy(read_block_data.data.data(), mifare_data.data() + sector_index, sizeof(DataBlock));
266 FlushWithBreak(BreakType::Normal);
267
268 is_data_moddified = false;
269 286
270 return ResultSuccess; 287 return ResultSuccess;
271} 288}
272 289
273Result NfpDevice::FlushWithBreak(BreakType break_type) { 290Result NfcDevice::WriteMifare(std::span<const MifareWriteBlockParameter> parameters) {
274 if (break_type != BreakType::Normal) { 291 Result result = ResultSuccess;
275 LOG_ERROR(Service_NFC, "Break type not implemented {}", break_type);
276 return WrongDeviceState;
277 }
278 292
279 std::vector<u8> data(sizeof(EncryptedNTAG215File)); 293 for (std::size_t i = 0; i < parameters.size(); i++) {
280 if (is_plain_amiibo) { 294 result = WriteMifare(parameters[i]);
281 memcpy(data.data(), &tag_data, sizeof(tag_data)); 295 if (result.IsError()) {
282 } else { 296 break;
283 if (!AmiiboCrypto::EncodeAmiibo(tag_data, encrypted_tag_data)) {
284 LOG_ERROR(Service_NFP, "Failed to encode data");
285 return WriteAmiiboFailed;
286 } 297 }
287
288 memcpy(data.data(), &encrypted_tag_data, sizeof(encrypted_tag_data));
289 } 298 }
290 299
291 if (!npad_device->WriteNfc(data)) { 300 if (!npad_device->WriteNfc(mifare_data)) {
292 LOG_ERROR(Service_NFP, "Error writing to file"); 301 LOG_ERROR(Service_NFP, "Error writing to file");
293 return WriteAmiiboFailed; 302 return Mifare::ResultReadError;
303 }
304
305 return result;
306}
307
308Result NfcDevice::WriteMifare(const MifareWriteBlockParameter& parameter) {
309 const std::size_t sector_index = parameter.sector_number * sizeof(DataBlock);
310
311 if (device_state != DeviceState::TagFound && device_state != DeviceState::TagMounted) {
312 LOG_ERROR(Service_NFC, "Wrong device state {}", device_state);
313 if (device_state == DeviceState::TagRemoved) {
314 return ResultTagRemoved;
315 }
316 return ResultWrongDeviceState;
317 }
318
319 if (mifare_data.size() < sector_index + sizeof(DataBlock)) {
320 return Mifare::ResultReadError;
294 } 321 }
295 322
323 // TODO: Use parameter.sector_key to encrypt the data
324 memcpy(mifare_data.data() + sector_index, parameter.data.data(), sizeof(DataBlock));
325
296 return ResultSuccess; 326 return ResultSuccess;
297} 327}
298 328
299Result NfpDevice::Mount(MountTarget mount_target_) { 329Result NfcDevice::SendCommandByPassThrough(const Time::Clock::TimeSpanType& timeout,
330 std::span<const u8> command_data,
331 std::span<u8> out_data) {
332 // Not implemented
333 return ResultSuccess;
334}
335
336Result NfcDevice::Mount(NFP::ModelType model_type, NFP::MountTarget mount_target_) {
300 if (device_state != DeviceState::TagFound) { 337 if (device_state != DeviceState::TagFound) {
301 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state); 338 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state);
302 return WrongDeviceState; 339 return ResultWrongDeviceState;
303 } 340 }
304 341
305 // The loaded amiibo is not encrypted 342 // The loaded amiibo is not encrypted
@@ -309,22 +346,22 @@ Result NfpDevice::Mount(MountTarget mount_target_) {
309 return ResultSuccess; 346 return ResultSuccess;
310 } 347 }
311 348
312 if (!AmiiboCrypto::IsAmiiboValid(encrypted_tag_data)) { 349 if (!NFP::AmiiboCrypto::IsAmiiboValid(encrypted_tag_data)) {
313 LOG_ERROR(Service_NFP, "Not an amiibo"); 350 LOG_ERROR(Service_NFP, "Not an amiibo");
314 return NotAnAmiibo; 351 return ResultNotAnAmiibo;
315 } 352 }
316 353
317 // Mark amiibos as read only when keys are missing 354 // Mark amiibos as read only when keys are missing
318 if (!AmiiboCrypto::IsKeyAvailable()) { 355 if (!NFP::AmiiboCrypto::IsKeyAvailable()) {
319 LOG_ERROR(Service_NFP, "No keys detected"); 356 LOG_ERROR(Service_NFP, "No keys detected");
320 device_state = DeviceState::TagMounted; 357 device_state = DeviceState::TagMounted;
321 mount_target = MountTarget::Rom; 358 mount_target = NFP::MountTarget::Rom;
322 return ResultSuccess; 359 return ResultSuccess;
323 } 360 }
324 361
325 if (!AmiiboCrypto::DecodeAmiibo(encrypted_tag_data, tag_data)) { 362 if (!NFP::AmiiboCrypto::DecodeAmiibo(encrypted_tag_data, tag_data)) {
326 LOG_ERROR(Service_NFP, "Can't decode amiibo {}", device_state); 363 LOG_ERROR(Service_NFP, "Can't decode amiibo {}", device_state);
327 return CorruptedData; 364 return ResultCorruptedData;
328 } 365 }
329 366
330 device_state = DeviceState::TagMounted; 367 device_state = DeviceState::TagMounted;
@@ -332,13 +369,13 @@ Result NfpDevice::Mount(MountTarget mount_target_) {
332 return ResultSuccess; 369 return ResultSuccess;
333} 370}
334 371
335Result NfpDevice::Unmount() { 372Result NfcDevice::Unmount() {
336 if (device_state != DeviceState::TagMounted) { 373 if (device_state != DeviceState::TagMounted) {
337 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state); 374 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state);
338 if (device_state == DeviceState::TagRemoved) { 375 if (device_state == DeviceState::TagRemoved) {
339 return TagRemoved; 376 return ResultTagRemoved;
340 } 377 }
341 return WrongDeviceState; 378 return ResultWrongDeviceState;
342 } 379 }
343 380
344 // Save data before unloading the amiibo 381 // Save data before unloading the amiibo
@@ -347,43 +384,123 @@ Result NfpDevice::Unmount() {
347 } 384 }
348 385
349 device_state = DeviceState::TagFound; 386 device_state = DeviceState::TagFound;
350 mount_target = MountTarget::None; 387 mount_target = NFP::MountTarget::None;
351 is_app_area_open = false; 388 is_app_area_open = false;
352 389
353 return ResultSuccess; 390 return ResultSuccess;
354} 391}
355 392
356Result NfpDevice::GetTagInfo(TagInfo& tag_info) const { 393Result NfcDevice::Flush() {
357 if (device_state != DeviceState::TagFound && device_state != DeviceState::TagMounted) { 394 if (device_state != DeviceState::TagMounted) {
358 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state); 395 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state);
359 if (device_state == DeviceState::TagRemoved) { 396 if (device_state == DeviceState::TagRemoved) {
360 return TagRemoved; 397 return ResultTagRemoved;
361 } 398 }
362 return WrongDeviceState; 399 return ResultWrongDeviceState;
363 } 400 }
364 401
365 tag_info = { 402 if (mount_target == NFP::MountTarget::None || mount_target == NFP::MountTarget::Rom) {
366 .uuid = encrypted_tag_data.uuid.uid, 403 LOG_ERROR(Service_NFP, "Amiibo is read only", device_state);
367 .uuid_length = static_cast<u8>(encrypted_tag_data.uuid.uid.size()), 404 return ResultWrongDeviceState;
368 .protocol = TagProtocol::TypeA, 405 }
369 .tag_type = TagType::Type2, 406
370 }; 407 auto& settings = tag_data.settings;
408
409 const auto& current_date = GetAmiiboDate(current_posix_time);
410 if (settings.write_date.raw_date != current_date.raw_date) {
411 settings.write_date = current_date;
412 UpdateSettingsCrc();
413 }
414
415 tag_data.write_counter++;
416
417 FlushWithBreak(NFP::BreakType::Normal);
418
419 is_data_moddified = false;
371 420
372 return ResultSuccess; 421 return ResultSuccess;
373} 422}
374 423
375Result NfpDevice::GetCommonInfo(CommonInfo& common_info) const { 424Result NfcDevice::FlushDebug() {
425 if (device_state != DeviceState::TagMounted) {
426 LOG_ERROR(Service_NFC, "Wrong device state {}", device_state);
427 if (device_state == DeviceState::TagRemoved) {
428 return ResultTagRemoved;
429 }
430 return ResultWrongDeviceState;
431 }
432
433 if (mount_target == NFP::MountTarget::None || mount_target == NFP::MountTarget::Rom) {
434 LOG_ERROR(Service_NFC, "Amiibo is read only", device_state);
435 return ResultWrongDeviceState;
436 }
437
438 tag_data.write_counter++;
439
440 FlushWithBreak(NFP::BreakType::Normal);
441
442 is_data_moddified = false;
443
444 return ResultSuccess;
445}
446
447Result NfcDevice::FlushWithBreak(NFP::BreakType break_type) {
448 if (break_type != NFP::BreakType::Normal) {
449 LOG_ERROR(Service_NFC, "Break type not implemented {}", break_type);
450 return ResultWrongDeviceState;
451 }
452
453 std::vector<u8> data(sizeof(NFP::EncryptedNTAG215File));
454 if (is_plain_amiibo) {
455 memcpy(data.data(), &tag_data, sizeof(tag_data));
456 } else {
457 if (!NFP::AmiiboCrypto::EncodeAmiibo(tag_data, encrypted_tag_data)) {
458 LOG_ERROR(Service_NFP, "Failed to encode data");
459 return ResultWriteAmiiboFailed;
460 }
461
462 memcpy(data.data(), &encrypted_tag_data, sizeof(encrypted_tag_data));
463 }
464
465 if (!npad_device->WriteNfc(data)) {
466 LOG_ERROR(Service_NFP, "Error writing to file");
467 return ResultWriteAmiiboFailed;
468 }
469
470 return ResultSuccess;
471}
472
473Result NfcDevice::Restore() {
474 if (device_state != DeviceState::TagMounted) {
475 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state);
476 if (device_state == DeviceState::TagRemoved) {
477 return ResultTagRemoved;
478 }
479 return ResultWrongDeviceState;
480 }
481
482 if (mount_target == NFP::MountTarget::None || mount_target == NFP::MountTarget::Rom) {
483 LOG_ERROR(Service_NFC, "Amiibo is read only", device_state);
484 return ResultWrongDeviceState;
485 }
486
487 // TODO: Load amiibo from backup on system
488 LOG_ERROR(Service_NFP, "Not Implemented");
489 return ResultSuccess;
490}
491
492Result NfcDevice::GetCommonInfo(NFP::CommonInfo& common_info) const {
376 if (device_state != DeviceState::TagMounted) { 493 if (device_state != DeviceState::TagMounted) {
377 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state); 494 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state);
378 if (device_state == DeviceState::TagRemoved) { 495 if (device_state == DeviceState::TagRemoved) {
379 return TagRemoved; 496 return ResultTagRemoved;
380 } 497 }
381 return WrongDeviceState; 498 return ResultWrongDeviceState;
382 } 499 }
383 500
384 if (mount_target == MountTarget::None || mount_target == MountTarget::Rom) { 501 if (mount_target == NFP::MountTarget::None || mount_target == NFP::MountTarget::Rom) {
385 LOG_ERROR(Service_NFP, "Amiibo is read only", device_state); 502 LOG_ERROR(Service_NFP, "Amiibo is read only", device_state);
386 return WrongDeviceState; 503 return ResultWrongDeviceState;
387 } 504 }
388 505
389 const auto& settings = tag_data.settings; 506 const auto& settings = tag_data.settings;
@@ -393,18 +510,18 @@ Result NfpDevice::GetCommonInfo(CommonInfo& common_info) const {
393 .last_write_date = settings.write_date.GetWriteDate(), 510 .last_write_date = settings.write_date.GetWriteDate(),
394 .write_counter = tag_data.write_counter, 511 .write_counter = tag_data.write_counter,
395 .version = tag_data.amiibo_version, 512 .version = tag_data.amiibo_version,
396 .application_area_size = sizeof(ApplicationArea), 513 .application_area_size = sizeof(NFP::ApplicationArea),
397 }; 514 };
398 return ResultSuccess; 515 return ResultSuccess;
399} 516}
400 517
401Result NfpDevice::GetModelInfo(ModelInfo& model_info) const { 518Result NfcDevice::GetModelInfo(NFP::ModelInfo& model_info) const {
402 if (device_state != DeviceState::TagMounted) { 519 if (device_state != DeviceState::TagMounted) {
403 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state); 520 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state);
404 if (device_state == DeviceState::TagRemoved) { 521 if (device_state == DeviceState::TagRemoved) {
405 return TagRemoved; 522 return ResultTagRemoved;
406 } 523 }
407 return WrongDeviceState; 524 return ResultWrongDeviceState;
408 } 525 }
409 526
410 const auto& model_info_data = encrypted_tag_data.user_memory.model_info; 527 const auto& model_info_data = encrypted_tag_data.user_memory.model_info;
@@ -418,22 +535,22 @@ Result NfpDevice::GetModelInfo(ModelInfo& model_info) const {
418 return ResultSuccess; 535 return ResultSuccess;
419} 536}
420 537
421Result NfpDevice::GetRegisterInfo(RegisterInfo& register_info) const { 538Result NfcDevice::GetRegisterInfo(NFP::RegisterInfo& register_info) const {
422 if (device_state != DeviceState::TagMounted) { 539 if (device_state != DeviceState::TagMounted) {
423 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state); 540 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state);
424 if (device_state == DeviceState::TagRemoved) { 541 if (device_state == DeviceState::TagRemoved) {
425 return TagRemoved; 542 return ResultTagRemoved;
426 } 543 }
427 return WrongDeviceState; 544 return ResultWrongDeviceState;
428 } 545 }
429 546
430 if (mount_target == MountTarget::None || mount_target == MountTarget::Rom) { 547 if (mount_target == NFP::MountTarget::None || mount_target == NFP::MountTarget::Rom) {
431 LOG_ERROR(Service_NFP, "Amiibo is read only", device_state); 548 LOG_ERROR(Service_NFP, "Amiibo is read only", device_state);
432 return WrongDeviceState; 549 return ResultWrongDeviceState;
433 } 550 }
434 551
435 if (tag_data.settings.settings.amiibo_initialized == 0) { 552 if (tag_data.settings.settings.amiibo_initialized == 0) {
436 return RegistrationIsNotInitialized; 553 return ResultRegistrationIsNotInitialized;
437 } 554 }
438 555
439 Service::Mii::MiiManager manager; 556 Service::Mii::MiiManager manager;
@@ -450,22 +567,22 @@ Result NfpDevice::GetRegisterInfo(RegisterInfo& register_info) const {
450 return ResultSuccess; 567 return ResultSuccess;
451} 568}
452 569
453Result NfpDevice::GetRegisterInfoPrivate(RegisterInfoPrivate& register_info) const { 570Result NfcDevice::GetRegisterInfoPrivate(NFP::RegisterInfoPrivate& register_info) const {
454 if (device_state != DeviceState::TagMounted) { 571 if (device_state != DeviceState::TagMounted) {
455 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state); 572 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state);
456 if (device_state == DeviceState::TagRemoved) { 573 if (device_state == DeviceState::TagRemoved) {
457 return TagRemoved; 574 return ResultTagRemoved;
458 } 575 }
459 return WrongDeviceState; 576 return ResultWrongDeviceState;
460 } 577 }
461 578
462 if (mount_target == MountTarget::None || mount_target == MountTarget::Rom) { 579 if (mount_target == NFP::MountTarget::None || mount_target == NFP::MountTarget::Rom) {
463 LOG_ERROR(Service_NFP, "Amiibo is read only", device_state); 580 LOG_ERROR(Service_NFP, "Amiibo is read only", device_state);
464 return WrongDeviceState; 581 return ResultWrongDeviceState;
465 } 582 }
466 583
467 if (tag_data.settings.settings.amiibo_initialized == 0) { 584 if (tag_data.settings.settings.amiibo_initialized == 0) {
468 return RegistrationIsNotInitialized; 585 return ResultRegistrationIsNotInitialized;
469 } 586 }
470 587
471 Service::Mii::MiiManager manager; 588 Service::Mii::MiiManager manager;
@@ -482,18 +599,18 @@ Result NfpDevice::GetRegisterInfoPrivate(RegisterInfoPrivate& register_info) con
482 return ResultSuccess; 599 return ResultSuccess;
483} 600}
484 601
485Result NfpDevice::GetAdminInfo(AdminInfo& admin_info) const { 602Result NfcDevice::GetAdminInfo(NFP::AdminInfo& admin_info) const {
486 if (device_state != DeviceState::TagMounted) { 603 if (device_state != DeviceState::TagMounted) {
487 LOG_ERROR(Service_NFC, "Wrong device state {}", device_state); 604 LOG_ERROR(Service_NFC, "Wrong device state {}", device_state);
488 if (device_state == DeviceState::TagRemoved) { 605 if (device_state == DeviceState::TagRemoved) {
489 return TagRemoved; 606 return ResultTagRemoved;
490 } 607 }
491 return WrongDeviceState; 608 return ResultWrongDeviceState;
492 } 609 }
493 610
494 if (mount_target == MountTarget::None || mount_target == MountTarget::Rom) { 611 if (mount_target == NFP::MountTarget::None || mount_target == NFP::MountTarget::Rom) {
495 LOG_ERROR(Service_NFC, "Amiibo is read only", device_state); 612 LOG_ERROR(Service_NFC, "Amiibo is read only", device_state);
496 return WrongDeviceState; 613 return ResultWrongDeviceState;
497 } 614 }
498 615
499 u8 flags = static_cast<u8>(tag_data.settings.settings.raw >> 0x4); 616 u8 flags = static_cast<u8>(tag_data.settings.settings.raw >> 0x4);
@@ -503,17 +620,18 @@ Result NfpDevice::GetAdminInfo(AdminInfo& admin_info) const {
503 620
504 u64 application_id = 0; 621 u64 application_id = 0;
505 u32 application_area_id = 0; 622 u32 application_area_id = 0;
506 AppAreaVersion app_area_version = AppAreaVersion::NotSet; 623 NFP::AppAreaVersion app_area_version = NFP::AppAreaVersion::NotSet;
507 if (tag_data.settings.settings.appdata_initialized != 0) { 624 if (tag_data.settings.settings.appdata_initialized != 0) {
508 application_id = tag_data.application_id; 625 application_id = tag_data.application_id;
509 app_area_version = 626 app_area_version = static_cast<NFP::AppAreaVersion>(
510 static_cast<AppAreaVersion>(application_id >> application_id_version_offset & 0xf); 627 application_id >> NFP::application_id_version_offset & 0xf);
511 628
512 // Restore application id to original value 629 // Restore application id to original value
513 if (application_id >> 0x38 != 0) { 630 if (application_id >> 0x38 != 0) {
514 const u8 application_byte = tag_data.application_id_byte & 0xf; 631 const u8 application_byte = tag_data.application_id_byte & 0xf;
515 application_id = RemoveVersionByte(application_id) | 632 application_id =
516 (static_cast<u64>(application_byte) << application_id_version_offset); 633 RemoveVersionByte(application_id) |
634 (static_cast<u64>(application_byte) << NFP::application_id_version_offset);
517 } 635 }
518 636
519 application_area_id = tag_data.application_area_id; 637 application_area_id = tag_data.application_area_id;
@@ -532,22 +650,22 @@ Result NfpDevice::GetAdminInfo(AdminInfo& admin_info) const {
532 return ResultSuccess; 650 return ResultSuccess;
533} 651}
534 652
535Result NfpDevice::DeleteRegisterInfo() { 653Result NfcDevice::DeleteRegisterInfo() {
536 if (device_state != DeviceState::TagMounted) { 654 if (device_state != DeviceState::TagMounted) {
537 LOG_ERROR(Service_NFC, "Wrong device state {}", device_state); 655 LOG_ERROR(Service_NFC, "Wrong device state {}", device_state);
538 if (device_state == DeviceState::TagRemoved) { 656 if (device_state == DeviceState::TagRemoved) {
539 return TagRemoved; 657 return ResultTagRemoved;
540 } 658 }
541 return WrongDeviceState; 659 return ResultWrongDeviceState;
542 } 660 }
543 661
544 if (mount_target == MountTarget::None || mount_target == MountTarget::Rom) { 662 if (mount_target == NFP::MountTarget::None || mount_target == NFP::MountTarget::Rom) {
545 LOG_ERROR(Service_NFC, "Amiibo is read only", device_state); 663 LOG_ERROR(Service_NFC, "Amiibo is read only", device_state);
546 return WrongDeviceState; 664 return ResultWrongDeviceState;
547 } 665 }
548 666
549 if (tag_data.settings.settings.amiibo_initialized == 0) { 667 if (tag_data.settings.settings.amiibo_initialized == 0) {
550 return RegistrationIsNotInitialized; 668 return ResultRegistrationIsNotInitialized;
551 } 669 }
552 670
553 Common::TinyMT rng{}; 671 Common::TinyMT rng{};
@@ -564,18 +682,18 @@ Result NfpDevice::DeleteRegisterInfo() {
564 return Flush(); 682 return Flush();
565} 683}
566 684
567Result NfpDevice::SetRegisterInfoPrivate(const AmiiboName& amiibo_name) { 685Result NfcDevice::SetRegisterInfoPrivate(const NFP::RegisterInfoPrivate& register_info) {
568 if (device_state != DeviceState::TagMounted) { 686 if (device_state != DeviceState::TagMounted) {
569 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state); 687 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state);
570 if (device_state == DeviceState::TagRemoved) { 688 if (device_state == DeviceState::TagRemoved) {
571 return TagRemoved; 689 return ResultTagRemoved;
572 } 690 }
573 return WrongDeviceState; 691 return ResultWrongDeviceState;
574 } 692 }
575 693
576 if (mount_target == MountTarget::None || mount_target == MountTarget::Rom) { 694 if (mount_target == NFP::MountTarget::None || mount_target == NFP::MountTarget::Rom) {
577 LOG_ERROR(Service_NFP, "Amiibo is read only", device_state); 695 LOG_ERROR(Service_NFP, "Amiibo is read only", device_state);
578 return WrongDeviceState; 696 return ResultWrongDeviceState;
579 } 697 }
580 698
581 Service::Mii::MiiManager manager; 699 Service::Mii::MiiManager manager;
@@ -587,7 +705,7 @@ Result NfpDevice::SetRegisterInfoPrivate(const AmiiboName& amiibo_name) {
587 settings.write_date.raw_date = 0; 705 settings.write_date.raw_date = 0;
588 } 706 }
589 707
590 SetAmiiboName(settings, amiibo_name); 708 SetAmiiboName(settings, register_info.amiibo_name);
591 tag_data.owner_mii = manager.BuildFromStoreData(mii); 709 tag_data.owner_mii = manager.BuildFromStoreData(mii);
592 tag_data.mii_extension = manager.SetFromStoreData(mii); 710 tag_data.mii_extension = manager.SetFromStoreData(mii);
593 tag_data.unknown = 0; 711 tag_data.unknown = 0;
@@ -601,18 +719,18 @@ Result NfpDevice::SetRegisterInfoPrivate(const AmiiboName& amiibo_name) {
601 return Flush(); 719 return Flush();
602} 720}
603 721
604Result NfpDevice::RestoreAmiibo() { 722Result NfcDevice::RestoreAmiibo() {
605 if (device_state != DeviceState::TagMounted) { 723 if (device_state != DeviceState::TagMounted) {
606 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state); 724 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state);
607 if (device_state == DeviceState::TagRemoved) { 725 if (device_state == DeviceState::TagRemoved) {
608 return TagRemoved; 726 return ResultTagRemoved;
609 } 727 }
610 return WrongDeviceState; 728 return ResultWrongDeviceState;
611 } 729 }
612 730
613 if (mount_target == MountTarget::None || mount_target == MountTarget::Rom) { 731 if (mount_target == NFP::MountTarget::None || mount_target == NFP::MountTarget::Rom) {
614 LOG_ERROR(Service_NFP, "Amiibo is read only", device_state); 732 LOG_ERROR(Service_NFP, "Amiibo is read only", device_state);
615 return WrongDeviceState; 733 return ResultWrongDeviceState;
616 } 734 }
617 735
618 // TODO: Load amiibo from backup on system 736 // TODO: Load amiibo from backup on system
@@ -620,7 +738,7 @@ Result NfpDevice::RestoreAmiibo() {
620 return ResultSuccess; 738 return ResultSuccess;
621} 739}
622 740
623Result NfpDevice::Format() { 741Result NfcDevice::Format() {
624 auto result1 = DeleteApplicationArea(); 742 auto result1 = DeleteApplicationArea();
625 auto result2 = DeleteRegisterInfo(); 743 auto result2 = DeleteRegisterInfo();
626 744
@@ -635,28 +753,28 @@ Result NfpDevice::Format() {
635 return Flush(); 753 return Flush();
636} 754}
637 755
638Result NfpDevice::OpenApplicationArea(u32 access_id) { 756Result NfcDevice::OpenApplicationArea(u32 access_id) {
639 if (device_state != DeviceState::TagMounted) { 757 if (device_state != DeviceState::TagMounted) {
640 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state); 758 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state);
641 if (device_state == DeviceState::TagRemoved) { 759 if (device_state == DeviceState::TagRemoved) {
642 return TagRemoved; 760 return ResultTagRemoved;
643 } 761 }
644 return WrongDeviceState; 762 return ResultWrongDeviceState;
645 } 763 }
646 764
647 if (mount_target == MountTarget::None || mount_target == MountTarget::Rom) { 765 if (mount_target == NFP::MountTarget::None || mount_target == NFP::MountTarget::Rom) {
648 LOG_ERROR(Service_NFP, "Amiibo is read only", device_state); 766 LOG_ERROR(Service_NFP, "Amiibo is read only", device_state);
649 return WrongDeviceState; 767 return ResultWrongDeviceState;
650 } 768 }
651 769
652 if (tag_data.settings.settings.appdata_initialized.Value() == 0) { 770 if (tag_data.settings.settings.appdata_initialized.Value() == 0) {
653 LOG_WARNING(Service_NFP, "Application area is not initialized"); 771 LOG_WARNING(Service_NFP, "Application area is not initialized");
654 return ApplicationAreaIsNotInitialized; 772 return ResultApplicationAreaIsNotInitialized;
655 } 773 }
656 774
657 if (tag_data.application_area_id != access_id) { 775 if (tag_data.application_area_id != access_id) {
658 LOG_WARNING(Service_NFP, "Wrong application area id"); 776 LOG_WARNING(Service_NFP, "Wrong application area id");
659 return WrongApplicationAreaId; 777 return ResultWrongApplicationAreaId;
660 } 778 }
661 779
662 is_app_area_open = true; 780 is_app_area_open = true;
@@ -664,25 +782,25 @@ Result NfpDevice::OpenApplicationArea(u32 access_id) {
664 return ResultSuccess; 782 return ResultSuccess;
665} 783}
666 784
667Result NfpDevice::GetApplicationAreaId(u32& application_area_id) const { 785Result NfcDevice::GetApplicationAreaId(u32& application_area_id) const {
668 application_area_id = {}; 786 application_area_id = {};
669 787
670 if (device_state != DeviceState::TagMounted) { 788 if (device_state != DeviceState::TagMounted) {
671 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state); 789 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state);
672 if (device_state == DeviceState::TagRemoved) { 790 if (device_state == DeviceState::TagRemoved) {
673 return TagRemoved; 791 return ResultTagRemoved;
674 } 792 }
675 return WrongDeviceState; 793 return ResultWrongDeviceState;
676 } 794 }
677 795
678 if (mount_target == MountTarget::None || mount_target == MountTarget::Rom) { 796 if (mount_target == NFP::MountTarget::None || mount_target == NFP::MountTarget::Rom) {
679 LOG_ERROR(Service_NFP, "Amiibo is read only", device_state); 797 LOG_ERROR(Service_NFP, "Amiibo is read only", device_state);
680 return WrongDeviceState; 798 return ResultWrongDeviceState;
681 } 799 }
682 800
683 if (tag_data.settings.settings.appdata_initialized.Value() == 0) { 801 if (tag_data.settings.settings.appdata_initialized.Value() == 0) {
684 LOG_WARNING(Service_NFP, "Application area is not initialized"); 802 LOG_WARNING(Service_NFP, "Application area is not initialized");
685 return ApplicationAreaIsNotInitialized; 803 return ResultApplicationAreaIsNotInitialized;
686 } 804 }
687 805
688 application_area_id = tag_data.application_area_id; 806 application_area_id = tag_data.application_area_id;
@@ -690,64 +808,61 @@ Result NfpDevice::GetApplicationAreaId(u32& application_area_id) const {
690 return ResultSuccess; 808 return ResultSuccess;
691} 809}
692 810
693Result NfpDevice::GetApplicationArea(std::vector<u8>& data) const { 811Result NfcDevice::GetApplicationArea(std::span<u8> data) const {
694 if (device_state != DeviceState::TagMounted) { 812 if (device_state != DeviceState::TagMounted) {
695 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state); 813 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state);
696 if (device_state == DeviceState::TagRemoved) { 814 if (device_state == DeviceState::TagRemoved) {
697 return TagRemoved; 815 return ResultTagRemoved;
698 } 816 }
699 return WrongDeviceState; 817 return ResultWrongDeviceState;
700 } 818 }
701 819
702 if (mount_target == MountTarget::None || mount_target == MountTarget::Rom) { 820 if (mount_target == NFP::MountTarget::None || mount_target == NFP::MountTarget::Rom) {
703 LOG_ERROR(Service_NFP, "Amiibo is read only", device_state); 821 LOG_ERROR(Service_NFP, "Amiibo is read only", device_state);
704 return WrongDeviceState; 822 return ResultWrongDeviceState;
705 } 823 }
706 824
707 if (!is_app_area_open) { 825 if (!is_app_area_open) {
708 LOG_ERROR(Service_NFP, "Application area is not open"); 826 LOG_ERROR(Service_NFP, "Application area is not open");
709 return WrongDeviceState; 827 return ResultWrongDeviceState;
710 } 828 }
711 829
712 if (tag_data.settings.settings.appdata_initialized.Value() == 0) { 830 if (tag_data.settings.settings.appdata_initialized.Value() == 0) {
713 LOG_ERROR(Service_NFP, "Application area is not initialized"); 831 LOG_ERROR(Service_NFP, "Application area is not initialized");
714 return ApplicationAreaIsNotInitialized; 832 return ResultApplicationAreaIsNotInitialized;
715 }
716
717 if (data.size() > sizeof(ApplicationArea)) {
718 data.resize(sizeof(ApplicationArea));
719 } 833 }
720 834
721 memcpy(data.data(), tag_data.application_area.data(), data.size()); 835 memcpy(data.data(), tag_data.application_area.data(),
836 std::min(data.size(), sizeof(NFP::ApplicationArea)));
722 837
723 return ResultSuccess; 838 return ResultSuccess;
724} 839}
725 840
726Result NfpDevice::SetApplicationArea(std::span<const u8> data) { 841Result NfcDevice::SetApplicationArea(std::span<const u8> data) {
727 if (device_state != DeviceState::TagMounted) { 842 if (device_state != DeviceState::TagMounted) {
728 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state); 843 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state);
729 if (device_state == DeviceState::TagRemoved) { 844 if (device_state == DeviceState::TagRemoved) {
730 return TagRemoved; 845 return ResultTagRemoved;
731 } 846 }
732 return WrongDeviceState; 847 return ResultWrongDeviceState;
733 } 848 }
734 849
735 if (mount_target == MountTarget::None || mount_target == MountTarget::Rom) { 850 if (mount_target == NFP::MountTarget::None || mount_target == NFP::MountTarget::Rom) {
736 LOG_ERROR(Service_NFP, "Amiibo is read only", device_state); 851 LOG_ERROR(Service_NFP, "Amiibo is read only", device_state);
737 return WrongDeviceState; 852 return ResultWrongDeviceState;
738 } 853 }
739 854
740 if (!is_app_area_open) { 855 if (!is_app_area_open) {
741 LOG_ERROR(Service_NFP, "Application area is not open"); 856 LOG_ERROR(Service_NFP, "Application area is not open");
742 return WrongDeviceState; 857 return ResultWrongDeviceState;
743 } 858 }
744 859
745 if (tag_data.settings.settings.appdata_initialized.Value() == 0) { 860 if (tag_data.settings.settings.appdata_initialized.Value() == 0) {
746 LOG_ERROR(Service_NFP, "Application area is not initialized"); 861 LOG_ERROR(Service_NFP, "Application area is not initialized");
747 return ApplicationAreaIsNotInitialized; 862 return ResultApplicationAreaIsNotInitialized;
748 } 863 }
749 864
750 if (data.size() > sizeof(ApplicationArea)) { 865 if (data.size() > sizeof(NFP::ApplicationArea)) {
751 LOG_ERROR(Service_NFP, "Wrong data size {}", data.size()); 866 LOG_ERROR(Service_NFP, "Wrong data size {}", data.size());
752 return ResultUnknown; 867 return ResultUnknown;
753 } 868 }
@@ -756,9 +871,9 @@ Result NfpDevice::SetApplicationArea(std::span<const u8> data) {
756 std::memcpy(tag_data.application_area.data(), data.data(), data.size()); 871 std::memcpy(tag_data.application_area.data(), data.data(), data.size());
757 // Fill remaining data with random numbers 872 // Fill remaining data with random numbers
758 rng.GenerateRandomBytes(tag_data.application_area.data() + data.size(), 873 rng.GenerateRandomBytes(tag_data.application_area.data() + data.size(),
759 sizeof(ApplicationArea) - data.size()); 874 sizeof(NFP::ApplicationArea) - data.size());
760 875
761 if (tag_data.application_write_counter != counter_limit) { 876 if (tag_data.application_write_counter != NFP::counter_limit) {
762 tag_data.application_write_counter++; 877 tag_data.application_write_counter++;
763 } 878 }
764 879
@@ -767,64 +882,64 @@ Result NfpDevice::SetApplicationArea(std::span<const u8> data) {
767 return ResultSuccess; 882 return ResultSuccess;
768} 883}
769 884
770Result NfpDevice::CreateApplicationArea(u32 access_id, std::span<const u8> data) { 885Result NfcDevice::CreateApplicationArea(u32 access_id, std::span<const u8> data) {
771 if (device_state != DeviceState::TagMounted) { 886 if (device_state != DeviceState::TagMounted) {
772 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state); 887 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state);
773 if (device_state == DeviceState::TagRemoved) { 888 if (device_state == DeviceState::TagRemoved) {
774 return TagRemoved; 889 return ResultTagRemoved;
775 } 890 }
776 return WrongDeviceState; 891 return ResultWrongDeviceState;
777 } 892 }
778 893
779 if (tag_data.settings.settings.appdata_initialized.Value() != 0) { 894 if (tag_data.settings.settings.appdata_initialized.Value() != 0) {
780 LOG_ERROR(Service_NFP, "Application area already exist"); 895 LOG_ERROR(Service_NFP, "Application area already exist");
781 return ApplicationAreaExist; 896 return ResultApplicationAreaExist;
782 } 897 }
783 898
784 return RecreateApplicationArea(access_id, data); 899 return RecreateApplicationArea(access_id, data);
785} 900}
786 901
787Result NfpDevice::RecreateApplicationArea(u32 access_id, std::span<const u8> data) { 902Result NfcDevice::RecreateApplicationArea(u32 access_id, std::span<const u8> data) {
788 if (device_state != DeviceState::TagMounted) { 903 if (device_state != DeviceState::TagMounted) {
789 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state); 904 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state);
790 if (device_state == DeviceState::TagRemoved) { 905 if (device_state == DeviceState::TagRemoved) {
791 return TagRemoved; 906 return ResultTagRemoved;
792 } 907 }
793 return WrongDeviceState; 908 return ResultWrongDeviceState;
794 } 909 }
795 910
796 if (is_app_area_open) { 911 if (is_app_area_open) {
797 LOG_ERROR(Service_NFP, "Application area is open"); 912 LOG_ERROR(Service_NFP, "Application area is open");
798 return WrongDeviceState; 913 return ResultWrongDeviceState;
799 } 914 }
800 915
801 if (mount_target == MountTarget::None || mount_target == MountTarget::Rom) { 916 if (mount_target == NFP::MountTarget::None || mount_target == NFP::MountTarget::Rom) {
802 LOG_ERROR(Service_NFP, "Amiibo is read only", device_state); 917 LOG_ERROR(Service_NFP, "Amiibo is read only", device_state);
803 return WrongDeviceState; 918 return ResultWrongDeviceState;
804 } 919 }
805 920
806 if (data.size() > sizeof(ApplicationArea)) { 921 if (data.size() > sizeof(NFP::ApplicationArea)) {
807 LOG_ERROR(Service_NFP, "Wrong data size {}", data.size()); 922 LOG_ERROR(Service_NFP, "Wrong data size {}", data.size());
808 return WrongApplicationAreaSize; 923 return ResultWrongApplicationAreaSize;
809 } 924 }
810 925
811 Common::TinyMT rng{}; 926 Common::TinyMT rng{};
812 std::memcpy(tag_data.application_area.data(), data.data(), data.size()); 927 std::memcpy(tag_data.application_area.data(), data.data(), data.size());
813 // Fill remaining data with random numbers 928 // Fill remaining data with random numbers
814 rng.GenerateRandomBytes(tag_data.application_area.data() + data.size(), 929 rng.GenerateRandomBytes(tag_data.application_area.data() + data.size(),
815 sizeof(ApplicationArea) - data.size()); 930 sizeof(NFP::ApplicationArea) - data.size());
816 931
817 if (tag_data.application_write_counter != counter_limit) { 932 if (tag_data.application_write_counter != NFP::counter_limit) {
818 tag_data.application_write_counter++; 933 tag_data.application_write_counter++;
819 } 934 }
820 935
821 const u64 application_id = system.GetApplicationProcessProgramID(); 936 const u64 application_id = system.GetApplicationProcessProgramID();
822 937
823 tag_data.application_id_byte = 938 tag_data.application_id_byte =
824 static_cast<u8>(application_id >> application_id_version_offset & 0xf); 939 static_cast<u8>(application_id >> NFP::application_id_version_offset & 0xf);
825 tag_data.application_id = 940 tag_data.application_id =
826 RemoveVersionByte(application_id) | 941 RemoveVersionByte(application_id) | (static_cast<u64>(NFP::AppAreaVersion::NintendoSwitch)
827 (static_cast<u64>(AppAreaVersion::NintendoSwitch) << application_id_version_offset); 942 << NFP::application_id_version_offset);
828 tag_data.settings.settings.appdata_initialized.Assign(1); 943 tag_data.settings.settings.appdata_initialized.Assign(1);
829 tag_data.application_area_id = access_id; 944 tag_data.application_area_id = access_id;
830 tag_data.unknown = {}; 945 tag_data.unknown = {};
@@ -835,30 +950,30 @@ Result NfpDevice::RecreateApplicationArea(u32 access_id, std::span<const u8> dat
835 return Flush(); 950 return Flush();
836} 951}
837 952
838Result NfpDevice::DeleteApplicationArea() { 953Result NfcDevice::DeleteApplicationArea() {
839 if (device_state != DeviceState::TagMounted) { 954 if (device_state != DeviceState::TagMounted) {
840 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state); 955 LOG_ERROR(Service_NFP, "Wrong device state {}", device_state);
841 if (device_state == DeviceState::TagRemoved) { 956 if (device_state == DeviceState::TagRemoved) {
842 return TagRemoved; 957 return ResultTagRemoved;
843 } 958 }
844 return WrongDeviceState; 959 return ResultWrongDeviceState;
845 } 960 }
846 961
847 if (mount_target == MountTarget::None || mount_target == MountTarget::Rom) { 962 if (mount_target == NFP::MountTarget::None || mount_target == NFP::MountTarget::Rom) {
848 LOG_ERROR(Service_NFP, "Amiibo is read only", device_state); 963 LOG_ERROR(Service_NFP, "Amiibo is read only", device_state);
849 return WrongDeviceState; 964 return ResultWrongDeviceState;
850 } 965 }
851 966
852 if (tag_data.settings.settings.appdata_initialized == 0) { 967 if (tag_data.settings.settings.appdata_initialized == 0) {
853 return ApplicationAreaIsNotInitialized; 968 return ResultApplicationAreaIsNotInitialized;
854 } 969 }
855 970
856 if (tag_data.application_write_counter != counter_limit) { 971 if (tag_data.application_write_counter != NFP::counter_limit) {
857 tag_data.application_write_counter++; 972 tag_data.application_write_counter++;
858 } 973 }
859 974
860 Common::TinyMT rng{}; 975 Common::TinyMT rng{};
861 rng.GenerateRandomBytes(tag_data.application_area.data(), sizeof(ApplicationArea)); 976 rng.GenerateRandomBytes(tag_data.application_area.data(), sizeof(NFP::ApplicationArea));
862 rng.GenerateRandomBytes(&tag_data.application_id, sizeof(u64)); 977 rng.GenerateRandomBytes(&tag_data.application_id, sizeof(u64));
863 rng.GenerateRandomBytes(&tag_data.application_area_id, sizeof(u32)); 978 rng.GenerateRandomBytes(&tag_data.application_area_id, sizeof(u32));
864 rng.GenerateRandomBytes(&tag_data.application_id_byte, sizeof(u8)); 979 rng.GenerateRandomBytes(&tag_data.application_id_byte, sizeof(u8));
@@ -872,18 +987,18 @@ Result NfpDevice::DeleteApplicationArea() {
872 return Flush(); 987 return Flush();
873} 988}
874 989
875Result NfpDevice::ExistApplicationArea(bool& has_application_area) { 990Result NfcDevice::ExistsApplicationArea(bool& has_application_area) const {
876 if (device_state != DeviceState::TagMounted) { 991 if (device_state != DeviceState::TagMounted) {
877 LOG_ERROR(Service_NFC, "Wrong device state {}", device_state); 992 LOG_ERROR(Service_NFC, "Wrong device state {}", device_state);
878 if (device_state == DeviceState::TagRemoved) { 993 if (device_state == DeviceState::TagRemoved) {
879 return TagRemoved; 994 return ResultTagRemoved;
880 } 995 }
881 return WrongDeviceState; 996 return ResultWrongDeviceState;
882 } 997 }
883 998
884 if (mount_target == MountTarget::None || mount_target == MountTarget::Rom) { 999 if (mount_target == NFP::MountTarget::None || mount_target == NFP::MountTarget::Rom) {
885 LOG_ERROR(Service_NFC, "Amiibo is read only", device_state); 1000 LOG_ERROR(Service_NFC, "Amiibo is read only", device_state);
886 return WrongDeviceState; 1001 return ResultWrongDeviceState;
887 } 1002 }
888 1003
889 has_application_area = tag_data.settings.settings.appdata_initialized.Value() != 0; 1004 has_application_area = tag_data.settings.settings.appdata_initialized.Value() != 0;
@@ -891,21 +1006,21 @@ Result NfpDevice::ExistApplicationArea(bool& has_application_area) {
891 return ResultSuccess; 1006 return ResultSuccess;
892} 1007}
893 1008
894Result NfpDevice::GetAll(NfpData& data) const { 1009Result NfcDevice::GetAll(NFP::NfpData& data) const {
895 if (device_state != DeviceState::TagMounted) { 1010 if (device_state != DeviceState::TagMounted) {
896 LOG_ERROR(Service_NFC, "Wrong device state {}", device_state); 1011 LOG_ERROR(Service_NFC, "Wrong device state {}", device_state);
897 if (device_state == DeviceState::TagRemoved) { 1012 if (device_state == DeviceState::TagRemoved) {
898 return TagRemoved; 1013 return ResultTagRemoved;
899 } 1014 }
900 return WrongDeviceState; 1015 return ResultWrongDeviceState;
901 } 1016 }
902 1017
903 if (mount_target == MountTarget::None || mount_target == MountTarget::Rom) { 1018 if (mount_target == NFP::MountTarget::None || mount_target == NFP::MountTarget::Rom) {
904 LOG_ERROR(Service_NFC, "Amiibo is read only", device_state); 1019 LOG_ERROR(Service_NFC, "Amiibo is read only", device_state);
905 return WrongDeviceState; 1020 return ResultWrongDeviceState;
906 } 1021 }
907 1022
908 CommonInfo common_info{}; 1023 NFP::CommonInfo common_info{};
909 Service::Mii::MiiManager manager; 1024 Service::Mii::MiiManager manager;
910 const u64 application_id = tag_data.application_id; 1025 const u64 application_id = tag_data.application_id;
911 1026
@@ -930,8 +1045,8 @@ Result NfpDevice::GetAll(NfpData& data) const {
930 .settings_crc_counter = tag_data.settings.crc_counter, 1045 .settings_crc_counter = tag_data.settings.crc_counter,
931 .font_region = tag_data.settings.settings.font_region, 1046 .font_region = tag_data.settings.settings.font_region,
932 .tag_type = PackedTagType::Type2, 1047 .tag_type = PackedTagType::Type2,
933 .console_type = 1048 .console_type = static_cast<NFP::AppAreaVersion>(
934 static_cast<AppAreaVersion>(application_id >> application_id_version_offset & 0xf), 1049 application_id >> NFP::application_id_version_offset & 0xf),
935 .application_id_byte = tag_data.application_id_byte, 1050 .application_id_byte = tag_data.application_id_byte,
936 .application_area = tag_data.application_area, 1051 .application_area = tag_data.application_area,
937 }; 1052 };
@@ -939,18 +1054,18 @@ Result NfpDevice::GetAll(NfpData& data) const {
939 return ResultSuccess; 1054 return ResultSuccess;
940} 1055}
941 1056
942Result NfpDevice::SetAll(const NfpData& data) { 1057Result NfcDevice::SetAll(const NFP::NfpData& data) {
943 if (device_state != DeviceState::TagMounted) { 1058 if (device_state != DeviceState::TagMounted) {
944 LOG_ERROR(Service_NFC, "Wrong device state {}", device_state); 1059 LOG_ERROR(Service_NFC, "Wrong device state {}", device_state);
945 if (device_state == DeviceState::TagRemoved) { 1060 if (device_state == DeviceState::TagRemoved) {
946 return TagRemoved; 1061 return ResultTagRemoved;
947 } 1062 }
948 return WrongDeviceState; 1063 return ResultWrongDeviceState;
949 } 1064 }
950 1065
951 if (mount_target == MountTarget::None || mount_target == MountTarget::Rom) { 1066 if (mount_target == NFP::MountTarget::None || mount_target == NFP::MountTarget::Rom) {
952 LOG_ERROR(Service_NFC, "Amiibo is read only", device_state); 1067 LOG_ERROR(Service_NFC, "Amiibo is read only", device_state);
953 return WrongDeviceState; 1068 return ResultWrongDeviceState;
954 } 1069 }
955 1070
956 tag_data.constant_value = data.magic; 1071 tag_data.constant_value = data.magic;
@@ -977,18 +1092,18 @@ Result NfpDevice::SetAll(const NfpData& data) {
977 return ResultSuccess; 1092 return ResultSuccess;
978} 1093}
979 1094
980Result NfpDevice::BreakTag(BreakType break_type) { 1095Result NfcDevice::BreakTag(NFP::BreakType break_type) {
981 if (device_state != DeviceState::TagMounted) { 1096 if (device_state != DeviceState::TagMounted) {
982 LOG_ERROR(Service_NFC, "Wrong device state {}", device_state); 1097 LOG_ERROR(Service_NFC, "Wrong device state {}", device_state);
983 if (device_state == DeviceState::TagRemoved) { 1098 if (device_state == DeviceState::TagRemoved) {
984 return TagRemoved; 1099 return ResultTagRemoved;
985 } 1100 }
986 return WrongDeviceState; 1101 return ResultWrongDeviceState;
987 } 1102 }
988 1103
989 if (mount_target == MountTarget::None || mount_target == MountTarget::Rom) { 1104 if (mount_target == NFP::MountTarget::None || mount_target == NFP::MountTarget::Rom) {
990 LOG_ERROR(Service_NFC, "Amiibo is read only", device_state); 1105 LOG_ERROR(Service_NFC, "Amiibo is read only", device_state);
991 return WrongDeviceState; 1106 return ResultWrongDeviceState;
992 } 1107 }
993 1108
994 // TODO: Complete this implementation 1109 // TODO: Complete this implementation
@@ -996,28 +1111,28 @@ Result NfpDevice::BreakTag(BreakType break_type) {
996 return FlushWithBreak(break_type); 1111 return FlushWithBreak(break_type);
997} 1112}
998 1113
999Result NfpDevice::ReadBackupData() { 1114Result NfcDevice::ReadBackupData(std::span<u8> data) const {
1000 // Not implemented 1115 // Not implemented
1001 return ResultSuccess; 1116 return ResultSuccess;
1002} 1117}
1003 1118
1004Result NfpDevice::WriteBackupData() { 1119Result NfcDevice::WriteBackupData(std::span<const u8> data) {
1005 // Not implemented 1120 // Not implemented
1006 return ResultSuccess; 1121 return ResultSuccess;
1007} 1122}
1008 1123
1009Result NfpDevice::WriteNtf() { 1124Result NfcDevice::WriteNtf(std::span<const u8> data) {
1010 if (device_state != DeviceState::TagMounted) { 1125 if (device_state != DeviceState::TagMounted) {
1011 LOG_ERROR(Service_NFC, "Wrong device state {}", device_state); 1126 LOG_ERROR(Service_NFC, "Wrong device state {}", device_state);
1012 if (device_state == DeviceState::TagRemoved) { 1127 if (device_state == DeviceState::TagRemoved) {
1013 return TagRemoved; 1128 return ResultTagRemoved;
1014 } 1129 }
1015 return WrongDeviceState; 1130 return ResultWrongDeviceState;
1016 } 1131 }
1017 1132
1018 if (mount_target == MountTarget::None || mount_target == MountTarget::Rom) { 1133 if (mount_target == NFP::MountTarget::None || mount_target == NFP::MountTarget::Rom) {
1019 LOG_ERROR(Service_NFC, "Amiibo is read only", device_state); 1134 LOG_ERROR(Service_NFC, "Amiibo is read only", device_state);
1020 return WrongDeviceState; 1135 return ResultWrongDeviceState;
1021 } 1136 }
1022 1137
1023 // Not implemented 1138 // Not implemented
@@ -1025,29 +1140,12 @@ Result NfpDevice::WriteNtf() {
1025 return ResultSuccess; 1140 return ResultSuccess;
1026} 1141}
1027 1142
1028u64 NfpDevice::GetHandle() const { 1143NFP::AmiiboName NfcDevice::GetAmiiboName(const NFP::AmiiboSettings& settings) const {
1029 // Generate a handle based of the npad id 1144 std::array<char16_t, NFP::amiibo_name_length> settings_amiibo_name{};
1030 return static_cast<u64>(npad_id); 1145 NFP::AmiiboName amiibo_name{};
1031}
1032
1033u32 NfpDevice::GetApplicationAreaSize() const {
1034 return sizeof(ApplicationArea);
1035}
1036
1037DeviceState NfpDevice::GetCurrentState() const {
1038 return device_state;
1039}
1040
1041Core::HID::NpadIdType NfpDevice::GetNpadId() const {
1042 return npad_id;
1043}
1044
1045AmiiboName NfpDevice::GetAmiiboName(const AmiiboSettings& settings) const {
1046 std::array<char16_t, amiibo_name_length> settings_amiibo_name{};
1047 AmiiboName amiibo_name{};
1048 1146
1049 // Convert from big endian to little endian 1147 // Convert from big endian to little endian
1050 for (std::size_t i = 0; i < amiibo_name_length; i++) { 1148 for (std::size_t i = 0; i < NFP::amiibo_name_length; i++) {
1051 settings_amiibo_name[i] = static_cast<u16>(settings.amiibo_name[i]); 1149 settings_amiibo_name[i] = static_cast<u16>(settings.amiibo_name[i]);
1052 } 1150 }
1053 1151
@@ -1058,8 +1156,8 @@ AmiiboName NfpDevice::GetAmiiboName(const AmiiboSettings& settings) const {
1058 return amiibo_name; 1156 return amiibo_name;
1059} 1157}
1060 1158
1061void NfpDevice::SetAmiiboName(AmiiboSettings& settings, const AmiiboName& amiibo_name) { 1159void NfcDevice::SetAmiiboName(NFP::AmiiboSettings& settings, const NFP::AmiiboName& amiibo_name) {
1062 std::array<char16_t, amiibo_name_length> settings_amiibo_name{}; 1160 std::array<char16_t, NFP::amiibo_name_length> settings_amiibo_name{};
1063 1161
1064 // Convert from utf8 to utf16 1162 // Convert from utf8 to utf16
1065 const auto amiibo_name_utf16 = Common::UTF8ToUTF16(amiibo_name.data()); 1163 const auto amiibo_name_utf16 = Common::UTF8ToUTF16(amiibo_name.data());
@@ -1067,16 +1165,16 @@ void NfpDevice::SetAmiiboName(AmiiboSettings& settings, const AmiiboName& amiibo
1067 amiibo_name_utf16.size() * sizeof(char16_t)); 1165 amiibo_name_utf16.size() * sizeof(char16_t));
1068 1166
1069 // Convert from little endian to big endian 1167 // Convert from little endian to big endian
1070 for (std::size_t i = 0; i < amiibo_name_length; i++) { 1168 for (std::size_t i = 0; i < NFP::amiibo_name_length; i++) {
1071 settings.amiibo_name[i] = static_cast<u16_be>(settings_amiibo_name[i]); 1169 settings.amiibo_name[i] = static_cast<u16_be>(settings_amiibo_name[i]);
1072 } 1170 }
1073} 1171}
1074 1172
1075AmiiboDate NfpDevice::GetAmiiboDate(s64 posix_time) const { 1173NFP::AmiiboDate NfcDevice::GetAmiiboDate(s64 posix_time) const {
1076 const auto& time_zone_manager = 1174 const auto& time_zone_manager =
1077 system.GetTimeManager().GetTimeZoneContentManager().GetTimeZoneManager(); 1175 system.GetTimeManager().GetTimeZoneContentManager().GetTimeZoneManager();
1078 Time::TimeZone::CalendarInfo calendar_info{}; 1176 Time::TimeZone::CalendarInfo calendar_info{};
1079 AmiiboDate amiibo_date{}; 1177 NFP::AmiiboDate amiibo_date{};
1080 1178
1081 amiibo_date.SetYear(2000); 1179 amiibo_date.SetYear(2000);
1082 amiibo_date.SetMonth(1); 1180 amiibo_date.SetMonth(1);
@@ -1091,14 +1189,14 @@ AmiiboDate NfpDevice::GetAmiiboDate(s64 posix_time) const {
1091 return amiibo_date; 1189 return amiibo_date;
1092} 1190}
1093 1191
1094u64 NfpDevice::RemoveVersionByte(u64 application_id) const { 1192u64 NfcDevice::RemoveVersionByte(u64 application_id) const {
1095 return application_id & ~(0xfULL << application_id_version_offset); 1193 return application_id & ~(0xfULL << NFP::application_id_version_offset);
1096} 1194}
1097 1195
1098void NfpDevice::UpdateSettingsCrc() { 1196void NfcDevice::UpdateSettingsCrc() {
1099 auto& settings = tag_data.settings; 1197 auto& settings = tag_data.settings;
1100 1198
1101 if (settings.crc_counter != counter_limit) { 1199 if (settings.crc_counter != NFP::counter_limit) {
1102 settings.crc_counter++; 1200 settings.crc_counter++;
1103 } 1201 }
1104 1202
@@ -1109,7 +1207,7 @@ void NfpDevice::UpdateSettingsCrc() {
1109 settings.crc = crc.checksum(); 1207 settings.crc = crc.checksum();
1110} 1208}
1111 1209
1112void NfpDevice::UpdateRegisterInfoCrc() { 1210void NfcDevice::UpdateRegisterInfoCrc() {
1113#pragma pack(push, 1) 1211#pragma pack(push, 1)
1114 struct CrcData { 1212 struct CrcData {
1115 Mii::Ver3StoreData mii; 1213 Mii::Ver3StoreData mii;
@@ -1134,4 +1232,18 @@ void NfpDevice::UpdateRegisterInfoCrc() {
1134 tag_data.register_info_crc = crc.checksum(); 1232 tag_data.register_info_crc = crc.checksum();
1135} 1233}
1136 1234
1137} // namespace Service::NFP 1235u64 NfcDevice::GetHandle() const {
1236 // Generate a handle based of the npad id
1237 return static_cast<u64>(npad_id);
1238}
1239
1240DeviceState NfcDevice::GetCurrentState() const {
1241 return device_state;
1242}
1243
1244Result NfcDevice::GetNpadId(Core::HID::NpadIdType& out_npad_id) const {
1245 out_npad_id = npad_id;
1246 return ResultSuccess;
1247}
1248
1249} // namespace Service::NFC
diff --git a/src/core/hle/service/nfc/common/device.h b/src/core/hle/service/nfc/common/device.h
new file mode 100644
index 000000000..654eda98e
--- /dev/null
+++ b/src/core/hle/service/nfc/common/device.h
@@ -0,0 +1,138 @@
1// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4#pragma once
5
6#include <span>
7
8#include "common/common_types.h"
9#include "core/hle/service/kernel_helpers.h"
10#include "core/hle/service/nfc/mifare_types.h"
11#include "core/hle/service/nfc/nfc_types.h"
12#include "core/hle/service/nfp/nfp_types.h"
13#include "core/hle/service/service.h"
14#include "core/hle/service/time/clock_types.h"
15
16namespace Kernel {
17class KEvent;
18class KReadableEvent;
19} // namespace Kernel
20
21namespace Core {
22class System;
23} // namespace Core
24
25namespace Core::HID {
26class EmulatedController;
27enum class ControllerTriggerType;
28enum class NpadIdType : u32;
29} // namespace Core::HID
30
31namespace Service::NFC {
32class NfcDevice {
33public:
34 NfcDevice(Core::HID::NpadIdType npad_id_, Core::System& system_,
35 KernelHelpers::ServiceContext& service_context_,
36 Kernel::KEvent* availability_change_event_);
37 ~NfcDevice();
38
39 void Initialize();
40 void Finalize();
41
42 Result StartDetection(NfcProtocol allowed_protocol);
43 Result StopDetection();
44
45 Result GetTagInfo(TagInfo& tag_info, bool is_mifare) const;
46
47 Result ReadMifare(std::span<const MifareReadBlockParameter> parameters,
48 std::span<MifareReadBlockData> read_block_data) const;
49 Result ReadMifare(const MifareReadBlockParameter& parameter,
50 MifareReadBlockData& read_block_data) const;
51
52 Result WriteMifare(std::span<const MifareWriteBlockParameter> parameters);
53 Result WriteMifare(const MifareWriteBlockParameter& parameter);
54
55 Result SendCommandByPassThrough(const Time::Clock::TimeSpanType& timeout,
56 std::span<const u8> command_data, std::span<u8> out_data);
57
58 Result Mount(NFP::ModelType model_type, NFP::MountTarget mount_target);
59 Result Unmount();
60
61 Result Flush();
62 Result FlushDebug();
63 Result FlushWithBreak(NFP::BreakType break_type);
64 Result Restore();
65
66 Result GetCommonInfo(NFP::CommonInfo& common_info) const;
67 Result GetModelInfo(NFP::ModelInfo& model_info) const;
68 Result GetRegisterInfo(NFP::RegisterInfo& register_info) const;
69 Result GetRegisterInfoPrivate(NFP::RegisterInfoPrivate& register_info) const;
70 Result GetAdminInfo(NFP::AdminInfo& admin_info) const;
71
72 Result DeleteRegisterInfo();
73 Result SetRegisterInfoPrivate(const NFP::RegisterInfoPrivate& register_info);
74 Result RestoreAmiibo();
75 Result Format();
76
77 Result OpenApplicationArea(u32 access_id);
78 Result GetApplicationAreaId(u32& application_area_id) const;
79 Result GetApplicationArea(std::span<u8> data) const;
80 Result SetApplicationArea(std::span<const u8> data);
81 Result CreateApplicationArea(u32 access_id, std::span<const u8> data);
82 Result RecreateApplicationArea(u32 access_id, std::span<const u8> data);
83 Result DeleteApplicationArea();
84 Result ExistsApplicationArea(bool& has_application_area) const;
85
86 Result GetAll(NFP::NfpData& data) const;
87 Result SetAll(const NFP::NfpData& data);
88 Result BreakTag(NFP::BreakType break_type);
89 Result ReadBackupData(std::span<u8> data) const;
90 Result WriteBackupData(std::span<const u8> data);
91 Result WriteNtf(std::span<const u8> data);
92
93 u64 GetHandle() const;
94 DeviceState GetCurrentState() const;
95 Result GetNpadId(Core::HID::NpadIdType& out_npad_id) const;
96
97 Kernel::KReadableEvent& GetActivateEvent() const;
98 Kernel::KReadableEvent& GetDeactivateEvent() const;
99
100private:
101 void NpadUpdate(Core::HID::ControllerTriggerType type);
102 bool LoadNfcTag(std::span<const u8> data);
103 void CloseNfcTag();
104
105 NFP::AmiiboName GetAmiiboName(const NFP::AmiiboSettings& settings) const;
106 void SetAmiiboName(NFP::AmiiboSettings& settings, const NFP::AmiiboName& amiibo_name);
107 NFP::AmiiboDate GetAmiiboDate(s64 posix_time) const;
108 u64 RemoveVersionByte(u64 application_id) const;
109 void UpdateSettingsCrc();
110 void UpdateRegisterInfoCrc();
111
112 bool is_controller_set{};
113 int callback_key;
114 const Core::HID::NpadIdType npad_id;
115 Core::System& system;
116 Core::HID::EmulatedController* npad_device = nullptr;
117 KernelHelpers::ServiceContext& service_context;
118 Kernel::KEvent* activate_event = nullptr;
119 Kernel::KEvent* deactivate_event = nullptr;
120 Kernel::KEvent* availability_change_event = nullptr;
121
122 bool is_initalized{};
123 NfcProtocol allowed_protocols{};
124 DeviceState device_state{DeviceState::Unavailable};
125
126 // NFP data
127 bool is_data_moddified{};
128 bool is_app_area_open{};
129 bool is_plain_amiibo{};
130 s64 current_posix_time{};
131 NFP::MountTarget mount_target{NFP::MountTarget::None};
132
133 NFP::NTAG215File tag_data{};
134 std::vector<u8> mifare_data{};
135 NFP::EncryptedNTAG215File encrypted_tag_data{};
136};
137
138} // namespace Service::NFC
diff --git a/src/core/hle/service/nfc/common/device_manager.cpp b/src/core/hle/service/nfc/common/device_manager.cpp
new file mode 100644
index 000000000..d5deaaf27
--- /dev/null
+++ b/src/core/hle/service/nfc/common/device_manager.cpp
@@ -0,0 +1,695 @@
1// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-3.0-or-later
3
4#include "common/logging/log.h"
5#include "core/core.h"
6#include "core/hid/hid_types.h"
7#include "core/hle/kernel/k_event.h"
8#include "core/hle/service/ipc_helpers.h"
9#include "core/hle/service/nfc/common/device.h"
10#include "core/hle/service/nfc/common/device_manager.h"
11#include "core/hle/service/nfc/nfc_result.h"
12#include "core/hle/service/time/clock_types.h"
13
14namespace Service::NFC {
15
16DeviceManager::DeviceManager(Core::System& system_, KernelHelpers::ServiceContext& service_context_)
17 : system{system_}, service_context{service_context_} {
18
19 availability_change_event =
20 service_context.CreateEvent("Nfc:DeviceManager:AvailabilityChangeEvent");
21
22 for (u32 device_index = 0; device_index < devices.size(); device_index++) {
23 devices[device_index] =
24 std::make_shared<NfcDevice>(Core::HID::IndexToNpadIdType(device_index), system,
25 service_context, availability_change_event);
26 }
27
28 is_initialized = false;
29}
30
31DeviceManager ::~DeviceManager() {
32 service_context.CloseEvent(availability_change_event);
33}
34
35Result DeviceManager::Initialize() {
36 for (auto& device : devices) {
37 device->Initialize();
38 }
39 is_initialized = true;
40 return ResultSuccess;
41}
42
43Result DeviceManager::Finalize() {
44 for (auto& device : devices) {
45 device->Finalize();
46 }
47 is_initialized = false;
48 return ResultSuccess;
49}
50
51Result DeviceManager::ListDevices(std::vector<u64>& nfp_devices,
52 std::size_t max_allowed_devices) const {
53 for (auto& device : devices) {
54 if (nfp_devices.size() >= max_allowed_devices) {
55 continue;
56 }
57 if (device->GetCurrentState() != DeviceState::Unavailable) {
58 nfp_devices.push_back(device->GetHandle());
59 }
60 }
61
62 if (nfp_devices.empty()) {
63 return ResultDeviceNotFound;
64 }
65
66 return ResultSuccess;
67}
68
69DeviceState DeviceManager::GetDeviceState(u64 device_handle) const {
70 std::scoped_lock lock{mutex};
71
72 std::shared_ptr<NfcDevice> device = nullptr;
73 const auto result = GetDeviceFromHandle(device_handle, device, false);
74
75 if (result.IsSuccess()) {
76 return device->GetCurrentState();
77 }
78
79 return DeviceState::Unavailable;
80}
81
82Result DeviceManager::GetNpadId(u64 device_handle, Core::HID::NpadIdType& npad_id) const {
83 std::scoped_lock lock{mutex};
84
85 std::shared_ptr<NfcDevice> device = nullptr;
86 auto result = GetDeviceHandle(device_handle, device);
87
88 if (result.IsSuccess()) {
89 result = device->GetNpadId(npad_id);
90 result = VerifyDeviceResult(device, result);
91 }
92
93 return result;
94}
95
96Kernel::KReadableEvent& DeviceManager::AttachAvailabilityChangeEvent() const {
97 return availability_change_event->GetReadableEvent();
98}
99
100Result DeviceManager::StartDetection(u64 device_handle, NfcProtocol tag_protocol) {
101 std::scoped_lock lock{mutex};
102
103 std::shared_ptr<NfcDevice> device = nullptr;
104 auto result = GetDeviceHandle(device_handle, device);
105
106 if (result.IsSuccess()) {
107 result = device->StartDetection(tag_protocol);
108 result = VerifyDeviceResult(device, result);
109 }
110
111 return result;
112}
113
114Result DeviceManager::StopDetection(u64 device_handle) {
115 std::scoped_lock lock{mutex};
116
117 std::shared_ptr<NfcDevice> device = nullptr;
118 auto result = GetDeviceHandle(device_handle, device);
119
120 if (result.IsSuccess()) {
121 result = device->StopDetection();
122 result = VerifyDeviceResult(device, result);
123 }
124
125 return result;
126}
127
128Result DeviceManager::GetTagInfo(u64 device_handle, TagInfo& tag_info, bool is_mifare) const {
129 std::scoped_lock lock{mutex};
130
131 std::shared_ptr<NfcDevice> device = nullptr;
132 auto result = GetDeviceHandle(device_handle, device);
133
134 if (result.IsSuccess()) {
135 result = device->GetTagInfo(tag_info, is_mifare);
136 result = VerifyDeviceResult(device, result);
137 }
138
139 return result;
140}
141
142Kernel::KReadableEvent& DeviceManager::AttachActivateEvent(u64 device_handle) const {
143 std::scoped_lock lock{mutex};
144
145 std::shared_ptr<NfcDevice> device = nullptr;
146 GetDeviceFromHandle(device_handle, device, false);
147
148 // TODO: Return proper error code on failure
149 return device->GetActivateEvent();
150}
151
152Kernel::KReadableEvent& DeviceManager::AttachDeactivateEvent(u64 device_handle) const {
153 std::scoped_lock lock{mutex};
154
155 std::shared_ptr<NfcDevice> device = nullptr;
156 GetDeviceFromHandle(device_handle, device, false);
157
158 // TODO: Return proper error code on failure
159 return device->GetDeactivateEvent();
160}
161
162Result DeviceManager::ReadMifare(u64 device_handle,
163 std::span<const MifareReadBlockParameter> read_parameters,
164 std::span<MifareReadBlockData> read_data) {
165 std::scoped_lock lock{mutex};
166
167 std::shared_ptr<NfcDevice> device = nullptr;
168 auto result = GetDeviceHandle(device_handle, device);
169
170 if (result.IsSuccess()) {
171 result = device->ReadMifare(read_parameters, read_data);
172 result = VerifyDeviceResult(device, result);
173 }
174
175 return result;
176}
177
178Result DeviceManager::WriteMifare(u64 device_handle,
179 std::span<const MifareWriteBlockParameter> write_parameters) {
180 std::scoped_lock lock{mutex};
181
182 std::shared_ptr<NfcDevice> device = nullptr;
183 auto result = GetDeviceHandle(device_handle, device);
184
185 if (result.IsSuccess()) {
186 result = device->WriteMifare(write_parameters);
187 result = VerifyDeviceResult(device, result);
188 }
189
190 return result;
191}
192
193Result DeviceManager::SendCommandByPassThrough(u64 device_handle,
194 const Time::Clock::TimeSpanType& timeout,
195 std::span<const u8> command_data,
196 std::span<u8> out_data) {
197 std::scoped_lock lock{mutex};
198
199 std::shared_ptr<NfcDevice> device = nullptr;
200 auto result = GetDeviceHandle(device_handle, device);
201
202 if (result.IsSuccess()) {
203 result = device->SendCommandByPassThrough(timeout, command_data, out_data);
204 result = VerifyDeviceResult(device, result);
205 }
206
207 return result;
208}
209
210Result DeviceManager::Mount(u64 device_handle, NFP::ModelType model_type,
211 NFP::MountTarget mount_target) {
212 std::scoped_lock lock{mutex};
213
214 std::shared_ptr<NfcDevice> device = nullptr;
215 auto result = GetDeviceHandle(device_handle, device);
216
217 if (result.IsSuccess()) {
218 result = device->Mount(model_type, mount_target);
219 result = VerifyDeviceResult(device, result);
220 }
221
222 return result;
223}
224
225Result DeviceManager::Unmount(u64 device_handle) {
226 std::scoped_lock lock{mutex};
227
228 std::shared_ptr<NfcDevice> device = nullptr;
229 auto result = GetDeviceHandle(device_handle, device);
230
231 if (result.IsSuccess()) {
232 result = device->Unmount();
233 result = VerifyDeviceResult(device, result);
234 }
235
236 return result;
237}
238
239Result DeviceManager::OpenApplicationArea(u64 device_handle, u32 access_id) {
240 std::scoped_lock lock{mutex};
241
242 std::shared_ptr<NfcDevice> device = nullptr;
243 auto result = GetDeviceHandle(device_handle, device);
244
245 if (result.IsSuccess()) {
246 result = device->OpenApplicationArea(access_id);
247 result = VerifyDeviceResult(device, result);
248 }
249
250 return result;
251}
252
253Result DeviceManager::GetApplicationArea(u64 device_handle, std::span<u8> data) const {
254 std::scoped_lock lock{mutex};
255
256 std::shared_ptr<NfcDevice> device = nullptr;
257 auto result = GetDeviceHandle(device_handle, device);
258
259 if (result.IsSuccess()) {
260 result = device->GetApplicationArea(data);
261 result = VerifyDeviceResult(device, result);
262 }
263
264 return result;
265}
266
267Result DeviceManager::SetApplicationArea(u64 device_handle, std::span<const u8> data) {
268 std::scoped_lock lock{mutex};
269
270 std::shared_ptr<NfcDevice> device = nullptr;
271 auto result = GetDeviceHandle(device_handle, device);
272
273 if (result.IsSuccess()) {
274 result = device->SetApplicationArea(data);
275 result = VerifyDeviceResult(device, result);
276 }
277
278 return result;
279}
280
281Result DeviceManager::Flush(u64 device_handle) {
282 std::scoped_lock lock{mutex};
283
284 std::shared_ptr<NfcDevice> device = nullptr;
285 auto result = GetDeviceHandle(device_handle, device);
286
287 if (result.IsSuccess()) {
288 result = device->Flush();
289 result = VerifyDeviceResult(device, result);
290 }
291
292 return result;
293}
294
295Result DeviceManager::Restore(u64 device_handle) {
296 std::scoped_lock lock{mutex};
297
298 std::shared_ptr<NfcDevice> device = nullptr;
299 auto result = GetDeviceHandle(device_handle, device);
300
301 if (result.IsSuccess()) {
302 result = device->Restore();
303 result = VerifyDeviceResult(device, result);
304 }
305
306 return result;
307}
308
309Result DeviceManager::CreateApplicationArea(u64 device_handle, u32 access_id,
310 std::span<const u8> data) {
311 std::scoped_lock lock{mutex};
312
313 std::shared_ptr<NfcDevice> device = nullptr;
314 auto result = GetDeviceHandle(device_handle, device);
315
316 if (result.IsSuccess()) {
317 result = device->CreateApplicationArea(access_id, data);
318 result = VerifyDeviceResult(device, result);
319 }
320
321 return result;
322}
323
324Result DeviceManager::GetRegisterInfo(u64 device_handle, NFP::RegisterInfo& register_info) const {
325 std::scoped_lock lock{mutex};
326
327 std::shared_ptr<NfcDevice> device = nullptr;
328 auto result = GetDeviceHandle(device_handle, device);
329
330 if (result.IsSuccess()) {
331 result = device->GetRegisterInfo(register_info);
332 result = VerifyDeviceResult(device, result);
333 }
334
335 return result;
336}
337
338Result DeviceManager::GetCommonInfo(u64 device_handle, NFP::CommonInfo& common_info) const {
339 std::scoped_lock lock{mutex};
340
341 std::shared_ptr<NfcDevice> device = nullptr;
342 auto result = GetDeviceHandle(device_handle, device);
343
344 if (result.IsSuccess()) {
345 result = device->GetCommonInfo(common_info);
346 result = VerifyDeviceResult(device, result);
347 }
348
349 return result;
350}
351
352Result DeviceManager::GetModelInfo(u64 device_handle, NFP::ModelInfo& model_info) const {
353 std::scoped_lock lock{mutex};
354
355 std::shared_ptr<NfcDevice> device = nullptr;
356 auto result = GetDeviceHandle(device_handle, device);
357
358 if (result.IsSuccess()) {
359 result = device->GetModelInfo(model_info);
360 result = VerifyDeviceResult(device, result);
361 }
362
363 return result;
364}
365
366u32 DeviceManager::GetApplicationAreaSize() const {
367 return sizeof(NFP::ApplicationArea);
368}
369
370Result DeviceManager::RecreateApplicationArea(u64 device_handle, u32 access_id,
371 std::span<const u8> data) {
372 std::scoped_lock lock{mutex};
373
374 std::shared_ptr<NfcDevice> device = nullptr;
375 auto result = GetDeviceHandle(device_handle, device);
376
377 if (result.IsSuccess()) {
378 result = device->RecreateApplicationArea(access_id, data);
379 result = VerifyDeviceResult(device, result);
380 }
381
382 return result;
383}
384
385Result DeviceManager::Format(u64 device_handle) {
386 std::scoped_lock lock{mutex};
387
388 std::shared_ptr<NfcDevice> device = nullptr;
389 auto result = GetDeviceHandle(device_handle, device);
390
391 if (result.IsSuccess()) {
392 result = device->Format();
393 result = VerifyDeviceResult(device, result);
394 }
395
396 return result;
397}
398
399Result DeviceManager::GetAdminInfo(u64 device_handle, NFP::AdminInfo& admin_info) const {
400 std::scoped_lock lock{mutex};
401
402 std::shared_ptr<NfcDevice> device = nullptr;
403 auto result = GetDeviceHandle(device_handle, device);
404
405 if (result.IsSuccess()) {
406 result = device->GetAdminInfo(admin_info);
407 result = VerifyDeviceResult(device, result);
408 }
409
410 return result;
411}
412
413Result DeviceManager::GetRegisterInfoPrivate(u64 device_handle,
414 NFP::RegisterInfoPrivate& register_info) const {
415 std::scoped_lock lock{mutex};
416
417 std::shared_ptr<NfcDevice> device = nullptr;
418 auto result = GetDeviceHandle(device_handle, device);
419
420 if (result.IsSuccess()) {
421 result = device->GetRegisterInfoPrivate(register_info);
422 result = VerifyDeviceResult(device, result);
423 }
424
425 return result;
426}
427
428Result DeviceManager::SetRegisterInfoPrivate(u64 device_handle,
429 const NFP::RegisterInfoPrivate& register_info) {
430 std::scoped_lock lock{mutex};
431
432 std::shared_ptr<NfcDevice> device = nullptr;
433 auto result = GetDeviceHandle(device_handle, device);
434
435 if (result.IsSuccess()) {
436 result = device->SetRegisterInfoPrivate(register_info);
437 result = VerifyDeviceResult(device, result);
438 }
439
440 return result;
441}
442
443Result DeviceManager::DeleteRegisterInfo(u64 device_handle) {
444 std::scoped_lock lock{mutex};
445
446 std::shared_ptr<NfcDevice> device = nullptr;
447 auto result = GetDeviceHandle(device_handle, device);
448
449 if (result.IsSuccess()) {
450 result = device->DeleteRegisterInfo();
451 result = VerifyDeviceResult(device, result);
452 }
453
454 return result;
455}
456
457Result DeviceManager::DeleteApplicationArea(u64 device_handle) {
458 std::scoped_lock lock{mutex};
459
460 std::shared_ptr<NfcDevice> device = nullptr;
461 auto result = GetDeviceHandle(device_handle, device);
462
463 if (result.IsSuccess()) {
464 result = device->DeleteApplicationArea();
465 result = VerifyDeviceResult(device, result);
466 }
467
468 return result;
469}
470
471Result DeviceManager::ExistsApplicationArea(u64 device_handle, bool& has_application_area) const {
472 std::scoped_lock lock{mutex};
473
474 std::shared_ptr<NfcDevice> device = nullptr;
475 auto result = GetDeviceHandle(device_handle, device);
476
477 if (result.IsSuccess()) {
478 result = device->ExistsApplicationArea(has_application_area);
479 result = VerifyDeviceResult(device, result);
480 }
481
482 return result;
483}
484
485Result DeviceManager::GetAll(u64 device_handle, NFP::NfpData& nfp_data) const {
486 std::scoped_lock lock{mutex};
487
488 std::shared_ptr<NfcDevice> device = nullptr;
489 auto result = GetDeviceHandle(device_handle, device);
490
491 if (result.IsSuccess()) {
492 result = device->GetAll(nfp_data);
493 result = VerifyDeviceResult(device, result);
494 }
495
496 return result;
497}
498
499Result DeviceManager::SetAll(u64 device_handle, const NFP::NfpData& nfp_data) {
500 std::scoped_lock lock{mutex};
501
502 std::shared_ptr<NfcDevice> device = nullptr;
503 auto result = GetDeviceHandle(device_handle, device);
504
505 if (result.IsSuccess()) {
506 result = device->SetAll(nfp_data);
507 result = VerifyDeviceResult(device, result);
508 }
509
510 return result;
511}
512
513Result DeviceManager::FlushDebug(u64 device_handle) {
514 std::scoped_lock lock{mutex};
515
516 std::shared_ptr<NfcDevice> device = nullptr;
517 auto result = GetDeviceHandle(device_handle, device);
518
519 if (result.IsSuccess()) {
520 result = device->FlushDebug();
521 result = VerifyDeviceResult(device, result);
522 }
523
524 return result;
525}
526
527Result DeviceManager::BreakTag(u64 device_handle, NFP::BreakType break_type) {
528 std::scoped_lock lock{mutex};
529
530 std::shared_ptr<NfcDevice> device = nullptr;
531 auto result = GetDeviceHandle(device_handle, device);
532
533 if (result.IsSuccess()) {
534 result = device->BreakTag(break_type);
535 result = VerifyDeviceResult(device, result);
536 }
537
538 return result;
539}
540
541Result DeviceManager::ReadBackupData(u64 device_handle, std::span<u8> data) const {
542 std::scoped_lock lock{mutex};
543
544 std::shared_ptr<NfcDevice> device = nullptr;
545 auto result = GetDeviceHandle(device_handle, device);
546
547 if (result.IsSuccess()) {
548 result = device->ReadBackupData(data);
549 result = VerifyDeviceResult(device, result);
550 }
551
552 return result;
553}
554
555Result DeviceManager::WriteBackupData(u64 device_handle, std::span<const u8> data) {
556 std::scoped_lock lock{mutex};
557
558 std::shared_ptr<NfcDevice> device = nullptr;
559 auto result = GetDeviceHandle(device_handle, device);
560
561 if (result.IsSuccess()) {
562 result = device->WriteBackupData(data);
563 result = VerifyDeviceResult(device, result);
564 }
565
566 return result;
567}
568
569Result DeviceManager::WriteNtf(u64 device_handle, NFP::WriteType, std::span<const u8> data) {
570 std::scoped_lock lock{mutex};
571
572 std::shared_ptr<NfcDevice> device = nullptr;
573 auto result = GetDeviceHandle(device_handle, device);
574
575 if (result.IsSuccess()) {
576 result = device->WriteNtf(data);
577 result = VerifyDeviceResult(device, result);
578 }
579
580 return result;
581}
582
583Result DeviceManager::GetDeviceFromHandle(u64 handle, std::shared_ptr<NfcDevice>& nfc_device,
584 bool check_state) const {
585 if (check_state) {
586 const Result is_parameter_set = IsNfcParameterSet();
587 if (is_parameter_set.IsError()) {
588 return is_parameter_set;
589 }
590 const Result is_enabled = IsNfcEnabled();
591 if (is_enabled.IsError()) {
592 return is_enabled;
593 }
594 const Result is_nfc_initialized = IsNfcInitialized();
595 if (is_nfc_initialized.IsError()) {
596 return is_nfc_initialized;
597 }
598 }
599
600 for (auto& device : devices) {
601 if (device->GetHandle() == handle) {
602 nfc_device = device;
603 return ResultSuccess;
604 }
605 }
606
607 return ResultDeviceNotFound;
608}
609
610std::optional<std::shared_ptr<NfcDevice>> DeviceManager::GetNfcDevice(u64 handle) {
611 for (auto& device : devices) {
612 if (device->GetHandle() == handle) {
613 return device;
614 }
615 }
616 return std::nullopt;
617}
618
619const std::optional<std::shared_ptr<NfcDevice>> DeviceManager::GetNfcDevice(u64 handle) const {
620 for (auto& device : devices) {
621 if (device->GetHandle() == handle) {
622 return device;
623 }
624 }
625 return std::nullopt;
626}
627
628Result DeviceManager::GetDeviceHandle(u64 handle, std::shared_ptr<NfcDevice>& device) const {
629 const auto result = GetDeviceFromHandle(handle, device, true);
630 if (result.IsError()) {
631 return result;
632 }
633 return CheckDeviceState(device);
634}
635
636Result DeviceManager::VerifyDeviceResult(std::shared_ptr<NfcDevice> device,
637 Result operation_result) const {
638 if (operation_result.IsSuccess()) {
639 return operation_result;
640 }
641
642 const Result is_parameter_set = IsNfcParameterSet();
643 if (is_parameter_set.IsError()) {
644 return is_parameter_set;
645 }
646 const Result is_enabled = IsNfcEnabled();
647 if (is_enabled.IsError()) {
648 return is_enabled;
649 }
650 const Result is_nfc_initialized = IsNfcInitialized();
651 if (is_nfc_initialized.IsError()) {
652 return is_nfc_initialized;
653 }
654 const Result device_state = CheckDeviceState(device);
655 if (device_state.IsError()) {
656 return device_state;
657 }
658
659 return operation_result;
660}
661
662Result DeviceManager::CheckDeviceState(std::shared_ptr<NfcDevice> device) const {
663 if (device == nullptr) {
664 return ResultInvalidArgument;
665 }
666
667 return ResultSuccess;
668}
669
670Result DeviceManager::IsNfcEnabled() const {
671 // TODO: This calls nn::settings::detail::GetNfcEnableFlag
672 const bool is_enabled = true;
673 if (!is_enabled) {
674 return ResultNfcDisabled;
675 }
676 return ResultSuccess;
677}
678
679Result DeviceManager::IsNfcParameterSet() const {
680 // TODO: This calls checks against a bool on offset 0x450
681 const bool is_set = true;
682 if (!is_set) {
683 return ResultUnknown76;
684 }
685 return ResultSuccess;
686}
687
688Result DeviceManager::IsNfcInitialized() const {
689 if (!is_initialized) {
690 return ResultNfcNotInitialized;
691 }
692 return ResultSuccess;
693}
694
695} // namespace Service::NFC
diff --git a/src/core/hle/service/nfc/common/device_manager.h b/src/core/hle/service/nfc/common/device_manager.h
new file mode 100644
index 000000000..2971e280f
--- /dev/null
+++ b/src/core/hle/service/nfc/common/device_manager.h
@@ -0,0 +1,100 @@
1// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-3.0-or-later
3
4#pragma once
5
6#include <array>
7#include <memory>
8#include <optional>
9#include <span>
10
11#include "core/hid/hid_types.h"
12#include "core/hle/service/kernel_helpers.h"
13#include "core/hle/service/nfc/mifare_types.h"
14#include "core/hle/service/nfc/nfc_types.h"
15#include "core/hle/service/nfp/nfp_types.h"
16#include "core/hle/service/service.h"
17#include "core/hle/service/time/clock_types.h"
18
19namespace Service::NFC {
20class NfcDevice;
21
22class DeviceManager {
23public:
24 explicit DeviceManager(Core::System& system_, KernelHelpers::ServiceContext& service_context_);
25 ~DeviceManager();
26
27 // Nfc device manager
28 Result Initialize();
29 Result Finalize();
30 Result ListDevices(std::vector<u64>& nfp_devices, std::size_t max_allowed_devices) const;
31 DeviceState GetDeviceState(u64 device_handle) const;
32 Result GetNpadId(u64 device_handle, Core::HID::NpadIdType& npad_id) const;
33 Kernel::KReadableEvent& AttachAvailabilityChangeEvent() const;
34 Result StartDetection(u64 device_handle, NfcProtocol tag_protocol);
35 Result StopDetection(u64 device_handle);
36 Result GetTagInfo(u64 device_handle, NFP::TagInfo& tag_info, bool is_mifare) const;
37 Kernel::KReadableEvent& AttachActivateEvent(u64 device_handle) const;
38 Kernel::KReadableEvent& AttachDeactivateEvent(u64 device_handle) const;
39 Result ReadMifare(u64 device_handle,
40 const std::span<const MifareReadBlockParameter> read_parameters,
41 std::span<MifareReadBlockData> read_data);
42 Result WriteMifare(u64 device_handle,
43 std::span<const MifareWriteBlockParameter> write_parameters);
44 Result SendCommandByPassThrough(u64 device_handle, const Time::Clock::TimeSpanType& timeout,
45 std::span<const u8> command_data, std::span<u8> out_data);
46
47 // Nfp device manager
48 Result Mount(u64 device_handle, NFP::ModelType model_type, NFP::MountTarget mount_target);
49 Result Unmount(u64 device_handle);
50 Result OpenApplicationArea(u64 device_handle, u32 access_id);
51 Result GetApplicationArea(u64 device_handle, std::span<u8> data) const;
52 Result SetApplicationArea(u64 device_handle, std::span<const u8> data);
53 Result Flush(u64 device_handle);
54 Result Restore(u64 device_handle);
55 Result CreateApplicationArea(u64 device_handle, u32 access_id, std::span<const u8> data);
56 Result GetRegisterInfo(u64 device_handle, NFP::RegisterInfo& register_info) const;
57 Result GetCommonInfo(u64 device_handle, NFP::CommonInfo& common_info) const;
58 Result GetModelInfo(u64 device_handle, NFP::ModelInfo& model_info) const;
59 u32 GetApplicationAreaSize() const;
60 Result RecreateApplicationArea(u64 device_handle, u32 access_id, std::span<const u8> data);
61 Result Format(u64 device_handle);
62 Result GetAdminInfo(u64 device_handle, NFP::AdminInfo& admin_info) const;
63 Result GetRegisterInfoPrivate(u64 device_handle, NFP::RegisterInfoPrivate& register_info) const;
64 Result SetRegisterInfoPrivate(u64 device_handle, const NFP::RegisterInfoPrivate& register_info);
65 Result DeleteRegisterInfo(u64 device_handle);
66 Result DeleteApplicationArea(u64 device_handle);
67 Result ExistsApplicationArea(u64 device_handle, bool& has_application_area) const;
68 Result GetAll(u64 device_handle, NFP::NfpData& nfp_data) const;
69 Result SetAll(u64 device_handle, const NFP::NfpData& nfp_data);
70 Result FlushDebug(u64 device_handle);
71 Result BreakTag(u64 device_handle, NFP::BreakType break_type);
72 Result ReadBackupData(u64 device_handle, std::span<u8> data) const;
73 Result WriteBackupData(u64 device_handle, std::span<const u8> data);
74 Result WriteNtf(u64 device_handle, NFP::WriteType, std::span<const u8> data);
75
76private:
77 Result IsNfcEnabled() const;
78 Result IsNfcParameterSet() const;
79 Result IsNfcInitialized() const;
80
81 Result GetDeviceFromHandle(u64 handle, std::shared_ptr<NfcDevice>& device,
82 bool check_state) const;
83
84 Result GetDeviceHandle(u64 handle, std::shared_ptr<NfcDevice>& device) const;
85 Result VerifyDeviceResult(std::shared_ptr<NfcDevice> device, Result operation_result) const;
86 Result CheckDeviceState(std::shared_ptr<NfcDevice> device) const;
87
88 std::optional<std::shared_ptr<NfcDevice>> GetNfcDevice(u64 handle);
89 const std::optional<std::shared_ptr<NfcDevice>> GetNfcDevice(u64 handle) const;
90
91 bool is_initialized = false;
92 mutable std::mutex mutex;
93 std::array<std::shared_ptr<NfcDevice>, 10> devices{};
94
95 Core::System& system;
96 KernelHelpers::ServiceContext service_context;
97 Kernel::KEvent* availability_change_event;
98};
99
100} // namespace Service::NFC
diff --git a/src/core/hle/service/nfc/mifare_result.h b/src/core/hle/service/nfc/mifare_result.h
new file mode 100644
index 000000000..4b60048a5
--- /dev/null
+++ b/src/core/hle/service/nfc/mifare_result.h
@@ -0,0 +1,17 @@
1// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-3.0-or-later
3
4#pragma once
5
6#include "core/hle/result.h"
7
8namespace Service::NFC::Mifare {
9
10constexpr Result ResultDeviceNotFound(ErrorModule::NFCMifare, 64);
11constexpr Result ResultInvalidArgument(ErrorModule::NFCMifare, 65);
12constexpr Result ResultWrongDeviceState(ErrorModule::NFCMifare, 73);
13constexpr Result ResultNfcDisabled(ErrorModule::NFCMifare, 80);
14constexpr Result ResultTagRemoved(ErrorModule::NFCMifare, 97);
15constexpr Result ResultReadError(ErrorModule::NFCMifare, 288);
16
17} // namespace Service::NFC::Mifare
diff --git a/src/core/hle/service/nfc/mifare_types.h b/src/core/hle/service/nfc/mifare_types.h
new file mode 100644
index 000000000..75b59f021
--- /dev/null
+++ b/src/core/hle/service/nfc/mifare_types.h
@@ -0,0 +1,63 @@
1// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-3.0-or-later
3
4#pragma once
5
6#include <array>
7
8#include "common/common_funcs.h"
9#include "common/common_types.h"
10
11namespace Service::NFC {
12
13enum class MifareCmd : u8 {
14 AuthA = 0x60,
15 AuthB = 0x61,
16 Read = 0x30,
17 Write = 0xA0,
18 Transfer = 0xB0,
19 Decrement = 0xC0,
20 Increment = 0xC1,
21 Store = 0xC2
22};
23
24using DataBlock = std::array<u8, 0x10>;
25using KeyData = std::array<u8, 0x6>;
26
27struct SectorKey {
28 MifareCmd command;
29 u8 unknown; // Usually 1
30 INSERT_PADDING_BYTES(0x6);
31 KeyData sector_key;
32 INSERT_PADDING_BYTES(0x2);
33};
34static_assert(sizeof(SectorKey) == 0x10, "SectorKey is an invalid size");
35
36// This is nn::nfc::MifareReadBlockParameter
37struct MifareReadBlockParameter {
38 u8 sector_number;
39 INSERT_PADDING_BYTES(0x7);
40 SectorKey sector_key;
41};
42static_assert(sizeof(MifareReadBlockParameter) == 0x18,
43 "MifareReadBlockParameter is an invalid size");
44
45// This is nn::nfc::MifareReadBlockData
46struct MifareReadBlockData {
47 DataBlock data;
48 u8 sector_number;
49 INSERT_PADDING_BYTES(0x7);
50};
51static_assert(sizeof(MifareReadBlockData) == 0x18, "MifareReadBlockData is an invalid size");
52
53// This is nn::nfc::MifareWriteBlockParameter
54struct MifareWriteBlockParameter {
55 DataBlock data;
56 u8 sector_number;
57 INSERT_PADDING_BYTES(0x7);
58 SectorKey sector_key;
59};
60static_assert(sizeof(MifareWriteBlockParameter) == 0x28,
61 "MifareWriteBlockParameter is an invalid size");
62
63} // namespace Service::NFC
diff --git a/src/core/hle/service/nfc/mifare_user.cpp b/src/core/hle/service/nfc/mifare_user.cpp
deleted file mode 100644
index e0bbd46e1..000000000
--- a/src/core/hle/service/nfc/mifare_user.cpp
+++ /dev/null
@@ -1,400 +0,0 @@
1// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4#include "common/logging/log.h"
5#include "core/core.h"
6#include "core/hid/hid_types.h"
7#include "core/hle/kernel/k_event.h"
8#include "core/hle/service/ipc_helpers.h"
9#include "core/hle/service/nfc/mifare_user.h"
10#include "core/hle/service/nfc/nfc_device.h"
11#include "core/hle/service/nfc/nfc_result.h"
12
13namespace Service::NFC {
14
15MFIUser::MFIUser(Core::System& system_)
16 : ServiceFramework{system_, "NFC::MFIUser"}, service_context{system_, service_name} {
17 static const FunctionInfo functions[] = {
18 {0, &MFIUser::Initialize, "Initialize"},
19 {1, &MFIUser::Finalize, "Finalize"},
20 {2, &MFIUser::ListDevices, "ListDevices"},
21 {3, &MFIUser::StartDetection, "StartDetection"},
22 {4, &MFIUser::StopDetection, "StopDetection"},
23 {5, &MFIUser::Read, "Read"},
24 {6, &MFIUser::Write, "Write"},
25 {7, &MFIUser::GetTagInfo, "GetTagInfo"},
26 {8, &MFIUser::GetActivateEventHandle, "GetActivateEventHandle"},
27 {9, &MFIUser::GetDeactivateEventHandle, "GetDeactivateEventHandle"},
28 {10, &MFIUser::GetState, "GetState"},
29 {11, &MFIUser::GetDeviceState, "GetDeviceState"},
30 {12, &MFIUser::GetNpadId, "GetNpadId"},
31 {13, &MFIUser::GetAvailabilityChangeEventHandle, "GetAvailabilityChangeEventHandle"},
32 };
33 RegisterHandlers(functions);
34
35 availability_change_event = service_context.CreateEvent("MFIUser:AvailabilityChangeEvent");
36
37 for (u32 device_index = 0; device_index < 10; device_index++) {
38 devices[device_index] =
39 std::make_shared<NfcDevice>(Core::HID::IndexToNpadIdType(device_index), system,
40 service_context, availability_change_event);
41 }
42}
43
44MFIUser ::~MFIUser() {
45 availability_change_event->Close();
46}
47
48void MFIUser::Initialize(HLERequestContext& ctx) {
49 LOG_INFO(Service_NFC, "called");
50
51 state = State::Initialized;
52
53 for (auto& device : devices) {
54 device->Initialize();
55 }
56
57 IPC::ResponseBuilder rb{ctx, 2, 0};
58 rb.Push(ResultSuccess);
59}
60
61void MFIUser::Finalize(HLERequestContext& ctx) {
62 LOG_INFO(Service_NFC, "called");
63
64 state = State::NonInitialized;
65
66 for (auto& device : devices) {
67 device->Finalize();
68 }
69
70 IPC::ResponseBuilder rb{ctx, 2};
71 rb.Push(ResultSuccess);
72}
73
74void MFIUser::ListDevices(HLERequestContext& ctx) {
75 LOG_DEBUG(Service_NFC, "called");
76
77 if (state == State::NonInitialized) {
78 IPC::ResponseBuilder rb{ctx, 2};
79 rb.Push(MifareNfcDisabled);
80 return;
81 }
82
83 if (!ctx.CanWriteBuffer()) {
84 IPC::ResponseBuilder rb{ctx, 2};
85 rb.Push(MifareInvalidArgument);
86 return;
87 }
88
89 if (ctx.GetWriteBufferSize() == 0) {
90 IPC::ResponseBuilder rb{ctx, 2};
91 rb.Push(MifareInvalidArgument);
92 return;
93 }
94
95 std::vector<u64> nfp_devices;
96 const std::size_t max_allowed_devices = ctx.GetWriteBufferNumElements<u64>();
97
98 for (const auto& device : devices) {
99 if (nfp_devices.size() >= max_allowed_devices) {
100 continue;
101 }
102 if (device->GetCurrentState() != NFP::DeviceState::Unavailable) {
103 nfp_devices.push_back(device->GetHandle());
104 }
105 }
106
107 if (nfp_devices.empty()) {
108 IPC::ResponseBuilder rb{ctx, 2};
109 rb.Push(MifareDeviceNotFound);
110 return;
111 }
112
113 ctx.WriteBuffer(nfp_devices);
114
115 IPC::ResponseBuilder rb{ctx, 3};
116 rb.Push(ResultSuccess);
117 rb.Push(static_cast<s32>(nfp_devices.size()));
118}
119
120void MFIUser::StartDetection(HLERequestContext& ctx) {
121 IPC::RequestParser rp{ctx};
122 const auto device_handle{rp.Pop<u64>()};
123 LOG_INFO(Service_NFC, "called, device_handle={}", device_handle);
124
125 if (state == State::NonInitialized) {
126 IPC::ResponseBuilder rb{ctx, 2};
127 rb.Push(MifareNfcDisabled);
128 return;
129 }
130
131 auto device = GetNfcDevice(device_handle);
132
133 if (!device.has_value()) {
134 IPC::ResponseBuilder rb{ctx, 2};
135 rb.Push(MifareDeviceNotFound);
136 return;
137 }
138
139 const auto result = device.value()->StartDetection(NFP::TagProtocol::All);
140 IPC::ResponseBuilder rb{ctx, 2};
141 rb.Push(result);
142}
143
144void MFIUser::StopDetection(HLERequestContext& ctx) {
145 IPC::RequestParser rp{ctx};
146 const auto device_handle{rp.Pop<u64>()};
147 LOG_INFO(Service_NFC, "called, device_handle={}", device_handle);
148
149 if (state == State::NonInitialized) {
150 IPC::ResponseBuilder rb{ctx, 2};
151 rb.Push(MifareNfcDisabled);
152 return;
153 }
154
155 auto device = GetNfcDevice(device_handle);
156
157 if (!device.has_value()) {
158 IPC::ResponseBuilder rb{ctx, 2};
159 rb.Push(MifareDeviceNotFound);
160 return;
161 }
162
163 const auto result = device.value()->StopDetection();
164 IPC::ResponseBuilder rb{ctx, 2};
165 rb.Push(result);
166}
167
168void MFIUser::Read(HLERequestContext& ctx) {
169 IPC::RequestParser rp{ctx};
170 const auto device_handle{rp.Pop<u64>()};
171 const auto buffer{ctx.ReadBuffer()};
172 const auto number_of_commands{ctx.GetReadBufferNumElements<NFP::MifareReadBlockParameter>()};
173 std::vector<NFP::MifareReadBlockParameter> read_commands(number_of_commands);
174
175 memcpy(read_commands.data(), buffer.data(),
176 number_of_commands * sizeof(NFP::MifareReadBlockParameter));
177
178 LOG_INFO(Service_NFC, "(STUBBED) called, device_handle={}, read_commands_size={}",
179 device_handle, number_of_commands);
180
181 if (state == State::NonInitialized) {
182 IPC::ResponseBuilder rb{ctx, 2};
183 rb.Push(MifareNfcDisabled);
184 return;
185 }
186
187 auto device = GetNfcDevice(device_handle);
188
189 if (!device.has_value()) {
190 IPC::ResponseBuilder rb{ctx, 2};
191 rb.Push(MifareDeviceNotFound);
192 return;
193 }
194
195 Result result = ResultSuccess;
196 std::vector<NFP::MifareReadBlockData> out_data(number_of_commands);
197 for (std::size_t i = 0; i < number_of_commands; i++) {
198 result = device.value()->MifareRead(read_commands[i], out_data[i]);
199 if (result.IsError()) {
200 break;
201 }
202 }
203
204 ctx.WriteBuffer(out_data);
205 IPC::ResponseBuilder rb{ctx, 2};
206 rb.Push(result);
207}
208
209void MFIUser::Write(HLERequestContext& ctx) {
210 IPC::RequestParser rp{ctx};
211 const auto device_handle{rp.Pop<u64>()};
212 const auto buffer{ctx.ReadBuffer()};
213 const auto number_of_commands{ctx.GetReadBufferNumElements<NFP::MifareWriteBlockParameter>()};
214 std::vector<NFP::MifareWriteBlockParameter> write_commands(number_of_commands);
215
216 memcpy(write_commands.data(), buffer.data(),
217 number_of_commands * sizeof(NFP::MifareWriteBlockParameter));
218
219 LOG_INFO(Service_NFC, "(STUBBED) called, device_handle={}, write_commands_size={}",
220 device_handle, number_of_commands);
221
222 if (state == State::NonInitialized) {
223 IPC::ResponseBuilder rb{ctx, 2};
224 rb.Push(MifareNfcDisabled);
225 return;
226 }
227
228 auto device = GetNfcDevice(device_handle);
229
230 if (!device.has_value()) {
231 IPC::ResponseBuilder rb{ctx, 2};
232 rb.Push(MifareDeviceNotFound);
233 return;
234 }
235
236 Result result = ResultSuccess;
237 std::vector<NFP::MifareReadBlockData> out_data(number_of_commands);
238 for (std::size_t i = 0; i < number_of_commands; i++) {
239 result = device.value()->MifareWrite(write_commands[i]);
240 if (result.IsError()) {
241 break;
242 }
243 }
244
245 if (result.IsSuccess()) {
246 result = device.value()->Flush();
247 }
248
249 IPC::ResponseBuilder rb{ctx, 2};
250 rb.Push(result);
251}
252
253void MFIUser::GetTagInfo(HLERequestContext& ctx) {
254 IPC::RequestParser rp{ctx};
255 const auto device_handle{rp.Pop<u64>()};
256 LOG_INFO(Service_NFC, "called, device_handle={}", device_handle);
257
258 if (state == State::NonInitialized) {
259 IPC::ResponseBuilder rb{ctx, 2};
260 rb.Push(MifareNfcDisabled);
261 return;
262 }
263
264 auto device = GetNfcDevice(device_handle);
265
266 if (!device.has_value()) {
267 IPC::ResponseBuilder rb{ctx, 2};
268 rb.Push(MifareDeviceNotFound);
269 return;
270 }
271
272 NFP::TagInfo tag_info{};
273 const auto result = device.value()->GetTagInfo(tag_info, true);
274 ctx.WriteBuffer(tag_info);
275 IPC::ResponseBuilder rb{ctx, 2};
276 rb.Push(result);
277}
278
279void MFIUser::GetActivateEventHandle(HLERequestContext& ctx) {
280 IPC::RequestParser rp{ctx};
281 const auto device_handle{rp.Pop<u64>()};
282 LOG_DEBUG(Service_NFC, "called, device_handle={}", device_handle);
283
284 if (state == State::NonInitialized) {
285 IPC::ResponseBuilder rb{ctx, 2};
286 rb.Push(MifareNfcDisabled);
287 return;
288 }
289
290 auto device = GetNfcDevice(device_handle);
291
292 if (!device.has_value()) {
293 IPC::ResponseBuilder rb{ctx, 2};
294 rb.Push(MifareDeviceNotFound);
295 return;
296 }
297
298 IPC::ResponseBuilder rb{ctx, 2, 1};
299 rb.Push(ResultSuccess);
300 rb.PushCopyObjects(device.value()->GetActivateEvent());
301}
302
303void MFIUser::GetDeactivateEventHandle(HLERequestContext& ctx) {
304 IPC::RequestParser rp{ctx};
305 const auto device_handle{rp.Pop<u64>()};
306 LOG_DEBUG(Service_NFC, "called, device_handle={}", device_handle);
307
308 if (state == State::NonInitialized) {
309 IPC::ResponseBuilder rb{ctx, 2};
310 rb.Push(MifareNfcDisabled);
311 return;
312 }
313
314 auto device = GetNfcDevice(device_handle);
315
316 if (!device.has_value()) {
317 IPC::ResponseBuilder rb{ctx, 2};
318 rb.Push(MifareDeviceNotFound);
319 return;
320 }
321
322 IPC::ResponseBuilder rb{ctx, 2, 1};
323 rb.Push(ResultSuccess);
324 rb.PushCopyObjects(device.value()->GetDeactivateEvent());
325}
326
327void MFIUser::GetState(HLERequestContext& ctx) {
328 LOG_DEBUG(Service_NFC, "called");
329
330 IPC::ResponseBuilder rb{ctx, 3};
331 rb.Push(ResultSuccess);
332 rb.PushEnum(state);
333}
334
335void MFIUser::GetDeviceState(HLERequestContext& ctx) {
336 IPC::RequestParser rp{ctx};
337 const auto device_handle{rp.Pop<u64>()};
338 LOG_DEBUG(Service_NFC, "called, device_handle={}", device_handle);
339
340 auto device = GetNfcDevice(device_handle);
341
342 if (!device.has_value()) {
343 IPC::ResponseBuilder rb{ctx, 2};
344 rb.Push(MifareDeviceNotFound);
345 return;
346 }
347
348 IPC::ResponseBuilder rb{ctx, 3};
349 rb.Push(ResultSuccess);
350 rb.PushEnum(device.value()->GetCurrentState());
351}
352
353void MFIUser::GetNpadId(HLERequestContext& ctx) {
354 IPC::RequestParser rp{ctx};
355 const auto device_handle{rp.Pop<u64>()};
356 LOG_DEBUG(Service_NFC, "called, device_handle={}", device_handle);
357
358 if (state == State::NonInitialized) {
359 IPC::ResponseBuilder rb{ctx, 2};
360 rb.Push(MifareNfcDisabled);
361 return;
362 }
363
364 auto device = GetNfcDevice(device_handle);
365
366 if (!device.has_value()) {
367 IPC::ResponseBuilder rb{ctx, 2};
368 rb.Push(MifareDeviceNotFound);
369 return;
370 }
371
372 IPC::ResponseBuilder rb{ctx, 3};
373 rb.Push(ResultSuccess);
374 rb.PushEnum(device.value()->GetNpadId());
375}
376
377void MFIUser::GetAvailabilityChangeEventHandle(HLERequestContext& ctx) {
378 LOG_INFO(Service_NFC, "called");
379
380 if (state == State::NonInitialized) {
381 IPC::ResponseBuilder rb{ctx, 2};
382 rb.Push(MifareNfcDisabled);
383 return;
384 }
385
386 IPC::ResponseBuilder rb{ctx, 2, 1};
387 rb.Push(ResultSuccess);
388 rb.PushCopyObjects(availability_change_event->GetReadableEvent());
389}
390
391std::optional<std::shared_ptr<NfcDevice>> MFIUser::GetNfcDevice(u64 handle) {
392 for (auto& device : devices) {
393 if (device->GetHandle() == handle) {
394 return device;
395 }
396 }
397 return std::nullopt;
398}
399
400} // namespace Service::NFC
diff --git a/src/core/hle/service/nfc/mifare_user.h b/src/core/hle/service/nfc/mifare_user.h
deleted file mode 100644
index 9701f1d7f..000000000
--- a/src/core/hle/service/nfc/mifare_user.h
+++ /dev/null
@@ -1,52 +0,0 @@
1// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4#pragma once
5
6#include <array>
7#include <memory>
8#include <optional>
9
10#include "core/hle/service/kernel_helpers.h"
11#include "core/hle/service/service.h"
12
13namespace Service::NFC {
14class NfcDevice;
15
16class MFIUser final : public ServiceFramework<MFIUser> {
17public:
18 explicit MFIUser(Core::System& system_);
19 ~MFIUser();
20
21private:
22 enum class State : u32 {
23 NonInitialized,
24 Initialized,
25 };
26
27 void Initialize(HLERequestContext& ctx);
28 void Finalize(HLERequestContext& ctx);
29 void ListDevices(HLERequestContext& ctx);
30 void StartDetection(HLERequestContext& ctx);
31 void StopDetection(HLERequestContext& ctx);
32 void Read(HLERequestContext& ctx);
33 void Write(HLERequestContext& ctx);
34 void GetTagInfo(HLERequestContext& ctx);
35 void GetActivateEventHandle(HLERequestContext& ctx);
36 void GetDeactivateEventHandle(HLERequestContext& ctx);
37 void GetState(HLERequestContext& ctx);
38 void GetDeviceState(HLERequestContext& ctx);
39 void GetNpadId(HLERequestContext& ctx);
40 void GetAvailabilityChangeEventHandle(HLERequestContext& ctx);
41
42 std::optional<std::shared_ptr<NfcDevice>> GetNfcDevice(u64 handle);
43
44 KernelHelpers::ServiceContext service_context;
45
46 std::array<std::shared_ptr<NfcDevice>, 10> devices{};
47
48 State state{State::NonInitialized};
49 Kernel::KEvent* availability_change_event;
50};
51
52} // namespace Service::NFC
diff --git a/src/core/hle/service/nfc/nfc.cpp b/src/core/hle/service/nfc/nfc.cpp
index 6595e34ed..30ae989b9 100644
--- a/src/core/hle/service/nfc/nfc.cpp
+++ b/src/core/hle/service/nfc/nfc.cpp
@@ -6,14 +6,115 @@
6#include "common/logging/log.h" 6#include "common/logging/log.h"
7#include "common/settings.h" 7#include "common/settings.h"
8#include "core/hle/service/ipc_helpers.h" 8#include "core/hle/service/ipc_helpers.h"
9#include "core/hle/service/nfc/mifare_user.h"
10#include "core/hle/service/nfc/nfc.h" 9#include "core/hle/service/nfc/nfc.h"
11#include "core/hle/service/nfc/nfc_user.h" 10#include "core/hle/service/nfc/nfc_interface.h"
12#include "core/hle/service/server_manager.h" 11#include "core/hle/service/server_manager.h"
13#include "core/hle/service/service.h" 12#include "core/hle/service/service.h"
14 13
15namespace Service::NFC { 14namespace Service::NFC {
16 15
16class IUser final : public NfcInterface {
17public:
18 explicit IUser(Core::System& system_) : NfcInterface(system_, "NFC::IUser", BackendType::Nfc) {
19 // clang-format off
20 static const FunctionInfo functions[] = {
21 {0, &NfcInterface::Initialize, "InitializeOld"},
22 {1, &NfcInterface::Finalize, "FinalizeOld"},
23 {2, &NfcInterface::GetState, "GetStateOld"},
24 {3, &NfcInterface::IsNfcEnabled, "IsNfcEnabledOld"},
25 {400, &NfcInterface::Initialize, "Initialize"},
26 {401, &NfcInterface::Finalize, "Finalize"},
27 {402, &NfcInterface::GetState, "GetState"},
28 {403, &NfcInterface::IsNfcEnabled, "IsNfcEnabled"},
29 {404, &NfcInterface::ListDevices, "ListDevices"},
30 {405, &NfcInterface::GetDeviceState, "GetDeviceState"},
31 {406, &NfcInterface::GetNpadId, "GetNpadId"},
32 {407, &NfcInterface::AttachAvailabilityChangeEvent, "AttachAvailabilityChangeEvent"},
33 {408, &NfcInterface::StartDetection, "StartDetection"},
34 {409, &NfcInterface::StopDetection, "StopDetection"},
35 {410, &NfcInterface::GetTagInfo, "GetTagInfo"},
36 {411, &NfcInterface::AttachActivateEvent, "AttachActivateEvent"},
37 {412, &NfcInterface::AttachDeactivateEvent, "AttachDeactivateEvent"},
38 {1000, &NfcInterface::ReadMifare, "ReadMifare"},
39 {1001, &NfcInterface::WriteMifare ,"WriteMifare"},
40 {1300, &NfcInterface::SendCommandByPassThrough, "SendCommandByPassThrough"},
41 {1301, nullptr, "KeepPassThroughSession"},
42 {1302, nullptr, "ReleasePassThroughSession"},
43 };
44 // clang-format on
45
46 RegisterHandlers(functions);
47 }
48};
49
50class ISystem final : public NfcInterface {
51public:
52 explicit ISystem(Core::System& system_)
53 : NfcInterface{system_, "NFC::ISystem", BackendType::Nfc} {
54 // clang-format off
55 static const FunctionInfo functions[] = {
56 {0, &NfcInterface::Initialize, "InitializeOld"},
57 {1, &NfcInterface::Finalize, "FinalizeOld"},
58 {2, &NfcInterface::GetState, "GetStateOld"},
59 {3, &NfcInterface::IsNfcEnabled, "IsNfcEnabledOld"},
60 {100, nullptr, "SetNfcEnabledOld"},
61 {400, &NfcInterface::Initialize, "Initialize"},
62 {401, &NfcInterface::Finalize, "Finalize"},
63 {402, &NfcInterface::GetState, "GetState"},
64 {403, &NfcInterface::IsNfcEnabled, "IsNfcEnabled"},
65 {404, &NfcInterface::ListDevices, "ListDevices"},
66 {405, &NfcInterface::GetDeviceState, "GetDeviceState"},
67 {406, &NfcInterface::GetNpadId, "GetNpadId"},
68 {407, &NfcInterface::AttachAvailabilityChangeEvent, "AttachAvailabilityChangeEvent"},
69 {408, &NfcInterface::StartDetection, "StartDetection"},
70 {409, &NfcInterface::StopDetection, "StopDetection"},
71 {410, &NfcInterface::GetTagInfo, "GetTagInfo"},
72 {411, &NfcInterface::AttachActivateEvent, "AttachActivateEvent"},
73 {412, &NfcInterface::AttachDeactivateEvent, "AttachDeactivateEvent"},
74 {500, nullptr, "SetNfcEnabled"},
75 {510, nullptr, "OutputTestWave"},
76 {1000, &NfcInterface::ReadMifare, "ReadMifare"},
77 {1001, &NfcInterface::WriteMifare, "WriteMifare"},
78 {1300, &NfcInterface::SendCommandByPassThrough, "SendCommandByPassThrough"},
79 {1301, nullptr, "KeepPassThroughSession"},
80 {1302, nullptr, "ReleasePassThroughSession"},
81 };
82 // clang-format on
83
84 RegisterHandlers(functions);
85 }
86};
87
88// MFInterface has an unique interface but it's identical to NfcInterface so we can keep the code
89// simpler
90using MFInterface = NfcInterface;
91class MFIUser final : public MFInterface {
92public:
93 explicit MFIUser(Core::System& system_)
94 : MFInterface{system_, "NFC::MFInterface", BackendType::Mifare} {
95 // clang-format off
96 static const FunctionInfoTyped<MFIUser> functions[] = {
97 {0, &MFIUser::Initialize, "Initialize"},
98 {1, &MFIUser::Finalize, "Finalize"},
99 {2, &MFIUser::ListDevices, "ListDevices"},
100 {3, &MFIUser::StartDetection, "StartDetection"},
101 {4, &MFIUser::StopDetection, "StopDetection"},
102 {5, &MFIUser::ReadMifare, "Read"},
103 {6, &MFIUser::WriteMifare, "Write"},
104 {7, &MFIUser::GetTagInfo, "GetTagInfo"},
105 {8, &MFIUser::AttachActivateEvent, "GetActivateEventHandle"},
106 {9, &MFIUser::AttachDeactivateEvent, "GetDeactivateEventHandle"},
107 {10, &MFIUser::GetState, "GetState"},
108 {11, &MFIUser::GetDeviceState, "GetDeviceState"},
109 {12, &MFIUser::GetNpadId, "GetNpadId"},
110 {13, &MFIUser::AttachAvailabilityChangeEvent, "GetAvailabilityChangeEventHandle"},
111 };
112 // clang-format on
113
114 RegisterHandlers(functions);
115 }
116};
117
17class IAm final : public ServiceFramework<IAm> { 118class IAm final : public ServiceFramework<IAm> {
18public: 119public:
19 explicit IAm(Core::System& system_) : ServiceFramework{system_, "NFC::IAm"} { 120 explicit IAm(Core::System& system_) : ServiceFramework{system_, "NFC::IAm"} {
@@ -34,7 +135,7 @@ public:
34 explicit NFC_AM(Core::System& system_) : ServiceFramework{system_, "nfc:am"} { 135 explicit NFC_AM(Core::System& system_) : ServiceFramework{system_, "nfc:am"} {
35 // clang-format off 136 // clang-format off
36 static const FunctionInfo functions[] = { 137 static const FunctionInfo functions[] = {
37 {0, &NFC_AM::CreateAmInterface, "CreateAmInterface"}, 138 {0, &NFC_AM::CreateAmNfcInterface, "CreateAmNfcInterface"},
38 }; 139 };
39 // clang-format on 140 // clang-format on
40 141
@@ -42,7 +143,7 @@ public:
42 } 143 }
43 144
44private: 145private:
45 void CreateAmInterface(HLERequestContext& ctx) { 146 void CreateAmNfcInterface(HLERequestContext& ctx) {
46 LOG_DEBUG(Service_NFC, "called"); 147 LOG_DEBUG(Service_NFC, "called");
47 148
48 IPC::ResponseBuilder rb{ctx, 2, 0, 1}; 149 IPC::ResponseBuilder rb{ctx, 2, 0, 1};
@@ -56,7 +157,7 @@ public:
56 explicit NFC_MF_U(Core::System& system_) : ServiceFramework{system_, "nfc:mf:u"} { 157 explicit NFC_MF_U(Core::System& system_) : ServiceFramework{system_, "nfc:mf:u"} {
57 // clang-format off 158 // clang-format off
58 static const FunctionInfo functions[] = { 159 static const FunctionInfo functions[] = {
59 {0, &NFC_MF_U::CreateUserInterface, "CreateUserInterface"}, 160 {0, &NFC_MF_U::CreateUserNfcInterface, "CreateUserNfcInterface"},
60 }; 161 };
61 // clang-format on 162 // clang-format on
62 163
@@ -64,7 +165,7 @@ public:
64 } 165 }
65 166
66private: 167private:
67 void CreateUserInterface(HLERequestContext& ctx) { 168 void CreateUserNfcInterface(HLERequestContext& ctx) {
68 LOG_DEBUG(Service_NFC, "called"); 169 LOG_DEBUG(Service_NFC, "called");
69 170
70 IPC::ResponseBuilder rb{ctx, 2, 0, 1}; 171 IPC::ResponseBuilder rb{ctx, 2, 0, 1};
@@ -78,7 +179,7 @@ public:
78 explicit NFC_U(Core::System& system_) : ServiceFramework{system_, "nfc:user"} { 179 explicit NFC_U(Core::System& system_) : ServiceFramework{system_, "nfc:user"} {
79 // clang-format off 180 // clang-format off
80 static const FunctionInfo functions[] = { 181 static const FunctionInfo functions[] = {
81 {0, &NFC_U::CreateUserInterface, "CreateUserInterface"}, 182 {0, &NFC_U::CreateUserNfcInterface, "CreateUserNfcInterface"},
82 }; 183 };
83 // clang-format on 184 // clang-format on
84 185
@@ -86,7 +187,7 @@ public:
86 } 187 }
87 188
88private: 189private:
89 void CreateUserInterface(HLERequestContext& ctx) { 190 void CreateUserNfcInterface(HLERequestContext& ctx) {
90 LOG_DEBUG(Service_NFC, "called"); 191 LOG_DEBUG(Service_NFC, "called");
91 192
92 IPC::ResponseBuilder rb{ctx, 2, 0, 1}; 193 IPC::ResponseBuilder rb{ctx, 2, 0, 1};
@@ -95,49 +196,12 @@ private:
95 } 196 }
96}; 197};
97 198
98class ISystem final : public ServiceFramework<ISystem> {
99public:
100 explicit ISystem(Core::System& system_) : ServiceFramework{system_, "ISystem"} {
101 // clang-format off
102 static const FunctionInfo functions[] = {
103 {0, nullptr, "Initialize"},
104 {1, nullptr, "Finalize"},
105 {2, nullptr, "GetStateOld"},
106 {3, nullptr, "IsNfcEnabledOld"},
107 {100, nullptr, "SetNfcEnabledOld"},
108 {400, nullptr, "InitializeSystem"},
109 {401, nullptr, "FinalizeSystem"},
110 {402, nullptr, "GetState"},
111 {403, nullptr, "IsNfcEnabled"},
112 {404, nullptr, "ListDevices"},
113 {405, nullptr, "GetDeviceState"},
114 {406, nullptr, "GetNpadId"},
115 {407, nullptr, "AttachAvailabilityChangeEvent"},
116 {408, nullptr, "StartDetection"},
117 {409, nullptr, "StopDetection"},
118 {410, nullptr, "GetTagInfo"},
119 {411, nullptr, "AttachActivateEvent"},
120 {412, nullptr, "AttachDeactivateEvent"},
121 {500, nullptr, "SetNfcEnabled"},
122 {510, nullptr, "OutputTestWave"},
123 {1000, nullptr, "ReadMifare"},
124 {1001, nullptr, "WriteMifare"},
125 {1300, nullptr, "SendCommandByPassThrough"},
126 {1301, nullptr, "KeepPassThroughSession"},
127 {1302, nullptr, "ReleasePassThroughSession"},
128 };
129 // clang-format on
130
131 RegisterHandlers(functions);
132 }
133};
134
135class NFC_SYS final : public ServiceFramework<NFC_SYS> { 199class NFC_SYS final : public ServiceFramework<NFC_SYS> {
136public: 200public:
137 explicit NFC_SYS(Core::System& system_) : ServiceFramework{system_, "nfc:sys"} { 201 explicit NFC_SYS(Core::System& system_) : ServiceFramework{system_, "nfc:sys"} {
138 // clang-format off 202 // clang-format off
139 static const FunctionInfo functions[] = { 203 static const FunctionInfo functions[] = {
140 {0, &NFC_SYS::CreateSystemInterface, "CreateSystemInterface"}, 204 {0, &NFC_SYS::CreateSystemNfcInterface, "CreateSystemNfcInterface"},
141 }; 205 };
142 // clang-format on 206 // clang-format on
143 207
@@ -145,7 +209,7 @@ public:
145 } 209 }
146 210
147private: 211private:
148 void CreateSystemInterface(HLERequestContext& ctx) { 212 void CreateSystemNfcInterface(HLERequestContext& ctx) {
149 LOG_DEBUG(Service_NFC, "called"); 213 LOG_DEBUG(Service_NFC, "called");
150 214
151 IPC::ResponseBuilder rb{ctx, 2, 0, 1}; 215 IPC::ResponseBuilder rb{ctx, 2, 0, 1};
@@ -161,6 +225,7 @@ void LoopProcess(Core::System& system) {
161 server_manager->RegisterNamedService("nfc:mf:u", std::make_shared<NFC_MF_U>(system)); 225 server_manager->RegisterNamedService("nfc:mf:u", std::make_shared<NFC_MF_U>(system));
162 server_manager->RegisterNamedService("nfc:user", std::make_shared<NFC_U>(system)); 226 server_manager->RegisterNamedService("nfc:user", std::make_shared<NFC_U>(system));
163 server_manager->RegisterNamedService("nfc:sys", std::make_shared<NFC_SYS>(system)); 227 server_manager->RegisterNamedService("nfc:sys", std::make_shared<NFC_SYS>(system));
228
164 ServerManager::RunServer(std::move(server_manager)); 229 ServerManager::RunServer(std::move(server_manager));
165} 230}
166 231
diff --git a/src/core/hle/service/nfc/nfc_device.cpp b/src/core/hle/service/nfc/nfc_device.cpp
deleted file mode 100644
index c7db74d14..000000000
--- a/src/core/hle/service/nfc/nfc_device.cpp
+++ /dev/null
@@ -1,288 +0,0 @@
1// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4#include "common/input.h"
5#include "common/logging/log.h"
6#include "core/core.h"
7#include "core/hid/emulated_controller.h"
8#include "core/hid/hid_core.h"
9#include "core/hid/hid_types.h"
10#include "core/hle/kernel/k_event.h"
11#include "core/hle/service/ipc_helpers.h"
12#include "core/hle/service/nfc/nfc_device.h"
13#include "core/hle/service/nfc/nfc_result.h"
14#include "core/hle/service/nfc/nfc_user.h"
15
16namespace Service::NFC {
17NfcDevice::NfcDevice(Core::HID::NpadIdType npad_id_, Core::System& system_,
18 KernelHelpers::ServiceContext& service_context_,
19 Kernel::KEvent* availability_change_event_)
20 : npad_id{npad_id_}, system{system_}, service_context{service_context_},
21 availability_change_event{availability_change_event_} {
22 activate_event = service_context.CreateEvent("IUser:NFCActivateEvent");
23 deactivate_event = service_context.CreateEvent("IUser:NFCDeactivateEvent");
24 npad_device = system.HIDCore().GetEmulatedController(npad_id);
25
26 Core::HID::ControllerUpdateCallback engine_callback{
27 .on_change = [this](Core::HID::ControllerTriggerType type) { NpadUpdate(type); },
28 .is_npad_service = false,
29 };
30 is_controller_set = true;
31 callback_key = npad_device->SetCallback(engine_callback);
32}
33
34NfcDevice::~NfcDevice() {
35 activate_event->Close();
36 deactivate_event->Close();
37 if (!is_controller_set) {
38 return;
39 }
40 npad_device->DeleteCallback(callback_key);
41 is_controller_set = false;
42};
43
44void NfcDevice::NpadUpdate(Core::HID::ControllerTriggerType type) {
45 if (!is_initalized) {
46 return;
47 }
48
49 if (type == Core::HID::ControllerTriggerType::Connected) {
50 Initialize();
51 availability_change_event->Signal();
52 return;
53 }
54
55 if (type == Core::HID::ControllerTriggerType::Disconnected) {
56 device_state = NFP::DeviceState::Unavailable;
57 availability_change_event->Signal();
58 return;
59 }
60
61 if (type != Core::HID::ControllerTriggerType::Nfc) {
62 return;
63 }
64
65 if (!npad_device->IsConnected()) {
66 return;
67 }
68
69 const auto nfc_status = npad_device->GetNfc();
70 switch (nfc_status.state) {
71 case Common::Input::NfcState::NewAmiibo:
72 LoadNfcTag(nfc_status.data);
73 break;
74 case Common::Input::NfcState::AmiiboRemoved:
75 if (device_state != NFP::DeviceState::SearchingForTag) {
76 CloseNfcTag();
77 }
78 break;
79 default:
80 break;
81 }
82}
83
84bool NfcDevice::LoadNfcTag(std::span<const u8> data) {
85 if (device_state != NFP::DeviceState::SearchingForTag) {
86 LOG_ERROR(Service_NFC, "Game is not looking for nfc tag, current state {}", device_state);
87 return false;
88 }
89
90 if (data.size() < sizeof(NFP::EncryptedNTAG215File)) {
91 LOG_ERROR(Service_NFC, "Not an amiibo, size={}", data.size());
92 return false;
93 }
94
95 tag_data.resize(data.size());
96 memcpy(tag_data.data(), data.data(), data.size());
97 memcpy(&encrypted_tag_data, data.data(), sizeof(NFP::EncryptedNTAG215File));
98
99 device_state = NFP::DeviceState::TagFound;
100 deactivate_event->GetReadableEvent().Clear();
101 activate_event->Signal();
102 return true;
103}
104
105void NfcDevice::CloseNfcTag() {
106 LOG_INFO(Service_NFC, "Remove nfc tag");
107
108 device_state = NFP::DeviceState::TagRemoved;
109 encrypted_tag_data = {};
110 activate_event->GetReadableEvent().Clear();
111 deactivate_event->Signal();
112}
113
114Kernel::KReadableEvent& NfcDevice::GetActivateEvent() const {
115 return activate_event->GetReadableEvent();
116}
117
118Kernel::KReadableEvent& NfcDevice::GetDeactivateEvent() const {
119 return deactivate_event->GetReadableEvent();
120}
121
122void NfcDevice::Initialize() {
123 device_state =
124 npad_device->HasNfc() ? NFP::DeviceState::Initialized : NFP::DeviceState::Unavailable;
125 encrypted_tag_data = {};
126 is_initalized = true;
127}
128
129void NfcDevice::Finalize() {
130 if (device_state == NFP::DeviceState::SearchingForTag ||
131 device_state == NFP::DeviceState::TagRemoved) {
132 StopDetection();
133 }
134 device_state = NFP::DeviceState::Unavailable;
135 is_initalized = false;
136}
137
138Result NfcDevice::StartDetection(NFP::TagProtocol allowed_protocol) {
139 if (device_state != NFP::DeviceState::Initialized &&
140 device_state != NFP::DeviceState::TagRemoved) {
141 LOG_ERROR(Service_NFC, "Wrong device state {}", device_state);
142 return WrongDeviceState;
143 }
144
145 if (npad_device->SetPollingMode(Core::HID::EmulatedDeviceIndex::RightIndex,
146 Common::Input::PollingMode::NFC) !=
147 Common::Input::DriverResult::Success) {
148 LOG_ERROR(Service_NFC, "Nfc not supported");
149 return NfcDisabled;
150 }
151
152 device_state = NFP::DeviceState::SearchingForTag;
153 allowed_protocols = allowed_protocol;
154 return ResultSuccess;
155}
156
157Result NfcDevice::StopDetection() {
158 npad_device->SetPollingMode(Core::HID::EmulatedDeviceIndex::RightIndex,
159 Common::Input::PollingMode::Active);
160
161 if (device_state == NFP::DeviceState::Initialized) {
162 return ResultSuccess;
163 }
164
165 if (device_state == NFP::DeviceState::TagFound ||
166 device_state == NFP::DeviceState::TagMounted) {
167 CloseNfcTag();
168 return ResultSuccess;
169 }
170 if (device_state == NFP::DeviceState::SearchingForTag ||
171 device_state == NFP::DeviceState::TagRemoved) {
172 device_state = NFP::DeviceState::Initialized;
173 return ResultSuccess;
174 }
175
176 LOG_ERROR(Service_NFC, "Wrong device state {}", device_state);
177 return WrongDeviceState;
178}
179
180Result NfcDevice::Flush() {
181 if (device_state != NFP::DeviceState::TagFound &&
182 device_state != NFP::DeviceState::TagMounted) {
183 LOG_ERROR(Service_NFC, "Wrong device state {}", device_state);
184 if (device_state == NFP::DeviceState::TagRemoved) {
185 return TagRemoved;
186 }
187 return WrongDeviceState;
188 }
189
190 if (!npad_device->WriteNfc(tag_data)) {
191 LOG_ERROR(Service_NFP, "Error writing to file");
192 return MifareReadError;
193 }
194
195 return ResultSuccess;
196}
197
198Result NfcDevice::GetTagInfo(NFP::TagInfo& tag_info, bool is_mifare) const {
199 if (device_state != NFP::DeviceState::TagFound &&
200 device_state != NFP::DeviceState::TagMounted) {
201 LOG_ERROR(Service_NFC, "Wrong device state {}", device_state);
202 if (device_state == NFP::DeviceState::TagRemoved) {
203 return TagRemoved;
204 }
205 return WrongDeviceState;
206 }
207
208 if (is_mifare) {
209 tag_info = {
210 .uuid = encrypted_tag_data.uuid.uid,
211 .uuid_length = static_cast<u8>(encrypted_tag_data.uuid.uid.size()),
212 .protocol = NFP::TagProtocol::TypeA,
213 .tag_type = NFP::TagType::Type4,
214 };
215 return ResultSuccess;
216 }
217
218 // Protocol and tag type may change here
219 tag_info = {
220 .uuid = encrypted_tag_data.uuid.uid,
221 .uuid_length = static_cast<u8>(encrypted_tag_data.uuid.uid.size()),
222 .protocol = NFP::TagProtocol::TypeA,
223 .tag_type = NFP::TagType::Type2,
224 };
225
226 return ResultSuccess;
227}
228
229Result NfcDevice::MifareRead(const NFP::MifareReadBlockParameter& parameter,
230 NFP::MifareReadBlockData& read_block_data) {
231 const std::size_t sector_index = parameter.sector_number * sizeof(NFP::DataBlock);
232 read_block_data.sector_number = parameter.sector_number;
233
234 if (device_state != NFP::DeviceState::TagFound &&
235 device_state != NFP::DeviceState::TagMounted) {
236 LOG_ERROR(Service_NFC, "Wrong device state {}", device_state);
237 if (device_state == NFP::DeviceState::TagRemoved) {
238 return TagRemoved;
239 }
240 return WrongDeviceState;
241 }
242
243 if (tag_data.size() < sector_index + sizeof(NFP::DataBlock)) {
244 return MifareReadError;
245 }
246
247 // TODO: Use parameter.sector_key to read encrypted data
248 memcpy(read_block_data.data.data(), tag_data.data() + sector_index, sizeof(NFP::DataBlock));
249
250 return ResultSuccess;
251}
252
253Result NfcDevice::MifareWrite(const NFP::MifareWriteBlockParameter& parameter) {
254 const std::size_t sector_index = parameter.sector_number * sizeof(NFP::DataBlock);
255
256 if (device_state != NFP::DeviceState::TagFound &&
257 device_state != NFP::DeviceState::TagMounted) {
258 LOG_ERROR(Service_NFC, "Wrong device state {}", device_state);
259 if (device_state == NFP::DeviceState::TagRemoved) {
260 return TagRemoved;
261 }
262 return WrongDeviceState;
263 }
264
265 if (tag_data.size() < sector_index + sizeof(NFP::DataBlock)) {
266 return MifareReadError;
267 }
268
269 // TODO: Use parameter.sector_key to encrypt the data
270 memcpy(tag_data.data() + sector_index, parameter.data.data(), sizeof(NFP::DataBlock));
271
272 return ResultSuccess;
273}
274
275u64 NfcDevice::GetHandle() const {
276 // Generate a handle based of the npad id
277 return static_cast<u64>(npad_id);
278}
279
280NFP::DeviceState NfcDevice::GetCurrentState() const {
281 return device_state;
282}
283
284Core::HID::NpadIdType NfcDevice::GetNpadId() const {
285 return npad_id;
286}
287
288} // namespace Service::NFC
diff --git a/src/core/hle/service/nfc/nfc_device.h b/src/core/hle/service/nfc/nfc_device.h
deleted file mode 100644
index ea63f0537..000000000
--- a/src/core/hle/service/nfc/nfc_device.h
+++ /dev/null
@@ -1,78 +0,0 @@
1// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4#pragma once
5
6#include "common/common_types.h"
7#include "core/hle/service/kernel_helpers.h"
8#include "core/hle/service/nfp/nfp_types.h"
9#include "core/hle/service/service.h"
10
11namespace Kernel {
12class KEvent;
13class KReadableEvent;
14} // namespace Kernel
15
16namespace Core {
17class System;
18} // namespace Core
19
20namespace Core::HID {
21class EmulatedController;
22enum class ControllerTriggerType;
23enum class NpadIdType : u32;
24} // namespace Core::HID
25
26namespace Service::NFC {
27class NfcDevice {
28public:
29 NfcDevice(Core::HID::NpadIdType npad_id_, Core::System& system_,
30 KernelHelpers::ServiceContext& service_context_,
31 Kernel::KEvent* availability_change_event_);
32 ~NfcDevice();
33
34 void Initialize();
35 void Finalize();
36
37 Result StartDetection(NFP::TagProtocol allowed_protocol);
38 Result StopDetection();
39 Result Flush();
40
41 Result GetTagInfo(NFP::TagInfo& tag_info, bool is_mifare) const;
42
43 Result MifareRead(const NFP::MifareReadBlockParameter& parameter,
44 NFP::MifareReadBlockData& read_block_data);
45
46 Result MifareWrite(const NFP::MifareWriteBlockParameter& parameter);
47
48 u64 GetHandle() const;
49 NFP::DeviceState GetCurrentState() const;
50 Core::HID::NpadIdType GetNpadId() const;
51
52 Kernel::KReadableEvent& GetActivateEvent() const;
53 Kernel::KReadableEvent& GetDeactivateEvent() const;
54
55private:
56 void NpadUpdate(Core::HID::ControllerTriggerType type);
57 bool LoadNfcTag(std::span<const u8> data);
58 void CloseNfcTag();
59
60 bool is_controller_set{};
61 int callback_key;
62 const Core::HID::NpadIdType npad_id;
63 Core::System& system;
64 Core::HID::EmulatedController* npad_device = nullptr;
65 KernelHelpers::ServiceContext& service_context;
66 Kernel::KEvent* activate_event = nullptr;
67 Kernel::KEvent* deactivate_event = nullptr;
68 Kernel::KEvent* availability_change_event = nullptr;
69
70 bool is_initalized{};
71 NFP::TagProtocol allowed_protocols{};
72 NFP::DeviceState device_state{NFP::DeviceState::Unavailable};
73
74 NFP::EncryptedNTAG215File encrypted_tag_data{};
75 std::vector<u8> tag_data{};
76};
77
78} // namespace Service::NFC
diff --git a/src/core/hle/service/nfc/nfc_interface.cpp b/src/core/hle/service/nfc/nfc_interface.cpp
new file mode 100644
index 000000000..0fa29d398
--- /dev/null
+++ b/src/core/hle/service/nfc/nfc_interface.cpp
@@ -0,0 +1,382 @@
1// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4#include "common/logging/log.h"
5#include "core/core.h"
6#include "core/hid/hid_types.h"
7#include "core/hle/kernel/k_event.h"
8#include "core/hle/service/ipc_helpers.h"
9#include "core/hle/service/nfc/common/device.h"
10#include "core/hle/service/nfc/common/device_manager.h"
11#include "core/hle/service/nfc/mifare_result.h"
12#include "core/hle/service/nfc/mifare_types.h"
13#include "core/hle/service/nfc/nfc_interface.h"
14#include "core/hle/service/nfc/nfc_result.h"
15#include "core/hle/service/nfc/nfc_types.h"
16#include "core/hle/service/nfp/nfp_result.h"
17#include "core/hle/service/time/clock_types.h"
18
19namespace Service::NFC {
20
21NfcInterface::NfcInterface(Core::System& system_, const char* name, BackendType service_backend)
22 : ServiceFramework{system_, name}, service_context{system_, service_name},
23 backend_type{service_backend} {}
24
25NfcInterface ::~NfcInterface() = default;
26
27void NfcInterface::Initialize(HLERequestContext& ctx) {
28 LOG_INFO(Service_NFC, "called");
29
30 auto manager = GetManager();
31 auto result = manager->Initialize();
32
33 if (result.IsSuccess()) {
34 state = State::Initialized;
35 } else {
36 manager->Finalize();
37 }
38
39 IPC::ResponseBuilder rb{ctx, 2, 0};
40 rb.Push(result);
41}
42
43void NfcInterface::Finalize(HLERequestContext& ctx) {
44 LOG_INFO(Service_NFC, "called");
45
46 if (state != State::NonInitialized) {
47 if (GetBackendType() != BackendType::None) {
48 GetManager()->Finalize();
49 }
50 device_manager = nullptr;
51 state = State::NonInitialized;
52 }
53
54 IPC::ResponseBuilder rb{ctx, 2};
55 rb.Push(ResultSuccess);
56}
57
58void NfcInterface::GetState(HLERequestContext& ctx) {
59 LOG_DEBUG(Service_NFC, "called");
60
61 IPC::ResponseBuilder rb{ctx, 3};
62 rb.Push(ResultSuccess);
63 rb.PushEnum(state);
64}
65
66void NfcInterface::IsNfcEnabled(HLERequestContext& ctx) {
67 LOG_DEBUG(Service_NFC, "called");
68
69 // TODO: This calls nn::settings::detail::GetNfcEnableFlag
70 const bool is_enabled = true;
71
72 IPC::ResponseBuilder rb{ctx, 3};
73 rb.Push(ResultSuccess);
74 rb.Push(is_enabled);
75}
76
77void NfcInterface::ListDevices(HLERequestContext& ctx) {
78 std::vector<u64> nfp_devices;
79 const std::size_t max_allowed_devices = ctx.GetWriteBufferNumElements<u64>();
80 LOG_DEBUG(Service_NFC, "called");
81
82 auto result = GetManager()->ListDevices(nfp_devices, max_allowed_devices);
83 result = TranslateResultToServiceError(result);
84
85 if (result.IsError()) {
86 IPC::ResponseBuilder rb{ctx, 2};
87 rb.Push(result);
88 return;
89 }
90
91 ctx.WriteBuffer(nfp_devices);
92
93 IPC::ResponseBuilder rb{ctx, 3};
94 rb.Push(ResultSuccess);
95 rb.Push(static_cast<s32>(nfp_devices.size()));
96}
97
98void NfcInterface::GetDeviceState(HLERequestContext& ctx) {
99 IPC::RequestParser rp{ctx};
100 const auto device_handle{rp.Pop<u64>()};
101 LOG_DEBUG(Service_NFC, "called, device_handle={}", device_handle);
102
103 const auto device_state = GetManager()->GetDeviceState(device_handle);
104
105 if (device_state > DeviceState::Finalized) {
106 ASSERT_MSG(false, "Invalid device state");
107 }
108
109 IPC::ResponseBuilder rb{ctx, 3};
110 rb.Push(ResultSuccess);
111 rb.PushEnum(device_state);
112}
113
114void NfcInterface::GetNpadId(HLERequestContext& ctx) {
115 IPC::RequestParser rp{ctx};
116 const auto device_handle{rp.Pop<u64>()};
117 LOG_DEBUG(Service_NFC, "called, device_handle={}", device_handle);
118
119 Core::HID::NpadIdType npad_id{};
120 auto result = GetManager()->GetNpadId(device_handle, npad_id);
121 result = TranslateResultToServiceError(result);
122
123 if (result.IsError()) {
124 IPC::ResponseBuilder rb{ctx, 2};
125 rb.Push(result);
126 return;
127 }
128
129 IPC::ResponseBuilder rb{ctx, 3};
130 rb.Push(ResultSuccess);
131 rb.PushEnum(npad_id);
132}
133
134void NfcInterface::AttachAvailabilityChangeEvent(HLERequestContext& ctx) {
135 LOG_INFO(Service_NFC, "called");
136
137 IPC::ResponseBuilder rb{ctx, 2, 1};
138 rb.Push(ResultSuccess);
139 rb.PushCopyObjects(GetManager()->AttachAvailabilityChangeEvent());
140}
141
142void NfcInterface::StartDetection(HLERequestContext& ctx) {
143 IPC::RequestParser rp{ctx};
144 const auto device_handle{rp.Pop<u64>()};
145 const auto tag_protocol{rp.PopEnum<NfcProtocol>()};
146 LOG_INFO(Service_NFC, "called, device_handle={}, nfp_protocol={}", device_handle, tag_protocol);
147
148 auto result = GetManager()->StartDetection(device_handle, tag_protocol);
149 result = TranslateResultToServiceError(result);
150
151 IPC::ResponseBuilder rb{ctx, 2};
152 rb.Push(result);
153}
154
155void NfcInterface::StopDetection(HLERequestContext& ctx) {
156 IPC::RequestParser rp{ctx};
157 const auto device_handle{rp.Pop<u64>()};
158 LOG_INFO(Service_NFC, "called, device_handle={}", device_handle);
159
160 auto result = GetManager()->StopDetection(device_handle);
161 result = TranslateResultToServiceError(result);
162
163 IPC::ResponseBuilder rb{ctx, 2};
164 rb.Push(result);
165}
166
167void NfcInterface::GetTagInfo(HLERequestContext& ctx) {
168 IPC::RequestParser rp{ctx};
169 const auto device_handle{rp.Pop<u64>()};
170 LOG_INFO(Service_NFC, "called, device_handle={}", device_handle);
171
172 TagInfo tag_info{};
173 auto result =
174 GetManager()->GetTagInfo(device_handle, tag_info, backend_type == BackendType::Mifare);
175 result = TranslateResultToServiceError(result);
176
177 if (result.IsSuccess()) {
178 ctx.WriteBuffer(tag_info);
179 }
180
181 IPC::ResponseBuilder rb{ctx, 2};
182 rb.Push(result);
183}
184
185void NfcInterface::AttachActivateEvent(HLERequestContext& ctx) {
186 IPC::RequestParser rp{ctx};
187 const auto device_handle{rp.Pop<u64>()};
188 LOG_DEBUG(Service_NFC, "called, device_handle={}", device_handle);
189
190 IPC::ResponseBuilder rb{ctx, 2, 1};
191 rb.Push(ResultSuccess);
192 rb.PushCopyObjects(GetManager()->AttachActivateEvent(device_handle));
193}
194
195void NfcInterface::AttachDeactivateEvent(HLERequestContext& ctx) {
196 IPC::RequestParser rp{ctx};
197 const auto device_handle{rp.Pop<u64>()};
198 LOG_DEBUG(Service_NFC, "called, device_handle={}", device_handle);
199
200 IPC::ResponseBuilder rb{ctx, 2, 1};
201 rb.Push(ResultSuccess);
202 rb.PushCopyObjects(GetManager()->AttachDeactivateEvent(device_handle));
203}
204
205void NfcInterface::ReadMifare(HLERequestContext& ctx) {
206 IPC::RequestParser rp{ctx};
207 const auto device_handle{rp.Pop<u64>()};
208 const auto buffer{ctx.ReadBuffer()};
209 const auto number_of_commands{ctx.GetReadBufferNumElements<MifareReadBlockParameter>()};
210 std::vector<MifareReadBlockParameter> read_commands(number_of_commands);
211
212 memcpy(read_commands.data(), buffer.data(),
213 number_of_commands * sizeof(MifareReadBlockParameter));
214
215 LOG_INFO(Service_NFC, "(STUBBED) called, device_handle={}, read_commands_size={}",
216 device_handle, number_of_commands);
217
218 std::vector<MifareReadBlockData> out_data(number_of_commands);
219 auto result = GetManager()->ReadMifare(device_handle, read_commands, out_data);
220 result = TranslateResultToServiceError(result);
221
222 if (result.IsSuccess()) {
223 ctx.WriteBuffer(out_data);
224 }
225
226 IPC::ResponseBuilder rb{ctx, 2};
227 rb.Push(result);
228}
229
230void NfcInterface::WriteMifare(HLERequestContext& ctx) {
231 IPC::RequestParser rp{ctx};
232 const auto device_handle{rp.Pop<u64>()};
233 const auto buffer{ctx.ReadBuffer()};
234 const auto number_of_commands{ctx.GetReadBufferNumElements<MifareWriteBlockParameter>()};
235 std::vector<MifareWriteBlockParameter> write_commands(number_of_commands);
236
237 memcpy(write_commands.data(), buffer.data(),
238 number_of_commands * sizeof(MifareWriteBlockParameter));
239
240 LOG_INFO(Service_NFC, "(STUBBED) called, device_handle={}, write_commands_size={}",
241 device_handle, number_of_commands);
242
243 auto result = GetManager()->WriteMifare(device_handle, write_commands);
244 result = TranslateResultToServiceError(result);
245
246 IPC::ResponseBuilder rb{ctx, 2};
247 rb.Push(result);
248}
249
250void NfcInterface::SendCommandByPassThrough(HLERequestContext& ctx) {
251 IPC::RequestParser rp{ctx};
252 const auto device_handle{rp.Pop<u64>()};
253 const auto timeout{rp.PopRaw<Time::Clock::TimeSpanType>()};
254 const auto command_data{ctx.ReadBuffer()};
255 LOG_INFO(Service_NFC, "(STUBBED) called, device_handle={}, timeout={}, data_size={}",
256 device_handle, timeout.ToSeconds(), command_data.size());
257
258 std::vector<u8> out_data(1);
259 auto result =
260 GetManager()->SendCommandByPassThrough(device_handle, timeout, command_data, out_data);
261 result = TranslateResultToServiceError(result);
262
263 if (result.IsError()) {
264 IPC::ResponseBuilder rb{ctx, 2};
265 rb.Push(result);
266 return;
267 }
268
269 ctx.WriteBuffer(out_data);
270
271 IPC::ResponseBuilder rb{ctx, 3};
272 rb.Push(ResultSuccess);
273 rb.Push(static_cast<u32>(out_data.size()));
274}
275
276std::shared_ptr<DeviceManager> NfcInterface::GetManager() {
277 if (device_manager == nullptr) {
278 device_manager = std::make_shared<DeviceManager>(system, service_context);
279 }
280 return device_manager;
281}
282
283BackendType NfcInterface::GetBackendType() const {
284 return backend_type;
285}
286
287Result NfcInterface::TranslateResultToServiceError(Result result) const {
288 const auto backend = GetBackendType();
289
290 if (result.IsSuccess()) {
291 return result;
292 }
293
294 if (result.module != ErrorModule::NFC) {
295 return result;
296 }
297
298 switch (backend) {
299 case BackendType::Mifare:
300 return TranslateResultToNfp(result);
301 case BackendType::Nfp: {
302 return TranslateResultToNfp(result);
303 }
304 default:
305 if (result != ResultUnknown216) {
306 return result;
307 }
308 return ResultUnknown74;
309 }
310}
311
312Result NfcInterface::TranslateResultToNfp(Result result) const {
313 if (result == ResultDeviceNotFound) {
314 return NFP::ResultDeviceNotFound;
315 }
316 if (result == ResultInvalidArgument) {
317 return NFP::ResultInvalidArgument;
318 }
319 if (result == ResultWrongApplicationAreaSize) {
320 return NFP::ResultWrongApplicationAreaSize;
321 }
322 if (result == ResultWrongDeviceState) {
323 return NFP::ResultWrongDeviceState;
324 }
325 if (result == ResultUnknown74) {
326 return NFP::ResultUnknown74;
327 }
328 if (result == ResultNfcDisabled) {
329 return NFP::ResultNfcDisabled;
330 }
331 if (result == ResultNfcNotInitialized) {
332 return NFP::ResultNfcDisabled;
333 }
334 if (result == ResultWriteAmiiboFailed) {
335 return NFP::ResultWriteAmiiboFailed;
336 }
337 if (result == ResultTagRemoved) {
338 return NFP::ResultTagRemoved;
339 }
340 if (result == ResultRegistrationIsNotInitialized) {
341 return NFP::ResultRegistrationIsNotInitialized;
342 }
343 if (result == ResultApplicationAreaIsNotInitialized) {
344 return NFP::ResultApplicationAreaIsNotInitialized;
345 }
346 if (result == ResultCorruptedData) {
347 return NFP::ResultCorruptedData;
348 }
349 if (result == ResultWrongApplicationAreaId) {
350 return NFP::ResultWrongApplicationAreaId;
351 }
352 if (result == ResultApplicationAreaExist) {
353 return NFP::ResultApplicationAreaExist;
354 }
355 if (result == ResultNotAnAmiibo) {
356 return NFP::ResultNotAnAmiibo;
357 }
358 LOG_WARNING(Service_NFC, "Result conversion not handled");
359 return result;
360}
361
362Result NfcInterface::TranslateResultToMifare(Result result) const {
363 if (result == ResultDeviceNotFound) {
364 return Mifare::ResultDeviceNotFound;
365 }
366 if (result == ResultInvalidArgument) {
367 return Mifare::ResultInvalidArgument;
368 }
369 if (result == ResultWrongDeviceState) {
370 return Mifare::ResultWrongDeviceState;
371 }
372 if (result == ResultNfcDisabled) {
373 return Mifare::ResultNfcDisabled;
374 }
375 if (result == ResultTagRemoved) {
376 return Mifare::ResultTagRemoved;
377 }
378 LOG_WARNING(Service_NFC, "Result conversion not handled");
379 return result;
380}
381
382} // namespace Service::NFC
diff --git a/src/core/hle/service/nfc/nfc_user.h b/src/core/hle/service/nfc/nfc_interface.h
index aee046ae8..08be174d8 100644
--- a/src/core/hle/service/nfc/nfc_user.h
+++ b/src/core/hle/service/nfc/nfc_interface.h
@@ -3,26 +3,17 @@
3 3
4#pragma once 4#pragma once
5 5
6#include <array>
7#include <memory>
8#include <optional>
9
10#include "core/hle/service/kernel_helpers.h" 6#include "core/hle/service/kernel_helpers.h"
7#include "core/hle/service/nfc/nfc_types.h"
11#include "core/hle/service/service.h" 8#include "core/hle/service/service.h"
12 9
13namespace Service::NFC { 10namespace Service::NFC {
14class NfcDevice; 11class DeviceManager;
15 12
16class IUser final : public ServiceFramework<IUser> { 13class NfcInterface : public ServiceFramework<NfcInterface> {
17public: 14public:
18 explicit IUser(Core::System& system_); 15 explicit NfcInterface(Core::System& system_, const char* name, BackendType service_backend);
19 ~IUser(); 16 ~NfcInterface();
20
21private:
22 enum class State : u32 {
23 NonInitialized,
24 Initialized,
25 };
26 17
27 void Initialize(HLERequestContext& ctx); 18 void Initialize(HLERequestContext& ctx);
28 void Finalize(HLERequestContext& ctx); 19 void Finalize(HLERequestContext& ctx);
@@ -37,16 +28,22 @@ private:
37 void GetTagInfo(HLERequestContext& ctx); 28 void GetTagInfo(HLERequestContext& ctx);
38 void AttachActivateEvent(HLERequestContext& ctx); 29 void AttachActivateEvent(HLERequestContext& ctx);
39 void AttachDeactivateEvent(HLERequestContext& ctx); 30 void AttachDeactivateEvent(HLERequestContext& ctx);
31 void ReadMifare(HLERequestContext& ctx);
32 void WriteMifare(HLERequestContext& ctx);
40 void SendCommandByPassThrough(HLERequestContext& ctx); 33 void SendCommandByPassThrough(HLERequestContext& ctx);
41 34
42 std::optional<std::shared_ptr<NfcDevice>> GetNfcDevice(u64 handle); 35protected:
36 std::shared_ptr<DeviceManager> GetManager();
37 BackendType GetBackendType() const;
38 Result TranslateResultToServiceError(Result result) const;
39 Result TranslateResultToNfp(Result result) const;
40 Result TranslateResultToMifare(Result result) const;
43 41
44 KernelHelpers::ServiceContext service_context; 42 KernelHelpers::ServiceContext service_context;
45 43
46 std::array<std::shared_ptr<NfcDevice>, 10> devices{}; 44 BackendType backend_type;
47
48 State state{State::NonInitialized}; 45 State state{State::NonInitialized};
49 Kernel::KEvent* availability_change_event; 46 std::shared_ptr<DeviceManager> device_manager = nullptr;
50}; 47};
51 48
52} // namespace Service::NFC 49} // namespace Service::NFC
diff --git a/src/core/hle/service/nfc/nfc_result.h b/src/core/hle/service/nfc/nfc_result.h
index 146b8ba61..917d79ef8 100644
--- a/src/core/hle/service/nfc/nfc_result.h
+++ b/src/core/hle/service/nfc/nfc_result.h
@@ -1,5 +1,5 @@
1// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project 1// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later 2// SPDX-License-Identifier: GPL-3.0-or-later
3 3
4#pragma once 4#pragma once
5 5
@@ -7,17 +7,22 @@
7 7
8namespace Service::NFC { 8namespace Service::NFC {
9 9
10constexpr Result DeviceNotFound(ErrorModule::NFC, 64); 10constexpr Result ResultDeviceNotFound(ErrorModule::NFC, 64);
11constexpr Result InvalidArgument(ErrorModule::NFC, 65); 11constexpr Result ResultInvalidArgument(ErrorModule::NFC, 65);
12constexpr Result WrongDeviceState(ErrorModule::NFC, 73); 12constexpr Result ResultWrongApplicationAreaSize(ErrorModule::NFP, 68);
13constexpr Result NfcDisabled(ErrorModule::NFC, 80); 13constexpr Result ResultWrongDeviceState(ErrorModule::NFC, 73);
14constexpr Result TagRemoved(ErrorModule::NFC, 97); 14constexpr Result ResultUnknown74(ErrorModule::NFC, 74);
15 15constexpr Result ResultUnknown76(ErrorModule::NFC, 76);
16constexpr Result MifareDeviceNotFound(ErrorModule::NFCMifare, 64); 16constexpr Result ResultNfcNotInitialized(ErrorModule::NFC, 77);
17constexpr Result MifareInvalidArgument(ErrorModule::NFCMifare, 65); 17constexpr Result ResultNfcDisabled(ErrorModule::NFC, 80);
18constexpr Result MifareWrongDeviceState(ErrorModule::NFCMifare, 73); 18constexpr Result ResultWriteAmiiboFailed(ErrorModule::NFP, 88);
19constexpr Result MifareNfcDisabled(ErrorModule::NFCMifare, 80); 19constexpr Result ResultTagRemoved(ErrorModule::NFC, 97);
20constexpr Result MifareTagRemoved(ErrorModule::NFCMifare, 97); 20constexpr Result ResultRegistrationIsNotInitialized(ErrorModule::NFP, 120);
21constexpr Result MifareReadError(ErrorModule::NFCMifare, 288); 21constexpr Result ResultApplicationAreaIsNotInitialized(ErrorModule::NFP, 128);
22constexpr Result ResultCorruptedData(ErrorModule::NFP, 144);
23constexpr Result ResultWrongApplicationAreaId(ErrorModule::NFP, 152);
24constexpr Result ResultApplicationAreaExist(ErrorModule::NFP, 168);
25constexpr Result ResultNotAnAmiibo(ErrorModule::NFP, 178);
26constexpr Result ResultUnknown216(ErrorModule::NFC, 216);
22 27
23} // namespace Service::NFC 28} // namespace Service::NFC
diff --git a/src/core/hle/service/nfc/nfc_types.h b/src/core/hle/service/nfc/nfc_types.h
new file mode 100644
index 000000000..c7ebd1fdb
--- /dev/null
+++ b/src/core/hle/service/nfc/nfc_types.h
@@ -0,0 +1,90 @@
1// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-3.0-or-later
3
4#pragma once
5
6#include <array>
7
8#include "common/common_funcs.h"
9#include "common/common_types.h"
10
11namespace Service::NFC {
12enum class BackendType : u32 {
13 None,
14 Nfc,
15 Nfp,
16 Mifare,
17};
18
19// This is nn::nfc::DeviceState
20enum class DeviceState : u32 {
21 Initialized,
22 SearchingForTag,
23 TagFound,
24 TagRemoved,
25 TagMounted,
26 Unavailable,
27 Finalized,
28};
29
30// This is nn::nfc::State
31enum class State : u32 {
32 NonInitialized,
33 Initialized,
34};
35
36// This is nn::nfc::TagType
37enum class TagType : u32 {
38 None,
39 Type1, // ISO14443A RW 96-2k bytes 106kbit/s
40 Type2, // ISO14443A RW/RO 540 bytes 106kbit/s
41 Type3, // Sony FeliCa RW/RO 2k bytes 212kbit/s
42 Type4, // ISO14443A RW/RO 4k-32k bytes 424kbit/s
43 Type5, // ISO15693 RW/RO 540 bytes 106kbit/s
44};
45
46enum class PackedTagType : u8 {
47 None,
48 Type1, // ISO14443A RW 96-2k bytes 106kbit/s
49 Type2, // ISO14443A RW/RO 540 bytes 106kbit/s
50 Type3, // Sony FeliCa RW/RO 2k bytes 212kbit/s
51 Type4, // ISO14443A RW/RO 4k-32k bytes 424kbit/s
52 Type5, // ISO15693 RW/RO 540 bytes 106kbit/s
53};
54
55// This is nn::nfc::NfcProtocol
56// Verify this enum. It might be completely wrong default protocol is 0x48
57enum class NfcProtocol : u32 {
58 None,
59 TypeA = 1U << 0, // ISO14443A
60 TypeB = 1U << 1, // ISO14443B
61 TypeF = 1U << 2, // Sony FeliCa
62 Unknown1 = 1U << 3,
63 Unknown2 = 1U << 5,
64 All = 0xFFFFFFFFU,
65};
66
67// this is nn::nfc::TestWaveType
68enum class TestWaveType : u32 {
69 Unknown,
70};
71
72using UniqueSerialNumber = std::array<u8, 7>;
73using UniqueSerialNumberExtension = std::array<u8, 3>;
74
75// This is nn::nfc::DeviceHandle
76using DeviceHandle = u64;
77
78// This is nn::nfc::TagInfo
79struct TagInfo {
80 UniqueSerialNumber uuid;
81 UniqueSerialNumberExtension uuid_extension;
82 u8 uuid_length;
83 INSERT_PADDING_BYTES(0x15);
84 NfcProtocol protocol;
85 TagType tag_type;
86 INSERT_PADDING_BYTES(0x30);
87};
88static_assert(sizeof(TagInfo) == 0x58, "TagInfo is an invalid size");
89
90} // namespace Service::NFC
diff --git a/src/core/hle/service/nfc/nfc_user.cpp b/src/core/hle/service/nfc/nfc_user.cpp
deleted file mode 100644
index 7c162a4f3..000000000
--- a/src/core/hle/service/nfc/nfc_user.cpp
+++ /dev/null
@@ -1,365 +0,0 @@
1// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4#include "common/logging/log.h"
5#include "core/core.h"
6#include "core/hid/hid_types.h"
7#include "core/hle/kernel/k_event.h"
8#include "core/hle/service/ipc_helpers.h"
9#include "core/hle/service/nfc/nfc_device.h"
10#include "core/hle/service/nfc/nfc_result.h"
11#include "core/hle/service/nfc/nfc_user.h"
12#include "core/hle/service/time/clock_types.h"
13
14namespace Service::NFC {
15
16IUser::IUser(Core::System& system_)
17 : ServiceFramework{system_, "NFC::IUser"}, service_context{system_, service_name} {
18 static const FunctionInfo functions[] = {
19 {0, &IUser::Initialize, "InitializeOld"},
20 {1, &IUser::Finalize, "FinalizeOld"},
21 {2, &IUser::GetState, "GetStateOld"},
22 {3, &IUser::IsNfcEnabled, "IsNfcEnabledOld"},
23 {400, &IUser::Initialize, "Initialize"},
24 {401, &IUser::Finalize, "Finalize"},
25 {402, &IUser::GetState, "GetState"},
26 {403, &IUser::IsNfcEnabled, "IsNfcEnabled"},
27 {404, &IUser::ListDevices, "ListDevices"},
28 {405, &IUser::GetDeviceState, "GetDeviceState"},
29 {406, &IUser::GetNpadId, "GetNpadId"},
30 {407, &IUser::AttachAvailabilityChangeEvent, "AttachAvailabilityChangeEvent"},
31 {408, &IUser::StartDetection, "StartDetection"},
32 {409, &IUser::StopDetection, "StopDetection"},
33 {410, &IUser::GetTagInfo, "GetTagInfo"},
34 {411, &IUser::AttachActivateEvent, "AttachActivateEvent"},
35 {412, &IUser::AttachDeactivateEvent, "AttachDeactivateEvent"},
36 {1000, nullptr, "ReadMifare"},
37 {1001, nullptr, "WriteMifare"},
38 {1300, &IUser::SendCommandByPassThrough, "SendCommandByPassThrough"},
39 {1301, nullptr, "KeepPassThroughSession"},
40 {1302, nullptr, "ReleasePassThroughSession"},
41 };
42 RegisterHandlers(functions);
43
44 availability_change_event = service_context.CreateEvent("IUser:AvailabilityChangeEvent");
45
46 for (u32 device_index = 0; device_index < 10; device_index++) {
47 devices[device_index] =
48 std::make_shared<NfcDevice>(Core::HID::IndexToNpadIdType(device_index), system,
49 service_context, availability_change_event);
50 }
51}
52
53IUser ::~IUser() {
54 availability_change_event->Close();
55}
56
57void IUser::Initialize(HLERequestContext& ctx) {
58 LOG_INFO(Service_NFC, "called");
59
60 state = State::Initialized;
61
62 for (auto& device : devices) {
63 device->Initialize();
64 }
65
66 IPC::ResponseBuilder rb{ctx, 2, 0};
67 rb.Push(ResultSuccess);
68}
69
70void IUser::Finalize(HLERequestContext& ctx) {
71 LOG_INFO(Service_NFC, "called");
72
73 state = State::NonInitialized;
74
75 for (auto& device : devices) {
76 device->Finalize();
77 }
78
79 IPC::ResponseBuilder rb{ctx, 2};
80 rb.Push(ResultSuccess);
81}
82
83void IUser::GetState(HLERequestContext& ctx) {
84 LOG_DEBUG(Service_NFC, "called");
85
86 IPC::ResponseBuilder rb{ctx, 3};
87 rb.Push(ResultSuccess);
88 rb.PushEnum(state);
89}
90
91void IUser::IsNfcEnabled(HLERequestContext& ctx) {
92 LOG_DEBUG(Service_NFC, "called");
93
94 IPC::ResponseBuilder rb{ctx, 3};
95 rb.Push(ResultSuccess);
96 rb.Push(state != State::NonInitialized);
97}
98
99void IUser::ListDevices(HLERequestContext& ctx) {
100 LOG_DEBUG(Service_NFC, "called");
101
102 if (state == State::NonInitialized) {
103 IPC::ResponseBuilder rb{ctx, 2};
104 rb.Push(NfcDisabled);
105 return;
106 }
107
108 if (!ctx.CanWriteBuffer()) {
109 IPC::ResponseBuilder rb{ctx, 2};
110 rb.Push(InvalidArgument);
111 return;
112 }
113
114 if (ctx.GetWriteBufferSize() == 0) {
115 IPC::ResponseBuilder rb{ctx, 2};
116 rb.Push(InvalidArgument);
117 return;
118 }
119
120 std::vector<u64> nfp_devices;
121 const std::size_t max_allowed_devices = ctx.GetWriteBufferNumElements<u64>();
122
123 for (auto& device : devices) {
124 if (nfp_devices.size() >= max_allowed_devices) {
125 continue;
126 }
127 if (device->GetCurrentState() != NFP::DeviceState::Unavailable) {
128 nfp_devices.push_back(device->GetHandle());
129 }
130 }
131
132 if (nfp_devices.empty()) {
133 IPC::ResponseBuilder rb{ctx, 2};
134 rb.Push(DeviceNotFound);
135 return;
136 }
137
138 ctx.WriteBuffer(nfp_devices);
139
140 IPC::ResponseBuilder rb{ctx, 3};
141 rb.Push(ResultSuccess);
142 rb.Push(static_cast<s32>(nfp_devices.size()));
143}
144
145void IUser::GetDeviceState(HLERequestContext& ctx) {
146 IPC::RequestParser rp{ctx};
147 const auto device_handle{rp.Pop<u64>()};
148 LOG_DEBUG(Service_NFC, "called, device_handle={}", device_handle);
149
150 auto device = GetNfcDevice(device_handle);
151
152 if (!device.has_value()) {
153 IPC::ResponseBuilder rb{ctx, 2};
154 rb.Push(DeviceNotFound);
155 return;
156 }
157
158 IPC::ResponseBuilder rb{ctx, 3};
159 rb.Push(ResultSuccess);
160 rb.PushEnum(device.value()->GetCurrentState());
161}
162
163void IUser::GetNpadId(HLERequestContext& ctx) {
164 IPC::RequestParser rp{ctx};
165 const auto device_handle{rp.Pop<u64>()};
166 LOG_DEBUG(Service_NFC, "called, device_handle={}", device_handle);
167
168 if (state == State::NonInitialized) {
169 IPC::ResponseBuilder rb{ctx, 2};
170 rb.Push(NfcDisabled);
171 return;
172 }
173
174 auto device = GetNfcDevice(device_handle);
175
176 if (!device.has_value()) {
177 IPC::ResponseBuilder rb{ctx, 2};
178 rb.Push(DeviceNotFound);
179 return;
180 }
181
182 IPC::ResponseBuilder rb{ctx, 3};
183 rb.Push(ResultSuccess);
184 rb.PushEnum(device.value()->GetNpadId());
185}
186
187void IUser::AttachAvailabilityChangeEvent(HLERequestContext& ctx) {
188 LOG_INFO(Service_NFC, "called");
189
190 if (state == State::NonInitialized) {
191 IPC::ResponseBuilder rb{ctx, 2};
192 rb.Push(NfcDisabled);
193 return;
194 }
195
196 IPC::ResponseBuilder rb{ctx, 2, 1};
197 rb.Push(ResultSuccess);
198 rb.PushCopyObjects(availability_change_event->GetReadableEvent());
199}
200
201void IUser::StartDetection(HLERequestContext& ctx) {
202 IPC::RequestParser rp{ctx};
203 const auto device_handle{rp.Pop<u64>()};
204 const auto nfp_protocol{rp.PopEnum<NFP::TagProtocol>()};
205 LOG_INFO(Service_NFC, "called, device_handle={}, nfp_protocol={}", device_handle, nfp_protocol);
206
207 if (state == State::NonInitialized) {
208 IPC::ResponseBuilder rb{ctx, 2};
209 rb.Push(NfcDisabled);
210 return;
211 }
212
213 auto device = GetNfcDevice(device_handle);
214
215 if (!device.has_value()) {
216 IPC::ResponseBuilder rb{ctx, 2};
217 rb.Push(DeviceNotFound);
218 return;
219 }
220
221 const auto result = device.value()->StartDetection(nfp_protocol);
222 IPC::ResponseBuilder rb{ctx, 2};
223 rb.Push(result);
224}
225
226void IUser::StopDetection(HLERequestContext& ctx) {
227 IPC::RequestParser rp{ctx};
228 const auto device_handle{rp.Pop<u64>()};
229 LOG_INFO(Service_NFC, "called, device_handle={}", device_handle);
230
231 if (state == State::NonInitialized) {
232 IPC::ResponseBuilder rb{ctx, 2};
233 rb.Push(NfcDisabled);
234 return;
235 }
236
237 auto device = GetNfcDevice(device_handle);
238
239 if (!device.has_value()) {
240 IPC::ResponseBuilder rb{ctx, 2};
241 rb.Push(DeviceNotFound);
242 return;
243 }
244
245 const auto result = device.value()->StopDetection();
246 IPC::ResponseBuilder rb{ctx, 2};
247 rb.Push(result);
248}
249
250void IUser::GetTagInfo(HLERequestContext& ctx) {
251 IPC::RequestParser rp{ctx};
252 const auto device_handle{rp.Pop<u64>()};
253 LOG_INFO(Service_NFC, "called, device_handle={}", device_handle);
254
255 if (state == State::NonInitialized) {
256 IPC::ResponseBuilder rb{ctx, 2};
257 rb.Push(NfcDisabled);
258 return;
259 }
260
261 auto device = GetNfcDevice(device_handle);
262
263 if (!device.has_value()) {
264 IPC::ResponseBuilder rb{ctx, 2};
265 rb.Push(DeviceNotFound);
266 return;
267 }
268
269 NFP::TagInfo tag_info{};
270 const auto result = device.value()->GetTagInfo(tag_info, false);
271 ctx.WriteBuffer(tag_info);
272 IPC::ResponseBuilder rb{ctx, 2};
273 rb.Push(result);
274}
275
276void IUser::AttachActivateEvent(HLERequestContext& ctx) {
277 IPC::RequestParser rp{ctx};
278 const auto device_handle{rp.Pop<u64>()};
279 LOG_DEBUG(Service_NFC, "called, device_handle={}", device_handle);
280
281 if (state == State::NonInitialized) {
282 IPC::ResponseBuilder rb{ctx, 2};
283 rb.Push(NfcDisabled);
284 return;
285 }
286
287 auto device = GetNfcDevice(device_handle);
288
289 if (!device.has_value()) {
290 IPC::ResponseBuilder rb{ctx, 2};
291 rb.Push(DeviceNotFound);
292 return;
293 }
294
295 IPC::ResponseBuilder rb{ctx, 2, 1};
296 rb.Push(ResultSuccess);
297 rb.PushCopyObjects(device.value()->GetActivateEvent());
298}
299
300void IUser::AttachDeactivateEvent(HLERequestContext& ctx) {
301 IPC::RequestParser rp{ctx};
302 const auto device_handle{rp.Pop<u64>()};
303 LOG_DEBUG(Service_NFC, "called, device_handle={}", device_handle);
304
305 if (state == State::NonInitialized) {
306 IPC::ResponseBuilder rb{ctx, 2};
307 rb.Push(NfcDisabled);
308 return;
309 }
310
311 auto device = GetNfcDevice(device_handle);
312
313 if (!device.has_value()) {
314 IPC::ResponseBuilder rb{ctx, 2};
315 rb.Push(DeviceNotFound);
316 return;
317 }
318
319 IPC::ResponseBuilder rb{ctx, 2, 1};
320 rb.Push(ResultSuccess);
321 rb.PushCopyObjects(device.value()->GetDeactivateEvent());
322}
323
324void IUser::SendCommandByPassThrough(HLERequestContext& ctx) {
325 IPC::RequestParser rp{ctx};
326 const auto device_handle{rp.Pop<u64>()};
327 const auto timeout{rp.PopRaw<Time::Clock::TimeSpanType>()};
328 const auto command_data{ctx.ReadBuffer()};
329
330 LOG_INFO(Service_NFC, "(STUBBED) called, device_handle={}, timeout={}, data_size={}",
331 device_handle, timeout.ToSeconds(), command_data.size());
332
333 if (state == State::NonInitialized) {
334 IPC::ResponseBuilder rb{ctx, 2};
335 rb.Push(NfcDisabled);
336 return;
337 }
338
339 auto device = GetNfcDevice(device_handle);
340
341 if (!device.has_value()) {
342 IPC::ResponseBuilder rb{ctx, 2};
343 rb.Push(DeviceNotFound);
344 return;
345 }
346
347 std::vector<u8> out_data(1);
348 // TODO: Request data from nfc device
349 ctx.WriteBuffer(out_data);
350
351 IPC::ResponseBuilder rb{ctx, 3};
352 rb.Push(ResultSuccess);
353 rb.Push(static_cast<u32>(out_data.size()));
354}
355
356std::optional<std::shared_ptr<NfcDevice>> IUser::GetNfcDevice(u64 handle) {
357 for (auto& device : devices) {
358 if (device->GetHandle() == handle) {
359 return device;
360 }
361 }
362 return std::nullopt;
363}
364
365} // namespace Service::NFC
diff --git a/src/core/hle/service/nfp/nfp.cpp b/src/core/hle/service/nfp/nfp.cpp
index 2714f4bea..2eeabc138 100644
--- a/src/core/hle/service/nfp/nfp.cpp
+++ b/src/core/hle/service/nfp/nfp.cpp
@@ -13,7 +13,7 @@ class IUser final : public Interface {
13public: 13public:
14 explicit IUser(Core::System& system_) : Interface(system_, "NFP:IUser") { 14 explicit IUser(Core::System& system_) : Interface(system_, "NFP:IUser") {
15 // clang-format off 15 // clang-format off
16 static const FunctionInfo functions[] = { 16 static const FunctionInfoTyped<IUser> functions[] = {
17 {0, &IUser::Initialize, "Initialize"}, 17 {0, &IUser::Initialize, "Initialize"},
18 {1, &IUser::Finalize, "Finalize"}, 18 {1, &IUser::Finalize, "Finalize"},
19 {2, &IUser::ListDevices, "ListDevices"}, 19 {2, &IUser::ListDevices, "ListDevices"},
@@ -50,7 +50,7 @@ class ISystem final : public Interface {
50public: 50public:
51 explicit ISystem(Core::System& system_) : Interface(system_, "NFP:ISystem") { 51 explicit ISystem(Core::System& system_) : Interface(system_, "NFP:ISystem") {
52 // clang-format off 52 // clang-format off
53 static const FunctionInfo functions[] = { 53 static const FunctionInfoTyped<ISystem> functions[] = {
54 {0, &ISystem::InitializeSystem, "InitializeSystem"}, 54 {0, &ISystem::InitializeSystem, "InitializeSystem"},
55 {1, &ISystem::FinalizeSystem, "FinalizeSystem"}, 55 {1, &ISystem::FinalizeSystem, "FinalizeSystem"},
56 {2, &ISystem::ListDevices, "ListDevices"}, 56 {2, &ISystem::ListDevices, "ListDevices"},
@@ -89,7 +89,7 @@ class IDebug final : public Interface {
89public: 89public:
90 explicit IDebug(Core::System& system_) : Interface(system_, "NFP:IDebug") { 90 explicit IDebug(Core::System& system_) : Interface(system_, "NFP:IDebug") {
91 // clang-format off 91 // clang-format off
92 static const FunctionInfo functions[] = { 92 static const FunctionInfoTyped<IDebug> functions[] = {
93 {0, &IDebug::InitializeDebug, "InitializeDebug"}, 93 {0, &IDebug::InitializeDebug, "InitializeDebug"},
94 {1, &IDebug::FinalizeDebug, "FinalizeDebug"}, 94 {1, &IDebug::FinalizeDebug, "FinalizeDebug"},
95 {2, &IDebug::ListDevices, "ListDevices"}, 95 {2, &IDebug::ListDevices, "ListDevices"},
@@ -126,9 +126,9 @@ public:
126 {201, &IDebug::SetAll, "SetAll"}, 126 {201, &IDebug::SetAll, "SetAll"},
127 {202, &IDebug::FlushDebug, "FlushDebug"}, 127 {202, &IDebug::FlushDebug, "FlushDebug"},
128 {203, &IDebug::BreakTag, "BreakTag"}, 128 {203, &IDebug::BreakTag, "BreakTag"},
129 {204, nullptr, "ReadBackupData"}, 129 {204, &IDebug::ReadBackupData, "ReadBackupData"},
130 {205, nullptr, "WriteBackupData"}, 130 {205, &IDebug::WriteBackupData, "WriteBackupData"},
131 {206, nullptr, "WriteNtf"}, 131 {206, &IDebug::WriteNtf, "WriteNtf"},
132 }; 132 };
133 // clang-format on 133 // clang-format on
134 134
@@ -152,16 +152,10 @@ private:
152 void CreateUserInterface(HLERequestContext& ctx) { 152 void CreateUserInterface(HLERequestContext& ctx) {
153 LOG_DEBUG(Service_NFP, "called"); 153 LOG_DEBUG(Service_NFP, "called");
154 154
155 if (user_interface == nullptr) {
156 user_interface = std::make_shared<IUser>(system);
157 }
158
159 IPC::ResponseBuilder rb{ctx, 2, 0, 1}; 155 IPC::ResponseBuilder rb{ctx, 2, 0, 1};
160 rb.Push(ResultSuccess); 156 rb.Push(ResultSuccess);
161 rb.PushIpcInterface<IUser>(user_interface); 157 rb.PushIpcInterface<IUser>(system);
162 } 158 }
163
164 std::shared_ptr<IUser> user_interface;
165}; 159};
166 160
167class ISystemManager final : public ServiceFramework<ISystemManager> { 161class ISystemManager final : public ServiceFramework<ISystemManager> {
@@ -180,16 +174,10 @@ private:
180 void CreateSystemInterface(HLERequestContext& ctx) { 174 void CreateSystemInterface(HLERequestContext& ctx) {
181 LOG_DEBUG(Service_NFP, "called"); 175 LOG_DEBUG(Service_NFP, "called");
182 176
183 if (system_interface == nullptr) {
184 system_interface = std::make_shared<ISystem>(system);
185 }
186
187 IPC::ResponseBuilder rb{ctx, 2, 0, 1}; 177 IPC::ResponseBuilder rb{ctx, 2, 0, 1};
188 rb.Push(ResultSuccess); 178 rb.Push(ResultSuccess);
189 rb.PushIpcInterface<ISystem>(system_interface); 179 rb.PushIpcInterface<ISystem>(system);
190 } 180 }
191
192 std::shared_ptr<ISystem> system_interface;
193}; 181};
194 182
195class IDebugManager final : public ServiceFramework<IDebugManager> { 183class IDebugManager final : public ServiceFramework<IDebugManager> {
@@ -208,16 +196,10 @@ private:
208 void CreateDebugInterface(HLERequestContext& ctx) { 196 void CreateDebugInterface(HLERequestContext& ctx) {
209 LOG_DEBUG(Service_NFP, "called"); 197 LOG_DEBUG(Service_NFP, "called");
210 198
211 if (system_interface == nullptr) {
212 system_interface = std::make_shared<IDebug>(system);
213 }
214
215 IPC::ResponseBuilder rb{ctx, 2, 0, 1}; 199 IPC::ResponseBuilder rb{ctx, 2, 0, 1};
216 rb.Push(ResultSuccess); 200 rb.Push(ResultSuccess);
217 rb.PushIpcInterface<IDebug>(system_interface); 201 rb.PushIpcInterface<IDebug>(system);
218 } 202 }
219
220 std::shared_ptr<IDebug> system_interface;
221}; 203};
222 204
223void LoopProcess(Core::System& system) { 205void LoopProcess(Core::System& system) {
diff --git a/src/core/hle/service/nfp/nfp_device.h b/src/core/hle/service/nfp/nfp_device.h
deleted file mode 100644
index bab05538a..000000000
--- a/src/core/hle/service/nfp/nfp_device.h
+++ /dev/null
@@ -1,120 +0,0 @@
1// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4#pragma once
5
6#include <span>
7#include <vector>
8
9#include "common/common_types.h"
10#include "core/hle/service/kernel_helpers.h"
11#include "core/hle/service/nfp/nfp_types.h"
12#include "core/hle/service/service.h"
13
14namespace Kernel {
15class KEvent;
16class KReadableEvent;
17} // namespace Kernel
18
19namespace Core {
20class System;
21} // namespace Core
22
23namespace Core::HID {
24class EmulatedController;
25enum class ControllerTriggerType;
26enum class NpadIdType : u32;
27} // namespace Core::HID
28
29namespace Service::NFP {
30class NfpDevice {
31public:
32 NfpDevice(Core::HID::NpadIdType npad_id_, Core::System& system_,
33 KernelHelpers::ServiceContext& service_context_,
34 Kernel::KEvent* availability_change_event_);
35 ~NfpDevice();
36
37 void Initialize();
38 void Finalize();
39
40 Result StartDetection(TagProtocol allowed_protocol);
41 Result StopDetection();
42 Result Mount(MountTarget mount_target);
43 Result Unmount();
44
45 Result Flush();
46 Result FlushDebug();
47 Result FlushWithBreak(BreakType break_type);
48
49 Result GetTagInfo(TagInfo& tag_info) const;
50 Result GetCommonInfo(CommonInfo& common_info) const;
51 Result GetModelInfo(ModelInfo& model_info) const;
52 Result GetRegisterInfo(RegisterInfo& register_info) const;
53 Result GetRegisterInfoPrivate(RegisterInfoPrivate& register_info) const;
54 Result GetAdminInfo(AdminInfo& admin_info) const;
55
56 Result DeleteRegisterInfo();
57 Result SetRegisterInfoPrivate(const AmiiboName& amiibo_name);
58 Result RestoreAmiibo();
59 Result Format();
60
61 Result OpenApplicationArea(u32 access_id);
62 Result GetApplicationAreaId(u32& application_area_id) const;
63 Result GetApplicationArea(std::vector<u8>& data) const;
64 Result SetApplicationArea(std::span<const u8> data);
65 Result CreateApplicationArea(u32 access_id, std::span<const u8> data);
66 Result RecreateApplicationArea(u32 access_id, std::span<const u8> data);
67 Result DeleteApplicationArea();
68 Result ExistApplicationArea(bool& has_application_area);
69
70 Result GetAll(NfpData& data) const;
71 Result SetAll(const NfpData& data);
72 Result BreakTag(BreakType break_type);
73 Result ReadBackupData();
74 Result WriteBackupData();
75 Result WriteNtf();
76
77 u64 GetHandle() const;
78 u32 GetApplicationAreaSize() const;
79 DeviceState GetCurrentState() const;
80 Core::HID::NpadIdType GetNpadId() const;
81
82 Kernel::KReadableEvent& GetActivateEvent() const;
83 Kernel::KReadableEvent& GetDeactivateEvent() const;
84
85private:
86 void NpadUpdate(Core::HID::ControllerTriggerType type);
87 bool LoadAmiibo(std::span<const u8> data);
88 void CloseAmiibo();
89
90 AmiiboName GetAmiiboName(const AmiiboSettings& settings) const;
91 void SetAmiiboName(AmiiboSettings& settings, const AmiiboName& amiibo_name);
92 AmiiboDate GetAmiiboDate(s64 posix_time) const;
93 u64 RemoveVersionByte(u64 application_id) const;
94 void UpdateSettingsCrc();
95 void UpdateRegisterInfoCrc();
96
97 bool is_controller_set{};
98 int callback_key;
99 const Core::HID::NpadIdType npad_id;
100 Core::System& system;
101 Core::HID::EmulatedController* npad_device = nullptr;
102 KernelHelpers::ServiceContext& service_context;
103 Kernel::KEvent* activate_event = nullptr;
104 Kernel::KEvent* deactivate_event = nullptr;
105 Kernel::KEvent* availability_change_event = nullptr;
106
107 bool is_initalized{};
108 bool is_data_moddified{};
109 bool is_app_area_open{};
110 bool is_plain_amiibo{};
111 TagProtocol allowed_protocols{};
112 s64 current_posix_time{};
113 MountTarget mount_target{MountTarget::None};
114 DeviceState device_state{DeviceState::Unavailable};
115
116 NTAG215File tag_data{};
117 EncryptedNTAG215File encrypted_tag_data{};
118};
119
120} // namespace Service::NFP
diff --git a/src/core/hle/service/nfp/nfp_interface.cpp b/src/core/hle/service/nfp/nfp_interface.cpp
index 2ed8bb1ba..21d159154 100644
--- a/src/core/hle/service/nfp/nfp_interface.cpp
+++ b/src/core/hle/service/nfp/nfp_interface.cpp
@@ -1,4 +1,4 @@
1// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project 1// SPDX-FileCopyrightText: Copyright 2023 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/logging/log.h" 4#include "common/logging/log.h"
@@ -6,198 +6,34 @@
6#include "core/hid/hid_types.h" 6#include "core/hid/hid_types.h"
7#include "core/hle/kernel/k_event.h" 7#include "core/hle/kernel/k_event.h"
8#include "core/hle/service/ipc_helpers.h" 8#include "core/hle/service/ipc_helpers.h"
9#include "core/hle/service/nfp/nfp_device.h" 9#include "core/hle/service/nfc/common/device.h"
10#include "core/hle/service/nfc/common/device_manager.h"
11#include "core/hle/service/nfc/nfc_types.h"
10#include "core/hle/service/nfp/nfp_interface.h" 12#include "core/hle/service/nfp/nfp_interface.h"
11#include "core/hle/service/nfp/nfp_result.h" 13#include "core/hle/service/nfp/nfp_result.h"
14#include "core/hle/service/nfp/nfp_types.h"
12 15
13namespace Service::NFP { 16namespace Service::NFP {
14 17
15Interface::Interface(Core::System& system_, const char* name) 18Interface::Interface(Core::System& system_, const char* name)
16 : ServiceFramework{system_, name}, service_context{system_, service_name} { 19 : NfcInterface{system_, name, NFC::BackendType::Nfp} {}
17 availability_change_event = service_context.CreateEvent("IUser:AvailabilityChangeEvent");
18 20
19 for (u32 device_index = 0; device_index < 10; device_index++) { 21Interface::~Interface() = default;
20 devices[device_index] =
21 std::make_shared<NfpDevice>(Core::HID::IndexToNpadIdType(device_index), system,
22 service_context, availability_change_event);
23 }
24}
25
26Interface::~Interface() {
27 availability_change_event->Close();
28}
29
30void Interface::Initialize(HLERequestContext& ctx) {
31 LOG_INFO(Service_NFP, "called");
32
33 state = State::Initialized;
34
35 for (auto& device : devices) {
36 device->Initialize();
37 }
38
39 IPC::ResponseBuilder rb{ctx, 2};
40 rb.Push(ResultSuccess);
41}
42 22
43void Interface::InitializeSystem(HLERequestContext& ctx) { 23void Interface::InitializeSystem(HLERequestContext& ctx) {
44 LOG_INFO(Service_NFP, "called"); 24 Initialize(ctx);
45
46 state = State::Initialized;
47
48 for (auto& device : devices) {
49 device->Initialize();
50 }
51
52 IPC::ResponseBuilder rb{ctx, 2};
53 rb.Push(ResultSuccess);
54} 25}
55 26
56void Interface::InitializeDebug(HLERequestContext& ctx) { 27void Interface::InitializeDebug(HLERequestContext& ctx) {
57 LOG_INFO(Service_NFP, "called"); 28 Initialize(ctx);
58
59 state = State::Initialized;
60
61 for (auto& device : devices) {
62 device->Initialize();
63 }
64
65 IPC::ResponseBuilder rb{ctx, 2};
66 rb.Push(ResultSuccess);
67}
68
69void Interface::Finalize(HLERequestContext& ctx) {
70 LOG_INFO(Service_NFP, "called");
71
72 state = State::NonInitialized;
73
74 for (auto& device : devices) {
75 device->Finalize();
76 }
77
78 IPC::ResponseBuilder rb{ctx, 2};
79 rb.Push(ResultSuccess);
80} 29}
81 30
82void Interface::FinalizeSystem(HLERequestContext& ctx) { 31void Interface::FinalizeSystem(HLERequestContext& ctx) {
83 LOG_INFO(Service_NFP, "called"); 32 Finalize(ctx);
84
85 state = State::NonInitialized;
86
87 for (auto& device : devices) {
88 device->Finalize();
89 }
90
91 IPC::ResponseBuilder rb{ctx, 2};
92 rb.Push(ResultSuccess);
93} 33}
94 34
95void Interface::FinalizeDebug(HLERequestContext& ctx) { 35void Interface::FinalizeDebug(HLERequestContext& ctx) {
96 LOG_INFO(Service_NFP, "called"); 36 Finalize(ctx);
97
98 state = State::NonInitialized;
99
100 for (auto& device : devices) {
101 device->Finalize();
102 }
103
104 IPC::ResponseBuilder rb{ctx, 2};
105 rb.Push(ResultSuccess);
106}
107
108void Interface::ListDevices(HLERequestContext& ctx) {
109 LOG_DEBUG(Service_NFP, "called");
110
111 if (state == State::NonInitialized) {
112 IPC::ResponseBuilder rb{ctx, 2};
113 rb.Push(NfcDisabled);
114 return;
115 }
116
117 if (!ctx.CanWriteBuffer()) {
118 IPC::ResponseBuilder rb{ctx, 2};
119 rb.Push(InvalidArgument);
120 return;
121 }
122
123 if (ctx.GetWriteBufferSize() == 0) {
124 IPC::ResponseBuilder rb{ctx, 2};
125 rb.Push(InvalidArgument);
126 return;
127 }
128
129 std::vector<u64> nfp_devices;
130 const std::size_t max_allowed_devices = ctx.GetWriteBufferNumElements<u64>();
131
132 for (const auto& device : devices) {
133 if (nfp_devices.size() >= max_allowed_devices) {
134 continue;
135 }
136 if (device->GetCurrentState() != DeviceState::Unavailable) {
137 nfp_devices.push_back(device->GetHandle());
138 }
139 }
140
141 if (nfp_devices.empty()) {
142 IPC::ResponseBuilder rb{ctx, 2};
143 rb.Push(DeviceNotFound);
144 return;
145 }
146
147 ctx.WriteBuffer(nfp_devices);
148
149 IPC::ResponseBuilder rb{ctx, 3};
150 rb.Push(ResultSuccess);
151 rb.Push(static_cast<s32>(nfp_devices.size()));
152}
153
154void Interface::StartDetection(HLERequestContext& ctx) {
155 IPC::RequestParser rp{ctx};
156 const auto device_handle{rp.Pop<u64>()};
157 const auto nfp_protocol{rp.PopEnum<TagProtocol>()};
158 LOG_INFO(Service_NFP, "called, device_handle={}, nfp_protocol={}", device_handle, nfp_protocol);
159
160 if (state == State::NonInitialized) {
161 IPC::ResponseBuilder rb{ctx, 2};
162 rb.Push(NfcDisabled);
163 return;
164 }
165
166 auto device = GetNfpDevice(device_handle);
167
168 if (!device.has_value()) {
169 IPC::ResponseBuilder rb{ctx, 2};
170 rb.Push(DeviceNotFound);
171 return;
172 }
173
174 const auto result = device.value()->StartDetection(nfp_protocol);
175 IPC::ResponseBuilder rb{ctx, 2};
176 rb.Push(result);
177}
178
179void Interface::StopDetection(HLERequestContext& ctx) {
180 IPC::RequestParser rp{ctx};
181 const auto device_handle{rp.Pop<u64>()};
182 LOG_INFO(Service_NFP, "called, device_handle={}", device_handle);
183
184 if (state == State::NonInitialized) {
185 IPC::ResponseBuilder rb{ctx, 2};
186 rb.Push(NfcDisabled);
187 return;
188 }
189
190 auto device = GetNfpDevice(device_handle);
191
192 if (!device.has_value()) {
193 IPC::ResponseBuilder rb{ctx, 2};
194 rb.Push(DeviceNotFound);
195 return;
196 }
197
198 const auto result = device.value()->StopDetection();
199 IPC::ResponseBuilder rb{ctx, 2};
200 rb.Push(result);
201} 37}
202 38
203void Interface::Mount(HLERequestContext& ctx) { 39void Interface::Mount(HLERequestContext& ctx) {
@@ -208,21 +44,9 @@ void Interface::Mount(HLERequestContext& ctx) {
208 LOG_INFO(Service_NFP, "called, device_handle={}, model_type={}, mount_target={}", device_handle, 44 LOG_INFO(Service_NFP, "called, device_handle={}, model_type={}, mount_target={}", device_handle,
209 model_type, mount_target); 45 model_type, mount_target);
210 46
211 if (state == State::NonInitialized) { 47 auto result = GetManager()->Mount(device_handle, model_type, mount_target);
212 IPC::ResponseBuilder rb{ctx, 2}; 48 result = TranslateResultToServiceError(result);
213 rb.Push(NfcDisabled);
214 return;
215 }
216
217 auto device = GetNfpDevice(device_handle);
218
219 if (!device.has_value()) {
220 IPC::ResponseBuilder rb{ctx, 2};
221 rb.Push(DeviceNotFound);
222 return;
223 }
224 49
225 const auto result = device.value()->Mount(mount_target);
226 IPC::ResponseBuilder rb{ctx, 2}; 50 IPC::ResponseBuilder rb{ctx, 2};
227 rb.Push(result); 51 rb.Push(result);
228} 52}
@@ -232,21 +56,9 @@ void Interface::Unmount(HLERequestContext& ctx) {
232 const auto device_handle{rp.Pop<u64>()}; 56 const auto device_handle{rp.Pop<u64>()};
233 LOG_INFO(Service_NFP, "called, device_handle={}", device_handle); 57 LOG_INFO(Service_NFP, "called, device_handle={}", device_handle);
234 58
235 if (state == State::NonInitialized) { 59 auto result = GetManager()->Unmount(device_handle);
236 IPC::ResponseBuilder rb{ctx, 2}; 60 result = TranslateResultToServiceError(result);
237 rb.Push(NfcDisabled);
238 return;
239 }
240
241 auto device = GetNfpDevice(device_handle);
242
243 if (!device.has_value()) {
244 IPC::ResponseBuilder rb{ctx, 2};
245 rb.Push(DeviceNotFound);
246 return;
247 }
248 61
249 const auto result = device.value()->Unmount();
250 IPC::ResponseBuilder rb{ctx, 2}; 62 IPC::ResponseBuilder rb{ctx, 2};
251 rb.Push(result); 63 rb.Push(result);
252} 64}
@@ -257,21 +69,9 @@ void Interface::OpenApplicationArea(HLERequestContext& ctx) {
257 const auto access_id{rp.Pop<u32>()}; 69 const auto access_id{rp.Pop<u32>()};
258 LOG_INFO(Service_NFP, "called, device_handle={}, access_id={}", device_handle, access_id); 70 LOG_INFO(Service_NFP, "called, device_handle={}, access_id={}", device_handle, access_id);
259 71
260 if (state == State::NonInitialized) { 72 auto result = GetManager()->OpenApplicationArea(device_handle, access_id);
261 IPC::ResponseBuilder rb{ctx, 2}; 73 result = TranslateResultToServiceError(result);
262 rb.Push(NfcDisabled);
263 return;
264 }
265
266 auto device = GetNfpDevice(device_handle);
267
268 if (!device.has_value()) {
269 IPC::ResponseBuilder rb{ctx, 2};
270 rb.Push(DeviceNotFound);
271 return;
272 }
273 74
274 const auto result = device.value()->OpenApplicationArea(access_id);
275 IPC::ResponseBuilder rb{ctx, 2}; 75 IPC::ResponseBuilder rb{ctx, 2};
276 rb.Push(result); 76 rb.Push(result);
277} 77}
@@ -282,28 +82,16 @@ void Interface::GetApplicationArea(HLERequestContext& ctx) {
282 const auto data_size = ctx.GetWriteBufferSize(); 82 const auto data_size = ctx.GetWriteBufferSize();
283 LOG_INFO(Service_NFP, "called, device_handle={}", device_handle); 83 LOG_INFO(Service_NFP, "called, device_handle={}", device_handle);
284 84
285 if (state == State::NonInitialized) { 85 std::vector<u8> data(data_size);
286 IPC::ResponseBuilder rb{ctx, 2}; 86 auto result = GetManager()->GetApplicationArea(device_handle, data);
287 rb.Push(NfcDisabled); 87 result = TranslateResultToServiceError(result);
288 return;
289 }
290
291 if (!ctx.CanWriteBuffer()) {
292 IPC::ResponseBuilder rb{ctx, 2};
293 rb.Push(InvalidArgument);
294 return;
295 }
296
297 auto device = GetNfpDevice(device_handle);
298 88
299 if (!device.has_value()) { 89 if (result.IsError()) {
300 IPC::ResponseBuilder rb{ctx, 2}; 90 IPC::ResponseBuilder rb{ctx, 2};
301 rb.Push(DeviceNotFound); 91 rb.Push(result);
302 return; 92 return;
303 } 93 }
304 94
305 std::vector<u8> data(data_size);
306 const auto result = device.value()->GetApplicationArea(data);
307 ctx.WriteBuffer(data); 95 ctx.WriteBuffer(data);
308 IPC::ResponseBuilder rb{ctx, 3}; 96 IPC::ResponseBuilder rb{ctx, 3};
309 rb.Push(result); 97 rb.Push(result);
@@ -316,27 +104,9 @@ void Interface::SetApplicationArea(HLERequestContext& ctx) {
316 const auto data{ctx.ReadBuffer()}; 104 const auto data{ctx.ReadBuffer()};
317 LOG_INFO(Service_NFP, "called, device_handle={}, data_size={}", device_handle, data.size()); 105 LOG_INFO(Service_NFP, "called, device_handle={}, data_size={}", device_handle, data.size());
318 106
319 if (state == State::NonInitialized) { 107 auto result = GetManager()->SetApplicationArea(device_handle, data);
320 IPC::ResponseBuilder rb{ctx, 2}; 108 result = TranslateResultToServiceError(result);
321 rb.Push(NfcDisabled);
322 return;
323 }
324
325 if (!ctx.CanReadBuffer()) {
326 IPC::ResponseBuilder rb{ctx, 2};
327 rb.Push(InvalidArgument);
328 return;
329 }
330
331 auto device = GetNfpDevice(device_handle);
332
333 if (!device.has_value()) {
334 IPC::ResponseBuilder rb{ctx, 2};
335 rb.Push(DeviceNotFound);
336 return;
337 }
338 109
339 const auto result = device.value()->SetApplicationArea(data);
340 IPC::ResponseBuilder rb{ctx, 2}; 110 IPC::ResponseBuilder rb{ctx, 2};
341 rb.Push(result); 111 rb.Push(result);
342} 112}
@@ -346,21 +116,9 @@ void Interface::Flush(HLERequestContext& ctx) {
346 const auto device_handle{rp.Pop<u64>()}; 116 const auto device_handle{rp.Pop<u64>()};
347 LOG_INFO(Service_NFP, "called, device_handle={}", device_handle); 117 LOG_INFO(Service_NFP, "called, device_handle={}", device_handle);
348 118
349 if (state == State::NonInitialized) { 119 auto result = GetManager()->Flush(device_handle);
350 IPC::ResponseBuilder rb{ctx, 2}; 120 result = TranslateResultToServiceError(result);
351 rb.Push(NfcDisabled);
352 return;
353 }
354
355 auto device = GetNfpDevice(device_handle);
356 121
357 if (!device.has_value()) {
358 IPC::ResponseBuilder rb{ctx, 2};
359 rb.Push(DeviceNotFound);
360 return;
361 }
362
363 const auto result = device.value()->Flush();
364 IPC::ResponseBuilder rb{ctx, 2}; 122 IPC::ResponseBuilder rb{ctx, 2};
365 rb.Push(result); 123 rb.Push(result);
366} 124}
@@ -370,21 +128,9 @@ void Interface::Restore(HLERequestContext& ctx) {
370 const auto device_handle{rp.Pop<u64>()}; 128 const auto device_handle{rp.Pop<u64>()};
371 LOG_WARNING(Service_NFP, "(STUBBED) called, device_handle={}", device_handle); 129 LOG_WARNING(Service_NFP, "(STUBBED) called, device_handle={}", device_handle);
372 130
373 if (state == State::NonInitialized) { 131 auto result = GetManager()->Restore(device_handle);
374 IPC::ResponseBuilder rb{ctx, 2}; 132 result = TranslateResultToServiceError(result);
375 rb.Push(NfcDisabled);
376 return;
377 }
378 133
379 auto device = GetNfpDevice(device_handle);
380
381 if (!device.has_value()) {
382 IPC::ResponseBuilder rb{ctx, 2};
383 rb.Push(DeviceNotFound);
384 return;
385 }
386
387 const auto result = device.value()->RestoreAmiibo();
388 IPC::ResponseBuilder rb{ctx, 2}; 134 IPC::ResponseBuilder rb{ctx, 2};
389 rb.Push(result); 135 rb.Push(result);
390} 136}
@@ -397,53 +143,9 @@ void Interface::CreateApplicationArea(HLERequestContext& ctx) {
397 LOG_INFO(Service_NFP, "called, device_handle={}, data_size={}, access_id={}", device_handle, 143 LOG_INFO(Service_NFP, "called, device_handle={}, data_size={}, access_id={}", device_handle,
398 access_id, data.size()); 144 access_id, data.size());
399 145
400 if (state == State::NonInitialized) { 146 auto result = GetManager()->CreateApplicationArea(device_handle, access_id, data);
401 IPC::ResponseBuilder rb{ctx, 2}; 147 result = TranslateResultToServiceError(result);
402 rb.Push(NfcDisabled);
403 return;
404 }
405
406 if (!ctx.CanReadBuffer()) {
407 IPC::ResponseBuilder rb{ctx, 2};
408 rb.Push(InvalidArgument);
409 return;
410 }
411
412 auto device = GetNfpDevice(device_handle);
413
414 if (!device.has_value()) {
415 IPC::ResponseBuilder rb{ctx, 2};
416 rb.Push(DeviceNotFound);
417 return;
418 }
419
420 const auto result = device.value()->CreateApplicationArea(access_id, data);
421 IPC::ResponseBuilder rb{ctx, 2};
422 rb.Push(result);
423}
424
425void Interface::GetTagInfo(HLERequestContext& ctx) {
426 IPC::RequestParser rp{ctx};
427 const auto device_handle{rp.Pop<u64>()};
428 LOG_INFO(Service_NFP, "called, device_handle={}", device_handle);
429
430 if (state == State::NonInitialized) {
431 IPC::ResponseBuilder rb{ctx, 2};
432 rb.Push(NfcDisabled);
433 return;
434 }
435
436 auto device = GetNfpDevice(device_handle);
437
438 if (!device.has_value()) {
439 IPC::ResponseBuilder rb{ctx, 2};
440 rb.Push(DeviceNotFound);
441 return;
442 }
443 148
444 TagInfo tag_info{};
445 const auto result = device.value()->GetTagInfo(tag_info);
446 ctx.WriteBuffer(tag_info);
447 IPC::ResponseBuilder rb{ctx, 2}; 149 IPC::ResponseBuilder rb{ctx, 2};
448 rb.Push(result); 150 rb.Push(result);
449} 151}
@@ -453,23 +155,14 @@ void Interface::GetRegisterInfo(HLERequestContext& ctx) {
453 const auto device_handle{rp.Pop<u64>()}; 155 const auto device_handle{rp.Pop<u64>()};
454 LOG_INFO(Service_NFP, "called, device_handle={}", device_handle); 156 LOG_INFO(Service_NFP, "called, device_handle={}", device_handle);
455 157
456 if (state == State::NonInitialized) { 158 RegisterInfo register_info{};
457 IPC::ResponseBuilder rb{ctx, 2}; 159 auto result = GetManager()->GetRegisterInfo(device_handle, register_info);
458 rb.Push(NfcDisabled); 160 result = TranslateResultToServiceError(result);
459 return;
460 }
461
462 auto device = GetNfpDevice(device_handle);
463 161
464 if (!device.has_value()) { 162 if (result.IsSuccess()) {
465 IPC::ResponseBuilder rb{ctx, 2}; 163 ctx.WriteBuffer(register_info);
466 rb.Push(DeviceNotFound);
467 return;
468 } 164 }
469 165
470 RegisterInfo register_info{};
471 const auto result = device.value()->GetRegisterInfo(register_info);
472 ctx.WriteBuffer(register_info);
473 IPC::ResponseBuilder rb{ctx, 2}; 166 IPC::ResponseBuilder rb{ctx, 2};
474 rb.Push(result); 167 rb.Push(result);
475} 168}
@@ -479,23 +172,14 @@ void Interface::GetCommonInfo(HLERequestContext& ctx) {
479 const auto device_handle{rp.Pop<u64>()}; 172 const auto device_handle{rp.Pop<u64>()};
480 LOG_INFO(Service_NFP, "called, device_handle={}", device_handle); 173 LOG_INFO(Service_NFP, "called, device_handle={}", device_handle);
481 174
482 if (state == State::NonInitialized) { 175 CommonInfo common_info{};
483 IPC::ResponseBuilder rb{ctx, 2}; 176 auto result = GetManager()->GetCommonInfo(device_handle, common_info);
484 rb.Push(NfcDisabled); 177 result = TranslateResultToServiceError(result);
485 return;
486 }
487
488 auto device = GetNfpDevice(device_handle);
489 178
490 if (!device.has_value()) { 179 if (result.IsSuccess()) {
491 IPC::ResponseBuilder rb{ctx, 2}; 180 ctx.WriteBuffer(common_info);
492 rb.Push(DeviceNotFound);
493 return;
494 } 181 }
495 182
496 CommonInfo common_info{};
497 const auto result = device.value()->GetCommonInfo(common_info);
498 ctx.WriteBuffer(common_info);
499 IPC::ResponseBuilder rb{ctx, 2}; 183 IPC::ResponseBuilder rb{ctx, 2};
500 rb.Push(result); 184 rb.Push(result);
501} 185}
@@ -505,155 +189,26 @@ void Interface::GetModelInfo(HLERequestContext& ctx) {
505 const auto device_handle{rp.Pop<u64>()}; 189 const auto device_handle{rp.Pop<u64>()};
506 LOG_INFO(Service_NFP, "called, device_handle={}", device_handle); 190 LOG_INFO(Service_NFP, "called, device_handle={}", device_handle);
507 191
508 if (state == State::NonInitialized) { 192 ModelInfo model_info{};
509 IPC::ResponseBuilder rb{ctx, 2}; 193 auto result = GetManager()->GetModelInfo(device_handle, model_info);
510 rb.Push(NfcDisabled); 194 result = TranslateResultToServiceError(result);
511 return;
512 }
513
514 auto device = GetNfpDevice(device_handle);
515 195
516 if (!device.has_value()) { 196 if (result.IsSuccess()) {
517 IPC::ResponseBuilder rb{ctx, 2}; 197 ctx.WriteBuffer(model_info);
518 rb.Push(DeviceNotFound);
519 return;
520 } 198 }
521 199
522 ModelInfo model_info{};
523 const auto result = device.value()->GetModelInfo(model_info);
524 ctx.WriteBuffer(model_info);
525 IPC::ResponseBuilder rb{ctx, 2}; 200 IPC::ResponseBuilder rb{ctx, 2};
526 rb.Push(result); 201 rb.Push(result);
527} 202}
528 203
529void Interface::AttachActivateEvent(HLERequestContext& ctx) {
530 IPC::RequestParser rp{ctx};
531 const auto device_handle{rp.Pop<u64>()};
532 LOG_DEBUG(Service_NFP, "called, device_handle={}", device_handle);
533
534 if (state == State::NonInitialized) {
535 IPC::ResponseBuilder rb{ctx, 2};
536 rb.Push(NfcDisabled);
537 return;
538 }
539
540 auto device = GetNfpDevice(device_handle);
541
542 if (!device.has_value()) {
543 IPC::ResponseBuilder rb{ctx, 2};
544 rb.Push(DeviceNotFound);
545 return;
546 }
547
548 IPC::ResponseBuilder rb{ctx, 2, 1};
549 rb.Push(ResultSuccess);
550 rb.PushCopyObjects(device.value()->GetActivateEvent());
551}
552
553void Interface::AttachDeactivateEvent(HLERequestContext& ctx) {
554 IPC::RequestParser rp{ctx};
555 const auto device_handle{rp.Pop<u64>()};
556 LOG_DEBUG(Service_NFP, "called, device_handle={}", device_handle);
557
558 if (state == State::NonInitialized) {
559 IPC::ResponseBuilder rb{ctx, 2};
560 rb.Push(NfcDisabled);
561 return;
562 }
563
564 auto device = GetNfpDevice(device_handle);
565
566 if (!device.has_value()) {
567 IPC::ResponseBuilder rb{ctx, 2};
568 rb.Push(DeviceNotFound);
569 return;
570 }
571
572 IPC::ResponseBuilder rb{ctx, 2, 1};
573 rb.Push(ResultSuccess);
574 rb.PushCopyObjects(device.value()->GetDeactivateEvent());
575}
576
577void Interface::GetState(HLERequestContext& ctx) {
578 LOG_DEBUG(Service_NFP, "called");
579
580 IPC::ResponseBuilder rb{ctx, 3};
581 rb.Push(ResultSuccess);
582 rb.PushEnum(state);
583}
584
585void Interface::GetDeviceState(HLERequestContext& ctx) {
586 IPC::RequestParser rp{ctx};
587 const auto device_handle{rp.Pop<u64>()};
588 LOG_DEBUG(Service_NFP, "called, device_handle={}", device_handle);
589
590 auto device = GetNfpDevice(device_handle);
591
592 if (!device.has_value()) {
593 IPC::ResponseBuilder rb{ctx, 2};
594 rb.Push(DeviceNotFound);
595 return;
596 }
597
598 IPC::ResponseBuilder rb{ctx, 3};
599 rb.Push(ResultSuccess);
600 rb.PushEnum(device.value()->GetCurrentState());
601}
602
603void Interface::GetNpadId(HLERequestContext& ctx) {
604 IPC::RequestParser rp{ctx};
605 const auto device_handle{rp.Pop<u64>()};
606 LOG_DEBUG(Service_NFP, "called, device_handle={}", device_handle);
607
608 if (state == State::NonInitialized) {
609 IPC::ResponseBuilder rb{ctx, 2};
610 rb.Push(NfcDisabled);
611 return;
612 }
613
614 auto device = GetNfpDevice(device_handle);
615
616 if (!device.has_value()) {
617 IPC::ResponseBuilder rb{ctx, 2};
618 rb.Push(DeviceNotFound);
619 return;
620 }
621
622 IPC::ResponseBuilder rb{ctx, 3};
623 rb.Push(ResultSuccess);
624 rb.PushEnum(device.value()->GetNpadId());
625}
626
627void Interface::GetApplicationAreaSize(HLERequestContext& ctx) { 204void Interface::GetApplicationAreaSize(HLERequestContext& ctx) {
628 IPC::RequestParser rp{ctx}; 205 IPC::RequestParser rp{ctx};
629 const auto device_handle{rp.Pop<u64>()}; 206 const auto device_handle{rp.Pop<u64>()};
630 LOG_DEBUG(Service_NFP, "called, device_handle={}", device_handle); 207 LOG_DEBUG(Service_NFP, "called, device_handle={}", device_handle);
631 208
632 auto device = GetNfpDevice(device_handle);
633
634 if (!device.has_value()) {
635 IPC::ResponseBuilder rb{ctx, 2};
636 rb.Push(DeviceNotFound);
637 return;
638 }
639
640 IPC::ResponseBuilder rb{ctx, 3}; 209 IPC::ResponseBuilder rb{ctx, 3};
641 rb.Push(ResultSuccess); 210 rb.Push(ResultSuccess);
642 rb.Push(device.value()->GetApplicationAreaSize()); 211 rb.Push(GetManager()->GetApplicationAreaSize());
643}
644
645void Interface::AttachAvailabilityChangeEvent(HLERequestContext& ctx) {
646 LOG_INFO(Service_NFP, "called");
647
648 if (state == State::NonInitialized) {
649 IPC::ResponseBuilder rb{ctx, 2};
650 rb.Push(NfcDisabled);
651 return;
652 }
653
654 IPC::ResponseBuilder rb{ctx, 2, 1};
655 rb.Push(ResultSuccess);
656 rb.PushCopyObjects(availability_change_event->GetReadableEvent());
657} 212}
658 213
659void Interface::RecreateApplicationArea(HLERequestContext& ctx) { 214void Interface::RecreateApplicationArea(HLERequestContext& ctx) {
@@ -664,21 +219,9 @@ void Interface::RecreateApplicationArea(HLERequestContext& ctx) {
664 LOG_INFO(Service_NFP, "called, device_handle={}, data_size={}, access_id={}", device_handle, 219 LOG_INFO(Service_NFP, "called, device_handle={}, data_size={}, access_id={}", device_handle,
665 access_id, data.size()); 220 access_id, data.size());
666 221
667 if (state == State::NonInitialized) { 222 auto result = GetManager()->RecreateApplicationArea(device_handle, access_id, data);
668 IPC::ResponseBuilder rb{ctx, 2}; 223 result = TranslateResultToServiceError(result);
669 rb.Push(NfcDisabled);
670 return;
671 }
672 224
673 auto device = GetNfpDevice(device_handle);
674
675 if (!device.has_value()) {
676 IPC::ResponseBuilder rb{ctx, 2};
677 rb.Push(DeviceNotFound);
678 return;
679 }
680
681 const auto result = device.value()->RecreateApplicationArea(access_id, data);
682 IPC::ResponseBuilder rb{ctx, 2}; 225 IPC::ResponseBuilder rb{ctx, 2};
683 rb.Push(result); 226 rb.Push(result);
684} 227}
@@ -686,23 +229,11 @@ void Interface::RecreateApplicationArea(HLERequestContext& ctx) {
686void Interface::Format(HLERequestContext& ctx) { 229void Interface::Format(HLERequestContext& ctx) {
687 IPC::RequestParser rp{ctx}; 230 IPC::RequestParser rp{ctx};
688 const auto device_handle{rp.Pop<u64>()}; 231 const auto device_handle{rp.Pop<u64>()};
689 LOG_DEBUG(Service_NFP, "called, device_handle={}", device_handle); 232 LOG_INFO(Service_NFP, "called, device_handle={}", device_handle);
690
691 if (state == State::NonInitialized) {
692 IPC::ResponseBuilder rb{ctx, 2};
693 rb.Push(NfcDisabled);
694 return;
695 }
696 233
697 auto device = GetNfpDevice(device_handle); 234 auto result = GetManager()->Format(device_handle);
235 result = TranslateResultToServiceError(result);
698 236
699 if (!device.has_value()) {
700 IPC::ResponseBuilder rb{ctx, 2};
701 rb.Push(DeviceNotFound);
702 return;
703 }
704
705 const auto result = device.value()->Format();
706 IPC::ResponseBuilder rb{ctx, 2}; 237 IPC::ResponseBuilder rb{ctx, 2};
707 rb.Push(result); 238 rb.Push(result);
708} 239}
@@ -712,23 +243,14 @@ void Interface::GetAdminInfo(HLERequestContext& ctx) {
712 const auto device_handle{rp.Pop<u64>()}; 243 const auto device_handle{rp.Pop<u64>()};
713 LOG_INFO(Service_NFP, "called, device_handle={}", device_handle); 244 LOG_INFO(Service_NFP, "called, device_handle={}", device_handle);
714 245
715 if (state == State::NonInitialized) { 246 AdminInfo admin_info{};
716 IPC::ResponseBuilder rb{ctx, 2}; 247 auto result = GetManager()->GetAdminInfo(device_handle, admin_info);
717 rb.Push(NfcDisabled); 248 result = TranslateResultToServiceError(result);
718 return;
719 }
720
721 auto device = GetNfpDevice(device_handle);
722 249
723 if (!device.has_value()) { 250 if (result.IsSuccess()) {
724 IPC::ResponseBuilder rb{ctx, 2}; 251 ctx.WriteBuffer(admin_info);
725 rb.Push(DeviceNotFound);
726 return;
727 } 252 }
728 253
729 AdminInfo admin_info{};
730 const auto result = device.value()->GetAdminInfo(admin_info);
731 ctx.WriteBuffer(admin_info);
732 IPC::ResponseBuilder rb{ctx, 2}; 254 IPC::ResponseBuilder rb{ctx, 2};
733 rb.Push(result); 255 rb.Push(result);
734} 256}
@@ -738,23 +260,14 @@ void Interface::GetRegisterInfoPrivate(HLERequestContext& ctx) {
738 const auto device_handle{rp.Pop<u64>()}; 260 const auto device_handle{rp.Pop<u64>()};
739 LOG_INFO(Service_NFP, "called, device_handle={}", device_handle); 261 LOG_INFO(Service_NFP, "called, device_handle={}", device_handle);
740 262
741 if (state == State::NonInitialized) { 263 RegisterInfoPrivate register_info{};
742 IPC::ResponseBuilder rb{ctx, 2}; 264 auto result = GetManager()->GetRegisterInfoPrivate(device_handle, register_info);
743 rb.Push(NfcDisabled); 265 result = TranslateResultToServiceError(result);
744 return;
745 }
746
747 auto device = GetNfpDevice(device_handle);
748 266
749 if (!device.has_value()) { 267 if (result.IsSuccess()) {
750 IPC::ResponseBuilder rb{ctx, 2}; 268 ctx.WriteBuffer(register_info);
751 rb.Push(DeviceNotFound);
752 return;
753 } 269 }
754 270
755 RegisterInfoPrivate register_info{};
756 const auto result = device.value()->GetRegisterInfoPrivate(register_info);
757 ctx.WriteBuffer(register_info);
758 IPC::ResponseBuilder rb{ctx, 2}; 271 IPC::ResponseBuilder rb{ctx, 2};
759 rb.Push(result); 272 rb.Push(result);
760} 273}
@@ -762,25 +275,15 @@ void Interface::GetRegisterInfoPrivate(HLERequestContext& ctx) {
762void Interface::SetRegisterInfoPrivate(HLERequestContext& ctx) { 275void Interface::SetRegisterInfoPrivate(HLERequestContext& ctx) {
763 IPC::RequestParser rp{ctx}; 276 IPC::RequestParser rp{ctx};
764 const auto device_handle{rp.Pop<u64>()}; 277 const auto device_handle{rp.Pop<u64>()};
765 const auto buffer{ctx.ReadBuffer()}; 278 const auto register_info_buffer{ctx.ReadBuffer()};
766 LOG_DEBUG(Service_NFP, "called, device_handle={}, buffer_size={}", device_handle, 279 LOG_INFO(Service_NFP, "called, device_handle={}, buffer_size={}", device_handle,
767 buffer.size()); 280 register_info_buffer.size());
768 281
769 if (state == State::NonInitialized) { 282 RegisterInfoPrivate register_info{};
770 IPC::ResponseBuilder rb{ctx, 2}; 283 memcpy(&register_info, register_info_buffer.data(), sizeof(RegisterInfoPrivate));
771 rb.Push(NfcDisabled); 284 auto result = GetManager()->SetRegisterInfoPrivate(device_handle, register_info);
772 return; 285 result = TranslateResultToServiceError(result);
773 }
774
775 auto device = GetNfpDevice(device_handle);
776
777 if (!device.has_value()) {
778 IPC::ResponseBuilder rb{ctx, 2};
779 rb.Push(DeviceNotFound);
780 return;
781 }
782 286
783 const auto result = device.value()->SetRegisterInfoPrivate({});
784 IPC::ResponseBuilder rb{ctx, 2}; 287 IPC::ResponseBuilder rb{ctx, 2};
785 rb.Push(result); 288 rb.Push(result);
786} 289}
@@ -788,23 +291,11 @@ void Interface::SetRegisterInfoPrivate(HLERequestContext& ctx) {
788void Interface::DeleteRegisterInfo(HLERequestContext& ctx) { 291void Interface::DeleteRegisterInfo(HLERequestContext& ctx) {
789 IPC::RequestParser rp{ctx}; 292 IPC::RequestParser rp{ctx};
790 const auto device_handle{rp.Pop<u64>()}; 293 const auto device_handle{rp.Pop<u64>()};
791 LOG_DEBUG(Service_NFP, "called, device_handle={}", device_handle); 294 LOG_INFO(Service_NFP, "called, device_handle={}", device_handle);
792
793 if (state == State::NonInitialized) {
794 IPC::ResponseBuilder rb{ctx, 2};
795 rb.Push(NfcDisabled);
796 return;
797 }
798 295
799 auto device = GetNfpDevice(device_handle); 296 auto result = GetManager()->DeleteRegisterInfo(device_handle);
297 result = TranslateResultToServiceError(result);
800 298
801 if (!device.has_value()) {
802 IPC::ResponseBuilder rb{ctx, 2};
803 rb.Push(DeviceNotFound);
804 return;
805 }
806
807 const auto result = device.value()->DeleteRegisterInfo();
808 IPC::ResponseBuilder rb{ctx, 2}; 299 IPC::ResponseBuilder rb{ctx, 2};
809 rb.Push(result); 300 rb.Push(result);
810} 301}
@@ -812,23 +303,11 @@ void Interface::DeleteRegisterInfo(HLERequestContext& ctx) {
812void Interface::DeleteApplicationArea(HLERequestContext& ctx) { 303void Interface::DeleteApplicationArea(HLERequestContext& ctx) {
813 IPC::RequestParser rp{ctx}; 304 IPC::RequestParser rp{ctx};
814 const auto device_handle{rp.Pop<u64>()}; 305 const auto device_handle{rp.Pop<u64>()};
815 LOG_DEBUG(Service_NFP, "called, device_handle={}", device_handle); 306 LOG_INFO(Service_NFP, "called, device_handle={}", device_handle);
816
817 if (state == State::NonInitialized) {
818 IPC::ResponseBuilder rb{ctx, 2};
819 rb.Push(NfcDisabled);
820 return;
821 }
822 307
823 auto device = GetNfpDevice(device_handle); 308 auto result = GetManager()->DeleteApplicationArea(device_handle);
309 result = TranslateResultToServiceError(result);
824 310
825 if (!device.has_value()) {
826 IPC::ResponseBuilder rb{ctx, 2};
827 rb.Push(DeviceNotFound);
828 return;
829 }
830
831 const auto result = device.value()->DeleteApplicationArea();
832 IPC::ResponseBuilder rb{ctx, 2}; 311 IPC::ResponseBuilder rb{ctx, 2};
833 rb.Push(result); 312 rb.Push(result);
834} 313}
@@ -836,24 +315,18 @@ void Interface::DeleteApplicationArea(HLERequestContext& ctx) {
836void Interface::ExistsApplicationArea(HLERequestContext& ctx) { 315void Interface::ExistsApplicationArea(HLERequestContext& ctx) {
837 IPC::RequestParser rp{ctx}; 316 IPC::RequestParser rp{ctx};
838 const auto device_handle{rp.Pop<u64>()}; 317 const auto device_handle{rp.Pop<u64>()};
839 LOG_DEBUG(Service_NFP, "called, device_handle={}", device_handle); 318 LOG_INFO(Service_NFP, "called, device_handle={}", device_handle);
840
841 if (state == State::NonInitialized) {
842 IPC::ResponseBuilder rb{ctx, 2};
843 rb.Push(NfcDisabled);
844 return;
845 }
846 319
847 auto device = GetNfpDevice(device_handle); 320 bool has_application_area = false;
321 auto result = GetManager()->ExistsApplicationArea(device_handle, has_application_area);
322 result = TranslateResultToServiceError(result);
848 323
849 if (!device.has_value()) { 324 if (result.IsError()) {
850 IPC::ResponseBuilder rb{ctx, 2}; 325 IPC::ResponseBuilder rb{ctx, 2};
851 rb.Push(DeviceNotFound); 326 rb.Push(result);
852 return; 327 return;
853 } 328 }
854 329
855 bool has_application_area = false;
856 const auto result = device.value()->ExistApplicationArea(has_application_area);
857 IPC::ResponseBuilder rb{ctx, 3}; 330 IPC::ResponseBuilder rb{ctx, 3};
858 rb.Push(result); 331 rb.Push(result);
859 rb.Push(has_application_area); 332 rb.Push(has_application_area);
@@ -862,27 +335,16 @@ void Interface::ExistsApplicationArea(HLERequestContext& ctx) {
862void Interface::GetAll(HLERequestContext& ctx) { 335void Interface::GetAll(HLERequestContext& ctx) {
863 IPC::RequestParser rp{ctx}; 336 IPC::RequestParser rp{ctx};
864 const auto device_handle{rp.Pop<u64>()}; 337 const auto device_handle{rp.Pop<u64>()};
865 LOG_DEBUG(Service_NFP, "called, device_handle={}", device_handle); 338 LOG_INFO(Service_NFP, "called, device_handle={}", device_handle);
866
867 if (state == State::NonInitialized) {
868 IPC::ResponseBuilder rb{ctx, 2};
869 rb.Push(NfcDisabled);
870 return;
871 }
872 339
873 auto device = GetNfpDevice(device_handle); 340 NfpData nfp_data{};
341 auto result = GetManager()->GetAll(device_handle, nfp_data);
342 result = TranslateResultToServiceError(result);
874 343
875 if (!device.has_value()) { 344 if (result.IsSuccess()) {
876 IPC::ResponseBuilder rb{ctx, 2}; 345 ctx.WriteBuffer(nfp_data);
877 rb.Push(DeviceNotFound);
878 return;
879 } 346 }
880 347
881 NfpData data{};
882 const auto result = device.value()->GetAll(data);
883
884 ctx.WriteBuffer(data);
885
886 IPC::ResponseBuilder rb{ctx, 2}; 348 IPC::ResponseBuilder rb{ctx, 2};
887 rb.Push(result); 349 rb.Push(result);
888} 350}
@@ -890,28 +352,15 @@ void Interface::GetAll(HLERequestContext& ctx) {
890void Interface::SetAll(HLERequestContext& ctx) { 352void Interface::SetAll(HLERequestContext& ctx) {
891 IPC::RequestParser rp{ctx}; 353 IPC::RequestParser rp{ctx};
892 const auto device_handle{rp.Pop<u64>()}; 354 const auto device_handle{rp.Pop<u64>()};
893 const auto nfp_data{ctx.ReadBuffer()}; 355 const auto nfp_data_buffer{ctx.ReadBuffer()};
894
895 LOG_DEBUG(Service_NFP, "called, device_handle={}", device_handle);
896
897 if (state == State::NonInitialized) {
898 IPC::ResponseBuilder rb{ctx, 2};
899 rb.Push(NfcDisabled);
900 return;
901 }
902 356
903 auto device = GetNfpDevice(device_handle); 357 LOG_INFO(Service_NFP, "called, device_handle={}", device_handle);
904
905 if (!device.has_value()) {
906 IPC::ResponseBuilder rb{ctx, 2};
907 rb.Push(DeviceNotFound);
908 return;
909 }
910 358
911 NfpData data{}; 359 NfpData nfp_data{};
912 memcpy(&data, nfp_data.data(), sizeof(NfpData)); 360 memcpy(&nfp_data, nfp_data_buffer.data(), sizeof(NfpData));
361 auto result = GetManager()->SetAll(device_handle, nfp_data);
362 result = TranslateResultToServiceError(result);
913 363
914 const auto result = device.value()->SetAll(data);
915 IPC::ResponseBuilder rb{ctx, 2}; 364 IPC::ResponseBuilder rb{ctx, 2};
916 rb.Push(result); 365 rb.Push(result);
917} 366}
@@ -919,23 +368,11 @@ void Interface::SetAll(HLERequestContext& ctx) {
919void Interface::FlushDebug(HLERequestContext& ctx) { 368void Interface::FlushDebug(HLERequestContext& ctx) {
920 IPC::RequestParser rp{ctx}; 369 IPC::RequestParser rp{ctx};
921 const auto device_handle{rp.Pop<u64>()}; 370 const auto device_handle{rp.Pop<u64>()};
922 LOG_DEBUG(Service_NFP, "called, device_handle={}", device_handle); 371 LOG_INFO(Service_NFP, "called, device_handle={}", device_handle);
923
924 if (state == State::NonInitialized) {
925 IPC::ResponseBuilder rb{ctx, 2};
926 rb.Push(NfcDisabled);
927 return;
928 }
929 372
930 auto device = GetNfpDevice(device_handle); 373 auto result = GetManager()->FlushDebug(device_handle);
374 result = TranslateResultToServiceError(result);
931 375
932 if (!device.has_value()) {
933 IPC::ResponseBuilder rb{ctx, 2};
934 rb.Push(DeviceNotFound);
935 return;
936 }
937
938 const auto result = device.value()->FlushDebug();
939 IPC::ResponseBuilder rb{ctx, 2}; 376 IPC::ResponseBuilder rb{ctx, 2};
940 rb.Push(result); 377 rb.Push(result);
941} 378}
@@ -944,23 +381,12 @@ void Interface::BreakTag(HLERequestContext& ctx) {
944 IPC::RequestParser rp{ctx}; 381 IPC::RequestParser rp{ctx};
945 const auto device_handle{rp.Pop<u64>()}; 382 const auto device_handle{rp.Pop<u64>()};
946 const auto break_type{rp.PopEnum<BreakType>()}; 383 const auto break_type{rp.PopEnum<BreakType>()};
947 LOG_DEBUG(Service_NFP, "called, device_handle={}, break_type={}", device_handle, break_type); 384 LOG_WARNING(Service_NFP, "(STUBBED) called, device_handle={}, break_type={}", device_handle,
385 break_type);
948 386
949 if (state == State::NonInitialized) { 387 auto result = GetManager()->BreakTag(device_handle, break_type);
950 IPC::ResponseBuilder rb{ctx, 2}; 388 result = TranslateResultToServiceError(result);
951 rb.Push(NfcDisabled);
952 return;
953 }
954 389
955 auto device = GetNfpDevice(device_handle);
956
957 if (!device.has_value()) {
958 IPC::ResponseBuilder rb{ctx, 2};
959 rb.Push(DeviceNotFound);
960 return;
961 }
962
963 const auto result = device.value()->BreakTag(break_type);
964 IPC::ResponseBuilder rb{ctx, 2}; 390 IPC::ResponseBuilder rb{ctx, 2};
965 rb.Push(result); 391 rb.Push(result);
966} 392}
@@ -968,23 +394,16 @@ void Interface::BreakTag(HLERequestContext& ctx) {
968void Interface::ReadBackupData(HLERequestContext& ctx) { 394void Interface::ReadBackupData(HLERequestContext& ctx) {
969 IPC::RequestParser rp{ctx}; 395 IPC::RequestParser rp{ctx};
970 const auto device_handle{rp.Pop<u64>()}; 396 const auto device_handle{rp.Pop<u64>()};
971 LOG_DEBUG(Service_NFP, "called, device_handle={}", device_handle); 397 LOG_WARNING(Service_NFP, "(STUBBED) called, device_handle={}", device_handle);
972
973 if (state == State::NonInitialized) {
974 IPC::ResponseBuilder rb{ctx, 2};
975 rb.Push(NfcDisabled);
976 return;
977 }
978 398
979 auto device = GetNfpDevice(device_handle); 399 std::vector<u8> backup_data{};
400 auto result = GetManager()->ReadBackupData(device_handle, backup_data);
401 result = TranslateResultToServiceError(result);
980 402
981 if (!device.has_value()) { 403 if (result.IsSuccess()) {
982 IPC::ResponseBuilder rb{ctx, 2}; 404 ctx.WriteBuffer(backup_data);
983 rb.Push(DeviceNotFound);
984 return;
985 } 405 }
986 406
987 const auto result = device.value()->ReadBackupData();
988 IPC::ResponseBuilder rb{ctx, 2}; 407 IPC::ResponseBuilder rb{ctx, 2};
989 rb.Push(result); 408 rb.Push(result);
990} 409}
@@ -992,23 +411,12 @@ void Interface::ReadBackupData(HLERequestContext& ctx) {
992void Interface::WriteBackupData(HLERequestContext& ctx) { 411void Interface::WriteBackupData(HLERequestContext& ctx) {
993 IPC::RequestParser rp{ctx}; 412 IPC::RequestParser rp{ctx};
994 const auto device_handle{rp.Pop<u64>()}; 413 const auto device_handle{rp.Pop<u64>()};
995 LOG_DEBUG(Service_NFP, "called, device_handle={}", device_handle); 414 const auto backup_data_buffer{ctx.ReadBuffer()};
996 415 LOG_WARNING(Service_NFP, "(STUBBED) called, device_handle={}", device_handle);
997 if (state == State::NonInitialized) {
998 IPC::ResponseBuilder rb{ctx, 2};
999 rb.Push(NfcDisabled);
1000 return;
1001 }
1002
1003 auto device = GetNfpDevice(device_handle);
1004 416
1005 if (!device.has_value()) { 417 auto result = GetManager()->WriteBackupData(device_handle, backup_data_buffer);
1006 IPC::ResponseBuilder rb{ctx, 2}; 418 result = TranslateResultToServiceError(result);
1007 rb.Push(DeviceNotFound);
1008 return;
1009 }
1010 419
1011 const auto result = device.value()->WriteBackupData();
1012 IPC::ResponseBuilder rb{ctx, 2}; 420 IPC::ResponseBuilder rb{ctx, 2};
1013 rb.Push(result); 421 rb.Push(result);
1014} 422}
@@ -1016,34 +424,15 @@ void Interface::WriteBackupData(HLERequestContext& ctx) {
1016void Interface::WriteNtf(HLERequestContext& ctx) { 424void Interface::WriteNtf(HLERequestContext& ctx) {
1017 IPC::RequestParser rp{ctx}; 425 IPC::RequestParser rp{ctx};
1018 const auto device_handle{rp.Pop<u64>()}; 426 const auto device_handle{rp.Pop<u64>()};
1019 LOG_DEBUG(Service_NFP, "called, device_handle={}", device_handle); 427 const auto write_type{rp.PopEnum<WriteType>()};
1020 428 const auto ntf_data_buffer{ctx.ReadBuffer()};
1021 if (state == State::NonInitialized) { 429 LOG_WARNING(Service_NFP, "(STUBBED) called, device_handle={}", device_handle);
1022 IPC::ResponseBuilder rb{ctx, 2};
1023 rb.Push(NfcDisabled);
1024 return;
1025 }
1026 430
1027 auto device = GetNfpDevice(device_handle); 431 auto result = GetManager()->WriteNtf(device_handle, write_type, ntf_data_buffer);
432 result = TranslateResultToServiceError(result);
1028 433
1029 if (!device.has_value()) {
1030 IPC::ResponseBuilder rb{ctx, 2};
1031 rb.Push(DeviceNotFound);
1032 return;
1033 }
1034
1035 const auto result = device.value()->WriteNtf();
1036 IPC::ResponseBuilder rb{ctx, 2}; 434 IPC::ResponseBuilder rb{ctx, 2};
1037 rb.Push(result); 435 rb.Push(result);
1038} 436}
1039 437
1040std::optional<std::shared_ptr<NfpDevice>> Interface::GetNfpDevice(u64 handle) {
1041 for (auto& device : devices) {
1042 if (device->GetHandle() == handle) {
1043 return device;
1044 }
1045 }
1046 return std::nullopt;
1047}
1048
1049} // namespace Service::NFP 438} // namespace Service::NFP
diff --git a/src/core/hle/service/nfp/nfp_interface.h b/src/core/hle/service/nfp/nfp_interface.h
index 616c94b06..fa985b068 100644
--- a/src/core/hle/service/nfp/nfp_interface.h
+++ b/src/core/hle/service/nfp/nfp_interface.h
@@ -1,32 +1,23 @@
1// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project 1// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later 2// SPDX-License-Identifier: GPL-2.0-or-later
3 3
4#pragma once 4#pragma once
5 5
6#include <array>
7#include <memory>
8#include <optional>
9
10#include "core/hle/service/kernel_helpers.h" 6#include "core/hle/service/kernel_helpers.h"
7#include "core/hle/service/nfc/nfc_interface.h"
11#include "core/hle/service/service.h" 8#include "core/hle/service/service.h"
12 9
13namespace Service::NFP { 10namespace Service::NFP {
14class NfpDevice;
15 11
16class Interface : public ServiceFramework<Interface> { 12class Interface : public NFC::NfcInterface {
17public: 13public:
18 explicit Interface(Core::System& system_, const char* name); 14 explicit Interface(Core::System& system_, const char* name);
19 ~Interface() override; 15 ~Interface() override;
20 16
21 void Initialize(HLERequestContext& ctx);
22 void InitializeSystem(HLERequestContext& ctx); 17 void InitializeSystem(HLERequestContext& ctx);
23 void InitializeDebug(HLERequestContext& ctx); 18 void InitializeDebug(HLERequestContext& ctx);
24 void Finalize(HLERequestContext& ctx);
25 void FinalizeSystem(HLERequestContext& ctx); 19 void FinalizeSystem(HLERequestContext& ctx);
26 void FinalizeDebug(HLERequestContext& ctx); 20 void FinalizeDebug(HLERequestContext& ctx);
27 void ListDevices(HLERequestContext& ctx);
28 void StartDetection(HLERequestContext& ctx);
29 void StopDetection(HLERequestContext& ctx);
30 void Mount(HLERequestContext& ctx); 21 void Mount(HLERequestContext& ctx);
31 void Unmount(HLERequestContext& ctx); 22 void Unmount(HLERequestContext& ctx);
32 void OpenApplicationArea(HLERequestContext& ctx); 23 void OpenApplicationArea(HLERequestContext& ctx);
@@ -35,17 +26,10 @@ public:
35 void Flush(HLERequestContext& ctx); 26 void Flush(HLERequestContext& ctx);
36 void Restore(HLERequestContext& ctx); 27 void Restore(HLERequestContext& ctx);
37 void CreateApplicationArea(HLERequestContext& ctx); 28 void CreateApplicationArea(HLERequestContext& ctx);
38 void GetTagInfo(HLERequestContext& ctx);
39 void GetRegisterInfo(HLERequestContext& ctx); 29 void GetRegisterInfo(HLERequestContext& ctx);
40 void GetCommonInfo(HLERequestContext& ctx); 30 void GetCommonInfo(HLERequestContext& ctx);
41 void GetModelInfo(HLERequestContext& ctx); 31 void GetModelInfo(HLERequestContext& ctx);
42 void AttachActivateEvent(HLERequestContext& ctx);
43 void AttachDeactivateEvent(HLERequestContext& ctx);
44 void GetState(HLERequestContext& ctx);
45 void GetDeviceState(HLERequestContext& ctx);
46 void GetNpadId(HLERequestContext& ctx);
47 void GetApplicationAreaSize(HLERequestContext& ctx); 32 void GetApplicationAreaSize(HLERequestContext& ctx);
48 void AttachAvailabilityChangeEvent(HLERequestContext& ctx);
49 void RecreateApplicationArea(HLERequestContext& ctx); 33 void RecreateApplicationArea(HLERequestContext& ctx);
50 void Format(HLERequestContext& ctx); 34 void Format(HLERequestContext& ctx);
51 void GetAdminInfo(HLERequestContext& ctx); 35 void GetAdminInfo(HLERequestContext& ctx);
@@ -61,21 +45,6 @@ public:
61 void ReadBackupData(HLERequestContext& ctx); 45 void ReadBackupData(HLERequestContext& ctx);
62 void WriteBackupData(HLERequestContext& ctx); 46 void WriteBackupData(HLERequestContext& ctx);
63 void WriteNtf(HLERequestContext& ctx); 47 void WriteNtf(HLERequestContext& ctx);
64
65private:
66 enum class State : u32 {
67 NonInitialized,
68 Initialized,
69 };
70
71 std::optional<std::shared_ptr<NfpDevice>> GetNfpDevice(u64 handle);
72
73 KernelHelpers::ServiceContext service_context;
74
75 std::array<std::shared_ptr<NfpDevice>, 10> devices{};
76
77 State state{State::NonInitialized};
78 Kernel::KEvent* availability_change_event;
79}; 48};
80 49
81} // namespace Service::NFP 50} // namespace Service::NFP
diff --git a/src/core/hle/service/nfp/nfp_result.h b/src/core/hle/service/nfp/nfp_result.h
index d8e4cf094..4c126cd81 100644
--- a/src/core/hle/service/nfp/nfp_result.h
+++ b/src/core/hle/service/nfp/nfp_result.h
@@ -1,5 +1,5 @@
1// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project 1// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-3.0-or-later 2// SPDX-License-Identifier: GPL-2.0-or-later
3 3
4#pragma once 4#pragma once
5 5
@@ -7,18 +7,19 @@
7 7
8namespace Service::NFP { 8namespace Service::NFP {
9 9
10constexpr Result DeviceNotFound(ErrorModule::NFP, 64); 10constexpr Result ResultDeviceNotFound(ErrorModule::NFP, 64);
11constexpr Result InvalidArgument(ErrorModule::NFP, 65); 11constexpr Result ResultInvalidArgument(ErrorModule::NFP, 65);
12constexpr Result WrongApplicationAreaSize(ErrorModule::NFP, 68); 12constexpr Result ResultWrongApplicationAreaSize(ErrorModule::NFP, 68);
13constexpr Result WrongDeviceState(ErrorModule::NFP, 73); 13constexpr Result ResultWrongDeviceState(ErrorModule::NFP, 73);
14constexpr Result NfcDisabled(ErrorModule::NFP, 80); 14constexpr Result ResultUnknown74(ErrorModule::NFC, 74);
15constexpr Result WriteAmiiboFailed(ErrorModule::NFP, 88); 15constexpr Result ResultNfcDisabled(ErrorModule::NFP, 80);
16constexpr Result TagRemoved(ErrorModule::NFP, 97); 16constexpr Result ResultWriteAmiiboFailed(ErrorModule::NFP, 88);
17constexpr Result RegistrationIsNotInitialized(ErrorModule::NFP, 120); 17constexpr Result ResultTagRemoved(ErrorModule::NFP, 97);
18constexpr Result ApplicationAreaIsNotInitialized(ErrorModule::NFP, 128); 18constexpr Result ResultRegistrationIsNotInitialized(ErrorModule::NFP, 120);
19constexpr Result CorruptedData(ErrorModule::NFP, 144); 19constexpr Result ResultApplicationAreaIsNotInitialized(ErrorModule::NFP, 128);
20constexpr Result WrongApplicationAreaId(ErrorModule::NFP, 152); 20constexpr Result ResultCorruptedData(ErrorModule::NFP, 144);
21constexpr Result ApplicationAreaExist(ErrorModule::NFP, 168); 21constexpr Result ResultWrongApplicationAreaId(ErrorModule::NFP, 152);
22constexpr Result NotAnAmiibo(ErrorModule::NFP, 178); 22constexpr Result ResultApplicationAreaExist(ErrorModule::NFP, 168);
23constexpr Result ResultNotAnAmiibo(ErrorModule::NFP, 178);
23 24
24} // namespace Service::NFP 25} // namespace Service::NFP
diff --git a/src/core/hle/service/nfp/nfp_types.h b/src/core/hle/service/nfp/nfp_types.h
index 1ef047cee..7d36d5ee6 100644
--- a/src/core/hle/service/nfp/nfp_types.h
+++ b/src/core/hle/service/nfp/nfp_types.h
@@ -7,32 +7,19 @@
7 7
8#include "common/swap.h" 8#include "common/swap.h"
9#include "core/hle/service/mii/types.h" 9#include "core/hle/service/mii/types.h"
10#include "core/hle/service/nfc/nfc_types.h"
10 11
11namespace Service::NFP { 12namespace Service::NFP {
12static constexpr std::size_t amiibo_name_length = 0xA; 13static constexpr std::size_t amiibo_name_length = 0xA;
13static constexpr std::size_t application_id_version_offset = 0x1c; 14static constexpr std::size_t application_id_version_offset = 0x1c;
14static constexpr std::size_t counter_limit = 0xffff; 15static constexpr std::size_t counter_limit = 0xffff;
15 16
16enum class ServiceType : u32 { 17// This is nn::nfp::ModelType
17 User,
18 Debug,
19 System,
20};
21
22enum class DeviceState : u32 {
23 Initialized,
24 SearchingForTag,
25 TagFound,
26 TagRemoved,
27 TagMounted,
28 Unavailable,
29 Finalized,
30};
31
32enum class ModelType : u32 { 18enum class ModelType : u32 {
33 Amiibo, 19 Amiibo,
34}; 20};
35 21
22// This is nn::nfp::MountTarget
36enum class MountTarget : u32 { 23enum class MountTarget : u32 {
37 None, 24 None,
38 Rom, 25 Rom,
@@ -72,35 +59,6 @@ enum class AmiiboSeries : u8 {
72 Diablo, 59 Diablo,
73}; 60};
74 61
75enum class TagType : u32 {
76 None,
77 Type1, // ISO14443A RW 96-2k bytes 106kbit/s
78 Type2, // ISO14443A RW/RO 540 bytes 106kbit/s
79 Type3, // Sony Felica RW/RO 2k bytes 212kbit/s
80 Type4, // ISO14443A RW/RO 4k-32k bytes 424kbit/s
81 Type5, // ISO15693 RW/RO 540 bytes 106kbit/s
82};
83
84enum class PackedTagType : u8 {
85 None,
86 Type1, // ISO14443A RW 96-2k bytes 106kbit/s
87 Type2, // ISO14443A RW/RO 540 bytes 106kbit/s
88 Type3, // Sony Felica RW/RO 2k bytes 212kbit/s
89 Type4, // ISO14443A RW/RO 4k-32k bytes 424kbit/s
90 Type5, // ISO15693 RW/RO 540 bytes 106kbit/s
91};
92
93// Verify this enum. It might be completely wrong default protocol is 0x48
94enum class TagProtocol : u32 {
95 None,
96 TypeA = 1U << 0, // ISO14443A
97 TypeB = 1U << 1, // ISO14443B
98 TypeF = 1U << 2, // Sony Felica
99 Unknown1 = 1U << 3,
100 Unknown2 = 1U << 5,
101 All = 0xFFFFFFFFU,
102};
103
104enum class AppAreaVersion : u8 { 62enum class AppAreaVersion : u8 {
105 Nintendo3DS = 0, 63 Nintendo3DS = 0,
106 NintendoWiiU = 1, 64 NintendoWiiU = 1,
@@ -115,6 +73,11 @@ enum class BreakType : u32 {
115 Unknown2, 73 Unknown2,
116}; 74};
117 75
76enum class WriteType : u32 {
77 Unknown0,
78 Unknown1,
79};
80
118enum class CabinetMode : u8 { 81enum class CabinetMode : u8 {
119 StartNicknameAndOwnerSettings, 82 StartNicknameAndOwnerSettings,
120 StartGameDataEraser, 83 StartGameDataEraser,
@@ -122,27 +85,16 @@ enum class CabinetMode : u8 {
122 StartFormatter, 85 StartFormatter,
123}; 86};
124 87
125enum class MifareCmd : u8 {
126 AuthA = 0x60,
127 AuthB = 0x61,
128 Read = 0x30,
129 Write = 0xA0,
130 Transfer = 0xB0,
131 Decrement = 0xC0,
132 Increment = 0xC1,
133 Store = 0xC2
134};
135
136using UniqueSerialNumber = std::array<u8, 7>;
137using LockBytes = std::array<u8, 2>; 88using LockBytes = std::array<u8, 2>;
138using HashData = std::array<u8, 0x20>; 89using HashData = std::array<u8, 0x20>;
139using ApplicationArea = std::array<u8, 0xD8>; 90using ApplicationArea = std::array<u8, 0xD8>;
140using AmiiboName = std::array<char, (amiibo_name_length * 4) + 1>; 91using AmiiboName = std::array<char, (amiibo_name_length * 4) + 1>;
141using DataBlock = std::array<u8, 0x10>; 92
142using KeyData = std::array<u8, 0x6>; 93// This is nn::nfp::TagInfo
94using TagInfo = NFC::TagInfo;
143 95
144struct TagUuid { 96struct TagUuid {
145 UniqueSerialNumber uid; 97 NFC::UniqueSerialNumber uid;
146 u8 nintendo_id; 98 u8 nintendo_id;
147 LockBytes lock_bytes; 99 LockBytes lock_bytes;
148}; 100};
@@ -243,7 +195,7 @@ struct AmiiboModelInfo {
243 AmiiboType amiibo_type; 195 AmiiboType amiibo_type;
244 u16_be model_number; 196 u16_be model_number;
245 AmiiboSeries series; 197 AmiiboSeries series;
246 PackedTagType tag_type; 198 NFC::PackedTagType tag_type;
247 INSERT_PADDING_BYTES(0x4); // Unknown 199 INSERT_PADDING_BYTES(0x4); // Unknown
248}; 200};
249static_assert(sizeof(AmiiboModelInfo) == 0xC, "AmiiboModelInfo is an invalid size"); 201static_assert(sizeof(AmiiboModelInfo) == 0xC, "AmiiboModelInfo is an invalid size");
@@ -298,7 +250,7 @@ struct NTAG215File {
298 u32_be register_info_crc; 250 u32_be register_info_crc;
299 ApplicationArea application_area; // Encrypted Game data 251 ApplicationArea application_area; // Encrypted Game data
300 HashData hmac_tag; // Hash 252 HashData hmac_tag; // Hash
301 UniqueSerialNumber uid; // Unique serial number 253 NFC::UniqueSerialNumber uid; // Unique serial number
302 u8 nintendo_id; // Tag UUID 254 u8 nintendo_id; // Tag UUID
303 AmiiboModelInfo model_info; 255 AmiiboModelInfo model_info;
304 HashData keygen_salt; // Salt 256 HashData keygen_salt; // Salt
@@ -326,17 +278,7 @@ static_assert(sizeof(EncryptedNTAG215File) == sizeof(NTAG215File),
326static_assert(std::is_trivially_copyable_v<EncryptedNTAG215File>, 278static_assert(std::is_trivially_copyable_v<EncryptedNTAG215File>,
327 "EncryptedNTAG215File must be trivially copyable."); 279 "EncryptedNTAG215File must be trivially copyable.");
328 280
329struct TagInfo { 281// This is nn::nfp::CommonInfo
330 UniqueSerialNumber uuid;
331 INSERT_PADDING_BYTES(0x3);
332 u8 uuid_length;
333 INSERT_PADDING_BYTES(0x15);
334 TagProtocol protocol;
335 TagType tag_type;
336 INSERT_PADDING_BYTES(0x30);
337};
338static_assert(sizeof(TagInfo) == 0x58, "TagInfo is an invalid size");
339
340struct CommonInfo { 282struct CommonInfo {
341 WriteDate last_write_date; 283 WriteDate last_write_date;
342 u16 write_counter; 284 u16 write_counter;
@@ -347,6 +289,7 @@ struct CommonInfo {
347}; 289};
348static_assert(sizeof(CommonInfo) == 0x40, "CommonInfo is an invalid size"); 290static_assert(sizeof(CommonInfo) == 0x40, "CommonInfo is an invalid size");
349 291
292// This is nn::nfp::ModelInfo
350struct ModelInfo { 293struct ModelInfo {
351 u16 character_id; 294 u16 character_id;
352 u8 character_variant; 295 u8 character_variant;
@@ -357,6 +300,7 @@ struct ModelInfo {
357}; 300};
358static_assert(sizeof(ModelInfo) == 0x40, "ModelInfo is an invalid size"); 301static_assert(sizeof(ModelInfo) == 0x40, "ModelInfo is an invalid size");
359 302
303// This is nn::nfp::RegisterInfo
360struct RegisterInfo { 304struct RegisterInfo {
361 Service::Mii::CharInfo mii_char_info; 305 Service::Mii::CharInfo mii_char_info;
362 WriteDate creation_date; 306 WriteDate creation_date;
@@ -366,6 +310,7 @@ struct RegisterInfo {
366}; 310};
367static_assert(sizeof(RegisterInfo) == 0x100, "RegisterInfo is an invalid size"); 311static_assert(sizeof(RegisterInfo) == 0x100, "RegisterInfo is an invalid size");
368 312
313// This is nn::nfp::RegisterInfoPrivate
369struct RegisterInfoPrivate { 314struct RegisterInfoPrivate {
370 Service::Mii::MiiStoreData mii_store_data; 315 Service::Mii::MiiStoreData mii_store_data;
371 WriteDate creation_date; 316 WriteDate creation_date;
@@ -375,12 +320,13 @@ struct RegisterInfoPrivate {
375}; 320};
376static_assert(sizeof(RegisterInfoPrivate) == 0x100, "RegisterInfoPrivate is an invalid size"); 321static_assert(sizeof(RegisterInfoPrivate) == 0x100, "RegisterInfoPrivate is an invalid size");
377 322
323// This is nn::nfp::AdminInfo
378struct AdminInfo { 324struct AdminInfo {
379 u64 application_id; 325 u64 application_id;
380 u32 application_area_id; 326 u32 application_area_id;
381 u16 crc_change_counter; 327 u16 crc_change_counter;
382 u8 flags; 328 u8 flags;
383 PackedTagType tag_type; 329 NFC::PackedTagType tag_type;
384 AppAreaVersion app_area_version; 330 AppAreaVersion app_area_version;
385 INSERT_PADDING_BYTES(0x7); 331 INSERT_PADDING_BYTES(0x7);
386 INSERT_PADDING_BYTES(0x28); 332 INSERT_PADDING_BYTES(0x28);
@@ -411,7 +357,7 @@ struct NfpData {
411 u32 access_id; 357 u32 access_id;
412 u16 settings_crc_counter; 358 u16 settings_crc_counter;
413 u8 font_region; 359 u8 font_region;
414 PackedTagType tag_type; 360 NFC::PackedTagType tag_type;
415 AppAreaVersion console_type; 361 AppAreaVersion console_type;
416 u8 application_id_byte; 362 u8 application_id_byte;
417 INSERT_PADDING_BYTES(0x2E); 363 INSERT_PADDING_BYTES(0x2E);
@@ -420,37 +366,4 @@ struct NfpData {
420static_assert(sizeof(NfpData) == 0x298, "NfpData is an invalid size"); 366static_assert(sizeof(NfpData) == 0x298, "NfpData is an invalid size");
421#pragma pack() 367#pragma pack()
422 368
423struct SectorKey {
424 MifareCmd command;
425 u8 unknown; // Usually 1
426 INSERT_PADDING_BYTES(0x6);
427 KeyData sector_key;
428 INSERT_PADDING_BYTES(0x2);
429};
430static_assert(sizeof(SectorKey) == 0x10, "SectorKey is an invalid size");
431
432struct MifareReadBlockParameter {
433 u8 sector_number;
434 INSERT_PADDING_BYTES(0x7);
435 SectorKey sector_key;
436};
437static_assert(sizeof(MifareReadBlockParameter) == 0x18,
438 "MifareReadBlockParameter is an invalid size");
439
440struct MifareReadBlockData {
441 DataBlock data;
442 u8 sector_number;
443 INSERT_PADDING_BYTES(0x7);
444};
445static_assert(sizeof(MifareReadBlockData) == 0x18, "MifareReadBlockData is an invalid size");
446
447struct MifareWriteBlockParameter {
448 DataBlock data;
449 u8 sector_number;
450 INSERT_PADDING_BYTES(0x7);
451 SectorKey sector_key;
452};
453static_assert(sizeof(MifareWriteBlockParameter) == 0x28,
454 "MifareWriteBlockParameter is an invalid size");
455
456} // namespace Service::NFP 369} // namespace Service::NFP
diff --git a/src/core/hle/service/nifm/nifm.cpp b/src/core/hle/service/nifm/nifm.cpp
index 0c042f412..91d42853e 100644
--- a/src/core/hle/service/nifm/nifm.cpp
+++ b/src/core/hle/service/nifm/nifm.cpp
@@ -218,7 +218,7 @@ public:
218 218
219private: 219private:
220 void Submit(HLERequestContext& ctx) { 220 void Submit(HLERequestContext& ctx) {
221 LOG_WARNING(Service_NIFM, "(STUBBED) called"); 221 LOG_DEBUG(Service_NIFM, "(STUBBED) called");
222 222
223 if (state == RequestState::NotSubmitted) { 223 if (state == RequestState::NotSubmitted) {
224 UpdateState(RequestState::OnHold); 224 UpdateState(RequestState::OnHold);
@@ -229,7 +229,7 @@ private:
229 } 229 }
230 230
231 void GetRequestState(HLERequestContext& ctx) { 231 void GetRequestState(HLERequestContext& ctx) {
232 LOG_WARNING(Service_NIFM, "(STUBBED) called"); 232 LOG_DEBUG(Service_NIFM, "(STUBBED) called");
233 233
234 IPC::ResponseBuilder rb{ctx, 3}; 234 IPC::ResponseBuilder rb{ctx, 3};
235 rb.Push(ResultSuccess); 235 rb.Push(ResultSuccess);
@@ -237,7 +237,7 @@ private:
237 } 237 }
238 238
239 void GetResult(HLERequestContext& ctx) { 239 void GetResult(HLERequestContext& ctx) {
240 LOG_WARNING(Service_NIFM, "(STUBBED) called"); 240 LOG_DEBUG(Service_NIFM, "(STUBBED) called");
241 241
242 const auto result = [this] { 242 const auto result = [this] {
243 const auto has_connection = Network::GetHostIPv4Address().has_value(); 243 const auto has_connection = Network::GetHostIPv4Address().has_value();
diff --git a/src/core/hle/service/service.h b/src/core/hle/service/service.h
index 0f79a1b7e..45b2c43b7 100644
--- a/src/core/hle/service/service.h
+++ b/src/core/hle/service/service.h
@@ -142,7 +142,8 @@ template <typename Self>
142class ServiceFramework : public ServiceFrameworkBase { 142class ServiceFramework : public ServiceFrameworkBase {
143protected: 143protected:
144 /// Contains information about a request type which is handled by the service. 144 /// Contains information about a request type which is handled by the service.
145 struct FunctionInfo : FunctionInfoBase { 145 template <typename T>
146 struct FunctionInfoTyped : FunctionInfoBase {
146 // TODO(yuriks): This function could be constexpr, but clang is the only compiler that 147 // TODO(yuriks): This function could be constexpr, but clang is the only compiler that
147 // doesn't emit an ICE or a wrong diagnostic because of the static_cast. 148 // doesn't emit an ICE or a wrong diagnostic because of the static_cast.
148 149
@@ -155,12 +156,13 @@ protected:
155 * the request 156 * the request
156 * @param name_ human-friendly name for the request. Used mostly for logging purposes. 157 * @param name_ human-friendly name for the request. Used mostly for logging purposes.
157 */ 158 */
158 FunctionInfo(u32 expected_header_, HandlerFnP<Self> handler_callback_, const char* name_) 159 FunctionInfoTyped(u32 expected_header_, HandlerFnP<T> handler_callback_, const char* name_)
159 : FunctionInfoBase{ 160 : FunctionInfoBase{
160 expected_header_, 161 expected_header_,
161 // Type-erase member function pointer by casting it down to the base class. 162 // Type-erase member function pointer by casting it down to the base class.
162 static_cast<HandlerFnP<ServiceFrameworkBase>>(handler_callback_), name_} {} 163 static_cast<HandlerFnP<ServiceFrameworkBase>>(handler_callback_), name_} {}
163 }; 164 };
165 using FunctionInfo = FunctionInfoTyped<Self>;
164 166
165 /** 167 /**
166 * Initializes the handler with no functions installed. 168 * Initializes the handler with no functions installed.
@@ -175,8 +177,8 @@ protected:
175 : ServiceFrameworkBase(system_, service_name_, max_sessions_, Invoker) {} 177 : ServiceFrameworkBase(system_, service_name_, max_sessions_, Invoker) {}
176 178
177 /// Registers handlers in the service. 179 /// Registers handlers in the service.
178 template <std::size_t N> 180 template <typename T = Self, std::size_t N>
179 void RegisterHandlers(const FunctionInfo (&functions)[N]) { 181 void RegisterHandlers(const FunctionInfoTyped<T> (&functions)[N]) {
180 RegisterHandlers(functions, N); 182 RegisterHandlers(functions, N);
181 } 183 }
182 184
@@ -184,13 +186,14 @@ protected:
184 * Registers handlers in the service. Usually prefer using the other RegisterHandlers 186 * Registers handlers in the service. Usually prefer using the other RegisterHandlers
185 * overload in order to avoid needing to specify the array size. 187 * overload in order to avoid needing to specify the array size.
186 */ 188 */
187 void RegisterHandlers(const FunctionInfo* functions, std::size_t n) { 189 template <typename T = Self>
190 void RegisterHandlers(const FunctionInfoTyped<T>* functions, std::size_t n) {
188 RegisterHandlersBase(functions, n); 191 RegisterHandlersBase(functions, n);
189 } 192 }
190 193
191 /// Registers handlers in the service. 194 /// Registers handlers in the service.
192 template <std::size_t N> 195 template <typename T = Self, std::size_t N>
193 void RegisterHandlersTipc(const FunctionInfo (&functions)[N]) { 196 void RegisterHandlersTipc(const FunctionInfoTyped<T> (&functions)[N]) {
194 RegisterHandlersTipc(functions, N); 197 RegisterHandlersTipc(functions, N);
195 } 198 }
196 199
@@ -198,7 +201,8 @@ protected:
198 * Registers handlers in the service. Usually prefer using the other RegisterHandlers 201 * Registers handlers in the service. Usually prefer using the other RegisterHandlers
199 * overload in order to avoid needing to specify the array size. 202 * overload in order to avoid needing to specify the array size.
200 */ 203 */
201 void RegisterHandlersTipc(const FunctionInfo* functions, std::size_t n) { 204 template <typename T = Self>
205 void RegisterHandlersTipc(const FunctionInfoTyped<T>* functions, std::size_t n) {
202 RegisterHandlersBaseTipc(functions, n); 206 RegisterHandlersBaseTipc(functions, n);
203 } 207 }
204 208
diff --git a/src/core/internal_network/network.cpp b/src/core/internal_network/network.cpp
index bf97b0ebc..75ac10a9c 100644
--- a/src/core/internal_network/network.cpp
+++ b/src/core/internal_network/network.cpp
@@ -356,7 +356,7 @@ NetworkInstance::~NetworkInstance() {
356std::optional<IPv4Address> GetHostIPv4Address() { 356std::optional<IPv4Address> GetHostIPv4Address() {
357 const auto network_interface = Network::GetSelectedNetworkInterface(); 357 const auto network_interface = Network::GetSelectedNetworkInterface();
358 if (!network_interface.has_value()) { 358 if (!network_interface.has_value()) {
359 LOG_ERROR(Network, "GetSelectedNetworkInterface returned no interface"); 359 LOG_DEBUG(Network, "GetSelectedNetworkInterface returned no interface");
360 return {}; 360 return {};
361 } 361 }
362 362
diff --git a/src/core/internal_network/network_interface.cpp b/src/core/internal_network/network_interface.cpp
index 7b8e510a2..4c909a6d3 100644
--- a/src/core/internal_network/network_interface.cpp
+++ b/src/core/internal_network/network_interface.cpp
@@ -200,7 +200,7 @@ std::optional<NetworkInterface> GetSelectedNetworkInterface() {
200 }); 200 });
201 201
202 if (res == network_interfaces.end()) { 202 if (res == network_interfaces.end()) {
203 LOG_ERROR(Network, "Couldn't find selected interface \"{}\"", selected_network_interface); 203 LOG_DEBUG(Network, "Couldn't find selected interface \"{}\"", selected_network_interface);
204 return std::nullopt; 204 return std::nullopt;
205 } 205 }
206 206
diff --git a/src/core/memory.cpp b/src/core/memory.cpp
index a9667463f..514ba0d66 100644
--- a/src/core/memory.cpp
+++ b/src/core/memory.cpp
@@ -13,10 +13,12 @@
13#include "common/swap.h" 13#include "common/swap.h"
14#include "core/core.h" 14#include "core/core.h"
15#include "core/device_memory.h" 15#include "core/device_memory.h"
16#include "core/hardware_properties.h"
16#include "core/hle/kernel/k_page_table.h" 17#include "core/hle/kernel/k_page_table.h"
17#include "core/hle/kernel/k_process.h" 18#include "core/hle/kernel/k_process.h"
18#include "core/memory.h" 19#include "core/memory.h"
19#include "video_core/gpu.h" 20#include "video_core/gpu.h"
21#include "video_core/rasterizer_download_area.h"
20 22
21namespace Core::Memory { 23namespace Core::Memory {
22 24
@@ -243,7 +245,7 @@ struct Memory::Impl {
243 [&](const Common::ProcessAddress current_vaddr, const std::size_t copy_amount, 245 [&](const Common::ProcessAddress current_vaddr, const std::size_t copy_amount,
244 const u8* const host_ptr) { 246 const u8* const host_ptr) {
245 if constexpr (!UNSAFE) { 247 if constexpr (!UNSAFE) {
246 system.GPU().FlushRegion(GetInteger(current_vaddr), copy_amount); 248 HandleRasterizerDownload(GetInteger(current_vaddr), copy_amount);
247 } 249 }
248 std::memcpy(dest_buffer, host_ptr, copy_amount); 250 std::memcpy(dest_buffer, host_ptr, copy_amount);
249 }, 251 },
@@ -334,7 +336,7 @@ struct Memory::Impl {
334 }, 336 },
335 [&](const Common::ProcessAddress current_vaddr, const std::size_t copy_amount, 337 [&](const Common::ProcessAddress current_vaddr, const std::size_t copy_amount,
336 u8* const host_ptr) { 338 u8* const host_ptr) {
337 system.GPU().FlushRegion(GetInteger(current_vaddr), copy_amount); 339 HandleRasterizerDownload(GetInteger(current_vaddr), copy_amount);
338 WriteBlockImpl<false>(process, dest_addr, host_ptr, copy_amount); 340 WriteBlockImpl<false>(process, dest_addr, host_ptr, copy_amount);
339 }, 341 },
340 [&](const std::size_t copy_amount) { 342 [&](const std::size_t copy_amount) {
@@ -373,7 +375,7 @@ struct Memory::Impl {
373 const std::size_t block_size) { 375 const std::size_t block_size) {
374 // dc ivac: Invalidate to point of coherency 376 // dc ivac: Invalidate to point of coherency
375 // GPU flush -> CPU invalidate 377 // GPU flush -> CPU invalidate
376 system.GPU().FlushRegion(GetInteger(current_vaddr), block_size); 378 HandleRasterizerDownload(GetInteger(current_vaddr), block_size);
377 }; 379 };
378 return PerformCacheOperation(process, dest_addr, size, on_rasterizer); 380 return PerformCacheOperation(process, dest_addr, size, on_rasterizer);
379 } 381 }
@@ -462,7 +464,8 @@ struct Memory::Impl {
462 } 464 }
463 465
464 if (Settings::IsFastmemEnabled()) { 466 if (Settings::IsFastmemEnabled()) {
465 const bool is_read_enable = !Settings::IsGPULevelExtreme() || !cached; 467 const bool is_read_enable =
468 !Settings::values.use_reactive_flushing.GetValue() || !cached;
466 system.DeviceMemory().buffer.Protect(vaddr, size, is_read_enable, !cached); 469 system.DeviceMemory().buffer.Protect(vaddr, size, is_read_enable, !cached);
467 } 470 }
468 471
@@ -651,7 +654,7 @@ struct Memory::Impl {
651 LOG_ERROR(HW_Memory, "Unmapped Read{} @ 0x{:016X}", sizeof(T) * 8, 654 LOG_ERROR(HW_Memory, "Unmapped Read{} @ 0x{:016X}", sizeof(T) * 8,
652 GetInteger(vaddr)); 655 GetInteger(vaddr));
653 }, 656 },
654 [&]() { system.GPU().FlushRegion(GetInteger(vaddr), sizeof(T)); }); 657 [&]() { HandleRasterizerDownload(GetInteger(vaddr), sizeof(T)); });
655 if (ptr) { 658 if (ptr) {
656 std::memcpy(&result, ptr, sizeof(T)); 659 std::memcpy(&result, ptr, sizeof(T));
657 } 660 }
@@ -712,7 +715,19 @@ struct Memory::Impl {
712 return true; 715 return true;
713 } 716 }
714 717
718 void HandleRasterizerDownload(VAddr address, size_t size) {
719 const size_t core = system.GetCurrentHostThreadID();
720 auto& current_area = rasterizer_areas[core];
721 const VAddr end_address = address + size;
722 if (current_area.start_address <= address && end_address <= current_area.end_address)
723 [[likely]] {
724 return;
725 }
726 current_area = system.GPU().OnCPURead(address, size);
727 }
728
715 Common::PageTable* current_page_table = nullptr; 729 Common::PageTable* current_page_table = nullptr;
730 std::array<VideoCore::RasterizerDownloadArea, Core::Hardware::NUM_CPU_CORES> rasterizer_areas{};
716 Core::System& system; 731 Core::System& system;
717}; 732};
718 733
diff --git a/src/input_common/helpers/joycon_protocol/common_protocol.cpp b/src/input_common/helpers/joycon_protocol/common_protocol.cpp
index 2b42a4555..077d72cd0 100644
--- a/src/input_common/helpers/joycon_protocol/common_protocol.cpp
+++ b/src/input_common/helpers/joycon_protocol/common_protocol.cpp
@@ -236,13 +236,13 @@ DriverResult JoyconCommonProtocol::GetMCUDataResponse(ReportMode report_mode,
236 return DriverResult::Success; 236 return DriverResult::Success;
237} 237}
238 238
239DriverResult JoyconCommonProtocol::SendMCUData(ReportMode report_mode, SubCommand sc, 239DriverResult JoyconCommonProtocol::SendMCUData(ReportMode report_mode, MCUSubCommand sc,
240 std::span<const u8> buffer, 240 std::span<const u8> buffer,
241 MCUCommandResponse& output) { 241 MCUCommandResponse& output) {
242 SubCommandPacket packet{ 242 SubCommandPacket packet{
243 .output_report = OutputReport::MCU_DATA, 243 .output_report = OutputReport::MCU_DATA,
244 .packet_counter = GetCounter(), 244 .packet_counter = GetCounter(),
245 .sub_command = sc, 245 .mcu_sub_command = sc,
246 .command_data = {}, 246 .command_data = {},
247 }; 247 };
248 248
@@ -269,8 +269,7 @@ DriverResult JoyconCommonProtocol::WaitSetMCUMode(ReportMode report_mode, MCUMod
269 std::size_t tries{}; 269 std::size_t tries{};
270 270
271 do { 271 do {
272 const std::vector<u8> mcu_data{static_cast<u8>(MCUMode::Standby)}; 272 const auto result = SendMCUData(report_mode, MCUSubCommand::SetDeviceMode, {}, output);
273 const auto result = SendMCUData(report_mode, SubCommand::STATE, mcu_data, output);
274 273
275 if (result != DriverResult::Success) { 274 if (result != DriverResult::Success) {
276 return result; 275 return result;
diff --git a/src/input_common/helpers/joycon_protocol/common_protocol.h b/src/input_common/helpers/joycon_protocol/common_protocol.h
index 62cae739a..411ec018a 100644
--- a/src/input_common/helpers/joycon_protocol/common_protocol.h
+++ b/src/input_common/helpers/joycon_protocol/common_protocol.h
@@ -156,7 +156,7 @@ public:
156 * @param buffer data to be send 156 * @param buffer data to be send
157 * @returns output buffer containing the response 157 * @returns output buffer containing the response
158 */ 158 */
159 DriverResult SendMCUData(ReportMode report_mode, SubCommand sc, std::span<const u8> buffer, 159 DriverResult SendMCUData(ReportMode report_mode, MCUSubCommand sc, std::span<const u8> buffer,
160 MCUCommandResponse& output); 160 MCUCommandResponse& output);
161 161
162 /** 162 /**
diff --git a/src/input_common/helpers/joycon_protocol/joycon_types.h b/src/input_common/helpers/joycon_protocol/joycon_types.h
index dcac0e422..b03143e04 100644
--- a/src/input_common/helpers/joycon_protocol/joycon_types.h
+++ b/src/input_common/helpers/joycon_protocol/joycon_types.h
@@ -575,7 +575,6 @@ struct NFCPollingCommandData {
575static_assert(sizeof(NFCPollingCommandData) == 0x05, "NFCPollingCommandData is an invalid size"); 575static_assert(sizeof(NFCPollingCommandData) == 0x05, "NFCPollingCommandData is an invalid size");
576 576
577struct NFCRequestState { 577struct NFCRequestState {
578 MCUSubCommand sub_command;
579 NFCReadCommand command_argument; 578 NFCReadCommand command_argument;
580 u8 packet_id; 579 u8 packet_id;
581 INSERT_PADDING_BYTES(0x1); 580 INSERT_PADDING_BYTES(0x1);
@@ -587,6 +586,7 @@ struct NFCRequestState {
587 NFCPollingCommandData nfc_polling; 586 NFCPollingCommandData nfc_polling;
588 }; 587 };
589 u8 crc; 588 u8 crc;
589 INSERT_PADDING_BYTES(0x1);
590}; 590};
591static_assert(sizeof(NFCRequestState) == 0x26, "NFCRequestState is an invalid size"); 591static_assert(sizeof(NFCRequestState) == 0x26, "NFCRequestState is an invalid size");
592 592
@@ -659,7 +659,10 @@ struct SubCommandPacket {
659 OutputReport output_report; 659 OutputReport output_report;
660 u8 packet_counter; 660 u8 packet_counter;
661 INSERT_PADDING_BYTES(0x8); // This contains vibration data 661 INSERT_PADDING_BYTES(0x8); // This contains vibration data
662 SubCommand sub_command; 662 union {
663 SubCommand sub_command;
664 MCUSubCommand mcu_sub_command;
665 };
663 std::array<u8, 0x26> command_data; 666 std::array<u8, 0x26> command_data;
664}; 667};
665static_assert(sizeof(SubCommandPacket) == 0x31, "SubCommandPacket is an invalid size"); 668static_assert(sizeof(SubCommandPacket) == 0x31, "SubCommandPacket is an invalid size");
diff --git a/src/input_common/helpers/joycon_protocol/nfc.cpp b/src/input_common/helpers/joycon_protocol/nfc.cpp
index eeba82986..77ea6d5cf 100644
--- a/src/input_common/helpers/joycon_protocol/nfc.cpp
+++ b/src/input_common/helpers/joycon_protocol/nfc.cpp
@@ -278,7 +278,6 @@ DriverResult NfcProtocol::GetAmiiboData(std::vector<u8>& ntag_data) {
278 278
279DriverResult NfcProtocol::SendStartPollingRequest(MCUCommandResponse& output) { 279DriverResult NfcProtocol::SendStartPollingRequest(MCUCommandResponse& output) {
280 NFCRequestState request{ 280 NFCRequestState request{
281 .sub_command = MCUSubCommand::ReadDeviceMode,
282 .command_argument = NFCReadCommand::StartPolling, 281 .command_argument = NFCReadCommand::StartPolling,
283 .packet_id = 0x0, 282 .packet_id = 0x0,
284 .packet_flag = MCUPacketFlag::LastCommandPacket, 283 .packet_flag = MCUPacketFlag::LastCommandPacket,
@@ -296,13 +295,13 @@ DriverResult NfcProtocol::SendStartPollingRequest(MCUCommandResponse& output) {
296 295
297 std::array<u8, sizeof(NFCRequestState)> request_data{}; 296 std::array<u8, sizeof(NFCRequestState)> request_data{};
298 memcpy(request_data.data(), &request, sizeof(NFCRequestState)); 297 memcpy(request_data.data(), &request, sizeof(NFCRequestState));
299 request_data[37] = CalculateMCU_CRC8(request_data.data() + 1, 36); 298 request_data[36] = CalculateMCU_CRC8(request_data.data(), 36);
300 return SendMCUData(ReportMode::NFC_IR_MODE_60HZ, SubCommand::STATE, request_data, output); 299 return SendMCUData(ReportMode::NFC_IR_MODE_60HZ, MCUSubCommand::ReadDeviceMode, request_data,
300 output);
301} 301}
302 302
303DriverResult NfcProtocol::SendStopPollingRequest(MCUCommandResponse& output) { 303DriverResult NfcProtocol::SendStopPollingRequest(MCUCommandResponse& output) {
304 NFCRequestState request{ 304 NFCRequestState request{
305 .sub_command = MCUSubCommand::ReadDeviceMode,
306 .command_argument = NFCReadCommand::StopPolling, 305 .command_argument = NFCReadCommand::StopPolling,
307 .packet_id = 0x0, 306 .packet_id = 0x0,
308 .packet_flag = MCUPacketFlag::LastCommandPacket, 307 .packet_flag = MCUPacketFlag::LastCommandPacket,
@@ -313,13 +312,13 @@ DriverResult NfcProtocol::SendStopPollingRequest(MCUCommandResponse& output) {
313 312
314 std::array<u8, sizeof(NFCRequestState)> request_data{}; 313 std::array<u8, sizeof(NFCRequestState)> request_data{};
315 memcpy(request_data.data(), &request, sizeof(NFCRequestState)); 314 memcpy(request_data.data(), &request, sizeof(NFCRequestState));
316 request_data[37] = CalculateMCU_CRC8(request_data.data() + 1, 36); 315 request_data[36] = CalculateMCU_CRC8(request_data.data(), 36);
317 return SendMCUData(ReportMode::NFC_IR_MODE_60HZ, SubCommand::STATE, request_data, output); 316 return SendMCUData(ReportMode::NFC_IR_MODE_60HZ, MCUSubCommand::ReadDeviceMode, request_data,
317 output);
318} 318}
319 319
320DriverResult NfcProtocol::SendStartWaitingRecieveRequest(MCUCommandResponse& output) { 320DriverResult NfcProtocol::SendStartWaitingRecieveRequest(MCUCommandResponse& output) {
321 NFCRequestState request{ 321 NFCRequestState request{
322 .sub_command = MCUSubCommand::ReadDeviceMode,
323 .command_argument = NFCReadCommand::StartWaitingRecieve, 322 .command_argument = NFCReadCommand::StartWaitingRecieve,
324 .packet_id = 0x0, 323 .packet_id = 0x0,
325 .packet_flag = MCUPacketFlag::LastCommandPacket, 324 .packet_flag = MCUPacketFlag::LastCommandPacket,
@@ -330,13 +329,13 @@ DriverResult NfcProtocol::SendStartWaitingRecieveRequest(MCUCommandResponse& out
330 329
331 std::vector<u8> request_data(sizeof(NFCRequestState)); 330 std::vector<u8> request_data(sizeof(NFCRequestState));
332 memcpy(request_data.data(), &request, sizeof(NFCRequestState)); 331 memcpy(request_data.data(), &request, sizeof(NFCRequestState));
333 request_data[37] = CalculateMCU_CRC8(request_data.data() + 1, 36); 332 request_data[36] = CalculateMCU_CRC8(request_data.data(), 36);
334 return SendMCUData(ReportMode::NFC_IR_MODE_60HZ, SubCommand::STATE, request_data, output); 333 return SendMCUData(ReportMode::NFC_IR_MODE_60HZ, MCUSubCommand::ReadDeviceMode, request_data,
334 output);
335} 335}
336 336
337DriverResult NfcProtocol::SendReadAmiiboRequest(MCUCommandResponse& output, NFCPages ntag_pages) { 337DriverResult NfcProtocol::SendReadAmiiboRequest(MCUCommandResponse& output, NFCPages ntag_pages) {
338 NFCRequestState request{ 338 NFCRequestState request{
339 .sub_command = MCUSubCommand::ReadDeviceMode,
340 .command_argument = NFCReadCommand::Ntag, 339 .command_argument = NFCReadCommand::Ntag,
341 .packet_id = 0x0, 340 .packet_id = 0x0,
342 .packet_flag = MCUPacketFlag::LastCommandPacket, 341 .packet_flag = MCUPacketFlag::LastCommandPacket,
@@ -355,8 +354,9 @@ DriverResult NfcProtocol::SendReadAmiiboRequest(MCUCommandResponse& output, NFCP
355 354
356 std::array<u8, sizeof(NFCRequestState)> request_data{}; 355 std::array<u8, sizeof(NFCRequestState)> request_data{};
357 memcpy(request_data.data(), &request, sizeof(NFCRequestState)); 356 memcpy(request_data.data(), &request, sizeof(NFCRequestState));
358 request_data[37] = CalculateMCU_CRC8(request_data.data() + 1, 36); 357 request_data[36] = CalculateMCU_CRC8(request_data.data(), 36);
359 return SendMCUData(ReportMode::NFC_IR_MODE_60HZ, SubCommand::STATE, request_data, output); 358 return SendMCUData(ReportMode::NFC_IR_MODE_60HZ, MCUSubCommand::ReadDeviceMode, request_data,
359 output);
360} 360}
361 361
362NFCReadBlockCommand NfcProtocol::GetReadBlockCommand(NFCPages pages) const { 362NFCReadBlockCommand NfcProtocol::GetReadBlockCommand(NFCPages pages) const {
diff --git a/src/input_common/input_poller.cpp b/src/input_common/input_poller.cpp
index 5c2c4a463..380a01542 100644
--- a/src/input_common/input_poller.cpp
+++ b/src/input_common/input_poller.cpp
@@ -667,7 +667,7 @@ public:
667 .raw_value = input_engine->GetAxis(identifier, axis_z), 667 .raw_value = input_engine->GetAxis(identifier, axis_z),
668 .properties = properties_z, 668 .properties = properties_z,
669 }; 669 };
670 status.delta_timestamp = 5000; 670 status.delta_timestamp = 1000;
671 status.force_update = true; 671 status.force_update = true;
672 return status; 672 return status;
673 } 673 }
diff --git a/src/tests/video_core/memory_tracker.cpp b/src/tests/video_core/memory_tracker.cpp
index 3981907a2..618793668 100644
--- a/src/tests/video_core/memory_tracker.cpp
+++ b/src/tests/video_core/memory_tracker.cpp
@@ -535,12 +535,12 @@ TEST_CASE("MemoryTracker: Cached write downloads") {
535 memory_track->MarkRegionAsGpuModified(c + PAGE, PAGE); 535 memory_track->MarkRegionAsGpuModified(c + PAGE, PAGE);
536 int num = 0; 536 int num = 0;
537 memory_track->ForEachDownloadRangeAndClear(c, WORD, [&](u64 offset, u64 size) { ++num; }); 537 memory_track->ForEachDownloadRangeAndClear(c, WORD, [&](u64 offset, u64 size) { ++num; });
538 REQUIRE(num == 1); 538 REQUIRE(num == 0);
539 num = 0; 539 num = 0;
540 memory_track->ForEachUploadRange(c, WORD, [&](u64 offset, u64 size) { ++num; }); 540 memory_track->ForEachUploadRange(c, WORD, [&](u64 offset, u64 size) { ++num; });
541 REQUIRE(num == 0); 541 REQUIRE(num == 0);
542 REQUIRE(!memory_track->IsRegionCpuModified(c + PAGE, PAGE)); 542 REQUIRE(!memory_track->IsRegionCpuModified(c + PAGE, PAGE));
543 REQUIRE(!memory_track->IsRegionGpuModified(c + PAGE, PAGE)); 543 REQUIRE(memory_track->IsRegionGpuModified(c + PAGE, PAGE));
544 memory_track->FlushCachedWrites(); 544 memory_track->FlushCachedWrites();
545 REQUIRE(memory_track->IsRegionCpuModified(c + PAGE, PAGE)); 545 REQUIRE(memory_track->IsRegionCpuModified(c + PAGE, PAGE));
546 REQUIRE(!memory_track->IsRegionGpuModified(c + PAGE, PAGE)); 546 REQUIRE(!memory_track->IsRegionGpuModified(c + PAGE, PAGE));
diff --git a/src/video_core/buffer_cache/buffer_base.h b/src/video_core/buffer_cache/buffer_base.h
index 9cbd95c4b..0bb3bf8ae 100644
--- a/src/video_core/buffer_cache/buffer_base.h
+++ b/src/video_core/buffer_cache/buffer_base.h
@@ -18,6 +18,7 @@ namespace VideoCommon {
18enum class BufferFlagBits { 18enum class BufferFlagBits {
19 Picked = 1 << 0, 19 Picked = 1 << 0,
20 CachedWrites = 1 << 1, 20 CachedWrites = 1 << 1,
21 PreemtiveDownload = 1 << 2,
21}; 22};
22DECLARE_ENUM_FLAG_OPERATORS(BufferFlagBits) 23DECLARE_ENUM_FLAG_OPERATORS(BufferFlagBits)
23 24
@@ -54,6 +55,10 @@ public:
54 flags |= BufferFlagBits::Picked; 55 flags |= BufferFlagBits::Picked;
55 } 56 }
56 57
58 void MarkPreemtiveDownload() noexcept {
59 flags |= BufferFlagBits::PreemtiveDownload;
60 }
61
57 /// Unmark buffer as picked 62 /// Unmark buffer as picked
58 void Unpick() noexcept { 63 void Unpick() noexcept {
59 flags &= ~BufferFlagBits::Picked; 64 flags &= ~BufferFlagBits::Picked;
@@ -84,6 +89,10 @@ public:
84 return True(flags & BufferFlagBits::CachedWrites); 89 return True(flags & BufferFlagBits::CachedWrites);
85 } 90 }
86 91
92 bool IsPreemtiveDownload() const noexcept {
93 return True(flags & BufferFlagBits::PreemtiveDownload);
94 }
95
87 /// Returns the base CPU address of the buffer 96 /// Returns the base CPU address of the buffer
88 [[nodiscard]] VAddr CpuAddr() const noexcept { 97 [[nodiscard]] VAddr CpuAddr() const noexcept {
89 return cpu_addr; 98 return cpu_addr;
diff --git a/src/video_core/buffer_cache/buffer_cache.h b/src/video_core/buffer_cache/buffer_cache.h
index e534e1e9c..6624919a4 100644
--- a/src/video_core/buffer_cache/buffer_cache.h
+++ b/src/video_core/buffer_cache/buffer_cache.h
@@ -23,8 +23,6 @@ BufferCache<P>::BufferCache(VideoCore::RasterizerInterface& rasterizer_,
23 common_ranges.clear(); 23 common_ranges.clear();
24 inline_buffer_id = NULL_BUFFER_ID; 24 inline_buffer_id = NULL_BUFFER_ID;
25 25
26 active_async_buffers = !Settings::IsGPULevelHigh();
27
28 if (!runtime.CanReportMemoryUsage()) { 26 if (!runtime.CanReportMemoryUsage()) {
29 minimum_memory = DEFAULT_EXPECTED_MEMORY; 27 minimum_memory = DEFAULT_EXPECTED_MEMORY;
30 critical_memory = DEFAULT_CRITICAL_MEMORY; 28 critical_memory = DEFAULT_CRITICAL_MEMORY;
@@ -75,8 +73,6 @@ void BufferCache<P>::TickFrame() {
75 uniform_cache_hits[0] = 0; 73 uniform_cache_hits[0] = 0;
76 uniform_cache_shots[0] = 0; 74 uniform_cache_shots[0] = 0;
77 75
78 active_async_buffers = !Settings::IsGPULevelHigh();
79
80 const bool skip_preferred = hits * 256 < shots * 251; 76 const bool skip_preferred = hits * 256 < shots * 251;
81 uniform_buffer_skip_cache_size = skip_preferred ? DEFAULT_SKIP_CACHE_SIZE : 0; 77 uniform_buffer_skip_cache_size = skip_preferred ? DEFAULT_SKIP_CACHE_SIZE : 0;
82 78
@@ -111,9 +107,25 @@ void BufferCache<P>::WriteMemory(VAddr cpu_addr, u64 size) {
111template <class P> 107template <class P>
112void BufferCache<P>::CachedWriteMemory(VAddr cpu_addr, u64 size) { 108void BufferCache<P>::CachedWriteMemory(VAddr cpu_addr, u64 size) {
113 memory_tracker.CachedCpuWrite(cpu_addr, size); 109 memory_tracker.CachedCpuWrite(cpu_addr, size);
114 const IntervalType add_interval{Common::AlignDown(cpu_addr, YUZU_PAGESIZE), 110}
115 Common::AlignUp(cpu_addr + size, YUZU_PAGESIZE)}; 111
116 cached_ranges.add(add_interval); 112template <class P>
113std::optional<VideoCore::RasterizerDownloadArea> BufferCache<P>::GetFlushArea(VAddr cpu_addr,
114 u64 size) {
115 std::optional<VideoCore::RasterizerDownloadArea> area{};
116 area.emplace();
117 VAddr cpu_addr_start_aligned = Common::AlignDown(cpu_addr, Core::Memory::YUZU_PAGESIZE);
118 VAddr cpu_addr_end_aligned = Common::AlignUp(cpu_addr + size, Core::Memory::YUZU_PAGESIZE);
119 area->start_address = cpu_addr_start_aligned;
120 area->end_address = cpu_addr_end_aligned;
121 if (memory_tracker.IsRegionPreflushable(cpu_addr, size)) {
122 area->preemtive = true;
123 return area;
124 };
125 memory_tracker.MarkRegionAsPreflushable(cpu_addr_start_aligned,
126 cpu_addr_end_aligned - cpu_addr_start_aligned);
127 area->preemtive = !IsRegionGpuModified(cpu_addr, size);
128 return area;
117} 129}
118 130
119template <class P> 131template <class P>
@@ -205,7 +217,7 @@ bool BufferCache<P>::DMACopy(GPUVAddr src_address, GPUVAddr dest_address, u64 am
205 if (has_new_downloads) { 217 if (has_new_downloads) {
206 memory_tracker.MarkRegionAsGpuModified(*cpu_dest_address, amount); 218 memory_tracker.MarkRegionAsGpuModified(*cpu_dest_address, amount);
207 } 219 }
208 std::vector<u8> tmp_buffer(amount); 220 tmp_buffer.resize(amount);
209 cpu_memory.ReadBlockUnsafe(*cpu_src_address, tmp_buffer.data(), amount); 221 cpu_memory.ReadBlockUnsafe(*cpu_src_address, tmp_buffer.data(), amount);
210 cpu_memory.WriteBlockUnsafe(*cpu_dest_address, tmp_buffer.data(), amount); 222 cpu_memory.WriteBlockUnsafe(*cpu_dest_address, tmp_buffer.data(), amount);
211 return true; 223 return true;
@@ -441,9 +453,7 @@ void BufferCache<P>::BindComputeTextureBuffer(size_t tbo_index, GPUVAddr gpu_add
441 453
442template <class P> 454template <class P>
443void BufferCache<P>::FlushCachedWrites() { 455void BufferCache<P>::FlushCachedWrites() {
444 cached_write_buffer_ids.clear();
445 memory_tracker.FlushCachedWrites(); 456 memory_tracker.FlushCachedWrites();
446 cached_ranges.clear();
447} 457}
448 458
449template <class P> 459template <class P>
@@ -474,9 +484,8 @@ void BufferCache<P>::CommitAsyncFlushesHigh() {
474 484
475 if (committed_ranges.empty()) { 485 if (committed_ranges.empty()) {
476 if constexpr (IMPLEMENTS_ASYNC_DOWNLOADS) { 486 if constexpr (IMPLEMENTS_ASYNC_DOWNLOADS) {
477 if (active_async_buffers) { 487
478 async_buffers.emplace_back(std::optional<Async_Buffer>{}); 488 async_buffers.emplace_back(std::optional<Async_Buffer>{});
479 }
480 } 489 }
481 return; 490 return;
482 } 491 }
@@ -537,64 +546,65 @@ void BufferCache<P>::CommitAsyncFlushesHigh() {
537 committed_ranges.clear(); 546 committed_ranges.clear();
538 if (downloads.empty()) { 547 if (downloads.empty()) {
539 if constexpr (IMPLEMENTS_ASYNC_DOWNLOADS) { 548 if constexpr (IMPLEMENTS_ASYNC_DOWNLOADS) {
540 if (active_async_buffers) { 549
541 async_buffers.emplace_back(std::optional<Async_Buffer>{}); 550 async_buffers.emplace_back(std::optional<Async_Buffer>{});
542 }
543 } 551 }
544 return; 552 return;
545 } 553 }
546 if (active_async_buffers) { 554 if constexpr (IMPLEMENTS_ASYNC_DOWNLOADS) {
547 if constexpr (IMPLEMENTS_ASYNC_DOWNLOADS) { 555 auto download_staging = runtime.DownloadStagingBuffer(total_size_bytes, true);
548 auto download_staging = runtime.DownloadStagingBuffer(total_size_bytes, true); 556 boost::container::small_vector<BufferCopy, 4> normalized_copies;
549 boost::container::small_vector<BufferCopy, 4> normalized_copies; 557 IntervalSet new_async_range{};
550 IntervalSet new_async_range{}; 558 runtime.PreCopyBarrier();
551 runtime.PreCopyBarrier(); 559 for (auto& [copy, buffer_id] : downloads) {
552 for (auto& [copy, buffer_id] : downloads) { 560 copy.dst_offset += download_staging.offset;
553 copy.dst_offset += download_staging.offset; 561 const std::array copies{copy};
554 const std::array copies{copy}; 562 BufferCopy second_copy{copy};
555 BufferCopy second_copy{copy}; 563 Buffer& buffer = slot_buffers[buffer_id];
556 Buffer& buffer = slot_buffers[buffer_id]; 564 second_copy.src_offset = static_cast<size_t>(buffer.CpuAddr()) + copy.src_offset;
557 second_copy.src_offset = static_cast<size_t>(buffer.CpuAddr()) + copy.src_offset; 565 VAddr orig_cpu_addr = static_cast<VAddr>(second_copy.src_offset);
558 VAddr orig_cpu_addr = static_cast<VAddr>(second_copy.src_offset); 566 const IntervalType base_interval{orig_cpu_addr, orig_cpu_addr + copy.size};
559 const IntervalType base_interval{orig_cpu_addr, orig_cpu_addr + copy.size}; 567 async_downloads += std::make_pair(base_interval, 1);
560 async_downloads += std::make_pair(base_interval, 1); 568 runtime.CopyBuffer(download_staging.buffer, buffer, copies, false);
561 runtime.CopyBuffer(download_staging.buffer, buffer, copies, false); 569 normalized_copies.push_back(second_copy);
562 normalized_copies.push_back(second_copy);
563 }
564 runtime.PostCopyBarrier();
565 pending_downloads.emplace_back(std::move(normalized_copies));
566 async_buffers.emplace_back(download_staging);
567 } else {
568 committed_ranges.clear();
569 uncommitted_ranges.clear();
570 } 570 }
571 runtime.PostCopyBarrier();
572 pending_downloads.emplace_back(std::move(normalized_copies));
573 async_buffers.emplace_back(download_staging);
571 } else { 574 } else {
572 if constexpr (USE_MEMORY_MAPS) { 575 if (!Settings::IsGPULevelHigh()) {
573 auto download_staging = runtime.DownloadStagingBuffer(total_size_bytes); 576 committed_ranges.clear();
574 runtime.PreCopyBarrier(); 577 uncommitted_ranges.clear();
575 for (auto& [copy, buffer_id] : downloads) {
576 // Have in mind the staging buffer offset for the copy
577 copy.dst_offset += download_staging.offset;
578 const std::array copies{copy};
579 runtime.CopyBuffer(download_staging.buffer, slot_buffers[buffer_id], copies, false);
580 }
581 runtime.PostCopyBarrier();
582 runtime.Finish();
583 for (const auto& [copy, buffer_id] : downloads) {
584 const Buffer& buffer = slot_buffers[buffer_id];
585 const VAddr cpu_addr = buffer.CpuAddr() + copy.src_offset;
586 // Undo the modified offset
587 const u64 dst_offset = copy.dst_offset - download_staging.offset;
588 const u8* read_mapped_memory = download_staging.mapped_span.data() + dst_offset;
589 cpu_memory.WriteBlockUnsafe(cpu_addr, read_mapped_memory, copy.size);
590 }
591 } else { 578 } else {
592 const std::span<u8> immediate_buffer = ImmediateBuffer(largest_copy); 579 if constexpr (USE_MEMORY_MAPS) {
593 for (const auto& [copy, buffer_id] : downloads) { 580 auto download_staging = runtime.DownloadStagingBuffer(total_size_bytes);
594 Buffer& buffer = slot_buffers[buffer_id]; 581 runtime.PreCopyBarrier();
595 buffer.ImmediateDownload(copy.src_offset, immediate_buffer.subspan(0, copy.size)); 582 for (auto& [copy, buffer_id] : downloads) {
596 const VAddr cpu_addr = buffer.CpuAddr() + copy.src_offset; 583 // Have in mind the staging buffer offset for the copy
597 cpu_memory.WriteBlockUnsafe(cpu_addr, immediate_buffer.data(), copy.size); 584 copy.dst_offset += download_staging.offset;
585 const std::array copies{copy};
586 runtime.CopyBuffer(download_staging.buffer, slot_buffers[buffer_id], copies,
587 false);
588 }
589 runtime.PostCopyBarrier();
590 runtime.Finish();
591 for (const auto& [copy, buffer_id] : downloads) {
592 const Buffer& buffer = slot_buffers[buffer_id];
593 const VAddr cpu_addr = buffer.CpuAddr() + copy.src_offset;
594 // Undo the modified offset
595 const u64 dst_offset = copy.dst_offset - download_staging.offset;
596 const u8* read_mapped_memory = download_staging.mapped_span.data() + dst_offset;
597 cpu_memory.WriteBlockUnsafe(cpu_addr, read_mapped_memory, copy.size);
598 }
599 } else {
600 const std::span<u8> immediate_buffer = ImmediateBuffer(largest_copy);
601 for (const auto& [copy, buffer_id] : downloads) {
602 Buffer& buffer = slot_buffers[buffer_id];
603 buffer.ImmediateDownload(copy.src_offset,
604 immediate_buffer.subspan(0, copy.size));
605 const VAddr cpu_addr = buffer.CpuAddr() + copy.src_offset;
606 cpu_memory.WriteBlockUnsafe(cpu_addr, immediate_buffer.data(), copy.size);
607 }
598 } 608 }
599 } 609 }
600 } 610 }
@@ -1629,7 +1639,6 @@ void BufferCache<P>::DeleteBuffer(BufferId buffer_id, bool do_not_mark) {
1629 replace(transform_feedback_buffers); 1639 replace(transform_feedback_buffers);
1630 replace(compute_uniform_buffers); 1640 replace(compute_uniform_buffers);
1631 replace(compute_storage_buffers); 1641 replace(compute_storage_buffers);
1632 std::erase(cached_write_buffer_ids, buffer_id);
1633 1642
1634 // Mark the whole buffer as CPU written to stop tracking CPU writes 1643 // Mark the whole buffer as CPU written to stop tracking CPU writes
1635 if (!do_not_mark) { 1644 if (!do_not_mark) {
diff --git a/src/video_core/buffer_cache/buffer_cache_base.h b/src/video_core/buffer_cache/buffer_cache_base.h
index 656baa550..0445ec47f 100644
--- a/src/video_core/buffer_cache/buffer_cache_base.h
+++ b/src/video_core/buffer_cache/buffer_cache_base.h
@@ -188,6 +188,8 @@ public:
188 188
189 void DownloadMemory(VAddr cpu_addr, u64 size); 189 void DownloadMemory(VAddr cpu_addr, u64 size);
190 190
191 std::optional<VideoCore::RasterizerDownloadArea> GetFlushArea(VAddr cpu_addr, u64 size);
192
191 bool InlineMemory(VAddr dest_address, size_t copy_size, std::span<const u8> inlined_buffer); 193 bool InlineMemory(VAddr dest_address, size_t copy_size, std::span<const u8> inlined_buffer);
192 194
193 void BindGraphicsUniformBuffer(size_t stage, u32 index, GPUVAddr gpu_addr, u32 size); 195 void BindGraphicsUniformBuffer(size_t stage, u32 index, GPUVAddr gpu_addr, u32 size);
@@ -541,8 +543,6 @@ private:
541 std::array<std::array<u32, NUM_GRAPHICS_UNIFORM_BUFFERS>, NUM_STAGES>, Empty> 543 std::array<std::array<u32, NUM_GRAPHICS_UNIFORM_BUFFERS>, NUM_STAGES>, Empty>
542 uniform_buffer_binding_sizes{}; 544 uniform_buffer_binding_sizes{};
543 545
544 std::vector<BufferId> cached_write_buffer_ids;
545
546 MemoryTracker memory_tracker; 546 MemoryTracker memory_tracker;
547 IntervalSet uncommitted_ranges; 547 IntervalSet uncommitted_ranges;
548 IntervalSet common_ranges; 548 IntervalSet common_ranges;
@@ -572,9 +572,8 @@ private:
572 u64 critical_memory = 0; 572 u64 critical_memory = 0;
573 BufferId inline_buffer_id; 573 BufferId inline_buffer_id;
574 574
575 bool active_async_buffers = false;
576
577 std::array<BufferId, ((1ULL << 39) >> CACHING_PAGEBITS)> page_table; 575 std::array<BufferId, ((1ULL << 39) >> CACHING_PAGEBITS)> page_table;
576 std::vector<u8> tmp_buffer;
578}; 577};
579 578
580} // namespace VideoCommon 579} // namespace VideoCommon
diff --git a/src/video_core/buffer_cache/memory_tracker_base.h b/src/video_core/buffer_cache/memory_tracker_base.h
index dc4ebfcaa..6036b21c9 100644
--- a/src/video_core/buffer_cache/memory_tracker_base.h
+++ b/src/video_core/buffer_cache/memory_tracker_base.h
@@ -66,6 +66,14 @@ public:
66 }); 66 });
67 } 67 }
68 68
69 /// Returns true if a region has been marked as Preflushable
70 [[nodiscard]] bool IsRegionPreflushable(VAddr query_cpu_addr, u64 query_size) noexcept {
71 return IteratePages<false>(
72 query_cpu_addr, query_size, [](Manager* manager, u64 offset, size_t size) {
73 return manager->template IsRegionModified<Type::Preflushable>(offset, size);
74 });
75 }
76
69 /// Mark region as CPU modified, notifying the rasterizer about this change 77 /// Mark region as CPU modified, notifying the rasterizer about this change
70 void MarkRegionAsCpuModified(VAddr dirty_cpu_addr, u64 query_size) { 78 void MarkRegionAsCpuModified(VAddr dirty_cpu_addr, u64 query_size) {
71 IteratePages<true>(dirty_cpu_addr, query_size, 79 IteratePages<true>(dirty_cpu_addr, query_size,
@@ -93,6 +101,15 @@ public:
93 }); 101 });
94 } 102 }
95 103
104 /// Mark region as modified from the host GPU
105 void MarkRegionAsPreflushable(VAddr dirty_cpu_addr, u64 query_size) noexcept {
106 IteratePages<true>(dirty_cpu_addr, query_size,
107 [](Manager* manager, u64 offset, size_t size) {
108 manager->template ChangeRegionState<Type::Preflushable, true>(
109 manager->GetCpuAddr() + offset, size);
110 });
111 }
112
96 /// Unmark region as modified from the host GPU 113 /// Unmark region as modified from the host GPU
97 void UnmarkRegionAsGpuModified(VAddr dirty_cpu_addr, u64 query_size) noexcept { 114 void UnmarkRegionAsGpuModified(VAddr dirty_cpu_addr, u64 query_size) noexcept {
98 IteratePages<true>(dirty_cpu_addr, query_size, 115 IteratePages<true>(dirty_cpu_addr, query_size,
@@ -102,6 +119,15 @@ public:
102 }); 119 });
103 } 120 }
104 121
122 /// Unmark region as modified from the host GPU
123 void UnmarkRegionAsPreflushable(VAddr dirty_cpu_addr, u64 query_size) noexcept {
124 IteratePages<true>(dirty_cpu_addr, query_size,
125 [](Manager* manager, u64 offset, size_t size) {
126 manager->template ChangeRegionState<Type::Preflushable, false>(
127 manager->GetCpuAddr() + offset, size);
128 });
129 }
130
105 /// Mark region as modified from the CPU 131 /// Mark region as modified from the CPU
106 /// but don't mark it as modified until FlusHCachedWrites is called. 132 /// but don't mark it as modified until FlusHCachedWrites is called.
107 void CachedCpuWrite(VAddr dirty_cpu_addr, u64 query_size) { 133 void CachedCpuWrite(VAddr dirty_cpu_addr, u64 query_size) {
diff --git a/src/video_core/buffer_cache/word_manager.h b/src/video_core/buffer_cache/word_manager.h
index a42455045..a336bde41 100644
--- a/src/video_core/buffer_cache/word_manager.h
+++ b/src/video_core/buffer_cache/word_manager.h
@@ -26,6 +26,7 @@ enum class Type {
26 GPU, 26 GPU,
27 CachedCPU, 27 CachedCPU,
28 Untracked, 28 Untracked,
29 Preflushable,
29}; 30};
30 31
31/// Vector tracking modified pages tightly packed with small vector optimization 32/// Vector tracking modified pages tightly packed with small vector optimization
@@ -55,17 +56,20 @@ struct Words {
55 gpu.stack.fill(0); 56 gpu.stack.fill(0);
56 cached_cpu.stack.fill(0); 57 cached_cpu.stack.fill(0);
57 untracked.stack.fill(~u64{0}); 58 untracked.stack.fill(~u64{0});
59 preflushable.stack.fill(0);
58 } else { 60 } else {
59 // Share allocation between CPU and GPU pages and set their default values 61 // Share allocation between CPU and GPU pages and set their default values
60 u64* const alloc = new u64[num_words * 4]; 62 u64* const alloc = new u64[num_words * 5];
61 cpu.heap = alloc; 63 cpu.heap = alloc;
62 gpu.heap = alloc + num_words; 64 gpu.heap = alloc + num_words;
63 cached_cpu.heap = alloc + num_words * 2; 65 cached_cpu.heap = alloc + num_words * 2;
64 untracked.heap = alloc + num_words * 3; 66 untracked.heap = alloc + num_words * 3;
67 preflushable.heap = alloc + num_words * 4;
65 std::fill_n(cpu.heap, num_words, ~u64{0}); 68 std::fill_n(cpu.heap, num_words, ~u64{0});
66 std::fill_n(gpu.heap, num_words, 0); 69 std::fill_n(gpu.heap, num_words, 0);
67 std::fill_n(cached_cpu.heap, num_words, 0); 70 std::fill_n(cached_cpu.heap, num_words, 0);
68 std::fill_n(untracked.heap, num_words, ~u64{0}); 71 std::fill_n(untracked.heap, num_words, ~u64{0});
72 std::fill_n(preflushable.heap, num_words, 0);
69 } 73 }
70 // Clean up tailing bits 74 // Clean up tailing bits
71 const u64 last_word_size = size_bytes % BYTES_PER_WORD; 75 const u64 last_word_size = size_bytes % BYTES_PER_WORD;
@@ -88,13 +92,14 @@ struct Words {
88 gpu = rhs.gpu; 92 gpu = rhs.gpu;
89 cached_cpu = rhs.cached_cpu; 93 cached_cpu = rhs.cached_cpu;
90 untracked = rhs.untracked; 94 untracked = rhs.untracked;
95 preflushable = rhs.preflushable;
91 rhs.cpu.heap = nullptr; 96 rhs.cpu.heap = nullptr;
92 return *this; 97 return *this;
93 } 98 }
94 99
95 Words(Words&& rhs) noexcept 100 Words(Words&& rhs) noexcept
96 : size_bytes{rhs.size_bytes}, num_words{rhs.num_words}, cpu{rhs.cpu}, gpu{rhs.gpu}, 101 : size_bytes{rhs.size_bytes}, num_words{rhs.num_words}, cpu{rhs.cpu}, gpu{rhs.gpu},
97 cached_cpu{rhs.cached_cpu}, untracked{rhs.untracked} { 102 cached_cpu{rhs.cached_cpu}, untracked{rhs.untracked}, preflushable{rhs.preflushable} {
98 rhs.cpu.heap = nullptr; 103 rhs.cpu.heap = nullptr;
99 } 104 }
100 105
@@ -129,6 +134,8 @@ struct Words {
129 return std::span<u64>(cached_cpu.Pointer(IsShort()), num_words); 134 return std::span<u64>(cached_cpu.Pointer(IsShort()), num_words);
130 } else if constexpr (type == Type::Untracked) { 135 } else if constexpr (type == Type::Untracked) {
131 return std::span<u64>(untracked.Pointer(IsShort()), num_words); 136 return std::span<u64>(untracked.Pointer(IsShort()), num_words);
137 } else if constexpr (type == Type::Preflushable) {
138 return std::span<u64>(preflushable.Pointer(IsShort()), num_words);
132 } 139 }
133 } 140 }
134 141
@@ -142,6 +149,8 @@ struct Words {
142 return std::span<const u64>(cached_cpu.Pointer(IsShort()), num_words); 149 return std::span<const u64>(cached_cpu.Pointer(IsShort()), num_words);
143 } else if constexpr (type == Type::Untracked) { 150 } else if constexpr (type == Type::Untracked) {
144 return std::span<const u64>(untracked.Pointer(IsShort()), num_words); 151 return std::span<const u64>(untracked.Pointer(IsShort()), num_words);
152 } else if constexpr (type == Type::Preflushable) {
153 return std::span<const u64>(preflushable.Pointer(IsShort()), num_words);
145 } 154 }
146 } 155 }
147 156
@@ -151,6 +160,7 @@ struct Words {
151 WordsArray<stack_words> gpu; 160 WordsArray<stack_words> gpu;
152 WordsArray<stack_words> cached_cpu; 161 WordsArray<stack_words> cached_cpu;
153 WordsArray<stack_words> untracked; 162 WordsArray<stack_words> untracked;
163 WordsArray<stack_words> preflushable;
154}; 164};
155 165
156template <class RasterizerInterface, size_t stack_words = 1> 166template <class RasterizerInterface, size_t stack_words = 1>
@@ -292,6 +302,9 @@ public:
292 (pending_pointer - pending_offset) * BYTES_PER_PAGE); 302 (pending_pointer - pending_offset) * BYTES_PER_PAGE);
293 }; 303 };
294 IterateWords(offset, size, [&](size_t index, u64 mask) { 304 IterateWords(offset, size, [&](size_t index, u64 mask) {
305 if constexpr (type == Type::GPU) {
306 mask &= ~untracked_words[index];
307 }
295 const u64 word = state_words[index] & mask; 308 const u64 word = state_words[index] & mask;
296 if constexpr (clear) { 309 if constexpr (clear) {
297 if constexpr (type == Type::CPU || type == Type::CachedCPU) { 310 if constexpr (type == Type::CPU || type == Type::CachedCPU) {
@@ -340,8 +353,13 @@ public:
340 static_assert(type != Type::Untracked); 353 static_assert(type != Type::Untracked);
341 354
342 const std::span<const u64> state_words = words.template Span<type>(); 355 const std::span<const u64> state_words = words.template Span<type>();
356 [[maybe_unused]] const std::span<const u64> untracked_words =
357 words.template Span<Type::Untracked>();
343 bool result = false; 358 bool result = false;
344 IterateWords(offset, size, [&](size_t index, u64 mask) { 359 IterateWords(offset, size, [&](size_t index, u64 mask) {
360 if constexpr (type == Type::GPU) {
361 mask &= ~untracked_words[index];
362 }
345 const u64 word = state_words[index] & mask; 363 const u64 word = state_words[index] & mask;
346 if (word != 0) { 364 if (word != 0) {
347 result = true; 365 result = true;
@@ -362,9 +380,14 @@ public:
362 [[nodiscard]] std::pair<u64, u64> ModifiedRegion(u64 offset, u64 size) const noexcept { 380 [[nodiscard]] std::pair<u64, u64> ModifiedRegion(u64 offset, u64 size) const noexcept {
363 static_assert(type != Type::Untracked); 381 static_assert(type != Type::Untracked);
364 const std::span<const u64> state_words = words.template Span<type>(); 382 const std::span<const u64> state_words = words.template Span<type>();
383 [[maybe_unused]] const std::span<const u64> untracked_words =
384 words.template Span<Type::Untracked>();
365 u64 begin = std::numeric_limits<u64>::max(); 385 u64 begin = std::numeric_limits<u64>::max();
366 u64 end = 0; 386 u64 end = 0;
367 IterateWords(offset, size, [&](size_t index, u64 mask) { 387 IterateWords(offset, size, [&](size_t index, u64 mask) {
388 if constexpr (type == Type::GPU) {
389 mask &= ~untracked_words[index];
390 }
368 const u64 word = state_words[index] & mask; 391 const u64 word = state_words[index] & mask;
369 if (word == 0) { 392 if (word == 0) {
370 return; 393 return;
diff --git a/src/video_core/engines/maxwell_dma.cpp b/src/video_core/engines/maxwell_dma.cpp
index e68850dc5..ebe5536de 100644
--- a/src/video_core/engines/maxwell_dma.cpp
+++ b/src/video_core/engines/maxwell_dma.cpp
@@ -223,7 +223,7 @@ void MaxwellDMA::CopyBlockLinearToPitch() {
223 write_buffer.resize_destructive(dst_size); 223 write_buffer.resize_destructive(dst_size);
224 224
225 memory_manager.ReadBlock(src_operand.address, read_buffer.data(), src_size); 225 memory_manager.ReadBlock(src_operand.address, read_buffer.data(), src_size);
226 memory_manager.ReadBlockUnsafe(dst_operand.address, write_buffer.data(), dst_size); 226 memory_manager.ReadBlock(dst_operand.address, write_buffer.data(), dst_size);
227 227
228 UnswizzleSubrect(write_buffer, read_buffer, bytes_per_pixel, width, height, depth, x_offset, 228 UnswizzleSubrect(write_buffer, read_buffer, bytes_per_pixel, width, height, depth, x_offset,
229 src_params.origin.y, x_elements, regs.line_count, block_height, block_depth, 229 src_params.origin.y, x_elements, regs.line_count, block_height, block_depth,
@@ -288,11 +288,7 @@ void MaxwellDMA::CopyPitchToBlockLinear() {
288 write_buffer.resize_destructive(dst_size); 288 write_buffer.resize_destructive(dst_size);
289 289
290 memory_manager.ReadBlock(regs.offset_in, read_buffer.data(), src_size); 290 memory_manager.ReadBlock(regs.offset_in, read_buffer.data(), src_size);
291 if (Settings::IsGPULevelExtreme()) { 291 memory_manager.ReadBlockUnsafe(regs.offset_out, write_buffer.data(), dst_size);
292 memory_manager.ReadBlock(regs.offset_out, write_buffer.data(), dst_size);
293 } else {
294 memory_manager.ReadBlockUnsafe(regs.offset_out, write_buffer.data(), dst_size);
295 }
296 292
297 // If the input is linear and the output is tiled, swizzle the input and copy it over. 293 // If the input is linear and the output is tiled, swizzle the input and copy it over.
298 SwizzleSubrect(write_buffer, read_buffer, bytes_per_pixel, width, height, depth, x_offset, 294 SwizzleSubrect(write_buffer, read_buffer, bytes_per_pixel, width, height, depth, x_offset,
diff --git a/src/video_core/fence_manager.h b/src/video_core/fence_manager.h
index 3b2f6aab6..35d699bbf 100644
--- a/src/video_core/fence_manager.h
+++ b/src/video_core/fence_manager.h
@@ -59,6 +59,11 @@ public:
59 buffer_cache.AccumulateFlushes(); 59 buffer_cache.AccumulateFlushes();
60 } 60 }
61 61
62 void SignalReference() {
63 std::function<void()> do_nothing([] {});
64 SignalFence(std::move(do_nothing));
65 }
66
62 void SyncOperation(std::function<void()>&& func) { 67 void SyncOperation(std::function<void()>&& func) {
63 uncommitted_operations.emplace_back(std::move(func)); 68 uncommitted_operations.emplace_back(std::move(func));
64 } 69 }
diff --git a/src/video_core/gpu.cpp b/src/video_core/gpu.cpp
index 2e7f9c5ed..295a416a8 100644
--- a/src/video_core/gpu.cpp
+++ b/src/video_core/gpu.cpp
@@ -283,6 +283,21 @@ struct GPU::Impl {
283 gpu_thread.FlushRegion(addr, size); 283 gpu_thread.FlushRegion(addr, size);
284 } 284 }
285 285
286 VideoCore::RasterizerDownloadArea OnCPURead(VAddr addr, u64 size) {
287 auto raster_area = rasterizer->GetFlushArea(addr, size);
288 if (raster_area.preemtive) {
289 return raster_area;
290 }
291 raster_area.preemtive = true;
292 const u64 fence = RequestSyncOperation([this, &raster_area]() {
293 rasterizer->FlushRegion(raster_area.start_address,
294 raster_area.end_address - raster_area.start_address);
295 });
296 gpu_thread.TickGPU();
297 WaitForSyncOperation(fence);
298 return raster_area;
299 }
300
286 /// Notify rasterizer that any caches of the specified region should be invalidated 301 /// Notify rasterizer that any caches of the specified region should be invalidated
287 void InvalidateRegion(VAddr addr, u64 size) { 302 void InvalidateRegion(VAddr addr, u64 size) {
288 gpu_thread.InvalidateRegion(addr, size); 303 gpu_thread.InvalidateRegion(addr, size);
@@ -538,6 +553,10 @@ void GPU::SwapBuffers(const Tegra::FramebufferConfig* framebuffer) {
538 impl->SwapBuffers(framebuffer); 553 impl->SwapBuffers(framebuffer);
539} 554}
540 555
556VideoCore::RasterizerDownloadArea GPU::OnCPURead(VAddr addr, u64 size) {
557 return impl->OnCPURead(addr, size);
558}
559
541void GPU::FlushRegion(VAddr addr, u64 size) { 560void GPU::FlushRegion(VAddr addr, u64 size) {
542 impl->FlushRegion(addr, size); 561 impl->FlushRegion(addr, size);
543} 562}
diff --git a/src/video_core/gpu.h b/src/video_core/gpu.h
index 8a871593a..e49c40cf2 100644
--- a/src/video_core/gpu.h
+++ b/src/video_core/gpu.h
@@ -10,6 +10,7 @@
10#include "core/hle/service/nvdrv/nvdata.h" 10#include "core/hle/service/nvdrv/nvdata.h"
11#include "video_core/cdma_pusher.h" 11#include "video_core/cdma_pusher.h"
12#include "video_core/framebuffer_config.h" 12#include "video_core/framebuffer_config.h"
13#include "video_core/rasterizer_download_area.h"
13 14
14namespace Core { 15namespace Core {
15class System; 16class System;
@@ -241,6 +242,9 @@ public:
241 void SwapBuffers(const Tegra::FramebufferConfig* framebuffer); 242 void SwapBuffers(const Tegra::FramebufferConfig* framebuffer);
242 243
243 /// Notify rasterizer that any caches of the specified region should be flushed to Switch memory 244 /// Notify rasterizer that any caches of the specified region should be flushed to Switch memory
245 [[nodiscard]] VideoCore::RasterizerDownloadArea OnCPURead(VAddr addr, u64 size);
246
247 /// Notify rasterizer that any caches of the specified region should be flushed to Switch memory
244 void FlushRegion(VAddr addr, u64 size); 248 void FlushRegion(VAddr addr, u64 size);
245 249
246 /// Notify rasterizer that any caches of the specified region should be invalidated 250 /// Notify rasterizer that any caches of the specified region should be invalidated
diff --git a/src/video_core/query_cache.h b/src/video_core/query_cache.h
index 941de95c1..1528cc1dd 100644
--- a/src/video_core/query_cache.h
+++ b/src/video_core/query_cache.h
@@ -255,7 +255,6 @@ private:
255 if (!in_range(query)) { 255 if (!in_range(query)) {
256 continue; 256 continue;
257 } 257 }
258 rasterizer.UpdatePagesCachedCount(query.GetCpuAddr(), query.SizeInBytes(), -1);
259 AsyncJobId async_job_id = query.GetAsyncJob(); 258 AsyncJobId async_job_id = query.GetAsyncJob();
260 auto flush_result = query.Flush(async); 259 auto flush_result = query.Flush(async);
261 if (async_job_id == NULL_ASYNC_JOB_ID) { 260 if (async_job_id == NULL_ASYNC_JOB_ID) {
@@ -273,7 +272,6 @@ private:
273 272
274 /// Registers the passed parameters as cached and returns a pointer to the stored cached query. 273 /// Registers the passed parameters as cached and returns a pointer to the stored cached query.
275 CachedQuery* Register(VideoCore::QueryType type, VAddr cpu_addr, u8* host_ptr, bool timestamp) { 274 CachedQuery* Register(VideoCore::QueryType type, VAddr cpu_addr, u8* host_ptr, bool timestamp) {
276 rasterizer.UpdatePagesCachedCount(cpu_addr, CachedQuery::SizeInBytes(timestamp), 1);
277 const u64 page = static_cast<u64>(cpu_addr) >> YUZU_PAGEBITS; 275 const u64 page = static_cast<u64>(cpu_addr) >> YUZU_PAGEBITS;
278 return &cached_queries[page].emplace_back(static_cast<QueryCache&>(*this), type, cpu_addr, 276 return &cached_queries[page].emplace_back(static_cast<QueryCache&>(*this), type, cpu_addr,
279 host_ptr); 277 host_ptr);
diff --git a/src/video_core/rasterizer_download_area.h b/src/video_core/rasterizer_download_area.h
new file mode 100644
index 000000000..2d7425c79
--- /dev/null
+++ b/src/video_core/rasterizer_download_area.h
@@ -0,0 +1,16 @@
1// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-3.0-or-later
3
4#pragma once
5
6#include "common/common_types.h"
7
8namespace VideoCore {
9
10struct RasterizerDownloadArea {
11 VAddr start_address;
12 VAddr end_address;
13 bool preemtive;
14};
15
16} // namespace VideoCore \ No newline at end of file
diff --git a/src/video_core/rasterizer_interface.h b/src/video_core/rasterizer_interface.h
index 33e2610bc..7566a8c4e 100644
--- a/src/video_core/rasterizer_interface.h
+++ b/src/video_core/rasterizer_interface.h
@@ -12,6 +12,7 @@
12#include "video_core/cache_types.h" 12#include "video_core/cache_types.h"
13#include "video_core/engines/fermi_2d.h" 13#include "video_core/engines/fermi_2d.h"
14#include "video_core/gpu.h" 14#include "video_core/gpu.h"
15#include "video_core/rasterizer_download_area.h"
15 16
16namespace Tegra { 17namespace Tegra {
17class MemoryManager; 18class MemoryManager;
@@ -95,6 +96,8 @@ public:
95 virtual bool MustFlushRegion(VAddr addr, u64 size, 96 virtual bool MustFlushRegion(VAddr addr, u64 size,
96 VideoCommon::CacheType which = VideoCommon::CacheType::All) = 0; 97 VideoCommon::CacheType which = VideoCommon::CacheType::All) = 0;
97 98
99 virtual RasterizerDownloadArea GetFlushArea(VAddr addr, u64 size) = 0;
100
98 /// Notify rasterizer that any caches of the specified region should be invalidated 101 /// Notify rasterizer that any caches of the specified region should be invalidated
99 virtual void InvalidateRegion(VAddr addr, u64 size, 102 virtual void InvalidateRegion(VAddr addr, u64 size,
100 VideoCommon::CacheType which = VideoCommon::CacheType::All) = 0; 103 VideoCommon::CacheType which = VideoCommon::CacheType::All) = 0;
diff --git a/src/video_core/renderer_null/null_rasterizer.cpp b/src/video_core/renderer_null/null_rasterizer.cpp
index 2b5c7defa..bf2ce4c49 100644
--- a/src/video_core/renderer_null/null_rasterizer.cpp
+++ b/src/video_core/renderer_null/null_rasterizer.cpp
@@ -1,6 +1,8 @@
1// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project 1// SPDX-FileCopyrightText: Copyright 2022 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/alignment.h"
5#include "core/memory.h"
4#include "video_core/host1x/host1x.h" 6#include "video_core/host1x/host1x.h"
5#include "video_core/memory_manager.h" 7#include "video_core/memory_manager.h"
6#include "video_core/renderer_null/null_rasterizer.h" 8#include "video_core/renderer_null/null_rasterizer.h"
@@ -46,6 +48,14 @@ bool RasterizerNull::MustFlushRegion(VAddr addr, u64 size, VideoCommon::CacheTyp
46} 48}
47void RasterizerNull::InvalidateRegion(VAddr addr, u64 size, VideoCommon::CacheType) {} 49void RasterizerNull::InvalidateRegion(VAddr addr, u64 size, VideoCommon::CacheType) {}
48void RasterizerNull::OnCPUWrite(VAddr addr, u64 size) {} 50void RasterizerNull::OnCPUWrite(VAddr addr, u64 size) {}
51VideoCore::RasterizerDownloadArea RasterizerNull::GetFlushArea(VAddr addr, u64 size) {
52 VideoCore::RasterizerDownloadArea new_area{
53 .start_address = Common::AlignDown(addr, Core::Memory::YUZU_PAGESIZE),
54 .end_address = Common::AlignUp(addr + size, Core::Memory::YUZU_PAGESIZE),
55 .preemtive = true,
56 };
57 return new_area;
58}
49void RasterizerNull::InvalidateGPUCache() {} 59void RasterizerNull::InvalidateGPUCache() {}
50void RasterizerNull::UnmapMemory(VAddr addr, u64 size) {} 60void RasterizerNull::UnmapMemory(VAddr addr, u64 size) {}
51void RasterizerNull::ModifyGPUMemory(size_t as_id, GPUVAddr addr, u64 size) {} 61void RasterizerNull::ModifyGPUMemory(size_t as_id, GPUVAddr addr, u64 size) {}
diff --git a/src/video_core/renderer_null/null_rasterizer.h b/src/video_core/renderer_null/null_rasterizer.h
index 0c59e6a1f..a8d35d2c1 100644
--- a/src/video_core/renderer_null/null_rasterizer.h
+++ b/src/video_core/renderer_null/null_rasterizer.h
@@ -54,6 +54,7 @@ public:
54 void InvalidateRegion(VAddr addr, u64 size, 54 void InvalidateRegion(VAddr addr, u64 size,
55 VideoCommon::CacheType which = VideoCommon::CacheType::All) override; 55 VideoCommon::CacheType which = VideoCommon::CacheType::All) override;
56 void OnCPUWrite(VAddr addr, u64 size) override; 56 void OnCPUWrite(VAddr addr, u64 size) override;
57 VideoCore::RasterizerDownloadArea GetFlushArea(VAddr addr, u64 size) override;
57 void InvalidateGPUCache() override; 58 void InvalidateGPUCache() override;
58 void UnmapMemory(VAddr addr, u64 size) override; 59 void UnmapMemory(VAddr addr, u64 size) override;
59 void ModifyGPUMemory(size_t as_id, GPUVAddr addr, u64 size) override; 60 void ModifyGPUMemory(size_t as_id, GPUVAddr addr, u64 size) override;
diff --git a/src/video_core/renderer_opengl/gl_rasterizer.cpp b/src/video_core/renderer_opengl/gl_rasterizer.cpp
index 0089b4b27..f5baa0f3c 100644
--- a/src/video_core/renderer_opengl/gl_rasterizer.cpp
+++ b/src/video_core/renderer_opengl/gl_rasterizer.cpp
@@ -433,6 +433,29 @@ bool RasterizerOpenGL::MustFlushRegion(VAddr addr, u64 size, VideoCommon::CacheT
433 return false; 433 return false;
434} 434}
435 435
436VideoCore::RasterizerDownloadArea RasterizerOpenGL::GetFlushArea(VAddr addr, u64 size) {
437 {
438 std::scoped_lock lock{texture_cache.mutex};
439 auto area = texture_cache.GetFlushArea(addr, size);
440 if (area) {
441 return *area;
442 }
443 }
444 {
445 std::scoped_lock lock{buffer_cache.mutex};
446 auto area = buffer_cache.GetFlushArea(addr, size);
447 if (area) {
448 return *area;
449 }
450 }
451 VideoCore::RasterizerDownloadArea new_area{
452 .start_address = Common::AlignDown(addr, Core::Memory::YUZU_PAGESIZE),
453 .end_address = Common::AlignUp(addr + size, Core::Memory::YUZU_PAGESIZE),
454 .preemtive = true,
455 };
456 return new_area;
457}
458
436void RasterizerOpenGL::InvalidateRegion(VAddr addr, u64 size, VideoCommon::CacheType which) { 459void RasterizerOpenGL::InvalidateRegion(VAddr addr, u64 size, VideoCommon::CacheType which) {
437 MICROPROFILE_SCOPE(OpenGL_CacheManagement); 460 MICROPROFILE_SCOPE(OpenGL_CacheManagement);
438 if (addr == 0 || size == 0) { 461 if (addr == 0 || size == 0) {
@@ -1281,7 +1304,7 @@ bool AccelerateDMA::DmaBufferImageCopy(const Tegra::DMA::ImageCopy& copy_info,
1281 const Tegra::DMA::BufferOperand& buffer_operand, 1304 const Tegra::DMA::BufferOperand& buffer_operand,
1282 const Tegra::DMA::ImageOperand& image_operand) { 1305 const Tegra::DMA::ImageOperand& image_operand) {
1283 std::scoped_lock lock{buffer_cache.mutex, texture_cache.mutex}; 1306 std::scoped_lock lock{buffer_cache.mutex, texture_cache.mutex};
1284 const auto image_id = texture_cache.DmaImageId(image_operand); 1307 const auto image_id = texture_cache.DmaImageId(image_operand, IS_IMAGE_UPLOAD);
1285 if (image_id == VideoCommon::NULL_IMAGE_ID) { 1308 if (image_id == VideoCommon::NULL_IMAGE_ID) {
1286 return false; 1309 return false;
1287 } 1310 }
diff --git a/src/video_core/renderer_opengl/gl_rasterizer.h b/src/video_core/renderer_opengl/gl_rasterizer.h
index ad6978bd0..410d8ffc5 100644
--- a/src/video_core/renderer_opengl/gl_rasterizer.h
+++ b/src/video_core/renderer_opengl/gl_rasterizer.h
@@ -95,6 +95,7 @@ public:
95 VideoCommon::CacheType which = VideoCommon::CacheType::All) override; 95 VideoCommon::CacheType which = VideoCommon::CacheType::All) override;
96 bool MustFlushRegion(VAddr addr, u64 size, 96 bool MustFlushRegion(VAddr addr, u64 size,
97 VideoCommon::CacheType which = VideoCommon::CacheType::All) override; 97 VideoCommon::CacheType which = VideoCommon::CacheType::All) override;
98 VideoCore::RasterizerDownloadArea GetFlushArea(VAddr addr, u64 size) override;
98 void InvalidateRegion(VAddr addr, u64 size, 99 void InvalidateRegion(VAddr addr, u64 size,
99 VideoCommon::CacheType which = VideoCommon::CacheType::All) override; 100 VideoCommon::CacheType which = VideoCommon::CacheType::All) override;
100 void OnCPUWrite(VAddr addr, u64 size) override; 101 void OnCPUWrite(VAddr addr, u64 size) override;
diff --git a/src/video_core/renderer_opengl/gl_texture_cache.cpp b/src/video_core/renderer_opengl/gl_texture_cache.cpp
index 052456f61..31118886f 100644
--- a/src/video_core/renderer_opengl/gl_texture_cache.cpp
+++ b/src/video_core/renderer_opengl/gl_texture_cache.cpp
@@ -231,7 +231,7 @@ void ApplySwizzle(GLuint handle, PixelFormat format, std::array<SwizzleSource, 4
231 231
232[[nodiscard]] bool CanBeAccelerated(const TextureCacheRuntime& runtime, 232[[nodiscard]] bool CanBeAccelerated(const TextureCacheRuntime& runtime,
233 const VideoCommon::ImageInfo& info) { 233 const VideoCommon::ImageInfo& info) {
234 if (IsPixelFormatASTC(info.format) && !runtime.HasNativeASTC()) { 234 if (IsPixelFormatASTC(info.format) && info.size.depth == 1 && !runtime.HasNativeASTC()) {
235 return Settings::values.accelerate_astc.GetValue() && 235 return Settings::values.accelerate_astc.GetValue() &&
236 !Settings::values.async_astc.GetValue(); 236 !Settings::values.async_astc.GetValue();
237 } 237 }
diff --git a/src/video_core/renderer_vulkan/vk_rasterizer.cpp b/src/video_core/renderer_vulkan/vk_rasterizer.cpp
index d1489fc95..628e1376f 100644
--- a/src/video_core/renderer_vulkan/vk_rasterizer.cpp
+++ b/src/video_core/renderer_vulkan/vk_rasterizer.cpp
@@ -502,6 +502,22 @@ bool RasterizerVulkan::MustFlushRegion(VAddr addr, u64 size, VideoCommon::CacheT
502 return false; 502 return false;
503} 503}
504 504
505VideoCore::RasterizerDownloadArea RasterizerVulkan::GetFlushArea(VAddr addr, u64 size) {
506 {
507 std::scoped_lock lock{texture_cache.mutex};
508 auto area = texture_cache.GetFlushArea(addr, size);
509 if (area) {
510 return *area;
511 }
512 }
513 VideoCore::RasterizerDownloadArea new_area{
514 .start_address = Common::AlignDown(addr, Core::Memory::YUZU_PAGESIZE),
515 .end_address = Common::AlignUp(addr + size, Core::Memory::YUZU_PAGESIZE),
516 .preemtive = true,
517 };
518 return new_area;
519}
520
505void RasterizerVulkan::InvalidateRegion(VAddr addr, u64 size, VideoCommon::CacheType which) { 521void RasterizerVulkan::InvalidateRegion(VAddr addr, u64 size, VideoCommon::CacheType which) {
506 if (addr == 0 || size == 0) { 522 if (addr == 0 || size == 0) {
507 return; 523 return;
@@ -598,7 +614,7 @@ void RasterizerVulkan::SignalSyncPoint(u32 value) {
598} 614}
599 615
600void RasterizerVulkan::SignalReference() { 616void RasterizerVulkan::SignalReference() {
601 fence_manager.SignalOrdering(); 617 fence_manager.SignalReference();
602} 618}
603 619
604void RasterizerVulkan::ReleaseFences() { 620void RasterizerVulkan::ReleaseFences() {
@@ -631,7 +647,7 @@ void RasterizerVulkan::WaitForIdle() {
631 cmdbuf.SetEvent(event, flags); 647 cmdbuf.SetEvent(event, flags);
632 cmdbuf.WaitEvents(event, flags, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, {}, {}, {}); 648 cmdbuf.WaitEvents(event, flags, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, {}, {}, {});
633 }); 649 });
634 SignalReference(); 650 fence_manager.SignalOrdering();
635} 651}
636 652
637void RasterizerVulkan::FragmentBarrier() { 653void RasterizerVulkan::FragmentBarrier() {
@@ -777,7 +793,7 @@ bool AccelerateDMA::DmaBufferImageCopy(const Tegra::DMA::ImageCopy& copy_info,
777 const Tegra::DMA::BufferOperand& buffer_operand, 793 const Tegra::DMA::BufferOperand& buffer_operand,
778 const Tegra::DMA::ImageOperand& image_operand) { 794 const Tegra::DMA::ImageOperand& image_operand) {
779 std::scoped_lock lock{buffer_cache.mutex, texture_cache.mutex}; 795 std::scoped_lock lock{buffer_cache.mutex, texture_cache.mutex};
780 const auto image_id = texture_cache.DmaImageId(image_operand); 796 const auto image_id = texture_cache.DmaImageId(image_operand, IS_IMAGE_UPLOAD);
781 if (image_id == VideoCommon::NULL_IMAGE_ID) { 797 if (image_id == VideoCommon::NULL_IMAGE_ID) {
782 return false; 798 return false;
783 } 799 }
diff --git a/src/video_core/renderer_vulkan/vk_rasterizer.h b/src/video_core/renderer_vulkan/vk_rasterizer.h
index 1659fbc13..9bd422850 100644
--- a/src/video_core/renderer_vulkan/vk_rasterizer.h
+++ b/src/video_core/renderer_vulkan/vk_rasterizer.h
@@ -92,6 +92,7 @@ public:
92 VideoCommon::CacheType which = VideoCommon::CacheType::All) override; 92 VideoCommon::CacheType which = VideoCommon::CacheType::All) override;
93 bool MustFlushRegion(VAddr addr, u64 size, 93 bool MustFlushRegion(VAddr addr, u64 size,
94 VideoCommon::CacheType which = VideoCommon::CacheType::All) override; 94 VideoCommon::CacheType which = VideoCommon::CacheType::All) override;
95 VideoCore::RasterizerDownloadArea GetFlushArea(VAddr addr, u64 size) override;
95 void InvalidateRegion(VAddr addr, u64 size, 96 void InvalidateRegion(VAddr addr, u64 size,
96 VideoCommon::CacheType which = VideoCommon::CacheType::All) override; 97 VideoCommon::CacheType which = VideoCommon::CacheType::All) override;
97 void InnerInvalidation(std::span<const std::pair<VAddr, std::size_t>> sequences) override; 98 void InnerInvalidation(std::span<const std::pair<VAddr, std::size_t>> sequences) override;
diff --git a/src/video_core/renderer_vulkan/vk_texture_cache.cpp b/src/video_core/renderer_vulkan/vk_texture_cache.cpp
index 99dd1260a..9ca7751c5 100644
--- a/src/video_core/renderer_vulkan/vk_texture_cache.cpp
+++ b/src/video_core/renderer_vulkan/vk_texture_cache.cpp
@@ -1268,7 +1268,7 @@ Image::Image(TextureCacheRuntime& runtime_, const ImageInfo& info_, GPUVAddr gpu
1268 if (IsPixelFormatASTC(info.format) && !runtime->device.IsOptimalAstcSupported()) { 1268 if (IsPixelFormatASTC(info.format) && !runtime->device.IsOptimalAstcSupported()) {
1269 if (Settings::values.async_astc.GetValue()) { 1269 if (Settings::values.async_astc.GetValue()) {
1270 flags |= VideoCommon::ImageFlagBits::AsynchronousDecode; 1270 flags |= VideoCommon::ImageFlagBits::AsynchronousDecode;
1271 } else if (Settings::values.accelerate_astc.GetValue()) { 1271 } else if (Settings::values.accelerate_astc.GetValue() && info.size.depth == 1) {
1272 flags |= VideoCommon::ImageFlagBits::AcceleratedUpload; 1272 flags |= VideoCommon::ImageFlagBits::AcceleratedUpload;
1273 } 1273 }
1274 flags |= VideoCommon::ImageFlagBits::Converted; 1274 flags |= VideoCommon::ImageFlagBits::Converted;
diff --git a/src/video_core/texture_cache/image_info.cpp b/src/video_core/texture_cache/image_info.cpp
index 11f3f78a1..e8ddde691 100644
--- a/src/video_core/texture_cache/image_info.cpp
+++ b/src/video_core/texture_cache/image_info.cpp
@@ -4,6 +4,7 @@
4#include <fmt/format.h> 4#include <fmt/format.h>
5 5
6#include "common/assert.h" 6#include "common/assert.h"
7#include "common/settings.h"
7#include "video_core/surface.h" 8#include "video_core/surface.h"
8#include "video_core/texture_cache/format_lookup_table.h" 9#include "video_core/texture_cache/format_lookup_table.h"
9#include "video_core/texture_cache/image_info.h" 10#include "video_core/texture_cache/image_info.h"
@@ -22,6 +23,8 @@ using VideoCore::Surface::PixelFormat;
22using VideoCore::Surface::SurfaceType; 23using VideoCore::Surface::SurfaceType;
23 24
24ImageInfo::ImageInfo(const TICEntry& config) noexcept { 25ImageInfo::ImageInfo(const TICEntry& config) noexcept {
26 forced_flushed = config.IsPitchLinear() && !Settings::values.use_reactive_flushing.GetValue();
27 dma_downloaded = forced_flushed;
25 format = PixelFormatFromTextureInfo(config.format, config.r_type, config.g_type, config.b_type, 28 format = PixelFormatFromTextureInfo(config.format, config.r_type, config.g_type, config.b_type,
26 config.a_type, config.srgb_conversion); 29 config.a_type, config.srgb_conversion);
27 num_samples = NumSamples(config.msaa_mode); 30 num_samples = NumSamples(config.msaa_mode);
@@ -117,6 +120,9 @@ ImageInfo::ImageInfo(const TICEntry& config) noexcept {
117 120
118ImageInfo::ImageInfo(const Maxwell3D::Regs::RenderTargetConfig& ct, 121ImageInfo::ImageInfo(const Maxwell3D::Regs::RenderTargetConfig& ct,
119 Tegra::Texture::MsaaMode msaa_mode) noexcept { 122 Tegra::Texture::MsaaMode msaa_mode) noexcept {
123 forced_flushed =
124 ct.tile_mode.is_pitch_linear && !Settings::values.use_reactive_flushing.GetValue();
125 dma_downloaded = forced_flushed;
120 format = VideoCore::Surface::PixelFormatFromRenderTargetFormat(ct.format); 126 format = VideoCore::Surface::PixelFormatFromRenderTargetFormat(ct.format);
121 rescaleable = false; 127 rescaleable = false;
122 if (ct.tile_mode.is_pitch_linear) { 128 if (ct.tile_mode.is_pitch_linear) {
@@ -155,6 +161,9 @@ ImageInfo::ImageInfo(const Maxwell3D::Regs::RenderTargetConfig& ct,
155 161
156ImageInfo::ImageInfo(const Maxwell3D::Regs::Zeta& zt, const Maxwell3D::Regs::ZetaSize& zt_size, 162ImageInfo::ImageInfo(const Maxwell3D::Regs::Zeta& zt, const Maxwell3D::Regs::ZetaSize& zt_size,
157 Tegra::Texture::MsaaMode msaa_mode) noexcept { 163 Tegra::Texture::MsaaMode msaa_mode) noexcept {
164 forced_flushed =
165 zt.tile_mode.is_pitch_linear && !Settings::values.use_reactive_flushing.GetValue();
166 dma_downloaded = forced_flushed;
158 format = VideoCore::Surface::PixelFormatFromDepthFormat(zt.format); 167 format = VideoCore::Surface::PixelFormatFromDepthFormat(zt.format);
159 size.width = zt_size.width; 168 size.width = zt_size.width;
160 size.height = zt_size.height; 169 size.height = zt_size.height;
@@ -195,6 +204,9 @@ ImageInfo::ImageInfo(const Maxwell3D::Regs::Zeta& zt, const Maxwell3D::Regs::Zet
195 204
196ImageInfo::ImageInfo(const Fermi2D::Surface& config) noexcept { 205ImageInfo::ImageInfo(const Fermi2D::Surface& config) noexcept {
197 UNIMPLEMENTED_IF_MSG(config.layer != 0, "Surface layer is not zero"); 206 UNIMPLEMENTED_IF_MSG(config.layer != 0, "Surface layer is not zero");
207 forced_flushed = config.linear == Fermi2D::MemoryLayout::Pitch &&
208 !Settings::values.use_reactive_flushing.GetValue();
209 dma_downloaded = forced_flushed;
198 format = VideoCore::Surface::PixelFormatFromRenderTargetFormat(config.format); 210 format = VideoCore::Surface::PixelFormatFromRenderTargetFormat(config.format);
199 rescaleable = false; 211 rescaleable = false;
200 if (config.linear == Fermi2D::MemoryLayout::Pitch) { 212 if (config.linear == Fermi2D::MemoryLayout::Pitch) {
diff --git a/src/video_core/texture_cache/image_info.h b/src/video_core/texture_cache/image_info.h
index 4b7dfa315..8a4cb0cbd 100644
--- a/src/video_core/texture_cache/image_info.h
+++ b/src/video_core/texture_cache/image_info.h
@@ -39,6 +39,8 @@ struct ImageInfo {
39 u32 tile_width_spacing = 0; 39 u32 tile_width_spacing = 0;
40 bool rescaleable = false; 40 bool rescaleable = false;
41 bool downscaleable = false; 41 bool downscaleable = false;
42 bool forced_flushed = false;
43 bool dma_downloaded = false;
42}; 44};
43 45
44} // namespace VideoCommon 46} // namespace VideoCommon
diff --git a/src/video_core/texture_cache/image_view_base.cpp b/src/video_core/texture_cache/image_view_base.cpp
index bcad40353..d134b6738 100644
--- a/src/video_core/texture_cache/image_view_base.cpp
+++ b/src/video_core/texture_cache/image_view_base.cpp
@@ -4,7 +4,6 @@
4#include <algorithm> 4#include <algorithm>
5 5
6#include "common/assert.h" 6#include "common/assert.h"
7#include "common/settings.h"
8#include "video_core/compatible_formats.h" 7#include "video_core/compatible_formats.h"
9#include "video_core/surface.h" 8#include "video_core/surface.h"
10#include "video_core/texture_cache/formatter.h" 9#include "video_core/texture_cache/formatter.h"
@@ -26,8 +25,7 @@ ImageViewBase::ImageViewBase(const ImageViewInfo& info, const ImageInfo& image_i
26 ASSERT_MSG(VideoCore::Surface::IsViewCompatible(image_info.format, info.format, false, true), 25 ASSERT_MSG(VideoCore::Surface::IsViewCompatible(image_info.format, info.format, false, true),
27 "Image view format {} is incompatible with image format {}", info.format, 26 "Image view format {} is incompatible with image format {}", info.format,
28 image_info.format); 27 image_info.format);
29 const bool is_async = Settings::values.use_asynchronous_gpu_emulation.GetValue(); 28 if (image_info.forced_flushed) {
30 if (image_info.type == ImageType::Linear && is_async) {
31 flags |= ImageViewFlagBits::PreemtiveDownload; 29 flags |= ImageViewFlagBits::PreemtiveDownload;
32 } 30 }
33 if (image_info.type == ImageType::e3D && info.type != ImageViewType::e3D) { 31 if (image_info.type == ImageType::e3D && info.type != ImageViewType::e3D) {
diff --git a/src/video_core/texture_cache/texture_cache.h b/src/video_core/texture_cache/texture_cache.h
index b5297e76b..e1198dcf8 100644
--- a/src/video_core/texture_cache/texture_cache.h
+++ b/src/video_core/texture_cache/texture_cache.h
@@ -491,6 +491,32 @@ void TextureCache<P>::DownloadMemory(VAddr cpu_addr, size_t size) {
491} 491}
492 492
493template <class P> 493template <class P>
494std::optional<VideoCore::RasterizerDownloadArea> TextureCache<P>::GetFlushArea(VAddr cpu_addr,
495 u64 size) {
496 std::optional<VideoCore::RasterizerDownloadArea> area{};
497 ForEachImageInRegion(cpu_addr, size, [&](ImageId, ImageBase& image) {
498 if (False(image.flags & ImageFlagBits::GpuModified)) {
499 return;
500 }
501 if (!area) {
502 area.emplace();
503 area->start_address = cpu_addr;
504 area->end_address = cpu_addr + size;
505 area->preemtive = true;
506 }
507 area->start_address = std::min(area->start_address, image.cpu_addr);
508 area->end_address = std::max(area->end_address, image.cpu_addr_end);
509 for (auto image_view_id : image.image_view_ids) {
510 auto& image_view = slot_image_views[image_view_id];
511 image_view.flags |= ImageViewFlagBits::PreemtiveDownload;
512 }
513 area->preemtive &= image.info.forced_flushed;
514 image.info.forced_flushed = true;
515 });
516 return area;
517}
518
519template <class P>
494void TextureCache<P>::UnmapMemory(VAddr cpu_addr, size_t size) { 520void TextureCache<P>::UnmapMemory(VAddr cpu_addr, size_t size) {
495 std::vector<ImageId> deleted_images; 521 std::vector<ImageId> deleted_images;
496 ForEachImageInRegion(cpu_addr, size, [&](ImageId id, Image&) { deleted_images.push_back(id); }); 522 ForEachImageInRegion(cpu_addr, size, [&](ImageId id, Image&) { deleted_images.push_back(id); });
@@ -683,6 +709,7 @@ void TextureCache<P>::CommitAsyncFlushes() {
683 download_info.async_buffer_id = last_async_buffer_id; 709 download_info.async_buffer_id = last_async_buffer_id;
684 } 710 }
685 } 711 }
712
686 if (any_none_dma) { 713 if (any_none_dma) {
687 auto download_map = runtime.DownloadStagingBuffer(total_size_bytes, true); 714 auto download_map = runtime.DownloadStagingBuffer(total_size_bytes, true);
688 for (const PendingDownload& download_info : download_ids) { 715 for (const PendingDownload& download_info : download_ids) {
@@ -695,6 +722,7 @@ void TextureCache<P>::CommitAsyncFlushes() {
695 } 722 }
696 uncommitted_async_buffers.emplace_back(download_map); 723 uncommitted_async_buffers.emplace_back(download_map);
697 } 724 }
725
698 async_buffers.emplace_back(std::move(uncommitted_async_buffers)); 726 async_buffers.emplace_back(std::move(uncommitted_async_buffers));
699 uncommitted_async_buffers.clear(); 727 uncommitted_async_buffers.clear();
700 } 728 }
@@ -783,17 +811,22 @@ void TextureCache<P>::PopAsyncFlushes() {
783} 811}
784 812
785template <class P> 813template <class P>
786ImageId TextureCache<P>::DmaImageId(const Tegra::DMA::ImageOperand& operand) { 814ImageId TextureCache<P>::DmaImageId(const Tegra::DMA::ImageOperand& operand, bool is_upload) {
787 const ImageInfo dst_info(operand); 815 const ImageInfo dst_info(operand);
788 const ImageId dst_id = FindDMAImage(dst_info, operand.address); 816 const ImageId dst_id = FindDMAImage(dst_info, operand.address);
789 if (!dst_id) { 817 if (!dst_id) {
790 return NULL_IMAGE_ID; 818 return NULL_IMAGE_ID;
791 } 819 }
792 const auto& image = slot_images[dst_id]; 820 auto& image = slot_images[dst_id];
793 if (False(image.flags & ImageFlagBits::GpuModified)) { 821 if (False(image.flags & ImageFlagBits::GpuModified)) {
794 // No need to waste time on an image that's synced with guest 822 // No need to waste time on an image that's synced with guest
795 return NULL_IMAGE_ID; 823 return NULL_IMAGE_ID;
796 } 824 }
825 if (!is_upload && !image.info.dma_downloaded) {
826 // Force a full sync.
827 image.info.dma_downloaded = true;
828 return NULL_IMAGE_ID;
829 }
797 const auto base = image.TryFindBase(operand.address); 830 const auto base = image.TryFindBase(operand.address);
798 if (!base) { 831 if (!base) {
799 return NULL_IMAGE_ID; 832 return NULL_IMAGE_ID;
@@ -1290,7 +1323,6 @@ ImageId TextureCache<P>::JoinImages(const ImageInfo& info, GPUVAddr gpu_addr, VA
1290 all_siblings.push_back(overlap_id); 1323 all_siblings.push_back(overlap_id);
1291 } else { 1324 } else {
1292 bad_overlap_ids.push_back(overlap_id); 1325 bad_overlap_ids.push_back(overlap_id);
1293 overlap.flags |= ImageFlagBits::BadOverlap;
1294 } 1326 }
1295 }; 1327 };
1296 ForEachImageInRegion(cpu_addr, size_bytes, region_check); 1328 ForEachImageInRegion(cpu_addr, size_bytes, region_check);
@@ -1401,7 +1433,12 @@ ImageId TextureCache<P>::JoinImages(const ImageInfo& info, GPUVAddr gpu_addr, VA
1401 ImageBase& aliased = slot_images[aliased_id]; 1433 ImageBase& aliased = slot_images[aliased_id];
1402 aliased.overlapping_images.push_back(new_image_id); 1434 aliased.overlapping_images.push_back(new_image_id);
1403 new_image.overlapping_images.push_back(aliased_id); 1435 new_image.overlapping_images.push_back(aliased_id);
1404 new_image.flags |= ImageFlagBits::BadOverlap; 1436 if (aliased.info.resources.levels == 1 && aliased.overlapping_images.size() > 1) {
1437 aliased.flags |= ImageFlagBits::BadOverlap;
1438 }
1439 if (new_image.info.resources.levels == 1 && new_image.overlapping_images.size() > 1) {
1440 new_image.flags |= ImageFlagBits::BadOverlap;
1441 }
1405 } 1442 }
1406 RegisterImage(new_image_id); 1443 RegisterImage(new_image_id);
1407 return new_image_id; 1444 return new_image_id;
diff --git a/src/video_core/texture_cache/texture_cache_base.h b/src/video_core/texture_cache/texture_cache_base.h
index 758b7e212..0720494e5 100644
--- a/src/video_core/texture_cache/texture_cache_base.h
+++ b/src/video_core/texture_cache/texture_cache_base.h
@@ -179,6 +179,8 @@ public:
179 /// Download contents of host images to guest memory in a region 179 /// Download contents of host images to guest memory in a region
180 void DownloadMemory(VAddr cpu_addr, size_t size); 180 void DownloadMemory(VAddr cpu_addr, size_t size);
181 181
182 std::optional<VideoCore::RasterizerDownloadArea> GetFlushArea(VAddr cpu_addr, u64 size);
183
182 /// Remove images in a region 184 /// Remove images in a region
183 void UnmapMemory(VAddr cpu_addr, size_t size); 185 void UnmapMemory(VAddr cpu_addr, size_t size);
184 186
@@ -205,7 +207,7 @@ public:
205 /// Pop asynchronous downloads 207 /// Pop asynchronous downloads
206 void PopAsyncFlushes(); 208 void PopAsyncFlushes();
207 209
208 [[nodiscard]] ImageId DmaImageId(const Tegra::DMA::ImageOperand& operand); 210 [[nodiscard]] ImageId DmaImageId(const Tegra::DMA::ImageOperand& operand, bool is_upload);
209 211
210 [[nodiscard]] std::pair<Image*, BufferImageCopy> DmaBufferImageCopy( 212 [[nodiscard]] std::pair<Image*, BufferImageCopy> DmaBufferImageCopy(
211 const Tegra::DMA::ImageCopy& copy_info, const Tegra::DMA::BufferOperand& buffer_operand, 213 const Tegra::DMA::ImageCopy& copy_info, const Tegra::DMA::BufferOperand& buffer_operand,
diff --git a/src/video_core/texture_cache/util.cpp b/src/video_core/texture_cache/util.cpp
index de37db684..f1071aa23 100644
--- a/src/video_core/texture_cache/util.cpp
+++ b/src/video_core/texture_cache/util.cpp
@@ -896,11 +896,11 @@ void ConvertImage(std::span<const u8> input, const ImageInfo& info, std::span<u8
896 ASSERT(copy.buffer_row_length == Common::AlignUp(mip_size.width, tile_size.width)); 896 ASSERT(copy.buffer_row_length == Common::AlignUp(mip_size.width, tile_size.width));
897 ASSERT(copy.buffer_image_height == Common::AlignUp(mip_size.height, tile_size.height)); 897 ASSERT(copy.buffer_image_height == Common::AlignUp(mip_size.height, tile_size.height));
898 if (IsPixelFormatASTC(info.format)) { 898 if (IsPixelFormatASTC(info.format)) {
899 ASSERT(copy.image_extent.depth == 1); 899 Tegra::Texture::ASTC::Decompress(
900 Tegra::Texture::ASTC::Decompress(input.subspan(copy.buffer_offset), 900 input.subspan(copy.buffer_offset), copy.image_extent.width,
901 copy.image_extent.width, copy.image_extent.height, 901 copy.image_extent.height,
902 copy.image_subresource.num_layers, tile_size.width, 902 copy.image_subresource.num_layers * copy.image_extent.depth, tile_size.width,
903 tile_size.height, output.subspan(output_offset)); 903 tile_size.height, output.subspan(output_offset));
904 } else { 904 } else {
905 DecompressBC4(input.subspan(copy.buffer_offset), copy.image_extent, 905 DecompressBC4(input.subspan(copy.buffer_offset), copy.image_extent,
906 output.subspan(output_offset)); 906 output.subspan(output_offset));
diff --git a/src/yuzu/applets/qt_amiibo_settings.cpp b/src/yuzu/applets/qt_amiibo_settings.cpp
index 4559df5b1..4988fcc83 100644
--- a/src/yuzu/applets/qt_amiibo_settings.cpp
+++ b/src/yuzu/applets/qt_amiibo_settings.cpp
@@ -8,7 +8,7 @@
8 8
9#include "common/assert.h" 9#include "common/assert.h"
10#include "common/string_util.h" 10#include "common/string_util.h"
11#include "core/hle/service/nfp/nfp_device.h" 11#include "core/hle/service/nfc/common/device.h"
12#include "core/hle/service/nfp/nfp_result.h" 12#include "core/hle/service/nfp/nfp_result.h"
13#include "input_common/drivers/virtual_amiibo.h" 13#include "input_common/drivers/virtual_amiibo.h"
14#include "input_common/main.h" 14#include "input_common/main.h"
@@ -22,7 +22,7 @@
22QtAmiiboSettingsDialog::QtAmiiboSettingsDialog(QWidget* parent, 22QtAmiiboSettingsDialog::QtAmiiboSettingsDialog(QWidget* parent,
23 Core::Frontend::CabinetParameters parameters_, 23 Core::Frontend::CabinetParameters parameters_,
24 InputCommon::InputSubsystem* input_subsystem_, 24 InputCommon::InputSubsystem* input_subsystem_,
25 std::shared_ptr<Service::NFP::NfpDevice> nfp_device_) 25 std::shared_ptr<Service::NFC::NfcDevice> nfp_device_)
26 : QDialog(parent), ui(std::make_unique<Ui::QtAmiiboSettingsDialog>()), 26 : QDialog(parent), ui(std::make_unique<Ui::QtAmiiboSettingsDialog>()),
27 input_subsystem{input_subsystem_}, nfp_device{std::move(nfp_device_)}, 27 input_subsystem{input_subsystem_}, nfp_device{std::move(nfp_device_)},
28 parameters(std::move(parameters_)) { 28 parameters(std::move(parameters_)) {
@@ -52,11 +52,11 @@ void QtAmiiboSettingsDialog::LoadInfo() {
52 return; 52 return;
53 } 53 }
54 54
55 if (nfp_device->GetCurrentState() != Service::NFP::DeviceState::TagFound && 55 if (nfp_device->GetCurrentState() != Service::NFC::DeviceState::TagFound &&
56 nfp_device->GetCurrentState() != Service::NFP::DeviceState::TagMounted) { 56 nfp_device->GetCurrentState() != Service::NFC::DeviceState::TagMounted) {
57 return; 57 return;
58 } 58 }
59 nfp_device->Mount(Service::NFP::MountTarget::All); 59 nfp_device->Mount(Service::NFP::ModelType::Amiibo, Service::NFP::MountTarget::All);
60 60
61 LoadAmiiboInfo(); 61 LoadAmiiboInfo();
62 LoadAmiiboData(); 62 LoadAmiiboData();
@@ -261,7 +261,7 @@ void QtAmiiboSettings::Close() const {
261void QtAmiiboSettings::ShowCabinetApplet( 261void QtAmiiboSettings::ShowCabinetApplet(
262 const Core::Frontend::CabinetCallback& callback_, 262 const Core::Frontend::CabinetCallback& callback_,
263 const Core::Frontend::CabinetParameters& parameters, 263 const Core::Frontend::CabinetParameters& parameters,
264 std::shared_ptr<Service::NFP::NfpDevice> nfp_device) const { 264 std::shared_ptr<Service::NFC::NfcDevice> nfp_device) const {
265 callback = std::move(callback_); 265 callback = std::move(callback_);
266 emit MainWindowShowAmiiboSettings(parameters, nfp_device); 266 emit MainWindowShowAmiiboSettings(parameters, nfp_device);
267} 267}
diff --git a/src/yuzu/applets/qt_amiibo_settings.h b/src/yuzu/applets/qt_amiibo_settings.h
index bc389a33f..ee66a0255 100644
--- a/src/yuzu/applets/qt_amiibo_settings.h
+++ b/src/yuzu/applets/qt_amiibo_settings.h
@@ -23,9 +23,9 @@ namespace Ui {
23class QtAmiiboSettingsDialog; 23class QtAmiiboSettingsDialog;
24} 24}
25 25
26namespace Service::NFP { 26namespace Service::NFC {
27class NfpDevice; 27class NfcDevice;
28} // namespace Service::NFP 28} // namespace Service::NFC
29 29
30class QtAmiiboSettingsDialog final : public QDialog { 30class QtAmiiboSettingsDialog final : public QDialog {
31 Q_OBJECT 31 Q_OBJECT
@@ -33,7 +33,7 @@ class QtAmiiboSettingsDialog final : public QDialog {
33public: 33public:
34 explicit QtAmiiboSettingsDialog(QWidget* parent, Core::Frontend::CabinetParameters parameters_, 34 explicit QtAmiiboSettingsDialog(QWidget* parent, Core::Frontend::CabinetParameters parameters_,
35 InputCommon::InputSubsystem* input_subsystem_, 35 InputCommon::InputSubsystem* input_subsystem_,
36 std::shared_ptr<Service::NFP::NfpDevice> nfp_device_); 36 std::shared_ptr<Service::NFC::NfcDevice> nfp_device_);
37 ~QtAmiiboSettingsDialog() override; 37 ~QtAmiiboSettingsDialog() override;
38 38
39 int exec() override; 39 int exec() override;
@@ -52,7 +52,7 @@ private:
52 std::unique_ptr<Ui::QtAmiiboSettingsDialog> ui; 52 std::unique_ptr<Ui::QtAmiiboSettingsDialog> ui;
53 53
54 InputCommon::InputSubsystem* input_subsystem; 54 InputCommon::InputSubsystem* input_subsystem;
55 std::shared_ptr<Service::NFP::NfpDevice> nfp_device; 55 std::shared_ptr<Service::NFC::NfcDevice> nfp_device;
56 56
57 // Parameters sent in from the backend HLE applet. 57 // Parameters sent in from the backend HLE applet.
58 Core::Frontend::CabinetParameters parameters; 58 Core::Frontend::CabinetParameters parameters;
@@ -71,11 +71,11 @@ public:
71 void Close() const override; 71 void Close() const override;
72 void ShowCabinetApplet(const Core::Frontend::CabinetCallback& callback_, 72 void ShowCabinetApplet(const Core::Frontend::CabinetCallback& callback_,
73 const Core::Frontend::CabinetParameters& parameters, 73 const Core::Frontend::CabinetParameters& parameters,
74 std::shared_ptr<Service::NFP::NfpDevice> nfp_device) const override; 74 std::shared_ptr<Service::NFC::NfcDevice> nfp_device) const override;
75 75
76signals: 76signals:
77 void MainWindowShowAmiiboSettings(const Core::Frontend::CabinetParameters& parameters, 77 void MainWindowShowAmiiboSettings(const Core::Frontend::CabinetParameters& parameters,
78 std::shared_ptr<Service::NFP::NfpDevice> nfp_device) const; 78 std::shared_ptr<Service::NFC::NfcDevice> nfp_device) const;
79 void MainWindowRequestExit() const; 79 void MainWindowRequestExit() const;
80 80
81private: 81private:
diff --git a/src/yuzu/bootmanager.h b/src/yuzu/bootmanager.h
index 4276be82b..b7b9d4141 100644
--- a/src/yuzu/bootmanager.h
+++ b/src/yuzu/bootmanager.h
@@ -8,7 +8,6 @@
8#include <cstddef> 8#include <cstddef>
9#include <memory> 9#include <memory>
10#include <mutex> 10#include <mutex>
11#include <stop_token>
12#include <utility> 11#include <utility>
13#include <vector> 12#include <vector>
14 13
diff --git a/src/yuzu/configuration/config.cpp b/src/yuzu/configuration/config.cpp
index a85eb4687..a49d12266 100644
--- a/src/yuzu/configuration/config.cpp
+++ b/src/yuzu/configuration/config.cpp
@@ -710,6 +710,7 @@ void Config::ReadRendererValues() {
710 ReadGlobalSetting(Settings::values.nvdec_emulation); 710 ReadGlobalSetting(Settings::values.nvdec_emulation);
711 ReadGlobalSetting(Settings::values.accelerate_astc); 711 ReadGlobalSetting(Settings::values.accelerate_astc);
712 ReadGlobalSetting(Settings::values.async_astc); 712 ReadGlobalSetting(Settings::values.async_astc);
713 ReadGlobalSetting(Settings::values.use_reactive_flushing);
713 ReadGlobalSetting(Settings::values.shader_backend); 714 ReadGlobalSetting(Settings::values.shader_backend);
714 ReadGlobalSetting(Settings::values.use_asynchronous_shaders); 715 ReadGlobalSetting(Settings::values.use_asynchronous_shaders);
715 ReadGlobalSetting(Settings::values.use_fast_gpu_time); 716 ReadGlobalSetting(Settings::values.use_fast_gpu_time);
@@ -1355,6 +1356,7 @@ void Config::SaveRendererValues() {
1355 Settings::values.nvdec_emulation.UsingGlobal()); 1356 Settings::values.nvdec_emulation.UsingGlobal());
1356 WriteGlobalSetting(Settings::values.accelerate_astc); 1357 WriteGlobalSetting(Settings::values.accelerate_astc);
1357 WriteGlobalSetting(Settings::values.async_astc); 1358 WriteGlobalSetting(Settings::values.async_astc);
1359 WriteGlobalSetting(Settings::values.use_reactive_flushing);
1358 WriteSetting(QString::fromStdString(Settings::values.shader_backend.GetLabel()), 1360 WriteSetting(QString::fromStdString(Settings::values.shader_backend.GetLabel()),
1359 static_cast<u32>(Settings::values.shader_backend.GetValue(global)), 1361 static_cast<u32>(Settings::values.shader_backend.GetValue(global)),
1360 static_cast<u32>(Settings::values.shader_backend.GetDefault()), 1362 static_cast<u32>(Settings::values.shader_backend.GetDefault()),
diff --git a/src/yuzu/configuration/configure_graphics_advanced.cpp b/src/yuzu/configuration/configure_graphics_advanced.cpp
index 005b022ca..627ed8b17 100644
--- a/src/yuzu/configuration/configure_graphics_advanced.cpp
+++ b/src/yuzu/configuration/configure_graphics_advanced.cpp
@@ -21,6 +21,7 @@ ConfigureGraphicsAdvanced::~ConfigureGraphicsAdvanced() = default;
21 21
22void ConfigureGraphicsAdvanced::SetConfiguration() { 22void ConfigureGraphicsAdvanced::SetConfiguration() {
23 const bool runtime_lock = !system.IsPoweredOn(); 23 const bool runtime_lock = !system.IsPoweredOn();
24 ui->use_reactive_flushing->setEnabled(runtime_lock);
24 ui->async_present->setEnabled(runtime_lock); 25 ui->async_present->setEnabled(runtime_lock);
25 ui->renderer_force_max_clock->setEnabled(runtime_lock); 26 ui->renderer_force_max_clock->setEnabled(runtime_lock);
26 ui->async_astc->setEnabled(runtime_lock); 27 ui->async_astc->setEnabled(runtime_lock);
@@ -29,6 +30,7 @@ void ConfigureGraphicsAdvanced::SetConfiguration() {
29 30
30 ui->async_present->setChecked(Settings::values.async_presentation.GetValue()); 31 ui->async_present->setChecked(Settings::values.async_presentation.GetValue());
31 ui->renderer_force_max_clock->setChecked(Settings::values.renderer_force_max_clock.GetValue()); 32 ui->renderer_force_max_clock->setChecked(Settings::values.renderer_force_max_clock.GetValue());
33 ui->use_reactive_flushing->setChecked(Settings::values.use_reactive_flushing.GetValue());
32 ui->async_astc->setChecked(Settings::values.async_astc.GetValue()); 34 ui->async_astc->setChecked(Settings::values.async_astc.GetValue());
33 ui->use_asynchronous_shaders->setChecked(Settings::values.use_asynchronous_shaders.GetValue()); 35 ui->use_asynchronous_shaders->setChecked(Settings::values.use_asynchronous_shaders.GetValue());
34 ui->use_fast_gpu_time->setChecked(Settings::values.use_fast_gpu_time.GetValue()); 36 ui->use_fast_gpu_time->setChecked(Settings::values.use_fast_gpu_time.GetValue());
@@ -60,6 +62,8 @@ void ConfigureGraphicsAdvanced::ApplyConfiguration() {
60 renderer_force_max_clock); 62 renderer_force_max_clock);
61 ConfigurationShared::ApplyPerGameSetting(&Settings::values.max_anisotropy, 63 ConfigurationShared::ApplyPerGameSetting(&Settings::values.max_anisotropy,
62 ui->anisotropic_filtering_combobox); 64 ui->anisotropic_filtering_combobox);
65 ConfigurationShared::ApplyPerGameSetting(&Settings::values.use_reactive_flushing,
66 ui->use_reactive_flushing, use_reactive_flushing);
63 ConfigurationShared::ApplyPerGameSetting(&Settings::values.async_astc, ui->async_astc, 67 ConfigurationShared::ApplyPerGameSetting(&Settings::values.async_astc, ui->async_astc,
64 async_astc); 68 async_astc);
65 ConfigurationShared::ApplyPerGameSetting(&Settings::values.use_asynchronous_shaders, 69 ConfigurationShared::ApplyPerGameSetting(&Settings::values.use_asynchronous_shaders,
@@ -91,6 +95,7 @@ void ConfigureGraphicsAdvanced::SetupPerGameUI() {
91 ui->async_present->setEnabled(Settings::values.async_presentation.UsingGlobal()); 95 ui->async_present->setEnabled(Settings::values.async_presentation.UsingGlobal());
92 ui->renderer_force_max_clock->setEnabled( 96 ui->renderer_force_max_clock->setEnabled(
93 Settings::values.renderer_force_max_clock.UsingGlobal()); 97 Settings::values.renderer_force_max_clock.UsingGlobal());
98 ui->use_reactive_flushing->setEnabled(Settings::values.use_reactive_flushing.UsingGlobal());
94 ui->async_astc->setEnabled(Settings::values.async_astc.UsingGlobal()); 99 ui->async_astc->setEnabled(Settings::values.async_astc.UsingGlobal());
95 ui->use_asynchronous_shaders->setEnabled( 100 ui->use_asynchronous_shaders->setEnabled(
96 Settings::values.use_asynchronous_shaders.UsingGlobal()); 101 Settings::values.use_asynchronous_shaders.UsingGlobal());
@@ -108,6 +113,8 @@ void ConfigureGraphicsAdvanced::SetupPerGameUI() {
108 ConfigurationShared::SetColoredTristate(ui->renderer_force_max_clock, 113 ConfigurationShared::SetColoredTristate(ui->renderer_force_max_clock,
109 Settings::values.renderer_force_max_clock, 114 Settings::values.renderer_force_max_clock,
110 renderer_force_max_clock); 115 renderer_force_max_clock);
116 ConfigurationShared::SetColoredTristate(
117 ui->use_reactive_flushing, Settings::values.use_reactive_flushing, use_reactive_flushing);
111 ConfigurationShared::SetColoredTristate(ui->async_astc, Settings::values.async_astc, 118 ConfigurationShared::SetColoredTristate(ui->async_astc, Settings::values.async_astc,
112 async_astc); 119 async_astc);
113 ConfigurationShared::SetColoredTristate(ui->use_asynchronous_shaders, 120 ConfigurationShared::SetColoredTristate(ui->use_asynchronous_shaders,
diff --git a/src/yuzu/configuration/configure_graphics_advanced.h b/src/yuzu/configuration/configure_graphics_advanced.h
index ff5060957..ae3c10946 100644
--- a/src/yuzu/configuration/configure_graphics_advanced.h
+++ b/src/yuzu/configuration/configure_graphics_advanced.h
@@ -40,6 +40,7 @@ private:
40 ConfigurationShared::CheckState renderer_force_max_clock; 40 ConfigurationShared::CheckState renderer_force_max_clock;
41 ConfigurationShared::CheckState use_vsync; 41 ConfigurationShared::CheckState use_vsync;
42 ConfigurationShared::CheckState async_astc; 42 ConfigurationShared::CheckState async_astc;
43 ConfigurationShared::CheckState use_reactive_flushing;
43 ConfigurationShared::CheckState use_asynchronous_shaders; 44 ConfigurationShared::CheckState use_asynchronous_shaders;
44 ConfigurationShared::CheckState use_fast_gpu_time; 45 ConfigurationShared::CheckState use_fast_gpu_time;
45 ConfigurationShared::CheckState use_vulkan_driver_pipeline_cache; 46 ConfigurationShared::CheckState use_vulkan_driver_pipeline_cache;
diff --git a/src/yuzu/configuration/configure_graphics_advanced.ui b/src/yuzu/configuration/configure_graphics_advanced.ui
index d073fe9b1..9d8cbea09 100644
--- a/src/yuzu/configuration/configure_graphics_advanced.ui
+++ b/src/yuzu/configuration/configure_graphics_advanced.ui
@@ -97,6 +97,16 @@
97 </widget> 97 </widget>
98 </item> 98 </item>
99 <item> 99 <item>
100 <widget class="QCheckBox" name="use_reactive_flushing">
101 <property name="toolTip">
102 <string>Uses reactive flushing instead of predictive flushing. Allowing a more accurate syncing of memory.</string>
103 </property>
104 <property name="text">
105 <string>Enable Reactive Flushing</string>
106 </property>
107 </widget>
108 </item>
109 <item>
100 <widget class="QCheckBox" name="use_asynchronous_shaders"> 110 <widget class="QCheckBox" name="use_asynchronous_shaders">
101 <property name="toolTip"> 111 <property name="toolTip">
102 <string>Enables asynchronous shader compilation, which may reduce shader stutter. This feature is experimental.</string> 112 <string>Enables asynchronous shader compilation, which may reduce shader stutter. This feature is experimental.</string>
diff --git a/src/yuzu/configuration/configure_input_player.cpp b/src/yuzu/configuration/configure_input_player.cpp
index 561a08dc5..2c2e7e47b 100644
--- a/src/yuzu/configuration/configure_input_player.cpp
+++ b/src/yuzu/configuration/configure_input_player.cpp
@@ -479,6 +479,9 @@ ConfigureInputPlayer::ConfigureInputPlayer(QWidget* parent, std::size_t player_i
479 param.Set("threshold", new_threshold / 1000.0f); 479 param.Set("threshold", new_threshold / 1000.0f);
480 emulated_controller->SetMotionParam(motion_id, param); 480 emulated_controller->SetMotionParam(motion_id, param);
481 }); 481 });
482 context_menu.addAction(tr("Calibrate sensor"), [&] {
483 emulated_controller->StartMotionCalibration();
484 });
482 } 485 }
483 context_menu.exec(motion_map[motion_id]->mapToGlobal(menu_location)); 486 context_menu.exec(motion_map[motion_id]->mapToGlobal(menu_location));
484 }); 487 });
diff --git a/src/yuzu/configuration/configure_input_player_widget.cpp b/src/yuzu/configuration/configure_input_player_widget.cpp
index fe1ee2289..a188eef92 100644
--- a/src/yuzu/configuration/configure_input_player_widget.cpp
+++ b/src/yuzu/configuration/configure_input_player_widget.cpp
@@ -582,9 +582,9 @@ void PlayerControlPreview::DrawDualController(QPainter& p, const QPointF center)
582 using namespace Settings::NativeMotion; 582 using namespace Settings::NativeMotion;
583 p.setPen(colors.outline); 583 p.setPen(colors.outline);
584 p.setBrush(colors.transparent); 584 p.setBrush(colors.transparent);
585 Draw3dCube(p, center + QPointF(-180, -5), 585 Draw3dCube(p, center + QPointF(-180, 90),
586 motion_values[Settings::NativeMotion::MotionLeft].euler, 20.0f); 586 motion_values[Settings::NativeMotion::MotionLeft].euler, 20.0f);
587 Draw3dCube(p, center + QPointF(180, -5), 587 Draw3dCube(p, center + QPointF(180, 90),
588 motion_values[Settings::NativeMotion::MotionRight].euler, 20.0f); 588 motion_values[Settings::NativeMotion::MotionRight].euler, 20.0f);
589 } 589 }
590 590
@@ -2926,14 +2926,14 @@ void PlayerControlPreview::DrawArrow(QPainter& p, const QPointF center, const Di
2926void PlayerControlPreview::Draw3dCube(QPainter& p, QPointF center, const Common::Vec3f& euler, 2926void PlayerControlPreview::Draw3dCube(QPainter& p, QPointF center, const Common::Vec3f& euler,
2927 float size) { 2927 float size) {
2928 std::array<Common::Vec3f, 8> cube{ 2928 std::array<Common::Vec3f, 8> cube{
2929 Common::Vec3f{-1, -1, -1}, 2929 Common::Vec3f{-0.7f, -1, -0.5f},
2930 {-1, 1, -1}, 2930 {-0.7f, 1, -0.5f},
2931 {1, 1, -1}, 2931 {0.7f, 1, -0.5f},
2932 {1, -1, -1}, 2932 {0.7f, -1, -0.5f},
2933 {-1, -1, 1}, 2933 {-0.7f, -1, 0.5f},
2934 {-1, 1, 1}, 2934 {-0.7f, 1, 0.5f},
2935 {1, 1, 1}, 2935 {0.7f, 1, 0.5f},
2936 {1, -1, 1}, 2936 {0.7f, -1, 0.5f},
2937 }; 2937 };
2938 2938
2939 for (Common::Vec3f& point : cube) { 2939 for (Common::Vec3f& point : cube) {
diff --git a/src/yuzu/main.cpp b/src/yuzu/main.cpp
index ba9eece1d..d932e33a7 100644
--- a/src/yuzu/main.cpp
+++ b/src/yuzu/main.cpp
@@ -571,8 +571,8 @@ void GMainWindow::RegisterMetaTypes() {
571 571
572 // Cabinet Applet 572 // Cabinet Applet
573 qRegisterMetaType<Core::Frontend::CabinetParameters>("Core::Frontend::CabinetParameters"); 573 qRegisterMetaType<Core::Frontend::CabinetParameters>("Core::Frontend::CabinetParameters");
574 qRegisterMetaType<std::shared_ptr<Service::NFP::NfpDevice>>( 574 qRegisterMetaType<std::shared_ptr<Service::NFC::NfcDevice>>(
575 "std::shared_ptr<Service::NFP::NfpDevice>"); 575 "std::shared_ptr<Service::NFC::NfcDevice>");
576 576
577 // Controller Applet 577 // Controller Applet
578 qRegisterMetaType<Core::Frontend::ControllerParameters>("Core::Frontend::ControllerParameters"); 578 qRegisterMetaType<Core::Frontend::ControllerParameters>("Core::Frontend::ControllerParameters");
@@ -600,7 +600,7 @@ void GMainWindow::RegisterMetaTypes() {
600} 600}
601 601
602void GMainWindow::AmiiboSettingsShowDialog(const Core::Frontend::CabinetParameters& parameters, 602void GMainWindow::AmiiboSettingsShowDialog(const Core::Frontend::CabinetParameters& parameters,
603 std::shared_ptr<Service::NFP::NfpDevice> nfp_device) { 603 std::shared_ptr<Service::NFC::NfcDevice> nfp_device) {
604 cabinet_applet = 604 cabinet_applet =
605 new QtAmiiboSettingsDialog(this, parameters, input_subsystem.get(), nfp_device); 605 new QtAmiiboSettingsDialog(this, parameters, input_subsystem.get(), nfp_device);
606 SCOPE_EXIT({ 606 SCOPE_EXIT({
diff --git a/src/yuzu/main.h b/src/yuzu/main.h
index 3bbc31ada..7b23f2a59 100644
--- a/src/yuzu/main.h
+++ b/src/yuzu/main.h
@@ -93,9 +93,9 @@ enum class SwkbdReplyType : u32;
93enum class WebExitReason : u32; 93enum class WebExitReason : u32;
94} // namespace Service::AM::Applets 94} // namespace Service::AM::Applets
95 95
96namespace Service::NFP { 96namespace Service::NFC {
97class NfpDevice; 97class NfcDevice;
98} // namespace Service::NFP 98} // namespace Service::NFC
99 99
100namespace Ui { 100namespace Ui {
101class MainWindow; 101class MainWindow;
@@ -188,7 +188,7 @@ public slots:
188 void OnExit(); 188 void OnExit();
189 void OnSaveConfig(); 189 void OnSaveConfig();
190 void AmiiboSettingsShowDialog(const Core::Frontend::CabinetParameters& parameters, 190 void AmiiboSettingsShowDialog(const Core::Frontend::CabinetParameters& parameters,
191 std::shared_ptr<Service::NFP::NfpDevice> nfp_device); 191 std::shared_ptr<Service::NFC::NfcDevice> nfp_device);
192 void AmiiboSettingsRequestExit(); 192 void AmiiboSettingsRequestExit();
193 void ControllerSelectorReconfigureControllers( 193 void ControllerSelectorReconfigureControllers(
194 const Core::Frontend::ControllerParameters& parameters); 194 const Core::Frontend::ControllerParameters& parameters);
diff --git a/src/yuzu/qt_common.cpp b/src/yuzu/qt_common.cpp
index 5ac9fe310..5d0fd7674 100644
--- a/src/yuzu/qt_common.cpp
+++ b/src/yuzu/qt_common.cpp
@@ -8,7 +8,7 @@
8#include "core/frontend/emu_window.h" 8#include "core/frontend/emu_window.h"
9#include "yuzu/qt_common.h" 9#include "yuzu/qt_common.h"
10 10
11#ifdef __linux__ 11#if !defined(WIN32) && !defined(__APPLE__)
12#include <qpa/qplatformnativeinterface.h> 12#include <qpa/qplatformnativeinterface.h>
13#endif 13#endif
14 14
diff --git a/src/yuzu_cmd/config.cpp b/src/yuzu_cmd/config.cpp
index a6418e693..abe7092fc 100644
--- a/src/yuzu_cmd/config.cpp
+++ b/src/yuzu_cmd/config.cpp
@@ -312,6 +312,7 @@ void Config::ReadValues() {
312 ReadSetting("Renderer", Settings::values.use_asynchronous_gpu_emulation); 312 ReadSetting("Renderer", Settings::values.use_asynchronous_gpu_emulation);
313 ReadSetting("Renderer", Settings::values.vsync_mode); 313 ReadSetting("Renderer", Settings::values.vsync_mode);
314 ReadSetting("Renderer", Settings::values.shader_backend); 314 ReadSetting("Renderer", Settings::values.shader_backend);
315 ReadSetting("Renderer", Settings::values.use_reactive_flushing);
315 ReadSetting("Renderer", Settings::values.use_asynchronous_shaders); 316 ReadSetting("Renderer", Settings::values.use_asynchronous_shaders);
316 ReadSetting("Renderer", Settings::values.nvdec_emulation); 317 ReadSetting("Renderer", Settings::values.nvdec_emulation);
317 ReadSetting("Renderer", Settings::values.accelerate_astc); 318 ReadSetting("Renderer", Settings::values.accelerate_astc);
diff --git a/src/yuzu_cmd/default_ini.h b/src/yuzu_cmd/default_ini.h
index 086ed4cfa..5e7c3ac04 100644
--- a/src/yuzu_cmd/default_ini.h
+++ b/src/yuzu_cmd/default_ini.h
@@ -340,6 +340,10 @@ use_vsync =
340# 0: GLSL, 1 (default): GLASM, 2: SPIR-V 340# 0: GLSL, 1 (default): GLASM, 2: SPIR-V
341shader_backend = 341shader_backend =
342 342
343# Uses reactive flushing instead of predictive flushing. Allowing a more accurate syncing of memory.
344# 0: Off, 1 (default): On
345use_reactive_flushing =
346
343# Whether to allow asynchronous shader building. 347# Whether to allow asynchronous shader building.
344# 0 (default): Off, 1: On 348# 0 (default): Off, 1: On
345use_asynchronous_shaders = 349use_asynchronous_shaders =