id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7,024
|
kern_svc_interrupt_event.cpp
|
Atmosphere-NX_Atmosphere/libraries/libmesosphere/source/svc/kern_svc_interrupt_event.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <mesosphere.hpp>
namespace ams::kern::svc {
/* ============================= Common ============================= */
namespace {
constexpr bool IsValidInterruptType(ams::svc::InterruptType type) {
switch (type) {
case ams::svc::InterruptType_Edge:
case ams::svc::InterruptType_Level:
return true;
default:
return false;
}
}
Result CreateInterruptEvent(ams::svc::Handle *out, int32_t interrupt_id, ams::svc::InterruptType type) {
/* Validate the type. */
R_UNLESS(IsValidInterruptType(type), svc::ResultInvalidEnumValue());
/* Check whether the interrupt is allowed. */
auto &process = GetCurrentProcess();
R_UNLESS(process.IsPermittedInterrupt(interrupt_id), svc::ResultNotFound());
/* Get the current handle table. */
auto &handle_table = process.GetHandleTable();
/* Create the interrupt event. */
KInterruptEvent *event = KInterruptEvent::Create();
R_UNLESS(event != nullptr, svc::ResultOutOfResource());
ON_SCOPE_EXIT { event->Close(); };
/* Initialize the event. */
R_TRY(event->Initialize(interrupt_id, type));
/* Register the event. */
KInterruptEvent::Register(event);
/* Add the event to the handle table. */
R_TRY(handle_table.Add(out, event));
R_SUCCEED();
}
}
/* ============================= 64 ABI ============================= */
Result CreateInterruptEvent64(ams::svc::Handle *out_read_handle, int32_t interrupt_id, ams::svc::InterruptType interrupt_type) {
R_RETURN(CreateInterruptEvent(out_read_handle, interrupt_id, interrupt_type));
}
/* ============================= 64From32 ABI ============================= */
Result CreateInterruptEvent64From32(ams::svc::Handle *out_read_handle, int32_t interrupt_id, ams::svc::InterruptType interrupt_type) {
R_RETURN(CreateInterruptEvent(out_read_handle, interrupt_id, interrupt_type));
}
}
| 2,838
|
C++
|
.cpp
| 58
| 40.275862
| 138
| 0.595221
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,025
|
kern_svc_shared_memory.cpp
|
Atmosphere-NX_Atmosphere/libraries/libmesosphere/source/svc/kern_svc_shared_memory.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <mesosphere.hpp>
namespace ams::kern::svc {
/* ============================= Common ============================= */
namespace {
constexpr bool IsValidSharedMemoryPermission(ams::svc::MemoryPermission perm) {
switch (perm) {
case ams::svc::MemoryPermission_Read:
case ams::svc::MemoryPermission_ReadWrite:
return true;
default:
return false;
}
}
constexpr bool IsValidRemoteSharedMemoryPermission(ams::svc::MemoryPermission perm) {
return IsValidSharedMemoryPermission(perm) || perm == ams::svc::MemoryPermission_DontCare;
}
Result MapSharedMemory(ams::svc::Handle shmem_handle, uintptr_t address, size_t size, ams::svc::MemoryPermission map_perm) {
/* Validate the address/size. */
R_UNLESS(util::IsAligned(address, PageSize), svc::ResultInvalidAddress());
R_UNLESS(util::IsAligned(size, PageSize), svc::ResultInvalidSize());
R_UNLESS(size > 0, svc::ResultInvalidSize());
R_UNLESS((address < address + size), svc::ResultInvalidCurrentMemory());
/* Validate the permission. */
R_UNLESS(IsValidSharedMemoryPermission(map_perm), svc::ResultInvalidNewMemoryPermission());
/* Get the current process. */
auto &process = GetCurrentProcess();
auto &page_table = process.GetPageTable();
/* Get the shared memory. */
KScopedAutoObject shmem = process.GetHandleTable().GetObject<KSharedMemory>(shmem_handle);
R_UNLESS(shmem.IsNotNull(), svc::ResultInvalidHandle());
/* Verify that the mapping is in range. */
R_UNLESS(page_table.CanContain(address, size, KMemoryState_Shared), svc::ResultInvalidMemoryRegion());
/* Add the shared memory to the process. */
R_TRY(process.AddSharedMemory(shmem.GetPointerUnsafe(), address, size));
/* Ensure that we clean up the shared memory if we fail to map it. */
ON_RESULT_FAILURE { process.RemoveSharedMemory(shmem.GetPointerUnsafe(), address, size); };
/* Map the shared memory. */
R_RETURN(shmem->Map(std::addressof(page_table), address, size, std::addressof(process), map_perm));
}
Result UnmapSharedMemory(ams::svc::Handle shmem_handle, uintptr_t address, size_t size) {
/* Validate the address/size. */
R_UNLESS(util::IsAligned(address, PageSize), svc::ResultInvalidAddress());
R_UNLESS(util::IsAligned(size, PageSize), svc::ResultInvalidSize());
R_UNLESS(size > 0, svc::ResultInvalidSize());
R_UNLESS((address < address + size), svc::ResultInvalidCurrentMemory());
/* Get the current process. */
auto &process = GetCurrentProcess();
auto &page_table = process.GetPageTable();
/* Get the shared memory. */
KScopedAutoObject shmem = process.GetHandleTable().GetObject<KSharedMemory>(shmem_handle);
R_UNLESS(shmem.IsNotNull(), svc::ResultInvalidHandle());
/* Verify that the mapping is in range. */
R_UNLESS(page_table.CanContain(address, size, KMemoryState_Shared), svc::ResultInvalidMemoryRegion());
/* Unmap the shared memory. */
R_TRY(shmem->Unmap(std::addressof(page_table), address, size, std::addressof(process)));
/* Remove the shared memory from the process. */
process.RemoveSharedMemory(shmem.GetPointerUnsafe(), address, size);
R_SUCCEED();
}
Result CreateSharedMemory(ams::svc::Handle *out, size_t size, ams::svc::MemoryPermission owner_perm, ams::svc::MemoryPermission remote_perm) {
/* Validate the size. */
R_UNLESS(0 < size && size < kern::MainMemorySizeMax, svc::ResultInvalidSize());
R_UNLESS(util::IsAligned(size, PageSize), svc::ResultInvalidSize());
/* Validate the permissions. */
R_UNLESS(IsValidSharedMemoryPermission(owner_perm), svc::ResultInvalidNewMemoryPermission());
R_UNLESS(IsValidRemoteSharedMemoryPermission(remote_perm), svc::ResultInvalidNewMemoryPermission());
/* Create the shared memory. */
KSharedMemory *shmem = KSharedMemory::Create();
R_UNLESS(shmem != nullptr, svc::ResultOutOfResource());
/* Ensure the only reference is in the handle table when we're done. */
ON_SCOPE_EXIT { shmem->Close(); };
/* Initialize the shared memory. */
R_TRY(shmem->Initialize(GetCurrentProcessPointer(), size, owner_perm, remote_perm));
/* Register the shared memory. */
KSharedMemory::Register(shmem);
/* Add the shared memory to the handle table. */
R_TRY(GetCurrentProcess().GetHandleTable().Add(out, shmem));
R_SUCCEED();
}
}
/* ============================= 64 ABI ============================= */
Result MapSharedMemory64(ams::svc::Handle shmem_handle, ams::svc::Address address, ams::svc::Size size, ams::svc::MemoryPermission map_perm) {
R_RETURN(MapSharedMemory(shmem_handle, address, size, map_perm));
}
Result UnmapSharedMemory64(ams::svc::Handle shmem_handle, ams::svc::Address address, ams::svc::Size size) {
R_RETURN(UnmapSharedMemory(shmem_handle, address, size));
}
Result CreateSharedMemory64(ams::svc::Handle *out_handle, ams::svc::Size size, ams::svc::MemoryPermission owner_perm, ams::svc::MemoryPermission remote_perm) {
R_RETURN(CreateSharedMemory(out_handle, size, owner_perm, remote_perm));
}
/* ============================= 64From32 ABI ============================= */
Result MapSharedMemory64From32(ams::svc::Handle shmem_handle, ams::svc::Address address, ams::svc::Size size, ams::svc::MemoryPermission map_perm) {
R_RETURN(MapSharedMemory(shmem_handle, address, size, map_perm));
}
Result UnmapSharedMemory64From32(ams::svc::Handle shmem_handle, ams::svc::Address address, ams::svc::Size size) {
R_RETURN(UnmapSharedMemory(shmem_handle, address, size));
}
Result CreateSharedMemory64From32(ams::svc::Handle *out_handle, ams::svc::Size size, ams::svc::MemoryPermission owner_perm, ams::svc::MemoryPermission remote_perm) {
R_RETURN(CreateSharedMemory(out_handle, size, owner_perm, remote_perm));
}
}
| 7,283
|
C++
|
.cpp
| 116
| 52.681034
| 169
| 0.6287
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,026
|
kern_svc_exception.cpp
|
Atmosphere-NX_Atmosphere/libraries/libmesosphere/source/svc/kern_svc_exception.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <mesosphere.hpp>
namespace ams::kern::svc {
/* ============================= Common ============================= */
namespace {
#if defined(MESOSPHERE_BUILD_FOR_DEBUGGING)
void PrintBreak(ams::svc::BreakReason break_reason) {
/* Print that break was called. */
MESOSPHERE_RELEASE_LOG("%s: svc::Break(%d) was called, pid=%ld, tid=%ld\n", GetCurrentProcess().GetName(), static_cast<s32>(break_reason), GetCurrentProcess().GetId(), GetCurrentThread().GetId());
/* Print the current thread's registers. */
KDebug::PrintRegister();
/* Print a backtrace. */
KDebug::PrintBacktrace();
}
#endif
void Break(ams::svc::BreakReason break_reason, uintptr_t address, size_t size) {
/* Determine whether the break is only a notification. */
const bool is_notification = (break_reason & ams::svc::BreakReason_NotificationOnlyFlag) != 0;
/* If the break isn't a notification, print it. */
if (!is_notification) {
#if defined(MESOSPHERE_BUILD_FOR_DEBUGGING)
PrintBreak(break_reason);
#endif
}
/* If the current process is attached to debugger, try to notify it. */
if (GetCurrentProcess().IsAttachedToDebugger()) {
if (R_SUCCEEDED(KDebug::BreakIfAttached(break_reason, address, size))) {
/* If we attached, set the pc to the instruction before the current one and return. */
KDebug::SetPreviousProgramCounter();
return;
}
}
/* If the break is only a notification, we're done. */
if (is_notification) {
return;
}
/* Print that break was called. */
MESOSPHERE_EXCEPTION_LOG("Break() called. ");
/* Try to enter JIT debug state. */
if (GetCurrentProcess().EnterJitDebug(ams::svc::DebugEvent_Exception, ams::svc::DebugException_UserBreak, KDebug::GetProgramCounter(GetCurrentThread()), break_reason, address, size)) {
/* We entered JIT debug, so set the pc to the instruction before the current one and return. */
KDebug::SetPreviousProgramCounter();
return;
}
/* Exit the current process. */
GetCurrentProcess().Exit();
}
}
/* ============================= 64 ABI ============================= */
void Break64(ams::svc::BreakReason break_reason, ams::svc::Address arg, ams::svc::Size size) {
return Break(break_reason, arg, size);
}
/* ============================= 64From32 ABI ============================= */
void Break64From32(ams::svc::BreakReason break_reason, ams::svc::Address arg, ams::svc::Size size) {
return Break(break_reason, arg, size);
}
}
| 3,603
|
C++
|
.cpp
| 71
| 40.943662
| 208
| 0.581554
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,027
|
kern_svc_register.cpp
|
Atmosphere-NX_Atmosphere/libraries/libmesosphere/source/svc/kern_svc_register.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <mesosphere.hpp>
namespace ams::kern::svc {
/* ============================= Common ============================= */
namespace {
Result ReadWriteRegister(uint32_t *out, ams::svc::PhysicalAddress address, uint32_t mask, uint32_t value) {
/* Clear the output unconditionally. */
*out = 0;
/* Read/write the register. */
R_RETURN(KSystemControl::ReadWriteRegister(out, address, mask, value));
}
}
/* ============================= 64 ABI ============================= */
Result ReadWriteRegister64(uint32_t *out_value, ams::svc::PhysicalAddress address, uint32_t mask, uint32_t value) {
R_RETURN(ReadWriteRegister(out_value, address, mask, value));
}
/* ============================= 64From32 ABI ============================= */
Result ReadWriteRegister64From32(uint32_t *out_value, ams::svc::PhysicalAddress address, uint32_t mask, uint32_t value) {
R_RETURN(ReadWriteRegister(out_value, address, mask, value));
}
}
| 1,697
|
C++
|
.cpp
| 35
| 43.457143
| 125
| 0.61599
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,028
|
kern_svc_secure_monitor_call.cpp
|
Atmosphere-NX_Atmosphere/libraries/libmesosphere/source/svc/kern_svc_secure_monitor_call.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <mesosphere.hpp>
namespace ams::kern::svc {
/* ============================= Common ============================= */
namespace {
}
/* ============================= 64 ABI ============================= */
void CallSecureMonitor64(ams::svc::lp64::SecureMonitorArguments *args) {
KSystemControl::CallSecureMonitorFromUser(args);
}
/* ============================= 64From32 ABI ============================= */
/* CallSecureMonitor64From32 is not supported. */
}
| 1,166
|
C++
|
.cpp
| 27
| 39.777778
| 82
| 0.602837
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,029
|
kern_svc_port.cpp
|
Atmosphere-NX_Atmosphere/libraries/libmesosphere/source/svc/kern_svc_port.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <mesosphere.hpp>
namespace ams::kern::svc {
/* ============================= Common ============================= */
namespace {
Result ManageNamedPort(ams::svc::Handle *out_server_handle, KUserPointer<const char *> user_name, s32 max_sessions) {
/* Copy the provided name from user memory to kernel memory. */
char name[KObjectName::NameLengthMax] = {};
R_TRY(user_name.CopyStringTo(name, sizeof(name)));
/* Validate that sessions and name are valid. */
R_UNLESS(max_sessions >= 0, svc::ResultOutOfRange());
R_UNLESS(name[sizeof(name) - 1] == '\x00', svc::ResultOutOfRange());
if (max_sessions > 0) {
/* Get the current handle table. */
auto &handle_table = GetCurrentProcess().GetHandleTable();
/* Create a new port. */
KPort *port = KPort::Create();
R_UNLESS(port != nullptr, svc::ResultOutOfResource());
/* Initialize the new port. */
port->Initialize(max_sessions, false, 0);
/* Register the port. */
KPort::Register(port);
/* Ensure that our only reference to the port is in the handle table when we're done. */
ON_SCOPE_EXIT {
port->GetClientPort().Close();
port->GetServerPort().Close();
};
/* Register the handle in the table. */
R_TRY(handle_table.Add(out_server_handle, std::addressof(port->GetServerPort())));
ON_RESULT_FAILURE { handle_table.Remove(*out_server_handle); };
/* Create a new object name. */
R_TRY(KObjectName::NewFromName(std::addressof(port->GetClientPort()), name));
} else /* if (max_sessions == 0) */ {
/* Ensure that this else case is correct. */
MESOSPHERE_AUDIT(max_sessions == 0);
/* If we're closing, there's no server handle. */
*out_server_handle = ams::svc::InvalidHandle;
/* Delete the object. */
R_TRY(KObjectName::Delete<KClientPort>(name));
}
R_SUCCEED();
}
Result CreatePort(ams::svc::Handle *out_server, ams::svc::Handle *out_client, int32_t max_sessions, bool is_light, uintptr_t name) {
/* Ensure max sessions is valid. */
R_UNLESS(max_sessions > 0, svc::ResultOutOfRange());
/* Get the current handle table. */
auto &handle_table = GetCurrentProcess().GetHandleTable();
/* Create a new port. */
KPort *port = KPort::Create();
R_UNLESS(port != nullptr, svc::ResultOutOfResource());
/* Initialize the port. */
port->Initialize(max_sessions, is_light, name);
/* Ensure that we clean up the port (and its only references are handle table) on function end. */
ON_SCOPE_EXIT {
port->GetServerPort().Close();
port->GetClientPort().Close();
};
/* Register the port. */
KPort::Register(port);
/* Add the client to the handle table. */
R_TRY(handle_table.Add(out_client, std::addressof(port->GetClientPort())));
/* Ensure that we maintain a clean handle state on exit. */
ON_RESULT_FAILURE { handle_table.Remove(*out_client); };
/* Add the server to the handle table. */
R_RETURN(handle_table.Add(out_server, std::addressof(port->GetServerPort())));
}
Result ConnectToNamedPort(ams::svc::Handle *out, KUserPointer<const char *> user_name) {
/* Copy the provided name from user memory to kernel memory. */
char name[KObjectName::NameLengthMax] = {};
R_TRY(user_name.CopyStringTo(name, sizeof(name)));
/* Validate that name is valid. */
R_UNLESS(name[sizeof(name) - 1] == '\x00', svc::ResultOutOfRange());
/* Get the current handle table. */
auto &handle_table = GetCurrentProcess().GetHandleTable();
/* Find the client port. */
auto port = KObjectName::Find<KClientPort>(name);
R_UNLESS(port.IsNotNull(), svc::ResultNotFound());
/* Reserve a handle for the port. */
/* NOTE: Nintendo really does write directly to the output handle here. */
R_TRY(handle_table.Reserve(out));
ON_RESULT_FAILURE { handle_table.Unreserve(*out); };
/* Create a session. */
KClientSession *session;
R_TRY(port->CreateSession(std::addressof(session)));
/* Register the session in the table, close the extra reference. */
handle_table.Register(*out, session);
session->Close();
/* We succeeded. */
R_SUCCEED();
}
Result ConnectToPort(ams::svc::Handle *out, ams::svc::Handle port) {
/* Get the current handle table. */
auto &handle_table = GetCurrentProcess().GetHandleTable();
/* Get the client port. */
KScopedAutoObject client_port = handle_table.GetObject<KClientPort>(port);
R_UNLESS(client_port.IsNotNull(), svc::ResultInvalidHandle());
/* Reserve a handle for the port. */
/* NOTE: Nintendo really does write directly to the output handle here. */
R_TRY(handle_table.Reserve(out));
ON_RESULT_FAILURE { handle_table.Unreserve(*out); };
/* Create the session. */
KAutoObject *session;
if (client_port->IsLight()) {
R_TRY(client_port->CreateLightSession(reinterpret_cast<KLightClientSession **>(std::addressof(session))));
} else {
R_TRY(client_port->CreateSession(reinterpret_cast<KClientSession **>(std::addressof(session))));
}
/* Register the session. */
handle_table.Register(*out, session);
session->Close();
/* We succeeded. */
R_SUCCEED();
}
}
/* ============================= 64 ABI ============================= */
Result ConnectToNamedPort64(ams::svc::Handle *out_handle, KUserPointer<const char *> name) {
R_RETURN(ConnectToNamedPort(out_handle, name));
}
Result CreatePort64(ams::svc::Handle *out_server_handle, ams::svc::Handle *out_client_handle, int32_t max_sessions, bool is_light, ams::svc::Address name) {
R_RETURN(CreatePort(out_server_handle, out_client_handle, max_sessions, is_light, name));
}
Result ManageNamedPort64(ams::svc::Handle *out_server_handle, KUserPointer<const char *> name, int32_t max_sessions) {
R_RETURN(ManageNamedPort(out_server_handle, name, max_sessions));
}
Result ConnectToPort64(ams::svc::Handle *out_handle, ams::svc::Handle port) {
R_RETURN(ConnectToPort(out_handle, port));
}
/* ============================= 64From32 ABI ============================= */
Result ConnectToNamedPort64From32(ams::svc::Handle *out_handle, KUserPointer<const char *> name) {
R_RETURN(ConnectToNamedPort(out_handle, name));
}
Result CreatePort64From32(ams::svc::Handle *out_server_handle, ams::svc::Handle *out_client_handle, int32_t max_sessions, bool is_light, ams::svc::Address name) {
R_RETURN(CreatePort(out_server_handle, out_client_handle, max_sessions, is_light, name));
}
Result ManageNamedPort64From32(ams::svc::Handle *out_server_handle, KUserPointer<const char *> name, int32_t max_sessions) {
R_RETURN(ManageNamedPort(out_server_handle, name, max_sessions));
}
Result ConnectToPort64From32(ams::svc::Handle *out_handle, ams::svc::Handle port) {
R_RETURN(ConnectToPort(out_handle, port));
}
}
| 8,607
|
C++
|
.cpp
| 155
| 44.206452
| 166
| 0.586289
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,030
|
kern_svc_session.cpp
|
Atmosphere-NX_Atmosphere/libraries/libmesosphere/source/svc/kern_svc_session.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <mesosphere.hpp>
namespace ams::kern::svc {
/* ============================= Common ============================= */
namespace {
template<typename T>
Result CreateSession(ams::svc::Handle *out_server, ams::svc::Handle *out_client, uintptr_t name) {
/* Get the current process and handle table. */
auto &process = GetCurrentProcess();
auto &handle_table = process.GetHandleTable();
/* Declare the session we're going to allocate. */
T *session;
/* Reserve a new session from the process resource limit. */
KScopedResourceReservation session_reservation(std::addressof(process), ams::svc::LimitableResource_SessionCountMax);
if (session_reservation.Succeeded()) {
/* Allocate a session normally. */
session = T::Create();
} else {
/* We couldn't reserve a session. Check that we support dynamically expanding the resource limit. */
R_UNLESS(process.GetResourceLimit() == std::addressof(Kernel::GetSystemResourceLimit()), svc::ResultLimitReached());
R_UNLESS(KTargetSystem::IsDynamicResourceLimitsEnabled(), svc::ResultLimitReached());
/* Try to allocate a session from unused slab memory. */
session = T::CreateFromUnusedSlabMemory();
R_UNLESS(session != nullptr, svc::ResultLimitReached());
ON_RESULT_FAILURE { session->Close(); };
/* If we're creating a KSession, we want to add two KSessionRequests to the heap, to prevent request exhaustion. */
/* NOTE: Nintendo checks if session->DynamicCast<KSession *>() != nullptr, but there's no reason to not do this statically. */
if constexpr (std::same_as<T, KSession>) {
for (size_t i = 0; i < 2; ++i) {
KSessionRequest *request = KSessionRequest::CreateFromUnusedSlabMemory();
R_UNLESS(request != nullptr, svc::ResultLimitReached());
request->Close();
}
}
/* We successfully allocated a session, so add the object we allocated to the resource limit. */
Kernel::GetSystemResourceLimit().Add(ams::svc::LimitableResource_SessionCountMax, 1);
}
/* Check that we successfully created a session. */
R_UNLESS(session != nullptr, svc::ResultOutOfResource());
/* Initialize the session. */
session->Initialize(nullptr, name);
/* Commit the session reservation. */
session_reservation.Commit();
/* Ensure that we clean up the session (and its only references are handle table) on function end. */
ON_SCOPE_EXIT {
session->GetClientSession().Close();
session->GetServerSession().Close();
};
/* Register the session. */
T::Register(session);
/* Add the server session to the handle table. */
R_TRY(handle_table.Add(out_server, std::addressof(session->GetServerSession())));
/* Ensure that we maintaing a clean handle state on exit. */
ON_RESULT_FAILURE { handle_table.Remove(*out_server); };
/* Add the client session to the handle table. */
R_RETURN(handle_table.Add(out_client, std::addressof(session->GetClientSession())));
}
Result CreateSession(ams::svc::Handle *out_server, ams::svc::Handle *out_client, bool is_light, uintptr_t name) {
if (is_light) {
R_RETURN(CreateSession<KLightSession>(out_server, out_client, name));
} else {
R_RETURN(CreateSession<KSession>(out_server, out_client, name));
}
}
Result AcceptSession(ams::svc::Handle *out, ams::svc::Handle port_handle) {
/* Get the current handle table. */
auto &handle_table = GetCurrentProcess().GetHandleTable();
/* Get the server port. */
KScopedAutoObject port = handle_table.GetObject<KServerPort>(port_handle);
R_UNLESS(port.IsNotNull(), svc::ResultInvalidHandle());
/* Reserve an entry for the new session. */
R_TRY(handle_table.Reserve(out));
ON_RESULT_FAILURE { handle_table.Unreserve(*out); };
/* Accept the session. */
KAutoObject *session;
if (port->IsLight()) {
session = port->AcceptLightSession();
} else {
session = port->AcceptSession();
}
/* Ensure we accepted successfully. */
R_UNLESS(session != nullptr, svc::ResultNotFound());
/* Register the session. */
handle_table.Register(*out, session);
session->Close();
R_SUCCEED();
}
}
/* ============================= 64 ABI ============================= */
Result CreateSession64(ams::svc::Handle *out_server_session_handle, ams::svc::Handle *out_client_session_handle, bool is_light, ams::svc::Address name) {
R_RETURN(CreateSession(out_server_session_handle, out_client_session_handle, is_light, name));
}
Result AcceptSession64(ams::svc::Handle *out_handle, ams::svc::Handle port) {
R_RETURN(AcceptSession(out_handle, port));
}
/* ============================= 64From32 ABI ============================= */
Result CreateSession64From32(ams::svc::Handle *out_server_session_handle, ams::svc::Handle *out_client_session_handle, bool is_light, ams::svc::Address name) {
R_RETURN(CreateSession(out_server_session_handle, out_client_session_handle, is_light, name));
}
Result AcceptSession64From32(ams::svc::Handle *out_handle, ams::svc::Handle port) {
R_RETURN(AcceptSession(out_handle, port));
}
}
| 6,664
|
C++
|
.cpp
| 117
| 45.495726
| 163
| 0.590972
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,031
|
kern_svc_lock.cpp
|
Atmosphere-NX_Atmosphere/libraries/libmesosphere/source/svc/kern_svc_lock.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <mesosphere.hpp>
namespace ams::kern::svc {
/* ============================= Common ============================= */
namespace {
constexpr bool IsKernelAddress(uintptr_t address) {
return KernelVirtualAddressSpaceBase <= address && address < KernelVirtualAddressSpaceEnd;
}
Result ArbitrateLock(ams::svc::Handle thread_handle, uintptr_t address, uint32_t tag) {
/* Validate the input address. */
R_UNLESS(!IsKernelAddress(address), svc::ResultInvalidCurrentMemory());
R_UNLESS(util::IsAligned(address, sizeof(u32)), svc::ResultInvalidAddress());
R_RETURN(KConditionVariable::WaitForAddress(thread_handle, address, tag));
}
Result ArbitrateUnlock(uintptr_t address) {
/* Validate the input address. */
R_UNLESS(!IsKernelAddress(address), svc::ResultInvalidCurrentMemory());
R_UNLESS(util::IsAligned(address, sizeof(u32)), svc::ResultInvalidAddress());
R_RETURN(KConditionVariable::SignalToAddress(address));
}
}
/* ============================= 64 ABI ============================= */
Result ArbitrateLock64(ams::svc::Handle thread_handle, ams::svc::Address address, uint32_t tag) {
R_RETURN(ArbitrateLock(thread_handle, address, tag));
}
Result ArbitrateUnlock64(ams::svc::Address address) {
R_RETURN(ArbitrateUnlock(address));
}
/* ============================= 64From32 ABI ============================= */
Result ArbitrateLock64From32(ams::svc::Handle thread_handle, ams::svc::Address address, uint32_t tag) {
R_RETURN(ArbitrateLock(thread_handle, address, tag));
}
Result ArbitrateUnlock64From32(ams::svc::Address address) {
R_RETURN(ArbitrateUnlock(address));
}
}
| 2,505
|
C++
|
.cpp
| 50
| 43.7
| 107
| 0.631816
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,032
|
kern_svc_ipc.cpp
|
Atmosphere-NX_Atmosphere/libraries/libmesosphere/source/svc/kern_svc_ipc.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <mesosphere.hpp>
#pragma GCC push_options
#pragma GCC optimize ("-O3")
namespace ams::kern::svc {
/* ============================= Common ============================= */
namespace {
ALWAYS_INLINE Result SendSyncRequestImpl(uintptr_t message, size_t buffer_size, ams::svc::Handle session_handle) {
/* Get the client session. */
KScopedAutoObject session = GetCurrentProcess().GetHandleTable().GetObject<KClientSession>(session_handle);
R_UNLESS(session.IsNotNull(), svc::ResultInvalidHandle());
/* Get the parent, and persist a reference to it until we're done. */
KScopedAutoObject parent = session->GetParent();
MESOSPHERE_ASSERT(parent.IsNotNull());
/* Send the request. */
R_RETURN(session->SendSyncRequest(message, buffer_size));
}
ALWAYS_INLINE Result ReplyAndReceiveImpl(int32_t *out_index, uintptr_t message, size_t buffer_size, KPhysicalAddress message_paddr, KSynchronizationObject **objs, int32_t num_objects, ams::svc::Handle reply_target, int64_t timeout_ns) {
/* Reply to the target, if one is specified. */
if (reply_target != ams::svc::InvalidHandle) {
KScopedAutoObject session = GetCurrentProcess().GetHandleTable().GetObject<KServerSession>(reply_target);
R_UNLESS(session.IsNotNull(), svc::ResultInvalidHandle());
/* If we fail to reply, we want to set the output index to -1. */
ON_RESULT_FAILURE { *out_index = -1; };
/* Send the reply. */
R_TRY(session->SendReply(message, buffer_size, message_paddr));
}
/* Receive a message. */
{
/* Convert the timeout from nanoseconds to ticks. */
/* NOTE: Nintendo does not use this conversion logic in WaitSynchronization... */
s64 timeout;
if (timeout_ns > 0) {
const ams::svc::Tick offset_tick(TimeSpan::FromNanoSeconds(timeout_ns));
if (AMS_LIKELY(offset_tick > 0)) {
timeout = KHardwareTimer::GetTick() + offset_tick + 2;
if (AMS_UNLIKELY(timeout <= 0)) {
timeout = std::numeric_limits<s64>::max();
}
} else {
timeout = std::numeric_limits<s64>::max();
}
} else {
timeout = timeout_ns;
}
/* Wait for a message. */
while (true) {
/* Close any pending objects before we wait. */
GetCurrentThread().DestroyClosedObjects();
/* Wait for an object. */
s32 index;
Result result = KSynchronizationObject::Wait(std::addressof(index), objs, num_objects, timeout);
if (svc::ResultTimedOut::Includes(result)) {
R_THROW(result);
}
/* Receive the request. */
if (R_SUCCEEDED(result)) {
KServerSession *session = objs[index]->DynamicCast<KServerSession *>();
if (session != nullptr) {
result = session->ReceiveRequest(message, buffer_size, message_paddr);
if (svc::ResultNotFound::Includes(result)) {
continue;
}
}
}
*out_index = index;
R_RETURN(result);
}
}
}
ALWAYS_INLINE Result ReplyAndReceiveImpl(int32_t *out_index, uintptr_t message, size_t buffer_size, KPhysicalAddress message_paddr, KUserPointer<const ams::svc::Handle *> user_handles, int32_t num_handles, ams::svc::Handle reply_target, int64_t timeout_ns) {
/* Ensure number of handles is valid. */
R_UNLESS(0 <= num_handles && num_handles <= ams::svc::ArgumentHandleCountMax, svc::ResultOutOfRange());
/* Get the synchronization context. */
auto &handle_table = GetCurrentProcess().GetHandleTable();
KSynchronizationObject **objs = GetCurrentThread().GetSynchronizationObjectBuffer();
ams::svc::Handle *handles = GetCurrentThread().GetHandleBuffer();
/* Copy user handles. */
if (num_handles > 0) {
/* Ensure that we can try to get the handles. */
R_UNLESS(GetCurrentProcess().GetPageTable().Contains(KProcessAddress(user_handles.GetUnsafePointer()), num_handles * sizeof(ams::svc::Handle)), svc::ResultInvalidPointer());
/* Get the handles. */
R_TRY(user_handles.CopyArrayTo(handles, num_handles));
/* Convert the handles to objects. */
R_UNLESS(handle_table.GetMultipleObjects<KSynchronizationObject>(objs, handles, num_handles), svc::ResultInvalidHandle());
}
/* Ensure handles are closed when we're done. */
ON_SCOPE_EXIT {
for (auto i = 0; i < num_handles; ++i) {
objs[i]->Close();
}
};
R_RETURN(ReplyAndReceiveImpl(out_index, message, buffer_size, message_paddr, objs, num_handles, reply_target, timeout_ns));
}
ALWAYS_INLINE Result SendSyncRequest(ams::svc::Handle session_handle) {
R_RETURN(SendSyncRequestImpl(0, 0, session_handle));
}
ALWAYS_INLINE Result SendSyncRequestWithUserBuffer(uintptr_t message, size_t buffer_size, ams::svc::Handle session_handle) {
/* Validate that the message buffer is page aligned and does not overflow. */
R_UNLESS(util::IsAligned(message, PageSize), svc::ResultInvalidAddress());
R_UNLESS(buffer_size > 0, svc::ResultInvalidSize());
R_UNLESS(util::IsAligned(buffer_size, PageSize), svc::ResultInvalidSize());
R_UNLESS(message < message + buffer_size, svc::ResultInvalidCurrentMemory());
/* Get the process page table. */
auto &page_table = GetCurrentProcess().GetPageTable();
/* Lock the message buffer. */
R_TRY(page_table.LockForIpcUserBuffer(nullptr, message, buffer_size));
{
/* If we fail to send the message, unlock the message buffer. */
ON_RESULT_FAILURE { page_table.UnlockForIpcUserBuffer(message, buffer_size); };
/* Send the request. */
MESOSPHERE_ASSERT(message != 0);
R_TRY(SendSyncRequestImpl(message, buffer_size, session_handle));
}
/* We successfully processed, so try to unlock the message buffer. */
R_RETURN(page_table.UnlockForIpcUserBuffer(message, buffer_size));
}
ALWAYS_INLINE Result SendAsyncRequestWithUserBufferImpl(ams::svc::Handle *out_event_handle, uintptr_t message, size_t buffer_size, ams::svc::Handle session_handle) {
/* Get the process and handle table. */
auto &process = GetCurrentProcess();
auto &handle_table = process.GetHandleTable();
/* Reserve a new event from the process resource limit. */
KScopedResourceReservation event_reservation(std::addressof(process), ams::svc::LimitableResource_EventCountMax);
R_UNLESS(event_reservation.Succeeded(), svc::ResultLimitReached());
/* Get the client session. */
KScopedAutoObject session = GetCurrentProcess().GetHandleTable().GetObject<KClientSession>(session_handle);
R_UNLESS(session.IsNotNull(), svc::ResultInvalidHandle());
/* Get the parent, and persist a reference to it until we're done. */
KScopedAutoObject parent = session->GetParent();
MESOSPHERE_ASSERT(parent.IsNotNull());
/* Create a new event. */
KEvent *event = KEvent::Create();
R_UNLESS(event != nullptr, svc::ResultOutOfResource());
/* Initialize the event. */
event->Initialize();
/* Commit our reservation. */
event_reservation.Commit();
/* At end of scope, kill the standing event references. */
ON_SCOPE_EXIT {
event->GetReadableEvent().Close();
event->Close();
};
/* Register the event. */
KEvent::Register(event);
/* Add the readable event to the handle table. */
R_TRY(handle_table.Add(out_event_handle, std::addressof(event->GetReadableEvent())));
/* Ensure that if we fail to send the request, we close the readable handle. */
ON_RESULT_FAILURE { handle_table.Remove(*out_event_handle); };
/* Send the async request. */
R_RETURN(session->SendAsyncRequest(event, message, buffer_size));
}
ALWAYS_INLINE Result SendAsyncRequestWithUserBuffer(ams::svc::Handle *out_event_handle, uintptr_t message, size_t buffer_size, ams::svc::Handle session_handle) {
/* Validate that the message buffer is page aligned and does not overflow. */
R_UNLESS(util::IsAligned(message, PageSize), svc::ResultInvalidAddress());
R_UNLESS(buffer_size > 0, svc::ResultInvalidSize());
R_UNLESS(util::IsAligned(buffer_size, PageSize), svc::ResultInvalidSize());
R_UNLESS(message < message + buffer_size, svc::ResultInvalidCurrentMemory());
/* Get the process page table. */
auto &page_table = GetCurrentProcess().GetPageTable();
/* Lock the message buffer. */
R_TRY(page_table.LockForIpcUserBuffer(nullptr, message, buffer_size));
/* Ensure that if we fail and aren't terminating that we unlock the user buffer. */
ON_RESULT_FAILURE_BESIDES(svc::ResultTerminationRequested) {
page_table.UnlockForIpcUserBuffer(message, buffer_size);
};
/* Send the request. */
MESOSPHERE_ASSERT(message != 0);
R_RETURN(SendAsyncRequestWithUserBufferImpl(out_event_handle, message, buffer_size, session_handle));
}
ALWAYS_INLINE Result ReplyAndReceive(int32_t *out_index, KUserPointer<const ams::svc::Handle *> handles, int32_t num_handles, ams::svc::Handle reply_target, int64_t timeout_ns) {
R_RETURN(ReplyAndReceiveImpl(out_index, 0, 0, Null<KPhysicalAddress>, handles, num_handles, reply_target, timeout_ns));
}
ALWAYS_INLINE Result ReplyAndReceiveWithUserBuffer(int32_t *out_index, uintptr_t message, size_t buffer_size, KUserPointer<const ams::svc::Handle *> handles, int32_t num_handles, ams::svc::Handle reply_target, int64_t timeout_ns) {
/* Validate that the message buffer is page aligned and does not overflow. */
R_UNLESS(util::IsAligned(message, PageSize), svc::ResultInvalidAddress());
R_UNLESS(buffer_size > 0, svc::ResultInvalidSize());
R_UNLESS(util::IsAligned(buffer_size, PageSize), svc::ResultInvalidSize());
R_UNLESS(message < message + buffer_size, svc::ResultInvalidCurrentMemory());
/* Get the process page table. */
auto &page_table = GetCurrentProcess().GetPageTable();
/* Lock the message buffer, getting its physical address. */
KPhysicalAddress message_paddr;
R_TRY(page_table.LockForIpcUserBuffer(std::addressof(message_paddr), message, buffer_size));
{
/* If we fail to send the message, unlock the message buffer. */
ON_RESULT_FAILURE { page_table.UnlockForIpcUserBuffer(message, buffer_size); };
/* Reply/Receive the request. */
MESOSPHERE_ASSERT(message != 0);
R_TRY(ReplyAndReceiveImpl(out_index, message, buffer_size, message_paddr, handles, num_handles, reply_target, timeout_ns));
}
/* We successfully processed, so try to unlock the message buffer. */
R_RETURN(page_table.UnlockForIpcUserBuffer(message, buffer_size));
}
}
/* ============================= 64 ABI ============================= */
Result SendSyncRequest64(ams::svc::Handle session_handle) {
R_RETURN(SendSyncRequest(session_handle));
}
Result SendSyncRequestWithUserBuffer64(ams::svc::Address message_buffer, ams::svc::Size message_buffer_size, ams::svc::Handle session_handle) {
R_RETURN(SendSyncRequestWithUserBuffer(message_buffer, message_buffer_size, session_handle));
}
Result SendAsyncRequestWithUserBuffer64(ams::svc::Handle *out_event_handle, ams::svc::Address message_buffer, ams::svc::Size message_buffer_size, ams::svc::Handle session_handle) {
R_RETURN(SendAsyncRequestWithUserBuffer(out_event_handle, message_buffer, message_buffer_size, session_handle));
}
Result ReplyAndReceive64(int32_t *out_index, KUserPointer<const ams::svc::Handle *> handles, int32_t num_handles, ams::svc::Handle reply_target, int64_t timeout_ns) {
R_RETURN(ReplyAndReceive(out_index, handles, num_handles, reply_target, timeout_ns));
}
Result ReplyAndReceiveWithUserBuffer64(int32_t *out_index, ams::svc::Address message_buffer, ams::svc::Size message_buffer_size, KUserPointer<const ams::svc::Handle *> handles, int32_t num_handles, ams::svc::Handle reply_target, int64_t timeout_ns) {
R_RETURN(ReplyAndReceiveWithUserBuffer(out_index, message_buffer, message_buffer_size, handles, num_handles, reply_target, timeout_ns));
}
/* ============================= 64From32 ABI ============================= */
Result SendSyncRequest64From32(ams::svc::Handle session_handle) {
R_RETURN(SendSyncRequest(session_handle));
}
Result SendSyncRequestWithUserBuffer64From32(ams::svc::Address message_buffer, ams::svc::Size message_buffer_size, ams::svc::Handle session_handle) {
R_RETURN(SendSyncRequestWithUserBuffer(message_buffer, message_buffer_size, session_handle));
}
Result SendAsyncRequestWithUserBuffer64From32(ams::svc::Handle *out_event_handle, ams::svc::Address message_buffer, ams::svc::Size message_buffer_size, ams::svc::Handle session_handle) {
R_RETURN(SendAsyncRequestWithUserBuffer(out_event_handle, message_buffer, message_buffer_size, session_handle));
}
Result ReplyAndReceive64From32(int32_t *out_index, KUserPointer<const ams::svc::Handle *> handles, int32_t num_handles, ams::svc::Handle reply_target, int64_t timeout_ns) {
R_RETURN(ReplyAndReceive(out_index, handles, num_handles, reply_target, timeout_ns));
}
Result ReplyAndReceiveWithUserBuffer64From32(int32_t *out_index, ams::svc::Address message_buffer, ams::svc::Size message_buffer_size, KUserPointer<const ams::svc::Handle *> handles, int32_t num_handles, ams::svc::Handle reply_target, int64_t timeout_ns) {
R_RETURN(ReplyAndReceiveWithUserBuffer(out_index, message_buffer, message_buffer_size, handles, num_handles, reply_target, timeout_ns));
}
}
#pragma GCC pop_options
| 16,058
|
C++
|
.cpp
| 242
| 53.413223
| 266
| 0.617285
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,033
|
kern_svc_physical_memory.cpp
|
Atmosphere-NX_Atmosphere/libraries/libmesosphere/source/svc/kern_svc_physical_memory.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <mesosphere.hpp>
namespace ams::kern::svc {
/* ============================= Common ============================= */
namespace {
Result SetHeapSize(uintptr_t *out_address, size_t size) {
/* Validate size. */
R_UNLESS(util::IsAligned(size, ams::svc::HeapSizeAlignment), svc::ResultInvalidSize());
R_UNLESS(size < ams::kern::MainMemorySizeMax, svc::ResultInvalidSize());
/* Set the heap size. */
KProcessAddress address = Null<KProcessAddress>;
R_TRY(GetCurrentProcess().GetPageTable().SetHeapSize(std::addressof(address), size));
/* Set the output. */
*out_address = GetInteger(address);
R_SUCCEED();
}
Result SetUnsafeLimit(size_t limit) {
/* Ensure the size is aligned. */
R_UNLESS(util::IsAligned(limit, PageSize), svc::ResultInvalidSize());
/* Ensure that the size is not bigger than we can accommodate. */
R_UNLESS(limit <= Kernel::GetMemoryManager().GetSize(KMemoryManager::Pool_Unsafe), svc::ResultOutOfRange());
/* Set the size. */
R_RETURN(Kernel::GetUnsafeMemory().SetLimitSize(limit));
}
Result MapPhysicalMemory(uintptr_t address, size_t size) {
/* Validate address / size. */
const size_t min_alignment = Kernel::GetMemoryManager().GetMinimumAlignment(GetCurrentProcess().GetMemoryPool());
R_UNLESS(util::IsAligned(address, min_alignment), svc::ResultInvalidAddress());
R_UNLESS(util::IsAligned(size, min_alignment), svc::ResultInvalidSize());
R_UNLESS(size > 0, svc::ResultInvalidSize());
R_UNLESS((address < address + size), svc::ResultInvalidMemoryRegion());
/* Verify that the process has system resource. */
auto &process = GetCurrentProcess();
R_UNLESS(process.GetTotalSystemResourceSize() > 0, svc::ResultInvalidState());
/* Verify that the region is in range. */
auto &page_table = process.GetPageTable();
R_UNLESS(page_table.IsInAliasRegion(address, size), svc::ResultInvalidMemoryRegion());
/* Map the memory. */
R_TRY(page_table.MapPhysicalMemory(address, size));
R_SUCCEED();
}
Result UnmapPhysicalMemory(uintptr_t address, size_t size) {
/* Validate address / size. */
const size_t min_alignment = Kernel::GetMemoryManager().GetMinimumAlignment(GetCurrentProcess().GetMemoryPool());
R_UNLESS(util::IsAligned(address, min_alignment), svc::ResultInvalidAddress());
R_UNLESS(util::IsAligned(size, min_alignment), svc::ResultInvalidSize());
R_UNLESS(size > 0, svc::ResultInvalidSize());
R_UNLESS((address < address + size), svc::ResultInvalidMemoryRegion());
/* Verify that the process has system resource. */
auto &process = GetCurrentProcess();
R_UNLESS(process.GetTotalSystemResourceSize() > 0, svc::ResultInvalidState());
/* Verify that the region is in range. */
auto &page_table = process.GetPageTable();
R_UNLESS(page_table.IsInAliasRegion(address, size), svc::ResultInvalidMemoryRegion());
/* Unmap the memory. */
R_TRY(page_table.UnmapPhysicalMemory(address, size));
R_SUCCEED();
}
Result MapPhysicalMemoryUnsafe(uintptr_t address, size_t size) {
/* Validate address / size. */
R_UNLESS(util::IsAligned(address, PageSize), svc::ResultInvalidAddress());
R_UNLESS(util::IsAligned(size, PageSize), svc::ResultInvalidSize());
R_UNLESS(size > 0, svc::ResultInvalidSize());
R_UNLESS((address < address + size), svc::ResultInvalidCurrentMemory());
/* Verify that the region is in range. */
auto &process = GetCurrentProcess();
auto &page_table = process.GetPageTable();
R_UNLESS(page_table.IsInUnsafeAliasRegion(address, size), svc::ResultInvalidMemoryRegion());
/* Verify that the process isn't already using the unsafe pool. */
R_UNLESS(process.GetMemoryPool() != KMemoryManager::Pool_Unsafe, svc::ResultInvalidMemoryPool());
/* Map the memory. */
R_TRY(page_table.MapPhysicalMemoryUnsafe(address, size));
R_SUCCEED();
}
Result UnmapPhysicalMemoryUnsafe(uintptr_t address, size_t size) {
/* Validate address / size. */
R_UNLESS(util::IsAligned(address, PageSize), svc::ResultInvalidAddress());
R_UNLESS(util::IsAligned(size, PageSize), svc::ResultInvalidSize());
R_UNLESS(size > 0, svc::ResultInvalidSize());
R_UNLESS((address < address + size), svc::ResultInvalidCurrentMemory());
/* Verify that the region is in range. */
auto &process = GetCurrentProcess();
auto &page_table = process.GetPageTable();
R_UNLESS(page_table.IsInUnsafeAliasRegion(address, size), svc::ResultInvalidMemoryRegion());
/* Unmap the memory. */
R_TRY(page_table.UnmapPhysicalMemoryUnsafe(address, size));
R_SUCCEED();
}
}
/* ============================= 64 ABI ============================= */
Result SetHeapSize64(ams::svc::Address *out_address, ams::svc::Size size) {
static_assert(sizeof(*out_address) == sizeof(uintptr_t));
R_RETURN(SetHeapSize(reinterpret_cast<uintptr_t *>(out_address), size));
}
Result MapPhysicalMemory64(ams::svc::Address address, ams::svc::Size size) {
R_RETURN(MapPhysicalMemory(address, size));
}
Result UnmapPhysicalMemory64(ams::svc::Address address, ams::svc::Size size) {
R_RETURN(UnmapPhysicalMemory(address, size));
}
Result MapPhysicalMemoryUnsafe64(ams::svc::Address address, ams::svc::Size size) {
R_RETURN(MapPhysicalMemoryUnsafe(address, size));
}
Result UnmapPhysicalMemoryUnsafe64(ams::svc::Address address, ams::svc::Size size) {
R_RETURN(UnmapPhysicalMemoryUnsafe(address, size));
}
Result SetUnsafeLimit64(ams::svc::Size limit) {
R_RETURN(SetUnsafeLimit(limit));
}
/* ============================= 64From32 ABI ============================= */
Result SetHeapSize64From32(ams::svc::Address *out_address, ams::svc::Size size) {
static_assert(sizeof(*out_address) == sizeof(uintptr_t));
R_RETURN(SetHeapSize(reinterpret_cast<uintptr_t *>(out_address), size));
}
Result MapPhysicalMemory64From32(ams::svc::Address address, ams::svc::Size size) {
R_RETURN(MapPhysicalMemory(address, size));
}
Result UnmapPhysicalMemory64From32(ams::svc::Address address, ams::svc::Size size) {
R_RETURN(UnmapPhysicalMemory(address, size));
}
Result MapPhysicalMemoryUnsafe64From32(ams::svc::Address address, ams::svc::Size size) {
R_RETURN(MapPhysicalMemoryUnsafe(address, size));
}
Result UnmapPhysicalMemoryUnsafe64From32(ams::svc::Address address, ams::svc::Size size) {
R_RETURN(UnmapPhysicalMemoryUnsafe(address, size));
}
Result SetUnsafeLimit64From32(ams::svc::Size limit) {
R_RETURN(SetUnsafeLimit(limit));
}
}
| 8,210
|
C++
|
.cpp
| 144
| 47.444444
| 125
| 0.61805
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,034
|
kern_svc_cache.cpp
|
Atmosphere-NX_Atmosphere/libraries/libmesosphere/source/svc/kern_svc_cache.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <mesosphere.hpp>
namespace ams::kern::svc {
/* ============================= Common ============================= */
namespace {
class CacheOperation {
public:
virtual void Operate(void *address, size_t size) const = 0;
};
Result DoProcessCacheOperation(const CacheOperation &operation, KProcessPageTable &page_table, uintptr_t address, size_t size) {
/* Determine aligned extents. */
const uintptr_t aligned_start = util::AlignDown(address, PageSize);
const uintptr_t aligned_end = util::AlignUp(address + size, PageSize);
/* Iterate over and operate on contiguous ranges. */
uintptr_t cur_address = aligned_start;
size_t remaining = size;
while (remaining > 0) {
/* Get a contiguous range to operate on. */
KPageTableBase::MemoryRange contig_range;
R_TRY(page_table.OpenMemoryRangeForProcessCacheOperation(std::addressof(contig_range), cur_address, aligned_end - cur_address));
/* Close the range when we're done operating on it. */
ON_SCOPE_EXIT { contig_range.Close(); };
/* Adjust to remain within range. */
KVirtualAddress operate_address = KMemoryLayout::GetLinearVirtualAddress(contig_range.GetAddress());
size_t operate_size = contig_range.GetSize();
if (cur_address < address) {
operate_address += (address - cur_address);
operate_size -= (address - cur_address);
}
if (operate_size > remaining) {
operate_size = remaining;
}
/* Operate. */
operation.Operate(GetVoidPointer(operate_address), operate_size);
/* Advance. */
cur_address += contig_range.GetSize();
remaining -= operate_size;
}
MESOSPHERE_ASSERT(remaining == 0);
R_SUCCEED();
}
void FlushEntireDataCache() {
/* Flushing cache takes up to 1ms, so determine our minimum end tick. */
const s64 timeout = KHardwareTimer::GetTick() + ams::svc::Tick(TimeSpan::FromMilliSeconds(1));
/* Flush the entire data cache. */
cpu::FlushEntireDataCache();
/* Wait for 1ms to have passed. */
while (KHardwareTimer::GetTick() < timeout) {
cpu::Yield();
}
}
Result FlushDataCache(uintptr_t address, size_t size) {
/* Succeed if there's nothing to do. */
R_SUCCEED_IF(size == 0);
/* Validate that the region is within range. */
R_UNLESS(GetCurrentProcess().GetPageTable().Contains(address, size), svc::ResultInvalidCurrentMemory());
/* Flush the cache. */
R_TRY(cpu::FlushDataCache(reinterpret_cast<void *>(address), size));
R_SUCCEED();
}
Result InvalidateProcessDataCache(ams::svc::Handle process_handle, uint64_t address, uint64_t size) {
/* Validate address/size. */
R_UNLESS(size > 0, svc::ResultInvalidSize());
R_UNLESS(address == static_cast<uintptr_t>(address), svc::ResultInvalidCurrentMemory());
R_UNLESS(size == static_cast<size_t>(size), svc::ResultInvalidCurrentMemory());
/* Get the process from its handle. */
KScopedAutoObject process = GetCurrentProcess().GetHandleTable().GetObject<KProcess>(process_handle);
R_UNLESS(process.IsNotNull(), svc::ResultInvalidHandle());
/* Invalidate the cache. */
if (process.GetPointerUnsafe() == GetCurrentProcessPointer()) {
R_TRY(process->GetPageTable().InvalidateCurrentProcessDataCache(address, size));
} else {
R_TRY(process->GetPageTable().InvalidateProcessDataCache(address, size));
}
R_SUCCEED();
}
Result StoreProcessDataCache(ams::svc::Handle process_handle, uint64_t address, uint64_t size) {
/* Validate address/size. */
R_UNLESS(size > 0, svc::ResultInvalidSize());
R_UNLESS(address == static_cast<uintptr_t>(address), svc::ResultInvalidCurrentMemory());
R_UNLESS(size == static_cast<size_t>(size), svc::ResultInvalidCurrentMemory());
/* Get the process from its handle. */
KScopedAutoObject process = GetCurrentProcess().GetHandleTable().GetObject<KProcess>(process_handle);
R_UNLESS(process.IsNotNull(), svc::ResultInvalidHandle());
/* Verify the region is within range. */
auto &page_table = process->GetPageTable();
R_UNLESS(page_table.Contains(address, size), svc::ResultInvalidCurrentMemory());
/* Perform the operation. */
if (process.GetPointerUnsafe() == GetCurrentProcessPointer()) {
R_RETURN(cpu::StoreDataCache(reinterpret_cast<void *>(address), size));
} else {
class StoreCacheOperation : public CacheOperation {
public:
virtual void Operate(void *address, size_t size) const override { cpu::StoreDataCache(address, size); }
} operation;
R_RETURN(DoProcessCacheOperation(operation, page_table, address, size));
}
}
Result FlushProcessDataCache(ams::svc::Handle process_handle, uint64_t address, uint64_t size) {
/* Validate address/size. */
R_UNLESS(size > 0, svc::ResultInvalidSize());
R_UNLESS(address == static_cast<uintptr_t>(address), svc::ResultInvalidCurrentMemory());
R_UNLESS(size == static_cast<size_t>(size), svc::ResultInvalidCurrentMemory());
/* Get the process from its handle. */
KScopedAutoObject process = GetCurrentProcess().GetHandleTable().GetObject<KProcess>(process_handle);
R_UNLESS(process.IsNotNull(), svc::ResultInvalidHandle());
/* Verify the region is within range. */
auto &page_table = process->GetPageTable();
R_UNLESS(page_table.Contains(address, size), svc::ResultInvalidCurrentMemory());
/* Perform the operation. */
if (process.GetPointerUnsafe() == GetCurrentProcessPointer()) {
R_RETURN(cpu::FlushDataCache(reinterpret_cast<void *>(address), size));
} else {
class FlushCacheOperation : public CacheOperation {
public:
virtual void Operate(void *address, size_t size) const override { cpu::FlushDataCache(address, size); }
} operation;
R_RETURN(DoProcessCacheOperation(operation, page_table, address, size));
}
}
}
/* ============================= 64 ABI ============================= */
void FlushEntireDataCache64() {
return FlushEntireDataCache();
}
Result FlushDataCache64(ams::svc::Address address, ams::svc::Size size) {
R_RETURN(FlushDataCache(address, size));
}
Result InvalidateProcessDataCache64(ams::svc::Handle process_handle, uint64_t address, uint64_t size) {
R_RETURN(InvalidateProcessDataCache(process_handle, address, size));
}
Result StoreProcessDataCache64(ams::svc::Handle process_handle, uint64_t address, uint64_t size) {
R_RETURN(StoreProcessDataCache(process_handle, address, size));
}
Result FlushProcessDataCache64(ams::svc::Handle process_handle, uint64_t address, uint64_t size) {
R_RETURN(FlushProcessDataCache(process_handle, address, size));
}
/* ============================= 64From32 ABI ============================= */
void FlushEntireDataCache64From32() {
return FlushEntireDataCache();
}
Result FlushDataCache64From32(ams::svc::Address address, ams::svc::Size size) {
R_RETURN(FlushDataCache(address, size));
}
Result InvalidateProcessDataCache64From32(ams::svc::Handle process_handle, uint64_t address, uint64_t size) {
R_RETURN(InvalidateProcessDataCache(process_handle, address, size));
}
Result StoreProcessDataCache64From32(ams::svc::Handle process_handle, uint64_t address, uint64_t size) {
R_RETURN(StoreProcessDataCache(process_handle, address, size));
}
Result FlushProcessDataCache64From32(ams::svc::Handle process_handle, uint64_t address, uint64_t size) {
R_RETURN(FlushProcessDataCache(process_handle, address, size));
}
}
| 9,475
|
C++
|
.cpp
| 168
| 45.017857
| 144
| 0.602959
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,035
|
kern_svc_debug_string.cpp
|
Atmosphere-NX_Atmosphere/libraries/libmesosphere/source/svc/kern_svc_debug_string.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <mesosphere.hpp>
namespace ams::kern::svc {
/* ============================= Common ============================= */
namespace {
Result OutputDebugString(KUserPointer<const char *> debug_str, size_t len) {
/* Succeed immediately if there's nothing to output. */
R_SUCCEED_IF(len == 0);
/* Ensure that the data being output is in range. */
R_UNLESS(GetCurrentProcess().GetPageTable().Contains(KProcessAddress(debug_str.GetUnsafePointer()), len), svc::ResultInvalidCurrentMemory());
/* Output the string. */
R_RETURN(KDebugLog::PrintUserString(debug_str, len));
}
}
/* ============================= 64 ABI ============================= */
Result OutputDebugString64(KUserPointer<const char *> debug_str, ams::svc::Size len) {
R_RETURN(OutputDebugString(debug_str, len));
}
/* ============================= 64From32 ABI ============================= */
Result OutputDebugString64From32(KUserPointer<const char *> debug_str, ams::svc::Size len) {
R_RETURN(OutputDebugString(debug_str, len));
}
}
| 1,800
|
C++
|
.cpp
| 37
| 43.162162
| 153
| 0.612793
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,036
|
kern_svc_device_address_space.cpp
|
Atmosphere-NX_Atmosphere/libraries/libmesosphere/source/svc/kern_svc_device_address_space.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <mesosphere.hpp>
namespace ams::kern::svc {
/* ============================= Common ============================= */
namespace {
constexpr inline u64 DeviceAddressSpaceAlignMask = (1ul << 22) - 1;
constexpr bool IsProcessAndDeviceAligned(uint64_t process_address, uint64_t device_address) {
return (process_address & DeviceAddressSpaceAlignMask) == (device_address & DeviceAddressSpaceAlignMask);
}
Result CreateDeviceAddressSpace(ams::svc::Handle *out, uint64_t das_address, uint64_t das_size) {
/* Validate input. */
R_UNLESS(util::IsAligned(das_address, PageSize), svc::ResultInvalidMemoryRegion());
R_UNLESS(util::IsAligned(das_size, PageSize), svc::ResultInvalidMemoryRegion());
R_UNLESS(das_size > 0, svc::ResultInvalidMemoryRegion());
R_UNLESS((das_address < das_address + das_size), svc::ResultInvalidMemoryRegion());
/* Create the device address space. */
KDeviceAddressSpace *das = KDeviceAddressSpace::Create();
R_UNLESS(das != nullptr, svc::ResultOutOfResource());
ON_SCOPE_EXIT { das->Close(); };
/* Initialize the device address space. */
R_TRY(das->Initialize(das_address, das_size));
/* Register the device address space. */
KDeviceAddressSpace::Register(das);
/* Add to the handle table. */
R_TRY(GetCurrentProcess().GetHandleTable().Add(out, das));
R_SUCCEED();
}
Result AttachDeviceAddressSpace(ams::svc::DeviceName device_name, ams::svc::Handle das_handle) {
/* Get the device address space. */
KScopedAutoObject das = GetCurrentProcess().GetHandleTable().GetObject<KDeviceAddressSpace>(das_handle);
R_UNLESS(das.IsNotNull(), svc::ResultInvalidHandle());
/* Attach. */
R_RETURN(das->Attach(device_name));
}
Result DetachDeviceAddressSpace(ams::svc::DeviceName device_name, ams::svc::Handle das_handle) {
/* Get the device address space. */
KScopedAutoObject das = GetCurrentProcess().GetHandleTable().GetObject<KDeviceAddressSpace>(das_handle);
R_UNLESS(das.IsNotNull(), svc::ResultInvalidHandle());
/* Detach. */
R_RETURN(das->Detach(device_name));
}
constexpr bool IsValidDeviceMemoryPermission(ams::svc::MemoryPermission device_perm) {
switch (device_perm) {
case ams::svc::MemoryPermission_Read:
case ams::svc::MemoryPermission_Write:
case ams::svc::MemoryPermission_ReadWrite:
return true;
default:
return false;
}
}
Result MapDeviceAddressSpaceByForce(ams::svc::Handle das_handle, ams::svc::Handle process_handle, uint64_t process_address, size_t size, uint64_t device_address, u32 option) {
/* Decode the option. */
const util::BitPack32 option_pack = { option };
const auto device_perm = option_pack.Get<ams::svc::MapDeviceAddressSpaceOption::Permission>();
const auto reserved = option_pack.Get<ams::svc::MapDeviceAddressSpaceOption::Reserved>();
/* Validate input. */
R_UNLESS(util::IsAligned(process_address, PageSize), svc::ResultInvalidAddress());
R_UNLESS(util::IsAligned(device_address, PageSize), svc::ResultInvalidAddress());
R_UNLESS(util::IsAligned(size, PageSize), svc::ResultInvalidSize());
R_UNLESS(size > 0, svc::ResultInvalidSize());
R_UNLESS((process_address < process_address + size), svc::ResultInvalidCurrentMemory());
R_UNLESS((device_address < device_address + size), svc::ResultInvalidMemoryRegion());
R_UNLESS((process_address == static_cast<uintptr_t>(process_address)), svc::ResultInvalidCurrentMemory());
R_UNLESS(IsValidDeviceMemoryPermission(device_perm), svc::ResultInvalidNewMemoryPermission());
R_UNLESS(reserved == 0, svc::ResultInvalidEnumValue());
/* Get the device address space. */
KScopedAutoObject das = GetCurrentProcess().GetHandleTable().GetObject<KDeviceAddressSpace>(das_handle);
R_UNLESS(das.IsNotNull(), svc::ResultInvalidHandle());
/* Get the process. */
KScopedAutoObject process = GetCurrentProcess().GetHandleTable().GetObject<KProcess>(process_handle);
R_UNLESS(process.IsNotNull(), svc::ResultInvalidHandle());
/* Validate that the process address is within range. */
auto &page_table = process->GetPageTable();
R_UNLESS(page_table.Contains(process_address, size), svc::ResultInvalidCurrentMemory());
/* Map. */
R_RETURN(das->MapByForce(std::addressof(page_table), KProcessAddress(process_address), size, device_address, option));
}
Result MapDeviceAddressSpaceAligned(ams::svc::Handle das_handle, ams::svc::Handle process_handle, uint64_t process_address, size_t size, uint64_t device_address, u32 option) {
/* Decode the option. */
const util::BitPack32 option_pack = { option };
const auto device_perm = option_pack.Get<ams::svc::MapDeviceAddressSpaceOption::Permission>();
const auto reserved = option_pack.Get<ams::svc::MapDeviceAddressSpaceOption::Reserved>();
/* Validate input. */
R_UNLESS(util::IsAligned(process_address, PageSize), svc::ResultInvalidAddress());
R_UNLESS(util::IsAligned(device_address, PageSize), svc::ResultInvalidAddress());
R_UNLESS(IsProcessAndDeviceAligned(process_address, device_address), svc::ResultInvalidAddress());
R_UNLESS(util::IsAligned(size, PageSize), svc::ResultInvalidSize());
R_UNLESS(size > 0, svc::ResultInvalidSize());
R_UNLESS((process_address < process_address + size), svc::ResultInvalidCurrentMemory());
R_UNLESS((device_address < device_address + size), svc::ResultInvalidMemoryRegion());
R_UNLESS((process_address == static_cast<uintptr_t>(process_address)), svc::ResultInvalidCurrentMemory());
R_UNLESS(IsValidDeviceMemoryPermission(device_perm), svc::ResultInvalidNewMemoryPermission());
R_UNLESS(reserved == 0, svc::ResultInvalidEnumValue());
/* Get the device address space. */
KScopedAutoObject das = GetCurrentProcess().GetHandleTable().GetObject<KDeviceAddressSpace>(das_handle);
R_UNLESS(das.IsNotNull(), svc::ResultInvalidHandle());
/* Get the process. */
KScopedAutoObject process = GetCurrentProcess().GetHandleTable().GetObject<KProcess>(process_handle);
R_UNLESS(process.IsNotNull(), svc::ResultInvalidHandle());
/* Validate that the process address is within range. */
auto &page_table = process->GetPageTable();
R_UNLESS(page_table.Contains(process_address, size), svc::ResultInvalidCurrentMemory());
/* Map. */
R_RETURN(das->MapAligned(std::addressof(page_table), KProcessAddress(process_address), size, device_address, option));
}
Result UnmapDeviceAddressSpace(ams::svc::Handle das_handle, ams::svc::Handle process_handle, uint64_t process_address, size_t size, uint64_t device_address) {
/* Validate input. */
R_UNLESS(util::IsAligned(process_address, PageSize), svc::ResultInvalidAddress());
R_UNLESS(util::IsAligned(device_address, PageSize), svc::ResultInvalidAddress());
R_UNLESS(util::IsAligned(size, PageSize), svc::ResultInvalidSize());
R_UNLESS(size > 0, svc::ResultInvalidSize());
R_UNLESS((process_address < process_address + size), svc::ResultInvalidCurrentMemory());
R_UNLESS((device_address < device_address + size), svc::ResultInvalidMemoryRegion());
R_UNLESS((process_address == static_cast<uintptr_t>(process_address)), svc::ResultInvalidCurrentMemory());
/* Get the device address space. */
KScopedAutoObject das = GetCurrentProcess().GetHandleTable().GetObject<KDeviceAddressSpace>(das_handle);
R_UNLESS(das.IsNotNull(), svc::ResultInvalidHandle());
/* Get the process. */
KScopedAutoObject process = GetCurrentProcess().GetHandleTable().GetObject<KProcess>(process_handle);
R_UNLESS(process.IsNotNull(), svc::ResultInvalidHandle());
/* Validate that the process address is within range. */
auto &page_table = process->GetPageTable();
R_UNLESS(page_table.Contains(process_address, size), svc::ResultInvalidCurrentMemory());
R_RETURN(das->Unmap(std::addressof(page_table), KProcessAddress(process_address), size, device_address));
}
}
/* ============================= 64 ABI ============================= */
Result CreateDeviceAddressSpace64(ams::svc::Handle *out_handle, uint64_t das_address, uint64_t das_size) {
R_RETURN(CreateDeviceAddressSpace(out_handle, das_address, das_size));
}
Result AttachDeviceAddressSpace64(ams::svc::DeviceName device_name, ams::svc::Handle das_handle) {
R_RETURN(AttachDeviceAddressSpace(device_name, das_handle));
}
Result DetachDeviceAddressSpace64(ams::svc::DeviceName device_name, ams::svc::Handle das_handle) {
R_RETURN(DetachDeviceAddressSpace(device_name, das_handle));
}
Result MapDeviceAddressSpaceByForce64(ams::svc::Handle das_handle, ams::svc::Handle process_handle, uint64_t process_address, ams::svc::Size size, uint64_t device_address, u32 option) {
R_RETURN(MapDeviceAddressSpaceByForce(das_handle, process_handle, process_address, size, device_address, option));
}
Result MapDeviceAddressSpaceAligned64(ams::svc::Handle das_handle, ams::svc::Handle process_handle, uint64_t process_address, ams::svc::Size size, uint64_t device_address, u32 option) {
R_RETURN(MapDeviceAddressSpaceAligned(das_handle, process_handle, process_address, size, device_address, option));
}
Result UnmapDeviceAddressSpace64(ams::svc::Handle das_handle, ams::svc::Handle process_handle, uint64_t process_address, ams::svc::Size size, uint64_t device_address) {
R_RETURN(UnmapDeviceAddressSpace(das_handle, process_handle, process_address, size, device_address));
}
/* ============================= 64From32 ABI ============================= */
Result CreateDeviceAddressSpace64From32(ams::svc::Handle *out_handle, uint64_t das_address, uint64_t das_size) {
R_RETURN(CreateDeviceAddressSpace(out_handle, das_address, das_size));
}
Result AttachDeviceAddressSpace64From32(ams::svc::DeviceName device_name, ams::svc::Handle das_handle) {
R_RETURN(AttachDeviceAddressSpace(device_name, das_handle));
}
Result DetachDeviceAddressSpace64From32(ams::svc::DeviceName device_name, ams::svc::Handle das_handle) {
R_RETURN(DetachDeviceAddressSpace(device_name, das_handle));
}
Result MapDeviceAddressSpaceByForce64From32(ams::svc::Handle das_handle, ams::svc::Handle process_handle, uint64_t process_address, ams::svc::Size size, uint64_t device_address, u32 option) {
R_RETURN(MapDeviceAddressSpaceByForce(das_handle, process_handle, process_address, size, device_address, option));
}
Result MapDeviceAddressSpaceAligned64From32(ams::svc::Handle das_handle, ams::svc::Handle process_handle, uint64_t process_address, ams::svc::Size size, uint64_t device_address, u32 option) {
R_RETURN(MapDeviceAddressSpaceAligned(das_handle, process_handle, process_address, size, device_address, option));
}
Result UnmapDeviceAddressSpace64From32(ams::svc::Handle das_handle, ams::svc::Handle process_handle, uint64_t process_address, ams::svc::Size size, uint64_t device_address) {
R_RETURN(UnmapDeviceAddressSpace(das_handle, process_handle, process_address, size, device_address));
}
}
| 13,430
|
C++
|
.cpp
| 180
| 64.216667
| 195
| 0.636846
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,037
|
kern_svc_tick.cpp
|
Atmosphere-NX_Atmosphere/libraries/libmesosphere/source/svc/kern_svc_tick.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <mesosphere.hpp>
namespace ams::kern::svc {
/* ============================= Common ============================= */
namespace {
int64_t GetSystemTick() {
return KHardwareTimer::GetTick();
}
}
/* ============================= 64 ABI ============================= */
int64_t GetSystemTick64() {
return GetSystemTick();
}
/* ============================= 64From32 ABI ============================= */
int64_t GetSystemTick64From32() {
return GetSystemTick();
}
}
| 1,207
|
C++
|
.cpp
| 32
| 33.46875
| 82
| 0.575966
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,038
|
kern_svc_process.cpp
|
Atmosphere-NX_Atmosphere/libraries/libmesosphere/source/svc/kern_svc_process.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <mesosphere.hpp>
namespace ams::kern::svc {
/* ============================= Common ============================= */
namespace {
constexpr bool IsValidVirtualCoreId(int32_t core_id) {
return (0 <= core_id && core_id < static_cast<int32_t>(cpu::NumVirtualCores));
}
void ExitProcess() {
GetCurrentProcess().Exit();
MESOSPHERE_PANIC("Process survived call to exit");
}
Result GetProcessId(u64 *out_process_id, ams::svc::Handle handle) {
/* Get the object from the handle table. */
KScopedAutoObject obj = GetCurrentProcess().GetHandleTable().GetObject<KAutoObject>(handle);
R_UNLESS(obj.IsNotNull(), svc::ResultInvalidHandle());
/* Get the process from the object. */
if (KProcess *process = obj->DynamicCast<KProcess *>(); process != nullptr) {
/* The object is a process, so we can use it directly. */
/* Make sure the target process exists. */
R_UNLESS(process != nullptr, svc::ResultInvalidHandle());
/* Get the process id. */
*out_process_id = process->GetId();
} else if (KThread *t = obj->DynamicCast<KThread *>(); t != nullptr) {
/* The object is a thread, so we want to use its parent. */
KProcess *process = t->GetOwnerProcess();
/* Make sure the target process exists. */
R_UNLESS(process != nullptr, svc::ResultInvalidHandle());
/* Get the process id. */
*out_process_id = process->GetId();
} else if (KDebug *d = obj->DynamicCast<KDebug *>(); d != nullptr) {
/* The object is a debug, so we want to use the process it's attached to. */
/* Make sure the target process exists. */
R_UNLESS(d->IsAttached(), svc::ResultInvalidHandle());
R_UNLESS(d->OpenProcess(), svc::ResultInvalidHandle());
ON_SCOPE_EXIT { d->CloseProcess(); };
/* Get the process id. */
*out_process_id = d->GetProcessUnsafe()->GetProcessId();
} else {
R_THROW(svc::ResultInvalidHandle());
}
R_SUCCEED();
}
Result GetProcessList(int32_t *out_num_processes, KUserPointer<uint64_t *> out_process_ids, int32_t max_out_count) {
/* Only allow invoking the svc on development hardware. */
R_UNLESS(KTargetSystem::IsDebugMode(), svc::ResultNotImplemented());
/* Validate that the out count is valid. */
R_UNLESS((0 <= max_out_count && max_out_count <= static_cast<int32_t>(std::numeric_limits<int32_t>::max() / sizeof(u64))), svc::ResultOutOfRange());
/* Validate that the pointer is in range. */
if (max_out_count > 0) {
R_UNLESS(GetCurrentProcess().GetPageTable().Contains(KProcessAddress(out_process_ids.GetUnsafePointer()), max_out_count * sizeof(u64)), svc::ResultInvalidCurrentMemory());
}
/* Get the process list. */
R_RETURN(KProcess::GetProcessList(out_num_processes, out_process_ids, max_out_count));
}
Result CreateProcess(ams::svc::Handle *out, const ams::svc::CreateProcessParameter ¶ms, KUserPointer<const uint32_t *> user_caps, int32_t num_caps) {
/* Validate the capabilities pointer. */
R_UNLESS(num_caps >= 0, svc::ResultInvalidPointer());
if (num_caps > 0) {
/* Check for overflow. */
R_UNLESS(((num_caps * sizeof(u32)) / sizeof(u32)) == static_cast<size_t>(num_caps), svc::ResultInvalidPointer());
/* Validate that the pointer is in range. */
R_UNLESS(GetCurrentProcess().GetPageTable().Contains(KProcessAddress(user_caps.GetUnsafePointer()), num_caps * sizeof(u32)), svc::ResultInvalidPointer());
}
/* Validate that the parameter flags are valid. */
R_UNLESS((params.flags & ~ams::svc::CreateProcessFlag_All) == 0, svc::ResultInvalidEnumValue());
/* Validate that 64-bit process is okay. */
const bool is_64_bit = (params.flags & ams::svc::CreateProcessFlag_Is64Bit) != 0;
if constexpr (sizeof(void *) < sizeof(u64)) {
R_UNLESS(!is_64_bit, svc::ResultInvalidCombination());
}
/* Decide on an address space map region. */
uintptr_t map_start, map_end;
size_t map_size;
switch (params.flags & ams::svc::CreateProcessFlag_AddressSpaceMask) {
case ams::svc::CreateProcessFlag_AddressSpace32Bit:
case ams::svc::CreateProcessFlag_AddressSpace32BitWithoutAlias:
{
map_start = KAddressSpaceInfo::GetAddressSpaceStart(static_cast<ams::svc::CreateProcessFlag>(params.flags), KAddressSpaceInfo::Type_MapSmall);
map_size = KAddressSpaceInfo::GetAddressSpaceSize(static_cast<ams::svc::CreateProcessFlag>(params.flags), KAddressSpaceInfo::Type_MapSmall);
map_end = map_start + map_size;
}
break;
case ams::svc::CreateProcessFlag_AddressSpace64BitDeprecated:
{
/* 64-bit address space requires 64-bit process. */
R_UNLESS(is_64_bit, svc::ResultInvalidCombination());
map_start = KAddressSpaceInfo::GetAddressSpaceStart(static_cast<ams::svc::CreateProcessFlag>(params.flags), KAddressSpaceInfo::Type_MapSmall);
map_size = KAddressSpaceInfo::GetAddressSpaceSize(static_cast<ams::svc::CreateProcessFlag>(params.flags), KAddressSpaceInfo::Type_MapSmall);
map_end = map_start + map_size;
}
break;
case ams::svc::CreateProcessFlag_AddressSpace64Bit:
{
/* 64-bit address space requires 64-bit process. */
R_UNLESS(is_64_bit, svc::ResultInvalidCombination());
map_start = KAddressSpaceInfo::GetAddressSpaceStart(static_cast<ams::svc::CreateProcessFlag>(params.flags), KAddressSpaceInfo::Type_Map39Bit);
map_end = map_start + KAddressSpaceInfo::GetAddressSpaceSize(static_cast<ams::svc::CreateProcessFlag>(params.flags), KAddressSpaceInfo::Type_Map39Bit);
map_size = KAddressSpaceInfo::GetAddressSpaceSize(static_cast<ams::svc::CreateProcessFlag>(params.flags), KAddressSpaceInfo::Type_Heap);
}
break;
default:
R_THROW(svc::ResultInvalidEnumValue());
}
/* Validate the pool partition. */
if (GetTargetFirmware() >= TargetFirmware_5_0_0) {
switch (params.flags & ams::svc::CreateProcessFlag_PoolPartitionMask) {
case ams::svc::CreateProcessFlag_PoolPartitionApplication:
case ams::svc::CreateProcessFlag_PoolPartitionApplet:
case ams::svc::CreateProcessFlag_PoolPartitionSystem:
case ams::svc::CreateProcessFlag_PoolPartitionSystemNonSecure:
break;
default:
R_THROW(svc::ResultInvalidEnumValue());
}
}
/* Check that the code address is aligned. */
R_UNLESS(util::IsAligned(params.code_address, KProcess::AslrAlignment), svc::ResultInvalidAddress());
/* Check that the number of code pages is >= 0. */
R_UNLESS(params.code_num_pages >= 0, svc::ResultInvalidSize());
/* Check that the number of extra resource pages is >= 0. */
R_UNLESS(params.system_resource_num_pages >= 0, svc::ResultInvalidSize());
/* Validate that the alias region extra size is allowed, if enabled. */
if (params.flags & ams::svc::CreateProcessFlag_EnableAliasRegionExtraSize) {
/* Check that we have a 64-bit address space. */
R_UNLESS((params.flags & ams::svc::CreateProcessFlag_AddressSpaceMask) == ams::svc::CreateProcessFlag_AddressSpace64Bit, svc::ResultInvalidState());
/* Check that the system resource page count is non-zero. */
R_UNLESS(params.system_resource_num_pages > 0, svc::ResultInvalidState());
/* Check that debug mode is enabled. */
R_UNLESS(KTargetSystem::IsDebugMode(), svc::ResultInvalidState());
}
/* Convert to sizes. */
const size_t code_num_pages = params.code_num_pages;
const size_t system_resource_num_pages = params.system_resource_num_pages;
const size_t total_pages = code_num_pages + system_resource_num_pages;
const size_t code_size = code_num_pages * PageSize;
const size_t system_resource_size = system_resource_num_pages * PageSize;
const size_t total_size = code_size + system_resource_size;
/* Check for overflow. */
R_UNLESS((code_size / PageSize) == code_num_pages, svc::ResultInvalidSize());
R_UNLESS((system_resource_size / PageSize) == system_resource_num_pages, svc::ResultInvalidSize());
R_UNLESS((code_num_pages + system_resource_num_pages) >= code_num_pages, svc::ResultOutOfMemory());
R_UNLESS((total_size / PageSize) == total_pages, svc::ResultInvalidSize());
/* Check that the number of pages is valid. */
R_UNLESS(code_num_pages < (map_size / PageSize), svc::ResultInvalidMemoryRegion());
/* Validate that the code falls within the map reigon. */
R_UNLESS(map_start <= params.code_address, svc::ResultInvalidMemoryRegion());
R_UNLESS(params.code_address < params.code_address + code_size, svc::ResultInvalidMemoryRegion());
R_UNLESS(params.code_address + code_size - 1 <= map_end - 1, svc::ResultInvalidMemoryRegion());
/* Check that the number of pages is valid for the kernel address space. */
R_UNLESS(code_num_pages < (kern::MainMemorySizeMax / PageSize), svc::ResultOutOfMemory());
R_UNLESS(system_resource_num_pages < (kern::MainMemorySizeMax / PageSize), svc::ResultOutOfMemory());
R_UNLESS(total_pages < (kern::MainMemorySizeMax / PageSize), svc::ResultOutOfMemory());
/* Check that optimized memory allocation is used only for applications. */
const bool optimize_allocs = (params.flags & ams::svc::CreateProcessFlag_OptimizeMemoryAllocation) != 0;
const bool is_application = (params.flags & ams::svc::CreateProcessFlag_IsApplication) != 0;
R_UNLESS(!optimize_allocs || is_application, svc::ResultBusy());
/* Check that the user-provided capabilities are accessible and refer to valid regions. */
R_TRY(KCapabilities::CheckCapabilities(user_caps, num_caps));
/* Get the current handle table. */
auto &handle_table = GetCurrentProcess().GetHandleTable();
/* Create the new process. */
KProcess *process = KProcess::Create();
R_UNLESS(process != nullptr, svc::ResultOutOfResource());
/* Ensure that the only reference to the process is in the handle table when we're done. */
ON_SCOPE_EXIT { process->Close(); };
/* Get the resource limit from the handle. */
KScopedAutoObject resource_limit = handle_table.GetObject<KResourceLimit>(params.reslimit);
R_UNLESS(resource_limit.IsNotNull() || params.reslimit == ams::svc::InvalidHandle, svc::ResultInvalidHandle());
/* Decide on a resource limit for the process. */
KResourceLimit *process_resource_limit = resource_limit.IsNotNull() ? resource_limit.GetPointerUnsafe() : std::addressof(Kernel::GetSystemResourceLimit());
/* Get the pool for the process. */
const auto pool = [](u32 flags) ALWAYS_INLINE_LAMBDA -> KMemoryManager::Pool {
if (GetTargetFirmware() >= TargetFirmware_5_0_0) {
switch (flags & ams::svc::CreateProcessFlag_PoolPartitionMask) {
case ams::svc::CreateProcessFlag_PoolPartitionApplication:
return KMemoryManager::Pool_Application;
case ams::svc::CreateProcessFlag_PoolPartitionApplet:
return KMemoryManager::Pool_Applet;
case ams::svc::CreateProcessFlag_PoolPartitionSystem:
return KMemoryManager::Pool_System;
case ams::svc::CreateProcessFlag_PoolPartitionSystemNonSecure:
default:
return KMemoryManager::Pool_SystemNonSecure;
}
} else if (GetTargetFirmware() >= TargetFirmware_4_0_0) {
if ((flags & ams::svc::CreateProcessFlag_DeprecatedUseSecureMemory) != 0) {
return KMemoryManager::Pool_Secure;
} else {
return static_cast<KMemoryManager::Pool>(KSystemControl::GetCreateProcessMemoryPool());
}
} else {
return static_cast<KMemoryManager::Pool>(KSystemControl::GetCreateProcessMemoryPool());
}
}(params.flags);
/* Initialize the process. */
R_TRY(process->Initialize(params, user_caps, num_caps, process_resource_limit, pool));
/* Register the process. */
KProcess::Register(process);
/* Add the process to the handle table. */
R_TRY(handle_table.Add(out, process));
R_SUCCEED();
}
template<typename T>
Result CreateProcess(ams::svc::Handle *out, KUserPointer<const T *> user_parameters, KUserPointer<const uint32_t *> user_caps, int32_t num_caps) {
/* Read the parameters from user space. */
T params;
R_TRY(user_parameters.CopyTo(std::addressof(params)));
/* Invoke the implementation. */
if constexpr (std::same_as<T, ams::svc::CreateProcessParameter>) {
R_RETURN(CreateProcess(out, params, user_caps, num_caps));
} else {
/* Convert the parameters. */
ams::svc::CreateProcessParameter converted_params;
static_assert(sizeof(T{}.name) == sizeof(ams::svc::CreateProcessParameter{}.name));
std::memcpy(converted_params.name, params.name, sizeof(converted_params.name));
converted_params.version = params.version;
converted_params.program_id = params.program_id;
converted_params.code_address = params.code_address;
converted_params.code_num_pages = params.code_num_pages;
converted_params.flags = params.flags;
converted_params.reslimit = params.reslimit;
converted_params.system_resource_num_pages = params.system_resource_num_pages;
/* Invoke. */
R_RETURN(CreateProcess(out, converted_params, user_caps, num_caps));
}
}
Result StartProcess(ams::svc::Handle process_handle, int32_t priority, int32_t core_id, uint64_t main_thread_stack_size) {
/* Validate stack size. */
const uint64_t aligned_stack_size = util::AlignUp(main_thread_stack_size, Kernel::GetMemoryManager().GetMinimumAlignment(GetCurrentProcess().GetMemoryPool()));
R_UNLESS(aligned_stack_size >= main_thread_stack_size, svc::ResultOutOfMemory());
R_UNLESS(aligned_stack_size == static_cast<size_t>(aligned_stack_size), svc::ResultOutOfMemory());
/* Get the target process. */
KScopedAutoObject process = GetCurrentProcess().GetHandleTable().GetObject<KProcess>(process_handle);
R_UNLESS(process.IsNotNull(), svc::ResultInvalidHandle());
/* Validate the core id. */
R_UNLESS(IsValidVirtualCoreId(core_id), svc::ResultInvalidCoreId());
R_UNLESS(((1ul << core_id) & process->GetCoreMask()) != 0, svc::ResultInvalidCoreId());
/* Validate the priority. */
R_UNLESS(ams::svc::HighestThreadPriority <= priority && priority <= ams::svc::LowestThreadPriority, svc::ResultInvalidPriority());
R_UNLESS(process->CheckThreadPriority(priority), svc::ResultInvalidPriority());
/* Set the process's ideal processor. */
process->SetIdealCoreId(core_id);
/* Run the process. */
R_RETURN(process->Run(priority, static_cast<size_t>(aligned_stack_size)));
}
Result TerminateProcess(ams::svc::Handle process_handle) {
/* Get the target process. */
KProcess *process = GetCurrentProcess().GetHandleTable().GetObject<KProcess>(process_handle).ReleasePointerUnsafe();
R_UNLESS(process != nullptr, svc::ResultInvalidHandle());
if (process != GetCurrentProcessPointer()) {
/* We're terminating another process. Close our reference after terminating the process. */
ON_SCOPE_EXIT { process->Close(); };
/* Terminate the process. */
R_TRY(process->Terminate());
} else {
/* We're terminating ourselves. Close our reference immediately. */
process->Close();
/* Exit. */
ExitProcess();
}
R_SUCCEED();
}
Result GetProcessInfo(int64_t *out, ams::svc::Handle process_handle, ams::svc::ProcessInfoType info_type) {
/* Get the target process. */
KScopedAutoObject process = GetCurrentProcess().GetHandleTable().GetObject<KProcess>(process_handle);
R_UNLESS(process.IsNotNull(), svc::ResultInvalidHandle());
/* Get the info. */
switch (info_type) {
case ams::svc::ProcessInfoType_ProcessState:
{
/* Get the process's state. */
KProcess::State state;
{
KScopedLightLock proc_lk(process->GetStateLock());
KScopedSchedulerLock sl;
state = process->GetState();
}
/* Convert to svc state. */
switch (state) {
case KProcess::State_Created: *out = ams::svc::ProcessState_Created; break;
case KProcess::State_CreatedAttached: *out = ams::svc::ProcessState_CreatedAttached; break;
case KProcess::State_Running: *out = ams::svc::ProcessState_Running; break;
case KProcess::State_Crashed: *out = ams::svc::ProcessState_Crashed; break;
case KProcess::State_RunningAttached: *out = ams::svc::ProcessState_RunningAttached; break;
case KProcess::State_Terminating: *out = ams::svc::ProcessState_Terminating; break;
case KProcess::State_Terminated: *out = ams::svc::ProcessState_Terminated; break;
case KProcess::State_DebugBreak: *out = ams::svc::ProcessState_DebugBreak; break;
MESOSPHERE_UNREACHABLE_DEFAULT_CASE();
}
}
break;
default:
R_THROW(svc::ResultInvalidEnumValue());
}
R_SUCCEED();
}
}
/* ============================= 64 ABI ============================= */
void ExitProcess64() {
return ExitProcess();
}
Result GetProcessId64(uint64_t *out_process_id, ams::svc::Handle process_handle) {
R_RETURN(GetProcessId(out_process_id, process_handle));
}
Result GetProcessList64(int32_t *out_num_processes, KUserPointer<uint64_t *> out_process_ids, int32_t max_out_count) {
R_RETURN(GetProcessList(out_num_processes, out_process_ids, max_out_count));
}
Result CreateProcess64(ams::svc::Handle *out_handle, KUserPointer<const ams::svc::lp64::CreateProcessParameter *> parameters, KUserPointer<const uint32_t *> caps, int32_t num_caps) {
R_RETURN(CreateProcess(out_handle, parameters, caps, num_caps));
}
Result StartProcess64(ams::svc::Handle process_handle, int32_t priority, int32_t core_id, uint64_t main_thread_stack_size) {
R_RETURN(StartProcess(process_handle, priority, core_id, main_thread_stack_size));
}
Result TerminateProcess64(ams::svc::Handle process_handle) {
R_RETURN(TerminateProcess(process_handle));
}
Result GetProcessInfo64(int64_t *out_info, ams::svc::Handle process_handle, ams::svc::ProcessInfoType info_type) {
R_RETURN(GetProcessInfo(out_info, process_handle, info_type));
}
/* ============================= 64From32 ABI ============================= */
void ExitProcess64From32() {
return ExitProcess();
}
Result GetProcessId64From32(uint64_t *out_process_id, ams::svc::Handle process_handle) {
R_RETURN(GetProcessId(out_process_id, process_handle));
}
Result GetProcessList64From32(int32_t *out_num_processes, KUserPointer<uint64_t *> out_process_ids, int32_t max_out_count) {
R_RETURN(GetProcessList(out_num_processes, out_process_ids, max_out_count));
}
Result CreateProcess64From32(ams::svc::Handle *out_handle, KUserPointer<const ams::svc::ilp32::CreateProcessParameter *> parameters, KUserPointer<const uint32_t *> caps, int32_t num_caps) {
R_RETURN(CreateProcess(out_handle, parameters, caps, num_caps));
}
Result StartProcess64From32(ams::svc::Handle process_handle, int32_t priority, int32_t core_id, uint64_t main_thread_stack_size) {
R_RETURN(StartProcess(process_handle, priority, core_id, main_thread_stack_size));
}
Result TerminateProcess64From32(ams::svc::Handle process_handle) {
R_RETURN(TerminateProcess(process_handle));
}
Result GetProcessInfo64From32(int64_t *out_info, ams::svc::Handle process_handle, ams::svc::ProcessInfoType info_type) {
R_RETURN(GetProcessInfo(out_info, process_handle, info_type));
}
}
| 23,760
|
C++
|
.cpp
| 357
| 51.991597
| 193
| 0.589535
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,039
|
kern_svc_address_translation.cpp
|
Atmosphere-NX_Atmosphere/libraries/libmesosphere/source/svc/kern_svc_address_translation.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <mesosphere.hpp>
namespace ams::kern::svc {
/* ============================= Common ============================= */
namespace {
Result QueryPhysicalAddress(ams::svc::PhysicalMemoryInfo *out_info, uintptr_t address) {
/* NOTE: In 10.0.0, Nintendo stubbed this SVC. Should we do so? */
/* R_UNLESS(GetTargetFirmware() < TargetFirmware_10_0_0, svc::ResultInvalidCurrentMemory()); */
/* Get reference to page table. */
auto &pt = GetCurrentProcess().GetPageTable();
/* Check that the address is valid. */
R_UNLESS(pt.Contains(address, 1), svc::ResultInvalidCurrentMemory());
/* Query the physical mapping. */
R_TRY(pt.QueryPhysicalAddress(out_info, address));
R_SUCCEED();
}
Result QueryMemoryMapping(uintptr_t *out_address, size_t *out_size, uint64_t phys_addr, size_t size) {
/* Declare variables we'll populate. */
KProcessAddress found_address = Null<KProcessAddress>;
size_t found_size = 0;
/* Get reference to page table. */
auto &pt = GetCurrentProcess().GetPageTable();
/* Check whether the address is aligned. */
const bool aligned = util::IsAligned(phys_addr, PageSize);
auto QueryMappingFromPageTable = [&](uint64_t phys_addr, size_t size) ALWAYS_INLINE_LAMBDA -> Result {
/* The size must be non-zero. */
R_UNLESS(size > 0, svc::ResultInvalidSize());
/* The request must not overflow. */
R_UNLESS((phys_addr < phys_addr + size), svc::ResultNotFound());
/* Query the mapping. */
R_TRY_CATCH(pt.QueryIoMapping(std::addressof(found_address), phys_addr, size)) {
R_CATCH(svc::ResultNotFound) {
/* If we failed to find an io mapping, check if the address is a static mapping. */
R_TRY(pt.QueryStaticMapping(std::addressof(found_address), phys_addr, size));
}
} R_END_TRY_CATCH;
/* Use the size as the found size. */
found_size = size;
R_SUCCEED();
};
if (aligned) {
/* Query the input. */
R_TRY(QueryMappingFromPageTable(phys_addr, size));
} else {
if (kern::GetTargetFirmware() < TargetFirmware_8_0_0 && phys_addr >= PageSize) {
/* Query the aligned-down page. */
const size_t offset = phys_addr & (PageSize - 1);
R_TRY(QueryMappingFromPageTable(phys_addr - offset, size + offset));
/* Adjust the output address. */
found_address += offset;
} else {
/* Newer kernel only allows unaligned addresses when they're special enum members. */
R_UNLESS(phys_addr < PageSize, svc::ResultNotFound());
/* Try to find the memory region. */
const KMemoryRegion * const region = [] ALWAYS_INLINE_LAMBDA (ams::svc::MemoryRegionType type) -> const KMemoryRegion * {
switch (type) {
case ams::svc::MemoryRegionType_KernelTraceBuffer: return KMemoryLayout::GetPhysicalKernelTraceBufferRegion();
case ams::svc::MemoryRegionType_OnMemoryBootImage: return KMemoryLayout::GetPhysicalOnMemoryBootImageRegion();
case ams::svc::MemoryRegionType_DTB: return KMemoryLayout::GetPhysicalDTBRegion();
default: return nullptr;
}
}(static_cast<ams::svc::MemoryRegionType>(phys_addr));
/* Ensure that we found the region. */
R_UNLESS(region != nullptr, svc::ResultNotFound());
/* Chcek that the region is valid. */
MESOSPHERE_ABORT_UNLESS(region->GetEndAddress() != 0);
R_TRY(pt.QueryStaticMapping(std::addressof(found_address), region->GetAddress(), region->GetSize()));
found_size = region->GetSize();
}
}
/* We succeeded. */
MESOSPHERE_ASSERT(found_address != Null<KProcessAddress>);
MESOSPHERE_ASSERT(found_size != 0);
if (out_address != nullptr) {
*out_address = GetInteger(found_address);
}
if (out_size != nullptr) {
*out_size = found_size;
}
R_SUCCEED();
}
}
/* ============================= 64 ABI ============================= */
Result QueryPhysicalAddress64(ams::svc::lp64::PhysicalMemoryInfo *out_info, ams::svc::Address address) {
R_RETURN(QueryPhysicalAddress(out_info, address));
}
Result QueryMemoryMapping64(ams::svc::Address *out_address, ams::svc::Size *out_size, ams::svc::PhysicalAddress physical_address, ams::svc::Size size) {
static_assert(sizeof(*out_address) == sizeof(uintptr_t));
static_assert(sizeof(*out_size) == sizeof(size_t));
R_RETURN(QueryMemoryMapping(reinterpret_cast<uintptr_t *>(out_address), reinterpret_cast<size_t *>(out_size), physical_address, size));
}
Result LegacyQueryIoMapping64(ams::svc::Address *out_address, ams::svc::PhysicalAddress physical_address, ams::svc::Size size) {
static_assert(sizeof(*out_address) == sizeof(uintptr_t));
R_RETURN(QueryMemoryMapping(reinterpret_cast<uintptr_t *>(out_address), nullptr, physical_address, size));
}
/* ============================= 64From32 ABI ============================= */
Result QueryPhysicalAddress64From32(ams::svc::ilp32::PhysicalMemoryInfo *out_info, ams::svc::Address address) {
ams::svc::PhysicalMemoryInfo info = {};
R_TRY(QueryPhysicalAddress(std::addressof(info), address));
*out_info = {
.physical_address = info.physical_address,
.virtual_address = static_cast<u32>(info.virtual_address),
.size = static_cast<u32>(info.size),
};
R_SUCCEED();
}
Result QueryMemoryMapping64From32(ams::svc::Address *out_address, ams::svc::Size *out_size, ams::svc::PhysicalAddress physical_address, ams::svc::Size size) {
static_assert(sizeof(*out_address) == sizeof(uintptr_t));
static_assert(sizeof(*out_size) == sizeof(size_t));
R_RETURN(QueryMemoryMapping(reinterpret_cast<uintptr_t *>(out_address), reinterpret_cast<size_t *>(out_size), physical_address, size));
}
Result LegacyQueryIoMapping64From32(ams::svc::Address *out_address, ams::svc::PhysicalAddress physical_address, ams::svc::Size size) {
static_assert(sizeof(*out_address) == sizeof(uintptr_t));
R_RETURN(QueryMemoryMapping(reinterpret_cast<uintptr_t *>(out_address), nullptr, physical_address, size));
}
}
| 7,772
|
C++
|
.cpp
| 130
| 47.246154
| 162
| 0.579784
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,040
|
kern_svc_transfer_memory.cpp
|
Atmosphere-NX_Atmosphere/libraries/libmesosphere/source/svc/kern_svc_transfer_memory.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <mesosphere.hpp>
namespace ams::kern::svc {
/* ============================= Common ============================= */
namespace {
constexpr bool IsValidTransferMemoryPermission(ams::svc::MemoryPermission perm) {
switch (perm) {
case ams::svc::MemoryPermission_None:
case ams::svc::MemoryPermission_Read:
case ams::svc::MemoryPermission_ReadWrite:
return true;
default:
return false;
}
}
Result MapTransferMemory(ams::svc::Handle trmem_handle, uintptr_t address, size_t size, ams::svc::MemoryPermission map_perm) {
/* Validate the address/size. */
R_UNLESS(util::IsAligned(address, PageSize), svc::ResultInvalidAddress());
R_UNLESS(util::IsAligned(size, PageSize), svc::ResultInvalidSize());
R_UNLESS(size > 0, svc::ResultInvalidSize());
R_UNLESS((address < address + size), svc::ResultInvalidCurrentMemory());
/* Validate the permission. */
R_UNLESS(IsValidTransferMemoryPermission(map_perm), svc::ResultInvalidState());
/* Get the transfer memory. */
KScopedAutoObject trmem = GetCurrentProcess().GetHandleTable().GetObject<KTransferMemory>(trmem_handle);
R_UNLESS(trmem.IsNotNull(), svc::ResultInvalidHandle());
/* Verify that the mapping is in range. */
R_UNLESS(GetCurrentProcess().GetPageTable().CanContain(address, size, KMemoryState_Transfered), svc::ResultInvalidMemoryRegion());
/* Map the transfer memory. */
R_TRY(trmem->Map(address, size, map_perm));
/* We succeeded. */
R_SUCCEED();
}
Result UnmapTransferMemory(ams::svc::Handle trmem_handle, uintptr_t address, size_t size) {
/* Validate the address/size. */
R_UNLESS(util::IsAligned(address, PageSize), svc::ResultInvalidAddress());
R_UNLESS(util::IsAligned(size, PageSize), svc::ResultInvalidSize());
R_UNLESS(size > 0, svc::ResultInvalidSize());
R_UNLESS((address < address + size), svc::ResultInvalidCurrentMemory());
/* Get the transfer memory. */
KScopedAutoObject trmem = GetCurrentProcess().GetHandleTable().GetObject<KTransferMemory>(trmem_handle);
R_UNLESS(trmem.IsNotNull(), svc::ResultInvalidHandle());
/* Verify that the mapping is in range. */
R_UNLESS(GetCurrentProcess().GetPageTable().CanContain(address, size, KMemoryState_Transfered), svc::ResultInvalidMemoryRegion());
/* Unmap the transfer memory. */
R_TRY(trmem->Unmap(address, size));
R_SUCCEED();
}
Result CreateTransferMemory(ams::svc::Handle *out, uintptr_t address, size_t size, ams::svc::MemoryPermission map_perm) {
/* Validate the size. */
R_UNLESS(util::IsAligned(address, PageSize), svc::ResultInvalidAddress());
R_UNLESS(util::IsAligned(size, PageSize), svc::ResultInvalidSize());
R_UNLESS(size > 0, svc::ResultInvalidSize());
R_UNLESS((address < address + size), svc::ResultInvalidCurrentMemory());
/* Validate the permissions. */
R_UNLESS(IsValidTransferMemoryPermission(map_perm), svc::ResultInvalidNewMemoryPermission());
/* Get the current process and handle table. */
auto &process = GetCurrentProcess();
auto &handle_table = process.GetHandleTable();
/* Reserve a new transfer memory from the process resource limit. */
KScopedResourceReservation trmem_reservation(std::addressof(process), ams::svc::LimitableResource_TransferMemoryCountMax);
R_UNLESS(trmem_reservation.Succeeded(), svc::ResultLimitReached());
/* Create the transfer memory. */
KTransferMemory *trmem = KTransferMemory::Create();
R_UNLESS(trmem != nullptr, svc::ResultOutOfResource());
/* Ensure the only reference is in the handle table when we're done. */
ON_SCOPE_EXIT { trmem->Close(); };
/* Ensure that the region is in range. */
R_UNLESS(process.GetPageTable().Contains(address, size), svc::ResultInvalidCurrentMemory());
/* Initialize the transfer memory. */
R_TRY(trmem->Initialize(address, size, map_perm));
/* Commit the reservation. */
trmem_reservation.Commit();
/* Register the transfer memory. */
KTransferMemory::Register(trmem);
/* Add the transfer memory to the handle table. */
R_TRY(handle_table.Add(out, trmem));
R_SUCCEED();
}
}
/* ============================= 64 ABI ============================= */
Result MapTransferMemory64(ams::svc::Handle trmem_handle, ams::svc::Address address, ams::svc::Size size, ams::svc::MemoryPermission owner_perm) {
R_RETURN(MapTransferMemory(trmem_handle, address, size, owner_perm));
}
Result UnmapTransferMemory64(ams::svc::Handle trmem_handle, ams::svc::Address address, ams::svc::Size size) {
R_RETURN(UnmapTransferMemory(trmem_handle, address, size));
}
Result CreateTransferMemory64(ams::svc::Handle *out_handle, ams::svc::Address address, ams::svc::Size size, ams::svc::MemoryPermission map_perm) {
R_RETURN(CreateTransferMemory(out_handle, address, size, map_perm));
}
/* ============================= 64From32 ABI ============================= */
Result MapTransferMemory64From32(ams::svc::Handle trmem_handle, ams::svc::Address address, ams::svc::Size size, ams::svc::MemoryPermission owner_perm) {
R_RETURN(MapTransferMemory(trmem_handle, address, size, owner_perm));
}
Result UnmapTransferMemory64From32(ams::svc::Handle trmem_handle, ams::svc::Address address, ams::svc::Size size) {
R_RETURN(UnmapTransferMemory(trmem_handle, address, size));
}
Result CreateTransferMemory64From32(ams::svc::Handle *out_handle, ams::svc::Address address, ams::svc::Size size, ams::svc::MemoryPermission map_perm) {
R_RETURN(CreateTransferMemory(out_handle, address, size, map_perm));
}
}
| 7,073
|
C++
|
.cpp
| 115
| 51.330435
| 156
| 0.622598
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,041
|
kern_svc_memory.cpp
|
Atmosphere-NX_Atmosphere/libraries/libmesosphere/source/svc/kern_svc_memory.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <mesosphere.hpp>
namespace ams::kern::svc {
/* ============================= Common ============================= */
namespace {
constexpr bool IsValidSetMemoryPermission(ams::svc::MemoryPermission perm) {
switch (perm) {
case ams::svc::MemoryPermission_None:
case ams::svc::MemoryPermission_Read:
case ams::svc::MemoryPermission_ReadWrite:
return true;
default:
return false;
}
}
Result SetMemoryPermission(uintptr_t address, size_t size, ams::svc::MemoryPermission perm) {
/* Validate address / size. */
R_UNLESS(util::IsAligned(address, PageSize), svc::ResultInvalidAddress());
R_UNLESS(util::IsAligned(size, PageSize), svc::ResultInvalidSize());
R_UNLESS(size > 0, svc::ResultInvalidSize());
R_UNLESS((address < address + size), svc::ResultInvalidCurrentMemory());
/* Validate the permission. */
R_UNLESS(IsValidSetMemoryPermission(perm), svc::ResultInvalidNewMemoryPermission());
/* Validate that the region is in range for the current process. */
auto &page_table = GetCurrentProcess().GetPageTable();
R_UNLESS(page_table.Contains(address, size), svc::ResultInvalidCurrentMemory());
/* Set the memory attribute. */
R_RETURN(page_table.SetMemoryPermission(address, size, perm));
}
Result SetMemoryAttribute(uintptr_t address, size_t size, uint32_t mask, uint32_t attr) {
/* Validate address / size. */
R_UNLESS(util::IsAligned(address, PageSize), svc::ResultInvalidAddress());
R_UNLESS(util::IsAligned(size, PageSize), svc::ResultInvalidSize());
R_UNLESS(size > 0, svc::ResultInvalidSize());
R_UNLESS((address < address + size), svc::ResultInvalidCurrentMemory());
/* Validate the attribute and mask. */
constexpr u32 SupportedMask = ams::svc::MemoryAttribute_Uncached | ams::svc::MemoryAttribute_PermissionLocked;
R_UNLESS((mask | attr) == mask, svc::ResultInvalidCombination());
R_UNLESS((mask | attr | SupportedMask) == SupportedMask, svc::ResultInvalidCombination());
/* Check that permission locked is either being set or not masked. */
R_UNLESS((mask & ams::svc::MemoryAttribute_PermissionLocked) == (attr & ams::svc::MemoryAttribute_PermissionLocked), svc::ResultInvalidCombination());
/* Validate that the region is in range for the current process. */
auto &page_table = GetCurrentProcess().GetPageTable();
R_UNLESS(page_table.Contains(address, size), svc::ResultInvalidCurrentMemory());
/* Set the memory attribute. */
R_RETURN(page_table.SetMemoryAttribute(address, size, mask, attr));
}
Result MapMemory(uintptr_t dst_address, uintptr_t src_address, size_t size) {
/* Validate that addresses are page aligned. */
R_UNLESS(util::IsAligned(dst_address, PageSize), svc::ResultInvalidAddress());
R_UNLESS(util::IsAligned(src_address, PageSize), svc::ResultInvalidAddress());
/* Validate that size is positive and page aligned. */
R_UNLESS(size > 0, svc::ResultInvalidSize());
R_UNLESS(util::IsAligned(size, PageSize), svc::ResultInvalidSize());
/* Ensure that neither mapping overflows. */
R_UNLESS(src_address < src_address + size, svc::ResultInvalidCurrentMemory());
R_UNLESS(dst_address < dst_address + size, svc::ResultInvalidCurrentMemory());
/* Get the page table we're operating on. */
auto &page_table = GetCurrentProcess().GetPageTable();
/* Ensure that the memory we're mapping is in range. */
R_UNLESS(page_table.Contains(src_address, size), svc::ResultInvalidCurrentMemory());
R_UNLESS(page_table.CanContain(dst_address, size, KMemoryState_Stack), svc::ResultInvalidMemoryRegion());
/* Map the memory. */
R_RETURN(page_table.MapMemory(dst_address, src_address, size));
}
Result UnmapMemory(uintptr_t dst_address, uintptr_t src_address, size_t size) {
/* Validate that addresses are page aligned. */
R_UNLESS(util::IsAligned(dst_address, PageSize), svc::ResultInvalidAddress());
R_UNLESS(util::IsAligned(src_address, PageSize), svc::ResultInvalidAddress());
/* Validate that size is positive and page aligned. */
R_UNLESS(size > 0, svc::ResultInvalidSize());
R_UNLESS(util::IsAligned(size, PageSize), svc::ResultInvalidSize());
/* Ensure that neither mapping overflows. */
R_UNLESS(src_address < src_address + size, svc::ResultInvalidCurrentMemory());
R_UNLESS(dst_address < dst_address + size, svc::ResultInvalidCurrentMemory());
/* Get the page table we're operating on. */
auto &page_table = GetCurrentProcess().GetPageTable();
/* Ensure that the memory we're unmapping is in range. */
R_UNLESS(page_table.Contains(src_address, size), svc::ResultInvalidCurrentMemory());
R_UNLESS(page_table.CanContain(dst_address, size, KMemoryState_Stack), svc::ResultInvalidMemoryRegion());
/* Unmap the memory. */
R_RETURN(page_table.UnmapMemory(dst_address, src_address, size));
}
}
/* ============================= 64 ABI ============================= */
Result SetMemoryPermission64(ams::svc::Address address, ams::svc::Size size, ams::svc::MemoryPermission perm) {
R_RETURN(SetMemoryPermission(address, size, perm));
}
Result SetMemoryAttribute64(ams::svc::Address address, ams::svc::Size size, uint32_t mask, uint32_t attr) {
R_RETURN(SetMemoryAttribute(address, size, mask, attr));
}
Result MapMemory64(ams::svc::Address dst_address, ams::svc::Address src_address, ams::svc::Size size) {
R_RETURN(MapMemory(dst_address, src_address, size));
}
Result UnmapMemory64(ams::svc::Address dst_address, ams::svc::Address src_address, ams::svc::Size size) {
R_RETURN(UnmapMemory(dst_address, src_address, size));
}
/* ============================= 64From32 ABI ============================= */
Result SetMemoryPermission64From32(ams::svc::Address address, ams::svc::Size size, ams::svc::MemoryPermission perm) {
R_RETURN(SetMemoryPermission(address, size, perm));
}
Result SetMemoryAttribute64From32(ams::svc::Address address, ams::svc::Size size, uint32_t mask, uint32_t attr) {
R_RETURN(SetMemoryAttribute(address, size, mask, attr));
}
Result MapMemory64From32(ams::svc::Address dst_address, ams::svc::Address src_address, ams::svc::Size size) {
R_RETURN(MapMemory(dst_address, src_address, size));
}
Result UnmapMemory64From32(ams::svc::Address dst_address, ams::svc::Address src_address, ams::svc::Size size) {
R_RETURN(UnmapMemory(dst_address, src_address, size));
}
}
| 8,044
|
C++
|
.cpp
| 125
| 54.336
| 162
| 0.623446
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,042
|
kern_svc_synchronization.cpp
|
Atmosphere-NX_Atmosphere/libraries/libmesosphere/source/svc/kern_svc_synchronization.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <mesosphere.hpp>
namespace ams::kern::svc {
/* ============================= Common ============================= */
namespace {
Result CloseHandle(ams::svc::Handle handle) {
/* Remove the handle. */
R_UNLESS(GetCurrentProcess().GetHandleTable().Remove(handle), svc::ResultInvalidHandle());
R_SUCCEED();
}
Result ResetSignal(ams::svc::Handle handle) {
/* Get the current handle table. */
auto &handle_table = GetCurrentProcess().GetHandleTable();
/* Try to reset as readable event. */
{
KScopedAutoObject readable_event = handle_table.GetObject<KReadableEvent>(handle);
if (readable_event.IsNotNull()) {
if (auto * const interrupt_event = readable_event->DynamicCast<KInterruptEvent *>(); interrupt_event != nullptr) {
R_RETURN(interrupt_event->Reset());
} else {
R_RETURN(readable_event->Reset());
}
}
}
/* Try to reset as process. */
{
KScopedAutoObject process = handle_table.GetObject<KProcess>(handle);
if (process.IsNotNull()) {
R_RETURN(process->Reset());
}
}
R_THROW(svc::ResultInvalidHandle());
}
Result WaitSynchronizationImpl(int32_t *out_index, KSynchronizationObject **objs, int32_t num_handles, int64_t timeout_ns) {
/* Convert the timeout from nanoseconds to ticks. */
s64 timeout;
if (timeout_ns > 0) {
u64 ticks = KHardwareTimer::GetTick();
ticks += ams::svc::Tick(TimeSpan::FromNanoSeconds(timeout_ns));
ticks += 2;
timeout = ticks;
} else {
timeout = timeout_ns;
}
R_RETURN(KSynchronizationObject::Wait(out_index, objs, num_handles, timeout));
}
Result WaitSynchronization(int32_t *out_index, KUserPointer<const ams::svc::Handle *> user_handles, int32_t num_handles, int64_t timeout_ns) {
/* Ensure number of handles is valid. */
R_UNLESS(0 <= num_handles && num_handles <= ams::svc::ArgumentHandleCountMax, svc::ResultOutOfRange());
/* Get the synchronization context. */
auto &handle_table = GetCurrentProcess().GetHandleTable();
KSynchronizationObject **objs = GetCurrentThread().GetSynchronizationObjectBuffer();
ams::svc::Handle *handles = GetCurrentThread().GetHandleBuffer();
/* Copy user handles. */
if (num_handles > 0) {
/* Ensure that we can try to get the handles. */
R_UNLESS(GetCurrentProcess().GetPageTable().Contains(KProcessAddress(user_handles.GetUnsafePointer()), num_handles * sizeof(ams::svc::Handle)), svc::ResultInvalidPointer());
/* Get the handles. */
R_TRY(user_handles.CopyArrayTo(handles, num_handles));
/* Convert the handles to objects. */
R_UNLESS(handle_table.GetMultipleObjects<KSynchronizationObject>(objs, handles, num_handles), svc::ResultInvalidHandle());
}
/* Ensure handles are closed when we're done. */
ON_SCOPE_EXIT {
for (auto i = 0; i < num_handles; ++i) {
objs[i]->Close();
}
};
/* Wait on the objects. */
R_TRY_CATCH(WaitSynchronizationImpl(out_index, objs, num_handles, timeout_ns)) {
R_CONVERT(svc::ResultSessionClosed, ResultSuccess())
} R_END_TRY_CATCH;
R_SUCCEED();
}
Result CancelSynchronization(ams::svc::Handle handle) {
/* Get the thread from its handle. */
KScopedAutoObject thread = GetCurrentProcess().GetHandleTable().GetObject<KThread>(handle);
R_UNLESS(thread.IsNotNull(), svc::ResultInvalidHandle());
/* Cancel the thread's wait. */
thread->WaitCancel();
R_SUCCEED();
}
void SynchronizePreemptionState() {
/* Lock the scheduler. */
KScopedSchedulerLock sl;
/* If the current thread is pinned, unpin it. */
KProcess *cur_process = GetCurrentProcessPointer();
if (cur_process->GetPinnedThread(GetCurrentCoreId()) == GetCurrentThreadPointer()) {
/* Clear the current thread's interrupt flag. */
GetCurrentThread().ClearInterruptFlag();
/* Unpin the current thread. */
cur_process->UnpinCurrentThread();
}
}
}
/* ============================= 64 ABI ============================= */
Result CloseHandle64(ams::svc::Handle handle) {
R_RETURN(CloseHandle(handle));
}
Result ResetSignal64(ams::svc::Handle handle) {
R_RETURN(ResetSignal(handle));
}
Result WaitSynchronization64(int32_t *out_index, KUserPointer<const ams::svc::Handle *> handles, int32_t num_handles, int64_t timeout_ns) {
R_RETURN(WaitSynchronization(out_index, handles, num_handles, timeout_ns));
}
Result CancelSynchronization64(ams::svc::Handle handle) {
R_RETURN(CancelSynchronization(handle));
}
void SynchronizePreemptionState64() {
return SynchronizePreemptionState();
}
/* ============================= 64From32 ABI ============================= */
Result CloseHandle64From32(ams::svc::Handle handle) {
R_RETURN(CloseHandle(handle));
}
Result ResetSignal64From32(ams::svc::Handle handle) {
R_RETURN(ResetSignal(handle));
}
Result WaitSynchronization64From32(int32_t *out_index, KUserPointer<const ams::svc::Handle *> handles, int32_t num_handles, int64_t timeout_ns) {
R_RETURN(WaitSynchronization(out_index, handles, num_handles, timeout_ns));
}
Result CancelSynchronization64From32(ams::svc::Handle handle) {
R_RETURN(CancelSynchronization(handle));
}
void SynchronizePreemptionState64From32() {
return SynchronizePreemptionState();
}
}
| 6,941
|
C++
|
.cpp
| 142
| 37.93662
| 189
| 0.588818
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,043
|
kern_svc_info.cpp
|
Atmosphere-NX_Atmosphere/libraries/libmesosphere/source/svc/kern_svc_info.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <mesosphere.hpp>
namespace ams::kern::svc {
/* ============================= Common ============================= */
namespace {
Result GetInitialProcessIdRange(u64 *out, ams::svc::InitialProcessIdRangeInfo info) {
switch (info) {
case ams::svc::InitialProcessIdRangeInfo_Minimum:
MESOSPHERE_ABORT_UNLESS(GetInitialProcessIdMin() <= GetInitialProcessIdMax());
*out = GetInitialProcessIdMin();
break;
case ams::svc::InitialProcessIdRangeInfo_Maximum:
MESOSPHERE_ABORT_UNLESS(GetInitialProcessIdMin() <= GetInitialProcessIdMax());
*out = GetInitialProcessIdMax();
break;
default:
R_THROW(svc::ResultInvalidCombination());
}
R_SUCCEED();
}
Result GetInfoImpl(u64 *out, ams::svc::InfoType info_type, KProcess *process) {
switch (info_type) {
case ams::svc::InfoType_CoreMask:
*out = process->GetCoreMask();
break;
case ams::svc::InfoType_PriorityMask:
*out = process->GetPriorityMask();
break;
case ams::svc::InfoType_AliasRegionAddress:
*out = GetInteger(process->GetPageTable().GetAliasRegionStart());
break;
case ams::svc::InfoType_AliasRegionSize:
*out = process->GetPageTable().GetAliasRegionSize();
break;
case ams::svc::InfoType_HeapRegionAddress:
*out = GetInteger(process->GetPageTable().GetHeapRegionStart());
break;
case ams::svc::InfoType_HeapRegionSize:
*out = process->GetPageTable().GetHeapRegionSize();
break;
case ams::svc::InfoType_TotalMemorySize:
*out = process->GetTotalUserPhysicalMemorySize();
break;
case ams::svc::InfoType_UsedMemorySize:
*out = process->GetUsedUserPhysicalMemorySize();
break;
case ams::svc::InfoType_AslrRegionAddress:
*out = GetInteger(process->GetPageTable().GetAliasCodeRegionStart());
break;
case ams::svc::InfoType_AslrRegionSize:
*out = process->GetPageTable().GetAliasCodeRegionSize();
break;
case ams::svc::InfoType_StackRegionAddress:
*out = GetInteger(process->GetPageTable().GetStackRegionStart());
break;
case ams::svc::InfoType_StackRegionSize:
*out = process->GetPageTable().GetStackRegionSize();
break;
case ams::svc::InfoType_SystemResourceSizeTotal:
*out = process->GetTotalSystemResourceSize();
break;
case ams::svc::InfoType_SystemResourceSizeUsed:
*out = process->GetUsedSystemResourceSize();
break;
case ams::svc::InfoType_ProgramId:
*out = process->GetProgramId();
break;
case ams::svc::InfoType_UserExceptionContextAddress:
*out = GetInteger(process->GetProcessLocalRegionAddress());
break;
case ams::svc::InfoType_TotalNonSystemMemorySize:
*out = process->GetTotalNonSystemUserPhysicalMemorySize();
break;
case ams::svc::InfoType_UsedNonSystemMemorySize:
*out = process->GetUsedNonSystemUserPhysicalMemorySize();
break;
case ams::svc::InfoType_IsApplication:
*out = process->IsApplication();
break;
case ams::svc::InfoType_FreeThreadCount:
if (KResourceLimit *resource_limit = process->GetResourceLimit(); resource_limit != nullptr) {
const auto current_value = resource_limit->GetCurrentValue(ams::svc::LimitableResource_ThreadCountMax);
const auto limit_value = resource_limit->GetLimitValue(ams::svc::LimitableResource_ThreadCountMax);
*out = limit_value - current_value;
} else {
*out = 0;
}
break;
case ams::svc::InfoType_AliasRegionExtraSize:
*out = process->GetPageTable().GetAliasRegionExtraSize();
break;
MESOSPHERE_UNREACHABLE_DEFAULT_CASE();
}
R_SUCCEED();
}
Result GetInfo(u64 *out, ams::svc::InfoType info_type, ams::svc::Handle handle, u64 info_subtype) {
switch (info_type) {
case ams::svc::InfoType_CoreMask:
case ams::svc::InfoType_PriorityMask:
case ams::svc::InfoType_AliasRegionAddress:
case ams::svc::InfoType_AliasRegionSize:
case ams::svc::InfoType_HeapRegionAddress:
case ams::svc::InfoType_HeapRegionSize:
case ams::svc::InfoType_TotalMemorySize:
case ams::svc::InfoType_UsedMemorySize:
case ams::svc::InfoType_AslrRegionAddress:
case ams::svc::InfoType_AslrRegionSize:
case ams::svc::InfoType_StackRegionAddress:
case ams::svc::InfoType_StackRegionSize:
case ams::svc::InfoType_SystemResourceSizeTotal:
case ams::svc::InfoType_SystemResourceSizeUsed:
case ams::svc::InfoType_ProgramId:
case ams::svc::InfoType_UserExceptionContextAddress:
case ams::svc::InfoType_TotalNonSystemMemorySize:
case ams::svc::InfoType_UsedNonSystemMemorySize:
case ams::svc::InfoType_IsApplication:
case ams::svc::InfoType_FreeThreadCount:
case ams::svc::InfoType_AliasRegionExtraSize:
{
/* These info types don't support non-zero subtypes. */
R_UNLESS(info_subtype == 0, svc::ResultInvalidCombination());
/* Get the process from its handle. */
KScopedAutoObject process = GetCurrentProcess().GetHandleTable().GetObject<KProcess>(handle);
#if defined(MESOSPHERE_ENABLE_GET_INFO_OF_DEBUG_PROCESS)
/* If we the process is valid, use it. */
if (process.IsNotNull()) {
R_RETURN(GetInfoImpl(out, info_type, process.GetPointerUnsafe()));
}
/* Otherwise, as a mesosphere extension check if we were passed a usable KDebug. */
KScopedAutoObject debug = GetCurrentProcess().GetHandleTable().GetObject<KDebug>(handle);
R_UNLESS(debug.IsNotNull(), svc::ResultInvalidHandle());
/* Get the process from the debug object. */
/* TODO: ResultInvalidHandle()? */
R_UNLESS(debug->IsAttached(), svc::ResultProcessTerminated());
R_UNLESS(debug->OpenProcess(), svc::ResultProcessTerminated());
/* Close the process when we're done. */
ON_SCOPE_EXIT { debug->CloseProcess(); };
/* Return the info. */
R_RETURN(GetInfoImpl(out, info_type, debug->GetProcessUnsafe()));
#else
/* Verify that the process is valid. */
R_UNLESS(process.IsNotNull(), svc::ResultInvalidHandle());
/* Return the relevant info. */
R_RETURN(GetInfoImpl(out, info_type, process.GetPointerUnsafe()));
#endif
}
break;
case ams::svc::InfoType_DebuggerAttached:
{
/* Verify the input handle is invalid. */
R_UNLESS(handle == ams::svc::InvalidHandle, svc::ResultInvalidHandle());
/* Verify the sub-type is valid. */
R_UNLESS(info_subtype == 0, svc::ResultInvalidCombination());
/* Get whether debugger is attached. */
*out = GetCurrentProcess().GetDebugObject() != nullptr;
}
break;
case ams::svc::InfoType_ResourceLimit:
{
/* Verify the input handle is invalid. */
R_UNLESS(handle == ams::svc::InvalidHandle, svc::ResultInvalidHandle());
/* Verify the sub-type is valid. */
R_UNLESS(info_subtype == 0, svc::ResultInvalidCombination());
/* Get the handle table and resource limit. */
KHandleTable &handle_table = GetCurrentProcess().GetHandleTable();
KResourceLimit *resource_limit = GetCurrentProcess().GetResourceLimit();
if (resource_limit != nullptr) {
/* Get a new handle for the resource limit. */
ams::svc::Handle tmp;
R_TRY(handle_table.Add(std::addressof(tmp), resource_limit));
/* Set the output. */
*out = tmp;
} else {
/* Set the output. */
*out = ams::svc::InvalidHandle;
}
}
break;
case ams::svc::InfoType_IdleTickCount:
{
/* Verify the input handle is invalid. */
R_UNLESS(handle == ams::svc::InvalidHandle, svc::ResultInvalidHandle());
/* Disable dispatch while we get the tick count. */
KScopedDisableDispatch dd;
/* Verify the requested core is valid. */
const bool core_valid = (info_subtype == static_cast<u64>(-1ul)) || (info_subtype == static_cast<u64>(GetCurrentCoreId()));
R_UNLESS(core_valid, svc::ResultInvalidCombination());
/* Get the idle tick count. */
*out = Kernel::GetScheduler().GetIdleThread()->GetCpuTime() - Kernel::GetInterruptTaskManager().GetCpuTime();
}
break;
case ams::svc::InfoType_RandomEntropy:
{
/* Verify the input handle is invalid. */
R_UNLESS(handle == ams::svc::InvalidHandle, svc::ResultInvalidHandle());
/* Verify the requested entropy is valid. */
R_UNLESS(info_subtype < 4, svc::ResultInvalidCombination());
/* Get the entropy. */
*out = GetCurrentProcess().GetRandomEntropy(info_subtype);
}
break;
case ams::svc::InfoType_InitialProcessIdRange:
{
/* NOTE: This info type was added in 4.0.0, and removed in 5.0.0. */
R_UNLESS(GetTargetFirmware() < TargetFirmware_5_0_0, svc::ResultInvalidEnumValue());
/* Verify the input handle is invalid. */
R_UNLESS(handle == ams::svc::InvalidHandle, svc::ResultInvalidHandle());
/* Get the process id range. */
R_TRY(GetInitialProcessIdRange(out, static_cast<ams::svc::InitialProcessIdRangeInfo>(info_subtype)));
}
break;
case ams::svc::InfoType_ThreadTickCount:
{
/* Verify the requested core is valid. */
const bool core_valid = (info_subtype == static_cast<u64>(-1ul)) || (info_subtype < cpu::NumVirtualCores);
R_UNLESS(core_valid, svc::ResultInvalidCombination());
/* Get the thread from its handle. */
KScopedAutoObject thread = GetCurrentProcess().GetHandleTable().GetObject<KThread>(handle);
R_UNLESS(thread.IsNotNull(), svc::ResultInvalidHandle());
/* Disable dispatch while we get the tick count. */
KScopedDisableDispatch dd;
/* Determine the tick count. */
s64 tick_count;
if (info_subtype == static_cast<u64>(-1ul)) {
tick_count = thread->GetCpuTime();
if (GetCurrentThreadPointer() == thread.GetPointerUnsafe()) {
const s64 cur_tick = KHardwareTimer::GetTick();
const s64 prev_switch = Kernel::GetScheduler().GetLastContextSwitchTime();
tick_count += (cur_tick - prev_switch);
}
} else {
const s32 phys_core = cpu::VirtualToPhysicalCoreMap[info_subtype];
MESOSPHERE_ABORT_UNLESS(phys_core < static_cast<s32>(cpu::NumCores));
tick_count = thread->GetCpuTime(phys_core);
if (GetCurrentThreadPointer() == thread.GetPointerUnsafe() && phys_core == GetCurrentCoreId()) {
const s64 cur_tick = KHardwareTimer::GetTick();
const s64 prev_switch = Kernel::GetScheduler().GetLastContextSwitchTime();
tick_count += (cur_tick - prev_switch);
}
}
/* Set the output. */
*out = tick_count;
}
break;
case ams::svc::InfoType_IsSvcPermitted:
{
/* Verify the input handle is invalid. */
R_UNLESS(handle == ams::svc::InvalidHandle, svc::ResultInvalidHandle());
/* Verify the sub-type is valid. */
R_UNLESS(info_subtype == svc::SvcId_SynchronizePreemptionState, svc::ResultInvalidCombination());
/* Get whether the svc is permitted. */
*out = GetCurrentProcess().IsPermittedSvc(static_cast<svc::SvcId>(info_subtype));
}
break;
case ams::svc::InfoType_IoRegionHint:
{
/* Verify the sub-type is valid. */
R_UNLESS(info_subtype == 0, svc::ResultInvalidCombination());
/* Get the io region from its handle. */
KScopedAutoObject io_region = GetCurrentProcess().GetHandleTable().GetObject<KIoRegion>(handle);
R_UNLESS(io_region.IsNotNull(), svc::ResultInvalidHandle());
/* Get the io region's address hint. */
*out = io_region->GetHint();
}
break;
case ams::svc::InfoType_TransferMemoryHint:
{
/* Verify the sub-type is valid. */
R_UNLESS(info_subtype == 0, svc::ResultInvalidCombination());
/* Get the transfer memory from its handle. */
KScopedAutoObject transfer_memory = GetCurrentProcess().GetHandleTable().GetObject<KTransferMemory>(handle);
R_UNLESS(transfer_memory.IsNotNull(), svc::ResultInvalidHandle());
/* Get the transfer memory's address hint. */
*out = transfer_memory->GetHint();
}
break;
case ams::svc::InfoType_MesosphereMeta:
{
/* Verify the handle is invalid. */
R_UNLESS(handle == ams::svc::InvalidHandle, svc::ResultInvalidHandle());
switch (static_cast<ams::svc::MesosphereMetaInfo>(info_subtype)) {
case ams::svc::MesosphereMetaInfo_KernelVersion:
{
/* Return the supported kernel version. */
*out = ams::svc::SupportedKernelVersion;
}
break;
case ams::svc::MesosphereMetaInfo_IsKTraceEnabled:
{
/* Return whether the kernel supports tracing. */
constexpr u64 KTraceValue = ams::kern::IsKTraceEnabled ? 1 : 0;
*out = KTraceValue;
}
break;
case ams::svc::MesosphereMetaInfo_IsSingleStepEnabled:
{
/* Return whether the kernel supports hardware single step. */
#if defined(MESOSPHERE_ENABLE_HARDWARE_SINGLE_STEP)
*out = 1;
#else
*out = 0;
#endif
}
break;
default:
R_THROW(svc::ResultInvalidCombination());
}
}
break;
case ams::svc::InfoType_MesosphereCurrentProcess:
{
/* Verify the input handle is invalid. */
R_UNLESS(handle == ams::svc::InvalidHandle, svc::ResultInvalidHandle());
/* Verify the sub-type is valid. */
R_UNLESS(info_subtype == 0, svc::ResultInvalidCombination());
/* Get the handle table. */
KHandleTable &handle_table = GetCurrentProcess().GetHandleTable();
/* Get a new handle for the current process. */
ams::svc::Handle tmp;
R_TRY(handle_table.Add(std::addressof(tmp), GetCurrentProcessPointer()));
/* Set the output. */
*out = tmp;
}
break;
default:
{
/* For debug, log the invalid info call. */
MESOSPHERE_LOG("GetInfo(%p, %u, %08x, %lu) was called\n", out, static_cast<u32>(info_type), static_cast<u32>(handle), info_subtype);
}
R_THROW(svc::ResultInvalidEnumValue());
}
R_SUCCEED();
}
constexpr bool IsValidMemoryPool(u64 pool) {
switch (static_cast<KMemoryManager::Pool>(pool)) {
case KMemoryManager::Pool_Application:
case KMemoryManager::Pool_Applet:
case KMemoryManager::Pool_System:
case KMemoryManager::Pool_SystemNonSecure:
return true;
default:
return false;
}
}
Result GetSystemInfo(u64 *out, ams::svc::SystemInfoType info_type, ams::svc::Handle handle, u64 info_subtype) {
switch (info_type) {
case ams::svc::SystemInfoType_TotalPhysicalMemorySize:
case ams::svc::SystemInfoType_UsedPhysicalMemorySize:
{
/* Verify the input handle is invalid. */
R_UNLESS(handle == ams::svc::InvalidHandle, svc::ResultInvalidHandle());
/* Verify the sub-type is valid. */
R_UNLESS(IsValidMemoryPool(info_subtype), svc::ResultInvalidCombination());
/* Convert to pool. */
const auto pool = static_cast<KMemoryManager::Pool>(info_subtype);
/* Get the memory size. */
auto &mm = Kernel::GetMemoryManager();
switch (info_type) {
case ams::svc::SystemInfoType_TotalPhysicalMemorySize:
*out = mm.GetSize(pool);
break;
case ams::svc::SystemInfoType_UsedPhysicalMemorySize:
*out = mm.GetSize(pool) - mm.GetFreeSize(pool);
break;
MESOSPHERE_UNREACHABLE_DEFAULT_CASE();
}
}
break;
case ams::svc::SystemInfoType_InitialProcessIdRange:
{
/* Verify the handle is invalid. */
R_UNLESS(handle == ams::svc::InvalidHandle, svc::ResultInvalidHandle());
/* Get the process id range. */
R_TRY(GetInitialProcessIdRange(out, static_cast<ams::svc::InitialProcessIdRangeInfo>(info_subtype)));
}
break;
default:
R_THROW(svc::ResultInvalidEnumValue());
}
R_SUCCEED();
}
}
/* ============================= 64 ABI ============================= */
Result GetInfo64(uint64_t *out, ams::svc::InfoType info_type, ams::svc::Handle handle, uint64_t info_subtype) {
R_RETURN(GetInfo(out, info_type, handle, info_subtype));
}
Result GetSystemInfo64(uint64_t *out, ams::svc::SystemInfoType info_type, ams::svc::Handle handle, uint64_t info_subtype) {
R_RETURN(GetSystemInfo(out, info_type, handle, info_subtype));
}
/* ============================= 64From32 ABI ============================= */
Result GetInfo64From32(uint64_t *out, ams::svc::InfoType info_type, ams::svc::Handle handle, uint64_t info_subtype) {
R_RETURN(GetInfo(out, info_type, handle, info_subtype));
}
Result GetSystemInfo64From32(uint64_t *out, ams::svc::SystemInfoType info_type, ams::svc::Handle handle, uint64_t info_subtype) {
R_RETURN(GetSystemInfo(out, info_type, handle, info_subtype));
}
}
| 23,726
|
C++
|
.cpp
| 411
| 36.518248
| 156
| 0.489959
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,044
|
kern_svc_insecure_memory.cpp
|
Atmosphere-NX_Atmosphere/libraries/libmesosphere/source/svc/kern_svc_insecure_memory.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <mesosphere.hpp>
namespace ams::kern::svc {
/* ============================= Common ============================= */
namespace {
Result MapInsecurePhysicalMemory(uintptr_t address, size_t size) {
/* Validate the address/size. */
R_UNLESS(util::IsAligned(size, PageSize), svc::ResultInvalidSize());
R_UNLESS(size > 0, svc::ResultInvalidSize());
R_UNLESS(util::IsAligned(address, PageSize), svc::ResultInvalidAddress());
R_UNLESS((address < address + size), svc::ResultInvalidCurrentMemory());
/* Verify that the mapping is in range. */
auto &pt = GetCurrentProcess().GetPageTable();
R_UNLESS(GetCurrentProcess().GetPageTable().CanContain(address, size, KMemoryState_Insecure), svc::ResultInvalidMemoryRegion());
/* Map the insecure memory. */
R_RETURN(pt.MapInsecurePhysicalMemory(address, size));
}
Result UnmapInsecurePhysicalMemory(uintptr_t address, size_t size) {
/* Validate the address/size. */
R_UNLESS(util::IsAligned(size, PageSize), svc::ResultInvalidSize());
R_UNLESS(size > 0, svc::ResultInvalidSize());
R_UNLESS(util::IsAligned(address, PageSize), svc::ResultInvalidAddress());
R_UNLESS((address < address + size), svc::ResultInvalidCurrentMemory());
/* Verify that the mapping is in range. */
auto &pt = GetCurrentProcess().GetPageTable();
R_UNLESS(GetCurrentProcess().GetPageTable().CanContain(address, size, KMemoryState_Insecure), svc::ResultInvalidMemoryRegion());
/* Map the insecure memory. */
R_RETURN(pt.UnmapInsecurePhysicalMemory(address, size));
}
}
/* ============================= 64 ABI ============================= */
Result MapInsecurePhysicalMemory64(ams::svc::Address address, ams::svc::Size size) {
R_RETURN(MapInsecurePhysicalMemory(address, size));
}
Result UnmapInsecurePhysicalMemory64(ams::svc::Address address, ams::svc::Size size) {
R_RETURN(UnmapInsecurePhysicalMemory(address, size));
}
/* ============================= 64From32 ABI ============================= */
Result MapInsecurePhysicalMemory64From32(ams::svc::Address address, ams::svc::Size size) {
R_RETURN(MapInsecurePhysicalMemory(address, size));
}
Result UnmapInsecurePhysicalMemory64From32(ams::svc::Address address, ams::svc::Size size) {
R_RETURN(UnmapInsecurePhysicalMemory(address, size));
}
}
| 3,308
|
C++
|
.cpp
| 59
| 48.508475
| 140
| 0.624072
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,045
|
kern_svc_thread_profiler.cpp
|
Atmosphere-NX_Atmosphere/libraries/libmesosphere/source/svc/kern_svc_thread_profiler.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <mesosphere.hpp>
namespace ams::kern::svc {
/* ============================= Common ============================= */
namespace {
Result GetLastThreadInfoImpl(ams::svc::LastThreadContext *out_context, uintptr_t *out_tls_address, uint32_t *out_flags) {
/* Disable interrupts. */
KScopedInterruptDisable di;
/* Get the previous thread. */
KThread *prev_thread = Kernel::GetScheduler().GetPreviousThread();
R_UNLESS(prev_thread != nullptr, svc::ResultNoThread());
/* Verify the last thread was owned by the current process. */
R_UNLESS(prev_thread->GetOwnerProcess() == GetCurrentProcessPointer(), svc::ResultUnknownThread());
/* Clear the output flags. */
*out_flags = 0;
/* Get the thread's exception context. */
GetExceptionContext(prev_thread)->GetSvcThreadContext(out_context);
/* Get the tls address. */
*out_tls_address = GetInteger(prev_thread->GetThreadLocalRegionAddress());
/* Set the syscall flag if appropriate. */
if (prev_thread->IsCallingSvc()) {
*out_flags |= ams::svc::LastThreadInfoFlag_ThreadInSystemCall;
}
R_SUCCEED();
}
Result SynchronizeCurrentProcessToFutureTime(int64_t ns) {
/* Get the wait object. */
KWaitObject *wait_object = GetCurrentProcess().GetWaitObjectPointer();
/* Convert the timeout from nanoseconds to ticks. */
s64 timeout;
if (ns > 0) {
u64 ticks = KHardwareTimer::GetTick();
ticks += ams::svc::Tick(TimeSpan::FromNanoSeconds(ns));
ticks += 2;
timeout = ticks;
} else {
timeout = ns;
}
/* Synchronize to the desired time. */
R_TRY(wait_object->Synchronize(timeout));
R_SUCCEED();
}
Result GetDebugFutureThreadInfo(ams::svc::LastThreadContext *out_context, uint64_t *out_thread_id, ams::svc::Handle debug_handle, int64_t ns) {
/* Only allow invoking the svc on development hardware. */
R_UNLESS(KTargetSystem::IsDebugMode(), svc::ResultNoThread());
/* Get the debug object. */
KScopedAutoObject debug = GetCurrentProcess().GetHandleTable().GetObject<KDebug>(debug_handle);
R_UNLESS(debug.IsNotNull(), svc::ResultInvalidHandle());
/* Synchronize the current process to the desired time. */
R_TRY(SynchronizeCurrentProcessToFutureTime(ns));
/* Get the running thread info. */
R_TRY(debug->GetRunningThreadInfo(out_context, out_thread_id));
R_SUCCEED();
}
Result LegacyGetFutureThreadInfo(ams::svc::LastThreadContext *out_context, uintptr_t *out_tls_address, uint32_t *out_flags, int64_t ns) {
/* Only allow invoking the svc on development hardware. */
R_UNLESS(KTargetSystem::IsDebugMode(), svc::ResultNoThread());
/* Synchronize the current process to the desired time. */
R_TRY(SynchronizeCurrentProcessToFutureTime(ns));
/* Get the thread info. */
R_TRY(GetLastThreadInfoImpl(out_context, out_tls_address, out_flags));
R_SUCCEED();
}
Result GetLastThreadInfo(ams::svc::LastThreadContext *out_context, uintptr_t *out_tls_address, uint32_t *out_flags) {
/* Only allow invoking the svc on development hardware. */
R_UNLESS(KTargetSystem::IsDebugMode(), svc::ResultNoThread());
/* Get the thread info. */
R_TRY(GetLastThreadInfoImpl(out_context, out_tls_address, out_flags));
R_SUCCEED();
}
}
/* ============================= 64 ABI ============================= */
Result GetDebugFutureThreadInfo64(ams::svc::lp64::LastThreadContext *out_context, uint64_t *out_thread_id, ams::svc::Handle debug_handle, int64_t ns) {
R_RETURN(GetDebugFutureThreadInfo(out_context, out_thread_id, debug_handle, ns));
}
Result LegacyGetFutureThreadInfo64(ams::svc::lp64::LastThreadContext *out_context, ams::svc::Address *out_tls_address, uint32_t *out_flags, int64_t ns) {
R_RETURN(LegacyGetFutureThreadInfo(out_context, reinterpret_cast<uintptr_t *>(out_tls_address), out_flags, ns));
}
Result GetLastThreadInfo64(ams::svc::lp64::LastThreadContext *out_context, ams::svc::Address *out_tls_address, uint32_t *out_flags) {
static_assert(sizeof(*out_tls_address) == sizeof(uintptr_t));
R_RETURN(GetLastThreadInfo(out_context, reinterpret_cast<uintptr_t *>(out_tls_address), out_flags));
}
/* ============================= 64From32 ABI ============================= */
Result GetDebugFutureThreadInfo64From32(ams::svc::ilp32::LastThreadContext *out_context, uint64_t *out_thread_id, ams::svc::Handle debug_handle, int64_t ns) {
ams::svc::LastThreadContext context = {};
R_TRY(GetDebugFutureThreadInfo(std::addressof(context), out_thread_id, debug_handle, ns));
*out_context = {
.fp = static_cast<u32>(context.fp),
.sp = static_cast<u32>(context.sp),
.lr = static_cast<u32>(context.lr),
.pc = static_cast<u32>(context.pc),
};
R_SUCCEED();
}
Result LegacyGetFutureThreadInfo64From32(ams::svc::ilp32::LastThreadContext *out_context, ams::svc::Address *out_tls_address, uint32_t *out_flags, int64_t ns) {
static_assert(sizeof(*out_tls_address) == sizeof(uintptr_t));
ams::svc::LastThreadContext context = {};
R_TRY(LegacyGetFutureThreadInfo(std::addressof(context), reinterpret_cast<uintptr_t *>(out_tls_address), out_flags, ns));
*out_context = {
.fp = static_cast<u32>(context.fp),
.sp = static_cast<u32>(context.sp),
.lr = static_cast<u32>(context.lr),
.pc = static_cast<u32>(context.pc),
};
R_SUCCEED();
}
Result GetLastThreadInfo64From32(ams::svc::ilp32::LastThreadContext *out_context, ams::svc::Address *out_tls_address, uint32_t *out_flags) {
static_assert(sizeof(*out_tls_address) == sizeof(uintptr_t));
ams::svc::LastThreadContext context = {};
R_TRY(GetLastThreadInfo(std::addressof(context), reinterpret_cast<uintptr_t *>(out_tls_address), out_flags));
*out_context = {
.fp = static_cast<u32>(context.fp),
.sp = static_cast<u32>(context.sp),
.lr = static_cast<u32>(context.lr),
.pc = static_cast<u32>(context.pc),
};
R_SUCCEED();
}
}
| 7,400
|
C++
|
.cpp
| 133
| 45.609023
| 164
| 0.616417
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,046
|
util_utf8_string_util.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/util/util_utf8_string_util.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <vapours.hpp>
namespace ams::util {
namespace {
constexpr inline const u8 CodePointByteLengthTable[0x100] = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};
constexpr ALWAYS_INLINE size_t GetCodePointByteLength(u8 c) {
return CodePointByteLengthTable[c];
}
constexpr ALWAYS_INLINE bool IsValidTail(u8 c) {
return (c & 0xC0) == 0x80;
}
constexpr inline bool VerifyCode(const u8 *code, size_t size) {
switch (size) {
case 1:
break;
case 2:
if (!IsValidTail(code[1])) {
return false;
}
break;
case 3:
if (code[0] == 0xE0 && (code[1] & 0x20) == 0x00) {
return false;
}
if (code[0] == 0xED && (code[1] & 0x20) != 0x00) {
return false;
}
if (!IsValidTail(code[1]) || !IsValidTail(code[2])) {
return false;
}
break;
case 4:
if (code[0] == 0xF0 && (code[1] & 0x30) == 0x00) {
return false;
}
if (code[0] == 0xF4 && (code[1] & 0x30) != 0x00) {
return false;
}
if (!IsValidTail(code[1]) || !IsValidTail(code[2]) || !IsValidTail(code[3])) {
return false;
}
break;
default:
return false;
}
return true;
}
}
bool VerifyUtf8String(const char *str, size_t size) {
return GetCodePointCountOfUtf8String(str, size) != -1;
}
int GetCodePointCountOfUtf8String(const char *str, size_t size) {
/* Check pre-conditions. */
AMS_ASSERT(str != nullptr);
AMS_ASSERT(size > 0);
/* Parse codepoints. */
int count = 0;
while (size > 0) {
/* Get and check the current codepoint. */
const u8 *code = reinterpret_cast<const u8 *>(str);
const size_t code_size = GetCodePointByteLength(code[0]);
if (code_size > size || !VerifyCode(code, code_size)) {
return -1;
}
/* Advance. */
str += code_size;
size -= code_size;
/* Increment count. */
++count;
}
return count;
}
}
| 4,203
|
C++
|
.cpp
| 104
| 27.807692
| 98
| 0.439
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,047
|
util_format_string.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/util/util_format_string.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <vapours.hpp>
namespace ams::util {
AMS_PRAGMA_BEGIN_OPTIMIZE("-Os")
namespace {
/* Useful definitions for our VSNPrintf implementation. */
enum FormatSpecifierFlag : u32 {
FormatSpecifierFlag_None = 0,
FormatSpecifierFlag_EmptySign = (1 << 0),
FormatSpecifierFlag_ForceSign = (1 << 1),
FormatSpecifierFlag_Hash = (1 << 2),
FormatSpecifierFlag_LeftJustify = (1 << 3),
FormatSpecifierFlag_ZeroPad = (1 << 4),
FormatSpecifierFlag_Char = (1 << 5),
FormatSpecifierFlag_Short = (1 << 6),
FormatSpecifierFlag_Long = (1 << 7),
FormatSpecifierFlag_LongLong = (1 << 8),
FormatSpecifierFlag_Uppercase = (1 << 9),
FormatSpecifierFlag_HasPrecision = (1 << 10),
};
using FormatSpecifierFlagStorage = std::underlying_type<FormatSpecifierFlag>::type;
constexpr ALWAYS_INLINE bool IsDigit(char c) {
return '0' <= c && c <= '9';
}
constexpr ALWAYS_INLINE u32 ParseU32(const char *&str) {
u32 value = 0;
do {
value = (value * 10) + static_cast<u32>(*(str++) - '0');
} while (IsDigit(*str));
return value;
}
constexpr ALWAYS_INLINE size_t Strnlen(const char *str, size_t max) {
const char *cur = str;
while (*cur && max--) {
cur++;
}
return static_cast<size_t>(cur - str);
}
int TVSNPrintfImpl(char * const dst, const size_t dst_size, const char *format, ::std::va_list vl) {
size_t dst_index = 0;
auto WriteCharacter = [dst, dst_size, &dst_index](char c) ALWAYS_INLINE_LAMBDA {
if (const size_t i = (dst_index++); i < dst_size) {
dst[i] = c;
}
};
/* Loop over every character in the string, looking for format specifiers. */
while (*format) {
if (const char c = *(format++); c != '%') {
WriteCharacter(c);
continue;
}
/* We have to parse a format specifier. */
/* Start by parsing flags. */
FormatSpecifierFlagStorage flags = FormatSpecifierFlag_None;
auto SetFlag = [&flags](FormatSpecifierFlag f) ALWAYS_INLINE_LAMBDA { flags |= f; };
auto ClearFlag = [&flags](FormatSpecifierFlag f) ALWAYS_INLINE_LAMBDA { flags &= ~f; };
auto HasFlag = [&flags](FormatSpecifierFlag f) ALWAYS_INLINE_LAMBDA { return (flags & f) != 0; };
{
bool parsed_flags = false;
while (!parsed_flags) {
switch (*format) {
case ' ': SetFlag(FormatSpecifierFlag_EmptySign); format++; break;
case '+': SetFlag(FormatSpecifierFlag_ForceSign); format++; break;
case '#': SetFlag(FormatSpecifierFlag_Hash); format++; break;
case '-': SetFlag(FormatSpecifierFlag_LeftJustify); format++; break;
case '0': SetFlag(FormatSpecifierFlag_ZeroPad); format++; break;
default:
parsed_flags = true;
break;
}
}
}
/* Next, parse width. */
u32 width = 0;
if (IsDigit(*format)) {
/* Integer width. */
width = ParseU32(format);
} else if (*format == '*') {
/* Dynamic width. */
const int _width = va_arg(vl, int);
if (_width >= 0) {
width = static_cast<u32>(_width);
} else {
SetFlag(FormatSpecifierFlag_LeftJustify);
width = static_cast<u32>(-_width);
}
format++;
}
/* Next, parse precision if present. */
u32 precision = 0;
if (*format == '.') {
SetFlag(FormatSpecifierFlag_HasPrecision);
format++;
if (IsDigit(*format)) {
/* Integer precision. */
precision = ParseU32(format);
} else if (*format == '*') {
/* Dynamic precision. */
const int _precision = va_arg(vl, int);
if (_precision > 0) {
precision = static_cast<u32>(_precision);
}
format++;
}
}
/* Parse length. */
constexpr bool SizeIsLong = sizeof(size_t) == sizeof(long);
constexpr bool PointerIsLong = sizeof(uintptr_t) == sizeof(long);
constexpr bool IntMaxIsLong = sizeof(intmax_t) == sizeof(long);
constexpr bool PtrDiffIsLong = sizeof(ptrdiff_t) == sizeof(long);
switch (*format) {
case 'z':
SetFlag(SizeIsLong ? FormatSpecifierFlag_Long : FormatSpecifierFlag_LongLong);
format++;
break;
case 'j':
SetFlag(IntMaxIsLong ? FormatSpecifierFlag_Long : FormatSpecifierFlag_LongLong);
format++;
break;
case 't':
SetFlag(PtrDiffIsLong ? FormatSpecifierFlag_Long : FormatSpecifierFlag_LongLong);
format++;
break;
case 'h':
SetFlag(FormatSpecifierFlag_Short);
format++;
if (*format == 'h') {
SetFlag(FormatSpecifierFlag_Char);
format++;
}
break;
case 'l':
SetFlag(FormatSpecifierFlag_Long);
format++;
if (*format == 'l') {
SetFlag(FormatSpecifierFlag_LongLong);
format++;
}
break;
default:
break;
}
const char specifier = *(format++);
switch (specifier) {
case 'p':
if constexpr (PointerIsLong) {
SetFlag(FormatSpecifierFlag_Long);
} else {
SetFlag(FormatSpecifierFlag_LongLong);
}
SetFlag(FormatSpecifierFlag_Hash);
[[fallthrough]];
case 'd':
case 'i':
case 'u':
case 'b':
case 'o':
case 'x':
case 'X':
{
/* Determine the base to print with. */
u32 base;
switch (specifier) {
case 'b':
base = 2;
break;
case 'o':
base = 8;
break;
case 'X':
SetFlag(FormatSpecifierFlag_Uppercase);
[[fallthrough]];
case 'p':
case 'x':
base = 16;
break;
default:
base = 10;
ClearFlag(FormatSpecifierFlag_Hash);
break;
}
/* Precision implies no zero-padding. */
if (HasFlag(FormatSpecifierFlag_HasPrecision)) {
ClearFlag(FormatSpecifierFlag_ZeroPad);
}
/* Unsigned types don't get signs. */
const bool is_unsigned = base != 10 || specifier == 'u';
if (is_unsigned) {
ClearFlag(FormatSpecifierFlag_EmptySign);
ClearFlag(FormatSpecifierFlag_ForceSign);
}
auto PrintInteger = [&](bool negative, uintmax_t value) {
constexpr size_t BufferSize = 64; /* Binary digits for 64-bit numbers may use 64 digits. */
char buf[BufferSize];
size_t len = 0;
/* No hash flag for zero. */
if (value == 0) {
ClearFlag(FormatSpecifierFlag_Hash);
}
if (!HasFlag(FormatSpecifierFlag_HasPrecision) || value != 0) {
do {
const char digit = static_cast<char>(value % base);
buf[len++] = (digit < 10) ? ('0' + digit) : ((HasFlag(FormatSpecifierFlag_Uppercase) ? 'A' : 'a') + digit - 10);
value /= base;
} while (value);
}
/* Determine our prefix length. */
size_t prefix_len = 0;
const bool has_sign = negative || HasFlag(FormatSpecifierFlag_ForceSign) || HasFlag(FormatSpecifierFlag_EmptySign);
if (has_sign) {
prefix_len++;
}
if (HasFlag(FormatSpecifierFlag_Hash)) {
prefix_len += (base != 8) ? 2 : 1;
}
/* Determine zero-padding count. */
size_t num_zeroes = (len < precision) ? precision - len : 0;
if (!HasFlag(FormatSpecifierFlag_LeftJustify) && HasFlag(FormatSpecifierFlag_ZeroPad)) {
num_zeroes = (len + prefix_len < width) ? width - len - prefix_len : 0;
}
/* Print out left padding. */
if (!HasFlag(FormatSpecifierFlag_LeftJustify)) {
for (size_t i = len + prefix_len + num_zeroes; i < static_cast<size_t>(width); i++) {
WriteCharacter(' ');
}
}
/* Print out sign. */
if (negative) {
WriteCharacter('-');
} else if (HasFlag(FormatSpecifierFlag_ForceSign)) {
WriteCharacter('+');
} else if (HasFlag(FormatSpecifierFlag_EmptySign)) {
WriteCharacter(' ');
}
/* Print out base prefix. */
if (HasFlag(FormatSpecifierFlag_Hash)) {
WriteCharacter('0');
if (base == 2) {
WriteCharacter('b');
} else if (base == 16) {
WriteCharacter('x');
}
}
/* Print out zeroes. */
for (size_t i = 0; i < num_zeroes; i++) {
WriteCharacter('0');
}
/* Print out digits. */
for (size_t i = 0; i < len; i++) {
WriteCharacter(buf[len - 1 - i]);
}
/* Print out right padding. */
if (HasFlag(FormatSpecifierFlag_LeftJustify)) {
for (size_t i = len + prefix_len + num_zeroes; i < static_cast<size_t>(width); i++) {
WriteCharacter(' ');
}
}
};
/* Output the integer. */
if (is_unsigned) {
uintmax_t n = 0;
if (HasFlag(FormatSpecifierFlag_LongLong)) {
n = static_cast<unsigned long long>(va_arg(vl, unsigned long long));
} else if (HasFlag(FormatSpecifierFlag_Long)) {
n = static_cast<unsigned long>(va_arg(vl, unsigned long));
} else if (HasFlag(FormatSpecifierFlag_Char)) {
n = static_cast<unsigned char>(va_arg(vl, unsigned int));
} else if (HasFlag(FormatSpecifierFlag_Short)) {
n = static_cast<unsigned short>(va_arg(vl, unsigned int));
} else {
n = static_cast<unsigned int>(va_arg(vl, unsigned int));
}
if (specifier == 'p' && n == 0) {
WriteCharacter('(');
WriteCharacter('n');
WriteCharacter('i');
WriteCharacter('l');
WriteCharacter(')');
} else {
PrintInteger(false, n);
}
} else {
intmax_t n = 0;
if (HasFlag(FormatSpecifierFlag_LongLong)) {
n = static_cast<signed long long>(va_arg(vl, signed long long));
} else if (HasFlag(FormatSpecifierFlag_Long)) {
n = static_cast<signed long>(va_arg(vl, signed long));
} else if (HasFlag(FormatSpecifierFlag_Char)) {
n = static_cast<signed char>(va_arg(vl, signed int));
} else if (HasFlag(FormatSpecifierFlag_Short)) {
n = static_cast<signed short>(va_arg(vl, signed int));
} else {
n = static_cast<signed int>(va_arg(vl, signed int));
}
const bool negative = n < 0;
const uintmax_t u = (negative) ? static_cast<uintmax_t>(-n) : static_cast<uintmax_t>(n);
PrintInteger(negative, u);
}
}
break;
case 'c':
{
size_t len = 1;
if (!HasFlag(FormatSpecifierFlag_LeftJustify)) {
while (len++ < width) {
WriteCharacter(' ');
}
}
WriteCharacter(static_cast<char>(va_arg(vl, int)));
if (HasFlag(FormatSpecifierFlag_LeftJustify)) {
while (len++ < width) {
WriteCharacter(' ');
}
}
}
break;
case 's':
{
const char *str = va_arg(vl, char *);
if (str == nullptr) {
str = "(null)";
}
size_t len = Strnlen(str, precision > 0 ? precision : std::numeric_limits<size_t>::max());
if (HasFlag(FormatSpecifierFlag_HasPrecision)) {
len = (len < precision) ? len : precision;
}
if (!HasFlag(FormatSpecifierFlag_LeftJustify)) {
while (len++ < width) {
WriteCharacter(' ');
}
}
while (*str && (!HasFlag(FormatSpecifierFlag_HasPrecision) || (precision--) != 0)) {
WriteCharacter(*(str++));
}
if (HasFlag(FormatSpecifierFlag_LeftJustify)) {
while (len++ < width) {
WriteCharacter(' ');
}
}
}
break;
case '%':
default:
WriteCharacter(specifier);
break;
}
}
/* Ensure null termination. */
WriteCharacter('\0');
if (dst_size > 0) {
dst[dst_size - 1] = '\0';
}
/* Return number of characters that would have been printed sans the null terminator. */
return static_cast<int>(dst_index) - 1;
}
}
AMS_PRAGMA_END_OPTIMIZE()
int TVSNPrintf(char *dst, size_t dst_size, const char *fmt, std::va_list vl) {
return TVSNPrintfImpl(dst, dst_size, fmt, vl);
}
int TSNPrintf(char *dst, size_t dst_size, const char *fmt, ...) {
std::va_list vl;
va_start(vl, fmt);
const int len = TVSNPrintf(dst, dst_size, fmt, vl);
va_end(vl);
return len;
}
int VSNPrintf(char *dst, size_t dst_size, const char *fmt, std::va_list vl) {
/* TODO: floating point support? */
return TVSNPrintfImpl(dst, dst_size, fmt, vl);
}
int SNPrintf(char *dst, size_t dst_size, const char *fmt, ...) {
std::va_list vl;
va_start(vl, fmt);
const int len = VSNPrintf(dst, dst_size, fmt, vl);
va_end(vl);
return len;
}
}
| 20,185
|
C++
|
.cpp
| 393
| 27.071247
| 152
| 0.381184
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,048
|
test_intrusive_red_black_tree.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/test/test_intrusive_red_black_tree.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <vapours.hpp>
/* TODO: Define to enable tests? */
#if 0
namespace ams::test {
template<typename T>
concept IsRedBlackTreeTestNode = std::constructible_from<T, int> && requires (T &t, const T &ct) {
{ ct.GetValue() } -> std::same_as<int>;
{ t.GetNode() } -> std::same_as< util::IntrusiveRedBlackTreeNode &>;
{ ct.GetNode() } -> std::same_as<const util::IntrusiveRedBlackTreeNode &>;
};
template<typename T> requires IsRedBlackTreeTestNode<T>
struct TestComparator {
using RedBlackKeyType = int;
static constexpr int Compare(const T &lhs, const T &rhs) {
if (lhs.GetValue() < rhs.GetValue()) {
return -1;
} else if (lhs.GetValue() > rhs.GetValue()) {
return 1;
} else {
return 0;
}
}
static constexpr int Compare(const int &lhs, const T &rhs) {
if (lhs < rhs.GetValue()) {
return -1;
} else if (lhs > rhs.GetValue()) {
return 1;
} else {
return 0;
}
}
};
class TestBaseNode : public util::IntrusiveRedBlackTreeBaseNode<TestBaseNode> {
private:
const int m_value;
public:
constexpr TestBaseNode(int value) : m_value(value) { /* ... */ }
constexpr int GetValue() const { return m_value; }
constexpr util::IntrusiveRedBlackTreeNode &GetNode() { return static_cast< util::IntrusiveRedBlackTreeNode &>(*this); }
constexpr const util::IntrusiveRedBlackTreeNode &GetNode() const { return static_cast<const util::IntrusiveRedBlackTreeNode &>(*this); }
};
static_assert(IsRedBlackTreeTestNode<TestBaseNode>);
class TestTreeTypes;
class TestMemberNode {
private:
friend class TestTreeTypes;
private:
const int m_value;
util::IntrusiveRedBlackTreeNode m_node;
public:
constexpr TestMemberNode(int value) : m_value(value), m_node() { /* ... */ }
constexpr int GetValue() const { return m_value; }
constexpr util::IntrusiveRedBlackTreeNode &GetNode() { return m_node; }
constexpr const util::IntrusiveRedBlackTreeNode &GetNode() const { return m_node; }
};
static_assert(IsRedBlackTreeTestNode<TestMemberNode>);
class TestTreeTypes {
public:
using BaseTree = util::IntrusiveRedBlackTreeBaseTraits<TestBaseNode>::TreeType<TestComparator<TestBaseNode>>;
using MemberTree = util::IntrusiveRedBlackTreeMemberTraits<&TestMemberNode::m_node>::TreeType<TestComparator<TestMemberNode>>;
};
using TestBaseTree = TestTreeTypes::BaseTree;
using TestMemberTree = TestTreeTypes::MemberTree;
template<typename Tree, typename Node>
consteval bool TestUsage() {
constexpr int Values[] = { -3, 0, 5, 7, 11111111, 924, -100, 68, 70, 69, };
/* Get sorted array. */
std::array<int, util::size(Values)> sorted_values{};
std::copy(std::begin(Values), std::end(Values), std::begin(sorted_values));
std::sort(std::begin(sorted_values), std::end(sorted_values));
/* Create the tree. */
Tree tree{};
AMS_ASSUME(tree.begin() == tree.end());
/* Create a node for each value. */
/* TODO: GCC bug in constant evaluation fails if we use constexpr new/dynamically allocated nodes. */
/* Check if this works in gcc 11. */
std::array<Node, util::size(Values)> nodes = [&]<size_t... Ix>(std::index_sequence<Ix...>) {
return std::array<Node, util::size(Values)> { Node(Values[Ix])... };
}(std::make_index_sequence<util::size(Values)>());
/* Insert each node into the tree. */
for (size_t i = 0; i < util::size(Values); ++i) {
tree.insert(nodes[i]);
if (std::distance(tree.begin(), tree.end()) != static_cast<int>(i + 1)) {
return false;
}
}
/* Verify that the nodes are in sorted order. */
{
size_t i = 0;
for (const auto &node : tree) {
if (node.GetValue() != sorted_values[i++]) {
return false;
}
}
}
/* Verify correctness with begin() */
{
size_t i = 0;
for (auto it = tree.begin(); it != tree.end(); ++it) {
if (it->GetValue() != sorted_values[i++]) {
return false;
}
}
}
/* Verify correctness with cbegin() */
{
size_t i = 0;
for (auto it = tree.cbegin(); it != tree.cend(); ++it) {
if (it->GetValue() != sorted_values[i++]) {
return false;
}
}
}
/* Verify min/max. */
if (tree.front().GetValue() != sorted_values[0]) {
return false;
}
if (tree.back().GetValue() != sorted_values[sorted_values.size() - 1]) {
return false;
}
/* Remove a value. */
tree.erase(tree.iterator_to(nodes[3]));
/* Verify nodes are in sorted order. */
{
size_t i = 0;
for (const auto &node : tree) {
if (node.GetValue() == nodes[3].GetValue()) {
return false;
}
if (node.GetValue() != sorted_values[i++]) {
if (node.GetValue() != sorted_values[i++]) {
return false;
}
}
}
}
/* Add the node back. */
tree.insert(nodes[3]);
/* Verify nodes are in sorted order. */
{
size_t i = 0;
for (const auto &node : tree) {
if (node.GetValue() != sorted_values[i++]) {
return false;
}
}
}
/* Verify that find works. */
for (size_t i = 0; i < util::size(Values); ++i) {
if (tree.find(Node(Values[i])) != tree.iterator_to(nodes[i])) {
return false;
}
if (tree.nfind(Node(sorted_values[i]))->GetValue() != sorted_values[i]) {
return false;
}
if (tree.find_key(Values[i]) != tree.iterator_to(nodes[i])) {
return false;
}
if (tree.nfind_key(sorted_values[i])->GetValue() != sorted_values[i]) {
return false;
}
}
if (tree.find(Node(std::numeric_limits<int>::min())) != tree.end()) {
return false;
}
/* Verify that nfind works. */
for (size_t i = 0; i < util::size(Values) - 1; ++i) {
if (tree.nfind(Node(sorted_values[i] + 1))->GetValue() != sorted_values[i + 1]) {
return false;
}
if (tree.nfind_key(sorted_values[i] + 1)->GetValue() != sorted_values[i + 1]) {
return false;
}
}
return true;
}
static_assert(TestUsage<TestBaseTree, TestBaseNode>());
static_assert(TestUsage<TestMemberTree, TestMemberNode>());
}
#endif
| 7,986
|
C++
|
.cpp
| 195
| 30.317949
| 148
| 0.537271
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,049
|
sdmmc_sd_card.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/sdmmc/sdmmc_sd_card.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if defined(ATMOSPHERE_IS_STRATOSPHERE)
#include <stratosphere.hpp>
#elif defined(ATMOSPHERE_IS_MESOSPHERE)
#include <mesosphere.hpp>
#elif defined(ATMOSPHERE_IS_EXOSPHERE)
#include <exosphere.hpp>
#else
#include <vapours.hpp>
#endif
#include "impl/sdmmc_sd_card_device_accessor.hpp"
#include "impl/sdmmc_port_mmc0.hpp"
#include "impl/sdmmc_port_sd_card0.hpp"
#include "impl/sdmmc_port_gc_asic0.hpp"
namespace ams::sdmmc {
namespace {
impl::SdCardDeviceAccessor *GetSdCardDeviceAccessor(Port port) {
/* Get the accessor. */
impl::SdCardDeviceAccessor *sd_card_device_accessor = nullptr;
switch (port) {
case Port_SdCard0: sd_card_device_accessor = impl::GetSdCardDeviceAccessorOfPortSdCard0(); break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
/* Ensure it's valid */
AMS_ABORT_UNLESS(sd_card_device_accessor != nullptr);
return sd_card_device_accessor;
}
}
void SetSdCardWorkBuffer(Port port, void *buffer, size_t buffer_size) {
return GetSdCardDeviceAccessor(port)->SetSdCardWorkBuffer(buffer, buffer_size);
}
void PutSdCardToSleep(Port port) {
return GetSdCardDeviceAccessor(port)->PutSdCardToSleep();
}
void AwakenSdCard(Port port) {
return GetSdCardDeviceAccessor(port)->AwakenSdCard();
}
Result GetSdCardProtectedAreaCapacity(u32 *out_num_sectors, Port port) {
R_RETURN(GetSdCardDeviceAccessor(port)->GetSdCardProtectedAreaCapacity(out_num_sectors));
}
Result GetSdCardScr(void *dst, size_t dst_size, Port port) {
R_RETURN(GetSdCardDeviceAccessor(port)->GetSdCardScr(dst, dst_size));
}
Result GetSdCardSwitchFunctionStatus(void *dst, size_t dst_size, Port port, SdCardSwitchFunction switch_function) {
R_RETURN(GetSdCardDeviceAccessor(port)->GetSdCardSwitchFunctionStatus(dst, dst_size, switch_function));
}
Result GetSdCardCurrentConsumption(u16 *out_current_consumption, Port port, SpeedMode speed_mode) {
R_RETURN(GetSdCardDeviceAccessor(port)->GetSdCardCurrentConsumption(out_current_consumption, speed_mode));
}
Result GetSdCardSdStatus(void *dst, size_t dst_size, Port port) {
R_RETURN(GetSdCardDeviceAccessor(port)->GetSdCardSdStatus(dst, dst_size));
}
Result CheckSdCardConnection(SpeedMode *out_speed_mode, BusWidth *out_bus_width, Port port) {
R_RETURN(GetSdCardDeviceAccessor(port)->CheckConnection(out_speed_mode, out_bus_width));
}
bool IsSdCardInserted(Port port) {
return GetSdCardDeviceAccessor(port)->IsSdCardInserted();
}
bool IsSdCardRemoved(Port port) {
return GetSdCardDeviceAccessor(port)->IsSdCardRemoved();
}
void RegisterSdCardDetectionEventCallback(Port port, DeviceDetectionEventCallback callback, void *arg) {
return GetSdCardDeviceAccessor(port)->RegisterSdCardDetectionEventCallback(callback, arg);
}
void UnregisterSdCardDetectionEventCallback(Port port) {
return GetSdCardDeviceAccessor(port)->UnregisterSdCardDetectionEventCallback();
}
}
| 3,773
|
C++
|
.cpp
| 82
| 40.341463
| 119
| 0.732698
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,050
|
sdmmc_mmc.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/sdmmc/sdmmc_mmc.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if defined(ATMOSPHERE_IS_STRATOSPHERE)
#include <stratosphere.hpp>
#elif defined(ATMOSPHERE_IS_MESOSPHERE)
#include <mesosphere.hpp>
#elif defined(ATMOSPHERE_IS_EXOSPHERE)
#include <exosphere.hpp>
#else
#include <vapours.hpp>
#endif
#include "impl/sdmmc_mmc_device_accessor.hpp"
#include "impl/sdmmc_port_mmc0.hpp"
#include "impl/sdmmc_port_sd_card0.hpp"
#include "impl/sdmmc_port_gc_asic0.hpp"
namespace ams::sdmmc {
namespace {
impl::MmcDeviceAccessor *GetMmcDeviceAccessor(Port port) {
/* Get the accessor. */
impl::MmcDeviceAccessor *mmc_device_accessor = nullptr;
switch (port) {
case Port_Mmc0: mmc_device_accessor = impl::GetMmcDeviceAccessorOfPortMmc0(); break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
/* Ensure it's valid */
AMS_ABORT_UNLESS(mmc_device_accessor != nullptr);
return mmc_device_accessor;
}
}
void SetMmcWorkBuffer(Port port, void *buffer, size_t buffer_size) {
return GetMmcDeviceAccessor(port)->SetMmcWorkBuffer(buffer, buffer_size);
}
void PutMmcToSleep(Port port) {
return GetMmcDeviceAccessor(port)->PutMmcToSleep();
}
void AwakenMmc(Port port) {
return GetMmcDeviceAccessor(port)->AwakenMmc();
}
Result SelectMmcPartition(Port port, MmcPartition mmc_partition) {
R_RETURN(GetMmcDeviceAccessor(port)->SelectMmcPartition(mmc_partition));
}
Result EraseMmc(Port port) {
R_RETURN(GetMmcDeviceAccessor(port)->EraseMmc());
}
Result GetMmcBootPartitionCapacity(u32 *out_num_sectors, Port port) {
R_RETURN(GetMmcDeviceAccessor(port)->GetMmcBootPartitionCapacity(out_num_sectors));
}
Result GetMmcExtendedCsd(void *out_buffer, size_t buffer_size, Port port) {
R_RETURN(GetMmcDeviceAccessor(port)->GetMmcExtendedCsd(out_buffer, buffer_size));
}
Result CheckMmcConnection(SpeedMode *out_speed_mode, BusWidth *out_bus_width, Port port) {
R_RETURN(GetMmcDeviceAccessor(port)->CheckConnection(out_speed_mode, out_bus_width));
}
}
| 2,760
|
C++
|
.cpp
| 67
| 35.776119
| 103
| 0.711086
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,051
|
sdmmc_common.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/sdmmc/sdmmc_common.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if defined(ATMOSPHERE_IS_STRATOSPHERE)
#include <stratosphere.hpp>
#elif defined(ATMOSPHERE_IS_MESOSPHERE)
#include <mesosphere.hpp>
#elif defined(ATMOSPHERE_IS_EXOSPHERE)
#include <exosphere.hpp>
#else
#include <vapours.hpp>
#endif
#include "impl/sdmmc_i_host_controller.hpp"
#include "impl/sdmmc_i_device_accessor.hpp"
#include "impl/sdmmc_clock_reset_controller.hpp"
#include "impl/sdmmc_port_mmc0.hpp"
#include "impl/sdmmc_port_sd_card0.hpp"
#include "impl/sdmmc_port_gc_asic0.hpp"
namespace ams::sdmmc {
namespace {
impl::IHostController *GetHostController(Port port) {
/* Get the controller. */
impl::IHostController *host_controller = nullptr;
switch (port) {
case Port_Mmc0: host_controller = impl::GetHostControllerOfPortMmc0(); break;
case Port_SdCard0: host_controller = impl::GetHostControllerOfPortSdCard0(); break;
case Port_GcAsic0: host_controller = impl::GetHostControllerOfPortGcAsic0(); break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
/* Ensure it's valid */
AMS_ABORT_UNLESS(host_controller != nullptr);
return host_controller;
}
impl::IDeviceAccessor *GetDeviceAccessor(Port port) {
/* Get the accessor. */
impl::IDeviceAccessor *device_accessor = nullptr;
switch (port) {
case Port_Mmc0: device_accessor = impl::GetDeviceAccessorOfPortMmc0(); break;
case Port_SdCard0: device_accessor = impl::GetDeviceAccessorOfPortSdCard0(); break;
case Port_GcAsic0: device_accessor = impl::GetDeviceAccessorOfPortGcAsic0(); break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
/* Ensure it's valid */
AMS_ABORT_UNLESS(device_accessor != nullptr);
return device_accessor;
}
}
void Initialize(Port port) {
return GetDeviceAccessor(port)->Initialize();
}
void Finalize(Port port) {
return GetDeviceAccessor(port)->Finalize();
}
#if defined(AMS_SDMMC_USE_PCV_CLOCK_RESET_CONTROL)
void SwitchToPcvClockResetControl() {
return impl::ClockResetController::SwitchToPcvControl();
}
#endif
#if defined(AMS_SDMMC_USE_DEVICE_VIRTUAL_ADDRESS)
void RegisterDeviceVirtualAddress(Port port, uintptr_t buffer, size_t buffer_size, ams::dd::DeviceVirtualAddress buffer_device_virtual_address) {
return GetDeviceAccessor(port)->RegisterDeviceVirtualAddress(buffer, buffer_size, buffer_device_virtual_address);
}
void UnregisterDeviceVirtualAddress(Port port, uintptr_t buffer, size_t buffer_size, ams::dd::DeviceVirtualAddress buffer_device_virtual_address) {
return GetDeviceAccessor(port)->UnregisterDeviceVirtualAddress(buffer, buffer_size, buffer_device_virtual_address);
}
#endif
void ChangeCheckTransferInterval(Port port, u32 ms) {
return GetHostController(port)->ChangeCheckTransferInterval(ms);
}
void SetDefaultCheckTransferInterval(Port port) {
return GetHostController(port)->SetDefaultCheckTransferInterval();
}
Result Activate(Port port) {
R_RETURN(GetDeviceAccessor(port)->Activate());
}
void Deactivate(Port port) {
return GetDeviceAccessor(port)->Deactivate();
}
Result Read(void *dst, size_t dst_size, Port port, u32 sector_index, u32 num_sectors) {
R_RETURN(GetDeviceAccessor(port)->ReadWrite(sector_index, num_sectors, dst, dst_size, true));
}
Result Write(Port port, u32 sector_index, u32 num_sectors, const void *src, size_t src_size) {
R_RETURN(GetDeviceAccessor(port)->ReadWrite(sector_index, num_sectors, const_cast<void *>(src), src_size, false));
}
Result CheckConnection(SpeedMode *out_speed_mode, BusWidth *out_bus_width, Port port) {
R_RETURN(GetDeviceAccessor(port)->CheckConnection(out_speed_mode, out_bus_width));
}
Result GetDeviceSpeedMode(SpeedMode *out, Port port) {
R_RETURN(GetDeviceAccessor(port)->GetSpeedMode(out));
}
Result GetDeviceMemoryCapacity(u32 *out_num_sectors, Port port) {
R_RETURN(GetDeviceAccessor(port)->GetMemoryCapacity(out_num_sectors));
}
Result GetDeviceStatus(u32 *out_device_status, Port port) {
R_RETURN(GetDeviceAccessor(port)->GetDeviceStatus(out_device_status));
}
Result GetDeviceCid(void *out, size_t out_size, Port port) {
R_RETURN(GetDeviceAccessor(port)->GetCid(out, out_size));
}
Result GetDeviceCsd(void *out, size_t out_size, Port port) {
R_RETURN(GetDeviceAccessor(port)->GetCsd(out, out_size));
}
void GetAndClearErrorInfo(ErrorInfo *out_error_info, size_t *out_log_size, char *out_log_buffer, size_t log_buffer_size, Port port) {
return GetDeviceAccessor(port)->GetAndClearErrorInfo(out_error_info, out_log_size, out_log_buffer, log_buffer_size);
}
}
| 5,598
|
C++
|
.cpp
| 118
| 40.805085
| 151
| 0.700532
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,052
|
sdmmc_gc_asic.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/sdmmc/sdmmc_gc_asic.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if defined(ATMOSPHERE_IS_STRATOSPHERE)
#include <stratosphere.hpp>
#elif defined(ATMOSPHERE_IS_MESOSPHERE)
#include <mesosphere.hpp>
#elif defined(ATMOSPHERE_IS_EXOSPHERE)
#include <exosphere.hpp>
#else
#include <vapours.hpp>
#endif
#include "impl/sdmmc_gc_asic_device_accessor.hpp"
#include "impl/sdmmc_port_mmc0.hpp"
#include "impl/sdmmc_port_sd_card0.hpp"
#include "impl/sdmmc_port_gc_asic0.hpp"
namespace ams::sdmmc {
namespace {
impl::GcAsicDeviceAccessor *GetGcAsicDeviceAccessor(Port port) {
/* Get the accessor. */
impl::GcAsicDeviceAccessor *gc_asic_device_accessor = nullptr;
switch (port) {
case Port_GcAsic0: gc_asic_device_accessor = impl::GetGcAsicDeviceAccessorOfPortGcAsic0(); break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
/* Ensure it's valid */
AMS_ABORT_UNLESS(gc_asic_device_accessor != nullptr);
return gc_asic_device_accessor;
}
}
void PutGcAsicToSleep(Port port) {
return GetGcAsicDeviceAccessor(port)->PutGcAsicToSleep();
}
Result AwakenGcAsic(Port port) {
R_RETURN(GetGcAsicDeviceAccessor(port)->AwakenGcAsic());
}
Result WriteGcAsicOperation(Port port, const void *op_buf, size_t op_buf_size) {
R_RETURN(GetGcAsicDeviceAccessor(port)->WriteGcAsicOperation(op_buf, op_buf_size));
}
Result FinishGcAsicOperation(Port port) {
R_RETURN(GetGcAsicDeviceAccessor(port)->FinishGcAsicOperation());
}
Result AbortGcAsicOperation(Port port) {
R_RETURN(GetGcAsicDeviceAccessor(port)->AbortGcAsicOperation());
}
Result SleepGcAsic(Port port) {
R_RETURN(GetGcAsicDeviceAccessor(port)->SleepGcAsic());
}
Result UpdateGcAsicKey(Port port) {
R_RETURN(GetGcAsicDeviceAccessor(port)->UpdateGcAsicKey());
}
void SignalGcRemovedEvent(Port port) {
return GetGcAsicDeviceAccessor(port)->SignalGcRemovedEvent();
}
void ClearGcRemovedEvent(Port port) {
return GetGcAsicDeviceAccessor(port)->ClearGcRemovedEvent();
}
}
| 2,749
|
C++
|
.cpp
| 70
| 33.8
| 113
| 0.711336
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,053
|
sdmmc_base_device_accessor.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/sdmmc/impl/sdmmc_base_device_accessor.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if defined(ATMOSPHERE_IS_STRATOSPHERE)
#include <stratosphere.hpp>
#elif defined(ATMOSPHERE_IS_MESOSPHERE)
#include <mesosphere.hpp>
#elif defined(ATMOSPHERE_IS_EXOSPHERE)
#include <exosphere.hpp>
#else
#include <vapours.hpp>
#endif
#include "sdmmc_base_device_accessor.hpp"
namespace ams::sdmmc::impl {
#if defined(AMS_SDMMC_THREAD_SAFE)
#define AMS_SDMMC_LOCK_BASE_DEVICE_MUTEX() std::scoped_lock lk(m_base_device->m_device_mutex)
#else
#define AMS_SDMMC_LOCK_BASE_DEVICE_MUTEX()
#endif
void BaseDevice::GetLegacyCapacityParameters(u8 *out_c_size_mult, u8 *out_read_bl_len) const {
AMS_ABORT_UNLESS(out_c_size_mult != nullptr);
AMS_ABORT_UNLESS(out_read_bl_len != nullptr);
/* Extract C_SIZE_MULT and READ_BL_LEN from the CSD. */
*out_c_size_mult = static_cast<u8>((m_csd[2] >> 7) & 0x7);
*out_read_bl_len = static_cast<u8>((m_csd[4] >> 8) & 0xF);
}
Result BaseDevice::SetLegacyMemoryCapacity() {
/* Get csize from the csd. */
const u32 c_size = ((m_csd[3] >> 6) & 0x3FF) | ((m_csd[4] & 0x3) << 10);
/* Get c_size_mult and read_bl_len. */
u8 c_size_mult, read_bl_len;
this->GetLegacyCapacityParameters(std::addressof(c_size_mult), std::addressof(read_bl_len));
/* Validate the parameters. */
R_UNLESS((read_bl_len + c_size_mult + 2) >= 9, sdmmc::ResultUnexpectedDeviceCsdValue());
/* Set memory capacity. */
m_memory_capacity = (c_size + 1) << ((read_bl_len + c_size_mult + 2) - 9);
m_is_valid_memory_capacity = true;
R_SUCCEED();
}
Result BaseDevice::CheckDeviceStatus(u32 r1_resp) const {
/* Check if there are any errors at all. */
R_SUCCEED_IF((r1_resp & DeviceStatus_ErrorMask) == 0);
/* Check errors individually. */
#define AMS_SDMMC_CHECK_DEVICE_STATUS_ERROR(__ERROR__) R_UNLESS((r1_resp & DeviceStatus_##__ERROR__) == 0, sdmmc::ResultDeviceStatus##__ERROR__())
AMS_SDMMC_CHECK_DEVICE_STATUS_ERROR(ComCrcError);
AMS_SDMMC_CHECK_DEVICE_STATUS_ERROR(DeviceEccFailed);
AMS_SDMMC_CHECK_DEVICE_STATUS_ERROR(CcError);
AMS_SDMMC_CHECK_DEVICE_STATUS_ERROR(Error);
if (this->GetDeviceType() == DeviceType_Mmc) {
AMS_SDMMC_CHECK_DEVICE_STATUS_ERROR(SwitchError);
}
AMS_SDMMC_CHECK_DEVICE_STATUS_ERROR(AddressMisaligned);
AMS_SDMMC_CHECK_DEVICE_STATUS_ERROR(BlockLenError);
AMS_SDMMC_CHECK_DEVICE_STATUS_ERROR(EraseSeqError);
AMS_SDMMC_CHECK_DEVICE_STATUS_ERROR(EraseParam);
AMS_SDMMC_CHECK_DEVICE_STATUS_ERROR(WpViolation);
AMS_SDMMC_CHECK_DEVICE_STATUS_ERROR(LockUnlockFailed);
AMS_SDMMC_CHECK_DEVICE_STATUS_ERROR(CidCsdOverwrite);
AMS_SDMMC_CHECK_DEVICE_STATUS_ERROR(WpEraseSkip);
AMS_SDMMC_CHECK_DEVICE_STATUS_ERROR(WpEraseSkip);
AMS_SDMMC_CHECK_DEVICE_STATUS_ERROR(EraseReset);
AMS_SDMMC_CHECK_DEVICE_STATUS_ERROR(IllegalCommand);
AMS_SDMMC_CHECK_DEVICE_STATUS_ERROR(AddressOutOfRange);
#undef AMS_SDMMC_CHECK_DEVICE_STATUS_ERROR
R_SUCCEED();
}
DeviceState BaseDevice::GetDeviceState(u32 r1_resp) const {
return static_cast<DeviceState>((r1_resp & DeviceStatus_CurrentStateMask) >> DeviceStatus_CurrentStateShift);
}
Result BaseDeviceAccessor::IssueCommandAndCheckR1(u32 *out_response, u32 command_index, u32 command_arg, bool is_busy, DeviceState expected_state, u32 status_ignore_mask) const {
/* Issue the command. */
constexpr ResponseType CommandResponseType = ResponseType_R1;
Command command(command_index, command_arg, CommandResponseType, is_busy);
R_TRY(m_host_controller->IssueCommand(std::addressof(command)));
/* Get the response. */
AMS_ABORT_UNLESS(out_response != nullptr);
m_host_controller->GetLastResponse(out_response, sizeof(u32), CommandResponseType);
/* Mask out the ignored status bits. */
if (status_ignore_mask != 0) {
*out_response &= ~status_ignore_mask;
}
/* Check the r1 response for errors. */
AMS_ABORT_UNLESS(m_base_device != nullptr);
R_TRY(m_base_device->CheckDeviceStatus(*out_response));
/* Check the device state. */
if (expected_state != DeviceState_Unknown) {
R_UNLESS(m_base_device->GetDeviceState(*out_response) == expected_state, sdmmc::ResultUnexpectedDeviceState());
}
R_SUCCEED();
}
Result BaseDeviceAccessor::IssueCommandGoIdleState() const {
/* Issue the command. */
Command command(CommandIndex_GoIdleState, 0, ResponseType_R0, false);
R_RETURN(m_host_controller->IssueCommand(std::addressof(command)));
}
Result BaseDeviceAccessor::IssueCommandAllSendCid(void *dst, size_t dst_size) const {
/* Issue the command. */
constexpr ResponseType CommandResponseType = ResponseType_R2;
Command command(CommandIndex_AllSendCid, 0, CommandResponseType, false);
R_TRY(m_host_controller->IssueCommand(std::addressof(command)));
/* Copy the data out. */
AMS_ABORT_UNLESS(dst != nullptr);
AMS_ABORT_UNLESS(util::IsAligned(reinterpret_cast<uintptr_t>(dst), alignof(u32)));
AMS_ABORT_UNLESS(dst_size >= DeviceCidSize);
m_host_controller->GetLastResponse(static_cast<u32 *>(dst), DeviceCidSize, CommandResponseType);
R_SUCCEED();
}
Result BaseDeviceAccessor::IssueCommandSelectCard() const {
/* Get the command argument. */
AMS_ABORT_UNLESS(m_base_device != nullptr);
const u32 arg = static_cast<u32>(m_base_device->GetRca()) << 16;
/* Issue the command. */
R_RETURN(this->IssueCommandAndCheckR1(CommandIndex_SelectCard, arg, true, DeviceState_Unknown));
}
Result BaseDeviceAccessor::IssueCommandSendCsd(void *dst, size_t dst_size) const {
/* Get the command argument. */
AMS_ABORT_UNLESS(m_base_device != nullptr);
const u32 arg = static_cast<u32>(m_base_device->GetRca()) << 16;
/* Issue the command. */
constexpr ResponseType CommandResponseType = ResponseType_R2;
Command command(CommandIndex_SendCsd, arg, CommandResponseType, false);
R_TRY(m_host_controller->IssueCommand(std::addressof(command)));
/* Copy the data out. */
AMS_ABORT_UNLESS(dst != nullptr);
AMS_ABORT_UNLESS(util::IsAligned(reinterpret_cast<uintptr_t>(dst), alignof(u32)));
AMS_ABORT_UNLESS(dst_size >= DeviceCsdSize);
m_host_controller->GetLastResponse(static_cast<u32 *>(dst), DeviceCsdSize, CommandResponseType);
R_SUCCEED();
}
Result BaseDeviceAccessor::IssueCommandSendStatus(u32 *out_device_status, u32 status_ignore_mask) const {
/* Get the command argument. */
AMS_ABORT_UNLESS(m_base_device != nullptr);
const u32 arg = static_cast<u32>(m_base_device->GetRca()) << 16;
/* Issue the command. */
R_RETURN(this->IssueCommandAndCheckR1(out_device_status, CommandIndex_SendStatus, arg, false, DeviceState_Tran, status_ignore_mask));
}
Result BaseDeviceAccessor::IssueCommandSetBlockLenToSectorSize() const {
/* Issue the command. */
R_RETURN(this->IssueCommandAndCheckR1(CommandIndex_SetBlockLen, SectorSize, false, DeviceState_Tran));
}
Result BaseDeviceAccessor::IssueCommandMultipleBlock(u32 *out_num_transferred_blocks, u32 sector_index, u32 num_sectors, void *buf, bool is_read) const {
/* Get the argument. */
AMS_ABORT_UNLESS(m_base_device != nullptr);
const u32 arg = m_base_device->IsHighCapacity() ? sector_index : sector_index * SectorSize;
/* Get the command index and transfer direction. */
const u32 command_index = is_read ? CommandIndex_ReadMultipleBlock : CommandIndex_WriteMultipleBlock;
const auto xfer_direction = is_read ? TransferDirection_ReadFromDevice : TransferDirection_WriteToDevice;
/* Issue the command. */
constexpr ResponseType CommandResponseType = ResponseType_R1;
Command command(command_index, arg, CommandResponseType, false);
TransferData xfer_data(buf, SectorSize, num_sectors, xfer_direction, true, true);
Result result = m_host_controller->IssueCommand(std::addressof(command), std::addressof(xfer_data), out_num_transferred_blocks);
/* Handle the failure case. */
if (R_FAILED(result)) {
/* Check if we were removed. */
R_TRY(this->CheckRemoved());
/* By default, we'll want to return the result we just got. */
Result result_to_return = result;
/* Stop transmission. */
u32 resp = 0;
result = m_host_controller->IssueStopTransmissionCommand(std::addressof(resp));
if (R_SUCCEEDED(result)) {
result = m_base_device->CheckDeviceStatus(resp & (~DeviceStatus_IllegalCommand));
if (R_FAILED(result)) {
result_to_return = result;
}
}
/* Check if we were removed. */
R_TRY(this->CheckRemoved());
/* Get the device status. */
u32 device_status = 0;
result = this->IssueCommandSendStatus(std::addressof(device_status), DeviceStatus_IllegalCommand);
/* If there's a device status error we don't already have, we prefer to return it. */
if (!sdmmc::ResultDeviceStatusHasError::Includes(result_to_return) && sdmmc::ResultDeviceStatusHasError::Includes(result)) {
result_to_return = result;
}
/* Return the result we chose. */
R_RETURN(result_to_return);
}
/* Get the responses. */
u32 resp, st_resp;
m_host_controller->GetLastResponse(std::addressof(resp), sizeof(resp), CommandResponseType);
m_host_controller->GetLastStopTransmissionResponse(std::addressof(st_resp), sizeof(st_resp));
/* Check the device status. */
R_TRY(m_base_device->CheckDeviceStatus(resp));
/* Decide on what errors to ignore. */
u32 status_ignore_mask = 0;
if (is_read) {
AMS_ABORT_UNLESS(out_num_transferred_blocks != nullptr);
if ((*out_num_transferred_blocks + sector_index) == m_base_device->GetMemoryCapacity()) {
status_ignore_mask = DeviceStatus_AddressOutOfRange;
}
}
/* Check the device status. */
R_TRY(m_base_device->CheckDeviceStatus(st_resp & ~status_ignore_mask));
R_SUCCEED();
}
Result BaseDeviceAccessor::ReadWriteSingle(u32 *out_num_transferred_blocks, u32 sector_index, u32 num_sectors, void *buf, bool is_read) const {
/* Issue the read/write command. */
AMS_ABORT_UNLESS(out_num_transferred_blocks != nullptr);
R_TRY(this->IssueCommandMultipleBlock(out_num_transferred_blocks, sector_index, num_sectors, buf, is_read));
/* Decide on what errors to ignore. */
u32 status_ignore_mask = 0;
if (is_read) {
AMS_ABORT_UNLESS(m_base_device != nullptr);
if ((*out_num_transferred_blocks + sector_index) == m_base_device->GetMemoryCapacity()) {
status_ignore_mask = DeviceStatus_AddressOutOfRange;
}
}
/* Get and check the status. */
u32 device_status;
R_TRY(this->IssueCommandSendStatus(std::addressof(device_status), status_ignore_mask));
R_SUCCEED();
}
Result BaseDeviceAccessor::ReadWriteMultiple(u32 sector_index, u32 num_sectors, u32 sector_index_alignment, void *buf, size_t buf_size, bool is_read) {
/* Verify that we can send the command. */
AMS_ABORT_UNLESS(m_base_device != nullptr);
/* If we want to read zero sectors, there's no work for us to do. */
R_SUCCEED_IF(num_sectors == 0);
/* Check that the buffer is big enough for the sectors we're reading. */
AMS_ABORT_UNLESS((buf_size / SectorSize) >= num_sectors);
/* Read sectors repeatedly until we've read all the ones we want. */
u32 cur_sector_index = sector_index;
u32 remaining_sectors = num_sectors;
u8 *cur_buf = static_cast<u8 *>(buf);
while (remaining_sectors > 0) {
/* Determine how many sectors we can read in this iteration. */
u32 cur_sectors = remaining_sectors;
if (sector_index_alignment > 0) {
AMS_ABORT_UNLESS((cur_sector_index % sector_index_alignment) == 0);
const u32 max_sectors = m_host_controller->GetMaxTransferNumBlocks();
if (remaining_sectors > max_sectors) {
cur_sectors = max_sectors - (max_sectors % sector_index_alignment);
}
}
/* Try to perform the read/write. */
u32 num_transferred_blocks = 0;
Result result = this->ReadWriteSingle(std::addressof(num_transferred_blocks), cur_sector_index, cur_sectors, cur_buf, is_read);
if (R_FAILED(result)) {
/* Check if we were removed. */
R_TRY(this->CheckRemoved());
/* Log that we failed to read/write. */
this->PushErrorLog(false, "%s %X %X:%X", is_read ? "R" : "W", cur_sector_index, cur_sectors, result.GetValue());
/* Retry the read/write. */
num_transferred_blocks = 0;
result = this->ReadWriteSingle(std::addressof(num_transferred_blocks), cur_sector_index, cur_sectors, cur_buf, is_read);
if (R_FAILED(result)) {
/* Check if we were removed. */
R_TRY(this->CheckRemoved());
/* Log that we failed to read/write. */
this->PushErrorLog(false, "%s %X %X:%X", is_read ? "R" : "W", cur_sector_index, cur_sectors, result.GetValue());
/* Re-startup the connection, to see if that helps. */
R_TRY(this->ReStartup());
/* Retry the read/write a third time. */
num_transferred_blocks = 0;
result = this->ReadWriteSingle(std::addressof(num_transferred_blocks), cur_sector_index, cur_sectors, cur_buf, is_read);
if (R_FAILED(result)) {
/* Log that we failed after a re-startup. */
this->PushErrorLog(true, "%s %X %X:%X", is_read ? "R" : "W", cur_sector_index, cur_sectors, result.GetValue());
R_RETURN(result);
}
/* Log that we succeeded after a retry. */
this->PushErrorLog(true, "%s %X %X:0", is_read ? "R" : "W", cur_sector_index, cur_sectors);
/* Increment the number of error corrections we've done. */
++m_num_read_write_error_corrections;
}
}
/* Update our tracking variables. */
AMS_ABORT_UNLESS(remaining_sectors >= num_transferred_blocks);
remaining_sectors -= num_transferred_blocks;
cur_sector_index += num_transferred_blocks;
cur_buf += num_transferred_blocks * SectorSize;
}
R_SUCCEED();
}
#if defined(AMS_SDMMC_USE_DEVICE_VIRTUAL_ADDRESS)
void BaseDeviceAccessor::RegisterDeviceVirtualAddress(uintptr_t buffer, size_t buffer_size, ams::dd::DeviceVirtualAddress buffer_device_virtual_address) {
/* Lock exclusive access of the base device. */
AMS_ABORT_UNLESS(m_base_device != nullptr);
AMS_SDMMC_LOCK_BASE_DEVICE_MUTEX();
/* Register the address. */
return m_host_controller->RegisterDeviceVirtualAddress(buffer, buffer_size, buffer_device_virtual_address);
}
void BaseDeviceAccessor::UnregisterDeviceVirtualAddress(uintptr_t buffer, size_t buffer_size, ams::dd::DeviceVirtualAddress buffer_device_virtual_address) {
/* Lock exclusive access of the base device. */
AMS_ABORT_UNLESS(m_base_device != nullptr);
AMS_SDMMC_LOCK_BASE_DEVICE_MUTEX();
/* Register the address. */
return m_host_controller->UnregisterDeviceVirtualAddress(buffer, buffer_size, buffer_device_virtual_address);
}
#endif
Result BaseDeviceAccessor::Activate() {
/* Lock exclusive access of the base device. */
AMS_ABORT_UNLESS(m_base_device != nullptr);
AMS_SDMMC_LOCK_BASE_DEVICE_MUTEX();
/* Check that the device is awake. */
R_UNLESS(m_base_device->IsAwake(), sdmmc::ResultNotAwakened());
/* If the device is already active, we don't need to do anything. */
R_SUCCEED_IF(m_base_device->IsActive());
/* Activate the base device. */
auto activate_guard = SCOPE_GUARD { ++m_num_activation_failures; };
R_TRY(this->OnActivate());
/* We successfully activated the device. */
activate_guard.Cancel();
m_base_device->SetActive();
R_SUCCEED();
}
void BaseDeviceAccessor::Deactivate() {
/* Lock exclusive access of the base device. */
AMS_ABORT_UNLESS(m_base_device != nullptr);
AMS_SDMMC_LOCK_BASE_DEVICE_MUTEX();
/* Deactivate the base device. */
if (m_base_device->IsActive()) {
m_host_controller->Shutdown();
m_base_device->Deactivate();
}
}
Result BaseDeviceAccessor::ReadWrite(u32 sector_index, u32 num_sectors, void *buffer, size_t buffer_size, bool is_read) {
/* Lock exclusive access of the base device. */
AMS_ABORT_UNLESS(m_base_device != nullptr);
AMS_SDMMC_LOCK_BASE_DEVICE_MUTEX();
/* Check that the device is accessible. */
R_TRY(m_base_device->CheckAccessible());
/* Perform the read/write. */
auto rw_guard = SCOPE_GUARD { ++m_num_read_write_failures; };
R_TRY(this->OnReadWrite(sector_index, num_sectors, buffer, buffer_size, is_read));
/* We successfully performed the read/write. */
rw_guard.Cancel();
R_SUCCEED();
}
Result BaseDeviceAccessor::CheckConnection(SpeedMode *out_speed_mode, BusWidth *out_bus_width) {
/* Lock exclusive access of the base device. */
AMS_ABORT_UNLESS(m_base_device != nullptr);
AMS_SDMMC_LOCK_BASE_DEVICE_MUTEX();
/* Check that the device is accessible. */
R_TRY(m_base_device->CheckAccessible());
/* Get the current speed mode/bus width. */
*out_speed_mode = m_host_controller->GetSpeedMode();
*out_bus_width = m_host_controller->GetBusWidth();
/* Verify that we can get the status. */
R_TRY(m_host_controller->GetInternalStatus());
R_SUCCEED();
}
Result BaseDeviceAccessor::GetMemoryCapacity(u32 *out_sectors) const {
/* Lock exclusive access of the base device. */
AMS_ABORT_UNLESS(m_base_device != nullptr);
AMS_SDMMC_LOCK_BASE_DEVICE_MUTEX();
/* Check that the device is accessible. */
R_TRY(m_base_device->CheckAccessible());
/* Get the capacity. */
AMS_ABORT_UNLESS(out_sectors != nullptr);
*out_sectors = m_base_device->GetMemoryCapacity();
R_SUCCEED();
}
Result BaseDeviceAccessor::GetDeviceStatus(u32 *out) const {
/* Lock exclusive access of the base device. */
AMS_ABORT_UNLESS(m_base_device != nullptr);
AMS_SDMMC_LOCK_BASE_DEVICE_MUTEX();
/* Check that the device is accessible. */
R_TRY(m_base_device->CheckAccessible());
/* Get the status. */
R_TRY(this->IssueCommandSendStatus(out, 0));
R_SUCCEED();
}
Result BaseDeviceAccessor::GetOcr(u32 *out) const {
/* Lock exclusive access of the base device. */
AMS_ABORT_UNLESS(m_base_device != nullptr);
AMS_SDMMC_LOCK_BASE_DEVICE_MUTEX();
/* Check that the device is accessible. */
R_TRY(m_base_device->CheckAccessible());
/* Get the ocr. */
AMS_ABORT_UNLESS(out != nullptr);
*out = m_base_device->GetOcr();
R_SUCCEED();
}
Result BaseDeviceAccessor::GetRca(u16 *out) const {
/* Lock exclusive access of the base device. */
AMS_ABORT_UNLESS(m_base_device != nullptr);
AMS_SDMMC_LOCK_BASE_DEVICE_MUTEX();
/* Check that the device is accessible. */
R_TRY(m_base_device->CheckAccessible());
/* Get the rca. */
AMS_ABORT_UNLESS(out != nullptr);
*out = m_base_device->GetRca();
R_SUCCEED();
}
Result BaseDeviceAccessor::GetCid(void *out, size_t size) const {
/* Lock exclusive access of the base device. */
AMS_ABORT_UNLESS(m_base_device != nullptr);
AMS_SDMMC_LOCK_BASE_DEVICE_MUTEX();
/* Check that the device is accessible. */
R_TRY(m_base_device->CheckAccessible());
/* Get the cid. */
m_base_device->GetCid(out, size);
R_SUCCEED();
}
Result BaseDeviceAccessor::GetCsd(void *out, size_t size) const {
/* Lock exclusive access of the base device. */
AMS_ABORT_UNLESS(m_base_device != nullptr);
AMS_SDMMC_LOCK_BASE_DEVICE_MUTEX();
/* Check that the device is accessible. */
R_TRY(m_base_device->CheckAccessible());
/* Get the csd. */
m_base_device->GetCsd(out, size);
R_SUCCEED();
}
void BaseDeviceAccessor::GetAndClearErrorInfo(ErrorInfo *out_error_info, size_t *out_log_size, char *out_log_buffer, size_t log_buffer_size) {
/* Lock exclusive access of the base device. */
AMS_ABORT_UNLESS(m_base_device != nullptr);
AMS_SDMMC_LOCK_BASE_DEVICE_MUTEX();
/* Set the output error info. */
AMS_ABORT_UNLESS(out_error_info != nullptr);
out_error_info->num_activation_failures = m_num_activation_failures;
out_error_info->num_activation_error_corrections = m_num_activation_error_corrections;
out_error_info->num_read_write_failures = m_num_read_write_failures;
out_error_info->num_read_write_error_corrections = m_num_read_write_error_corrections;
this->ClearErrorInfo();
/* Check if we should write logs. */
if (out_log_size == nullptr) {
return;
}
/* Check if we can write logs. */
if (out_log_buffer == nullptr || log_buffer_size == 0) {
*out_log_size = 0;
return;
}
/* Get and clear our logs. */
#if defined(AMS_SDMMC_USE_LOGGER)
{
if (m_error_logger.HasLog()) {
this->PushErrorTimeStamp();
*out_log_size = m_error_logger.GetAndClearLogs(out_log_buffer, log_buffer_size);
} else {
*out_log_size = 0;
}
}
#else
{
*out_log_size = 0;
}
#endif
}
}
| 23,732
|
C++
|
.cpp
| 455
| 42.454945
| 182
| 0.627316
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,054
|
sdmmc_clock_reset_controller.reg.board.nintendo_nx.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/sdmmc/impl/sdmmc_clock_reset_controller.reg.board.nintendo_nx.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if defined(ATMOSPHERE_IS_STRATOSPHERE)
#include <stratosphere.hpp>
#elif defined(ATMOSPHERE_IS_MESOSPHERE)
#include <mesosphere.hpp>
#elif defined(ATMOSPHERE_IS_EXOSPHERE)
#include <exosphere.hpp>
#else
#include <vapours.hpp>
#endif
#include "sdmmc_clock_reset_controller.reg.board.nintendo_nx.hpp"
#include "sdmmc_timer.hpp"
namespace ams::sdmmc::impl::ClockResetController::reg {
namespace {
#if defined(AMS_SDMMC_THREAD_SAFE)
constinit os::SdkMutex g_init_mutex;
#define AMS_SDMMC_LOCK_INIT_MUTEX() std::scoped_lock lk(g_init_mutex)
#else
#define AMS_SDMMC_LOCK_INIT_MUTEX()
#endif
constinit bool g_is_initialized = false;
struct ModuleInfo {
u32 target_frequency_khz;
u32 actual_frequency_khz;
};
constinit ModuleInfo g_module_infos[Module_Count] = {};
constexpr inline dd::PhysicalAddress ClockResetControllerRegistersPhysicalAddress = UINT64_C(0x60006000);
constexpr inline size_t ClockResetControllerRegistersSize = 4_KB;
constinit uintptr_t g_clkrst_registers_address = 0;
[[maybe_unused]] void InitializePllc4() {
/* Check that we have registers we can write to. */
AMS_ABORT_UNLESS(g_clkrst_registers_address != 0);
/* Check if PLLC4_BASE has the expected value; if it does, we have nothing to do. */
constexpr u32 ExpectedPllc4Base = 0x58006804;
if (ams::reg::Read(g_clkrst_registers_address + CLK_RST_CONTROLLER_PLLC4_BASE) == ExpectedPllc4Base) {
return;
}
/* Disable PLLC4_ENABLE, if it's currently set. */
if (ams::reg::HasValue(g_clkrst_registers_address + CLK_RST_CONTROLLER_PLLC4_BASE, CLK_RST_REG_BITS_ENUM(PLLC4_BASE_PLLC4_ENABLE, ENABLE))) {
ams::reg::ReadWrite(g_clkrst_registers_address + CLK_RST_CONTROLLER_PLLC4_BASE, CLK_RST_REG_BITS_ENUM(PLLC4_BASE_PLLC4_ENABLE, DISABLE));
}
/* Operate on the register with PLLC4_ENABLE cleared. */
{
/* Clear IDDQ, read to be sure it takes, wait 5 us. */
ams::reg::ReadWrite(g_clkrst_registers_address + CLK_RST_CONTROLLER_PLLC4_BASE, CLK_RST_REG_BITS_ENUM(PLLC4_BASE_PLLC4_IDDQ, OFF));
ams::reg::Read(g_clkrst_registers_address + CLK_RST_CONTROLLER_PLLC4_BASE);
WaitMicroSeconds(5);
/* Write the expected value sans IDDQ/PLLC4_ENABLE. */
constexpr u32 ExpectedPllc4BaseMask = ~ams::reg::EncodeMask(CLK_RST_REG_BITS_MASK(PLLC4_BASE_PLLC4_ENABLE),
CLK_RST_REG_BITS_MASK(PLLC4_BASE_PLLC4_IDDQ));
ams::reg::Write(g_clkrst_registers_address + CLK_RST_CONTROLLER_PLLC4_BASE, ExpectedPllc4Base & ExpectedPllc4BaseMask);
}
/* Write PLLC4_ENABLE, and read to be sure our configuration takes. */
ams::reg::ReadWrite(g_clkrst_registers_address + CLK_RST_CONTROLLER_PLLC4_BASE, CLK_RST_REG_BITS_ENUM(PLLC4_BASE_PLLC4_ENABLE, ENABLE));
ams::reg::Read(g_clkrst_registers_address + CLK_RST_CONTROLLER_PLLC4_BASE);
/* Wait up to 1s for changes to take. */
{
ManualTimer timer(1000);
while (true) {
/* Check if we're done. */
if (!ams::reg::HasValue(g_clkrst_registers_address + CLK_RST_CONTROLLER_PLLC4_BASE, CLK_RST_REG_BITS_ENUM(PLLC4_BASE_PLLC4_LOCK, NOT_LOCK))) {
break;
}
/* Check that we haven't timed out. */
AMS_ABORT_UNLESS(timer.Update());
}
}
}
void InitializeLegacyTmClk() {
/* Check that we have registers we can write to. */
AMS_ABORT_UNLESS(g_clkrst_registers_address != 0);
/* Configure the legacy tm clock as 12MHz. */
ams::reg::Write(g_clkrst_registers_address + CLK_RST_CONTROLLER_CLK_SOURCE_SDMMC_LEGACY_TM, CLK_RST_REG_BITS_ENUM (CLK_SOURCE_LEGACY_TM_CLK_SRC, PLLP_OUT0),
CLK_RST_REG_BITS_VALUE(CLK_SOURCE_LEGACY_TM_CLK_DIVISOR, 66));
/* Enable clock to the legacy tm. */
ams::reg::Write(g_clkrst_registers_address + CLK_RST_CONTROLLER_CLK_ENB_Y_SET, CLK_RST_REG_BITS_ENUM(CLK_ENB_Y_CLK_ENB_LEGACY_TM, ENABLE));
}
bool IsResetReleased(Module module) {
/* Check that we have registers we can write to. */
AMS_ABORT_UNLESS(g_clkrst_registers_address != 0);
/* Get the reset bit from RST_DEVICES_* */
switch (module) {
case Module_Sdmmc1: return ams::reg::HasValue(g_clkrst_registers_address + CLK_RST_CONTROLLER_RST_DEVICES_L, CLK_RST_REG_BITS_ENUM(RST_DEVICES_L_SWR_SDMMC1_RST, DISABLE));
case Module_Sdmmc2: return ams::reg::HasValue(g_clkrst_registers_address + CLK_RST_CONTROLLER_RST_DEVICES_L, CLK_RST_REG_BITS_ENUM(RST_DEVICES_L_SWR_SDMMC2_RST, DISABLE));
case Module_Sdmmc3: return ams::reg::HasValue(g_clkrst_registers_address + CLK_RST_CONTROLLER_RST_DEVICES_U, CLK_RST_REG_BITS_ENUM(RST_DEVICES_U_SWR_SDMMC3_RST, DISABLE));
case Module_Sdmmc4: return ams::reg::HasValue(g_clkrst_registers_address + CLK_RST_CONTROLLER_RST_DEVICES_L, CLK_RST_REG_BITS_ENUM(RST_DEVICES_L_SWR_SDMMC4_RST, DISABLE));
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
void SetReset(Module module) {
/* Check that we have registers we can write to. */
AMS_ABORT_UNLESS(g_clkrst_registers_address != 0);
/* Set reset in RST_DEV_*_SET */
switch (module) {
case Module_Sdmmc1: return ams::reg::Write(g_clkrst_registers_address + CLK_RST_CONTROLLER_RST_DEV_L_SET, CLK_RST_REG_BITS_ENUM(RST_DEV_L_SDMMC1_RST, ENABLE));
case Module_Sdmmc2: return ams::reg::Write(g_clkrst_registers_address + CLK_RST_CONTROLLER_RST_DEV_L_SET, CLK_RST_REG_BITS_ENUM(RST_DEV_L_SDMMC2_RST, ENABLE));
case Module_Sdmmc3: return ams::reg::Write(g_clkrst_registers_address + CLK_RST_CONTROLLER_RST_DEV_U_SET, CLK_RST_REG_BITS_ENUM(RST_DEV_U_SDMMC3_RST, ENABLE));
case Module_Sdmmc4: return ams::reg::Write(g_clkrst_registers_address + CLK_RST_CONTROLLER_RST_DEV_L_SET, CLK_RST_REG_BITS_ENUM(RST_DEV_L_SDMMC4_RST, ENABLE));
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
void ClearReset(Module module) {
/* Check that we have registers we can write to. */
AMS_ABORT_UNLESS(g_clkrst_registers_address != 0);
/* Set reset in RST_DEV_*_CLR */
switch (module) {
case Module_Sdmmc1: return ams::reg::Write(g_clkrst_registers_address + CLK_RST_CONTROLLER_RST_DEV_L_CLR, CLK_RST_REG_BITS_ENUM(RST_DEV_L_SDMMC1_RST, ENABLE));
case Module_Sdmmc2: return ams::reg::Write(g_clkrst_registers_address + CLK_RST_CONTROLLER_RST_DEV_L_CLR, CLK_RST_REG_BITS_ENUM(RST_DEV_L_SDMMC2_RST, ENABLE));
case Module_Sdmmc3: return ams::reg::Write(g_clkrst_registers_address + CLK_RST_CONTROLLER_RST_DEV_U_CLR, CLK_RST_REG_BITS_ENUM(RST_DEV_U_SDMMC3_RST, ENABLE));
case Module_Sdmmc4: return ams::reg::Write(g_clkrst_registers_address + CLK_RST_CONTROLLER_RST_DEV_L_CLR, CLK_RST_REG_BITS_ENUM(RST_DEV_L_SDMMC4_RST, ENABLE));
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
bool IsClockEnabled(Module module) {
/* Check that we have registers we can write to. */
AMS_ABORT_UNLESS(g_clkrst_registers_address != 0);
/* Get the enable bit from CLK_OUT_ENB_* */
switch (module) {
case Module_Sdmmc1: return ams::reg::HasValue(g_clkrst_registers_address + CLK_RST_CONTROLLER_CLK_OUT_ENB_L, CLK_RST_REG_BITS_ENUM(CLK_OUT_ENB_L_CLK_ENB_SDMMC1, ENABLE));
case Module_Sdmmc2: return ams::reg::HasValue(g_clkrst_registers_address + CLK_RST_CONTROLLER_CLK_OUT_ENB_L, CLK_RST_REG_BITS_ENUM(CLK_OUT_ENB_L_CLK_ENB_SDMMC2, ENABLE));
case Module_Sdmmc3: return ams::reg::HasValue(g_clkrst_registers_address + CLK_RST_CONTROLLER_CLK_OUT_ENB_U, CLK_RST_REG_BITS_ENUM(CLK_OUT_ENB_U_CLK_ENB_SDMMC3, ENABLE));
case Module_Sdmmc4: return ams::reg::HasValue(g_clkrst_registers_address + CLK_RST_CONTROLLER_CLK_OUT_ENB_L, CLK_RST_REG_BITS_ENUM(CLK_OUT_ENB_L_CLK_ENB_SDMMC4, ENABLE));
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
void SetClockEnable(Module module) {
/* Check that we have registers we can write to. */
AMS_ABORT_UNLESS(g_clkrst_registers_address != 0);
/* Set clock enable bit in CLK_ENB_*_SET */
switch (module) {
case Module_Sdmmc1: return ams::reg::Write(g_clkrst_registers_address + CLK_RST_CONTROLLER_CLK_ENB_L_SET, CLK_RST_REG_BITS_ENUM(CLK_ENB_L_CLK_ENB_SDMMC1, ENABLE));
case Module_Sdmmc2: return ams::reg::Write(g_clkrst_registers_address + CLK_RST_CONTROLLER_CLK_ENB_L_SET, CLK_RST_REG_BITS_ENUM(CLK_ENB_L_CLK_ENB_SDMMC2, ENABLE));
case Module_Sdmmc3: return ams::reg::Write(g_clkrst_registers_address + CLK_RST_CONTROLLER_CLK_ENB_U_SET, CLK_RST_REG_BITS_ENUM(CLK_ENB_U_CLK_ENB_SDMMC3, ENABLE));
case Module_Sdmmc4: return ams::reg::Write(g_clkrst_registers_address + CLK_RST_CONTROLLER_CLK_ENB_L_SET, CLK_RST_REG_BITS_ENUM(CLK_ENB_L_CLK_ENB_SDMMC4, ENABLE));
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
void ClearClockEnable(Module module) {
/* Check that we have registers we can write to. */
AMS_ABORT_UNLESS(g_clkrst_registers_address != 0);
/* Set clock enable bit in CLK_ENB_*_CLR */
switch (module) {
case Module_Sdmmc1: return ams::reg::Write(g_clkrst_registers_address + CLK_RST_CONTROLLER_CLK_ENB_L_CLR, CLK_RST_REG_BITS_ENUM(CLK_ENB_L_CLK_ENB_SDMMC1, ENABLE));
case Module_Sdmmc2: return ams::reg::Write(g_clkrst_registers_address + CLK_RST_CONTROLLER_CLK_ENB_L_CLR, CLK_RST_REG_BITS_ENUM(CLK_ENB_L_CLK_ENB_SDMMC2, ENABLE));
case Module_Sdmmc3: return ams::reg::Write(g_clkrst_registers_address + CLK_RST_CONTROLLER_CLK_ENB_U_CLR, CLK_RST_REG_BITS_ENUM(CLK_ENB_U_CLK_ENB_SDMMC3, ENABLE));
case Module_Sdmmc4: return ams::reg::Write(g_clkrst_registers_address + CLK_RST_CONTROLLER_CLK_ENB_L_CLR, CLK_RST_REG_BITS_ENUM(CLK_ENB_L_CLK_ENB_SDMMC4, ENABLE));
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
void SetClockSourceSdmmc(u32 *out_actual_frequency_khz, Module module, u32 target_frequency_khz) {
/* Check that we can write to output. */
AMS_ABORT_UNLESS(out_actual_frequency_khz != nullptr);
/* Determine frequency/divisor. */
u32 clk_m = ams::reg::Encode(CLK_RST_REG_BITS_ENUM(CLK_SOURCE_SDMMCX_SDMMCX_CLK_SRC, PLLP_OUT0));
u8 n;
switch (target_frequency_khz) {
case 25'000:
*out_actual_frequency_khz = 24'728;
n = 31;
break;
case 26'000:
*out_actual_frequency_khz = 25'500;
n = 30;
break;
case 40'800:
*out_actual_frequency_khz = 40'800;
n = 18;
break;
case 50'000:
*out_actual_frequency_khz = 48'000;
n = 15;
break;
case 52'000:
*out_actual_frequency_khz = 51'000;
n = 14;
break;
case 100'000:
#if defined(AMS_SDMMC_SET_PLLC4_BASE)
*out_actual_frequency_khz = 99'840;
n = 2;
clk_m = ams::reg::Encode(CLK_RST_REG_BITS_ENUM(CLK_SOURCE_SDMMCX_SDMMCX_CLK_SRC, PLLC4_OUT2));
#else
*out_actual_frequency_khz = 90'667;
n = 7;
#endif
break;
case 200'000:
#if defined(AMS_SDMMC_SET_PLLC4_BASE)
*out_actual_frequency_khz = 199'680;
n = 0;
if (module == Module_Sdmmc2 || module == Module_Sdmmc4) {
clk_m = ams::reg::Encode(CLK_RST_REG_BITS_ENUM(CLK_SOURCE_SDMMC24_SDMMC24_CLK_SRC, PLLC4_OUT2_LJ));
} else {
clk_m = ams::reg::Encode(CLK_RST_REG_BITS_ENUM(CLK_SOURCE_SDMMCX_SDMMCX_CLK_SRC, PLLC4_OUT2));
}
#else
*out_actual_frequency_khz = 163'200;
n = 3;
#endif
break;
case 208'000:
*out_actual_frequency_khz = 204'000;
n = 2;
break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
/* Set frequencies in module info. */
g_module_infos[module].target_frequency_khz = target_frequency_khz;
g_module_infos[module].actual_frequency_khz = *out_actual_frequency_khz;
/* Check that we have registers we can write to. */
AMS_ABORT_UNLESS(g_clkrst_registers_address != 0);
/* Update the clock source. */
switch (module) {
case Module_Sdmmc1: ams::reg::Write(g_clkrst_registers_address + CLK_RST_CONTROLLER_CLK_SOURCE_SDMMC1, clk_m | static_cast<u32>(n)); break;
case Module_Sdmmc2: ams::reg::Write(g_clkrst_registers_address + CLK_RST_CONTROLLER_CLK_SOURCE_SDMMC2, clk_m | static_cast<u32>(n)); break;
case Module_Sdmmc3: ams::reg::Write(g_clkrst_registers_address + CLK_RST_CONTROLLER_CLK_SOURCE_SDMMC3, clk_m | static_cast<u32>(n)); break;
case Module_Sdmmc4: ams::reg::Write(g_clkrst_registers_address + CLK_RST_CONTROLLER_CLK_SOURCE_SDMMC4, clk_m | static_cast<u32>(n)); break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
void EnsureControl(Module module) {
/* Read from RST_DEVICES_* to be sure previous configuration takes. */
switch (module) {
case Module_Sdmmc1: ams::reg::Read(g_clkrst_registers_address + CLK_RST_CONTROLLER_RST_DEVICES_L); break;
case Module_Sdmmc2: ams::reg::Read(g_clkrst_registers_address + CLK_RST_CONTROLLER_RST_DEVICES_L); break;
case Module_Sdmmc3: ams::reg::Read(g_clkrst_registers_address + CLK_RST_CONTROLLER_RST_DEVICES_U); break;
case Module_Sdmmc4: ams::reg::Read(g_clkrst_registers_address + CLK_RST_CONTROLLER_RST_DEVICES_L); break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
}
void Initialize(Module module) {
/* Initialization isn't module specific. */
AMS_UNUSED(module);
/* Acquire exclusive access to the initialization lock. */
AMS_SDMMC_LOCK_INIT_MUTEX();
/* If we've already initialized, we don't need to do anything. */
if (g_is_initialized) {
return;
}
/* Clear module infos. */
std::memset(g_module_infos, 0, sizeof(g_module_infos));
/* Get the registers address. */
g_clkrst_registers_address = dd::QueryIoMapping(ClockResetControllerRegistersPhysicalAddress, ClockResetControllerRegistersSize);
AMS_ABORT_UNLESS(g_clkrst_registers_address != 0);
/* Perform register initialization. */
#if defined(AMS_SDMMC_SET_PLLC4_BASE)
InitializePllc4();
#endif
InitializeLegacyTmClk();
/* Mark that we've initialized. */
g_is_initialized = true;
}
void Finalize(Module module) {
/* Nothing is needed for finalization. */
AMS_UNUSED(module);
}
bool IsAvailable(Module module) {
return IsResetReleased(module) && IsClockEnabled(module);
}
void SetClockFrequencyKHz(u32 *out_actual_frequency_khz, Module module, u32 target_frequency_khz) {
/* If we're not changing the clock frequency, we don't need to do anything. */
if (target_frequency_khz == g_module_infos[module].target_frequency_khz) {
*out_actual_frequency_khz = g_module_infos[module].actual_frequency_khz;
return;
}
/* Temporarily disable clock. */
const bool clock_enabled = IsClockEnabled(module);
if (clock_enabled) {
ClearClockEnable(module);
}
/* Set the clock source. */
SetClockSourceSdmmc(out_actual_frequency_khz, module, target_frequency_khz);
/* Re-enable clock, if we should. */
if (clock_enabled) {
SetClockEnable(module);
}
/* Ensure that our configuration takes. */
EnsureControl(module);
}
void AssertReset(Module module) {
/* Set reset and disable clock. */
SetReset(module);
ClearClockEnable(module);
/* Ensure that our configuration takes. */
EnsureControl(module);
}
void ReleaseReset(Module module, u32 target_frequency_khz) {
/* Disable clock if it's enabled. */
if (IsClockEnabled(module)) {
ClearClockEnable(module);
}
/* Set reset. */
SetReset(module);
/* Set the clock source. */
u32 actual_source_frequency_khz;
SetClockSourceSdmmc(std::addressof(actual_source_frequency_khz), module, target_frequency_khz);
/* Enable clock. */
SetClockEnable(module);
/* Ensure that our configuration takes. */
EnsureControl(module);
/* Wait 100 clocks. */
WaitClocks(100, actual_source_frequency_khz);
/* Clear reset. */
ClearReset(module);
/* Ensure that our configuration takes. */
EnsureControl(module);
}
}
| 19,253
|
C++
|
.cpp
| 323
| 46.427245
| 187
| 0.593362
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,055
|
sdmmc_port_gc_asic0.board.nintendo_nx.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/sdmmc/impl/sdmmc_port_gc_asic0.board.nintendo_nx.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if defined(ATMOSPHERE_IS_STRATOSPHERE)
#include <stratosphere.hpp>
#elif defined(ATMOSPHERE_IS_MESOSPHERE)
#include <mesosphere.hpp>
#elif defined(ATMOSPHERE_IS_EXOSPHERE)
#include <exosphere.hpp>
#else
#include <vapours.hpp>
#endif
#include "sdmmc_port_gc_asic0.hpp"
#include "sdmmc_select_sdmmc_controller.hpp"
namespace ams::sdmmc::impl {
namespace {
SdmmcControllerForPortGcAsic0 g_gc_asic0_host_controller;
GcAsicDeviceAccessor g_gc_asic0_device_accessor(std::addressof(g_gc_asic0_host_controller));
}
IHostController *GetHostControllerOfPortGcAsic0() {
return std::addressof(g_gc_asic0_host_controller);
}
IDeviceAccessor *GetDeviceAccessorOfPortGcAsic0() {
return std::addressof(g_gc_asic0_device_accessor);
}
GcAsicDeviceAccessor *GetGcAsicDeviceAccessorOfPortGcAsic0() {
return std::addressof(g_gc_asic0_device_accessor);
}
}
| 1,552
|
C++
|
.cpp
| 41
| 34.536585
| 100
| 0.758322
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,056
|
sdmmc_device_detector.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/sdmmc/impl/sdmmc_device_detector.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if defined(ATMOSPHERE_IS_STRATOSPHERE)
#include <stratosphere.hpp>
#elif defined(ATMOSPHERE_IS_MESOSPHERE)
#include <mesosphere.hpp>
#elif defined(ATMOSPHERE_IS_EXOSPHERE)
#include <exosphere.hpp>
#else
#include <vapours.hpp>
#endif
#if defined(AMS_SDMMC_USE_SD_CARD_DETECTOR)
#include "sdmmc_device_detector.hpp"
namespace ams::sdmmc::impl {
bool DeviceDetector::IsCurrentInserted() {
return gpio::GetValue(std::addressof(m_gpio_pad_session)) == m_inserted_gpio_value;
}
void DeviceDetector::HandleDeviceStatus(bool prev_inserted, bool cur_inserted) {
if (!prev_inserted && !cur_inserted) {
/* Not inserted -> Not inserted, nothing to do. */
} else if (!prev_inserted && cur_inserted) {
/* Card was inserted. */
if (m_callback_info.inserted_callback != nullptr) {
m_callback_info.inserted_callback(m_callback_info.inserted_callback_arg);
}
} else if (prev_inserted && !cur_inserted) {
/* Card was removed. */
if (m_callback_info.removed_callback != nullptr) {
m_callback_info.removed_callback(m_callback_info.removed_callback_arg);
}
} else /* if (prev_inserted && cur_inserted) */ {
/* Card was removed, and then inserted. */
if (m_callback_info.removed_callback != nullptr) {
m_callback_info.removed_callback(m_callback_info.removed_callback_arg);
}
if (m_callback_info.inserted_callback != nullptr) {
m_callback_info.inserted_callback(m_callback_info.inserted_callback_arg);
}
}
}
void DeviceDetector::DetectorThread() {
/* Initialize the gpio session. */
gpio::Initialize();
/* Open and configure the pad session. */
gpio::OpenSession(std::addressof(m_gpio_pad_session), m_gpio_device_code);
gpio::SetDirection(std::addressof(m_gpio_pad_session), gpio::Direction_Input);
gpio::SetDebounceTime(std::addressof(m_gpio_pad_session), m_gpio_debounce_ms);
gpio::SetDebounceEnabled(std::addressof(m_gpio_pad_session), true);
gpio::SetInterruptMode(std::addressof(m_gpio_pad_session), gpio::InterruptMode_AnyEdge);
/* Get the gpio session's interrupt event. */
os::SystemEventType gpio_event;
R_ABORT_UNLESS(gpio::BindInterrupt(std::addressof(gpio_event), std::addressof(m_gpio_pad_session)));
/* Initialize and link multi wait/holders. */
os::MultiWaitType multi_wait;
os::MultiWaitHolderType detector_thread_end_holder;
os::MultiWaitHolderType request_sleep_wake_event_holder;
os::MultiWaitHolderType gpio_event_holder;
os::InitializeMultiWait(std::addressof(multi_wait));
os::InitializeMultiWaitHolder(std::addressof(detector_thread_end_holder), std::addressof(m_detector_thread_end_event));
os::LinkMultiWaitHolder(std::addressof(multi_wait), std::addressof(detector_thread_end_holder));
os::InitializeMultiWaitHolder(std::addressof(request_sleep_wake_event_holder), std::addressof(m_request_sleep_wake_event));
os::LinkMultiWaitHolder(std::addressof(multi_wait), std::addressof(request_sleep_wake_event_holder));
os::InitializeMultiWaitHolder(std::addressof(gpio_event_holder), std::addressof(gpio_event));
os::LinkMultiWaitHolder(std::addressof(multi_wait), std::addressof(gpio_event_holder));
/* Wait before detecting the initial state of the card. */
os::SleepThread(TimeSpan::FromMilliSeconds(m_gpio_debounce_ms));
bool cur_inserted = this->IsCurrentInserted();
m_is_prev_inserted = cur_inserted;
/* Set state as awake. */
m_state = State_Awake;
os::SignalEvent(std::addressof(m_ready_device_status_event));
/* Enable interrupts to be informed of device status. */
gpio::SetInterruptEnable(std::addressof(m_gpio_pad_session), true);
/* Wait, servicing our events. */
while (true) {
/* Get the signaled holder. */
os::MultiWaitHolderType *signaled_holder = os::WaitAny(std::addressof(multi_wait));
/* Process the holder. */
bool insert_change = false;
if (signaled_holder == std::addressof(detector_thread_end_holder)) {
/* We should kill ourselves. */
os::ClearEvent(std::addressof(m_detector_thread_end_event));
m_state = State_Finalized;
break;
} else if (signaled_holder == std::addressof(request_sleep_wake_event_holder)) {
/* A request for us to sleep/wake has come in, so we'll acknowledge it. */
os::ClearEvent(std::addressof(m_request_sleep_wake_event));
m_state = State_Sleep;
os::SignalEvent(std::addressof(m_acknowledge_sleep_awake_event));
/* Temporarily unlink our interrupt event. */
os::UnlinkMultiWaitHolder(std::addressof(gpio_event_holder));
/* Wait to be signaled. */
signaled_holder = os::WaitAny(std::addressof(multi_wait));
/* Link our interrupt event back in. */
os::LinkMultiWaitHolder(std::addressof(multi_wait), std::addressof(gpio_event_holder));
/* We're awake again. Either because we should exit, or because we were asked to wake up. */
os::ClearEvent(std::addressof(m_request_sleep_wake_event));
m_state = State_Awake;
os::SignalEvent(std::addressof(m_acknowledge_sleep_awake_event));
/* If we were asked to exit, do so. */
if (signaled_holder == std::addressof(detector_thread_end_holder)) {
/* We should kill ourselves. */
os::ClearEvent(std::addressof(m_detector_thread_end_event));
m_state = State_Finalized;
break;
} else /* if (signaled_holder == std::addressof(request_sleep_wake_event_holder)) */ {
if ((m_force_detection) ||
(({ bool active; R_SUCCEEDED(gpio::IsWakeEventActive(std::addressof(active), m_gpio_device_code)) && active; })) ||
(os::TryWaitSystemEvent(std::addressof(gpio_event))) ||
(m_is_prev_inserted != this->IsCurrentInserted()))
{
insert_change = true;
}
}
} else /* if (signaled_holder == std::addressof(gpio_event_holder)) */ {
/* An event was detected. */
insert_change = true;
}
/* Handle an insert change, if one occurred. */
if (insert_change) {
/* Call the relevant callback, if we have one. */
if (m_device_detection_event_callback != nullptr) {
m_device_detection_event_callback(m_device_detection_event_callback_arg);
}
/* Clear the interrupt event. */
os::ClearSystemEvent(std::addressof(gpio_event));
gpio::ClearInterruptStatus(std::addressof(m_gpio_pad_session));
gpio::SetInterruptEnable(std::addressof(m_gpio_pad_session), true);
/* Update insertion status. */
cur_inserted = this->IsCurrentInserted();
this->HandleDeviceStatus(m_is_prev_inserted, cur_inserted);
m_is_prev_inserted = cur_inserted;
}
}
/* Disable interrupts to our gpio event. */
gpio::SetInterruptEnable(std::addressof(m_gpio_pad_session), false);
/* Finalize and unlink multi wait/holders. */
os::UnlinkMultiWaitHolder(std::addressof(gpio_event_holder));
os::FinalizeMultiWaitHolder(std::addressof(gpio_event_holder));
os::UnlinkMultiWaitHolder(std::addressof(request_sleep_wake_event_holder));
os::FinalizeMultiWaitHolder(std::addressof(request_sleep_wake_event_holder));
os::UnlinkMultiWaitHolder(std::addressof(detector_thread_end_holder));
os::FinalizeMultiWaitHolder(std::addressof(detector_thread_end_holder));
os::FinalizeMultiWait(std::addressof(multi_wait));
/* Finalize the gpio session. */
gpio::UnbindInterrupt(std::addressof(m_gpio_pad_session));
gpio::CloseSession(std::addressof(m_gpio_pad_session));
gpio::Finalize();
}
void DeviceDetector::Initialize(CallbackInfo *ci) {
/* Transition our state from finalized to initializing. */
AMS_ABORT_UNLESS(m_state == State_Finalized);
m_state = State_Initializing;
/* Set our callback infos. */
m_callback_info = *ci;
/* Initialize our events. */
os::InitializeEvent(std::addressof(m_ready_device_status_event), false, os::EventClearMode_ManualClear);
os::InitializeEvent(std::addressof(m_request_sleep_wake_event), false, os::EventClearMode_ManualClear);
os::InitializeEvent(std::addressof(m_acknowledge_sleep_awake_event), false, os::EventClearMode_ManualClear);
os::InitializeEvent(std::addressof(m_detector_thread_end_event), false, os::EventClearMode_ManualClear);
/* Create and start the detector thread. */
os::CreateThread(std::addressof(m_detector_thread), DetectorThreadEntry, this, m_detector_thread_stack, sizeof(m_detector_thread_stack), AMS_GET_SYSTEM_THREAD_PRIORITY(sdmmc, DeviceDetector));
os::SetThreadNamePointer(std::addressof(m_detector_thread), AMS_GET_SYSTEM_THREAD_NAME(sdmmc, DeviceDetector));
os::StartThread(std::addressof(m_detector_thread));
}
void DeviceDetector::Finalize() {
/* Ensure we're not already finalized. */
AMS_ABORT_UNLESS(m_state != State_Finalized);
/* Signal event to end the detector thread. */
os::SignalEvent(std::addressof(m_detector_thread_end_event));
os::WaitThread(std::addressof(m_detector_thread));
/* Finalize thread and events. */
os::DestroyThread(std::addressof(m_detector_thread));
os::FinalizeEvent(std::addressof(m_ready_device_status_event));
os::FinalizeEvent(std::addressof(m_request_sleep_wake_event));
os::FinalizeEvent(std::addressof(m_acknowledge_sleep_awake_event));
os::FinalizeEvent(std::addressof(m_detector_thread_end_event));
}
void DeviceDetector::PutToSleep() {
/* Signal request, wait for acknowledgement. */
os::SignalEvent(std::addressof(m_request_sleep_wake_event));
os::WaitEvent(std::addressof(m_acknowledge_sleep_awake_event));
os::ClearEvent(std::addressof(m_acknowledge_sleep_awake_event));
}
void DeviceDetector::Awaken(bool force_det) {
/* Signal request, wait for acknowledgement. */
m_force_detection = force_det;
os::SignalEvent(std::addressof(m_request_sleep_wake_event));
os::WaitEvent(std::addressof(m_acknowledge_sleep_awake_event));
os::ClearEvent(std::addressof(m_acknowledge_sleep_awake_event));
}
bool DeviceDetector::IsInserted() {
bool inserted = false;
switch (m_state) {
case State_Initializing:
/* Wait for us to know whether the device is inserted. */
os::WaitEvent(std::addressof(m_ready_device_status_event));
[[fallthrough]];
case State_Awake:
/* Get whether the device is currently inserted. */
inserted = this->IsCurrentInserted();
break;
case State_Sleep:
case State_Finalized:
/* Get whether the device was inserted when we last knew. */
inserted = m_is_prev_inserted;
break;
}
return inserted;
}
void DeviceDetector::RegisterDetectionEventCallback(DeviceDetectionEventCallback cb, void *arg) {
m_device_detection_event_callback_arg = arg;
m_device_detection_event_callback = cb;
}
void DeviceDetector::UnregisterDetectionEventCallback() {
m_device_detection_event_callback = nullptr;
}
}
#endif
| 12,891
|
C++
|
.cpp
| 232
| 44.866379
| 200
| 0.63658
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,057
|
sdmmc_port_sd_card0.board.nintendo_nx.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/sdmmc/impl/sdmmc_port_sd_card0.board.nintendo_nx.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if defined(ATMOSPHERE_IS_STRATOSPHERE)
#include <stratosphere.hpp>
#elif defined(ATMOSPHERE_IS_MESOSPHERE)
#include <mesosphere.hpp>
#elif defined(ATMOSPHERE_IS_EXOSPHERE)
#include <exosphere.hpp>
#else
#include <vapours.hpp>
#endif
#include "sdmmc_port_sd_card0.hpp"
#include "sdmmc_select_sdmmc_controller.hpp"
namespace ams::sdmmc::impl {
namespace {
SdmmcControllerForPortSdCard0 g_sd_card0_host_controller;
#if defined(AMS_SDMMC_USE_SD_CARD_DETECTOR)
constexpr inline u32 SdCard0DebounceMilliSeconds = 128;
DeviceDetector g_sd_card0_detector(gpio::DeviceCode_SdCd, gpio::GpioValue_Low, SdCard0DebounceMilliSeconds);
SdCardDeviceAccessor g_sd_card0_device_accessor(std::addressof(g_sd_card0_host_controller), std::addressof(g_sd_card0_detector));
#else
SdCardDeviceAccessor g_sd_card0_device_accessor(std::addressof(g_sd_card0_host_controller));
#endif
}
IHostController *GetHostControllerOfPortSdCard0() {
return std::addressof(g_sd_card0_host_controller);
}
IDeviceAccessor *GetDeviceAccessorOfPortSdCard0() {
return std::addressof(g_sd_card0_device_accessor);
}
SdCardDeviceAccessor *GetSdCardDeviceAccessorOfPortSdCard0() {
return std::addressof(g_sd_card0_device_accessor);
}
}
| 1,975
|
C++
|
.cpp
| 47
| 37.489362
| 141
| 0.745293
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,058
|
sdmmc_timer.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/sdmmc/impl/sdmmc_timer.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if defined(ATMOSPHERE_IS_STRATOSPHERE)
#include <stratosphere.hpp>
#elif defined(ATMOSPHERE_IS_MESOSPHERE)
#include <mesosphere.hpp>
#elif defined(ATMOSPHERE_IS_EXOSPHERE)
#include <exosphere.hpp>
#else
#include <vapours.hpp>
#endif
#include "sdmmc_timer.hpp"
namespace ams::sdmmc::impl {
namespace {
#if defined(AMS_SDMMC_USE_OS_TIMER)
void SpinWaitMicroSeconds(u32 us) {
const os::Tick timeout_tick = os::GetSystemTick() + os::ConvertToTick(TimeSpan::FromMicroSeconds(us)) + os::Tick(1);
while (true) {
if (os::GetSystemTick() > timeout_tick) {
break;
}
}
}
ALWAYS_INLINE void DataSynchronizationBarrier() {
#if defined(ATMOSPHERE_ARCH_ARM64)
__asm__ __volatile__("dsb sy" ::: "memory");
#elif defined(ATMOSPHERE_ARCH_ARM)
__asm__ __volatile__("dsb" ::: "memory");
#elif defined(ATMOSPHERE_ARCH_X64) || defined(ATMOSPHERE_ARCH_X86)
/* Nothing needed? */
__asm__ __volatile__("" ::: "memory");
#else
#error "Unknown architecture for DataSynchronizationBarrier"
#endif
}
ALWAYS_INLINE void InstructionSynchronizationBarrier() {
#if defined(ATMOSPHERE_ARCH_ARM64) || defined(ATMOSPHERE_ARCH_ARM)
__asm__ __volatile__("isb" ::: "memory");
#elif defined(ATMOSPHERE_ARCH_X64) || defined(ATMOSPHERE_ARCH_X86)
/* Nothing needed? */
__asm__ __volatile__("" ::: "memory");
#else
#error "Unknown architecture for InstructionSynchronizationBarrier"
#endif
}
#endif
}
void WaitMicroSeconds(u32 us) {
#if defined(AMS_SDMMC_USE_OS_TIMER)
/* Ensure that nothing is reordered before we wait. */
DataSynchronizationBarrier();
InstructionSynchronizationBarrier();
/* If the time is small, spinloop, otherwise pend ourselves. */
if (us < 100) {
SpinWaitMicroSeconds(us);
} else {
os::SleepThread(TimeSpan::FromMicroSeconds(us));
}
/* Ensure that nothing is reordered after we wait. */
DataSynchronizationBarrier();
InstructionSynchronizationBarrier();
#elif defined(AMS_SDMMC_USE_UTIL_TIMER)
util::WaitMicroSeconds(us);
#else
#error "Unknown context for ams::sdmmc::impl::WaitMicroSeconds"
#endif
}
void WaitClocks(u32 num_clocks, u32 clock_frequency_khz) {
AMS_ABORT_UNLESS(clock_frequency_khz > 0);
WaitMicroSeconds(util::DivideUp(1000 * num_clocks, clock_frequency_khz));
}
}
| 3,432
|
C++
|
.cpp
| 85
| 31.741176
| 128
| 0.618405
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,059
|
sdmmc_clock_reset_controller.pcv.board.nintendo_nx.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/sdmmc/impl/sdmmc_clock_reset_controller.pcv.board.nintendo_nx.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if defined(ATMOSPHERE_IS_STRATOSPHERE)
#include <stratosphere.hpp>
#elif defined(ATMOSPHERE_IS_MESOSPHERE)
#include <mesosphere.hpp>
#elif defined(ATMOSPHERE_IS_EXOSPHERE)
#include <exosphere.hpp>
#else
#include <vapours.hpp>
#endif
#include "sdmmc_clock_reset_controller.pcv.board.nintendo_nx.hpp"
namespace ams::sdmmc::impl::ClockResetController::pcv {
#if defined(AMS_SDMMC_USE_PCV_CLOCK_RESET_CONTROL)
void Initialize(Module module) {
AMS_UNUSED(module);
AMS_ABORT("PCV Control not implemented");
}
void Finalize(Module module) {
AMS_UNUSED(module);
AMS_ABORT("PCV Control not implemented");
}
bool IsAvailable(Module module) {
AMS_UNUSED(module);
AMS_ABORT("PCV Control not implemented");
}
void SetClockFrequencyKHz(u32 *out_actual_frequency, Module module, u32 target_frequency) {
AMS_UNUSED(out_actual_frequency, module, target_frequency);
AMS_ABORT("PCV Control not implemented");
}
void AssertReset(Module module) {
AMS_UNUSED(module);
AMS_ABORT("PCV Control not implemented");
}
void ReleaseReset(Module module, u32 target_frequency_khz) {
AMS_UNUSED(module, target_frequency_khz);
AMS_ABORT("PCV Control not implemented");
}
#else
void Initialize(Module module) {
AMS_UNUSED(module);
AMS_ABORT("PCV Control not supported");
}
void Finalize(Module module) {
AMS_UNUSED(module);
AMS_ABORT("PCV Control not supported");
}
bool IsAvailable(Module module) {
AMS_UNUSED(module);
AMS_ABORT("PCV Control not supported");
}
void SetClockFrequencyKHz(u32 *out_actual_frequency, Module module, u32 target_frequency) {
AMS_UNUSED(out_actual_frequency, module, target_frequency);
AMS_ABORT("PCV Control not supported");
}
void AssertReset(Module module) {
AMS_UNUSED(module);
AMS_ABORT("PCV Control not supported");
}
void ReleaseReset(Module module, u32 target_frequency_khz) {
AMS_UNUSED(module, target_frequency_khz);
AMS_ABORT("PCV Control not supported");
}
#endif
}
| 3,016
|
C++
|
.cpp
| 78
| 30.961538
| 99
| 0.653886
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,060
|
sdmmc_sd_host_standard_controller.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/sdmmc/impl/sdmmc_sd_host_standard_controller.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if defined(ATMOSPHERE_IS_STRATOSPHERE)
#include <stratosphere.hpp>
#elif defined(ATMOSPHERE_IS_MESOSPHERE)
#include <mesosphere.hpp>
#elif defined(ATMOSPHERE_IS_EXOSPHERE)
#include <exosphere.hpp>
#else
#include <vapours.hpp>
#endif
#include "sdmmc_sd_host_standard_controller.hpp"
#include "sdmmc_timer.hpp"
#if defined(ATMOSPHERE_IS_STRATOSPHERE)
#include <stratosphere/dd.hpp>
#endif
namespace ams::sdmmc::impl {
namespace {
constexpr inline u32 ControllerReactionTimeoutMilliSeconds = 2000;
constexpr inline u32 CommandTimeoutMilliSeconds = 2000;
constexpr inline u32 DefaultCheckTransferIntervalMilliSeconds = 1500;
constexpr inline u32 BusyTimeoutMilliSeconds = 2000;
}
#if defined(AMS_SDMMC_USE_DEVICE_VIRTUAL_ADDRESS)
void SdHostStandardController::ResetBufferInfos() {
for (auto &info : m_buffer_infos) {
info.buffer_address = 0;
info.buffer_size = 0;
}
}
dd::DeviceVirtualAddress SdHostStandardController::GetDeviceVirtualAddress(uintptr_t buffer, size_t buffer_size) {
/* Try to find the buffer in our registered regions. */
dd::DeviceVirtualAddress device_addr = 0;
for (const auto &info : m_buffer_infos) {
if (info.buffer_address <= buffer && (buffer + buffer_size) <= (info.buffer_address + info.buffer_size)) {
device_addr = info.buffer_device_virtual_address + (buffer - info.buffer_address);
break;
}
}
/* Ensure that we found the buffer. */
AMS_ABORT_UNLESS(device_addr != 0);
return device_addr;
}
#endif
void SdHostStandardController::EnsureControl() {
/* Perform a read of clock control to be sure previous configuration takes. */
reg::Read(m_registers->clock_control);
}
Result SdHostStandardController::EnableInternalClock() {
/* Enable internal clock. */
reg::ReadWrite(m_registers->clock_control, SD_REG_BITS_ENUM(CLOCK_CONTROL_INTERNAL_CLOCK_ENABLE, OSCILLATE));
this->EnsureControl();
/* Wait for the internal clock to become stable. */
{
ManualTimer timer(ControllerReactionTimeoutMilliSeconds);
while (true) {
/* Check if the clock is steady. */
if (reg::HasValue(m_registers->clock_control, SD_REG_BITS_ENUM(CLOCK_CONTROL_INTERNAL_CLOCK_STABLE, READY))) {
break;
}
/* If not, check for timeout. */
R_UNLESS(timer.Update(), sdmmc::ResultInternalClockStableSoftwareTimeout());
}
}
/* Configure to use host controlled divided clock. */
reg::ReadWrite(m_registers->host_control2, SD_REG_BITS_ENUM(HOST_CONTROL2_PRESET_VALUE_ENABLE, HOST_DRIVER));
reg::ReadWrite(m_registers->clock_control, SD_REG_BITS_ENUM(CLOCK_CONTROL_CLOCK_GENERATOR_SELECT, DIVIDED_CLOCK));
/* Set host version 4.0.0 enable. */
reg::ReadWrite(m_registers->host_control2, SD_REG_BITS_ENUM(HOST_CONTROL2_HOST_VERSION_4_ENABLE, VERSION_4));
/* Set host 64 bit addressing enable. */
AMS_ABORT_UNLESS(reg::HasValue(m_registers->capabilities, SD_REG_BITS_ENUM(CAPABILITIES_64_BIT_SYSTEM_ADDRESS_SUPPORT_FOR_V3, SUPPORTED)));
reg::ReadWrite(m_registers->host_control2, SD_REG_BITS_ENUM(HOST_CONTROL2_64_BIT_ADDRESSING, 64_BIT_ADDRESSING));
/* Select SDMA mode. */
reg::ReadWrite(m_registers->host_control, SD_REG_BITS_ENUM(HOST_CONTROL_DMA_SELECT, SDMA));
/* Configure timeout control to use the maximum timeout value (TMCLK * 2^27) */
reg::ReadWrite(m_registers->timeout_control, SD_REG_BITS_VALUE(TIMEOUT_CONTROL_DATA_TIMEOUT_COUNTER, 0b1110));
R_SUCCEED();
}
void SdHostStandardController::SetBusPower(BusPower bus_power) {
/* Check that we support the bus power. */
AMS_ABORT_UNLESS(this->IsSupportedBusPower(bus_power));
/* Set the appropriate power. */
switch (bus_power) {
case BusPower_Off:
reg::ReadWrite(m_registers->power_control, SD_REG_BITS_ENUM(POWER_CONTROL_SD_BUS_POWER_FOR_VDD1, OFF));
break;
case BusPower_1_8V:
reg::ReadWrite(m_registers->power_control, SD_REG_BITS_ENUM(POWER_CONTROL_SD_BUS_VOLTAGE_SELECT_FOR_VDD1, 1_8V));
reg::ReadWrite(m_registers->power_control, SD_REG_BITS_ENUM(POWER_CONTROL_SD_BUS_POWER_FOR_VDD1, ON));
break;
case BusPower_3_3V:
reg::ReadWrite(m_registers->power_control, SD_REG_BITS_ENUM(POWER_CONTROL_SD_BUS_VOLTAGE_SELECT_FOR_VDD1, 3_3V));
reg::ReadWrite(m_registers->power_control, SD_REG_BITS_ENUM(POWER_CONTROL_SD_BUS_POWER_FOR_VDD1, ON));
break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
void SdHostStandardController::EnableInterruptStatus() {
/* Set the status register interrupt enables. */
reg::ReadWrite(m_registers->normal_int_enable, SD_HOST_STANDARD_NORMAL_INTERRUPT_ENABLE_ISSUE_COMMAND(ENABLED));
reg::ReadWrite(m_registers->error_int_enable, SD_HOST_STANDARD_ERROR_INTERRUPT_ENABLE_ISSUE_COMMAND (ENABLED));
/* Read/write the interrupt enables to be sure they take. */
reg::Write(m_registers->normal_int_enable, reg::Read(m_registers->normal_int_enable));
reg::Write(m_registers->error_int_enable, reg::Read(m_registers->error_int_enable));
/* If we're using interrupt events, configure appropriately. */
#if defined(AMS_SDMMC_USE_OS_EVENTS)
{
/* Clear interrupts. */
this->ClearInterrupt();
/* Enable the interrupt signals. */
reg::ReadWrite(m_registers->normal_signal_enable, SD_HOST_STANDARD_NORMAL_INTERRUPT_ENABLE_ISSUE_COMMAND(ENABLED));
reg::ReadWrite(m_registers->error_signal_enable, SD_HOST_STANDARD_ERROR_INTERRUPT_ENABLE_ISSUE_COMMAND (ENABLED));
}
#endif
}
void SdHostStandardController::DisableInterruptStatus() {
/* If we're using interrupt events, configure appropriately. */
#if defined(AMS_SDMMC_USE_OS_EVENTS)
{
/* Disable the interrupt signals. */
reg::ReadWrite(m_registers->normal_signal_enable, SD_HOST_STANDARD_NORMAL_INTERRUPT_ENABLE_ISSUE_COMMAND(MASKED));
reg::ReadWrite(m_registers->error_signal_enable, SD_HOST_STANDARD_ERROR_INTERRUPT_ENABLE_ISSUE_COMMAND (MASKED));
}
#endif
/* Mask the status register interrupt enables. */
reg::ReadWrite(m_registers->normal_int_enable, SD_HOST_STANDARD_NORMAL_INTERRUPT_ENABLE_ISSUE_COMMAND(MASKED));
reg::ReadWrite(m_registers->error_int_enable, SD_HOST_STANDARD_ERROR_INTERRUPT_ENABLE_ISSUE_COMMAND (MASKED));
}
#if defined(AMS_SDMMC_USE_OS_EVENTS)
Result SdHostStandardController::WaitInterrupt(u32 timeout_ms) {
/* Ensure that we control the registers. */
this->EnsureControl();
/* Wait for the interrupt to be signaled. */
os::MultiWaitHolderType *signaled_holder = os::TimedWaitAny(std::addressof(m_multi_wait), TimeSpan::FromMilliSeconds(timeout_ms));
if (signaled_holder == std::addressof(m_interrupt_event_holder)) {
/* We received the interrupt. */
R_SUCCEED();
} else if (signaled_holder == std::addressof(m_removed_event_holder)) {
/* The device was removed. */
R_THROW(sdmmc::ResultDeviceRemoved());
} else {
/* Timeout occurred. */
R_THROW(sdmmc::ResultWaitInterruptSoftwareTimeout());
}
}
void SdHostStandardController::ClearInterrupt() {
/* Ensure that we control the registers. */
this->EnsureControl();
/* Clear the interrupt event. */
os::ClearInterruptEvent(m_interrupt_event);
}
#endif
void SdHostStandardController::SetTransfer(u32 *out_num_transferred_blocks, const TransferData *xfer_data) {
/* Ensure the transfer data is valid. */
AMS_ABORT_UNLESS(xfer_data->block_size != 0);
AMS_ABORT_UNLESS(xfer_data->num_blocks != 0);
/* Determine the number of blocks. */
const u16 num_blocks = std::min<u16>(xfer_data->num_blocks, SdHostStandardRegisters::BlockCountMax);
/* Determine the address/how many blocks to transfer. */
#if defined(AMS_SDMMC_USE_DEVICE_VIRTUAL_ADDRESS)
const u64 address = this->GetDeviceVirtualAddress(reinterpret_cast<uintptr_t>(xfer_data->buffer), xfer_data->block_size * num_blocks);
const u16 num_xfer_blocks = num_blocks;
#else
const u64 address = reinterpret_cast<uintptr_t>(xfer_data->buffer);
const u16 num_xfer_blocks = num_blocks;
#endif
/* Verify the address is usable. */
AMS_ABORT_UNLESS(util::IsAligned(address, BufferDeviceVirtualAddressAlignment));
/* Configure for sdma. */
reg::Write(m_registers->adma_address, static_cast<u32>(address >> 0));
reg::Write(m_registers->upper_adma_address, static_cast<u32>(address >> BITSIZEOF(u32)));
/* Set our next sdma address. */
m_next_sdma_address = util::AlignDown<u64>(address + SdmaBufferBoundary, SdmaBufferBoundary);
/* Configure block size. */
AMS_ABORT_UNLESS(xfer_data->block_size <= SdHostStandardBlockSizeTransferBlockSizeMax);
reg::Write(m_registers->block_size, SD_REG_BITS_ENUM (BLOCK_SIZE_SDMA_BUFFER_BOUNDARY, 512_KB),
SD_REG_BITS_VALUE(BLOCK_SIZE_TRANSFER_BLOCK_SIZE, static_cast<u16>(xfer_data->block_size)));
/* Configure transfer blocks. */
reg::Write(m_registers->block_count, num_xfer_blocks);
if (out_num_transferred_blocks != nullptr) {
*out_num_transferred_blocks = num_xfer_blocks;
}
/* Configure transfer mode. */
reg::Write(m_registers->transfer_mode, SD_REG_BITS_ENUM (TRANSFER_MODE_DMA_ENABLE, ENABLE),
SD_REG_BITS_ENUM_SEL(TRANSFER_MODE_BLOCK_COUNT_ENABLE, (xfer_data->is_multi_block_transfer), ENABLE, DISABLE),
SD_REG_BITS_ENUM_SEL(TRANSFER_MODE_MULTI_BLOCK_SELECT, (xfer_data->is_multi_block_transfer), MULTI_BLOCK, SINGLE_BLOCK),
SD_REG_BITS_ENUM_SEL(TRANSFER_MODE_DATA_TRANSFER_DIRECTION, (xfer_data->transfer_direction == TransferDirection_ReadFromDevice), READ, WRITE),
SD_REG_BITS_ENUM_SEL(TRANSFER_MODE_AUTO_CMD_ENABLE, (xfer_data->is_stop_transmission_command_enabled), CMD12_ENABLE, DISABLE));
}
void SdHostStandardController::SetTransferForTuning() {
/* Get the tuning block size. */
u16 tuning_block_size;
switch (this->GetBusWidth()) {
case BusWidth_4Bit:
tuning_block_size = 64;
break;
case BusWidth_8Bit:
tuning_block_size = 128;
break;
case BusWidth_1Bit:
AMS_UNREACHABLE_DEFAULT_CASE();
}
/* Configure block size. */
AMS_ABORT_UNLESS(tuning_block_size <= SdHostStandardBlockSizeTransferBlockSizeMax);
reg::Write(m_registers->block_size, SD_REG_BITS_VALUE(BLOCK_SIZE_TRANSFER_BLOCK_SIZE, tuning_block_size));
/* Configure transfer blocks. */
reg::Write(m_registers->block_count, 1);
/* Configure transfer mode. */
reg::Write(m_registers->transfer_mode, SD_REG_BITS_ENUM(TRANSFER_MODE_DATA_TRANSFER_DIRECTION, READ));
}
void SdHostStandardController::SetCommand(const Command *command, bool has_xfer_data) {
/* Encode the command value. */
u16 command_val = 0;
/* Encode the response type. */
switch (command->response_type) {
case ResponseType_R0:
command_val |= reg::Encode(SD_REG_BITS_ENUM(COMMAND_RESPONSE_TYPE, NO_RESPONSE),
SD_REG_BITS_ENUM(COMMAND_CRC_CHECK, DISABLE),
SD_REG_BITS_ENUM(COMMAND_INDEX_CHECK, DISABLE));
break;
case ResponseType_R1:
case ResponseType_R6:
case ResponseType_R7:
command_val |= reg::Encode(SD_REG_BITS_ENUM_SEL(COMMAND_RESPONSE_TYPE, command->is_busy, RESPONSE_LENGTH_48_CHECK_BUSY_AFTER_RESPONSE, RESPONSE_LENGTH_48),
SD_REG_BITS_ENUM (COMMAND_CRC_CHECK, ENABLE),
SD_REG_BITS_ENUM (COMMAND_INDEX_CHECK, ENABLE));
break;
case ResponseType_R2:
command_val |= reg::Encode(SD_REG_BITS_ENUM(COMMAND_RESPONSE_TYPE, RESPONSE_LENGTH_136),
SD_REG_BITS_ENUM(COMMAND_CRC_CHECK, ENABLE),
SD_REG_BITS_ENUM(COMMAND_INDEX_CHECK, DISABLE));
break;
case ResponseType_R3:
command_val |= reg::Encode(SD_REG_BITS_ENUM(COMMAND_RESPONSE_TYPE, RESPONSE_LENGTH_48),
SD_REG_BITS_ENUM(COMMAND_CRC_CHECK, DISABLE),
SD_REG_BITS_ENUM(COMMAND_INDEX_CHECK, DISABLE));
break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
/* Encode the data present select. */
command_val |= reg::Encode(SD_REG_BITS_ENUM_SEL(COMMAND_DATA_PRESENT, has_xfer_data, DATA_PRESENT, NO_DATA_PRESENT));
/* Encode the command index. */
AMS_ABORT_UNLESS(command->command_index <= SdHostStandardCommandIndexMax);
command_val |= reg::Encode(SD_REG_BITS_VALUE(COMMAND_COMMAND_INDEX, command->command_index));
/* Write the command and argument. */
reg::Write(m_registers->argument, command->command_argument);
reg::Write(m_registers->command, command_val);
}
void SdHostStandardController::SetCommandForTuning(u32 command_index) {
Command command(command_index, 0, ResponseType_R1, false);
return this->SetCommand(std::addressof(command), true);
}
Result SdHostStandardController::ResetCmdDatLine() {
/* Set the software reset cmd/dat bits. */
reg::ReadWrite(m_registers->software_reset, SD_REG_BITS_ENUM(SOFTWARE_RESET_FOR_CMD, RESET),
SD_REG_BITS_ENUM(SOFTWARE_RESET_FOR_DAT, RESET));
/* Ensure that we control the registers. */
this->EnsureControl();
/* Wait until reset is done. */
{
ManualTimer timer(ControllerReactionTimeoutMilliSeconds);
while (true) {
/* Check if the target has been removed. */
R_TRY(this->CheckRemoved());
/* Check if command inhibit is no longer present. */
if (reg::HasValue(m_registers->software_reset, SD_REG_BITS_ENUM(SOFTWARE_RESET_FOR_CMD, WORK),
SD_REG_BITS_ENUM(SOFTWARE_RESET_FOR_DAT, WORK)))
{
break;
}
/* Otherwise, check if we've timed out. */
if (!timer.Update()) {
R_THROW(sdmmc::ResultAbortTransactionSoftwareTimeout());
}
}
}
R_SUCCEED();
}
Result SdHostStandardController::AbortTransaction() {
R_TRY(this->ResetCmdDatLine());
R_SUCCEED();
}
Result SdHostStandardController::WaitWhileCommandInhibit(bool has_dat) {
/* Ensure that we control the registers. */
this->EnsureControl();
/* Wait while command inhibit cmd is set. */
{
ManualTimer timer(ControllerReactionTimeoutMilliSeconds);
while (true) {
/* Check if the target has been removed. */
R_TRY(this->CheckRemoved());
/* Check if command inhibit is no longer present. */
if (reg::HasValue(m_registers->present_state, SD_REG_BITS_ENUM(PRESENT_STATE_COMMAND_INHIBIT_CMD, READY))) {
break;
}
/* Otherwise, check if we've timed out. */
if (!timer.Update()) {
this->AbortTransaction();
R_THROW(sdmmc::ResultCommandInhibitCmdSoftwareTimeout());
}
}
}
/* Wait while command inhibit dat is set. */
if (has_dat) {
ManualTimer timer(ControllerReactionTimeoutMilliSeconds);
while (true) {
/* Check if the target has been removed. */
R_TRY(this->CheckRemoved());
/* Check if command inhibit is no longer present. */
if (reg::HasValue(m_registers->present_state, SD_REG_BITS_ENUM(PRESENT_STATE_COMMAND_INHIBIT_DAT, READY))) {
break;
}
/* Otherwise, check if we've timed out. */
if (!timer.Update()) {
this->AbortTransaction();
R_THROW(sdmmc::ResultCommandInhibitDatSoftwareTimeout());
}
}
}
R_SUCCEED();
}
Result SdHostStandardController::CheckAndClearInterruptStatus(volatile u16 *out_normal_int_status, u16 wait_mask) {
/* Read the statuses. */
volatile u16 normal_int_status = reg::Read(m_registers->normal_int_status);
volatile u16 error_int_status = reg::Read(m_registers->error_int_status);
volatile u16 auto_cmd_err_status = reg::Read(m_registers->acmd12_err);
/* Set the output status, if necessary. */
if (out_normal_int_status != nullptr) {
*out_normal_int_status = normal_int_status;
}
/* If we don't have an error interrupt, just use the normal status. */
if (reg::HasValue(normal_int_status, SD_REG_BITS_ENUM(NORMAL_INTERRUPT_STATUS_ERROR_INTERRUPT, NO_ERROR))) {
/* If the wait mask has any bits set, we're done waiting for the interrupt. */
const u16 masked_status = (normal_int_status & wait_mask);
R_UNLESS(masked_status != 0, sdmmc::ResultNoWaitedInterrupt());
/* Write the masked value to the status register to ensure consistent state. */
reg::Write(m_registers->normal_int_status, masked_status);
R_SUCCEED();
}
/* We have an error interrupt. Write the status to the register to ensure consistent state. */
reg::Write(m_registers->error_int_status, error_int_status);
/* Check the error interrupt status bits, and return appropriate errors. */
R_UNLESS(reg::HasValue(error_int_status, SD_REG_BITS_ENUM(ERROR_INTERRUPT_STATUS_COMMAND_INDEX, NO_ERROR)), sdmmc::ResultResponseIndexError());
R_UNLESS(reg::HasValue(error_int_status, SD_REG_BITS_ENUM(ERROR_INTERRUPT_STATUS_COMMAND_END_BIT, NO_ERROR)), sdmmc::ResultResponseEndBitError());
R_UNLESS(reg::HasValue(error_int_status, SD_REG_BITS_ENUM(ERROR_INTERRUPT_STATUS_COMMAND_CRC, NO_ERROR)), sdmmc::ResultResponseCrcError());
R_UNLESS(reg::HasValue(error_int_status, SD_REG_BITS_ENUM(ERROR_INTERRUPT_STATUS_COMMAND_TIMEOUT, NO_ERROR)), sdmmc::ResultResponseTimeoutError());
R_UNLESS(reg::HasValue(error_int_status, SD_REG_BITS_ENUM(ERROR_INTERRUPT_STATUS_DATA_END_BIT, NO_ERROR)), sdmmc::ResultDataEndBitError());
R_UNLESS(reg::HasValue(error_int_status, SD_REG_BITS_ENUM(ERROR_INTERRUPT_STATUS_DATA_CRC, NO_ERROR)), sdmmc::ResultDataCrcError());
R_UNLESS(reg::HasValue(error_int_status, SD_REG_BITS_ENUM(ERROR_INTERRUPT_STATUS_DATA_TIMEOUT, NO_ERROR)), sdmmc::ResultDataTimeoutError());
/* Check for auto cmd errors. */
if (reg::HasValue(error_int_status, SD_REG_BITS_ENUM(ERROR_INTERRUPT_STATUS_AUTO_CMD, ERROR))) {
R_UNLESS(reg::HasValue(auto_cmd_err_status, SD_REG_BITS_ENUM(AUTO_CMD_ERROR_AUTO_CMD_INDEX, NO_ERROR)), sdmmc::ResultAutoCommandResponseIndexError());
R_UNLESS(reg::HasValue(auto_cmd_err_status, SD_REG_BITS_ENUM(AUTO_CMD_ERROR_AUTO_CMD_END_BIT, NO_ERROR)), sdmmc::ResultAutoCommandResponseEndBitError());
R_UNLESS(reg::HasValue(auto_cmd_err_status, SD_REG_BITS_ENUM(AUTO_CMD_ERROR_AUTO_CMD_CRC, NO_ERROR)), sdmmc::ResultAutoCommandResponseCrcError());
R_UNLESS(reg::HasValue(auto_cmd_err_status, SD_REG_BITS_ENUM(AUTO_CMD_ERROR_AUTO_CMD_TIMEOUT, NO_ERROR)), sdmmc::ResultAutoCommandResponseTimeoutError());
/* An known auto cmd error occurred. */
R_THROW(sdmmc::ResultSdHostStandardUnknownAutoCmdError());
} else {
/* Unknown error occurred. */
R_THROW(sdmmc::ResultSdHostStandardUnknownError());
}
}
Result SdHostStandardController::WaitCommandComplete() {
#if defined(AMS_SDMMC_USE_OS_EVENTS)
{
/* Wait for interrupt. */
Result result = this->WaitInterrupt(CommandTimeoutMilliSeconds);
if (R_SUCCEEDED(result)) {
/* If we succeeded, check/clear our interrupt status. */
result = this->CheckAndClearInterruptStatus(nullptr, reg::Encode(SD_REG_BITS_ENUM(NORMAL_INTERRUPT_STATUS_COMMAND_COMPLETE, COMPLETE)));
this->ClearInterrupt();
if (R_FAILED(result)) {
this->AbortTransaction();
}
R_RETURN(result);
} else if (sdmmc::ResultDeviceRemoved::Includes(result)) {
/* Otherwise, check if the device was removed. */
R_RETURN(result);
} else {
/* If the device wasn't removed, cancel our transaction. */
this->AbortTransaction();
R_THROW(sdmmc::ResultCommandCompleteSoftwareTimeout());
}
}
#else
{
/* Ensure that we control the registers. */
this->EnsureControl();
/* Wait while command is not complete. */
{
ManualTimer timer(CommandTimeoutMilliSeconds);
while (true) {
/* Check and clear the interrupt status. */
const auto result = this->CheckAndClearInterruptStatus(nullptr, reg::Encode(SD_REG_BITS_ENUM(NORMAL_INTERRUPT_STATUS_COMMAND_COMPLETE, COMPLETE)));
/* If we succeeded, we're done. */
if (R_SUCCEEDED(result)) {
R_SUCCEED();
} else if (sdmmc::ResultNoWaitedInterrupt::Includes(result)) {
/* Otherwise, if the wait for the interrupt isn't done, update the timer and check for timeout. */
if (!timer.Update()) {
this->AbortTransaction();
R_THROW(sdmmc::ResultCommandCompleteSoftwareTimeout());
}
} else {
/* Otherwise, we have a generic failure. */
this->AbortTransaction();
R_RETURN(result);
}
}
}
}
#endif
}
Result SdHostStandardController::WaitTransferComplete() {
#if defined(AMS_SDMMC_USE_OS_EVENTS)
{
/* Wait while transfer is not complete. */
while (true) {
/* Get the last block count. */
const u16 last_block_count = reg::Read(m_registers->block_count);
/* Wait for interrupt. */
Result result = this->WaitInterrupt(m_check_transfer_interval_ms);
if (R_SUCCEEDED(result)) {
/* If we succeeded, check/clear our interrupt status. */
volatile u16 normal_int_status;
result = this->CheckAndClearInterruptStatus(std::addressof(normal_int_status), reg::Encode(SD_REG_BITS_ENUM(NORMAL_INTERRUPT_STATUS_TRANSFER_COMPLETE, COMPLETE),
SD_REG_BITS_ENUM(NORMAL_INTERRUPT_STATUS_DMA_INTERRUPT, GENERATED)));
this->ClearInterrupt();
/* If the interrupt succeeded, check status. */
if (R_SUCCEEDED(result)) {
/* If the transfer is complete, we're done. */
if (reg::HasValue(normal_int_status, SD_REG_BITS_ENUM(NORMAL_INTERRUPT_STATUS_TRANSFER_COMPLETE, COMPLETE))) {
R_SUCCEED();
}
/* Otherwise, if a DMA interrupt was generated, advance to the next address. */
if (reg::HasValue(normal_int_status, SD_REG_BITS_ENUM(NORMAL_INTERRUPT_STATUS_DMA_INTERRUPT, GENERATED))) {
reg::Write(m_registers->adma_address, static_cast<u32>(m_next_sdma_address >> 0));
reg::Write(m_registers->upper_adma_address, static_cast<u32>(m_next_sdma_address >> BITSIZEOF(u32)));
m_next_sdma_address += SdmaBufferBoundary;
}
} else {
/* Abort the transaction. */
this->AbortTransaction();
R_RETURN(result);
}
R_RETURN(result);
} else if (sdmmc::ResultDeviceRemoved::Includes(result)) {
/* Otherwise, check if the device was removed. */
R_RETURN(result);
} else {
/* Otherwise, timeout if the transfer hasn't advanced. */
if (last_block_count != reg::Read(m_registers->block_count)) {
this->AbortTransaction();
R_THROW(sdmmc::ResultTransferCompleteSoftwareTimeout());
}
}
}
}
#else
{
/* Wait while transfer is not complete. */
while (true) {
/* Get the last block count. */
const u16 last_block_count = reg::Read(m_registers->block_count);
/* Wait until transfer times out. */
{
ManualTimer timer(m_check_transfer_interval_ms);
while (true) {
/* Check/clear our interrupt status. */
volatile u16 normal_int_status;
const auto result = this->CheckAndClearInterruptStatus(std::addressof(normal_int_status), reg::Encode(SD_REG_BITS_ENUM(NORMAL_INTERRUPT_STATUS_TRANSFER_COMPLETE, COMPLETE),
SD_REG_BITS_ENUM(NORMAL_INTERRUPT_STATUS_DMA_INTERRUPT, GENERATED)));
/* If the check succeeded, check status. */
if (R_SUCCEEDED(result)) {
/* If the transfer is complete, we're done. */
if (reg::HasValue(normal_int_status, SD_REG_BITS_ENUM(NORMAL_INTERRUPT_STATUS_TRANSFER_COMPLETE, COMPLETE))) {
R_SUCCEED();
}
/* Otherwise, if a DMA interrupt was generated, advance to the next address. */
if (reg::HasValue(normal_int_status, SD_REG_BITS_ENUM(NORMAL_INTERRUPT_STATUS_DMA_INTERRUPT, GENERATED))) {
reg::Write(m_registers->adma_address, static_cast<u32>(m_next_sdma_address >> 0));
reg::Write(m_registers->upper_adma_address, static_cast<u32>(m_next_sdma_address >> BITSIZEOF(u32)));
m_next_sdma_address += SdmaBufferBoundary;
}
} else if (sdmmc::ResultNoWaitedInterrupt::Includes(result)) {
/* Otherwise, if the wait for the interrupt isn't done, update the timer and check for timeout. */
if (!timer.Update()) {
/* Only timeout if the transfer hasn't advanced. */
if (last_block_count != reg::Read(m_registers->block_count)) {
this->AbortTransaction();
R_THROW(sdmmc::ResultTransferCompleteSoftwareTimeout());
}
break;
}
} else {
/* Otherwise, we have a generic failure. */
this->AbortTransaction();
R_RETURN(result);
}
}
}
}
}
#endif
}
Result SdHostStandardController::WaitWhileBusy() {
/* Ensure that we control the registers. */
this->EnsureControl();
/* Wait while busy. */
{
ManualTimer timer(BusyTimeoutMilliSeconds);
while (true) {
/* Check if the target has been removed. */
R_TRY(this->CheckRemoved());
/* If the DAT0 line signal is level high, we're done. */
if (reg::HasValue(m_registers->present_state, SD_REG_BITS_ENUM(PRESENT_STATE_DAT0_LINE_SIGNAL_LEVEL, HIGH))) {
R_SUCCEED();
}
/* Otherwise, check if we're timed out. */
if (!timer.Update()) {
this->AbortTransaction();
R_THROW(sdmmc::ResultBusySoftwareTimeout());
}
}
}
}
void SdHostStandardController::GetResponse(u32 *out_response, size_t response_size, ResponseType response_type) const {
/* Check that we can write the response. */
AMS_ABORT_UNLESS(out_response != nullptr);
/* Get the response appropriately. */
switch (response_type) {
case ResponseType_R1:
case ResponseType_R3:
case ResponseType_R6:
case ResponseType_R7:
/* 32-bit response. */
AMS_ABORT_UNLESS(response_size >= sizeof(u32) * 1);
out_response[0] = reg::Read(m_registers->response[0]);
break;
case ResponseType_R2:
/* 128-bit response. */
AMS_ABORT_UNLESS(response_size >= sizeof(u32) * 4);
out_response[0] = reg::Read(m_registers->response[0]);
out_response[1] = reg::Read(m_registers->response[1]);
out_response[2] = reg::Read(m_registers->response[2]);
out_response[3] = reg::Read(m_registers->response[3]);
break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
Result SdHostStandardController::IssueCommandWithDeviceClock(const Command *command, TransferData *xfer_data, u32 *out_num_transferred_blocks) {
/* Wait until we can issue the command. */
R_TRY(this->WaitWhileCommandInhibit((xfer_data != nullptr) || command->is_busy));
/* Configure for the transfer. */
u32 num_transferred_blocks = 0;
if (xfer_data != nullptr) {
/* Setup the transfer, and get the number of blocks. */
this->SetTransfer(std::addressof(num_transferred_blocks), xfer_data);
/* Ensure the device sees consistent data with the cpu. */
dd::FlushDataCache(xfer_data->buffer, xfer_data->block_size * num_transferred_blocks);
}
/* Issue the command with interrupt status enabled. */
{
this->EnableInterruptStatus();
ON_SCOPE_EXIT { this->DisableInterruptStatus(); };
/* Set the command. */
this->SetCommand(command, xfer_data != nullptr);
/* Wait for the command to complete. */
R_TRY(this->WaitCommandComplete());
/* Process any response. */
if (command->response_type != ResponseType_R0) {
m_last_response_type = command->response_type;
this->GetResponse(m_last_response, sizeof(m_last_response), m_last_response_type);
}
/* Wait for data to be transferred. */
if (xfer_data != nullptr) {
R_TRY(this->WaitTransferComplete());
}
}
/* If data was transferred, ensure we're in a consistent state. */
if (xfer_data != nullptr) {
/* Ensure the cpu sees consistent data with the device. */
if (xfer_data->transfer_direction == TransferDirection_ReadFromDevice) {
dd::InvalidateDataCache(xfer_data->buffer, xfer_data->block_size * num_transferred_blocks);
}
/* Set the number of transferred blocks. */
if (out_num_transferred_blocks != nullptr) {
*out_num_transferred_blocks = num_transferred_blocks;
}
/* Process stop transition command. */
m_last_stop_transmission_response = m_registers->response[3];
}
/* Wait until we're no longer busy. */
if (command->is_busy || (xfer_data != nullptr)) {
R_TRY(this->WaitWhileBusy());
}
R_SUCCEED();
}
Result SdHostStandardController::IssueStopTransmissionCommandWithDeviceClock(u32 *out_response) {
/* Wait until we can issue the command. */
R_TRY(this->WaitWhileCommandInhibit(false));
/* Issue the command with interrupt status enabled. */
constexpr ResponseType StopTransmissionCommandResponseType = ResponseType_R1;
{
this->EnableInterruptStatus();
ON_SCOPE_EXIT { this->DisableInterruptStatus(); };
/* Set the command. */
Command command(CommandIndex_StopTransmission, 0, StopTransmissionCommandResponseType, true);
this->SetCommand(std::addressof(command), false);
/* Wait for the command to complete. */
R_TRY(this->WaitCommandComplete());
}
/* Process response. */
this->GetResponse(out_response, sizeof(u32), StopTransmissionCommandResponseType);
/* Wait until we're done. */
R_TRY(this->WaitWhileBusy());
R_SUCCEED();
}
SdHostStandardController::SdHostStandardController(dd::PhysicalAddress registers_phys_addr, size_t registers_size) {
/* Translate the physical address to a address. */
const uintptr_t registers_addr = dd::QueryIoMapping(registers_phys_addr, registers_size);
/* Set registers. */
AMS_ABORT_UNLESS(registers_addr != 0);
m_registers = reinterpret_cast<SdHostStandardRegisters *>(registers_addr);
/* Reset DMA buffers, if we have any. */
#if defined(AMS_SDMMC_USE_DEVICE_VIRTUAL_ADDRESS)
this->ResetBufferInfos();
#endif
/* Clear removed event, if we have one. */
#if defined(AMS_SDMMC_USE_OS_EVENTS)
m_removed_event = nullptr;
#endif
/* Clear dma address. */
m_next_sdma_address = 0;
m_check_transfer_interval_ms = DefaultCheckTransferIntervalMilliSeconds;
/* Clear clock/power trackers. */
m_device_clock_frequency_khz = 0;
m_is_power_saving_enable = false;
m_is_device_clock_enable = false;
/* Clear last response. */
m_last_response_type = ResponseType_R0;
std::memset(m_last_response, 0, sizeof(m_last_response));
m_last_stop_transmission_response = 0;
}
void SdHostStandardController::Initialize() {
#if defined(AMS_SDMMC_USE_OS_EVENTS)
{
os::InitializeMultiWait(std::addressof(m_multi_wait));
AMS_ABORT_UNLESS(m_interrupt_event != nullptr);
os::InitializeMultiWaitHolder(std::addressof(m_interrupt_event_holder), m_interrupt_event);
os::LinkMultiWaitHolder(std::addressof(m_multi_wait), std::addressof(m_interrupt_event_holder));
if (m_removed_event != nullptr) {
os::InitializeMultiWaitHolder(std::addressof(m_removed_event_holder), m_removed_event);
os::LinkMultiWaitHolder(std::addressof(m_multi_wait), std::addressof(m_removed_event_holder));
}
}
#endif
}
void SdHostStandardController::Finalize() {
#if defined(AMS_SDMMC_USE_OS_EVENTS)
{
if (m_removed_event != nullptr) {
os::UnlinkMultiWaitHolder(std::addressof(m_removed_event_holder));
os::FinalizeMultiWaitHolder(std::addressof(m_removed_event_holder));
}
os::UnlinkMultiWaitHolder(std::addressof(m_interrupt_event_holder));
os::FinalizeMultiWaitHolder(std::addressof(m_interrupt_event_holder));
os::FinalizeMultiWait(std::addressof(m_multi_wait));
}
#endif
}
#if defined(AMS_SDMMC_USE_DEVICE_VIRTUAL_ADDRESS)
void SdHostStandardController::RegisterDeviceVirtualAddress(uintptr_t buffer, size_t buffer_size, ams::dd::DeviceVirtualAddress buffer_device_virtual_address) {
/* Find and set a free info. */
for (auto &info : m_buffer_infos) {
if (info.buffer_address == 0) {
info = {
.buffer_address = buffer,
.buffer_size = buffer_size,
.buffer_device_virtual_address = buffer_device_virtual_address,
};
return;
}
}
AMS_ABORT("Out of BufferInfos\n");
}
void SdHostStandardController::UnregisterDeviceVirtualAddress(uintptr_t buffer, size_t buffer_size, ams::dd::DeviceVirtualAddress buffer_device_virtual_address) {
/* Find and clear the buffer info. */
for (auto &info : m_buffer_infos) {
if (info.buffer_address == buffer) {
AMS_ABORT_UNLESS(info.buffer_size == buffer_size);
AMS_ABORT_UNLESS(info.buffer_device_virtual_address == buffer_device_virtual_address);
info.buffer_address = 0;
info.buffer_size = 0;
return;
}
}
AMS_ABORT("BufferInfo not found\n");
}
#endif
void SdHostStandardController::SetWorkBuffer(void *wb, size_t wb_size) {
AMS_UNUSED(wb, wb_size);
AMS_ABORT("WorkBuffer is not needed\n");
}
BusPower SdHostStandardController::GetBusPower() const {
/* Check if the bus has power. */
if (reg::HasValue(m_registers->power_control, SD_REG_BITS_ENUM(POWER_CONTROL_SD_BUS_POWER_FOR_VDD1, ON))) {
/* If it does, return the corresponding power. */
switch (reg::GetValue(m_registers->power_control, SD_REG_BITS_MASK(POWER_CONTROL_SD_BUS_VOLTAGE_SELECT_FOR_VDD1))) {
case SD_HOST_STANDARD_POWER_CONTROL_SD_BUS_VOLTAGE_SELECT_FOR_VDD1_1_8V:
return BusPower_1_8V;
case SD_HOST_STANDARD_POWER_CONTROL_SD_BUS_VOLTAGE_SELECT_FOR_VDD1_3_3V:
return BusPower_3_3V;
AMS_UNREACHABLE_DEFAULT_CASE();
}
} else {
/* It doesn't, so it's off. */
return BusPower_Off;
}
}
void SdHostStandardController::SetBusWidth(BusWidth bus_width) {
/* Check that we support the bus width. */
AMS_ABORT_UNLESS(this->IsSupportedBusWidth(bus_width));
/* Set the appropriate data transfer width. */
switch (bus_width) {
case BusWidth_1Bit:
reg::ReadWrite(m_registers->host_control, SD_REG_BITS_ENUM(HOST_CONTROL_DATA_TRANSFER_WIDTH, ONE_BIT));
reg::ReadWrite(m_registers->host_control, SD_REG_BITS_ENUM(HOST_CONTROL_EXTENDED_DATA_TRANSFER_WIDTH, USE_DATA_TRANSFER_WIDTH));
break;
case BusWidth_4Bit:
reg::ReadWrite(m_registers->host_control, SD_REG_BITS_ENUM(HOST_CONTROL_DATA_TRANSFER_WIDTH, FOUR_BIT));
reg::ReadWrite(m_registers->host_control, SD_REG_BITS_ENUM(HOST_CONTROL_EXTENDED_DATA_TRANSFER_WIDTH, USE_DATA_TRANSFER_WIDTH));
break;
case BusWidth_8Bit:
reg::ReadWrite(m_registers->host_control, SD_REG_BITS_ENUM(HOST_CONTROL_EXTENDED_DATA_TRANSFER_WIDTH, EIGHT_BIT));
break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
BusWidth SdHostStandardController::GetBusWidth() const {
/* Check if the bus is using eight-bit extended data transfer. */
if (reg::HasValue(m_registers->host_control, SD_REG_BITS_ENUM(HOST_CONTROL_EXTENDED_DATA_TRANSFER_WIDTH, EIGHT_BIT))) {
return BusWidth_8Bit;
} else {
/* Bus is configured as USE_DATA_TRANSFER_WIDTH, so check if it's four bit. */
if (reg::HasValue(m_registers->host_control, SD_REG_BITS_ENUM(HOST_CONTROL_DATA_TRANSFER_WIDTH, FOUR_BIT))) {
return BusWidth_4Bit;
} else {
return BusWidth_1Bit;
}
}
}
void SdHostStandardController::SetPowerSaving(bool en) {
/* Set whether we're power saving enable. */
m_is_power_saving_enable = en;
/* Configure accordingly. */
if (m_is_power_saving_enable) {
/* We want to disable SD clock if it's enabled. */
if (reg::HasValue(m_registers->clock_control, SD_REG_BITS_ENUM(CLOCK_CONTROL_SD_CLOCK_ENABLE, ENABLE))) {
reg::ReadWrite(m_registers->clock_control, SD_REG_BITS_ENUM(CLOCK_CONTROL_SD_CLOCK_ENABLE, DISABLE));
}
} else {
/* We want to enable SD clock if it's disabled and we're supposed to enable device clock. */
if (m_is_device_clock_enable && reg::HasValue(m_registers->clock_control, SD_REG_BITS_ENUM(CLOCK_CONTROL_SD_CLOCK_ENABLE, DISABLE))) {
reg::ReadWrite(m_registers->clock_control, SD_REG_BITS_ENUM(CLOCK_CONTROL_SD_CLOCK_ENABLE, ENABLE));
}
}
}
void SdHostStandardController::EnableDeviceClock() {
/* If we're not in power-saving mode and the device clock is disabled, enable it. */
if (!m_is_power_saving_enable && reg::HasValue(m_registers->clock_control, SD_REG_BITS_ENUM(CLOCK_CONTROL_SD_CLOCK_ENABLE, DISABLE))) {
reg::ReadWrite(m_registers->clock_control, SD_REG_BITS_ENUM(CLOCK_CONTROL_SD_CLOCK_ENABLE, ENABLE));
}
m_is_device_clock_enable = true;
}
void SdHostStandardController::DisableDeviceClock() {
/* Unconditionally disable the device clock. */
m_is_device_clock_enable = false;
reg::ReadWrite(m_registers->clock_control, SD_REG_BITS_ENUM(CLOCK_CONTROL_SD_CLOCK_ENABLE, DISABLE));
}
void SdHostStandardController::ChangeCheckTransferInterval(u32 ms) {
m_check_transfer_interval_ms = ms;
}
void SdHostStandardController::SetDefaultCheckTransferInterval() {
m_check_transfer_interval_ms = DefaultCheckTransferIntervalMilliSeconds;
}
Result SdHostStandardController::IssueCommand(const Command *command, TransferData *xfer_data, u32 *out_num_transferred_blocks) {
/* We need to have device clock enabled to issue commands. */
AMS_ABORT_UNLESS(m_is_device_clock_enable);
/* Check if we need to temporarily re-enable the device clock. */
const bool clock_disabled = reg::HasValue(m_registers->clock_control, SD_REG_BITS_ENUM(CLOCK_CONTROL_SD_CLOCK_ENABLE, DISABLE));
/* Ensure that the clock is enabled and the device is usable for the period we're using it. */
if (clock_disabled) {
/* Turn on the clock. */
reg::ReadWrite(m_registers->clock_control, SD_REG_BITS_ENUM(CLOCK_CONTROL_SD_CLOCK_ENABLE, ENABLE));
/* Ensure that our configuration takes. */
this->EnsureControl();
/* Wait 8 device clocks to be sure that it's usable. */
WaitClocks(8, m_device_clock_frequency_khz);
}
ON_SCOPE_EXIT { if (clock_disabled) { reg::ReadWrite(m_registers->clock_control, SD_REG_BITS_ENUM(CLOCK_CONTROL_SD_CLOCK_ENABLE, DISABLE)); } };
/* Issue the command. */
{
/* After we issue the command, we need to wait 8 device clocks. */
ON_SCOPE_EXIT { WaitClocks(8, m_device_clock_frequency_khz); };
R_RETURN(this->IssueCommandWithDeviceClock(command, xfer_data, out_num_transferred_blocks));
}
}
Result SdHostStandardController::IssueStopTransmissionCommand(u32 *out_response) {
/* We need to have device clock enabled to issue commands. */
AMS_ABORT_UNLESS(m_is_device_clock_enable);
/* Check if we need to temporarily re-enable the device clock. */
const bool clock_disabled = reg::HasValue(m_registers->clock_control, SD_REG_BITS_ENUM(CLOCK_CONTROL_SD_CLOCK_ENABLE, DISABLE));
/* Ensure that the clock is enabled and the device is usable for the period we're using it. */
if (clock_disabled) {
/* Turn on the clock. */
reg::ReadWrite(m_registers->clock_control, SD_REG_BITS_ENUM(CLOCK_CONTROL_SD_CLOCK_ENABLE, ENABLE));
/* Ensure that our configuration takes. */
this->EnsureControl();
/* Wait 8 device clocks to be sure that it's usable. */
WaitClocks(8, m_device_clock_frequency_khz);
}
ON_SCOPE_EXIT { if (clock_disabled) { reg::ReadWrite(m_registers->clock_control, SD_REG_BITS_ENUM(CLOCK_CONTROL_SD_CLOCK_ENABLE, DISABLE)); } };
/* Issue the command. */
{
/* After we issue the command, we need to wait 8 device clocks. */
ON_SCOPE_EXIT { WaitClocks(8, m_device_clock_frequency_khz); };
R_RETURN(this->IssueStopTransmissionCommandWithDeviceClock(out_response));
}
}
void SdHostStandardController::GetLastResponse(u32 *out_response, size_t response_size, ResponseType response_type) const {
/* Check that we can get the response. */
AMS_ABORT_UNLESS(out_response != nullptr);
AMS_ABORT_UNLESS(response_type == m_last_response_type);
/* Get the response appropriately. */
switch (response_type) {
case ResponseType_R1:
case ResponseType_R3:
case ResponseType_R6:
case ResponseType_R7:
/* 32-bit response. */
AMS_ABORT_UNLESS(response_size >= sizeof(u32) * 1);
out_response[0] = m_last_response[0];
break;
case ResponseType_R2:
/* 128-bit response. */
AMS_ABORT_UNLESS(response_size >= sizeof(u32) * 4);
out_response[0] = m_last_response[0];
out_response[1] = m_last_response[1];
out_response[2] = m_last_response[2];
out_response[3] = m_last_response[3];
break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
void SdHostStandardController::GetLastStopTransmissionResponse(u32 *out_response, size_t response_size) const {
/* Check that we can get the response. */
AMS_ABORT_UNLESS(out_response != nullptr);
AMS_ABORT_UNLESS(response_size >= sizeof(u32));
/* Get the response. */
out_response[0] = m_last_stop_transmission_response;
}
}
| 48,732
|
C++
|
.cpp
| 876
| 42.332192
| 199
| 0.592749
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,061
|
sdmmc_sd_card_device_accessor.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/sdmmc/impl/sdmmc_sd_card_device_accessor.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if defined(ATMOSPHERE_IS_STRATOSPHERE)
#include <stratosphere.hpp>
#elif defined(ATMOSPHERE_IS_MESOSPHERE)
#include <mesosphere.hpp>
#elif defined(ATMOSPHERE_IS_EXOSPHERE)
#include <exosphere.hpp>
#else
#include <vapours.hpp>
#endif
#include "sdmmc_sd_card_device_accessor.hpp"
#include "sdmmc_timer.hpp"
namespace ams::sdmmc::impl {
#if defined(AMS_SDMMC_THREAD_SAFE)
#define AMS_SDMMC_LOCK_SD_CARD_DEVICE_MUTEX() std::scoped_lock lk(m_sd_card_device.m_device_mutex)
#else
#define AMS_SDMMC_LOCK_SD_CARD_DEVICE_MUTEX()
#endif
#if defined(AMS_SDMMC_USE_SD_CARD_DETECTOR)
#define AMS_SDMMC_CHECK_SD_CARD_REMOVED() R_UNLESS(!m_sd_card_device.IsRemoved(), sdmmc::ResultDeviceRemoved())
#else
#define AMS_SDMMC_CHECK_SD_CARD_REMOVED()
#endif
namespace {
constexpr inline u32 OcrCardPowerUpStatus = (1 << 31);
constexpr inline u32 OcrCardCapacityStatus = (1 << 30);
constexpr inline u32 OcrSwitchingTo1_8VAccepted = (1 << 24);
constexpr bool IsLessThanSpecification1_1(const u8 *scr) {
AMS_ABORT_UNLESS(scr != nullptr);
const u8 sd_spec = scr[0] & 0xF;
return sd_spec < 1;
}
constexpr u32 GetSendOpCmdArgument(bool spec_under_2, bool uhs_i_supported) {
const u32 hcs = !spec_under_2 ? (1u << 30) : (0u << 30);
const u32 xpc = !spec_under_2 ? (1u << 28) : (0u << 28);
const u32 s18r = (!spec_under_2 && uhs_i_supported) ? (1u << 24) : (0u << 24);
return hcs | xpc | s18r | 0x00100000u;
}
constexpr bool IsLessThanCsdVersion2(const u8 *csd) {
AMS_ABORT_UNLESS(csd != nullptr);
/* Check whether CSD_STRUCTURE is 0. */
return ((csd[14] & 0xC0) >> 6) == 0;
}
constexpr u32 GetMemoryCapacityFromCsd(const u16 *csd) {
AMS_ABORT_UNLESS(csd != nullptr);
/* Get CSIZE, convert appropriately. */
const u32 csize = (static_cast<u32>(csd[3] & 0x3FFF) << 8) | (static_cast<u32>(csd[2] & 0xFF00) >> 8);
return (1 + csize) << 10;
}
constexpr u8 GetSdBusWidths(const u8 *scr) {
AMS_ABORT_UNLESS(scr != nullptr);
return scr[1] & 0xF;
}
constexpr bool IsSupportedBusWidth4Bit(u8 sd_bw) {
return (sd_bw & 0x4) != 0;
}
constexpr bool IsSupportedAccessMode(const u8 *status, SwitchFunctionAccessMode access_mode) {
AMS_ABORT_UNLESS(status != nullptr);
return (status[13] & (1u << access_mode)) != 0;
}
constexpr u8 GetAccessModeFromFunctionSelection(const u8 *status) {
AMS_ABORT_UNLESS(status != nullptr);
return (status[16] & 0xF);
}
constexpr bool IsAccessModeInFunctionSelection(const u8 *status, SwitchFunctionAccessMode mode) {
return GetAccessModeFromFunctionSelection(status) == static_cast<u8>(mode);
}
constexpr u16 GetMaximumCurrentConsumption(const u8 *status) {
AMS_ABORT_UNLESS(status != nullptr);
return (static_cast<u16>(status[0]) << 8) |
(static_cast<u16>(status[1]) << 0);
}
constexpr u32 GetSizeOfProtectedArea(const u8 *sd_status) {
return (static_cast<u32>(sd_status[4]) << 24) |
(static_cast<u32>(sd_status[5]) << 16) |
(static_cast<u32>(sd_status[6]) << 8) |
(static_cast<u32>(sd_status[7]) << 0);
}
Result GetCurrentSpeedMode(SpeedMode *out_sm, const u8 *status, bool is_uhs_i) {
AMS_ABORT_UNLESS(out_sm != nullptr);
/* Get the access mode. */
switch (static_cast<SwitchFunctionAccessMode>(GetAccessModeFromFunctionSelection(status))) {
case SwitchFunctionAccessMode_Default:
if (is_uhs_i) {
*out_sm = SpeedMode_SdCardSdr12;
} else {
*out_sm = SpeedMode_SdCardDefaultSpeed;
}
break;
case SwitchFunctionAccessMode_HighSpeed:
if (is_uhs_i) {
*out_sm = SpeedMode_SdCardSdr25;
} else {
*out_sm = SpeedMode_SdCardHighSpeed;
}
break;
case SwitchFunctionAccessMode_Sdr50:
*out_sm = SpeedMode_SdCardSdr50;
break;
case SwitchFunctionAccessMode_Sdr104:
*out_sm = SpeedMode_SdCardSdr104;
break;
case SwitchFunctionAccessMode_Ddr50:
*out_sm = SpeedMode_SdCardDdr50;
break;
default:
R_THROW(sdmmc::ResultUnexpectedSdCardSwitchFunctionStatus());
}
R_SUCCEED();
}
}
void SdCardDevice::SetOcrAndHighCapacity(u32 ocr) {
/* Set ocr. */
BaseDevice::SetOcr(ocr);
/* Set high capacity. */
BaseDevice::SetHighCapacity((ocr & OcrCardCapacityStatus) != 0);
}
#if defined(AMS_SDMMC_USE_SD_CARD_DETECTOR)
void SdCardDeviceAccessor::RemovedCallback() {
/* Signal that the device was removed. */
m_sd_card_device.SignalRemovedEvent();
/* Acquire exclusive access to the device. */
AMS_SDMMC_LOCK_SD_CARD_DEVICE_MUTEX();
/* Shut down. */
BaseDeviceAccessor::GetHostController()->Shutdown();
}
#endif
Result SdCardDeviceAccessor::IssueCommandSendRelativeAddr(u16 *out_rca) const {
/* Issue the command. */
constexpr ResponseType CommandResponseType = ResponseType_R6;
Command command(CommandIndex_SendRelativeAddr, 0, CommandResponseType, false);
IHostController *hc = BaseDeviceAccessor::GetHostController();
R_TRY(hc->IssueCommand(std::addressof(command)));
/* Get the response. */
u32 resp;
hc->GetLastResponse(std::addressof(resp), sizeof(resp), CommandResponseType);
/* Set the output rca. */
AMS_ABORT_UNLESS(out_rca != nullptr);
*out_rca = static_cast<u16>(resp >> 16);
R_SUCCEED();
}
Result SdCardDeviceAccessor::IssueCommandSendIfCond() const {
/* Get the argument. */
constexpr u32 SendIfCommandArgument = 0x01AAu;
constexpr u32 SendIfCommandArgumentMask = 0x0FFFu;
/* Issue the command. */
constexpr ResponseType CommandResponseType = ResponseType_R7;
Command command(CommandIndex_SendIfCond, SendIfCommandArgument, CommandResponseType, false);
IHostController *hc = BaseDeviceAccessor::GetHostController();
R_TRY(hc->IssueCommand(std::addressof(command)));
/* Get the response. */
u32 resp;
hc->GetLastResponse(std::addressof(resp), sizeof(resp), CommandResponseType);
/* Verify that our argument was returned to us. */
R_UNLESS((resp & SendIfCommandArgumentMask) == (SendIfCommandArgument & SendIfCommandArgumentMask), sdmmc::ResultSdCardValidationError());
R_SUCCEED();
}
Result SdCardDeviceAccessor::IssueCommandCheckSupportedFunction(void *dst, size_t dst_size) const {
/* Validate the output buffer. */
AMS_ABORT_UNLESS(dst != nullptr);
AMS_ABORT_UNLESS(dst_size >= SdCardSwitchFunctionStatusSize);
/* Get the argument. */
constexpr u32 CheckSupportedFunctionArgument = 0x00FFFFFF;
/* Issue the command. */
constexpr ResponseType CommandResponseType = ResponseType_R1;
Command command(CommandIndex_Switch, CheckSupportedFunctionArgument, CommandResponseType, false);
TransferData xfer_data(dst, SdCardSwitchFunctionStatusSize, 1, TransferDirection_ReadFromDevice);
IHostController *hc = BaseDeviceAccessor::GetHostController();
R_TRY(hc->IssueCommand(std::addressof(command), std::addressof(xfer_data)));
/* Get the response. */
u32 resp;
hc->GetLastResponse(std::addressof(resp), sizeof(resp), CommandResponseType);
R_TRY(m_sd_card_device.CheckDeviceStatus(resp));
R_SUCCEED();
}
Result SdCardDeviceAccessor::IssueCommandSwitchAccessMode(void *dst, size_t dst_size, bool set_function, SwitchFunctionAccessMode access_mode) const {
/* Validate the output buffer. */
AMS_ABORT_UNLESS(dst != nullptr);
AMS_ABORT_UNLESS(dst_size >= SdCardSwitchFunctionStatusSize);
/* Get the argument. */
const u32 arg = (set_function ? (1u << 31) : (0u << 31)) | 0x00FFFFF0 | static_cast<u32>(access_mode);
/* Issue the command. */
constexpr ResponseType CommandResponseType = ResponseType_R1;
Command command(CommandIndex_Switch, arg, CommandResponseType, false);
TransferData xfer_data(dst, SdCardSwitchFunctionStatusSize, 1, TransferDirection_ReadFromDevice);
IHostController *hc = BaseDeviceAccessor::GetHostController();
R_TRY(hc->IssueCommand(std::addressof(command), std::addressof(xfer_data)));
/* Get the response. */
u32 resp;
hc->GetLastResponse(std::addressof(resp), sizeof(resp), CommandResponseType);
R_TRY(m_sd_card_device.CheckDeviceStatus(resp));
R_SUCCEED();
}
Result SdCardDeviceAccessor::IssueCommandVoltageSwitch() const {
/* Issue the command. */
R_TRY(BaseDeviceAccessor::IssueCommandAndCheckR1(CommandIndex_VoltageSwitch, 0, false, DeviceState_Ready));
R_SUCCEED();
}
Result SdCardDeviceAccessor::IssueCommandAppCmd(DeviceState expected_state, u32 ignore_mask) const {
/* Get arg. */
const u32 arg = static_cast<u32>(m_sd_card_device.GetRca()) << 16;
/* Issue the command. */
constexpr ResponseType CommandResponseType = ResponseType_R1;
Command command(CommandIndex_AppCmd, arg, CommandResponseType, false);
IHostController *hc = BaseDeviceAccessor::GetHostController();
R_TRY(hc->IssueCommand(std::addressof(command)));
/* Get the response. */
u32 resp;
hc->GetLastResponse(std::addressof(resp), sizeof(resp), CommandResponseType);
/* Mask out the ignored status bits. */
if (ignore_mask != 0) {
resp &= ~ignore_mask;
}
/* Check the device status. */
R_TRY(m_sd_card_device.CheckDeviceStatus(resp));
/* Check the app command bit. */
R_UNLESS((resp & DeviceStatus_AppCmd) != 0, sdmmc::ResultUnexpectedSdCardAcmdDisabled());
/* Check the device state. */
if (expected_state != DeviceState_Unknown) {
R_UNLESS(m_sd_card_device.GetDeviceState(resp) == expected_state, sdmmc::ResultUnexpectedDeviceState());
}
R_SUCCEED();
}
Result SdCardDeviceAccessor::IssueCommandSetBusWidth4Bit() const {
/* Issue the application command. */
constexpr u32 Arg = 0x2;
R_TRY(BaseDeviceAccessor::IssueCommandAndCheckR1(SdApplicationCommandIndex_SetBusWidth, Arg, false, DeviceState_Tran));
R_SUCCEED();
}
Result SdCardDeviceAccessor::IssueCommandSdStatus(void *dst, size_t dst_size) const {
/* Validate the output buffer. */
AMS_ABORT_UNLESS(dst != nullptr);
AMS_ABORT_UNLESS(dst_size >= SdCardSdStatusSize);
/* Issue the application command. */
constexpr ResponseType CommandResponseType = ResponseType_R1;
Command command(SdApplicationCommandIndex_SdStatus, 0, CommandResponseType, false);
TransferData xfer_data(dst, SdCardSdStatusSize, 1, TransferDirection_ReadFromDevice);
IHostController *hc = BaseDeviceAccessor::GetHostController();
R_TRY(hc->IssueCommand(std::addressof(command), std::addressof(xfer_data)));
/* Get the response. */
u32 resp;
hc->GetLastResponse(std::addressof(resp), sizeof(resp), CommandResponseType);
R_TRY(m_sd_card_device.CheckDeviceStatus(resp));
R_SUCCEED();
}
Result SdCardDeviceAccessor::IssueCommandSendOpCond(u32 *out_ocr, bool spec_under_2, bool uhs_i_supported) const {
/* Get the argument. */
const u32 arg = GetSendOpCmdArgument(spec_under_2, uhs_i_supported);
/* Issue the application command. */
constexpr ResponseType CommandResponseType = ResponseType_R3;
Command command(SdApplicationCommandIndex_SdSendOpCond, arg, CommandResponseType, false);
IHostController *hc = BaseDeviceAccessor::GetHostController();
R_TRY(hc->IssueCommand(std::addressof(command)));
/* Get the response. */
hc->GetLastResponse(out_ocr, sizeof(u32), CommandResponseType);
R_SUCCEED();
}
Result SdCardDeviceAccessor::IssueCommandClearCardDetect() const {
/* Issue the application command. */
R_TRY(BaseDeviceAccessor::IssueCommandAndCheckR1(SdApplicationCommandIndex_SetClearCardDetect, 0, false, DeviceState_Tran));
R_SUCCEED();
}
Result SdCardDeviceAccessor::IssueCommandSendScr(void *dst, size_t dst_size) const {
/* Validate the output buffer. */
AMS_ABORT_UNLESS(dst != nullptr);
AMS_ABORT_UNLESS(dst_size >= SdCardScrSize);
/* Issue the application command. */
constexpr ResponseType CommandResponseType = ResponseType_R1;
Command command(SdApplicationCommandIndex_SendScr, 0, CommandResponseType, false);
TransferData xfer_data(dst, SdCardScrSize, 1, TransferDirection_ReadFromDevice);
IHostController *hc = BaseDeviceAccessor::GetHostController();
R_TRY(hc->IssueCommand(std::addressof(command), std::addressof(xfer_data)));
/* Get the response. */
u32 resp;
hc->GetLastResponse(std::addressof(resp), sizeof(resp), CommandResponseType);
R_TRY(m_sd_card_device.CheckDeviceStatus(resp));
R_SUCCEED();
}
Result SdCardDeviceAccessor::EnterUhsIMode() {
/* Send voltage switch command. */
R_TRY(this->IssueCommandVoltageSwitch());
/* Switch to sdr12. */
R_TRY(BaseDeviceAccessor::GetHostController()->SwitchToSdr12());
R_SUCCEED();
}
Result SdCardDeviceAccessor::ChangeToReadyState(bool spec_under_2, bool uhs_i_supported) {
/* Decide on an ignore mask. */
u32 ignore_mask = spec_under_2 ? static_cast<u32>(DeviceStatus_IllegalCommand) : 0u;
/* Be prepared to wait up to 3.0 seconds to change state. */
ManualTimer timer(3000);
while (true) {
/* We want to get ocr, which requires our sending an application command. */
R_TRY(this->IssueCommandAppCmd(DeviceState_Unknown, ignore_mask));
ignore_mask = 0;
/* Get the ocr, and check if we're done. */
u32 ocr;
R_TRY(this->IssueCommandSendOpCond(std::addressof(ocr), spec_under_2, uhs_i_supported));
if ((ocr & OcrCardPowerUpStatus) != 0) {
m_sd_card_device.SetOcrAndHighCapacity(ocr);
/* Handle uhs i mode. */
m_sd_card_device.SetUhsIMode(false);
if (uhs_i_supported && ((ocr & OcrSwitchingTo1_8VAccepted) != 0)) {
R_TRY(this->EnterUhsIMode());
m_sd_card_device.SetUhsIMode(true);
}
R_SUCCEED();
}
/* Check if we've timed out. */
R_UNLESS(timer.Update(), sdmmc::ResultSdCardInitializationSoftwareTimeout());
/* Try again in 1ms. */
WaitMicroSeconds(1000);
}
}
Result SdCardDeviceAccessor::ChangeToStbyStateAndGetRca() {
/* Be prepared to wait up to 1.0 seconds to change state. */
ManualTimer timer(1000);
while (true) {
/* Get rca. */
u16 rca;
R_TRY(this->IssueCommandSendRelativeAddr(std::addressof(rca)));
if (rca != 0) {
m_sd_card_device.SetRca(rca);
R_SUCCEED();
}
/* Check if we've timed out. */
R_UNLESS(timer.Update(), sdmmc::ResultSdCardGetValidRcaSoftwareTimeout());
}
}
Result SdCardDeviceAccessor::SetMemoryCapacity(const void *csd) {
if (IsLessThanCsdVersion2(static_cast<const u8 *>(csd))) {
R_TRY(m_sd_card_device.SetLegacyMemoryCapacity());
} else {
AMS_ABORT_UNLESS(util::IsAligned(reinterpret_cast<uintptr_t>(csd), alignof(u16)));
m_sd_card_device.SetMemoryCapacity(GetMemoryCapacityFromCsd(static_cast<const u16 *>(csd)));
}
R_SUCCEED();
}
Result SdCardDeviceAccessor::GetScr(void *dst, size_t dst_size) const {
/* Issue the application command. */
R_TRY(this->IssueCommandAppCmd(DeviceState_Tran));
R_TRY(this->IssueCommandSendScr(dst, dst_size));
R_SUCCEED();
}
Result SdCardDeviceAccessor::ExtendBusWidth(BusWidth max_bw, u8 sd_bw) {
/* If the maximum bus width is 1bit, we can't extend. */
R_SUCCEED_IF(max_bw == BusWidth_1Bit);
/* If 4bit mode isn't supported, we can't extend. */
R_SUCCEED_IF(!IsSupportedBusWidth4Bit(sd_bw));
/* If the host controller doesn't support 4bit mode, we can't extend. */
IHostController *hc = BaseDeviceAccessor::GetHostController();
R_SUCCEED_IF(!hc->IsSupportedBusWidth(BusWidth_4Bit));
/* Issue the application command to change to 4bit mode. */
R_TRY(this->IssueCommandAppCmd(DeviceState_Tran));
R_TRY(this->IssueCommandSetBusWidth4Bit());
/* Set the host controller's bus width. */
hc->SetBusWidth(BusWidth_4Bit);
R_SUCCEED();
}
Result SdCardDeviceAccessor::SwitchAccessMode(SwitchFunctionAccessMode access_mode, void *wb, size_t wb_size) {
/* Issue command to check if we can switch access mode. */
R_TRY(this->IssueCommandSwitchAccessMode(wb, wb_size, false, access_mode));
R_UNLESS(IsAccessModeInFunctionSelection(static_cast<const u8 *>(wb), access_mode), sdmmc::ResultSdCardCannotSwitchAccessMode());
/* Check if we can accept the resulting current consumption. */
constexpr u16 AcceptableCurrentLimit = 800; /* mA */
R_UNLESS(GetMaximumCurrentConsumption(static_cast<const u8 *>(wb)) < AcceptableCurrentLimit, sdmmc::ResultSdCardUnacceptableCurrentConsumption());
/* Switch the access mode. */
R_TRY(this->IssueCommandSwitchAccessMode(wb, wb_size, true, access_mode));
R_UNLESS(IsAccessModeInFunctionSelection(static_cast<const u8 *>(wb), access_mode), sdmmc::ResultSdCardFailedSwitchAccessMode());
R_SUCCEED();
}
Result SdCardDeviceAccessor::ExtendBusSpeedAtUhsIMode(SpeedMode max_sm, void *wb, size_t wb_size) {
/* Check that we're in 4bit bus mode. */
IHostController *hc = BaseDeviceAccessor::GetHostController();
R_UNLESS(hc->GetBusWidth() == BusWidth_4Bit, sdmmc::ResultSdCardNot4BitBusWidthAtUhsIMode());
/* Determine what speed mode/access mode we should switch to. */
R_TRY(this->IssueCommandCheckSupportedFunction(wb, wb_size));
SwitchFunctionAccessMode target_am;
SpeedMode target_sm;
if (max_sm == SpeedMode_SdCardSdr104 && IsSupportedAccessMode(static_cast<const u8 *>(wb), SwitchFunctionAccessMode_Sdr104)) {
target_am = SwitchFunctionAccessMode_Sdr104;
target_sm = SpeedMode_SdCardSdr104;
} else if ((max_sm == SpeedMode_SdCardSdr104 || max_sm == SpeedMode_SdCardSdr50) && IsSupportedAccessMode(static_cast<const u8 *>(wb), SwitchFunctionAccessMode_Sdr50)) {
target_am = SwitchFunctionAccessMode_Sdr50;
target_sm = SpeedMode_SdCardSdr50;
} else {
R_THROW(sdmmc::ResultSdCardNotSupportSdr104AndSdr50());
}
/* Switch the access mode. */
R_TRY(this->SwitchAccessMode(target_am, wb, wb_size));
/* Set the host controller speed mode and perform tuning using command index 19. */
R_TRY(hc->SetSpeedMode(target_sm));
R_TRY(hc->Tuning(target_sm, 19));
/* Check status. */
R_TRY(BaseDeviceAccessor::IssueCommandSendStatus());
R_SUCCEED();
}
Result SdCardDeviceAccessor::ExtendBusSpeedAtNonUhsIMode(SpeedMode max_sm, bool spec_under_1_1, void *wb, size_t wb_size) {
/* If the maximum speed is default speed, we have nothing to do. */
R_SUCCEED_IF(max_sm == SpeedMode_SdCardDefaultSpeed);
/* Otherwise, if the spec is under 1.1, we have nothing to do. */
R_SUCCEED_IF(spec_under_1_1);
/* Otherwise, Check if high speed is supported. */
R_TRY(this->IssueCommandCheckSupportedFunction(wb, wb_size));
R_SUCCEED_IF(!IsSupportedAccessMode(static_cast<const u8 *>(wb), SwitchFunctionAccessMode_HighSpeed));
/* Switch the access mode. */
R_TRY(this->SwitchAccessMode(SwitchFunctionAccessMode_HighSpeed, wb, wb_size));
/* Check status. */
R_TRY(BaseDeviceAccessor::IssueCommandSendStatus());
/* Set the host controller speed mode. */
R_TRY(BaseDeviceAccessor::GetHostController()->SetSpeedMode(SpeedMode_SdCardHighSpeed));
R_SUCCEED();
}
Result SdCardDeviceAccessor::GetSdStatus(void *dst, size_t dst_size) const {
/* Issue the application command. */
R_TRY(this->IssueCommandAppCmd(DeviceState_Tran));
R_TRY(this->IssueCommandSdStatus(dst, dst_size));
R_SUCCEED();
}
void SdCardDeviceAccessor::TryDisconnectDat3PullUpResistor() const {
/* Issue the application command to clear card detect. */
/* NOTE: Nintendo accepts a failure. */
if (R_SUCCEEDED(this->IssueCommandAppCmd(DeviceState_Tran))) {
/* NOTE: Nintendo does not check the result of this. */
this->IssueCommandClearCardDetect();
}
/* NOTE: Nintendo does not check the result of this. */
BaseDeviceAccessor::IssueCommandSendStatus();
}
Result SdCardDeviceAccessor::StartupSdCardDevice(BusWidth max_bw, SpeedMode max_sm, void *wb, size_t wb_size) {
/* Start up the host controller. */
IHostController *hc = BaseDeviceAccessor::GetHostController();
R_TRY(hc->Startup(BusPower_3_3V, BusWidth_1Bit, SpeedMode_SdCardIdentification, false));
/* Wait 1ms for configuration to take. */
WaitMicroSeconds(1000);
/* Wait an additional 74 clocks for configuration to take. */
WaitClocks(74, hc->GetDeviceClockFrequencyKHz());
/* Go to idle state. */
R_TRY(BaseDeviceAccessor::IssueCommandGoIdleState());
/* Check whether the spec is under 2.0. */
bool spec_under_2 = false;
R_TRY_CATCH(this->IssueCommandSendIfCond()) {
R_CATCH(sdmmc::ResultResponseTimeoutError) { spec_under_2 = true; }
} R_END_TRY_CATCH;
/* Set the rca to 0. */
m_sd_card_device.SetRca(0);
/* Go to ready state. */
const bool can_use_uhs_i_mode = (max_bw != BusWidth_1Bit) && (max_sm == SpeedMode_SdCardSdr104 || max_sm == SpeedMode_SdCardSdr50);
const bool uhs_i_supported = hc->IsSupportedTuning() && hc->IsSupportedBusPower(BusPower_1_8V);
R_TRY(this->ChangeToReadyState(spec_under_2, can_use_uhs_i_mode && uhs_i_supported));
/* Get the CID. */
R_TRY(BaseDeviceAccessor::IssueCommandAllSendCid(wb, wb_size));
m_sd_card_device.SetCid(wb, wb_size);
/* Go to stby state and get the RCA. */
R_TRY(this->ChangeToStbyStateAndGetRca());
/* Get the CSD. */
R_TRY(BaseDeviceAccessor::IssueCommandSendCsd(wb, wb_size));
m_sd_card_device.SetCsd(wb, wb_size);
R_TRY(this->SetMemoryCapacity(wb));
/* Set the host controller speed mode to default if we're not in uhs i mode. */
if (!m_sd_card_device.IsUhsIMode()) {
R_TRY(hc->SetSpeedMode(SpeedMode_SdCardDefaultSpeed));
}
/* Issue select card command. */
R_TRY(BaseDeviceAccessor::IssueCommandSelectCard());
/* Set block length to sector size. */
R_TRY(BaseDeviceAccessor::IssueCommandSetBlockLenToSectorSize());
/* Try to disconnect dat3 pullup resistor. */
TryDisconnectDat3PullUpResistor();
/* Get the SCR. */
R_TRY(this->GetScr(wb, wb_size));
const u8 sd_bw = GetSdBusWidths(static_cast<const u8 *>(wb));
const bool spec_under_1_1 = IsLessThanSpecification1_1(static_cast<const u8 *>(wb));
/* Extend the bus width to the largest that we can. */
R_TRY(this->ExtendBusWidth(max_bw, sd_bw));
/* Extend the bus speed to as fast as we can. */
if (m_sd_card_device.IsUhsIMode()) {
R_TRY(this->ExtendBusSpeedAtUhsIMode(max_sm, wb, wb_size));
} else {
R_TRY(this->ExtendBusSpeedAtNonUhsIMode(max_sm, spec_under_1_1, wb, wb_size));
R_TRY(this->GetSdStatus(wb, wb_size));
}
/* Enable power saving. */
hc->SetPowerSaving(true);
R_SUCCEED();
}
Result SdCardDeviceAccessor::OnActivate() {
/* Define the possible startup parameters. */
constexpr const struct {
BusWidth bus_width;
SpeedMode speed_mode;
} StartupParameters[] = {
#if defined(AMS_SDMMC_ENABLE_SD_UHS_I)
{ BusWidth_4Bit, SpeedMode_SdCardSdr104 },
{ BusWidth_4Bit, SpeedMode_SdCardSdr104 },
{ BusWidth_4Bit, SpeedMode_SdCardHighSpeed },
{ BusWidth_4Bit, SpeedMode_SdCardDefaultSpeed },
{ BusWidth_1Bit, SpeedMode_SdCardHighSpeed },
#else
{ BusWidth_4Bit, SpeedMode_SdCardHighSpeed },
{ BusWidth_4Bit, SpeedMode_SdCardHighSpeed },
{ BusWidth_4Bit, SpeedMode_SdCardDefaultSpeed },
{ BusWidth_1Bit, SpeedMode_SdCardHighSpeed },
#endif
};
/* Try to start up with each set of parameters. */
Result result;
for (int i = 0; i < static_cast<int>(util::size(StartupParameters)); ++i) {
/* Alias the parameters. */
const auto ¶ms = StartupParameters[i];
/* Set our max bus width/speed mode. */
m_max_bus_width = params.bus_width;
m_max_speed_mode = params.speed_mode;
/* Try to start up the device. */
result = this->StartupSdCardDevice(m_max_bus_width, m_max_speed_mode, m_work_buffer, m_work_buffer_size);
if (R_SUCCEEDED(result)) {
/* If we previously failed to start up the device, log the error correction. */
if (i != 0) {
BaseDeviceAccessor::PushErrorLog(true, "S %d %d:0", m_max_bus_width, m_max_speed_mode);
BaseDeviceAccessor::IncrementNumActivationErrorCorrections();
}
R_SUCCEED();
}
/* Check if we were removed. */
AMS_SDMMC_CHECK_SD_CARD_REMOVED();
/* Log that our startup failed. */
BaseDeviceAccessor::PushErrorLog(false, "S %d %d:%X", m_max_bus_width, m_max_speed_mode, result.GetValue());
/* Shut down the host controller before we try to start up again. */
BaseDeviceAccessor::GetHostController()->Shutdown();
}
/* We failed to start up with all sets of parameters. */
/* Check the csd for errors. */
if (sdmmc::ResultUnexpectedDeviceCsdValue::Includes(result)) {
u32 csd[DeviceCsdSize / sizeof(u32)];
m_sd_card_device.GetCsd(csd, sizeof(csd));
BaseDeviceAccessor::PushErrorLog(false, "%06X%08X%08X%08X", csd[3] & 0x00FFFFFF, csd[2], csd[1], csd[0]);
}
BaseDeviceAccessor::PushErrorTimeStamp();
/* Check if we failed because the sd card is removed. */
#if defined(AMS_SDMMC_USE_SD_CARD_DETECTOR)
if (sdmmc::ResultCommunicationNotAttained::Includes(result)) {
WaitMicroSeconds(m_sd_card_detector->GetDebounceMilliSeconds() * 1000);
AMS_SDMMC_CHECK_SD_CARD_REMOVED();
}
#endif
R_RETURN(result);
}
Result SdCardDeviceAccessor::OnReadWrite(u32 sector_index, u32 num_sectors, void *buf, size_t buf_size, bool is_read) {
/* Do the read/write. */
const Result result = BaseDeviceAccessor::ReadWriteMultiple(sector_index, num_sectors, 0, buf, buf_size, is_read);
/* Check if we failed because the sd card is removed. */
#if defined(AMS_SDMMC_USE_SD_CARD_DETECTOR)
if (sdmmc::ResultCommunicationNotAttained::Includes(result)) {
WaitMicroSeconds(m_sd_card_detector->GetDebounceMilliSeconds() * 1000);
AMS_SDMMC_CHECK_SD_CARD_REMOVED();
}
#endif
R_RETURN(result);
}
Result SdCardDeviceAccessor::ReStartup() {
/* Shut down the host controller. */
BaseDeviceAccessor::GetHostController()->Shutdown();
/* Perform start up. */
Result result = this->StartupSdCardDevice(m_max_bus_width, m_max_speed_mode, m_work_buffer, m_work_buffer_size);
if (R_FAILED(result)) {
AMS_SDMMC_CHECK_SD_CARD_REMOVED();
BaseDeviceAccessor::PushErrorLog(false, "S %d %d:%X", m_max_bus_width, m_max_speed_mode, result.GetValue());
R_RETURN(result);
}
R_SUCCEED();
}
void SdCardDeviceAccessor::Initialize() {
/* Acquire exclusive access to the device. */
AMS_SDMMC_LOCK_SD_CARD_DEVICE_MUTEX();
/* If we've already initialized, we don't need to do anything. */
if (m_is_initialized) {
return;
}
/* Set the base device to our sd card device. */
BaseDeviceAccessor::SetDevice(std::addressof(m_sd_card_device));
/* Initialize. */
IHostController *hc = BaseDeviceAccessor::GetHostController();
#if defined(AMS_SDMMC_USE_SD_CARD_DETECTOR)
{
/* TODO: We probably want this (and other sd card detection stuff) to be conditional pcv control active. */
/* This will be a requirement to support sd card access with detector in stratosphere before PCV is alive. */
m_sd_card_device.InitializeRemovedEvent();
hc->PreSetRemovedEvent(m_sd_card_device.GetRemovedEvent());
CallbackInfo ci = {
.inserted_callback = nullptr,
.inserted_callback_arg = this,
.removed_callback = RemovedCallbackEntry,
.removed_callback_arg = this,
};
m_sd_card_detector->Initialize(std::addressof(ci));
}
#endif
hc->Initialize();
/* Mark ourselves as initialized. */
m_is_initialized = true;
}
void SdCardDeviceAccessor::Finalize() {
/* Acquire exclusive access to the device. */
AMS_SDMMC_LOCK_SD_CARD_DEVICE_MUTEX();
/* If we've already finalized, we don't need to do anything. */
if (!m_is_initialized) {
return;
}
m_is_initialized = false;
/* Deactivate the device. */
BaseDeviceAccessor::Deactivate();
/* Finalize the host controller. */
BaseDeviceAccessor::GetHostController()->Finalize();
/* Finalize the detector. */
#if defined(AMS_SDMMC_USE_SD_CARD_DETECTOR)
{
m_sd_card_detector->Finalize();
m_sd_card_device.FinalizeRemovedEvent();
}
#endif
}
Result SdCardDeviceAccessor::Activate() {
/* Activate the detector. */
#if defined(AMS_SDMMC_USE_SD_CARD_DETECTOR)
{
/* Acquire exclusive access to the device. */
AMS_SDMMC_LOCK_SD_CARD_DEVICE_MUTEX();
/* Check that we're awake. */
R_UNLESS(m_sd_card_device.IsAwake(), sdmmc::ResultNotAwakened());
/* Check that we're not already active. */
R_SUCCEED_IF(m_sd_card_device.IsActive());
/* Clear the removed event. */
m_sd_card_device.ClearRemovedEvent();
/* Check that the SD card is inserted. */
R_UNLESS(m_sd_card_detector->IsInserted(), sdmmc::ResultNoDevice());
}
#endif
/* Activate the base device. */
R_RETURN(BaseDeviceAccessor::Activate());
}
Result SdCardDeviceAccessor::GetSpeedMode(SpeedMode *out_speed_mode) const {
/* Check that we can write to output. */
AMS_ABORT_UNLESS(out_speed_mode != nullptr);
/* Acquire exclusive access to the device. */
AMS_SDMMC_LOCK_SD_CARD_DEVICE_MUTEX();
/* Check that we're accessible. */
R_TRY(m_sd_card_device.CheckAccessible());
/* Check whether we're specification 1 (and thus default speed). */
R_TRY(this->GetScr(m_work_buffer, m_work_buffer_size));
if (IsLessThanSpecification1_1(static_cast<const u8 *>(m_work_buffer))) {
*out_speed_mode = SpeedMode_SdCardDefaultSpeed;
R_SUCCEED();
}
/* Get the current speed mode. */
R_TRY(this->IssueCommandCheckSupportedFunction(m_work_buffer, m_work_buffer_size));
R_TRY(GetCurrentSpeedMode(out_speed_mode, static_cast<const u8 *>(m_work_buffer), m_sd_card_device.IsUhsIMode()));
R_SUCCEED();
}
void SdCardDeviceAccessor::PutSdCardToSleep() {
/* Acquire exclusive access to the device. */
AMS_SDMMC_LOCK_SD_CARD_DEVICE_MUTEX();
/* If the device isn't awake, we don't need to do anything. */
if (!m_sd_card_device.IsAwake()) {
return;
}
/* Put the device to sleep. */
m_sd_card_device.PutToSleep();
/* Put the detector to sleep. */
#if defined(AMS_SDMMC_USE_SD_CARD_DETECTOR)
m_sd_card_detector->PutToSleep();
#endif
/* If necessary, put the host controller to sleep. */
#if defined(AMS_SDMMC_USE_SD_CARD_DETECTOR)
if (m_sd_card_device.IsActive() && !m_sd_card_device.IsRemoved())
#else
if (m_sd_card_device.IsActive())
#endif
{
BaseDeviceAccessor::GetHostController()->PutToSleep();
}
}
void SdCardDeviceAccessor::AwakenSdCard() {
/* Acquire exclusive access to the device. */
AMS_SDMMC_LOCK_SD_CARD_DEVICE_MUTEX();
/* If the device is awake, we don't need to do anything. */
if (m_sd_card_device.IsAwake()) {
return;
}
/* Wake the host controller, if we need to.*/
bool force_det = false;
#if defined(AMS_SDMMC_USE_SD_CARD_DETECTOR)
if (m_sd_card_device.IsActive() && !m_sd_card_device.IsRemoved())
#else
if (m_sd_card_device.IsActive())
#endif
{
const Result result = BaseDeviceAccessor::GetHostController()->Awaken();
if (R_SUCCEEDED(result)) {
force_det = R_FAILED(BaseDeviceAccessor::IssueCommandSendStatus());
} else {
BaseDeviceAccessor::PushErrorLog(true, "A:%X", result.GetValue());
force_det = true;
}
}
/* Wake the detector. */
#if defined(AMS_SDMMC_USE_SD_CARD_DETECTOR)
m_sd_card_detector->Awaken(force_det);
#else
AMS_UNUSED(force_det);
#endif
/* Wake the device. */
m_sd_card_device.Awaken();
}
Result SdCardDeviceAccessor::GetSdCardScr(void *dst, size_t dst_size) const {
/* Acquire exclusive access to the device. */
AMS_SDMMC_LOCK_SD_CARD_DEVICE_MUTEX();
/* Check that we're accessible. */
R_TRY(m_sd_card_device.CheckAccessible());
/* Get the SCR. */
R_TRY(this->GetScr(dst, dst_size));
R_SUCCEED();
}
Result SdCardDeviceAccessor::GetSdCardSwitchFunctionStatus(void *dst, size_t dst_size, SdCardSwitchFunction switch_function) const {
/* Acquire exclusive access to the device. */
AMS_SDMMC_LOCK_SD_CARD_DEVICE_MUTEX();
/* Check that we're accessible. */
R_TRY(m_sd_card_device.CheckAccessible());
/* Check whether we're specification 1 (and thus can't switch). */
R_TRY(this->GetScr(dst, dst_size));
R_UNLESS(!IsLessThanSpecification1_1(static_cast<const u8 *>(dst)), sdmmc::ResultSdCardNotSupportSwitchFunctionStatus());
/* Get the status. */
if (switch_function == SdCardSwitchFunction_CheckSupportedFunction) {
R_TRY(this->IssueCommandCheckSupportedFunction(dst, dst_size));
} else {
SwitchFunctionAccessMode am;
switch (switch_function) {
case SdCardSwitchFunction_CheckDefault: am = SwitchFunctionAccessMode_Default; break;
case SdCardSwitchFunction_CheckHighSpeed: am = SwitchFunctionAccessMode_HighSpeed; break;
case SdCardSwitchFunction_CheckSdr50: am = SwitchFunctionAccessMode_Sdr50; break;
case SdCardSwitchFunction_CheckSdr104: am = SwitchFunctionAccessMode_Sdr104; break;
case SdCardSwitchFunction_CheckDdr50: am = SwitchFunctionAccessMode_Ddr50; break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
R_TRY(this->IssueCommandSwitchAccessMode(dst, dst_size, false, am));
}
R_SUCCEED();
}
Result SdCardDeviceAccessor::GetSdCardCurrentConsumption(u16 *out_current_consumption, SpeedMode speed_mode) const {
/* Acquire exclusive access to the device. */
AMS_SDMMC_LOCK_SD_CARD_DEVICE_MUTEX();
/* Check that we're accessible. */
R_TRY(m_sd_card_device.CheckAccessible());
/* Check whether we're specification 1 (and thus can't switch). */
R_TRY(this->GetScr(m_work_buffer, m_work_buffer_size));
R_UNLESS(!IsLessThanSpecification1_1(static_cast<const u8 *>(m_work_buffer)), sdmmc::ResultSdCardNotSupportSwitchFunctionStatus());
/* Determine the access mode. */
SwitchFunctionAccessMode am;
switch (speed_mode) {
case SpeedMode_SdCardSdr12:
case SpeedMode_SdCardDefaultSpeed:
am = SwitchFunctionAccessMode_Default;
break;
case SpeedMode_SdCardSdr25:
case SpeedMode_SdCardHighSpeed:
am = SwitchFunctionAccessMode_HighSpeed;
break;
case SpeedMode_SdCardSdr50:
am = SwitchFunctionAccessMode_Sdr50;
break;
case SpeedMode_SdCardSdr104:
am = SwitchFunctionAccessMode_Sdr104;
break;
case SpeedMode_SdCardDdr50:
am = SwitchFunctionAccessMode_Ddr50;
break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
/* Check that the mode is supported. */
R_TRY(this->IssueCommandSwitchAccessMode(m_work_buffer, m_work_buffer_size, false, am));
R_UNLESS(IsSupportedAccessMode(static_cast<const u8 *>(m_work_buffer), am), sdmmc::ResultSdCardNotSupportAccessMode());
/* Get the current consumption. */
AMS_ABORT_UNLESS(out_current_consumption != nullptr);
*out_current_consumption = GetMaximumCurrentConsumption(static_cast<const u8 *>(m_work_buffer));
R_SUCCEED();
}
Result SdCardDeviceAccessor::GetSdCardSdStatus(void *dst, size_t dst_size) const {
/* Acquire exclusive access to the device. */
AMS_SDMMC_LOCK_SD_CARD_DEVICE_MUTEX();
/* Check that we're accessible. */
R_TRY(m_sd_card_device.CheckAccessible());
/* Get the status. */
R_TRY(this->GetSdStatus(dst, dst_size));
R_SUCCEED();
}
Result SdCardDeviceAccessor::GetSdCardProtectedAreaCapacity(u32 *out_num_sectors) const {
AMS_ABORT_UNLESS(out_num_sectors != nullptr);
/* Get the sd status. */
R_TRY(this->GetSdCardSdStatus(m_work_buffer, m_work_buffer_size));
const u32 size_of_protected_area = GetSizeOfProtectedArea(static_cast<const u8 *>(m_work_buffer));
/* Get the csd. */
u8 csd[DeviceCsdSize];
m_sd_card_device.GetCsd(csd, sizeof(csd));
/* Handle based on csd version. */
if (IsLessThanCsdVersion2(csd)) {
/* Get c_size_mult and read_bl_len. */
u8 c_size_mult, read_bl_len;
m_sd_card_device.GetLegacyCapacityParameters(std::addressof(c_size_mult), std::addressof(read_bl_len));
/* Validate the parameters. */
R_UNLESS((read_bl_len + c_size_mult + 2) >= 9, sdmmc::ResultUnexpectedDeviceCsdValue());
/* Calculate capacity. */
*out_num_sectors = size_of_protected_area << ((read_bl_len + c_size_mult + 2) - 9);
} else {
/* SIZE_OF_PROTECTED_AREA is in bytes. */
*out_num_sectors = size_of_protected_area / SectorSize;
}
R_SUCCEED();
}
}
| 41,954
|
C++
|
.cpp
| 831
| 40.255114
| 177
| 0.626974
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,062
|
sdmmc_sdmmc_controller.board.nintendo_nx.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/sdmmc/impl/sdmmc_sdmmc_controller.board.nintendo_nx.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if defined(ATMOSPHERE_IS_STRATOSPHERE)
#include <stratosphere.hpp>
#elif defined(ATMOSPHERE_IS_MESOSPHERE)
#include <mesosphere.hpp>
#elif defined(ATMOSPHERE_IS_EXOSPHERE)
#include <exosphere.hpp>
#else
#include <vapours.hpp>
#endif
#include "sdmmc_sdmmc_controller.board.nintendo_nx.hpp"
#include "sdmmc_io_impl.board.nintendo_nx.hpp"
#include "sdmmc_timer.hpp"
namespace ams::sdmmc::impl {
/* FOR REFERENCE: board-specific sdmmc registers. */
//struct SdmmcRegisters {
// /* Standard registers. */
// volatile SdHostStandardRegisters sd_host_standard_registers;
//
// /* Vendor specific registers */
// volatile uint32_t vendor_clock_cntrl;
// volatile uint32_t vendor_sys_sw_cntrl;
// volatile uint32_t vendor_err_intr_status;
// volatile uint32_t vendor_cap_overrides;
// volatile uint32_t vendor_boot_cntrl;
// volatile uint32_t vendor_boot_ack_timeout;
// volatile uint32_t vendor_boot_dat_timeout;
// volatile uint32_t vendor_debounce_count;
// volatile uint32_t vendor_misc_cntrl;
// volatile uint32_t max_current_override;
// volatile uint32_t max_current_override_hi;
// volatile uint32_t _0x12c[0x20];
// volatile uint32_t vendor_io_trim_cntrl;
//
// /* Start of sdmmc2/sdmmc4 only */
// volatile uint32_t vendor_dllcal_cfg;
// volatile uint32_t vendor_dll_ctrl0;
// volatile uint32_t vendor_dll_ctrl1;
// volatile uint32_t vendor_dllcal_cfg_sta;
// /* End of sdmmc2/sdmmc4 only */
//
// volatile uint32_t vendor_tuning_cntrl0;
// volatile uint32_t vendor_tuning_cntrl1;
// volatile uint32_t vendor_tuning_status0;
// volatile uint32_t vendor_tuning_status1;
// volatile uint32_t vendor_clk_gate_hysteresis_count;
// volatile uint32_t vendor_preset_val0;
// volatile uint32_t vendor_preset_val1;
// volatile uint32_t vendor_preset_val2;
// volatile uint32_t sdmemcomppadctrl;
// volatile uint32_t auto_cal_config;
// volatile uint32_t auto_cal_interval;
// volatile uint32_t auto_cal_status;
// volatile uint32_t io_spare;
// volatile uint32_t sdmmca_mccif_fifoctrl;
// volatile uint32_t timeout_wcoal_sdmmca;
// volatile uint32_t _0x1fc;
//};
DEFINE_SD_REG_BIT_ENUM(VENDOR_CLOCK_CNTRL_SPI_MODE_CLKEN_OVERRIDE, 2, NORMAL, OVERRIDE);
DEFINE_SD_REG(VENDOR_CLOCK_CNTRL_TAP_VAL, 16, 8);
DEFINE_SD_REG(VENDOR_CLOCK_CNTRL_TRIM_VAL, 24, 5);
DEFINE_SD_REG(VENDOR_CAP_OVERRIDES_DQS_TRIM_VAL, 8, 6);
DEFINE_SD_REG(VENDOR_IO_TRIM_CNTRL_SEL_VREG, 2, 1);
DEFINE_SD_REG_BIT_ENUM(VENDOR_DLLCAL_CFG_CALIBRATE, 31, DISABLE, ENABLE);
DEFINE_SD_REG_BIT_ENUM(VENDOR_DLLCAL_CFG_STA_DLL_CAL_ACTIVE, 31, DONE, RUNNING);
DEFINE_SD_REG(VENDOR_TUNING_CNTRL0_MUL_M, 6, 7);
DEFINE_SD_REG_THREE_BIT_ENUM(VENDOR_TUNING_CNTRL0_NUM_TUNING_ITERATIONS, 13, TRIES_40, TRIES_64, TRIES_128, TRIES_192, TRIES_256, RESERVED5, RESERVED6, RESERVED7);
DEFINE_SD_REG_BIT_ENUM(VENDOR_TUNING_CNTRL0_TAP_VALUE_UPDATED_BY_HW, 17, NOT_UPDATED_BY_HW, UPDATED_BY_HW);
DEFINE_SD_REG(SDMEMCOMPPADCTRL_SDMMC2TMC_CFG_SDMEMCOMP_VREF_SEL, 0, 4);
DEFINE_SD_REG(SDMEMCOMPPADCTRL_PAD_E_INPUT_OR_E_PWRD, 31, 1);
DEFINE_SD_REG(AUTO_CAL_CONFIG_AUTO_CAL_PU_OFFSET, 0, 7);
DEFINE_SD_REG(AUTO_CAL_CONFIG_AUTO_CAL_PD_OFFSET, 8, 7);
DEFINE_SD_REG_BIT_ENUM(AUTO_CAL_CONFIG_AUTO_CAL_ENABLE, 29, DISABLED, ENABLED);
DEFINE_SD_REG_BIT_ENUM(AUTO_CAL_CONFIG_AUTO_CAL_START, 31, DISABLED, ENABLED);
DEFINE_SD_REG(AUTO_CAL_STATUS_AUTO_CAL_PULLUP, 0, 7);
DEFINE_SD_REG_BIT_ENUM(AUTO_CAL_STATUS_AUTO_CAL_ACTIVE, 31, INACTIVE, ACTIVE);
DEFINE_SD_REG_BIT_ENUM(IO_SPARE_SPARE_OUT_3, 19, TWO_CYCLE_DELAY, ONE_CYCLE_DELAY);
namespace {
constexpr inline u32 TuningCommandTimeoutMilliSeconds = 5;
constexpr void GetDividerSetting(u32 *out_target_clock_frequency_khz, u16 *out_x, SpeedMode speed_mode) {
switch (speed_mode) {
case SpeedMode_MmcIdentification:
*out_target_clock_frequency_khz = 26000;
*out_x = 66;
break;
case SpeedMode_MmcLegacySpeed:
*out_target_clock_frequency_khz = 26000;
*out_x = 1;
break;
case SpeedMode_MmcHighSpeed:
*out_target_clock_frequency_khz = 52000;
*out_x = 1;
break;
case SpeedMode_MmcHs200:
*out_target_clock_frequency_khz = 200000;
*out_x = 1;
break;
case SpeedMode_MmcHs400:
*out_target_clock_frequency_khz = 200000;
*out_x = 1;
break;
case SpeedMode_SdCardIdentification:
*out_target_clock_frequency_khz = 25000;
*out_x = 64;
break;
case SpeedMode_SdCardDefaultSpeed:
*out_target_clock_frequency_khz = 25000;
*out_x = 1;
break;
case SpeedMode_SdCardHighSpeed:
*out_target_clock_frequency_khz = 50000;
*out_x = 1;
break;
case SpeedMode_SdCardSdr12:
*out_target_clock_frequency_khz = 25000;
*out_x = 1;
break;
case SpeedMode_SdCardSdr50:
*out_target_clock_frequency_khz = 100000;
*out_x = 1;
break;
case SpeedMode_SdCardSdr104:
*out_target_clock_frequency_khz = 200000;
*out_x = 1;
break;
case SpeedMode_GcAsicFpgaSpeed:
*out_target_clock_frequency_khz = 40800;
*out_x = 1;
break;
case SpeedMode_GcAsicSpeed:
*out_target_clock_frequency_khz = 200000;
*out_x = 2;
break;
case SpeedMode_SdCardSdr25:
case SpeedMode_SdCardDdr50:
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
}
namespace {
#if defined(AMS_SDMMC_THREAD_SAFE)
constinit os::SdkMutex g_soc_mutex;
#define AMS_SDMMC_LOCK_SOC_MUTEX() std::scoped_lock lk(g_soc_mutex)
#else
#define AMS_SDMMC_LOCK_SOC_MUTEX()
#endif
constinit bool g_determined_soc = false;
constinit bool g_is_soc_mariko = false;
}
bool IsSocMariko() {
if (!g_determined_soc) {
/* Ensure we have exclusive access to the soc variables. */
AMS_SDMMC_LOCK_SOC_MUTEX();
/* Check the SocType. */
#if defined(ATMOSPHERE_IS_EXOSPHERE)
{
g_is_soc_mariko = fuse::GetSocType() == fuse::SocType_Mariko;
}
#elif defined(ATMOSPHERE_IS_MESOSPHERE)
{
MESOSPHERE_TODO("Detect mariko via KSystemControl call?");
}
#elif defined(ATMOSPHERE_IS_STRATOSPHERE)
{
/* Connect to spl for the duration of our check. */
spl::Initialize();
ON_SCOPE_EXIT { spl::Finalize(); };
g_is_soc_mariko = spl::GetSocType() == spl::SocType_Mariko;
}
#else
#error "Unknown execution context for ams::sdmmc::impl::IsSocMariko"
#endif
/* Note that we determined the soc. */
g_determined_soc = true;
}
return g_is_soc_mariko;
}
void SdmmcController::ReleaseReset(SpeedMode speed_mode) {
/* Get the clock reset module. */
const auto module = this->GetClockResetModule();
/* If the module is available, disable clock. */
if (ClockResetController::IsAvailable(module)) {
SdHostStandardController::DisableDeviceClock();
SdHostStandardController::EnsureControl();
}
/* Get the correct divider setting for the speed mode. */
u32 target_clock_frequency_khz;
u16 x;
GetDividerSetting(std::addressof(target_clock_frequency_khz), std::addressof(x), speed_mode);
/* Release reset. */
ClockResetController::ReleaseReset(module, target_clock_frequency_khz);
}
void SdmmcController::AssertReset() {
return ClockResetController::AssertReset(this->GetClockResetModule());
}
Result SdmmcController::StartupCore(BusPower bus_power) {
/* Set schmitt trigger. */
this->SetSchmittTrigger(bus_power);
/* Select one-cycle delay version of cmd_oen. */
reg::ReadWrite(m_sdmmc_registers->io_spare, SD_REG_BITS_ENUM(IO_SPARE_SPARE_OUT_3, ONE_CYCLE_DELAY));
/* Select regulated reference voltage for trimmer and DLL supply. */
reg::ReadWrite(m_sdmmc_registers->vendor_io_trim_cntrl, SD_REG_BITS_VALUE(VENDOR_IO_TRIM_CNTRL_SEL_VREG, 0));
/* Configure outbound tap value. */
reg::ReadWrite(m_sdmmc_registers->vendor_clock_cntrl, SD_REG_BITS_VALUE(VENDOR_CLOCK_CNTRL_TRIM_VAL, this->GetOutboundTapValue()));
/* Configure SPI_MODE_CLKEN_OVERRIDE. */
reg::ReadWrite(m_sdmmc_registers->vendor_clock_cntrl, SD_REG_BITS_ENUM(VENDOR_CLOCK_CNTRL_SPI_MODE_CLKEN_OVERRIDE, NORMAL));
/* Set slew codes. */
this->SetSlewCodes();
/* Set vref sel. */
reg::ReadWrite(m_sdmmc_registers->sdmemcomppadctrl, SD_REG_BITS_VALUE(SDMEMCOMPPADCTRL_SDMMC2TMC_CFG_SDMEMCOMP_VREF_SEL, this->GetVrefSelValue()));
/* Perform drive strength calibration at the new power. */
this->SetDriveCodeOffsets(bus_power);
this->CalibrateDriveStrength(bus_power);
/* Enable internal clock. */
R_TRY(SdHostStandardController::EnableInternalClock());
R_SUCCEED();
}
Result SdmmcController::SetClockTrimmer(SpeedMode speed_mode, u8 tap_value) {
/* If speed mode is Hs400, set the dqs trim value. */
if (speed_mode == SpeedMode_MmcHs400) {
reg::ReadWrite(m_sdmmc_registers->vendor_cap_overrides, SD_REG_BITS_VALUE(VENDOR_CAP_OVERRIDES_DQS_TRIM_VAL, 40));
}
/* Configure tap value as updated by software. */
reg::ReadWrite(m_sdmmc_registers->vendor_tuning_cntrl0, SD_REG_BITS_ENUM(VENDOR_TUNING_CNTRL0_TAP_VALUE_UPDATED_BY_HW, NOT_UPDATED_BY_HW));
/* Set the inbound tap value. */
reg::ReadWrite(m_sdmmc_registers->vendor_clock_cntrl, SD_REG_BITS_VALUE(VENDOR_CLOCK_CNTRL_TAP_VAL, tap_value));
/* Reset the cmd/dat line. */
R_TRY(SdHostStandardController::ResetCmdDatLine());
R_SUCCEED();
}
u8 SdmmcController::GetCurrentTapValue() {
return static_cast<u8>(reg::GetValue(m_sdmmc_registers->vendor_clock_cntrl, SD_REG_BITS_MASK(VENDOR_CLOCK_CNTRL_TAP_VAL)));
}
Result SdmmcController::CalibrateDll() {
/* Check if we need to temporarily re-enable the device clock. */
const bool clock_disabled = reg::HasValue(m_sdmmc_registers->sd_host_standard_registers.clock_control, SD_REG_BITS_ENUM(CLOCK_CONTROL_SD_CLOCK_ENABLE, DISABLE));
/* Ensure that the clock is enabled for the period we're using it. */
if (clock_disabled) {
/* Turn on the clock. */
reg::ReadWrite(m_sdmmc_registers->sd_host_standard_registers.clock_control, SD_REG_BITS_ENUM(CLOCK_CONTROL_SD_CLOCK_ENABLE, ENABLE));
}
ON_SCOPE_EXIT { if (clock_disabled) { reg::ReadWrite(m_sdmmc_registers->sd_host_standard_registers.clock_control, SD_REG_BITS_ENUM(CLOCK_CONTROL_SD_CLOCK_ENABLE, DISABLE)); } };
/* Begin calibration. */
reg::ReadWrite(m_sdmmc_registers->vendor_dllcal_cfg, SD_REG_BITS_ENUM(VENDOR_DLLCAL_CFG_CALIBRATE, ENABLE));
/* Wait up to 5ms for calibration to begin. */
{
ManualTimer timer(5);
while (true) {
/* If calibration is done, we're done. */
if (!reg::HasValue(m_sdmmc_registers->vendor_dllcal_cfg, SD_REG_BITS_ENUM(VENDOR_DLLCAL_CFG_CALIBRATE, ENABLE))) {
break;
}
/* Otherwise, check if we've timed out. */
R_UNLESS((timer.Update()), sdmmc::ResultSdmmcDllCalibrationSoftwareTimeout());
}
}
/* Wait up to 10ms for calibration to complete. */
{
ManualTimer timer(10);
while (true) {
/* If calibration is done, we're done. */
if (reg::HasValue(m_sdmmc_registers->vendor_dllcal_cfg_sta, SD_REG_BITS_ENUM(VENDOR_DLLCAL_CFG_STA_DLL_CAL_ACTIVE, DONE))) {
break;
}
/* Otherwise, check if we've timed out. */
R_UNLESS((timer.Update()), sdmmc::ResultSdmmcDllApplicationSoftwareTimeout());
}
}
R_SUCCEED();
}
Result SdmmcController::SetSpeedModeWithTapValue(SpeedMode speed_mode, u8 tap_value) {
/* Check if we need to temporarily disable the device clock. */
const bool clock_enabled = reg::HasValue(m_sdmmc_registers->sd_host_standard_registers.clock_control, SD_REG_BITS_ENUM(CLOCK_CONTROL_SD_CLOCK_ENABLE, ENABLE));
/* Ensure that the clock is disabled for the period we're using it. */
if (clock_enabled) {
/* Turn off the clock. */
reg::ReadWrite(m_sdmmc_registers->sd_host_standard_registers.clock_control, SD_REG_BITS_ENUM(CLOCK_CONTROL_SD_CLOCK_ENABLE, DISABLE));
}
/* Set clock trimmer. */
/* NOTE: Nintendo does not re-enable the clock if this fails... */
R_TRY(this->SetClockTrimmer(speed_mode, tap_value));
/* Configure for the desired speed mode. */
switch (speed_mode) {
case SpeedMode_MmcIdentification:
case SpeedMode_SdCardIdentification:
case SpeedMode_MmcLegacySpeed:
case SpeedMode_SdCardDefaultSpeed:
/* Set as normal speed, 3.3V. */
reg::ReadWrite(m_sdmmc_registers->sd_host_standard_registers.host_control, SD_REG_BITS_ENUM(HOST_CONTROL_HIGH_SPEED_ENABLE, NORMAL_SPEED));
reg::ReadWrite(m_sdmmc_registers->sd_host_standard_registers.host_control2, SD_REG_BITS_ENUM(HOST_CONTROL2_1_8V_SIGNALING_ENABLE, 3_3V_SIGNALING));
break;
case SpeedMode_MmcHighSpeed:
case SpeedMode_SdCardHighSpeed:
/* Set as high speed, 3.3V. */
reg::ReadWrite(m_sdmmc_registers->sd_host_standard_registers.host_control, SD_REG_BITS_ENUM(HOST_CONTROL_HIGH_SPEED_ENABLE, HIGH_SPEED));
reg::ReadWrite(m_sdmmc_registers->sd_host_standard_registers.host_control2, SD_REG_BITS_ENUM(HOST_CONTROL2_1_8V_SIGNALING_ENABLE, 3_3V_SIGNALING));
break;
case SpeedMode_MmcHs200:
/* Set as HS200, 1.8V. */
reg::ReadWrite(m_sdmmc_registers->sd_host_standard_registers.host_control2, SD_REG_BITS_ENUM(HOST_CONTROL2_UHS_MODE_SELECT, HS200));
reg::ReadWrite(m_sdmmc_registers->sd_host_standard_registers.host_control2, SD_REG_BITS_ENUM(HOST_CONTROL2_1_8V_SIGNALING_ENABLE, 1_8V_SIGNALING));
break;
case SpeedMode_MmcHs400:
/* Set as HS400, 1.8V. */
reg::ReadWrite(m_sdmmc_registers->sd_host_standard_registers.host_control2, SD_REG_BITS_ENUM(HOST_CONTROL2_UHS_MODE_SELECT, HS400));
reg::ReadWrite(m_sdmmc_registers->sd_host_standard_registers.host_control2, SD_REG_BITS_ENUM(HOST_CONTROL2_1_8V_SIGNALING_ENABLE, 1_8V_SIGNALING));
break;
case SpeedMode_SdCardSdr12:
/* Set as SDR12, 1.8V. */
reg::ReadWrite(m_sdmmc_registers->sd_host_standard_registers.host_control2, SD_REG_BITS_ENUM(HOST_CONTROL2_UHS_MODE_SELECT, SDR12));
reg::ReadWrite(m_sdmmc_registers->sd_host_standard_registers.host_control2, SD_REG_BITS_ENUM(HOST_CONTROL2_1_8V_SIGNALING_ENABLE, 1_8V_SIGNALING));
break;
case SpeedMode_SdCardSdr50:
case SpeedMode_SdCardSdr104:
/* Set as SDR104, 1.8V. */
reg::ReadWrite(m_sdmmc_registers->sd_host_standard_registers.host_control2, SD_REG_BITS_ENUM(HOST_CONTROL2_UHS_MODE_SELECT, SDR104));
reg::ReadWrite(m_sdmmc_registers->sd_host_standard_registers.host_control2, SD_REG_BITS_ENUM(HOST_CONTROL2_1_8V_SIGNALING_ENABLE, 1_8V_SIGNALING));
break;
case SpeedMode_GcAsicFpgaSpeed:
case SpeedMode_GcAsicSpeed:
/* Set as HS200, 1.8V. */
reg::ReadWrite(m_sdmmc_registers->sd_host_standard_registers.host_control2, SD_REG_BITS_ENUM(HOST_CONTROL2_UHS_MODE_SELECT, HS200));
reg::ReadWrite(m_sdmmc_registers->sd_host_standard_registers.host_control2, SD_REG_BITS_ENUM(HOST_CONTROL2_1_8V_SIGNALING_ENABLE, 1_8V_SIGNALING));
break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
SdHostStandardController::EnsureControl();
/* Get the divider setting. */
u32 target_source_clock_frequency_khz;
u16 x;
GetDividerSetting(std::addressof(target_source_clock_frequency_khz), std::addressof(x), speed_mode);
/* Set the clock frequency. */
u32 actual_source_clock_frequency_khz;
ClockResetController::SetClockFrequencyKHz(std::addressof(actual_source_clock_frequency_khz), this->GetClockResetModule(), target_source_clock_frequency_khz);
/* Set the device clock frequency. */
const u32 actual_device_clock_frequency_khz = util::DivideUp(actual_source_clock_frequency_khz, x);
SdHostStandardController::SetDeviceClockFrequencyKHz(actual_device_clock_frequency_khz);
/* Check that the divider is correct. */
AMS_ABORT_UNLESS((x == 1) || util::IsAligned(x, 2));
/* Write the divider val to clock control. */
const u16 n = x / 2;
const u16 upper_n = n >> 8;
reg::ReadWrite(m_sdmmc_registers->sd_host_standard_registers.clock_control, SD_REG_BITS_VALUE(CLOCK_CONTROL_SDCLK_FREQUENCY_SELECT, n),
SD_REG_BITS_VALUE(CLOCK_CONTROL_UPPER_BITS_OF_SDCLK_FREQUENCY_SELECT, upper_n));
/* Re-enable the clock, if we should. */
if (clock_enabled) {
/* Turn on the clock. */
reg::ReadWrite(m_sdmmc_registers->sd_host_standard_registers.clock_control, SD_REG_BITS_ENUM(CLOCK_CONTROL_SD_CLOCK_ENABLE, ENABLE));
}
/* If speed mode is Hs400, calibrate dll. */
if (speed_mode == SpeedMode_MmcHs400) {
R_TRY(this->CalibrateDll());
}
/* Set the current speed mode. */
m_current_speed_mode = speed_mode;
R_SUCCEED();
}
Result SdmmcController::IssueTuningCommand(u32 command_index) {
/* Check that we're not power saving enable. */
AMS_ABORT_UNLESS(!SdHostStandardController::IsPowerSavingEnable());
/* Wait until command inhibit is done. */
R_TRY(SdHostStandardController::WaitWhileCommandInhibit(true));
/* Set transfer for tuning. */
SdHostStandardController::SetTransferForTuning();
/* If necessary, clear interrupt and enable buffer read ready signal. */
#if defined(AMS_SDMMC_USE_OS_EVENTS)
{
this->ClearInterrupt();
reg::ReadWrite(m_sdmmc_registers->sd_host_standard_registers.normal_signal_enable, SD_REG_BITS_ENUM(NORMAL_INTERRUPT_BUFFER_READ_READY, ENABLED));
}
#endif
/* Set the buffer read ready enable, and read status to ensure it takes. */
reg::ReadWrite(m_sdmmc_registers->sd_host_standard_registers.normal_int_enable, SD_REG_BITS_ENUM(NORMAL_INTERRUPT_BUFFER_READ_READY, ENABLED));
reg::Write(m_sdmmc_registers->sd_host_standard_registers.normal_int_status, reg::Read(m_sdmmc_registers->sd_host_standard_registers.normal_int_status));
/* Issue command with clock disabled. */
reg::ReadWrite(m_sdmmc_registers->sd_host_standard_registers.clock_control, SD_REG_BITS_ENUM(CLOCK_CONTROL_SD_CLOCK_ENABLE, DISABLE));
{
SdHostStandardController::SetCommandForTuning(command_index);
SdHostStandardController::EnsureControl();
WaitMicroSeconds(1);
SdHostStandardController::AbortTransaction();
}
reg::ReadWrite(m_sdmmc_registers->sd_host_standard_registers.clock_control, SD_REG_BITS_ENUM(CLOCK_CONTROL_SD_CLOCK_ENABLE, ENABLE));
/* When we're done waiting, ensure that we clean up appropriately. */
ON_SCOPE_EXIT {
/* Clear the buffer read ready signal, if we should. */
#if defined(AMS_SDMMC_USE_OS_EVENTS)
reg::ReadWrite(m_sdmmc_registers->sd_host_standard_registers.normal_signal_enable, SD_REG_BITS_ENUM(NORMAL_INTERRUPT_BUFFER_READ_READY, MASKED));
#endif
/* Clear the buffer read ready enable. */
reg::ReadWrite(m_sdmmc_registers->sd_host_standard_registers.normal_int_enable, SD_REG_BITS_ENUM(NORMAL_INTERRUPT_BUFFER_READ_READY, MASKED));
/* Wait 8 clocks to ensure configuration takes. */
SdHostStandardController::EnsureControl();
WaitClocks(8, SdHostStandardController::GetDeviceClockFrequencyKHz());
};
/* Wait for the command to finish. */
#if defined(AMS_SDMMC_USE_OS_EVENTS)
{
const auto result = SdHostStandardController::WaitInterrupt(TuningCommandTimeoutMilliSeconds);
if (R_SUCCEEDED(result)) {
/* If we succeeded, clear the interrupt. */
reg::Write(m_sdmmc_registers->sd_host_standard_registers.normal_int_status, SD_REG_BITS_ENUM(NORMAL_INTERRUPT_BUFFER_READ_READY, ENABLED));
this->ClearInterrupt();
R_SUCCEED();
} else if (sdmmc::ResultWaitInterruptSoftwareTimeout::Includes(result)) {
SdHostStandardController::AbortTransaction();
R_THROW(sdmmc::ResultIssueTuningCommandSoftwareTimeout());
} else {
R_RETURN(result);
}
}
#else
{
SdHostStandardController::EnsureControl();
ManualTimer timer(TuningCommandTimeoutMilliSeconds);
while (true) {
/* Check if we received the interrupt. */
if (reg::HasValue(m_sdmmc_registers->sd_host_standard_registers.normal_int_status, SD_REG_BITS_ENUM(NORMAL_INTERRUPT_BUFFER_READ_READY, ENABLED))) {
/* If we did, acknowledge it. */
reg::Write(m_sdmmc_registers->sd_host_standard_registers.normal_int_status, SD_REG_BITS_ENUM(NORMAL_INTERRUPT_BUFFER_READ_READY, ENABLED));
R_SUCCEED();
}
/* Otherwise, check if we timed out. */
if (!timer.Update()) {
SdHostStandardController::AbortTransaction();
R_THROW(sdmmc::ResultIssueTuningCommandSoftwareTimeout());
}
}
}
#endif
}
void SdmmcController::SetDriveCodeOffsets(BusPower bus_power) {
/* Get the offsets. */
u8 pd, pu;
this->GetAutoCalOffsets(std::addressof(pd), std::addressof(pu), bus_power);
/* Set the offsets. */
reg::ReadWrite(m_sdmmc_registers->auto_cal_config, SD_REG_BITS_VALUE(AUTO_CAL_CONFIG_AUTO_CAL_PD_OFFSET, pd),
SD_REG_BITS_VALUE(AUTO_CAL_CONFIG_AUTO_CAL_PU_OFFSET, pu));
/* Wait for 1ms to ensure that our configuration takes. */
/* NOTE/HACK: Nintendo does not (need) to do this, but they use SvcSleepThread for waits. */
/* It's unclear why this wait is necessary, but not doing it causes drive strength calibration to fail if done immediately afterwards. */
util::WaitMicroSeconds(1000);
}
void SdmmcController::CalibrateDriveStrength(BusPower bus_power) {
/* Reset drive strength calibration status. */
m_drive_strength_calibration_status = sdmmc::ResultDriveStrengthCalibrationNotCompleted();
/* Check if we need to temporarily disable the device clock. */
const bool clock_enabled = reg::HasValue(m_sdmmc_registers->sd_host_standard_registers.clock_control, SD_REG_BITS_ENUM(CLOCK_CONTROL_SD_CLOCK_ENABLE, ENABLE));
/* Ensure that the clock is disabled for the period we're using it. */
if (clock_enabled) {
/* Turn off the clock. */
reg::ReadWrite(m_sdmmc_registers->sd_host_standard_registers.clock_control, SD_REG_BITS_ENUM(CLOCK_CONTROL_SD_CLOCK_ENABLE, DISABLE));
}
/* Calibrate with the clock disabled. */
{
/* Set SDMEMCOMPPADCTRL_PAD_E_INPUT_OR_E_PWRD. */
if (reg::HasValue(m_sdmmc_registers->sdmemcomppadctrl, SD_REG_BITS_VALUE(SDMEMCOMPPADCTRL_PAD_E_INPUT_OR_E_PWRD, 0))) {
reg::ReadWrite(m_sdmmc_registers->sdmemcomppadctrl, SD_REG_BITS_VALUE(SDMEMCOMPPADCTRL_PAD_E_INPUT_OR_E_PWRD, 1));
SdHostStandardController::EnsureControl();
WaitMicroSeconds(1);
}
/* Calibrate with SDMEMCOMPPADCTRL_PAD_E_INPUT_OR_E_PWRD set. */
{
/* Begin autocal. */
reg::ReadWrite(m_sdmmc_registers->auto_cal_config, SD_REG_BITS_ENUM(AUTO_CAL_CONFIG_AUTO_CAL_START, ENABLED),
SD_REG_BITS_ENUM(AUTO_CAL_CONFIG_AUTO_CAL_ENABLE, ENABLED));
SdHostStandardController::EnsureControl();
WaitMicroSeconds(2);
/* Wait up to 10ms for auto cal to complete. */
ManualTimer timer(10);
while (true) {
/* Check if auto cal is inactive. */
if (reg::HasValue(m_sdmmc_registers->auto_cal_status, SD_REG_BITS_ENUM(AUTO_CAL_STATUS_AUTO_CAL_ACTIVE, INACTIVE))) {
/* Check the pullup status. */
const u32 pullup = (reg::GetValue(m_sdmmc_registers->auto_cal_status, SD_REG_BITS_MASK(AUTO_CAL_STATUS_AUTO_CAL_PULLUP))) & 0x1F;
if (pullup == 0x1F) {
m_drive_strength_calibration_status = sdmmc::ResultSdmmcCompShortToGnd();
}
if (pullup == 0) {
m_drive_strength_calibration_status = sdmmc::ResultSdmmcCompOpen();
}
break;
}
/* Otherwise, check if we've timed out. */
if (!timer.Update()) {
m_drive_strength_calibration_status = sdmmc::ResultDriveStrengthCalibrationSoftwareTimeout();
this->SetDriveStrengthToDefaultValues(bus_power);
reg::ReadWrite(m_sdmmc_registers->auto_cal_config, SD_REG_BITS_ENUM(AUTO_CAL_CONFIG_AUTO_CAL_ENABLE, DISABLED));
break;
}
}
}
/* Clear SDMEMCOMPPADCTRL_PAD_E_INPUT_OR_E_PWRD. */
reg::ReadWrite(m_sdmmc_registers->sdmemcomppadctrl, SD_REG_BITS_VALUE(SDMEMCOMPPADCTRL_PAD_E_INPUT_OR_E_PWRD, 0));
}
/* Re-enable the clock, if we should. */
if (clock_enabled) {
/* Turn on the clock. */
reg::ReadWrite(m_sdmmc_registers->sd_host_standard_registers.clock_control, SD_REG_BITS_ENUM(CLOCK_CONTROL_SD_CLOCK_ENABLE, ENABLE));
}
/* If calibration didn't receive a replacement error, set internal state to success. */
if (sdmmc::ResultDriveStrengthCalibrationNotCompleted::Includes(m_drive_strength_calibration_status)) {
m_drive_strength_calibration_status = ResultSuccess();
}
}
Result SdmmcController::Startup(BusPower bus_power, BusWidth bus_width, SpeedMode speed_mode, bool power_saving_enable) {
/* Verify that we're awake. */
AMS_ABORT_UNLESS(m_is_awake);
/* Release the controller from reset. */
this->ReleaseReset(speed_mode);
/* Mark that we're not shutdown. */
m_is_shutdown = false;
/* Power on the controller. */
R_TRY(this->PowerOn(bus_power));
/* Start up for the specific power. */
R_TRY(this->StartupCore(bus_power));
/* Set our current power/width/speed. */
SdHostStandardController::SetBusWidth(bus_width);
SdHostStandardController::SetBusPower(bus_power);
R_TRY(this->SetSpeedMode(speed_mode));
this->SetPowerSaving(power_saving_enable);
/* Enable clock to the device. */
SdHostStandardController::EnableDeviceClock();
/* Ensure that we can control the device. */
SdHostStandardController::EnsureControl();
R_SUCCEED();
}
void SdmmcController::Shutdown() {
/* If we're already shut down, there's nothing to do. */
if (m_is_shutdown) {
return;
}
/* If we're currently awake, we need to disable clock/power. */
if (m_is_awake) {
SdHostStandardController::DisableDeviceClock();
SdHostStandardController::SetBusPower(BusPower_Off);
SdHostStandardController::EnsureControl();
}
/* Power off. */
this->PowerOff();
/* If awake, assert reset. */
if (m_is_awake) {
this->AssertReset();
}
/* Mark that we're shutdown. */
m_is_shutdown = true;
}
void SdmmcController::PutToSleep() {
/* If we're already shut down or asleep, there's nothing to do. */
if (m_is_shutdown || !m_is_awake) {
return;
}
/* Save values before sleep. */
m_bus_power_before_sleep = SdHostStandardController::GetBusPower();
m_bus_width_before_sleep = SdHostStandardController::GetBusWidth();
m_speed_mode_before_sleep = m_current_speed_mode;
m_tap_value_before_sleep = this->GetCurrentTapValue();
m_is_powersaving_enable_before_sleep = SdHostStandardController::IsPowerSavingEnable();
/* Disable clock/power to the device. */
SdHostStandardController::DisableDeviceClock();
SdHostStandardController::SetBusPower(BusPower_Off);
SdHostStandardController::EnsureControl();
/* Assert reset. */
this->AssertReset();
/* Mark that we're asleep. */
m_is_awake = false;
}
Result SdmmcController::Awaken() {
/* If we're shut down, or if we're awake already, there's nothing to do. */
R_SUCCEED_IF(m_is_shutdown);
R_SUCCEED_IF(m_is_awake);
/* Mark that we're awake. */
m_is_awake = true;
/* Clear pad parked status. */
this->ClearPadParked();
/* Release reset. */
this->ReleaseReset(m_speed_mode_before_sleep);
/* Start up for the correct power. */
R_TRY(this->StartupCore(m_bus_power_before_sleep));
/* Configure values to what they were before sleep. */
SdHostStandardController::SetBusWidth(m_bus_width_before_sleep);
SdHostStandardController::SetBusPower(m_bus_power_before_sleep);
R_TRY(this->SetSpeedModeWithTapValue(m_speed_mode_before_sleep, m_tap_value_before_sleep));
this->SetPowerSaving(m_is_powersaving_enable_before_sleep);
/* Enable clock to the device. */
SdHostStandardController::EnableDeviceClock();
SdHostStandardController::EnsureControl();
R_SUCCEED();
}
Result SdmmcController::SwitchToSdr12() {
/* Disable clock. */
reg::ReadWrite(m_sdmmc_registers->sd_host_standard_registers.clock_control, SD_REG_BITS_ENUM(CLOCK_CONTROL_SD_CLOCK_ENABLE, DISABLE));
/* Check that the dat lines are all low. */
R_UNLESS(reg::HasValue(m_sdmmc_registers->sd_host_standard_registers.present_state, SD_REG_BITS_VALUE(PRESENT_STATE_DAT0_3_LINE_SIGNAL_LEVEL, 0b0000)), sdmmc::ResultSdCardNotReadyToVoltageSwitch());
/* Set Speed Mode. */
R_TRY(this->SetSpeedMode(SpeedMode_SdCardSdr12));
/* Set voltage to 1.8V. */
SdHostStandardController::EnsureControl();
R_TRY(this->LowerBusPower());
this->SetSchmittTrigger(BusPower_1_8V);
/* Perform drive strength calibration at the new power. */
this->SetDriveCodeOffsets(BusPower_1_8V);
this->CalibrateDriveStrength(BusPower_1_8V);
/* Set the bus power in standard controller. */
SdHostStandardController::SetBusPower(BusPower_1_8V);
/* Wait up to 5ms for the switch to take. */
SdHostStandardController::EnsureControl();
WaitMicroSeconds(5000);
/* Check that we switched to 1.8V. */
R_UNLESS(reg::HasValue(m_sdmmc_registers->sd_host_standard_registers.host_control2, SD_REG_BITS_ENUM(HOST_CONTROL2_1_8V_SIGNALING_ENABLE, 1_8V_SIGNALING)), sdmmc::ResultSdHostStandardFailSwitchTo1_8V());
/* Enable clock, and wait 1ms. */
reg::ReadWrite(m_sdmmc_registers->sd_host_standard_registers.clock_control, SD_REG_BITS_ENUM(CLOCK_CONTROL_SD_CLOCK_ENABLE, ENABLE));
SdHostStandardController::EnsureControl();
WaitMicroSeconds(1000);
/* Check that the dat lines are all high. */
R_UNLESS(reg::HasValue(m_sdmmc_registers->sd_host_standard_registers.present_state, SD_REG_BITS_VALUE(PRESENT_STATE_DAT0_3_LINE_SIGNAL_LEVEL, 0b1111)), sdmmc::ResultSdCardNotCompleteVoltageSwitch());
R_SUCCEED();
}
Result SdmmcController::SetSpeedMode(SpeedMode speed_mode) {
/* Get the tap value. */
u8 tap_value;
if (speed_mode == SpeedMode_MmcHs400) {
AMS_ABORT_UNLESS(m_is_valid_tap_value_for_hs_400);
tap_value = m_tap_value_for_hs_400;
} else {
tap_value = this->GetDefaultInboundTapValue();
}
/* Set the speed mode. */
R_TRY(this->SetSpeedModeWithTapValue(speed_mode, tap_value));
R_SUCCEED();
}
void SdmmcController::SetPowerSaving(bool en) {
/* If necessary, calibrate the drive strength. */
if (this->IsNeedPeriodicDriveStrengthCalibration() && !en && SdHostStandardController::IsDeviceClockEnable()) {
this->CalibrateDriveStrength(SdHostStandardController::GetBusPower());
}
return SdHostStandardController::SetPowerSaving(en);
}
void SdmmcController::EnableDeviceClock() {
/* If necessary, calibrate the drive strength. */
if (this->IsNeedPeriodicDriveStrengthCalibration() && !SdHostStandardController::IsPowerSavingEnable()) {
this->CalibrateDriveStrength(SdHostStandardController::GetBusPower());
}
return SdHostStandardController::EnableDeviceClock();
}
Result SdmmcController::IssueCommand(const Command *command, TransferData *xfer_data, u32 *out_num_transferred_blocks) {
/* If necessary, calibrate the drive strength. */
if (this->IsNeedPeriodicDriveStrengthCalibration() && SdHostStandardController::IsPowerSavingEnable()) {
this->CalibrateDriveStrength(SdHostStandardController::GetBusPower());
}
R_RETURN(SdHostStandardController::IssueCommand(command, xfer_data, out_num_transferred_blocks));
}
Result SdmmcController::IssueStopTransmissionCommand(u32 *out_response) {
/* If necessary, calibrate the drive strength. */
if (this->IsNeedPeriodicDriveStrengthCalibration() && SdHostStandardController::IsPowerSavingEnable()) {
this->CalibrateDriveStrength(SdHostStandardController::GetBusPower());
}
R_RETURN(SdHostStandardController::IssueStopTransmissionCommand(out_response));
}
Result SdmmcController::Tuning(SpeedMode speed_mode, u32 command_index) {
/* Clear vendor tuning control 1. */
reg::Write(m_sdmmc_registers->vendor_tuning_cntrl1, 0);
/* Determine/configure the number of tries. */
int num_tries;
switch (speed_mode) {
case SpeedMode_MmcHs200:
case SpeedMode_MmcHs400:
case SpeedMode_SdCardSdr104:
num_tries = 128;
reg::ReadWrite(m_sdmmc_registers->vendor_tuning_cntrl0, SD_REG_BITS_ENUM(VENDOR_TUNING_CNTRL0_NUM_TUNING_ITERATIONS, TRIES_128));
break;
case SpeedMode_SdCardSdr50:
case SpeedMode_GcAsicFpgaSpeed:
case SpeedMode_GcAsicSpeed:
num_tries = 256;
reg::ReadWrite(m_sdmmc_registers->vendor_tuning_cntrl0, SD_REG_BITS_ENUM(VENDOR_TUNING_CNTRL0_NUM_TUNING_ITERATIONS, TRIES_256));
break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
/* Configure the multiplier. */
reg::ReadWrite(m_sdmmc_registers->vendor_tuning_cntrl0, SD_REG_BITS_VALUE(VENDOR_TUNING_CNTRL0_MUL_M, 1));
/* Configure tap value to be updated by hardware. */
reg::ReadWrite(m_sdmmc_registers->vendor_tuning_cntrl0, SD_REG_BITS_ENUM(VENDOR_TUNING_CNTRL0_TAP_VALUE_UPDATED_BY_HW, UPDATED_BY_HW));
/* Configure to execute tuning. */
reg::ReadWrite(m_sdmmc_registers->sd_host_standard_registers.host_control2, SD_REG_BITS_ENUM(HOST_CONTROL2_EXECUTE_TUNING, EXECUTE_TUNING));
/* Perform tuning num_tries times. */
for (int i = 0; /* ... */; ++i) {
/* Check if we've been removed. */
R_TRY(this->CheckRemoved());
/* Issue the command. */
this->IssueTuningCommand(command_index);
/* Check if tuning is done. */
if (i >= num_tries) {
break;
}
if (reg::HasValue(m_sdmmc_registers->sd_host_standard_registers.host_control2, SD_REG_BITS_ENUM(HOST_CONTROL2_EXECUTE_TUNING, TUNING_COMPLETED))) {
break;
}
}
/* Check if we're using the tuned clock. */
R_UNLESS(reg::HasValue(m_sdmmc_registers->sd_host_standard_registers.host_control2, SD_REG_BITS_ENUM(HOST_CONTROL2_SAMPLING_CLOCK, USING_TUNED_CLOCK)), sdmmc::ResultTuningFailed());
R_SUCCEED();
}
void SdmmcController::SaveTuningStatusForHs400() {
/* Save the current tap value. */
m_tap_value_for_hs_400 = GetCurrentTapValue();
m_is_valid_tap_value_for_hs_400 = true;
}
Result Sdmmc1Controller::PowerOnForRegisterControl(BusPower bus_power) {
AMS_ABORT_UNLESS(bus_power == BusPower_3_3V);
/* Nintendo sets the current bus power regardless of whether the call succeeds. */
ON_SCOPE_EXIT { m_current_bus_power = BusPower_3_3V; };
/* pcv::PowerOn(pcv::PowerControlTarget_SdCard, 3300000); */
R_TRY(m_power_controller->PowerOn(BusPower_3_3V));
R_SUCCEED();
}
void Sdmmc1Controller::PowerOffForRegisterControl() {
/* If we're already off, there's nothing to do. */
if (m_current_bus_power == BusPower_Off) {
return;
}
/* If we're at 3.3V, lower to 1.8V. */
if (m_current_bus_power == BusPower_3_3V) {
/* pcv::ChangeVoltage(pcv::PowerControlTarget_SdCard, 1800000); */
m_power_controller->LowerBusPower();
/* Set our bus power. */
m_current_bus_power = BusPower_1_8V;
}
/* pinmux::SetPinAssignment(std::addressof(m_pinmux_session), pinmux::PinAssignment_Sdmmc1OutputHigh); */
pinmux_impl::SetPinAssignment(pinmux_impl::PinAssignment_Sdmmc1OutputHigh);
/* pcv::PowerOff(pcv::PowerControlTarget_SdCard); */
m_power_controller->PowerOff();
/* Set our bus power. */
m_current_bus_power = BusPower_Off;
/* pinmux::SetPinAssignment(std::addressof(m_pinmux_session), pinmux::PinAssignment_Sdmmc1ResetState); */
pinmux_impl::SetPinAssignment(pinmux_impl::PinAssignment_Sdmmc1ResetState);
}
Result Sdmmc1Controller::LowerBusPowerForRegisterControl() {
/* Nintendo sets the current bus power regardless of whether the call succeeds. */
ON_SCOPE_EXIT { m_current_bus_power = BusPower_1_8V; };
/* pcv::ChangeVoltage(pcv::PowerControlTarget_SdCard, 1800000); */
R_TRY(m_power_controller->LowerBusPower());
R_SUCCEED();
}
void Sdmmc1Controller::SetSchmittTriggerForRegisterControl(BusPower bus_power) {
SdHostStandardController::EnsureControl();
if (IsSocMariko()) {
/* pinmux::SetPinAssignment(std::addressof(m_pinmux_session), pinmux::PinAssignment_Sdmmc1SchmtEnable); */
pinmux_impl::SetPinAssignment(pinmux_impl::PinAssignment_Sdmmc1SchmtEnable);
} else {
switch (bus_power) {
case BusPower_1_8V:
/* pinmux::SetPinAssignment(std::addressof(m_pinmux_session), pinmux::PinAssignment_Sdmmc1SchmtEnable); */
pinmux_impl::SetPinAssignment(pinmux_impl::PinAssignment_Sdmmc1SchmtEnable);
break;
case BusPower_3_3V:
/* pinmux::SetPinAssignment(std::addressof(m_pinmux_session), pinmux::PinAssignment_Sdmmc1SchmtDisable); */
pinmux_impl::SetPinAssignment(pinmux_impl::PinAssignment_Sdmmc1SchmtDisable);
break;
case BusPower_Off:
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
}
#if defined(AMS_SDMMC_USE_PCV_CLOCK_RESET_CONTROL)
Result Sdmmc1Controller::PowerOnForPcvControl(BusPower bus_power) {
AMS_ABORT_UNLESS(bus_power == BusPower_3_3V);
/* Nintendo sets the current bus power regardless of whether the call succeeds. */
ON_SCOPE_EXIT { m_current_bus_power = BusPower_3_3V; };
/* TODO: R_RETURN(pcv::PowerOn(pcv::PowerControlTarget_SdCard, 3300000)); */
R_SUCCEED();
}
void Sdmmc1Controller::PowerOffForPcvControl() {
/* If we're already off, there's nothing to do. */
if (m_current_bus_power == BusPower_Off) {
return;
}
/* If we're at 3.3V, lower to 1.8V. */
{
/* TODO: pcv::ChangeVoltage(pcv::PowerControlTarget_SdCard, 1800000); */
m_current_bus_power = BusPower_1_8V;
}
/* TODO: pinmux::SetPinAssignment(std::addressof(m_pinmux_session), pinmux::PinAssignment_Sdmmc1OutputHigh); */
/* TODO: pcv::PowerOff(pcv::PowerControlTarget_SdCard); */
m_current_bus_power = BusPower_Off;
/* TODO: pinmux::SetPinAssignment(std::addressof(m_pinmux_session), pinmux::PinAssignment_Sdmmc1ResetState); */
}
Result Sdmmc1Controller::LowerBusPowerForPcvControl() {
/* Nintendo sets the current bus power regardless of whether the call succeeds. */
ON_SCOPE_EXIT { m_current_bus_power = BusPower_1_8V; };
/* TODO: R_RETURN(pcv::ChangeVoltage(pcv::PowerControlTarget_SdCard, 1800000)); */
R_SUCCEED();
}
void Sdmmc1Controller::SetSchmittTriggerForPcvControl(BusPower bus_power) {
SdHostStandardController::EnsureControl();
if (IsSocMariko()) {
/* TODO: pinmux::SetPinAssignment(std::addressof(m_pinmux_session), pinmux::PinAssignment_Sdmmc1SchmtEnable); */
} else {
switch (bus_power) {
case BusPower_1_8V:
/* TODO: pinmux::SetPinAssignment(std::addressof(m_pinmux_session), pinmux::PinAssignment_Sdmmc1SchmtEnable); */
break;
case BusPower_3_3V:
/* TODO: pinmux::SetPinAssignment(std::addressof(m_pinmux_session), pinmux::PinAssignment_Sdmmc1SchmtDisable); */
break;
case BusPower_Off:
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
}
#endif
Result Sdmmc1Controller::PowerOn(BusPower bus_power) {
#if defined(AMS_SDMMC_USE_PCV_CLOCK_RESET_CONTROL)
if (m_is_pcv_control) {
R_RETURN(this->PowerOnForPcvControl(bus_power));
} else
#endif
{
R_RETURN(this->PowerOnForRegisterControl(bus_power));
}
}
void Sdmmc1Controller::PowerOff() {
#if defined(AMS_SDMMC_USE_PCV_CLOCK_RESET_CONTROL)
if (m_is_pcv_control) {
return this->PowerOffForPcvControl();
} else
#endif
{
return this->PowerOffForRegisterControl();
}
}
Result Sdmmc1Controller::LowerBusPower() {
#if defined(AMS_SDMMC_USE_PCV_CLOCK_RESET_CONTROL)
if (m_is_pcv_control) {
R_RETURN(this->LowerBusPowerForPcvControl());
} else
#endif
{
R_RETURN(this->LowerBusPowerForRegisterControl());
}
}
void Sdmmc1Controller::SetSchmittTrigger(BusPower bus_power) {
#if defined(AMS_SDMMC_USE_PCV_CLOCK_RESET_CONTROL)
if (m_is_pcv_control) {
return this->SetSchmittTriggerForPcvControl(bus_power);
} else
#endif
{
return this->SetSchmittTriggerForRegisterControl(bus_power);
}
}
void Sdmmc1Controller::Initialize() {
return this->InitializeForRegisterControl();
}
void Sdmmc1Controller::Finalize() {
#if defined(AMS_SDMMC_USE_PCV_CLOCK_RESET_CONTROL)
if (m_is_pcv_control) {
return this->FinalizeForPcvControl();
} else
#endif
{
return this->FinalizeForRegisterControl();
}
}
void Sdmmc1Controller::InitializeForRegisterControl() {
#if defined(AMS_SDMMC_USE_PCV_CLOCK_RESET_CONTROL)
/* Mark ourselves as initialized by register control. */
m_is_pcv_control = false;
#endif
/* pinmux::Initialize(); */
/* This just opens a session handle to pinmux service, no work to do. */
/* pinmux::OpenSession(std::addressof(m_pinmux_session), pinmux::AssignablePinGroupName_Sdmmc1); */
/* This just sets the session's internal value to the pin group name, so nothing to do here either. */
/* pcv::Initialize(); */
/* This initializes a lot of globals in pcv, most of which we don't care about. */
/* However, we do care about the Sdmmc1PowerController. */
AMS_ABORT_UNLESS(m_power_controller == nullptr);
m_power_controller = util::ConstructAt(m_power_controller_storage);
/* Perform base initialization. */
SdmmcController::Initialize();
}
void Sdmmc1Controller::FinalizeForRegisterControl() {
/* Perform base finalization. */
SdmmcController::Finalize();
/* pcv::Finalize(); */
/* As with initialize, we mostly don't care about the globals this touches. */
/* However, we do want to finalize the Sdmmc1PowerController. */
AMS_ABORT_UNLESS(m_power_controller != nullptr);
m_power_controller = nullptr;
util::DestroyAt(m_power_controller_storage);
/* pinmux::CloseSession(std::addressof(m_pinmux_session)); */
/* This does nothing. */
/* pinmux::Finalize(); */
/* This does nothing. */
#if defined(AMS_SDMMC_USE_PCV_CLOCK_RESET_CONTROL)
/* Mark ourselves as initialized by register control. */
m_is_pcv_control = false;
#endif
}
#if defined(AMS_SDMMC_USE_PCV_CLOCK_RESET_CONTROL)
void Sdmmc1Controller::InitializeForPcvControl() {
/* Mark ourselves as initialized by pcv control. */
m_is_pcv_control = true;
/* TODO: pinmux::Initialize(); */
/* TODO: pinmux::OpenSession(std::addressof(m_pinmux_session), pinmux::AssignablePinGroupName_Sdmmc1); */
/* TODO: pcv::Initialize(); */
/* Perform base initialization. */
SdmmcController::Initialize();
}
void Sdmmc1Controller::FinalizeForPcvControl() {
/* Perform base finalization. */
SdmmcController::Finalize();
/* TODO: pcv::Finalize(); */
/* TODO: pinmux::CloseSession(std::addressof(m_pinmux_session)); */
/* TODO: pinmux::Finalize(); */
/* Mark ourselves as initialized by register control. */
m_is_pcv_control = false;
}
#endif
namespace {
constexpr inline dd::PhysicalAddress PmcRegistersPhysicalAddress = 0x7000E400;
}
Result Sdmmc1Controller::PowerController::ControlVddioSdmmc1(BusPower bus_power) {
/* Configure appropriate voltage. */
switch (bus_power) {
case BusPower_Off:
R_TRY(SetSdCardVoltageEnabled(false));
break;
case BusPower_1_8V:
R_TRY(SetSdCardVoltageValue(1'800'000));
R_TRY(SetSdCardVoltageEnabled(true));
break;
case BusPower_3_3V:
R_TRY(SetSdCardVoltageValue(3'300'000));
R_TRY(SetSdCardVoltageEnabled(true));
break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
R_SUCCEED();
}
void Sdmmc1Controller::PowerController::SetSdmmcIoMode(bool is_3_3V) {
/* Determine the address we're updating. */
constexpr dd::PhysicalAddress ApbdevPmcPwrDetValAddress = PmcRegistersPhysicalAddress + APBDEV_PMC_PWR_DET_VAL;
/* Read the current value. */
u32 value = dd::ReadIoRegister(ApbdevPmcPwrDetValAddress);
/* Mask out the existing bits. */
value &= ~(reg::EncodeMask(PMC_REG_BITS_MASK(PWR_DET_VAL_SDMMC1)));
/* ORR in the new bits. */
value |= reg::Encode(PMC_REG_BITS_ENUM_SEL(PWR_DET_VAL_SDMMC1, is_3_3V, ENABLE, DISABLE));
/* Write the new value. */
dd::WriteIoRegister(ApbdevPmcPwrDetValAddress, value);
/* Read the value back to be sure our write takes. */
dd::ReadIoRegister(ApbdevPmcPwrDetValAddress);
}
void Sdmmc1Controller::PowerController::ControlRailSdmmc1Io(bool is_power_on) {
/* Determine the address we're updating. */
constexpr dd::PhysicalAddress ApbdevPmcNoIoPowerAddress = PmcRegistersPhysicalAddress + APBDEV_PMC_NO_IOPOWER;
/* Read the current value. */
u32 value = dd::ReadIoRegister(ApbdevPmcNoIoPowerAddress);
/* Mask out the existing bits. */
value &= ~(reg::EncodeMask(PMC_REG_BITS_MASK(NO_IOPOWER_SDMMC1)));
/* ORR in the new bits. */
value |= reg::Encode(PMC_REG_BITS_ENUM_SEL(NO_IOPOWER_SDMMC1, is_power_on, DISABLE, ENABLE));
/* Write the new value. */
dd::WriteIoRegister(ApbdevPmcNoIoPowerAddress, value);
/* Read the value back to be sure our write takes. */
dd::ReadIoRegister(ApbdevPmcNoIoPowerAddress);
}
Sdmmc1Controller::PowerController::PowerController() : m_current_bus_power(BusPower_Off) {
/* gpio::Initialize(); */
/* ... */
/* Open gpio session. */
/* gpio::OpenSession(std::addressof(m_gpio_pad_session), gpio::GpioPadName_PowSdEn); */
gpio_impl::OpenSession(gpio_impl::GpioPadName_PowSdEn);
/* Configure the gpio as low/output. */
/* gpio::SetValue(std::addressof(m_gpio_pad_session), gpio::GpioValue_Low); */
gpio_impl::SetValue(gpio_impl::GpioPadName_PowSdEn, gpio_impl::GpioValue_Low);
/* gpio::SetDirection(std::addressof(m_gpio_pad_session), gpio::Direction_Output); */
gpio_impl::SetDirection(gpio_impl::GpioPadName_PowSdEn, gpio_impl::Direction_Output);
}
Sdmmc1Controller::PowerController::~PowerController() {
/* gpio::CloseSession(std::addressof(m_gpio_pad_session)); */
gpio_impl::CloseSession(gpio_impl::GpioPadName_PowSdEn);
/* gpio::Finalize(); */
/* ... */
}
Result Sdmmc1Controller::PowerController::PowerOn(BusPower bus_power) {
/* Bus power should be off, and if it's not we don't need to do anything. */
AMS_ASSERT(m_current_bus_power == BusPower_Off);
R_SUCCEED_IF(m_current_bus_power != BusPower_Off);
/* Power on requires the target bus power be 3.3V. */
AMS_ABORT_UNLESS(bus_power == BusPower_3_3V);
/* Enable the rail. */
this->ControlRailSdmmc1Io(true);
/* Set the SD power GPIO to high. */
/* gpio::SetValue(std::addressof(m_gpio_pad_session), gpio::GpioValue_High); */
gpio_impl::SetValue(gpio_impl::GpioPadName_PowSdEn, gpio_impl::GpioValue_High);
/* Wait 10ms for power change to take. */
WaitMicroSeconds(10000);
/* Configure Sdmmc1 IO as 3.3V. */
this->SetSdmmcIoMode(true);
R_TRY(this->ControlVddioSdmmc1(BusPower_3_3V));
/* Wait 130 us for changes to take. */
WaitMicroSeconds(130);
/* Update our current bus power. */
m_current_bus_power = bus_power;
R_SUCCEED();
}
Result Sdmmc1Controller::PowerController::PowerOff() {
/* Bus power should be on, and if it's not we don't need to do anything. */
AMS_ASSERT(m_current_bus_power != BusPower_Off);
R_SUCCEED_IF(m_current_bus_power == BusPower_Off);
/* Bus power should be 1.8V. */
/* NOTE: the result returned here is 0x8C0 (regulator::ResultIllegalRequest()) on newer firmwares. */
AMS_ASSERT(m_current_bus_power == BusPower_1_8V);
R_UNLESS(m_current_bus_power == BusPower_1_8V, pcv::ResultIllegalRequest());
/* Disable vddio, and wait 4 ms. */
this->ControlVddioSdmmc1(BusPower_Off);
WaitMicroSeconds(4000);
/* Set the SD power GPIO to low. */
/* gpio::SetValue(std::addressof(m_gpio_pad_session), gpio::GpioValue_Low); */
gpio_impl::SetValue(gpio_impl::GpioPadName_PowSdEn, gpio_impl::GpioValue_Low);
/* Wait 239ms for the gpio config to take. */
WaitMicroSeconds(239000);
/* Disable the rail. */
this->ControlRailSdmmc1Io(false);
this->SetSdmmcIoMode(true);
/* Update our current bus power. */
m_current_bus_power = BusPower_Off;
R_SUCCEED();
}
Result Sdmmc1Controller::PowerController::LowerBusPower() {
/* Bus power should be 3.3V, and if it's not we don't need to do anything. */
AMS_ASSERT(m_current_bus_power == BusPower_3_3V);
R_SUCCEED_IF(m_current_bus_power != BusPower_3_3V);
/* Configure as 1.8V, then wait 150us for it to take. */
R_TRY(this->ControlVddioSdmmc1(BusPower_1_8V));
WaitMicroSeconds(150);
this->SetSdmmcIoMode(false);
/* Update our current bus power. */
m_current_bus_power = BusPower_1_8V;
R_SUCCEED();
}
}
| 56,270
|
C++
|
.cpp
| 1,058
| 42.324197
| 211
| 0.621563
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,063
|
sdmmc_mmc_device_accessor.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/sdmmc/impl/sdmmc_mmc_device_accessor.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if defined(ATMOSPHERE_IS_STRATOSPHERE)
#include <stratosphere.hpp>
#elif defined(ATMOSPHERE_IS_MESOSPHERE)
#include <mesosphere.hpp>
#elif defined(ATMOSPHERE_IS_EXOSPHERE)
#include <exosphere.hpp>
#else
#include <vapours.hpp>
#endif
#include "sdmmc_mmc_device_accessor.hpp"
#include "sdmmc_timer.hpp"
namespace ams::sdmmc::impl {
#if defined(AMS_SDMMC_THREAD_SAFE)
#define AMS_SDMMC_LOCK_MMC_DEVICE_MUTEX() std::scoped_lock lk(m_mmc_device.m_device_mutex)
#else
#define AMS_SDMMC_LOCK_MMC_DEVICE_MUTEX()
#endif
namespace {
constexpr inline u32 OcrCardPowerUpStatus = (1 << 31);
constexpr inline u32 OcrAccessMode_Mask = (3 << 29);
constexpr inline u32 OcrAccessMode_SectorMode = (2 << 29);
constexpr inline u8 ManufacturerId_Toshiba = 0x11;
enum DeviceType : u8 {
DeviceType_HighSpeed26MHz = (1u << 0),
DeviceType_HighSpeed52MHz = (1u << 1),
DeviceType_HighSpeedDdr52MHz1_8VOr3_0V = (1u << 2),
DeviceType_HighSpeedDdr52MHz1_2V = (1u << 3),
DeviceType_Hs200Sdr200MHz1_8V = (1u << 4),
DeviceType_Hs200Sdr200MHz1_2V = (1u << 5),
DeviceType_Hs400Sdr200MHz1_8V = (1u << 6),
DeviceType_Hs400Sdr200MHz1_2V = (1u << 7),
};
constexpr bool IsToshibaMmc(const u8 *cid) {
/* Check whether the CID's manufacturer id field is Toshiba. */
AMS_ABORT_UNLESS(cid != nullptr);
return cid[14] == ManufacturerId_Toshiba;
}
constexpr bool IsLessThanSpecification4(const u8 *csd) {
const u8 spec_vers = ((csd[14] >> 2) & 0xF);
return spec_vers < 4;
}
constexpr bool IsBkopAutoEnable(const u8 *ext_csd) {
/* Check the AUTO_EN bit of BKOPS_EN. */
return (ext_csd[163] & (1u << 1)) != 0;
}
constexpr u8 GetDeviceType(const u8 *ext_csd) {
/* Get the DEVICE_TYPE register. */
AMS_ABORT_UNLESS(ext_csd != nullptr);
return ext_csd[196];
}
constexpr bool IsSupportedHs400(u8 device_type) {
return (device_type & DeviceType_Hs400Sdr200MHz1_8V) != 0;
}
constexpr bool IsSupportedHs200(u8 device_type) {
return (device_type & DeviceType_Hs200Sdr200MHz1_8V) != 0;
}
constexpr bool IsSupportedHighSpeed(u8 device_type) {
return (device_type & DeviceType_HighSpeed52MHz) != 0;
}
constexpr u32 GetMemoryCapacityFromExtCsd(const u32 *ext_csd) {
/* Get the SEC_COUNT register. */
AMS_ABORT_UNLESS(ext_csd != nullptr);
return ext_csd[212 / sizeof(u32)];
}
constexpr u32 GetBootPartitionMemoryCapacityFromExtCsd(const u8 *ext_csd) {
/* Get the BOOT_SIZE_MULT register. */
AMS_ABORT_UNLESS(ext_csd != nullptr);
return ext_csd[226] * (128_KB / SectorSize);
}
constexpr Result GetCurrentSpeedModeFromExtCsd(SpeedMode *out, const u8 *ext_csd) {
/* Get the HS_TIMING register. */
AMS_ABORT_UNLESS(out != nullptr);
AMS_ABORT_UNLESS(ext_csd != nullptr);
switch (ext_csd[185] & 0xF) {
case 0: *out = SpeedMode_MmcLegacySpeed; break;
case 1: *out = SpeedMode_MmcHighSpeed; break;
case 2: *out = SpeedMode_MmcHs200; break;
case 3: *out = SpeedMode_MmcHs400; break;
default: R_THROW(sdmmc::ResultUnexpectedMmcExtendedCsdValue());
}
R_SUCCEED();
}
}
void MmcDevice::SetOcrAndHighCapacity(u32 ocr) {
/* Set ocr. */
BaseDevice::SetOcr(ocr);
/* Set high capacity. */
BaseDevice::SetHighCapacity((ocr & OcrAccessMode_Mask) == OcrAccessMode_SectorMode);
}
Result MmcDeviceAccessor::IssueCommandSendOpCond(u32 *out_ocr, BusPower bus_power) const {
/* Get the command argument. */
u32 arg = OcrAccessMode_SectorMode;
switch (bus_power) {
case BusPower_1_8V: arg |= 0x000080; break;
case BusPower_3_3V: arg |= 0x03F800; break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
/* Issue the command. */
constexpr ResponseType CommandResponseType = ResponseType_R3;
Command command(CommandIndex_SendOpCond, arg, CommandResponseType, false);
IHostController *hc = BaseDeviceAccessor::GetHostController();
R_TRY(hc->IssueCommand(std::addressof(command)));
/* Get the response. */
hc->GetLastResponse(out_ocr, sizeof(*out_ocr), CommandResponseType);
R_SUCCEED();
}
Result MmcDeviceAccessor::IssueCommandSetRelativeAddr() const {
/* Get rca. */
const u32 rca = m_mmc_device.GetRca();
AMS_ABORT_UNLESS(rca > 0);
/* Issue comamnd. */
const u32 arg = rca << 16;
R_TRY(BaseDeviceAccessor::IssueCommandAndCheckR1(CommandIndex_SetRelativeAddr, arg, false, DeviceState_Unknown));
R_SUCCEED();
}
Result MmcDeviceAccessor::IssueCommandSwitch(CommandSwitch cs) const {
/* Get the command argument. */
const u32 arg = GetCommandSwitchArgument(cs);
/* Issue the command. */
R_TRY(BaseDeviceAccessor::IssueCommandAndCheckR1(CommandIndex_Switch, arg, true, DeviceState_Unknown));
R_SUCCEED();
}
Result MmcDeviceAccessor::IssueCommandSendExtCsd(void *dst, size_t dst_size) const {
/* Validate the output buffer. */
AMS_ABORT_UNLESS(dst != nullptr);
AMS_ABORT_UNLESS(dst_size >= MmcExtendedCsdSize);
/* Issue the command. */
constexpr ResponseType CommandResponseType = ResponseType_R1;
Command command(CommandIndex_SendExtCsd, 0, CommandResponseType, false);
TransferData xfer_data(dst, MmcExtendedCsdSize, 1, TransferDirection_ReadFromDevice);
IHostController *hc = BaseDeviceAccessor::GetHostController();
R_TRY(hc->IssueCommand(std::addressof(command), std::addressof(xfer_data)));
/* Get the response. */
u32 resp;
hc->GetLastResponse(std::addressof(resp), sizeof(resp), CommandResponseType);
R_TRY(m_mmc_device.CheckDeviceStatus(resp));
R_SUCCEED();
}
Result MmcDeviceAccessor::IssueCommandEraseGroupStart(u32 sector_index) const {
/* Get the command argument. */
const u32 arg = m_mmc_device.IsHighCapacity() ? sector_index : sector_index * SectorSize;
/* Issue the command. */
R_TRY(BaseDeviceAccessor::IssueCommandAndCheckR1(CommandIndex_EraseGroupStart, arg, false, DeviceState_Unknown));
R_SUCCEED();
}
Result MmcDeviceAccessor::IssueCommandEraseGroupEnd(u32 sector_index) const {
/* Get the command argument. */
const u32 arg = m_mmc_device.IsHighCapacity() ? sector_index : sector_index * SectorSize;
/* Issue the command. */
R_TRY(BaseDeviceAccessor::IssueCommandAndCheckR1(CommandIndex_EraseGroupEnd, arg, false, DeviceState_Tran));
R_SUCCEED();
}
Result MmcDeviceAccessor::IssueCommandErase() const {
/* Issue the command. */
R_TRY(BaseDeviceAccessor::IssueCommandAndCheckR1(CommandIndex_Erase, 0, false, DeviceState_Tran));
R_SUCCEED();
}
Result MmcDeviceAccessor::CancelToshibaMmcModel() {
/* Special erase sequence done by Nintendo on Toshiba MMCs. */
R_TRY(this->IssueCommandSwitch(CommandSwitch_SetBitsProductionStateAwarenessEnable));
R_TRY(BaseDeviceAccessor::IssueCommandSendStatus());
R_TRY(this->IssueCommandSwitch(CommandSwitch_ClearBitsAutoModeEnable));
R_TRY(BaseDeviceAccessor::IssueCommandSendStatus());
R_TRY(this->IssueCommandSwitch(CommandSwitch_WriteProductionStateAwarenessPreSolderingWrites));
R_TRY(BaseDeviceAccessor::IssueCommandSendStatus());
R_TRY(this->IssueCommandSwitch(CommandSwitch_WriteProductionStateAwarenessPreSolderingPostWrites));
R_TRY(BaseDeviceAccessor::IssueCommandSendStatus());
R_TRY(this->IssueCommandSwitch(CommandSwitch_WriteProductionStateAwarenessNormal));
R_TRY(BaseDeviceAccessor::IssueCommandSendStatus());
R_SUCCEED();
}
Result MmcDeviceAccessor::ChangeToReadyState(BusPower bus_power) {
/* Be prepared to wait up to 1.5 seconds to change state. */
ManualTimer timer(1500);
while (true) {
/* Get the ocr, and check if we're done. */
u32 ocr;
R_TRY(this->IssueCommandSendOpCond(std::addressof(ocr), bus_power));
if ((ocr & OcrCardPowerUpStatus) != 0) {
m_mmc_device.SetOcrAndHighCapacity(ocr);
R_SUCCEED();
}
/* Check if we've timed out. */
R_UNLESS(timer.Update(), sdmmc::ResultMmcInitializationSoftwareTimeout());
/* Try again in 1ms. */
WaitMicroSeconds(1000);
}
}
Result MmcDeviceAccessor::ExtendBusWidth(BusWidth max_bw) {
/* If the maximum bus width is 1bit, we can't extend. */
R_SUCCEED_IF(max_bw == BusWidth_1Bit);
/* Determine what bus width to switch to. */
IHostController *hc = BaseDeviceAccessor::GetHostController();
BusWidth target_bw = BusWidth_1Bit;
CommandSwitch cs;
if (max_bw == BusWidth_8Bit && hc->IsSupportedBusWidth(BusWidth_8Bit)) {
target_bw = BusWidth_8Bit;
cs = CommandSwitch_WriteBusWidth8Bit;
} else if ((max_bw == BusWidth_8Bit || max_bw == BusWidth_4Bit) && hc->IsSupportedBusWidth(BusWidth_4Bit)) {
target_bw = BusWidth_4Bit;
cs = CommandSwitch_WriteBusWidth4Bit;
} else {
/* Target bus width is 1bit. */
R_SUCCEED();
}
/* Set the bus width. */
R_TRY(this->IssueCommandSwitch(cs));
R_TRY(BaseDeviceAccessor::IssueCommandSendStatus());
hc->SetBusWidth(target_bw);
R_SUCCEED();
}
Result MmcDeviceAccessor::EnableBkopsAuto() {
/* Issue the command. */
R_TRY(this->IssueCommandSwitch(CommandSwitch_SetBitsBkopsEnAutoEn));
R_TRY(BaseDeviceAccessor::IssueCommandSendStatus());
R_SUCCEED();
}
Result MmcDeviceAccessor::ChangeToHighSpeed(bool check_before) {
/* Issue high speed command. */
R_TRY(this->IssueCommandSwitch(CommandSwitch_WriteHsTimingHighSpeed));
/* If we should check status before setting mode, do so. */
if (check_before) {
R_TRY(BaseDeviceAccessor::IssueCommandSendStatus());
}
/* Set the host controller to high speed. */
R_TRY(BaseDeviceAccessor::GetHostController()->SetSpeedMode(SpeedMode_MmcHighSpeed));
/* If we should check status after setting mode, do so. */
if (!check_before) {
R_TRY(BaseDeviceAccessor::IssueCommandSendStatus());
}
R_SUCCEED();
}
Result MmcDeviceAccessor::ChangeToHs200() {
/* Issue Hs200 command. */
R_TRY(this->IssueCommandSwitch(CommandSwitch_WriteHsTimingHs200));
/* Set the host controller to Hs200. */
IHostController *hc = BaseDeviceAccessor::GetHostController();
R_TRY(hc->SetSpeedMode(SpeedMode_MmcHs200));
/* Perform tuning using command index 21. */
R_TRY(hc->Tuning(SpeedMode_MmcHs200, 21));
/* Check status. */
R_TRY(BaseDeviceAccessor::IssueCommandSendStatus());
R_SUCCEED();
}
Result MmcDeviceAccessor::ChangeToHs400() {
/* Change first to Hs200. */
R_TRY(this->ChangeToHs200());
/* Save tuning status. */
IHostController *hc = BaseDeviceAccessor::GetHostController();
hc->SaveTuningStatusForHs400();
/* Change to high speed. */
R_TRY(this->ChangeToHighSpeed(false));
/* Issue Hs400 command. */
R_TRY(this->IssueCommandSwitch(CommandSwitch_WriteBusWidth8BitDdr));
R_TRY(this->IssueCommandSwitch(CommandSwitch_WriteHsTimingHs400));
/* Set the host controller to Hs400. */
R_TRY(hc->SetSpeedMode(SpeedMode_MmcHs400));
/* Check status. */
R_TRY(BaseDeviceAccessor::IssueCommandSendStatus());
R_SUCCEED();
}
Result MmcDeviceAccessor::ExtendBusSpeed(u8 device_type, SpeedMode max_sm) {
/* We want to switch to the highest speed we can. */
/* Check Hs400/Hs200 first. */
IHostController *hc = BaseDeviceAccessor::GetHostController();
if (hc->IsSupportedTuning() && hc->GetBusPower() == BusPower_1_8V) {
if (hc->GetBusWidth() == BusWidth_8Bit && IsSupportedHs400(device_type) && max_sm == SpeedMode_MmcHs400) {
R_RETURN(this->ChangeToHs400());
} else if ((hc->GetBusWidth() == BusWidth_8Bit || hc->GetBusWidth() == BusWidth_4Bit) && IsSupportedHs200(device_type) && (max_sm == SpeedMode_MmcHs400 || max_sm == SpeedMode_MmcHs200)) {
R_RETURN(this->ChangeToHs200());
}
}
/* Check if we can switch to high speed. */
if (IsSupportedHighSpeed(device_type)) {
R_RETURN(this->ChangeToHighSpeed(true));
}
/* We can't, so stay at normal speeds. */
R_SUCCEED();
}
Result MmcDeviceAccessor::StartupMmcDevice(BusWidth max_bw, SpeedMode max_sm, void *wb, size_t wb_size) {
/* Start up at an appropriate bus power. */
IHostController *hc = BaseDeviceAccessor::GetHostController();
const BusPower bp = hc->IsSupportedBusPower(BusPower_1_8V) ? BusPower_1_8V : BusPower_3_3V;
R_TRY(hc->Startup(bp, BusWidth_1Bit, SpeedMode_MmcIdentification, false));
/* Wait 1ms for configuration to take. */
WaitMicroSeconds(1000);
/* Wait an additional 74 clocks for configuration to take. */
WaitClocks(74, hc->GetDeviceClockFrequencyKHz());
/* Go to idle state. */
R_TRY(BaseDeviceAccessor::IssueCommandGoIdleState());
m_current_partition = MmcPartition_UserData;
/* Go to ready state. */
R_TRY(this->ChangeToReadyState(bp));
/* Get the CID. */
R_TRY(BaseDeviceAccessor::IssueCommandAllSendCid(wb, wb_size));
m_mmc_device.SetCid(wb, wb_size);
const bool is_toshiba = IsToshibaMmc(static_cast<const u8 *>(wb));
/* Issue set relative addr. */
R_TRY(this->IssueCommandSetRelativeAddr());
/* Get the CSD. */
R_TRY(BaseDeviceAccessor::IssueCommandSendCsd(wb, wb_size));
m_mmc_device.SetCsd(wb, wb_size);
const bool spec_under_4 = IsLessThanSpecification4(static_cast<const u8 *>(wb));
/* Set the speed mode to legacy. */
R_TRY(hc->SetSpeedMode(SpeedMode_MmcLegacySpeed));
/* Issue select card command. */
R_TRY(BaseDeviceAccessor::IssueCommandSelectCard());
/* Set block length to sector size. */
R_TRY(BaseDeviceAccessor::IssueCommandSetBlockLenToSectorSize());
/* If the device SPEC_VERS is less than 4, extended csd/switch aren't supported. */
if (spec_under_4) {
R_TRY(m_mmc_device.SetLegacyMemoryCapacity());
m_mmc_device.SetActive();
R_SUCCEED();
}
/* Extend the bus width to the largest that we can. */
R_TRY(this->ExtendBusWidth(max_bw));
/* Get the extended csd. */
R_TRY(this->IssueCommandSendExtCsd(wb, wb_size));
AMS_ABORT_UNLESS(util::IsAligned(reinterpret_cast<uintptr_t>(wb), alignof(u32)));
m_mmc_device.SetMemoryCapacity(GetMemoryCapacityFromExtCsd(static_cast<const u32 *>(wb)));
/* If the mmc is manufactured by toshiba, try to enable bkops auto. */
if (is_toshiba && !IsBkopAutoEnable(static_cast<const u8 *>(wb))) {
/* NOTE: Nintendo does not check the result of this. */
this->EnableBkopsAuto();
}
/* Extend the bus speed to as fast as we can. */
const u8 device_type = GetDeviceType(static_cast<const u8 *>(wb));
R_TRY(this->ExtendBusSpeed(device_type, max_sm));
/* Enable power saving. */
hc->SetPowerSaving(true);
R_SUCCEED();
}
Result MmcDeviceAccessor::OnActivate() {
/* Define the possible startup parameters. */
constexpr const struct {
BusWidth bus_width;
SpeedMode speed_mode;
} StartupParameters[] = {
#if defined(AMS_SDMMC_ENABLE_MMC_HS400)
{ BusWidth_8Bit, SpeedMode_MmcHs400 },
#else
{ BusWidth_8Bit, SpeedMode_MmcHighSpeed },
#endif
{ BusWidth_8Bit, SpeedMode_MmcHighSpeed },
{ BusWidth_1Bit, SpeedMode_MmcHighSpeed },
};
/* Try to start up with each set of parameters. */
Result result;
for (int i = 0; i < static_cast<int>(util::size(StartupParameters)); ++i) {
/* Alias the parameters. */
const auto ¶ms = StartupParameters[i];
/* Set our max bus width/speed mode. */
m_max_bus_width = params.bus_width;
m_max_speed_mode = params.speed_mode;
/* Try to start up the device. */
result = this->StartupMmcDevice(m_max_bus_width, m_max_speed_mode, m_work_buffer, m_work_buffer_size);
if (R_SUCCEEDED(result)) {
/* If we previously failed to start up the device, log the error correction. */
if (i != 0) {
BaseDeviceAccessor::PushErrorLog(true, "S %d %d:0", m_max_bus_width, m_max_speed_mode);
BaseDeviceAccessor::IncrementNumActivationErrorCorrections();
}
R_SUCCEED();
}
/* Log that our startup failed. */
BaseDeviceAccessor::PushErrorLog(false, "S %d %d:%X", m_max_bus_width, m_max_speed_mode, result.GetValue());
/* Shut down the host controller before we try to start up again. */
BaseDeviceAccessor::GetHostController()->Shutdown();
}
/* We failed to start up with all sets of parameters. */
BaseDeviceAccessor::PushErrorTimeStamp();
R_RETURN(result);
}
Result MmcDeviceAccessor::OnReadWrite(u32 sector_index, u32 num_sectors, void *buf, size_t buf_size, bool is_read) {
/* Get the sector index alignment. */
u32 sector_index_alignment = 0;
if (!is_read) {
constexpr u32 MmcWriteSectorAlignment = 16_KB / SectorSize;
sector_index_alignment = MmcWriteSectorAlignment;
AMS_ABORT_UNLESS(util::IsAligned(sector_index, MmcWriteSectorAlignment));
}
/* Do the read/write. */
R_RETURN(BaseDeviceAccessor::ReadWriteMultiple(sector_index, num_sectors, sector_index_alignment, buf, buf_size, is_read));
}
Result MmcDeviceAccessor::ReStartup() {
/* Shut down the host controller. */
BaseDeviceAccessor::GetHostController()->Shutdown();
/* Perform start up. */
Result result = this->StartupMmcDevice(m_max_bus_width, m_max_speed_mode, m_work_buffer, m_work_buffer_size);
if (R_FAILED(result)) {
BaseDeviceAccessor::PushErrorLog(false, "S %d %d:%X", m_max_bus_width, m_max_speed_mode, result.GetValue());
R_RETURN(result);
}
R_SUCCEED();
}
void MmcDeviceAccessor::Initialize() {
/* Acquire exclusive access to the device. */
AMS_SDMMC_LOCK_MMC_DEVICE_MUTEX();
/* If we've already initialized, we don't need to do anything. */
if (m_is_initialized) {
return;
}
/* Set the base device to our mmc device. */
BaseDeviceAccessor::SetDevice(std::addressof(m_mmc_device));
/* Initialize. */
BaseDeviceAccessor::GetHostController()->Initialize();
m_is_initialized = true;
}
void MmcDeviceAccessor::Finalize() {
/* Acquire exclusive access to the device. */
AMS_SDMMC_LOCK_MMC_DEVICE_MUTEX();
/* If we've already finalized, we don't need to do anything. */
if (!m_is_initialized) {
return;
}
m_is_initialized = false;
/* Deactivate the device. */
BaseDeviceAccessor::Deactivate();
/* Finalize the host controller. */
BaseDeviceAccessor::GetHostController()->Finalize();
}
Result MmcDeviceAccessor::GetSpeedMode(SpeedMode *out_speed_mode) const {
/* Check that we can write to output. */
AMS_ABORT_UNLESS(out_speed_mode != nullptr);
/* Get the current speed mode from the ext csd. */
R_TRY(GetMmcExtendedCsd(m_work_buffer, m_work_buffer_size));
R_TRY(GetCurrentSpeedModeFromExtCsd(out_speed_mode, static_cast<const u8 *>(m_work_buffer)));
R_SUCCEED();
}
void MmcDeviceAccessor::PutMmcToSleep() {
/* Acquire exclusive access to the device. */
AMS_SDMMC_LOCK_MMC_DEVICE_MUTEX();
/* If the device isn't awake, we don't need to do anything. */
if (!m_mmc_device.IsAwake()) {
return;
}
/* Put the device to sleep. */
m_mmc_device.PutToSleep();
/* If necessary, put the host controller to sleep. */
if (m_mmc_device.IsActive()) {
BaseDeviceAccessor::GetHostController()->PutToSleep();
}
}
void MmcDeviceAccessor::AwakenMmc() {
/* Acquire exclusive access to the device. */
AMS_SDMMC_LOCK_MMC_DEVICE_MUTEX();
/* If the device is awake, we don't need to do anything. */
if (m_mmc_device.IsAwake()) {
return;
}
/* Wake the host controller, if we need to.*/
if (m_mmc_device.IsActive()) {
const Result result = BaseDeviceAccessor::GetHostController()->Awaken();
if (R_FAILED(result)) {
BaseDeviceAccessor::PushErrorLog(true, "A:%X", result.GetValue());
}
}
/* Wake the device. */
m_mmc_device.Awaken();
}
Result MmcDeviceAccessor::SelectMmcPartition(MmcPartition part) {
/* Acquire exclusive access to the device. */
AMS_SDMMC_LOCK_MMC_DEVICE_MUTEX();
/* Check that we can access the device. */
R_TRY(m_mmc_device.CheckAccessible());
/* Determine the appropriate SWITCH subcommand. */
CommandSwitch cs;
switch (part) {
case MmcPartition_UserData: cs = CommandSwitch_WritePartitionAccessDefault; break;
case MmcPartition_BootPartition1: cs = CommandSwitch_WritePartitionAccessRwBootPartition1; break;
case MmcPartition_BootPartition2: cs = CommandSwitch_WritePartitionAccessRwBootPartition2; break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
/* Change partition. */
m_current_partition = MmcPartition_Unknown;
{
R_TRY(this->IssueCommandSwitch(cs));
R_TRY(BaseDeviceAccessor::IssueCommandSendStatus());
}
m_current_partition = part;
R_SUCCEED();
}
Result MmcDeviceAccessor::EraseMmc() {
/* Acquire exclusive access to the device. */
AMS_SDMMC_LOCK_MMC_DEVICE_MUTEX();
/* Check that we can access the device. */
R_TRY(m_mmc_device.CheckAccessible());
/* Get the partition capacity. */
u32 part_capacity;
switch (m_current_partition) {
case MmcPartition_UserData:
part_capacity = m_mmc_device.GetMemoryCapacity();
break;
case MmcPartition_BootPartition1:
case MmcPartition_BootPartition2:
R_TRY(this->GetMmcBootPartitionCapacity(std::addressof(part_capacity)));
break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
/* Begin the erase. */
R_TRY(this->IssueCommandEraseGroupStart(0));
R_TRY(this->IssueCommandEraseGroupEnd(part_capacity - 1));
/* Issue the erase command, allowing 30 seconds for it to complete. */
ManualTimer timer(30000);
Result result = this->IssueCommandErase();
R_TRY_CATCH(result) {
R_CATCH(sdmmc::ResultDataTimeoutError) { /* Data timeout error is acceptable. */ }
R_CATCH(sdmmc::ResultCommandCompleteSoftwareTimeout) { /* Command complete software timeout error is acceptable. */ }
R_CATCH(sdmmc::ResultBusySoftwareTimeout) { /* Busy software timeout error is acceptable. */ }
} R_END_TRY_CATCH;
/* Wait for the erase to finish. */
while (true) {
/* Check if we're done. */
result = BaseDeviceAccessor::IssueCommandSendStatus();
if (R_SUCCEEDED(result)) {
break;
}
/* Otherwise, check if we should reject the error. */
if (!sdmmc::ResultUnexpectedDeviceState::Includes(result)) {
R_RETURN(result);
}
/* Check if timeout has been exceeded. */
R_UNLESS(timer.Update(), sdmmc::ResultMmcEraseSoftwareTimeout());
}
/* If the partition is user data, check if we need to perform toshiba-specific erase. */
if (m_current_partition == MmcPartition_UserData) {
u8 cid[DeviceCidSize];
m_mmc_device.GetCid(cid, sizeof(cid));
if (IsToshibaMmc(cid)) {
/* NOTE: Nintendo does not check the result of this operation. */
this->CancelToshibaMmcModel();
}
}
R_SUCCEED();
}
Result MmcDeviceAccessor::GetMmcBootPartitionCapacity(u32 *out_num_sectors) const {
/* Get the capacity from the extended csd. */
AMS_ABORT_UNLESS(out_num_sectors != nullptr);
R_TRY(this->GetMmcExtendedCsd(m_work_buffer, m_work_buffer_size));
*out_num_sectors = GetBootPartitionMemoryCapacityFromExtCsd(static_cast<const u8 *>(m_work_buffer));
R_SUCCEED();
}
Result MmcDeviceAccessor::GetMmcExtendedCsd(void *dst, size_t dst_size) const {
/* Acquire exclusive access to the device. */
AMS_SDMMC_LOCK_MMC_DEVICE_MUTEX();
/* Check that we can access the device. */
R_TRY(m_mmc_device.CheckAccessible());
/* Get the csd. */
u8 csd[DeviceCsdSize];
m_mmc_device.GetCsd(csd, sizeof(csd));
/* Check that the card supports ext csd. */
R_UNLESS(!IsLessThanSpecification4(csd), sdmmc::ResultMmcNotSupportExtendedCsd());
/* Get the ext csd. */
R_TRY(this->IssueCommandSendExtCsd(dst, dst_size));
R_SUCCEED();
}
}
| 27,538
|
C++
|
.cpp
| 573
| 38.373473
| 200
| 0.624058
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,064
|
sdmmc_gc_asic_device_accessor.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/sdmmc/impl/sdmmc_gc_asic_device_accessor.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if defined(ATMOSPHERE_IS_STRATOSPHERE)
#include <stratosphere.hpp>
#elif defined(ATMOSPHERE_IS_MESOSPHERE)
#include <mesosphere.hpp>
#elif defined(ATMOSPHERE_IS_EXOSPHERE)
#include <exosphere.hpp>
#else
#include <vapours.hpp>
#endif
#include "sdmmc_gc_asic_device_accessor.hpp"
#include "sdmmc_timer.hpp"
namespace ams::sdmmc::impl {
#if defined(AMS_SDMMC_THREAD_SAFE)
#define AMS_SDMMC_LOCK_GC_ASIC_DEVICE_MUTEX() std::scoped_lock lk(m_gc_asic_device.m_device_mutex)
#else
#define AMS_SDMMC_LOCK_GC_ASIC_DEVICE_MUTEX()
#endif
#if defined(AMS_SDMMC_USE_OS_EVENTS)
#define AMS_SDMMC_CHECK_GC_ASIC_REMOVED() R_UNLESS(!m_gc_asic_device.IsRemoved(), sdmmc::ResultDeviceRemoved())
#else
#define AMS_SDMMC_CHECK_GC_ASIC_REMOVED()
#endif
Result GcAsicDeviceAccessor::IssueCommandWriteOperation(const void *op_buf, size_t op_buf_size) const {
/* Validate the operation buffer. */
AMS_ABORT_UNLESS(op_buf != nullptr);
AMS_ABORT_UNLESS(op_buf_size >= GcAsicOperationSize);
/* Issue the command. */
constexpr ResponseType CommandResponseType = ResponseType_R1;
Command command(CommandIndex_GcAsicWriteOperation, 0, CommandResponseType, false);
TransferData xfer_data(const_cast<void *>(op_buf), GcAsicOperationSize, 1, TransferDirection_WriteToDevice);
IHostController *hc = BaseDeviceAccessor::GetHostController();
Result result = hc->IssueCommand(std::addressof(command), std::addressof(xfer_data));
if (R_FAILED(result)) {
/* We failed to write operation. Check if we were removed. */
AMS_SDMMC_CHECK_GC_ASIC_REMOVED();
/* Determine what result we should return. */
Result return_result = result;
{
/* Issue a stop transmission command. */
u32 resp = 0;
result = hc->IssueStopTransmissionCommand(std::addressof(resp));
if (R_SUCCEEDED(result)) {
/* If we successfully stopped transmission but have an error status, we prefer to return that. */
result = m_gc_asic_device.CheckDeviceStatus(resp);
if (R_FAILED(result)) {
return_result = result;
}
}
/* Check again if we were removed. */
AMS_SDMMC_CHECK_GC_ASIC_REMOVED();
/* Request device status. */
u32 device_status;
result = BaseDeviceAccessor::IssueCommandSendStatus(std::addressof(device_status), 0);
/* If we got a device status error here and we didn't previously, we prefer to return that. */
if (!sdmmc::ResultDeviceStatusHasError::Includes(return_result) && sdmmc::ResultDeviceStatusHasError::Includes(result)) {
return_result = result;
}
}
R_RETURN(return_result);
}
/* Get the response. */
u32 resp;
hc->GetLastResponse(std::addressof(resp), sizeof(resp), CommandResponseType);
R_TRY(m_gc_asic_device.CheckDeviceStatus(resp));
R_SUCCEED();
}
Result GcAsicDeviceAccessor::IssueCommandFinishOperation() const {
/* Issue the command. */
R_TRY(BaseDeviceAccessor::IssueCommandAndCheckR1(CommandIndex_GcAsicFinishOperation, 0, true, DeviceState_Tran));
R_SUCCEED();
}
Result GcAsicDeviceAccessor::IssueCommandSleep() {
/* Issue the command. */
R_TRY(BaseDeviceAccessor::IssueCommandAndCheckR1(CommandIndex_GcAsicSleep, 0, true, DeviceState_Tran));
R_SUCCEED();
}
Result GcAsicDeviceAccessor::IssueCommandUpdateKey() const {
/* Issue the command. */
R_TRY(BaseDeviceAccessor::IssueCommandAndCheckR1(CommandIndex_GcAsicUpdateKey, 0, true, DeviceState_Tran));
R_SUCCEED();
}
Result GcAsicDeviceAccessor::StartupGcAsicDevice() {
/* Start up the host controller. */
IHostController *hc = BaseDeviceAccessor::GetHostController();
R_TRY(hc->Startup(BusPower_1_8V, BusWidth_8Bit, SpeedMode_GcAsicSpeed, false));
/* Wait 10 clocks for configuration to take. */
WaitClocks(10, hc->GetDeviceClockFrequencyKHz());
/* Perform tuning with command index 21. */
AMS_ABORT_UNLESS(hc->IsSupportedTuning());
R_TRY(hc->Tuning(SpeedMode_GcAsicSpeed, 21));
/* Set the device as low capacity/no memory. */
m_gc_asic_device.SetHighCapacity(false);
m_gc_asic_device.SetMemoryCapacity(0);
/* Enable power saving. */
hc->SetPowerSaving(true);
R_SUCCEED();
}
Result GcAsicDeviceAccessor::OnActivate() {
/* If we fail to start up the device, ensure the host controller is shut down. */
auto power_guard = SCOPE_GUARD { BaseDeviceAccessor::GetHostController()->Shutdown(); };
/* Try to start up the device. */
R_TRY(this->StartupGcAsicDevice());
/* We started up, so we don't need to power down. */
power_guard.Cancel();
R_SUCCEED();
}
Result GcAsicDeviceAccessor::OnReadWrite(u32 sector_index, u32 num_sectors, void *buf, size_t buf_size, bool is_read) {
/* Check that we're not performing zero-byte rw. */
AMS_ABORT_UNLESS(num_sectors > 0);
/* Check that the buffer is big enough for the rw. */
AMS_ABORT_UNLESS((buf_size / SectorSize) >= num_sectors);
/* Perform the read/write. */
u32 num_transferred_blocks;
R_TRY(BaseDeviceAccessor::ReadWriteSingle(std::addressof(num_transferred_blocks), sector_index, num_sectors, buf, is_read));
/* Require that we read/wrote as many sectors as we expected. */
AMS_ABORT_UNLESS(num_transferred_blocks == num_sectors);
R_SUCCEED();
}
void GcAsicDeviceAccessor::Initialize() {
/* Acquire exclusive access to the device. */
AMS_SDMMC_LOCK_GC_ASIC_DEVICE_MUTEX();
/* If we've already initialized, we don't need to do anything. */
if (m_is_initialized) {
return;
}
/* Set the base device to our gc asic device. */
BaseDeviceAccessor::SetDevice(std::addressof(m_gc_asic_device));
/* Initialize. */
IHostController *hc = BaseDeviceAccessor::GetHostController();
#if defined(AMS_SDMMC_USE_OS_EVENTS)
{
m_gc_asic_device.InitializeRemovedEvent();
hc->PreSetRemovedEvent(m_gc_asic_device.GetRemovedEvent());
}
#endif
hc->Initialize();
/* Mark ourselves as initialized. */
m_is_initialized = true;
}
void GcAsicDeviceAccessor::Finalize() {
/* Acquire exclusive access to the device. */
AMS_SDMMC_LOCK_GC_ASIC_DEVICE_MUTEX();
/* If we've already finalized, we don't need to do anything. */
if (!m_is_initialized) {
return;
}
m_is_initialized = false;
/* Deactivate the device. */
BaseDeviceAccessor::Deactivate();
/* Finalize the host controller. */
BaseDeviceAccessor::GetHostController()->Finalize();
/* Finalize the removed event. */
#if defined(AMS_SDMMC_USE_OS_EVENTS)
{
m_gc_asic_device.FinalizeRemovedEvent();
}
#endif
}
Result GcAsicDeviceAccessor::GetSpeedMode(SpeedMode *out_speed_mode) const {
/* Check that we can write to output. */
AMS_ABORT_UNLESS(out_speed_mode != nullptr);
/* Acquire exclusive access to the device. */
AMS_SDMMC_LOCK_GC_ASIC_DEVICE_MUTEX();
/* Check that we're accessible. */
R_TRY(m_gc_asic_device.CheckAccessible());
*out_speed_mode = SpeedMode_GcAsicSpeed;
R_SUCCEED();
}
void GcAsicDeviceAccessor::PutGcAsicToSleep() {
/* Acquire exclusive access to the device. */
AMS_SDMMC_LOCK_GC_ASIC_DEVICE_MUTEX();
/* If the device isn't awake, we don't need to do anything. */
if (!m_gc_asic_device.IsAwake()) {
return;
}
/* If necessary, put the host controller to sleep. */
#if defined(AMS_SDMMC_USE_OS_EVENTS)
if (m_gc_asic_device.IsActive() && !m_gc_asic_device.IsRemoved())
#else
if (m_gc_asic_device.IsActive())
#endif
{
BaseDeviceAccessor::GetHostController()->PutToSleep();
}
/* Put the gc asic device to sleep. */
m_gc_asic_device.PutToSleep();
}
Result GcAsicDeviceAccessor::AwakenGcAsic() {
/* Acquire exclusive access to the device. */
AMS_SDMMC_LOCK_GC_ASIC_DEVICE_MUTEX();
/* If the device is awake, we don't need to do anything. */
R_SUCCEED_IF(m_gc_asic_device.IsAwake());
/* Wake the device. */
m_gc_asic_device.Awaken();
/* Wake the host controller, if we need to.*/
#if defined(AMS_SDMMC_USE_OS_EVENTS)
if (m_gc_asic_device.IsActive() && !m_gc_asic_device.IsRemoved())
#else
if (m_gc_asic_device.IsActive())
#endif
{
R_TRY(BaseDeviceAccessor::GetHostController()->Awaken());
}
R_SUCCEED();
}
Result GcAsicDeviceAccessor::WriteGcAsicOperation(const void *op_buf, size_t op_buf_size) {
/* Acquire exclusive access to the device. */
AMS_SDMMC_LOCK_GC_ASIC_DEVICE_MUTEX();
/* Check that we're accessible. */
R_TRY(m_gc_asic_device.CheckAccessible());
/* Issue the command. */
R_TRY(this->IssueCommandWriteOperation(op_buf, op_buf_size));
R_TRY(BaseDeviceAccessor::IssueCommandSendStatus());
R_SUCCEED();
}
Result GcAsicDeviceAccessor::FinishGcAsicOperation() {
/* Acquire exclusive access to the device. */
AMS_SDMMC_LOCK_GC_ASIC_DEVICE_MUTEX();
/* Check that we're accessible. */
R_TRY(m_gc_asic_device.CheckAccessible());
/* Issue the command. */
R_TRY(this->IssueCommandFinishOperation());
R_TRY(BaseDeviceAccessor::IssueCommandSendStatus());
R_SUCCEED();
}
Result GcAsicDeviceAccessor::AbortGcAsicOperation() {
/* Acquire exclusive access to the device. */
AMS_SDMMC_LOCK_GC_ASIC_DEVICE_MUTEX();
/* Check that we're accessible. */
R_TRY(m_gc_asic_device.CheckAccessible());
/* Issue stop transmission command. */
u32 resp = 0;
R_TRY(BaseDeviceAccessor::GetHostController()->IssueStopTransmissionCommand(std::addressof(resp)));
R_TRY(m_gc_asic_device.CheckDeviceStatus(resp));
R_SUCCEED();
}
Result GcAsicDeviceAccessor::SleepGcAsic() {
/* Acquire exclusive access to the device. */
AMS_SDMMC_LOCK_GC_ASIC_DEVICE_MUTEX();
/* Check that we're accessible. */
R_TRY(m_gc_asic_device.CheckAccessible());
/* Issue the command. */
R_TRY(this->IssueCommandSleep());
R_TRY(BaseDeviceAccessor::IssueCommandSendStatus());
R_SUCCEED();
}
Result GcAsicDeviceAccessor::UpdateGcAsicKey() {
/* Acquire exclusive access to the device. */
AMS_SDMMC_LOCK_GC_ASIC_DEVICE_MUTEX();
/* Check that we're accessible. */
R_TRY(m_gc_asic_device.CheckAccessible());
/* Issue the command. */
R_TRY(this->IssueCommandUpdateKey());
R_TRY(BaseDeviceAccessor::IssueCommandSendStatus());
R_SUCCEED();
}
}
| 12,214
|
C++
|
.cpp
| 272
| 36.088235
| 137
| 0.633873
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,065
|
sdmmc_clock_reset_controller.board.nintendo_nx.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/sdmmc/impl/sdmmc_clock_reset_controller.board.nintendo_nx.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if defined(ATMOSPHERE_IS_STRATOSPHERE)
#include <stratosphere.hpp>
#elif defined(ATMOSPHERE_IS_MESOSPHERE)
#include <mesosphere.hpp>
#elif defined(ATMOSPHERE_IS_EXOSPHERE)
#include <exosphere.hpp>
#else
#include <vapours.hpp>
#endif
#include "sdmmc_clock_reset_controller.hpp"
#include "sdmmc_clock_reset_controller.reg.board.nintendo_nx.hpp"
#include "sdmmc_clock_reset_controller.pcv.board.nintendo_nx.hpp"
namespace ams::sdmmc::impl::ClockResetController {
namespace {
constinit bool g_is_module_initialized[Module_Count] = {};
#if defined(AMS_SDMMC_THREAD_SAFE)
constinit os::SdkMutex g_module_mutex;
#define AMS_SDMMC_LOCK_MODULE_MUTEX() std::scoped_lock lk(g_module_mutex)
#else
#define AMS_SDMMC_LOCK_MODULE_MUTEX()
#endif
#if defined(AMS_SDMMC_USE_PCV_CLOCK_RESET_CONTROL)
constinit bool g_is_pcv_control = false;
#define AMS_SDMMC_IF_IS_PCV_CONTROL() if (g_is_pcv_control)
#else
#define AMS_SDMMC_IF_IS_PCV_CONTROL() if constexpr (false)
#endif
}
void Initialize(Module module) {
/* Acquire exclusive access to module state. */
AMS_SDMMC_LOCK_MODULE_MUTEX();
/* Mark the module as initialized. */
g_is_module_initialized[module] = true;
/* Initialize the module. */
AMS_SDMMC_IF_IS_PCV_CONTROL() {
ClockResetController::pcv::Initialize(module);
} else {
ClockResetController::reg::Initialize(module);
}
}
void Finalize(Module module) {
/* Acquire exclusive access to module state. */
AMS_SDMMC_LOCK_MODULE_MUTEX();
/* Finalize the module. */
AMS_SDMMC_IF_IS_PCV_CONTROL() {
ClockResetController::pcv::Finalize(module);
} else {
ClockResetController::reg::Finalize(module);
}
/* Mark the module as finalized. */
g_is_module_initialized[module] = false;
}
bool IsAvailable(Module module) {
AMS_SDMMC_IF_IS_PCV_CONTROL() {
return ClockResetController::pcv::IsAvailable(module);
} else {
return ClockResetController::reg::IsAvailable(module);
}
}
#if defined(AMS_SDMMC_USE_PCV_CLOCK_RESET_CONTROL)
void SwitchToPcvControl() {
/* Acquire exclusive access to module state. */
AMS_SDMMC_LOCK_MODULE_MUTEX();
/* If we're already using pcv control, we don't need to do anything. */
AMS_SDMMC_IF_IS_PCV_CONTROL() {
return;
}
/* Finalize all modules. */
for (int i = 0; i < Module_Count; ++i) {
if (g_is_module_initialized[i]) {
ClockResetController::reg::Finalize(static_cast<Module>(i));
}
}
/* Mark that we've switched to pcv control. */
/* Initialize modules using pcv control. */
for (int i = 0; i < Module_Count; ++i) {
if (g_is_module_initialized[i]) {
ClockResetController::pcv::Initialize(static_cast<Module>(i));
}
}
}
#endif
void SetClockFrequencyKHz(u32 *out_actual_frequency, Module module, u32 target_frequency) {
AMS_SDMMC_IF_IS_PCV_CONTROL() {
return ClockResetController::pcv::SetClockFrequencyKHz(out_actual_frequency, module, target_frequency);
} else {
return ClockResetController::reg::SetClockFrequencyKHz(out_actual_frequency, module, target_frequency);
}
}
void AssertReset(Module module) {
AMS_SDMMC_IF_IS_PCV_CONTROL() {
return ClockResetController::pcv::AssertReset(module);
} else {
return ClockResetController::reg::AssertReset(module);
}
}
void ReleaseReset(Module module, u32 target_frequency_khz) {
AMS_SDMMC_IF_IS_PCV_CONTROL() {
return ClockResetController::pcv::ReleaseReset(module, target_frequency_khz);
} else {
return ClockResetController::reg::ReleaseReset(module, target_frequency_khz);
}
}
}
| 4,756
|
C++
|
.cpp
| 119
| 32.226891
| 115
| 0.644517
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,066
|
sdmmc_port_mmc0.board.nintendo_nx.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/sdmmc/impl/sdmmc_port_mmc0.board.nintendo_nx.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if defined(ATMOSPHERE_IS_STRATOSPHERE)
#include <stratosphere.hpp>
#elif defined(ATMOSPHERE_IS_MESOSPHERE)
#include <mesosphere.hpp>
#elif defined(ATMOSPHERE_IS_EXOSPHERE)
#include <exosphere.hpp>
#else
#include <vapours.hpp>
#endif
#include "sdmmc_port_mmc0.hpp"
#include "sdmmc_select_sdmmc_controller.hpp"
#include "sdmmc_base_device_accessor.hpp"
namespace ams::sdmmc::impl {
namespace {
SdmmcControllerForPortMmc0 g_mmc0_host_controller;
MmcDeviceAccessor g_mmc0_device_accessor(std::addressof(g_mmc0_host_controller));
}
IHostController *GetHostControllerOfPortMmc0() {
return std::addressof(g_mmc0_host_controller);
}
IDeviceAccessor *GetDeviceAccessorOfPortMmc0() {
return std::addressof(g_mmc0_device_accessor);
}
MmcDeviceAccessor *GetMmcDeviceAccessorOfPortMmc0() {
return std::addressof(g_mmc0_device_accessor);
}
}
| 1,545
|
C++
|
.cpp
| 42
| 33.52381
| 89
| 0.756359
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,067
|
sdmmc_io_impl.board.nintendo_nx.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/sdmmc/impl/sdmmc_io_impl.board.nintendo_nx.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if defined(ATMOSPHERE_IS_STRATOSPHERE)
#include <stratosphere.hpp>
#elif defined(ATMOSPHERE_IS_MESOSPHERE)
#include <mesosphere.hpp>
#elif defined(ATMOSPHERE_IS_EXOSPHERE)
#include <exosphere.hpp>
#else
#include <vapours.hpp>
#endif
#include "sdmmc_timer.hpp"
#include "sdmmc_sdmmc_controller.board.nintendo_nx.hpp"
#include "sdmmc_io_impl.board.nintendo_nx.hpp"
namespace ams::sdmmc::impl {
/* Lovingly taken from libexosphere. */
namespace i2c_impl {
enum Port {
Port_1 = 0,
/* TODO: Support other ports? */
Port_5 = 4,
Port_Count = 5,
};
constexpr inline const dd::PhysicalAddress I2c5RegistersAddress = UINT64_C(0x7000D000);
constexpr inline const size_t I2c5RegistersSize = 4_KB;
namespace {
constexpr inline size_t MaxTransferSize = sizeof(u32);
constinit std::array<uintptr_t, Port_Count> g_register_addresses = [] {
std::array<uintptr_t, Port_Count> arr = {};
return arr;
}();
void LoadConfig(uintptr_t address) {
/* Configure for TIMEOUT and MSTR config load. */
/* NOTE: Nintendo writes value 1 to reserved bit 5 here. This bit is documented as having no meaning. */
/* We will reproduce the write just in case it is undocumented. */
reg::Write(address + I2C_CONFIG_LOAD, I2C_REG_BITS_VALUE(CONFIG_LOAD_RESERVED_BIT_5, 1),
I2C_REG_BITS_ENUM (CONFIG_LOAD_TIMEOUT_CONFIG_LOAD, ENABLE),
I2C_REG_BITS_ENUM (CONFIG_LOAD_SLV_CONFIG_LOAD, DISABLE),
I2C_REG_BITS_ENUM (CONFIG_LOAD_MSTR_CONFIG_LOAD, ENABLE));
/* Wait up to 20 microseconds for the master config to be loaded. */
for (int i = 0; i < 20; ++i) {
if (reg::HasValue(address + I2C_CONFIG_LOAD, I2C_REG_BITS_ENUM(CONFIG_LOAD_MSTR_CONFIG_LOAD, DISABLE))) {
return;
}
util::WaitMicroSeconds(1);
}
}
void ClearBus(uintptr_t address) {
/* Configure the bus clear register. */
reg::Write(address + I2C_BUS_CLEAR_CONFIG, I2C_REG_BITS_VALUE(BUS_CLEAR_CONFIG_BC_SCLK_THRESHOLD, 9),
I2C_REG_BITS_ENUM (BUS_CLEAR_CONFIG_BC_STOP_COND, NO_STOP),
I2C_REG_BITS_ENUM (BUS_CLEAR_CONFIG_BC_TERMINATE, IMMEDIATE),
I2C_REG_BITS_ENUM (BUS_CLEAR_CONFIG_BC_ENABLE, ENABLE));
/* Load the config. */
LoadConfig(address);
/* Wait up to 250us (in 25 us increments) until the bus clear is done. */
for (int i = 0; i < 10; ++i) {
if (reg::HasValue(address + I2C_INTERRUPT_STATUS_REGISTER, I2C_REG_BITS_ENUM(INTERRUPT_STATUS_REGISTER_BUS_CLEAR_DONE, SET))) {
break;
}
util::WaitMicroSeconds(25);
}
/* Read the bus clear status. */
reg::Read(address + I2C_BUS_CLEAR_STATUS);
}
void InitializePort(uintptr_t address) {
/* Calculate the divisor. */
constexpr int Divisor = util::DivideUp(19200, 8 * 400);
/* Set the divisor. */
reg::Write(address + I2C_CLK_DIVISOR_REGISTER, I2C_REG_BITS_VALUE(CLK_DIVISOR_REGISTER_STD_FAST_MODE, Divisor - 1),
I2C_REG_BITS_VALUE(CLK_DIVISOR_REGISTER_HSMODE, 1));
/* Clear the bus. */
ClearBus(address);
/* Clear the status. */
reg::Write(address + I2C_INTERRUPT_STATUS_REGISTER, reg::Read(address + I2C_INTERRUPT_STATUS_REGISTER));
}
bool Write(uintptr_t base_address, Port port, int address, const void *src, size_t src_size, bool unused) {
AMS_UNUSED(port, unused);
/* Ensure we don't write too much. */
u32 data = 0;
if (src_size > MaxTransferSize) {
return false;
}
/* Copy the data to a transfer word. */
std::memcpy(std::addressof(data), src, src_size);
/* Configure the to write the 7-bit address. */
reg::Write(base_address + I2C_I2C_CMD_ADDR0, I2C_REG_BITS_VALUE(I2C_CMD_ADDR0_7BIT_ADDR, address),
I2C_REG_BITS_ENUM (I2C_CMD_ADDR0_7BIT_RW, WRITE));
/* Configure to write the data. */
reg::Write(base_address + I2C_I2C_CMD_DATA1, data);
/* Configure to write the correct amount of data. */
reg::Write(base_address + I2C_I2C_CNFG, I2C_REG_BITS_ENUM (I2C_CNFG_DEBOUNCE_CNT, DEBOUNCE_4T),
I2C_REG_BITS_ENUM (I2C_CNFG_NEW_MASTER_FSM, ENABLE),
I2C_REG_BITS_ENUM (I2C_CNFG_CMD1, WRITE),
I2C_REG_BITS_VALUE(I2C_CNFG_LENGTH, src_size - 1));
/* Load the configuration. */
LoadConfig(base_address);
/* Start the command. */
reg::ReadWrite(base_address + I2C_I2C_CNFG, I2C_REG_BITS_ENUM(I2C_CNFG_SEND, GO));
/* Wait for the command to be done. */
while (!reg::HasValue(base_address + I2C_I2C_STATUS, I2C_REG_BITS_ENUM(I2C_STATUS_BUSY, NOT_BUSY))) { /* ... */ }
/* Check if the transfer was successful. */
return reg::HasValue(base_address + I2C_I2C_STATUS, I2C_REG_BITS_ENUM(I2C_STATUS_CMD1_STAT, SL1_XFER_SUCCESSFUL));
}
bool Read(uintptr_t base_address, Port port, void *dst, size_t dst_size, int address, bool unused) {
AMS_UNUSED(port, unused);
/* Ensure we don't read too much. */
if (dst_size > MaxTransferSize) {
return false;
}
/* Configure the to read the 7-bit address. */
reg::Write(base_address + I2C_I2C_CMD_ADDR0, I2C_REG_BITS_VALUE(I2C_CMD_ADDR0_7BIT_ADDR, address),
I2C_REG_BITS_ENUM (I2C_CMD_ADDR0_7BIT_RW, READ));
/* Configure to read the correct amount of data. */
reg::Write(base_address + I2C_I2C_CNFG, I2C_REG_BITS_ENUM (I2C_CNFG_DEBOUNCE_CNT, DEBOUNCE_4T),
I2C_REG_BITS_ENUM (I2C_CNFG_NEW_MASTER_FSM, ENABLE),
I2C_REG_BITS_ENUM (I2C_CNFG_CMD1, READ),
I2C_REG_BITS_VALUE(I2C_CNFG_LENGTH, dst_size - 1));
/* Load the configuration. */
LoadConfig(base_address);
/* Start the command. */
reg::ReadWrite(base_address + I2C_I2C_CNFG, I2C_REG_BITS_ENUM(I2C_CNFG_SEND, GO));
/* Wait for the command to be done. */
while (!reg::HasValue(base_address + I2C_I2C_STATUS, I2C_REG_BITS_ENUM(I2C_STATUS_BUSY, NOT_BUSY))) { /* ... */ }
/* Check that the transfer was successful. */
if (!reg::HasValue(base_address + I2C_I2C_STATUS, I2C_REG_BITS_ENUM(I2C_STATUS_CMD1_STAT, SL1_XFER_SUCCESSFUL))) {
return false;
}
/* Read and copy out the data. */
u32 data = reg::Read(base_address + I2C_I2C_CMD_DATA1);
std::memcpy(dst, std::addressof(data), dst_size);
return true;
}
}
void SetRegisterAddress(Port port, uintptr_t address) {
g_register_addresses[port] = address;
}
void Initialize(Port port) {
InitializePort(g_register_addresses[port]);
}
bool Query(void *dst, size_t dst_size, Port port, int address, int r) {
const uintptr_t base_address = g_register_addresses[port];
/* Select the register we want to read. */
bool success = Write(base_address, port, address, std::addressof(r), 1, false);
if (success) {
/* If we successfully selected, read data from the register. */
success = Read(base_address, port, dst, dst_size, address, true);
}
return success;
}
bool Send(Port port, int address, int r, const void *src, size_t src_size) {
const uintptr_t base_address = g_register_addresses[port];
/* Create a transfer buffer, make sure we can use it. */
u8 buffer[MaxTransferSize];
if (src_size > sizeof(buffer) - 1) {
return false;
}
/* Copy data into the buffer. */
buffer[0] = static_cast<u8>(r);
std::memcpy(buffer + 1, src, src_size);
return Write(base_address, port, address, buffer, src_size + 1, false);
}
}
namespace max7762x {
/* The only regulator we care about for SD card power is ldo2. */
constexpr inline const u8 Max77620PwrI2cAddr = 0x3C;
constexpr inline const u32 Max77620Ldo2MvStep = 50'000; /* 50 mV (50K uV) steps. */
constexpr inline const u32 Max77620Ldo2MvMin = 800'000; /* 0.8V min voltage. */
constexpr inline const u32 Max77620Ldo2MvDefault = 1'800'000; /* 1.8V default voltage. */
constexpr inline const u32 Max77620Ldo2MvMax = 3'300'000; /* 3.3V max voltage. */
constexpr inline const u8 Max77620Ldo2VoltAddr = 0x27;
constexpr inline const u8 Max77620Ldo2CfgAddr = 0x28;
constexpr inline const u8 Max77620Ldo2VoltMask = 0x3F;
constexpr inline const u8 Max77620Ldo2EnableMask = 0xC0;
constexpr inline const u8 Max77620Ldo2EnableShift = 0x6;
constexpr inline const u8 Max77620Ldo2StatusMask = 0x00;
namespace {
#if defined(AMS_SDMMC_THREAD_SAFE)
constinit os::SdkMutex g_i2c_init_mutex;
#define AMS_SDMMC_LOCK_I2C_INIT_MUTEX() std::scoped_lock lk(g_i2c_init_mutex)
#else
#define AMS_SDMMC_LOCK_I2C_INIT_MUTEX()
#endif
constinit bool g_initialized_i2c = false;
void EnsureI2cInitialized() {
if (AMS_UNLIKELY(!g_initialized_i2c)) {
/* Ensure we have exclusive access to the i2c init status. */
AMS_SDMMC_LOCK_I2C_INIT_MUTEX();
if (AMS_LIKELY(!g_initialized_i2c)) {
i2c_impl::SetRegisterAddress(i2c_impl::Port_5, dd::QueryIoMapping(i2c_impl::I2c5RegistersAddress, i2c_impl::I2c5RegistersSize));
i2c_impl::Initialize(i2c_impl::Port_5);
g_initialized_i2c = true;
}
}
}
}
bool SetVoltageEnabled(bool en) {
/* Ensure that we can use i2c to communicate with the max7762x regulator. */
EnsureI2cInitialized();
/* Read the current value. */
u8 val;
if (!i2c_impl::Query(std::addressof(val), sizeof(val), i2c_impl::Port_5, Max77620PwrI2cAddr, Max77620Ldo2VoltAddr)) {
return false;
}
/* Set or clear the enable mask. */
val &= ~Max77620Ldo2EnableMask;
if (en) {
val |= ((3 << Max77620Ldo2EnableShift) & Max77620Ldo2EnableMask);
}
/* Write the updated value. */
if (!i2c_impl::Send(i2c_impl::Port_5, Max77620PwrI2cAddr, Max77620Ldo2VoltAddr, std::addressof(val), sizeof(val))) {
return false;
}
/* Wait 1ms for change to take. */
WaitMicroSeconds(1);
/* Voltage is now enabled/disabled. */
return true;
}
bool SetVoltageValue(u32 micro_volts) {
/* Ensure that we can use i2c to communicate with the max7762x regulator. */
EnsureI2cInitialized();
/* Check that the value is within range. */
if (micro_volts < Max77620Ldo2MvMin || Max77620Ldo2MvMax < micro_volts) {
return false;
}
/* Determine the mult. */
const u32 mult = util::DivideUp(micro_volts - Max77620Ldo2MvMin, Max77620Ldo2MvStep);
/* Read the current value. */
u8 val;
if (!i2c_impl::Query(std::addressof(val), sizeof(val), i2c_impl::Port_5, Max77620PwrI2cAddr, Max77620Ldo2VoltAddr)) {
return false;
}
/* Set the new voltage. */
val &= ~Max77620Ldo2VoltMask;
val |= (mult & Max77620Ldo2VoltMask);
/* Write the updated value. */
if (!i2c_impl::Send(i2c_impl::Port_5, Max77620PwrI2cAddr, Max77620Ldo2VoltAddr, std::addressof(val), sizeof(val))) {
return false;
}
/* Wait 1ms for change to take. */
WaitMicroSeconds(1);
/* Voltage is now set. */
return true;
}
}
Result SetSdCardVoltageEnabled(bool en) {
/* TODO: A way for this to be non-fatal? */
AMS_ABORT_UNLESS(max7762x::SetVoltageEnabled(en));
R_SUCCEED();
}
Result SetSdCardVoltageValue(u32 micro_volts) {
/* TODO: A way for this to be non-fatal? */
AMS_ABORT_UNLESS(max7762x::SetVoltageValue(micro_volts));
R_SUCCEED();
}
namespace gpio_impl {
namespace {
constexpr inline dd::PhysicalAddress GpioRegistersPhysicalAddress = 0x6000d000;
constexpr inline size_t GpioRegistersSize = 4_KB;
enum GpioPadPort {
GpioPadPort_A = 0,
GpioPadPort_B = 1,
GpioPadPort_C = 2,
GpioPadPort_D = 3,
GpioPadPort_E = 4,
GpioPadPort_F = 5,
GpioPadPort_G = 6,
GpioPadPort_H = 7,
GpioPadPort_I = 8,
GpioPadPort_J = 9,
GpioPadPort_K = 10,
GpioPadPort_L = 11,
GpioPadPort_M = 12,
GpioPadPort_N = 13,
GpioPadPort_O = 14,
GpioPadPort_P = 15,
GpioPadPort_Q = 16,
GpioPadPort_R = 17,
GpioPadPort_S = 18,
GpioPadPort_T = 19,
GpioPadPort_U = 20,
GpioPadPort_V = 21,
GpioPadPort_W = 22,
GpioPadPort_X = 23,
GpioPadPort_Y = 24,
GpioPadPort_Z = 25,
GpioPadPort_AA = 26,
GpioPadPort_BB = 27,
GpioPadPort_CC = 28,
GpioPadPort_DD = 29,
GpioPadPort_EE = 30,
GpioPadPort_FF = 31,
};
consteval unsigned int GetInternalGpioPadNumber(GpioPadPort port, unsigned int which) {
AMS_ASSUME(which < 8);
return (static_cast<unsigned int>(port) * 8) + which;
}
enum InternalGpioPadNumber {
InternalGpioPadNumber_E4 = GetInternalGpioPadNumber(GpioPadPort_E, 4),
InternalGpioPadNumber_M0 = GetInternalGpioPadNumber(GpioPadPort_M, 0),
};
constexpr int ConvertInternalGpioPadNumberToController(InternalGpioPadNumber number) {
return (number >> 5);
}
constexpr int ConvertInternalGpioPadNumberToPort(InternalGpioPadNumber number) {
return (number >> 3);
}
constexpr int ConvertInternalGpioPadNumberToBitIndex(InternalGpioPadNumber number) {
return (number & 7);
}
constexpr int ConvertPortNumberToOffset(int port_number) {
return (port_number & 3);
}
struct PadNameToInternalPadNumberEntry {
GpioPadName pad_name;
InternalGpioPadNumber internal_number;
};
constexpr inline const PadNameToInternalPadNumberEntry PadNameToInternalPadNumberTable[] = {
{ GpioPadName_PowSdEn, InternalGpioPadNumber_E4 },
};
constexpr InternalGpioPadNumber ConvertPadNameToInternalPadNumber(GpioPadName pad) {
const PadNameToInternalPadNumberEntry *target = nullptr;
for (const auto &entry : PadNameToInternalPadNumberTable) {
if (entry.pad_name == pad) {
target = std::addressof(entry);
break;
}
}
AMS_ABORT_UNLESS(target != nullptr);
return target->internal_number;
}
enum GpioRegisterType {
GpioRegisterType_GPIO_CNF = 0,
GpioRegisterType_GPIO_OE = 1,
GpioRegisterType_GPIO_OUT = 2,
GpioRegisterType_GPIO_IN = 3,
GpioRegisterType_GPIO_INT_STA = 4,
GpioRegisterType_GPIO_INT_ENB = 5,
GpioRegisterType_GPIO_INT_LVL = 6,
GpioRegisterType_GPIO_INT_CLR = 7,
GpioRegisterType_GPIO_DB_CTRL = 8,
GpioRegisterType_GPIO_DB_CNT = 9,
};
constexpr inline uintptr_t MaskedWriteAddressOffset = 0x80;
constexpr inline int MaskedWriteBitOffset = 8;
constexpr uintptr_t GetGpioRegisterAddress(uintptr_t gpio_address, GpioRegisterType reg_type, InternalGpioPadNumber pad_number) {
const auto controller = ConvertInternalGpioPadNumberToController(pad_number);
const auto port = ConvertInternalGpioPadNumberToPort(pad_number);
const auto offset = ConvertPortNumberToOffset(port);
switch (reg_type) {
default:
return gpio_address + (0x100 * controller) + (0x10 * reg_type) + (0x4 * offset);
case GpioRegisterType_GPIO_DB_CTRL:
return gpio_address + (0x100 * controller) + (0x10 * GpioRegisterType_GPIO_IN) + (0x4 * offset);
case GpioRegisterType_GPIO_DB_CNT:
return gpio_address + (0x100 * controller) + MaskedWriteAddressOffset + (0x10 * GpioRegisterType_GPIO_INT_CLR) + (0x4 * offset);
}
}
void SetMaskedBit(uintptr_t pad_address, int index, int value) {
const uintptr_t mask_address = pad_address + MaskedWriteAddressOffset;
reg::Write(mask_address, (1u << (MaskedWriteBitOffset + index)) | (static_cast<unsigned int>(value) << index));
}
void SetMaskedBits(uintptr_t pad_address, unsigned int mask, unsigned int value) {
const uintptr_t mask_address = pad_address + MaskedWriteAddressOffset;
reg::Write(mask_address, (mask << MaskedWriteBitOffset) | (value));
}
}
void OpenSession(GpioPadName pad) {
/* Convert the pad to an internal number. */
const auto pad_number = ConvertPadNameToInternalPadNumber(pad);
/* Get the gpio registers address. */
const uintptr_t gpio_address = dd::QueryIoMapping(GpioRegistersPhysicalAddress, GpioRegistersSize);
/* Configure the pad as GPIO by setting the appropriate bit in CNF. */
const uintptr_t pad_address = GetGpioRegisterAddress(gpio_address, GpioRegisterType_GPIO_CNF, pad_number);
const uintptr_t pad_index = ConvertInternalGpioPadNumberToBitIndex(pad_number);
SetMaskedBit(pad_address, pad_index, 1);
/* Read the pad address to make sure our configuration takes. */
reg::Read(pad_address);
}
void CloseSession(GpioPadName pad) {
/* Nothing needs to be done here, as the only thing official code does is unbind the interrupt event. */
AMS_UNUSED(pad);
}
void SetDirection(GpioPadName pad, Direction direction) {
/* Convert the pad to an internal number. */
const auto pad_number = ConvertPadNameToInternalPadNumber(pad);
/* Get the gpio registers address. */
const uintptr_t gpio_address = dd::QueryIoMapping(GpioRegistersPhysicalAddress, GpioRegistersSize);
/* Configure the pad direction modifying the appropriate bit in OE. */
const uintptr_t pad_address = GetGpioRegisterAddress(gpio_address, GpioRegisterType_GPIO_OE, pad_number);
const uintptr_t pad_index = ConvertInternalGpioPadNumberToBitIndex(pad_number);
SetMaskedBit(pad_address, pad_index, direction);
/* Read the pad address to make sure our configuration takes. */
reg::Read(pad_address);
}
void SetValue(GpioPadName pad, GpioValue value) {
/* Convert the pad to an internal number. */
const auto pad_number = ConvertPadNameToInternalPadNumber(pad);
/* Get the gpio registers address. */
const uintptr_t gpio_address = dd::QueryIoMapping(GpioRegistersPhysicalAddress, GpioRegistersSize);
/* Configure the pad value modifying the appropriate bit in OUT. */
const uintptr_t pad_address = GetGpioRegisterAddress(gpio_address, GpioRegisterType_GPIO_OUT, pad_number);
const uintptr_t pad_index = ConvertInternalGpioPadNumberToBitIndex(pad_number);
SetMaskedBit(pad_address, pad_index, value);
/* Read the pad address to make sure our configuration takes. */
reg::Read(pad_address);
}
}
namespace pinmux_impl {
namespace {
constexpr auto Sdmmc1ClkCmdDat03PadNumber = gpio_impl::InternalGpioPadNumber_M0;
constexpr unsigned int Sdmmc1ClkCmdDat03PadMask = 0x3F;
constexpr unsigned int Sdmmc1ClkCmdDat03PadCnfGpio = 0x3F;
constexpr unsigned int Sdmmc1ClkCmdDat03PadCnfSfio = 0x00;
constexpr unsigned int Sdmmc1ClkCmdDat03PadOutHigh = 0x3F;
constexpr unsigned int Sdmmc1ClkCmdDat03PadOutLow = 0x00;
constexpr unsigned int Sdmmc1ClkCmdDat03PadOeOutput = 0x3F;
constexpr unsigned int Sdmmc1ClkCmdDat03PadOeInput = 0x00;
struct PinmuxDefinition {
u32 reg_offset;
u32 mask_val;
u32 pm_val;
};
/* NOTE: We only use the SDMMC1 pins, which are conveniently the first few... */
constexpr const PinmuxDefinition PinmuxDefinitionMap[] = {
{0x00003000, 0x72FF, 0x01}, /* Sdmmc1Clk */
{0x00003004, 0x72FF, 0x02}, /* Sdmmc1Cmd */
{0x00003008, 0x72FF, 0x02}, /* Sdmmc1Dat3 */
{0x0000300C, 0x72FF, 0x02}, /* Sdmmc1Dat2 */
{0x00003010, 0x72FF, 0x02}, /* Sdmmc1Dat1 */
{0x00003014, 0x72FF, 0x01}, /* Sdmmc1Dat0 */
};
enum PinmuxPadIndex {
PinmuxPadIndex_Sdmmc1Clk = 0,
PinmuxPadIndex_Sdmmc1Cmd = 1,
PinmuxPadIndex_Sdmmc1Dat3 = 2,
PinmuxPadIndex_Sdmmc1Dat2 = 3,
PinmuxPadIndex_Sdmmc1Dat1 = 4,
PinmuxPadIndex_Sdmmc1Dat0 = 5,
PinmuxPadIndex_Count,
};
static_assert(util::size(PinmuxDefinitionMap) == PinmuxPadIndex_Count);
consteval const PinmuxDefinition GetDefinition(PinmuxPadIndex pad_index) {
AMS_ABORT_UNLESS(pad_index < PinmuxPadIndex_Count);
return PinmuxDefinitionMap[pad_index];
}
template<PinmuxPadIndex PadIndex, u32 PinmuxConfigVal, u32 PinmuxConfigMaskVal>
ALWAYS_INLINE u32 UpdatePinmuxPad(uintptr_t pinmux_base_vaddr) {
constexpr const PinmuxDefinition Definition = GetDefinition(PadIndex);
/* Fetch this PINMUX's register offset */
constexpr u32 PinmuxRegOffset = Definition.reg_offset;
/* Fetch this PINMUX's mask value */
constexpr u32 PinmuxMaskVal = Definition.mask_val;
/* Get current register ptr. */
const uintptr_t pinmux_reg = pinmux_base_vaddr + PinmuxRegOffset;
/* Read from the PINMUX register */
u32 pinmux_val = reg::Read(pinmux_reg);
/* This PINMUX register is locked */
AMS_ABORT_UNLESS((pinmux_val & 0x80) == 0);
constexpr u32 PmVal = (PinmuxConfigVal & 0x07);
/* Adjust PM */
if constexpr (PinmuxConfigMaskVal & 0x07) {
/* Apply additional changes first */
if constexpr (PmVal == 0x05) {
/* This pin supports PUPD change */
if constexpr (PinmuxMaskVal & 0x0C) {
/* Change PUPD */
if ((pinmux_val & 0x0C) != 0x04) {
pinmux_val &= 0xFFFFFFF3;
pinmux_val |= 0x04;
}
}
/* This pin supports Tristate change */
if constexpr (PinmuxMaskVal & 0x10) {
/* Change Tristate */
if (!(pinmux_val & 0x10)) {
pinmux_val |= 0x10;
}
}
/* This pin supports EInput change */
if constexpr (PinmuxMaskVal & 0x40) {
/* Change EInput */
if (pinmux_val & 0x40) {
pinmux_val &= 0xFFFFFFBF;
}
}
}
/* Translate PM value if necessary */
constexpr u32 TranslatedPmVal = (PmVal == 0x04 || PmVal == 0x05 || PmVal >= 0x06) ? Definition.pm_val : PmVal;
/* This pin supports PM change */
if constexpr (PinmuxMaskVal & 0x03) {
/* Change PM */
if ((pinmux_val & 0x03) != (TranslatedPmVal & 0x03)) {
pinmux_val &= 0xFFFFFFFC;
pinmux_val |= (TranslatedPmVal & 0x03);
}
}
}
constexpr u32 PupdConfigVal = (PinmuxConfigVal & 0x18);
/* Adjust PUPD */
if constexpr (PinmuxConfigMaskVal & 0x18) {
if constexpr (PupdConfigVal < 0x11) {
/* This pin supports PUPD change */
if constexpr (PinmuxMaskVal & 0x0C) {
/* Change PUPD */
if (((pinmux_val >> 0x02) & 0x03) != (PupdConfigVal >> 0x03)) {
pinmux_val &= 0xFFFFFFF3;
pinmux_val |= (PupdConfigVal >> 0x01);
}
}
}
}
constexpr u32 EodConfigVal = (PinmuxConfigVal & 0x60);
/* Adjust EOd field */
if constexpr (PinmuxConfigMaskVal & 0x60) {
if constexpr (EodConfigVal == 0x20) {
/* This pin supports Tristate change */
if constexpr (PinmuxMaskVal & 0x10) {
/* Change Tristate */
if (!(pinmux_val & 0x10)) {
pinmux_val |= 0x10;
}
}
/* This pin supports EInput change */
if constexpr (PinmuxMaskVal & 0x40) {
/* Change EInput */
if (!(pinmux_val & 0x40)) {
pinmux_val |= 0x40;
}
}
/* This pin supports EOd change */
if constexpr (PinmuxMaskVal & 0x800) {
/* Change EOd */
if (pinmux_val & 0x800) {
pinmux_val &= 0xFFFFF7FF;
}
}
} else if constexpr (EodConfigVal == 0x40) {
/* This pin supports Tristate change */
if constexpr (PinmuxMaskVal & 0x10) {
/* Change Tristate */
if (pinmux_val & 0x10) {
pinmux_val &= 0xFFFFFFEF;
}
}
/* This pin supports EInput change */
if constexpr (PinmuxMaskVal & 0x40) {
/* Change EInput */
if (!(pinmux_val & 0x40)) {
pinmux_val |= 0x40;
}
}
/* This pin supports EOd change */
if constexpr (PinmuxMaskVal & 0x800) {
/* Change EOd */
if (pinmux_val & 0x800) {
pinmux_val &= 0xFFFFF7FF;
}
}
} else if constexpr (EodConfigVal == 0x60) {
/* This pin supports Tristate change */
if constexpr (PinmuxMaskVal & 0x10) {
/* Change Tristate */
if (pinmux_val & 0x10) {
pinmux_val &= 0xFFFFFFEF;
}
}
/* This pin supports EInput change */
if constexpr (PinmuxMaskVal & 0x40) {
/* Change EInput */
if (!(pinmux_val & 0x40)) {
pinmux_val |= 0x40;
}
}
/* This pin supports EOd change */
if constexpr (PinmuxMaskVal & 0x800) {
/* Change EOd */
if (!(pinmux_val & 0x800)) {
pinmux_val |= 0x800;
}
}
} else {
/* This pin supports Tristate change */
if constexpr (PinmuxMaskVal & 0x10) {
/* Change Tristate */
if (pinmux_val & 0x10) {
pinmux_val &= 0xFFFFFFEF;
}
}
/* This pin supports EInput change */
if constexpr (PinmuxMaskVal & 0x40) {
/* Change EInput */
if (pinmux_val & 0x40) {
pinmux_val &= 0xFFFFFFBF;
}
}
/* This pin supports EOd change */
if constexpr (PinmuxMaskVal & 0x800) {
/* Change EOd */
if (pinmux_val & 0x800) {
pinmux_val &= 0xFFFFF7FF;
}
}
}
}
constexpr u32 LockConfigVal = (PinmuxConfigVal & 0x80);
/* Adjust Lock */
if constexpr (PinmuxConfigMaskVal & 0x80) {
/* This pin supports Lock change */
if constexpr (PinmuxMaskVal & 0x80) {
/* Change Lock */
if ((pinmux_val ^ PinmuxConfigVal) & 0x80) {
pinmux_val &= 0xFFFFFF7F;
pinmux_val |= LockConfigVal;
}
}
}
constexpr u32 IoResetConfigVal = (((PinmuxConfigVal >> 0x08) & 0x1) << 0x10);
/* Adjust IoReset */
if constexpr (PinmuxConfigMaskVal & 0x100) {
/* This pin supports IoReset change */
if constexpr (PinmuxMaskVal & 0x10000) {
/* Change IoReset */
if (((pinmux_val >> 0x10) ^ (PinmuxConfigVal >> 0x08)) & 0x01) {
pinmux_val &= 0xFFFEFFFF;
pinmux_val |= IoResetConfigVal;
}
}
}
constexpr u32 ParkConfigVal = (((PinmuxConfigVal >> 0x0A) & 0x1) << 0x5);
/* Adjust Park */
if constexpr (PinmuxConfigMaskVal & 0x400) {
/* This pin supports Park change */
if constexpr (PinmuxMaskVal & 0x20) {
/* Change Park */
if (((pinmux_val >> 0x05) ^ (PinmuxConfigVal >> 0x0A)) & 0x01) {
pinmux_val &= 0xFFFFFFDF;
pinmux_val |= ParkConfigVal;
}
}
}
constexpr u32 ElpdrConfigVal = (((PinmuxConfigVal >> 0x0B) & 0x1) << 0x08);
/* Adjust ELpdr */
if constexpr (PinmuxConfigMaskVal & 0x800) {
/* This pin supports ELpdr change */
if constexpr (PinmuxMaskVal & 0x100) {
/* Change ELpdr */
if (((pinmux_val >> 0x08) ^ (PinmuxConfigVal >> 0x0B)) & 0x01) {
pinmux_val &= 0xFFFFFEFF;
pinmux_val |= ElpdrConfigVal;
}
}
}
constexpr u32 EhsmConfigVal = (((PinmuxConfigVal >> 0x0C) & 0x1) << 0x09);
/* Adjust EHsm */
if constexpr (PinmuxConfigMaskVal & 0x1000) {
/* This pin supports EHsm change */
if constexpr (PinmuxMaskVal & 0x200) {
/* Change EHsm */
if (((pinmux_val >> 0x09) ^ (PinmuxConfigVal >> 0x0C)) & 0x01) {
pinmux_val &= 0xFFFFFDFF;
pinmux_val |= EhsmConfigVal;
}
}
}
constexpr u32 EIoHvConfigVal = (((PinmuxConfigVal >> 0x09) & 0x1) << 0x0A);
/* Adjust EIoHv */
if constexpr (PinmuxConfigMaskVal & 0x200) {
/* This pin supports EIoHv change */
if constexpr (PinmuxMaskVal & 0x400) {
/* Change EIoHv */
if (((pinmux_val >> 0x0A) ^ (PinmuxConfigVal >> 0x09)) & 0x01) {
pinmux_val &= 0xFFFFFBFF;
pinmux_val |= EIoHvConfigVal;
}
}
}
constexpr u32 EschmtConfigVal = (((PinmuxConfigVal >> 0x0D) & 0x1) << 0x0C);
/* Adjust ESchmt */
if constexpr (PinmuxConfigMaskVal & 0x2000) {
/* This pin supports ESchmt change */
if constexpr (PinmuxMaskVal & 0x1000) {
/* Change ESchmt */
if (((pinmux_val >> 0x0C) ^ (PinmuxConfigVal >> 0x0D)) & 0x01) {
pinmux_val &= 0xFFFFEFFF;
pinmux_val |= EschmtConfigVal;
}
}
}
constexpr u32 PreempConfigVal = (((PinmuxConfigVal >> 0x10) & 0x1) << 0xF);
/* Adjust Preemp */
if constexpr (PinmuxConfigMaskVal & 0x10000) {
/* This pin supports Preemp change */
if constexpr (PinmuxMaskVal & 0x8000) {
/* Change Preemp */
if (((pinmux_val >> 0x0F) ^ (PinmuxConfigVal >> 0x10)) & 0x01) {
pinmux_val &= 0xFFFF7FFF;
pinmux_val |= PreempConfigVal;
}
}
}
constexpr u32 DrvTypeConfigVal = (((PinmuxConfigVal >> 0x0E) & 0x3) << 0xD);
/* Adjust DrvType */
if constexpr (PinmuxConfigMaskVal & 0xC000) {
/* This pin supports DrvType change */
if constexpr (PinmuxMaskVal & 0x6000) {
/* Change DrvType */
if (((pinmux_val >> 0x0D) ^ (PinmuxConfigVal >> 0x0E)) & 0x03) {
pinmux_val &= 0xFFFF9FFF;
pinmux_val |= DrvTypeConfigVal;
}
}
}
/* Write to the appropriate PINMUX register */
reg::Write(pinmux_reg, pinmux_val);
/* Do a dummy read from the PINMUX register */
pinmux_val = reg::Read(pinmux_reg);
return pinmux_val;
}
}
void SetPinAssignment(PinAssignment assignment) {
/* Get the apb registers address. */
const uintptr_t apb_address = dd::QueryIoMapping(ApbMiscRegistersPhysicalAddress, ApbMiscRegistersSize);
AMS_UNUSED(apb_address);
/* Set the pin assignment. */
switch (assignment) {
case PinAssignment_Sdmmc1OutputHigh:
{
/* Clear Sdmmc1Clk pulldown. */
UpdatePinmuxPad<PinmuxPadIndex_Sdmmc1Clk, 0, 0x18>(apb_address);
/* Get the gpio registers address. */
const uintptr_t gpio_address = dd::QueryIoMapping(gpio_impl::GpioRegistersPhysicalAddress, gpio_impl::GpioRegistersSize);
/* Configure GPIO M0-5 (SDMMC1 CLK + CMD + DAT0/1/2/3) as gpio. */
const uintptr_t cnf_address = gpio_impl::GetGpioRegisterAddress(gpio_address, gpio_impl::GpioRegisterType_GPIO_CNF, Sdmmc1ClkCmdDat03PadNumber);
gpio_impl::SetMaskedBits(cnf_address, Sdmmc1ClkCmdDat03PadMask, Sdmmc1ClkCmdDat03PadCnfGpio);
/* Configure GPIO M0-5 (SDMMC1 CLK + CMD + DAT0/1/2/3) as high. */
const uintptr_t out_address = gpio_impl::GetGpioRegisterAddress(gpio_address, gpio_impl::GpioRegisterType_GPIO_OUT, Sdmmc1ClkCmdDat03PadNumber);
gpio_impl::SetMaskedBits(out_address, Sdmmc1ClkCmdDat03PadMask, Sdmmc1ClkCmdDat03PadOutHigh);
/* Configure GPIO M0-5 (SDMMC1 CLK + CMD + DAT0/1/2/3) as output. */
const uintptr_t oe_address = gpio_impl::GetGpioRegisterAddress(gpio_address, gpio_impl::GpioRegisterType_GPIO_OE, Sdmmc1ClkCmdDat03PadNumber);
gpio_impl::SetMaskedBits(oe_address, Sdmmc1ClkCmdDat03PadMask, Sdmmc1ClkCmdDat03PadOeOutput);
/* Read to be sure that our configuration takes. */
reg::Read(oe_address);
}
break;
case PinAssignment_Sdmmc1ResetState:
{
/* Get the gpio registers address. */
const uintptr_t gpio_address = dd::QueryIoMapping(gpio_impl::GpioRegistersPhysicalAddress, gpio_impl::GpioRegistersSize);
/* Configure GPIO M0-5 (SDMMC1 CLK + CMD + DAT0/1/2/3) as sfio. */
const uintptr_t cnf_address = gpio_impl::GetGpioRegisterAddress(gpio_address, gpio_impl::GpioRegisterType_GPIO_CNF, Sdmmc1ClkCmdDat03PadNumber);
gpio_impl::SetMaskedBits(cnf_address, Sdmmc1ClkCmdDat03PadMask, Sdmmc1ClkCmdDat03PadCnfSfio);
/* Configure GPIO M0-5 (SDMMC1 CLK + CMD + DAT0/1/2/3) as low. */
const uintptr_t out_address = gpio_impl::GetGpioRegisterAddress(gpio_address, gpio_impl::GpioRegisterType_GPIO_OUT, Sdmmc1ClkCmdDat03PadNumber);
gpio_impl::SetMaskedBits(out_address, Sdmmc1ClkCmdDat03PadMask, Sdmmc1ClkCmdDat03PadOutLow);
/* Configure GPIO M0-5 (SDMMC1 CLK + CMD + DAT0/1/2/3) as input. */
const uintptr_t oe_address = gpio_impl::GetGpioRegisterAddress(gpio_address, gpio_impl::GpioRegisterType_GPIO_OE, Sdmmc1ClkCmdDat03PadNumber);
gpio_impl::SetMaskedBits(oe_address, Sdmmc1ClkCmdDat03PadMask, Sdmmc1ClkCmdDat03PadOeInput);
/* Read to be sure that our configuration takes. */
reg::Read(oe_address);
/* Set Sdmmc1Clk pulldown. */
UpdatePinmuxPad<PinmuxPadIndex_Sdmmc1Clk, 0x8, 0x18>(apb_address);
}
break;
case PinAssignment_Sdmmc1SchmtEnable:
{
/* Set Schmitt enable for all pins in the group. */
UpdatePinmuxPad<PinmuxPadIndex_Sdmmc1Clk, 0x2000, 0x2000>(apb_address);
UpdatePinmuxPad<PinmuxPadIndex_Sdmmc1Cmd, 0x2000, 0x2000>(apb_address);
UpdatePinmuxPad<PinmuxPadIndex_Sdmmc1Dat3, 0x2000, 0x2000>(apb_address);
UpdatePinmuxPad<PinmuxPadIndex_Sdmmc1Dat2, 0x2000, 0x2000>(apb_address);
UpdatePinmuxPad<PinmuxPadIndex_Sdmmc1Dat1, 0x2000, 0x2000>(apb_address);
UpdatePinmuxPad<PinmuxPadIndex_Sdmmc1Dat0, 0x2000, 0x2000>(apb_address);
}
break;
case PinAssignment_Sdmmc1SchmtDisable:
{
/* Set Schmitt disable for all pins in the group. */
UpdatePinmuxPad<PinmuxPadIndex_Sdmmc1Clk, 0x0000, 0x2000>(apb_address);
UpdatePinmuxPad<PinmuxPadIndex_Sdmmc1Cmd, 0x0000, 0x2000>(apb_address);
UpdatePinmuxPad<PinmuxPadIndex_Sdmmc1Dat3, 0x0000, 0x2000>(apb_address);
UpdatePinmuxPad<PinmuxPadIndex_Sdmmc1Dat2, 0x0000, 0x2000>(apb_address);
UpdatePinmuxPad<PinmuxPadIndex_Sdmmc1Dat1, 0x0000, 0x2000>(apb_address);
UpdatePinmuxPad<PinmuxPadIndex_Sdmmc1Dat0, 0x0000, 0x2000>(apb_address);
}
break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
}
}
| 44,538
|
C++
|
.cpp
| 804
| 36.450249
| 168
| 0.505719
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,068
|
crypto_memory_clear.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/crypto/crypto_memory_clear.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <vapours.hpp>
namespace ams::crypto {
void ClearMemory(void *_mem, size_t size) {
volatile u8 *mem = reinterpret_cast<volatile u8 *>(_mem);
for (size_t i = 0; i < size; i++) {
mem[i] = 0;
}
}
}
| 885
|
C++
|
.cpp
| 24
| 33.333333
| 76
| 0.695804
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,069
|
crypto_memory_compare.arch.generic.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/crypto/crypto_memory_compare.arch.generic.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <vapours.hpp>
namespace ams::crypto {
bool IsSameBytes(const void *lhs, const void *rhs, size_t size) {
/* TODO: Should the generic impl be constant time? */
volatile u8 diff = 0;
const volatile u8 *lhs8 = static_cast<const volatile u8 *>(lhs);
const volatile u8 *rhs8 = static_cast<const volatile u8 *>(rhs);
for (size_t i = 0; i < size; ++i) {
diff = diff | (lhs8[i] ^ rhs8[i]);
}
return diff == 0;
}
}
| 1,129
|
C++
|
.cpp
| 28
| 35.964286
| 76
| 0.678213
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,070
|
crypto_hmac_sha256_generator.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/crypto/crypto_hmac_sha256_generator.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <vapours.hpp>
namespace ams::crypto {
void GenerateHmacSha256(void *dst, size_t dst_size, const void *data, size_t data_size, const void *key, size_t key_size) {
HmacSha256Generator hmac;
hmac.Initialize(key, key_size);
hmac.Update(data, data_size);
hmac.GetMac(dst, dst_size);
}
}
| 970
|
C++
|
.cpp
| 24
| 37
| 127
| 0.726115
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,071
|
crypto_memory_compare.arch.arm64.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/crypto/crypto_memory_compare.arch.arm64.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <vapours.hpp>
namespace ams::crypto {
bool IsSameBytes(const void *lhs, const void *rhs, size_t size) {
bool result;
u8 xor_acc, ltmp, rtmp;
size_t index;
__asm__ __volatile__(
/* Clear registers and prepare for comparison. */
" mov %w[xor_acc], #0\n"
" mov %w[index], #0\n"
" b 1f\n"
/* Compare one byte in constant time. */
"0:\n"
" ldrb %w[ltmp], [%[lhs]]\n"
" ldrb %w[rtmp], [%[rhs]]\n"
" adds %[lhs], %[lhs], #1\n"
" adds %[rhs], %[rhs], #1\n"
" eor %w[ltmp], %w[ltmp], %w[rtmp]\n"
" orr %w[xor_acc], %w[xor_acc], %w[ltmp]\n"
" adds %[index], %[index], #1\n"
/* Check if there is still data to compare. */
"1:\n"
" cmp %[index], %[size]\n"
" bcc 0b\n"
/* We're done, set result. */
" cmp %w[xor_acc], #0\n"
" cset %w[result], eq\n"
: [result]"=r"(result), [lhs]"+r"(lhs), [rhs]"+r"(rhs), [xor_acc]"=&r"(xor_acc), [index]"=&r"(index), [ltmp]"=&r"(ltmp), [rtmp]"=&r"(rtmp)
: "m"(*(const u8 (*)[size])lhs), "m"(*(const u8 (*)[size])lhs), [size]"r"(size)
: "cc"
);
return result;
}
}
| 2,049
|
C++
|
.cpp
| 49
| 33.612245
| 150
| 0.51129
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,072
|
crypto_sha256_generator.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/crypto/crypto_sha256_generator.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <vapours.hpp>
namespace ams::crypto {
void GenerateSha256(void *dst, size_t dst_size, const void *src, size_t src_size) {
Sha256Generator gen{};
gen.Initialize();
gen.Update(src, src_size);
gen.GetHash(dst, dst_size);
}
}
| 910
|
C++
|
.cpp
| 24
| 34.5
| 87
| 0.719955
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,073
|
crypto_hmac_sha1_generator.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/crypto/crypto_hmac_sha1_generator.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <vapours.hpp>
namespace ams::crypto {
void GenerateHmacSha1(void *dst, size_t dst_size, const void *data, size_t data_size, const void *key, size_t key_size) {
HmacSha1Generator hmac;
hmac.Initialize(key, key_size);
hmac.Update(data, data_size);
hmac.GetMac(dst, dst_size);
}
}
| 966
|
C++
|
.cpp
| 24
| 36.833333
| 125
| 0.724947
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,074
|
crypto_md5_generator.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/crypto/crypto_md5_generator.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <vapours.hpp>
namespace ams::crypto {
void GenerateMd5(void *dst, size_t dst_size, const void *src, size_t src_size) {
Md5Generator gen;
gen.Initialize();
gen.Update(src, src_size);
gen.GetHash(dst, dst_size);
}
}
| 902
|
C++
|
.cpp
| 24
| 34.166667
| 84
| 0.71968
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,075
|
crypto_aes_ctr_encryptor_decryptor.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/crypto/crypto_aes_ctr_encryptor_decryptor.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <vapours.hpp>
namespace ams::crypto {
size_t EncryptAes128Ctr(void *dst, size_t dst_size, const void *key, size_t key_size, const void *iv, size_t iv_size, const void *src, size_t src_size) {
Aes128CtrEncryptor aes;
aes.Initialize(key, key_size, iv, iv_size);
return aes.Update(dst, dst_size, src, src_size);
}
size_t EncryptAes192Ctr(void *dst, size_t dst_size, const void *key, size_t key_size, const void *iv, size_t iv_size, const void *src, size_t src_size) {
Aes192CtrEncryptor aes;
aes.Initialize(key, key_size, iv, iv_size);
return aes.Update(dst, dst_size, src, src_size);
}
size_t EncryptAes256Ctr(void *dst, size_t dst_size, const void *key, size_t key_size, const void *iv, size_t iv_size, const void *src, size_t src_size) {
Aes256CtrEncryptor aes;
aes.Initialize(key, key_size, iv, iv_size);
return aes.Update(dst, dst_size, src, src_size);
}
size_t DecryptAes128Ctr(void *dst, size_t dst_size, const void *key, size_t key_size, const void *iv, size_t iv_size, const void *src, size_t src_size) {
Aes128CtrDecryptor aes;
aes.Initialize(key, key_size, iv, iv_size);
return aes.Update(dst, dst_size, src, src_size);
}
size_t DecryptAes192Ctr(void *dst, size_t dst_size, const void *key, size_t key_size, const void *iv, size_t iv_size, const void *src, size_t src_size) {
Aes192CtrDecryptor aes;
aes.Initialize(key, key_size, iv, iv_size);
return aes.Update(dst, dst_size, src, src_size);
}
size_t DecryptAes256Ctr(void *dst, size_t dst_size, const void *key, size_t key_size, const void *iv, size_t iv_size, const void *src, size_t src_size) {
Aes256CtrDecryptor aes;
aes.Initialize(key, key_size, iv, iv_size);
return aes.Update(dst, dst_size, src, src_size);
}
size_t EncryptAes128CtrPartial(void *dst, size_t dst_size, const void *key, size_t key_size, const void *iv, size_t iv_size, s64 offset, const void *src, size_t src_size) {
Aes128CtrEncryptor aes;
aes.Initialize(key, key_size, iv, iv_size, offset);
return aes.Update(dst, dst_size, src, src_size);
}
size_t EncryptAes192CtrPartial(void *dst, size_t dst_size, const void *key, size_t key_size, const void *iv, size_t iv_size, s64 offset, const void *src, size_t src_size) {
Aes192CtrEncryptor aes;
aes.Initialize(key, key_size, iv, iv_size, offset);
return aes.Update(dst, dst_size, src, src_size);
}
size_t EncryptAes256CtrPartial(void *dst, size_t dst_size, const void *key, size_t key_size, const void *iv, size_t iv_size, s64 offset, const void *src, size_t src_size) {
Aes256CtrEncryptor aes;
aes.Initialize(key, key_size, iv, iv_size, offset);
return aes.Update(dst, dst_size, src, src_size);
}
size_t DecryptAes128CtrPartial(void *dst, size_t dst_size, const void *key, size_t key_size, const void *iv, size_t iv_size, s64 offset, const void *src, size_t src_size) {
Aes128CtrDecryptor aes;
aes.Initialize(key, key_size, iv, iv_size, offset);
return aes.Update(dst, dst_size, src, src_size);
}
size_t DecryptAes192CtrPartial(void *dst, size_t dst_size, const void *key, size_t key_size, const void *iv, size_t iv_size, s64 offset, const void *src, size_t src_size) {
Aes192CtrDecryptor aes;
aes.Initialize(key, key_size, iv, iv_size, offset);
return aes.Update(dst, dst_size, src, src_size);
}
size_t DecryptAes256CtrPartial(void *dst, size_t dst_size, const void *key, size_t key_size, const void *iv, size_t iv_size, s64 offset, const void *src, size_t src_size) {
Aes256CtrDecryptor aes;
aes.Initialize(key, key_size, iv, iv_size, offset);
return aes.Update(dst, dst_size, src, src_size);
}
}
| 4,520
|
C++
|
.cpp
| 78
| 51.666667
| 176
| 0.677507
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,076
|
crypto_memory_compare.arch.arm.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/crypto/crypto_memory_compare.arch.arm.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <vapours.hpp>
namespace ams::crypto {
bool IsSameBytes(const void *lhs, const void *rhs, size_t size) {
bool result;
u8 xor_acc, ltmp, rtmp;
size_t index;
__asm__ __volatile__(
/* Clear registers and prepare for comparison. */
" movs %[xor_acc], #0\n"
" movs %[index], #0\n"
" b 1f\n"
/* Compare one byte in constant time. */
"0:\n"
" ldrb %[ltmp], [%[lhs]]\n"
" ldrb %[rtmp], [%[rhs]]\n"
" adds %[lhs], #1\n"
" adds %[rhs], #1\n"
" eors %[ltmp], %[ltmp], %[rtmp]\n"
" orrs %[xor_acc], %[xor_acc], %[ltmp]\n"
" adds %[index], #1\n"
/* Check if there is still data to compare. */
"1:\n"
" cmp %[index], %[size]\n"
" bcc 0b\n"
/* We're done, set result. */
" cmp %[xor_acc], #0\n"
" moveq %[result], #1\n"
" movne %[result], #0\n"
: [result]"=r"(result), [lhs]"+r"(lhs), [rhs]"+r"(rhs), [xor_acc]"=&r"(xor_acc), [index]"=&r"(index), [ltmp]"=&r"(ltmp), [rtmp]"=&r"(rtmp)
: [size]"r"(size)
: "cc"
);
return result;
}
}
| 1,993
|
C++
|
.cpp
| 50
| 31.56
| 150
| 0.507748
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,077
|
crypto_aes_cbc_encryptor_decryptor.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/crypto/crypto_aes_cbc_encryptor_decryptor.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <vapours.hpp>
namespace ams::crypto {
size_t EncryptAes128Cbc(void *dst, size_t dst_size, const void *key, size_t key_size, const void *iv, size_t iv_size, const void *src, size_t src_size) {
Aes128CbcEncryptor aes;
aes.Initialize(key, key_size, iv, iv_size);
return aes.Update(dst, dst_size, src, src_size);
}
size_t EncryptAes192Cbc(void *dst, size_t dst_size, const void *key, size_t key_size, const void *iv, size_t iv_size, const void *src, size_t src_size) {
Aes192CbcEncryptor aes;
aes.Initialize(key, key_size, iv, iv_size);
return aes.Update(dst, dst_size, src, src_size);
}
size_t EncryptAes256Cbc(void *dst, size_t dst_size, const void *key, size_t key_size, const void *iv, size_t iv_size, const void *src, size_t src_size) {
Aes256CbcEncryptor aes;
aes.Initialize(key, key_size, iv, iv_size);
return aes.Update(dst, dst_size, src, src_size);
}
size_t DecryptAes128Cbc(void *dst, size_t dst_size, const void *key, size_t key_size, const void *iv, size_t iv_size, const void *src, size_t src_size) {
Aes128CbcDecryptor aes;
aes.Initialize(key, key_size, iv, iv_size);
return aes.Update(dst, dst_size, src, src_size);
}
size_t DecryptAes192Cbc(void *dst, size_t dst_size, const void *key, size_t key_size, const void *iv, size_t iv_size, const void *src, size_t src_size) {
Aes192CbcDecryptor aes;
aes.Initialize(key, key_size, iv, iv_size);
return aes.Update(dst, dst_size, src, src_size);
}
size_t DecryptAes256Cbc(void *dst, size_t dst_size, const void *key, size_t key_size, const void *iv, size_t iv_size, const void *src, size_t src_size) {
Aes256CbcDecryptor aes;
aes.Initialize(key, key_size, iv, iv_size);
return aes.Update(dst, dst_size, src, src_size);
}
}
| 2,522
|
C++
|
.cpp
| 48
| 47.083333
| 157
| 0.683698
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,078
|
crypto_sha1_generator.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/crypto/crypto_sha1_generator.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <vapours.hpp>
namespace ams::crypto {
void GenerateSha1(void *dst, size_t dst_size, const void *src, size_t src_size) {
Sha1Generator gen;
gen.Initialize();
gen.Update(src, src_size);
gen.GetHash(dst, dst_size);
}
}
| 904
|
C++
|
.cpp
| 24
| 34.25
| 85
| 0.72032
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,079
|
crypto_sha256_impl.arch.arm64.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/crypto/impl/crypto_sha256_impl.arch.arm64.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <vapours.hpp>
#if defined(ATMOSPHERE_IS_STRATOSPHERE)
#include <arm_neon.h>
namespace ams::crypto::impl {
namespace {
alignas(Sha256Impl::BlockSize) constexpr const u32 RoundConstants[0x40] = {
0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,
0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,
0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,
0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,
0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,
0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2,
};
}
void Sha256Impl::Initialize() {
/* Reset buffered bytes/bits. */
m_buffered_bytes = 0;
m_bits_consumed = 0;
/* Set intermediate hash. */
m_intermediate_hash[0] = 0x6A09E667;
m_intermediate_hash[1] = 0xBB67AE85;
m_intermediate_hash[2] = 0x3C6EF372;
m_intermediate_hash[3] = 0xA54FF53A;
m_intermediate_hash[4] = 0x510E527F;
m_intermediate_hash[5] = 0x9B05688C;
m_intermediate_hash[6] = 0x1F83D9AB;
m_intermediate_hash[7] = 0x5BE0CD19;
/* Set state. */
m_state = State_Initialized;
}
void Sha256Impl::Update(const void *data, size_t size) {
/* Verify we're in a state to update. */
AMS_ASSERT(m_state == State_Initialized);
/* Advance our input bit count. */
m_bits_consumed += BITSIZEOF(u8) * (((m_buffered_bytes + size) / BlockSize) * BlockSize);
/* Process anything we have buffered. */
const u8 *data8 = static_cast<const u8 *>(data);
size_t remaining = size;
if (m_buffered_bytes > 0) {
const size_t copy_size = std::min(BlockSize - m_buffered_bytes, remaining);
std::memcpy(m_buffer + m_buffered_bytes, data8, copy_size);
data8 += copy_size;
remaining -= copy_size;
m_buffered_bytes += copy_size;
/* Process a block, if we filled one. */
if (m_buffered_bytes == BlockSize) {
this->ProcessBlock(m_buffer);
m_buffered_bytes = 0;
}
}
/* Process blocks, if we have any. */
if (remaining >= BlockSize) {
const size_t blocks = remaining / BlockSize;
this->ProcessBlocks(data8, blocks);
data8 += BlockSize * blocks;
remaining -= BlockSize * blocks;
}
/* Copy any leftover data to our buffer. */
if (remaining > 0) {
m_buffered_bytes = remaining;
std::memcpy(m_buffer, data8, remaining);
}
}
void Sha256Impl::GetHash(void *dst, size_t size) {
/* Verify we're in a state to get hash. */
AMS_ASSERT(m_state == State_Initialized || m_state == State_Done);
AMS_ASSERT(size >= HashSize);
AMS_UNUSED(size);
/* If we need to, process the last block. */
if (m_state == State_Initialized) {
this->ProcessLastBlock();
m_state = State_Done;
}
/* Copy the output hash. */
if constexpr (util::IsLittleEndian()) {
static_assert(HashSize % sizeof(u32) == 0);
u32 *dst_32 = static_cast<u32 *>(dst);
for (size_t i = 0; i < HashSize / sizeof(u32); ++i) {
dst_32[i] = util::LoadBigEndian<u32>(m_intermediate_hash + i);
}
} else {
std::memcpy(dst, m_intermediate_hash, HashSize);
}
}
void Sha256Impl::InitializeWithContext(const Sha256Context *context) {
/* Copy state in from the context. */
std::memcpy(m_intermediate_hash, context->intermediate_hash, sizeof(m_intermediate_hash));
m_bits_consumed = context->bits_consumed;
/* Reset other fields. */
m_buffered_bytes = 0;
m_state = State_Initialized;
}
size_t Sha256Impl::GetContext(Sha256Context *context) const {
/* Check our state. */
AMS_ASSERT(m_state == State_Initialized);
/* Copy out the context. */
std::memcpy(context->intermediate_hash, m_intermediate_hash, sizeof(context->intermediate_hash));
context->bits_consumed = m_bits_consumed;
return m_buffered_bytes;
}
ALWAYS_INLINE void Sha256Impl::ProcessBlock(const void *data) {
return this->ProcessBlocks(static_cast<const u8 *>(data), 1);
}
void Sha256Impl::ProcessBlocks(const u8 *data, size_t block_count) {
/* Load previous hash with intermediate state, current hash with zeroes. */
uint32x4_t prev_hash0 = vld1q_u32(m_intermediate_hash + 0);
uint32x4_t prev_hash1 = vld1q_u32(m_intermediate_hash + 4);
uint32x4_t cur_hash0 = vdupq_n_u32(0);
uint32x4_t cur_hash1 = vdupq_n_u32(0);
/* Process blocks. */
do {
uint32x4_t round_constant0, round_constant1;
uint32x4_t data0, data1, data2, data3;
uint32x4_t tmp0, tmp1, tmp2, tmp3;
uint32x4_t tmp_hash;
/* Use optimized ASM implementation to process the block. */
__asm__ __volatile__ (
"ldp %q[data0], %q[data1], [%[data]], #0x20\n"
"ldp %q[data2], %q[data3], [%[data]], #0x20\n"
"add %[cur_hash0].4s, %[cur_hash0].4s, %[prev_hash0].4s\n"
"ldp %q[round_constant0], %q[round_constant1], [%[round_constants], 0x00]\n"
"add %[cur_hash1].4s, %[cur_hash1].4s, %[prev_hash1].4s\n"
"rev32 %[data0].16b, %[data0].16b\n"
"rev32 %[data1].16b, %[data1].16b\n"
"rev32 %[data2].16b, %[data2].16b\n"
"rev32 %[data3].16b, %[data3].16b\n"
"add %[tmp0].4s, %[data0].4s, %[round_constant0].4s\n"
"add %[tmp1].4s, %[data1].4s, %[round_constant1].4s\n"
"ldp %q[round_constant0], %q[round_constant1], [%[round_constants], 0x20]\n"
"sha256su0 %[data0].4s, %[data1].4s\n"
"mov %[prev_hash0].16b, %[cur_hash0].16b\n"
"sha256h %q[cur_hash0], %q[cur_hash1], %[tmp0].4s\n"
"mov %[prev_hash1].16b, %[cur_hash1].16b\n"
"sha256h2 %q[cur_hash1], %q[prev_hash0], %[tmp0].4s\n"
"sha256su0 %[data1].4s, %[data2].4s\n"
"sha256su1 %[data0].4s, %[data2].4s, %[data3].4s\n"
"add %[tmp2].4s, %[data2].4s, %[round_constant0].4s\n"
"mov %[tmp_hash].16b, %[cur_hash0].16b\n"
"sha256h %q[cur_hash0], %q[cur_hash1], %[tmp1].4s\n"
"sha256h2 %q[cur_hash1], %q[tmp_hash], %[tmp1].4s\n"
"sha256su0 %[data2].4s, %[data3].4s\n"
"sha256su1 %[data1].4s, %[data3].4s, %[data0].4s\n"
"add %[tmp3].4s, %[data3].4s, %[round_constant1].4s\n"
"mov %[tmp_hash].16b, %[cur_hash0].16b\n"
"ldp %q[round_constant0], %q[round_constant1], [%[round_constants], 0x40]\n"
"sha256h %q[cur_hash0], %q[cur_hash1], %[tmp2].4s\n"
"sha256h2 %q[cur_hash1], %q[tmp_hash], %[tmp2].4s\n"
"sha256su0 %[data3].4s, %[data0].4s\n"
"sha256su1 %[data2].4s, %[data0].4s, %[data1].4s\n"
"add %[tmp0].4s, %[data0].4s, %[round_constant0].4s\n"
"mov %[tmp_hash].16b, %[cur_hash0].16b\n"
"sha256h %q[cur_hash0], %q[cur_hash1], %[tmp3].4s\n"
"sha256h2 %q[cur_hash1], %q[tmp_hash], %[tmp3].4s\n"
"sha256su0 %[data0].4s, %[data1].4s\n"
"sha256su1 %[data3].4s, %[data1].4s, %[data2].4s\n"
"add %[tmp1].4s, %[data1].4s, %[round_constant1].4s\n"
"mov %[tmp_hash].16b, %[cur_hash0].16b\n"
"ldp %q[round_constant0], %q[round_constant1], [%[round_constants], 0x60]\n"
"sha256h %q[cur_hash0], %q[cur_hash1], %[tmp0].4s\n"
"sha256h2 %q[cur_hash1], %q[tmp_hash], %[tmp0].4s\n"
"sha256su0 %[data1].4s, %[data2].4s\n"
"sha256su1 %[data0].4s, %[data2].4s, %[data3].4s\n"
"add %[tmp2].4s, %[data2].4s, %[round_constant0].4s\n"
"mov %[tmp_hash].16b, %[cur_hash0].16b\n"
"sha256h %q[cur_hash0], %q[cur_hash1], %[tmp1].4s\n"
"sha256h2 %q[cur_hash1], %q[tmp_hash], %[tmp1].4s\n"
"sha256su0 %[data2].4s, %[data3].4s\n"
"sha256su1 %[data1].4s, %[data3].4s, %[data0].4s\n"
"add %[tmp3].4s, %[data3].4s, %[round_constant1].4s\n"
"mov %[tmp_hash].16b, %[cur_hash0].16b\n"
"ldp %q[round_constant0], %q[round_constant1], [%[round_constants], 0x80]\n"
"sha256h %q[cur_hash0], %q[cur_hash1], %[tmp2].4s\n"
"sha256h2 %q[cur_hash1], %q[tmp_hash], %[tmp2].4s\n"
"sha256su0 %[data3].4s, %[data0].4s\n"
"sha256su1 %[data2].4s, %[data0].4s, %[data1].4s\n"
"add %[tmp0].4s, %[data0].4s, %[round_constant0].4s\n"
"mov %[tmp_hash].16b, %[cur_hash0].16b\n"
"sha256h %q[cur_hash0], %q[cur_hash1], %[tmp3].4s\n"
"sha256h2 %q[cur_hash1], %q[tmp_hash], %[tmp3].4s\n"
"sha256su0 %[data0].4s, %[data1].4s\n"
"sha256su1 %[data3].4s, %[data1].4s, %[data2].4s\n"
"add %[tmp1].4s, %[data1].4s, %[round_constant1].4s\n"
"mov %[tmp_hash].16b, %[cur_hash0].16b\n"
"ldp %q[round_constant0], %q[round_constant1], [%[round_constants], 0xA0]\n"
"sha256h %q[cur_hash0], %q[cur_hash1], %[tmp0].4s\n"
"sha256h2 %q[cur_hash1], %q[tmp_hash], %[tmp0].4s\n"
"sha256su0 %[data1].4s, %[data2].4s\n"
"sha256su1 %[data0].4s, %[data2].4s, %[data3].4s\n"
"add %[tmp2].4s, %[data2].4s, %[round_constant0].4s\n"
"mov %[tmp_hash].16b, %[cur_hash0].16b\n"
"sha256h %q[cur_hash0], %q[cur_hash1], %[tmp1].4s\n"
"sha256h2 %q[cur_hash1], %q[tmp_hash], %[tmp1].4s\n"
"sha256su0 %[data2].4s, %[data3].4s\n"
"sha256su1 %[data1].4s, %[data3].4s, %[data0].4s\n"
"add %[tmp3].4s, %[data3].4s, %[round_constant1].4s\n"
"mov %[tmp_hash].16b, %[cur_hash0].16b\n"
"ldp %q[round_constant0], %q[round_constant1], [%[round_constants], 0xC0]\n"
"sha256h %q[cur_hash0], %q[cur_hash1], %[tmp2].4s\n"
"sha256h2 %q[cur_hash1], %q[tmp_hash], %[tmp2].4s\n"
"sha256su0 %[data3].4s, %[data0].4s\n"
"sha256su1 %[data2].4s, %[data0].4s, %[data1].4s\n"
"add %[tmp0].4s, %[data0].4s, %[round_constant0].4s\n"
"mov %[tmp_hash].16b, %[cur_hash0].16b\n"
"sha256h %q[cur_hash0], %q[cur_hash1], %[tmp3].4s\n"
"sha256h2 %q[cur_hash1], %q[tmp_hash], %[tmp3].4s\n"
"sha256su1 %[data3].4s, %[data1].4s, %[data2].4s\n"
"add %[tmp1].4s, %[data1].4s, %[round_constant1].4s\n"
"mov %[tmp_hash].16b, %[cur_hash0].16b\n"
"ldp %q[round_constant0], %q[round_constant1], [%[round_constants], 0xE0]\n"
"sha256h %q[cur_hash0], %q[cur_hash1], %[tmp0].4s\n"
"sha256h2 %q[cur_hash1], %q[tmp_hash], %[tmp0].4s\n"
"add %[tmp2].4s, %[data2].4s, %[round_constant0].4s\n"
"mov %[tmp_hash].16b, %[cur_hash0].16b\n"
"sha256h %q[cur_hash0], %q[cur_hash1], %[tmp1].4s\n"
"sha256h2 %q[cur_hash1], %q[tmp_hash], %[tmp1].4s\n"
"add %[tmp3].4s, %[data3].4s, %[round_constant1].4s\n"
"mov %[tmp_hash].16b, %[cur_hash0].16b\n"
"sha256h %q[cur_hash0], %q[cur_hash1], %[tmp2].4s\n"
"sha256h2 %q[cur_hash1], %q[tmp_hash], %[tmp2].4s\n"
"mov %[tmp_hash].16b, %[cur_hash0].16b\n"
"sha256h %q[cur_hash0], %q[cur_hash1], %[tmp3].4s\n"
"sha256h2 %q[cur_hash1], %q[tmp_hash], %[tmp3].4s\n"
: [data0]"=w"(data0), [data1]"=w"(data1), [data2]"=w"(data2), [data3]"=w"(data3),
[tmp0]"=w"(tmp0), [tmp1]"=w"(tmp1), [tmp2]"=w"(tmp2), [tmp3]"=w"(tmp3),
[round_constant0]"=w"(round_constant0), [round_constant1]"=w"(round_constant1),
[cur_hash0]"+w"(cur_hash0), [cur_hash1]"+w"(cur_hash1),
[prev_hash0]"+w"(prev_hash0), [prev_hash1]"+w"(prev_hash1),
[tmp_hash]"=w"(tmp_hash), [data]"+r"(data)
: [round_constants]"r"(RoundConstants)
:
);
} while (--block_count != 0);
/* Add hashes together, and store. */
cur_hash0 = vaddq_u32(prev_hash0, cur_hash0);
cur_hash1 = vaddq_u32(prev_hash1, cur_hash1);
vst1q_u32(m_intermediate_hash + 0, cur_hash0);
vst1q_u32(m_intermediate_hash + 4, cur_hash1);
}
void Sha256Impl::ProcessLastBlock() {
/* Setup the final block. */
constexpr const auto BlockSizeWithoutSizeField = BlockSize - sizeof(u64);
/* Increment our bits consumed. */
m_bits_consumed += BITSIZEOF(u8) * m_buffered_bytes;
/* Add 0x80 terminator. */
m_buffer[m_buffered_bytes++] = 0x80;
/* If we can process the size field directly, do so, otherwise set up to process it. */
if (m_buffered_bytes <= BlockSizeWithoutSizeField) {
/* Clear up to size field. */
std::memset(m_buffer + m_buffered_bytes, 0, BlockSizeWithoutSizeField - m_buffered_bytes);
} else {
/* Consume full block */
std::memset(m_buffer + m_buffered_bytes, 0, BlockSize - m_buffered_bytes);
this->ProcessBlock(m_buffer);
/* Clear up to size field. */
std::memset(m_buffer, 0, BlockSizeWithoutSizeField);
}
/* Store the size field. */
util::StoreBigEndian<u64>(reinterpret_cast<u64 *>(m_buffer + BlockSizeWithoutSizeField), m_bits_consumed);
/* Process the final block. */
this->ProcessBlock(m_buffer);
}
}
#endif
| 15,881
|
C++
|
.cpp
| 288
| 42.829861
| 114
| 0.530312
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,080
|
crypto_sha1_impl.arch.arm64.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/crypto/impl/crypto_sha1_impl.arch.arm64.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <vapours.hpp>
#if defined(ATMOSPHERE_IS_STRATOSPHERE)
#include <arm_neon.h>
namespace ams::crypto::impl {
namespace {
constexpr const u32 RoundConstants[4] = {
0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6
};
/* Define for loading work var from message. */
#define SHA1_LOAD_W_FROM_MESSAGE(which) \
w[which] = vreinterpretq_u32_u8(vrev32q_u8(vld1q_u8(data))); \
data += 0x10
#define SHA1_CALCULATE_W_FROM_PREVIOUS(i) \
w[i] = vsha1su1q_u32(vsha1su0q_u32(w[i-4], w[i-3], w[i-2]), w[i-1])
/* Define for doing four rounds of SHA1. */
#define SHA1_DO_ROUND(r, insn, constant) \
do { \
const u32 a = vgetq_lane_u32(cur_abcd, 0); \
cur_abcd = v##insn##q_u32(cur_abcd, cur_e, vaddq_u32(w[r], constant)); \
cur_e = vsha1h_u32(a); \
} while (0)
}
void Sha1Impl::Initialize() {
/* Reset buffered bytes/bits. */
m_buffered_bytes = 0;
m_bits_consumed = 0;
/* Set intermediate hash. */
m_intermediate_hash[0] = 0x67452301;
m_intermediate_hash[1] = 0xEFCDAB89;
m_intermediate_hash[2] = 0x98BADCFE;
m_intermediate_hash[3] = 0x10325476;
m_intermediate_hash[4] = 0xC3D2E1F0;
/* Set state. */
m_state = State_Initialized;
}
void Sha1Impl::Update(const void *data, size_t size) {
/* Verify we're in a state to update. */
AMS_ASSERT(m_state == State_Initialized);
/* Advance our input bit count. */
m_bits_consumed += BITSIZEOF(u8) * (((m_buffered_bytes + size) / BlockSize) * BlockSize);
/* Process anything we have buffered. */
const u8 *data8 = static_cast<const u8 *>(data);
size_t remaining = size;
if (m_buffered_bytes > 0) {
const size_t copy_size = std::min(BlockSize - m_buffered_bytes, remaining);
std::memcpy(m_buffer + m_buffered_bytes, data8, copy_size);
data8 += copy_size;
remaining -= copy_size;
m_buffered_bytes += copy_size;
/* Process a block, if we filled one. */
if (m_buffered_bytes == BlockSize) {
this->ProcessBlock(m_buffer);
m_buffered_bytes = 0;
}
}
/* Process blocks, if we have any. */
if (remaining >= BlockSize) {
const size_t blocks = remaining / BlockSize;
this->ProcessBlocks(data8, blocks);
data8 += BlockSize * blocks;
remaining -= BlockSize * blocks;
}
/* Copy any leftover data to our buffer. */
if (remaining > 0) {
m_buffered_bytes = remaining;
std::memcpy(m_buffer, data8, remaining);
}
}
void Sha1Impl::GetHash(void *dst, size_t size) {
/* Verify we're in a state to get hash. */
AMS_ASSERT(m_state == State_Initialized || m_state == State_Done);
AMS_ASSERT(size >= HashSize);
AMS_UNUSED(size);
/* If we need to, process the last block. */
if (m_state == State_Initialized) {
this->ProcessLastBlock();
m_state = State_Done;
}
/* Copy the output hash. */
if constexpr (util::IsLittleEndian()) {
static_assert(HashSize % sizeof(u32) == 0);
u32 *dst_32 = static_cast<u32 *>(dst);
for (size_t i = 0; i < HashSize / sizeof(u32); ++i) {
dst_32[i] = util::LoadBigEndian<u32>(m_intermediate_hash + i);
}
} else {
std::memcpy(dst, m_intermediate_hash, HashSize);
}
}
ALWAYS_INLINE void Sha1Impl::ProcessBlock(const void *data) {
return this->ProcessBlocks(static_cast<const u8 *>(data), 1);
}
void Sha1Impl::ProcessBlocks(const u8 *data, size_t block_count) {
/* Setup round constants. */
const uint32x4_t k0 = vdupq_n_u32(RoundConstants[0]);
const uint32x4_t k1 = vdupq_n_u32(RoundConstants[1]);
const uint32x4_t k2 = vdupq_n_u32(RoundConstants[2]);
const uint32x4_t k3 = vdupq_n_u32(RoundConstants[3]);
/* Load hash variables with intermediate state. */
uint32x4_t cur_abcd = vld1q_u32(m_intermediate_hash + 0);
u32 cur_e = m_intermediate_hash[4];
/* Actually do hash processing blocks. */
do {
/* Save current state. */
const uint32x4_t prev_abcd = cur_abcd;
const u32 prev_e = cur_e;
uint32x4_t w[20];
/* Setup w[0-3] with message. */
SHA1_LOAD_W_FROM_MESSAGE(0);
SHA1_LOAD_W_FROM_MESSAGE(1);
SHA1_LOAD_W_FROM_MESSAGE(2);
SHA1_LOAD_W_FROM_MESSAGE(3);
/* Calculate w[4-19], w[i] = sha1su1(sha1su0(w[i-4], w[i-3], w[i-2]), w[i-1]); */
SHA1_CALCULATE_W_FROM_PREVIOUS(4);
SHA1_CALCULATE_W_FROM_PREVIOUS(5);
SHA1_CALCULATE_W_FROM_PREVIOUS(6);
SHA1_CALCULATE_W_FROM_PREVIOUS(7);
SHA1_CALCULATE_W_FROM_PREVIOUS(8);
SHA1_CALCULATE_W_FROM_PREVIOUS(9);
SHA1_CALCULATE_W_FROM_PREVIOUS(10);
SHA1_CALCULATE_W_FROM_PREVIOUS(11);
SHA1_CALCULATE_W_FROM_PREVIOUS(12);
SHA1_CALCULATE_W_FROM_PREVIOUS(13);
SHA1_CALCULATE_W_FROM_PREVIOUS(14);
SHA1_CALCULATE_W_FROM_PREVIOUS(15);
SHA1_CALCULATE_W_FROM_PREVIOUS(16);
SHA1_CALCULATE_W_FROM_PREVIOUS(17);
SHA1_CALCULATE_W_FROM_PREVIOUS(18);
SHA1_CALCULATE_W_FROM_PREVIOUS(19);
/* Do round calculations 0-20. Uses sha1c, k0. */
SHA1_DO_ROUND(0, sha1c, k0);
SHA1_DO_ROUND(1, sha1c, k0);
SHA1_DO_ROUND(2, sha1c, k0);
SHA1_DO_ROUND(3, sha1c, k0);
SHA1_DO_ROUND(4, sha1c, k0);
/* Do round calculations 20-40. Uses sha1p, k1. */
SHA1_DO_ROUND(5, sha1p, k1);
SHA1_DO_ROUND(6, sha1p, k1);
SHA1_DO_ROUND(7, sha1p, k1);
SHA1_DO_ROUND(8, sha1p, k1);
SHA1_DO_ROUND(9, sha1p, k1);
/* Do round calculations 40-60. Uses sha1m, k2. */
SHA1_DO_ROUND(10, sha1m, k2);
SHA1_DO_ROUND(11, sha1m, k2);
SHA1_DO_ROUND(12, sha1m, k2);
SHA1_DO_ROUND(13, sha1m, k2);
SHA1_DO_ROUND(14, sha1m, k2);
/* Do round calculations 60-80. Uses sha1p, k3. */
SHA1_DO_ROUND(15, sha1p, k3);
SHA1_DO_ROUND(16, sha1p, k3);
SHA1_DO_ROUND(17, sha1p, k3);
SHA1_DO_ROUND(18, sha1p, k3);
SHA1_DO_ROUND(19, sha1p, k3);
/* Add to previous. */
cur_abcd = vaddq_u32(cur_abcd, prev_abcd);
cur_e = cur_e + prev_e;
} while (--block_count != 0);
/* Save result to intermediate hash. */
vst1q_u32(m_intermediate_hash, cur_abcd);
m_intermediate_hash[4] = cur_e;
}
void Sha1Impl::ProcessLastBlock() {
/* Setup the final block. */
constexpr const auto BlockSizeWithoutSizeField = BlockSize - sizeof(u64);
/* Increment our bits consumed. */
m_bits_consumed += BITSIZEOF(u8) * m_buffered_bytes;
/* Add 0x80 terminator. */
m_buffer[m_buffered_bytes++] = 0x80;
/* If we can process the size field directly, do so, otherwise set up to process it. */
if (m_buffered_bytes <= BlockSizeWithoutSizeField) {
/* Clear up to size field. */
std::memset(m_buffer + m_buffered_bytes, 0, BlockSizeWithoutSizeField - m_buffered_bytes);
} else {
/* Consume full block */
std::memset(m_buffer + m_buffered_bytes, 0, BlockSize - m_buffered_bytes);
this->ProcessBlock(m_buffer);
/* Clear up to size field. */
std::memset(m_buffer, 0, BlockSizeWithoutSizeField);
}
/* Store the size field. */
util::StoreBigEndian<u64>(reinterpret_cast<u64 *>(m_buffer + BlockSizeWithoutSizeField), m_bits_consumed);
/* Process the final block. */
this->ProcessBlock(m_buffer);
}
}
#endif
| 9,095
|
C++
|
.cpp
| 201
| 35.258706
| 114
| 0.560289
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,081
|
crypto_bignum_operations.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/crypto/impl/crypto_bignum_operations.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <vapours.hpp>
namespace ams::crypto::impl {
namespace {
constexpr ALWAYS_INLINE BigNum::Word GetTop2Bits(BigNum::Word w) {
return (w >> (BigNum::BitsPerWord - 2)) & 0x3u;
}
constexpr ALWAYS_INLINE void MultWord(BigNum::Word *dst, BigNum::Word lhs, BigNum::Word rhs) {
static_assert(sizeof(BigNum::DoubleWord) == sizeof(BigNum::Word) * 2);
BigNum::DoubleWord result = static_cast<BigNum::DoubleWord>(lhs) * static_cast<BigNum::DoubleWord>(rhs);
dst[0] = static_cast<BigNum::Word>(result & ~BigNum::Word());
dst[1] = static_cast<BigNum::Word>(result >> BITSIZEOF(BigNum::Word));
}
constexpr ALWAYS_INLINE BigNum::HalfWord GetUpperHalf(BigNum::Word word) {
static_assert(sizeof(BigNum::Word) == sizeof(BigNum::HalfWord) * 2);
return static_cast<BigNum::HalfWord>((word >> BITSIZEOF(BigNum::HalfWord)) & ~BigNum::HalfWord());
}
constexpr ALWAYS_INLINE BigNum::HalfWord GetLowerHalf(BigNum::Word word) {
static_assert(sizeof(BigNum::Word) == sizeof(BigNum::HalfWord) * 2);
return static_cast<BigNum::HalfWord>(word & ~BigNum::HalfWord());
}
constexpr ALWAYS_INLINE BigNum::Word ToUpperHalf(BigNum::HalfWord half) {
static_assert(sizeof(BigNum::Word) == sizeof(BigNum::HalfWord) * 2);
return static_cast<BigNum::Word>(half) << BITSIZEOF(BigNum::HalfWord);
}
[[maybe_unused]] constexpr ALWAYS_INLINE BigNum::Word ToLowerHalf(BigNum::HalfWord half) {
static_assert(sizeof(BigNum::Word) == sizeof(BigNum::HalfWord) * 2);
return static_cast<BigNum::Word>(half);
}
constexpr ALWAYS_INLINE BigNum::Word DivWord(const BigNum::Word *w, BigNum::Word div) {
using Word = BigNum::Word;
using HalfWord = BigNum::HalfWord;
Word work[2] = { w[0], w[1] };
HalfWord r_hi = 0, r_lo = 0;
HalfWord d_hi = GetUpperHalf(div);
HalfWord d_lo = GetLowerHalf(div);
if (d_hi == BigNum::MaxHalfWord) {
r_hi = GetUpperHalf(work[1]);
} else {
r_hi = GetLowerHalf(work[1] / (d_hi + 1));
}
{
const Word hh = static_cast<Word>(r_hi) * static_cast<Word>(d_hi);
const Word hl = static_cast<Word>(r_hi) * static_cast<Word>(d_lo);
const Word uhl = ToUpperHalf(static_cast<HalfWord>(hl));
if ((work[0] -= uhl) > (BigNum::MaxWord - uhl)) {
work[1]--;
}
work[1] -= GetUpperHalf(hl);
work[1] -= hh;
const Word udl = ToUpperHalf(d_lo);
while (work[1] > d_hi || (work[1] == d_hi && work[0] >= udl)) {
if ((work[0] -= udl) > (BigNum::MaxWord - udl)) {
work[1]--;
}
work[1] -= d_hi;
r_hi++;
}
}
if (d_hi == BigNum::MaxHalfWord) {
r_lo = GetLowerHalf(work[1]);
} else {
r_lo = GetLowerHalf((ToUpperHalf(static_cast<HalfWord>(work[1])) + GetUpperHalf(work[0])) / (d_hi + 1));
}
{
const Word ll = static_cast<Word>(r_lo) * static_cast<Word>(d_lo);
const Word lh = static_cast<Word>(r_lo) * static_cast<Word>(d_hi);
if ((work[0] -= ll) > (BigNum::MaxWord - ll)) {
work[1]--;
}
const Word ulh = ToUpperHalf(static_cast<HalfWord>(lh));
if ((work[0] -= ulh) > (BigNum::MaxWord - ulh)) {
work[1]--;
}
work[1] -= GetUpperHalf(lh);
while ((work[1] > 0) || (work[1] == 0 && work[0] >= div)) {
if ((work[0] -= div) > (BigNum::MaxWord - div)) {
work[1]--;
}
r_lo++;
}
}
return ToUpperHalf(r_hi) + r_lo;
}
}
bool BigNum::IsZero(const Word *w, size_t num_words) {
for (size_t i = 0; i < num_words; i++) {
if (w[i]) {
return false;
}
}
return true;
}
int BigNum::Compare(const Word *lhs, const Word *rhs, size_t num_words) {
for (s32 i = static_cast<s32>(num_words) - 1; i >= 0; i--) {
if (lhs[i] > rhs[i]) {
return 1;
} else if (lhs[i] < rhs[i]) {
return -1;
}
}
return 0;
}
size_t BigNum::CountWords(const Word *w, size_t num_words) {
s32 i = static_cast<s32>(num_words) - 1;
while (i >= 0 && !w[i]) {
i--;
}
return i + 1;
}
size_t BigNum::CountSignificantBits(Word w) {
size_t i;
for (i = 0; i < BitsPerWord && w != 0; i++) {
w >>= 1;
}
return i;
}
void BigNum::ClearToZero(Word *w, size_t num_words) {
for (size_t i = 0; i < num_words; i++) {
w[i] = 0;
}
}
void BigNum::SetToWord(Word *w, size_t num_words, Word v) {
ClearToZero(w, num_words);
w[0] = v;
}
void BigNum::Copy(Word *dst, const Word *src, size_t num_words) {
for (size_t i = 0; i < num_words; i++) {
dst[i] = src[i];
}
}
BigNum::Word BigNum::LeftShift(Word *dst, const Word *w, size_t num_words, const size_t shift) {
if (shift >= BitsPerWord) {
return 0;
}
const size_t invshift = BitsPerWord - shift;
Word carry = 0;
for (size_t i = 0; i < num_words; i++) {
const Word cur = w[i];
dst[i] = (cur << shift) | carry;
carry = shift ? (cur >> invshift) : 0;
}
return carry;
}
BigNum::Word BigNum::RightShift(Word *dst, const Word *w, size_t num_words, const size_t shift) {
if (shift >= BitsPerWord) {
return 0;
}
const size_t invshift = BitsPerWord - shift;
Word carry = 0;
for (s32 i = static_cast<s32>(num_words) - 1; i >= 0; i--) {
const Word cur = w[i];
dst[i] = (cur >> shift) | carry;
carry = shift ? (cur << invshift) : 0;
}
return carry;
}
BigNum::Word BigNum::MultSub(Word *dst, const Word *w, const Word *v, size_t num_words, Word mult) {
/* If multiplying by zero, nothing to do. */
if (mult == 0) {
return 0;
}
Word borrow = 0, work[2];
for (size_t i = 0; i < num_words; i++) {
/* Multiply, calculate borrow for next. */
MultWord(work, mult, v[i]);
if ((dst[i] = (w[i] - borrow)) > (MaxWord - borrow)) {
borrow = 1;
} else {
borrow = 0;
}
if ((dst[i] -= work[0]) > (MaxWord - work[0])) {
borrow++;
}
borrow += work[1];
}
return borrow;
}
bool BigNum::ExpMod(Word *dst, const Word *src, const Word *exp, size_t exp_words, const Word *mod, size_t mod_words, WordAllocator *allocator) {
/* Nintendo uses an algorithm that relies on powers of exp. */
bool needs_exp[4] = {};
if (exp_words > 1) {
needs_exp[2] = true;
needs_exp[3] = true;
} else {
Word exp_w = exp[0];
for (size_t i = 0; i < BitsPerWord / 2; i++) {
/* Nintendo at each step determines needed exponent from a pair of two bits. */
needs_exp[exp_w & 0x3u] = true;
exp_w >>= 2;
}
if (needs_exp[3]) {
needs_exp[2] = true;
}
}
/* Allocate space for powers 1, 2, 3. */
auto power_1 = allocator->Allocate(mod_words);
auto power_2 = allocator->Allocate(mod_words);
auto power_3 = allocator->Allocate(mod_words);
if (!(power_1.IsValid() && power_2.IsValid() && power_3.IsValid())) {
return false;
}
decltype(power_1)* powers[3] = { std::addressof(power_1), std::addressof(power_2), std::addressof(power_3) };
/* Set the powers of src. */
Copy(power_1.GetBuffer(), src, mod_words);
if (needs_exp[2]) {
if (!MultMod(power_2.GetBuffer(), power_1.GetBuffer(), src, mod, mod_words, allocator)) {
return false;
}
}
if (needs_exp[3]) {
if (!MultMod(power_3.GetBuffer(), power_2.GetBuffer(), src, mod, mod_words, allocator)) {
return false;
}
}
/* Allocate space to work. */
auto work = allocator->Allocate(mod_words);
if (!work.IsValid()) {
return false;
}
SetToWord(work.GetBuffer(), work.GetCount(), 1);
/* Ensure we're working with the correct exponent word count. */
exp_words = CountWords(exp, exp_words);
for (s32 i = static_cast<s32>(exp_words - 1); i >= 0; i--) {
Word cur_word = exp[i];
size_t cur_bits = BitsPerWord;
/* Remove leading zeroes in first word. */
if (i == static_cast<s32>(exp_words - 1)) {
while (!GetTop2Bits(cur_word)) {
cur_word <<= 2;
cur_bits -= 2;
}
}
/* Compute current modular multiplicative step. */
for (size_t j = 0; j < cur_bits; j += 2, cur_word <<= 2) {
/* Exponentiate current work to the 4th power. */
if (!MultMod(work.GetBuffer(), work.GetBuffer(), work.GetBuffer(), mod, mod_words, allocator)) {
return false;
}
if (!MultMod(work.GetBuffer(), work.GetBuffer(), work.GetBuffer(), mod, mod_words, allocator)) {
return false;
}
if (const Word top = GetTop2Bits(cur_word)) {
if (!MultMod(work.GetBuffer(), work.GetBuffer(), powers[top - 1]->GetBuffer(), mod, mod_words, allocator)) {
return false;
}
}
}
}
/* Copy work to output. */
Copy(dst, work.GetBuffer(), mod_words);
return true;
}
bool BigNum::MultMod(Word *dst, const Word *src, const Word *mult, const Word *mod, size_t num_words, WordAllocator *allocator) {
/* Allocate work. */
auto work = allocator->Allocate(2 * num_words);
if (!work.IsValid()) {
return false;
}
/* Multiply. */
if (!Mult(work.GetBuffer(), src, mult, num_words, allocator)) {
return false;
}
/* Mod. */
if (!Mod(dst, work.GetBuffer(), 2 * num_words, mod, num_words, allocator)) {
return false;
}
return true;
}
bool BigNum::Mod(Word *dst, const Word *src, size_t src_words, const Word *mod, size_t mod_words, WordAllocator *allocator) {
/* Allocate work. */
auto work = allocator->Allocate(src_words);
if (!work.IsValid()) {
return false;
}
if (!DivMod(work.GetBuffer(), dst, src, src_words, mod, mod_words, allocator)) {
return false;
}
return true;
}
bool BigNum::DivMod(Word *quot, Word *rem, const Word *top, size_t top_words, const Word *bot, size_t bot_words, WordAllocator *allocator) {
/* Allocate work. */
auto top_work = allocator->Allocate(top_words + 1);
auto bot_work = allocator->Allocate(bot_words);
if (!(top_work.IsValid() && bot_work.IsValid())) {
return false;
}
/* Prevent division by zero. */
size_t bot_work_words = CountWords(bot, bot_words);
if (bot_work_words == 0) {
return false;
}
ClearToZero(quot, top_words);
ClearToZero(top_work.GetBuffer(), bot_work_words);
/* Align to edges. */
const size_t shift = BitsPerWord - CountSignificantBits(bot[bot_work_words - 1]);
top_work.GetBuffer()[top_words] = LeftShift(top_work.GetBuffer(), top, top_words, shift);
LeftShift(bot_work.GetBuffer(), bot, bot_work_words, shift);
const Word tb = bot_work.GetBuffer()[bot_work_words - 1];
/* Repeatedly div + sub. */
for (s32 i = (top_words - bot_work_words); i >= 0; i--) {
Word cur_word;
if (tb == MaxWord) {
cur_word = top_work.GetBuffer()[i + bot_work_words];
} else {
cur_word = DivWord(top_work.GetBuffer() + i + bot_work_words - 1, tb + 1);
}
top_work.GetBuffer()[i + bot_work_words] -= MultSub(top_work.GetBuffer() + i, top_work.GetBuffer() + i, bot_work.GetBuffer(), bot_work_words, cur_word);
while (top_work.GetBuffer()[i + bot_work_words] || Compare(top_work.GetBuffer() + i, bot_work.GetBuffer(), bot_work_words) >= 0) {
cur_word++;
top_work.GetBuffer()[i + bot_work_words] -= Sub(top_work.GetBuffer() + i, top_work.GetBuffer() + i, bot_work.GetBuffer(), bot_work_words);
}
quot[i] = cur_word;
}
/* Calculate remainder. */
ClearToZero(rem, bot_words);
RightShift(rem, top_work.GetBuffer(), bot_work_words, shift);
return true;
}
bool BigNum::Mult(Word *dst, const Word *lhs, const Word *rhs, size_t num_words, WordAllocator *allocator) {
/* Allocate work. */
auto work = allocator->Allocate(2 * num_words);
if (!work.IsValid()) {
return false;
}
ClearToZero(work.GetBuffer(), work.GetCount());
/* Repeatedly add and multiply. */
const size_t lhs_words = CountWords(lhs, num_words);
const size_t rhs_words = CountWords(rhs, num_words);
for (size_t i = 0; i < lhs_words; i++) {
work.GetBuffer()[i + rhs_words] += MultAdd(work.GetBuffer() + i, rhs, rhs_words, lhs[i]);
}
/* Copy to output. */
Copy(dst, work.GetBuffer(), work.GetCount());
return true;
}
#if !defined(ATMOSPHERE_ARCH_ARM64)
BigNum::Word BigNum::Add(Word *dst, const Word *lhs, const Word *rhs, size_t num_words) {
Word carry = 0;
for (size_t i = 0; i < num_words; ++i) {
Word v;
if ((v = lhs[i] + carry) < carry) {
v = rhs[i];
} else if ((v += rhs[i]) < rhs[i]) {
carry = 1;
} else {
carry = 0;
}
dst[i] = v;
}
return carry;
}
BigNum::Word BigNum::Sub(Word *dst, const Word *lhs, const Word *rhs, size_t num_words) {
Word borrow = 0;
for (size_t i = 0; i < num_words; ++i) {
Word v;
if ((v = lhs[i] - borrow) > (BigNum::MaxWord - borrow)) {
v = BigNum::MaxWord - rhs[i];
} else if ((v -= rhs[i]) > (BigNum::MaxWord - rhs[i])) {
borrow = 1;
} else {
borrow = 0;
}
dst[i] = v;
}
return borrow;
}
BigNum::Word BigNum::MultAdd(Word *dst, const Word *w, size_t num_words, Word mult) {
/* If multiplying by zero, nothing to do. */
if (mult == 0) {
return 0;
}
Word carry = 0, work[2];
for (size_t i = 0; i < num_words; i++) {
/* Multiply, calculate carry for next. */
MultWord(work, mult, w[i]);
if ((dst[i] += carry) < carry) {
carry = 1;
} else {
carry = 0;
}
if ((dst[i] += work[0]) < work[0]) {
carry++;
}
carry += work[1];
}
return carry;
}
#endif
}
| 16,785
|
C++
|
.cpp
| 404
| 30.173267
| 164
| 0.504909
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,082
|
crypto_sha256_impl.arch.generic.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/crypto/impl/crypto_sha256_impl.arch.generic.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <vapours.hpp>
namespace ams::crypto::impl {
namespace {
alignas(Sha256Impl::BlockSize) constexpr const u32 RoundConstants[0x40] = {
0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,
0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,
0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,
0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,
0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,
0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2,
};
constexpr ALWAYS_INLINE u32 Choose(u32 x, u32 y, u32 z) {
return (x & y) ^ ((~x) & z);
}
constexpr ALWAYS_INLINE u32 Majority(u32 x, u32 y, u32 z) {
return (x & y) ^ (x & z) ^ (y & z);
}
constexpr ALWAYS_INLINE u32 LargeSigma0(u32 x) {
return util::RotateRight<u32>(x, 2) ^ util::RotateRight<u32>(x, 13) ^ util::RotateRight<u32>(x, 22);
}
constexpr ALWAYS_INLINE u32 LargeSigma1(u32 x) {
return util::RotateRight<u32>(x, 6) ^ util::RotateRight<u32>(x, 11) ^ util::RotateRight<u32>(x, 25);
}
constexpr ALWAYS_INLINE u32 SmallSigma0(u32 x) {
return util::RotateRight<u32>(x, 7) ^ util::RotateRight<u32>(x, 18) ^ (x >> 3);
}
constexpr ALWAYS_INLINE u32 SmallSigma1(u32 x) {
return util::RotateRight<u32>(x, 17) ^ util::RotateRight<u32>(x, 19) ^ (x >> 10);
}
}
void Sha256Impl::Initialize() {
/* Reset buffered bytes/bits. */
m_buffered_bytes = 0;
m_bits_consumed = 0;
/* Set intermediate hash. */
m_intermediate_hash[0] = 0x6A09E667;
m_intermediate_hash[1] = 0xBB67AE85;
m_intermediate_hash[2] = 0x3C6EF372;
m_intermediate_hash[3] = 0xA54FF53A;
m_intermediate_hash[4] = 0x510E527F;
m_intermediate_hash[5] = 0x9B05688C;
m_intermediate_hash[6] = 0x1F83D9AB;
m_intermediate_hash[7] = 0x5BE0CD19;
/* Set state. */
m_state = State_Initialized;
}
void Sha256Impl::Update(const void *data, size_t size) {
/* Verify we're in a state to update. */
AMS_ASSERT(m_state == State_Initialized);
/* Advance our input bit count. */
m_bits_consumed += BITSIZEOF(u8) * (((m_buffered_bytes + size) / BlockSize) * BlockSize);
/* Process anything we have buffered. */
const u8 *data8 = static_cast<const u8 *>(data);
size_t remaining = size;
if (m_buffered_bytes > 0) {
const size_t copy_size = std::min(BlockSize - m_buffered_bytes, remaining);
std::memcpy(m_buffer + m_buffered_bytes, data8, copy_size);
data8 += copy_size;
remaining -= copy_size;
m_buffered_bytes += copy_size;
/* Process a block, if we filled one. */
if (m_buffered_bytes == BlockSize) {
this->ProcessBlock(m_buffer);
m_buffered_bytes = 0;
}
}
/* Process blocks, if we have any. */
while (remaining >= BlockSize) {
this->ProcessBlock(data8);
data8 += BlockSize;
remaining -= BlockSize;
}
/* Copy any leftover data to our buffer. */
if (remaining > 0) {
m_buffered_bytes = remaining;
std::memcpy(m_buffer, data8, remaining);
}
}
void Sha256Impl::GetHash(void *dst, size_t size) {
/* Verify we're in a state to get hash. */
AMS_ASSERT(m_state == State_Initialized || m_state == State_Done);
AMS_ASSERT(size >= HashSize);
AMS_UNUSED(size);
/* If we need to, process the last block. */
if (m_state == State_Initialized) {
this->ProcessLastBlock();
m_state = State_Done;
}
/* Copy the output hash. */
if constexpr (util::IsLittleEndian()) {
static_assert(HashSize % sizeof(u32) == 0);
u32 *dst_32 = static_cast<u32 *>(dst);
for (size_t i = 0; i < HashSize / sizeof(u32); ++i) {
dst_32[i] = util::LoadBigEndian<u32>(m_intermediate_hash + i);
}
} else {
std::memcpy(dst, m_intermediate_hash, HashSize);
}
}
void Sha256Impl::InitializeWithContext(const Sha256Context *context) {
/* Copy state in from the context. */
std::memcpy(m_intermediate_hash, context->intermediate_hash, sizeof(m_intermediate_hash));
m_bits_consumed = context->bits_consumed;
/* Reset other fields. */
m_buffered_bytes = 0;
m_state = State_Initialized;
}
size_t Sha256Impl::GetContext(Sha256Context *context) const {
/* Check our state. */
AMS_ASSERT(m_state == State_Initialized);
/* Copy out the context. */
std::memcpy(context->intermediate_hash, m_intermediate_hash, sizeof(context->intermediate_hash));
context->bits_consumed = m_bits_consumed;
return m_buffered_bytes;
}
void Sha256Impl::ProcessBlock(const void *data) {
/* Load work variables. */
u32 a = m_intermediate_hash[0];
u32 b = m_intermediate_hash[1];
u32 c = m_intermediate_hash[2];
u32 d = m_intermediate_hash[3];
u32 e = m_intermediate_hash[4];
u32 f = m_intermediate_hash[5];
u32 g = m_intermediate_hash[6];
u32 h = m_intermediate_hash[7];
u32 tmp[2];
size_t i;
/* Copy the input. */
u32 w[64];
if constexpr (util::IsLittleEndian()) {
static_assert(BlockSize % sizeof(u32) == 0);
const u32 *src_32 = static_cast<const u32 *>(data);
for (size_t i = 0; i < BlockSize / sizeof(u32); ++i) {
w[i] = util::LoadBigEndian<u32>(src_32 + i);
}
} else {
std::memcpy(w, data, BlockSize);
}
/* Initialize the rest of w. */
for (i = BlockSize / sizeof(u32); i < util::size(w); ++i) {
const u32 *prev = w + (i - BlockSize / sizeof(u32));
w[i] = prev[0] + SmallSigma0(prev[1]) + prev[9] + SmallSigma1(prev[14]);
}
/* Perform rounds. */
for (i = 0; i < 64; ++i) {
tmp[0] = h + LargeSigma1(e) + Choose(e, f, g) + RoundConstants[i] + w[i];
tmp[1] = LargeSigma0(a) + Majority(a, b, c);
h = g;
g = f;
f = e;
e = d + tmp[0];
d = c;
c = b;
b = a;
a = tmp[0] + tmp[1];
}
/* Update intermediate hash. */
m_intermediate_hash[0] += a;
m_intermediate_hash[1] += b;
m_intermediate_hash[2] += c;
m_intermediate_hash[3] += d;
m_intermediate_hash[4] += e;
m_intermediate_hash[5] += f;
m_intermediate_hash[6] += g;
m_intermediate_hash[7] += h;
}
void Sha256Impl::ProcessLastBlock() {
/* Setup the final block. */
constexpr const auto BlockSizeWithoutSizeField = BlockSize - sizeof(u64);
/* Increment our bits consumed. */
m_bits_consumed += BITSIZEOF(u8) * m_buffered_bytes;
/* Add 0x80 terminator. */
m_buffer[m_buffered_bytes++] = 0x80;
/* If we can process the size field directly, do so, otherwise set up to process it. */
if (m_buffered_bytes <= BlockSizeWithoutSizeField) {
/* Clear up to size field. */
std::memset(m_buffer + m_buffered_bytes, 0, BlockSizeWithoutSizeField - m_buffered_bytes);
} else {
/* Consume full block */
std::memset(m_buffer + m_buffered_bytes, 0, BlockSize - m_buffered_bytes);
this->ProcessBlock(m_buffer);
/* Clear up to size field. */
std::memset(m_buffer, 0, BlockSizeWithoutSizeField);
}
/* Store the size field. */
util::StoreBigEndian<u64>(reinterpret_cast<u64 *>(m_buffer + BlockSizeWithoutSizeField), m_bits_consumed);
/* Process the final block. */
this->ProcessBlock(m_buffer);
}
}
| 9,398
|
C++
|
.cpp
| 215
| 34.027907
| 114
| 0.577916
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,083
|
crypto_ctr_mode_impl.arch.arm64.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/crypto/impl/crypto_ctr_mode_impl.arch.arm64.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <vapours.hpp>
#ifdef ATMOSPHERE_IS_STRATOSPHERE
#include <arm_neon.h>
namespace ams::crypto::impl {
/* Variable management macros. */
#define DECLARE_ROUND_KEY_VAR(n) \
const uint8x16_t round_key_##n = vld1q_u8(keys + (BlockSize * n))
#define AES_ENC_DEC_OUTPUT_THREE_BLOCKS() \
[tmp0]"+w"(tmp0), [tmp1]"+w"(tmp1), [tmp2]"+w"(tmp2)
#define AES_ENC_DEC_OUTPUT_THREE_CTRS() \
[ctr0]"+w"(ctr0), [ctr1]"+w"(ctr1), [ctr2]"+w"(ctr2)
#define AES_ENC_DEC_OUTPUT_ONE_BLOCK() \
[tmp0]"+w"(tmp0)
#define AES_ENC_DEC_OUTPUT_ONE_CTR() \
[ctr0]"+w"(ctr0)
#define CTR_INCREMENT_OUTPUT_HIGH_LOW() \
[high]"=&r"(high), [low]"=&r"(low)
#define CTR_INCREMENT_OUTPUT_HIGH_LOW_TMP() \
[high_tmp]"=&r"(high_tmp), [low_tmp]"=&r"(low_tmp)
#define CTR_INCREMENT_OUTPUT_HL_SINGLE_TMP() \
[hl_tmp]"=&r"(hl_tmp)
#define AES_ENC_DEC_INPUT_ROUND_KEY(n) \
[round_key_##n]"w"(round_key_##n)
/* AES Encryption macros. */
#define AES_ENC_ROUND(n, i) \
"aese %[tmp" #i "].16b, %[round_key_" #n "].16b\n" \
"aesmc %[tmp" #i "].16b, %[tmp" #i "].16b\n"
#define AES_ENC_SECOND_LAST_ROUND(n, i) \
"aese %[tmp" #i "].16b, %[round_key_" #n "].16b\n"
#define AES_ENC_LAST_ROUND(n, i) \
"eor %[tmp" #i "].16b, %[tmp" #i "].16b, %[round_key_" #n "].16b\n"
namespace {
ALWAYS_INLINE uint8x16_t IncrementCounterOptimized(const uint8x16_t ctr) {
uint8x16_t inc;
uint64_t high, low;
/* Use ASM. TODO: Better than using intrinsics? */
__asm__ __volatile__ (
"mov %[high], %[ctr].d[0]\n"
"mov %[low], %[ctr].d[1]\n"
"rev %[high], %[high]\n"
"rev %[low], %[low]\n"
"adds %[low], %[low], 1\n"
"cinc %[high], %[high], cs\n"
"rev %[high], %[high]\n"
"rev %[low], %[low]\n"
"mov %[inc].d[0], %[high]\n"
"mov %[inc].d[1], %[low]\n"
: [inc]"=w"(inc),
CTR_INCREMENT_OUTPUT_HIGH_LOW()
: [ctr]"w"(ctr)
: "cc"
);
return inc;
}
}
template<>
void CtrModeImpl<AesEncryptor128>::ProcessBlocks(u8 *dst, const u8 *src, size_t num_blocks) {
/* Preload all round keys + iv into neon registers. */
const u8 *keys = m_block_cipher->GetRoundKey();
DECLARE_ROUND_KEY_VAR(0);
DECLARE_ROUND_KEY_VAR(1);
DECLARE_ROUND_KEY_VAR(2);
DECLARE_ROUND_KEY_VAR(3);
DECLARE_ROUND_KEY_VAR(4);
DECLARE_ROUND_KEY_VAR(5);
DECLARE_ROUND_KEY_VAR(6);
DECLARE_ROUND_KEY_VAR(7);
DECLARE_ROUND_KEY_VAR(8);
DECLARE_ROUND_KEY_VAR(9);
DECLARE_ROUND_KEY_VAR(10);
uint8x16_t ctr0 = vld1q_u8(m_counter);
uint64_t high, low;
/* Process three blocks at a time, when possible. */
if (num_blocks >= 3) {
/* Increment CTR twice. */
uint8x16_t ctr1 = IncrementCounterOptimized(ctr0);
uint8x16_t ctr2 = IncrementCounterOptimized(ctr1);
uint64_t high_tmp, low_tmp;
while (num_blocks >= 3) {
/* Read blocks in. Keep them in registers for XOR later. */
const uint8x16_t block0 = vld1q_u8(src);
src += AesEncryptor128::BlockSize;
const uint8x16_t block1 = vld1q_u8(src);
src += AesEncryptor128::BlockSize;
const uint8x16_t block2 = vld1q_u8(src);
src += AesEncryptor128::BlockSize;
/* We'll be encrypting the three CTRs. */
uint8x16_t tmp0 = ctr0, tmp1 = ctr1, tmp2 = ctr2;
/* Actually do encryption, use optimized asm. */
/* Interleave CTR calculations with AES ones, to mask latencies. */
__asm__ __volatile__ (
AES_ENC_ROUND(0, 0) "mov %[high], %[ctr2].d[0]\n"
AES_ENC_ROUND(0, 1) "mov %[low], %[ctr2].d[1]\n"
AES_ENC_ROUND(0, 2) "rev %[high], %[high]\n"
AES_ENC_ROUND(1, 0) "rev %[low], %[low]\n"
AES_ENC_ROUND(1, 1) "adds %[low], %[low], 1\n"
AES_ENC_ROUND(1, 2) "cinc %[high], %[high], cs\n"
AES_ENC_ROUND(2, 0) "rev %[high_tmp], %[high]\n"
AES_ENC_ROUND(2, 1) "rev %[low_tmp], %[low]\n"
AES_ENC_ROUND(2, 2) "mov %[ctr0].d[0], %[high_tmp]\n"
AES_ENC_ROUND(3, 0) "mov %[ctr0].d[1], %[low_tmp]\n"
AES_ENC_ROUND(3, 1) "adds %[low], %[low], 1\n"
AES_ENC_ROUND(3, 2) "cinc %[high], %[high], cs\n"
AES_ENC_ROUND(4, 0) "rev %[high_tmp], %[high]\n"
AES_ENC_ROUND(4, 1) "rev %[low_tmp], %[low]\n"
AES_ENC_ROUND(4, 2) "mov %[ctr1].d[0], %[high_tmp]\n"
AES_ENC_ROUND(5, 0) "mov %[ctr1].d[1], %[low_tmp]\n"
AES_ENC_ROUND(5, 1) "adds %[low], %[low], 1\n"
AES_ENC_ROUND(5, 2) "cinc %[high], %[high], cs\n"
AES_ENC_ROUND(6, 0) "rev %[high_tmp], %[high]\n"
AES_ENC_ROUND(6, 1) "rev %[low_tmp], %[low]\n"
AES_ENC_ROUND(6, 2) "mov %[ctr2].d[0], %[high_tmp]\n"
AES_ENC_ROUND(7, 0) "mov %[ctr2].d[1], %[low_tmp]\n"
AES_ENC_ROUND(7, 1)
AES_ENC_ROUND(7, 2)
AES_ENC_ROUND(8, 0) AES_ENC_ROUND(8, 1) AES_ENC_ROUND(8, 2)
AES_ENC_SECOND_LAST_ROUND(9, 0) AES_ENC_SECOND_LAST_ROUND(9, 1) AES_ENC_SECOND_LAST_ROUND(9, 2)
AES_ENC_LAST_ROUND(10, 0) AES_ENC_LAST_ROUND(10, 1) AES_ENC_LAST_ROUND(10, 2)
: AES_ENC_DEC_OUTPUT_THREE_BLOCKS(),
AES_ENC_DEC_OUTPUT_THREE_CTRS(),
CTR_INCREMENT_OUTPUT_HIGH_LOW(),
CTR_INCREMENT_OUTPUT_HIGH_LOW_TMP()
: AES_ENC_DEC_INPUT_ROUND_KEY(0),
AES_ENC_DEC_INPUT_ROUND_KEY(1),
AES_ENC_DEC_INPUT_ROUND_KEY(2),
AES_ENC_DEC_INPUT_ROUND_KEY(3),
AES_ENC_DEC_INPUT_ROUND_KEY(4),
AES_ENC_DEC_INPUT_ROUND_KEY(5),
AES_ENC_DEC_INPUT_ROUND_KEY(6),
AES_ENC_DEC_INPUT_ROUND_KEY(7),
AES_ENC_DEC_INPUT_ROUND_KEY(8),
AES_ENC_DEC_INPUT_ROUND_KEY(9),
AES_ENC_DEC_INPUT_ROUND_KEY(10)
: "cc"
);
/* XOR blocks. */
tmp0 = veorq_u8(block0, tmp0);
tmp1 = veorq_u8(block1, tmp1);
tmp2 = veorq_u8(block2, tmp2);
/* Store to output. */
vst1q_u8(dst, tmp0);
dst += AesEncryptor128::BlockSize;
vst1q_u8(dst, tmp1);
dst += AesEncryptor128::BlockSize;
vst1q_u8(dst, tmp2);
dst += AesEncryptor128::BlockSize;
num_blocks -= 3;
}
}
while (num_blocks >= 1) {
/* Read block in, keep in register for XOR. */
const uint8x16_t block0 = vld1q_u8(src);
src += AesEncryptor128::BlockSize;
/* We'll be encrypting the CTR. */
uint8x16_t tmp0 = ctr0;
/* Actually do encryption, use optimized asm. */
/* Interleave CTR calculations with AES ones, to mask latencies. */
__asm__ __volatile__ (
AES_ENC_ROUND(0, 0) "mov %[high], %[ctr0].d[0]\n"
AES_ENC_ROUND(1, 0) "mov %[low], %[ctr0].d[1]\n"
AES_ENC_ROUND(2, 0) "rev %[high], %[high]\n"
AES_ENC_ROUND(3, 0) "rev %[low], %[low]\n"
AES_ENC_ROUND(4, 0) "adds %[low], %[low], 1\n"
AES_ENC_ROUND(5, 0) "cinc %[high], %[high], cs\n"
AES_ENC_ROUND(6, 0) "rev %[high], %[high]\n"
AES_ENC_ROUND(7, 0) "rev %[low], %[low]\n"
AES_ENC_ROUND(8, 0) "mov %[ctr0].d[0], %[high]\n"
AES_ENC_SECOND_LAST_ROUND(9, 0) "mov %[ctr0].d[1], %[low]\n"
AES_ENC_LAST_ROUND(10, 0)
: AES_ENC_DEC_OUTPUT_ONE_BLOCK(),
AES_ENC_DEC_OUTPUT_ONE_CTR(),
CTR_INCREMENT_OUTPUT_HIGH_LOW()
: AES_ENC_DEC_INPUT_ROUND_KEY(0),
AES_ENC_DEC_INPUT_ROUND_KEY(1),
AES_ENC_DEC_INPUT_ROUND_KEY(2),
AES_ENC_DEC_INPUT_ROUND_KEY(3),
AES_ENC_DEC_INPUT_ROUND_KEY(4),
AES_ENC_DEC_INPUT_ROUND_KEY(5),
AES_ENC_DEC_INPUT_ROUND_KEY(6),
AES_ENC_DEC_INPUT_ROUND_KEY(7),
AES_ENC_DEC_INPUT_ROUND_KEY(8),
AES_ENC_DEC_INPUT_ROUND_KEY(9),
AES_ENC_DEC_INPUT_ROUND_KEY(10)
: "cc"
);
/* XOR blocks. */
tmp0 = veorq_u8(block0, tmp0);
/* Store to output. */
vst1q_u8(dst, tmp0);
dst += AesEncryptor128::BlockSize;
num_blocks--;
}
vst1q_u8(m_counter, ctr0);
}
template<>
void CtrModeImpl<AesEncryptor192>::ProcessBlocks(u8 *dst, const u8 *src, size_t num_blocks) {
/* Preload all round keys + iv into neon registers. */
const u8 *keys = m_block_cipher->GetRoundKey();
DECLARE_ROUND_KEY_VAR(0);
DECLARE_ROUND_KEY_VAR(1);
DECLARE_ROUND_KEY_VAR(2);
DECLARE_ROUND_KEY_VAR(3);
DECLARE_ROUND_KEY_VAR(4);
DECLARE_ROUND_KEY_VAR(5);
DECLARE_ROUND_KEY_VAR(6);
DECLARE_ROUND_KEY_VAR(7);
DECLARE_ROUND_KEY_VAR(8);
DECLARE_ROUND_KEY_VAR(9);
DECLARE_ROUND_KEY_VAR(10);
DECLARE_ROUND_KEY_VAR(11);
DECLARE_ROUND_KEY_VAR(12);
uint8x16_t ctr0 = vld1q_u8(m_counter);
uint64_t high, low;
/* Process three blocks at a time, when possible. */
if (num_blocks >= 3) {
/* Increment CTR twice. */
uint8x16_t ctr1 = IncrementCounterOptimized(ctr0);
uint8x16_t ctr2 = IncrementCounterOptimized(ctr1);
uint64_t high_tmp, low_tmp;
while (num_blocks >= 3) {
/* Read blocks in. Keep them in registers for XOR later. */
const uint8x16_t block0 = vld1q_u8(src);
src += AesEncryptor192::BlockSize;
const uint8x16_t block1 = vld1q_u8(src);
src += AesEncryptor192::BlockSize;
const uint8x16_t block2 = vld1q_u8(src);
src += AesEncryptor192::BlockSize;
/* We'll be encrypting the three CTRs. */
uint8x16_t tmp0 = ctr0, tmp1 = ctr1, tmp2 = ctr2;
/* Actually do encryption, use optimized asm. */
/* Interleave CTR calculations with AES ones, to mask latencies. */
__asm__ __volatile__ (
AES_ENC_ROUND(0, 0) "mov %[high], %[ctr2].d[0]\n"
AES_ENC_ROUND(0, 1) "mov %[low], %[ctr2].d[1]\n"
AES_ENC_ROUND(0, 2) "rev %[high], %[high]\n"
AES_ENC_ROUND(1, 0) "rev %[low], %[low]\n"
AES_ENC_ROUND(1, 1) "adds %[low], %[low], 1\n"
AES_ENC_ROUND(1, 2) "cinc %[high], %[high], cs\n"
AES_ENC_ROUND(2, 0) "rev %[high_tmp], %[high]\n"
AES_ENC_ROUND(2, 1) "rev %[low_tmp], %[low]\n"
AES_ENC_ROUND(2, 2) "mov %[ctr0].d[0], %[high_tmp]\n"
AES_ENC_ROUND(3, 0) "mov %[ctr0].d[1], %[low_tmp]\n"
AES_ENC_ROUND(3, 1) "adds %[low], %[low], 1\n"
AES_ENC_ROUND(3, 2) "cinc %[high], %[high], cs\n"
AES_ENC_ROUND(4, 0) "rev %[high_tmp], %[high]\n"
AES_ENC_ROUND(4, 1) "rev %[low_tmp], %[low]\n"
AES_ENC_ROUND(4, 2) "mov %[ctr1].d[0], %[high_tmp]\n"
AES_ENC_ROUND(5, 0) "mov %[ctr1].d[1], %[low_tmp]\n"
AES_ENC_ROUND(5, 1) "adds %[low], %[low], 1\n"
AES_ENC_ROUND(5, 2) "cinc %[high], %[high], cs\n"
AES_ENC_ROUND(6, 0) "rev %[high_tmp], %[high]\n"
AES_ENC_ROUND(6, 1) "rev %[low_tmp], %[low]\n"
AES_ENC_ROUND(6, 2) "mov %[ctr2].d[0], %[high_tmp]\n"
AES_ENC_ROUND(7, 0) "mov %[ctr2].d[1], %[low_tmp]\n"
AES_ENC_ROUND(7, 1)
AES_ENC_ROUND(7, 2)
AES_ENC_ROUND(8, 0) AES_ENC_ROUND(8, 1) AES_ENC_ROUND(8, 2)
AES_ENC_ROUND(9, 0) AES_ENC_ROUND(9, 1) AES_ENC_ROUND(9, 2)
AES_ENC_ROUND(10, 0) AES_ENC_ROUND(10, 1) AES_ENC_ROUND(10, 2)
AES_ENC_SECOND_LAST_ROUND(11, 0) AES_ENC_SECOND_LAST_ROUND(11, 1) AES_ENC_SECOND_LAST_ROUND(11, 2)
AES_ENC_LAST_ROUND(12, 0) AES_ENC_LAST_ROUND(12, 1) AES_ENC_LAST_ROUND(12, 2)
: AES_ENC_DEC_OUTPUT_THREE_BLOCKS(),
AES_ENC_DEC_OUTPUT_THREE_CTRS(),
CTR_INCREMENT_OUTPUT_HIGH_LOW(),
CTR_INCREMENT_OUTPUT_HIGH_LOW_TMP()
: AES_ENC_DEC_INPUT_ROUND_KEY(0),
AES_ENC_DEC_INPUT_ROUND_KEY(1),
AES_ENC_DEC_INPUT_ROUND_KEY(2),
AES_ENC_DEC_INPUT_ROUND_KEY(3),
AES_ENC_DEC_INPUT_ROUND_KEY(4),
AES_ENC_DEC_INPUT_ROUND_KEY(5),
AES_ENC_DEC_INPUT_ROUND_KEY(6),
AES_ENC_DEC_INPUT_ROUND_KEY(7),
AES_ENC_DEC_INPUT_ROUND_KEY(8),
AES_ENC_DEC_INPUT_ROUND_KEY(9),
AES_ENC_DEC_INPUT_ROUND_KEY(10),
AES_ENC_DEC_INPUT_ROUND_KEY(11),
AES_ENC_DEC_INPUT_ROUND_KEY(12)
: "cc"
);
/* XOR blocks. */
tmp0 = veorq_u8(block0, tmp0);
tmp1 = veorq_u8(block1, tmp1);
tmp2 = veorq_u8(block2, tmp2);
/* Store to output. */
vst1q_u8(dst, tmp0);
dst += AesEncryptor192::BlockSize;
vst1q_u8(dst, tmp1);
dst += AesEncryptor192::BlockSize;
vst1q_u8(dst, tmp2);
dst += AesEncryptor192::BlockSize;
num_blocks -= 3;
}
}
while (num_blocks >= 1) {
/* Read block in, keep in register for XOR. */
const uint8x16_t block0 = vld1q_u8(src);
src += AesEncryptor192::BlockSize;
/* We'll be encrypting the CTR. */
uint8x16_t tmp0 = ctr0;
/* Actually do encryption, use optimized asm. */
/* Interleave CTR calculations with AES ones, to mask latencies. */
__asm__ __volatile__ (
AES_ENC_ROUND(0, 0) "mov %[high], %[ctr0].d[0]\n"
AES_ENC_ROUND(1, 0) "mov %[low], %[ctr0].d[1]\n"
AES_ENC_ROUND(2, 0) "rev %[high], %[high]\n"
AES_ENC_ROUND(3, 0) "rev %[low], %[low]\n"
AES_ENC_ROUND(4, 0) "adds %[low], %[low], 1\n"
AES_ENC_ROUND(5, 0) "cinc %[high], %[high], cs\n"
AES_ENC_ROUND(6, 0) "rev %[high], %[high]\n"
AES_ENC_ROUND(7, 0) "rev %[low], %[low]\n"
AES_ENC_ROUND(8, 0) "mov %[ctr0].d[0], %[high]\n"
AES_ENC_ROUND(9, 0) "mov %[ctr0].d[1], %[low]\n"
AES_ENC_ROUND(10, 0)
AES_ENC_SECOND_LAST_ROUND(11, 0)
AES_ENC_LAST_ROUND(12, 0)
: AES_ENC_DEC_OUTPUT_ONE_BLOCK(),
AES_ENC_DEC_OUTPUT_ONE_CTR(),
CTR_INCREMENT_OUTPUT_HIGH_LOW()
: AES_ENC_DEC_INPUT_ROUND_KEY(0),
AES_ENC_DEC_INPUT_ROUND_KEY(1),
AES_ENC_DEC_INPUT_ROUND_KEY(2),
AES_ENC_DEC_INPUT_ROUND_KEY(3),
AES_ENC_DEC_INPUT_ROUND_KEY(4),
AES_ENC_DEC_INPUT_ROUND_KEY(5),
AES_ENC_DEC_INPUT_ROUND_KEY(6),
AES_ENC_DEC_INPUT_ROUND_KEY(7),
AES_ENC_DEC_INPUT_ROUND_KEY(8),
AES_ENC_DEC_INPUT_ROUND_KEY(9),
AES_ENC_DEC_INPUT_ROUND_KEY(10),
AES_ENC_DEC_INPUT_ROUND_KEY(11),
AES_ENC_DEC_INPUT_ROUND_KEY(12)
: "cc"
);
/* XOR blocks. */
tmp0 = veorq_u8(block0, tmp0);
/* Store to output. */
vst1q_u8(dst, tmp0);
dst += AesEncryptor192::BlockSize;
num_blocks--;
}
vst1q_u8(m_counter, ctr0);
}
template<>
void CtrModeImpl<AesEncryptor256>::ProcessBlocks(u8 *dst, const u8 *src, size_t num_blocks) {
/* Preload all round keys + iv into neon registers. */
const u8 *keys = m_block_cipher->GetRoundKey();
DECLARE_ROUND_KEY_VAR(0);
DECLARE_ROUND_KEY_VAR(1);
DECLARE_ROUND_KEY_VAR(2);
DECLARE_ROUND_KEY_VAR(3);
DECLARE_ROUND_KEY_VAR(4);
DECLARE_ROUND_KEY_VAR(5);
DECLARE_ROUND_KEY_VAR(6);
DECLARE_ROUND_KEY_VAR(7);
DECLARE_ROUND_KEY_VAR(8);
DECLARE_ROUND_KEY_VAR(9);
DECLARE_ROUND_KEY_VAR(10);
DECLARE_ROUND_KEY_VAR(11);
DECLARE_ROUND_KEY_VAR(12);
DECLARE_ROUND_KEY_VAR(13);
DECLARE_ROUND_KEY_VAR(14);
uint8x16_t ctr0 = vld1q_u8(m_counter);
uint64_t high, low;
/* Process three blocks at a time, when possible. */
if (num_blocks >= 3) {
/* Increment CTR twice. */
uint8x16_t ctr1 = IncrementCounterOptimized(ctr0);
uint8x16_t ctr2 = IncrementCounterOptimized(ctr1);
uint64_t hl_tmp;
while (num_blocks >= 3) {
/* Read blocks in. Keep them in registers for XOR later. */
const uint8x16_t block0 = vld1q_u8(src);
src += AesEncryptor256::BlockSize;
const uint8x16_t block1 = vld1q_u8(src);
src += AesEncryptor256::BlockSize;
const uint8x16_t block2 = vld1q_u8(src);
src += AesEncryptor256::BlockSize;
/* We'll be encrypting the three CTRs. */
uint8x16_t tmp0 = ctr0, tmp1 = ctr1, tmp2 = ctr2;
/* Actually do encryption, use optimized asm. */
/* Interleave CTR calculations with AES ones, to mask latencies. */
/* Note: ASM here only uses one temporary u64 instead of two, due to 30 operand limit. */
__asm__ __volatile__ (
AES_ENC_ROUND(0, 0) "mov %[high], %[ctr2].d[0]\n"
AES_ENC_ROUND(0, 1) "mov %[low], %[ctr2].d[1]\n"
AES_ENC_ROUND(0, 2) "rev %[high], %[high]\n"
AES_ENC_ROUND(1, 0) "rev %[low], %[low]\n"
AES_ENC_ROUND(1, 1) "adds %[low], %[low], 1\n"
AES_ENC_ROUND(1, 2) "cinc %[high], %[high], cs\n"
AES_ENC_ROUND(2, 0) "rev %[hl_tmp], %[high]\n"
AES_ENC_ROUND(2, 1) "mov %[ctr0].d[0], %[hl_tmp]\n"
AES_ENC_ROUND(2, 2) "rev %[hl_tmp], %[low]\n"
AES_ENC_ROUND(3, 0) "mov %[ctr0].d[1], %[hl_tmp]\n"
AES_ENC_ROUND(3, 1) "adds %[low], %[low], 1\n"
AES_ENC_ROUND(3, 2) "cinc %[high], %[high], cs\n"
AES_ENC_ROUND(4, 0) "rev %[hl_tmp], %[high]\n"
AES_ENC_ROUND(4, 1) "mov %[ctr1].d[0], %[hl_tmp]\n"
AES_ENC_ROUND(4, 2) "rev %[hl_tmp], %[low]\n"
AES_ENC_ROUND(5, 0) "mov %[ctr1].d[1], %[hl_tmp]\n"
AES_ENC_ROUND(5, 1) "adds %[low], %[low], 1\n"
AES_ENC_ROUND(5, 2) "cinc %[high], %[high], cs\n"
AES_ENC_ROUND(6, 0) "rev %[hl_tmp], %[high]\n"
AES_ENC_ROUND(6, 1) "mov %[ctr2].d[0], %[hl_tmp]\n"
AES_ENC_ROUND(6, 2) "rev %[hl_tmp], %[low]\n"
AES_ENC_ROUND(7, 0) "mov %[ctr2].d[1], %[hl_tmp]\n"
AES_ENC_ROUND(7, 1)
AES_ENC_ROUND(7, 2)
AES_ENC_ROUND(8, 0) AES_ENC_ROUND(8, 1) AES_ENC_ROUND(8, 2)
AES_ENC_ROUND(9, 0) AES_ENC_ROUND(9, 1) AES_ENC_ROUND(9, 2)
AES_ENC_ROUND(10, 0) AES_ENC_ROUND(10, 1) AES_ENC_ROUND(10, 2)
AES_ENC_ROUND(11, 0) AES_ENC_ROUND(11, 1) AES_ENC_ROUND(11, 2)
AES_ENC_ROUND(12, 0) AES_ENC_ROUND(12, 1) AES_ENC_ROUND(12, 2)
AES_ENC_SECOND_LAST_ROUND(13, 0) AES_ENC_SECOND_LAST_ROUND(13, 1) AES_ENC_SECOND_LAST_ROUND(13, 2)
AES_ENC_LAST_ROUND(14, 0) AES_ENC_LAST_ROUND(14, 1) AES_ENC_LAST_ROUND(14, 2)
: AES_ENC_DEC_OUTPUT_THREE_BLOCKS(),
AES_ENC_DEC_OUTPUT_THREE_CTRS(),
CTR_INCREMENT_OUTPUT_HIGH_LOW(),
CTR_INCREMENT_OUTPUT_HL_SINGLE_TMP()
: AES_ENC_DEC_INPUT_ROUND_KEY(0),
AES_ENC_DEC_INPUT_ROUND_KEY(1),
AES_ENC_DEC_INPUT_ROUND_KEY(2),
AES_ENC_DEC_INPUT_ROUND_KEY(3),
AES_ENC_DEC_INPUT_ROUND_KEY(4),
AES_ENC_DEC_INPUT_ROUND_KEY(5),
AES_ENC_DEC_INPUT_ROUND_KEY(6),
AES_ENC_DEC_INPUT_ROUND_KEY(7),
AES_ENC_DEC_INPUT_ROUND_KEY(8),
AES_ENC_DEC_INPUT_ROUND_KEY(9),
AES_ENC_DEC_INPUT_ROUND_KEY(10),
AES_ENC_DEC_INPUT_ROUND_KEY(11),
AES_ENC_DEC_INPUT_ROUND_KEY(12),
AES_ENC_DEC_INPUT_ROUND_KEY(13),
AES_ENC_DEC_INPUT_ROUND_KEY(14)
: "cc"
);
/* XOR blocks. */
tmp0 = veorq_u8(block0, tmp0);
tmp1 = veorq_u8(block1, tmp1);
tmp2 = veorq_u8(block2, tmp2);
/* Store to output. */
vst1q_u8(dst, tmp0);
dst += AesEncryptor256::BlockSize;
vst1q_u8(dst, tmp1);
dst += AesEncryptor256::BlockSize;
vst1q_u8(dst, tmp2);
dst += AesEncryptor256::BlockSize;
num_blocks -= 3;
}
}
while (num_blocks >= 1) {
/* Read block in, keep in register for XOR. */
const uint8x16_t block0 = vld1q_u8(src);
src += AesEncryptor256::BlockSize;
/* We'll be encrypting the CTR. */
uint8x16_t tmp0 = ctr0;
/* Actually do encryption, use optimized asm. */
/* Interleave CTR calculations with AES ones, to mask latencies. */
__asm__ __volatile__ (
AES_ENC_ROUND(0, 0) "mov %[high], %[ctr0].d[0]\n"
AES_ENC_ROUND(1, 0) "mov %[low], %[ctr0].d[1]\n"
AES_ENC_ROUND(2, 0) "rev %[high], %[high]\n"
AES_ENC_ROUND(3, 0) "rev %[low], %[low]\n"
AES_ENC_ROUND(4, 0) "adds %[low], %[low], 1\n"
AES_ENC_ROUND(5, 0) "cinc %[high], %[high], cs\n"
AES_ENC_ROUND(6, 0) "rev %[high], %[high]\n"
AES_ENC_ROUND(7, 0) "rev %[low], %[low]\n"
AES_ENC_ROUND(8, 0) "mov %[ctr0].d[0], %[high]\n"
AES_ENC_ROUND(9, 0) "mov %[ctr0].d[1], %[low]\n"
AES_ENC_ROUND(10, 0)
AES_ENC_ROUND(11, 0)
AES_ENC_ROUND(12, 0)
AES_ENC_SECOND_LAST_ROUND(13, 0)
AES_ENC_LAST_ROUND(14, 0)
: AES_ENC_DEC_OUTPUT_ONE_BLOCK(),
AES_ENC_DEC_OUTPUT_ONE_CTR(),
CTR_INCREMENT_OUTPUT_HIGH_LOW()
: AES_ENC_DEC_INPUT_ROUND_KEY(0),
AES_ENC_DEC_INPUT_ROUND_KEY(1),
AES_ENC_DEC_INPUT_ROUND_KEY(2),
AES_ENC_DEC_INPUT_ROUND_KEY(3),
AES_ENC_DEC_INPUT_ROUND_KEY(4),
AES_ENC_DEC_INPUT_ROUND_KEY(5),
AES_ENC_DEC_INPUT_ROUND_KEY(6),
AES_ENC_DEC_INPUT_ROUND_KEY(7),
AES_ENC_DEC_INPUT_ROUND_KEY(8),
AES_ENC_DEC_INPUT_ROUND_KEY(9),
AES_ENC_DEC_INPUT_ROUND_KEY(10),
AES_ENC_DEC_INPUT_ROUND_KEY(11),
AES_ENC_DEC_INPUT_ROUND_KEY(12),
AES_ENC_DEC_INPUT_ROUND_KEY(13),
AES_ENC_DEC_INPUT_ROUND_KEY(14)
: "cc"
);
/* XOR blocks. */
tmp0 = veorq_u8(block0, tmp0);
/* Store to output. */
vst1q_u8(dst, tmp0);
dst += AesEncryptor256::BlockSize;
num_blocks--;
}
vst1q_u8(m_counter, ctr0);
}
}
#else
/* TODO: Non-EL0 implementation. */
namespace ams::crypto::impl {
}
#endif
| 26,248
|
C++
|
.cpp
| 524
| 34.769084
| 118
| 0.476634
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,084
|
crypto_bignum.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/crypto/impl/crypto_bignum.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <vapours.hpp>
namespace ams::crypto::impl {
void BigNum::ImportImpl(Word *out, size_t out_size, const u8 *src, size_t src_size) {
size_t octet_ofs = src_size;
size_t word_ofs = 0;
/* Parse octets into words. */
while (word_ofs < out_size && octet_ofs > 0) {
Word w = 0;
for (size_t shift = 0; octet_ofs > 0 && shift < BITSIZEOF(Word); shift += BITSIZEOF(u8)) {
w |= static_cast<Word>(src[--octet_ofs]) << shift;
}
out[word_ofs++] = w;
}
/* Zero-fill upper words. */
while (word_ofs < out_size) {
out[word_ofs++] = 0;
}
}
void BigNum::ExportImpl(u8 *out, size_t out_size, const Word *src, size_t src_size) {
size_t octet_ofs = out_size;
/* Parse words into octets. */
for (size_t word_ofs = 0; word_ofs < src_size && octet_ofs > 0; word_ofs++) {
const Word w = src[word_ofs];
for (size_t shift = 0; octet_ofs > 0 && shift < BITSIZEOF(Word); shift += BITSIZEOF(u8)) {
out[--octet_ofs] = static_cast<u8>(w >> shift);
}
}
/* Zero-clear remaining octets. */
while (octet_ofs > 0) {
out[--octet_ofs] = 0;
}
}
size_t BigNum::GetSize() const {
if (m_num_words == 0) {
return 0;
}
static_assert(sizeof(Word) == 4);
size_t size = m_num_words * sizeof(Word);
const Word last = m_words[m_num_words - 1];
AMS_ASSERT(last != 0);
if (last >= 0x01000000u) {
return size - 0;
} else if (last >= 0x00010000u) {
return size - 1;
} else if (last >= 0x00000100u) {
return size - 2;
} else {
return size - 3;
}
}
bool BigNum::Import(const void *src, size_t src_size) {
AMS_ASSERT((src != nullptr) || (src_size != 0));
/* Ignore leading zeroes. */
const u8 *data = static_cast<const u8 *>(src);
while (src_size > 0 && *data == 0) {
++data;
--src_size;
}
/* Ensure we have space for the number. */
AMS_ASSERT(src_size <= m_max_words * sizeof(Word));
if (AMS_UNLIKELY(!(src_size <= m_max_words * sizeof(Word)))) {
return false;
}
/* Import. */
m_num_words = util::AlignUp(src_size, sizeof(Word)) / sizeof(Word);
ImportImpl(m_words, m_max_words, data, src_size);
return true;
}
void BigNum::Export(void *dst, size_t dst_size) {
AMS_ASSERT(dst_size >= this->GetSize());
ExportImpl(static_cast<u8 *>(dst), dst_size, m_words, m_num_words);
}
bool BigNum::ExpMod(void *dst, const void *src, size_t size, const BigNum &exp, u32 *work_buf, size_t work_buf_size) const {
/* Can't exponentiate with or about zero. */
if (this->IsZero() || exp.IsZero()) {
return false;
}
AMS_ASSERT(size == this->GetSize());
/* Create an allocator. */
WordAllocator allocator(work_buf, work_buf_size / sizeof(Word));
ON_SCOPE_EXIT { ClearMemory(work_buf, allocator.GetMaxUsedSize()); };
/* Create a BigNum for the signature. */
BigNum signature;
auto signature_words = allocator.Allocate(size / sizeof(Word));
if (!signature_words.IsValid()) {
return false;
}
/* Import data for the signature. */
signature.ReserveStatic(signature_words.GetBuffer(), signature_words.GetCount());
if (!signature.Import(src, size)) {
return false;
}
/* Perform the exponentiation. */
if (!ExpMod(signature.m_words, signature.m_words, exp.m_words, exp.m_num_words, m_words, m_num_words, std::addressof(allocator))) {
return false;
}
/* We succeeded, so export. */
signature.UpdateCount();
signature.Export(dst, size);
return true;
}
void BigNum::ClearToZero() {
std::memset(m_words, 0, m_num_words * sizeof(Word));
}
void BigNum::UpdateCount() {
m_num_words = CountWords(m_words, m_max_words);
}
}
| 4,872
|
C++
|
.cpp
| 123
| 31.178862
| 139
| 0.566561
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,085
|
crypto_xts_mode_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/crypto/impl/crypto_xts_mode_impl.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <vapours.hpp>
namespace ams::crypto::impl {
namespace {
/* TODO: Support non-Nintendo Endianness */
void MultiplyTweakGeneric(u64 *tweak) {
const u64 carry = tweak[1] & (static_cast<u64>(1) << (BITSIZEOF(u64) - 1));
tweak[1] = ((tweak[1] << 1) | (tweak[0] >> (BITSIZEOF(u64) - 1)));
tweak[0] = (tweak[0] << 1);
if (carry) {
tweak[0] ^= static_cast<u64>(0x87);
}
}
}
void XtsModeImpl::ProcessBlock(u8 *dst, const u8 *src) {
u8 tmp[BlockSize];
/* Xor. */
for (size_t i = 0; i < BlockSize; i++) {
tmp[i] = m_tweak[i] ^ src[i];
}
/* Crypt */
m_cipher_func(tmp, tmp, m_cipher_ctx);
/* Xor. */
for (size_t i = 0; i < BlockSize; i++) {
dst[i] = m_tweak[i] ^ tmp[i];
}
MultiplyTweakGeneric(reinterpret_cast<u64 *>(m_tweak));
}
size_t XtsModeImpl::FinalizeEncryption(void *dst, size_t dst_size) {
AMS_ASSERT(m_state == State_Processing);
AMS_UNUSED(dst_size);
u8 *dst_u8 = static_cast<u8 *>(dst);
size_t processed = 0;
if (m_num_buffered == 0) {
this->ProcessBlock(dst_u8, m_last_block);
processed = BlockSize;
} else {
this->ProcessBlock(m_last_block, m_last_block);
std::memcpy(m_buffer + m_num_buffered, m_last_block + m_num_buffered, BlockSize - m_num_buffered);
this->ProcessBlock(dst_u8, m_buffer);
std::memcpy(dst_u8 + BlockSize, m_last_block, m_num_buffered);
processed = BlockSize + m_num_buffered;
}
m_state = State_Done;
return processed;
}
size_t XtsModeImpl::FinalizeDecryption(void *dst, size_t dst_size) {
AMS_ASSERT(m_state == State_Processing);
AMS_UNUSED(dst_size);
u8 *dst_u8 = static_cast<u8 *>(dst);
size_t processed = 0;
if (m_num_buffered == 0) {
this->ProcessBlock(dst_u8, m_last_block);
processed = BlockSize;
} else {
u8 tmp_tweak[BlockSize];
std::memcpy(tmp_tweak, m_tweak, BlockSize);
MultiplyTweakGeneric(reinterpret_cast<u64 *>(m_tweak));
this->ProcessBlock(m_last_block, m_last_block);
std::memcpy(m_buffer + m_num_buffered, m_last_block + m_num_buffered, BlockSize - m_num_buffered);
std::memcpy(m_tweak, tmp_tweak, BlockSize);
this->ProcessBlock(dst_u8, m_buffer);
std::memcpy(dst_u8 + BlockSize, m_last_block, m_num_buffered);
processed = BlockSize + m_num_buffered;
}
m_state = State_Done;
return processed;
}
size_t XtsModeImpl::ProcessPartialData(u8 *dst, const u8 *src, size_t size) {
size_t processed = 0;
std::memcpy(m_buffer + m_num_buffered, src, size);
m_num_buffered += size;
if (m_num_buffered == BlockSize) {
if (m_state == State_Processing) {
this->ProcessBlock(dst, m_last_block);
processed += BlockSize;
}
std::memcpy(m_last_block, m_buffer, BlockSize);
m_num_buffered = 0;
m_state = State_Processing;
}
return processed;
}
size_t XtsModeImpl::ProcessRemainingData(u8 *dst, const u8 *src, size_t size) {
AMS_UNUSED(dst);
std::memcpy(m_buffer, src, size);
m_num_buffered = size;
return 0;
}
}
| 4,200
|
C++
|
.cpp
| 104
| 31.326923
| 110
| 0.578402
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,086
|
crypto_ctr_mode_impl.arch.x64.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/crypto/impl/crypto_ctr_mode_impl.arch.x64.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <vapours.hpp>
#include "crypto_aes_impl.arch.x64.hpp"
namespace ams::crypto::impl {
template<> void CtrModeImpl<AesEncryptor128>::ProcessBlocks(u8 *dst, const u8 *src, size_t num_blocks) {
/* Check pre-conditions. */
AMS_ASSERT(src != nullptr);
AMS_ASSERT(dst != nullptr);
/* If we have aes-ni, use an optimized impl. */
if (IsAesNiAvailable()) {
/* Load all keys into sse2 registers. */
const u8 *raw_round_keys = m_block_cipher->GetRoundKey();
const __m128i round_keys[AesEncryptor128::RoundKeySize / BlockSize] = {
_mm_loadu_si128(reinterpret_cast<const __m128i *>(raw_round_keys + BlockSize * 0)),
_mm_loadu_si128(reinterpret_cast<const __m128i *>(raw_round_keys + BlockSize * 1)),
_mm_loadu_si128(reinterpret_cast<const __m128i *>(raw_round_keys + BlockSize * 2)),
_mm_loadu_si128(reinterpret_cast<const __m128i *>(raw_round_keys + BlockSize * 3)),
_mm_loadu_si128(reinterpret_cast<const __m128i *>(raw_round_keys + BlockSize * 4)),
_mm_loadu_si128(reinterpret_cast<const __m128i *>(raw_round_keys + BlockSize * 5)),
_mm_loadu_si128(reinterpret_cast<const __m128i *>(raw_round_keys + BlockSize * 6)),
_mm_loadu_si128(reinterpret_cast<const __m128i *>(raw_round_keys + BlockSize * 7)),
_mm_loadu_si128(reinterpret_cast<const __m128i *>(raw_round_keys + BlockSize * 8)),
_mm_loadu_si128(reinterpret_cast<const __m128i *>(raw_round_keys + BlockSize * 9)),
_mm_loadu_si128(reinterpret_cast<const __m128i *>(raw_round_keys + BlockSize * 10)),
};
static_assert(AesEncryptor128::RoundKeySize / BlockSize == 11);
/* Declare constant for counter math. */
const __m128i One = _mm_setr_epi8(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1);
/* Process eight blocks at a time, while we can. */
constexpr const auto UnrolledBlockCount = 8;
constexpr const auto CounterThreshold = static_cast<u8>(0x100 - UnrolledBlockCount);
/* Load the counter. */
auto counter = _mm_loadu_si128(reinterpret_cast<const __m128i *>(m_counter));
size_t cur_blocks;
for (cur_blocks = 0; cur_blocks + UnrolledBlockCount <= num_blocks; cur_blocks += UnrolledBlockCount) {
__m128i b0;
__m128i b1;
__m128i b2;
__m128i b3;
__m128i b4;
__m128i b5;
__m128i b6;
__m128i b7;
__m128i key = round_keys[0];
/* Get the last byte of the block. */
static_assert(util::IsLittleEndian());
const u8 counter_val = _mm_extract_epi16(counter, 7) >> BITSIZEOF(u8);
/* Do initial encryption of each block. */
if (CounterThreshold <= counter_val) {
/* We'll overwrap, so take slow path for counter. */
_mm_storeu_si128(reinterpret_cast<__m128i *>(m_counter), counter);
b0 = _mm_xor_si128(_mm_loadu_si128(reinterpret_cast<const __m128i *>(m_counter)), key);
this->IncrementCounter();
b1 = _mm_xor_si128(_mm_loadu_si128(reinterpret_cast<const __m128i *>(m_counter)), key);
this->IncrementCounter();
b2 = _mm_xor_si128(_mm_loadu_si128(reinterpret_cast<const __m128i *>(m_counter)), key);
this->IncrementCounter();
b3 = _mm_xor_si128(_mm_loadu_si128(reinterpret_cast<const __m128i *>(m_counter)), key);
this->IncrementCounter();
b4 = _mm_xor_si128(_mm_loadu_si128(reinterpret_cast<const __m128i *>(m_counter)), key);
this->IncrementCounter();
b5 = _mm_xor_si128(_mm_loadu_si128(reinterpret_cast<const __m128i *>(m_counter)), key);
this->IncrementCounter();
b6 = _mm_xor_si128(_mm_loadu_si128(reinterpret_cast<const __m128i *>(m_counter)), key);
this->IncrementCounter();
b7 = _mm_xor_si128(_mm_loadu_si128(reinterpret_cast<const __m128i *>(m_counter)), key);
this->IncrementCounter();
counter = _mm_loadu_si128(reinterpret_cast<const __m128i *>(m_counter));
} else {
/* We can take the fast path for the counter. */
b0 = _mm_xor_si128(counter, key);
counter = _mm_add_epi64(counter, One);
b1 = _mm_xor_si128(counter, key);
counter = _mm_add_epi64(counter, One);
b2 = _mm_xor_si128(counter, key);
counter = _mm_add_epi64(counter, One);
b3 = _mm_xor_si128(counter, key);
counter = _mm_add_epi64(counter, One);
b4 = _mm_xor_si128(counter, key);
counter = _mm_add_epi64(counter, One);
b5 = _mm_xor_si128(counter, key);
counter = _mm_add_epi64(counter, One);
b6 = _mm_xor_si128(counter, key);
counter = _mm_add_epi64(counter, One);
b7 = _mm_xor_si128(counter, key);
counter = _mm_add_epi64(counter, One);
}
/* Do encryption for all rounds. */
key = round_keys[1];
b0 = _mm_aesenc_si128(b0, key);
b1 = _mm_aesenc_si128(b1, key);
b2 = _mm_aesenc_si128(b2, key);
b3 = _mm_aesenc_si128(b3, key);
b4 = _mm_aesenc_si128(b4, key);
b5 = _mm_aesenc_si128(b5, key);
b6 = _mm_aesenc_si128(b6, key);
b7 = _mm_aesenc_si128(b7, key);
key = round_keys[2];
b0 = _mm_aesenc_si128(b0, key);
b1 = _mm_aesenc_si128(b1, key);
b2 = _mm_aesenc_si128(b2, key);
b3 = _mm_aesenc_si128(b3, key);
b4 = _mm_aesenc_si128(b4, key);
b5 = _mm_aesenc_si128(b5, key);
b6 = _mm_aesenc_si128(b6, key);
b7 = _mm_aesenc_si128(b7, key);
key = round_keys[3];
b0 = _mm_aesenc_si128(b0, key);
b1 = _mm_aesenc_si128(b1, key);
b2 = _mm_aesenc_si128(b2, key);
b3 = _mm_aesenc_si128(b3, key);
b4 = _mm_aesenc_si128(b4, key);
b5 = _mm_aesenc_si128(b5, key);
b6 = _mm_aesenc_si128(b6, key);
b7 = _mm_aesenc_si128(b7, key);
key = round_keys[4];
b0 = _mm_aesenc_si128(b0, key);
b1 = _mm_aesenc_si128(b1, key);
b2 = _mm_aesenc_si128(b2, key);
b3 = _mm_aesenc_si128(b3, key);
b4 = _mm_aesenc_si128(b4, key);
b5 = _mm_aesenc_si128(b5, key);
b6 = _mm_aesenc_si128(b6, key);
b7 = _mm_aesenc_si128(b7, key);
key = round_keys[5];
b0 = _mm_aesenc_si128(b0, key);
b1 = _mm_aesenc_si128(b1, key);
b2 = _mm_aesenc_si128(b2, key);
b3 = _mm_aesenc_si128(b3, key);
b4 = _mm_aesenc_si128(b4, key);
b5 = _mm_aesenc_si128(b5, key);
b6 = _mm_aesenc_si128(b6, key);
b7 = _mm_aesenc_si128(b7, key);
key = round_keys[6];
b0 = _mm_aesenc_si128(b0, key);
b1 = _mm_aesenc_si128(b1, key);
b2 = _mm_aesenc_si128(b2, key);
b3 = _mm_aesenc_si128(b3, key);
b4 = _mm_aesenc_si128(b4, key);
b5 = _mm_aesenc_si128(b5, key);
b6 = _mm_aesenc_si128(b6, key);
b7 = _mm_aesenc_si128(b7, key);
key = round_keys[7];
b0 = _mm_aesenc_si128(b0, key);
b1 = _mm_aesenc_si128(b1, key);
b2 = _mm_aesenc_si128(b2, key);
b3 = _mm_aesenc_si128(b3, key);
b4 = _mm_aesenc_si128(b4, key);
b5 = _mm_aesenc_si128(b5, key);
b6 = _mm_aesenc_si128(b6, key);
b7 = _mm_aesenc_si128(b7, key);
key = round_keys[8];
b0 = _mm_aesenc_si128(b0, key);
b1 = _mm_aesenc_si128(b1, key);
b2 = _mm_aesenc_si128(b2, key);
b3 = _mm_aesenc_si128(b3, key);
b4 = _mm_aesenc_si128(b4, key);
b5 = _mm_aesenc_si128(b5, key);
b6 = _mm_aesenc_si128(b6, key);
b7 = _mm_aesenc_si128(b7, key);
key = round_keys[9];
b0 = _mm_aesenc_si128(b0, key);
b1 = _mm_aesenc_si128(b1, key);
b2 = _mm_aesenc_si128(b2, key);
b3 = _mm_aesenc_si128(b3, key);
b4 = _mm_aesenc_si128(b4, key);
b5 = _mm_aesenc_si128(b5, key);
b6 = _mm_aesenc_si128(b6, key);
b7 = _mm_aesenc_si128(b7, key);
key = round_keys[10];
b0 = _mm_aesenclast_si128(b0, key);
b1 = _mm_aesenclast_si128(b1, key);
b2 = _mm_aesenclast_si128(b2, key);
b3 = _mm_aesenclast_si128(b3, key);
b4 = _mm_aesenclast_si128(b4, key);
b5 = _mm_aesenclast_si128(b5, key);
b6 = _mm_aesenclast_si128(b6, key);
b7 = _mm_aesenclast_si128(b7, key);
/* Write the blocks. */
_mm_storeu_si128(reinterpret_cast<__m128i *>(dst + BlockSize * 0), _mm_xor_si128(_mm_loadu_si128(reinterpret_cast<const __m128i *>(src + BlockSize * 0)), b0));
_mm_storeu_si128(reinterpret_cast<__m128i *>(dst + BlockSize * 1), _mm_xor_si128(_mm_loadu_si128(reinterpret_cast<const __m128i *>(src + BlockSize * 1)), b1));
_mm_storeu_si128(reinterpret_cast<__m128i *>(dst + BlockSize * 2), _mm_xor_si128(_mm_loadu_si128(reinterpret_cast<const __m128i *>(src + BlockSize * 2)), b2));
_mm_storeu_si128(reinterpret_cast<__m128i *>(dst + BlockSize * 3), _mm_xor_si128(_mm_loadu_si128(reinterpret_cast<const __m128i *>(src + BlockSize * 3)), b3));
_mm_storeu_si128(reinterpret_cast<__m128i *>(dst + BlockSize * 4), _mm_xor_si128(_mm_loadu_si128(reinterpret_cast<const __m128i *>(src + BlockSize * 4)), b4));
_mm_storeu_si128(reinterpret_cast<__m128i *>(dst + BlockSize * 5), _mm_xor_si128(_mm_loadu_si128(reinterpret_cast<const __m128i *>(src + BlockSize * 5)), b5));
_mm_storeu_si128(reinterpret_cast<__m128i *>(dst + BlockSize * 6), _mm_xor_si128(_mm_loadu_si128(reinterpret_cast<const __m128i *>(src + BlockSize * 6)), b6));
_mm_storeu_si128(reinterpret_cast<__m128i *>(dst + BlockSize * 7), _mm_xor_si128(_mm_loadu_si128(reinterpret_cast<const __m128i *>(src + BlockSize * 7)), b7));
src += BlockSize * UnrolledBlockCount;
dst += BlockSize * UnrolledBlockCount;
}
/* Store the updated counter. */
_mm_storeu_si128(reinterpret_cast<__m128i *>(m_counter), counter);
/* Process blocks one at a time. */
for (/* ... */; cur_blocks < num_blocks; ++cur_blocks) {
/* Load current counter. */
__m128i b = _mm_loadu_si128(reinterpret_cast<const __m128i *>(m_counter));
/* Do aes rounds. */
b = _mm_xor_si128(b, round_keys[0]);
b = _mm_aesenc_si128(b, round_keys[1]);
b = _mm_aesenc_si128(b, round_keys[2]);
b = _mm_aesenc_si128(b, round_keys[3]);
b = _mm_aesenc_si128(b, round_keys[4]);
b = _mm_aesenc_si128(b, round_keys[5]);
b = _mm_aesenc_si128(b, round_keys[6]);
b = _mm_aesenc_si128(b, round_keys[7]);
b = _mm_aesenc_si128(b, round_keys[8]);
b = _mm_aesenc_si128(b, round_keys[9]);
b = _mm_aesenclast_si128(b, round_keys[10]);
/* Write the block. */
_mm_storeu_si128(reinterpret_cast<__m128i *>(dst), _mm_xor_si128(_mm_loadu_si128(reinterpret_cast<const __m128i *>(src)), b));
/* Advance. */
src += BlockSize;
dst += BlockSize;
this->IncrementCounter();
}
} else {
/* Fall back to the default implementation. */
while (num_blocks--) {
this->ProcessBlock(dst, src, BlockSize);
dst += BlockSize;
src += BlockSize;
}
}
}
}
| 13,698
|
C++
|
.cpp
| 239
| 41.518828
| 175
| 0.507931
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,087
|
crypto_sha3_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/crypto/impl/crypto_sha3_impl.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <vapours.hpp>
namespace ams::crypto::impl {
namespace {
constexpr auto NumRounds = 24;
constexpr const u64 IotaRoundConstant[NumRounds] = {
UINT64_C(0x0000000000000001), UINT64_C(0x0000000000008082),
UINT64_C(0x800000000000808A), UINT64_C(0x8000000080008000),
UINT64_C(0x000000000000808B), UINT64_C(0x0000000080000001),
UINT64_C(0x8000000080008081), UINT64_C(0x8000000000008009),
UINT64_C(0x000000000000008A), UINT64_C(0x0000000000000088),
UINT64_C(0x0000000080008009), UINT64_C(0x000000008000000A),
UINT64_C(0x000000008000808B), UINT64_C(0x800000000000008B),
UINT64_C(0x8000000000008089), UINT64_C(0x8000000000008003),
UINT64_C(0x8000000000008002), UINT64_C(0x8000000000000080),
UINT64_C(0x000000000000800A), UINT64_C(0x800000008000000A),
UINT64_C(0x8000000080008081), UINT64_C(0x8000000000008080),
UINT64_C(0x0000000080000001), UINT64_C(0x8000000080008008)
};
constexpr const int RhoShiftBit[NumRounds] = {
1, 3, 6, 10, 15, 21, 28, 36,
45, 55, 2, 14, 27, 41, 56, 8,
25, 43, 62, 18, 39, 61, 20, 44
};
constexpr const int RhoNextIndex[NumRounds] = {
10, 7, 11, 17, 18, 3, 5, 16,
8, 21, 24, 4, 15, 23, 19, 13,
12, 2, 20, 14, 22, 9, 6, 1
};
}
template<size_t HashSize>
void Sha3Impl<HashSize>::Initialize() {
/* Clear internal state. */
std::memset(m_internal_state, 0, sizeof(m_internal_state));
/* Reset buffered bytes. */
m_buffered_bytes = 0;
/* Set state. */
m_state = State_Initialized;
}
template<size_t HashSize>
void Sha3Impl<HashSize>::Update(const void *data, size_t size) {
/* Verify we're in a state to update. */
AMS_ASSERT(m_state == State_Initialized);
/* Process we have anything buffered. */
const u8 *data8 = static_cast<const u8 *>(data);
size_t remaining = size;
if (m_buffered_bytes > 0) {
/* Determine how much we can copy. */
const size_t copy_size = std::min(BlockSize - m_buffered_bytes, remaining);
/* Mix the bytes into our state. */
u8 *dst8 = reinterpret_cast<u8 *>(m_internal_state) + m_buffered_bytes;
for (size_t i = 0; i < copy_size; ++i) {
dst8[i] ^= data8[i];
}
/* Advance. */
data8 += copy_size;
remaining -= copy_size;
m_buffered_bytes += copy_size;
/* Process a block, if we filled one. */
if (m_buffered_bytes == BlockSize) {
this->ProcessBlock();
m_buffered_bytes = 0;
}
}
/* Process blocks, if we have any. */
while (remaining >= BlockSize) {
/* Mix the bytes into our state. */
u8 *dst8 = reinterpret_cast<u8 *>(m_internal_state);
for (size_t i = 0; i < BlockSize; ++i) {
dst8[i] ^= data8[i];
}
this->ProcessBlock();
data8 += BlockSize;
remaining -= BlockSize;
}
/* Copy any leftover data to our buffer. */
if (remaining > 0) {
u8 *dst8 = reinterpret_cast<u8 *>(m_internal_state);
for (size_t i = 0; i < remaining; ++i) {
dst8[i] ^= data8[i];
}
m_buffered_bytes = remaining;
}
}
template<size_t HashSize>
void Sha3Impl<HashSize>::GetHash(void *dst, size_t size) {
/* Verify we're in a state to get hash. */
AMS_ASSERT(m_state == State_Initialized || m_state == State_Done);
AMS_ASSERT(size >= HashSize);
AMS_UNUSED(size);
/* If we need to, process the last block. */
if (m_state == State_Initialized) {
this->ProcessLastBlock();
m_state = State_Done;
}
/* Copy the output hash. */
std::memcpy(dst, m_internal_state, HashSize);
}
template<size_t HashSize>
void Sha3Impl<HashSize>::InitializeWithContext(const Sha3Context *context) {
/* Check the context is for the right hash size. */
AMS_ASSERT(context->hash_size == HashSize);
/* Set buffered bytes. */
m_buffered_bytes = context->buffered_bytes;
/* Copy state in from the context. */
std::memcpy(m_internal_state, context->internal_state, sizeof(m_internal_state));
/* Reset other fields. */
m_state = State_Initialized;
}
template<size_t HashSize>
void Sha3Impl<HashSize>::GetContext(Sha3Context *context) const {
/* Check our state. */
AMS_ASSERT(m_state == State_Initialized);
/* Set the output hash size. */
context->hash_size = HashSize;
/* Set buffered bytes. */
context->buffered_bytes = m_buffered_bytes;
/* Copy out the context. */
std::memcpy(context->internal_state, m_internal_state, sizeof(context->internal_state));
}
template<size_t HashSize>
void Sha3Impl<HashSize>::ProcessBlock() {
/* Ensure correct endianness. */
if constexpr (util::IsBigEndian()) {
for (size_t i = 0; i < util::size(m_internal_state); ++i) {
m_internal_state[i] = util::LoadLittleEndian<u64>(m_internal_state + i);
}
}
/* Perform all rounds. */
uint64_t tmp, C[5];
for (auto round = 0; round < NumRounds; ++round) {
/* Handle theta. */
for (size_t i = 0; i < 5; ++i) {
C[i] = m_internal_state[i] ^ m_internal_state[i + 5] ^ m_internal_state[i + 10] ^ m_internal_state[i + 15] ^ m_internal_state[i + 20];
}
for (size_t i = 0; i < 5; ++i) {
tmp = C[(i + 4) % 5] ^ util::RotateLeft<u64>(C[(i + 1) % 5], 1);
for (size_t j = 0; j < 5; ++j) {
m_internal_state[5 * j + i] ^= tmp;
}
}
/* Handle rho/pi. */
tmp = m_internal_state[1];
for (size_t i = 0; i < NumRounds; ++i) {
const auto rho_next_idx = RhoNextIndex[i];
C[0] = m_internal_state[rho_next_idx];
m_internal_state[rho_next_idx] = util::RotateLeft<u64>(tmp, RhoShiftBit[i]);
tmp = C[0];
}
/* Handle chi. */
for (size_t i = 0; i < 5; ++i) {
for (size_t j = 0; j < 5; ++j) {
C[j] = m_internal_state[5 * i + j];
}
for (size_t j = 0; j < 5; ++j) {
m_internal_state[5 * i + j] ^= (~C[(j + 1) % 5]) & C[(j + 2) % 5];
}
}
/* Handle iota. */
m_internal_state[0] ^= IotaRoundConstant[round];
}
/* Ensure correct endianness. */
if constexpr (util::IsBigEndian()) {
for (size_t i = 0; i < util::size(m_internal_state); ++i) {
util::StoreLittleEndian<u64>(m_internal_state + i, m_internal_state[i]);
}
}
}
template<size_t HashSize>
void Sha3Impl<HashSize>::ProcessLastBlock() {
/* Mix final bits (011) into our state. */
reinterpret_cast<u8 *>(m_internal_state)[m_buffered_bytes] ^= 0b110;
/* Mix in the high bit of the last word in our block. */
constexpr u64 FinalMask = UINT64_C(0x8000000000000000);
m_internal_state[(BlockSize / sizeof(u64)) - 1] ^= FinalMask;
/* Process the last block. */
this->ProcessBlock();
}
/* Explicitly instantiate the supported hash sizes. */
template class Sha3Impl<224 / BITSIZEOF(u8)>;
template class Sha3Impl<256 / BITSIZEOF(u8)>;
template class Sha3Impl<384 / BITSIZEOF(u8)>;
template class Sha3Impl<512 / BITSIZEOF(u8)>;
}
| 8,665
|
C++
|
.cpp
| 198
| 33.560606
| 150
| 0.555252
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,088
|
crypto_cbc_mac_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/crypto/impl/crypto_cbc_mac_impl.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <vapours.hpp>
namespace ams::crypto::impl {
void CbcMacImpl::ProcessBlock(const void *data) {
/* Procses the block. */
const u8 *data8 = static_cast<const u8 *>(data);
u8 block[BlockSize];
for (size_t i = 0; i < BlockSize; ++i) {
block[i] = data8[i] ^ m_mac[i];
}
m_cipher_function(m_mac, block, m_cipher_context);
}
void CbcMacImpl::ProcessPartialData(const void *data, size_t size) {
/* Copy in the data. */
std::memcpy(m_buffer + m_buffered_bytes, data, size);
m_buffered_bytes += size;
}
void CbcMacImpl::ProcessRemainingData(const void *data, size_t size) {
/* If we have a block remaining, process it. */
if (m_buffered_bytes == BlockSize) {
this->ProcessBlock(m_buffer);
m_buffered_bytes = 0;
}
/* Copy the remaining data. */
std::memcpy(m_buffer, data, size);
m_buffered_bytes = size;
}
void CbcMacImpl::GetMac(void *mac, size_t mac_size) {
/* Check pre-conditions. */
AMS_ASSERT(m_state == State_Initialized || m_state == State_Done);
AMS_ASSERT(mac_size >= BlockSize);
AMS_UNUSED(mac_size);
/* Ensure we're done. */
if (m_state == State_Initialized) {
if (m_buffered_bytes == BlockSize) {
this->ProcessBlock(m_buffer);
m_buffered_bytes = 0;
}
m_state = State_Done;
}
/* Copy out the mac. */
std::memcpy(mac, m_mac, sizeof(m_mac));
}
void CbcMacImpl::MaskBufferedData(const void *data, size_t size) {
/* Check pre-conditions. */
AMS_ASSERT(m_buffered_bytes == BlockSize);
AMS_ASSERT(size == BlockSize);
AMS_UNUSED(size);
/* Mask the data. */
for (size_t i = 0; i < BlockSize; ++i) {
m_buffer[i] ^= static_cast<const u8 *>(data)[i];
}
}
}
| 2,608
|
C++
|
.cpp
| 68
| 31.014706
| 76
| 0.601899
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,089
|
crypto_sha1_impl.arch.generic.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/crypto/impl/crypto_sha1_impl.arch.generic.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <vapours.hpp>
namespace ams::crypto::impl {
namespace {
constexpr const u32 RoundConstants[4] = {
0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6
};
constexpr ALWAYS_INLINE u32 Choose(u32 x, u32 y, u32 z) {
return (x & y) ^ ((~x) & z);
}
constexpr ALWAYS_INLINE u32 Majority(u32 x, u32 y, u32 z) {
return (x & y) ^ (x & z) ^ (y & z);
}
constexpr ALWAYS_INLINE u32 Parity(u32 x, u32 y, u32 z) {
return x ^ y ^ z;
}
}
void Sha1Impl::Initialize() {
/* Reset buffered bytes/bits. */
m_buffered_bytes = 0;
m_bits_consumed = 0;
/* Set intermediate hash. */
m_intermediate_hash[0] = 0x67452301;
m_intermediate_hash[1] = 0xEFCDAB89;
m_intermediate_hash[2] = 0x98BADCFE;
m_intermediate_hash[3] = 0x10325476;
m_intermediate_hash[4] = 0xC3D2E1F0;
/* Set state. */
m_state = State_Initialized;
}
void Sha1Impl::Update(const void *data, size_t size) {
/* Verify we're in a state to update. */
AMS_ASSERT(m_state == State_Initialized);
/* Advance our input bit count. */
m_bits_consumed += BITSIZEOF(u8) * (((m_buffered_bytes + size) / BlockSize) * BlockSize);
/* Process anything we have buffered. */
const u8 *data8 = static_cast<const u8 *>(data);
size_t remaining = size;
if (m_buffered_bytes > 0) {
const size_t copy_size = std::min(BlockSize - m_buffered_bytes, remaining);
std::memcpy(m_buffer + m_buffered_bytes, data8, copy_size);
data8 += copy_size;
remaining -= copy_size;
m_buffered_bytes += copy_size;
/* Process a block, if we filled one. */
if (m_buffered_bytes == BlockSize) {
this->ProcessBlock(m_buffer);
m_buffered_bytes = 0;
}
}
/* Process blocks, while we have any. */
while (remaining >= BlockSize) {
this->ProcessBlock(data8);
data8 += BlockSize;
remaining -= BlockSize;
}
/* Copy any leftover data to our buffer. */
if (remaining > 0) {
m_buffered_bytes = remaining;
std::memcpy(m_buffer, data8, remaining);
}
}
void Sha1Impl::GetHash(void *dst, size_t size) {
/* Verify we're in a state to get hash. */
AMS_ASSERT(m_state == State_Initialized || m_state == State_Done);
AMS_ASSERT(size >= HashSize);
AMS_UNUSED(size);
/* If we need to, process the last block. */
if (m_state == State_Initialized) {
this->ProcessLastBlock();
m_state = State_Done;
}
/* Copy the output hash. */
if constexpr (util::IsLittleEndian()) {
static_assert(HashSize % sizeof(u32) == 0);
u32 *dst_32 = static_cast<u32 *>(dst);
for (size_t i = 0; i < HashSize / sizeof(u32); ++i) {
dst_32[i] = util::LoadBigEndian<u32>(m_intermediate_hash + i);
}
} else {
std::memcpy(dst, m_intermediate_hash, HashSize);
}
}
void Sha1Impl::ProcessBlock(const void *data) {
/* Load work variables. */
u32 a = m_intermediate_hash[0];
u32 b = m_intermediate_hash[1];
u32 c = m_intermediate_hash[2];
u32 d = m_intermediate_hash[3];
u32 e = m_intermediate_hash[4];
u32 tmp;
size_t i;
/* Copy the input. */
u32 w[80];
if constexpr (util::IsLittleEndian()) {
static_assert(BlockSize % sizeof(u32) == 0);
const u32 *src_32 = static_cast<const u32 *>(data);
for (size_t i = 0; i < BlockSize / sizeof(u32); ++i) {
w[i] = util::LoadBigEndian<u32>(src_32 + i);
}
} else {
std::memcpy(w, data, BlockSize);
}
/* Initialize the rest of w. */
for (i = BlockSize / sizeof(u32); i < util::size(w); ++i) {
const u32 *prev = w + (i - BlockSize / sizeof(u32));
w[i] = util::RotateLeft<u32>(prev[0] ^ prev[2] ^ prev[8] ^ prev[13], 1);
}
/* Perform rounds. */
for (i = 0; i < 20; ++i) {
tmp = util::RotateLeft<u32>(a, 5) + Choose(b, c, d) + e + w[i] + RoundConstants[0];
e = d;
d = c;
c = util::RotateLeft<u32>(b, 30);
b = a;
a = tmp;
}
for (/* ... */; i < 40; ++i) {
tmp = util::RotateLeft<u32>(a, 5) + Parity(b, c, d) + e + w[i] + RoundConstants[1];
e = d;
d = c;
c = util::RotateLeft<u32>(b, 30);
b = a;
a = tmp;
}
for (/* ... */; i < 60; ++i) {
tmp = util::RotateLeft<u32>(a, 5) + Majority(b, c, d) + e + w[i] + RoundConstants[2];
e = d;
d = c;
c = util::RotateLeft<u32>(b, 30);
b = a;
a = tmp;
}
for (/* ... */; i < 80; ++i) {
tmp = util::RotateLeft<u32>(a, 5) + Parity(b, c, d) + e + w[i] + RoundConstants[3];
e = d;
d = c;
c = util::RotateLeft<u32>(b, 30);
b = a;
a = tmp;
}
/* Update intermediate hash. */
m_intermediate_hash[0] += a;
m_intermediate_hash[1] += b;
m_intermediate_hash[2] += c;
m_intermediate_hash[3] += d;
m_intermediate_hash[4] += e;
}
void Sha1Impl::ProcessLastBlock() {
/* Setup the final block. */
constexpr const auto BlockSizeWithoutSizeField = BlockSize - sizeof(u64);
/* Increment our bits consumed. */
m_bits_consumed += BITSIZEOF(u8) * m_buffered_bytes;
/* Add 0x80 terminator. */
m_buffer[m_buffered_bytes++] = 0x80;
/* If we can process the size field directly, do so, otherwise set up to process it. */
if (m_buffered_bytes <= BlockSizeWithoutSizeField) {
/* Clear up to size field. */
std::memset(m_buffer + m_buffered_bytes, 0, BlockSizeWithoutSizeField - m_buffered_bytes);
} else {
/* Consume full block */
std::memset(m_buffer + m_buffered_bytes, 0, BlockSize - m_buffered_bytes);
this->ProcessBlock(m_buffer);
/* Clear up to size field. */
std::memset(m_buffer, 0, BlockSizeWithoutSizeField);
}
/* Store the size field. */
util::StoreBigEndian<u64>(reinterpret_cast<u64 *>(m_buffer + BlockSizeWithoutSizeField), m_bits_consumed);
/* Process the final block. */
this->ProcessBlock(m_buffer);
}
}
| 7,463
|
C++
|
.cpp
| 186
| 30.365591
| 114
| 0.532606
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,090
|
crypto_aes_impl.arch.x64.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/crypto/impl/crypto_aes_impl.arch.x64.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <vapours.hpp>
#include "crypto_aes_impl.arch.x64.hpp"
namespace ams::crypto::impl {
namespace {
constexpr bool IsSupportedKeySize(size_t size) {
return size == 16 || size == 24 || size == 32;
}
constexpr int WordsPerBlock = AesImpl<16>::BlockSize / sizeof(u32);
static_assert(AesImpl<16>::BlockSize == AesImpl<24>::BlockSize);
static_assert(AesImpl<16>::BlockSize == AesImpl<32>::BlockSize);
bool GetAesNiAvailabilityImpl() {
/* Call cpu id. */
int a = 0, b = 0, c = 0, d = 0;
__asm__ __volatile__("cpuid" : "=a"(a), "=b"(b), "=c"(c), "=d"(d) : "0"(1) : "memory");
/* Check for AES-NI and SSE2. */
return (c & (1 << 25)) && (d & (1 << 26));
}
static_assert(util::IsLittleEndian());
constexpr const u8 RoundKeyRcon0[] = {
0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36, 0x6C, 0xD8, 0xAB, 0x4D, 0x9A, 0x2F,
0x5E, 0xBC, 0x63, 0xC6, 0x97, 0x35, 0x6A, 0xD4, 0xB3, 0x7D, 0xFA, 0xEF, 0xC5, 0x91,
};
constexpr const u8 SubBytesTable[0x100] = {
0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,
0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,
0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,
0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,
0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,
0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,
0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,
0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2,
0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,
0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,
0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,
0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,
0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A,
0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,
0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,
0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16,
};
constexpr const u8 InvSubBytesTable[0x100] = {
0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB,
0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB,
0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E,
0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25,
0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92,
0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84,
0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06,
0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B,
0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73,
0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E,
0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B,
0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4,
0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F,
0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF,
0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61,
0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D,
};
constexpr bool IsSubBytesTableValid() {
for (size_t i = 0; i < 0x100; ++i) {
if (SubBytesTable[InvSubBytesTable[i]] != i) {
return false;
}
if (InvSubBytesTable[SubBytesTable[i]] != i) {
return false;
}
}
return true;
}
static_assert(IsSubBytesTableValid());
constexpr const u32 EncryptTable[0x100] = {
0xA56363C6, 0x847C7CF8, 0x997777EE, 0x8D7B7BF6, 0x0DF2F2FF, 0xBD6B6BD6, 0xB16F6FDE, 0x54C5C591,
0x50303060, 0x03010102, 0xA96767CE, 0x7D2B2B56, 0x19FEFEE7, 0x62D7D7B5, 0xE6ABAB4D, 0x9A7676EC,
0x45CACA8F, 0x9D82821F, 0x40C9C989, 0x877D7DFA, 0x15FAFAEF, 0xEB5959B2, 0xC947478E, 0x0BF0F0FB,
0xECADAD41, 0x67D4D4B3, 0xFDA2A25F, 0xEAAFAF45, 0xBF9C9C23, 0xF7A4A453, 0x967272E4, 0x5BC0C09B,
0xC2B7B775, 0x1CFDFDE1, 0xAE93933D, 0x6A26264C, 0x5A36366C, 0x413F3F7E, 0x02F7F7F5, 0x4FCCCC83,
0x5C343468, 0xF4A5A551, 0x34E5E5D1, 0x08F1F1F9, 0x937171E2, 0x73D8D8AB, 0x53313162, 0x3F15152A,
0x0C040408, 0x52C7C795, 0x65232346, 0x5EC3C39D, 0x28181830, 0xA1969637, 0x0F05050A, 0xB59A9A2F,
0x0907070E, 0x36121224, 0x9B80801B, 0x3DE2E2DF, 0x26EBEBCD, 0x6927274E, 0xCDB2B27F, 0x9F7575EA,
0x1B090912, 0x9E83831D, 0x742C2C58, 0x2E1A1A34, 0x2D1B1B36, 0xB26E6EDC, 0xEE5A5AB4, 0xFBA0A05B,
0xF65252A4, 0x4D3B3B76, 0x61D6D6B7, 0xCEB3B37D, 0x7B292952, 0x3EE3E3DD, 0x712F2F5E, 0x97848413,
0xF55353A6, 0x68D1D1B9, 0x00000000, 0x2CEDEDC1, 0x60202040, 0x1FFCFCE3, 0xC8B1B179, 0xED5B5BB6,
0xBE6A6AD4, 0x46CBCB8D, 0xD9BEBE67, 0x4B393972, 0xDE4A4A94, 0xD44C4C98, 0xE85858B0, 0x4ACFCF85,
0x6BD0D0BB, 0x2AEFEFC5, 0xE5AAAA4F, 0x16FBFBED, 0xC5434386, 0xD74D4D9A, 0x55333366, 0x94858511,
0xCF45458A, 0x10F9F9E9, 0x06020204, 0x817F7FFE, 0xF05050A0, 0x443C3C78, 0xBA9F9F25, 0xE3A8A84B,
0xF35151A2, 0xFEA3A35D, 0xC0404080, 0x8A8F8F05, 0xAD92923F, 0xBC9D9D21, 0x48383870, 0x04F5F5F1,
0xDFBCBC63, 0xC1B6B677, 0x75DADAAF, 0x63212142, 0x30101020, 0x1AFFFFE5, 0x0EF3F3FD, 0x6DD2D2BF,
0x4CCDCD81, 0x140C0C18, 0x35131326, 0x2FECECC3, 0xE15F5FBE, 0xA2979735, 0xCC444488, 0x3917172E,
0x57C4C493, 0xF2A7A755, 0x827E7EFC, 0x473D3D7A, 0xAC6464C8, 0xE75D5DBA, 0x2B191932, 0x957373E6,
0xA06060C0, 0x98818119, 0xD14F4F9E, 0x7FDCDCA3, 0x66222244, 0x7E2A2A54, 0xAB90903B, 0x8388880B,
0xCA46468C, 0x29EEEEC7, 0xD3B8B86B, 0x3C141428, 0x79DEDEA7, 0xE25E5EBC, 0x1D0B0B16, 0x76DBDBAD,
0x3BE0E0DB, 0x56323264, 0x4E3A3A74, 0x1E0A0A14, 0xDB494992, 0x0A06060C, 0x6C242448, 0xE45C5CB8,
0x5DC2C29F, 0x6ED3D3BD, 0xEFACAC43, 0xA66262C4, 0xA8919139, 0xA4959531, 0x37E4E4D3, 0x8B7979F2,
0x32E7E7D5, 0x43C8C88B, 0x5937376E, 0xB76D6DDA, 0x8C8D8D01, 0x64D5D5B1, 0xD24E4E9C, 0xE0A9A949,
0xB46C6CD8, 0xFA5656AC, 0x07F4F4F3, 0x25EAEACF, 0xAF6565CA, 0x8E7A7AF4, 0xE9AEAE47, 0x18080810,
0xD5BABA6F, 0x887878F0, 0x6F25254A, 0x722E2E5C, 0x241C1C38, 0xF1A6A657, 0xC7B4B473, 0x51C6C697,
0x23E8E8CB, 0x7CDDDDA1, 0x9C7474E8, 0x211F1F3E, 0xDD4B4B96, 0xDCBDBD61, 0x868B8B0D, 0x858A8A0F,
0x907070E0, 0x423E3E7C, 0xC4B5B571, 0xAA6666CC, 0xD8484890, 0x05030306, 0x01F6F6F7, 0x120E0E1C,
0xA36161C2, 0x5F35356A, 0xF95757AE, 0xD0B9B969, 0x91868617, 0x58C1C199, 0x271D1D3A, 0xB99E9E27,
0x38E1E1D9, 0x13F8F8EB, 0xB398982B, 0x33111122, 0xBB6969D2, 0x70D9D9A9, 0x898E8E07, 0xA7949433,
0xB69B9B2D, 0x221E1E3C, 0x92878715, 0x20E9E9C9, 0x49CECE87, 0xFF5555AA, 0x78282850, 0x7ADFDFA5,
0x8F8C8C03, 0xF8A1A159, 0x80898909, 0x170D0D1A, 0xDABFBF65, 0x31E6E6D7, 0xC6424284, 0xB86868D0,
0xC3414182, 0xB0999929, 0x772D2D5A, 0x110F0F1E, 0xCBB0B07B, 0xFC5454A8, 0xD6BBBB6D, 0x3A16162C,
};
constexpr const u32 DecryptTable[0x100] = {
0x50A7F451, 0x5365417E, 0xC3A4171A, 0x965E273A, 0xCB6BAB3B, 0xF1459D1F, 0xAB58FAAC, 0x9303E34B,
0x55FA3020, 0xF66D76AD, 0x9176CC88, 0x254C02F5, 0xFCD7E54F, 0xD7CB2AC5, 0x80443526, 0x8FA362B5,
0x495AB1DE, 0x671BBA25, 0x980EEA45, 0xE1C0FE5D, 0x02752FC3, 0x12F04C81, 0xA397468D, 0xC6F9D36B,
0xE75F8F03, 0x959C9215, 0xEB7A6DBF, 0xDA595295, 0x2D83BED4, 0xD3217458, 0x2969E049, 0x44C8C98E,
0x6A89C275, 0x78798EF4, 0x6B3E5899, 0xDD71B927, 0xB64FE1BE, 0x17AD88F0, 0x66AC20C9, 0xB43ACE7D,
0x184ADF63, 0x82311AE5, 0x60335197, 0x457F5362, 0xE07764B1, 0x84AE6BBB, 0x1CA081FE, 0x942B08F9,
0x58684870, 0x19FD458F, 0x876CDE94, 0xB7F87B52, 0x23D373AB, 0xE2024B72, 0x578F1FE3, 0x2AAB5566,
0x0728EBB2, 0x03C2B52F, 0x9A7BC586, 0xA50837D3, 0xF2872830, 0xB2A5BF23, 0xBA6A0302, 0x5C8216ED,
0x2B1CCF8A, 0x92B479A7, 0xF0F207F3, 0xA1E2694E, 0xCDF4DA65, 0xD5BE0506, 0x1F6234D1, 0x8AFEA6C4,
0x9D532E34, 0xA055F3A2, 0x32E18A05, 0x75EBF6A4, 0x39EC830B, 0xAAEF6040, 0x069F715E, 0x51106EBD,
0xF98A213E, 0x3D06DD96, 0xAE053EDD, 0x46BDE64D, 0xB58D5491, 0x055DC471, 0x6FD40604, 0xFF155060,
0x24FB9819, 0x97E9BDD6, 0xCC434089, 0x779ED967, 0xBD42E8B0, 0x888B8907, 0x385B19E7, 0xDBEEC879,
0x470A7CA1, 0xE90F427C, 0xC91E84F8, 0x00000000, 0x83868009, 0x48ED2B32, 0xAC70111E, 0x4E725A6C,
0xFBFF0EFD, 0x5638850F, 0x1ED5AE3D, 0x27392D36, 0x64D90F0A, 0x21A65C68, 0xD1545B9B, 0x3A2E3624,
0xB1670A0C, 0x0FE75793, 0xD296EEB4, 0x9E919B1B, 0x4FC5C080, 0xA220DC61, 0x694B775A, 0x161A121C,
0x0ABA93E2, 0xE52AA0C0, 0x43E0223C, 0x1D171B12, 0x0B0D090E, 0xADC78BF2, 0xB9A8B62D, 0xC8A91E14,
0x8519F157, 0x4C0775AF, 0xBBDD99EE, 0xFD607FA3, 0x9F2601F7, 0xBCF5725C, 0xC53B6644, 0x347EFB5B,
0x7629438B, 0xDCC623CB, 0x68FCEDB6, 0x63F1E4B8, 0xCADC31D7, 0x10856342, 0x40229713, 0x2011C684,
0x7D244A85, 0xF83DBBD2, 0x1132F9AE, 0x6DA129C7, 0x4B2F9E1D, 0xF330B2DC, 0xEC52860D, 0xD0E3C177,
0x6C16B32B, 0x99B970A9, 0xFA489411, 0x2264E947, 0xC48CFCA8, 0x1A3FF0A0, 0xD82C7D56, 0xEF903322,
0xC74E4987, 0xC1D138D9, 0xFEA2CA8C, 0x360BD498, 0xCF81F5A6, 0x28DE7AA5, 0x268EB7DA, 0xA4BFAD3F,
0xE49D3A2C, 0x0D927850, 0x9BCC5F6A, 0x62467E54, 0xC2138DF6, 0xE8B8D890, 0x5EF7392E, 0xF5AFC382,
0xBE805D9F, 0x7C93D069, 0xA92DD56F, 0xB31225CF, 0x3B99ACC8, 0xA77D1810, 0x6E639CE8, 0x7BBB3BDB,
0x097826CD, 0xF418596E, 0x01B79AEC, 0xA89A4F83, 0x656E95E6, 0x7EE6FFAA, 0x08CFBC21, 0xE6E815EF,
0xD99BE7BA, 0xCE366F4A, 0xD4099FEA, 0xD67CB029, 0xAFB2A431, 0x31233F2A, 0x3094A5C6, 0xC066A235,
0x37BC4E74, 0xA6CA82FC, 0xB0D090E0, 0x15D8A733, 0x4A9804F1, 0xF7DAEC41, 0x0E50CD7F, 0x2FF69117,
0x8DD64D76, 0x4DB0EF43, 0x544DAACC, 0xDF0496E4, 0xE3B5D19E, 0x1B886A4C, 0xB81F2CC1, 0x7F516546,
0x04EA5E9D, 0x5D358C01, 0x737487FA, 0x2E410BFB, 0x5A1D67B3, 0x52D2DB92, 0x335610E9, 0x1347D66D,
0x8C61D79A, 0x7A0CA137, 0x8E14F859, 0x893C13EB, 0xEE27A9CE, 0x35C961B7, 0xEDE51CE1, 0x3CB1477A,
0x59DFD29C, 0x3F73F255, 0x79CE1418, 0xBF37C773, 0xEACDF753, 0x5BAAFD5F, 0x146F3DDF, 0x86DB4478,
0x81F3AFCA, 0x3EC468B9, 0x2C342438, 0x5F40A3C2, 0x72C31D16, 0x0C25E2BC, 0x8B493C28, 0x41950DFF,
0x7101A839, 0xDEB30C08, 0x9CE4B4D8, 0x90C15664, 0x6184CB7B, 0x70B632D5, 0x745C6C48, 0x4257B8D0,
};
constexpr auto AesWordByte0Shift = 0 * BITSIZEOF(u8);
constexpr auto AesWordByte1Shift = 1 * BITSIZEOF(u8);
constexpr auto AesWordByte2Shift = 2 * BITSIZEOF(u8);
constexpr auto AesWordByte3Shift = 3 * BITSIZEOF(u8);
constexpr auto AesMixShift = 3 * BITSIZEOF(u8);
constexpr void InverseMixColumns(u32 *dst, const u32 *src) {
for (auto i = 0; i < WordsPerBlock; ++i) {
const u32 v0 = src[i];
const u32 v1 = (((v0 & 0x7F7F7F7Fu) << 1) ^ (((v0 & 0x80808080) >> 7) * 0x1B));
const u32 v2 = (((v1 & 0x7F7F7F7Fu) << 1) ^ (((v1 & 0x80808080) >> 7) * 0x1B));
const u32 v3 = (((v2 & 0x7F7F7F7Fu) << 1) ^ (((v2 & 0x80808080) >> 7) * 0x1B));
u32 v = v0 ^ v3;
v ^= util::RotateLeft(v, AesMixShift) ^ v2;
v ^= util::RotateLeft(v, AesMixShift) ^ v1;
v ^= util::RotateLeft(v, AesMixShift) ^ v0;
dst[i] = v;
}
}
constexpr u32 SubBytesAndRotate(u32 v) {
return (static_cast<u32>(SubBytesTable[(v >> AesWordByte0Shift) & 0xFFu]) << AesWordByte3Shift) ^
(static_cast<u32>(SubBytesTable[(v >> AesWordByte1Shift) & 0xFFu]) << AesWordByte0Shift) ^
(static_cast<u32>(SubBytesTable[(v >> AesWordByte2Shift) & 0xFFu]) << AesWordByte1Shift) ^
(static_cast<u32>(SubBytesTable[(v >> AesWordByte3Shift) & 0xFFu]) << AesWordByte2Shift);
}
constexpr u32 SubBytes(u32 v) {
return (static_cast<u32>(SubBytesTable[(v >> AesWordByte0Shift) & 0xFFu]) << AesWordByte0Shift) ^
(static_cast<u32>(SubBytesTable[(v >> AesWordByte1Shift) & 0xFFu]) << AesWordByte1Shift) ^
(static_cast<u32>(SubBytesTable[(v >> AesWordByte2Shift) & 0xFFu]) << AesWordByte2Shift) ^
(static_cast<u32>(SubBytesTable[(v >> AesWordByte3Shift) & 0xFFu]) << AesWordByte3Shift);
}
constexpr u32 ShiftSubMix(u32 v0, u32 v1, u32 v2, u32 v3) {
return (util::RotateLeft(static_cast<u32>(EncryptTable[(v0 >> AesWordByte0Shift) & 0xFFu]), AesWordByte0Shift)) ^
(util::RotateLeft(static_cast<u32>(EncryptTable[(v1 >> AesWordByte1Shift) & 0xFFu]), AesWordByte1Shift)) ^
(util::RotateLeft(static_cast<u32>(EncryptTable[(v2 >> AesWordByte2Shift) & 0xFFu]), AesWordByte2Shift)) ^
(util::RotateLeft(static_cast<u32>(EncryptTable[(v3 >> AesWordByte3Shift) & 0xFFu]), AesWordByte3Shift));
}
constexpr u32 ShiftSub(u32 v0, u32 v1, u32 v2, u32 v3) {
return (static_cast<u32>(SubBytesTable[(v0 >> AesWordByte0Shift) & 0xFFu]) << AesWordByte0Shift) ^
(static_cast<u32>(SubBytesTable[(v1 >> AesWordByte1Shift) & 0xFFu]) << AesWordByte1Shift) ^
(static_cast<u32>(SubBytesTable[(v2 >> AesWordByte2Shift) & 0xFFu]) << AesWordByte2Shift) ^
(static_cast<u32>(SubBytesTable[(v3 >> AesWordByte3Shift) & 0xFFu]) << AesWordByte3Shift);
}
constexpr u32 InvShiftSubMix(u32 v0, u32 v1, u32 v2, u32 v3) {
return (util::RotateLeft(static_cast<u32>(DecryptTable[(v0 >> AesWordByte0Shift) & 0xFFu]), AesWordByte0Shift)) ^
(util::RotateLeft(static_cast<u32>(DecryptTable[(v1 >> AesWordByte1Shift) & 0xFFu]), AesWordByte1Shift)) ^
(util::RotateLeft(static_cast<u32>(DecryptTable[(v2 >> AesWordByte2Shift) & 0xFFu]), AesWordByte2Shift)) ^
(util::RotateLeft(static_cast<u32>(DecryptTable[(v3 >> AesWordByte3Shift) & 0xFFu]), AesWordByte3Shift));
}
constexpr u32 InvShiftSub(u32 v0, u32 v1, u32 v2, u32 v3) {
return (static_cast<u32>(InvSubBytesTable[(v0 >> AesWordByte0Shift) & 0xFFu]) << AesWordByte0Shift) ^
(static_cast<u32>(InvSubBytesTable[(v1 >> AesWordByte1Shift) & 0xFFu]) << AesWordByte1Shift) ^
(static_cast<u32>(InvSubBytesTable[(v2 >> AesWordByte2Shift) & 0xFFu]) << AesWordByte2Shift) ^
(static_cast<u32>(InvSubBytesTable[(v3 >> AesWordByte3Shift) & 0xFFu]) << AesWordByte3Shift);
}
}
const bool g_is_aes_ni_available = GetAesNiAvailabilityImpl();
template<size_t KeySize>
AesImpl<KeySize>::~AesImpl() {
ClearMemory(this, sizeof(*this));
}
template<size_t KeySize>
void AesImpl<KeySize>::Initialize(const void *key, size_t key_size, bool is_encrypt) {
/* Check pre-conditions. */
static_assert(IsSupportedKeySize(KeySize));
AMS_ASSERT(key != nullptr);
AMS_ASSERT(key_size == KeySize);
AMS_UNUSED(key_size);
/* Set up key. */
u32 *dst = m_round_keys;
std::memcpy(dst, key, KeySize);
/* Perform key scheduling. */
constexpr auto InitialKeyWords = KeySize / sizeof(u32);
u32 tmp = dst[InitialKeyWords - 1];
for (auto i = InitialKeyWords; i < (RoundCount + 1) * 4; ++i) {
const auto idx_in_key = i % InitialKeyWords;
if (idx_in_key == 0) {
/* At start of key word, we need to handle sub/rotate/rcon. */
tmp = SubBytesAndRotate(tmp);
tmp ^= (RoundKeyRcon0[i / InitialKeyWords - 1] << AesWordByte0Shift);
} else if ((InitialKeyWords > 6) && idx_in_key == 4) {
/* Halfway into a 256-bit key word, we need to do an additional subbytes. */
tmp = SubBytes(tmp);
}
/* Set the key word. */
tmp ^= dst[i - InitialKeyWords];
dst[i] = tmp;
}
/* If decrypting, perform inverse mix columns on all round keys. */
if (!is_encrypt) {
if (IsAesNiAvailable()) {
auto *key8 = reinterpret_cast<u8 *>(m_round_keys) + BlockSize;
for (auto i = 1; i < RoundCount; ++i) {
auto * const key128 = reinterpret_cast<__m128i *>(key8);
_mm_storeu_si128(key128, _mm_aesimc_si128(_mm_loadu_si128(key128)));
key8 += BlockSize;
}
} else {
for (auto i = 1; i < RoundCount; ++i) {
InverseMixColumns(m_round_keys + WordsPerBlock * i, m_round_keys + WordsPerBlock * i);
}
}
}
}
template<size_t KeySize>
void AesImpl<KeySize>::EncryptBlock(void *dst, size_t dst_size, const void *src, size_t src_size) const {
static_assert(IsSupportedKeySize(KeySize));
AMS_ASSERT(dst_size == BlockSize && src_size == BlockSize);
AMS_UNUSED(dst_size, src_size);
/* Perform block encryption. */
if (IsAesNiAvailable()) {
const auto *key8 = reinterpret_cast<const u8 *>(m_round_keys);
/* Load the block. */
auto block = _mm_loadu_si128(reinterpret_cast<const __m128i *>(src));
/* Add the first round key. */
block = _mm_xor_si128(block, _mm_loadu_si128(reinterpret_cast<const __m128i *>(key8)));
key8 += BlockSize;
/* Perform aes round on remaining round keys. */
for (auto i = 1; i < RoundCount; ++i) {
block = _mm_aesenc_si128(block, _mm_loadu_si128(reinterpret_cast<const __m128i *>(key8)));
key8 += BlockSize;
}
/* Do final update. */
block = _mm_aesenclast_si128(block, _mm_loadu_si128(reinterpret_cast<const __m128i *>(key8)));
/* Store the output. */
_mm_storeu_si128(reinterpret_cast<__m128i *>(dst), block);
} else {
static_assert(WordsPerBlock == 4);
/* Without AES-NI, we'll operate on words. */
const u32 *key32 = m_round_keys;
const u32 *src32 = static_cast<const u32 *>(src);
u32 *dst32 = static_cast< u32 *>(dst);
/* Add the first round key. */
u32 v0 = src32[0] ^ key32[0];
u32 v1 = src32[1] ^ key32[1];
u32 v2 = src32[2] ^ key32[2];
u32 v3 = src32[3] ^ key32[3];
key32 += 4;
/* Perform each round. */
auto round = RoundCount;
while (--round > 0) {
/* Perform aes round. */
const u32 e0 = ShiftSubMix(v0, v1, v2, v3);
const u32 e1 = ShiftSubMix(v1, v2, v3, v0);
const u32 e2 = ShiftSubMix(v2, v3, v0, v1);
const u32 e3 = ShiftSubMix(v3, v0, v1, v2);
/* Add the round key. */
v0 = e0 ^ key32[0];
v1 = e1 ^ key32[1];
v2 = e2 ^ key32[2];
v3 = e3 ^ key32[3];
key32 += 4;
}
/* Perform the final round. */
dst32[0] = key32[0] ^ ShiftSub(v0, v1, v2, v3);
dst32[1] = key32[1] ^ ShiftSub(v1, v2, v3, v0);
dst32[2] = key32[2] ^ ShiftSub(v2, v3, v0, v1);
dst32[3] = key32[3] ^ ShiftSub(v3, v0, v1, v2);
}
}
template<size_t KeySize>
void AesImpl<KeySize>::DecryptBlock(void *dst, size_t dst_size, const void *src, size_t src_size) const {
static_assert(IsSupportedKeySize(KeySize));
AMS_ASSERT(dst_size == BlockSize && src_size == BlockSize);
AMS_UNUSED(dst_size, src_size);
/* Perform block decryption. */
if (IsAesNiAvailable()) {
const auto *key8 = reinterpret_cast<const u8 *>(m_round_keys) + (RoundCount * BlockSize);
/* Load the block. */
auto block = _mm_loadu_si128(reinterpret_cast<const __m128i *>(src));
/* Add the final round key. */
block = _mm_xor_si128(block, _mm_loadu_si128(reinterpret_cast<const __m128i *>(key8)));
key8 -= BlockSize;
/* Perform aes invround on remaining round keys. */
for (auto i = RoundCount; i > 1; --i) {
block = _mm_aesdec_si128(block, _mm_loadu_si128(reinterpret_cast<const __m128i *>(key8)));
key8 -= BlockSize;
}
/* Do final update. */
block = _mm_aesdeclast_si128(block, _mm_loadu_si128(reinterpret_cast<const __m128i *>(key8)));
/* Store the output. */
_mm_storeu_si128(reinterpret_cast<__m128i *>(dst), block);
} else {
static_assert(WordsPerBlock == 4);
/* Without AES-NI, we'll operate on words. */
const u32 *key32 = m_round_keys + WordsPerBlock * RoundCount;
const u32 *src32 = static_cast<const u32 *>(src);
u32 *dst32 = static_cast< u32 *>(dst);
/* Add the final round key. */
u32 v0 = src32[0] ^ key32[0];
u32 v1 = src32[1] ^ key32[1];
u32 v2 = src32[2] ^ key32[2];
u32 v3 = src32[3] ^ key32[3];
key32 -= 4;
/* Perform each round. */
auto round = RoundCount;
while (--round > 0) {
/* Perform aes inv round. */
const u32 e0 = InvShiftSubMix(v0, v3, v2, v1);
const u32 e1 = InvShiftSubMix(v1, v0, v3, v2);
const u32 e2 = InvShiftSubMix(v2, v1, v0, v3);
const u32 e3 = InvShiftSubMix(v3, v2, v1, v0);
/* Add the round key. */
v0 = e0 ^ key32[0];
v1 = e1 ^ key32[1];
v2 = e2 ^ key32[2];
v3 = e3 ^ key32[3];
key32 -= 4;
}
/* Perform the final round. */
dst32[0] = key32[0] ^ InvShiftSub(v0, v3, v2, v1);
dst32[1] = key32[1] ^ InvShiftSub(v1, v0, v3, v2);
dst32[2] = key32[2] ^ InvShiftSub(v2, v1, v0, v3);
dst32[3] = key32[3] ^ InvShiftSub(v3, v2, v1, v0);
}
}
/* Explicitly instantiate the three supported key sizes. */
template class AesImpl<16>;
template class AesImpl<24>;
template class AesImpl<32>;
}
| 24,883
|
C++
|
.cpp
| 373
| 54.265416
| 125
| 0.611886
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,091
|
crypto_md5_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/crypto/impl/crypto_md5_impl.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <vapours.hpp>
namespace ams::crypto::impl {
namespace {
struct Md5Constants {
static constexpr const u32 A = 0x67452301;
static constexpr const u32 B = 0xEFCDAB89;
static constexpr const u32 C = 0x98BADCFE;
static constexpr const u32 D = 0x10325476;
static constexpr const u32 T[] = {
0xD76AA478, 0xE8C7B756, 0x242070DB, 0xC1BDCEEE,
0xF57C0FAF, 0x4787C62A, 0xA8304613, 0xFD469501,
0x698098D8, 0x8B44F7AF, 0xFFFF5BB1, 0x895CD7BE,
0x6B901122, 0xFD987193, 0xA679438E, 0x49B40821,
0xF61E2562, 0xC040B340, 0x265E5A51, 0xE9B6C7AA,
0xD62F105D, 0x02441453, 0xD8A1E681, 0xE7D3FBC8,
0x21E1CDE6, 0xC33707D6, 0xF4D50D87, 0x455A14ED,
0xA9E3E905, 0xFCEFA3F8, 0x676F02D9, 0x8D2A4C8A,
0xFFFA3942, 0x8771F681, 0x6D9D6122, 0xFDE5380C,
0xA4BEEA44, 0x4BDECFA9, 0xF6BB4B60, 0xBEBFBC70,
0x289B7EC6, 0xEAA127FA, 0xD4EF3085, 0x04881D05,
0xD9D4D039, 0xE6DB99E5, 0x1FA27CF8, 0xC4AC5665,
0xF4292244, 0x432AFF97, 0xAB9423A7, 0xFC93A039,
0x655B59C3, 0x8F0CCC92, 0xFFEFF47D, 0x85845DD1,
0x6FA87E4F, 0xFE2CE6E0, 0xA3014314, 0x4E0811A1,
0xF7537E82, 0xBD3AF235, 0x2AD7D2BB, 0xEB86D391,
};
static constexpr u32 K[] = {
0x1, 0x6, 0xB, 0x0,
0x5, 0xA, 0xF, 0x4,
0x9, 0xE, 0x3, 0x8,
0xD, 0x2, 0x7, 0xC,
0x5, 0x8, 0xB, 0xE,
0x1, 0x4, 0x7, 0xA,
0xD, 0x0, 0x3, 0x6,
0x9, 0xC, 0xF, 0x2,
0x0, 0x7, 0xE, 0x5,
0xC, 0x3, 0xA, 0x1,
0x8, 0xF, 0x6, 0xD,
0x4, 0xB, 0x2, 0x9,
};
static constexpr u8 Padding[] = {
0x80
};
};
constexpr ALWAYS_INLINE u32 F(u32 x, u32 y, u32 z) { return (x & y) | ((~x) & z); }
constexpr ALWAYS_INLINE u32 G(u32 x, u32 y, u32 z) { return (x & z) | (y & (~z)); }
constexpr ALWAYS_INLINE u32 H(u32 x, u32 y, u32 z) { return x ^ y ^ z; }
constexpr ALWAYS_INLINE u32 I(u32 x, u32 y, u32 z) { return y ^ (x | (~z)); }
constexpr ALWAYS_INLINE u32 CalculateRound1(u32 a, u32 b, u32 c, u32 d, u32 x, u32 s, u32 t) { return b + util::RotateLeft<u32>(a + F(b, c, d) + x + t, s); }
constexpr ALWAYS_INLINE u32 CalculateRound2(u32 a, u32 b, u32 c, u32 d, u32 x, u32 s, u32 t) { return b + util::RotateLeft<u32>(a + G(b, c, d) + x + t, s); }
constexpr ALWAYS_INLINE u32 CalculateRound3(u32 a, u32 b, u32 c, u32 d, u32 x, u32 s, u32 t) { return b + util::RotateLeft<u32>(a + H(b, c, d) + x + t, s); }
constexpr ALWAYS_INLINE u32 CalculateRound4(u32 a, u32 b, u32 c, u32 d, u32 x, u32 s, u32 t) { return b + util::RotateLeft<u32>(a + I(b, c, d) + x + t, s); }
void Encode(u32 *dst, const u32 *src, size_t size) {
if constexpr (util::IsBigEndian()) {
for (size_t i = 0; i < size; i += sizeof(u32)) {
util::StoreLittleEndian(dst + i, src[i]);
}
} else {
std::memcpy(dst, src, size);
}
}
void Decode(u32 *dst, const u32 *src, size_t size) {
if constexpr (util::IsBigEndian()) {
for (size_t i = 0; i < size; i += sizeof(u32)) {
dst[i] = util::LoadLittleEndian(src + i);
}
} else {
std::memcpy(dst, src, size);
}
}
}
void Md5Impl::Initialize() {
/* Set constants. */
m_x.p.a = Md5Constants::A;
m_x.p.b = Md5Constants::B;
m_x.p.c = Md5Constants::C;
m_x.p.d = Md5Constants::D;
/* Set size. */
m_size = 0;
/* Set initialized. */
m_state = State_Initialized;
}
void Md5Impl::Update(const void *data, size_t size) {
/* Check pre-conditions. */
AMS_ASSERT(m_state == State_Initialized);
/* Determine how much we can process. */
const size_t work_idx = m_size % BlockSize;
const size_t work_remaining = BlockSize - work_idx;
/* Increment our size. */
m_size += size;
/* Copy in the data to our buffer, if we don't have a full block. */
if (work_remaining > size) {
if (size > 0) {
std::memcpy(m_y + work_idx, data, size);
}
return;
}
/* Copy what we can to complete our block. */
std::memcpy(m_y + work_idx, data, work_remaining);
/* Process the block. */
this->ProcessBlock();
/* Adjust size to account for what we've processed. */
size -= work_remaining;
/* Process as many full blocks as we can. */
const u8 *cur_block = static_cast<const u8 *>(data) + work_remaining;
for (size_t i = 0; i < size / BlockSize; ++i) {
std::memcpy(m_y, cur_block, BlockSize);
cur_block += BlockSize;
this->ProcessBlock();
}
/* Copy in any leftover data. */
if (const auto left = size % BlockSize; left > 0) {
std::memcpy(m_y, cur_block, left);
}
}
void Md5Impl::GetHash(void *dst, size_t size) {
/* Check pre-conditions. */
AMS_ASSERT(m_state == State_Initialized || m_state == State_Done);
AMS_ASSERT(size >= HashSize);
AMS_UNUSED(size);
/* If we need to, finish processing. */
if (m_state == State_Initialized) {
this->ProcessLastBlock();
m_state = State_Done;
}
/* Encode the result. */
Encode(static_cast<u32 *>(dst), m_x.state, HashSize);
}
void Md5Impl::ProcessBlock() {
/* Declare tracking pointers for rounds. */
u32 x[BlockSize / sizeof(u32)];
const u32 *p_t = Md5Constants::T;
const u32 *p_k = Md5Constants::K;
const u32 *p_x = x;
/* Extract current state. */
u32 a = m_x.p.a;
u32 b = m_x.p.b;
u32 c = m_x.p.c;
u32 d = m_x.p.d;
/* Decode the block into native endian. */
Decode(x, reinterpret_cast<const u32 *>(m_y), BlockSize);
/* Perform round 1. */
for (size_t i = 0; i < 4; ++i) {
a = CalculateRound1(a, b, c, d, *p_x++, 7, *p_t++);
d = CalculateRound1(d, a, b, c, *p_x++, 12, *p_t++);
c = CalculateRound1(c, d, a, b, *p_x++, 17, *p_t++);
b = CalculateRound1(b, c, d, a, *p_x++, 22, *p_t++);
}
/* Perform round 2. */
for (size_t i = 0; i < 4; ++i) {
a = CalculateRound2(a, b, c, d, x[*p_k++], 5, *p_t++);
d = CalculateRound2(d, a, b, c, x[*p_k++], 9, *p_t++);
c = CalculateRound2(c, d, a, b, x[*p_k++], 14, *p_t++);
b = CalculateRound2(b, c, d, a, x[*p_k++], 20, *p_t++);
}
/* Perform round 3. */
for (size_t i = 0; i < 4; ++i) {
a = CalculateRound3(a, b, c, d, x[*p_k++], 4, *p_t++);
d = CalculateRound3(d, a, b, c, x[*p_k++], 11, *p_t++);
c = CalculateRound3(c, d, a, b, x[*p_k++], 16, *p_t++);
b = CalculateRound3(b, c, d, a, x[*p_k++], 23, *p_t++);
}
/* Perform round 4. */
for (size_t i = 0; i < 4; ++i) {
a = CalculateRound4(a, b, c, d, x[*p_k++], 6, *p_t++);
d = CalculateRound4(d, a, b, c, x[*p_k++], 10, *p_t++);
c = CalculateRound4(c, d, a, b, x[*p_k++], 15, *p_t++);
b = CalculateRound4(b, c, d, a, x[*p_k++], 21, *p_t++);
}
/* Mix the result back into our state. */
m_x.p.a += a;
m_x.p.b += b;
m_x.p.c += c;
m_x.p.d += d;
}
void Md5Impl::ProcessLastBlock() {
/* Get bit count. */
const u64 bit_count = m_size * BITSIZEOF(u8);
/* Add padding byte unconditionally. */
this->Update(Md5Constants::Padding, sizeof(Md5Constants::Padding));
/* Determine remaining. */
size_t work_idx = m_size % BlockSize;
size_t work_remaining = BlockSize - work_idx;
/* We want to process 8000.....{bit count}. */
if (work_remaining < sizeof(u64)) {
std::memset(m_y + work_idx, 0, work_remaining);
this->ProcessBlock();
work_idx = 0;
work_remaining = BlockSize;
}
if (work_remaining > sizeof(u64)) {
std::memset(m_y + work_idx, 0, work_remaining - sizeof(u64));
}
util::StoreLittleEndian<u64>(reinterpret_cast<u64 *>(m_y + BlockSize - sizeof(u64)), bit_count);
this->ProcessBlock();
}
}
| 9,536
|
C++
|
.cpp
| 212
| 34.283019
| 165
| 0.523163
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,092
|
crypto_cbc_mac_impl.arch.generic.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/crypto/impl/crypto_cbc_mac_impl.arch.generic.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <vapours.hpp>
#include "crypto_update_impl.hpp"
namespace ams::crypto::impl {
void CbcMacImpl::UpdateGeneric(const void *data, size_t size) {
/* Check pre-conditions. */
AMS_ASSERT(m_state == State_Initialized);
/* Update. */
UpdateImpl<void>(this, data, size);
}
void CbcMacImpl::ProcessBlocksGeneric(const void *data, size_t num_blocks) {
/* If we have a block remaining, process it. */
if (m_buffered_bytes == BlockSize) {
this->ProcessBlock(m_buffer);
m_buffered_bytes = 0;
}
/* Process blocks. */
const u8 *data8 = static_cast<const u8 *>(data);
u8 block[BlockSize];
while ((--num_blocks) > 0) {
for (size_t i = 0; i < BlockSize; ++i) {
block[i] = data8[i] ^ m_mac[i];
}
m_cipher_function(m_mac, block, m_cipher_context);
data8 += BlockSize;
}
/* Process the last block. */
std::memcpy(m_buffer, data8, BlockSize);
m_buffered_bytes = BlockSize;
}
template<>
void CbcMacImpl::Update<AesEncryptor128>(const void *data, size_t size) {
this->UpdateGeneric(data, size);
}
}
| 1,874
|
C++
|
.cpp
| 49
| 31.734694
| 80
| 0.633756
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,093
|
crypto_xts_mode_impl.arch.arm64.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/crypto/impl/crypto_xts_mode_impl.arch.arm64.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <vapours.hpp>
#include "crypto_update_impl.hpp"
#ifdef ATMOSPHERE_IS_STRATOSPHERE
#include <arm_neon.h>
namespace ams::crypto::impl {
/* Variable management macros. */
#define DECLARE_ROUND_KEY_VAR(n) \
const uint8x16_t round_key_##n = vld1q_u8(keys + (BlockSize * n))
#define AES_ENC_DEC_OUTPUT_THREE_BLOCKS() \
[tmp0]"+w"(tmp0), [tmp1]"+w"(tmp1), [tmp2]"+w"(tmp2)
#define AES_ENC_DEC_OUTPUT_THREE_TWEAKS() \
[tweak0]"+w"(tweak0), [tweak1]"+w"(tweak1), [tweak2]"+w"(tweak2)
#define AES_ENC_DEC_OUTPUT_ONE_BLOCK() \
[tmp0]"+w"(tmp0)
#define AES_ENC_DEC_OUTPUT_ONE_TWEAK() \
[tweak0]"+w"(tweak0)
#define XTS_INCREMENT_OUTPUT_HIGH_LOW_MASK() \
[high]"=&r"(high), [low]"=&r"(low), [mask]"=&r"(mask)
#define XTS_INCREMENT_INPUT_XOR() \
[xorv]"r"(xorv)
#define AES_ENC_DEC_INPUT_ROUND_KEY(n) \
[round_key_##n]"w"(round_key_##n)
/* AES Encryption macros. */
#define AES_ENC_ROUND(n, i) \
"aese %[tmp" #i "].16b, %[round_key_" #n "].16b\n" \
"aesmc %[tmp" #i "].16b, %[tmp" #i "].16b\n"
#define AES_ENC_SECOND_LAST_ROUND(n, i) \
"aese %[tmp" #i "].16b, %[round_key_" #n "].16b\n"
#define AES_ENC_LAST_ROUND(n, i) \
"eor %[tmp" #i "].16b, %[tmp" #i "].16b, %[round_key_" #n "].16b\n"
/* AES Decryption macros. */
#define AES_DEC_ROUND(n, i) \
"aesd %[tmp" #i "].16b, %[round_key_" #n "].16b\n" \
"aesimc %[tmp" #i "].16b, %[tmp" #i "].16b\n"
#define AES_DEC_SECOND_LAST_ROUND(n, i) \
"aesd %[tmp" #i "].16b, %[round_key_" #n "].16b\n"
#define AES_DEC_LAST_ROUND(n, i) \
"eor %[tmp" #i "].16b, %[tmp" #i "].16b, %[round_key_" #n "].16b\n"
namespace {
/* TODO: Support non-Nintendo Endianness */
ALWAYS_INLINE uint8x16_t MultiplyTweak(const uint8x16_t tweak) {
/* TODO: Is the inline asm better than using intrinsics? */
#if 1
uint8x16_t mult;
uint64_t high, low, mask;
constexpr uint64_t xorv = 0x87ul;
/* Use ASM. TODO: Better than using intrinsics? */
__asm__ __volatile__ (
"mov %[high], %[tweak].d[1]\n"
"mov %[low], %[tweak].d[0]\n"
"and %[mask], %[xorv], %[high], asr 63\n"
"extr %[high], %[high], %[low], 63\n"
"eor %[low], %[mask], %[low], lsl 1\n"
"mov %[mult].d[1], %[high]\n"
"mov %[mult].d[0], %[low]\n"
: [mult]"=w"(mult),
XTS_INCREMENT_OUTPUT_HIGH_LOW_MASK()
: [tweak]"w"(tweak),
XTS_INCREMENT_INPUT_XOR()
: "cc"
);
return mult;
#else
constexpr uint64_t XorMask = 0x87ul;
const uint64x2_t tweak64 = vreinterpretq_u64_u8(tweak);
const uint64_t high = vgetq_lane_u64(tweak64, 1);
const uint64_t low = vgetq_lane_u64(tweak64, 0);
const uint64_t mask = static_cast<int64_t>(high) >> (BITSIZEOF(uint64_t) - 1);
return vreinterpretq_u8_u64(vcombine_u64(vmov_n_u64((low << 1) ^ (mask & XorMask)), vmov_n_u64((high << 1) | (low >> (BITSIZEOF(uint64_t) - 1)))));
#endif
}
}
size_t XtsModeImpl::UpdateGeneric(void *dst, size_t dst_size, const void *src, size_t src_size) {
AMS_ASSERT(m_state == State_Initialized || m_state == State_Processing);
return UpdateImpl<void>(this, dst, dst_size, src, src_size);
}
size_t XtsModeImpl::ProcessBlocksGeneric(u8 *dst, const u8 *src, size_t num_blocks) {
size_t processed = BlockSize * (num_blocks - 1);
if (m_state == State_Processing) {
this->ProcessBlock(dst, m_last_block);
dst += BlockSize;
processed += BlockSize;
}
uint8x16_t tweak = vld1q_u8(m_tweak);
while ((--num_blocks) > 0) {
/* Xor */
uint8x16_t block = vld1q_u8(src);
src += BlockSize;
block = veorq_u8(block, tweak);
/* Encrypt */
vst1q_u8(dst, block);
m_cipher_func(dst, dst, m_cipher_ctx);
block = vld1q_u8(dst);
/* Xor */
veorq_u8(block, tweak);
vst1q_u8(dst, block);
dst += BlockSize;
/* Increment tweak. */
tweak = MultiplyTweak(tweak);
}
vst1q_u8(m_tweak, tweak);
std::memcpy(m_last_block, src, BlockSize);
m_state = State_Processing;
return processed;
}
template<> size_t XtsModeImpl::Update<AesEncryptor128>(void *dst, size_t dst_size, const void *src, size_t src_size) { return UpdateImpl<AesEncryptor128>(this, dst, dst_size, src, src_size); }
template<> size_t XtsModeImpl::Update<AesEncryptor192>(void *dst, size_t dst_size, const void *src, size_t src_size) { return UpdateImpl<AesEncryptor192>(this, dst, dst_size, src, src_size); }
template<> size_t XtsModeImpl::Update<AesEncryptor256>(void *dst, size_t dst_size, const void *src, size_t src_size) { return UpdateImpl<AesEncryptor256>(this, dst, dst_size, src, src_size); }
template<> size_t XtsModeImpl::Update<AesDecryptor128>(void *dst, size_t dst_size, const void *src, size_t src_size) { return UpdateImpl<AesDecryptor128>(this, dst, dst_size, src, src_size); }
template<> size_t XtsModeImpl::Update<AesDecryptor192>(void *dst, size_t dst_size, const void *src, size_t src_size) { return UpdateImpl<AesDecryptor192>(this, dst, dst_size, src, src_size); }
template<> size_t XtsModeImpl::Update<AesDecryptor256>(void *dst, size_t dst_size, const void *src, size_t src_size) { return UpdateImpl<AesDecryptor256>(this, dst, dst_size, src, src_size); }
template<>
size_t XtsModeImpl::ProcessBlocks<AesEncryptor128>(u8 *dst, const u8 *src, size_t num_blocks) {
/* Handle last buffered block. */
size_t processed = (num_blocks - 1) * BlockSize;
if (m_state == State_Processing) {
this->ProcessBlock(dst, m_last_block);
dst += BlockSize;
processed += BlockSize;
}
/* Preload all round keys + iv into neon registers. */
const u8 *keys = static_cast<const AesEncryptor128 *>(m_cipher_ctx)->GetRoundKey();
DECLARE_ROUND_KEY_VAR(0);
DECLARE_ROUND_KEY_VAR(1);
DECLARE_ROUND_KEY_VAR(2);
DECLARE_ROUND_KEY_VAR(3);
DECLARE_ROUND_KEY_VAR(4);
DECLARE_ROUND_KEY_VAR(5);
DECLARE_ROUND_KEY_VAR(6);
DECLARE_ROUND_KEY_VAR(7);
DECLARE_ROUND_KEY_VAR(8);
DECLARE_ROUND_KEY_VAR(9);
DECLARE_ROUND_KEY_VAR(10);
uint8x16_t tweak0 = vld1q_u8(m_tweak);
constexpr uint64_t xorv = 0x87ul;
uint64_t high, low, mask;
/* Process three blocks at a time, when possible. */
if (num_blocks > 3) {
/* Multiply tweak twice. */
uint8x16_t tweak1 = MultiplyTweak(tweak0);
uint8x16_t tweak2 = MultiplyTweak(tweak1);
do {
/* Save tweaks for xor usage. */
const uint8x16_t mask0 = tweak0;
const uint8x16_t mask1 = tweak1;
const uint8x16_t mask2 = tweak2;
/* Read blocks in, XOR with tweaks. */
uint8x16_t tmp0 = veorq_u8(mask0, vld1q_u8(src)); src += BlockSize;
uint8x16_t tmp1 = veorq_u8(mask1, vld1q_u8(src)); src += BlockSize;
uint8x16_t tmp2 = veorq_u8(mask2, vld1q_u8(src)); src += BlockSize;
/* Actually do encryption, use optimized asm. */
/* Interleave GF mult calculations with AES ones, to mask latencies. */
__asm__ __volatile__ (
AES_ENC_ROUND(0, 0) "mov %[high], %[tweak2].d[1]\n"
AES_ENC_ROUND(0, 1) "mov %[low], %[tweak2].d[0]\n"
AES_ENC_ROUND(0, 2) "and %[mask], %[xorv], %[high], asr 63\n"
AES_ENC_ROUND(1, 0) "extr %[high], %[high], %[low], 63\n"
AES_ENC_ROUND(1, 1) "eor %[low], %[mask], %[low], lsl 1\n"
AES_ENC_ROUND(1, 2) "mov %[tweak0].d[1], %[high]\n"
AES_ENC_ROUND(2, 0) "mov %[tweak0].d[0], %[low]\n"
AES_ENC_ROUND(2, 1) "and %[mask], %[xorv], %[high], asr 63\n"
AES_ENC_ROUND(2, 2) "extr %[high], %[high], %[low], 63\n"
AES_ENC_ROUND(3, 0) "eor %[low], %[mask], %[low], lsl 1\n"
AES_ENC_ROUND(3, 1) "mov %[tweak1].d[1], %[high]\n"
AES_ENC_ROUND(3, 2) "mov %[tweak1].d[0], %[low]\n"
AES_ENC_ROUND(4, 0) "and %[mask], %[xorv], %[high], asr 63\n"
AES_ENC_ROUND(4, 1) "extr %[high], %[high], %[low], 63\n"
AES_ENC_ROUND(4, 2) "eor %[low], %[mask], %[low], lsl 1\n"
AES_ENC_ROUND(5, 0) "mov %[tweak2].d[1], %[high]\n"
AES_ENC_ROUND(5, 1) "mov %[tweak2].d[0], %[low]\n"
AES_ENC_ROUND(5, 2)
AES_ENC_ROUND(6, 0) AES_ENC_ROUND(6, 1) AES_ENC_ROUND(6, 2)
AES_ENC_ROUND(7, 0) AES_ENC_ROUND(7, 1) AES_ENC_ROUND(7, 2)
AES_ENC_ROUND(8, 0) AES_ENC_ROUND(8, 1) AES_ENC_ROUND(8, 2)
AES_ENC_SECOND_LAST_ROUND(9, 0) AES_ENC_SECOND_LAST_ROUND(9, 1) AES_ENC_SECOND_LAST_ROUND(9, 2)
AES_ENC_LAST_ROUND(10, 0) AES_ENC_LAST_ROUND(10, 1) AES_ENC_LAST_ROUND(10, 2)
: AES_ENC_DEC_OUTPUT_THREE_BLOCKS(),
AES_ENC_DEC_OUTPUT_THREE_TWEAKS(),
XTS_INCREMENT_OUTPUT_HIGH_LOW_MASK()
: XTS_INCREMENT_INPUT_XOR(),
AES_ENC_DEC_INPUT_ROUND_KEY(0),
AES_ENC_DEC_INPUT_ROUND_KEY(1),
AES_ENC_DEC_INPUT_ROUND_KEY(2),
AES_ENC_DEC_INPUT_ROUND_KEY(3),
AES_ENC_DEC_INPUT_ROUND_KEY(4),
AES_ENC_DEC_INPUT_ROUND_KEY(5),
AES_ENC_DEC_INPUT_ROUND_KEY(6),
AES_ENC_DEC_INPUT_ROUND_KEY(7),
AES_ENC_DEC_INPUT_ROUND_KEY(8),
AES_ENC_DEC_INPUT_ROUND_KEY(9),
AES_ENC_DEC_INPUT_ROUND_KEY(10)
: "cc"
);
/* XOR blocks. */
tmp0 = veorq_u8(mask0, tmp0);
tmp1 = veorq_u8(mask1, tmp1);
tmp2 = veorq_u8(mask2, tmp2);
/* Store to output. */
vst1q_u8(dst, tmp0); dst += BlockSize;
vst1q_u8(dst, tmp1); dst += BlockSize;
vst1q_u8(dst, tmp2); dst += BlockSize;
num_blocks -= 3;
} while (num_blocks > 3);
}
while ((--num_blocks) > 0) {
/* Save tweak for xor usage. */
const uint8x16_t mask0 = tweak0;
/* Read block in, XOR with tweak. */
uint8x16_t tmp0 = veorq_u8(mask0, vld1q_u8(src));
src += BlockSize;
/* Actually do encryption, use optimized asm. */
/* Interleave CTR calculations with AES ones, to mask latencies. */
__asm__ __volatile__ (
AES_ENC_ROUND(0, 0) "mov %[high], %[tweak0].d[1]\n"
AES_ENC_ROUND(1, 0) "mov %[low], %[tweak0].d[0]\n"
AES_ENC_ROUND(2, 0) "and %[mask], %[xorv], %[high], asr 63\n"
AES_ENC_ROUND(3, 0) "extr %[high], %[high], %[low], 63\n"
AES_ENC_ROUND(4, 0) "eor %[low], %[mask], %[low], lsl 1\n"
AES_ENC_ROUND(5, 0) "mov %[tweak0].d[1], %[high]\n"
AES_ENC_ROUND(6, 0) "mov %[tweak0].d[0], %[low]\n"
AES_ENC_ROUND(7, 0)
AES_ENC_ROUND(8, 0)
AES_ENC_SECOND_LAST_ROUND(9, 0)
AES_ENC_LAST_ROUND(10, 0)
: AES_ENC_DEC_OUTPUT_ONE_BLOCK(),
AES_ENC_DEC_OUTPUT_ONE_TWEAK(),
XTS_INCREMENT_OUTPUT_HIGH_LOW_MASK()
: XTS_INCREMENT_INPUT_XOR(),
AES_ENC_DEC_INPUT_ROUND_KEY(0),
AES_ENC_DEC_INPUT_ROUND_KEY(1),
AES_ENC_DEC_INPUT_ROUND_KEY(2),
AES_ENC_DEC_INPUT_ROUND_KEY(3),
AES_ENC_DEC_INPUT_ROUND_KEY(4),
AES_ENC_DEC_INPUT_ROUND_KEY(5),
AES_ENC_DEC_INPUT_ROUND_KEY(6),
AES_ENC_DEC_INPUT_ROUND_KEY(7),
AES_ENC_DEC_INPUT_ROUND_KEY(8),
AES_ENC_DEC_INPUT_ROUND_KEY(9),
AES_ENC_DEC_INPUT_ROUND_KEY(10)
: "cc"
);
/* XOR blocks. */
tmp0 = veorq_u8(mask0, tmp0);
/* Store to output. */
vst1q_u8(dst, tmp0);
dst += BlockSize;
}
vst1q_u8(m_tweak, tweak0);
std::memcpy(m_last_block, src, BlockSize);
m_state = State_Processing;
return processed;
}
template<>
size_t XtsModeImpl::ProcessBlocks<AesEncryptor192>(u8 *dst, const u8 *src, size_t num_blocks) {
/* Handle last buffered block. */
size_t processed = (num_blocks - 1) * BlockSize;
if (m_state == State_Processing) {
this->ProcessBlock(dst, m_last_block);
dst += BlockSize;
processed += BlockSize;
}
/* Preload all round keys + iv into neon registers. */
const u8 *keys = static_cast<const AesEncryptor192 *>(m_cipher_ctx)->GetRoundKey();
DECLARE_ROUND_KEY_VAR(0);
DECLARE_ROUND_KEY_VAR(1);
DECLARE_ROUND_KEY_VAR(2);
DECLARE_ROUND_KEY_VAR(3);
DECLARE_ROUND_KEY_VAR(4);
DECLARE_ROUND_KEY_VAR(5);
DECLARE_ROUND_KEY_VAR(6);
DECLARE_ROUND_KEY_VAR(7);
DECLARE_ROUND_KEY_VAR(8);
DECLARE_ROUND_KEY_VAR(9);
DECLARE_ROUND_KEY_VAR(10);
DECLARE_ROUND_KEY_VAR(11);
DECLARE_ROUND_KEY_VAR(12);
uint8x16_t tweak0 = vld1q_u8(m_tweak);
constexpr uint64_t xorv = 0x87ul;
uint64_t high, low, mask;
/* Process three blocks at a time, when possible. */
if (num_blocks > 3) {
/* Multiply tweak twice. */
uint8x16_t tweak1 = MultiplyTweak(tweak0);
uint8x16_t tweak2 = MultiplyTweak(tweak1);
do {
/* Save tweaks for xor usage. */
const uint8x16_t mask0 = tweak0;
const uint8x16_t mask1 = tweak1;
const uint8x16_t mask2 = tweak2;
/* Read blocks in, XOR with tweaks. */
uint8x16_t tmp0 = veorq_u8(mask0, vld1q_u8(src)); src += BlockSize;
uint8x16_t tmp1 = veorq_u8(mask1, vld1q_u8(src)); src += BlockSize;
uint8x16_t tmp2 = veorq_u8(mask2, vld1q_u8(src)); src += BlockSize;
/* Actually do encryption, use optimized asm. */
/* Interleave GF mult calculations with AES ones, to mask latencies. */
__asm__ __volatile__ (
AES_ENC_ROUND(0, 0) "mov %[high], %[tweak2].d[1]\n"
AES_ENC_ROUND(0, 1) "mov %[low], %[tweak2].d[0]\n"
AES_ENC_ROUND(0, 2) "and %[mask], %[xorv], %[high], asr 63\n"
AES_ENC_ROUND(1, 0) "extr %[high], %[high], %[low], 63\n"
AES_ENC_ROUND(1, 1) "eor %[low], %[mask], %[low], lsl 1\n"
AES_ENC_ROUND(1, 2) "mov %[tweak0].d[1], %[high]\n"
AES_ENC_ROUND(2, 0) "mov %[tweak0].d[0], %[low]\n"
AES_ENC_ROUND(2, 1) "and %[mask], %[xorv], %[high], asr 63\n"
AES_ENC_ROUND(2, 2) "extr %[high], %[high], %[low], 63\n"
AES_ENC_ROUND(3, 0) "eor %[low], %[mask], %[low], lsl 1\n"
AES_ENC_ROUND(3, 1) "mov %[tweak1].d[1], %[high]\n"
AES_ENC_ROUND(3, 2) "mov %[tweak1].d[0], %[low]\n"
AES_ENC_ROUND(4, 0) "and %[mask], %[xorv], %[high], asr 63\n"
AES_ENC_ROUND(4, 1) "extr %[high], %[high], %[low], 63\n"
AES_ENC_ROUND(4, 2) "eor %[low], %[mask], %[low], lsl 1\n"
AES_ENC_ROUND(5, 0) "mov %[tweak2].d[1], %[high]\n"
AES_ENC_ROUND(5, 1) "mov %[tweak2].d[0], %[low]\n"
AES_ENC_ROUND(5, 2)
AES_ENC_ROUND(6, 0) AES_ENC_ROUND(6, 1) AES_ENC_ROUND(6, 2)
AES_ENC_ROUND(7, 0) AES_ENC_ROUND(7, 1) AES_ENC_ROUND(7, 2)
AES_ENC_ROUND(8, 0) AES_ENC_ROUND(8, 1) AES_ENC_ROUND(8, 2)
AES_ENC_ROUND(9, 0) AES_ENC_ROUND(9, 1) AES_ENC_ROUND(9, 2)
AES_ENC_ROUND(10, 0) AES_ENC_ROUND(10, 1) AES_ENC_ROUND(10, 2)
AES_ENC_SECOND_LAST_ROUND(11, 0) AES_ENC_SECOND_LAST_ROUND(11, 1) AES_ENC_SECOND_LAST_ROUND(11, 2)
AES_ENC_LAST_ROUND(12, 0) AES_ENC_LAST_ROUND(12, 1) AES_ENC_LAST_ROUND(12, 2)
: AES_ENC_DEC_OUTPUT_THREE_BLOCKS(),
AES_ENC_DEC_OUTPUT_THREE_TWEAKS(),
XTS_INCREMENT_OUTPUT_HIGH_LOW_MASK()
: XTS_INCREMENT_INPUT_XOR(),
AES_ENC_DEC_INPUT_ROUND_KEY(0),
AES_ENC_DEC_INPUT_ROUND_KEY(1),
AES_ENC_DEC_INPUT_ROUND_KEY(2),
AES_ENC_DEC_INPUT_ROUND_KEY(3),
AES_ENC_DEC_INPUT_ROUND_KEY(4),
AES_ENC_DEC_INPUT_ROUND_KEY(5),
AES_ENC_DEC_INPUT_ROUND_KEY(6),
AES_ENC_DEC_INPUT_ROUND_KEY(7),
AES_ENC_DEC_INPUT_ROUND_KEY(8),
AES_ENC_DEC_INPUT_ROUND_KEY(9),
AES_ENC_DEC_INPUT_ROUND_KEY(10),
AES_ENC_DEC_INPUT_ROUND_KEY(11),
AES_ENC_DEC_INPUT_ROUND_KEY(12)
: "cc"
);
/* XOR blocks. */
tmp0 = veorq_u8(mask0, tmp0);
tmp1 = veorq_u8(mask1, tmp1);
tmp2 = veorq_u8(mask2, tmp2);
/* Store to output. */
vst1q_u8(dst, tmp0); dst += BlockSize;
vst1q_u8(dst, tmp1); dst += BlockSize;
vst1q_u8(dst, tmp2); dst += BlockSize;
num_blocks -= 3;
} while (num_blocks > 3);
}
while ((--num_blocks) > 0) {
/* Save tweak for xor usage. */
const uint8x16_t mask0 = tweak0;
/* Read block in, XOR with tweak. */
uint8x16_t tmp0 = veorq_u8(mask0, vld1q_u8(src));
src += BlockSize;
/* Actually do encryption, use optimized asm. */
/* Interleave CTR calculations with AES ones, to mask latencies. */
__asm__ __volatile__ (
AES_ENC_ROUND(0, 0) "mov %[high], %[tweak0].d[1]\n"
AES_ENC_ROUND(1, 0) "mov %[low], %[tweak0].d[0]\n"
AES_ENC_ROUND(2, 0) "and %[mask], %[xorv], %[high], asr 63\n"
AES_ENC_ROUND(3, 0) "extr %[high], %[high], %[low], 63\n"
AES_ENC_ROUND(4, 0) "eor %[low], %[mask], %[low], lsl 1\n"
AES_ENC_ROUND(5, 0) "mov %[tweak0].d[1], %[high]\n"
AES_ENC_ROUND(6, 0) "mov %[tweak0].d[0], %[low]\n"
AES_ENC_ROUND(7, 0)
AES_ENC_ROUND(8, 0)
AES_ENC_ROUND(9, 0)
AES_ENC_ROUND(10, 0)
AES_ENC_SECOND_LAST_ROUND(11, 0)
AES_ENC_LAST_ROUND(12, 0)
: AES_ENC_DEC_OUTPUT_ONE_BLOCK(),
AES_ENC_DEC_OUTPUT_ONE_TWEAK(),
XTS_INCREMENT_OUTPUT_HIGH_LOW_MASK()
: XTS_INCREMENT_INPUT_XOR(),
AES_ENC_DEC_INPUT_ROUND_KEY(0),
AES_ENC_DEC_INPUT_ROUND_KEY(1),
AES_ENC_DEC_INPUT_ROUND_KEY(2),
AES_ENC_DEC_INPUT_ROUND_KEY(3),
AES_ENC_DEC_INPUT_ROUND_KEY(4),
AES_ENC_DEC_INPUT_ROUND_KEY(5),
AES_ENC_DEC_INPUT_ROUND_KEY(6),
AES_ENC_DEC_INPUT_ROUND_KEY(7),
AES_ENC_DEC_INPUT_ROUND_KEY(8),
AES_ENC_DEC_INPUT_ROUND_KEY(9),
AES_ENC_DEC_INPUT_ROUND_KEY(10),
AES_ENC_DEC_INPUT_ROUND_KEY(11),
AES_ENC_DEC_INPUT_ROUND_KEY(12)
: "cc"
);
/* XOR blocks. */
tmp0 = veorq_u8(mask0, tmp0);
/* Store to output. */
vst1q_u8(dst, tmp0);
dst += BlockSize;
}
vst1q_u8(m_tweak, tweak0);
std::memcpy(m_last_block, src, BlockSize);
m_state = State_Processing;
return processed;
}
template<>
size_t XtsModeImpl::ProcessBlocks<AesEncryptor256>(u8 *dst, const u8 *src, size_t num_blocks) {
/* Handle last buffered block. */
size_t processed = (num_blocks - 1) * BlockSize;
if (m_state == State_Processing) {
this->ProcessBlock(dst, m_last_block);
dst += BlockSize;
processed += BlockSize;
}
/* Preload all round keys + iv into neon registers. */
const u8 *keys = static_cast<const AesEncryptor256 *>(m_cipher_ctx)->GetRoundKey();
DECLARE_ROUND_KEY_VAR(0);
DECLARE_ROUND_KEY_VAR(1);
DECLARE_ROUND_KEY_VAR(2);
DECLARE_ROUND_KEY_VAR(3);
DECLARE_ROUND_KEY_VAR(4);
DECLARE_ROUND_KEY_VAR(5);
DECLARE_ROUND_KEY_VAR(6);
DECLARE_ROUND_KEY_VAR(7);
DECLARE_ROUND_KEY_VAR(8);
DECLARE_ROUND_KEY_VAR(9);
DECLARE_ROUND_KEY_VAR(10);
DECLARE_ROUND_KEY_VAR(11);
DECLARE_ROUND_KEY_VAR(12);
DECLARE_ROUND_KEY_VAR(13);
DECLARE_ROUND_KEY_VAR(14);
uint8x16_t tweak0 = vld1q_u8(m_tweak);
constexpr uint64_t xorv = 0x87ul;
uint64_t high, low, mask;
/* Process three blocks at a time, when possible. */
if (num_blocks > 3) {
/* Multiply tweak twice. */
uint8x16_t tweak1 = MultiplyTweak(tweak0);
uint8x16_t tweak2 = MultiplyTweak(tweak1);
do {
/* Save tweaks for xor usage. */
const uint8x16_t mask0 = tweak0;
const uint8x16_t mask1 = tweak1;
const uint8x16_t mask2 = tweak2;
/* Read blocks in, XOR with tweaks. */
uint8x16_t tmp0 = veorq_u8(mask0, vld1q_u8(src)); src += BlockSize;
uint8x16_t tmp1 = veorq_u8(mask1, vld1q_u8(src)); src += BlockSize;
uint8x16_t tmp2 = veorq_u8(mask2, vld1q_u8(src)); src += BlockSize;
/* Actually do encryption, use optimized asm. */
/* Interleave GF mult calculations with AES ones, to mask latencies. */
__asm__ __volatile__ (
AES_ENC_ROUND(0, 0) "mov %[high], %[tweak2].d[1]\n"
AES_ENC_ROUND(0, 1) "mov %[low], %[tweak2].d[0]\n"
AES_ENC_ROUND(0, 2) "mov %[mask], #0x87\n"
AES_ENC_ROUND(1, 0) "and %[mask], %[mask], %[high], asr 63\n"
AES_ENC_ROUND(1, 1) "extr %[high], %[high], %[low], 63\n"
AES_ENC_ROUND(1, 2) "eor %[low], %[mask], %[low], lsl 1\n"
AES_ENC_ROUND(2, 0) "mov %[tweak0].d[1], %[high]\n"
AES_ENC_ROUND(2, 1) "mov %[tweak0].d[0], %[low]\n"
AES_ENC_ROUND(2, 2) "mov %[mask], #0x87\n"
AES_ENC_ROUND(3, 0) "and %[mask], %[mask], %[high], asr 63\n"
AES_ENC_ROUND(3, 1) "extr %[high], %[high], %[low], 63\n"
AES_ENC_ROUND(3, 2) "eor %[low], %[mask], %[low], lsl 1\n"
AES_ENC_ROUND(4, 0) "mov %[tweak1].d[1], %[high]\n"
AES_ENC_ROUND(4, 1) "mov %[tweak1].d[0], %[low]\n"
AES_ENC_ROUND(4, 2) "mov %[mask], #0x87\n"
AES_ENC_ROUND(5, 0) "and %[mask], %[mask], %[high], asr 63\n"
AES_ENC_ROUND(5, 1) "extr %[high], %[high], %[low], 63\n"
AES_ENC_ROUND(5, 2) "eor %[low], %[mask], %[low], lsl 1\n"
AES_ENC_ROUND(6, 0) "mov %[tweak2].d[1], %[high]\n"
AES_ENC_ROUND(6, 1) "mov %[tweak2].d[0], %[low]\n"
AES_ENC_ROUND(6, 2)
AES_ENC_ROUND(7, 0) AES_ENC_ROUND(7, 1) AES_ENC_ROUND(7, 2)
AES_ENC_ROUND(8, 0) AES_ENC_ROUND(8, 1) AES_ENC_ROUND(8, 2)
AES_ENC_ROUND(9, 0) AES_ENC_ROUND(9, 1) AES_ENC_ROUND(9, 2)
AES_ENC_ROUND(10, 0) AES_ENC_ROUND(10, 1) AES_ENC_ROUND(10, 2)
AES_ENC_ROUND(11, 0) AES_ENC_ROUND(11, 1) AES_ENC_ROUND(11, 2)
AES_ENC_ROUND(12, 0) AES_ENC_ROUND(12, 1) AES_ENC_ROUND(12, 2)
AES_ENC_SECOND_LAST_ROUND(13, 0) AES_ENC_SECOND_LAST_ROUND(13, 1) AES_ENC_SECOND_LAST_ROUND(13, 2)
AES_ENC_LAST_ROUND(14, 0) AES_ENC_LAST_ROUND(14, 1) AES_ENC_LAST_ROUND(14, 2)
: AES_ENC_DEC_OUTPUT_THREE_BLOCKS(),
AES_ENC_DEC_OUTPUT_THREE_TWEAKS(),
XTS_INCREMENT_OUTPUT_HIGH_LOW_MASK()
: AES_ENC_DEC_INPUT_ROUND_KEY(0),
AES_ENC_DEC_INPUT_ROUND_KEY(1),
AES_ENC_DEC_INPUT_ROUND_KEY(2),
AES_ENC_DEC_INPUT_ROUND_KEY(3),
AES_ENC_DEC_INPUT_ROUND_KEY(4),
AES_ENC_DEC_INPUT_ROUND_KEY(5),
AES_ENC_DEC_INPUT_ROUND_KEY(6),
AES_ENC_DEC_INPUT_ROUND_KEY(7),
AES_ENC_DEC_INPUT_ROUND_KEY(8),
AES_ENC_DEC_INPUT_ROUND_KEY(9),
AES_ENC_DEC_INPUT_ROUND_KEY(10),
AES_ENC_DEC_INPUT_ROUND_KEY(11),
AES_ENC_DEC_INPUT_ROUND_KEY(12),
AES_ENC_DEC_INPUT_ROUND_KEY(13),
AES_ENC_DEC_INPUT_ROUND_KEY(14)
: "cc"
);
/* XOR blocks. */
tmp0 = veorq_u8(mask0, tmp0);
tmp1 = veorq_u8(mask1, tmp1);
tmp2 = veorq_u8(mask2, tmp2);
/* Store to output. */
vst1q_u8(dst, tmp0); dst += BlockSize;
vst1q_u8(dst, tmp1); dst += BlockSize;
vst1q_u8(dst, tmp2); dst += BlockSize;
num_blocks -= 3;
} while (num_blocks > 3);
}
while ((--num_blocks) > 0) {
/* Save tweak for xor usage. */
const uint8x16_t mask0 = tweak0;
/* Read block in, XOR with tweak. */
uint8x16_t tmp0 = veorq_u8(mask0, vld1q_u8(src));
src += BlockSize;
/* Actually do encryption, use optimized asm. */
/* Interleave CTR calculations with AES ones, to mask latencies. */
__asm__ __volatile__ (
AES_ENC_ROUND(0, 0) "mov %[high], %[tweak0].d[1]\n"
AES_ENC_ROUND(1, 0) "mov %[low], %[tweak0].d[0]\n"
AES_ENC_ROUND(2, 0) "and %[mask], %[xorv], %[high], asr 63\n"
AES_ENC_ROUND(3, 0) "extr %[high], %[high], %[low], 63\n"
AES_ENC_ROUND(4, 0) "eor %[low], %[mask], %[low], lsl 1\n"
AES_ENC_ROUND(5, 0) "mov %[tweak0].d[1], %[high]\n"
AES_ENC_ROUND(6, 0) "mov %[tweak0].d[0], %[low]\n"
AES_ENC_ROUND(7, 0)
AES_ENC_ROUND(8, 0)
AES_ENC_ROUND(9, 0)
AES_ENC_ROUND(10, 0)
AES_ENC_ROUND(11, 0)
AES_ENC_ROUND(12, 0)
AES_ENC_SECOND_LAST_ROUND(13, 0)
AES_ENC_LAST_ROUND(14, 0)
: AES_ENC_DEC_OUTPUT_ONE_BLOCK(),
AES_ENC_DEC_OUTPUT_ONE_TWEAK(),
XTS_INCREMENT_OUTPUT_HIGH_LOW_MASK()
: XTS_INCREMENT_INPUT_XOR(),
AES_ENC_DEC_INPUT_ROUND_KEY(0),
AES_ENC_DEC_INPUT_ROUND_KEY(1),
AES_ENC_DEC_INPUT_ROUND_KEY(2),
AES_ENC_DEC_INPUT_ROUND_KEY(3),
AES_ENC_DEC_INPUT_ROUND_KEY(4),
AES_ENC_DEC_INPUT_ROUND_KEY(5),
AES_ENC_DEC_INPUT_ROUND_KEY(6),
AES_ENC_DEC_INPUT_ROUND_KEY(7),
AES_ENC_DEC_INPUT_ROUND_KEY(8),
AES_ENC_DEC_INPUT_ROUND_KEY(9),
AES_ENC_DEC_INPUT_ROUND_KEY(10),
AES_ENC_DEC_INPUT_ROUND_KEY(11),
AES_ENC_DEC_INPUT_ROUND_KEY(12),
AES_ENC_DEC_INPUT_ROUND_KEY(13),
AES_ENC_DEC_INPUT_ROUND_KEY(14)
: "cc"
);
/* XOR blocks. */
tmp0 = veorq_u8(mask0, tmp0);
/* Store to output. */
vst1q_u8(dst, tmp0);
dst += BlockSize;
}
vst1q_u8(m_tweak, tweak0);
std::memcpy(m_last_block, src, BlockSize);
m_state = State_Processing;
return processed;
}
template<>
size_t XtsModeImpl::ProcessBlocks<AesDecryptor128>(u8 *dst, const u8 *src, size_t num_blocks) {
/* Handle last buffered block. */
size_t processed = (num_blocks - 1) * BlockSize;
if (m_state == State_Processing) {
this->ProcessBlock(dst, m_last_block);
dst += BlockSize;
processed += BlockSize;
}
/* Preload all round keys + iv into neon registers. */
const u8 *keys = static_cast<const AesDecryptor128 *>(m_cipher_ctx)->GetRoundKey();
DECLARE_ROUND_KEY_VAR(0);
DECLARE_ROUND_KEY_VAR(1);
DECLARE_ROUND_KEY_VAR(2);
DECLARE_ROUND_KEY_VAR(3);
DECLARE_ROUND_KEY_VAR(4);
DECLARE_ROUND_KEY_VAR(5);
DECLARE_ROUND_KEY_VAR(6);
DECLARE_ROUND_KEY_VAR(7);
DECLARE_ROUND_KEY_VAR(8);
DECLARE_ROUND_KEY_VAR(9);
DECLARE_ROUND_KEY_VAR(10);
uint8x16_t tweak0 = vld1q_u8(m_tweak);
constexpr uint64_t xorv = 0x87ul;
uint64_t high, low, mask;
/* Process three blocks at a time, when possible. */
if (num_blocks > 3) {
/* Multiply tweak twice. */
uint8x16_t tweak1 = MultiplyTweak(tweak0);
uint8x16_t tweak2 = MultiplyTweak(tweak1);
do {
/* Save tweaks for xor usage. */
const uint8x16_t mask0 = tweak0;
const uint8x16_t mask1 = tweak1;
const uint8x16_t mask2 = tweak2;
/* Read blocks in, XOR with tweaks. */
uint8x16_t tmp0 = veorq_u8(mask0, vld1q_u8(src)); src += BlockSize;
uint8x16_t tmp1 = veorq_u8(mask1, vld1q_u8(src)); src += BlockSize;
uint8x16_t tmp2 = veorq_u8(mask2, vld1q_u8(src)); src += BlockSize;
/* Actually do encryption, use optimized asm. */
/* Interleave GF mult calculations with AES ones, to mask latencies. */
__asm__ __volatile__ (
AES_DEC_ROUND(10, 0) "mov %[high], %[tweak2].d[1]\n"
AES_DEC_ROUND(10, 1) "mov %[low], %[tweak2].d[0]\n"
AES_DEC_ROUND(10, 2) "and %[mask], %[xorv], %[high], asr 63\n"
AES_DEC_ROUND(9, 0) "extr %[high], %[high], %[low], 63\n"
AES_DEC_ROUND(9, 1) "eor %[low], %[mask], %[low], lsl 1\n"
AES_DEC_ROUND(9, 2) "mov %[tweak0].d[1], %[high]\n"
AES_DEC_ROUND(8, 0) "mov %[tweak0].d[0], %[low]\n"
AES_DEC_ROUND(8, 1) "and %[mask], %[xorv], %[high], asr 63\n"
AES_DEC_ROUND(8, 2) "extr %[high], %[high], %[low], 63\n"
AES_DEC_ROUND(7, 0) "eor %[low], %[mask], %[low], lsl 1\n"
AES_DEC_ROUND(7, 1) "mov %[tweak1].d[1], %[high]\n"
AES_DEC_ROUND(7, 2) "mov %[tweak1].d[0], %[low]\n"
AES_DEC_ROUND(6, 0) "and %[mask], %[xorv], %[high], asr 63\n"
AES_DEC_ROUND(6, 1) "extr %[high], %[high], %[low], 63\n"
AES_DEC_ROUND(6, 2) "eor %[low], %[mask], %[low], lsl 1\n"
AES_DEC_ROUND(5, 0) "mov %[tweak2].d[1], %[high]\n"
AES_DEC_ROUND(5, 1) "mov %[tweak2].d[0], %[low]\n"
AES_DEC_ROUND(5, 2)
AES_DEC_ROUND(4, 0) AES_DEC_ROUND(4, 1) AES_DEC_ROUND(4, 2)
AES_DEC_ROUND(3, 0) AES_DEC_ROUND(3, 1) AES_DEC_ROUND(3, 2)
AES_DEC_ROUND(2, 0) AES_DEC_ROUND(2, 1) AES_DEC_ROUND(2, 2)
AES_DEC_SECOND_LAST_ROUND(1, 0) AES_DEC_SECOND_LAST_ROUND(1, 1) AES_DEC_SECOND_LAST_ROUND(1, 2)
AES_DEC_LAST_ROUND(0, 0) AES_DEC_LAST_ROUND(0, 1) AES_DEC_LAST_ROUND(0, 2)
: AES_ENC_DEC_OUTPUT_THREE_BLOCKS(),
AES_ENC_DEC_OUTPUT_THREE_TWEAKS(),
XTS_INCREMENT_OUTPUT_HIGH_LOW_MASK()
: XTS_INCREMENT_INPUT_XOR(),
AES_ENC_DEC_INPUT_ROUND_KEY(0),
AES_ENC_DEC_INPUT_ROUND_KEY(1),
AES_ENC_DEC_INPUT_ROUND_KEY(2),
AES_ENC_DEC_INPUT_ROUND_KEY(3),
AES_ENC_DEC_INPUT_ROUND_KEY(4),
AES_ENC_DEC_INPUT_ROUND_KEY(5),
AES_ENC_DEC_INPUT_ROUND_KEY(6),
AES_ENC_DEC_INPUT_ROUND_KEY(7),
AES_ENC_DEC_INPUT_ROUND_KEY(8),
AES_ENC_DEC_INPUT_ROUND_KEY(9),
AES_ENC_DEC_INPUT_ROUND_KEY(10)
: "cc"
);
/* XOR blocks. */
tmp0 = veorq_u8(mask0, tmp0);
tmp1 = veorq_u8(mask1, tmp1);
tmp2 = veorq_u8(mask2, tmp2);
/* Store to output. */
vst1q_u8(dst, tmp0); dst += BlockSize;
vst1q_u8(dst, tmp1); dst += BlockSize;
vst1q_u8(dst, tmp2); dst += BlockSize;
num_blocks -= 3;
} while (num_blocks > 3);
}
while ((--num_blocks) > 0) {
/* Save tweak for xor usage. */
const uint8x16_t mask0 = tweak0;
/* Read block in, XOR with tweak. */
uint8x16_t tmp0 = veorq_u8(mask0, vld1q_u8(src));
src += BlockSize;
/* Actually do encryption, use optimized asm. */
/* Interleave CTR calculations with AES ones, to mask latencies. */
__asm__ __volatile__ (
AES_DEC_ROUND(10, 0) "mov %[high], %[tweak0].d[1]\n"
AES_DEC_ROUND(9, 0) "mov %[low], %[tweak0].d[0]\n"
AES_DEC_ROUND(8, 0) "and %[mask], %[xorv], %[high], asr 63\n"
AES_DEC_ROUND(7, 0) "extr %[high], %[high], %[low], 63\n"
AES_DEC_ROUND(6, 0) "eor %[low], %[mask], %[low], lsl 1\n"
AES_DEC_ROUND(5, 0) "mov %[tweak0].d[1], %[high]\n"
AES_DEC_ROUND(4, 0) "mov %[tweak0].d[0], %[low]\n"
AES_DEC_ROUND(3, 0)
AES_DEC_ROUND(2, 0)
AES_DEC_SECOND_LAST_ROUND(1, 0)
AES_DEC_LAST_ROUND(0, 0)
: AES_ENC_DEC_OUTPUT_ONE_BLOCK(),
AES_ENC_DEC_OUTPUT_ONE_TWEAK(),
XTS_INCREMENT_OUTPUT_HIGH_LOW_MASK()
: XTS_INCREMENT_INPUT_XOR(),
AES_ENC_DEC_INPUT_ROUND_KEY(0),
AES_ENC_DEC_INPUT_ROUND_KEY(1),
AES_ENC_DEC_INPUT_ROUND_KEY(2),
AES_ENC_DEC_INPUT_ROUND_KEY(3),
AES_ENC_DEC_INPUT_ROUND_KEY(4),
AES_ENC_DEC_INPUT_ROUND_KEY(5),
AES_ENC_DEC_INPUT_ROUND_KEY(6),
AES_ENC_DEC_INPUT_ROUND_KEY(7),
AES_ENC_DEC_INPUT_ROUND_KEY(8),
AES_ENC_DEC_INPUT_ROUND_KEY(9),
AES_ENC_DEC_INPUT_ROUND_KEY(10)
: "cc"
);
/* XOR blocks. */
tmp0 = veorq_u8(mask0, tmp0);
/* Store to output. */
vst1q_u8(dst, tmp0);
dst += BlockSize;
}
vst1q_u8(m_tweak, tweak0);
std::memcpy(m_last_block, src, BlockSize);
m_state = State_Processing;
return processed;
}
template<>
size_t XtsModeImpl::ProcessBlocks<AesDecryptor192>(u8 *dst, const u8 *src, size_t num_blocks) {
/* Handle last buffered block. */
size_t processed = (num_blocks - 1) * BlockSize;
if (m_state == State_Processing) {
this->ProcessBlock(dst, m_last_block);
dst += BlockSize;
processed += BlockSize;
}
/* Preload all round keys + iv into neon registers. */
const u8 *keys = static_cast<const AesDecryptor192 *>(m_cipher_ctx)->GetRoundKey();
DECLARE_ROUND_KEY_VAR(0);
DECLARE_ROUND_KEY_VAR(1);
DECLARE_ROUND_KEY_VAR(2);
DECLARE_ROUND_KEY_VAR(3);
DECLARE_ROUND_KEY_VAR(4);
DECLARE_ROUND_KEY_VAR(5);
DECLARE_ROUND_KEY_VAR(6);
DECLARE_ROUND_KEY_VAR(7);
DECLARE_ROUND_KEY_VAR(8);
DECLARE_ROUND_KEY_VAR(9);
DECLARE_ROUND_KEY_VAR(10);
DECLARE_ROUND_KEY_VAR(11);
DECLARE_ROUND_KEY_VAR(12);
uint8x16_t tweak0 = vld1q_u8(m_tweak);
constexpr uint64_t xorv = 0x87ul;
uint64_t high, low, mask;
/* Process three blocks at a time, when possible. */
if (num_blocks > 3) {
/* Multiply tweak twice. */
uint8x16_t tweak1 = MultiplyTweak(tweak0);
uint8x16_t tweak2 = MultiplyTweak(tweak1);
do {
/* Save tweaks for xor usage. */
const uint8x16_t mask0 = tweak0;
const uint8x16_t mask1 = tweak1;
const uint8x16_t mask2 = tweak2;
/* Read blocks in, XOR with tweaks. */
uint8x16_t tmp0 = veorq_u8(mask0, vld1q_u8(src)); src += BlockSize;
uint8x16_t tmp1 = veorq_u8(mask1, vld1q_u8(src)); src += BlockSize;
uint8x16_t tmp2 = veorq_u8(mask2, vld1q_u8(src)); src += BlockSize;
/* Actually do encryption, use optimized asm. */
/* Interleave GF mult calculations with AES ones, to mask latencies. */
__asm__ __volatile__ (
AES_DEC_ROUND(12, 0) "mov %[high], %[tweak2].d[1]\n"
AES_DEC_ROUND(12, 1) "mov %[low], %[tweak2].d[0]\n"
AES_DEC_ROUND(12, 2) "and %[mask], %[xorv], %[high], asr 63\n"
AES_DEC_ROUND(11, 0) "extr %[high], %[high], %[low], 63\n"
AES_DEC_ROUND(11, 1) "eor %[low], %[mask], %[low], lsl 1\n"
AES_DEC_ROUND(11, 2) "mov %[tweak0].d[1], %[high]\n"
AES_DEC_ROUND(10, 0) "mov %[tweak0].d[0], %[low]\n"
AES_DEC_ROUND(10, 1) "and %[mask], %[xorv], %[high], asr 63\n"
AES_DEC_ROUND(10, 2) "extr %[high], %[high], %[low], 63\n"
AES_DEC_ROUND(9, 0) "eor %[low], %[mask], %[low], lsl 1\n"
AES_DEC_ROUND(9, 1) "mov %[tweak1].d[1], %[high]\n"
AES_DEC_ROUND(9, 2) "mov %[tweak1].d[0], %[low]\n"
AES_DEC_ROUND(8, 0) "and %[mask], %[xorv], %[high], asr 63\n"
AES_DEC_ROUND(8, 1) "extr %[high], %[high], %[low], 63\n"
AES_DEC_ROUND(8, 2) "eor %[low], %[mask], %[low], lsl 1\n"
AES_DEC_ROUND(7, 0) "mov %[tweak2].d[1], %[high]\n"
AES_DEC_ROUND(7, 1) "mov %[tweak2].d[0], %[low]\n"
AES_DEC_ROUND(7, 2)
AES_DEC_ROUND(6, 0) AES_DEC_ROUND(6, 1) AES_DEC_ROUND(6, 2)
AES_DEC_ROUND(5, 0) AES_DEC_ROUND(5, 1) AES_DEC_ROUND(5, 2)
AES_DEC_ROUND(4, 0) AES_DEC_ROUND(4, 1) AES_DEC_ROUND(4, 2)
AES_DEC_ROUND(3, 0) AES_DEC_ROUND(3, 1) AES_DEC_ROUND(3, 2)
AES_DEC_ROUND(2, 0) AES_DEC_ROUND(2, 1) AES_DEC_ROUND(2, 2)
AES_DEC_SECOND_LAST_ROUND(1, 0) AES_DEC_SECOND_LAST_ROUND(1, 1) AES_DEC_SECOND_LAST_ROUND(1, 2)
AES_DEC_LAST_ROUND(0, 0) AES_DEC_LAST_ROUND(0, 1) AES_DEC_LAST_ROUND(0, 2)
: AES_ENC_DEC_OUTPUT_THREE_BLOCKS(),
AES_ENC_DEC_OUTPUT_THREE_TWEAKS(),
XTS_INCREMENT_OUTPUT_HIGH_LOW_MASK()
: XTS_INCREMENT_INPUT_XOR(),
AES_ENC_DEC_INPUT_ROUND_KEY(0),
AES_ENC_DEC_INPUT_ROUND_KEY(1),
AES_ENC_DEC_INPUT_ROUND_KEY(2),
AES_ENC_DEC_INPUT_ROUND_KEY(3),
AES_ENC_DEC_INPUT_ROUND_KEY(4),
AES_ENC_DEC_INPUT_ROUND_KEY(5),
AES_ENC_DEC_INPUT_ROUND_KEY(6),
AES_ENC_DEC_INPUT_ROUND_KEY(7),
AES_ENC_DEC_INPUT_ROUND_KEY(8),
AES_ENC_DEC_INPUT_ROUND_KEY(9),
AES_ENC_DEC_INPUT_ROUND_KEY(10),
AES_ENC_DEC_INPUT_ROUND_KEY(11),
AES_ENC_DEC_INPUT_ROUND_KEY(12)
: "cc"
);
/* XOR blocks. */
tmp0 = veorq_u8(mask0, tmp0);
tmp1 = veorq_u8(mask1, tmp1);
tmp2 = veorq_u8(mask2, tmp2);
/* Store to output. */
vst1q_u8(dst, tmp0); dst += BlockSize;
vst1q_u8(dst, tmp1); dst += BlockSize;
vst1q_u8(dst, tmp2); dst += BlockSize;
num_blocks -= 3;
} while (num_blocks > 3);
}
while ((--num_blocks) > 0) {
/* Save tweak for xor usage. */
const uint8x16_t mask0 = tweak0;
/* Read block in, XOR with tweak. */
uint8x16_t tmp0 = veorq_u8(mask0, vld1q_u8(src));
src += BlockSize;
/* Actually do encryption, use optimized asm. */
/* Interleave CTR calculations with AES ones, to mask latencies. */
__asm__ __volatile__ (
AES_DEC_ROUND(12, 0) "mov %[high], %[tweak0].d[1]\n"
AES_DEC_ROUND(11, 0) "mov %[low], %[tweak0].d[0]\n"
AES_DEC_ROUND(10, 0) "and %[mask], %[xorv], %[high], asr 63\n"
AES_DEC_ROUND(9, 0) "extr %[high], %[high], %[low], 63\n"
AES_DEC_ROUND(8, 0) "eor %[low], %[mask], %[low], lsl 1\n"
AES_DEC_ROUND(7, 0) "mov %[tweak0].d[1], %[high]\n"
AES_DEC_ROUND(6, 0) "mov %[tweak0].d[0], %[low]\n"
AES_DEC_ROUND(5, 0)
AES_DEC_ROUND(4, 0)
AES_DEC_ROUND(3, 0)
AES_DEC_ROUND(2, 0)
AES_DEC_SECOND_LAST_ROUND(1, 0)
AES_DEC_LAST_ROUND(0, 0)
: AES_ENC_DEC_OUTPUT_ONE_BLOCK(),
AES_ENC_DEC_OUTPUT_ONE_TWEAK(),
XTS_INCREMENT_OUTPUT_HIGH_LOW_MASK()
: XTS_INCREMENT_INPUT_XOR(),
AES_ENC_DEC_INPUT_ROUND_KEY(0),
AES_ENC_DEC_INPUT_ROUND_KEY(1),
AES_ENC_DEC_INPUT_ROUND_KEY(2),
AES_ENC_DEC_INPUT_ROUND_KEY(3),
AES_ENC_DEC_INPUT_ROUND_KEY(4),
AES_ENC_DEC_INPUT_ROUND_KEY(5),
AES_ENC_DEC_INPUT_ROUND_KEY(6),
AES_ENC_DEC_INPUT_ROUND_KEY(7),
AES_ENC_DEC_INPUT_ROUND_KEY(8),
AES_ENC_DEC_INPUT_ROUND_KEY(9),
AES_ENC_DEC_INPUT_ROUND_KEY(10),
AES_ENC_DEC_INPUT_ROUND_KEY(11),
AES_ENC_DEC_INPUT_ROUND_KEY(12)
: "cc"
);
/* XOR blocks. */
tmp0 = veorq_u8(mask0, tmp0);
/* Store to output. */
vst1q_u8(dst, tmp0);
dst += BlockSize;
}
vst1q_u8(m_tweak, tweak0);
std::memcpy(m_last_block, src, BlockSize);
m_state = State_Processing;
return processed;
}
template<>
size_t XtsModeImpl::ProcessBlocks<AesDecryptor256>(u8 *dst, const u8 *src, size_t num_blocks) {
/* Handle last buffered block. */
size_t processed = (num_blocks - 1) * BlockSize;
if (m_state == State_Processing) {
this->ProcessBlock(dst, m_last_block);
dst += BlockSize;
processed += BlockSize;
}
/* Preload all round keys + iv into neon registers. */
const u8 *keys = static_cast<const AesDecryptor256 *>(m_cipher_ctx)->GetRoundKey();
DECLARE_ROUND_KEY_VAR(0);
DECLARE_ROUND_KEY_VAR(1);
DECLARE_ROUND_KEY_VAR(2);
DECLARE_ROUND_KEY_VAR(3);
DECLARE_ROUND_KEY_VAR(4);
DECLARE_ROUND_KEY_VAR(5);
DECLARE_ROUND_KEY_VAR(6);
DECLARE_ROUND_KEY_VAR(7);
DECLARE_ROUND_KEY_VAR(8);
DECLARE_ROUND_KEY_VAR(9);
DECLARE_ROUND_KEY_VAR(10);
DECLARE_ROUND_KEY_VAR(11);
DECLARE_ROUND_KEY_VAR(12);
DECLARE_ROUND_KEY_VAR(13);
DECLARE_ROUND_KEY_VAR(14);
uint8x16_t tweak0 = vld1q_u8(m_tweak);
constexpr uint64_t xorv = 0x87ul;
uint64_t high, low, mask;
/* Process three blocks at a time, when possible. */
if (num_blocks > 3) {
/* Multiply tweak twice. */
uint8x16_t tweak1 = MultiplyTweak(tweak0);
uint8x16_t tweak2 = MultiplyTweak(tweak1);
do {
/* Save tweaks for xor usage. */
const uint8x16_t mask0 = tweak0;
const uint8x16_t mask1 = tweak1;
const uint8x16_t mask2 = tweak2;
/* Read blocks in, XOR with tweaks. */
uint8x16_t tmp0 = veorq_u8(mask0, vld1q_u8(src)); src += BlockSize;
uint8x16_t tmp1 = veorq_u8(mask1, vld1q_u8(src)); src += BlockSize;
uint8x16_t tmp2 = veorq_u8(mask2, vld1q_u8(src)); src += BlockSize;
/* Actually do encryption, use optimized asm. */
/* Interleave GF mult calculations with AES ones, to mask latencies. */
__asm__ __volatile__ (
AES_DEC_ROUND(14, 0) "mov %[high], %[tweak2].d[1]\n"
AES_DEC_ROUND(14, 1) "mov %[low], %[tweak2].d[0]\n"
AES_DEC_ROUND(14, 2) "mov %[mask], 0x87\n"
AES_DEC_ROUND(13, 0) "and %[mask], %[mask], %[high], asr 63\n"
AES_DEC_ROUND(13, 1) "extr %[high], %[high], %[low], 63\n"
AES_DEC_ROUND(13, 2) "eor %[low], %[mask], %[low], lsl 1\n"
AES_DEC_ROUND(12, 0) "mov %[tweak0].d[1], %[high]\n"
AES_DEC_ROUND(12, 1) "mov %[tweak0].d[0], %[low]\n"
AES_DEC_ROUND(12, 2) "mov %[mask], 0x87\n"
AES_DEC_ROUND(11, 0) "and %[mask], %[mask], %[high], asr 63\n"
AES_DEC_ROUND(11, 1) "extr %[high], %[high], %[low], 63\n"
AES_DEC_ROUND(11, 2) "eor %[low], %[mask], %[low], lsl 1\n"
AES_DEC_ROUND(10, 0) "mov %[tweak1].d[1], %[high]\n"
AES_DEC_ROUND(10, 1) "mov %[tweak1].d[0], %[low]\n"
AES_DEC_ROUND(10, 2) "mov %[mask], 0x87\n"
AES_DEC_ROUND(9, 0) "and %[mask], %[mask], %[high], asr 63\n"
AES_DEC_ROUND(9, 1) "extr %[high], %[high], %[low], 63\n"
AES_DEC_ROUND(9, 2) "eor %[low], %[mask], %[low], lsl 1\n"
AES_DEC_ROUND(8, 0) "mov %[tweak2].d[1], %[high]\n"
AES_DEC_ROUND(8, 1) "mov %[tweak2].d[0], %[low]\n"
AES_DEC_ROUND(8, 2)
AES_DEC_ROUND(7, 0) AES_DEC_ROUND(7, 1) AES_DEC_ROUND(7, 2)
AES_DEC_ROUND(6, 0) AES_DEC_ROUND(6, 1) AES_DEC_ROUND(6, 2)
AES_DEC_ROUND(5, 0) AES_DEC_ROUND(5, 1) AES_DEC_ROUND(5, 2)
AES_DEC_ROUND(4, 0) AES_DEC_ROUND(4, 1) AES_DEC_ROUND(4, 2)
AES_DEC_ROUND(3, 0) AES_DEC_ROUND(3, 1) AES_DEC_ROUND(3, 2)
AES_DEC_ROUND(2, 0) AES_DEC_ROUND(2, 1) AES_DEC_ROUND(2, 2)
AES_DEC_SECOND_LAST_ROUND(1, 0) AES_DEC_SECOND_LAST_ROUND(1, 1) AES_DEC_SECOND_LAST_ROUND(1, 2)
AES_DEC_LAST_ROUND(0, 0) AES_DEC_LAST_ROUND(0, 1) AES_DEC_LAST_ROUND(0, 2)
: AES_ENC_DEC_OUTPUT_THREE_BLOCKS(),
AES_ENC_DEC_OUTPUT_THREE_TWEAKS(),
XTS_INCREMENT_OUTPUT_HIGH_LOW_MASK()
: AES_ENC_DEC_INPUT_ROUND_KEY(0),
AES_ENC_DEC_INPUT_ROUND_KEY(1),
AES_ENC_DEC_INPUT_ROUND_KEY(2),
AES_ENC_DEC_INPUT_ROUND_KEY(3),
AES_ENC_DEC_INPUT_ROUND_KEY(4),
AES_ENC_DEC_INPUT_ROUND_KEY(5),
AES_ENC_DEC_INPUT_ROUND_KEY(6),
AES_ENC_DEC_INPUT_ROUND_KEY(7),
AES_ENC_DEC_INPUT_ROUND_KEY(8),
AES_ENC_DEC_INPUT_ROUND_KEY(9),
AES_ENC_DEC_INPUT_ROUND_KEY(10),
AES_ENC_DEC_INPUT_ROUND_KEY(11),
AES_ENC_DEC_INPUT_ROUND_KEY(12),
AES_ENC_DEC_INPUT_ROUND_KEY(13),
AES_ENC_DEC_INPUT_ROUND_KEY(14)
: "cc"
);
/* XOR blocks. */
tmp0 = veorq_u8(mask0, tmp0);
tmp1 = veorq_u8(mask1, tmp1);
tmp2 = veorq_u8(mask2, tmp2);
/* Store to output. */
vst1q_u8(dst, tmp0); dst += BlockSize;
vst1q_u8(dst, tmp1); dst += BlockSize;
vst1q_u8(dst, tmp2); dst += BlockSize;
num_blocks -= 3;
} while (num_blocks > 3);
}
while ((--num_blocks) > 0) {
/* Save tweak for xor usage. */
const uint8x16_t mask0 = tweak0;
/* Read block in, XOR with tweak. */
uint8x16_t tmp0 = veorq_u8(mask0, vld1q_u8(src));
src += BlockSize;
/* Actually do encryption, use optimized asm. */
/* Interleave CTR calculations with AES ones, to mask latencies. */
__asm__ __volatile__ (
AES_DEC_ROUND(14, 0) "mov %[high], %[tweak0].d[1]\n"
AES_DEC_ROUND(13, 0) "mov %[low], %[tweak0].d[0]\n"
AES_DEC_ROUND(12, 0) "and %[mask], %[xorv], %[high], asr 63\n"
AES_DEC_ROUND(11, 0) "extr %[high], %[high], %[low], 63\n"
AES_DEC_ROUND(10, 0) "eor %[low], %[mask], %[low], lsl 1\n"
AES_DEC_ROUND(9, 0) "mov %[tweak0].d[1], %[high]\n"
AES_DEC_ROUND(8, 0) "mov %[tweak0].d[0], %[low]\n"
AES_DEC_ROUND(7, 0)
AES_DEC_ROUND(6, 0)
AES_DEC_ROUND(5, 0)
AES_DEC_ROUND(4, 0)
AES_DEC_ROUND(3, 0)
AES_DEC_ROUND(2, 0)
AES_DEC_SECOND_LAST_ROUND(1, 0)
AES_DEC_LAST_ROUND(0, 0)
: AES_ENC_DEC_OUTPUT_ONE_BLOCK(),
AES_ENC_DEC_OUTPUT_ONE_TWEAK(),
XTS_INCREMENT_OUTPUT_HIGH_LOW_MASK()
: XTS_INCREMENT_INPUT_XOR(),
AES_ENC_DEC_INPUT_ROUND_KEY(0),
AES_ENC_DEC_INPUT_ROUND_KEY(1),
AES_ENC_DEC_INPUT_ROUND_KEY(2),
AES_ENC_DEC_INPUT_ROUND_KEY(3),
AES_ENC_DEC_INPUT_ROUND_KEY(4),
AES_ENC_DEC_INPUT_ROUND_KEY(5),
AES_ENC_DEC_INPUT_ROUND_KEY(6),
AES_ENC_DEC_INPUT_ROUND_KEY(7),
AES_ENC_DEC_INPUT_ROUND_KEY(8),
AES_ENC_DEC_INPUT_ROUND_KEY(9),
AES_ENC_DEC_INPUT_ROUND_KEY(10),
AES_ENC_DEC_INPUT_ROUND_KEY(11),
AES_ENC_DEC_INPUT_ROUND_KEY(12),
AES_ENC_DEC_INPUT_ROUND_KEY(13),
AES_ENC_DEC_INPUT_ROUND_KEY(14)
: "cc"
);
/* XOR blocks. */
tmp0 = veorq_u8(mask0, tmp0);
/* Store to output. */
vst1q_u8(dst, tmp0);
dst += BlockSize;
}
vst1q_u8(m_tweak, tweak0);
std::memcpy(m_last_block, src, BlockSize);
m_state = State_Processing;
return processed;
}
}
#else
/* TODO: Non-EL0 implementation. */
namespace ams::crypto::impl {
}
#endif
| 53,908
|
C++
|
.cpp
| 1,040
| 36.545192
| 196
| 0.488875
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,094
|
crypto_gcm_mode_impl.arch.arm64.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/crypto/impl/crypto_gcm_mode_impl.arch.arm64.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <vapours.hpp>
#if defined(ATMOSPHERE_IS_STRATOSPHERE)
/* TODO: EL0 implementation. */
namespace ams::crypto::impl {
}
#else
/* EL1+ implementation. */
namespace ams::crypto::impl {
namespace {
constexpr u64 GetMultiplyFactor(u8 value) {
constexpr size_t Shift = BITSIZEOF(u8) - 1;
constexpr u8 Mask = (1u << Shift);
return (value & Mask) >> Shift;
}
/* TODO: Big endian support, eventually? */
constexpr void GaloisShiftLeft(u64 *block) {
/* Shift the block left by one. */
block[1] <<= 1;
block[1] |= (block[0] & (static_cast<u64>(1) << (BITSIZEOF(u64) - 1))) >> (BITSIZEOF(u64) - 1);
block[0] <<= 1;
}
constexpr u8 GaloisShiftRight(u64 *block) {
/* Determine the mask to return. */
constexpr u8 GaloisFieldMask = 0xE1;
const u8 mask = (block[0] & 1) * GaloisFieldMask;
/* Shift the block right by one. */
block[0] >>= 1;
block[0] |= (block[1] & 1) << (BITSIZEOF(u64) - 1);
block[1] >>= 1;
/* Return the mask. */
return mask;
}
/* Multiply two 128-bit numbers X, Y in the GF(128) Galois Field. */
void GaloisFieldMult(void *dst, const void *x, const void *y) {
/* Our block size is 16 bytes (for a 128-bit integer). */
constexpr size_t BlockSize = 16;
constexpr size_t FieldSize = 128;
/* Declare work blocks for us to store temporary values. */
u8 x_block[BlockSize];
u8 y_block[BlockSize];
u8 out[BlockSize];
/* Declare 64-bit pointers for our convenience. */
u64 *x_64 = static_cast<u64 *>(static_cast<void *>(x_block));
u64 *y_64 = static_cast<u64 *>(static_cast<void *>(y_block));
u64 *out_64 = static_cast<u64 *>(static_cast<void *>(out));
/* Initialize our work blocks. */
for (size_t i = 0; i < BlockSize; ++i) {
x_block[i] = static_cast<const u8 *>(x)[BlockSize - 1 - i];
y_block[i] = static_cast<const u8 *>(y)[BlockSize - 1 - i];
out[i] = 0;
}
/* Perform multiplication on each bit in y. */
for (size_t i = 0; i < FieldSize; ++i) {
/* Get the multiply factor for this bit. */
const auto y_mult = GetMultiplyFactor(y_block[BlockSize - 1]);
/* Multiply x by the factor. */
out_64[0] ^= x_64[0] * y_mult;
out_64[1] ^= x_64[1] * y_mult;
/* Shift left y by one. */
GaloisShiftLeft(y_64);
/* Shift right x by one, and mask appropriately. */
const u8 x_mask = GaloisShiftRight(x_64);
x_block[BlockSize - 1] ^= x_mask;
}
/* Copy out our result. */
for (size_t i = 0; i < BlockSize; ++i) {
static_cast<u8 *>(dst)[i] = out[BlockSize - 1 - i];
}
}
}
template<class BlockCipher>
void GcmModeImpl<BlockCipher>::Initialize(const BlockCipher *block_cipher) {
/* Set member variables. */
m_block_cipher = block_cipher;
m_cipher_func = std::addressof(GcmModeImpl<BlockCipher>::ProcessBlock);
/* Pre-calculate values to speed up galois field multiplications later. */
this->InitializeHashKey();
/* Note that we're initialized. */
m_state = State_Initialized;
}
template<class BlockCipher>
void GcmModeImpl<BlockCipher>::Reset(const void *iv, size_t iv_size) {
/* Validate pre-conditions. */
AMS_ASSERT(m_state >= State_Initialized);
/* Reset blocks. */
m_block_x.block_128.Clear();
m_block_tmp.block_128.Clear();
/* Clear sizes. */
m_aad_size = 0;
m_msg_size = 0;
m_aad_remaining = 0;
m_msg_remaining = 0;
/* Update our state. */
m_state = State_ProcessingAad;
/* Set our iv. */
if (iv_size == 12) {
/* If our iv is the correct size, simply copy in the iv, and set the magic bit. */
std::memcpy(std::addressof(m_block_ek0), iv, iv_size);
util::StoreBigEndian(m_block_ek0.block_32 + 3, static_cast<u32>(1));
} else {
/* Clear our ek0 block. */
m_block_ek0.block_128.Clear();
/* Update using the iv as aad. */
this->UpdateAad(iv, iv_size);
/* Treat the iv as fake msg for the mac that will become our iv. */
m_msg_size = m_aad_size;
m_aad_size = 0;
/* Compute a non-final mac. */
this->ComputeMac(false);
/* Set our ek0 block to our calculated mac block. */
m_block_ek0 = m_block_x;
/* Clear our calculated mac block. */
m_block_x.block_128.Clear();
/* Reset our state. */
m_msg_size = 0;
m_aad_size = 0;
m_msg_remaining = 0;
m_aad_remaining = 0;
}
/* Set the working block to the iv. */
m_block_ek = m_block_ek0;
}
template<class BlockCipher>
void GcmModeImpl<BlockCipher>::UpdateAad(const void *aad, size_t aad_size) {
/* Validate pre-conditions. */
AMS_ASSERT(m_state == State_ProcessingAad);
AMS_ASSERT(m_msg_size == 0);
/* Update our aad size. */
m_aad_size += aad_size;
/* Define a working tracker variable. */
const u8 *cur_aad = static_cast<const u8 *>(aad);
/* Process any leftover aad data from a previous invocation. */
if (m_aad_remaining > 0) {
while (aad_size > 0) {
/* Copy in a byte of the aad to our partial block. */
m_block_x.block_8[m_aad_remaining] ^= *(cur_aad++);
/* Note that we consumed a byte. */
--aad_size;
/* Increment our partial block size. */
m_aad_remaining = (m_aad_remaining + 1) % BlockSize;
/* If we have a complete block, process it and move onward. */
GaloisFieldMult(std::addressof(m_block_x), std::addressof(m_block_x), std::addressof(m_h_mult_blocks[0]));
}
}
/* Process as many blocks as we can. */
while (aad_size >= BlockSize) {
/* Xor the current aad into our work block. */
for (size_t i = 0; i < BlockSize; ++i) {
m_block_x.block_8[i] ^= *(cur_aad++);
}
/* Multiply the blocks in our galois field. */
GaloisFieldMult(std::addressof(m_block_x), std::addressof(m_block_x), std::addressof(m_h_mult_blocks[0]));
/* Note that we've processed a block. */
aad_size -= BlockSize;
}
/* Update our state with whatever aad is left over. */
if (aad_size > 0) {
/* Note how much left over data we have. */
m_aad_remaining = static_cast<u32>(aad_size);
/* Xor the data in. */
for (size_t i = 0; i < aad_size; ++i) {
m_block_x.block_8[i] ^= *(cur_aad++);
}
}
}
/* TODO: template<class BlockCipher> size_t GcmModeImpl<BlockCipher>::UpdateEncrypt(void *dst, size_t dst_size, const void *src, size_t src_size); */
/* TODO: template<class BlockCipher> size_t GcmModeImpl<BlockCipher>::UpdateDecrypt(void *dst, size_t dst_size, const void *src, size_t src_size); */
template<class BlockCipher>
void GcmModeImpl<BlockCipher>::GetMac(void *dst, size_t dst_size) {
/* Validate pre-conditions. */
AMS_ASSERT(State_ProcessingAad <= m_state && m_state <= State_Done);
AMS_ASSERT(dst != nullptr);
AMS_ASSERT(dst_size >= MacSize);
AMS_ASSERT(m_aad_remaining == 0);
AMS_ASSERT(m_msg_remaining == 0);
AMS_UNUSED(dst_size);
/* If we haven't already done so, compute the final mac. */
if (m_state != State_Done) {
this->ComputeMac(true);
m_state = State_Done;
}
static_assert(sizeof(m_block_x) == MacSize);
std::memcpy(dst, std::addressof(m_block_x), MacSize);
}
template<class BlockCipher>
void GcmModeImpl<BlockCipher>::InitializeHashKey() {
/* We want to encrypt an empty block to use for intermediate calculations. */
/* NOTE: Non-EL1 implementations will do multiple encryptions ahead of time, */
/* to speed up galois field arithmetic. */
constexpr const Block EmptyBlock = {};
this->ProcessBlock(std::addressof(m_h_mult_blocks[0]), std::addressof(EmptyBlock), m_block_cipher);
}
template<class BlockCipher>
void GcmModeImpl<BlockCipher>::ComputeMac(bool encrypt) {
/* If we have leftover data, process it. */
if (m_aad_remaining > 0 || m_msg_remaining > 0) {
GaloisFieldMult(std::addressof(m_block_x), std::addressof(m_block_x), std::addressof(m_h_mult_blocks[0]));
}
/* Setup the last block. */
Block last_block = Block{ .block_128 = { m_msg_size, m_aad_size } };
/* Multiply the last block by 8 to account for bit vs byte sizes. */
static_assert(AMS_OFFSETOF(Block128, hi) == 0);
GaloisShiftLeft(std::addressof(last_block.block_128.hi));
GaloisShiftLeft(std::addressof(last_block.block_128.hi));
GaloisShiftLeft(std::addressof(last_block.block_128.hi));
/* Xor the data in. */
for (size_t i = 0; i < BlockSize; ++i) {
m_block_x.block_8[BlockSize - 1 - i] ^= last_block.block_8[i];
}
/* Perform the final multiplication. */
GaloisFieldMult(std::addressof(m_block_x), std::addressof(m_block_x), std::addressof(m_h_mult_blocks[0]));
/* If we need to do an encryption, do so. */
if (encrypt) {
/* Encrypt the iv. */
u8 enc_result[BlockSize];
this->ProcessBlock(enc_result, std::addressof(m_block_ek0), m_block_cipher);
/* Xor the iv in. */
for (size_t i = 0; i < BlockSize; ++i) {
m_block_x.block_8[i] ^= enc_result[i];
}
}
}
/* Explicitly instantiate the valid template classes. */
template class GcmModeImpl<AesEncryptor128>;
}
#endif
| 11,158
|
C++
|
.cpp
| 241
| 36.024896
| 153
| 0.560173
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,095
|
crypto_aes_impl.arch.arm64.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/crypto/impl/crypto_aes_impl.arch.arm64.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <vapours.hpp>
#if defined(ATMOSPHERE_IS_STRATOSPHERE)
#include <arm_neon.h>
#endif
namespace ams::crypto::impl {
#if defined(ATMOSPHERE_IS_STRATOSPHERE)
namespace {
/* Helper macros to setup for inline AES asm */
#define AES_ENC_DEC_SETUP_VARS() \
const auto *ctx = reinterpret_cast<const RoundKeyHelper<KeySize> *>(m_round_keys); \
static_assert(sizeof(*ctx) == sizeof(m_round_keys)); \
\
uint8x16_t tmp = vld1q_u8((const uint8_t *)src); \
uint8x16_t tmp2
#define AES_ENC_DEC_OUTPUT_VARS() \
[tmp]"+w"(tmp), [tmp2]"=w"(tmp2)
#define AES_ENC_DEC_STORE_RESULT() \
vst1q_u8((uint8_t *)dst, tmp)
/* Helper macros to do AES encryption, via inline asm. */
#define AES_ENC_ROUND(n) \
"ldr %q[tmp2], %[round_key_" #n "]\n" \
"aese %[tmp].16b, %[tmp2].16b\n" \
"aesmc %[tmp].16b, %[tmp].16b\n"
#define AES_ENC_FINAL_ROUND() \
"ldr %q[tmp2], %[round_key_second_last]\n" \
"aese %[tmp].16b, %[tmp2].16b\n" \
"ldr %q[tmp2], %[round_key_last]\n" \
"eor %[tmp].16b, %[tmp].16b, %[tmp2].16b"
#define AES_ENC_INPUT_ROUND_KEY(num_rounds, n) \
[round_key_##n]"m"(ctx->round_keys[(n-1)])
#define AES_ENC_INPUT_LAST_ROUND_KEYS(num_rounds) \
[round_key_second_last]"m"(ctx->round_keys[(num_rounds - 1)]), \
[round_key_last]"m"(ctx->round_keys[(num_rounds)])
/* Helper macros to do AES decryption, via inline asm. */
#define AES_DEC_ROUND(n) \
"ldr %q[tmp2], %[round_key_" #n "]\n" \
"aesd %[tmp].16b, %[tmp2].16b\n" \
"aesimc %[tmp].16b, %[tmp].16b\n"
#define AES_DEC_FINAL_ROUND() \
"ldr %q[tmp2], %[round_key_second_last]\n" \
"aesd %[tmp].16b, %[tmp2].16b\n" \
"ldr %q[tmp2], %[round_key_last]\n" \
"eor %[tmp].16b, %[tmp].16b, %[tmp2].16b"
#define AES_DEC_INPUT_ROUND_KEY(num_rounds, n) \
[round_key_##n]"m"(ctx->round_keys[(num_rounds + 1 - n)])
#define AES_DEC_INPUT_LAST_ROUND_KEYS(num_rounds) \
[round_key_second_last]"m"(ctx->round_keys[1]), \
[round_key_last]"m"(ctx->round_keys[0])
constexpr const u8 RoundKeyRcon0[] = {
0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36, 0x6C, 0xD8, 0xAB, 0x4D, 0x9A, 0x2F,
0x5E, 0xBC, 0x63, 0xC6, 0x97, 0x35, 0x6A, 0xD4, 0xB3, 0x7D, 0xFA, 0xEF, 0xC5, 0x91,
};
constexpr const u8 SubBytesTable[0x100] = {
0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,
0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,
0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,
0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,
0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,
0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,
0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,
0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2,
0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,
0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,
0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,
0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,
0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A,
0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,
0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,
0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16,
};
constexpr auto AesWordByte0Shift = 0 * BITSIZEOF(u8);
constexpr auto AesWordByte1Shift = 1 * BITSIZEOF(u8);
constexpr auto AesWordByte2Shift = 2 * BITSIZEOF(u8);
constexpr auto AesWordByte3Shift = 3 * BITSIZEOF(u8);
constexpr u32 SubBytesAndRotate(u32 v) {
return (static_cast<u32>(SubBytesTable[(v >> AesWordByte0Shift) & 0xFFu]) << AesWordByte3Shift) ^
(static_cast<u32>(SubBytesTable[(v >> AesWordByte1Shift) & 0xFFu]) << AesWordByte0Shift) ^
(static_cast<u32>(SubBytesTable[(v >> AesWordByte2Shift) & 0xFFu]) << AesWordByte1Shift) ^
(static_cast<u32>(SubBytesTable[(v >> AesWordByte3Shift) & 0xFFu]) << AesWordByte2Shift);
}
constexpr u32 SubBytes(u32 v) {
return (static_cast<u32>(SubBytesTable[(v >> AesWordByte0Shift) & 0xFFu]) << AesWordByte0Shift) ^
(static_cast<u32>(SubBytesTable[(v >> AesWordByte1Shift) & 0xFFu]) << AesWordByte1Shift) ^
(static_cast<u32>(SubBytesTable[(v >> AesWordByte2Shift) & 0xFFu]) << AesWordByte2Shift) ^
(static_cast<u32>(SubBytesTable[(v >> AesWordByte3Shift) & 0xFFu]) << AesWordByte3Shift);
}
}
template<size_t KeySize>
AesImpl<KeySize>::~AesImpl() {
ClearMemory(this, sizeof(*this));
}
template<size_t KeySize>
void AesImpl<KeySize>::Initialize(const void *key, size_t key_size, bool is_encrypt) {
/* Check pre-conditions. */
AMS_ASSERT(key_size == KeySize);
AMS_UNUSED(key_size);
/* Set up key. */
u32 *dst = m_round_keys;
std::memcpy(dst, key, KeySize);
/* Perform key scheduling. */
constexpr auto InitialKeyWords = KeySize / sizeof(u32);
u32 tmp = dst[InitialKeyWords - 1];
for (auto i = InitialKeyWords; i < (RoundCount + 1) * 4; ++i) {
const auto idx_in_key = i % InitialKeyWords;
if (idx_in_key == 0) {
/* At start of key word, we need to handle sub/rotate/rcon. */
tmp = SubBytesAndRotate(tmp);
tmp ^= (RoundKeyRcon0[i / InitialKeyWords - 1] << AesWordByte0Shift);
} else if ((InitialKeyWords > 6) && idx_in_key == 4) {
/* Halfway into a 256-bit key word, we need to do an additional subbytes. */
tmp = SubBytes(tmp);
}
/* Set the key word. */
tmp ^= dst[i - InitialKeyWords];
dst[i] = tmp;
}
/* If decrypting, perform inverse mix columns on all round keys. */
if (!is_encrypt) {
auto *key8 = reinterpret_cast<u8 *>(m_round_keys) + BlockSize;
for (auto i = 1; i < RoundCount; ++i) {
vst1q_u8(key8, vaesimcq_u8(vld1q_u8(key8)));
key8 += BlockSize;
}
}
}
template<size_t KeySize>
void AesImpl<KeySize>::EncryptBlock(void *dst, size_t dst_size, const void *src, size_t src_size) const {
AMS_UNUSED(src_size, dst_size);
/* Get the key. */
const u8 *key8 = reinterpret_cast<const u8 *>(m_round_keys);
/* Read the block. */
uint8x16_t block = vld1q_u8(static_cast<const u8 *>(src));
/* Encrypt block. */
for (auto round = 1; round < RoundCount; ++round) {
/* Do aes round. */
block = vaeseq_u8(block, vld1q_u8(key8));
key8 += BlockSize;
/* Do mix columns. */
block = vaesmcq_u8(block);
}
/* Do last aes round. */
block = vaeseq_u8(block, vld1q_u8(key8));
key8 += BlockSize;
/* Add the final round key. */
block = veorq_u8(block, vld1q_u8(key8));
/* Store the block. */
vst1q_u8(static_cast<u8 *>(dst), block);
}
template<size_t KeySize>
void AesImpl<KeySize>::DecryptBlock(void *dst, size_t dst_size, const void *src, size_t src_size) const {
AMS_UNUSED(src_size, dst_size);
/* Get the key. */
const u8 *key8 = reinterpret_cast<const u8 *>(m_round_keys) + (RoundCount * BlockSize);
/* Read the block. */
uint8x16_t block = vld1q_u8(static_cast<const u8 *>(src));
/* Encrypt block. */
for (auto round = RoundCount; round > 1; --round) {
/* Do aes round. */
block = vaesdq_u8(block, vld1q_u8(key8));
key8 -= BlockSize;
/* Do mix columns. */
block = vaesimcq_u8(block);
}
/* Do last aes round. */
block = vaesdq_u8(block, vld1q_u8(key8));
key8 -= BlockSize;
/* Add the first round key. */
block = veorq_u8(block, vld1q_u8(key8));
/* Store the block. */
vst1q_u8(static_cast<u8 *>(dst), block);
}
/* Specializations when building specifically for cortex-a57 (or for apple M* processors). */
#if defined(ATMOSPHERE_CPU_ARM_CORTEX_A57) || defined(ATMOSPHERE_OS_MACOS)
namespace {
template<size_t KeySize>
struct RoundKeyHelper {
u8 round_keys[AesImpl<KeySize>::RoundCount + 1][AesImpl<KeySize>::BlockSize];
};
}
template<>
void AesImpl<16>::EncryptBlock(void *dst, size_t dst_size, const void *src, size_t src_size) const {
AMS_UNUSED(src_size, dst_size);
/* Setup for asm */
AES_ENC_DEC_SETUP_VARS();
/* Use optimized assembly to do all rounds. */
__asm__ __volatile__ (
AES_ENC_ROUND(1)
AES_ENC_ROUND(2)
AES_ENC_ROUND(3)
AES_ENC_ROUND(4)
AES_ENC_ROUND(5)
AES_ENC_ROUND(6)
AES_ENC_ROUND(7)
AES_ENC_ROUND(8)
AES_ENC_ROUND(9)
AES_ENC_FINAL_ROUND()
: AES_ENC_DEC_OUTPUT_VARS()
: AES_ENC_INPUT_ROUND_KEY(RoundCount, 1),
AES_ENC_INPUT_ROUND_KEY(RoundCount, 2),
AES_ENC_INPUT_ROUND_KEY(RoundCount, 3),
AES_ENC_INPUT_ROUND_KEY(RoundCount, 4),
AES_ENC_INPUT_ROUND_KEY(RoundCount, 5),
AES_ENC_INPUT_ROUND_KEY(RoundCount, 6),
AES_ENC_INPUT_ROUND_KEY(RoundCount, 7),
AES_ENC_INPUT_ROUND_KEY(RoundCount, 8),
AES_ENC_INPUT_ROUND_KEY(RoundCount, 9),
AES_ENC_INPUT_LAST_ROUND_KEYS(RoundCount)
);
/* Store result. */
AES_ENC_DEC_STORE_RESULT();
}
template<>
void AesImpl<24>::EncryptBlock(void *dst, size_t dst_size, const void *src, size_t src_size) const {
AMS_UNUSED(src_size, dst_size);
/* Setup for asm */
AES_ENC_DEC_SETUP_VARS();
/* Use optimized assembly to do all rounds. */
__asm__ __volatile__ (
AES_ENC_ROUND(1)
AES_ENC_ROUND(2)
AES_ENC_ROUND(3)
AES_ENC_ROUND(4)
AES_ENC_ROUND(5)
AES_ENC_ROUND(6)
AES_ENC_ROUND(7)
AES_ENC_ROUND(8)
AES_ENC_ROUND(9)
AES_ENC_ROUND(10)
AES_ENC_ROUND(11)
AES_ENC_FINAL_ROUND()
: AES_ENC_DEC_OUTPUT_VARS()
: AES_ENC_INPUT_ROUND_KEY(RoundCount, 1),
AES_ENC_INPUT_ROUND_KEY(RoundCount, 2),
AES_ENC_INPUT_ROUND_KEY(RoundCount, 3),
AES_ENC_INPUT_ROUND_KEY(RoundCount, 4),
AES_ENC_INPUT_ROUND_KEY(RoundCount, 5),
AES_ENC_INPUT_ROUND_KEY(RoundCount, 6),
AES_ENC_INPUT_ROUND_KEY(RoundCount, 7),
AES_ENC_INPUT_ROUND_KEY(RoundCount, 8),
AES_ENC_INPUT_ROUND_KEY(RoundCount, 9),
AES_ENC_INPUT_ROUND_KEY(RoundCount, 10),
AES_ENC_INPUT_ROUND_KEY(RoundCount, 11),
AES_ENC_INPUT_LAST_ROUND_KEYS(RoundCount)
);
/* Store result. */
AES_ENC_DEC_STORE_RESULT();
}
template<>
void AesImpl<32>::EncryptBlock(void *dst, size_t dst_size, const void *src, size_t src_size) const {
AMS_UNUSED(src_size, dst_size);
/* Setup for asm */
AES_ENC_DEC_SETUP_VARS();
/* Use optimized assembly to do all rounds. */
__asm__ __volatile__ (
AES_ENC_ROUND(1)
AES_ENC_ROUND(2)
AES_ENC_ROUND(3)
AES_ENC_ROUND(4)
AES_ENC_ROUND(5)
AES_ENC_ROUND(6)
AES_ENC_ROUND(7)
AES_ENC_ROUND(8)
AES_ENC_ROUND(9)
AES_ENC_ROUND(10)
AES_ENC_ROUND(11)
AES_ENC_ROUND(12)
AES_ENC_ROUND(13)
AES_ENC_FINAL_ROUND()
: AES_ENC_DEC_OUTPUT_VARS()
: AES_ENC_INPUT_ROUND_KEY(RoundCount, 1),
AES_ENC_INPUT_ROUND_KEY(RoundCount, 2),
AES_ENC_INPUT_ROUND_KEY(RoundCount, 3),
AES_ENC_INPUT_ROUND_KEY(RoundCount, 4),
AES_ENC_INPUT_ROUND_KEY(RoundCount, 5),
AES_ENC_INPUT_ROUND_KEY(RoundCount, 6),
AES_ENC_INPUT_ROUND_KEY(RoundCount, 7),
AES_ENC_INPUT_ROUND_KEY(RoundCount, 8),
AES_ENC_INPUT_ROUND_KEY(RoundCount, 9),
AES_ENC_INPUT_ROUND_KEY(RoundCount, 10),
AES_ENC_INPUT_ROUND_KEY(RoundCount, 11),
AES_ENC_INPUT_ROUND_KEY(RoundCount, 12),
AES_ENC_INPUT_ROUND_KEY(RoundCount, 13),
AES_ENC_INPUT_LAST_ROUND_KEYS(RoundCount)
);
/* Store result. */
AES_ENC_DEC_STORE_RESULT();
}
template<>
void AesImpl<16>::DecryptBlock(void *dst, size_t dst_size, const void *src, size_t src_size) const {
AMS_UNUSED(src_size, dst_size);
/* Setup for asm */
AES_ENC_DEC_SETUP_VARS();
/* Use optimized assembly to do all rounds. */
__asm__ __volatile__ (
AES_DEC_ROUND(1)
AES_DEC_ROUND(2)
AES_DEC_ROUND(3)
AES_DEC_ROUND(4)
AES_DEC_ROUND(5)
AES_DEC_ROUND(6)
AES_DEC_ROUND(7)
AES_DEC_ROUND(8)
AES_DEC_ROUND(9)
AES_DEC_FINAL_ROUND()
: AES_ENC_DEC_OUTPUT_VARS()
: AES_DEC_INPUT_ROUND_KEY(RoundCount, 1),
AES_DEC_INPUT_ROUND_KEY(RoundCount, 2),
AES_DEC_INPUT_ROUND_KEY(RoundCount, 3),
AES_DEC_INPUT_ROUND_KEY(RoundCount, 4),
AES_DEC_INPUT_ROUND_KEY(RoundCount, 5),
AES_DEC_INPUT_ROUND_KEY(RoundCount, 6),
AES_DEC_INPUT_ROUND_KEY(RoundCount, 7),
AES_DEC_INPUT_ROUND_KEY(RoundCount, 8),
AES_DEC_INPUT_ROUND_KEY(RoundCount, 9),
AES_DEC_INPUT_LAST_ROUND_KEYS(RoundCount)
);
/* Store result. */
AES_ENC_DEC_STORE_RESULT();
}
template<>
void AesImpl<24>::DecryptBlock(void *dst, size_t dst_size, const void *src, size_t src_size) const {
AMS_UNUSED(src_size, dst_size);
/* Setup for asm */
AES_ENC_DEC_SETUP_VARS();
/* Use optimized assembly to do all rounds. */
__asm__ __volatile__ (
AES_DEC_ROUND(1)
AES_DEC_ROUND(2)
AES_DEC_ROUND(3)
AES_DEC_ROUND(4)
AES_DEC_ROUND(5)
AES_DEC_ROUND(6)
AES_DEC_ROUND(7)
AES_DEC_ROUND(8)
AES_DEC_ROUND(9)
AES_DEC_ROUND(10)
AES_DEC_ROUND(11)
AES_DEC_FINAL_ROUND()
: AES_ENC_DEC_OUTPUT_VARS()
: AES_DEC_INPUT_ROUND_KEY(RoundCount, 1),
AES_DEC_INPUT_ROUND_KEY(RoundCount, 2),
AES_DEC_INPUT_ROUND_KEY(RoundCount, 3),
AES_DEC_INPUT_ROUND_KEY(RoundCount, 4),
AES_DEC_INPUT_ROUND_KEY(RoundCount, 5),
AES_DEC_INPUT_ROUND_KEY(RoundCount, 6),
AES_DEC_INPUT_ROUND_KEY(RoundCount, 7),
AES_DEC_INPUT_ROUND_KEY(RoundCount, 8),
AES_DEC_INPUT_ROUND_KEY(RoundCount, 9),
AES_DEC_INPUT_ROUND_KEY(RoundCount, 10),
AES_DEC_INPUT_ROUND_KEY(RoundCount, 11),
AES_DEC_INPUT_LAST_ROUND_KEYS(RoundCount)
);
/* Store result. */
AES_ENC_DEC_STORE_RESULT();
}
template<>
void AesImpl<32>::DecryptBlock(void *dst, size_t dst_size, const void *src, size_t src_size) const {
AMS_UNUSED(src_size, dst_size);
/* Setup for asm */
AES_ENC_DEC_SETUP_VARS();
/* Use optimized assembly to do all rounds. */
__asm__ __volatile__ (
AES_DEC_ROUND(1)
AES_DEC_ROUND(2)
AES_DEC_ROUND(3)
AES_DEC_ROUND(4)
AES_DEC_ROUND(5)
AES_DEC_ROUND(6)
AES_DEC_ROUND(7)
AES_DEC_ROUND(8)
AES_DEC_ROUND(9)
AES_DEC_ROUND(10)
AES_DEC_ROUND(11)
AES_DEC_ROUND(12)
AES_DEC_ROUND(13)
AES_DEC_FINAL_ROUND()
: AES_ENC_DEC_OUTPUT_VARS()
: AES_DEC_INPUT_ROUND_KEY(RoundCount, 1),
AES_DEC_INPUT_ROUND_KEY(RoundCount, 2),
AES_DEC_INPUT_ROUND_KEY(RoundCount, 3),
AES_DEC_INPUT_ROUND_KEY(RoundCount, 4),
AES_DEC_INPUT_ROUND_KEY(RoundCount, 5),
AES_DEC_INPUT_ROUND_KEY(RoundCount, 6),
AES_DEC_INPUT_ROUND_KEY(RoundCount, 7),
AES_DEC_INPUT_ROUND_KEY(RoundCount, 8),
AES_DEC_INPUT_ROUND_KEY(RoundCount, 9),
AES_DEC_INPUT_ROUND_KEY(RoundCount, 10),
AES_DEC_INPUT_ROUND_KEY(RoundCount, 11),
AES_DEC_INPUT_ROUND_KEY(RoundCount, 12),
AES_DEC_INPUT_ROUND_KEY(RoundCount, 13),
AES_DEC_INPUT_LAST_ROUND_KEYS(RoundCount)
);
/* Store result. */
AES_ENC_DEC_STORE_RESULT();
}
#endif
/* Explicitly instantiate the three supported key sizes. */
template class AesImpl<16>;
template class AesImpl<24>;
template class AesImpl<32>;
#else
/* NOTE: Exosphere defines this in libexosphere. */
/* TODO: Non-EL0 implementation. */
#endif
}
| 19,487
|
C++
|
.cpp
| 420
| 35.161905
| 109
| 0.547796
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,096
|
crypto_xts_mode_impl.arch.generic.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/crypto/impl/crypto_xts_mode_impl.arch.generic.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <vapours.hpp>
#include "crypto_update_impl.hpp"
namespace ams::crypto::impl {
size_t XtsModeImpl::UpdateGeneric(void *dst, size_t dst_size, const void *src, size_t src_size) {
AMS_ASSERT(m_state == State_Initialized || m_state == State_Processing);
return UpdateImpl<void>(this, dst, dst_size, src, src_size);
}
size_t XtsModeImpl::ProcessBlocksGeneric(u8 *dst, const u8 *src, size_t num_blocks) {
size_t processed = BlockSize * (num_blocks - 1);
if (m_state == State_Processing) {
this->ProcessBlock(dst, m_last_block);
dst += BlockSize;
processed += BlockSize;
}
while ((--num_blocks) > 0) {
this->ProcessBlock(dst, src);
dst += BlockSize;
src += BlockSize;
}
std::memcpy(m_last_block, src, BlockSize);
m_state = State_Processing;
return processed;
}
template<> size_t XtsModeImpl::Update<AesEncryptor128>(void *dst, size_t dst_size, const void *src, size_t src_size) { return this->UpdateGeneric(dst, dst_size, src, src_size); }
template<> size_t XtsModeImpl::Update<AesEncryptor192>(void *dst, size_t dst_size, const void *src, size_t src_size) { return this->UpdateGeneric(dst, dst_size, src, src_size); }
template<> size_t XtsModeImpl::Update<AesEncryptor256>(void *dst, size_t dst_size, const void *src, size_t src_size) { return this->UpdateGeneric(dst, dst_size, src, src_size); }
template<> size_t XtsModeImpl::Update<AesDecryptor128>(void *dst, size_t dst_size, const void *src, size_t src_size) { return this->UpdateGeneric(dst, dst_size, src, src_size); }
template<> size_t XtsModeImpl::Update<AesDecryptor192>(void *dst, size_t dst_size, const void *src, size_t src_size) { return this->UpdateGeneric(dst, dst_size, src, src_size); }
template<> size_t XtsModeImpl::Update<AesDecryptor256>(void *dst, size_t dst_size, const void *src, size_t src_size) { return this->UpdateGeneric(dst, dst_size, src, src_size); }
}
| 2,683
|
C++
|
.cpp
| 45
| 53.777778
| 182
| 0.68393
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,097
|
result_get_name.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/result/result_get_name.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if !defined(ATMOSPHERE_OS_HORIZON) && (defined(AMS_BUILD_FOR_DEBUGGING) || defined(AMS_BUILD_FOR_AUDITING))
#define AMS_AUTO_GENERATE_RESULT_NAMES
#endif
#include <vapours.hpp>
namespace ams {
#if defined(AMS_AUTO_GENERATE_RESULT_NAMES)
#define AMS_INVOKE_MACRO_01(EXPR, n) EXPR(n); EXPR(n + (1 << 0));
#define AMS_INVOKE_MACRO_02(EXPR, n) AMS_INVOKE_MACRO_01(EXPR, n); AMS_INVOKE_MACRO_01(EXPR, n + (1 << 1));
#define AMS_INVOKE_MACRO_03(EXPR, n) AMS_INVOKE_MACRO_02(EXPR, n); AMS_INVOKE_MACRO_02(EXPR, n + (1 << 2));
#define AMS_INVOKE_MACRO_04(EXPR, n) AMS_INVOKE_MACRO_03(EXPR, n); AMS_INVOKE_MACRO_03(EXPR, n + (1 << 3));
#define AMS_INVOKE_MACRO_05(EXPR, n) AMS_INVOKE_MACRO_04(EXPR, n); AMS_INVOKE_MACRO_04(EXPR, n + (1 << 4));
#define AMS_INVOKE_MACRO_06(EXPR, n) AMS_INVOKE_MACRO_05(EXPR, n); AMS_INVOKE_MACRO_05(EXPR, n + (1 << 5));
#define AMS_INVOKE_MACRO_07(EXPR, n) AMS_INVOKE_MACRO_06(EXPR, n); AMS_INVOKE_MACRO_06(EXPR, n + (1 << 6));
#define AMS_INVOKE_MACRO_08(EXPR, n) AMS_INVOKE_MACRO_07(EXPR, n); AMS_INVOKE_MACRO_07(EXPR, n + (1 << 7));
#define AMS_INVOKE_MACRO_09(EXPR, n) AMS_INVOKE_MACRO_08(EXPR, n); AMS_INVOKE_MACRO_08(EXPR, n + (1 << 8));
#define AMS_INVOKE_MACRO_10(EXPR, n) AMS_INVOKE_MACRO_09(EXPR, n); AMS_INVOKE_MACRO_09(EXPR, n + (1 << 9));
#define AMS_INVOKE_MACRO_11(EXPR, n) AMS_INVOKE_MACRO_10(EXPR, n); AMS_INVOKE_MACRO_10(EXPR, n + (1 << 10));
#define AMS_INVOKE_MACRO_12(EXPR, n) AMS_INVOKE_MACRO_11(EXPR, n); AMS_INVOKE_MACRO_11(EXPR, n + (1 << 11));
#define AMS_INVOKE_MACRO_13(EXPR, n) AMS_INVOKE_MACRO_12(EXPR, n); AMS_INVOKE_MACRO_12(EXPR, n + (1 << 12));
namespace {
template<int Module, int Description>
constexpr const char *GetResultNameByModuleAndDescription() {
return ::ams::result::impl::ResultNameSpaceExistsImpl<Module>::template NameHolder<Description>::Name;
}
template<int Module>
constexpr const char *GetResultNameByModule(int description) {
#define AMS_TEST_RESULT_DESCRIPTION_DEFINED(n) if constexpr (::ams::result::impl::ResultNameSpaceExistsImpl<Module>::template NameHolder<n>::Exists) { if (description == n) { return GetResultNameByModuleAndDescription<Module, n>(); } }
AMS_INVOKE_MACRO_13(AMS_TEST_RESULT_DESCRIPTION_DEFINED, 0)
return "Unknown";
}
}
const char *GetResultName(int module, int description) {
#define AMS_TEST_RESULT_MODULE_DEFINED(n) if constexpr (::ams::result::impl::ResultNameSpaceExistsImpl<n>::Exists) { if (module == n) { return GetResultNameByModule<n>(description); } }
AMS_INVOKE_MACRO_08(AMS_TEST_RESULT_MODULE_DEFINED, 0)
return "Unknown";
}
#else
const char *GetResultName(int, int) {
return "Unknown";
}
#endif
}
| 3,493
|
C++
|
.cpp
| 57
| 55.894737
| 247
| 0.678363
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,098
|
dd_cache.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/dd/dd_cache.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if defined(ATMOSPHERE_IS_STRATOSPHERE)
#include <stratosphere.hpp>
#elif defined(ATMOSPHERE_IS_MESOSPHERE)
#include <mesosphere.hpp>
#elif defined(ATMOSPHERE_IS_EXOSPHERE)
#include <exosphere.hpp>
#else
#include <vapours.hpp>
#endif
#include "impl/dd_select_cache_impl.hpp"
namespace ams::dd {
void InvalidateDataCache(void *addr, size_t size) {
return impl::InvalidateDataCacheImpl(addr, size);
}
void StoreDataCache(void *addr, size_t size) {
return impl::StoreDataCacheImpl(addr, size);
}
void FlushDataCache(void *addr, size_t size) {
return impl::FlushDataCacheImpl(addr, size);
}
}
| 1,277
|
C++
|
.cpp
| 36
| 32.611111
| 76
| 0.745955
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,099
|
dd_io_mapping.os.horizon.cpp
|
Atmosphere-NX_Atmosphere/libraries/libvapours/source/dd/dd_io_mapping.os.horizon.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if defined(ATMOSPHERE_IS_STRATOSPHERE)
#include <stratosphere.hpp>
#elif defined(ATMOSPHERE_IS_MESOSPHERE)
#include <mesosphere.hpp>
#elif defined(ATMOSPHERE_IS_EXOSPHERE)
#include <exosphere.hpp>
#else
#include <vapours.hpp>
#endif
namespace ams::dd {
uintptr_t QueryIoMapping(dd::PhysicalAddress phys_addr, size_t size) {
#if defined(ATMOSPHERE_IS_EXOSPHERE)
#if defined(ATMOSPHERE_ARCH_ARM64)
/* TODO: Do this in a less shitty way. */
if (secmon::MemoryRegionPhysicalDeviceClkRst.Contains(phys_addr, size)) {
return secmon::MemoryRegionVirtualDeviceClkRst.GetAddress() + phys_addr - secmon::MemoryRegionPhysicalDeviceClkRst.GetAddress();
} else if (secmon::MemoryRegionPhysicalDeviceGpio.Contains(phys_addr, size)) {
return secmon::MemoryRegionVirtualDeviceGpio.GetAddress() + phys_addr - secmon::MemoryRegionPhysicalDeviceGpio.GetAddress();
} else if (secmon::MemoryRegionPhysicalDeviceApbMisc.Contains(phys_addr, size)) {
return secmon::MemoryRegionVirtualDeviceApbMisc.GetAddress() + phys_addr - secmon::MemoryRegionPhysicalDeviceApbMisc.GetAddress();
} else if (secmon::MemoryRegionPhysicalDeviceSdmmc.Contains(phys_addr, size)) {
return secmon::MemoryRegionVirtualDeviceSdmmc.GetAddress() + phys_addr - secmon::MemoryRegionPhysicalDeviceSdmmc.GetAddress();
} else if (secmon::MemoryRegionPhysicalDevicePmc.Contains(phys_addr, size)) {
return secmon::MemoryRegionVirtualDevicePmc.GetAddress() + phys_addr - secmon::MemoryRegionPhysicalDevicePmc.GetAddress();
} else if (secmon::MemoryRegionPhysicalDeviceI2c5.Contains(phys_addr, size)) {
return secmon::MemoryRegionVirtualDeviceI2c5.GetAddress() + phys_addr - secmon::MemoryRegionPhysicalDeviceI2c5.GetAddress();
} else if (secmon::MemoryRegionPhysicalDeviceI2c1.Contains(phys_addr, size)) {
return secmon::MemoryRegionVirtualDeviceI2c1.GetAddress() + phys_addr - secmon::MemoryRegionPhysicalDeviceI2c1.GetAddress();
} else {
AMS_UNUSED(size);
return static_cast<uintptr_t>(phys_addr);
}
#elif defined(ATMOSPHERE_ARCH_ARM)
/* TODO: BPMP translation? */
AMS_UNUSED(size);
return static_cast<uintptr_t>(phys_addr);
#else
#error "Unknown architecture for ams::dd::QueryIoMapping (EXOSPHERE)!"
#endif
#elif defined(ATMOSPHERE_IS_MESOSPHERE)
/* TODO: Kernel address translation? */
AMS_UNUSED(size);
return static_cast<uintptr_t>(phys_addr);
#elif defined(ATMOSPHERE_IS_STRATOSPHERE)
svc::Address virt_addr = 0;
const dd::PhysicalAddress aligned_addr = util::AlignDown(phys_addr, os::MemoryPageSize);
const size_t offset = phys_addr - aligned_addr;
const size_t aligned_size = size + offset;
if (hos::GetVersion() >= hos::Version_10_0_0) {
svc::Size region_size = 0;
R_TRY_CATCH(svc::QueryMemoryMapping(std::addressof(virt_addr), std::addressof(region_size), aligned_addr, aligned_size)) {
/* Official software handles this by returning 0. */
R_CATCH(svc::ResultNotFound) { return 0; }
} R_END_TRY_CATCH_WITH_ABORT_UNLESS;
AMS_ASSERT(region_size >= aligned_size);
} else {
R_TRY_CATCH(svc::LegacyQueryIoMapping(std::addressof(virt_addr), aligned_addr, aligned_size)) {
/* Official software handles this by returning 0. */
R_CATCH(svc::ResultNotFound) { return 0; }
} R_END_TRY_CATCH_WITH_ABORT_UNLESS;
}
return static_cast<uintptr_t>(virt_addr) + offset;
#else
#error "Unknown execution context for ams::dd::QueryIoMapping!"
#endif
}
namespace {
#if defined(ATMOSPHERE_IS_STRATOSPHERE)
#if defined(ATMOSPHERE_BOARD_NINTENDO_NX)
constexpr dd::PhysicalAddress PmcPhysStart = 0x7000E400;
constexpr dd::PhysicalAddress PmcPhysLast = 0x7000EFFF;
constexpr bool IsValidPmcPhysicalAddress(dd::PhysicalAddress phys_addr) {
return util::IsAligned(phys_addr, alignof(u32)) && PmcPhysStart <= phys_addr && phys_addr <= PmcPhysLast;
}
u32 ReadWritePmcRegisterImpl(dd::PhysicalAddress phys_addr, u32 value, u32 mask) {
u32 out_value;
R_ABORT_UNLESS(spl::smc::ConvertResult(spl::smc::AtmosphereReadWriteRegister(phys_addr, mask, value, std::addressof(out_value))));
return out_value;
}
bool TryReadModifyWritePmcRegister(u32 *out, dd::PhysicalAddress phys_addr, u32 value, u32 mask) {
if (IsValidPmcPhysicalAddress(phys_addr)) {
*out = ReadWritePmcRegisterImpl(phys_addr, value, mask);
return true;
} else {
return false;
}
}
#else
bool TryReadModifyWritePmcRegister(u32 *out, dd::PhysicalAddress phys_addr, u32 value, u32 mask) {
AMS_UNUSED(out, phys_addr, value, mask);
return false;
}
#endif
#endif
}
u32 ReadIoRegister(dd::PhysicalAddress phys_addr) {
#if defined(ATMOSPHERE_IS_EXOSPHERE) || defined(ATMOSPHERE_IS_MESOSPHERE)
return reg::Read(dd::QueryIoMapping(phys_addr, sizeof(u32)));
#elif defined(ATMOSPHERE_IS_STRATOSPHERE)
u32 val;
if (!TryReadModifyWritePmcRegister(std::addressof(val), phys_addr, 0, 0)) {
R_ABORT_UNLESS(svc::ReadWriteRegister(std::addressof(val), phys_addr, 0, 0));
}
return val;
#else
#error "Unknown execution context for ams::dd::ReadIoRegister!"
#endif
}
void WriteIoRegister(dd::PhysicalAddress phys_addr, u32 value) {
#if defined(ATMOSPHERE_IS_EXOSPHERE) || defined(ATMOSPHERE_IS_MESOSPHERE)
reg::Write(dd::QueryIoMapping(phys_addr, sizeof(u32)), value);
#elif defined(ATMOSPHERE_IS_STRATOSPHERE)
u32 out_val;
if (!TryReadModifyWritePmcRegister(std::addressof(out_val), phys_addr, value, 0xFFFFFFFF)) {
R_ABORT_UNLESS(svc::ReadWriteRegister(std::addressof(out_val), phys_addr, 0xFFFFFFFF, value));
}
AMS_UNUSED(out_val);
#else
#error "Unknown execution context for ams::dd::WriteIoRegister!"
#endif
}
u32 ReadModifyWriteIoRegister(PhysicalAddress phys_addr, u32 value, u32 mask) {
#if defined(ATMOSPHERE_IS_EXOSPHERE) || defined(ATMOSPHERE_IS_MESOSPHERE)
AMS_UNUSED(phys_addr, value, mask);
AMS_ABORT("ReadModifyWriteIoRegister TODO under non-stratosphere");
#elif defined(ATMOSPHERE_IS_STRATOSPHERE)
u32 out_val;
if (!TryReadModifyWritePmcRegister(std::addressof(out_val), phys_addr, value, mask)) {
R_ABORT_UNLESS(svc::ReadWriteRegister(std::addressof(out_val), phys_addr, mask, value));
}
return out_val;
#else
#error "Unknown execution context for ams::dd::ReadModifyWriteIoRegister!"
#endif
}
}
| 8,360
|
C++
|
.cpp
| 151
| 42.907285
| 150
| 0.623762
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,100
|
spl_secure_monitor_manager.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/spl/source/spl_secure_monitor_manager.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "spl_secure_monitor_manager.hpp"
namespace ams::spl {
void SecureMonitorManager::Initialize() {
return impl::Initialize();
}
Result SecureMonitorManager::ModularExponentiate(void *out, size_t out_size, const void *base, size_t base_size, const void *exp, size_t exp_size, const void *mod, size_t mod_size) {
R_RETURN(impl::ModularExponentiate(out, out_size, base, base_size, exp, exp_size, mod, mod_size));
}
Result SecureMonitorManager::GenerateAesKek(AccessKey *out_access_key, const KeySource &key_source, u32 generation, u32 option) {
R_RETURN(impl::GenerateAesKek(out_access_key, key_source, generation, option));
}
Result SecureMonitorManager::LoadAesKey(s32 keyslot, const void *owner, const AccessKey &access_key, const KeySource &key_source) {
R_TRY(this->TestAesKeySlot(nullptr, keyslot, owner));
R_RETURN(impl::LoadAesKey(keyslot, access_key, key_source));
}
Result SecureMonitorManager::GenerateAesKey(AesKey *out_key, const AccessKey &access_key, const KeySource &key_source) {
R_RETURN(impl::GenerateAesKey(out_key, access_key, key_source));
}
Result SecureMonitorManager::DecryptDeviceUniqueData(void *dst, size_t dst_size, const void *src, size_t src_size, const AccessKey &access_key, const KeySource &key_source, u32 option) {
R_RETURN(impl::DecryptDeviceUniqueData(dst, dst_size, src, src_size, access_key, key_source, option));
}
Result SecureMonitorManager::ReencryptDeviceUniqueData(void *dst, size_t dst_size, const void *src, size_t src_size, const AccessKey &access_key_dec, const KeySource &source_dec, const AccessKey &access_key_enc, const KeySource &source_enc, u32 option) {
R_RETURN(impl::ReencryptDeviceUniqueData(dst, dst_size, src, src_size, access_key_dec, source_dec, access_key_enc, source_enc, option));
}
Result SecureMonitorManager::GetConfig(u64 *out, spl::ConfigItem key) {
R_RETURN(impl::GetConfig(out, key));
}
Result SecureMonitorManager::SetConfig(spl::ConfigItem key, u64 value) {
R_RETURN(impl::SetConfig(key, value));
}
Result SecureMonitorManager::GetPackage2Hash(void *dst, const size_t size) {
R_RETURN(impl::GetPackage2Hash(dst, size));
}
Result SecureMonitorManager::GenerateRandomBytes(void *out, size_t size) {
R_RETURN(impl::GenerateRandomBytes(out, size));
}
Result SecureMonitorManager::DecryptAndStoreGcKey(const void *src, size_t src_size, const AccessKey &access_key, const KeySource &key_source, u32 option) {
R_RETURN(impl::DecryptAndStoreGcKey(src, src_size, access_key, key_source, option));
}
Result SecureMonitorManager::DecryptGcMessage(u32 *out_size, void *dst, size_t dst_size, const void *base, size_t base_size, const void *mod, size_t mod_size, const void *label_digest, size_t label_digest_size) {
R_RETURN(impl::DecryptGcMessage(out_size, dst, dst_size, base, base_size, mod, mod_size, label_digest, label_digest_size));
}
Result SecureMonitorManager::DecryptAndStoreSslClientCertKey(const void *src, size_t src_size, const AccessKey &access_key, const KeySource &key_source) {
R_RETURN(impl::DecryptAndStoreSslClientCertKey(src, src_size, access_key, key_source));
}
Result SecureMonitorManager::ModularExponentiateWithSslClientCertKey(void *out, size_t out_size, const void *base, size_t base_size, const void *mod, size_t mod_size) {
R_RETURN(impl::ModularExponentiateWithSslClientCertKey(out, out_size, base, base_size, mod, mod_size));
}
Result SecureMonitorManager::DecryptAndStoreDrmDeviceCertKey(const void *src, size_t src_size, const AccessKey &access_key, const KeySource &key_source) {
R_RETURN(impl::DecryptAndStoreDrmDeviceCertKey(src, src_size, access_key, key_source));
}
Result SecureMonitorManager::ModularExponentiateWithDrmDeviceCertKey(void *out, size_t out_size, const void *base, size_t base_size, const void *mod, size_t mod_size) {
R_RETURN(impl::ModularExponentiateWithDrmDeviceCertKey(out, out_size, base, base_size, mod, mod_size));
}
Result SecureMonitorManager::IsDevelopment(bool *out) {
R_RETURN(impl::IsDevelopment(out));
}
Result SecureMonitorManager::GenerateSpecificAesKey(AesKey *out_key, const KeySource &key_source, u32 generation, u32 which) {
R_RETURN(impl::GenerateSpecificAesKey(out_key, key_source, generation, which));
}
Result SecureMonitorManager::DecryptAesKey(AesKey *out_key, const KeySource &key_source, u32 generation, u32 option) {
R_RETURN(impl::DecryptAesKey(out_key, key_source, generation, option));
}
Result SecureMonitorManager::ComputeCtr(void *dst, size_t dst_size, s32 keyslot, const void *owner, const void *src, size_t src_size, const IvCtr &iv_ctr) {
R_TRY(this->TestAesKeySlot(nullptr, keyslot, owner));
R_RETURN(impl::ComputeCtr(dst, dst_size, keyslot, src, src_size, iv_ctr));
}
Result SecureMonitorManager::ComputeCmac(Cmac *out_cmac, s32 keyslot, const void *owner, const void *data, size_t size) {
R_TRY(this->TestAesKeySlot(nullptr, keyslot, owner));
R_RETURN(impl::ComputeCmac(out_cmac, keyslot, data, size));
}
Result SecureMonitorManager::LoadEsDeviceKey(const void *src, size_t src_size, const AccessKey &access_key, const KeySource &key_source, u32 option) {
R_RETURN(impl::LoadEsDeviceKey(src, src_size, access_key, key_source, option));
}
Result SecureMonitorManager::PrepareEsTitleKey(AccessKey *out_access_key, const void *base, size_t base_size, const void *mod, size_t mod_size, const void *label_digest, size_t label_digest_size, u32 generation) {
R_RETURN(impl::PrepareEsTitleKey(out_access_key, base, base_size, mod, mod_size, label_digest, label_digest_size, generation));
}
Result SecureMonitorManager::PrepareEsArchiveKey(AccessKey *out_access_key, const void *base, size_t base_size, const void *mod, size_t mod_size, const void *label_digest, size_t label_digest_size, u32 generation) {
R_RETURN(impl::PrepareEsArchiveKey(out_access_key, base, base_size, mod, mod_size, label_digest, label_digest_size, generation));
}
Result SecureMonitorManager::PrepareEsUnknown2Key(AccessKey *out_access_key, const void *base, size_t base_size, const void *mod, size_t mod_size, const void *label_digest, size_t label_digest_size, u32 generation) {
R_RETURN(impl::PrepareEsUnknown2Key(out_access_key, base, base_size, mod, mod_size, label_digest, label_digest_size, generation));
}
Result SecureMonitorManager::PrepareCommonEsTitleKey(AccessKey *out_access_key, const KeySource &key_source, u32 generation) {
R_RETURN(impl::PrepareCommonEsTitleKey(out_access_key, key_source, generation));
}
Result SecureMonitorManager::LoadPreparedAesKey(s32 keyslot, const void *owner, const AccessKey &access_key) {
R_TRY(this->TestAesKeySlot(nullptr, keyslot, owner));
R_RETURN(impl::LoadPreparedAesKey(keyslot, access_key));
}
Result SecureMonitorManager::AllocateAesKeySlot(s32 *out_keyslot, const void *owner) {
/* Allocate a new virtual keyslot. */
s32 keyslot;
R_TRY(impl::AllocateAesKeySlot(std::addressof(keyslot)));
/* Get the keyslot's index. */
s32 index;
bool virt;
R_ABORT_UNLESS(impl::TestAesKeySlot(std::addressof(index), std::addressof(virt), keyslot));
/* All allocated keyslots must be virtual. */
AMS_ABORT_UNLESS(virt);
m_aes_keyslot_owners[index] = owner;
*out_keyslot = keyslot;
R_SUCCEED();
}
Result SecureMonitorManager::DeallocateAesKeySlot(s32 keyslot, const void *owner) {
s32 index;
R_TRY(this->TestAesKeySlot(std::addressof(index), keyslot, owner));
m_aes_keyslot_owners[index] = nullptr;
R_RETURN(impl::DeallocateAesKeySlot(keyslot));
}
void SecureMonitorManager::DeallocateAesKeySlots(const void *owner) {
for (auto i = 0; i < impl::AesKeySlotCount; ++i) {
if (m_aes_keyslot_owners[i] == owner) {
m_aes_keyslot_owners[i] = nullptr;
impl::DeallocateAesKeySlot(impl::AesKeySlotMin + i);
}
}
}
Result SecureMonitorManager::SetBootReason(BootReasonValue boot_reason) {
R_RETURN(impl::SetBootReason(boot_reason));
}
Result SecureMonitorManager::GetBootReason(BootReasonValue *out) {
R_RETURN(impl::GetBootReason(out));
}
os::SystemEvent *SecureMonitorManager::GetAesKeySlotAvailableEvent() {
return impl::GetAesKeySlotAvailableEvent();
}
Result SecureMonitorManager::TestAesKeySlot(s32 *out_index, s32 keyslot, const void *owner) {
/* Validate the keyslot (and get the index). */
s32 index;
bool virt;
R_TRY(impl::TestAesKeySlot(std::addressof(index), std::addressof(virt), keyslot));
/* Check that the keyslot is physical (for legacy compat) or owned by the request maker. */
R_UNLESS(!virt || m_aes_keyslot_owners[index] == owner, spl::ResultInvalidKeySlot());
/* Set output index. */
if (out_index != nullptr) {
*out_index = index;
}
R_SUCCEED();
}
}
| 10,004
|
C++
|
.cpp
| 157
| 56.923567
| 258
| 0.711007
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,101
|
spl_main.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/spl/source/spl_main.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "spl_random_service.hpp"
#include "spl_general_service.hpp"
#include "spl_crypto_service.hpp"
#include "spl_ssl_service.hpp"
#include "spl_es_service.hpp"
#include "spl_fs_service.hpp"
#include "spl_manu_service.hpp"
#include "spl_deprecated_service.hpp"
namespace ams {
namespace spl {
namespace {
struct SplServerOptions {
static constexpr size_t PointerBufferSize = 0x800;
static constexpr size_t MaxDomains = 0;
static constexpr size_t MaxDomainObjects = 0;
static constexpr bool CanDeferInvokeRequest = false;
static constexpr bool CanManageMitmServers = false;
};
enum PortIndex {
PortIndex_General,
PortIndex_Random,
PortIndex_Crypto,
PortIndex_Fs,
PortIndex_Ssl,
PortIndex_Es,
PortIndex_Manu,
PortIndex_Count,
};
constexpr sm::ServiceName RandomServiceName = sm::ServiceName::Encode("csrng");
constexpr size_t RandomMaxSessions = 10; /* NOTE: Official is 9. */
constexpr sm::ServiceName GeneralServiceName = sm::ServiceName::Encode("spl:");
constexpr size_t DeprecatedMaxSessions = 13;
constexpr size_t GeneralMaxSessions = 9; /* NOTE: Official is 8. */
constexpr sm::ServiceName CryptoServiceName = sm::ServiceName::Encode("spl:mig");
constexpr size_t CryptoMaxSessions = 7; /* NOTE: Official is 6. */
constexpr sm::ServiceName SslServiceName = sm::ServiceName::Encode("spl:ssl");
constexpr size_t SslMaxSessions = 2; /* NOTE: Official is 2. */
constexpr sm::ServiceName EsServiceName = sm::ServiceName::Encode("spl:es");
constexpr size_t EsMaxSessions = 2; /* NOTE: Official is 2. */
constexpr sm::ServiceName FsServiceName = sm::ServiceName::Encode("spl:fs");
constexpr size_t FsMaxSessions = 3; /* NOTE: Official is 1. */
constexpr sm::ServiceName ManuServiceName = sm::ServiceName::Encode("spl:manu");
constexpr size_t ManuMaxSessions = 1; /* NOTE: Official is 1. */
/* csrng, spl:, spl:mig, spl:ssl, spl:es, spl:fs, spl:manu. */
/* TODO: Consider max sessions enforcement? */
constexpr size_t ModernMaxSessions = GeneralMaxSessions + CryptoMaxSessions + SslMaxSessions + EsMaxSessions + FsMaxSessions + ManuMaxSessions;
constexpr size_t NumSessions = RandomMaxSessions + std::max(DeprecatedMaxSessions, ModernMaxSessions) + 1;
class ServerManager final : public sf::hipc::ServerManager<PortIndex_Count, SplServerOptions, NumSessions> {
private:
sf::ExpHeapAllocator *m_allocator;
spl::SecureMonitorManager *m_secure_monitor_manager;
spl::GeneralService m_general_service;
sf::UnmanagedServiceObjectByPointer<spl::impl::IGeneralInterface, spl::GeneralService> m_general_service_object;
spl::RandomService m_random_service;
sf::UnmanagedServiceObjectByPointer<spl::impl::IRandomInterface, spl::RandomService> m_random_service_object;
public:
ServerManager(sf::ExpHeapAllocator *allocator, spl::SecureMonitorManager *manager) : m_allocator(allocator), m_secure_monitor_manager(manager), m_general_service(manager), m_general_service_object(std::addressof(m_general_service)), m_random_service(manager), m_random_service_object(std::addressof(m_random_service)) {
/* ... */
}
private:
virtual ams::Result OnNeedsToAccept(int port_index, Server *server) override;
};
using Allocator = sf::ExpHeapAllocator;
using ObjectFactory = sf::ObjectFactory<sf::ExpHeapAllocator::Policy>;
alignas(0x40) constinit u8 g_server_allocator_buffer[8_KB];
Allocator g_server_allocator;
constinit SecureMonitorManager g_secure_monitor_manager;
constinit bool g_use_new_server = false;
ServerManager g_server_manager(std::addressof(g_server_allocator), std::addressof(g_secure_monitor_manager));
ams::Result ServerManager::OnNeedsToAccept(int port_index, Server *server) {
switch (port_index) {
case PortIndex_General:
if (g_use_new_server) {
R_RETURN(this->AcceptImpl(server, m_general_service_object.GetShared()));
} else {
R_RETURN(this->AcceptImpl(server, ObjectFactory::CreateSharedEmplaced<spl::impl::IDeprecatedGeneralInterface, spl::DeprecatedService>(m_allocator, m_secure_monitor_manager)));
}
case PortIndex_Random:
R_RETURN(this->AcceptImpl(server, m_random_service_object.GetShared()));
case PortIndex_Crypto:
R_RETURN(this->AcceptImpl(server, ObjectFactory::CreateSharedEmplaced<spl::impl::ICryptoInterface, spl::CryptoService>(m_allocator, m_secure_monitor_manager)));
case PortIndex_Fs:
R_RETURN(this->AcceptImpl(server, ObjectFactory::CreateSharedEmplaced<spl::impl::IFsInterface, spl::FsService>(m_allocator, m_secure_monitor_manager)));
case PortIndex_Ssl:
R_RETURN(this->AcceptImpl(server, ObjectFactory::CreateSharedEmplaced<spl::impl::ISslInterface, spl::SslService>(m_allocator, m_secure_monitor_manager)));
case PortIndex_Es:
R_RETURN(this->AcceptImpl(server, ObjectFactory::CreateSharedEmplaced<spl::impl::IEsInterface, spl::EsService>(m_allocator, m_secure_monitor_manager)));
case PortIndex_Manu:
R_RETURN(this->AcceptImpl(server, ObjectFactory::CreateSharedEmplaced<spl::impl::IManuInterface, spl::ManuService>(m_allocator, m_secure_monitor_manager)));
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
void SplMain() {
/* Setup server allocator. */
g_server_allocator.Attach(lmem::CreateExpHeap(g_server_allocator_buffer, sizeof(g_server_allocator_buffer), lmem::CreateOption_None));
/* Initialize secure monitor manager. */
g_secure_monitor_manager.Initialize();
g_use_new_server = hos::GetVersion() >= hos::Version_4_0_0;
/* Create services. */
const auto fw_ver = hos::GetVersion();
R_ABORT_UNLESS(g_server_manager.RegisterServer(PortIndex_General, GeneralServiceName, fw_ver >= hos::Version_4_0_0 ? GeneralMaxSessions : DeprecatedMaxSessions));
R_ABORT_UNLESS(g_server_manager.RegisterServer(PortIndex_Random, RandomServiceName, RandomMaxSessions));
if (fw_ver >= hos::Version_4_0_0) {
R_ABORT_UNLESS(g_server_manager.RegisterServer(PortIndex_Crypto, CryptoServiceName, CryptoMaxSessions));
R_ABORT_UNLESS(g_server_manager.RegisterServer(PortIndex_Fs, FsServiceName, FsMaxSessions));
R_ABORT_UNLESS(g_server_manager.RegisterServer(PortIndex_Ssl, SslServiceName, SslMaxSessions));
R_ABORT_UNLESS(g_server_manager.RegisterServer(PortIndex_Es, EsServiceName, EsMaxSessions));
if (fw_ver >= hos::Version_5_0_0) {
g_server_manager.RegisterServer(PortIndex_Manu, ManuServiceName, ManuMaxSessions);
}
}
/* Loop forever, servicing our services. */
g_server_manager.LoopProcess();
}
}
}
namespace init {
void InitializeSystemModule() {
/* Initialize our connection to sm. */
R_ABORT_UNLESS(sm::Initialize());
}
void FinalizeSystemModule() { /* ... */ }
void Startup() { /* ... */ }
}
void NORETURN Exit(int rc) {
AMS_UNUSED(rc);
AMS_ABORT("Exit called by immortal process");
}
void Main() {
/* Set thread name. */
os::SetThreadNamePointer(os::GetCurrentThread(), AMS_GET_SYSTEM_THREAD_NAME(spl, Main));
AMS_ASSERT(os::GetThreadPriority(os::GetCurrentThread()) == AMS_GET_SYSTEM_THREAD_PRIORITY(spl, Main));
/* Invoke SPL main. */
spl::SplMain();
/* This can never be reached. */
AMS_ASSUME(false);
}
}
| 9,521
|
C++
|
.cpp
| 154
| 48.253247
| 339
| 0.615286
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,102
|
lm_main.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/LogManager/source/lm_main.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams {
namespace lm::srv {
void StartLogServerProxy();
void StopLogServerProxy();
void InitializeFlushThread();
void FinalizeFlushThread();
void InitializeIpcServer();
void LoopIpcServer();
void FinalizeIpcServer();
}
namespace init {
void InitializeSystemModule() {
/* Initialize our connection to sm. */
R_ABORT_UNLESS(sm::Initialize());
/* Initialize services we need. */
R_ABORT_UNLESS(::setsysInitialize());
R_ABORT_UNLESS(::pscmInitialize());
/* Verify that we can sanely execute. */
ams::CheckApiVersion();
}
void FinalizeSystemModule() { /* ... */ }
void Startup() { /* ... */ }
}
void Main() {
/* Check thread priority. */
AMS_ASSERT(os::GetThreadPriority(os::GetCurrentThread()) == AMS_GET_SYSTEM_THREAD_PRIORITY(LogManager, MainThread));
/* Set thread name. */
os::ChangeThreadPriority(os::GetCurrentThread(), AMS_GET_SYSTEM_THREAD_PRIORITY(lm, IpcServer));
os::SetThreadNamePointer(os::GetCurrentThread(), AMS_GET_SYSTEM_THREAD_NAME(lm, IpcServer));
/* Start log server proxy. */
lm::srv::StartLogServerProxy();
/* Initialize flush thread. */
lm::srv::InitializeFlushThread();
/* Process IPC server. */
lm::srv::InitializeIpcServer();
lm::srv::LoopIpcServer();
lm::srv::FinalizeIpcServer();
/* Finalize flush thread. */
lm::srv::FinalizeFlushThread();
/* Stop log server proxy. */
lm::srv::StopLogServerProxy();
}
}
| 2,353
|
C++
|
.cpp
| 59
| 32.661017
| 124
| 0.640563
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,103
|
htc_main.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/htc/source/htc_main.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams {
namespace htc {
namespace {
alignas(0x40) constinit u8 g_heap_buffer[4_KB];
lmem::HeapHandle g_heap_handle;
void *Allocate(size_t size) {
return lmem::AllocateFromExpHeap(g_heap_handle, size);
}
void Deallocate(void *p, size_t size) {
AMS_UNUSED(size);
return lmem::FreeToExpHeap(g_heap_handle, p);
}
void InitializeHeap() {
/* Setup server allocator. */
g_heap_handle = lmem::CreateExpHeap(g_heap_buffer, sizeof(g_heap_buffer), lmem::CreateOption_ThreadSafe);
}
}
namespace {
constexpr htclow::impl::DriverType DefaultHtclowDriverType = htclow::impl::DriverType::Usb;
constexpr inline size_t NumHtcsIpcThreads = 8;
alignas(os::ThreadStackAlignment) u8 g_htc_ipc_thread_stack[4_KB];
alignas(os::ThreadStackAlignment) u8 g_htcfs_ipc_thread_stack[4_KB];
alignas(os::ThreadStackAlignment) u8 g_htcs_ipc_thread_stack[NumHtcsIpcThreads][4_KB];
htclow::impl::DriverType GetHtclowDriverType() {
/* Get the transport type. */
char transport[0x10];
if (settings::fwdbg::GetSettingsItemValue(transport, sizeof(transport), "bsp0", "tm_transport") == 0) {
return DefaultHtclowDriverType;
}
/* Make the transport type case insensitive. */
transport[util::size(transport) - 1] = '\x00';
for (size_t i = 0; i < util::size(transport); ++i) {
transport[i] = std::tolower(static_cast<unsigned char>(transport[i]));
}
/* Select the transport. */
if (std::strstr(transport, "usb")) {
return htclow::impl::DriverType::Usb;
} else if (std::strstr(transport, "hb")) {
return htclow::impl::DriverType::HostBridge;
} else if (std::strstr(transport, "plainchannel")) {
return htclow::impl::DriverType::PlainChannel;
} else if (std::strstr(transport, "socket")) {
/* NOTE: Nintendo does not actually allow socket driver to be selected. */
/* Should we disallow this? Undesirable, because people will want to use docked tma. */
/* TODO: Right now, SocketDriver causes a hang on init. This is because */
/* the socket driver requires wi-fi, but wi-fi can't happen until the system is fully up. */
/* The system can't initialize fully until we acknowledge power state events. */
/* We can't acknowledge power state events until our driver is online. */
/* Resolving this chicken-and-egg problem without compromising design will require thought. */
//return htclow::impl::DriverType::Socket;
return DefaultHtclowDriverType;
} else {
return DefaultHtclowDriverType;
}
}
void HtcIpcThreadFunction(void *) {
htc::server::LoopHtcmiscServer();
}
void HtcfsIpcThreadFunction(void *) {
htcfs::LoopHipcServer();
}
void HtcsIpcThreadFunction(void *) {
htcs::server::LoopHipcServer();
}
}
namespace server {
void InitializePowerStateMonitor(htclow::impl::DriverType driver_type, htclow::HtclowManager *htclow_manager);
void FinalizePowerStateMonitor();
void LoopMonitorPowerState();
}
}
namespace htclow::driver {
void InitializeSocketApiForSocketDriver();
}
namespace init {
void InitializeSystemModule() {
/* Initialize heap. */
htc::InitializeHeap();
/* Initialize our connection to sm. */
R_ABORT_UNLESS(sm::Initialize());
/* Initialize fs. */
fs::InitializeForSystem();
fs::SetAllocator(htc::Allocate, htc::Deallocate);
fs::SetEnabledAutoAbort(false);
/* Initialize other services we need. */
R_ABORT_UNLESS(setsysInitialize());
R_ABORT_UNLESS(setcalInitialize());
R_ABORT_UNLESS(pscmInitialize());
/* Mount the SD card. */
R_ABORT_UNLESS(fs::MountSdCard("sdmc"));
/* Verify that we can sanely execute. */
ams::CheckApiVersion();
}
void FinalizeSystemModule() { /* ... */ }
void Startup() { /* ... */ }
}
void Main() {
/* Set thread name. */
os::SetThreadNamePointer(os::GetCurrentThread(), AMS_GET_SYSTEM_THREAD_NAME(htc, Main));
AMS_ASSERT(os::GetThreadPriority(os::GetCurrentThread()) == AMS_GET_SYSTEM_THREAD_PRIORITY(htc, Main));
/* Get and set the default driver type. */
const auto driver_type = htc::GetHtclowDriverType();
htclow::HtclowManagerHolder::SetDefaultDriver(driver_type);
/* If necessary, initialize the socket driver. */
if (driver_type == htclow::impl::DriverType::Socket) {
htclow::driver::InitializeSocketApiForSocketDriver();
}
/* Initialize the htclow manager. */
htclow::HtclowManagerHolder::AddReference();
ON_SCOPE_EXIT { htclow::HtclowManagerHolder::Release(); };
/* Get the htclow manager. */
auto *htclow_manager = htclow::HtclowManagerHolder::GetHtclowManager();
/* Initialize the htc misc server. */
htc::server::InitializeHtcmiscServer(htclow_manager);
/* Create the htc misc ipc thread. */
os::ThreadType htc_ipc_thread;
os::CreateThread(std::addressof(htc_ipc_thread), htc::HtcIpcThreadFunction, nullptr, htc::g_htc_ipc_thread_stack, sizeof(htc::g_htc_ipc_thread_stack), AMS_GET_SYSTEM_THREAD_PRIORITY(htc, HtcIpc));
os::SetThreadNamePointer(std::addressof(htc_ipc_thread), AMS_GET_SYSTEM_THREAD_NAME(htc, HtcIpc));
/* Initialize the htcfs server. */
htcfs::Initialize(htclow_manager);
htcfs::RegisterHipcServer();
/* Create the htcfs ipc thread. */
os::ThreadType htcfs_ipc_thread;
os::CreateThread(std::addressof(htcfs_ipc_thread), htc::HtcfsIpcThreadFunction, nullptr, htc::g_htcfs_ipc_thread_stack, sizeof(htc::g_htcfs_ipc_thread_stack), AMS_GET_SYSTEM_THREAD_PRIORITY(htc, HtcfsIpc));
os::SetThreadNamePointer(std::addressof(htcfs_ipc_thread), AMS_GET_SYSTEM_THREAD_NAME(htc, HtcfsIpc));
/* Initialize the htcs server. */
htcs::server::Initialize();
htcs::server::RegisterHipcServer();
/* Create the htcs ipc threads. */
os::ThreadType htcs_ipc_threads[htc::NumHtcsIpcThreads];
for (size_t i = 0; i < htc::NumHtcsIpcThreads; ++i) {
os::CreateThread(std::addressof(htcs_ipc_threads[i]), htc::HtcsIpcThreadFunction, nullptr, htc::g_htcs_ipc_thread_stack[i], sizeof(htc::g_htcs_ipc_thread_stack[i]), AMS_GET_SYSTEM_THREAD_PRIORITY(htc, HtcsIpc));
os::SetThreadNamePointer(std::addressof(htcs_ipc_threads[i]), AMS_GET_SYSTEM_THREAD_NAME(htc, HtcsIpc));
}
/* Initialize psc. */
htc::server::InitializePowerStateMonitor(driver_type, htclow_manager);
/* Start all threads. */
os::StartThread(std::addressof(htc_ipc_thread));
os::StartThread(std::addressof(htcfs_ipc_thread));
for (size_t i = 0; i < htc::NumHtcsIpcThreads; ++i) {
os::StartThread(std::addressof(htcs_ipc_threads[i]));
}
/* Loop psc monitor. */
htc::server::LoopMonitorPowerState();
/* Destroy all threads. */
for (size_t i = 0; i < htc::NumHtcsIpcThreads; ++i) {
os::WaitThread(std::addressof(htcs_ipc_threads[i]));
os::DestroyThread(std::addressof(htcs_ipc_threads[i]));
}
os::WaitThread(std::addressof(htcfs_ipc_thread));
os::DestroyThread(std::addressof(htcfs_ipc_thread));
os::WaitThread(std::addressof(htc_ipc_thread));
os::DestroyThread(std::addressof(htc_ipc_thread));
/* Finalize psc monitor. */
htc::server::FinalizePowerStateMonitor();
}
}
| 9,107
|
C++
|
.cpp
| 173
| 41.075145
| 223
| 0.608382
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,104
|
dmnt2_software_breakpoint.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/dmnt.gen2/source/dmnt2_software_breakpoint.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "dmnt2_software_breakpoint.hpp"
#include "dmnt2_debug_process.hpp"
#include "dmnt2_debug_log.hpp"
namespace ams::dmnt {
namespace {
constexpr const u8 Aarch64BreakInstruction[] = {0xFF, 0xFF, 0xFF, 0xE7};
constexpr const u8 Aarch32BreakInstruction[] = {0xFE, 0xDE, 0xFF, 0xE7};
constexpr const u8 Aarch32ThumbBreakInstruction[] = {0x80, 0xB6};
}
Result SoftwareBreakPoint::Clear(DebugProcess *debug_process) {
Result result = svc::ResultInvalidArgument();
if (m_in_use) {
if (m_address) {
result = debug_process->WriteMemory(std::addressof(m_insn), m_address, m_size);
if (R_SUCCEEDED(result)) {
AMS_DMNT2_GDB_LOG_DEBUG("SoftwareBreakPoint::Clear %p 0x%lx, insn=0x%x\n", this, m_address, m_insn);
} else {
AMS_DMNT2_GDB_LOG_DEBUG("SoftwareBreakPoint::Clear %p 0x%lx, insn=0x%x, !!! Fail %08x !!!\n", this, m_address, m_insn, result.GetValue());
}
this->Reset();
} else {
AMS_DMNT2_GDB_LOG_ERROR("SoftwareBreakPoint::Clear %p 0x%lx, insn=0x%x, !!! Null Address !!!\n", this, m_address, m_insn);
}
}
R_RETURN(result);
}
Result SoftwareBreakPoint::Set(DebugProcess *debug_process, uintptr_t address, size_t size, bool is_step) {
/* Set fields. */
m_is_step = is_step;
m_address = address;
m_size = size;
/* Read our instruction. */
Result result = debug_process->ReadMemory(std::addressof(m_insn), m_address, m_size);
AMS_DMNT2_GDB_LOG_DEBUG("SoftwareBreakPoint::Set %p 0x%lx, insn=0x%x\n", this, m_address, m_insn);
/* Set the breakpoint. */
if (debug_process->Is64Bit()) {
if (m_size == sizeof(Aarch64BreakInstruction)) {
result = debug_process->WriteMemory(Aarch64BreakInstruction, m_address, m_size);
} else {
result = svc::ResultInvalidArgument();
}
} else {
if (m_size == sizeof(Aarch32BreakInstruction) || m_size == sizeof(Aarch32ThumbBreakInstruction)) {
result = debug_process->WriteMemory(m_size == sizeof(Aarch32BreakInstruction) ? Aarch32BreakInstruction : Aarch32ThumbBreakInstruction, m_address, m_size);
} else {
result = svc::ResultInvalidArgument();
}
}
/* Check that we succeeded. */
if (R_SUCCEEDED(result)) {
m_in_use = true;
}
R_RETURN(result);
}
SoftwareBreakPointManager::SoftwareBreakPointManager(DebugProcess *debug_process) : BreakPointManager(debug_process) {
/* ... */
}
BreakPointBase *SoftwareBreakPointManager::GetBreakPoint(size_t index) {
if (index < util::size(m_breakpoints)) {
return m_breakpoints + index;
} else {
return nullptr;
}
}
}
| 3,662
|
C++
|
.cpp
| 81
| 36.555556
| 171
| 0.619849
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,105
|
dmnt2_transport_session.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/dmnt.gen2/source/dmnt2_transport_session.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "dmnt2_transport_layer.hpp"
#include "dmnt2_transport_session.hpp"
#include "dmnt2_debug_log.hpp"
namespace ams::dmnt {
TransportSession::TransportSession(int fd) : m_socket(fd), m_valid(true) {
/* Create our thread. */
R_ABORT_UNLESS(os::CreateThread(std::addressof(m_receive_thread), ReceiveThreadEntry, this, m_receive_thread_stack, sizeof(m_receive_thread_stack), os::HighestThreadPriority - 1));
/* Start our thread. */
os::StartThread(std::addressof(m_receive_thread));
/* Note that we connected. */
AMS_DMNT2_GDB_LOG_INFO("Created Session %d\n", m_socket);
}
TransportSession::~TransportSession() {
/* Note that we connected. */
AMS_DMNT2_GDB_LOG_INFO("Closing Session %d\n", m_socket);
/* Invalidate our receive buffer. */
m_receive_buffer.Invalidate();
/* Shutdown our socket. */
transport::Shutdown(m_socket);
/* Wait for our thread. */
os::WaitThread(std::addressof(m_receive_thread));
os::DestroyThread(std::addressof(m_receive_thread));
/* Close our socket. */
transport::Close(m_socket);
}
bool TransportSession::WaitToBeReadable() {
return m_receive_buffer.WaitToBeReadable();
}
bool TransportSession::WaitToBeReadable(TimeSpan timeout) {
return m_receive_buffer.WaitToBeReadable(timeout);
}
util::optional<char> TransportSession::GetChar() {
/* Wait for us to have data. */
m_receive_buffer.WaitToBeReadable();
/* Get our data. */
char c;
if (m_receive_buffer.Read(std::addressof(c), sizeof(c)) > 0) {
return c;
} else {
return util::nullopt;
}
}
ssize_t TransportSession::PutChar(char c) {
/* Send the character. */
const auto sent = transport::Send(m_socket, std::addressof(c), sizeof(c), 0);
if (sent < 0) {
m_valid = false;
}
return sent;
}
ssize_t TransportSession::PutString(const char *str) {
/* Repeatedly send until all is sent. */
const size_t len = std::strlen(str);
size_t remaining = len;
while (remaining > 0) {
const auto sent = transport::Send(m_socket, str, remaining, 0);
if (sent >= 0) {
remaining -= sent;
str += sent;
} else {
m_valid = false;
return sent;
}
}
return len;
}
void TransportSession::ReceiveThreadFunction() {
/* Create temporary buffer. */
u8 buffer[TransportReceiveBuffer::ReceiveBufferSize];
/* Loop receiving data. */
while (true) {
/* Receive data. */
const auto res = transport::Recv(m_socket, buffer, sizeof(buffer), 0);
if (res > 0) {
/* Write the data to our buffer. */
m_receive_buffer.WaitToBeWritable();
m_receive_buffer.Write(buffer, res);
} else {
/* Otherwise, if we got an error other than "try again", we're done. */
if (!transport::IsLastErrorEAgain()) {
AMS_DMNT2_GDB_LOG_INFO("Session %d invalid, res=%ld, err=%d\n", m_socket, res, static_cast<int>(transport::GetLastError()));
m_valid = false;
break;
}
}
}
/* Invalidate our receive buffer. */
m_receive_buffer.Invalidate();
}
}
| 4,225
|
C++
|
.cpp
| 106
| 31.160377
| 188
| 0.598243
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,106
|
dmnt2_gdb_packet_io.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/dmnt.gen2/source/dmnt2_gdb_packet_io.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "dmnt2_gdb_packet_io.hpp"
#include "dmnt2_debug_log.hpp"
namespace ams::dmnt {
namespace {
constexpr char BreakCharacter = '\x03'; /* ctrl-c */
constexpr int DecodeHex(char c) {
if ('a' <= c && c <= 'f') {
return 10 + (c - 'a');
} else if ('A' <= c && c <= 'F') {
return 10 + (c - 'A');
} else if ('0' <= c && c <= '9') {
return 0 + (c - '0');
} else {
return -1;
}
}
constexpr char EncodeHex(u8 v) {
return "0123456789abcdef"[v & 0xF];
}
}
void GdbPacketIo::SendPacket(bool *out_break, const char *src, TransportSession *session) {
/* Default to not breaked. */
*out_break = false;
/* Send a packet. */
while (true) {
std::scoped_lock lk(m_mutex);
size_t len = 0;
u8 checksum = 0;
while (src[len] != 0) {
checksum += static_cast<u8>(src[len++]);
}
char buffer[1 + GdbPacketBufferSize + 4];
buffer[0] = '$';
std::memcpy(buffer + 1, src, len);
buffer[1 + len] = '#';
buffer[2 + len] = EncodeHex(checksum >> 4);
buffer[3 + len] = EncodeHex(checksum >> 0);
buffer[4 + len] = 0;
if (session->PutString(buffer) < 0) {
/* Log (truncated) copy of packet. */
AMS_DMNT2_GDB_LOG_ERROR("Failed to send packet %s\n", buffer);
return;
}
if (m_no_ack) {
return;
}
/* Check to see if we need to retransmit. */
bool retransmit = false;
do {
if (const auto char_holder = session->GetChar(); char_holder) {
switch (*char_holder) {
case BreakCharacter:
*out_break = true;
return;
case '+':
return;
case '-':
retransmit = true;
break;
default:
break;
}
} else {
/* Log (truncated) copy of packet. */
AMS_DMNT2_GDB_LOG_ERROR("Failed to receive ack for %s\n", buffer);
return;
}
} while (!retransmit);
}
}
char *GdbPacketIo::ReceivePacket(bool *out_break, char *dst, size_t size, TransportSession *session) {
/* Default to not breaked. */
*out_break = false;
/* Receive a packet. */
while (true) {
/* Wait for data to be available. */
if (!session->WaitToBeReadable()) {
return nullptr;
}
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Verify that we still have data immediately available. */
if (!session->WaitToBeReadable(0)) {
continue;
}
/* Prepare to parse. */
enum class State {
Initial,
PacketData,
ChecksumHigh,
ChecksumLow
};
State state = State::Initial;
u8 checksum = 0;
int csum_high = -1, csum_low = -1;
size_t count = 0;
/* Read characters. */
while (true) {
if (const auto char_holder = session->GetChar(); char_holder) {
const auto c = *char_holder;
switch (state) {
case State::Initial:
if (c == '$') {
state = State::PacketData;
} else if (c == BreakCharacter) {
*out_break = true;
return nullptr;
}
break;
case State::PacketData:
/* TODO: Escaped characters. */
if (c == '#') {
dst[count] = 0;
state = State::ChecksumHigh;
} else {
AMS_ABORT_UNLESS(count < size - 1);
checksum += static_cast<u8>(c);
dst[count++] = c;
}
break;
case State::ChecksumHigh:
csum_high = DecodeHex(c);
state = State::ChecksumLow;
break;
case State::ChecksumLow:
csum_low = DecodeHex(c);
if (m_no_ack) {
return dst;
} else {
const u8 expectsum = (static_cast<u8>(csum_high) << 4) | (static_cast<u8>(csum_low) << 0);
if (csum_high < 0 || csum_low < 0 || checksum != expectsum) {
/* Request retransmission. */
state = State::Initial;
checksum = 0;
csum_high = -1;
csum_low = -1;
count = 0;
session->PutChar('-');
} else {
session->PutChar('+');
return dst;
}
}
break;
}
} else {
return nullptr;
}
}
}
}
}
| 6,756
|
C++
|
.cpp
| 168
| 22.52381
| 122
| 0.396678
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,107
|
dmnt2_transport_layer.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/dmnt.gen2/source/dmnt2_transport_layer.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "dmnt2_transport_layer.hpp"
namespace ams::dmnt::transport {
namespace {
enum SocketMode {
SocketMode_Invalid,
SocketMode_Htcs,
SocketMode_Tcp,
};
constexpr inline const u16 ListenPort_GdbServer = 22225;
constexpr inline const u16 ListenPort_GdbDebugLog = 22227;
constinit os::SdkMutex g_socket_init_mutex;
constinit SocketMode g_socket_mode = SocketMode_Invalid;
constexpr inline size_t RequiredAlignment = std::max(os::ThreadStackAlignment, os::MemoryPageSize);
using SocketConfigType = socket::SystemConfigLightDefault;
/* TODO: If we ever use resolvers, increase this. */
constexpr inline size_t SocketAllocatorSize = 4_KB;
constexpr inline size_t SocketMemoryPoolSize = util::AlignUp(SocketConfigType::PerTcpSocketWorstCaseMemoryPoolSize + SocketConfigType::PerUdpSocketWorstCaseMemoryPoolSize, os::MemoryPageSize);
constexpr inline size_t SocketRequiredSize = util::AlignUp(SocketMemoryPoolSize + SocketAllocatorSize, os::MemoryPageSize);
/* Declare the memory pool. */
alignas(RequiredAlignment) constinit u8 g_socket_memory[SocketRequiredSize];
constexpr inline const SocketConfigType SocketConfig(g_socket_memory, SocketRequiredSize, SocketAllocatorSize, 2);
}
void InitializeByHtcs() {
std::scoped_lock lk(g_socket_init_mutex);
AMS_ABORT_UNLESS(g_socket_mode == SocketMode_Invalid);
constexpr auto HtcsSocketCountMax = 8;
const size_t buffer_size = htcs::GetWorkingMemorySize(HtcsSocketCountMax);
AMS_ABORT_UNLESS(sizeof(g_socket_memory) >= buffer_size);
htcs::InitializeForSystem(g_socket_memory, sizeof(g_socket_memory), HtcsSocketCountMax);
g_socket_mode = SocketMode_Htcs;
}
void InitializeByTcp() {
std::scoped_lock lk(g_socket_init_mutex);
AMS_ABORT_UNLESS(g_socket_mode == SocketMode_Invalid);
R_ABORT_UNLESS(socket::Initialize(SocketConfig));
g_socket_mode = SocketMode_Tcp;
}
s32 Socket() {
switch (g_socket_mode) {
case SocketMode_Htcs: return htcs::Socket();
case SocketMode_Tcp: return socket::Socket(socket::Family::Af_Inet, socket::Type::Sock_Stream, socket::Protocol::IpProto_Tcp);
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
s32 Close(s32 desc) {
switch (g_socket_mode) {
case SocketMode_Htcs: return htcs::Close(desc);
case SocketMode_Tcp: return socket::Close(desc);
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
s32 Bind(s32 desc, PortName port_name) {
switch (g_socket_mode) {
case SocketMode_Htcs:
{
htcs::SockAddrHtcs addr;
addr.family = htcs::HTCS_AF_HTCS;
addr.peer_name = htcs::GetPeerNameAny();
switch (port_name) {
case PortName_GdbServer: std::strcpy(addr.port_name.name, "iywys@$gdb"); break;
case PortName_GdbDebugLog: std::strcpy(addr.port_name.name, "iywys@$dmnt2_log"); break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
return htcs::Bind(desc, std::addressof(addr));
}
break;
case SocketMode_Tcp:
{
socket::SockAddrIn addr = {};
addr.sin_family = socket::Family::Af_Inet;
addr.sin_addr.s_addr = socket::InAddr_Any;
switch (port_name){
case PortName_GdbServer: addr.sin_port = socket::InetHtons(static_cast<u16>(ListenPort_GdbServer)); break;
case PortName_GdbDebugLog: addr.sin_port = socket::InetHtons(static_cast<u16>(ListenPort_GdbDebugLog)); break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
return socket::Bind(desc, reinterpret_cast<socket::SockAddr *>(std::addressof(addr)), sizeof(addr));
}
break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
s32 Listen(s32 desc, s32 backlog_count) {
switch (g_socket_mode) {
case SocketMode_Htcs: return htcs::Listen(desc, backlog_count);
case SocketMode_Tcp: return socket::Listen(desc, backlog_count);
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
s32 Accept(s32 desc) {
switch (g_socket_mode) {
case SocketMode_Htcs:
{
htcs::SockAddrHtcs addr;
addr.family = htcs::HTCS_AF_HTCS;
addr.peer_name = htcs::GetPeerNameAny();
addr.port_name.name[0] = '\x00';
return htcs::Accept(desc, std::addressof(addr));
}
break;
case SocketMode_Tcp:
{
socket::SockAddrIn addr = {};
socket::SockLenT addr_len = sizeof(addr);
return socket::Accept(desc, reinterpret_cast<socket::SockAddr *>(std::addressof(addr)), std::addressof(addr_len));
}
break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
s32 Shutdown(s32 desc) {
switch (g_socket_mode) {
case SocketMode_Htcs: return htcs::Shutdown(desc, htcs::HTCS_SHUT_RDWR);
case SocketMode_Tcp: return socket::Shutdown(desc, socket::ShutdownMethod::Shut_RdWr);
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
ssize_t Recv(s32 desc, void *buffer, size_t buffer_size, s32 flags) {
switch (g_socket_mode) {
case SocketMode_Htcs: return htcs::Recv(desc, buffer, buffer_size, flags);
case SocketMode_Tcp: return socket::Recv(desc, buffer, buffer_size, static_cast<socket::MsgFlag>(flags));
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
ssize_t Send(s32 desc, const void *buffer, size_t buffer_size, s32 flags) {
switch (g_socket_mode) {
case SocketMode_Htcs: return htcs::Send(desc, buffer, buffer_size, flags);
case SocketMode_Tcp: return socket::Send(desc, buffer, buffer_size, static_cast<socket::MsgFlag>(flags));
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
s32 GetLastError() {
switch (g_socket_mode) {
case SocketMode_Htcs: return htcs::GetLastError();
case SocketMode_Tcp: return static_cast<s32>(socket::GetLastError());
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
bool IsLastErrorEAgain() {
switch (g_socket_mode) {
case SocketMode_Htcs: return htcs::GetLastError() == htcs::HTCS_EAGAIN;
case SocketMode_Tcp: return socket::GetLastError() == socket::Errno::EAgain;
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
}
| 7,656
|
C++
|
.cpp
| 162
| 36.061728
| 200
| 0.607641
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,108
|
dmnt2_gdb_server.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/dmnt.gen2/source/dmnt2_gdb_server.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "dmnt2_debug_log.hpp"
#include "dmnt2_transport_layer.hpp"
#include "dmnt2_gdb_server.hpp"
#include "dmnt2_gdb_server_impl.hpp"
namespace ams::dmnt {
namespace {
constexpr size_t ServerThreadStackSize = util::AlignUp(4 * GdbPacketBufferSize + os::MemoryPageSize, os::ThreadStackAlignment);
alignas(os::ThreadStackAlignment) constinit u8 g_server_thread_stack[ServerThreadStackSize];
alignas(os::ThreadStackAlignment) constinit u8 g_events_thread_stack[util::AlignUp(2 * GdbPacketBufferSize + os::MemoryPageSize, os::ThreadStackAlignment)];
constinit os::ThreadType g_server_thread;
constinit util::TypedStorage<GdbServerImpl> g_gdb_server;
void GdbServerThreadFunction(void *) {
/* Loop forever, servicing our gdb server. */
while (true) {
/* Get a socket. */
int fd;
while ((fd = transport::Socket()) == -1) {
os::SleepThread(TimeSpan::FromSeconds(1));
}
/* Ensure we cleanup the socket when we're done with it. */
ON_SCOPE_EXIT {
transport::Close(fd);
os::SleepThread(TimeSpan::FromSeconds(1));
};
/* Bind. */
if (transport::Bind(fd, transport::PortName_GdbServer) == -1) {
continue;
}
/* Listen on our port. */
while (transport::Listen(fd, 0) == 0) {
/* Continue accepting clients, so long as we can. */
int client_fd;
while (true) {
/* Try to accept a client. */
if (client_fd = transport::Accept(fd); client_fd < 0) {
break;
}
{
/* Create gdb server for the socket. */
util::ConstructAt(g_gdb_server, client_fd, g_events_thread_stack, sizeof(g_events_thread_stack));
ON_SCOPE_EXIT { util::DestroyAt(g_gdb_server); };
/* Process for the server. */
util::GetReference(g_gdb_server).LoopProcess();
}
/* Close the client socket. */
transport::Close(client_fd);
}
}
}
}
}
void InitializeGdbServer() {
/* Create and start gdb server threads. */
R_ABORT_UNLESS(os::CreateThread(std::addressof(g_server_thread), GdbServerThreadFunction, nullptr, g_server_thread_stack, sizeof(g_server_thread_stack), os::HighestThreadPriority - 1));
os::StartThread(std::addressof(g_server_thread));
}
}
| 3,508
|
C++
|
.cpp
| 73
| 35.191781
| 193
| 0.567417
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,109
|
dmnt2_hardware_watchpoint.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/dmnt.gen2/source/dmnt2_hardware_watchpoint.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "dmnt2_hardware_watchpoint.hpp"
#include "dmnt2_hardware_breakpoint.hpp"
#include "dmnt2_debug_process.hpp"
#include "dmnt2_debug_log.hpp"
namespace ams::dmnt {
namespace {
Result SetDataBreakPoint(svc::HardwareBreakPointRegisterName reg, svc::HardwareBreakPointRegisterName ctx, u64 address, u64 size, bool read, bool write) {
/* Determine lsc. */
const u8 lsc = (read ? 1 : 0) | (write ? 2 : 0);
/* Check that the watchpoint is valid. */
if (lsc != 0) {
R_UNLESS(HardwareWatchPointManager::IsValidWatchPoint(address, size), svc::ResultInvalidArgument());
}
/* Determine bas/mask. */
u8 bas = 0, mask = 0;
if (size <= 8) {
bas = ((1 << size) - 1) << (address & 7);
address = util::AlignDown(address, 8);
} else {
bas = 0xFF;
mask = util::PopCount(size - 1);
}
/* Build dbgbcr value. */
const u64 dbgbcr = (mask << 24) | (ctx << 16) | (bas << 5) | (lsc << 3) | ((lsc != 0) ? 1 : 0);
/* Set the breakpoint. */
const Result result = HardwareBreakPointManager::SetHardwareBreakPoint(reg, dbgbcr, address);
if (R_FAILED(result)) {
AMS_DMNT2_GDB_LOG_ERROR("SetDataBreakPoint FAIL 0x%08x, reg=%d, address=0x%lx\n", result.GetValue(), reg, address);
}
R_RETURN(result);
}
}
bool HardwareWatchPointManager::IsValidWatchPoint(u64 address, u64 size) {
/* Check size. */
if (size == 0) {
AMS_DMNT2_GDB_LOG_ERROR("HardwareWatchPointManager::IsValidWatchPoint(%lx, %lx) FAIL size == 0\n", address, size);
return false;
}
/* Validate. */
if (size <= 8) {
/* Check that address is aligned. */
if (util::AlignDown(address, 8) != util::AlignDown(address + size - 1, 8)) {
AMS_DMNT2_GDB_LOG_ERROR("HardwareWatchPointManager::IsValidWatchPoint(%lx, %lx) FAIL range crosses qword boundary\n", address, size);
return false;
}
} else {
/* Check size is small enough. */
if (size > 0x80000000) {
AMS_DMNT2_GDB_LOG_ERROR("HardwareWatchPointManager::IsValidWatchPoint(%lx, %lx) FAIL size too big\n", address, size);
return false;
}
/* Check size is power of two. */
if (!util::IsPowerOfTwo(size)) {
AMS_DMNT2_GDB_LOG_ERROR("HardwareWatchPointManager::IsValidWatchPoint(%lx, %lx) FAIL size not power of two\n", address, size);
return false;
}
/* Check alignment. */
if (!util::IsAligned(address, size)) {
AMS_DMNT2_GDB_LOG_ERROR("HardwareWatchPointManager::IsValidWatchPoint(%lx, %lx) FAIL address not size-aligned\n", address, size);
return false;
}
}
return true;
}
Result WatchPoint::Clear(DebugProcess *debug_process) {
AMS_UNUSED(debug_process);
Result result = svc::ResultInvalidArgument();
if (m_in_use) {
AMS_DMNT2_GDB_LOG_DEBUG("WatchPoint::Clear %p 0x%lx\n", this, m_address);
result = SetDataBreakPoint(m_reg, m_ctx, 0, 0, false, false);
this->Reset();
}
R_RETURN(result);
}
Result WatchPoint::Set(DebugProcess *debug_process, uintptr_t address, size_t size, bool read, bool write) {
/* Set fields. */
m_address = address;
m_size = size;
m_read = read;
m_write = write;
/* Set context breakpoint. */
R_TRY(HardwareBreakPointManager::SetContextBreakPoint(m_ctx, debug_process));
/* Set watchpoint. */
R_TRY(SetDataBreakPoint(m_reg, m_ctx, address, size, read, write));
/* Set as in-use. */
m_in_use = true;
R_SUCCEED();
}
HardwareWatchPointManager::HardwareWatchPointManager(DebugProcess *debug_process) : BreakPointManagerBase(debug_process) {
const svc::HardwareBreakPointRegisterName ctx = HardwareBreakPointManager::GetWatchPointContextRegister();
for (size_t i = 0; i < util::size(m_breakpoints); ++i) {
m_breakpoints[i].Initialize(static_cast<svc::HardwareBreakPointRegisterName>(svc::HardwareBreakPointRegisterName_D0 + i), ctx);
}
}
BreakPointBase *HardwareWatchPointManager::GetBreakPoint(size_t index) {
if (index < util::size(m_breakpoints)) {
return m_breakpoints + index;
} else {
return nullptr;
}
}
Result HardwareWatchPointManager::SetWatchPoint(u64 address, u64 size, bool read, bool write) {
/* Get a free watchpoint. */
auto *bp = static_cast<WatchPoint *>(this->GetFreeBreakPoint());
R_UNLESS(bp != nullptr, svc::ResultOutOfHandles());
/* Set the watchpoint. */
R_RETURN(bp->Set(m_debug_process, address, size, read, write));
}
Result HardwareWatchPointManager::GetWatchPointInfo(u64 address, bool &read, bool &write) {
/* Find a matching watchpoint. */
for (const auto &bp : m_breakpoints) {
if (bp.m_in_use) {
if (bp.m_address <= address && address < bp.m_address + bp.m_size) {
read = bp.m_read;
write = bp.m_write;
R_SUCCEED();
}
}
}
/* Otherwise, we failed. */
AMS_DMNT2_GDB_LOG_ERROR("HardwareWatchPointManager::GetWatchPointInfo FAIL 0x%lx\n", address);
read = false;
write = false;
R_THROW(svc::ResultInvalidArgument());
}
}
| 6,467
|
C++
|
.cpp
| 142
| 35.690141
| 162
| 0.592093
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,110
|
dmnt2_breakpoint_manager.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/dmnt.gen2/source/dmnt2_breakpoint_manager.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "dmnt2_breakpoint_manager.hpp"
#include "dmnt2_debug_process.hpp"
#include "dmnt2_debug_log.hpp"
namespace ams::dmnt {
BreakPointManager::BreakPointManager(DebugProcess *debug_process) : BreakPointManagerBase(debug_process) {
/* ... */
}
void BreakPointManager::ClearStep() {
BreakPoint *bp = nullptr;
for (size_t i = 0; (bp = static_cast<BreakPoint *>(this->GetBreakPoint(i))) != nullptr; ++i) {
if (bp->m_in_use && bp->m_is_step) {
AMS_DMNT2_GDB_LOG_DEBUG("BreakPointManager::ClearStep %p 0x%lx (idx=%zu)\n", bp, bp->m_address, i);
bp->Clear(m_debug_process);
}
}
}
Result BreakPointManager::SetBreakPoint(uintptr_t address, size_t size, bool is_step) {
/* Get a free breakpoint. */
BreakPoint *bp = static_cast<BreakPoint *>(this->GetFreeBreakPoint());
/* Set the breakpoint. */
Result result = svc::ResultOutOfHandles();
if (bp != nullptr) {
result = bp->Set(m_debug_process, address, size, is_step);
}
if (R_FAILED(result)) {
AMS_DMNT2_GDB_LOG_DEBUG("BreakPointManager::SetBreakPoint %p 0x%lx !!! Fail 0x%08x !!!\n", bp, address, result.GetValue());
}
R_RETURN(result);
}
}
| 1,967
|
C++
|
.cpp
| 46
| 36.76087
| 135
| 0.654469
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,111
|
dmnt2_hardware_breakpoint.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/dmnt.gen2/source/dmnt2_hardware_breakpoint.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "dmnt2_hardware_breakpoint.hpp"
#include "dmnt2_debug_process.hpp"
#include "dmnt2_debug_log.hpp"
namespace ams::dmnt {
namespace {
constinit auto g_last_bp_register = -1;
constinit auto g_first_bp_ctx_register = -1;
constinit auto g_last_bp_ctx_register = -1;
constinit auto g_last_wp_register = -1;
constinit os::SdkMutex g_multicore_lock;
constinit bool g_multicore_started = false;
alignas(os::ThreadStackAlignment) constinit u8 g_multicore_thread_stack[16_KB];
constinit os::ThreadType g_multicore_thread;
constinit os::MessageQueueType g_multicore_request_queue;
constinit os::MessageQueueType g_multicore_response_queue;
constinit uintptr_t g_multicore_request_storage[2];
constinit uintptr_t g_multicore_response_storage[2];
void MultiCoreThread(void *) {
/* Get thread core mask. */
s32 cur_core;
u64 core_mask;
R_ABORT_UNLESS(svc::GetThreadCoreMask(std::addressof(cur_core), std::addressof(core_mask), svc::PseudoHandle::CurrentThread));
/* Service requests. */
while (true) {
/* Wait for a request to come in. */
uintptr_t request_v;
os::ReceiveMessageQueue(std::addressof(request_v), std::addressof(g_multicore_request_queue));
/* Process the request. */
const uintptr_t *request = reinterpret_cast<const uintptr_t *>(request_v);
bool success = true;
if (request[0] == 1) {
/* Set on each core. */
for (s32 core = 0; core < 4; ++core) {
/* Switch to the desired core. */
R_ABORT_UNLESS(svc::SetThreadCoreMask(svc::PseudoHandle::CurrentThread, core, (1 << core)));
/* Get the core mask. */
R_ABORT_UNLESS(svc::GetThreadCoreMask(std::addressof(cur_core), std::addressof(core_mask), svc::PseudoHandle::CurrentThread));
/* Set the breakpoint. */
const Result result = svc::SetHardwareBreakPoint(static_cast<svc::HardwareBreakPointRegisterName>(request[1]), request[2], request[3]);
if (R_FAILED(result)) {
success = false;
AMS_DMNT2_GDB_LOG_ERROR("SetHardwareBreakPoint FAIL 0x%08x, core=%d, reg=%lu, ctrl=%lx, val=%lx\n", result.GetValue(), core, request[1], request[2], request[3]);
break;
}
}
}
os::SendMessageQueue(std::addressof(g_multicore_response_queue), static_cast<uintptr_t>(success));
}
}
void EnsureMultiCoreStarted() {
std::scoped_lock lk(g_multicore_lock);
if (!g_multicore_started) {
os::InitializeMessageQueue(std::addressof(g_multicore_request_queue), g_multicore_request_storage, util::size(g_multicore_request_storage));
os::InitializeMessageQueue(std::addressof(g_multicore_response_queue), g_multicore_response_storage, util::size(g_multicore_response_storage));
R_ABORT_UNLESS(os::CreateThread(std::addressof(g_multicore_thread), MultiCoreThread, nullptr, g_multicore_thread_stack, sizeof(g_multicore_thread_stack), os::HighestThreadPriority - 1));
os::StartThread(std::addressof(g_multicore_thread));
g_multicore_started = true;
}
}
}
Result HardwareBreakPoint::Clear(DebugProcess *debug_process) {
AMS_UNUSED(debug_process);
Result result = svc::ResultInvalidArgument();
if (m_in_use) {
AMS_DMNT2_GDB_LOG_DEBUG("HardwareBreakPoint::Clear %p 0x%lx\n", this, m_address);
result = HardwareBreakPointManager::SetExecutionBreakPoint(m_reg, m_ctx, 0);
this->Reset();
}
R_RETURN(result);
}
Result HardwareBreakPoint::Set(DebugProcess *debug_process, uintptr_t address, size_t size, bool is_step) {
/* Set fields. */
m_is_step = is_step;
m_address = address;
m_size = size;
/* Set context breakpoint. */
R_TRY(HardwareBreakPointManager::SetContextBreakPoint(m_ctx, debug_process));
/* Set execution breakpoint. */
R_TRY(HardwareBreakPointManager::SetExecutionBreakPoint(m_reg, m_ctx, address));
/* Set as in-use. */
m_in_use = true;
R_SUCCEED();
}
HardwareBreakPointManager::HardwareBreakPointManager(DebugProcess *debug_process) : BreakPointManager(debug_process) {
/* Determine the number of breakpoint registers. */
CountBreakPointRegisters();
/* Initialize all breakpoints. */
for (size_t i = 0; i < util::size(m_breakpoints); ++i) {
m_breakpoints[i].Initialize(static_cast<svc::HardwareBreakPointRegisterName>(svc::HardwareBreakPointRegisterName_I0 + i), static_cast<svc::HardwareBreakPointRegisterName>(g_first_bp_ctx_register));
}
}
BreakPointBase *HardwareBreakPointManager::GetBreakPoint(size_t index) {
if (index < util::size(m_breakpoints)) {
return m_breakpoints + index;
} else {
return nullptr;
}
}
Result HardwareBreakPointManager::SetHardwareBreakPoint(u32 r, u64 dbgbcr, u64 value) {
/* Send request. */
const uintptr_t request[4] = {
1,
r,
dbgbcr,
value
};
R_UNLESS(SendMultiCoreRequest(request), dmnt::ResultUnknown());
R_SUCCEED();
}
Result HardwareBreakPointManager::SetContextBreakPoint(svc::HardwareBreakPointRegisterName ctx, DebugProcess *debug_process) {
/* Encode the register. */
const u64 dbgbcr = (0x3 << 20) | (0 << 16) | (0xF << 5) | 1;
const Result result = SetHardwareBreakPoint(ctx, dbgbcr, debug_process->GetHandle());
if (R_FAILED(result)) {
AMS_DMNT2_GDB_LOG_ERROR("SetContextBreakPoint FAIL 0x%08x ctx=%d\n", result.GetValue(), ctx);
}
R_RETURN(result);
}
svc::HardwareBreakPointRegisterName HardwareBreakPointManager::GetWatchPointContextRegister() {
CountBreakPointRegisters();
return static_cast<svc::HardwareBreakPointRegisterName>(g_first_bp_ctx_register + 1);
}
Result HardwareBreakPointManager::SetExecutionBreakPoint(svc::HardwareBreakPointRegisterName reg, svc::HardwareBreakPointRegisterName ctx, u64 address) {
/* Encode the register. */
const u64 dbgbcr = (0x1 << 20) | (ctx << 16) | (0xF << 5) | ((address != 0) ? 1 : 0);
const Result result = SetHardwareBreakPoint(reg, dbgbcr, address);
if (R_FAILED(result)) {
AMS_DMNT2_GDB_LOG_ERROR("SetContextBreakPoint FAIL 0x%08x reg=%d, ctx=%d, address=%lx\n", result.GetValue(), reg, ctx, address);
}
R_RETURN(result);
}
void HardwareBreakPointManager::CountBreakPointRegisters() {
/* Determine the valid breakpoint extents. */
if (g_last_bp_ctx_register == -1) {
/* Keep setting until we see a failure. */
for (int i = svc::HardwareBreakPointRegisterName_I0; i <= static_cast<int>(svc::HardwareBreakPointRegisterName_I15); ++i) {
if (R_FAILED(svc::SetHardwareBreakPoint(static_cast<svc::HardwareBreakPointRegisterName>(i), 0, 0))) {
break;
}
g_last_bp_register = i;
}
AMS_DMNT2_GDB_LOG_DEBUG("Last valid breakpoint=%d\n", g_last_bp_register);
/* Determine the context register range. */
const u64 dbgbcr = (0x3 << 20) | (0x0 << 16) | (0xF << 5) | 1;
g_last_bp_ctx_register = g_last_bp_register;
for (int i = g_last_bp_ctx_register; i >= static_cast<int>(svc::HardwareBreakPointRegisterName_I0); --i) {
const Result result = svc::SetHardwareBreakPoint(static_cast<svc::HardwareBreakPointRegisterName>(i), dbgbcr, svc::PseudoHandle::CurrentProcess);
svc::SetHardwareBreakPoint(static_cast<svc::HardwareBreakPointRegisterName>(i), 0, 0);
if (R_FAILED(result)) {
if (!svc::ResultInvalidHandle::Includes(result)) {
break;
}
}
g_first_bp_ctx_register = i;
}
AMS_DMNT2_GDB_LOG_DEBUG("Context BreakPoints = %d-%d\n", g_first_bp_ctx_register, g_last_bp_ctx_register);
/* Determine valid watchpoint registers. */
for (int i = svc::HardwareBreakPointRegisterName_D0; i <= static_cast<int>(svc::HardwareBreakPointRegisterName_D15); ++i) {
if (R_FAILED(svc::SetHardwareBreakPoint(static_cast<svc::HardwareBreakPointRegisterName>(i), 0, 0))) {
break;
}
g_last_wp_register = i - svc::HardwareBreakPointRegisterName_D0;
}
AMS_DMNT2_GDB_LOG_DEBUG("Last valid watchpoint=%d\n", g_last_wp_register);
}
}
bool HardwareBreakPointManager::SendMultiCoreRequest(const void *request) {
/* Ensure the multi core thread is active. */
EnsureMultiCoreStarted();
/* Send the request. */
os::SendMessageQueue(std::addressof(g_multicore_request_queue), reinterpret_cast<uintptr_t>(request));
/* Get the response. */
uintptr_t response;
os::ReceiveMessageQueue(std::addressof(response), std::addressof(g_multicore_response_queue));
return static_cast<bool>(response);
}
}
| 10,410
|
C++
|
.cpp
| 193
| 42.689119
| 209
| 0.618008
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,112
|
dmnt2_transport_receive_buffer.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/dmnt.gen2/source/dmnt2_transport_receive_buffer.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "dmnt2_transport_receive_buffer.hpp"
namespace ams::dmnt {
ssize_t TransportReceiveBuffer::Read(void *dst, size_t size) {
/* Acquire exclusive access to ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that we're readable and valid. */
if (!(this->IsValid() && this->IsReadable())) {
return -1;
}
/* Check that we have data to read. */
const size_t readable = std::min(size, m_readable_size);
if (readable <= 0) {
return -1;
}
/* Copy the data. */
std::memcpy(dst, m_buffer + m_offset, readable);
/* Advance our pointers. */
m_readable_size -= readable;
m_offset += readable;
/* Handle the case where we're done consuming. */
if (m_readable_size == 0) {
m_offset = 0;
m_readable_event.Clear();
m_writable_event.Signal();
}
return readable;
}
ssize_t TransportReceiveBuffer::Write(const void *src, size_t size) {
/* Acquire exclusive access to ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that we're readable and valid. */
if (!(this->IsValid() && this->IsWritable())) {
return -1;
}
/* Copy the data to our buffer. */
std::memcpy(m_buffer, src, size);
/* Set our fields. */
m_readable_size = size;
m_offset = 0;
m_writable_event.Clear();
m_readable_event.Signal();
return size;
}
bool TransportReceiveBuffer::WaitToBeReadable() {
/* Check if we're already readable. */
{
std::scoped_lock lk(m_mutex);
if (this->IsReadable()) {
return true;
} else if (!this->IsValid()) {
return false;
} else {
m_readable_event.Clear();
}
}
/* Wait for us to be readable. */
m_readable_event.Wait();
return this->IsValid();
}
bool TransportReceiveBuffer::WaitToBeReadable(TimeSpan timeout) {
/* Check if we're already readable. */
{
std::scoped_lock lk(m_mutex);
if (this->IsReadable()) {
return true;
} else if (!this->IsValid()) {
return false;
} else {
m_readable_event.Clear();
}
}
/* Wait for us to be readable. */
const bool res = m_readable_event.TimedWait(timeout);
return res && this->IsValid();
}
bool TransportReceiveBuffer::WaitToBeWritable() {
/* Check if we're already writable. */
{
std::scoped_lock lk(m_mutex);
if (this->IsWritable()) {
return true;
} else if (!this->IsValid()) {
return false;
} else {
m_writable_event.Clear();
}
}
/* Wait for us to be writable. */
m_writable_event.Wait();
return this->IsValid();
}
void TransportReceiveBuffer::Invalidate() {
/* Acquire exclusive access to ourselves. */
std::scoped_lock lk(m_mutex);
/* Set ourselves as invalid. */
m_valid = false;
/* Signal our events. */
m_readable_event.Signal();
m_writable_event.Signal();
}
}
| 4,083
|
C++
|
.cpp
| 117
| 25.905983
| 76
| 0.556515
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,113
|
dmnt2_debug_process.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/dmnt.gen2/source/dmnt2_debug_process.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "dmnt2_debug_log.hpp"
#include "dmnt2_debug_process.hpp"
namespace ams::dmnt {
namespace {
s32 SignExtend(u32 value, u32 bits) {
return static_cast<s32>(value << (32 - bits)) >> (32 - bits);
}
}
Result DebugProcess::Attach(os::ProcessId process_id, bool start_process) {
/* Attach to the process. */
R_TRY(svc::DebugActiveProcess(std::addressof(m_debug_handle), process_id.value));
/* If necessary, start the process. */
if (start_process) {
R_ABORT_UNLESS(pm::dmnt::StartProcess(process_id));
}
/* Collect initial information. */
R_TRY(this->Start());
/* Get the attached modules. */
R_TRY(this->CollectModules());
/* Get our process id. */
u64 pid_value = 0;
svc::GetProcessId(std::addressof(pid_value), m_debug_handle);
m_process_id = { pid_value };
/* Get process info. */
this->CollectProcessInfo();
R_SUCCEED();
}
void DebugProcess::Detach() {
if (m_is_valid) {
m_software_breakpoints.ClearAll();
m_hardware_breakpoints.ClearAll();
m_hardware_watchpoints.ClearAll();
R_ABORT_UNLESS(svc::CloseHandle(m_debug_handle));
m_debug_handle = svc::InvalidHandle;
}
m_is_valid = false;
}
Result DebugProcess::Start() {
/* Process the initial debug events. */
s32 num_threads = 0;
bool attached = false;
while (num_threads == 0 || !attached) {
/* Wait for debug events to be available. */
s32 dummy_index;
R_ABORT_UNLESS(svc::WaitSynchronization(std::addressof(dummy_index), std::addressof(m_debug_handle), 1, svc::WaitInfinite));
/* Get debug event. */
svc::DebugEventInfo d;
R_ABORT_UNLESS(svc::GetDebugEvent(std::addressof(d), m_debug_handle));
/* Handle the debug event. */
switch (d.type) {
case svc::DebugEvent_CreateProcess:
{
/* Set our create process info. */
m_create_process_info = d.info.create_process;
/* Cache our bools. */
m_is_64_bit = (m_create_process_info.flags & svc::CreateProcessFlag_Is64Bit);
m_is_64_bit_address_space = (m_create_process_info.flags & svc::CreateProcessFlag_AddressSpaceMask) == svc::CreateProcessFlag_AddressSpace64Bit;
}
break;
case svc::DebugEvent_CreateThread:
{
++num_threads;
if (const s32 index = this->ThreadCreate(d.thread_id); index >= 0) {
const Result result = osdbg::InitializeThreadInfo(std::addressof(m_thread_infos[index]), m_debug_handle, std::addressof(m_create_process_info), std::addressof(d.info.create_thread));
if (R_FAILED(result)) {
AMS_DMNT2_GDB_LOG_WARN("DebugProcess::Start: InitializeThreadInfo(%lx) failed: %08x\n", d.thread_id, result.GetValue());
}
}
}
break;
case svc::DebugEvent_ExitThread:
{
--num_threads;
this->ThreadExit(d.thread_id);
}
break;
case svc::DebugEvent_Exception:
{
if (d.info.exception.type == svc::DebugException_DebuggerAttached) {
attached = true;
}
}
break;
default:
break;
}
}
/* Set ourselves as valid. */
m_is_valid = true;
this->SetDebugBreaked();
R_SUCCEED();
}
s32 DebugProcess::ThreadCreate(u64 thread_id) {
for (size_t i = 0; i < ThreadCountMax; ++i) {
if (!m_thread_valid[i]) {
m_thread_valid[i] = true;
m_thread_ids[i] = thread_id;
this->SetLastThreadId(thread_id);
this->SetLastSignal(GdbSignal_BreakpointTrap);
++m_thread_count;
return i;
}
}
return -1;
}
void DebugProcess::ThreadExit(u64 thread_id) {
for (size_t i = 0; i < ThreadCountMax; ++i) {
if (m_thread_valid[i] && m_thread_ids[i] == thread_id) {
m_thread_valid[i] = false;
m_thread_ids[i] = 0;
this->SetLastThreadId(thread_id);
this->SetLastSignal(GdbSignal_BreakpointTrap);
--m_thread_count;
break;
}
}
}
Result DebugProcess::CollectModules() {
/* Reset our module count. */
m_module_count = 0;
/* Traverse the address space, looking for modules. */
uintptr_t address = 0;
while (true) {
/* Query the current address. */
svc::MemoryInfo memory_info;
svc::PageInfo page_info;
if (R_SUCCEEDED(svc::QueryDebugProcessMemory(std::addressof(memory_info), std::addressof(page_info), m_debug_handle, address))) {
if (memory_info.permission == svc::MemoryPermission_ReadExecute && (memory_info.state == svc::MemoryState_Code || memory_info.state == svc::MemoryState_AliasCode)) {
/* Check that we can add the module. */
AMS_ABORT_UNLESS(m_module_count < ModuleCountMax);
/* Get module definition. */
auto &module = m_module_definitions[m_module_count++];
/* Set module address/size. */
module.SetAddressSize(memory_info.base_address, memory_info.size);
/* Get module name buffer. */
char *module_name = module.GetNameBuffer();
std::memset(module_name, 0, ModuleDefinition::PathLengthMax);
/* Read module path. */
struct {
u32 zero;
s32 path_length;
char path[ModuleDefinition::PathLengthMax];
} module_path;
if (R_SUCCEEDED(this->ReadMemory(std::addressof(module_path), memory_info.base_address + memory_info.size, sizeof(module_path)))) {
if (module_path.zero == 0 && module_path.path_length > 0) {
std::memcpy(module_name, module_path.path, std::min<size_t>(ModuleDefinition::PathLengthMax, module_path.path_length));
}
} else {
module_path.path_length = 0;
}
/* Truncate module name. */
module_name[ModuleDefinition::PathLengthMax - 1] = 0;
/* Set default module name start. */
module.SetNameStart(0);
/* Ignore leading directories. */
for (size_t i = 0; i < std::min<size_t>(ModuleDefinition::PathLengthMax, module_path.path_length) && module_name[i] != 0; ++i) {
if (module_name[i] == '/' || module_name[i] == '\\') {
module.SetNameStart(i + 1);
}
}
}
}
/* Check if we're done. */
const uintptr_t next_address = memory_info.base_address + memory_info.size;
if (memory_info.state == svc::MemoryState_Inaccessible) {
break;
}
if (next_address <= address) {
break;
}
address = next_address;
}
R_SUCCEED();
}
void DebugProcess::CollectProcessInfo() {
/* Define helper for getting process info. */
auto CollectProcessInfoImpl = [&](os::NativeHandle handle) -> Result {
/* Collect all values. */
R_TRY(svc::GetInfo(std::addressof(m_process_alias_address), svc::InfoType_AliasRegionAddress, handle, 0));
R_TRY(svc::GetInfo(std::addressof(m_process_alias_size), svc::InfoType_AliasRegionSize, handle, 0));
R_TRY(svc::GetInfo(std::addressof(m_process_heap_address), svc::InfoType_HeapRegionAddress, handle, 0));
R_TRY(svc::GetInfo(std::addressof(m_process_heap_size), svc::InfoType_HeapRegionSize, handle, 0));
R_TRY(svc::GetInfo(std::addressof(m_process_aslr_address), svc::InfoType_AslrRegionAddress, handle, 0));
R_TRY(svc::GetInfo(std::addressof(m_process_aslr_size), svc::InfoType_AslrRegionSize, handle, 0));
R_TRY(svc::GetInfo(std::addressof(m_process_stack_address), svc::InfoType_StackRegionAddress, handle, 0));
R_TRY(svc::GetInfo(std::addressof(m_process_stack_size), svc::InfoType_StackRegionSize, handle, 0));
if (m_program_location.program_id == ncm::InvalidProgramId) {
R_TRY(svc::GetInfo(std::addressof(m_program_location.program_id.value), svc::InfoType_ProgramId, handle, 0));
}
u64 value;
R_TRY(svc::GetInfo(std::addressof(value), svc::InfoType_IsApplication, handle, 0));
m_is_application = value != 0;
R_SUCCEED();
};
/* Get process info/status. */
os::NativeHandle process_handle;
if (R_FAILED(pm::dmnt::AtmosphereGetProcessInfo(std::addressof(process_handle), std::addressof(m_program_location), std::addressof(m_process_override_status), m_process_id))) {
process_handle = os::InvalidNativeHandle;
m_program_location = { ncm::InvalidProgramId, };
m_process_override_status = {};
}
ON_SCOPE_EXIT { os::CloseNativeHandle(process_handle); };
/* Try collecting from our debug handle, then the process handle. */
if (R_FAILED(CollectProcessInfoImpl(m_debug_handle)) && R_FAILED(CollectProcessInfoImpl(process_handle))) {
m_process_alias_address = 0;
m_process_alias_size = 0;
m_process_heap_address = 0;
m_process_heap_size = 0;
m_process_aslr_address = 0;
m_process_aslr_size = 0;
m_process_stack_address = 0;
m_process_stack_size = 0;
m_is_application = false;
}
}
Result DebugProcess::GetThreadContext(svc::ThreadContext *out, u64 thread_id, u32 flags) {
R_RETURN(svc::GetDebugThreadContext(out, m_debug_handle, thread_id, flags));
}
Result DebugProcess::SetThreadContext(const svc::ThreadContext *ctx, u64 thread_id, u32 flags) {
R_RETURN(svc::SetDebugThreadContext(m_debug_handle, thread_id, ctx, flags));
}
Result DebugProcess::ReadMemory(void *dst, uintptr_t address, size_t size) {
R_RETURN(svc::ReadDebugProcessMemory(reinterpret_cast<uintptr_t>(dst), m_debug_handle, address, size));
}
Result DebugProcess::WriteMemory(const void *src, uintptr_t address, size_t size) {
R_RETURN(svc::WriteDebugProcessMemory(m_debug_handle, reinterpret_cast<uintptr_t>(src), address, size));
}
Result DebugProcess::QueryMemory(svc::MemoryInfo *out, uintptr_t address) {
svc::PageInfo dummy;
R_RETURN(svc::QueryDebugProcessMemory(out, std::addressof(dummy), m_debug_handle, address));
}
Result DebugProcess::Continue() {
AMS_DMNT2_GDB_LOG_DEBUG("DebugProcess::Continue() all\n");
u64 thread_ids[] = { 0 };
R_TRY(svc::ContinueDebugEvent(m_debug_handle, svc::ContinueFlag_ExceptionHandled | svc::ContinueFlag_EnableExceptionEvent | svc::ContinueFlag_ContinueAll, thread_ids, util::size(thread_ids)));
m_continue_thread_id = 0;
m_status = ProcessStatus_Running;
this->SetLastThreadId(0);
this->SetLastSignal(GdbSignal_Signal0);
R_SUCCEED();
}
Result DebugProcess::Continue(u64 thread_id) {
AMS_DMNT2_GDB_LOG_DEBUG("DebugProcess::Continue() thread_id=%lx\n", thread_id);
u64 thread_ids[] = { thread_id };
R_TRY(svc::ContinueDebugEvent(m_debug_handle, svc::ContinueFlag_ExceptionHandled | svc::ContinueFlag_EnableExceptionEvent, thread_ids, util::size(thread_ids)));
m_continue_thread_id = thread_id;
m_status = ProcessStatus_Running;
this->SetLastThreadId(0);
this->SetLastSignal(GdbSignal_Signal0);
R_SUCCEED();
}
Result DebugProcess::Step() {
AMS_DMNT2_GDB_LOG_DEBUG("DebugProcess::Step() all\n");
R_RETURN(this->Step(this->GetLastThreadId()));
}
Result DebugProcess::Step(u64 thread_id) {
AMS_DMNT2_GDB_LOG_DEBUG("DebugProcess::Step() thread_id=%lx\n", thread_id);
/* Get the thread context. */
svc::ThreadContext ctx;
R_TRY(this->GetThreadContext(std::addressof(ctx), thread_id, svc::ThreadContextFlag_Control));
/* Note that we're stepping. */
m_stepping = true;
if (m_use_hardware_single_step) {
/* Set thread single step. */
R_TRY(this->SetThreadContext(std::addressof(ctx), thread_id, svc::ThreadContextFlag_SetSingleStep));
} else {
/* Determine where we're stepping to. */
u64 current_pc = ctx.pc;
u64 step_target = 0;
this->GetBranchTarget(ctx, thread_id, current_pc, step_target);
/* Ensure we end with valid breakpoints. */
auto bp_guard = SCOPE_GUARD { this->ClearStep(); };
/* Set step breakpoint on current pc. */
/* TODO: aarch32 breakpoints. */
if (current_pc) {
R_TRY(m_step_breakpoints.SetBreakPoint(current_pc, sizeof(u32), true));
}
if (step_target) {
R_TRY(m_step_breakpoints.SetBreakPoint(step_target, sizeof(u32), true));
}
bp_guard.Cancel();
}
R_SUCCEED();
}
void DebugProcess::ClearStep() {
/* If we should, clear our step breakpoints. */
if (m_stepping) {
m_step_breakpoints.ClearStep();
m_stepping = false;
}
}
Result DebugProcess::Break() {
if (this->GetStatus() == ProcessStatus_Running) {
AMS_DMNT2_GDB_LOG_DEBUG("DebugProcess::Break\n");
R_RETURN(svc::BreakDebugProcess(m_debug_handle));
} else {
AMS_DMNT2_GDB_LOG_ERROR("DebugProcess::Break called on non-running process!\n");
R_SUCCEED();
}
}
Result DebugProcess::Terminate() {
if (this->IsValid()) {
R_ABORT_UNLESS(svc::TerminateDebugProcess(m_debug_handle));
this->Detach();
}
R_SUCCEED();
}
void DebugProcess::GetBranchTarget(svc::ThreadContext &ctx, u64 thread_id, u64 ¤t_pc, u64 &target) {
/* Save pc, in case we modify it. */
const u64 pc = current_pc;
/* Clear the target. */
target = 0;
/* By default, we advance by four. */
current_pc += 4;
/* Get the instruction where we were. */
u32 insn = 0;
this->ReadMemory(std::addressof(insn), pc, sizeof(insn));
/* Handle by architecture. */
bool is_call = false;
if (this->Is64Bit()) {
if ((insn & 0x7C000000) == 0x14000000) {
/* Unconditional branch (b/bl) */
if (insn != 0x14000001) {
is_call = (insn & 0x80000000) == 0x80000000;
current_pc = 0;
target = SignExtend(((insn & 0x03FFFFFF) << 2), 28) + pc;
}
} else if ((insn & 0x7E000000) == 0x34000000) {
/* Compare/Branch (cbz/cbnz) */
target = SignExtend(((insn & 0x00FFFFE0) >> 3), 21) + pc;
} else if ((insn & 0x7E000000) == 0x36000000) {
/* Test and branch (tbz/tbnz) */
target = SignExtend(((insn & 0x0007FFE0) >> 3), 16) + pc;
} else if ((insn & 0xFF000010) == 0x54000000) {
/* Conditional branch (b.*) */
if ((insn & 0xF) == 0xE) {
/* Unconditional. */
current_pc = 0;
}
target = SignExtend(((insn & 0x00FFFFE0) >> 3), 21) + pc;
} else if ((insn & 0xFF8FFC1F) == 0xD60F0000) {
/* Unconditional branch */
is_call = (insn & 0x00F00000) == 0x00300000;
if (!is_call) {
current_pc = 0;
}
/* Get the register. */
svc::ThreadContext new_ctx;
if (R_SUCCEEDED(this->GetThreadContext(std::addressof(new_ctx), thread_id, svc::ThreadContextFlag_Control | svc::ThreadContextFlag_General))) {
const int reg = (insn & 0x03E0) >> 5;
if (reg < 29) {
target = new_ctx.r[reg];
} else if (reg == 29) {
target = new_ctx.fp;
} else if (reg == 30) {
target = new_ctx.lr;
} else if (reg == 31) {
target = new_ctx.sp;
}
}
}
} else {
/* TODO aarch32 branch decoding */
AMS_UNUSED(ctx);
}
}
Result DebugProcess::SetBreakPoint(uintptr_t address, size_t size, bool is_step) {
R_RETURN(m_software_breakpoints.SetBreakPoint(address, size, is_step));
}
Result DebugProcess::ClearBreakPoint(uintptr_t address, size_t size) {
m_software_breakpoints.ClearBreakPoint(address, size);
R_SUCCEED();
}
Result DebugProcess::SetHardwareBreakPoint(uintptr_t address, size_t size, bool is_step) {
R_RETURN(m_hardware_breakpoints.SetBreakPoint(address, size, is_step));
}
Result DebugProcess::ClearHardwareBreakPoint(uintptr_t address, size_t size) {
m_hardware_breakpoints.ClearBreakPoint(address, size);
R_SUCCEED();
}
Result DebugProcess::SetWatchPoint(u64 address, u64 size, bool read, bool write) {
R_RETURN(m_hardware_watchpoints.SetWatchPoint(address, size, read, write));
}
Result DebugProcess::ClearWatchPoint(u64 address, u64 size) {
R_RETURN(m_hardware_watchpoints.ClearBreakPoint(address, size));
}
Result DebugProcess::GetWatchPointInfo(u64 address, bool &read, bool &write) {
R_RETURN(m_hardware_watchpoints.GetWatchPointInfo(address, read, write));
}
bool DebugProcess::IsValidWatchPoint(u64 address, u64 size) {
return HardwareWatchPointManager::IsValidWatchPoint(address, size);
}
Result DebugProcess::GetThreadCurrentCore(u32 *out, u64 thread_id) {
u64 dummy_value;
u32 val32 = 0;
R_TRY(svc::GetDebugThreadParam(std::addressof(dummy_value), std::addressof(val32), m_debug_handle, thread_id, svc::DebugThreadParam_CurrentCore));
*out = val32;
R_SUCCEED();
}
Result DebugProcess::GetProcessDebugEvent(svc::DebugEventInfo *out) {
/* Get the event. */
R_TRY(svc::GetDebugEvent(out, m_debug_handle));
/* Process the event. */
switch (out->type) {
case svc::DebugEvent_CreateProcess:
{
/* Set our create process info. */
m_create_process_info = out->info.create_process;
/* Cache our bools. */
m_is_64_bit = (m_create_process_info.flags & svc::CreateProcessFlag_Is64Bit);
m_is_64_bit_address_space = (m_create_process_info.flags & svc::CreateProcessFlag_AddressSpaceMask) == svc::CreateProcessFlag_AddressSpace64Bit;
}
break;
case svc::DebugEvent_CreateThread:
{
if (const s32 index = this->ThreadCreate(out->thread_id); index >= 0) {
const Result result = osdbg::InitializeThreadInfo(std::addressof(m_thread_infos[index]), m_debug_handle, std::addressof(m_create_process_info), std::addressof(out->info.create_thread));
if (R_FAILED(result)) {
AMS_DMNT2_GDB_LOG_WARN("DebugProcess::GetProcessDebugEvent: InitializeThreadInfo(%lx) failed: %08x\n", out->thread_id, result.GetValue());
}
}
}
break;
case svc::DebugEvent_ExitThread:
{
this->ThreadExit(out->thread_id);
}
break;
default:
break;
}
if (out->flags & svc::DebugEventFlag_Stopped) {
this->SetDebugBreaked();
}
R_SUCCEED();
}
u64 DebugProcess::GetLastThreadId() {
/* Select our first valid thread id. */
if (m_last_thread_id == 0) {
for (size_t i = 0; i < ThreadCountMax; ++i) {
if (m_thread_valid[i]) {
SetLastThreadId(m_thread_ids[i]);
break;
}
}
}
return m_last_thread_id;
}
Result DebugProcess::GetThreadList(s32 *out_count, u64 *out_thread_ids, size_t max_count) {
s32 count = 0;
for (size_t i = 0; i < ThreadCountMax; ++i) {
if (m_thread_valid[i]) {
if (count < static_cast<s32>(max_count)) {
out_thread_ids[count++] = m_thread_ids[i];
}
}
}
*out_count = count;
R_SUCCEED();
}
Result DebugProcess::GetThreadInfoList(s32 *out_count, osdbg::ThreadInfo **out_infos, size_t max_count) {
s32 count = 0;
for (size_t i = 0; i < ThreadCountMax; ++i) {
if (m_thread_valid[i]) {
if (count < static_cast<s32>(max_count)) {
out_infos[count++] = std::addressof(m_thread_infos[i]);
}
}
}
*out_count = count;
R_SUCCEED();
}
void DebugProcess::GetThreadName(char *dst, u64 thread_id) const {
for (size_t i = 0; i < ThreadCountMax; ++i) {
if (m_thread_valid[i] && m_thread_ids[i] == thread_id) {
if (R_FAILED(osdbg::GetThreadName(dst, std::addressof(m_thread_infos[i])))) {
if (m_thread_infos[i]._thread_type != 0) {
if (m_thread_infos[i]._thread_type_type == osdbg::ThreadTypeType_Libnx) {
util::TSNPrintf(dst, os::ThreadNameLengthMax, "libnx Thread_0x%010lx", reinterpret_cast<uintptr_t>(m_thread_infos[i]._thread_type));
} else {
util::TSNPrintf(dst, os::ThreadNameLengthMax, "Thread_0x%010lx", reinterpret_cast<uintptr_t>(m_thread_infos[i]._thread_type));
}
} else {
break;
}
}
return;
}
}
util::TSNPrintf(dst, os::ThreadNameLengthMax, "Thread_ID=%lu", thread_id);
}
}
| 24,243
|
C++
|
.cpp
| 508
| 34.714567
| 210
| 0.546794
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,114
|
dmnt2_breakpoint_manager_base.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/dmnt.gen2/source/dmnt2_breakpoint_manager_base.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "dmnt2_breakpoint_manager_base.hpp"
#include "dmnt2_debug_process.hpp"
#include "dmnt2_debug_log.hpp"
namespace ams::dmnt {
BreakPointManagerBase::BreakPointManagerBase(DebugProcess *debug_process) : m_debug_process(debug_process) {
/* ... */
}
void BreakPointManagerBase::ClearAll() {
BreakPointBase *bp = nullptr;
for (size_t i = 0; (bp = static_cast<BreakPointBase *>(this->GetBreakPoint(i))) != nullptr; ++i) {
if (bp->m_in_use) {
bp->Clear(m_debug_process);
}
}
}
void BreakPointManagerBase::Reset() {
BreakPointBase *bp = nullptr;
for (size_t i = 0; (bp = static_cast<BreakPointBase *>(this->GetBreakPoint(i))) != nullptr; ++i) {
bp->Reset();
}
}
Result BreakPointManagerBase::ClearBreakPoint(uintptr_t address, size_t size) {
BreakPointBase *bp = nullptr;
for (size_t i = 0; (bp = static_cast<BreakPointBase *>(this->GetBreakPoint(i))) != nullptr; ++i) {
if (bp->m_in_use && bp->m_address == address) {
AMS_ABORT_UNLESS(bp->m_size == size);
R_RETURN(bp->Clear(m_debug_process));
}
}
R_SUCCEED();
}
BreakPointBase *BreakPointManagerBase::GetFreeBreakPoint() {
BreakPointBase *bp = nullptr;
for (size_t i = 0; (bp = static_cast<BreakPointBase *>(this->GetBreakPoint(i))) != nullptr; ++i) {
if (!bp->m_in_use) {
return bp;
}
}
return nullptr;
}
}
| 2,238
|
C++
|
.cpp
| 57
| 32.491228
| 112
| 0.625575
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,115
|
dmnt2_main.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/dmnt.gen2/source/dmnt2_main.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "dmnt2_debug_log.hpp"
#include "dmnt2_gdb_server.hpp"
#include "dmnt2_transport_layer.hpp"
namespace ams {
namespace {
bool IsHtcEnabled() {
u8 enable_htc = 0;
settings::fwdbg::GetSettingsItemValue(std::addressof(enable_htc), sizeof(enable_htc), "atmosphere", "enable_htc");
return enable_htc != 0;
}
bool IsStandaloneGdbstubEnabled() {
u8 enable_gdbstub = 0;
settings::fwdbg::GetSettingsItemValue(std::addressof(enable_gdbstub), sizeof(enable_gdbstub), "atmosphere", "enable_standalone_gdbstub");
return enable_gdbstub != 0;
}
}
namespace init {
void InitializeSystemModule() {
/* Initialize our connection to sm. */
R_ABORT_UNLESS(sm::Initialize());
/* Initialize other services we need. */
R_ABORT_UNLESS(pmdmntInitialize());
/* Verify that we can sanely execute. */
ams::CheckApiVersion();
}
void FinalizeSystemModule() { /* ... */ }
void Startup() { /* ... */ }
}
void Main() {
/* Set thread name. */
os::SetThreadNamePointer(os::GetCurrentThread(), AMS_GET_SYSTEM_THREAD_NAME(dmnt, Main));
AMS_ASSERT(os::GetThreadPriority(os::GetCurrentThread()) == AMS_GET_SYSTEM_THREAD_PRIORITY(dmnt, Main));
bool use_htcs = false, use_tcp = false;
{
R_ABORT_UNLESS(::setsysInitialize());
ON_SCOPE_EXIT { ::setsysExit(); };
use_htcs = IsHtcEnabled();
use_tcp = IsStandaloneGdbstubEnabled();
}
/* Initialize transport layer. */
if (use_htcs) {
dmnt::transport::InitializeByHtcs();
} else if (use_tcp) {
dmnt::transport::InitializeByTcp();
} else {
return;
}
/* Initialize debug log thread. */
dmnt::InitializeDebugLog();
/* Start GdbServer. */
dmnt::InitializeGdbServer();
/* TODO */
while (true) {
os::SleepThread(TimeSpan::FromDays(1));
}
}
}
| 2,801
|
C++
|
.cpp
| 73
| 30.438356
| 149
| 0.612999
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,116
|
dmnt2_debug_log.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/dmnt.gen2/source/dmnt2_debug_log.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "dmnt2_debug_log.hpp"
// TODO: This should be converted to use log manager. */
//#define AMS_DMNT2_ENABLE_HTCS_DEBUG_LOG
#if defined(AMS_DMNT2_ENABLE_HTCS_DEBUG_LOG)
namespace ams::dmnt {
namespace {
constexpr size_t NumLogBuffers = 0x200;
constexpr size_t LogBufferSize = 0x100;
constexpr inline auto LogThreadPriority = os::HighestThreadPriority - 2;
constinit os::MessageQueueType g_buf_mq;
constinit os::MessageQueueType g_req_mq;
alignas(os::ThreadStackAlignment) u8 g_log_thread_stack[os::MemoryPageSize];
constinit char g_log_buffers[NumLogBuffers][LogBufferSize];
constinit uintptr_t g_buf_mq_storage[NumLogBuffers];
constinit uintptr_t g_req_mq_storage[NumLogBuffers];
constinit os::ThreadType g_log_thread;
util::optional<char *> GetLogBuffer() {
/* Try to get a log buffer. */
uintptr_t address;
if (os::TryReceiveMessageQueue(std::addressof(address), std::addressof(g_buf_mq))) {
return reinterpret_cast<char *>(address);
} else {
return util::nullopt;
}
}
/* TODO: This is a hack because we don't have a proper LogManager system module. */
/* Eventually, this should be refactored to use normal logging. */
void DebugLogThreadFunction(void *) {
/* Loop forever, servicing our log server. */
while (true) {
/* Get a socket. */
int fd;
while ((fd = htcs::Socket()) == -1) {
os::SleepThread(TimeSpan::FromSeconds(1));
}
/* Ensure we cleanup the socket when we're done with it. */
ON_SCOPE_EXIT {
htcs::Close(fd);
os::SleepThread(TimeSpan::FromSeconds(1));
};
/* Create a sock addr for our server. */
htcs::SockAddrHtcs addr;
addr.family = htcs::HTCS_AF_HTCS;
addr.peer_name = htcs::GetPeerNameAny();
std::strcpy(addr.port_name.name, "iywys@$dmnt2_log");
/* Bind. */
if (htcs::Bind(fd, std::addressof(addr)) == -1) {
continue;
}
/* Listen on our port. */
while (htcs::Listen(fd, 0) == 0) {
/* Continue accepting clients, so long as we can. */
int client_fd;
while (true) {
/* Try to accept a client. */
if (client_fd = htcs::Accept(fd, std::addressof(addr)); client_fd < 0) {
break;
}
/* Handle the client. */
while (true) {
/* Receive a log request. */
uintptr_t log_buffer_address;
os::ReceiveMessageQueue(std::addressof(log_buffer_address), std::addressof(g_req_mq));
/* Ensure we manage our request properly. */
ON_SCOPE_EXIT { os::SendMessageQueue(std::addressof(g_buf_mq), log_buffer_address); };
/* Send the data. */
const char * const log_buffer = reinterpret_cast<const char *>(log_buffer_address);
if (htcs::Send(client_fd, log_buffer, std::strlen(log_buffer), 0) < 0) {
break;
}
}
/* Close the client socket. */
htcs::Close(client_fd);
}
}
}
}
}
void InitializeDebugLog() {
/* Initialize logging message queues. */
os::InitializeMessageQueue(std::addressof(g_buf_mq), g_buf_mq_storage, NumLogBuffers);
os::InitializeMessageQueue(std::addressof(g_req_mq), g_req_mq_storage, NumLogBuffers);
/* Initially make all log buffers available. */
for (size_t i = 0; i < NumLogBuffers; ++i) {
os::SendMessageQueue(std::addressof(g_buf_mq), reinterpret_cast<uintptr_t>(g_log_buffers[i]));
}
/* Create and start the debug log thread. */
R_ABORT_UNLESS(os::CreateThread(std::addressof(g_log_thread), DebugLogThreadFunction, nullptr, g_log_thread_stack, sizeof(g_log_thread_stack), LogThreadPriority));
os::StartThread(std::addressof(g_log_thread));
}
void DebugLog(const char *prefix, const char *fmt, ...) {
/* Try to get a log buffer. */
const auto log_buffer_holder = GetLogBuffer();
if (!log_buffer_holder) {
return;
}
/* Format into the log buffer. */
char * const log_buffer = *log_buffer_holder;
{
const auto prefix_len = std::strlen(prefix);
std::memcpy(log_buffer, prefix, prefix_len);
{
std::va_list vl;
va_start(vl, fmt);
util::VSNPrintf(log_buffer + prefix_len, LogBufferSize - prefix_len, fmt, vl);
va_end(vl);
}
}
/* Request to log. */
os::SendMessageQueue(std::addressof(g_req_mq), reinterpret_cast<uintptr_t>(log_buffer));
}
}
#else
namespace ams::dmnt {
//#define AMS_DMNT2_ENABLE_SD_CARD_DEBUG_LOG
#if defined(AMS_DMNT2_ENABLE_SD_CARD_DEBUG_LOG)
namespace {
alignas(0x40) constinit u8 g_buffer[os::MemoryPageSize * 4];
constinit lmem::HeapHandle g_debug_log_heap;
constinit fs::FileHandle g_debug_log_file;
constinit os::SdkMutex g_fs_mutex;
constinit s64 g_fs_offset = 0;
void *Allocate(size_t size) {
return lmem::AllocateFromExpHeap(g_debug_log_heap, size);
}
void Deallocate(void *p, size_t size) {
AMS_UNUSED(size);
return lmem::FreeToExpHeap(g_debug_log_heap, p);
}
}
void InitializeDebugLog() {
g_debug_log_heap = lmem::CreateExpHeap(g_buffer, sizeof(g_buffer), lmem::CreateOption_ThreadSafe);
fs::SetAllocator(Allocate, Deallocate);
fs::InitializeForSystem();
fs::SetEnabledAutoAbort(false);
R_ABORT_UNLESS(fs::MountSdCard("sdmc"));
fs::DeleteFile("sdmc:/dmnt2.log");
R_ABORT_UNLESS(fs::CreateFile("sdmc:/dmnt2.log", 0));
R_ABORT_UNLESS(fs::OpenFile(std::addressof(g_debug_log_file), "sdmc:/dmnt2.log", fs::OpenMode_Write | fs::OpenMode_AllowAppend));
}
void DebugLog(const char *prefix, const char *fmt, ...) {
/* Do nothing. */
char buffer[0x200];
{
const auto prefix_len = std::strlen(prefix);
std::memcpy(buffer, prefix, prefix_len);
std::va_list vl;
va_start(vl, fmt);
util::VSNPrintf(buffer + prefix_len, sizeof(buffer) - prefix_len, fmt, vl);
va_end(vl);
}
const auto len = std::strlen(buffer);
std::scoped_lock lk(g_fs_mutex);
R_ABORT_UNLESS(fs::WriteFile(g_debug_log_file, g_fs_offset, buffer, len, fs::WriteOption::Flush));
g_fs_offset += len;
}
#else
void InitializeDebugLog() {
/* ... */
}
void DebugLog(const char *prefix, const char *fmt, ...) {
AMS_UNUSED(prefix, fmt);
}
#endif
}
#endif
| 8,177
|
C++
|
.cpp
| 182
| 33.076923
| 171
| 0.560625
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,117
|
dmnt2_gdb_server_impl.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/dmnt.gen2/source/dmnt2_gdb_server_impl.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "dmnt2_debug_log.hpp"
#include "dmnt2_gdb_server_impl.hpp"
namespace ams::dmnt {
namespace {
constexpr const u32 SdkBreakPoint = 0xE7FFFFFF;
constexpr const u32 SdkBreakPointMask = 0xFFFFFFFF;
constexpr const u32 ArmBreakPoint = 0xE7FFDEFE;
constexpr const u32 ArmBreakPointMask = 0xFFFFFFFF;
constexpr const u32 A64BreakPoint = 0xD4200000;
constexpr const u32 A64BreakPointMask = 0xFFE0001F;
constexpr const u32 A64Halt = 0xD4400000;
constexpr const u32 A64HaltMask = 0xFFE0001F;
constexpr const u32 A32BreakPoint = 0xE1200070;
constexpr const u32 A32BreakPointMask = 0xFFF000F0;
constexpr const u32 T16BreakPoint = 0x0000BE00;
constexpr const u32 T16BreakPointMask = 0x0000FF00;
constexpr const char TargetXmlAarch64[] =
"l<?xml version=\"1.0\"?>"
"<!DOCTYPE target SYSTEM \"gdb-target.dtd\">"
"<target>"
"<architecture>aarch64</architecture>"
"<xi:include href=\"aarch64-core.xml\"/>"
"<xi:include href=\"aarch64-fpu.xml\"/>"
"</target>";
constexpr const char Aarch64CoreXml[] =
"l<?xml version=\"1.0\"?>\n"
"<!DOCTYPE feature SYSTEM \"gdb-target.dtd\">\n"
"<feature name=\"org.gnu.gdb.aarch64.core\">\n"
"\t<reg name=\"x0\" bitsize=\"64\"/>\n"
"\t<reg name=\"x1\" bitsize=\"64\"/>\n"
"\t<reg name=\"x2\" bitsize=\"64\"/>\n"
"\t<reg name=\"x3\" bitsize=\"64\"/>\n"
"\t<reg name=\"x4\" bitsize=\"64\"/>\n"
"\t<reg name=\"x5\" bitsize=\"64\"/>\n"
"\t<reg name=\"x6\" bitsize=\"64\"/>\n"
"\t<reg name=\"x7\" bitsize=\"64\"/>\n"
"\t<reg name=\"x8\" bitsize=\"64\"/>\n"
"\t<reg name=\"x9\" bitsize=\"64\"/>\n"
"\t<reg name=\"x10\" bitsize=\"64\"/>\n"
"\t<reg name=\"x11\" bitsize=\"64\"/>\n"
"\t<reg name=\"x12\" bitsize=\"64\"/>\n"
"\t<reg name=\"x13\" bitsize=\"64\"/>\n"
"\t<reg name=\"x14\" bitsize=\"64\"/>\n"
"\t<reg name=\"x15\" bitsize=\"64\"/>\n"
"\t<reg name=\"x16\" bitsize=\"64\"/>\n"
"\t<reg name=\"x17\" bitsize=\"64\"/>\n"
"\t<reg name=\"x18\" bitsize=\"64\"/>\n"
"\t<reg name=\"x19\" bitsize=\"64\"/>\n"
"\t<reg name=\"x20\" bitsize=\"64\"/>\n"
"\t<reg name=\"x21\" bitsize=\"64\"/>\n"
"\t<reg name=\"x22\" bitsize=\"64\"/>\n"
"\t<reg name=\"x23\" bitsize=\"64\"/>\n"
"\t<reg name=\"x24\" bitsize=\"64\"/>\n"
"\t<reg name=\"x25\" bitsize=\"64\"/>\n"
"\t<reg name=\"x26\" bitsize=\"64\"/>\n"
"\t<reg name=\"x27\" bitsize=\"64\"/>\n"
"\t<reg name=\"x28\" bitsize=\"64\"/>\n"
"\t<reg name=\"x29\" bitsize=\"64\"/>\n"
"\t<reg name=\"x30\" bitsize=\"64\"/>\n"
"\t<reg name=\"sp\" bitsize=\"64\" type=\"data_ptr\"/>\n"
"\t<reg name=\"pc\" bitsize=\"64\" type=\"code_ptr\"/>\n"
"\t<flags id=\"cpsr_flags\" size=\"4\">\n"
"\t\t<field name=\"SP\" start=\"0\" end=\"0\" /><!-- Stack Pointer selection -->\n"
"\t\t<field name=\"EL\" start=\"2\" end=\"3\" /><!-- Exception level -->\n"
"\t\t<field name=\"nRW\" start=\"4\" end=\"4\" /><!-- Execution state (not Register Width) 0=64-bit 1-32-bit -->\n"
"\n"
"\t\t<field name=\"F\" start=\"6\" end=\"6\" /><!-- FIQ mask -->\n"
"\t\t<field name=\"I\" start=\"7\" end=\"7\" /><!-- IRQ mask -->\n"
"\t\t<field name=\"A\" start=\"8\" end=\"8\" /><!-- SError interrupt mask -->\n"
"\t\t<field name=\"D\" start=\"9\" end=\"9\" /><!-- Debug mask bit -->\n"
"\n"
"\t\t<field name=\"SSBS\" start=\"12\" end=\"12\"/><!-- Speculative Store Bypass Safe -->\n"
"\n"
"\t\t<field name=\"IL\" start=\"20\" end=\"20\"/><!-- Illegal execution state -->\n"
"\t\t<field name=\"SS\" start=\"21\" end=\"21\"/><!-- Software step -->\n"
"\t\t<field name=\"PAN\" start=\"22\" end=\"22\"/><!-- v8.1 Privileged Access Never -->\n"
"\t\t<field name=\"UAO\" start=\"23\" end=\"23\"/><!-- v8.2 User Access Override -->\n"
"\t\t<field name=\"DIT\" start=\"24\" end=\"24\"/><!-- v8.4 Data Independent Timing -->\n"
"\t\t<field name=\"TCO\" start=\"25\" end=\"25\"/><!-- v8.5 Tag Check Override -->\n"
"\n"
"\t\t<field name=\"V\" start=\"28\" end=\"28\"/><!-- oVerflow condition flag -->\n"
"\t\t<field name=\"C\" start=\"29\" end=\"29\"/><!-- Carry condition flag -->\n"
"\t\t<field name=\"Z\" start=\"30\" end=\"30\"/><!-- Zero condition flag -->\n"
"\t\t<field name=\"N\" start=\"31\" end=\"31\"/><!-- Negative condition flag -->\n"
"\t</flags>\n"
"\t<reg name=\"cpsr\" bitsize=\"32\" type=\"cpsr_flags\"/>\n"
"</feature>";
constexpr const char Aarch64FpuXml[] =
"l<?xml version=\"1.0\"?>\n"
"<!DOCTYPE feature SYSTEM \"gdb-target.dtd\">\n"
"<feature name=\"org.gnu.gdb.aarch64.fpu\">\n"
"\t<vector id=\"v2d\" type=\"ieee_double\" count=\"2\"/>\n"
"\t<vector id=\"v2u\" type=\"uint64\" count=\"2\"/>\n"
"\t<vector id=\"v2i\" type=\"int64\" count=\"2\"/>\n"
"\t<vector id=\"v4f\" type=\"ieee_single\" count=\"4\"/>\n"
"\t<vector id=\"v4u\" type=\"uint32\" count=\"4\"/>\n"
"\t<vector id=\"v4i\" type=\"int32\" count=\"4\"/>\n"
"\t<!-- <vector id=\"v8f\" type=\"ieee_half\" count=\"8\"/> -->\n"
"\t<vector id=\"v8u\" type=\"uint16\" count=\"8\"/>\n"
"\t<vector id=\"v8i\" type=\"int16\" count=\"8\"/>\n"
"\t<vector id=\"v16u\" type=\"uint8\" count=\"16\"/>\n"
"\t<vector id=\"v16i\" type=\"int8\" count=\"16\"/>\n"
"\t<vector id=\"v1u\" type=\"uint128\" count=\"1\"/>\n"
"\t<vector id=\"v1i\" type=\"int128\" count=\"1\"/>\n"
"\t<union id=\"vnd\">\n"
"\t\t<field name=\"f\" type=\"v2d\"/>\n"
"\t\t<field name=\"u\" type=\"v2u\"/>\n"
"\t\t<field name=\"s\" type=\"v2i\"/>\n"
"\t</union>\n"
"\t<union id=\"vns\">\n"
"\t\t<field name=\"f\" type=\"v4f\"/>\n"
"\t\t<field name=\"u\" type=\"v4u\"/>\n"
"\t\t<field name=\"s\" type=\"v4i\"/>\n"
"\t</union>\n"
"\t<union id=\"vnh\">\n"
"\t\t<!-- <field name=\"f\" type=\"v8f\"/> -->\n"
"\t\t<field name=\"u\" type=\"v8u\"/>\n"
"\t\t<field name=\"s\" type=\"v8i\"/>\n"
"\t</union>\n"
"\t<union id=\"vnb\">\n"
"\t\t<field name=\"u\" type=\"v16u\"/>\n"
"\t\t<field name=\"s\" type=\"v16i\"/>\n"
"\t</union>\n"
"\t<union id=\"vnq\">\n"
"\t\t<field name=\"u\" type=\"v1u\"/>\n"
"\t\t<field name=\"s\" type=\"v1i\"/>\n"
"\t</union>\n"
"\t<union id=\"aarch64v\">\n"
"\t\t<field name=\"d\" type=\"vnd\"/>\n"
"\t\t<field name=\"s\" type=\"vns\"/>\n"
"\t\t<field name=\"h\" type=\"vnh\"/>\n"
"\t\t<field name=\"b\" type=\"vnb\"/>\n"
"\t\t<field name=\"q\" type=\"vnq\"/>\n"
"\t</union>\n"
"\t<reg name=\"v0\" bitsize=\"128\" type=\"aarch64v\" regnum=\"34\"/>\n"
"\t<reg name=\"v1\" bitsize=\"128\" type=\"aarch64v\"/>\n"
"\t<reg name=\"v2\" bitsize=\"128\" type=\"aarch64v\"/>\n"
"\t<reg name=\"v3\" bitsize=\"128\" type=\"aarch64v\"/>\n"
"\t<reg name=\"v4\" bitsize=\"128\" type=\"aarch64v\"/>\n"
"\t<reg name=\"v5\" bitsize=\"128\" type=\"aarch64v\"/>\n"
"\t<reg name=\"v6\" bitsize=\"128\" type=\"aarch64v\"/>\n"
"\t<reg name=\"v7\" bitsize=\"128\" type=\"aarch64v\"/>\n"
"\t<reg name=\"v8\" bitsize=\"128\" type=\"aarch64v\"/>\n"
"\t<reg name=\"v9\" bitsize=\"128\" type=\"aarch64v\"/>\n"
"\t<reg name=\"v10\" bitsize=\"128\" type=\"aarch64v\"/>\n"
"\t<reg name=\"v11\" bitsize=\"128\" type=\"aarch64v\"/>\n"
"\t<reg name=\"v12\" bitsize=\"128\" type=\"aarch64v\"/>\n"
"\t<reg name=\"v13\" bitsize=\"128\" type=\"aarch64v\"/>\n"
"\t<reg name=\"v14\" bitsize=\"128\" type=\"aarch64v\"/>\n"
"\t<reg name=\"v15\" bitsize=\"128\" type=\"aarch64v\"/>\n"
"\t<reg name=\"v16\" bitsize=\"128\" type=\"aarch64v\"/>\n"
"\t<reg name=\"v17\" bitsize=\"128\" type=\"aarch64v\"/>\n"
"\t<reg name=\"v18\" bitsize=\"128\" type=\"aarch64v\"/>\n"
"\t<reg name=\"v19\" bitsize=\"128\" type=\"aarch64v\"/>\n"
"\t<reg name=\"v20\" bitsize=\"128\" type=\"aarch64v\"/>\n"
"\t<reg name=\"v21\" bitsize=\"128\" type=\"aarch64v\"/>\n"
"\t<reg name=\"v22\" bitsize=\"128\" type=\"aarch64v\"/>\n"
"\t<reg name=\"v23\" bitsize=\"128\" type=\"aarch64v\"/>\n"
"\t<reg name=\"v24\" bitsize=\"128\" type=\"aarch64v\"/>\n"
"\t<reg name=\"v25\" bitsize=\"128\" type=\"aarch64v\"/>\n"
"\t<reg name=\"v26\" bitsize=\"128\" type=\"aarch64v\"/>\n"
"\t<reg name=\"v27\" bitsize=\"128\" type=\"aarch64v\"/>\n"
"\t<reg name=\"v28\" bitsize=\"128\" type=\"aarch64v\"/>\n"
"\t<reg name=\"v29\" bitsize=\"128\" type=\"aarch64v\"/>\n"
"\t<reg name=\"v30\" bitsize=\"128\" type=\"aarch64v\"/>\n"
"\t<reg name=\"v31\" bitsize=\"128\" type=\"aarch64v\"/>\n"
"\t<reg name=\"fpsr\" bitsize=\"32\"/>\n"
"\t<reg name=\"fpcr\" bitsize=\"32\"/>\n"
"</feature>";
constexpr const char TargetXmlAarch32[] =
"l<?xml version=\"1.0\"?>"
"<!DOCTYPE target SYSTEM \"gdb-target.dtd\">"
"<target>"
"<architecture>arm</architecture>"
"<xi:include href=\"arm-core.xml\"/>"
"<xi:include href=\"arm-vfp.xml\"/>"
"</target>";
constexpr const char ArmCoreXml[] =
"l<?xml version=\"1.0\"?>\n"
"<!DOCTYPE target SYSTEM \"gdb-target.dtd\">\n"
"<feature name=\"org.gnu.gdb.arm.core\">\n"
"\t<reg name=\"r0\" bitsize=\"32\"/>\n"
"\t<reg name=\"r1\" bitsize=\"32\"/>\n"
"\t<reg name=\"r2\" bitsize=\"32\"/>\n"
"\t<reg name=\"r3\" bitsize=\"32\"/>\n"
"\t<reg name=\"r4\" bitsize=\"32\"/>\n"
"\t<reg name=\"r5\" bitsize=\"32\"/>\n"
"\t<reg name=\"r6\" bitsize=\"32\"/>\n"
"\t<reg name=\"r7\" bitsize=\"32\"/>\n"
"\t<reg name=\"r8\" bitsize=\"32\"/>\n"
"\t<reg name=\"r9\" bitsize=\"32\"/>\n"
"\t<reg name=\"r10\" bitsize=\"32\"/>\n"
"\t<reg name=\"r11\" bitsize=\"32\"/>\n"
"\t<reg name=\"r12\" bitsize=\"32\"/>\n"
"\t<reg name=\"sp\" bitsize=\"32\" type=\"data_ptr\"/>\n"
"\t<reg name=\"lr\" bitsize=\"32\"/>\n"
"\t<reg name=\"pc\" bitsize=\"32\" type=\"code_ptr\"/>\n"
"\t<reg name=\"cpsr\" bitsize=\"32\" regnum=\"25\"/>\n"
"</feature>\n";
constexpr const char ArmVfpXml[] =
"l<?xml version=\"1.0\"?>\n"
"<!DOCTYPE target SYSTEM \"gdb-target.dtd\">\n"
"<feature name=\"org.gnu.gdb.arm.vfp\">\n"
"\t<reg name=\"d0\" bitsize=\"64\" type=\"ieee_double\"/>\n"
"\t<reg name=\"d1\" bitsize=\"64\" type=\"ieee_double\"/>\n"
"\t<reg name=\"d2\" bitsize=\"64\" type=\"ieee_double\"/>\n"
"\t<reg name=\"d3\" bitsize=\"64\" type=\"ieee_double\"/>\n"
"\t<reg name=\"d4\" bitsize=\"64\" type=\"ieee_double\"/>\n"
"\t<reg name=\"d5\" bitsize=\"64\" type=\"ieee_double\"/>\n"
"\t<reg name=\"d6\" bitsize=\"64\" type=\"ieee_double\"/>\n"
"\t<reg name=\"d7\" bitsize=\"64\" type=\"ieee_double\"/>\n"
"\t<reg name=\"d8\" bitsize=\"64\" type=\"ieee_double\"/>\n"
"\t<reg name=\"d9\" bitsize=\"64\" type=\"ieee_double\"/>\n"
"\t<reg name=\"d10\" bitsize=\"64\" type=\"ieee_double\"/>\n"
"\t<reg name=\"d11\" bitsize=\"64\" type=\"ieee_double\"/>\n"
"\t<reg name=\"d12\" bitsize=\"64\" type=\"ieee_double\"/>\n"
"\t<reg name=\"d13\" bitsize=\"64\" type=\"ieee_double\"/>\n"
"\t<reg name=\"d14\" bitsize=\"64\" type=\"ieee_double\"/>\n"
"\t<reg name=\"d15\" bitsize=\"64\" type=\"ieee_double\"/>\n"
"\t<reg name=\"d16\" bitsize=\"64\" type=\"ieee_double\"/>\n"
"\t<reg name=\"d17\" bitsize=\"64\" type=\"ieee_double\"/>\n"
"\t<reg name=\"d18\" bitsize=\"64\" type=\"ieee_double\"/>\n"
"\t<reg name=\"d19\" bitsize=\"64\" type=\"ieee_double\"/>\n"
"\t<reg name=\"d20\" bitsize=\"64\" type=\"ieee_double\"/>\n"
"\t<reg name=\"d21\" bitsize=\"64\" type=\"ieee_double\"/>\n"
"\t<reg name=\"d22\" bitsize=\"64\" type=\"ieee_double\"/>\n"
"\t<reg name=\"d23\" bitsize=\"64\" type=\"ieee_double\"/>\n"
"\t<reg name=\"d24\" bitsize=\"64\" type=\"ieee_double\"/>\n"
"\t<reg name=\"d25\" bitsize=\"64\" type=\"ieee_double\"/>\n"
"\t<reg name=\"d26\" bitsize=\"64\" type=\"ieee_double\"/>\n"
"\t<reg name=\"d27\" bitsize=\"64\" type=\"ieee_double\"/>\n"
"\t<reg name=\"d28\" bitsize=\"64\" type=\"ieee_double\"/>\n"
"\t<reg name=\"d29\" bitsize=\"64\" type=\"ieee_double\"/>\n"
"\t<reg name=\"d30\" bitsize=\"64\" type=\"ieee_double\"/>\n"
"\t<reg name=\"d31\" bitsize=\"64\" type=\"ieee_double\"/>\n"
"\t<reg name=\"fpscr\" bitsize=\"32\" type=\"int\" group=\"float\"/>\n"
"</feature>\n";
constexpr const char * const MemoryStateNames[svc::MemoryState_Coverage + 1] = {
"----- Free -----", /* svc::MemoryState_Free */
"Io ", /* svc::MemoryState_Io */
"Static ", /* svc::MemoryState_Static */
"Code ", /* svc::MemoryState_Code */
"CodeData ", /* svc::MemoryState_CodeData */
"Normal ", /* svc::MemoryState_Normal */
"Shared ", /* svc::MemoryState_Shared */
"Alias ", /* svc::MemoryState_Alias */
"AliasCode ", /* svc::MemoryState_AliasCode */
"AliasCodeData ", /* svc::MemoryState_AliasCodeData */
"Ipc ", /* svc::MemoryState_Ipc */
"Stack ", /* svc::MemoryState_Stack */
"ThreadLocal ", /* svc::MemoryState_ThreadLocal */
"Transfered ", /* svc::MemoryState_Transfered */
"SharedTransfered", /* svc::MemoryState_SharedTransfered */
"SharedCode ", /* svc::MemoryState_SharedCode */
"Inaccessible ", /* svc::MemoryState_Inaccessible */
"NonSecureIpc ", /* svc::MemoryState_NonSecureIpc */
"NonDeviceIpc ", /* svc::MemoryState_NonDeviceIpc */
"Kernel ", /* svc::MemoryState_Kernel */
"GeneratedCode ", /* svc::MemoryState_GeneratedCode */
"CodeOut ", /* svc::MemoryState_CodeOut */
"Coverage ", /* svc::MemoryState_Coverage */
};
constexpr const char *GetMemoryStateName(svc::MemoryState state) {
if (static_cast<size_t>(state) < util::size(MemoryStateNames)) {
return MemoryStateNames[static_cast<size_t>(state)];
} else {
return "Unknown ";
}
}
constexpr const char *GetMemoryPermissionString(const svc::MemoryInfo &info) {
if (info.state == svc::MemoryState_Free) {
return " ";
} else {
switch (info.permission) {
case svc::MemoryPermission_ReadExecute:
return "r-x";
case svc::MemoryPermission_Read:
return "r--";
case svc::MemoryPermission_ReadWrite:
return "rw-";
default:
return "---";
}
}
}
bool ParsePrefix(char *&packet, const char *prefix) {
const auto len = std::strlen(prefix);
if (std::strncmp(packet, prefix, len) == 0) {
packet += len;
return true;
} else {
return false;
}
}
void AppendReplyOk(char * &reply, char * const reply_end) {
AMS_UNUSED(reply_end);
std::strcpy(reply, "OK");
reply += 2;
}
void AppendReplyError(char * reply, char * const reply_end, const char *err) {
AMS_UNUSED(reply_end);
std::strcpy(reply, err);
reply += std::strlen(err);
}
void AppendReplyFormat(char * &reply, char * const reply_end, const char *fmt, ...) __attribute__((format(printf, 3, 4)));
void AppendReplyFormat(char * &reply, char * const reply_end, const char *fmt, ...) {
if (const auto remaining_size = reply_end - reply; remaining_size > 0) {
std::va_list vl;
va_start(vl, fmt);
reply += util::VSNPrintf(reply, remaining_size, fmt, vl);
va_end(vl);
}
}
constexpr int DecodeHex(char c) {
if ('a' <= c && c <= 'f') {
return 10 + (c - 'a');
} else if ('A' <= c && c <= 'F') {
return 10 + (c - 'A');
} else if ('0' <= c && c <= '9') {
return 0 + (c - '0');
} else {
return -1;
}
}
constexpr u64 DecodeHex(const char *s) {
u64 value = 0;
while (true) {
const char c = *(s++);
if (int v = DecodeHex(c); v >= 0) {
value <<= 4;
value |= v & 0xF;
} else {
break;
}
}
return value;
}
void MemoryToHex(char *dst, char * const dst_end, const void *mem, size_t size) {
const u8 *mem_u8 = static_cast<const u8 *>(mem);
while (size-- > 0 && dst < dst_end - 1) {
const u8 v = *(mem_u8++);
*(dst++) = "0123456789abcdef"[v >> 4];
*(dst++) = "0123456789abcdef"[v & 0xF];
}
*dst = 0;
}
void HexToMemory(void *dst, const char *src, size_t size) {
u8 *dst_u8 = static_cast<u8 *>(dst);
for (size_t i = 0; i < size; ++i) {
u8 v = DecodeHex(*(src++)) << 4;
v |= DecodeHex(*(src++)) & 0xF;
*(dst_u8++) = v;
}
}
void ParseOffsetLength(const char *packet, u32 &offset, u32 &length) {
/* Default to zero. */
offset = 0;
length = 0;
bool parsed_offset = false;
while (*packet) {
const char c = *(packet++);
if (c == ',') {
parsed_offset = true;
} else if (auto hex = DecodeHex(c); hex >= 0) {
if (parsed_offset) {
length <<= 4;
length |= hex;
} else {
offset <<= 4;
offset |= hex;
}
}
}
AMS_DMNT2_GDB_LOG_DEBUG("Offset/Length %x/%x\n", offset, length);
}
s32 FindThreadIdIndex(u64 *thread_ids, s32 num_threads, u64 thread_id) {
for (auto i = 0; i < num_threads; ++i) {
if (thread_ids[i] == thread_id) {
return i;
}
}
return 0;
}
void SetGdbRegister32(char * &dst, char * const dst_end, u32 value) {
if (value != 0) {
AppendReplyFormat(dst, dst_end, "%08x", util::ConvertToBigEndian(value));
} else {
AppendReplyFormat(dst, dst_end, "0*\"00");
}
}
void SetGdbRegister64(char * &dst, char * const dst_end, u64 value) {
if (value != 0) {
AppendReplyFormat(dst, dst_end, "%016lx", util::ConvertToBigEndian(value));
} else {
AppendReplyFormat(dst, dst_end, "0*,");
}
}
void SetGdbRegister128(char * &dst, char * const dst_end, u128 value) {
if (value != 0) {
AppendReplyFormat(dst, dst_end, "%016lx%016lx", util::ConvertToBigEndian(static_cast<u64>(value >> 0)), util::ConvertToBigEndian(static_cast<u64>(value >> BITSIZEOF(u64))));
} else {
AppendReplyFormat(dst, dst_end, "0*<");
}
}
void SetGdbRegisterPacket(char * &dst, char * const dst_end, const svc::ThreadContext &thread_context, bool is_64_bit) {
/* Clear packet. */
dst[0] = 0;
if (is_64_bit) {
/* Copy general purpose registers. */
for (size_t i = 0; i < util::size(thread_context.r); ++i) {
SetGdbRegister64(dst, dst_end, thread_context.r[i]);
}
/* Copy special registers. */
SetGdbRegister64(dst, dst_end, thread_context.fp);
SetGdbRegister64(dst, dst_end, thread_context.lr);
SetGdbRegister64(dst, dst_end, thread_context.sp);
SetGdbRegister64(dst, dst_end, thread_context.pc);
SetGdbRegister32(dst, dst_end, thread_context.pstate);
/* Copy FPU registers. */
for (size_t i = 0; i < util::size(thread_context.v); ++i) {
SetGdbRegister128(dst, dst_end, thread_context.v[i]);
}
SetGdbRegister32(dst, dst_end, thread_context.fpsr);
SetGdbRegister32(dst, dst_end, thread_context.fpcr);
} else {
/* Copy general purpose registers. */
for (size_t i = 0; i < 15; ++i) {
SetGdbRegister32(dst, dst_end, thread_context.r[i]);
}
/* Copy special registers. */
SetGdbRegister32(dst, dst_end, thread_context.pc);
SetGdbRegister32(dst, dst_end, thread_context.pstate);
/* Copy FPU registers. */
for (size_t i = 0; i < util::size(thread_context.v) / 2; ++i) {
SetGdbRegister128(dst, dst_end, thread_context.v[i]);
}
const u32 fpscr = (thread_context.fpsr & 0xF80000FF) | (thread_context.fpcr & 0x07FFFF00);
SetGdbRegister32(dst, dst_end, fpscr);
}
}
void SetGdbRegisterPacket(char * &dst, char * const dst_end, const svc::ThreadContext &thread_context, u64 reg_num, bool is_64_bit) {
/* Clear packet. */
dst[0] = 0;
union {
u32 v32;
u64 v64;
u128 v128;
} v;
size_t reg_size = 0;
if (is_64_bit) {
if (reg_num < 29) {
v.v64 = thread_context.r[reg_num];
reg_size = sizeof(u64);
} else if (reg_num == 29) {
v.v64 = thread_context.fp;
reg_size = sizeof(u64);
} else if (reg_num == 30) {
v.v64 = thread_context.lr;
reg_size = sizeof(u64);
} else if (reg_num == 31) {
v.v64 = thread_context.sp;
reg_size = sizeof(u64);
} else if (reg_num == 32) {
v.v64 = thread_context.pc;
reg_size = sizeof(u64);
} else if (reg_num == 33) {
v.v32 = thread_context.pstate;
reg_size = sizeof(u32);
} else if (reg_num < 66) {
v.v128 = thread_context.v[reg_num - 34];
reg_size = sizeof(u128);
} else if (reg_num == 66) {
v.v32 = thread_context.fpsr;
reg_size = sizeof(u32);
} else if (reg_num == 67) {
v.v32 = thread_context.fpcr;
reg_size = sizeof(u32);
}
} else {
if (reg_num < 15) {
v.v32 = thread_context.r[reg_num];
reg_size = sizeof(u32);
} else if (reg_num == 15) {
v.v32 = thread_context.pc;
reg_size = sizeof(u32);
} else if (reg_num == 25) {
v.v32 = thread_context.pstate;
reg_size = sizeof(u32);
} else if (26 <= reg_num && reg_num < 58) {
const union {
u64 v64[2];
u128 v128;
} fpu_reg = { .v128 = thread_context.v[(reg_num - 26) / 2] };
v.v64 = fpu_reg.v64[(reg_num - 26) % 2];
reg_size = sizeof(u64);
} else if (reg_num == 58) {
const u32 fpscr = (thread_context.fpsr & 0xF80000FF) | (thread_context.fpcr & 0x07FFFF00);
v.v32 = fpscr;
reg_size = sizeof(u32);
}
}
switch (reg_size) {
case sizeof(u32): SetGdbRegister32 (dst, dst_end, v.v32 ); break;
case sizeof(u64): SetGdbRegister64 (dst, dst_end, v.v64 ); break;
case sizeof(u128): SetGdbRegister128(dst, dst_end, v.v128); break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
u64 Aarch32RegisterToAarch64Register(u64 reg_num) {
if (reg_num < 15) {
return reg_num;
} else if (reg_num == 15) {
return 32;
} else if (reg_num == 25) {
return 33;
} else if (26 <= reg_num && reg_num <= 57) {
return 34 + (reg_num - 26);
} else if (reg_num == 58) {
return 66;
} else {
AMS_ABORT("Unknown register number %lu\n", reg_num);
}
}
template<typename IntType> requires std::unsigned_integral<IntType>
util::optional<IntType> ParseGdbRegister(const char *&src) {
union {
IntType v;
u8 bytes[sizeof(v)];
} reg;
for (size_t i = 0; i < util::size(reg.bytes); ++i) {
const auto high = DecodeHex(*(src++));
const auto low = DecodeHex(*(src++));
if (high < 0 || low < 0) {
return util::nullopt;
}
reg.bytes[i] = (high << 4) | low;
}
return reg.v;
}
ALWAYS_INLINE util::optional<u32> ParseGdbRegister32(const char *&src) { return ParseGdbRegister<u32>(src); }
ALWAYS_INLINE util::optional<u64> ParseGdbRegister64(const char *&src) { return ParseGdbRegister<u64>(src); }
ALWAYS_INLINE util::optional<u128> ParseGdbRegister128(const char *&src) { return ParseGdbRegister<u128>(src); }
void ParseGdbRegisterPacket(svc::ThreadContext &thread_context, const char *src, bool is_64_bit) {
if (is_64_bit) {
/* Copy general purpose registers. */
for (size_t i = 0; i < util::size(thread_context.r); ++i) {
if (const auto v = ParseGdbRegister64(src); v.has_value()) {
thread_context.r[i] = *v;
} else {
return;
}
}
/* Copy special registers. */
if (const auto v = ParseGdbRegister64(src); v.has_value()) {
thread_context.fp = *v;
} else {
return;
}
if (const auto v = ParseGdbRegister64(src); v.has_value()) {
thread_context.lr = *v;
} else {
return;
}
if (const auto v = ParseGdbRegister64(src); v.has_value()) {
thread_context.sp = *v;
} else {
return;
}
if (const auto v = ParseGdbRegister64(src); v.has_value()) {
thread_context.pc = *v;
} else {
return;
}
if (const auto v = ParseGdbRegister32(src); v.has_value()) {
thread_context.pstate = *v;
} else {
return;
}
/* Copy FPU registers. */
for (size_t i = 0; i < util::size(thread_context.v); ++i) {
if (const auto v = ParseGdbRegister128(src); v.has_value()) {
thread_context.v[i] = *v;
} else {
return;
}
}
if (const auto v = ParseGdbRegister32(src); v.has_value()) {
thread_context.fpsr = *v;
} else {
return;
}
if (const auto v = ParseGdbRegister32(src); v.has_value()) {
thread_context.fpcr = *v;
} else {
return;
}
} else {
/* Copy general purpose registers. */
for (size_t i = 0; i < 15; ++i) {
if (const auto v = ParseGdbRegister32(src); v.has_value()) {
thread_context.r[i] = *v;
} else {
return;
}
}
/* Copy special registers. */
if (const auto v = ParseGdbRegister32(src); v.has_value()) {
thread_context.pc = *v;
} else {
return;
}
if (const auto v = ParseGdbRegister32(src); v.has_value()) {
thread_context.pstate = *v;
} else {
return;
}
/* Copy FPU registers. */
for (size_t i = 0; i < util::size(thread_context.v) / 2; ++i) {
if (const auto v = ParseGdbRegister128(src); v.has_value()) {
thread_context.v[i] = *v;
} else {
return;
}
}
if (const auto v = ParseGdbRegister32(src); v.has_value()) {
thread_context.fpsr = *v & 0xF80000FF;
thread_context.fpcr = *v & 0x07FFFF00;
} else {
return;
}
}
}
void ParseGdbRegisterPacket(svc::ThreadContext &thread_context, const char *src, u64 reg_num, bool is_64_bit) {
if (is_64_bit) {
if (reg_num < 29) {
if (const auto v = ParseGdbRegister64(src); v.has_value()) {
thread_context.r[reg_num] = *v;
}
} else if (reg_num == 29) {
if (const auto v = ParseGdbRegister64(src); v.has_value()) {
thread_context.fp = *v;
}
} else if (reg_num == 30) {
if (const auto v = ParseGdbRegister64(src); v.has_value()) {
thread_context.lr = *v;
}
} else if (reg_num == 31) {
if (const auto v = ParseGdbRegister64(src); v.has_value()) {
thread_context.sp = *v;
}
} else if (reg_num == 32) {
if (const auto v = ParseGdbRegister64(src); v.has_value()) {
thread_context.pc = *v;
}
} else if (reg_num == 33) {
if (const auto v = ParseGdbRegister32(src); v.has_value()) {
thread_context.pstate = *v;
}
} else if (reg_num < 66) {
if (const auto v = ParseGdbRegister128(src); v.has_value()) {
thread_context.v[reg_num - 34] = *v;
}
} else if (reg_num == 66) {
if (const auto v = ParseGdbRegister32(src); v.has_value()) {
thread_context.fpsr = *v;
}
} else if (reg_num == 67) {
if (const auto v = ParseGdbRegister32(src); v.has_value()) {
thread_context.fpcr = *v;
}
}
} else {
if (reg_num < 15) {
if (const auto v = ParseGdbRegister32(src); v.has_value()) {
thread_context.r[reg_num] = *v;
}
} else if (reg_num == 15) {
if (const auto v = ParseGdbRegister32(src); v.has_value()) {
thread_context.pc = *v;
}
} else if (reg_num == 25) {
if (const auto v = ParseGdbRegister32(src); v.has_value()) {
thread_context.pstate = *v;
}
} else if (26 <= reg_num && reg_num < 58) {
union {
u64 v64[2];
u128 v128;
} fpu_reg = { .v128 = thread_context.v[(reg_num - 26) / 2] };
if (const auto v = ParseGdbRegister64(src); v.has_value()) {
fpu_reg.v64[(reg_num - 26) % 2] = *v;
thread_context.v[(reg_num - 26) / 2] = fpu_reg.v128;
}
} else if (reg_num == 58) {
if (const auto v = ParseGdbRegister32(src); v.has_value()) {
thread_context.fpsr = *v & 0xF80000FF;
thread_context.fpcr = *v & 0x07FFFF00;
}
}
}
}
u32 RegisterToContextFlags(u64 reg_num, bool is_64_bit) {
/* Convert register number. */
if (!is_64_bit) {
reg_num = Aarch32RegisterToAarch64Register(reg_num);
}
/* Get flags. */
u32 flags = 0;
if (reg_num < 29) {
flags = svc::ThreadContextFlag_General;
} else if (reg_num < 34) {
flags = svc::ThreadContextFlag_Control;
} else if (reg_num < 66) {
flags = svc::ThreadContextFlag_Fpu;
} else if (reg_num == 66) {
flags = svc::ThreadContextFlag_FpuControl;
}
return flags;
}
constinit os::SdkMutex g_annex_buffer_lock;
constinit char g_annex_buffer[2 * GdbPacketBufferSize];
enum AnnexBufferContents {
AnnexBufferContents_Invalid,
AnnexBufferContents_Processes,
AnnexBufferContents_Threads,
AnnexBufferContents_Libraries,
};
constinit AnnexBufferContents g_annex_buffer_contents = AnnexBufferContents_Invalid;
void GetAnnexBufferContents(char * &dst, u32 offset, u32 length) {
const u32 annex_len = std::strlen(g_annex_buffer);
if (offset <= annex_len) {
if (offset + length < annex_len) {
dst[0] = 'm';
std::memcpy(dst + 1, g_annex_buffer + offset, length);
dst[1 + length] = 0;
dst += 1 + length;
} else {
const auto size = annex_len - offset;
dst[0] = 'l';
std::memcpy(dst + 1, g_annex_buffer + offset, size);
dst[1 + size] = 0;
dst += 1 + size;
}
} else {
dst[0] = '1';
dst[1] = 0;
dst += 1;
}
}
constinit os::SdkMutex g_event_request_lock;
constinit os::SdkMutex g_event_lock;
constinit os::SdkConditionVariable g_event_request_cv;
constinit os::SdkConditionVariable g_event_done_cv;
}
GdbServerImpl::GdbServerImpl(int socket, void *stack, size_t stack_size) : m_socket(socket), m_session(socket), m_packet_io(), m_state(State::Initial), m_debug_process(), m_event(os::EventClearMode_AutoClear) {
/* Create and start the events thread. */
R_ABORT_UNLESS(os::CreateThread(std::addressof(m_events_thread), DebugEventsThreadEntry, this, stack, stack_size, os::HighestThreadPriority - 1));
os::StartThread(std::addressof(m_events_thread));
/* Set our state. */
m_state = State::Running;
}
GdbServerImpl::~GdbServerImpl() {
/* Set ourselves as killed. */
m_killed = true;
/* Signal to our events thread. */
{
std::scoped_lock lk(g_event_request_lock);
g_event_request_cv.Signal();
}
/* Signal our event. */
m_event.Signal();
/* Wait for our thread to finish. */
os::WaitThread(std::addressof(m_events_thread));
os::DestroyThread(std::addressof(m_events_thread));
/* Clear our state. */
m_state = State::Destroyed;
/* Detach. */
if (this->HasDebugProcess()) {
m_debug_process.Detach();
}
}
void GdbServerImpl::DebugEventsThread() {
/* Process events. */
{
std::scoped_lock lk(g_event_lock);
/* Loop while we're not killed. */
while (!m_killed) {
/* Wait for a request to come in. */
g_event_request_cv.Wait(g_event_lock);
/* Check that we're not killed now. */
if (m_killed) {
break;
}
/* Detach. */
m_debug_process.Detach();
/* Check if we need to start the process. */
const bool start_process = m_process_id == m_wait_process_id;
{
/* Clear our wait process id. */
ON_SCOPE_EXIT { if (start_process) { m_wait_process_id = os::InvalidProcessId; } };
/* If we have a process id, attach. */
if (R_FAILED(m_debug_process.Attach(m_process_id, m_process_id == m_wait_process_id))) {
AMS_DMNT2_GDB_LOG_DEBUG("Failed to attach to %016lx\n", m_process_id.value);
g_event_done_cv.Signal();
continue;
}
}
/* Set our process id. */
m_process_id = m_debug_process.GetProcessId();
/* Signal that we're done attaching. */
g_event_done_cv.Signal();
/* Process debug events without the lock held. */
{
g_event_lock.Unlock();
this->ProcessDebugEvents();
g_event_lock.Lock();
}
/* Clear our process id and detach. */
m_process_id = os::InvalidProcessId;
m_debug_process.Detach();
}
}
/* Set our state. */
m_state = State::Exited;
}
void GdbServerImpl::ProcessDebugEvents() {
AMS_DMNT2_GDB_LOG_DEBUG("Processing debug events for %016lx\n", m_process_id.value);
u64 new_hb_nro_addr = 0;
u32 new_hb_nro_insn = 0;
while (true) {
/* Wait for an event to come in. */
const Result wait_result = [&] ALWAYS_INLINE_LAMBDA {
std::scoped_lock lk(g_event_lock);
s32 dummy = -1;
svc::Handle handle = m_debug_process.GetHandle();
R_RETURN(svc::WaitSynchronization(std::addressof(dummy), std::addressof(handle), 1, TimeSpan::FromMilliSeconds(20).GetNanoSeconds()));
}();
/* Check if we're killed. */
if (m_killed || !m_debug_process.IsValid()) {
break;
}
/* If we didn't get an event, try again. */
if (svc::ResultTimedOut::Includes(wait_result)) {
continue;
}
/* Try to get the event. */
svc::DebugEventInfo d;
if (R_FAILED(m_debug_process.GetProcessDebugEvent(std::addressof(d)))) {
continue;
}
/* Process the event. */
GdbSignal signal;
char send_buffer[GdbPacketBufferSize];
u64 thread_id = d.thread_id;
m_debug_process.ClearStep();
char * reply_cur = send_buffer;
char * const reply_end = std::end(send_buffer);
send_buffer[0] = 0;
switch (d.type) {
case svc::DebugEvent_Exception:
{
switch (d.info.exception.type) {
case svc::DebugException_BreakPoint:
{
signal = GdbSignal_BreakpointTrap;
const uintptr_t address = d.info.exception.address;
const bool is_instr = d.info.exception.specific.break_point.type == svc::BreakPointType_HardwareInstruction;
AMS_DMNT2_GDB_LOG_DEBUG("BreakPoint %lx, addr=%lx, type=%s\n", thread_id, address, is_instr ? "Instr" : "Data");
if (is_instr) {
AppendReplyFormat(reply_cur, reply_end, "T%02Xthread:p%lx.%lx;hwbreak:;", static_cast<u32>(signal), m_process_id.value, thread_id);
} else {
bool read = false, write = false;
const char *type = "watch";
if (R_SUCCEEDED(m_debug_process.GetWatchPointInfo(address, read, write))) {
if (read && write) {
type = "awatch";
} else if (read) {
type = "rwatch";
}
} else {
AMS_DMNT2_GDB_LOG_DEBUG("GetWatchPointInfo FAIL %lx, addr=%lx, type=%s\n", thread_id, address, is_instr ? "Instr" : "Data");
}
AppendReplyFormat(reply_cur, reply_end, "T%02Xthread:p%lx.%lx;%s:%lx;", static_cast<u32>(signal), m_process_id.value, thread_id, type, address);
}
}
break;
case svc::DebugException_UserBreak:
{
const uintptr_t address = d.info.exception.address;
const auto &info = d.info.exception.specific.user_break;
AMS_DMNT2_GDB_LOG_DEBUG("UserBreak %lx, addr=%lx, reason=%x, data=0x%lx, size=0x%lx\n", thread_id, address, info.break_reason, info.address, info.size);
/* Check reason. */
/* TODO: libnx/Nintendo provide addresses in different ways, but we could optimize to avoid iterating all memory repeatedly. */
if ((info.break_reason & svc::BreakReason_NotificationOnlyFlag) != 0) {
const auto reason = info.break_reason & ~svc::BreakReason_NotificationOnlyFlag;
if (reason == svc::BreakReason_PostLoadDll || reason == svc::BreakReason_PostUnloadDll) {
/* Re-collect the process's modules. */
m_debug_process.CollectModules();
}
if (m_debug_process.GetOverrideStatus().IsHbl() && reason == svc::BreakReason_PostLoadDll) {
if (R_SUCCEEDED(m_debug_process.ReadMemory(std::addressof(new_hb_nro_insn), info.address, sizeof(new_hb_nro_insn)))) {
const u32 break_insn = SdkBreakPoint;
if (R_SUCCEEDED(m_debug_process.WriteMemory(std::addressof(break_insn), info.address, sizeof(break_insn)))) {
AMS_DMNT2_GDB_LOG_DEBUG("Set automatic break on new homebrew NRO (%lx, %lx)\n", info.address, info.size);
new_hb_nro_addr = info.address;
} else {
AMS_DMNT2_GDB_LOG_DEBUG("Failed to set automatic break on new homebrew NRO (%lx, %lx)\n", info.address, info.size);
}
} else {
AMS_DMNT2_GDB_LOG_DEBUG("Failed to read first insn on new homebrew NRO (%lx, %lx)\n", info.address, info.size);
}
}
/* This was just a notification, so we should continue. */
m_debug_process.Continue();
continue;
}
/* Check if we should automatically continue. */
svc::ThreadContext ctx;
if (R_SUCCEEDED(m_debug_process.GetThreadContext(std::addressof(ctx), thread_id, svc::ThreadContextFlag_Control))) {
u32 insn = 0;
if (R_SUCCEEDED(m_debug_process.ReadMemory(std::addressof(insn), ctx.pc, sizeof(insn)))) {
constexpr u32 Aarch64SvcBreakValue = 0xD4000001 | (svc::SvcId_Break << 5);
constexpr u32 Aarch32SvcBreakValue = 0xEF000000 | (svc::SvcId_Break);
bool is_svc_break = m_debug_process.Is64Bit() ? (insn == Aarch64SvcBreakValue) : (insn == Aarch32SvcBreakValue);
if (!is_svc_break) {
AMS_DMNT2_GDB_LOG_ERROR("UserBreak from non-SvcBreak (%08x)\n", insn);
m_debug_process.Continue();
continue;
}
}
}
signal = GdbSignal_BreakpointTrap;
}
break;
case svc::DebugException_DebuggerBreak:
{
signal = GdbSignal_Interrupt;
thread_id = m_debug_process.GetPreferredDebuggerBreakThreadId();
svc::ThreadContext ctx;
if (thread_id == 0 || thread_id == static_cast<u64>(-1) || R_FAILED(m_debug_process.GetThreadContext(std::addressof(ctx), thread_id, svc::ThreadContextFlag_Control))) {
thread_id = m_debug_process.GetLastThreadId();
}
AMS_DMNT2_GDB_LOG_DEBUG("DebuggerBreak %lx, last=%lx\n", thread_id, m_debug_process.GetLastThreadId());
m_debug_process.SetLastThreadId(thread_id);
m_debug_process.SetThreadIdOverride(thread_id);
}
break;
case svc::DebugException_UndefinedInstruction:
{
signal = GdbSignal_IllegalInstruction;
uintptr_t address = d.info.exception.address;
const u32 insn = d.info.exception.specific.undefined_instruction.insn;
u32 new_insn = 0;
AMS_DMNT2_GDB_LOG_DEBUG("Undefined Instruction %lx, address=%p, insn=%08x\n", thread_id, reinterpret_cast<void *>(address), insn);
bool is_new_hb_nro = false;
svc::ThreadContext ctx;
if (R_SUCCEEDED(m_debug_process.GetThreadContext(std::addressof(ctx), thread_id, svc::ThreadContextFlag_Control))) {
bool insn_changed = false;
if (ctx.pstate & 0x20) {
/* Thumb mode. */
address &= ~1;
if (R_SUCCEEDED(m_debug_process.ReadMemory(std::addressof(new_insn), address, 2))) {
switch ((new_insn >> 11) & 0x1F) {
case 0x1D:
case 0x1E:
case 0x1F:
{
if (R_SUCCEEDED(m_debug_process.ReadMemory(reinterpret_cast<u8 *>(std::addressof(new_insn)) + 2, address + 2, 2))) {
insn_changed = (new_insn != insn);
}
}
break;
default:
insn_changed = (new_insn != insn);
break;
}
if ((insn & T16BreakPointMask) == T16BreakPoint) {
signal = GdbSignal_BreakpointTrap;
}
}
} else {
/* Non-thumb. */
if (R_SUCCEEDED(m_debug_process.ReadMemory(std::addressof(new_insn), address, sizeof(new_insn)))) {
insn_changed = (new_insn != insn);
}
if (((insn & SdkBreakPointMask) == SdkBreakPoint) ||
((insn & ArmBreakPointMask) == ArmBreakPoint) ||
((insn & A64BreakPointMask) == A64BreakPoint) ||
((insn & A32BreakPointMask) == A32BreakPoint) ||
((insn & A64HaltMask) == A64Halt))
{
signal = GdbSignal_BreakpointTrap;
}
if (m_debug_process.GetOverrideStatus().IsHbl() && address == new_hb_nro_addr && insn == SdkBreakPoint) {
if (R_SUCCEEDED(m_debug_process.WriteMemory(std::addressof(new_hb_nro_insn), new_hb_nro_addr, sizeof(new_hb_nro_insn)))) {
AMS_DMNT2_GDB_LOG_DEBUG("Did automatic break on new homebrew NRO (%lx)\n", address);
new_hb_nro_addr = 0;
new_hb_nro_insn = 0;
is_new_hb_nro = true;
} else {
AMS_DMNT2_GDB_LOG_ERROR("Failed to restore instruction for new homebrew NRO (%lx)!\n", address);
}
}
}
if (insn_changed) {
AMS_DMNT2_GDB_LOG_DEBUG("Instruction Changed %lx, address=%p, insn=%08x, new_insn=%08x\n", thread_id, reinterpret_cast<void *>(address), insn, new_insn);
}
}
if (signal == GdbSignal_IllegalInstruction) {
AMS_DMNT2_GDB_LOG_DEBUG("Illegal Instruction %lx, address=%p, insn=%08x\n", thread_id, reinterpret_cast<void *>(address), insn);
} else if (signal == GdbSignal_BreakpointTrap && ((insn & SdkBreakPointMask) != SdkBreakPoint)) {
AMS_DMNT2_GDB_LOG_DEBUG("Non-SDK BreakPoint %lx, address=%p, insn=%08x\n", thread_id, reinterpret_cast<void *>(address), insn);
}
if (signal == GdbSignal_BreakpointTrap && !is_new_hb_nro) {
AppendReplyFormat(reply_cur, reply_end, "T%02Xthread:p%lx.%lx;swbreak:;", static_cast<u32>(signal), m_process_id.value, thread_id);
}
m_debug_process.ClearStep();
}
break;
default:
AMS_DMNT2_GDB_LOG_DEBUG("Unhandled Exception %u %lx\n", static_cast<u32>(d.info.exception.type), thread_id);
signal = GdbSignal_SegmentationFault;
break;
}
if (reply_cur == send_buffer) {
AppendReplyFormat(reply_cur, reply_end, "T%02Xthread:p%lx.%lx;", static_cast<u32>(signal), m_process_id.value, thread_id);
}
m_debug_process.SetLastThreadId(thread_id);
m_debug_process.SetLastSignal(signal);
}
break;
case svc::DebugEvent_CreateThread:
{
AMS_DMNT2_GDB_LOG_DEBUG("CreateThread %lx\n", thread_id);
if (m_debug_process.IsValid()) {
m_debug_process.Continue();
} else {
AppendReplyFormat(reply_cur, reply_end, "W00");
}
}
break;
case svc::DebugEvent_ExitThread:
{
AMS_DMNT2_GDB_LOG_DEBUG("ExitThread %lx\n", thread_id);
if (m_debug_process.IsValid()) {
m_debug_process.Continue();
} else {
AppendReplyFormat(reply_cur, reply_end, "W00");
}
}
break;
case svc::DebugEvent_ExitProcess:
{
m_killed = true;
AMS_DMNT2_GDB_LOG_DEBUG("ExitProcess\n");
if (d.info.exit_process.reason == svc::ProcessExitReason_ExitProcess) {
AppendReplyFormat(reply_cur, reply_end, "W00");
} else {
AppendReplyFormat(reply_cur, reply_end, "X%02X", GdbSignal_Killed);
}
m_debug_process.Detach();
}
break;
default:
AMS_DMNT2_GDB_LOG_DEBUG("Unhandled ProcessEvent %u %lx\n", static_cast<u32>(d.type), thread_id);
m_debug_process.Continue();
break;
}
if (reply_cur != send_buffer) {
bool do_break;
this->SendPacket(std::addressof(do_break), send_buffer);
if (do_break) {
m_debug_process.Break();
}
}
}
}
void GdbServerImpl::AppendStopReplyPacket(GdbSignal signal) {
/* Set the signal. */
AppendReplyFormat(m_reply_cur, m_reply_end, "T%02X", static_cast<u32>(signal));
/* Get the last thread id. */
const u64 thread_id = m_debug_process.GetLastThreadId();
/* Get the thread context. */
svc::ThreadContext thread_context = {};
m_debug_process.GetThreadContext(std::addressof(thread_context), thread_id, svc::ThreadContextFlag_General | svc::ThreadContextFlag_Control);
/* Add important registers. */
/* TODO: aarch32 */
{
if (thread_context.fp != 0) {
AppendReplyFormat(m_reply_cur, m_reply_end, "1d:%016lx", util::ConvertToBigEndian(thread_context.fp));
} else {
AppendReplyFormat(m_reply_cur, m_reply_end, "1d:0*,");
}
if (thread_context.sp != 0) {
AppendReplyFormat(m_reply_cur, m_reply_end, ";1f:%016lx", util::ConvertToBigEndian(thread_context.sp));
} else {
AppendReplyFormat(m_reply_cur, m_reply_end, ";1f:0*,");
}
if (thread_context.pc != 0) {
AppendReplyFormat(m_reply_cur, m_reply_end, ";20:%016lx", util::ConvertToBigEndian(thread_context.pc));
} else {
AppendReplyFormat(m_reply_cur, m_reply_end, ";20:0*,");
}
}
/* Add the thread id. */
AppendReplyFormat(m_reply_cur, m_reply_end, ";thread:p%lx.%lx", m_process_id.value, thread_id);
/* Add the thread core. */
{
u32 core = 0;
m_debug_process.GetThreadCurrentCore(std::addressof(core), thread_id);
AppendReplyFormat(m_reply_cur, m_reply_end, ";core:%u;", core);
}
}
void GdbServerImpl::LoopProcess() {
/* Process packets. */
while (m_session.IsValid()) {
/* Receive a packet. */
bool do_break = false;
char recv_buf[GdbPacketBufferSize];
char *packet = this->ReceivePacket(std::addressof(do_break), recv_buf, sizeof(recv_buf));
if (!do_break && packet != nullptr) {
/* Process the packet. */
char reply_buffer[GdbPacketBufferSize];
this->ProcessPacket(packet, reply_buffer);
/* Send packet. */
this->SendPacket(std::addressof(do_break), reply_buffer);
}
/* If we should, break the process. */
if (do_break) {
m_debug_process.Break();
}
}
}
void GdbServerImpl::ProcessPacket(char *receive, char *reply) {
/* Set our fields. */
m_receive_packet = receive;
m_reply_cur = reply;
m_reply_end = reply + GdbPacketBufferSize;
/* Log the packet we're processing. */
AMS_DMNT2_GDB_LOG_DEBUG("Receive: %s\n", m_receive_packet);
/* Clear our reply packet. */
reply[0] = 0;
/* Handle the received packet. */
switch (m_receive_packet[0]) {
case 'D':
this->D();
break;
case 'G':
this->G();
break;
case 'H':
this->H();
break;
case 'M':
this->M();
break;
case 'P':
this->P();
break;
case 'Q':
this->Q();
break;
case 'T':
this->T();
break;
case 'Z':
this->Z();
break;
case 'c':
this->c();
break;
case 'k':
this->k();
break;
case 'g':
if (!this->g()) {
m_killed = true;
}
break;
case 'm':
this->m();
break;
case 'p':
this->p();
break;
case 'v':
this->v();
break;
case 'q':
this->q();
break;
case 'z':
this->z();
break;
case '!':
AppendReplyOk(m_reply_cur, m_reply_end);
break;
case '?':
this->QuestionMark();
break;
default:
AMS_DMNT2_GDB_LOG_DEBUG("Not Implemented: %s\n", m_receive_packet);
break;
}
}
void GdbServerImpl::D() {
m_debug_process.Detach();
AppendReplyOk(m_reply_cur, m_reply_end);
}
void GdbServerImpl::G() {
/* Get thread id. */
u32 thread_id = m_debug_process.GetThreadIdOverride();
if (thread_id == 0 || thread_id == static_cast<u32>(-1)) {
thread_id = m_debug_process.GetLastThreadId();
}
/* Get thread context. */
svc::ThreadContext ctx;
if (R_FAILED(m_debug_process.GetThreadContext(std::addressof(ctx), thread_id, svc::ThreadContextFlag_All))) {
AppendReplyError(m_reply_cur, m_reply_end, "E01");
return;
}
/* Update the thread context. */
ParseGdbRegisterPacket(ctx, m_receive_packet, m_debug_process.Is64Bit());
/* Set the thread context. */
if (R_SUCCEEDED(m_debug_process.SetThreadContext(std::addressof(ctx), thread_id, svc::ThreadContextFlag_All))) {
AppendReplyOk(m_reply_cur, m_reply_end);
} else {
AppendReplyError(m_reply_cur, m_reply_end, "E01");
}
}
void GdbServerImpl::H() {
if (this->HasDebugProcess()) {
if (ParsePrefix(m_receive_packet, "Hg") || ParsePrefix(m_receive_packet, "HG")) {
this->Hg();
} else {
AppendReplyError(m_reply_cur, m_reply_end, "E01");
}
} else {
AppendReplyError(m_reply_cur, m_reply_end, "E01");
}
}
void GdbServerImpl::Hg() {
bool success = false;
s64 thread_id;
if (const char *dot = std::strchr(m_receive_packet, '.'); dot != nullptr) {
thread_id = std::strcmp(dot + 1, "-1") == 0 ? -1 : static_cast<s64>(DecodeHex(dot + 1));
AMS_DMNT2_GDB_LOG_DEBUG("Set thread id = %lx\n", thread_id);
u64 thread_ids[DebugProcess::ThreadCountMax];
s32 num_threads;
if (R_SUCCEEDED(m_debug_process.GetThreadList(std::addressof(num_threads), thread_ids, util::size(thread_ids)))) {
if (thread_id == 0) {
thread_id = thread_ids[0];
}
for (auto i = 0; i < num_threads; ++i) {
if (thread_id == -1 || static_cast<u64>(thread_id) == thread_ids[i]) {
svc::ThreadContext context;
if (R_SUCCEEDED(m_debug_process.GetThreadContext(std::addressof(context), thread_ids[i], svc::ThreadContextFlag_Control))) {
success = true;
if (thread_id != -1) {
m_debug_process.SetThreadIdOverride(thread_ids[i]);
}
}
}
}
}
}
if (success) {
AppendReplyOk(m_reply_cur, m_reply_end);
} else {
AppendReplyError(m_reply_cur, m_reply_end, "E01");
}
}
void GdbServerImpl::M() {
++m_receive_packet;
/* Validate format. */
char *comma = std::strchr(m_receive_packet, ',');
if (comma == nullptr) {
AppendReplyError(m_reply_cur, m_reply_end, "E01");
return;
}
*comma = 0;
char *colon = std::strchr(comma + 1, ':');
if (colon == nullptr) {
AppendReplyError(m_reply_cur, m_reply_end, "E01");
return;
}
*colon = 0;
/* Parse address/length. */
const u64 address = DecodeHex(m_receive_packet);
const u64 length = DecodeHex(comma + 1);
if (length >= sizeof(m_buffer)) {
AppendReplyError(m_reply_cur, m_reply_end, "E01");
return;
}
/* Decode the memory. */
HexToMemory(m_buffer, colon + 1, length);
/* Write the memory. */
if (R_SUCCEEDED(m_debug_process.WriteMemory(m_buffer, address, length))) {
AppendReplyOk(m_reply_cur, m_reply_end);
} else {
AppendReplyError(m_reply_cur, m_reply_end, "E01");
}
}
void GdbServerImpl::P() {
++m_receive_packet;
/* Validate format. */
char *equal = std::strchr(m_receive_packet, '=');
if (equal == nullptr) {
AppendReplyError(m_reply_cur, m_reply_end, "E01");
return;
}
*equal = 0;
/* Decode the register. */
const u64 reg_num = DecodeHex(m_receive_packet);
/* Get the flags. */
const u32 flags = RegisterToContextFlags(reg_num, m_debug_process.Is64Bit());
/* Determine thread id. */
u32 thread_id = m_debug_process.GetThreadIdOverride();
if (thread_id == 0 || thread_id == static_cast<u32>(-1)) {
thread_id = m_debug_process.GetLastThreadId();
}
/* Update the register. */
svc::ThreadContext ctx;
if (R_SUCCEEDED(m_debug_process.GetThreadContext(std::addressof(ctx), thread_id, flags))) {
ParseGdbRegisterPacket(ctx, equal + 1, reg_num, m_debug_process.Is64Bit());
if (R_SUCCEEDED(m_debug_process.SetThreadContext(std::addressof(ctx), thread_id, flags))) {
AppendReplyOk(m_reply_cur, m_reply_end);
} else {
AppendReplyError(m_reply_cur, m_reply_end, "E01");
}
} else {
AppendReplyError(m_reply_cur, m_reply_end, "E01");
}
}
void GdbServerImpl::Q() {
if (ParsePrefix(m_receive_packet, "QStartNoAckMode")) {
this->QStartNoAckMode();
} else {
AMS_DMNT2_GDB_LOG_DEBUG("Not Implemented Q: %s\n", m_receive_packet);
}
}
void GdbServerImpl::QStartNoAckMode() {
m_packet_io.SetNoAck();
AppendReplyOk(m_reply_cur, m_reply_end);
}
void GdbServerImpl::T() {
if (const char *dot = std::strchr(m_receive_packet, '.'); dot != nullptr) {
const u64 thread_id = DecodeHex(dot + 1);
svc::ThreadContext ctx;
if (R_SUCCEEDED(m_debug_process.GetThreadContext(std::addressof(ctx), thread_id, svc::ThreadContextFlag_Control))) {
AppendReplyOk(m_reply_cur, m_reply_end);
} else {
AppendReplyFormat(m_reply_cur, m_reply_end, "E01");
}
} else {
AppendReplyError(m_reply_cur, m_reply_end, "E01");
}
}
void GdbServerImpl::Z() {
/* Increment past the 'Z'. */
++m_receive_packet;
/* Decode the type. */
if (!('0' <= m_receive_packet[0] && m_receive_packet[0] <= '4') || m_receive_packet[1] != ',') {
AppendReplyError(m_reply_cur, m_reply_end, "E01");
return;
}
const auto type = m_receive_packet[0] - '0';
m_receive_packet += 2;
/* Decode the address/length. */
const char *comma = std::strchr(m_receive_packet, ',');
if (comma == nullptr) {
AppendReplyError(m_reply_cur, m_reply_end, "E01");
return;
}
/* Parse address/length. */
const u64 address = DecodeHex(m_receive_packet);
const u64 length = DecodeHex(comma + 1);
switch (type) {
case 0: /* SW */
{
if (length == 2 || length == 4) {
if (R_SUCCEEDED(m_debug_process.SetBreakPoint(address, length, false))) {
AppendReplyOk(m_reply_cur, m_reply_end);
} else {
AppendReplyError(m_reply_cur, m_reply_end, "E01");
}
}
}
break;
case 1: /* HW */
{
if (length == 2 || length == 4) {
if (R_SUCCEEDED(m_debug_process.SetHardwareBreakPoint(address, length, false))) {
AppendReplyOk(m_reply_cur, m_reply_end);
} else {
AppendReplyError(m_reply_cur, m_reply_end, "E01");
}
}
}
break;
case 2: /* Watch-W */
{
if (m_debug_process.IsValidWatchPoint(address, length)) {
if (R_SUCCEEDED(m_debug_process.SetWatchPoint(address, length, false, true))) {
AppendReplyOk(m_reply_cur, m_reply_end);
} else {
AppendReplyError(m_reply_cur, m_reply_end, "E01");
}
}
}
break;
case 3: /* Watch-R */
{
if (m_debug_process.IsValidWatchPoint(address, length)) {
if (R_SUCCEEDED(m_debug_process.SetWatchPoint(address, length, true, false))) {
AppendReplyOk(m_reply_cur, m_reply_end);
} else {
AppendReplyError(m_reply_cur, m_reply_end, "E01");
}
}
}
break;
case 4: /* Watch-A */
{
if (m_debug_process.IsValidWatchPoint(address, length)) {
if (R_SUCCEEDED(m_debug_process.SetWatchPoint(address, length, true, true))) {
AppendReplyOk(m_reply_cur, m_reply_end);
} else {
AppendReplyError(m_reply_cur, m_reply_end, "E01");
}
}
}
break;
default:
break;
}
}
void GdbServerImpl::c() {
/* Get thread id. */
u64 thread_id = m_debug_process.GetThreadIdOverride();
if (thread_id == 0 || thread_id == static_cast<u64>(-1)) {
thread_id = m_debug_process.GetLastThreadId();
}
/* Continue the thread. */
Result result;
if (thread_id == m_debug_process.GetLastThreadId()) {
result = m_debug_process.Continue(thread_id);
} else {
result = m_debug_process.Continue();
}
if (R_SUCCEEDED(result)) {
AppendReplyOk(m_reply_cur, m_reply_end);
} else {
AppendReplyError(m_reply_cur, m_reply_end, "E01");
}
}
bool GdbServerImpl::g() {
/* Get thread id. */
u64 thread_id = m_debug_process.GetThreadIdOverride();
if (thread_id == 0 || thread_id == static_cast<u64>(-1)) {
thread_id = m_debug_process.GetLastThreadId();
}
/* Get thread context. */
svc::ThreadContext thread_context;
if (R_FAILED(m_debug_process.GetThreadContext(std::addressof(thread_context), thread_id, svc::ThreadContextFlag_All))) {
return false;
}
/* Populate reply packet. */
SetGdbRegisterPacket(m_reply_cur, m_reply_end, thread_context, m_debug_process.Is64Bit());
return true;
}
void GdbServerImpl::m() {
++m_receive_packet;
/* Validate format. */
const char *comma = std::strchr(m_receive_packet, ',');
if (comma == nullptr) {
AppendReplyError(m_reply_cur, m_reply_end, "E01");
return;
}
/* Parse address/length. */
const u64 address = DecodeHex(m_receive_packet);
const u64 length = DecodeHex(comma + 1);
if (length >= sizeof(m_buffer)) {
AppendReplyError(m_reply_cur, m_reply_end, "E01");
return;
}
/* Read the memory. */
/* TODO: Detect partial readability? */
if (R_FAILED(m_debug_process.ReadMemory(m_buffer, address, length))) {
AppendReplyError(m_reply_cur, m_reply_end, "E01");
return;
}
/* Encode the memory. */
MemoryToHex(m_reply_cur, m_reply_end, m_buffer, length);
}
void GdbServerImpl::k() {
m_debug_process.Terminate();
m_killed = true;
}
void GdbServerImpl::p() {
++m_receive_packet;
/* Decode the register. */
const u64 reg_num = DecodeHex(m_receive_packet);
/* Get the flags. */
const u32 flags = RegisterToContextFlags(reg_num, m_debug_process.Is64Bit());
/* Determine thread id. */
u32 thread_id = m_debug_process.GetThreadIdOverride();
if (thread_id == 0 || thread_id == static_cast<u32>(-1)) {
thread_id = m_debug_process.GetLastThreadId();
}
/* Get the register. */
svc::ThreadContext ctx;
if (R_SUCCEEDED(m_debug_process.GetThreadContext(std::addressof(ctx), thread_id, flags))) {
SetGdbRegisterPacket(m_reply_cur, m_reply_end, ctx, reg_num, m_debug_process.Is64Bit());
} else {
AppendReplyError(m_reply_cur, m_reply_end, "E01");
}
}
void GdbServerImpl::v() {
if (ParsePrefix(m_receive_packet, "vAttach;")) {
this->vAttach();
} else if (ParsePrefix(m_receive_packet, "vCont")) {
this->vCont();
} else {
AMS_DMNT2_GDB_LOG_DEBUG("Not Implemented v: %s\n", m_receive_packet);
}
}
void GdbServerImpl::vAttach() {
if (!this->HasDebugProcess()) {
/* Get the process id. */
if (const u64 process_id = DecodeHex(m_receive_packet); process_id != 0) {
/* Set our process id. */
m_process_id = { process_id };
/* Wait for us to be attached. */
{
std::scoped_lock lk(g_event_request_lock);
g_event_request_cv.Signal();
if (!g_event_done_cv.TimedWait(g_event_request_lock, TimeSpan::FromSeconds(2))) {
m_event.Signal();
}
}
/* If we're attached, send a stop reply packet. */
if (m_debug_process.IsValid()) {
/* Set the stop reply packet. */
this->AppendStopReplyPacket(m_debug_process.GetLastSignal());
} else {
AppendReplyError(m_reply_cur, m_reply_end, "E01");
}
} else {
AppendReplyError(m_reply_cur, m_reply_end, "E01");
}
} else {
AppendReplyError(m_reply_cur, m_reply_end, "E01");
}
}
void GdbServerImpl::vCont() {
/* Check if this is a query about what we support. */
if (ParsePrefix(m_receive_packet, "?")) {
AppendReplyFormat(m_reply_cur, m_reply_end, "vCont;c;C;s;S;");
return;
}
/* We want to parse semicolon separated fields repeatedly. */
char *saved;
char *token = strtok_r(m_receive_packet, ";", std::addressof(saved));
/* Validate the initial token. */
if (token == nullptr) {
return;
}
/* Prepare to parse threads. */
u64 thread_ids[DebugProcess::ThreadCountMax] = {};
u8 continue_modes[DebugProcess::ThreadCountMax] = {};
s32 num_threads;
if (R_FAILED(m_debug_process.GetThreadList(std::addressof(num_threads), thread_ids, util::size(thread_ids)))) {
AMS_DMNT2_GDB_LOG_ERROR("vCont: Failed to get thread list\n");
AppendReplyError(m_reply_cur, m_reply_end, "E01");
return;
}
/* Handle each token. */
Result result = ResultSuccess();
DebugProcess::ContinueMode default_continue_mode = DebugProcess::ContinueMode_Stopped;
while (token != nullptr && R_SUCCEEDED(result)) {
result = this->ParseVCont(token, thread_ids, continue_modes, num_threads, default_continue_mode);
token = strtok_r(nullptr, ";", std::addressof(saved));
}
AMS_DMNT2_GDB_LOG_DEBUG("vCont: NumThreads=%d, Default Continue Mode=%d\n", num_threads, static_cast<int>(default_continue_mode));
/* Act on all threads. */
s64 thread_id = -1;
for (auto i = 0; i < num_threads; ++i) {
if (continue_modes[i] == DebugProcess::ContinueMode_Step || (continue_modes[i] == DebugProcess::ContinueMode_Stopped && default_continue_mode == DebugProcess::ContinueMode_Step)) {
thread_id = thread_ids[i];
result = m_debug_process.Step(thread_ids[i]);
}
}
/* Continue the last thread. */
if (static_cast<u64>(thread_id) == m_debug_process.GetLastThreadId() && default_continue_mode != DebugProcess::ContinueMode_Continue) {
result = m_debug_process.Continue(thread_id);
} else {
result = m_debug_process.Continue();
}
/* Set reply. */
if (R_SUCCEEDED(result)) {
AppendReplyOk(m_reply_cur, m_reply_end);
} else {
AMS_DMNT2_GDB_LOG_ERROR("vCont: Failed %08x\n", result.GetValue());
AppendReplyError(m_reply_cur, m_reply_end, "E01");
}
}
Result GdbServerImpl::ParseVCont(char * const token, u64 *thread_ids, u8 *continue_modes, s32 num_threads, DebugProcess::ContinueMode &default_continue_mode) {
/* Parse the thread id. */
s64 thread_id = -1;
s32 signal = -1;
s32 thread_ix = -1;
if (token[0] && token[1]) {
if (char *colon = std::strchr(token, ':'); colon != nullptr) {
*colon = 0;
if (char *dot = std::strchr(colon + 1, '.'); dot != nullptr) {
*dot = 0;
thread_id = std::strcmp(dot + 1, "-1") == 0 ? -1 : static_cast<s64>(DecodeHex(dot + 1));
thread_ix = FindThreadIdIndex(thread_ids, num_threads, static_cast<u64>(thread_id));
}
}
}
/* Check that we don't already have a default mode. */
if (thread_id == -1 && default_continue_mode != DebugProcess::ContinueMode_Stopped) {
AMS_DMNT2_GDB_LOG_ERROR("vCont: Too many defaults specified\n");
}
/* Handle the action. */
switch (token[0]) {
case 'c':
if (thread_id > 0) {
AMS_DMNT2_GDB_LOG_DEBUG("vCont: Continue %lx\n", static_cast<u64>(thread_id));
continue_modes[thread_ix] = DebugProcess::ContinueMode_Continue;
} else {
default_continue_mode = DebugProcess::ContinueMode_Continue;
}
break;
case 'C':
if (token[1]) {
signal = std::strcmp(token + 1, "-1") == 0 ? -1 : static_cast<s32>(DecodeHex(token + 1));
}
AMS_DMNT2_GDB_LOG_WARN("vCont: Ignoring C, signal=%d\n", signal);
if (thread_id > 0) {
AMS_DMNT2_GDB_LOG_DEBUG("vCont: Continue %lx, signal=%d\n", static_cast<u64>(thread_id), signal);
continue_modes[thread_ix] = DebugProcess::ContinueMode_Continue;
} else {
default_continue_mode = DebugProcess::ContinueMode_Continue;
}
break;
case 's':
if (thread_id > 0) {
AMS_DMNT2_GDB_LOG_DEBUG("vCont: Step %lx\n", static_cast<u64>(thread_id));
continue_modes[thread_ix] = DebugProcess::ContinueMode_Step;
} else {
default_continue_mode = DebugProcess::ContinueMode_Step;
}
break;
case 'S':
if (token[1]) {
signal = std::strcmp(token + 1, "-1") == 0 ? -1 : static_cast<s32>(DecodeHex(token + 1));
}
AMS_DMNT2_GDB_LOG_WARN("vCont: Ignoring S, signal=%d\n", signal);
if (thread_id > 0) {
AMS_DMNT2_GDB_LOG_DEBUG("vCont: Step %lx, signal=%d\n", static_cast<u64>(thread_id), signal);
continue_modes[thread_ix] = DebugProcess::ContinueMode_Step;
} else {
default_continue_mode = DebugProcess::ContinueMode_Step;
}
break;
default:
AMS_DMNT2_GDB_LOG_WARN("vCont: Ignoring %c\n", token[0]);
break;
}
R_SUCCEED();
}
void GdbServerImpl::q() {
if (ParsePrefix(m_receive_packet, "qAttached:")) {
this->qAttached();
} else if (ParsePrefix(m_receive_packet, "qC")) {
this->qC();
} else if (ParsePrefix(m_receive_packet, "qRcmd,")) {
this->qRcmd();
} else if (ParsePrefix(m_receive_packet, "qSupported:")) {
this->qSupported();
} else if (ParsePrefix(m_receive_packet, "qXfer:")) {
this->qXfer();
} else {
AMS_DMNT2_GDB_LOG_DEBUG("Not Implemented q: %s\n", m_receive_packet);
}
}
void GdbServerImpl::qAttached() {
if (this->HasDebugProcess()) {
AppendReplyFormat(m_reply_cur, m_reply_end, "1");
} else {
AppendReplyError(m_reply_cur, m_reply_end, "E01");
}
}
void GdbServerImpl::qC() {
if (this->HasDebugProcess()) {
/* Send the thread id. */
AppendReplyFormat(m_reply_cur, m_reply_end, "QCp%lx.%lx", m_process_id.value, m_debug_process.GetLastThreadId());
} else {
AppendReplyError(m_reply_cur, m_reply_end, "E01");
}
}
void GdbServerImpl::qRcmd() {
/* Decode the command. */
const auto packet_len = std::strlen(m_receive_packet);
HexToMemory(m_buffer, m_receive_packet, packet_len);
m_buffer[packet_len / 2] = '\x00';
/* Convert our response to hex, on complete. */
ON_SCOPE_EXIT {
/* Convert response to hex. */
MemoryToHex(m_reply_cur, m_reply_end, m_buffer, std::strlen(m_buffer));
};
char *reply_cur = m_buffer;
char *reply_end = m_buffer + sizeof(m_buffer);
/* Parse the command. */
char *command = reinterpret_cast<char *>(m_buffer);
if (ParsePrefix(command, "help")) {
AppendReplyFormat(reply_cur, reply_end, "get info\n"
"get mappings\n"
"get mappings {address}\n"
"get mapping {address}\n"
"wait application\n"
"wait {program id}\n"
"wait homebrew\n");
} else if (ParsePrefix(command, "get base") || ParsePrefix(command, "get info") || ParsePrefix(command, "get modules")) {
if (!this->HasDebugProcess()) {
AppendReplyFormat(reply_cur, reply_end, "Not attached.\n");
return;
}
AppendReplyFormat(reply_cur, reply_end, "Process: 0x%lx (%s)\n"
"Program Id: 0x%016lx\n"
"Application: %d\n"
"Hbl: %d\n"
"Layout:\n", m_process_id.value, m_debug_process.GetProcessName(), m_debug_process.GetProgramLocation().program_id.value, m_debug_process.IsApplication(), m_debug_process.GetOverrideStatus().IsHbl());
AppendReplyFormat(reply_cur, reply_end, " Alias: 0x%010lx - 0x%010lx\n"
" Heap: 0x%010lx - 0x%010lx\n"
" Aslr: 0x%010lx - 0x%010lx\n"
" Stack: 0x%010lx - 0x%010lx\n"
"Modules:\n", m_debug_process.GetAliasRegionAddress(), m_debug_process.GetAliasRegionAddress() + m_debug_process.GetAliasRegionSize() - 1,
m_debug_process.GetHeapRegionAddress(), m_debug_process.GetHeapRegionAddress() + m_debug_process.GetHeapRegionSize() - 1,
m_debug_process.GetAslrRegionAddress(), m_debug_process.GetAslrRegionAddress() + m_debug_process.GetAslrRegionSize() - 1,
m_debug_process.GetStackRegionAddress(), m_debug_process.GetStackRegionAddress() + m_debug_process.GetStackRegionSize() - 1);
/* Get the module list. */
for (size_t i = 0; i < m_debug_process.GetModuleCount(); ++i) {
const char *module_name = m_debug_process.GetModuleName(i);
const auto name_len = std::strlen(module_name);
if (name_len < 5 || (std::strcmp(module_name + name_len - 4, ".elf") != 0 && std::strcmp(module_name + name_len - 4, ".nss") != 0)) {
AppendReplyFormat(reply_cur, reply_end, " 0x%010lx - 0x%010lx %s.elf\n", m_debug_process.GetModuleBaseAddress(i), m_debug_process.GetModuleBaseAddress(i) + m_debug_process.GetModuleSize(i) - 1, module_name);
} else {
AppendReplyFormat(reply_cur, reply_end, " 0x%010lx - 0x%010lx %s\n", m_debug_process.GetModuleBaseAddress(i), m_debug_process.GetModuleBaseAddress(i) + m_debug_process.GetModuleSize(i) - 1, module_name);
}
}
} else if (ParsePrefix(command, "get mappings")) {
if (!this->HasDebugProcess()) {
AppendReplyFormat(reply_cur, reply_end, "Not attached.\n");
return;
}
uintptr_t cur_addr = 0;
if (ParsePrefix(command, " ")) {
ParsePrefix(command, "0x");
cur_addr = DecodeHex(command);
}
AppendReplyFormat(reply_cur, reply_end, "Mappings (starting from 0x%010lx):\n", cur_addr);
while (true) {
/* Check if we have room for a mapping. */
if (reply_end - reply_cur < 0x48 * 2) {
AppendReplyFormat(reply_cur, reply_end, "<-- Send `monitor get mappings 0x%010lx` to continue -->\n", cur_addr);
break;
}
/* Get mapping. */
svc::MemoryInfo mem_info;
if (R_FAILED(m_debug_process.QueryMemory(std::addressof(mem_info), cur_addr))) {
break;
}
if (mem_info.state != svc::MemoryState_Inaccessible || mem_info.base_address + mem_info.size - 1 != std::numeric_limits<u64>::max()) {
const char *state = GetMemoryStateName(mem_info.state);
const char *perm = GetMemoryPermissionString(mem_info);
const char l = (mem_info.attribute & svc::MemoryAttribute_Locked) ? 'L' : '-';
const char i = (mem_info.attribute & svc::MemoryAttribute_IpcLocked) ? 'I' : '-';
const char d = (mem_info.attribute & svc::MemoryAttribute_DeviceShared) ? 'D' : '-';
const char u = (mem_info.attribute & svc::MemoryAttribute_Uncached) ? 'U' : '-';
AppendReplyFormat(reply_cur, reply_end, " 0x%010lx - 0x%010lx %s %s %c%c%c%c [%d, %d]\n", mem_info.base_address, mem_info.base_address + mem_info.size - 1, perm, state, l, i, d, u, mem_info.ipc_count, mem_info.device_count);
}
/* Advance. */
const uintptr_t next_address = mem_info.base_address + mem_info.size;
if (next_address <= cur_addr) {
break;
}
cur_addr = next_address;
}
} else if (ParsePrefix(command, "get mapping ")) {
if (!this->HasDebugProcess()) {
AppendReplyFormat(reply_cur, reply_end, "Not attached.\n");
return;
}
/* Allow optional "0x" prefix. */
ParsePrefix(command, "0x");
/* Decode address. */
const u64 address = DecodeHex(command);
/* Get mapping. */
svc::MemoryInfo mem_info;
if (R_FAILED(m_debug_process.QueryMemory(std::addressof(mem_info), address))) {
AppendReplyFormat(reply_cur, reply_end, "0x%016lx: No mapping.\n", address);
}
const char *state = GetMemoryStateName(mem_info.state);
const char *perm = GetMemoryPermissionString(mem_info);
const char l = (mem_info.attribute & svc::MemoryAttribute_Locked) ? 'L' : '-';
const char i = (mem_info.attribute & svc::MemoryAttribute_IpcLocked) ? 'I' : '-';
const char d = (mem_info.attribute & svc::MemoryAttribute_DeviceShared) ? 'D' : '-';
const char u = (mem_info.attribute & svc::MemoryAttribute_Uncached) ? 'U' : '-';
AppendReplyFormat(reply_cur, reply_end, "0x%010lx - 0x%010lx %s %s %c%c%c%c [%d, %d]\n", mem_info.base_address, mem_info.base_address + mem_info.size - 1, perm, state, l, i, d, u, mem_info.ipc_count, mem_info.device_count);
} else if (ParsePrefix(command, "wait application") || ParsePrefix(command, "wait app")) {
/* Wait for an application process. */
{
/* Get hook to creation of application process. */
os::NativeHandle h;
R_ABORT_UNLESS(pm::dmnt::HookToCreateApplicationProcess(std::addressof(h)));
/* Wait for event. */
os::SystemEvent hook_event(h, true, os::InvalidNativeHandle, false, os::EventClearMode_AutoClear);
hook_event.Wait();
}
/* Get application process id. */
R_ABORT_UNLESS(pm::dmnt::GetApplicationProcessId(std::addressof(m_wait_process_id)));
/* Note that we're attaching. */
AppendReplyFormat(reply_cur, reply_end, "Send `attach 0x%lx` to attach.\n", m_wait_process_id.value);
} else if (ParsePrefix(command, "wait ")) {
/* Allow optional "0x" prefix. */
ParsePrefix(command, "0x");
/* Decode program id. */
const ncm::ProgramId program_id(DecodeHex(command));
/* Wait for the process to be created. */
{
/* Get hook to creation of process with program id. */
os::NativeHandle h;
R_ABORT_UNLESS(pm::dmnt::HookToCreateProcess(std::addressof(h), program_id));
/* Wait for event. */
os::SystemEvent hook_event(h, true, os::InvalidNativeHandle, false, os::EventClearMode_AutoClear);
hook_event.Wait();
}
/* Get process id. */
R_ABORT_UNLESS(pm::dmnt::GetProcessId(std::addressof(m_wait_process_id), program_id));
/* Note that we're attaching. */
AppendReplyFormat(reply_cur, reply_end, "Send `attach 0x%lx` to attach.\n", m_wait_process_id.value);
} else {
std::memcpy(m_reply_cur, command, std::strlen(command) + 1);
AppendReplyFormat(reply_cur, reply_end, "Unknown command `%s`\n", m_reply_cur);
}
}
void GdbServerImpl::qSupported() {
/* Current string from devkita64-none-elf-gdb: */
/* qSupported:multiprocess+;swbreak+;hwbreak+;qRelocInsn+;fork-events+;vfork-events+;exec-events+;vContSupported+;QThreadEvents+;no-resumed+ */
AppendReplyFormat(m_reply_cur, m_reply_end, "PacketSize=%lx", GdbPacketBufferSize - 1);
AppendReplyFormat(m_reply_cur, m_reply_end, ";multiprocess+");
AppendReplyFormat(m_reply_cur, m_reply_end, ";qXfer:osdata:read+");
AppendReplyFormat(m_reply_cur, m_reply_end, ";qXfer:features:read+");
AppendReplyFormat(m_reply_cur, m_reply_end, ";qXfer:libraries:read+");
// TODO: AppendReplyFormat(m_reply_cur, m_reply_end, ";qXfer:libraries-svr4:read+");
// TODO: AppendReplyFormat(m_reply_cur, m_reply_end, ";augmented-libraries-svr4-read+");
AppendReplyFormat(m_reply_cur, m_reply_end, ";qXfer:threads:read+");
AppendReplyFormat(m_reply_cur, m_reply_end, ";qXfer:exec-file:read+");
AppendReplyFormat(m_reply_cur, m_reply_end, ";swbreak+");
AppendReplyFormat(m_reply_cur, m_reply_end, ";hwbreak+");
AppendReplyFormat(m_reply_cur, m_reply_end, ";vContSupported+");
AppendReplyFormat(m_reply_cur, m_reply_end, ";QStartNoAckMode+");
}
void GdbServerImpl::qXfer() {
/* Check for osdata. */
if (ParsePrefix(m_receive_packet, "osdata:read:")) {
this->qXferOsdataRead();
} else {
/* All other qXfer require debug process. */
if (!this->HasDebugProcess()) {
AppendReplyError(m_reply_cur, m_reply_end, "E01");
return;
}
/* Process. */
if (ParsePrefix(m_receive_packet, "features:read:")) {
this->qXferFeaturesRead();
} else if (ParsePrefix(m_receive_packet, "threads:read::")) {
if (!this->qXferThreadsRead()) {
m_killed = true;
AppendReplyError(m_reply_cur, m_reply_end, "E01");
}
} else if (ParsePrefix(m_receive_packet, "libraries:read::")) {
this->qXferLibrariesRead();
} else if (ParsePrefix(m_receive_packet, "exec-file:read:")) {
AppendReplyFormat(m_reply_cur, m_reply_end, "l%s", m_debug_process.GetProcessName());
} else {
AMS_DMNT2_GDB_LOG_DEBUG("Not Implemented qxfer: %s\n", m_receive_packet);
AppendReplyError(m_reply_cur, m_reply_end, "E01");
}
}
}
void GdbServerImpl::qXferFeaturesRead() {
/* Handle the qXfer. */
u32 offset, length;
if (ParsePrefix(m_receive_packet, "target.xml:")) {
/* Parse offset/length. */
ParseOffsetLength(m_receive_packet, offset, length);
/* Send the desired xml. */
std::strncpy(m_reply_cur, (this->Is64Bit() ? TargetXmlAarch64 : TargetXmlAarch32) + offset, length);
m_reply_cur[length] = 0;
m_reply_cur += std::strlen(m_reply_cur);
} else if (ParsePrefix(m_receive_packet, "aarch64-core.xml:")) {
/* Parse offset/length. */
ParseOffsetLength(m_receive_packet, offset, length);
/* Send the desired xml. */
std::strncpy(m_reply_cur, Aarch64CoreXml + offset, length);
m_reply_cur[length] = 0;
m_reply_cur += std::strlen(m_reply_cur);
} else if (ParsePrefix(m_receive_packet, "aarch64-fpu.xml:")) {
/* Parse offset/length. */
ParseOffsetLength(m_receive_packet, offset, length);
/* Send the desired xml. */
std::strncpy(m_reply_cur, Aarch64FpuXml + offset, length);
m_reply_cur[length] = 0;
m_reply_cur += std::strlen(m_reply_cur);
} else if (ParsePrefix(m_receive_packet, "arm-core.xml:")) {
/* Parse offset/length. */
ParseOffsetLength(m_receive_packet, offset, length);
/* Send the desired xml. */
std::strncpy(m_reply_cur, ArmCoreXml + offset, length);
m_reply_cur[length] = 0;
m_reply_cur += std::strlen(m_reply_cur);
} else if (ParsePrefix(m_receive_packet, "arm-vfp.xml:")) {
/* Parse offset/length. */
ParseOffsetLength(m_receive_packet, offset, length);
/* Send the desired xml. */
std::strncpy(m_reply_cur, ArmVfpXml + offset, length);
m_reply_cur[length] = 0;
m_reply_cur += std::strlen(m_reply_cur);
} else {
AMS_DMNT2_GDB_LOG_DEBUG("Not Implemented qxfer:features:read: %s\n", m_receive_packet);
AppendReplyError(m_reply_cur, m_reply_end, "E01");
}
}
void GdbServerImpl::qXferLibrariesRead() {
/* Handle the qXfer. */
u32 offset, length;
/* Parse offset/length. */
ParseOffsetLength(m_receive_packet, offset, length);
/* Acquire access to the annex buffer. */
std::scoped_lock lk(g_annex_buffer_lock);
/* If doing a fresh read, generate the module list. */
if (offset == 0 || g_annex_buffer_contents != AnnexBufferContents_Libraries) {
/* Prepare to write to annex buffer. */
char *dst_cur = g_annex_buffer;
char *dst_end = g_annex_buffer + sizeof(g_annex_buffer);
/* Set header. */
AppendReplyFormat(dst_cur, dst_end, "<library-list>");
/* Get the module list. */
for (size_t i = 0; i < m_debug_process.GetModuleCount(); ++i) {
AMS_DMNT2_GDB_LOG_DEBUG("Module[%zu]: %p, %s\n", i, reinterpret_cast<void *>(m_debug_process.GetModuleBaseAddress(i)), m_debug_process.GetModuleName(i));
const char *module_name = m_debug_process.GetModuleName(i);
const auto name_len = std::strlen(module_name);
if (name_len < 5 || (std::strcmp(module_name + name_len - 4, ".elf") != 0 && std::strcmp(module_name + name_len - 4, ".nss") != 0)) {
AppendReplyFormat(dst_cur, dst_end, "<library name=\"%s.elf\"><segment address=\"0x%lx\" /></library>", module_name, m_debug_process.GetModuleBaseAddress(i));
} else {
AppendReplyFormat(dst_cur, dst_end, "<library name=\"%s\"><segment address=\"0x%lx\" /></library>", module_name, m_debug_process.GetModuleBaseAddress(i));
}
}
AppendReplyFormat(dst_cur, dst_end, "</library-list>");
g_annex_buffer_contents = AnnexBufferContents_Libraries;
}
/* Copy out the module list. */
GetAnnexBufferContents(m_reply_cur, offset, length);
}
void GdbServerImpl::qXferOsdataRead() {
/* Handle the qXfer. */
u32 offset, length;
if (ParsePrefix(m_receive_packet, "processes:")) {
/* Parse offset/length. */
ParseOffsetLength(m_receive_packet, offset, length);
/* Acquire access to the annex buffer. */
std::scoped_lock lk(g_annex_buffer_lock);
/* If doing a fresh read, generate the process list. */
if (offset == 0 || g_annex_buffer_contents != AnnexBufferContents_Processes) {
/* Prepare to write to annex buffer. */
char *dst_cur = g_annex_buffer;
char *dst_end = g_annex_buffer + sizeof(g_annex_buffer);
/* Clear the process list buffer. */
dst_cur[0] = 0;
/* Set header. */
AppendReplyFormat(dst_cur, dst_end, "<?xml version=\"1.0\"?>\n<!DOCTYPE target SYSTEM \"osdata.dtd\">\n<osdata type=\"processes\">\n");
/* Get all processes. */
{
/* Get all process ids. */
u64 process_ids[0x50];
s32 num_process_ids;
R_ABORT_UNLESS(svc::GetProcessList(std::addressof(num_process_ids), process_ids, util::size(process_ids)));
/* Send all processes. */
for (s32 i = 0; i < num_process_ids; ++i) {
svc::Handle handle;
if (R_SUCCEEDED(svc::DebugActiveProcess(std::addressof(handle), process_ids[i]))) {
ON_SCOPE_EXIT { R_ABORT_UNLESS(svc::CloseHandle(handle)); };
/* Get the create process event. */
svc::DebugEventInfo d;
R_ABORT_UNLESS(svc::GetDebugEvent(std::addressof(d), handle));
AMS_ABORT_UNLESS(d.type == svc::DebugEvent_CreateProcess);
AppendReplyFormat(dst_cur, dst_end, "<item>\n<column name=\"pid\">%lu</column>\n<column name=\"command\">%s</column>\n</item>\n", d.info.create_process.process_id, d.info.create_process.name);
}
}
}
/* Set footer. */
AppendReplyFormat(dst_cur, dst_end, "</osdata>");
g_annex_buffer_contents = AnnexBufferContents_Processes;
}
/* Copy out the process list. */
GetAnnexBufferContents(m_reply_cur, offset, length);
} else {
AMS_DMNT2_GDB_LOG_DEBUG("Not Implemented qxfer:osdata:read: %s\n", m_receive_packet);
AppendReplyError(m_reply_cur, m_reply_end, "E01");
}
}
bool GdbServerImpl::qXferThreadsRead() {
/* Handle the qXfer. */
u32 offset, length;
/* Parse offset/length. */
ParseOffsetLength(m_receive_packet, offset, length);
/* Acquire access to the annex buffer. */
std::scoped_lock lk(g_annex_buffer_lock);
/* If doing a fresh read, generate the thread list. */
if (offset == 0 || g_annex_buffer_contents != AnnexBufferContents_Threads) {
/* Prepare to write to annex buffer. */
char *dst_cur = g_annex_buffer;
char *dst_end = g_annex_buffer + sizeof(g_annex_buffer);
/* Set header. */
AppendReplyFormat(dst_cur, dst_end, "<threads>");
/* Get the thread list. */
u64 thread_ids[DebugProcess::ThreadCountMax];
s32 num_threads;
if (R_SUCCEEDED(m_debug_process.GetThreadList(std::addressof(num_threads), thread_ids, util::size(thread_ids)))) {
for (auto i = 0; i < num_threads; ++i) {
/* Check that we can get the thread context. */
{
svc::ThreadContext dummy_context;
if (R_FAILED(m_debug_process.GetThreadContext(std::addressof(dummy_context), thread_ids[i], svc::ThreadContextFlag_All))) {
continue;
}
}
/* Get the thread core. */
u32 core = 0;
m_debug_process.GetThreadCurrentCore(std::addressof(core), thread_ids[i]);
/* Get the thread name. */
char name[os::ThreadNameLengthMax + 1];
m_debug_process.GetThreadName(name, thread_ids[i]);
name[sizeof(name) - 1] = '\x00';
/* Sanitize the thread name. */
char sanitized[os::ThreadNameLengthMax * 4 + 1];
{
char *cur = sanitized;
for (size_t i = 0; i < util::size(name); ++i) {
if (name[i] == '<') {
*(cur++) = '&';
*(cur++) = 'l';
*(cur++) = 't';
*(cur++) = ';';
} else if (name[i] == '>') {
*(cur++) = '&';
*(cur++) = 'g';
*(cur++) = 't';
*(cur++) = ';';
} else if (name[i] == '*' || name[i] == '#' || name[i] == '$' || name[i] == '}') {
*(cur++) = '}';
*(cur++) = name[i] ^ 0x20;
} else {
*(cur++) = name[i];
if (name[i] == '\x00') {
break;
}
}
}
}
/* Set the thread entry */
AppendReplyFormat(dst_cur, dst_end, "<thread id=\"p%lx.%lx\" core=\"%u\" name=\"%s\" />", m_process_id.value, thread_ids[i], core, sanitized);
}
}
AppendReplyFormat(dst_cur, dst_end, "</threads>");
g_annex_buffer_contents = AnnexBufferContents_Threads;
}
/* Copy out the threads list. */
GetAnnexBufferContents(m_reply_cur, offset, length);
return true;
}
void GdbServerImpl::z() {
/* Increment past the 'z'. */
++m_receive_packet;
/* Decode the type. */
if (!('0' <= m_receive_packet[0] && m_receive_packet[0] <= '4') || m_receive_packet[1] != ',') {
AppendReplyError(m_reply_cur, m_reply_end, "E01");
return;
}
const auto type = m_receive_packet[0] - '0';
m_receive_packet += 2;
/* Decode the address/length. */
const char *comma = std::strchr(m_receive_packet, ',');
if (comma == nullptr) {
AppendReplyError(m_reply_cur, m_reply_end, "E01");
return;
}
/* Parse address/length. */
const u64 address = DecodeHex(m_receive_packet);
const u64 length = DecodeHex(comma + 1);
switch (type) {
case 0: /* SW */
{
if (R_SUCCEEDED(m_debug_process.ClearBreakPoint(address, length))) {
AppendReplyOk(m_reply_cur, m_reply_end);
} else {
AppendReplyError(m_reply_cur, m_reply_end, "E01");
}
}
break;
case 1: /* HW */
{
if (R_SUCCEEDED(m_debug_process.ClearHardwareBreakPoint(address, length))) {
AppendReplyOk(m_reply_cur, m_reply_end);
} else {
AppendReplyError(m_reply_cur, m_reply_end, "E01");
}
}
break;
case 2: /* Watch-W */
case 3: /* Watch-R */
case 4: /* Watch-A */
{
if (R_SUCCEEDED(m_debug_process.ClearWatchPoint(address, length))) {
AppendReplyOk(m_reply_cur, m_reply_end);
} else {
AppendReplyError(m_reply_cur, m_reply_end, "E01");
}
}
break;
default:
break;
}
}
void GdbServerImpl::QuestionMark() {
if (m_debug_process.IsValid()) {
if (m_debug_process.GetLastThreadId() == 0) {
AppendReplyFormat(m_reply_cur, m_reply_end, "X01");
} else {
this->AppendStopReplyPacket(m_debug_process.GetLastSignal());
}
} else {
AppendReplyFormat(m_reply_cur, m_reply_end, "W00");
}
}
}
| 110,778
|
C++
|
.cpp
| 2,167
| 34.175358
| 252
| 0.466662
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,118
|
jpegdec_main.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/jpegdec/source/jpegdec_main.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "jpegdec_memory_management.hpp"
namespace ams {
namespace init {
void InitializeSystemModule() {
/* Initialize heap. */
jpegdec::InitializeJpegHeap();
/* Initialize our connection to sm. */
R_ABORT_UNLESS(sm::Initialize());
/* Verify that we can sanely execute. */
ams::CheckApiVersion();
}
void FinalizeSystemModule() { /* ... */ }
void Startup() { /* ... */ }
}
void Main() {
/* Set thread name. */
os::SetThreadNamePointer(os::GetCurrentThread(), AMS_GET_SYSTEM_THREAD_NAME(jpegdec, Main));
/* Official jpegdec changes its thread priority to 21 in main. */
/* This is because older versions of the sysmodule had priority 20 in npdm. */
os::ChangeThreadPriority(os::GetCurrentThread(), AMS_GET_SYSTEM_THREAD_PRIORITY(jpegdec, Main));
AMS_ASSERT(os::GetThreadPriority(os::GetCurrentThread()) == AMS_GET_SYSTEM_THREAD_PRIORITY(jpegdec, Main));
/* Initialize the capsrv library. */
R_ABORT_UNLESS(capsrv::server::InitializeForDecoderServer());
/* Service the decoder server. */
capsrv::server::DecoderControlServerThreadFunction(nullptr);
/* Finalize the capsrv library. */
capsrv::server::FinalizeForDecoderServer();
}
}
| 2,023
|
C++
|
.cpp
| 45
| 38.533333
| 115
| 0.672098
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,119
|
jpegdec_memory_management.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/jpegdec/source/jpegdec_memory_management.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "jpegdec_memory_management.hpp"
namespace ams::jpegdec {
namespace {
/* TODO: Update libjpeg-turbo to include Nintendo's changes (support for work buffer, rather than malloc) */
constexpr size_t JpegHeapSize = 96_KB;
alignas(0x10) constinit u8 g_jpeg_heap_memory[JpegHeapSize];
constinit lmem::HeapHandle g_jpeg_heap_handle;
}
void InitializeJpegHeap() {
g_jpeg_heap_handle = lmem::CreateExpHeap(g_jpeg_heap_memory, sizeof(g_jpeg_heap_memory), lmem::CreateOption_None);
}
}
extern "C" void *__wrap_jpeg_get_small(void *cinfo, size_t size) {
AMS_UNUSED(cinfo);
return ::ams::lmem::AllocateFromExpHeap(::ams::jpegdec::g_jpeg_heap_handle, size);
}
extern "C" void __wrap_jpeg_free_small(void *cinfo, void *ptr, size_t size) {
AMS_UNUSED(cinfo, size);
return ::ams::lmem::FreeToExpHeap(::ams::jpegdec::g_jpeg_heap_handle, ptr);
}
extern "C" void *__wrap_jpeg_get_large(void *cinfo, size_t size) {
AMS_UNUSED(cinfo);
return ::ams::lmem::AllocateFromExpHeap(::ams::jpegdec::g_jpeg_heap_handle, size);
}
extern "C" void __wrap_jpeg_free_large(void *cinfo, void *ptr, size_t size) {
AMS_UNUSED(cinfo, size);
return ::ams::lmem::FreeToExpHeap(::ams::jpegdec::g_jpeg_heap_handle, ptr);
}
| 1,949
|
C++
|
.cpp
| 44
| 40.727273
| 122
| 0.713833
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,120
|
jpegdec_environment.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/jpegdec/source/jpegdec_environment.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
extern "C" int __wrap_sprintf (char *str, const char *fmt, ...) {
AMS_UNUSED(fmt);
str[0] = '\x00';
return 0;
}
extern "C" int __wrap_fprintf(void *stream, const char *fmt, ...) {
AMS_UNUSED(stream, fmt);
return 0;
}
extern "C" void *__wrap_getenv(const char *) {
return nullptr;
}
extern "C" void __wrap_sscanf(const char *str, const char *format, ...) {
AMS_UNUSED(str, format);
AMS_ABORT("sscanf was called\n");
}
| 1,117
|
C++
|
.cpp
| 32
| 32.3125
| 76
| 0.701852
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,121
|
ldr_argument_store.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/loader/source/ldr_argument_store.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "ldr_argument_store.hpp"
namespace ams::ldr {
int ArgumentStore::FindIndex(Entry *map, ncm::ProgramId program_id) {
for (auto i = 0; i < ArgumentMapCount; ++i) {
if (map[i].program_id == program_id) {
return i;
}
}
return -1;
}
const ArgumentStore::Entry *ArgumentStore::Get(ncm::ProgramId program_id) {
/* Find the matching arguments entry. */
Entry *argument = nullptr;
if (auto idx = FindIndex(m_argument_map, program_id); idx >= 0) {
argument = m_argument_map + idx;
}
return argument;
}
Result ArgumentStore::Set(ncm::ProgramId program_id, const void *argument, size_t size) {
/* Check that the argument size is within bounds. */
R_UNLESS(size < ArgumentBufferSize, ldr::ResultArgumentOverflow());
/* Find either a matching arguments entry, or an empty entry. */
auto idx = FindIndex(m_argument_map, program_id);
if (idx < 0) {
idx = FindIndex(m_argument_map, ncm::InvalidProgramId);
}
R_UNLESS(idx >= 0, ldr::ResultArgumentCountOverflow());
/* Set the arguments in the entry. */
auto &entry = m_argument_map[idx];
entry.program_id = program_id;
entry.argument_size = size;
std::memcpy(entry.argument, argument, entry.argument_size);
R_SUCCEED();
}
}
| 2,098
|
C++
|
.cpp
| 51
| 34.627451
| 93
| 0.649804
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,122
|
ldr_meta.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/loader/source/ldr_meta.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "ldr_capabilities.hpp"
#include "ldr_content_management.hpp"
#include "ldr_development_manager.hpp"
#include "ldr_meta.hpp"
namespace ams::ldr {
namespace {
/* Convenience definitions. */
constexpr size_t MetaCacheBufferSize = 0x8000;
constexpr inline const char AtmosphereMetaPath[] = ENCODE_ATMOSPHERE_CODE_PATH("/main.npdm");
constexpr inline const char SdOrBaseMetaPath[] = ENCODE_SD_OR_CODE_PATH("/main.npdm");
constexpr inline const char BaseMetaPath[] = ENCODE_CODE_PATH("/main.npdm");
/* Types. */
struct MetaCache {
Meta meta;
u8 buffer[MetaCacheBufferSize];
};
/* Global storage. */
ncm::ProgramId g_cached_program_id;
cfg::OverrideStatus g_cached_override_status;
MetaCache g_meta_cache;
MetaCache g_original_meta_cache;
/* Helpers. */
Result ValidateSubregion(size_t allowed_start, size_t allowed_end, size_t start, size_t size, size_t min_size = 0) {
R_UNLESS(size >= min_size, ldr::ResultInvalidMeta());
R_UNLESS(allowed_start <= start, ldr::ResultInvalidMeta());
R_UNLESS(start <= allowed_end, ldr::ResultInvalidMeta());
R_UNLESS(start + size <= allowed_end, ldr::ResultInvalidMeta());
R_SUCCEED();
}
Result ValidateNpdm(const Npdm *npdm, size_t size) {
/* Validate magic. */
R_UNLESS(npdm->magic == Npdm::Magic, ldr::ResultInvalidMeta());
/* Validate flags. */
constexpr u32 InvalidMetaFlagMask = 0x80000000;
R_UNLESS(!(npdm->flags & InvalidMetaFlagMask), ldr::ResultInvalidMeta());
/* Validate Acid extents. */
R_TRY(ValidateSubregion(sizeof(Npdm), size, npdm->acid_offset, npdm->acid_size, sizeof(Acid)));
/* Validate Aci extends. */
R_TRY(ValidateSubregion(sizeof(Npdm), size, npdm->aci_offset, npdm->aci_size, sizeof(Aci)));
R_SUCCEED();
}
Result ValidateAcid(const Acid *acid, size_t size) {
/* Validate magic. */
R_UNLESS(acid->magic == Acid::Magic, ldr::ResultInvalidMeta());
/* Validate that the acid is for production if not development. */
if (!IsDevelopmentForAcidProductionCheck()) {
R_UNLESS((acid->flags & Acid::AcidFlag_Production) != 0, ldr::ResultInvalidMeta());
}
/* Validate that the acid version is correct. */
constexpr u8 SupportedSdkMajorVersion = ams::svc::ConvertToSdkMajorVersion(ams::svc::SupportedKernelMajorVersion);
if (acid->unknown_209 < SupportedSdkMajorVersion) {
R_UNLESS(acid->version == 0, ldr::ResultInvalidMeta());
R_UNLESS(acid->unknown_209 == 0, ldr::ResultInvalidMeta());
}
/* Validate Fac, Sac, Kac. */
R_TRY(ValidateSubregion(sizeof(Acid), size, acid->fac_offset, acid->fac_size));
R_TRY(ValidateSubregion(sizeof(Acid), size, acid->sac_offset, acid->sac_size));
R_TRY(ValidateSubregion(sizeof(Acid), size, acid->kac_offset, acid->kac_size));
R_SUCCEED();
}
Result ValidateAci(const Aci *aci, size_t size) {
/* Validate magic. */
R_UNLESS(aci->magic == Aci::Magic, ldr::ResultInvalidMeta());
/* Validate Fah, Sac, Kac. */
R_TRY(ValidateSubregion(sizeof(Aci), size, aci->fah_offset, aci->fah_size));
R_TRY(ValidateSubregion(sizeof(Aci), size, aci->sac_offset, aci->sac_size));
R_TRY(ValidateSubregion(sizeof(Aci), size, aci->kac_offset, aci->kac_size));
R_SUCCEED();
}
const u8 *GetAcidSignatureModulus(ncm::ContentMetaPlatform platform, u8 key_generation, bool unk_unused) {
return fssystem::GetAcidSignatureKeyModulus(platform, !IsDevelopmentForAcidSignatureCheck(), key_generation, unk_unused);
}
size_t GetAcidSignatureModulusSize(ncm::ContentMetaPlatform platform, bool unk_unused) {
return fssystem::GetAcidSignatureKeyModulusSize(platform, unk_unused);
}
Result ValidateAcidSignature(Meta *meta, ncm::ContentMetaPlatform platform, bool unk_unused) {
/* Loader did not check signatures prior to 10.0.0. */
if (hos::GetVersion() < hos::Version_10_0_0) {
meta->check_verification_data = false;
R_SUCCEED();
}
/* Get the signature key generation. */
const auto signature_key_generation = meta->npdm->signature_key_generation;
R_UNLESS(fssystem::IsValidSignatureKeyGeneration(platform, signature_key_generation), ldr::ResultInvalidMeta());
/* Verify the signature. */
const u8 *sig = meta->acid->signature;
const size_t sig_size = sizeof(meta->acid->signature);
const u8 *mod = GetAcidSignatureModulus(platform, signature_key_generation, unk_unused);
const size_t mod_size = GetAcidSignatureModulusSize(platform, unk_unused);
const u8 *exp = fssystem::GetAcidSignatureKeyPublicExponent();
const size_t exp_size = fssystem::AcidSignatureKeyPublicExponentSize;
const u8 *msg = meta->acid->modulus;
const size_t msg_size = meta->acid->size;
const bool is_signature_valid = crypto::VerifyRsa2048PssSha256(sig, sig_size, mod, mod_size, exp, exp_size, msg, msg_size);
R_UNLESS(is_signature_valid || !IsEnabledProgramVerification(), ldr::ResultInvalidAcidSignature());
meta->check_verification_data = is_signature_valid;
R_SUCCEED();
}
Result LoadMetaFromFile(fs::FileHandle file, MetaCache *cache) {
/* Reset cache. */
cache->meta = {};
/* Read from file. */
s64 npdm_size = 0;
{
/* Get file size. */
R_TRY(fs::GetFileSize(std::addressof(npdm_size), file));
/* Read data into cache buffer. */
R_UNLESS(npdm_size <= static_cast<s64>(MetaCacheBufferSize), ldr::ResultMetaOverflow());
R_TRY(fs::ReadFile(file, 0, cache->buffer, npdm_size));
}
/* Ensure size is big enough. */
R_UNLESS(npdm_size >= static_cast<s64>(sizeof(Npdm)), ldr::ResultInvalidMeta());
/* Validate the meta. */
{
Meta *meta = std::addressof(cache->meta);
Npdm *npdm = reinterpret_cast<Npdm *>(cache->buffer);
R_TRY(ValidateNpdm(npdm, npdm_size));
Acid *acid = reinterpret_cast<Acid *>(cache->buffer + npdm->acid_offset);
Aci *aci = reinterpret_cast<Aci *>(cache->buffer + npdm->aci_offset);
R_TRY(ValidateAcid(acid, npdm->acid_size));
R_TRY(ValidateAci(aci, npdm->aci_size));
/* Set Meta members. */
meta->npdm = npdm;
meta->acid = acid;
meta->aci = aci;
meta->acid_fac = reinterpret_cast<u8 *>(acid) + acid->fac_offset;
meta->acid_sac = reinterpret_cast<u8 *>(acid) + acid->sac_offset;
meta->acid_kac = reinterpret_cast<u8 *>(acid) + acid->kac_offset;
meta->aci_fah = reinterpret_cast<u8 *>(aci) + aci->fah_offset;
meta->aci_sac = reinterpret_cast<u8 *>(aci) + aci->sac_offset;
meta->aci_kac = reinterpret_cast<u8 *>(aci) + aci->kac_offset;
meta->modulus = acid->modulus;
}
R_SUCCEED();
}
}
/* API. */
Result LoadMeta(Meta *out_meta, const ncm::ProgramLocation &loc, const cfg::OverrideStatus &status, ncm::ContentMetaPlatform platform, bool unk_unused) {
/* Set the cached program id back to zero. */
g_cached_program_id = {};
/* Try to load meta from file. */
fs::FileHandle file;
R_TRY(fs::OpenFile(std::addressof(file), AtmosphereMetaPath, fs::OpenMode_Read));
{
ON_SCOPE_EXIT { fs::CloseFile(file); };
R_TRY(LoadMetaFromFile(file, std::addressof(g_meta_cache)));
}
/* Patch meta. Start by setting all program ids to the current program id. */
Meta *meta = std::addressof(g_meta_cache.meta);
meta->acid->program_id_min = loc.program_id;
meta->acid->program_id_max = loc.program_id;
meta->aci->program_id = loc.program_id;
/* For HBL, we need to copy some information from the base meta. */
if (status.IsHbl()) {
if (R_SUCCEEDED(fs::OpenFile(std::addressof(file), SdOrBaseMetaPath, fs::OpenMode_Read))) {
ON_SCOPE_EXIT { fs::CloseFile(file); };
if (R_SUCCEEDED(LoadMetaFromFile(file, std::addressof(g_original_meta_cache)))) {
Meta *o_meta = std::addressof(g_original_meta_cache.meta);
/* Fix pool partition. */
if (hos::GetVersion() >= hos::Version_5_0_0) {
meta->acid->flags = (meta->acid->flags & 0xFFFFFFC3) | (o_meta->acid->flags & 0x0000003C);
}
/* Fix flags. */
const u16 program_info_flags = MakeProgramInfoFlag(static_cast<const util::BitPack32 *>(o_meta->aci_kac), o_meta->aci->kac_size / sizeof(util::BitPack32));
UpdateProgramInfoFlag(program_info_flags, static_cast<util::BitPack32 *>(meta->acid_kac), meta->acid->kac_size / sizeof(util::BitPack32));
UpdateProgramInfoFlag(program_info_flags, static_cast<util::BitPack32 *>(meta->aci_kac), meta->aci->kac_size / sizeof(util::BitPack32));
}
}
/* Perform address space override. */
if (status.HasOverrideAddressSpace()) {
/* Clear the existing address space. */
meta->npdm->flags &= ~Npdm::MetaFlag_AddressSpaceTypeMask;
/* Set the new address space flag. */
switch (status.GetOverrideAddressSpaceFlags()) {
case cfg::impl::OverrideStatusFlag_AddressSpace32Bit: meta->npdm->flags |= (Npdm::AddressSpaceType_32Bit) << Npdm::MetaFlag_AddressSpaceTypeShift; break;
case cfg::impl::OverrideStatusFlag_AddressSpace64BitDeprecated: meta->npdm->flags |= (Npdm::AddressSpaceType_64BitDeprecated) << Npdm::MetaFlag_AddressSpaceTypeShift; break;
case cfg::impl::OverrideStatusFlag_AddressSpace32BitWithoutAlias: meta->npdm->flags |= (Npdm::AddressSpaceType_32BitWithoutAlias) << Npdm::MetaFlag_AddressSpaceTypeShift; break;
case cfg::impl::OverrideStatusFlag_AddressSpace64Bit: meta->npdm->flags |= (Npdm::AddressSpaceType_64Bit) << Npdm::MetaFlag_AddressSpaceTypeShift; break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
/* When hbl is applet, adjust main thread priority. */
if ((MakeProgramInfoFlag(static_cast<const util::BitPack32 *>(meta->aci_kac), meta->aci->kac_size / sizeof(util::BitPack32)) & ProgramInfoFlag_ApplicationTypeMask) == ProgramInfoFlag_Applet) {
constexpr auto HblMainThreadPriorityApplication = 44;
constexpr auto HblMainThreadPriorityApplet = 40;
if (meta->npdm->main_thread_priority == HblMainThreadPriorityApplication) {
meta->npdm->main_thread_priority = HblMainThreadPriorityApplet;
}
}
/* Fix the debug capabilities, to prevent needing a hbl recompilation. */
FixDebugCapabilityForHbl(static_cast<util::BitPack32 *>(meta->acid_kac), meta->acid->kac_size / sizeof(util::BitPack32));
FixDebugCapabilityForHbl(static_cast<util::BitPack32 *>(meta->aci_kac), meta->aci->kac_size / sizeof(util::BitPack32));
} else if (hos::GetVersion() >= hos::Version_10_0_0) {
/* If storage id is none, there is no base code filesystem, and thus it is impossible for us to validate. */
/* However, if we're an application, we are guaranteed a base code filesystem. */
if (static_cast<ncm::StorageId>(loc.storage_id) != ncm::StorageId::None || ncm::IsApplicationId(loc.program_id)) {
R_TRY(fs::OpenFile(std::addressof(file), BaseMetaPath, fs::OpenMode_Read));
ON_SCOPE_EXIT { fs::CloseFile(file); };
R_TRY(LoadMetaFromFile(file, std::addressof(g_original_meta_cache)));
R_TRY(ValidateAcidSignature(std::addressof(g_original_meta_cache.meta), platform, unk_unused));
meta->modulus = g_original_meta_cache.meta.modulus;
meta->check_verification_data = g_original_meta_cache.meta.check_verification_data;
}
}
/* Pre-process the capabilities. */
/* This is used to e.g. avoid passing memory region descriptor to older kernels. */
PreProcessCapability(static_cast<util::BitPack32 *>(meta->acid_kac), meta->acid->kac_size / sizeof(util::BitPack32));
PreProcessCapability(static_cast<util::BitPack32 *>(meta->aci_kac), meta->aci->kac_size / sizeof(util::BitPack32));
/* Set output. */
g_cached_program_id = loc.program_id;
g_cached_override_status = status;
*out_meta = *meta;
R_SUCCEED();
}
Result LoadMetaFromCache(Meta *out_meta, const ncm::ProgramLocation &loc, const cfg::OverrideStatus &status, ncm::ContentMetaPlatform platform) {
if (g_cached_program_id != loc.program_id || g_cached_override_status != status) {
R_RETURN(LoadMeta(out_meta, loc, status, platform, false));
}
*out_meta = g_meta_cache.meta;
R_SUCCEED();
}
void InvalidateMetaCache() {
/* Set the cached program id back to zero. */
g_cached_program_id = {};
}
}
| 14,819
|
C++
|
.cpp
| 242
| 49.070248
| 204
| 0.606501
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
7,123
|
ldr_capabilities.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/loader/source/ldr_capabilities.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "ldr_capabilities.hpp"
namespace ams::ldr {
namespace {
/* Types. */
enum class CapabilityId {
KernelFlags = 3,
SyscallMask = 4,
MapRange = 6,
MapPage = 7,
MapRegion = 10,
InterruptPair = 11,
ApplicationType = 13,
KernelVersion = 14,
HandleTable = 15,
DebugFlags = 16,
Empty = 32,
};
template<size_t Index, size_t Count, typename T = u32>
using CapabilityField = util::BitPack32::Field<Index, Count, T>;
#define DEFINE_CAPABILITY_FIELD(name, prev, ...) \
using name = CapabilityField<prev::Next, __VA_ARGS__>; \
constexpr ALWAYS_INLINE typename name::Type Get##name() const { return this->Get<name>(); }
constexpr ALWAYS_INLINE CapabilityId GetCapabilityId(util::BitPack32 cap) {
return static_cast<CapabilityId>(util::CountTrailingZeros<u32>(~cap.value));
}
constexpr inline util::BitPack32 EmptyCapability = {~u32{}};
static_assert(GetCapabilityId(EmptyCapability) == CapabilityId::Empty);
#define CAPABILITY_CLASS_NAME(id) Capability##id
#define DEFINE_CAPABILITY_CLASS(id, member_functions) \
class CAPABILITY_CLASS_NAME(id) { \
public: \
static constexpr CapabilityId Id = CapabilityId::id; \
using IdBits = CapabilityField<0, static_cast<size_t>(Id) + 1>; \
static constexpr u32 IdBitsValue = (static_cast<u32>(1) << static_cast<size_t>(Id)) - 1; \
private: \
util::BitPack32 m_value; \
private: \
template<typename FieldType> \
constexpr ALWAYS_INLINE typename FieldType::Type Get() const { return m_value.Get<FieldType>(); } \
template<typename FieldType> \
constexpr ALWAYS_INLINE void Set(typename FieldType::Type fv) { m_value.Set<FieldType>(fv); } \
constexpr ALWAYS_INLINE u32 GetValue() const { return m_value.value; } \
public: \
constexpr ALWAYS_INLINE CAPABILITY_CLASS_NAME(id)(util::BitPack32 v) : m_value{v} { /* ... */ } \
\
static constexpr CAPABILITY_CLASS_NAME(id) Decode(util::BitPack32 v) { return CAPABILITY_CLASS_NAME(id)(v); } \
\
member_functions \
}; \
static_assert(std::is_trivially_destructible<CAPABILITY_CLASS_NAME(id)>::value)
/* Class definitions. */
DEFINE_CAPABILITY_CLASS(KernelFlags,
DEFINE_CAPABILITY_FIELD(MaximumThreadPriority, IdBits, 6);
DEFINE_CAPABILITY_FIELD(MinimumThreadPriority, MaximumThreadPriority, 6);
DEFINE_CAPABILITY_FIELD(MinimumCoreId, MinimumThreadPriority, 8);
DEFINE_CAPABILITY_FIELD(MaximumCoreId, MinimumCoreId, 8);
bool IsValid(const util::BitPack32 *kac, size_t kac_count) const {
for (size_t i = 0; i < kac_count; i++) {
if (GetCapabilityId(kac[i]) == Id) {
const auto restriction = Decode(kac[i]);
if (this->GetMinimumThreadPriority() < restriction.GetMinimumThreadPriority() ||
this->GetMaximumThreadPriority() > restriction.GetMaximumThreadPriority() ||
this->GetMinimumThreadPriority() > this->GetMaximumThreadPriority()) {
return false;
}
if (this->GetMinimumCoreId() < restriction.GetMinimumCoreId() ||
this->GetMaximumCoreId() > restriction.GetMaximumCoreId() ||
this->GetMinimumCoreId() > this->GetMaximumCoreId()) {
return false;
}
return true;
}
}
return false;
}
);
DEFINE_CAPABILITY_CLASS(SyscallMask,
DEFINE_CAPABILITY_FIELD(Mask, IdBits, 24);
DEFINE_CAPABILITY_FIELD(Index, Mask, 3);
bool IsValid(const util::BitPack32 *kac, size_t kac_count) const {
for (size_t i = 0; i < kac_count; i++) {
if (GetCapabilityId(kac[i]) == Id) {
const auto restriction = Decode(kac[i]);
if (this->GetIndex() == restriction.GetIndex() && this->GetMask() == restriction.GetMask()) {
return true;
}
}
}
return false;
}
);
DEFINE_CAPABILITY_CLASS(MapRange,
DEFINE_CAPABILITY_FIELD(AddressSize, IdBits, 24);
DEFINE_CAPABILITY_FIELD(Flag, AddressSize, 1, bool);
static constexpr size_t SizeMax = 0x100000;
bool IsValid(const util::BitPack32 next_cap, const util::BitPack32 *kac, size_t kac_count) const {
if (GetCapabilityId(next_cap) != Id) {
return false;
}
const auto next = Decode(next_cap);
const u32 start = this->GetAddressSize();
const u32 size = next.GetAddressSize();
const u32 end = start + size;
if (size >= SizeMax) {
return false;
}
for (size_t i = 0; i < kac_count; i++) {
if (GetCapabilityId(kac[i]) == Id) {
const auto restriction = Decode(kac[i++]);
if (i >= kac_count || GetCapabilityId(kac[i]) != Id) {
return false;
}
const auto restriction_next = Decode(kac[i]);
const u32 restriction_start = restriction.GetAddressSize();
const u32 restriction_size = restriction_next.GetAddressSize();
const u32 restriction_end = restriction_start + restriction_size;
if (restriction_size >= SizeMax) {
continue;
}
if (this->GetFlag() == restriction.GetFlag() && next.GetFlag() == restriction_next.GetFlag()) {
if (restriction_start <= start && start <= restriction_end && end <= restriction_end) {
return true;
}
}
}
}
return false;
}
);
DEFINE_CAPABILITY_CLASS(MapPage,
DEFINE_CAPABILITY_FIELD(Address, IdBits, 24);
bool IsValid(const util::BitPack32 *kac, size_t kac_count) const {
for (size_t i = 0; i < kac_count; i++) {
if (GetCapabilityId(kac[i]) == Id) {
const auto restriction = Decode(kac[i]);
if (this->GetValue() == restriction.GetValue()) {
return true;
}
}
}
return false;
}
);
enum class MemoryRegionType : u32 {
NoMapping = 0,
KernelTraceBuffer = 1,
OnMemoryBootImage = 2,
DTB = 3,
};
DEFINE_CAPABILITY_CLASS(MapRegion,
DEFINE_CAPABILITY_FIELD(Region0, IdBits, 6, MemoryRegionType);
DEFINE_CAPABILITY_FIELD(ReadOnly0, Region0, 1, bool);
DEFINE_CAPABILITY_FIELD(Region1, ReadOnly0, 6, MemoryRegionType);
DEFINE_CAPABILITY_FIELD(ReadOnly1, Region1, 1, bool);
DEFINE_CAPABILITY_FIELD(Region2, ReadOnly1, 6, MemoryRegionType);
DEFINE_CAPABILITY_FIELD(ReadOnly2, Region2, 1, bool);
static bool IsValidRegionType(const util::BitPack32 *kac, size_t kac_count, MemoryRegionType region_type, bool is_read_only) {
if (region_type != MemoryRegionType::NoMapping) {
for (size_t i = 0; i < kac_count; i++) {
if (GetCapabilityId(kac[i]) == Id) {
const auto restriction = Decode(kac[i]);
if ((restriction.GetRegion0() == region_type && (is_read_only || !restriction.GetReadOnly0())) ||
(restriction.GetRegion1() == region_type && (is_read_only || !restriction.GetReadOnly1())) ||
(restriction.GetRegion2() == region_type && (is_read_only || !restriction.GetReadOnly2())))
{
return true;
}
}
}
return false;
} else {
return true;
}
}
bool IsValid(const util::BitPack32 *kac, size_t kac_count) const {
return IsValidRegionType(kac, kac_count, this->GetRegion0(), this->GetReadOnly0()) &&
IsValidRegionType(kac, kac_count, this->GetRegion1(), this->GetReadOnly1()) &&
IsValidRegionType(kac, kac_count, this->GetRegion2(), this->GetReadOnly2());
}
);
DEFINE_CAPABILITY_CLASS(InterruptPair,
DEFINE_CAPABILITY_FIELD(InterruptId0, IdBits, 10);
DEFINE_CAPABILITY_FIELD(InterruptId1, InterruptId0, 10);
static constexpr u32 EmptyInterruptId = 0x3FF;
bool IsSingleIdValid(const u32 id, const util::BitPack32 *kac, size_t kac_count) const {
for (size_t i = 0; i < kac_count; i++) {
if (GetCapabilityId(kac[i]) == Id) {
const auto restriction = Decode(kac[i]);
if (restriction.GetInterruptId0() == EmptyInterruptId && restriction.GetInterruptId1() == EmptyInterruptId) {
return true;
}
if (restriction.GetInterruptId0() == id || restriction.GetInterruptId1() == id) {
return true;
}
}
}
return false;
}
bool IsValid(const util::BitPack32 *kac, size_t kac_count) const {
return IsSingleIdValid(this->GetInterruptId0(), kac, kac_count) && IsSingleIdValid(this->GetInterruptId1(), kac, kac_count);
}
);
DEFINE_CAPABILITY_CLASS(ApplicationType,
DEFINE_CAPABILITY_FIELD(ApplicationType, IdBits, 3);
bool IsValid(const util::BitPack32 *kac, size_t kac_count) const {
for (size_t i = 0; i < kac_count; i++) {
if (GetCapabilityId(kac[i]) == Id) {
const auto restriction = Decode(kac[i]);
return restriction.GetValue() == this->GetValue();
}
}
return false;
}
static constexpr util::BitPack32 Encode(u32 app_type) {
util::BitPack32 encoded{IdBitsValue};
encoded.Set<ApplicationType>(app_type);
return encoded;
}
);
DEFINE_CAPABILITY_CLASS(KernelVersion,
DEFINE_CAPABILITY_FIELD(MinorVersion, IdBits, 4);
DEFINE_CAPABILITY_FIELD(MajorVersion, MinorVersion, 13);
bool IsValid(const util::BitPack32 *kac, size_t kac_count) const {
for (size_t i = 0; i < kac_count; i++) {
if (GetCapabilityId(kac[i]) == Id) {
const auto restriction = Decode(kac[i]);
return restriction.GetValue() == this->GetValue();
}
}
return false;
}
);
DEFINE_CAPABILITY_CLASS(HandleTable,
DEFINE_CAPABILITY_FIELD(Size, IdBits, 10);
bool IsValid(const util::BitPack32 *kac, size_t kac_count) const {
for (size_t i = 0; i < kac_count; i++) {
if (GetCapabilityId(kac[i]) == Id) {
const auto restriction = Decode(kac[i]);
return this->GetSize() <= restriction.GetSize();
}
}
return false;
}
);
DEFINE_CAPABILITY_CLASS(DebugFlags,
DEFINE_CAPABILITY_FIELD(AllowDebug, IdBits, 1, bool);
DEFINE_CAPABILITY_FIELD(ForceDebugProd, AllowDebug, 1, bool);
DEFINE_CAPABILITY_FIELD(ForceDebug, ForceDebugProd, 1, bool);
bool IsValid(const util::BitPack32 *kac, size_t kac_count) const {
u32 total = 0;
if (this->GetAllowDebug()) { ++total; }
if (this->GetForceDebugProd()) { ++total; }
if (this->GetForceDebug()) { ++total; }
if (total > 1) {
return false;
}
for (size_t i = 0; i < kac_count; i++) {
if (GetCapabilityId(kac[i]) == Id) {
const auto restriction = Decode(kac[i]);
return (restriction.GetValue() & this->GetValue()) == this->GetValue();
}
}
return false;
}
static constexpr util::BitPack32 Encode(bool allow_debug, bool force_debug_prod, bool force_debug) {
util::BitPack32 encoded{IdBitsValue};
encoded.Set<AllowDebug>(allow_debug);
encoded.Set<ForceDebugProd>(force_debug_prod);
encoded.Set<ForceDebug>(force_debug);
return encoded;
}
);
}
/* Capabilities API. */
Result TestCapability(const util::BitPack32 *kacd, size_t kacd_count, const util::BitPack32 *kac, size_t kac_count) {
for (size_t i = 0; i < kac_count; i++) {
const auto cap = kac[i];
const auto id = GetCapabilityId(cap);
#define VALIDATE_CASE(id) \
case CapabilityId::id: \
R_UNLESS(Capability##id::Decode(cap).IsValid(kacd, kacd_count), ldr::ResultInvalidCapability##id()); \
break
switch (id) {
VALIDATE_CASE(KernelFlags);
VALIDATE_CASE(SyscallMask);
VALIDATE_CASE(MapPage);
VALIDATE_CASE(MapRegion);
VALIDATE_CASE(InterruptPair);
VALIDATE_CASE(ApplicationType);
VALIDATE_CASE(KernelVersion);
VALIDATE_CASE(HandleTable);
VALIDATE_CASE(DebugFlags);
case CapabilityId::MapRange:
{
/* Map Range needs extra logic because there it involves two sequential caps. */
i++;
R_UNLESS(i < kac_count, ldr::ResultInvalidCapabilityMapRange());
R_UNLESS(CapabilityMapRange::Decode(cap).IsValid(kac[i], kacd, kacd_count), ldr::ResultInvalidCapabilityMapRange());
}
break;
default:
R_UNLESS(id == CapabilityId::Empty, ldr::ResultUnknownCapability());
break;
}
#undef VALIDATE_CASE
}
R_SUCCEED();
}
u16 MakeProgramInfoFlag(const util::BitPack32 *kac, size_t count) {
u16 flags = 0;
for (size_t i = 0; i < count; ++i) {
const auto cap = kac[i];
switch (GetCapabilityId(cap)) {
case CapabilityId::ApplicationType:
{
const auto app_type = CapabilityApplicationType::Decode(cap).GetApplicationType() & ProgramInfoFlag_ApplicationTypeMask;
if (app_type != ProgramInfoFlag_InvalidType) {
flags |= app_type;
}
}
break;
case CapabilityId::DebugFlags:
if (CapabilityDebugFlags::Decode(cap).GetAllowDebug()) {
flags |= ProgramInfoFlag_AllowDebug;
}
break;
default:
break;
}
}
return flags;
}
void UpdateProgramInfoFlag(u16 flags, util::BitPack32 *kac, size_t count) {
for (size_t i = 0; i < count; ++i) {
const auto cap = kac[i];
switch (GetCapabilityId(cap)) {
case CapabilityId::ApplicationType:
kac[i] = CapabilityApplicationType::Encode(flags & ProgramInfoFlag_ApplicationTypeMask);
break;
case CapabilityId::DebugFlags:
kac[i] = CapabilityDebugFlags::Encode((flags & ProgramInfoFlag_AllowDebug) != 0, CapabilityDebugFlags::Decode(cap).GetForceDebugProd(), CapabilityDebugFlags::Decode(cap).GetForceDebug());
break;
default:
break;
}
}
}
void FixDebugCapabilityForHbl(util::BitPack32 *kac, size_t count) {
for (size_t i = 0; i < count; ++i) {
const auto cap = kac[i];
switch (GetCapabilityId(cap)) {
case CapabilityId::DebugFlags:
/* 19.0.0+ disallows more than one flag set; we are always DebugMode for kernel, so ForceDebug is the most powerful/flexible flag to set. */
kac[i] = CapabilityDebugFlags::Encode(false, false, true);
break;
default:
break;
}
}
}
void PreProcessCapability(util::BitPack32 *kac, size_t count) {
for (size_t i = 0; i < count; ++i) {
const auto cap = kac[i];
switch (GetCapabilityId(cap)) {
/* NOTE: Currently, there is no pre-processing necessary. */
default:
break;
}
}
}
}
| 20,627
|
C++
|
.cpp
| 387
| 36.583979
| 207
| 0.471101
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.