Compare commits

..

51 Commits

Author SHA1 Message Date
05d0f10009 Android 195 2024-01-17 01:00:41 +00:00
ab7feed34d Merge yuzu-emu#12688 2024-01-17 01:00:41 +00:00
ef50fed8f7 Merge yuzu-emu#12644 2024-01-17 01:00:41 +00:00
659a6b1f1d Merge yuzu-emu#12579 2024-01-17 01:00:41 +00:00
2c29c2b8dd Merge pull request #12686 from szepeviktor/typos3
Fix more typos
2024-01-15 23:26:08 -05:00
16abda59be Fix typos in master 2024-01-16 00:09:25 +00:00
90ab89a0b0 Merge remote-tracking branch 'origin/master' into typos3 2024-01-16 00:09:00 +00:00
6531ad56a6 Fix typos in arrays.xml 2024-01-15 23:39:45 +00:00
e8671ed04e Fix one more typo 2024-01-15 23:34:11 +00:00
2044ae6b3a Fix more typos 2024-01-15 23:26:53 +00:00
c683ec2bcb Merge pull request #12681 from t895/stick-toggles
android: Fix overlay toggle ordering
2024-01-15 13:52:53 -05:00
2e4e33156e Merge pull request #12680 from t895/format-mainline
ci: Remove format step from mainline builds
2024-01-15 13:52:48 -05:00
04f4eeaca2 Merge pull request #12677 from GPUCode/whyy-modders
core: Support multiple modules per patcher
2024-01-15 13:52:38 -05:00
2e4b32204c Merge pull request #12665 from german77/proof
service: acc: Only save profiles when profiles have changed
2024-01-15 13:52:33 -05:00
34db13486a Merge pull request #12659 from liamwhite/audio-memory
audio: fetch process object from handle table
2024-01-15 13:52:01 -05:00
c6c6bb4041 Merge pull request #12652 from liamwhite/huge-pile-of-spirv-spaghetti
shader_recompiler: emulate 8-bit and 16-bit storage writes with cas loop
2024-01-15 13:51:36 -05:00
a2ffb419c9 Merge pull request #12612 from liamwhite/fs-pid
fsp-srv: use program registry for SetCurrentProcess
2024-01-15 13:51:14 -05:00
0127cec371 Merge pull request #12611 from liamwhite/resource-management-is-hard
kernel: fix resource management issues
2024-01-15 13:50:58 -05:00
db3a6075f5 Merge pull request #12610 from liamwhite/reply-and-dont-receive
server_manager: respond to session close correctly
2024-01-15 13:50:43 -05:00
8876a15227 android: Fix overlay toggle ordering 2024-01-15 12:41:49 -05:00
954eb40237 ci: Remove format step from mainline builds 2024-01-15 10:30:57 -05:00
d4acdac168 core: Support multiple modules per patcher 2024-01-15 00:46:05 +02:00
817c7c445d Merge pull request #12667 from t895/version-info
android: Show version name instead of build hash in about fragment
2024-01-13 20:23:12 -05:00
da714a362b Merge pull request #12666 from t895/ktlint-yuzu-verify
android: Move ktlintCheck to yuzu-verify
2024-01-13 20:23:02 -05:00
7b3941e5d4 android: Show version name instead of git hash in the about fragment 2024-01-13 18:12:19 -05:00
15d8a40529 android: Clean up git commands in build.gradle 2024-01-13 18:06:33 -05:00
cdeaca73c4 android: Move ktlintCheck to yuzu-verify 2024-01-13 17:41:01 -05:00
bee22540a1 service: acc: Only save profiles when profiles have changed 2024-01-13 14:28:29 -06:00
76880b84f9 loader: fix homebrew nro registration 2024-01-13 13:48:56 -05:00
2f0b57ca13 kernel: optimize page free on shutdown 2024-01-12 19:19:07 -05:00
f90a022d3a kernel: fix debugger and process list lifetime 2024-01-12 18:31:33 -05:00
f2fed21c11 kernel: fix page leak on process termination 2024-01-12 18:31:33 -05:00
d940974789 audio: fetch process object from handle table 2024-01-12 10:03:16 -05:00
f7a3c135e2 Merge pull request #12605 from german77/abstract
service: hid: Create abstracted pad structure
2024-01-12 10:02:13 -05:00
fcb0dff67c Merge pull request #12642 from t895/adapter-refactor
android: Refactor list adapters
2024-01-12 10:01:54 -05:00
b5dac5f525 service: hid: Create abstracted pad structure 2024-01-11 19:35:04 -06:00
a4d90a9a64 Merge pull request #12653 from liamwhite/once-more
ci: fix file mode check in format script
2024-01-11 19:58:41 -05:00
84787a2ada ci: fix file mode check in format script 2024-01-11 18:57:07 -05:00
2a0d707ce1 shader_recompiler: emulate 8-bit and 16-bit storage writes with cas loop 2024-01-11 16:50:59 -05:00
aae9eea532 fsp-srv: use program registry for SetCurrentProcess 2024-01-11 11:28:52 -05:00
d3ba6b334b android: Fix added driver path
While this didn't break anything, the extra separator was unnecessary
2024-01-10 23:14:04 -05:00
dac8c4ce4d android: Add button to use global driver value 2024-01-10 23:14:04 -05:00
9e974d4c7e android: Reload driver data on importing user data 2024-01-10 23:14:04 -05:00
6bfc3c530c android: Rework driver fragment
Applies settings upon selection and uses a new Driver model to represent the information in-view. Also switches from an async diff list to a plain one.
2024-01-10 23:14:04 -05:00
93239f191a android: Refactor DriverAdapter to use AbstractSingleSelectionList 2024-01-10 23:14:04 -05:00
b17db2b462 android: Create generic single selection list adapter 2024-01-10 23:14:04 -05:00
9130366a58 android: Refactor recycler view adapters to use AbstractListAdapter 2024-01-10 23:14:04 -05:00
ad0066a6b6 android: Create generic list adapter for basic lists
Simplifies basic setup for lists
2024-01-10 23:14:04 -05:00
78c323c4eb android: Refactor async diff adapters to use AbstractDiffAdapter 2024-01-10 23:14:04 -05:00
51ad2d10de android: Create generic adapter and viewholder
Eliminates repeated code associated with every async differ list
2024-01-10 23:14:04 -05:00
200b371d13 server_manager: respond to session close correctly 2024-01-07 21:33:24 -05:00
156 changed files with 4020 additions and 548 deletions

View File

@ -25,10 +25,13 @@ for f in $FILES_TO_LINT; do
"$CLANG_FORMAT" -i "$f"
done
DIFF=$(git diff)
DIFF=$(git -c core.fileMode=false diff)
if [ ! -z "$DIFF" ]; then
echo "!!! Not compliant to coding style, here is the fix:"
echo "$DIFF"
exit 1
fi
cd src/android
./gradlew ktlintCheck

View File

@ -8,17 +8,7 @@ variables:
DisplayVersion: $[counter(variables['DisplayPrefix'], 1)]
stages:
- stage: format
displayName: 'format'
jobs:
- job: format
displayName: 'clang'
pool:
vmImage: ubuntu-latest
steps:
- template: ./templates/format-check.yml
- stage: build
dependsOn: format
displayName: 'build'
jobs:
- job: build

View File

@ -13,13 +13,15 @@ jobs:
format:
name: 'verify format'
runs-on: ubuntu-latest
container:
image: yuzuemu/build-environments:linux-clang-format
options: -u 1001
steps:
- uses: actions/checkout@v3
with:
submodules: false
- name: set up JDK 17
uses: actions/setup-java@v3
with:
java-version: '17'
distribution: 'temurin'
- name: 'Verify Formatting'
run: bash -ex ./.ci/scripts/format/script.sh
build:

View File

@ -1,10 +1,8 @@
| Pull Request | Commit | Title | Author | Merged? |
|----|----|----|----|----|
| [12579](https://github.com/yuzu-emu/yuzu-android//pull/12579) | [`66ae60a9e`](https://github.com/yuzu-emu/yuzu-android//pull/12579/files) | Core: Implement Device Mapping & GPU SMMU | [FernandoS27](https://github.com/FernandoS27/) | Yes |
| [12610](https://github.com/yuzu-emu/yuzu-android//pull/12610) | [`200b371d1`](https://github.com/yuzu-emu/yuzu-android//pull/12610/files) | server_manager: respond to session close correctly | [liamwhite](https://github.com/liamwhite/) | Yes |
| [12611](https://github.com/yuzu-emu/yuzu-android//pull/12611) | [`642a29923`](https://github.com/yuzu-emu/yuzu-android//pull/12611/files) | kernel: fix resource management issues | [liamwhite](https://github.com/liamwhite/) | Yes |
| [12612](https://github.com/yuzu-emu/yuzu-android//pull/12612) | [`417df3b6e`](https://github.com/yuzu-emu/yuzu-android//pull/12612/files) | fsp-srv: use program registry for SetCurrentProcess | [liamwhite](https://github.com/liamwhite/) | Yes |
| [12642](https://github.com/yuzu-emu/yuzu-android//pull/12642) | [`4037afea1`](https://github.com/yuzu-emu/yuzu-android//pull/12642/files) | android: Refactor list adapters | [t895](https://github.com/t895/) | Yes |
| [12579](https://github.com/yuzu-emu/yuzu-android//pull/12579) | [`93ef41f03`](https://github.com/yuzu-emu/yuzu-android//pull/12579/files) | Core: Implement Device Mapping & GPU SMMU | [FernandoS27](https://github.com/FernandoS27/) | Yes |
| [12644](https://github.com/yuzu-emu/yuzu-android//pull/12644) | [`2044a289f`](https://github.com/yuzu-emu/yuzu-android//pull/12644/files) | shader_recompiler: fix Offset operand usage for non-OpImage*Gather | [liamwhite](https://github.com/liamwhite/) | Yes |
| [12688](https://github.com/yuzu-emu/yuzu-android//pull/12688) | [`e9eb017aa`](https://github.com/yuzu-emu/yuzu-android//pull/12688/files) | renderer_vulkan: recreate swapchain when frame size changes | [liamwhite](https://github.com/liamwhite/) | Yes |
End of merge log. You can find the original README.md below the break.

View File

@ -188,8 +188,15 @@ tasks.create<Delete>("ktlintReset") {
delete(File(buildDir.path + File.separator + "intermediates/ktLint"))
}
val showFormatHelp = {
logger.lifecycle(
"If this check fails, please try running \"gradlew ktlintFormat\" for automatic " +
"codestyle fixes"
)
}
tasks.getByPath("ktlintKotlinScriptCheck").doFirst { showFormatHelp.invoke() }
tasks.getByPath("ktlintMainSourceSetCheck").doFirst { showFormatHelp.invoke() }
tasks.getByPath("loadKtlintReporters").dependsOn("ktlintReset")
tasks.getByPath("preBuild").dependsOn("ktlintCheck")
ktlint {
version.set("0.47.1")
@ -228,71 +235,33 @@ dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.5.0")
}
fun getGitVersion(): String {
var versionName = "0.0"
try {
versionName = ProcessBuilder("git", "describe", "--always", "--long")
fun runGitCommand(command: List<String>): String {
return try {
ProcessBuilder(command)
.directory(project.rootDir)
.redirectOutput(ProcessBuilder.Redirect.PIPE)
.redirectError(ProcessBuilder.Redirect.PIPE)
.start().inputStream.bufferedReader().use { it.readText() }
.trim()
} catch (e: Exception) {
logger.error("Cannot find git")
""
}
}
fun getGitVersion(): String {
val versionName = if (System.getenv("GITHUB_ACTIONS") != null) {
val gitTag = System.getenv("GIT_TAG_NAME") ?: ""
gitTag
} else {
runGitCommand(listOf("git", "describe", "--always", "--long"))
.replace(Regex("(-0)?-[^-]+$"), "")
} catch (e: Exception) {
logger.error("Cannot find git, defaulting to dummy version number")
}
if (System.getenv("GITHUB_ACTIONS") != null) {
val gitTag = System.getenv("GIT_TAG_NAME")
versionName = gitTag ?: versionName
}
return versionName
return versionName.ifEmpty { "0.0" }
}
fun getGitHash(): String {
try {
val processBuilder = ProcessBuilder("git", "rev-parse", "--short", "HEAD")
processBuilder.directory(project.rootDir)
val process = processBuilder.start()
val inputStream = process.inputStream
val errorStream = process.errorStream
process.waitFor()
fun getGitHash(): String =
runGitCommand(listOf("git", "rev-parse", "--short", "HEAD")).ifEmpty { "dummy-hash" }
return if (process.exitValue() == 0) {
inputStream.bufferedReader()
.use { it.readText().trim() } // return the value of gitHash
} else {
val errorMessage = errorStream.bufferedReader().use { it.readText().trim() }
logger.error("Error running git command: $errorMessage")
"dummy-hash" // return a dummy hash value in case of an error
}
} catch (e: Exception) {
logger.error("$e: Cannot find git, defaulting to dummy build hash")
return "dummy-hash" // return a dummy hash value in case of an error
}
}
fun getBranch(): String {
try {
val processBuilder = ProcessBuilder("git", "rev-parse", "--abbrev-ref", "HEAD")
processBuilder.directory(project.rootDir)
val process = processBuilder.start()
val inputStream = process.inputStream
val errorStream = process.errorStream
process.waitFor()
return if (process.exitValue() == 0) {
inputStream.bufferedReader()
.use { it.readText().trim() } // return the value of gitHash
} else {
val errorMessage = errorStream.bufferedReader().use { it.readText().trim() }
logger.error("Error running git command: $errorMessage")
"dummy-hash" // return a dummy hash value in case of an error
}
} catch (e: Exception) {
logger.error("$e: Cannot find git, defaulting to dummy build hash")
return "dummy-hash" // return a dummy hash value in case of an error
}
}
fun getBranch(): String =
runGitCommand(listOf("git", "rev-parse", "--abbrev-ref", "HEAD")).ifEmpty { "dummy-hash" }

View File

@ -76,8 +76,8 @@ class AboutFragment : Fragment() {
binding.root.findNavController().navigate(R.id.action_aboutFragment_to_licensesFragment)
}
binding.textBuildHash.text = BuildConfig.GIT_HASH
binding.buttonBuildHash.setOnClickListener {
binding.textVersionName.text = BuildConfig.VERSION_NAME
binding.textVersionName.setOnClickListener {
val clipBoard =
requireContext().getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clip = ClipData.newPlainText(getString(R.string.build), BuildConfig.GIT_HASH)

View File

@ -104,7 +104,7 @@ object FileUtil {
/**
* Reference: https://stackoverflow.com/questions/42186820/documentfile-is-very-slow
* This function will be faster than DoucmentFile.listFiles
* This function will be faster than DocumentFile.listFiles
* @param uri Directory uri.
* @return CheapDocument lists.
*/

View File

@ -410,8 +410,8 @@ void EmulationSession::OnGamepadConnectEvent([[maybe_unused]] int index) {
jauto handheld = m_system.HIDCore().GetEmulatedController(Core::HID::NpadIdType::Handheld);
if (controller->GetNpadStyleIndex() == Core::HID::NpadStyleIndex::Handheld) {
handheld->SetNpadStyleIndex(Core::HID::NpadStyleIndex::ProController);
controller->SetNpadStyleIndex(Core::HID::NpadStyleIndex::ProController);
handheld->SetNpadStyleIndex(Core::HID::NpadStyleIndex::Fullkey);
controller->SetNpadStyleIndex(Core::HID::NpadStyleIndex::Fullkey);
handheld->Disconnect();
}
}

View File

@ -205,7 +205,7 @@ jboolean Java_org_yuzu_yuzu_1emu_utils_NativeConfig_getIsRuntimeModifiable(JNIEn
jstring jkey) {
auto setting = getSetting<std::string>(env, jkey);
if (setting != nullptr) {
return setting->RuntimeModfiable();
return setting->RuntimeModifiable();
}
return true;
}

View File

@ -147,7 +147,7 @@
android:layout_marginHorizontal="20dp" />
<LinearLayout
android:id="@+id/button_build_hash"
android:id="@+id/button_version_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/selectableItemBackground"
@ -164,7 +164,7 @@
android:textAlignment="viewStart" />
<com.google.android.material.textview.MaterialTextView
android:id="@+id/text_build_hash"
android:id="@+id/text_version_name"
style="@style/TextAppearance.Material3.BodyMedium"
android:layout_width="match_parent"
android:layout_height="wrap_content"

View File

@ -148,7 +148,7 @@
android:layout_marginHorizontal="20dp" />
<LinearLayout
android:id="@+id/button_build_hash"
android:id="@+id/button_version_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingVertical="16dp"
@ -165,7 +165,7 @@
android:text="@string/build" />
<com.google.android.material.textview.MaterialTextView
android:id="@+id/text_build_hash"
android:id="@+id/text_version_name"
style="@style/TextAppearance.Material3.BodyMedium"
android:layout_width="match_parent"
android:layout_height="wrap_content"

View File

@ -29,7 +29,7 @@
<item>@string/language_dutch</item>
<item>@string/language_english</item>
<item>@string/language_french</item>
<item>@string/langauge_german</item>
<item>@string/language_german</item>
<item>@string/language_italian</item>
<item>@string/language_japanese</item>
<item>@string/language_korean</item>
@ -228,10 +228,10 @@
<item>R</item>
<item>ZL</item>
<item>ZR</item>
<item>@string/gamepad_left_stick</item>
<item>@string/gamepad_right_stick</item>
<item>L3</item>
<item>R3</item>
<item>@string/gamepad_left_stick</item>
<item>@string/gamepad_right_stick</item>
<item>@string/gamepad_d_pad</item>
</string-array>

View File

@ -410,7 +410,7 @@
<string name="language_japanese" translatable="false">日本語</string>
<string name="language_english" translatable="false">English</string>
<string name="language_french" translatable="false">Français</string>
<string name="langauge_german" translatable="false">Deutsch</string>
<string name="language_german" translatable="false">Deutsch</string>
<string name="language_italian" translatable="false">Italiano</string>
<string name="language_spanish" translatable="false">Español</string>
<string name="language_chinese" translatable="false">简体中文</string>

View File

@ -11,7 +11,7 @@ ADSP::ADSP(Core::System& system, Sink::Sink& sink) {
opus_decoder = std::make_unique<OpusDecoder::OpusDecoder>(system);
opus_decoder->Send(Direction::DSP, OpusDecoder::Message::Start);
if (opus_decoder->Receive(Direction::Host) != OpusDecoder::Message::StartOK) {
LOG_ERROR(Service_Audio, "OpusDeocder failed to initialize.");
LOG_ERROR(Service_Audio, "OpusDecoder failed to initialize.");
return;
}
}

View File

@ -11,6 +11,8 @@
#include "core/guest_memory.h"
#include "core/memory.h"
#include "core/hle/kernel/k_process.h"
namespace AudioCore {
using namespace std::literals;
@ -26,7 +28,7 @@ DeviceSession::~DeviceSession() {
}
Result DeviceSession::Initialize(std::string_view name_, SampleFormat sample_format_,
u16 channel_count_, size_t session_id_, u32 handle_,
u16 channel_count_, size_t session_id_, Kernel::KProcess* handle_,
u64 applet_resource_user_id_, Sink::StreamType type_) {
if (stream) {
Finalize();
@ -37,6 +39,7 @@ Result DeviceSession::Initialize(std::string_view name_, SampleFormat sample_for
channel_count = channel_count_;
session_id = session_id_;
handle = handle_;
handle->Open();
applet_resource_user_id = applet_resource_user_id_;
if (type == Sink::StreamType::In) {
@ -55,6 +58,11 @@ void DeviceSession::Finalize() {
sink->CloseStream(stream);
stream = nullptr;
}
if (handle) {
handle->Close();
handle = nullptr;
}
}
void DeviceSession::Start() {
@ -92,7 +100,7 @@ void DeviceSession::AppendBuffers(std::span<const AudioBuffer> buffers) {
stream->AppendBuffer(new_buffer, tmp_samples);
} else {
Core::Memory::CpuGuestMemory<s16, Core::Memory::GuestMemoryFlags::UnsafeRead> samples(
system.ApplicationMemory(), buffer.samples, buffer.size / sizeof(s16));
handle->GetMemory(), buffer.samples, buffer.size / sizeof(s16));
stream->AppendBuffer(new_buffer, samples);
}
}
@ -101,7 +109,7 @@ void DeviceSession::AppendBuffers(std::span<const AudioBuffer> buffers) {
void DeviceSession::ReleaseBuffer(const AudioBuffer& buffer) const {
if (type == Sink::StreamType::In) {
auto samples{stream->ReleaseBuffer(buffer.size / sizeof(s16))};
system.ApplicationMemory().WriteBlockUnsafe(buffer.samples, samples.data(), buffer.size);
handle->GetMemory().WriteBlockUnsafe(buffer.samples, samples.data(), buffer.size);
}
}

View File

@ -20,6 +20,10 @@ struct EventType;
} // namespace Timing
} // namespace Core
namespace Kernel {
class KProcess;
} // namespace Kernel
namespace AudioCore {
namespace Sink {
@ -44,13 +48,13 @@ public:
* @param sample_format - Sample format for this device's output.
* @param channel_count - Number of channels for this device (2 or 6).
* @param session_id - This session's id.
* @param handle - Handle for this device session (unused).
* @param handle - Process handle for this device session.
* @param applet_resource_user_id - Applet resource user id for this device session (unused).
* @param type - Type of this stream (Render, In, Out).
* @return Result code for this call.
*/
Result Initialize(std::string_view name, SampleFormat sample_format, u16 channel_count,
size_t session_id, u32 handle, u64 applet_resource_user_id,
size_t session_id, Kernel::KProcess* handle, u64 applet_resource_user_id,
Sink::StreamType type);
/**
@ -137,8 +141,8 @@ private:
u16 channel_count{};
/// Session id of this device session
size_t session_id{};
/// Handle of this device session
u32 handle{};
/// Process handle of device memory owner
Kernel::KProcess* handle{};
/// Applet resource user id of this device session
u64 applet_resource_user_id{};
/// Total number of samples played by this device session

View File

@ -57,7 +57,7 @@ Result System::IsConfigValid(const std::string_view device_name,
}
Result System::Initialize(std::string device_name, const AudioInParameter& in_params,
const u32 handle_, const u64 applet_resource_user_id_) {
Kernel::KProcess* handle_, const u64 applet_resource_user_id_) {
auto result{IsConfigValid(device_name, in_params)};
if (result.IsError()) {
return result;

View File

@ -19,7 +19,8 @@ class System;
namespace Kernel {
class KEvent;
}
class KProcess;
} // namespace Kernel
namespace AudioCore::AudioIn {
@ -93,12 +94,12 @@ public:
*
* @param device_name - The name of the requested input device.
* @param in_params - Input parameters, see AudioInParameter.
* @param handle - Unused.
* @param handle - Process handle.
* @param applet_resource_user_id - Unused.
* @return Result code.
*/
Result Initialize(std::string device_name, const AudioInParameter& in_params, u32 handle,
u64 applet_resource_user_id);
Result Initialize(std::string device_name, const AudioInParameter& in_params,
Kernel::KProcess* handle, u64 applet_resource_user_id);
/**
* Start this system.
@ -244,8 +245,8 @@ public:
private:
/// Core system
Core::System& system;
/// (Unused)
u32 handle{};
/// Process handle
Kernel::KProcess* handle{};
/// (Unused)
u64 applet_resource_user_id{};
/// Buffer event, signalled when a buffer is ready

View File

@ -48,8 +48,8 @@ Result System::IsConfigValid(std::string_view device_name,
return Service::Audio::ResultInvalidChannelCount;
}
Result System::Initialize(std::string device_name, const AudioOutParameter& in_params, u32 handle_,
u64 applet_resource_user_id_) {
Result System::Initialize(std::string device_name, const AudioOutParameter& in_params,
Kernel::KProcess* handle_, u64 applet_resource_user_id_) {
auto result = IsConfigValid(device_name, in_params);
if (result.IsError()) {
return result;

View File

@ -19,7 +19,8 @@ class System;
namespace Kernel {
class KEvent;
}
class KProcess;
} // namespace Kernel
namespace AudioCore::AudioOut {
@ -84,12 +85,12 @@ public:
*
* @param device_name - The name of the requested output device.
* @param in_params - Input parameters, see AudioOutParameter.
* @param handle - Unused.
* @param handle - Process handle.
* @param applet_resource_user_id - Unused.
* @return Result code.
*/
Result Initialize(std::string device_name, const AudioOutParameter& in_params, u32 handle,
u64 applet_resource_user_id);
Result Initialize(std::string device_name, const AudioOutParameter& in_params,
Kernel::KProcess* handle, u64 applet_resource_user_id);
/**
* Start this system.
@ -228,8 +229,8 @@ public:
private:
/// Core system
Core::System& system;
/// (Unused)
u32 handle{};
/// Process handle
Kernel::KProcess* handle{};
/// (Unused)
u64 applet_resource_user_id{};
/// Buffer event, signalled when a buffer is ready

View File

@ -41,7 +41,7 @@ void CommandGenerator::GenerateDataSourceCommand(VoiceInfo& voice_info,
const VoiceState& voice_state, const s8 channel) {
if (voice_info.mix_id == UnusedMixId) {
if (voice_info.splitter_id != UnusedSplitterId) {
auto destination{splitter_context.GetDesintationData(voice_info.splitter_id, 0)};
auto destination{splitter_context.GetDestinationData(voice_info.splitter_id, 0)};
u32 dest_id{0};
while (destination != nullptr) {
if (destination->IsConfigured()) {
@ -55,7 +55,7 @@ void CommandGenerator::GenerateDataSourceCommand(VoiceInfo& voice_info,
}
}
dest_id++;
destination = splitter_context.GetDesintationData(voice_info.splitter_id, dest_id);
destination = splitter_context.GetDestinationData(voice_info.splitter_id, dest_id);
}
}
} else {
@ -234,7 +234,7 @@ void CommandGenerator::GenerateVoiceCommand(VoiceInfo& voice_info) {
if (voice_info.mix_id == UnusedMixId) {
if (voice_info.splitter_id != UnusedSplitterId) {
auto i{channel};
auto destination{splitter_context.GetDesintationData(voice_info.splitter_id, i)};
auto destination{splitter_context.GetDestinationData(voice_info.splitter_id, i)};
while (destination != nullptr) {
if (destination->IsConfigured()) {
const auto mix_id{destination->GetMixId()};
@ -249,7 +249,7 @@ void CommandGenerator::GenerateVoiceCommand(VoiceInfo& voice_info) {
}
}
i += voice_info.channel_count;
destination = splitter_context.GetDesintationData(voice_info.splitter_id, i);
destination = splitter_context.GetDestinationData(voice_info.splitter_id, i);
}
}
} else {
@ -591,7 +591,7 @@ void CommandGenerator::GenerateMixCommands(MixInfo& mix_info) {
if (mix_info.dst_splitter_id != UnusedSplitterId) {
s16 dest_id{0};
auto destination{
splitter_context.GetDesintationData(mix_info.dst_splitter_id, dest_id)};
splitter_context.GetDestinationData(mix_info.dst_splitter_id, dest_id)};
while (destination != nullptr) {
if (destination->IsConfigured()) {
auto splitter_mix_id{destination->GetMixId()};
@ -612,7 +612,7 @@ void CommandGenerator::GenerateMixCommands(MixInfo& mix_info) {
}
dest_id++;
destination =
splitter_context.GetDesintationData(mix_info.dst_splitter_id, dest_id);
splitter_context.GetDestinationData(mix_info.dst_splitter_id, dest_id);
}
}
} else {

View File

@ -93,7 +93,7 @@ bool MixInfo::UpdateConnection(EdgeMatrix& edge_matrix, const InParameter& in_pa
for (u32 i = 0; i < destination_count; i++) {
auto destination{
splitter_context.GetDesintationData(in_params.dest_splitter_id, i)};
splitter_context.GetDestinationData(in_params.dest_splitter_id, i)};
if (destination) {
const auto destination_id{destination->GetMixId()};

View File

@ -9,7 +9,7 @@
namespace AudioCore::Renderer {
SplitterDestinationData* SplitterContext::GetDesintationData(const s32 splitter_id,
SplitterDestinationData* SplitterContext::GetDestinationData(const s32 splitter_id,
const s32 destination_id) {
return splitter_infos[splitter_id].GetData(destination_id);
}

View File

@ -42,7 +42,7 @@ public:
* @param destination_id - Destination index within the splitter.
* @return Pointer to the found destination. May be nullptr.
*/
SplitterDestinationData* GetDesintationData(s32 splitter_id, s32 destination_id);
SplitterDestinationData* GetDestinationData(s32 splitter_id, s32 destination_id);
/**
* Get a splitter from the given index.

View File

@ -35,7 +35,7 @@ bool BasicSetting::Save() const {
return save;
}
bool BasicSetting::RuntimeModfiable() const {
bool BasicSetting::RuntimeModifiable() const {
return runtime_modifiable;
}

View File

@ -186,7 +186,7 @@ public:
/**
* @returns true if the current setting can be changed while the guest is running.
*/
[[nodiscard]] bool RuntimeModfiable() const;
[[nodiscard]] bool RuntimeModifiable() const;
/**
* @returns A unique number corresponding to the setting.

View File

@ -22,14 +22,10 @@ using NativeExecutionParameters = Kernel::KThread::NativeExecutionParameters;
constexpr size_t MaxRelativeBranch = 128_MiB;
constexpr u32 ModuleCodeIndex = 0x24 / sizeof(u32);
Patcher::Patcher() : c(m_patch_instructions) {}
Patcher::~Patcher() = default;
void Patcher::PatchText(const Kernel::PhysicalMemory& program_image,
const Kernel::CodeSet::Segment& code) {
// Branch to the first instruction of the module.
this->BranchToModule(0);
Patcher::Patcher() : c(m_patch_instructions) {
// The first word of the patch section is always a branch to the first instruction of the
// module.
c.dw(0);
// Write save context helper function.
c.l(m_save_context);
@ -38,6 +34,25 @@ void Patcher::PatchText(const Kernel::PhysicalMemory& program_image,
// Write load context helper function.
c.l(m_load_context);
WriteLoadContext();
}
Patcher::~Patcher() = default;
bool Patcher::PatchText(const Kernel::PhysicalMemory& program_image,
const Kernel::CodeSet::Segment& code) {
// If we have patched modules but cannot reach the new module, then it needs its own patcher.
const size_t image_size = program_image.size();
if (total_program_size + image_size > MaxRelativeBranch && total_program_size > 0) {
return false;
}
// Add a new module patch to our list
modules.emplace_back();
curr_patch = &modules.back();
// The first word of the patch section is always a branch to the first instruction of the
// module.
curr_patch->m_branch_to_module_relocations.push_back({0, 0});
// Retrieve text segment data.
const auto text = std::span{program_image}.subspan(code.offset, code.size);
@ -94,16 +109,17 @@ void Patcher::PatchText(const Kernel::PhysicalMemory& program_image,
}
if (auto exclusive = Exclusive{inst}; exclusive.Verify()) {
m_exclusives.push_back(i);
curr_patch->m_exclusives.push_back(i);
}
}
// Determine patching mode for the final relocation step
const size_t image_size = program_image.size();
total_program_size += image_size;
this->mode = image_size > MaxRelativeBranch ? PatchMode::PreText : PatchMode::PostData;
return true;
}
void Patcher::RelocateAndCopy(Common::ProcessAddress load_base,
bool Patcher::RelocateAndCopy(Common::ProcessAddress load_base,
const Kernel::CodeSet::Segment& code,
Kernel::PhysicalMemory& program_image,
EntryTrampolines* out_trampolines) {
@ -120,7 +136,7 @@ void Patcher::RelocateAndCopy(Common::ProcessAddress load_base,
if (mode == PatchMode::PreText) {
rc.B(rel.patch_offset - patch_size - rel.module_offset);
} else {
rc.B(image_size - rel.module_offset + rel.patch_offset);
rc.B(total_program_size - rel.module_offset + rel.patch_offset);
}
};
@ -129,7 +145,7 @@ void Patcher::RelocateAndCopy(Common::ProcessAddress load_base,
if (mode == PatchMode::PreText) {
rc.B(patch_size - rel.patch_offset + rel.module_offset);
} else {
rc.B(rel.module_offset - image_size - rel.patch_offset);
rc.B(rel.module_offset - total_program_size - rel.patch_offset);
}
};
@ -137,7 +153,7 @@ void Patcher::RelocateAndCopy(Common::ProcessAddress load_base,
if (mode == PatchMode::PreText) {
return GetInteger(load_base) + patch_offset;
} else {
return GetInteger(load_base) + image_size + patch_offset;
return GetInteger(load_base) + total_program_size + patch_offset;
}
};
@ -150,39 +166,50 @@ void Patcher::RelocateAndCopy(Common::ProcessAddress load_base,
};
// We are now ready to relocate!
for (const Relocation& rel : m_branch_to_patch_relocations) {
auto& patch = modules[m_relocate_module_index++];
for (const Relocation& rel : patch.m_branch_to_patch_relocations) {
ApplyBranchToPatchRelocation(text_words.data() + rel.module_offset / sizeof(u32), rel);
}
for (const Relocation& rel : m_branch_to_module_relocations) {
for (const Relocation& rel : patch.m_branch_to_module_relocations) {
ApplyBranchToModuleRelocation(m_patch_instructions.data() + rel.patch_offset / sizeof(u32),
rel);
}
// Rewrite PC constants and record post trampolines
for (const Relocation& rel : m_write_module_pc_relocations) {
for (const Relocation& rel : patch.m_write_module_pc_relocations) {
oaknut::CodeGenerator rc{m_patch_instructions.data() + rel.patch_offset / sizeof(u32)};
rc.dx(RebasePc(rel.module_offset));
}
for (const Trampoline& rel : m_trampolines) {
for (const Trampoline& rel : patch.m_trampolines) {
out_trampolines->insert({RebasePc(rel.module_offset), RebasePatch(rel.patch_offset)});
}
// Cortex-A57 seems to treat all exclusives as ordered, but newer processors do not.
// Convert to ordered to preserve this assumption.
for (const ModuleTextAddress i : m_exclusives) {
for (const ModuleTextAddress i : patch.m_exclusives) {
auto exclusive = Exclusive{text_words[i]};
text_words[i] = exclusive.AsOrdered();
}
// Copy to program image
if (this->mode == PatchMode::PreText) {
std::memcpy(program_image.data(), m_patch_instructions.data(),
m_patch_instructions.size() * sizeof(u32));
} else {
program_image.resize(image_size + patch_size);
std::memcpy(program_image.data() + image_size, m_patch_instructions.data(),
m_patch_instructions.size() * sizeof(u32));
// Remove the patched module size from the total. This is done so total_program_size
// always represents the distance from the currently patched module to the patch section.
total_program_size -= image_size;
// Only copy to the program image of the last module
if (m_relocate_module_index == modules.size()) {
if (this->mode == PatchMode::PreText) {
ASSERT(image_size == total_program_size);
std::memcpy(program_image.data(), m_patch_instructions.data(),
m_patch_instructions.size() * sizeof(u32));
} else {
program_image.resize(image_size + patch_size);
std::memcpy(program_image.data() + image_size, m_patch_instructions.data(),
m_patch_instructions.size() * sizeof(u32));
}
return true;
}
return false;
}
size_t Patcher::GetSectionSize() const noexcept {
@ -322,7 +349,7 @@ void Patcher::WriteSvcTrampoline(ModuleDestLabel module_dest, u32 svc_id) {
// Write the post-SVC trampoline address, which will jump back to the guest after restoring its
// state.
m_trampolines.push_back({c.offset(), module_dest});
curr_patch->m_trampolines.push_back({c.offset(), module_dest});
// Host called this location. Save the return address so we can
// unwind the stack properly when jumping back.

View File

@ -31,9 +31,9 @@ public:
explicit Patcher();
~Patcher();
void PatchText(const Kernel::PhysicalMemory& program_image,
bool PatchText(const Kernel::PhysicalMemory& program_image,
const Kernel::CodeSet::Segment& code);
void RelocateAndCopy(Common::ProcessAddress load_base, const Kernel::CodeSet::Segment& code,
bool RelocateAndCopy(Common::ProcessAddress load_base, const Kernel::CodeSet::Segment& code,
Kernel::PhysicalMemory& program_image, EntryTrampolines* out_trampolines);
size_t GetSectionSize() const noexcept;
@ -61,16 +61,16 @@ private:
private:
void BranchToPatch(uintptr_t module_dest) {
m_branch_to_patch_relocations.push_back({c.offset(), module_dest});
curr_patch->m_branch_to_patch_relocations.push_back({c.offset(), module_dest});
}
void BranchToModule(uintptr_t module_dest) {
m_branch_to_module_relocations.push_back({c.offset(), module_dest});
curr_patch->m_branch_to_module_relocations.push_back({c.offset(), module_dest});
c.dw(0);
}
void WriteModulePc(uintptr_t module_dest) {
m_write_module_pc_relocations.push_back({c.offset(), module_dest});
curr_patch->m_write_module_pc_relocations.push_back({c.offset(), module_dest});
c.dx(0);
}
@ -84,15 +84,22 @@ private:
uintptr_t module_offset; ///< Offset in bytes from the start of the text section.
};
struct ModulePatch {
std::vector<Trampoline> m_trampolines;
std::vector<Relocation> m_branch_to_patch_relocations{};
std::vector<Relocation> m_branch_to_module_relocations{};
std::vector<Relocation> m_write_module_pc_relocations{};
std::vector<ModuleTextAddress> m_exclusives{};
};
oaknut::VectorCodeGenerator c;
std::vector<Trampoline> m_trampolines;
std::vector<Relocation> m_branch_to_patch_relocations{};
std::vector<Relocation> m_branch_to_module_relocations{};
std::vector<Relocation> m_write_module_pc_relocations{};
std::vector<ModuleTextAddress> m_exclusives{};
oaknut::Label m_save_context{};
oaknut::Label m_load_context{};
PatchMode mode{PatchMode::None};
size_t total_program_size{};
size_t m_relocate_module_index{};
std::vector<ModulePatch> modules;
ModulePatch* curr_patch;
};
} // namespace Core::NCE

View File

@ -28,6 +28,10 @@ class Memory;
template <typename DTraits>
struct DeviceMemoryManagerAllocator;
struct Asid {
size_t id;
};
template <typename Traits>
class DeviceMemoryManager {
using DeviceInterface = typename Traits::DeviceInterface;
@ -43,15 +47,14 @@ public:
void AllocateFixed(DAddr start, size_t size);
void Free(DAddr start, size_t size);
void Map(DAddr address, VAddr virtual_address, size_t size, size_t process_id,
bool track = false);
void Map(DAddr address, VAddr virtual_address, size_t size, Asid asid, bool track = false);
void Unmap(DAddr address, size_t size);
void TrackContinuityImpl(DAddr address, VAddr virtual_address, size_t size, size_t process_id);
void TrackContinuity(DAddr address, VAddr virtual_address, size_t size, size_t process_id) {
void TrackContinuityImpl(DAddr address, VAddr virtual_address, size_t size, Asid asid);
void TrackContinuity(DAddr address, VAddr virtual_address, size_t size, Asid asid) {
std::scoped_lock lk(mapping_guard);
TrackContinuityImpl(address, virtual_address, size, process_id);
TrackContinuityImpl(address, virtual_address, size, asid);
}
// Write / Read
@ -105,8 +108,8 @@ public:
void WriteBlock(DAddr address, const void* src_pointer, size_t size);
void WriteBlockUnsafe(DAddr address, const void* src_pointer, size_t size);
size_t RegisterProcess(Memory::Memory* memory);
void UnregisterProcess(size_t id);
Asid RegisterProcess(Memory::Memory* memory);
void UnregisterProcess(Asid id);
void UpdatePagesCachedCount(DAddr addr, size_t size, s32 delta);
@ -163,17 +166,17 @@ private:
static constexpr size_t guest_max_as_bits = 39;
static constexpr size_t guest_as_size = 1ULL << guest_max_as_bits;
static constexpr size_t guest_mask = guest_as_size - 1ULL;
static constexpr size_t process_id_start_bit = guest_max_as_bits;
static constexpr size_t asid_start_bit = guest_max_as_bits;
std::pair<size_t, VAddr> ExtractCPUBacking(size_t page_index) {
std::pair<Asid, VAddr> ExtractCPUBacking(size_t page_index) {
auto content = cpu_backing_address[page_index];
const VAddr address = content & guest_mask;
const size_t process_id = static_cast<size_t>(content >> process_id_start_bit);
return std::make_pair(process_id, address);
const Asid asid{static_cast<size_t>(content >> asid_start_bit)};
return std::make_pair(asid, address);
}
void InsertCPUBacking(size_t page_index, VAddr address, size_t process_id) {
cpu_backing_address[page_index] = address | (process_id << process_id_start_bit);
void InsertCPUBacking(size_t page_index, VAddr address, Asid asid) {
cpu_backing_address[page_index] = address | (asid.id << asid_start_bit);
}
Common::VirtualBuffer<VAddr> cpu_backing_address;
@ -205,4 +208,4 @@ private:
std::mutex mapping_guard;
};
} // namespace Core
} // namespace Core

View File

@ -215,8 +215,8 @@ void DeviceMemoryManager<Traits>::Free(DAddr start, size_t size) {
template <typename Traits>
void DeviceMemoryManager<Traits>::Map(DAddr address, VAddr virtual_address, size_t size,
size_t process_id, bool track) {
Core::Memory::Memory* process_memory = registered_processes[process_id];
Asid asid, bool track) {
Core::Memory::Memory* process_memory = registered_processes[asid.id];
size_t start_page_d = address >> Memory::YUZU_PAGEBITS;
size_t num_pages = Common::AlignUp(size, Memory::YUZU_PAGESIZE) >> Memory::YUZU_PAGEBITS;
std::scoped_lock lk(mapping_guard);
@ -229,7 +229,7 @@ void DeviceMemoryManager<Traits>::Map(DAddr address, VAddr virtual_address, size
}
auto phys_addr = static_cast<u32>(GetRawPhysicalAddr(ptr) >> Memory::YUZU_PAGEBITS) + 1U;
compressed_physical_ptr[start_page_d + i] = phys_addr;
InsertCPUBacking(start_page_d + i, new_vaddress, process_id);
InsertCPUBacking(start_page_d + i, new_vaddress, asid);
const u32 base_dev = compressed_device_addr[phys_addr - 1U];
const u32 new_dev = static_cast<u32>(start_page_d + i);
if (base_dev == 0) [[likely]] {
@ -244,7 +244,7 @@ void DeviceMemoryManager<Traits>::Map(DAddr address, VAddr virtual_address, size
impl->multi_dev_address.Register(new_dev, start_id);
}
if (track) {
TrackContinuityImpl(address, virtual_address, size, process_id);
TrackContinuityImpl(address, virtual_address, size, asid);
}
}
@ -277,8 +277,8 @@ void DeviceMemoryManager<Traits>::Unmap(DAddr address, size_t size) {
}
template <typename Traits>
void DeviceMemoryManager<Traits>::TrackContinuityImpl(DAddr address, VAddr virtual_address,
size_t size, size_t process_id) {
Core::Memory::Memory* process_memory = registered_processes[process_id];
size_t size, Asid asid) {
Core::Memory::Memory* process_memory = registered_processes[asid.id];
size_t start_page_d = address >> Memory::YUZU_PAGEBITS;
size_t num_pages = Common::AlignUp(size, Memory::YUZU_PAGESIZE) >> Memory::YUZU_PAGEBITS;
uintptr_t last_ptr = 0;
@ -488,8 +488,8 @@ void DeviceMemoryManager<Traits>::WriteBlockUnsafe(DAddr address, const void* sr
}
template <typename Traits>
size_t DeviceMemoryManager<Traits>::RegisterProcess(Memory::Memory* memory_device_inter) {
size_t new_id;
Asid DeviceMemoryManager<Traits>::RegisterProcess(Memory::Memory* memory_device_inter) {
size_t new_id{};
if (!id_pool.empty()) {
new_id = id_pool.front();
id_pool.pop_front();
@ -498,29 +498,23 @@ size_t DeviceMemoryManager<Traits>::RegisterProcess(Memory::Memory* memory_devic
registered_processes.emplace_back(memory_device_inter);
new_id = registered_processes.size() - 1U;
}
return new_id;
return Asid{new_id};
}
template <typename Traits>
void DeviceMemoryManager<Traits>::UnregisterProcess(size_t id) {
registered_processes[id] = nullptr;
id_pool.push_front(id);
void DeviceMemoryManager<Traits>::UnregisterProcess(Asid asid) {
registered_processes[asid.id] = nullptr;
id_pool.push_front(asid.id);
}
template <typename Traits>
void DeviceMemoryManager<Traits>::UpdatePagesCachedCount(DAddr addr, size_t size, s32 delta) {
bool locked = false;
auto lock = [&] {
if (!locked) {
counter_guard.lock();
locked = true;
std::unique_lock<std::mutex> lk(counter_guard, std::defer_lock);
const auto Lock = [&] {
if (!lk) {
lk.lock();
}
};
SCOPE_EXIT({
if (locked) {
counter_guard.unlock();
}
});
u64 uncache_begin = 0;
u64 cache_begin = 0;
u64 uncache_bytes = 0;
@ -530,9 +524,9 @@ void DeviceMemoryManager<Traits>::UpdatePagesCachedCount(DAddr addr, size_t size
std::atomic_thread_fence(std::memory_order_acquire);
const size_t page_end = Common::DivCeil(addr + size, Memory::YUZU_PAGESIZE);
size_t page = addr >> Memory::YUZU_PAGEBITS;
auto [process_id, base_vaddress] = ExtractCPUBacking(page);
auto [asid, base_vaddress] = ExtractCPUBacking(page);
size_t vpage = base_vaddress >> Memory::YUZU_PAGEBITS;
auto* memory_device_inter = registered_processes[process_id];
auto* memory_device_inter = registered_processes[asid.id];
for (; page != page_end; ++page) {
std::atomic_uint8_t& count = cached_pages->at(page >> 3).Count(page);
@ -555,7 +549,7 @@ void DeviceMemoryManager<Traits>::UpdatePagesCachedCount(DAddr addr, size_t size
}
uncache_bytes += Memory::YUZU_PAGESIZE;
} else if (uncache_bytes > 0) {
lock();
Lock();
MarkRegionCaching(memory_device_inter, uncache_begin << Memory::YUZU_PAGEBITS,
uncache_bytes, false);
uncache_bytes = 0;
@ -566,7 +560,7 @@ void DeviceMemoryManager<Traits>::UpdatePagesCachedCount(DAddr addr, size_t size
}
cache_bytes += Memory::YUZU_PAGESIZE;
} else if (cache_bytes > 0) {
lock();
Lock();
MarkRegionCaching(memory_device_inter, cache_begin << Memory::YUZU_PAGEBITS, cache_bytes,
true);
cache_bytes = 0;
@ -574,12 +568,12 @@ void DeviceMemoryManager<Traits>::UpdatePagesCachedCount(DAddr addr, size_t size
vpage++;
}
if (uncache_bytes > 0) {
lock();
Lock();
MarkRegionCaching(memory_device_inter, uncache_begin << Memory::YUZU_PAGEBITS, uncache_bytes,
false);
}
if (cache_bytes > 0) {
lock();
Lock();
MarkRegionCaching(memory_device_inter, cache_begin << Memory::YUZU_PAGEBITS, cache_bytes,
true);
}

View File

@ -47,7 +47,7 @@ void DefaultControllerApplet::ReconfigureControllers(ReconfigureCallback callbac
// Connect controllers based on the following priority list from highest to lowest priority:
// Pro Controller -> Dual Joycons -> Left Joycon/Right Joycon -> Handheld
if (parameters.allow_pro_controller) {
controller->SetNpadStyleIndex(Core::HID::NpadStyleIndex::ProController);
controller->SetNpadStyleIndex(Core::HID::NpadStyleIndex::Fullkey);
controller->Connect(true);
} else if (parameters.allow_dual_joycons) {
controller->SetNpadStyleIndex(Core::HID::NpadStyleIndex::JoyconDual);

View File

@ -28,14 +28,14 @@ Result KMemoryBlockManager::Initialize(KProcessAddress st, KProcessAddress nd,
}
void KMemoryBlockManager::Finalize(KMemoryBlockSlabManager* slab_manager,
HostUnmapCallback&& host_unmap_callback) {
BlockCallback&& block_callback) {
// Erase every block until we have none left.
auto it = m_memory_block_tree.begin();
while (it != m_memory_block_tree.end()) {
KMemoryBlock* block = std::addressof(*it);
it = m_memory_block_tree.erase(it);
block_callback(block->GetAddress(), block->GetSize());
slab_manager->Free(block);
host_unmap_callback(block->GetAddress(), block->GetSize());
}
ASSERT(m_memory_block_tree.empty());

View File

@ -85,11 +85,11 @@ public:
public:
KMemoryBlockManager();
using HostUnmapCallback = std::function<void(Common::ProcessAddress, u64)>;
using BlockCallback = std::function<void(Common::ProcessAddress, u64)>;
Result Initialize(KProcessAddress st, KProcessAddress nd,
KMemoryBlockSlabManager* slab_manager);
void Finalize(KMemoryBlockSlabManager* slab_manager, HostUnmapCallback&& host_unmap_callback);
void Finalize(KMemoryBlockSlabManager* slab_manager, BlockCallback&& block_callback);
iterator end() {
return m_memory_block_tree.end();

View File

@ -435,69 +435,14 @@ Result KPageTableBase::FinalizeProcess() {
// Only process tables should be finalized.
ASSERT(!this->IsKernel());
// HLE processes don't have memory mapped.
R_SUCCEED_IF(m_impl == nullptr);
// NOTE: Here Nintendo calls an unknown OnFinalize function.
// this->OnFinalize();
// NOTE: Here Nintendo calls a second unknown OnFinalize function.
// this->OnFinalize2();
// Get implementation objects.
auto& impl = this->GetImpl();
auto& mm = m_kernel.MemoryManager();
// Traverse, freeing all pages.
{
// Get the address space size.
const size_t as_size = this->GetAddressSpaceSize();
// Begin the traversal.
TraversalContext context;
TraversalEntry cur_entry = {
.phys_addr = 0,
.block_size = 0,
};
bool cur_valid = false;
TraversalEntry next_entry;
bool next_valid;
size_t tot_size = 0;
next_valid = impl.BeginTraversal(std::addressof(next_entry), std::addressof(context),
this->GetAddressSpaceStart());
// Iterate over entries.
while (true) {
if ((!next_valid && !cur_valid) ||
(next_valid && cur_valid &&
next_entry.phys_addr == cur_entry.phys_addr + cur_entry.block_size)) {
cur_entry.block_size += next_entry.block_size;
} else {
if (cur_valid && IsHeapPhysicalAddressForFinalize(cur_entry.phys_addr)) {
mm.Close(cur_entry.phys_addr, cur_entry.block_size / PageSize);
}
// Update tracking variables.
tot_size += cur_entry.block_size;
cur_entry = next_entry;
cur_valid = next_valid;
}
if (cur_entry.block_size + tot_size >= as_size) {
break;
}
next_valid =
impl.ContinueTraversal(std::addressof(next_entry), std::addressof(context));
}
// Handle the last block.
if (cur_valid && IsHeapPhysicalAddressForFinalize(cur_entry.phys_addr)) {
mm.Close(cur_entry.phys_addr, cur_entry.block_size / PageSize);
}
}
// NOTE: Here Nintendo does a page table walk to discover heap pages to free.
// We will use the block manager finalization below to free them.
R_SUCCEED();
}
@ -505,14 +450,24 @@ Result KPageTableBase::FinalizeProcess() {
void KPageTableBase::Finalize() {
this->FinalizeProcess();
auto HostUnmapCallback = [&](KProcessAddress addr, u64 size) {
auto BlockCallback = [&](KProcessAddress addr, u64 size) {
if (m_impl->fastmem_arena) {
m_system.DeviceMemory().buffer.Unmap(GetInteger(addr), size, false);
}
// Get physical pages.
KPageGroup pg(m_kernel, m_block_info_manager);
this->MakePageGroup(pg, addr, size / PageSize);
// Free the pages.
pg.CloseAndReset();
};
// Finalize memory blocks.
m_memory_block_manager.Finalize(m_memory_block_slab_manager, std::move(HostUnmapCallback));
{
KScopedLightLock lk(m_general_lock);
m_memory_block_manager.Finalize(m_memory_block_slab_manager, std::move(BlockCallback));
}
// Free any unsafe mapped memory.
if (m_mapped_unsafe_physical_memory) {

View File

@ -1239,10 +1239,10 @@ void KProcess::LoadModule(CodeSet code_set, KProcessAddress base_addr) {
ReprotectSegment(code_set.DataSegment(), Svc::MemoryPermission::ReadWrite);
#ifdef HAS_NCE
if (this->IsApplication() && Settings::IsNceEnabled()) {
const auto& patch = code_set.PatchSegment();
if (this->IsApplication() && Settings::IsNceEnabled() && patch.size != 0) {
auto& buffer = m_kernel.System().DeviceMemory().buffer;
const auto& code = code_set.CodeSegment();
const auto& patch = code_set.PatchSegment();
buffer.Protect(GetInteger(base_addr + code.addr), code.size,
Common::MemoryPermission::Read | Common::MemoryPermission::Execute);
buffer.Protect(GetInteger(base_addr + patch.addr), patch.size,

View File

@ -112,7 +112,14 @@ struct KernelCore::Impl {
old_process->Close();
}
process_list.clear();
{
std::scoped_lock lk{process_list_lock};
for (auto* const process : process_list) {
process->Terminate();
process->Close();
}
process_list.clear();
}
next_object_id = 0;
next_kernel_process_id = KProcess::InitialProcessIdMin;

View File

@ -61,9 +61,7 @@ ProfileManager::ProfileManager() {
OpenUser(*GetUser(current));
}
ProfileManager::~ProfileManager() {
WriteUserSaveFile();
}
ProfileManager::~ProfileManager() = default;
/// After a users creation it needs to be "registered" to the system. AddToProfiles handles the
/// internal management of the users profiles
@ -113,6 +111,8 @@ Result ProfileManager::CreateNewUser(UUID uuid, const ProfileUsername& username)
return ERROR_USER_ALREADY_EXISTS;
}
is_save_needed = true;
return AddUser({
.user_uuid = uuid,
.username = username,
@ -326,6 +326,9 @@ bool ProfileManager::RemoveUser(UUID uuid) {
profiles[*index] = ProfileInfo{};
std::stable_partition(profiles.begin(), profiles.end(),
[](const ProfileInfo& profile) { return profile.user_uuid.IsValid(); });
is_save_needed = true;
return true;
}
@ -340,6 +343,8 @@ bool ProfileManager::SetProfileBase(UUID uuid, const ProfileBase& profile_new) {
profile.username = profile_new.username;
profile.creation_time = profile_new.timestamp;
is_save_needed = true;
return true;
}
@ -348,6 +353,7 @@ bool ProfileManager::SetProfileBaseAndData(Common::UUID uuid, const ProfileBase&
const auto index = GetUserIndex(uuid);
if (index.has_value() && SetProfileBase(uuid, profile_new)) {
profiles[*index].data = data_new;
is_save_needed = true;
return true;
}
@ -391,6 +397,10 @@ void ProfileManager::ParseUserSaveFile() {
}
void ProfileManager::WriteUserSaveFile() {
if (!is_save_needed) {
return;
}
ProfileDataRaw raw{};
for (std::size_t i = 0; i < MAX_USERS; ++i) {
@ -423,7 +433,10 @@ void ProfileManager::WriteUserSaveFile() {
if (!save.IsOpen() || !save.SetSize(sizeof(ProfileDataRaw)) || !save.WriteObject(raw)) {
LOG_WARNING(Service_ACC, "Failed to write save data to file... No changes to user data "
"made in current session will be saved.");
return;
}
is_save_needed = false;
}
}; // namespace Service::Account

View File

@ -103,6 +103,7 @@ private:
std::optional<std::size_t> AddToProfiles(const ProfileInfo& profile);
bool RemoveProfileAtIndex(std::size_t index);
bool is_save_needed{};
std::array<ProfileInfo, MAX_USERS> profiles{};
std::array<ProfileInfo, MAX_USERS> stored_opened_profiles{};
std::size_t user_count{};

View File

@ -18,11 +18,11 @@ using namespace AudioCore::AudioIn;
class IAudioIn final : public ServiceFramework<IAudioIn> {
public:
explicit IAudioIn(Core::System& system_, Manager& manager, size_t session_id,
const std::string& device_name, const AudioInParameter& in_params, u32 handle,
u64 applet_resource_user_id)
const std::string& device_name, const AudioInParameter& in_params,
Kernel::KProcess* handle, u64 applet_resource_user_id)
: ServiceFramework{system_, "IAudioIn"},
service_context{system_, "IAudioIn"}, event{service_context.CreateEvent("AudioInEvent")},
impl{std::make_shared<In>(system_, manager, event, session_id)} {
process{handle}, impl{std::make_shared<In>(system_, manager, event, session_id)} {
// clang-format off
static const FunctionInfo functions[] = {
{0, &IAudioIn::GetAudioInState, "GetAudioInState"},
@ -45,6 +45,8 @@ public:
RegisterHandlers(functions);
process->Open();
if (impl->GetSystem()
.Initialize(device_name, in_params, handle, applet_resource_user_id)
.IsError()) {
@ -55,6 +57,7 @@ public:
~IAudioIn() override {
impl->Free();
service_context.CloseEvent(event);
process->Close();
}
[[nodiscard]] std::shared_ptr<In> GetImpl() {
@ -196,6 +199,7 @@ private:
KernelHelpers::ServiceContext service_context;
Kernel::KEvent* event;
Kernel::KProcess* process;
std::shared_ptr<AudioCore::AudioIn::In> impl;
Common::ScratchBuffer<u64> released_buffer;
};
@ -267,6 +271,14 @@ void AudInU::OpenAudioIn(HLERequestContext& ctx) {
auto device_name = Common::StringFromBuffer(device_name_data);
auto handle{ctx.GetCopyHandle(0)};
auto process{ctx.GetObjectFromHandle<Kernel::KProcess>(handle)};
if (process.IsNull()) {
LOG_ERROR(Service_Audio, "Failed to get process handle");
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ResultUnknown);
return;
}
std::scoped_lock l{impl->mutex};
auto link{impl->LinkToManager()};
if (link.IsError()) {
@ -287,8 +299,9 @@ void AudInU::OpenAudioIn(HLERequestContext& ctx) {
LOG_DEBUG(Service_Audio, "Opening new AudioIn, sessionid={}, free sessions={}", new_session_id,
impl->num_free_sessions);
auto audio_in = std::make_shared<IAudioIn>(system, *impl, new_session_id, device_name,
in_params, handle, applet_resource_user_id);
auto audio_in =
std::make_shared<IAudioIn>(system, *impl, new_session_id, device_name, in_params,
process.GetPointerUnsafe(), applet_resource_user_id);
impl->sessions[new_session_id] = audio_in->GetImpl();
impl->applet_resource_user_ids[new_session_id] = applet_resource_user_id;
@ -318,6 +331,14 @@ void AudInU::OpenAudioInProtocolSpecified(HLERequestContext& ctx) {
auto device_name = Common::StringFromBuffer(device_name_data);
auto handle{ctx.GetCopyHandle(0)};
auto process{ctx.GetObjectFromHandle<Kernel::KProcess>(handle)};
if (process.IsNull()) {
LOG_ERROR(Service_Audio, "Failed to get process handle");
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ResultUnknown);
return;
}
std::scoped_lock l{impl->mutex};
auto link{impl->LinkToManager()};
if (link.IsError()) {
@ -338,8 +359,9 @@ void AudInU::OpenAudioInProtocolSpecified(HLERequestContext& ctx) {
LOG_DEBUG(Service_Audio, "Opening new AudioIn, sessionid={}, free sessions={}", new_session_id,
impl->num_free_sessions);
auto audio_in = std::make_shared<IAudioIn>(system, *impl, new_session_id, device_name,
in_params, handle, applet_resource_user_id);
auto audio_in =
std::make_shared<IAudioIn>(system, *impl, new_session_id, device_name, in_params,
process.GetPointerUnsafe(), applet_resource_user_id);
impl->sessions[new_session_id] = audio_in->GetImpl();
impl->applet_resource_user_ids[new_session_id] = applet_resource_user_id;

View File

@ -26,9 +26,10 @@ class IAudioOut final : public ServiceFramework<IAudioOut> {
public:
explicit IAudioOut(Core::System& system_, AudioCore::AudioOut::Manager& manager,
size_t session_id, const std::string& device_name,
const AudioOutParameter& in_params, u32 handle, u64 applet_resource_user_id)
const AudioOutParameter& in_params, Kernel::KProcess* handle,
u64 applet_resource_user_id)
: ServiceFramework{system_, "IAudioOut"}, service_context{system_, "IAudioOut"},
event{service_context.CreateEvent("AudioOutEvent")},
event{service_context.CreateEvent("AudioOutEvent")}, process{handle},
impl{std::make_shared<AudioCore::AudioOut::Out>(system_, manager, event, session_id)} {
// clang-format off
@ -50,11 +51,14 @@ public:
};
// clang-format on
RegisterHandlers(functions);
process->Open();
}
~IAudioOut() override {
impl->Free();
service_context.CloseEvent(event);
process->Close();
}
[[nodiscard]] std::shared_ptr<AudioCore::AudioOut::Out> GetImpl() {
@ -206,6 +210,7 @@ private:
KernelHelpers::ServiceContext service_context;
Kernel::KEvent* event;
Kernel::KProcess* process;
std::shared_ptr<AudioCore::AudioOut::Out> impl;
Common::ScratchBuffer<u64> released_buffer;
};
@ -257,6 +262,14 @@ void AudOutU::OpenAudioOut(HLERequestContext& ctx) {
auto device_name = Common::StringFromBuffer(device_name_data);
auto handle{ctx.GetCopyHandle(0)};
auto process{ctx.GetObjectFromHandle<Kernel::KProcess>(handle)};
if (process.IsNull()) {
LOG_ERROR(Service_Audio, "Failed to get process handle");
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ResultUnknown);
return;
}
auto link{impl->LinkToManager()};
if (link.IsError()) {
LOG_ERROR(Service_Audio, "Failed to link Audio Out to Audio Manager");
@ -276,10 +289,11 @@ void AudOutU::OpenAudioOut(HLERequestContext& ctx) {
LOG_DEBUG(Service_Audio, "Opening new AudioOut, sessionid={}, free sessions={}", new_session_id,
impl->num_free_sessions);
auto audio_out = std::make_shared<IAudioOut>(system, *impl, new_session_id, device_name,
in_params, handle, applet_resource_user_id);
result = audio_out->GetImpl()->GetSystem().Initialize(device_name, in_params, handle,
applet_resource_user_id);
auto audio_out =
std::make_shared<IAudioOut>(system, *impl, new_session_id, device_name, in_params,
process.GetPointerUnsafe(), applet_resource_user_id);
result = audio_out->GetImpl()->GetSystem().Initialize(
device_name, in_params, process.GetPointerUnsafe(), applet_resource_user_id);
if (result.IsError()) {
LOG_ERROR(Service_Audio, "Failed to initialize the AudioOut System!");
IPC::ResponseBuilder rb{ctx, 2};

View File

@ -40,7 +40,7 @@ Result SaveDataController::CreateSaveData(FileSys::VirtualDir* out_save_data,
FileSys::SaveDataSpaceId space,
const FileSys::SaveDataAttribute& attribute) {
LOG_TRACE(Service_FS, "Creating Save Data for space_id={:01X}, save_struct={}", space,
save_struct.DebugInfo());
attribute.DebugInfo());
auto save_data = factory->Create(space, attribute);
if (save_data == nullptr) {

View File

@ -1498,7 +1498,7 @@ void IHidServer::GetVibrationDeviceInfo(HLERequestContext& ctx) {
bool check_device_index = false;
switch (vibration_device_handle.npad_type) {
case Core::HID::NpadStyleIndex::ProController:
case Core::HID::NpadStyleIndex::Fullkey:
case Core::HID::NpadStyleIndex::Handheld:
case Core::HID::NpadStyleIndex::JoyconDual:
case Core::HID::NpadStyleIndex::JoyconLeft:

View File

@ -16,9 +16,8 @@
namespace Service::Nvidia::NvCore {
Session::Session(size_t id_, Kernel::KProcess* process_, size_t smmu_id_)
: id{id_}, process{process_}, smmu_id{smmu_id_},
has_preallocated_area{}, mapper{}, is_active{} {}
Session::Session(SessionId id_, Kernel::KProcess* process_, Core::Asid asid_)
: id{id_}, process{process_}, asid{asid_}, has_preallocated_area{}, mapper{}, is_active{} {}
Session::~Session() = default;
@ -41,7 +40,9 @@ Container::Container(Tegra::Host1x::Host1x& host1x_) {
Container::~Container() = default;
size_t Container::OpenSession(Kernel::KProcess* process) {
SessionId Container::OpenSession(Kernel::KProcess* process) {
using namespace Common::Literals;
std::scoped_lock lk(impl->session_guard);
for (auto& session : impl->sessions) {
if (!session.is_active) {
@ -54,14 +55,14 @@ size_t Container::OpenSession(Kernel::KProcess* process) {
size_t new_id{};
auto* memory_interface = &process->GetMemory();
auto& smmu = impl->host1x.MemoryManager();
auto smmu_id = smmu.RegisterProcess(memory_interface);
auto asid = smmu.RegisterProcess(memory_interface);
if (!impl->id_pool.empty()) {
new_id = impl->id_pool.front();
impl->id_pool.pop_front();
impl->sessions[new_id] = Session{new_id, process, smmu_id};
impl->sessions[new_id] = Session{SessionId{new_id}, process, asid};
} else {
new_id = impl->new_ids++;
impl->sessions.emplace_back(new_id, process, smmu_id);
impl->sessions.emplace_back(SessionId{new_id}, process, asid);
}
auto& session = impl->sessions[new_id];
session.is_active = true;
@ -80,7 +81,7 @@ size_t Container::OpenSession(Kernel::KProcess* process) {
cur_addr));
auto svc_mem_info = mem_info.GetSvcMemoryInfo();
// check if this memory block is heap
// Check if this memory block is heap.
if (svc_mem_info.state == Kernel::Svc::MemoryState::Normal) {
if (svc_mem_info.size > region_size) {
region_size = svc_mem_info.size;
@ -97,21 +98,21 @@ size_t Container::OpenSession(Kernel::KProcess* process) {
cur_addr = next_address;
}
session.has_preallocated_area = false;
auto start_region = (region_size >> 15) >= 1024 ? smmu.Allocate(region_size) : 0;
auto start_region = region_size >= 32_MiB ? smmu.Allocate(region_size) : 0;
if (start_region != 0) {
session.mapper = std::make_unique<HeapMapper>(region_start, start_region, region_size,
smmu_id, impl->host1x);
smmu.TrackContinuity(start_region, region_start, region_size, smmu_id);
asid, impl->host1x);
smmu.TrackContinuity(start_region, region_start, region_size, asid);
session.has_preallocated_area = true;
LOG_CRITICAL(Debug, "Preallocation created!");
LOG_DEBUG(Debug, "Preallocation created!");
}
}
return new_id;
return SessionId{new_id};
}
void Container::CloseSession(size_t id) {
void Container::CloseSession(SessionId session_id) {
std::scoped_lock lk(impl->session_guard);
auto& session = impl->sessions[id];
auto& session = impl->sessions[session_id.id];
auto& smmu = impl->host1x.MemoryManager();
if (session.has_preallocated_area) {
const DAddr region_start = session.mapper->GetRegionStart();
@ -121,13 +122,13 @@ void Container::CloseSession(size_t id) {
session.has_preallocated_area = false;
}
session.is_active = false;
smmu.UnregisterProcess(impl->sessions[id].smmu_id);
impl->id_pool.emplace_front(id);
smmu.UnregisterProcess(impl->sessions[session_id.id].asid);
impl->id_pool.emplace_front(session_id.id);
}
Session* Container::GetSession(size_t id) {
Session* Container::GetSession(SessionId session_id) {
std::atomic_thread_fence(std::memory_order_acquire);
return &impl->sessions[id];
return &impl->sessions[session_id.id];
}
NvMap& Container::GetNvMapFile() {

View File

@ -8,6 +8,7 @@
#include <memory>
#include <unordered_map>
#include "core/device_memory_manager.h"
#include "core/hle/service/nvdrv/nvdata.h"
namespace Kernel {
@ -26,8 +27,12 @@ class SyncpointManager;
struct ContainerImpl;
struct SessionId {
size_t id;
};
struct Session {
Session(size_t id_, Kernel::KProcess* process_, size_t smmu_id_);
Session(SessionId id_, Kernel::KProcess* process_, Core::Asid asid_);
~Session();
Session(const Session&) = delete;
@ -35,9 +40,9 @@ struct Session {
Session(Session&&) = default;
Session& operator=(Session&&) = default;
size_t id;
SessionId id;
Kernel::KProcess* process;
size_t smmu_id;
Core::Asid asid;
bool has_preallocated_area{};
std::unique_ptr<HeapMapper> mapper{};
bool is_active{};
@ -48,10 +53,10 @@ public:
explicit Container(Tegra::Host1x::Host1x& host1x);
~Container();
size_t OpenSession(Kernel::KProcess* process);
void CloseSession(size_t id);
SessionId OpenSession(Kernel::KProcess* process);
void CloseSession(SessionId id);
Session* GetSession(size_t id);
Session* GetSession(SessionId id);
NvMap& GetNvMapFile();

View File

@ -109,9 +109,9 @@ struct HeapMapper::HeapMapperInternal {
std::mutex guard;
};
HeapMapper::HeapMapper(VAddr start_vaddress, DAddr start_daddress, size_t size, size_t smmu_id,
HeapMapper::HeapMapper(VAddr start_vaddress, DAddr start_daddress, size_t size, Core::Asid asid,
Tegra::Host1x::Host1x& host1x)
: m_vaddress{start_vaddress}, m_daddress{start_daddress}, m_size{size}, m_smmu_id{smmu_id} {
: m_vaddress{start_vaddress}, m_daddress{start_daddress}, m_size{size}, m_asid{asid} {
m_internal = std::make_unique<HeapMapperInternal>(host1x);
}
@ -138,7 +138,7 @@ DAddr HeapMapper::Map(VAddr start, size_t size) {
const size_t offset = inter_addr - m_vaddress;
const size_t sub_size = inter_addr_end - inter_addr;
m_internal->device_memory.Map(m_daddress + offset, m_vaddress + offset, sub_size,
m_smmu_id);
m_asid);
}
}
m_internal->mapping_overlaps += std::make_pair(interval, 1);
@ -172,4 +172,4 @@ void HeapMapper::Unmap(VAddr start, size_t size) {
m_internal->base_set.clear();
}
} // namespace Service::Nvidia::NvCore
} // namespace Service::Nvidia::NvCore

View File

@ -6,6 +6,7 @@
#include <memory>
#include "common/common_types.h"
#include "core/device_memory_manager.h"
namespace Tegra::Host1x {
class Host1x;
@ -15,7 +16,7 @@ namespace Service::Nvidia::NvCore {
class HeapMapper {
public:
HeapMapper(VAddr start_vaddress, DAddr start_daddress, size_t size, size_t smmu_id,
HeapMapper(VAddr start_vaddress, DAddr start_daddress, size_t size, Core::Asid asid,
Tegra::Host1x::Host1x& host1x);
~HeapMapper();
@ -41,8 +42,8 @@ private:
VAddr m_vaddress;
DAddr m_daddress;
size_t m_size;
size_t m_smmu_id;
Core::Asid m_asid;
std::unique_ptr<HeapMapperInternal> m_internal;
};
} // namespace Service::Nvidia::NvCore
} // namespace Service::Nvidia::NvCore

View File

@ -22,7 +22,8 @@ NvMap::Handle::Handle(u64 size_, Id id_)
flags.raw = 0;
}
NvResult NvMap::Handle::Alloc(Flags pFlags, u32 pAlign, u8 pKind, u64 pAddress, size_t pSessionId) {
NvResult NvMap::Handle::Alloc(Flags pFlags, u32 pAlign, u8 pKind, u64 pAddress,
NvCore::SessionId pSessionId) {
std::scoped_lock lock(mutex);
// Handles cannot be allocated twice
if (allocated) {
@ -223,7 +224,7 @@ DAddr NvMap::PinHandle(NvMap::Handle::Id handle, bool low_area_pin) {
}
handle_description->d_address = address;
smmu.Map(address, vaddress, map_size, session->smmu_id, true);
smmu.Map(address, vaddress, map_size, session->asid, true);
handle_description->in_heap = false;
}
}

View File

@ -14,6 +14,7 @@
#include "common/bit_field.h"
#include "common/common_types.h"
#include "core/hle/service/nvdrv/core/container.h"
#include "core/hle/service/nvdrv/nvdata.h"
namespace Tegra {
@ -71,7 +72,7 @@ public:
u8 kind{}; //!< Used for memory compression
bool allocated{}; //!< If the handle has been allocated with `Alloc`
bool in_heap{};
size_t session_id{};
NvCore::SessionId session_id{};
DAddr d_address{}; //!< The memory location in the device's AS that this handle corresponds
//!< to, this can also be in the nvdrv tmem
@ -83,7 +84,7 @@ public:
* if a 0 address is passed
*/
[[nodiscard]] NvResult Alloc(Flags pFlags, u32 pAlign, u8 pKind, u64 pAddress,
size_t pSessionId);
NvCore::SessionId pSessionId);
/**
* @brief Increases the dupe counter of the handle for the given session

View File

@ -7,6 +7,7 @@
#include <vector>
#include "common/common_types.h"
#include "core/hle/service/nvdrv/core/container.h"
#include "core/hle/service/nvdrv/nvdata.h"
namespace Core {
@ -62,7 +63,7 @@ public:
* Called once a device is opened
* @param fd The device fd
*/
virtual void OnOpen(size_t session_id, DeviceFD fd) = 0;
virtual void OnOpen(NvCore::SessionId session_id, DeviceFD fd) = 0;
/**
* Called once a device is closed

View File

@ -35,7 +35,7 @@ NvResult nvdisp_disp0::Ioctl3(DeviceFD fd, Ioctl command, std::span<const u8> in
return NvResult::NotImplemented;
}
void nvdisp_disp0::OnOpen(size_t session_id, DeviceFD fd) {}
void nvdisp_disp0::OnOpen(NvCore::SessionId session_id, DeviceFD fd) {}
void nvdisp_disp0::OnClose(DeviceFD fd) {}
void nvdisp_disp0::flip(u32 buffer_handle, u32 offset, android::PixelFormat format, u32 width,

View File

@ -32,7 +32,7 @@ public:
NvResult Ioctl3(DeviceFD fd, Ioctl command, std::span<const u8> input, std::span<u8> output,
std::span<u8> inline_output) override;
void OnOpen(size_t session_id, DeviceFD fd) override;
void OnOpen(NvCore::SessionId session_id, DeviceFD fd) override;
void OnClose(DeviceFD fd) override;
/// Performs a screen flip, drawing the buffer pointed to by the handle.

View File

@ -86,7 +86,7 @@ NvResult nvhost_as_gpu::Ioctl3(DeviceFD fd, Ioctl command, std::span<const u8> i
return NvResult::NotImplemented;
}
void nvhost_as_gpu::OnOpen(size_t session_id, DeviceFD fd) {}
void nvhost_as_gpu::OnOpen(NvCore::SessionId session_id, DeviceFD fd) {}
void nvhost_as_gpu::OnClose(DeviceFD fd) {}
NvResult nvhost_as_gpu::AllocAsEx(IoctlAllocAsEx& params) {

View File

@ -55,7 +55,7 @@ public:
NvResult Ioctl3(DeviceFD fd, Ioctl command, std::span<const u8> input, std::span<u8> output,
std::span<u8> inline_output) override;
void OnOpen(size_t session_id, DeviceFD fd) override;
void OnOpen(NvCore::SessionId session_id, DeviceFD fd) override;
void OnClose(DeviceFD fd) override;
Kernel::KEvent* QueryEvent(u32 event_id) override;

View File

@ -76,7 +76,7 @@ NvResult nvhost_ctrl::Ioctl3(DeviceFD fd, Ioctl command, std::span<const u8> inp
return NvResult::NotImplemented;
}
void nvhost_ctrl::OnOpen(size_t session_id, DeviceFD fd) {}
void nvhost_ctrl::OnOpen(NvCore::SessionId session_id, DeviceFD fd) {}
void nvhost_ctrl::OnClose(DeviceFD fd) {}

View File

@ -32,7 +32,7 @@ public:
NvResult Ioctl3(DeviceFD fd, Ioctl command, std::span<const u8> input, std::span<u8> output,
std::span<u8> inline_output) override;
void OnOpen(size_t session_id, DeviceFD fd) override;
void OnOpen(NvCore::SessionId session_id, DeviceFD fd) override;
void OnClose(DeviceFD fd) override;
Kernel::KEvent* QueryEvent(u32 event_id) override;

View File

@ -82,7 +82,7 @@ NvResult nvhost_ctrl_gpu::Ioctl3(DeviceFD fd, Ioctl command, std::span<const u8>
return NvResult::NotImplemented;
}
void nvhost_ctrl_gpu::OnOpen(size_t session_id, DeviceFD fd) {}
void nvhost_ctrl_gpu::OnOpen(NvCore::SessionId session_id, DeviceFD fd) {}
void nvhost_ctrl_gpu::OnClose(DeviceFD fd) {}
NvResult nvhost_ctrl_gpu::GetCharacteristics1(IoctlCharacteristics& params) {

View File

@ -28,7 +28,7 @@ public:
NvResult Ioctl3(DeviceFD fd, Ioctl command, std::span<const u8> input, std::span<u8> output,
std::span<u8> inline_output) override;
void OnOpen(size_t session_id, DeviceFD fd) override;
void OnOpen(NvCore::SessionId session_id, DeviceFD fd) override;
void OnClose(DeviceFD fd) override;
Kernel::KEvent* QueryEvent(u32 event_id) override;

View File

@ -120,7 +120,7 @@ NvResult nvhost_gpu::Ioctl3(DeviceFD fd, Ioctl command, std::span<const u8> inpu
return NvResult::NotImplemented;
}
void nvhost_gpu::OnOpen(size_t session_id, DeviceFD fd) {}
void nvhost_gpu::OnOpen(NvCore::SessionId session_id, DeviceFD fd) {}
void nvhost_gpu::OnClose(DeviceFD fd) {}
NvResult nvhost_gpu::SetNVMAPfd(IoctlSetNvmapFD& params) {

View File

@ -47,7 +47,7 @@ public:
NvResult Ioctl3(DeviceFD fd, Ioctl command, std::span<const u8> input, std::span<u8> output,
std::span<u8> inline_output) override;
void OnOpen(size_t session_id, DeviceFD fd) override;
void OnOpen(NvCore::SessionId session_id, DeviceFD fd) override;
void OnClose(DeviceFD fd) override;
Kernel::KEvent* QueryEvent(u32 event_id) override;

View File

@ -68,7 +68,7 @@ NvResult nvhost_nvdec::Ioctl3(DeviceFD fd, Ioctl command, std::span<const u8> in
return NvResult::NotImplemented;
}
void nvhost_nvdec::OnOpen(size_t session_id, DeviceFD fd) {
void nvhost_nvdec::OnOpen(NvCore::SessionId session_id, DeviceFD fd) {
LOG_INFO(Service_NVDRV, "NVDEC video stream started");
system.SetNVDECActive(true);
sessions[fd] = session_id;

View File

@ -20,7 +20,7 @@ public:
NvResult Ioctl3(DeviceFD fd, Ioctl command, std::span<const u8> input, std::span<u8> output,
std::span<u8> inline_output) override;
void OnOpen(size_t session_id, DeviceFD fd) override;
void OnOpen(NvCore::SessionId session_id, DeviceFD fd) override;
void OnClose(DeviceFD fd) override;
};

View File

@ -127,7 +127,7 @@ protected:
NvCore::NvMap& nvmap;
NvCore::ChannelType channel_type;
std::array<u32, MaxSyncPoints> device_syncpoints{};
std::unordered_map<DeviceFD, size_t> sessions;
std::unordered_map<DeviceFD, NvCore::SessionId> sessions;
};
}; // namespace Devices
} // namespace Service::Nvidia

View File

@ -44,7 +44,7 @@ NvResult nvhost_nvjpg::Ioctl3(DeviceFD fd, Ioctl command, std::span<const u8> in
return NvResult::NotImplemented;
}
void nvhost_nvjpg::OnOpen(size_t session_id, DeviceFD fd) {}
void nvhost_nvjpg::OnOpen(NvCore::SessionId session_id, DeviceFD fd) {}
void nvhost_nvjpg::OnClose(DeviceFD fd) {}
NvResult nvhost_nvjpg::SetNVMAPfd(IoctlSetNvmapFD& params) {

View File

@ -22,7 +22,7 @@ public:
NvResult Ioctl3(DeviceFD fd, Ioctl command, std::span<const u8> input, std::span<u8> output,
std::span<u8> inline_output) override;
void OnOpen(size_t session_id, DeviceFD fd) override;
void OnOpen(NvCore::SessionId session_id, DeviceFD fd) override;
void OnClose(DeviceFD fd) override;
private:

View File

@ -68,7 +68,7 @@ NvResult nvhost_vic::Ioctl3(DeviceFD fd, Ioctl command, std::span<const u8> inpu
return NvResult::NotImplemented;
}
void nvhost_vic::OnOpen(size_t session_id, DeviceFD fd) {
void nvhost_vic::OnOpen(NvCore::SessionId session_id, DeviceFD fd) {
sessions[fd] = session_id;
}
@ -78,10 +78,7 @@ void nvhost_vic::OnClose(DeviceFD fd) {
if (iter != host1x_file.fd_to_id.end()) {
system.GPU().ClearCdmaInstance(iter->second);
}
auto it = sessions.find(fd);
if (it != sessions.end()) {
sessions.erase(it);
}
sessions.erase(fd);
}
} // namespace Service::Nvidia::Devices

View File

@ -19,7 +19,7 @@ public:
NvResult Ioctl3(DeviceFD fd, Ioctl command, std::span<const u8> input, std::span<u8> output,
std::span<u8> inline_output) override;
void OnOpen(size_t session_id, DeviceFD fd) override;
void OnOpen(NvCore::SessionId session_id, DeviceFD fd) override;
void OnClose(DeviceFD fd) override;
};
} // namespace Service::Nvidia::Devices

View File

@ -67,7 +67,7 @@ NvResult nvmap::Ioctl3(DeviceFD fd, Ioctl command, std::span<const u8> input, st
return NvResult::NotImplemented;
}
void nvmap::OnOpen(size_t session_id, DeviceFD fd) {
void nvmap::OnOpen(NvCore::SessionId session_id, DeviceFD fd) {
sessions[fd] = session_id;
}
void nvmap::OnClose(DeviceFD fd) {

View File

@ -33,7 +33,7 @@ public:
NvResult Ioctl3(DeviceFD fd, Ioctl command, std::span<const u8> input, std::span<u8> output,
std::span<u8> inline_output) override;
void OnOpen(size_t session_id, DeviceFD fd) override;
void OnOpen(NvCore::SessionId session_id, DeviceFD fd) override;
void OnClose(DeviceFD fd) override;
enum class HandleParameterType : u32_le {
@ -115,7 +115,7 @@ private:
NvCore::Container& container;
NvCore::NvMap& file;
std::unordered_map<DeviceFD, size_t> sessions;
std::unordered_map<DeviceFD, NvCore::SessionId> sessions;
};
} // namespace Service::Nvidia::Devices

View File

@ -52,15 +52,15 @@ void LoopProcess(Nvnflinger::Nvnflinger& nvnflinger, Core::System& system) {
return std::make_shared<NVDRV>(system, module, "nvdrv:a");
};
const auto NvdrvInterfaceFactoryForSysmodules = [&, module] {
return std::make_shared<NVDRV>(system, module, "nvdrv:a");
return std::make_shared<NVDRV>(system, module, "nvdrv:s");
};
const auto NvdrvInterfaceFactory = [&, module] {
const auto NvdrvInterfaceFactoryForTesting = [&, module] {
return std::make_shared<NVDRV>(system, module, "nvdrv:t");
};
server_manager->RegisterNamedService("nvdrv", NvdrvInterfaceFactoryForApplication);
server_manager->RegisterNamedService("nvdrv:a", NvdrvInterfaceFactoryForApplets);
server_manager->RegisterNamedService("nvdrv:s", NvdrvInterfaceFactoryForSysmodules);
server_manager->RegisterNamedService("nvdrv:t", NvdrvInterfaceFactory);
server_manager->RegisterNamedService("nvdrv:t", NvdrvInterfaceFactoryForTesting);
server_manager->RegisterNamedService("nvmemp", std::make_shared<NVMEMP>(system));
nvnflinger.SetNVDrvInstance(module);
ServerManager::RunServer(std::move(server_manager));
@ -122,7 +122,7 @@ NvResult Module::VerifyFD(DeviceFD fd) const {
return NvResult::Success;
}
DeviceFD Module::Open(const std::string& device_name, size_t session_id) {
DeviceFD Module::Open(const std::string& device_name, NvCore::SessionId session_id) {
auto it = builders.find(device_name);
if (it == builders.end()) {
LOG_ERROR(Service_NVDRV, "Trying to open unknown device {}", device_name);

View File

@ -77,7 +77,7 @@ public:
NvResult VerifyFD(DeviceFD fd) const;
/// Opens a device node and returns a file descriptor to it.
DeviceFD Open(const std::string& device_name, size_t session_id);
DeviceFD Open(const std::string& device_name, NvCore::SessionId session_id);
/// Sends an ioctl command to the specified file descriptor.
NvResult Ioctl1(DeviceFD fd, Ioctl command, std::span<const u8> input, std::span<u8> output);

View File

@ -35,7 +35,7 @@ private:
u64 pid{};
bool is_initialized{};
size_t session_id{};
NvCore::SessionId session_id{};
Common::ScratchBuffer<u8> output_buffer;
Common::ScratchBuffer<u8> inline_output_buffer;
};

View File

@ -4,6 +4,7 @@
#pragma once
#include "common/math_util.h"
#include "core/hle/service/nvdrv/core/container.h"
#include "core/hle/service/nvdrv/nvdata.h"
#include "core/hle/service/nvnflinger/nvnflinger.h"
#include "core/hle/service/nvnflinger/ui/fence.h"
@ -55,7 +56,7 @@ private:
u32 m_buffer_nvmap_handle = 0;
SharedMemoryPoolLayout m_pool_layout = {};
Nvidia::DeviceFD m_nvmap_fd = {};
size_t m_session_id = {};
Nvidia::NvCore::SessionId m_session_id = {};
std::unique_ptr<Kernel::KPageGroup> m_buffer_page_group;
std::mutex m_guard;

View File

@ -126,7 +126,7 @@ void Nvnflinger::ShutdownLayers() {
void Nvnflinger::SetNVDrvInstance(std::shared_ptr<Nvidia::Module> instance) {
nvdrv = std::move(instance);
disp_fd = nvdrv->Open("/dev/nvdisp_disp0", 0);
disp_fd = nvdrv->Open("/dev/nvdisp_disp0", {});
}
std::optional<u64> Nvnflinger::OpenDisplay(std::string_view name) {

View File

@ -19,8 +19,54 @@
#include "core/arm/nce/patcher.h"
#endif
#ifndef HAS_NCE
namespace Core::NCE {
class Patcher {};
} // namespace Core::NCE
#endif
namespace Loader {
struct PatchCollection {
explicit PatchCollection(bool is_application_) : is_application{is_application_} {
module_patcher_indices.fill(-1);
patchers.emplace_back();
}
std::vector<Core::NCE::Patcher>* GetPatchers() {
if (is_application && Settings::IsNceEnabled()) {
return &patchers;
}
return nullptr;
}
size_t GetTotalPatchSize() const {
size_t total_size{};
#ifdef HAS_NCE
for (auto& patcher : patchers) {
total_size += patcher.GetSectionSize();
}
#endif
return total_size;
}
void SaveIndex(size_t module) {
module_patcher_indices[module] = static_cast<s32>(patchers.size() - 1);
}
s32 GetIndex(size_t module) const {
return module_patcher_indices[module];
}
s32 GetLastIndex() const {
return static_cast<s32>(patchers.size()) - 1;
}
bool is_application;
std::vector<Core::NCE::Patcher> patchers;
std::array<s32, 13> module_patcher_indices{};
};
AppLoader_DeconstructedRomDirectory::AppLoader_DeconstructedRomDirectory(FileSys::VirtualFile file_,
bool override_update_)
: AppLoader(std::move(file_)), override_update(override_update_), is_hbl(false) {
@ -142,18 +188,7 @@ AppLoader_DeconstructedRomDirectory::LoadResult AppLoader_DeconstructedRomDirect
std::size_t code_size{};
// Define an nce patch context for each potential module.
#ifdef HAS_NCE
std::array<Core::NCE::Patcher, 13> module_patchers;
#endif
const auto GetPatcher = [&](size_t i) -> Core::NCE::Patcher* {
#ifdef HAS_NCE
if (is_application && Settings::IsNceEnabled()) {
return &module_patchers[i];
}
#endif
return nullptr;
};
PatchCollection patch_ctx{is_application};
// Use the NSO module loader to figure out the code layout
for (size_t i = 0; i < static_modules.size(); i++) {
@ -164,13 +199,14 @@ AppLoader_DeconstructedRomDirectory::LoadResult AppLoader_DeconstructedRomDirect
}
const bool should_pass_arguments = std::strcmp(module, "rtld") == 0;
const auto tentative_next_load_addr =
AppLoader_NSO::LoadModule(process, system, *module_file, code_size,
should_pass_arguments, false, {}, GetPatcher(i));
const auto tentative_next_load_addr = AppLoader_NSO::LoadModule(
process, system, *module_file, code_size, should_pass_arguments, false, {},
patch_ctx.GetPatchers(), patch_ctx.GetLastIndex());
if (!tentative_next_load_addr) {
return {ResultStatus::ErrorLoadingNSO, {}};
}
patch_ctx.SaveIndex(i);
code_size = *tentative_next_load_addr;
}
@ -184,6 +220,9 @@ AppLoader_DeconstructedRomDirectory::LoadResult AppLoader_DeconstructedRomDirect
return 0;
}();
// Add patch size to the total module size
code_size += patch_ctx.GetTotalPatchSize();
// Setup the process code layout
if (process.LoadFromMetadata(metadata, code_size, fastmem_base, is_hbl).IsError()) {
return {ResultStatus::ErrorUnableToParseKernelMetadata, {}};
@ -204,9 +243,9 @@ AppLoader_DeconstructedRomDirectory::LoadResult AppLoader_DeconstructedRomDirect
const VAddr load_addr{next_load_addr};
const bool should_pass_arguments = std::strcmp(module, "rtld") == 0;
const auto tentative_next_load_addr =
AppLoader_NSO::LoadModule(process, system, *module_file, load_addr,
should_pass_arguments, true, pm, GetPatcher(i));
const auto tentative_next_load_addr = AppLoader_NSO::LoadModule(
process, system, *module_file, load_addr, should_pass_arguments, true, pm,
patch_ctx.GetPatchers(), patch_ctx.GetIndex(i));
if (!tentative_next_load_addr) {
return {ResultStatus::ErrorLoadingNSO, {}};
}

View File

@ -275,12 +275,12 @@ AppLoader_NRO::LoadResult AppLoader_NRO::Load(Kernel::KProcess& process, Core::S
return {ResultStatus::ErrorLoadingNRO, {}};
}
if (romfs != nullptr) {
system.GetFileSystemController().RegisterProcess(
process.GetProcessId(), {},
std::make_unique<FileSys::RomFSFactory>(*this, system.GetContentProvider(),
system.GetFileSystemController()));
}
u64 program_id{};
ReadProgramId(program_id);
system.GetFileSystemController().RegisterProcess(
process.GetProcessId(), program_id,
std::make_unique<FileSys::RomFSFactory>(*this, system.GetContentProvider(),
system.GetFileSystemController()));
is_loaded = true;
return {ResultStatus::Success, LoadParameters{Kernel::KThread::DefaultThreadPriority,

View File

@ -77,7 +77,8 @@ std::optional<VAddr> AppLoader_NSO::LoadModule(Kernel::KProcess& process, Core::
const FileSys::VfsFile& nso_file, VAddr load_base,
bool should_pass_arguments, bool load_into_process,
std::optional<FileSys::PatchManager> pm,
Core::NCE::Patcher* patch) {
std::vector<Core::NCE::Patcher>* patches,
s32 patch_index) {
if (nso_file.GetSize() < sizeof(NSOHeader)) {
return std::nullopt;
}
@ -94,8 +95,11 @@ std::optional<VAddr> AppLoader_NSO::LoadModule(Kernel::KProcess& process, Core::
// Allocate some space at the beginning if we are patching in PreText mode.
const size_t module_start = [&]() -> size_t {
#ifdef HAS_NCE
if (patch && patch->GetPatchMode() == Core::NCE::PatchMode::PreText) {
return patch->GetSectionSize();
if (patches && load_into_process) {
auto* patch = &patches->operator[](patch_index);
if (patch->GetPatchMode() == Core::NCE::PatchMode::PreText) {
return patch->GetSectionSize();
}
}
#endif
return 0;
@ -160,27 +164,24 @@ std::optional<VAddr> AppLoader_NSO::LoadModule(Kernel::KProcess& process, Core::
#ifdef HAS_NCE
// If we are computing the process code layout and using nce backend, patch.
const auto& code = codeset.CodeSegment();
if (patch && patch->GetPatchMode() == Core::NCE::PatchMode::None) {
auto* patch = patches ? &patches->operator[](patch_index) : nullptr;
if (patch && !load_into_process) {
// Patch SVCs and MRS calls in the guest code
patch->PatchText(program_image, code);
// Add patch section size to the module size.
image_size += static_cast<u32>(patch->GetSectionSize());
while (!patch->PatchText(program_image, code)) {
patch = &patches->emplace_back();
}
} else if (patch) {
// Relocate code patch and copy to the program_image.
patch->RelocateAndCopy(load_base, code, program_image, &process.GetPostHandlers());
// Update patch section.
auto& patch_segment = codeset.PatchSegment();
patch_segment.addr =
patch->GetPatchMode() == Core::NCE::PatchMode::PreText ? 0 : image_size;
patch_segment.size = static_cast<u32>(patch->GetSectionSize());
// Add patch section size to the module size. In PreText mode image_size
// already contains the patch segment as part of module_start.
if (patch->GetPatchMode() == Core::NCE::PatchMode::PostData) {
image_size += patch_segment.size;
if (patch->RelocateAndCopy(load_base, code, program_image, &process.GetPostHandlers())) {
// Update patch section.
auto& patch_segment = codeset.PatchSegment();
patch_segment.addr =
patch->GetPatchMode() == Core::NCE::PatchMode::PreText ? 0 : image_size;
patch_segment.size = static_cast<u32>(patch->GetSectionSize());
}
// Refresh image_size to take account the patch section if it was added by RelocateAndCopy
image_size = static_cast<u32>(program_image.size());
}
#endif

View File

@ -93,7 +93,8 @@ public:
const FileSys::VfsFile& nso_file, VAddr load_base,
bool should_pass_arguments, bool load_into_process,
std::optional<FileSys::PatchManager> pm = {},
Core::NCE::Patcher* patch = nullptr);
std::vector<Core::NCE::Patcher>* patches = nullptr,
s32 patch_index = -1);
LoadResult Load(Kernel::KProcess& process, Core::System& system) override;

View File

@ -36,6 +36,30 @@ add_library(hid_core STATIC
irsensor/processor_base.h
irsensor/tera_plugin_processor.cpp
irsensor/tera_plugin_processor.h
resources/abstracted_pad/abstract_battery_handler.cpp
resources/abstracted_pad/abstract_battery_handler.h
resources/abstracted_pad/abstract_button_handler.cpp
resources/abstracted_pad/abstract_button_handler.h
resources/abstracted_pad/abstract_ir_sensor_handler.cpp
resources/abstracted_pad/abstract_ir_sensor_handler.h
resources/abstracted_pad/abstract_led_handler.cpp
resources/abstracted_pad/abstract_led_handler.h
resources/abstracted_pad/abstract_mcu_handler.cpp
resources/abstracted_pad/abstract_mcu_handler.h
resources/abstracted_pad/abstract_nfc_handler.cpp
resources/abstracted_pad/abstract_nfc_handler.h
resources/abstracted_pad/abstract_pad.cpp
resources/abstracted_pad/abstract_pad.h
resources/abstracted_pad/abstract_pad_holder.cpp
resources/abstracted_pad/abstract_pad_holder.h
resources/abstracted_pad/abstract_palma_handler.cpp
resources/abstracted_pad/abstract_palma_handler.h
resources/abstracted_pad/abstract_properties_handler.cpp
resources/abstracted_pad/abstract_properties_handler.h
resources/abstracted_pad/abstract_sixaxis_handler.cpp
resources/abstracted_pad/abstract_sixaxis_handler.h
resources/abstracted_pad/abstract_vibration_handler.cpp
resources/abstracted_pad/abstract_vibration_handler.h
resources/debug_pad/debug_pad.cpp
resources/debug_pad/debug_pad.h
resources/debug_pad/debug_pad_types.h
@ -56,6 +80,8 @@ add_library(hid_core STATIC
resources/npad/npad_resource.cpp
resources/npad/npad_resource.h
resources/npad/npad_types.h
resources/npad/npad_vibration.cpp
resources/npad/npad_vibration.h
resources/palma/palma.cpp
resources/palma/palma.h
resources/six_axis/console_six_axis.cpp
@ -78,6 +104,14 @@ add_library(hid_core STATIC
resources/touch_screen/touch_types.h
resources/unique_pad/unique_pad.cpp
resources/unique_pad/unique_pad.h
resources/vibration/gc_vibration_device.h
resources/vibration/gc_vibration_device.cpp
resources/vibration/n64_vibration_device.h
resources/vibration/n64_vibration_device.cpp
resources/vibration/vibration_base.h
resources/vibration/vibration_base.cpp
resources/vibration/vibration_device.h
resources/vibration/vibration_device.cpp
resources/applet_resource.cpp
resources/applet_resource.h
resources/controller_base.cpp

View File

@ -27,7 +27,7 @@ EmulatedController::~EmulatedController() = default;
NpadStyleIndex EmulatedController::MapSettingsTypeToNPad(Settings::ControllerType type) {
switch (type) {
case Settings::ControllerType::ProController:
return NpadStyleIndex::ProController;
return NpadStyleIndex::Fullkey;
case Settings::ControllerType::DualJoyconDetached:
return NpadStyleIndex::JoyconDual;
case Settings::ControllerType::LeftJoycon:
@ -49,13 +49,13 @@ NpadStyleIndex EmulatedController::MapSettingsTypeToNPad(Settings::ControllerTyp
case Settings::ControllerType::SegaGenesis:
return NpadStyleIndex::SegaGenesis;
default:
return NpadStyleIndex::ProController;
return NpadStyleIndex::Fullkey;
}
}
Settings::ControllerType EmulatedController::MapNPadToSettingsType(NpadStyleIndex type) {
switch (type) {
case NpadStyleIndex::ProController:
case NpadStyleIndex::Fullkey:
return Settings::ControllerType::ProController;
case NpadStyleIndex::JoyconDual:
return Settings::ControllerType::DualJoyconDetached;
@ -106,7 +106,7 @@ void EmulatedController::ReloadFromSettings() {
SetNpadStyleIndex(MapSettingsTypeToNPad(player.controller_type));
original_npad_type = npad_type;
} else {
SetNpadStyleIndex(NpadStyleIndex::ProController);
SetNpadStyleIndex(NpadStyleIndex::Fullkey);
original_npad_type = npad_type;
}
@ -509,11 +509,11 @@ void EmulatedController::ReloadInput() {
});
}
turbo_button_state = 0;
is_initalized = true;
is_initialized = true;
}
void EmulatedController::UnloadInput() {
is_initalized = false;
is_initialized = false;
for (auto& button : button_devices) {
button.reset();
}
@ -1073,7 +1073,7 @@ void EmulatedController::SetColors(const Common::Input::CallbackStatus& callback
.body = GetNpadColor(controller.color_values[index].body),
.button = GetNpadColor(controller.color_values[index].buttons),
};
if (npad_type == NpadStyleIndex::ProController) {
if (npad_type == NpadStyleIndex::Fullkey) {
controller.colors_state.left = {
.body = GetNpadColor(controller.color_values[index].left_grip),
.button = GetNpadColor(controller.color_values[index].buttons),
@ -1209,7 +1209,7 @@ void EmulatedController::SetNfc(const Common::Input::CallbackStatus& callback) {
}
bool EmulatedController::SetVibration(std::size_t device_index, VibrationValue vibration) {
if (!is_initalized) {
if (!is_initialized) {
return false;
}
if (device_index >= output_devices.size()) {
@ -1247,7 +1247,7 @@ bool EmulatedController::IsVibrationEnabled(std::size_t device_index) {
const auto player_index = Service::HID::NpadIdTypeToIndex(npad_id_type);
const auto& player = Settings::values.players.GetValue()[player_index];
if (!is_initalized) {
if (!is_initialized) {
return false;
}
@ -1270,7 +1270,7 @@ Common::Input::DriverResult EmulatedController::SetPollingMode(
EmulatedDeviceIndex device_index, Common::Input::PollingMode polling_mode) {
LOG_INFO(Service_HID, "Set polling mode {}, device_index={}", polling_mode, device_index);
if (!is_initalized) {
if (!is_initialized) {
return Common::Input::DriverResult::InvalidHandle;
}
@ -1319,7 +1319,7 @@ bool EmulatedController::SetCameraFormat(
Core::IrSensor::ImageTransferProcessorFormat camera_format) {
LOG_INFO(Service_HID, "Set camera format {}", camera_format);
if (!is_initalized) {
if (!is_initialized) {
return false;
}
@ -1347,7 +1347,7 @@ void EmulatedController::SetRingParam(Common::ParamPackage param) {
bool EmulatedController::HasNfc() const {
if (!is_initalized) {
if (!is_initialized) {
return false;
}
@ -1356,7 +1356,7 @@ bool EmulatedController::HasNfc() const {
switch (npad_type) {
case NpadStyleIndex::JoyconRight:
case NpadStyleIndex::JoyconDual:
case NpadStyleIndex::ProController:
case NpadStyleIndex::Fullkey:
case NpadStyleIndex::Handheld:
break;
default:
@ -1388,7 +1388,7 @@ bool EmulatedController::RemoveNfcHandle() {
}
bool EmulatedController::StartNfcPolling() {
if (!is_initalized) {
if (!is_initialized) {
return false;
}
@ -1403,7 +1403,7 @@ bool EmulatedController::StartNfcPolling() {
}
bool EmulatedController::StopNfcPolling() {
if (!is_initalized) {
if (!is_initialized) {
return false;
}
@ -1418,7 +1418,7 @@ bool EmulatedController::StopNfcPolling() {
}
bool EmulatedController::ReadAmiiboData(std::vector<u8>& data) {
if (!is_initalized) {
if (!is_initialized) {
return false;
}
@ -1434,7 +1434,7 @@ bool EmulatedController::ReadAmiiboData(std::vector<u8>& data) {
bool EmulatedController::ReadMifareData(const Common::Input::MifareRequest& request,
Common::Input::MifareRequest& out_data) {
if (!is_initalized) {
if (!is_initialized) {
return false;
}
@ -1450,7 +1450,7 @@ bool EmulatedController::ReadMifareData(const Common::Input::MifareRequest& requ
}
bool EmulatedController::WriteMifareData(const Common::Input::MifareRequest& request) {
if (!is_initalized) {
if (!is_initialized) {
return false;
}
@ -1465,7 +1465,7 @@ bool EmulatedController::WriteMifareData(const Common::Input::MifareRequest& req
}
bool EmulatedController::WriteNfc(const std::vector<u8>& data) {
if (!is_initalized) {
if (!is_initialized) {
return false;
}
@ -1480,7 +1480,7 @@ bool EmulatedController::WriteNfc(const std::vector<u8>& data) {
}
void EmulatedController::SetLedPattern() {
if (!is_initalized) {
if (!is_initialized) {
return;
}
@ -1508,8 +1508,8 @@ void EmulatedController::SetGyroscopeZeroDriftMode(GyroscopeZeroDriftMode mode)
motion.emulated.SetGyroThreshold(motion.emulated.ThresholdLoose);
break;
case GyroscopeZeroDriftMode::Tight:
motion_sensitivity = motion.emulated.IsAtRestThight;
motion.emulated.SetGyroThreshold(motion.emulated.ThresholdThight);
motion_sensitivity = motion.emulated.IsAtRestTight;
motion.emulated.SetGyroThreshold(motion.emulated.ThresholdTight);
break;
case GyroscopeZeroDriftMode::Standard:
default:
@ -1548,7 +1548,7 @@ void EmulatedController::SetSupportedNpadStyleTag(NpadStyleTag supported_styles)
// Fallback Fullkey controllers to Pro controllers
if (IsControllerFullkey() && supported_style_tag.fullkey) {
LOG_WARNING(Service_HID, "Reconnecting controller type {} as Pro controller", npad_type);
SetNpadStyleIndex(NpadStyleIndex::ProController);
SetNpadStyleIndex(NpadStyleIndex::Fullkey);
Connect();
return;
}
@ -1556,13 +1556,13 @@ void EmulatedController::SetSupportedNpadStyleTag(NpadStyleTag supported_styles)
// Fallback Dual joycon controllers to Pro controllers
if (npad_type == NpadStyleIndex::JoyconDual && supported_style_tag.fullkey) {
LOG_WARNING(Service_HID, "Reconnecting controller type {} as Pro controller", npad_type);
SetNpadStyleIndex(NpadStyleIndex::ProController);
SetNpadStyleIndex(NpadStyleIndex::Fullkey);
Connect();
return;
}
// Fallback Pro controllers to Dual joycon
if (npad_type == NpadStyleIndex::ProController && supported_style_tag.joycon_dual) {
if (npad_type == NpadStyleIndex::Fullkey && supported_style_tag.joycon_dual) {
LOG_WARNING(Service_HID, "Reconnecting controller type {} as Dual Joycons", npad_type);
SetNpadStyleIndex(NpadStyleIndex::JoyconDual);
Connect();
@ -1577,7 +1577,7 @@ bool EmulatedController::IsControllerFullkey(bool use_temporary_value) const {
std::scoped_lock lock{mutex};
const auto type = is_configuring && use_temporary_value ? tmp_npad_type : npad_type;
switch (type) {
case NpadStyleIndex::ProController:
case NpadStyleIndex::Fullkey:
case NpadStyleIndex::GameCube:
case NpadStyleIndex::NES:
case NpadStyleIndex::SNES:
@ -1593,7 +1593,7 @@ bool EmulatedController::IsControllerSupported(bool use_temporary_value) const {
std::scoped_lock lock{mutex};
const auto type = is_configuring && use_temporary_value ? tmp_npad_type : npad_type;
switch (type) {
case NpadStyleIndex::ProController:
case NpadStyleIndex::Fullkey:
return supported_style_tag.fullkey.As<bool>();
case NpadStyleIndex::Handheld:
return supported_style_tag.handheld.As<bool>();

View File

@ -559,7 +559,7 @@ private:
NpadStyleTag supported_style_tag{NpadStyleSet::All};
bool is_connected{false};
bool is_configuring{false};
bool is_initalized{false};
bool is_initialized{false};
bool system_buttons_enabled{true};
f32 motion_sensitivity{Core::HID::MotionInput::IsAtRestStandard};
u32 turbo_button_state{0};

View File

@ -13,12 +13,12 @@ class MotionInput {
public:
static constexpr float ThresholdLoose = 0.01f;
static constexpr float ThresholdStandard = 0.007f;
static constexpr float ThresholdThight = 0.002f;
static constexpr float ThresholdTight = 0.002f;
static constexpr float IsAtRestRelaxed = 0.05f;
static constexpr float IsAtRestLoose = 0.02f;
static constexpr float IsAtRestStandard = 0.01f;
static constexpr float IsAtRestThight = 0.005f;
static constexpr float IsAtRestTight = 0.005f;
static constexpr float GyroMaxValue = 5.0f;
static constexpr float AccelMaxValue = 7.0f;

View File

@ -15,7 +15,7 @@ constexpr Result ResultVibrationNotInitialized{ErrorModule::HID, 121};
constexpr Result ResultVibrationInvalidStyleIndex{ErrorModule::HID, 122};
constexpr Result ResultVibrationInvalidNpadId{ErrorModule::HID, 123};
constexpr Result ResultVibrationDeviceIndexOutOfRange{ErrorModule::HID, 124};
constexpr Result ResultVibrationStrenghtOutOfRange{ErrorModule::HID, 126};
constexpr Result ResultVibrationStrengthOutOfRange{ErrorModule::HID, 126};
constexpr Result ResultVibrationArraySizeMismatch{ErrorModule::HID, 131};
constexpr Result InvalidSixAxisFusionRange{ErrorModule::HID, 423};

View File

@ -220,6 +220,7 @@ enum class NpadIdType : u32 {
};
enum class NpadInterfaceType : u8 {
None = 0,
Bluetooth = 1,
Rail = 2,
Usb = 3,
@ -229,7 +230,7 @@ enum class NpadInterfaceType : u8 {
// This is nn::hid::NpadStyleIndex
enum class NpadStyleIndex : u8 {
None = 0,
ProController = 3,
Fullkey = 3,
Handheld = 4,
HandheldNES = 4,
JoyconDual = 5,

View File

@ -42,7 +42,7 @@ constexpr Result IsSixaxisHandleValid(const Core::HID::SixAxisSensorHandle& hand
constexpr Result IsVibrationHandleValid(const Core::HID::VibrationDeviceHandle& handle) {
switch (handle.npad_type) {
case Core::HID::NpadStyleIndex::ProController:
case Core::HID::NpadStyleIndex::Fullkey:
case Core::HID::NpadStyleIndex::Handheld:
case Core::HID::NpadStyleIndex::JoyconDual:
case Core::HID::NpadStyleIndex::JoyconLeft:

View File

@ -106,8 +106,8 @@ enum class HandAnalysisMode : u32 {
None,
Silhouette,
Image,
SilhoueteAndImage,
SilhuetteOnly,
SilhouetteAndImage,
SilhouetteOnly,
};
// This is nn::irsensor::IrSensorFunctionLevel

View File

@ -0,0 +1,197 @@
// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later
#include "core/core_timing.h"
#include "hid_core/hid_result.h"
#include "hid_core/hid_util.h"
#include "hid_core/resources/abstracted_pad/abstract_battery_handler.h"
#include "hid_core/resources/abstracted_pad/abstract_pad_holder.h"
#include "hid_core/resources/abstracted_pad/abstract_properties_handler.h"
#include "hid_core/resources/applet_resource.h"
#include "hid_core/resources/npad/npad_types.h"
#include "hid_core/resources/shared_memory_format.h"
namespace Service::HID {
NpadAbstractBatteryHandler::NpadAbstractBatteryHandler() {}
NpadAbstractBatteryHandler::~NpadAbstractBatteryHandler() = default;
void NpadAbstractBatteryHandler::SetAbstractPadHolder(NpadAbstractedPadHolder* holder) {
abstract_pad_holder = holder;
}
void NpadAbstractBatteryHandler::SetAppletResource(AppletResourceHolder* applet_resource) {
applet_resource_holder = applet_resource;
}
void NpadAbstractBatteryHandler::SetPropertiesHandler(NpadAbstractPropertiesHandler* handler) {
properties_handler = handler;
}
Result NpadAbstractBatteryHandler::IncrementRefCounter() {
if (ref_counter == std::numeric_limits<s32>::max() - 1) {
return ResultNpadHandlerOverflow;
}
ref_counter++;
return ResultSuccess;
}
Result NpadAbstractBatteryHandler::DecrementRefCounter() {
if (ref_counter == 0) {
return ResultNpadHandlerNotInitialized;
}
ref_counter--;
return ResultSuccess;
}
Result NpadAbstractBatteryHandler::UpdateBatteryState(u64 aruid) {
const auto npad_index = NpadIdTypeToIndex(properties_handler->GetNpadId());
AruidData* aruid_data = applet_resource_holder->applet_resource->GetAruidData(aruid);
if (aruid_data == nullptr) {
return ResultSuccess;
}
auto& npad_internal_state =
aruid_data->shared_memory_format->npad.npad_entry[npad_index].internal_state;
auto& system_properties = npad_internal_state.system_properties;
system_properties.is_charging_joy_dual.Assign(dual_battery.is_charging);
system_properties.is_powered_joy_dual.Assign(dual_battery.is_powered);
system_properties.is_charging_joy_left.Assign(left_battery.is_charging);
system_properties.is_powered_joy_left.Assign(left_battery.is_powered);
system_properties.is_charging_joy_right.Assign(right_battery.is_charging);
system_properties.is_powered_joy_right.Assign(right_battery.is_powered);
npad_internal_state.battery_level_dual = dual_battery.battery_level;
npad_internal_state.battery_level_left = left_battery.battery_level;
npad_internal_state.battery_level_right = right_battery.battery_level;
return ResultSuccess;
}
void NpadAbstractBatteryHandler::UpdateBatteryState() {
if (ref_counter == 0) {
return;
}
has_new_battery_data = GetNewBatteryState();
}
bool NpadAbstractBatteryHandler::GetNewBatteryState() {
bool has_changed = false;
Core::HID::NpadPowerInfo new_dual_battery_state{};
Core::HID::NpadPowerInfo new_left_battery_state{};
Core::HID::NpadPowerInfo new_right_battery_state{};
std::array<IAbstractedPad*, 5> abstract_pads{};
const std::size_t count = abstract_pad_holder->GetAbstractedPads(abstract_pads);
for (std::size_t i = 0; i < count; i++) {
auto* abstract_pad = abstract_pads[i];
if (!abstract_pad->internal_flags.is_connected) {
continue;
}
const auto power_info = abstract_pad->power_info;
if (power_info.battery_level > Core::HID::NpadBatteryLevel::Full) {
// Abort
continue;
}
const auto style = abstract_pad->assignment_style;
if (style.is_external_assigned || style.is_handheld_assigned) {
new_dual_battery_state = power_info;
}
if (style.is_external_left_assigned || style.is_handheld_left_assigned) {
new_left_battery_state = power_info;
}
if (style.is_external_right_assigned || style.is_handheld_right_assigned) {
new_right_battery_state = power_info;
}
if (abstract_pad->internal_flags.is_battery_low_ovln_required) {
if (abstract_pad->interface_type == Core::HID::NpadInterfaceType::Rail) {
// TODO
}
abstract_pad->internal_flags.is_battery_low_ovln_required.Assign(false);
}
}
if (dual_battery.battery_level != new_dual_battery_state.battery_level ||
dual_battery.is_charging != new_dual_battery_state.is_charging ||
dual_battery.is_powered != new_dual_battery_state.is_powered) {
has_changed = true;
dual_battery = new_dual_battery_state;
}
if (left_battery.battery_level != new_left_battery_state.battery_level ||
left_battery.is_charging != new_left_battery_state.is_charging ||
left_battery.is_powered != new_left_battery_state.is_powered) {
has_changed = true;
left_battery = new_left_battery_state;
}
if (right_battery.battery_level != new_right_battery_state.battery_level ||
right_battery.is_charging != new_right_battery_state.is_charging ||
right_battery.is_powered != new_right_battery_state.is_powered) {
has_changed = true;
right_battery = new_right_battery_state;
}
return has_changed;
}
void NpadAbstractBatteryHandler::UpdateCoreBatteryState() {
if (ref_counter == 0) {
return;
}
if (!has_new_battery_data) {
return;
}
UpdateBatteryState(0);
}
void NpadAbstractBatteryHandler::InitializeBatteryState(u64 aruid) {
UpdateBatteryState(aruid);
}
bool NpadAbstractBatteryHandler::HasBattery() const {
std::array<IAbstractedPad*, 5> abstract_pads{};
const std::size_t count = abstract_pad_holder->GetAbstractedPads(abstract_pads);
for (std::size_t i = 0; i < count; i++) {
const auto* abstract_pad = abstract_pads[i];
if (!abstract_pad->internal_flags.is_connected) {
continue;
}
return abstract_pad->disabled_feature_set.has_fullkey_battery ||
abstract_pad->disabled_feature_set.has_left_right_joy_battery;
}
return false;
}
void NpadAbstractBatteryHandler::HasLeftRightBattery(bool& has_left, bool& has_right) const {
std::array<IAbstractedPad*, 5> abstract_pads{};
const std::size_t count = abstract_pad_holder->GetAbstractedPads(abstract_pads);
has_left = false;
has_right = false;
for (std::size_t i = 0; i < count; i++) {
const auto* abstract_pad = abstract_pads[i];
if (!abstract_pad->internal_flags.is_connected) {
continue;
}
if (!abstract_pad->disabled_feature_set.has_fullkey_battery &&
!abstract_pad->disabled_feature_set.has_left_right_joy_battery) {
continue;
}
has_left = abstract_pad->assignment_style.is_external_left_assigned ||
abstract_pad->assignment_style.is_handheld_left_assigned;
has_right = abstract_pad->assignment_style.is_external_right_assigned ||
abstract_pad->assignment_style.is_handheld_right_assigned;
}
}
} // namespace Service::HID

View File

@ -0,0 +1,49 @@
// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include "common/common_types.h"
#include "core/hle/result.h"
#include "hid_core/hid_types.h"
namespace Service::HID {
struct AppletResourceHolder;
class NpadAbstractedPadHolder;
class NpadAbstractPropertiesHandler;
/// Handles Npad request from HID interfaces
class NpadAbstractBatteryHandler final {
public:
explicit NpadAbstractBatteryHandler();
~NpadAbstractBatteryHandler();
void SetAbstractPadHolder(NpadAbstractedPadHolder* holder);
void SetAppletResource(AppletResourceHolder* applet_resource);
void SetPropertiesHandler(NpadAbstractPropertiesHandler* handler);
Result IncrementRefCounter();
Result DecrementRefCounter();
Result UpdateBatteryState(u64 aruid);
void UpdateBatteryState();
bool GetNewBatteryState();
void UpdateCoreBatteryState();
void InitializeBatteryState(u64 aruid);
bool HasBattery() const;
void HasLeftRightBattery(bool& has_left, bool& has_right) const;
private:
AppletResourceHolder* applet_resource_holder{nullptr};
NpadAbstractedPadHolder* abstract_pad_holder{nullptr};
NpadAbstractPropertiesHandler* properties_handler{nullptr};
s32 ref_counter{};
Core::HID::NpadPowerInfo dual_battery{};
Core::HID::NpadPowerInfo left_battery{};
Core::HID::NpadPowerInfo right_battery{};
bool has_new_battery_data{};
};
} // namespace Service::HID

View File

@ -0,0 +1,199 @@
// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later
#include "hid_core/hid_result.h"
#include "hid_core/hid_util.h"
#include "hid_core/resources/abstracted_pad/abstract_button_handler.h"
#include "hid_core/resources/abstracted_pad/abstract_pad_holder.h"
#include "hid_core/resources/abstracted_pad/abstract_properties_handler.h"
#include "hid_core/resources/applet_resource.h"
#include "hid_core/resources/npad/npad_resource.h"
#include "hid_core/resources/npad/npad_types.h"
#include "hid_core/resources/shared_memory_format.h"
namespace Service::HID {
NpadAbstractButtonHandler::NpadAbstractButtonHandler() {}
NpadAbstractButtonHandler::~NpadAbstractButtonHandler() = default;
void NpadAbstractButtonHandler::SetAbstractPadHolder(NpadAbstractedPadHolder* holder) {
abstract_pad_holder = holder;
}
void NpadAbstractButtonHandler::SetAppletResource(AppletResourceHolder* applet_resource) {
applet_resource_holder = applet_resource;
}
void NpadAbstractButtonHandler::SetPropertiesHandler(NpadAbstractPropertiesHandler* handler) {
properties_handler = handler;
}
Result NpadAbstractButtonHandler::IncrementRefCounter() {
if (ref_counter == std::numeric_limits<s32>::max() - 1) {
return ResultNpadHandlerOverflow;
}
ref_counter++;
return ResultSuccess;
}
Result NpadAbstractButtonHandler::DecrementRefCounter() {
if (ref_counter == 0) {
return ResultNpadHandlerNotInitialized;
}
ref_counter--;
return ResultSuccess;
}
Result NpadAbstractButtonHandler::UpdateAllButtonWithHomeProtection(u64 aruid) {
const Core::HID::NpadIdType npad_id = properties_handler->GetNpadId();
auto* data = applet_resource_holder->applet_resource->GetAruidData(aruid);
if (data == nullptr) {
return ResultSuccess;
}
auto& npad_entry = data->shared_memory_format->npad.npad_entry[NpadIdTypeToIndex(npad_id)];
UpdateButtonLifo(npad_entry, aruid);
bool is_home_button_protection_enabled{};
const auto result = applet_resource_holder->shared_npad_resource->GetHomeProtectionEnabled(
is_home_button_protection_enabled, aruid, npad_id);
if (result.IsError()) {
return ResultSuccess;
}
npad_entry.internal_state.button_properties.is_home_button_protection_enabled.Assign(
is_home_button_protection_enabled);
return ResultSuccess;
}
void NpadAbstractButtonHandler::UpdateAllButtonLifo() {
Core::HID::NpadIdType npad_id = properties_handler->GetNpadId();
for (std::size_t i = 0; i < AruidIndexMax; i++) {
auto* data = applet_resource_holder->applet_resource->GetAruidDataByIndex(i);
auto& npad_entry = data->shared_memory_format->npad.npad_entry[NpadIdTypeToIndex(npad_id)];
UpdateButtonLifo(npad_entry, data->aruid);
}
}
void NpadAbstractButtonHandler::UpdateCoreBatteryState() {
Core::HID::NpadIdType npad_id = properties_handler->GetNpadId();
for (std::size_t i = 0; i < AruidIndexMax; i++) {
auto* data = applet_resource_holder->applet_resource->GetAruidDataByIndex(i);
auto& npad_entry = data->shared_memory_format->npad.npad_entry[NpadIdTypeToIndex(npad_id)];
UpdateButtonLifo(npad_entry, data->aruid);
}
}
void NpadAbstractButtonHandler::UpdateButtonState(u64 aruid) {
Core::HID::NpadIdType npad_id = properties_handler->GetNpadId();
auto* data = applet_resource_holder->applet_resource->GetAruidData(aruid);
if (data == nullptr) {
return;
}
auto& npad_entry = data->shared_memory_format->npad.npad_entry[NpadIdTypeToIndex(npad_id)];
UpdateButtonLifo(npad_entry, aruid);
}
Result NpadAbstractButtonHandler::SetHomeProtection(bool is_enabled, u64 aruid) {
const Core::HID::NpadIdType npad_id = properties_handler->GetNpadId();
auto result = applet_resource_holder->shared_npad_resource->SetHomeProtectionEnabled(
aruid, npad_id, is_enabled);
if (result.IsError()) {
return result;
}
auto* data = applet_resource_holder->applet_resource->GetAruidData(aruid);
if (data == nullptr) {
return ResultSuccess;
}
bool is_home_protection_enabled{};
result = applet_resource_holder->shared_npad_resource->GetHomeProtectionEnabled(
is_home_protection_enabled, aruid, npad_id);
if (result.IsError()) {
return ResultSuccess;
}
auto& npad_entry = data->shared_memory_format->npad.npad_entry[NpadIdTypeToIndex(npad_id)];
npad_entry.internal_state.button_properties.is_home_button_protection_enabled.Assign(
is_home_protection_enabled);
return ResultSuccess;
}
bool NpadAbstractButtonHandler::IsButtonPressedOnConsoleMode() {
return is_button_pressed_on_console_mode;
}
void NpadAbstractButtonHandler::EnableCenterClamp() {
std::array<IAbstractedPad*, 5> abstract_pads{};
const std::size_t count = abstract_pad_holder->GetAbstractedPads(abstract_pads);
for (std::size_t i = 0; i < count; i++) {
auto* abstract_pad = abstract_pads[i];
if (!abstract_pad->internal_flags.is_connected) {
continue;
}
abstract_pad->internal_flags.use_center_clamp.Assign(true);
}
}
void NpadAbstractButtonHandler::UpdateButtonLifo(NpadSharedMemoryEntry& shared_memory, u64 aruid) {
auto* npad_resource = applet_resource_holder->shared_npad_resource;
Core::HID::NpadStyleTag style_tag = {properties_handler->GetStyleSet(aruid)};
style_tag.system_ext.Assign(npad_resource->GetActiveData()->GetNpadSystemExtState());
UpdateNpadFullkeyLifo(style_tag, 0, aruid, shared_memory);
UpdateHandheldLifo(style_tag, 1, aruid, shared_memory);
UpdateJoyconDualLifo(style_tag, 2, aruid, shared_memory);
UpdateJoyconLeftLifo(style_tag, 3, aruid, shared_memory);
UpdateJoyconRightLifo(style_tag, 4, aruid, shared_memory);
UpdatePalmaLifo(style_tag, 5, aruid, shared_memory);
UpdateSystemExtLifo(style_tag, 6, aruid, shared_memory);
}
void NpadAbstractButtonHandler::UpdateNpadFullkeyLifo(Core::HID::NpadStyleTag style_tag,
int style_index, u64 aruid,
NpadSharedMemoryEntry& shared_memory) {
// TODO
}
void NpadAbstractButtonHandler::UpdateHandheldLifo(Core::HID::NpadStyleTag style_tag,
int style_index, u64 aruid,
NpadSharedMemoryEntry& shared_memory) {
// TODO
}
void NpadAbstractButtonHandler::UpdateJoyconDualLifo(Core::HID::NpadStyleTag style_tag,
int style_index, u64 aruid,
NpadSharedMemoryEntry& shared_memory) {
// TODO
}
void NpadAbstractButtonHandler::UpdateJoyconLeftLifo(Core::HID::NpadStyleTag style_tag,
int style_index, u64 aruid,
NpadSharedMemoryEntry& shared_memory) {
// TODO
}
void NpadAbstractButtonHandler::UpdateJoyconRightLifo(Core::HID::NpadStyleTag style_tag,
int style_index, u64 aruid,
NpadSharedMemoryEntry& shared_memory) {
// TODO
}
void NpadAbstractButtonHandler::UpdateSystemExtLifo(Core::HID::NpadStyleTag style_tag,
int style_index, u64 aruid,
NpadSharedMemoryEntry& shared_memory) {
// TODO
}
void NpadAbstractButtonHandler::UpdatePalmaLifo(Core::HID::NpadStyleTag style_tag, int style_index,
u64 aruid, NpadSharedMemoryEntry& shared_memory) {
// TODO
}
} // namespace Service::HID

View File

@ -0,0 +1,75 @@
// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include "common/common_types.h"
#include "core/hle/result.h"
#include "hid_core/hid_types.h"
namespace Service::HID {
struct NpadSharedMemoryEntry;
struct AppletResourceHolder;
class NpadAbstractedPadHolder;
class NpadAbstractPropertiesHandler;
/// Handles Npad request from HID interfaces
class NpadAbstractButtonHandler final {
public:
explicit NpadAbstractButtonHandler();
~NpadAbstractButtonHandler();
void SetAbstractPadHolder(NpadAbstractedPadHolder* holder);
void SetAppletResource(AppletResourceHolder* applet_resource);
void SetPropertiesHandler(NpadAbstractPropertiesHandler* handler);
Result IncrementRefCounter();
Result DecrementRefCounter();
Result UpdateAllButtonWithHomeProtection(u64 aruid);
void UpdateAllButtonLifo();
void UpdateCoreBatteryState();
void UpdateButtonState(u64 aruid);
Result SetHomeProtection(bool is_enabled, u64 aruid);
bool IsButtonPressedOnConsoleMode();
void EnableCenterClamp();
void UpdateButtonLifo(NpadSharedMemoryEntry& shared_memory, u64 aruid);
void UpdateNpadFullkeyLifo(Core::HID::NpadStyleTag style_tag, int index, u64 aruid,
NpadSharedMemoryEntry& shared_memory);
void UpdateHandheldLifo(Core::HID::NpadStyleTag style_tag, int index, u64 aruid,
NpadSharedMemoryEntry& shared_memory);
void UpdateJoyconDualLifo(Core::HID::NpadStyleTag style_tag, int index, u64 aruid,
NpadSharedMemoryEntry& shared_memory);
void UpdateJoyconLeftLifo(Core::HID::NpadStyleTag style_tag, int index, u64 aruid,
NpadSharedMemoryEntry& shared_memory);
void UpdateJoyconRightLifo(Core::HID::NpadStyleTag style_tag, int index, u64 aruid,
NpadSharedMemoryEntry& shared_memory);
void UpdateSystemExtLifo(Core::HID::NpadStyleTag style_tag, int index, u64 aruid,
NpadSharedMemoryEntry& shared_memory);
void UpdatePalmaLifo(Core::HID::NpadStyleTag style_tag, int index, u64 aruid,
NpadSharedMemoryEntry& shared_memory);
private:
struct GcTrigger {
float left;
float right;
};
AppletResourceHolder* applet_resource_holder{nullptr};
NpadAbstractedPadHolder* abstract_pad_holder{nullptr};
NpadAbstractPropertiesHandler* properties_handler{nullptr};
s32 ref_counter{};
bool is_button_pressed_on_console_mode{};
u64 gc_sampling_number{};
GcTrigger gc_trigger_state{};
};
} // namespace Service::HID

View File

@ -0,0 +1,126 @@
// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later
#include "core/hle/kernel/k_event.h"
#include "core/hle/kernel/k_readable_event.h"
#include "hid_core/hid_result.h"
#include "hid_core/resources/abstracted_pad/abstract_ir_sensor_handler.h"
#include "hid_core/resources/abstracted_pad/abstract_pad_holder.h"
#include "hid_core/resources/abstracted_pad/abstract_properties_handler.h"
#include "hid_core/resources/npad/npad_types.h"
namespace Service::HID {
NpadAbstractIrSensorHandler::NpadAbstractIrSensorHandler() {}
NpadAbstractIrSensorHandler::~NpadAbstractIrSensorHandler() = default;
void NpadAbstractIrSensorHandler::SetAbstractPadHolder(NpadAbstractedPadHolder* holder) {
abstract_pad_holder = holder;
}
void NpadAbstractIrSensorHandler::SetPropertiesHandler(NpadAbstractPropertiesHandler* handler) {
properties_handler = handler;
}
Result NpadAbstractIrSensorHandler::IncrementRefCounter() {
if (ref_counter == std::numeric_limits<s32>::max() - 1) {
return ResultNpadHandlerOverflow;
}
ref_counter++;
return ResultSuccess;
}
Result NpadAbstractIrSensorHandler::DecrementRefCounter() {
if (ref_counter == 0) {
return ResultNpadHandlerNotInitialized;
}
ref_counter--;
return ResultSuccess;
}
void NpadAbstractIrSensorHandler::UpdateIrSensorState() {
const auto previous_state = sensor_state;
std::array<IAbstractedPad*, 5> abstract_pads{};
const std::size_t count = abstract_pad_holder->GetAbstractedPads(abstract_pads);
if (count == 0) {
sensor_state = NpadIrSensorState::Disabled;
if (sensor_state == previous_state) {
return;
}
ir_sensor_event->Signal();
return;
}
bool is_found{};
for (std::size_t i = 0; i < count; i++) {
auto* abstract_pad = abstract_pads[i];
if (!abstract_pad->internal_flags.is_connected) {
continue;
}
if (!abstract_pad->disabled_feature_set.has_bluetooth_address) {
continue;
}
is_found = true;
xcd_handle = abstract_pad->xcd_handle;
}
if (is_found) {
if (sensor_state == NpadIrSensorState::Active) {
return;
}
sensor_state = NpadIrSensorState::Available;
if (sensor_state == previous_state) {
return;
}
ir_sensor_event->Signal();
return;
}
sensor_state = NpadIrSensorState::Unavailable;
if (sensor_state == previous_state) {
return;
}
ir_sensor_event->Signal();
return;
}
Result NpadAbstractIrSensorHandler::ActivateIrSensor(bool is_enabled) {
if (sensor_state == NpadIrSensorState::Unavailable) {
return ResultIrSensorIsNotReady;
}
if (is_enabled && sensor_state == NpadIrSensorState::Available) {
sensor_state = NpadIrSensorState::Active;
} else {
if (is_enabled) {
return ResultSuccess;
}
if (sensor_state != NpadIrSensorState::Active) {
return ResultSuccess;
}
sensor_state = NpadIrSensorState::Available;
}
ir_sensor_event->Signal();
return ResultSuccess;
}
Result NpadAbstractIrSensorHandler::GetIrSensorEventHandle(Kernel::KReadableEvent** out_event) {
*out_event = &ir_sensor_event->GetReadableEvent();
return ResultSuccess;
}
Result NpadAbstractIrSensorHandler::GetXcdHandleForNpadWithIrSensor(u64& handle) const {
if (sensor_state < NpadIrSensorState::Available) {
return ResultIrSensorIsNotReady;
}
handle = xcd_handle;
return ResultSuccess;
}
NpadIrSensorState NpadAbstractIrSensorHandler::GetSensorState() const {
return sensor_state;
}
} // namespace Service::HID

View File

@ -0,0 +1,56 @@
// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include "common/common_types.h"
#include "core/hle/result.h"
#include "hid_core/hid_types.h"
namespace Kernel {
class KEvent;
class KReadableEvent;
} // namespace Kernel
enum class NpadIrSensorState : u32 {
Disabled,
Unavailable,
Available,
Active,
};
namespace Service::HID {
class NpadAbstractedPadHolder;
class NpadAbstractPropertiesHandler;
/// Handles Npad request from HID interfaces
class NpadAbstractIrSensorHandler final {
public:
explicit NpadAbstractIrSensorHandler();
~NpadAbstractIrSensorHandler();
void SetAbstractPadHolder(NpadAbstractedPadHolder* holder);
void SetPropertiesHandler(NpadAbstractPropertiesHandler* handler);
Result IncrementRefCounter();
Result DecrementRefCounter();
void UpdateIrSensorState();
Result ActivateIrSensor(bool param_2);
Result GetIrSensorEventHandle(Kernel::KReadableEvent** out_event);
Result GetXcdHandleForNpadWithIrSensor(u64& handle) const;
NpadIrSensorState GetSensorState() const;
private:
NpadAbstractedPadHolder* abstract_pad_holder{nullptr};
NpadAbstractPropertiesHandler* properties_handler{nullptr};
s32 ref_counter{};
Kernel::KEvent* ir_sensor_event{nullptr};
u64 xcd_handle{};
NpadIrSensorState sensor_state{};
};
} // namespace Service::HID

View File

@ -0,0 +1,123 @@
// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later
#include "core/core_timing.h"
#include "hid_core/hid_result.h"
#include "hid_core/hid_util.h"
#include "hid_core/resources/abstracted_pad/abstract_led_handler.h"
#include "hid_core/resources/abstracted_pad/abstract_pad_holder.h"
#include "hid_core/resources/abstracted_pad/abstract_properties_handler.h"
#include "hid_core/resources/applet_resource.h"
#include "hid_core/resources/npad/npad_types.h"
namespace Service::HID {
NpadAbstractLedHandler::NpadAbstractLedHandler() {}
NpadAbstractLedHandler::~NpadAbstractLedHandler() = default;
void NpadAbstractLedHandler::SetAbstractPadHolder(NpadAbstractedPadHolder* holder) {
abstract_pad_holder = holder;
}
void NpadAbstractLedHandler::SetAppletResource(AppletResourceHolder* applet_resource) {
applet_resource_holder = applet_resource;
}
void NpadAbstractLedHandler::SetPropertiesHandler(NpadAbstractPropertiesHandler* handler) {
properties_handler = handler;
}
Result NpadAbstractLedHandler::IncrementRefCounter() {
if (ref_counter == std::numeric_limits<s32>::max() - 1) {
return ResultNpadHandlerOverflow;
}
ref_counter++;
return ResultSuccess;
}
Result NpadAbstractLedHandler::DecrementRefCounter() {
if (ref_counter == 0) {
return ResultNpadHandlerNotInitialized;
}
ref_counter--;
return ResultSuccess;
}
void NpadAbstractLedHandler::SetNpadLedHandlerLedPattern() {
const auto npad_id = properties_handler->GetNpadId();
switch (npad_id) {
case Core::HID::NpadIdType::Player1:
left_pattern = Core::HID::LedPattern{1, 0, 0, 0};
break;
case Core::HID::NpadIdType::Player2:
left_pattern = Core::HID::LedPattern{1, 1, 0, 0};
break;
case Core::HID::NpadIdType::Player3:
left_pattern = Core::HID::LedPattern{1, 1, 1, 0};
break;
case Core::HID::NpadIdType::Player4:
left_pattern = Core::HID::LedPattern{1, 1, 1, 1};
break;
case Core::HID::NpadIdType::Player5:
left_pattern = Core::HID::LedPattern{1, 0, 0, 1};
break;
case Core::HID::NpadIdType::Player6:
left_pattern = Core::HID::LedPattern{1, 0, 1, 0};
break;
case Core::HID::NpadIdType::Player7:
left_pattern = Core::HID::LedPattern{1, 0, 1, 1};
break;
case Core::HID::NpadIdType::Player8:
left_pattern = Core::HID::LedPattern{0, 1, 1, 0};
break;
case Core::HID::NpadIdType::Other:
case Core::HID::NpadIdType::Handheld:
left_pattern = Core::HID::LedPattern{0, 0, 0, 0};
break;
default:
ASSERT_MSG(false, "Invalid npad id type");
break;
}
switch (npad_id) {
case Core::HID::NpadIdType::Player1:
right_pattern = Core::HID::LedPattern{0, 0, 0, 1};
break;
case Core::HID::NpadIdType::Player2:
right_pattern = Core::HID::LedPattern{0, 1, 1, 1};
break;
case Core::HID::NpadIdType::Player3:
right_pattern = Core::HID::LedPattern{0, 1, 1, 1};
break;
case Core::HID::NpadIdType::Player4:
right_pattern = Core::HID::LedPattern{1, 1, 1, 1};
break;
case Core::HID::NpadIdType::Player5:
right_pattern = Core::HID::LedPattern{1, 0, 0, 1};
break;
case Core::HID::NpadIdType::Player6:
right_pattern = Core::HID::LedPattern{0, 1, 0, 1};
break;
case Core::HID::NpadIdType::Player7:
right_pattern = Core::HID::LedPattern{1, 1, 0, 1};
break;
case Core::HID::NpadIdType::Player8:
right_pattern = Core::HID::LedPattern{0, 1, 1, 0};
break;
case Core::HID::NpadIdType::Other:
case Core::HID::NpadIdType::Handheld:
right_pattern = Core::HID::LedPattern{0, 0, 0, 0};
break;
default:
ASSERT_MSG(false, "Invalid npad id type");
break;
}
}
void NpadAbstractLedHandler::SetLedBlinkingDevice(Core::HID::LedPattern pattern) {
led_blinking = pattern;
}
} // namespace Service::HID

View File

@ -0,0 +1,43 @@
// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include "common/common_types.h"
#include "core/hle/result.h"
#include "hid_core/hid_types.h"
namespace Service::HID {
struct AppletResourceHolder;
class NpadAbstractedPadHolder;
class NpadAbstractPropertiesHandler;
/// Handles Npad request from HID interfaces
class NpadAbstractLedHandler final {
public:
explicit NpadAbstractLedHandler();
~NpadAbstractLedHandler();
void SetAbstractPadHolder(NpadAbstractedPadHolder* holder);
void SetAppletResource(AppletResourceHolder* applet_resource);
void SetPropertiesHandler(NpadAbstractPropertiesHandler* handler);
Result IncrementRefCounter();
Result DecrementRefCounter();
void SetNpadLedHandlerLedPattern();
void SetLedBlinkingDevice(Core::HID::LedPattern pattern);
private:
AppletResourceHolder* applet_resource_holder{nullptr};
NpadAbstractedPadHolder* abstract_pad_holder{nullptr};
NpadAbstractPropertiesHandler* properties_handler{nullptr};
s32 ref_counter{};
Core::HID::LedPattern led_blinking{0, 0, 0, 0};
Core::HID::LedPattern left_pattern{0, 0, 0, 0};
Core::HID::LedPattern right_pattern{0, 0, 0, 0};
u64 led_interval{};
};
} // namespace Service::HID

View File

@ -0,0 +1,108 @@
// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later
#include "hid_core/hid_result.h"
#include "hid_core/resources/abstracted_pad/abstract_mcu_handler.h"
#include "hid_core/resources/abstracted_pad/abstract_pad_holder.h"
#include "hid_core/resources/abstracted_pad/abstract_properties_handler.h"
#include "hid_core/resources/npad/npad_types.h"
namespace Service::HID {
NpadAbstractMcuHandler::NpadAbstractMcuHandler() {}
NpadAbstractMcuHandler::~NpadAbstractMcuHandler() = default;
void NpadAbstractMcuHandler::SetAbstractPadHolder(NpadAbstractedPadHolder* holder) {
abstract_pad_holder = holder;
}
void NpadAbstractMcuHandler::SetPropertiesHandler(NpadAbstractPropertiesHandler* handler) {
properties_handler = handler;
}
Result NpadAbstractMcuHandler::IncrementRefCounter() {
if (ref_counter == std::numeric_limits<s32>::max() - 1) {
return ResultNpadHandlerOverflow;
}
ref_counter++;
return ResultSuccess;
}
Result NpadAbstractMcuHandler::DecrementRefCounter() {
if (ref_counter == 0) {
return ResultNpadHandlerNotInitialized;
}
ref_counter--;
return ResultSuccess;
}
void NpadAbstractMcuHandler::UpdateMcuState() {
std::array<IAbstractedPad*, 5> abstract_pads{};
const std::size_t count = properties_handler->GetAbstractedPads(abstract_pads);
if (count == 0) {
mcu_holder = {};
return;
}
for (std::size_t i = 0; i < count; i++) {
auto* abstract_pad = abstract_pads[i];
if (!abstract_pad->internal_flags.is_connected) {
continue;
}
if (!abstract_pad->disabled_feature_set.has_left_joy_rail_bus) {
if (!abstract_pad->disabled_feature_set.has_left_joy_six_axis_sensor &&
!abstract_pad->disabled_feature_set.has_right_joy_six_axis_sensor) {
continue;
}
if (mcu_holder[1].state != NpadMcuState::Active) {
mcu_holder[1].state = NpadMcuState::Available;
}
mcu_holder[1].abstracted_pad = abstract_pad;
continue;
}
if (mcu_holder[0].state != NpadMcuState::Active) {
mcu_holder[0].state = NpadMcuState::Available;
}
mcu_holder[0].abstracted_pad = abstract_pad;
}
}
Result NpadAbstractMcuHandler::GetAbstractedPad(IAbstractedPad** data, u32 mcu_index) {
if (mcu_holder[mcu_index].state == NpadMcuState::None ||
mcu_holder[mcu_index].abstracted_pad == nullptr) {
return ResultMcuIsNotReady;
}
*data = mcu_holder[mcu_index].abstracted_pad;
return ResultSuccess;
}
NpadMcuState NpadAbstractMcuHandler::GetMcuState(u32 mcu_index) {
return mcu_holder[mcu_index].state;
}
Result NpadAbstractMcuHandler::SetMcuState(bool is_enabled, u32 mcu_index) {
NpadMcuState& state = mcu_holder[mcu_index].state;
if (state == NpadMcuState::None) {
return ResultMcuIsNotReady;
}
if ((is_enabled) && (state == NpadMcuState::Available)) {
state = NpadMcuState::Active;
return ResultSuccess;
}
if (is_enabled) {
return ResultSuccess;
}
if (state != NpadMcuState::Active) {
return ResultSuccess;
}
state = NpadMcuState::Available;
return ResultSuccess;
}
} // namespace Service::HID

View File

@ -0,0 +1,52 @@
// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include "common/common_types.h"
#include "core/hle/result.h"
#include "hid_core/hid_types.h"
namespace Service::HID {
struct IAbstractedPad;
class NpadAbstractedPadHolder;
class NpadAbstractPropertiesHandler;
enum class NpadMcuState : u32 {
None,
Available,
Active,
};
struct NpadMcuHolder {
NpadMcuState state;
INSERT_PADDING_BYTES(0x4);
IAbstractedPad* abstracted_pad;
};
static_assert(sizeof(NpadMcuHolder) == 0x10, "NpadMcuHolder is an invalid size");
/// Handles Npad request from HID interfaces
class NpadAbstractMcuHandler final {
public:
explicit NpadAbstractMcuHandler();
~NpadAbstractMcuHandler();
void SetAbstractPadHolder(NpadAbstractedPadHolder* holder);
void SetPropertiesHandler(NpadAbstractPropertiesHandler* handler);
Result IncrementRefCounter();
Result DecrementRefCounter();
void UpdateMcuState();
Result GetAbstractedPad(IAbstractedPad** data, u32 mcu_index);
NpadMcuState GetMcuState(u32 mcu_index);
Result SetMcuState(bool is_enabled, u32 mcu_index);
private:
NpadAbstractedPadHolder* abstract_pad_holder{nullptr};
NpadAbstractPropertiesHandler* properties_handler{nullptr};
s32 ref_counter{};
std::array<NpadMcuHolder, 2> mcu_holder{};
};
} // namespace Service::HID

View File

@ -0,0 +1,140 @@
// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later
#include "core/hle/kernel/k_event.h"
#include "core/hle/kernel/k_readable_event.h"
#include "hid_core/hid_result.h"
#include "hid_core/resources/abstracted_pad/abstract_nfc_handler.h"
#include "hid_core/resources/abstracted_pad/abstract_pad_holder.h"
#include "hid_core/resources/abstracted_pad/abstract_properties_handler.h"
#include "hid_core/resources/npad/npad_types.h"
namespace Service::HID {
NpadAbstractNfcHandler::NpadAbstractNfcHandler() {}
NpadAbstractNfcHandler::~NpadAbstractNfcHandler() = default;
void NpadAbstractNfcHandler::SetAbstractPadHolder(NpadAbstractedPadHolder* holder) {
abstract_pad_holder = holder;
}
void NpadAbstractNfcHandler::SetPropertiesHandler(NpadAbstractPropertiesHandler* handler) {
properties_handler = handler;
}
Result NpadAbstractNfcHandler::IncrementRefCounter() {
if (ref_counter == std::numeric_limits<s32>::max() - 1) {
return ResultNpadHandlerOverflow;
}
ref_counter++;
return ResultSuccess;
}
Result NpadAbstractNfcHandler::DecrementRefCounter() {
if (ref_counter == 0) {
return ResultNpadHandlerNotInitialized;
}
ref_counter--;
return ResultSuccess;
}
void NpadAbstractNfcHandler::UpdateNfcState() {
std::array<IAbstractedPad*, 5> abstract_pads{};
const std::size_t count = properties_handler->GetAbstractedPads(abstract_pads);
if (count == 0) {
if (sensor_state == NpadNfcState::Active) {
nfc_activate_event->Signal();
}
if (sensor_state == NpadNfcState::Unavailable) {
return;
}
sensor_state = NpadNfcState::Unavailable;
input_event->Signal();
return;
}
bool is_found{};
for (std::size_t i = 0; i < count; i++) {
auto* abstract_pad = abstract_pads[i];
if (!abstract_pad->internal_flags.is_connected) {
continue;
}
if (!abstract_pad->disabled_feature_set.has_nfc) {
continue;
}
is_found = true;
xcd_handle = 0;
}
if (is_found) {
if (sensor_state == NpadNfcState::Active) {
return;
}
if (sensor_state == NpadNfcState::Available) {
return;
}
sensor_state = NpadNfcState::Available;
input_event->Signal();
return;
}
if (sensor_state == NpadNfcState::Active) {
nfc_activate_event->Signal();
}
if (sensor_state == NpadNfcState::Unavailable) {
return;
}
sensor_state = NpadNfcState::Unavailable;
input_event->Signal();
return;
}
bool NpadAbstractNfcHandler::HasNfcSensor() {
return sensor_state != NpadNfcState::Unavailable;
}
bool NpadAbstractNfcHandler::IsNfcActivated() {
return sensor_state == NpadNfcState::Active;
}
Result NpadAbstractNfcHandler::GetAcquireNfcActivateEventHandle(
Kernel::KReadableEvent** out_event) {
*out_event = &nfc_activate_event->GetReadableEvent();
return ResultSuccess;
}
void NpadAbstractNfcHandler::SetInputEvent(Kernel::KEvent* event) {
input_event = event;
}
Result NpadAbstractNfcHandler::ActivateNfc(bool is_enabled) {
if (sensor_state == NpadNfcState::Active) {
return ResultNfcIsNotReady;
}
NpadNfcState new_state = NpadNfcState::Available;
if (is_enabled) {
new_state = NpadNfcState::Active;
}
if (sensor_state != new_state) {
sensor_state = new_state;
nfc_activate_event->Signal();
}
return ResultSuccess;
}
Result NpadAbstractNfcHandler::GetXcdHandleWithNfc(u64& out_xcd_handle) const {
if (sensor_state == NpadNfcState::Unavailable) {
return ResultNfcIsNotReady;
}
if (xcd_handle == 0) {
return ResultNfcXcdHandleIsNotInitialized;
}
out_xcd_handle = xcd_handle;
return ResultSuccess;
}
} // namespace Service::HID

View File

@ -0,0 +1,57 @@
// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include "common/common_types.h"
#include "core/hle/result.h"
#include "hid_core/hid_types.h"
namespace Kernel {
class KReadableEvent;
}
enum class NpadNfcState : u32 {
Unavailable,
Available,
Active,
};
namespace Service::HID {
class NpadAbstractedPadHolder;
class NpadAbstractPropertiesHandler;
/// Handles Npad request from HID interfaces
class NpadAbstractNfcHandler final {
public:
explicit NpadAbstractNfcHandler();
~NpadAbstractNfcHandler();
void SetAbstractPadHolder(NpadAbstractedPadHolder* holder);
void SetPropertiesHandler(NpadAbstractPropertiesHandler* handler);
Result IncrementRefCounter();
Result DecrementRefCounter();
void UpdateNfcState();
bool HasNfcSensor();
bool IsNfcActivated();
Result GetAcquireNfcActivateEventHandle(Kernel::KReadableEvent** out_event);
void SetInputEvent(Kernel::KEvent* event);
Result ActivateNfc(bool is_enabled);
Result GetXcdHandleWithNfc(u64& out_xcd_handle) const;
private:
NpadAbstractedPadHolder* abstract_pad_holder{nullptr};
NpadAbstractPropertiesHandler* properties_handler{nullptr};
s32 ref_counter{};
Kernel::KEvent* nfc_activate_event{nullptr};
Kernel::KEvent* input_event{nullptr};
u64 xcd_handle{};
NpadNfcState sensor_state{NpadNfcState::Unavailable};
};
} // namespace Service::HID

View File

@ -0,0 +1,294 @@
// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later
#include "hid_core/hid_result.h"
#include "hid_core/resources/abstracted_pad/abstract_pad.h"
#include "hid_core/resources/applet_resource.h"
#include "hid_core/resources/npad/npad_types.h"
namespace Service::HID {
AbstractPad::AbstractPad() {}
AbstractPad::~AbstractPad() = default;
void AbstractPad::SetExternals(AppletResourceHolder* applet_resource,
CaptureButtonResource* capture_button_resource,
HomeButtonResource* home_button_resource,
SixAxisResource* sixaxis_resource, PalmaResource* palma_resource,
VibrationHandler* vibration) {
applet_resource_holder = applet_resource;
properties_handler.SetAppletResource(applet_resource_holder);
properties_handler.SetAbstractPadHolder(&abstract_pad_holder);
led_handler.SetAppletResource(applet_resource_holder);
led_handler.SetAbstractPadHolder(&abstract_pad_holder);
led_handler.SetPropertiesHandler(&properties_handler);
ir_sensor_handler.SetAbstractPadHolder(&abstract_pad_holder);
ir_sensor_handler.SetPropertiesHandler(&properties_handler);
nfc_handler.SetAbstractPadHolder(&abstract_pad_holder);
nfc_handler.SetPropertiesHandler(&properties_handler);
mcu_handler.SetAbstractPadHolder(&abstract_pad_holder);
mcu_handler.SetPropertiesHandler(&properties_handler);
std::array<NpadVibrationDevice*, 2> vibration_devices{&vibration_left, &vibration_right};
vibration_handler.SetAppletResource(applet_resource_holder);
vibration_handler.SetAbstractPadHolder(&abstract_pad_holder);
vibration_handler.SetPropertiesHandler(&properties_handler);
vibration_handler.SetN64Vibration(&vibration_n64);
vibration_handler.SetVibration(vibration_devices);
vibration_handler.SetGcVibration(&vibration_gc);
sixaxis_handler.SetAppletResource(applet_resource_holder);
sixaxis_handler.SetAbstractPadHolder(&abstract_pad_holder);
sixaxis_handler.SetPropertiesHandler(&properties_handler);
sixaxis_handler.SetSixaxisResource(sixaxis_resource);
button_handler.SetAppletResource(applet_resource_holder);
button_handler.SetAbstractPadHolder(&abstract_pad_holder);
button_handler.SetPropertiesHandler(&properties_handler);
battery_handler.SetAppletResource(applet_resource_holder);
battery_handler.SetAbstractPadHolder(&abstract_pad_holder);
battery_handler.SetPropertiesHandler(&properties_handler);
palma_handler.SetAbstractPadHolder(&abstract_pad_holder);
palma_handler.SetPropertiesHandler(&properties_handler);
palma_handler.SetPalmaResource(palma_resource);
}
void AbstractPad::SetNpadId(Core::HID::NpadIdType npad_id) {
properties_handler.SetNpadId(npad_id);
}
Result AbstractPad::Activate() {
if (ref_counter == std::numeric_limits<s32>::max() - 1) {
return ResultNpadHandlerOverflow;
}
if (ref_counter != 0) {
ref_counter++;
return ResultSuccess;
}
std::size_t stage = 0;
Result result = ResultSuccess;
if (result.IsSuccess()) {
stage++;
result = properties_handler.IncrementRefCounter();
}
if (result.IsSuccess()) {
stage++;
result = led_handler.IncrementRefCounter();
}
if (result.IsSuccess()) {
stage++;
result = ir_sensor_handler.IncrementRefCounter();
}
if (result.IsSuccess()) {
stage++;
result = mcu_handler.IncrementRefCounter();
}
if (result.IsSuccess()) {
stage++;
result = nfc_handler.IncrementRefCounter();
}
if (result.IsSuccess()) {
stage++;
result = vibration_handler.IncrementRefCounter();
}
if (result.IsSuccess()) {
stage++;
result = sixaxis_handler.IncrementRefCounter();
}
if (result.IsSuccess()) {
stage++;
result = button_handler.IncrementRefCounter();
}
if (result.IsSuccess()) {
stage++;
result = battery_handler.IncrementRefCounter();
}
if (result.IsSuccess()) {
stage++;
result = palma_handler.IncrementRefCounter();
}
if (result.IsSuccess()) {
ref_counter++;
return result;
}
if (stage > 9) {
battery_handler.DecrementRefCounter();
}
if (stage > 8) {
button_handler.DecrementRefCounter();
}
if (stage > 7) {
sixaxis_handler.DecrementRefCounter();
}
if (stage > 6) {
vibration_handler.DecrementRefCounter();
}
if (stage > 5) {
nfc_handler.DecrementRefCounter();
}
if (stage > 4) {
mcu_handler.DecrementRefCounter();
}
if (stage > 3) {
ir_sensor_handler.DecrementRefCounter();
}
if (stage > 2) {
led_handler.DecrementRefCounter();
}
if (stage > 1) {
properties_handler.DecrementRefCounter();
}
return result;
}
Result AbstractPad::Deactivate() {
if (ref_counter == 0) {
return ResultNpadResourceNotInitialized;
}
ref_counter--;
battery_handler.DecrementRefCounter();
button_handler.DecrementRefCounter();
sixaxis_handler.DecrementRefCounter();
vibration_handler.DecrementRefCounter();
nfc_handler.DecrementRefCounter();
ir_sensor_handler.DecrementRefCounter();
mcu_handler.DecrementRefCounter();
led_handler.DecrementRefCounter();
properties_handler.DecrementRefCounter();
palma_handler.DecrementRefCounter();
return ResultSuccess;
}
Result AbstractPad::ActivateNpad(u64 aruid) {
Result result = ResultSuccess;
if (result.IsSuccess()) {
result = properties_handler.ActivateNpadUnknown0x88(aruid);
}
if (result.IsSuccess()) {
result = sixaxis_handler.UpdateSixAxisState2(aruid);
}
if (result.IsSuccess()) {
result = battery_handler.UpdateBatteryState(aruid);
}
return result;
}
NpadAbstractedPadHolder* AbstractPad::GetAbstractedPadHolder() {
return &abstract_pad_holder;
}
NpadAbstractPropertiesHandler* AbstractPad::GetAbstractPropertiesHandler() {
return &properties_handler;
}
NpadAbstractLedHandler* AbstractPad::GetAbstractLedHandler() {
return &led_handler;
}
NpadAbstractIrSensorHandler* AbstractPad::GetAbstractIrSensorHandler() {
return &ir_sensor_handler;
}
NpadAbstractMcuHandler* AbstractPad::GetAbstractMcuHandler() {
return &mcu_handler;
}
NpadAbstractNfcHandler* AbstractPad::GetAbstractNfcHandler() {
return &nfc_handler;
}
NpadAbstractVibrationHandler* AbstractPad::GetAbstractVibrationHandler() {
return &vibration_handler;
}
NpadAbstractSixAxisHandler* AbstractPad::GetAbstractSixAxisHandler() {
return &sixaxis_handler;
}
NpadAbstractButtonHandler* AbstractPad::GetAbstractButtonHandler() {
return &button_handler;
}
NpadAbstractBatteryHandler* AbstractPad::GetAbstractBatteryHandler() {
return &battery_handler;
}
NpadN64VibrationDevice* AbstractPad::GetN64VibrationDevice() {
return &vibration_n64;
}
NpadVibrationDevice* AbstractPad::GetVibrationDevice(Core::HID::DeviceIndex device_index) {
if (device_index == Core::HID::DeviceIndex::Right) {
return &vibration_right;
}
return &vibration_left;
}
void AbstractPad::GetLeftRightVibrationDevice(std::vector<NpadVibrationDevice*> list) {
list.emplace_back(&vibration_left);
list.emplace_back(&vibration_right);
}
NpadGcVibrationDevice* AbstractPad::GetGCVibrationDevice() {
return &vibration_gc;
}
Core::HID::NpadIdType AbstractPad::GetLastActiveNpad() {
return properties_handler.GetNpadId();
}
void AbstractPad::UpdateInterfaceType() {
if (interface_type != properties_handler.GetInterfaceType()) {
Update();
}
battery_handler.UpdateBatteryState();
}
void AbstractPad::Update() {
properties_handler.UpdateDeviceType();
led_handler.SetNpadLedHandlerLedPattern();
vibration_handler.UpdateVibrationState();
sixaxis_handler.UpdateSixAxisState();
nfc_handler.UpdateNfcState();
ir_sensor_handler.UpdateIrSensorState();
mcu_handler.UpdateMcuState();
palma_handler.UpdatePalmaState();
battery_handler.UpdateBatteryState();
button_handler.EnableCenterClamp();
interface_type = properties_handler.GetInterfaceType();
std::scoped_lock lock{*applet_resource_holder->shared_mutex};
properties_handler.UpdateAllDeviceProperties();
battery_handler.UpdateCoreBatteryState();
button_handler.UpdateCoreBatteryState();
}
void AbstractPad::UpdatePadState() {
button_handler.UpdateAllButtonLifo();
sixaxis_handler.UpdateSixAxisState();
battery_handler.UpdateCoreBatteryState();
}
void AbstractPad::EnableAppletToGetInput(u64 aruid) {
button_handler.UpdateButtonState(aruid);
sixaxis_handler.UpdateSixAxisState(aruid);
battery_handler.UpdateBatteryState(aruid);
}
} // namespace Service::HID

View File

@ -0,0 +1,123 @@
// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include <array>
#include <mutex>
#include "common/common_types.h"
#include "core/hle/result.h"
#include "hid_core/hid_types.h"
#include "hid_core/resources/applet_resource.h"
#include "hid_core/resources/npad/npad_types.h"
#include "hid_core/resources/abstracted_pad/abstract_battery_handler.h"
#include "hid_core/resources/abstracted_pad/abstract_button_handler.h"
#include "hid_core/resources/abstracted_pad/abstract_ir_sensor_handler.h"
#include "hid_core/resources/abstracted_pad/abstract_led_handler.h"
#include "hid_core/resources/abstracted_pad/abstract_mcu_handler.h"
#include "hid_core/resources/abstracted_pad/abstract_nfc_handler.h"
#include "hid_core/resources/abstracted_pad/abstract_pad_holder.h"
#include "hid_core/resources/abstracted_pad/abstract_palma_handler.h"
#include "hid_core/resources/abstracted_pad/abstract_properties_handler.h"
#include "hid_core/resources/abstracted_pad/abstract_sixaxis_handler.h"
#include "hid_core/resources/abstracted_pad/abstract_vibration_handler.h"
#include "hid_core/resources/vibration/gc_vibration_device.h"
#include "hid_core/resources/vibration/n64_vibration_device.h"
#include "hid_core/resources/vibration/vibration_device.h"
namespace Service::HID {
class AppletResource;
class SixAxisResource;
class PalmaResource;
class NPadResource;
class AbstractPad;
class NpadLastActiveHandler;
class NpadIrNfcHandler;
class UniquePads;
class NpadPalmaHandler;
class FirmwareResource;
class NpadVibration;
class NpadHighestBattery;
class NpadGcVibration;
class CaptureButtonResource;
class HomeButtonResource;
class VibrationHandler;
struct HandheldConfig;
/// Handles Npad request from HID interfaces
class AbstractPad final {
public:
explicit AbstractPad();
~AbstractPad();
void SetExternals(AppletResourceHolder* applet_resource,
CaptureButtonResource* capture_button_resource,
HomeButtonResource* home_button_resource, SixAxisResource* sixaxis_resource,
PalmaResource* palma_resource, VibrationHandler* vibration);
void SetNpadId(Core::HID::NpadIdType npad_id);
Result Activate();
Result Deactivate();
Result ActivateNpad(u64 aruid);
NpadAbstractedPadHolder* GetAbstractedPadHolder();
NpadAbstractPropertiesHandler* GetAbstractPropertiesHandler();
NpadAbstractLedHandler* GetAbstractLedHandler();
NpadAbstractIrSensorHandler* GetAbstractIrSensorHandler();
NpadAbstractMcuHandler* GetAbstractMcuHandler();
NpadAbstractNfcHandler* GetAbstractNfcHandler();
NpadAbstractVibrationHandler* GetAbstractVibrationHandler();
NpadAbstractSixAxisHandler* GetAbstractSixAxisHandler();
NpadAbstractButtonHandler* GetAbstractButtonHandler();
NpadAbstractBatteryHandler* GetAbstractBatteryHandler();
NpadN64VibrationDevice* GetN64VibrationDevice();
NpadVibrationDevice* GetVibrationDevice(Core::HID::DeviceIndex device_index);
void GetLeftRightVibrationDevice(std::vector<NpadVibrationDevice*> list);
NpadGcVibrationDevice* GetGCVibrationDevice();
Core::HID::NpadIdType GetLastActiveNpad();
void UpdateInterfaceType();
void Update();
void UpdatePadState();
void EnableAppletToGetInput(u64 aruid);
private:
AppletResourceHolder* applet_resource_holder{nullptr};
NpadAbstractedPadHolder abstract_pad_holder{};
NpadAbstractPropertiesHandler properties_handler{};
NpadAbstractLedHandler led_handler{};
NpadAbstractIrSensorHandler ir_sensor_handler{};
NpadAbstractNfcHandler nfc_handler{};
NpadAbstractMcuHandler mcu_handler{};
NpadAbstractVibrationHandler vibration_handler{};
NpadAbstractSixAxisHandler sixaxis_handler{};
NpadAbstractButtonHandler button_handler{};
NpadAbstractBatteryHandler battery_handler{};
NpadAbstractPalmaHandler palma_handler{};
NpadN64VibrationDevice vibration_n64{};
NpadVibrationDevice vibration_left{};
NpadVibrationDevice vibration_right{};
NpadGcVibrationDevice vibration_gc{};
// SixAxisConfigHolder fullkey_config;
// SixAxisConfigHolder handheld_config;
// SixAxisConfigHolder dual_left_config;
// SixAxisConfigHolder dual_right_config;
// SixAxisConfigHolder left_config;
// SixAxisConfigHolder right_config;
s32 ref_counter{};
Core::HID::NpadInterfaceType interface_type{Core::HID::NpadInterfaceType::None};
};
using FullAbstractPad = std::array<AbstractPad, MaxSupportedNpadIdTypes>;
} // namespace Service::HID

View File

@ -0,0 +1,99 @@
// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later
#include "hid_core/hid_result.h"
#include "hid_core/resources/abstracted_pad/abstract_pad_holder.h"
#include "hid_core/resources/npad/npad_types.h"
namespace Service::HID {
Result NpadAbstractedPadHolder::RegisterAbstractPad(IAbstractedPad* abstracted_pad) {
if (list_size >= assignment_list.size()) {
return ResultNpadIsNotProController;
}
for (std::size_t i = 0; i < list_size; i++) {
if (assignment_list[i].device_type == abstracted_pad->device_type) {
return ResultNpadIsNotProController;
}
}
assignment_list[list_size] = {
.abstracted_pad = abstracted_pad,
.device_type = abstracted_pad->device_type,
.interface_type = abstracted_pad->interface_type,
.controller_id = abstracted_pad->controller_id,
};
list_size++;
return ResultSuccess;
}
void NpadAbstractedPadHolder::RemoveAbstractPadByControllerId(u64 controller_id) {
if (list_size == 0) {
return;
}
if (controller_id == 0) {
return;
}
for (std::size_t i = 0; i < list_size; i++) {
if (assignment_list[i].controller_id != controller_id) {
continue;
}
for (std::size_t e = i + 1; e < list_size; e++) {
assignment_list[e - 1] = assignment_list[e];
}
list_size--;
return;
}
}
void NpadAbstractedPadHolder::DetachAbstractedPad() {
while (list_size > 0) {
for (std::size_t i = 1; i < list_size; i++) {
assignment_list[i - 1] = assignment_list[i];
}
list_size--;
}
}
u64 NpadAbstractedPadHolder::RemoveAbstractPadByAssignmentStyle(
Service::HID::AssignmentStyle assignment_style) {
for (std::size_t i = 0; i < list_size; i++) {
if ((assignment_style.raw & assignment_list[i].abstracted_pad->assignment_style.raw) == 0) {
continue;
}
for (std::size_t e = i + 1; e < list_size; e++) {
assignment_list[e - 1] = assignment_list[e];
}
list_size--;
return list_size;
}
return list_size;
}
u32 NpadAbstractedPadHolder::GetAbstractedPads(std::span<IAbstractedPad*> list) const {
u32 num_elements = std::min(static_cast<u32>(list.size()), list_size);
for (std::size_t i = 0; i < num_elements; i++) {
list[i] = assignment_list[i].abstracted_pad;
}
return num_elements;
}
void NpadAbstractedPadHolder::SetAssignmentMode(const NpadJoyAssignmentMode& mode) {
assignment_mode = mode;
}
NpadJoyAssignmentMode NpadAbstractedPadHolder::GetAssignmentMode() const {
return assignment_mode;
}
std::size_t NpadAbstractedPadHolder::GetStyleIndexList(
std::span<Core::HID::NpadStyleIndex> list) const {
for (std::size_t i = 0; i < list_size; i++) {
list[i] = assignment_list[i].device_type;
}
return list_size;
}
} // namespace Service::HID

Some files were not shown because too many files have changed in this diff Show More