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,333
secmon_misc.cpp
Atmosphere-NX_Atmosphere/exosphere/program/source/secmon_misc.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 <exosphere.hpp> #include "secmon_misc.hpp" namespace ams::secmon { namespace { constinit pkg1::BctParameters g_bct_params = {}; constinit se::Sha256Hash g_package2_hash = {}; constinit u32 g_deprecated_boot_reason_value = {}; constinit u8 g_deprecated_boot_reason_state = {}; } void SaveBootInfo(const pkg1::SecureMonitorParameters &secmon_params) { /* Save the BCT parameters. */ g_bct_params = secmon_params.bct_params; /* Save the deprecated boot reason. */ g_deprecated_boot_reason_value = secmon_params.deprecated_boot_reason_value; g_deprecated_boot_reason_state = secmon_params.deprecated_boot_reason_state; } bool IsRecoveryBoot() { return (g_bct_params.bootloader_attributes & pkg1::BootloaderAttribute_RecoveryBoot) != 0; } u32 GetRestrictedSmcMask() { return (g_bct_params.bootloader_attributes & pkg1::BootloaderAttribute_RestrictedSmcMask) >> pkg1::BootloaderAttribute_RestrictedSmcShift; } bool IsJtagEnabled() { util::BitPack32 dbg_auth; HW_CPU_GET_DBGAUTHSTATUS_EL1(dbg_auth); return dbg_auth.Get<hw::DbgAuthStatusEl1::Nsid>() == 3; } void GetPackage2Hash(se::Sha256Hash *out) { *out = g_package2_hash; } void SetPackage2Hash(const se::Sha256Hash &hash) { g_package2_hash = hash; } u32 GetDeprecatedBootReason() { return (static_cast<u32>(g_deprecated_boot_reason_state) << 24) | (g_deprecated_boot_reason_value & 0x00FFFFFF); } }
2,208
C++
.cpp
52
37.076923
146
0.69888
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,334
secmon_page_mapper.cpp
Atmosphere-NX_Atmosphere/exosphere/program/source/secmon_page_mapper.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 <exosphere.hpp> #include "secmon_map.hpp" #include "secmon_page_mapper.hpp" namespace ams::secmon { namespace impl { void *PageMapperImpl::GetPointerTo(uintptr_t phys, size_t size) const { /* Ensure we stay within the page. */ if (util::AlignDown(phys, 4_KB) != m_physical_address) { return nullptr; } if (size != 0) { if (util::AlignDown(phys + size - 1, 4_KB) != m_physical_address) { return nullptr; } } return reinterpret_cast<void *>(phys + (m_virtual_address - m_physical_address)); } bool PageMapperImpl::CopyToMapping(uintptr_t dst_phys, const void *src, size_t size) const { void * const dst = this->GetPointerTo(dst_phys, size); if (dst == nullptr) { return false; } std::memcpy(dst, src, size); return true; } bool PageMapperImpl::CopyFromMapping(void *dst, uintptr_t src_phys, size_t size) const { const void * const src = this->GetPointerTo(src_phys, size); if (src == nullptr) { return false; } std::memcpy(dst, src, size); return true; } } bool UserPageMapper::Map() { return this->MapImpl<MapSmcUserPage>(); } bool AtmosphereIramPageMapper::Map() { return this->MapImpl<MapAtmosphereIramPage>(); } bool AtmosphereUserPageMapper::Map() { return this->MapImpl<MapAtmosphereUserPage>(); } AtmosphereIramPageMapper::~AtmosphereIramPageMapper() { this->UnmapImpl<UnmapAtmosphereIramPage>(); } AtmosphereUserPageMapper::~AtmosphereUserPageMapper() { this->UnmapImpl<UnmapAtmosphereUserPage>(); } }
2,495
C++
.cpp
65
30.353846
100
0.623188
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,335
secmon_cache.cpp
Atmosphere-NX_Atmosphere/exosphere/program/source/secmon_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 <exosphere.hpp> #include "secmon_cache.hpp" namespace ams::secmon { #include "secmon_cache_impl.inc" }
753
C++
.cpp
20
35.65
76
0.75513
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,336
secmon_mariko_fatal_error.cpp
Atmosphere-NX_Atmosphere/exosphere/program/source/secmon_mariko_fatal_error.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 <exosphere.hpp> #include "secmon_cpu_context.hpp" #include "secmon_map.hpp" #include "secmon_page_mapper.hpp" #include "secmon_mariko_fatal_error.hpp" #include "smc/secmon_smc_power_management.hpp" namespace ams::secmon { namespace { constinit u8 g_fatal_error_mask = 0; } void HandleMarikoFatalErrorInterrupt() { /* This interrupt handler doesn't return, so mark that we're at end of interrupt. */ gic::SetEndOfInterrupt(MarikoFatalErrorInterruptId); /* Get the current core id. */ const auto core_id = hw::GetCurrentCoreId(); /* Set that we received the fatal on the current core. */ g_fatal_error_mask |= (1u << core_id); hw::FlushDataCache(std::addressof(g_fatal_error_mask), sizeof(g_fatal_error_mask)); hw::DataSynchronizationBarrier(); /* If not all cores have received the fatal, we need to trigger the interrupt on other cores. */ if (g_fatal_error_mask != (1u << NumCores) - 1) { /* Configure and send the interrupt to the next core. */ const auto next_core = __builtin_ctz(~g_fatal_error_mask); gic::SetSpiTargetCpu(MarikoFatalErrorInterruptId, (1u << next_core)); gic::SetPending(MarikoFatalErrorInterruptId); } /* If current core is not 3, kill ourselves. */ if (core_id != NumCores - 1) { smc::PowerOffCpu(); } else { /* Wait for all cores to kill themselves. */ while (g_fatal_error_mask != (1u << NumCores) - 1) { util::WaitMicroSeconds(100); } } /* Copy the fatal error context to mariko tzram. */ { /* Map the iram page. */ constexpr uintptr_t FatalErrorPhysicalAddress = MemoryRegionPhysicalIramFatalErrorContext.GetAddress(); AtmosphereIramPageMapper mapper(FatalErrorPhysicalAddress); if (mapper.Map()) { /* Copy the fatal error context. */ void *dst = MemoryRegionVirtualTzramMarikoProgramFatalErrorContext.GetPointer<void>(); const void *src = mapper.GetPointerTo(FatalErrorPhysicalAddress, sizeof(ams::impl::FatalErrorContext)); std::memcpy(dst, src, sizeof(ams::impl::FatalErrorContext)); } } /* Map Dram for the mariko program. */ MapDramForMarikoProgram(); AMS_SECMON_LOG("%s\n", "Jumping to Mariko Fatal."); AMS_LOG_FLUSH(); /* Jump to the mariko fatal program. */ reinterpret_cast<void (*)()>(secmon::MemoryRegionVirtualTzramMarikoProgram.GetAddress())(); /* The mariko fatal program never returns. */ __builtin_unreachable(); AMS_INFINITE_LOOP(); } }
3,423
C++
.cpp
73
38.876712
119
0.64847
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,337
secmon_map.cpp
Atmosphere-NX_Atmosphere/exosphere/program/source/secmon_map.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 <exosphere.hpp> #include "secmon_cache.hpp" #include "secmon_setup.hpp" #include "secmon_spinlock.hpp" #include "secmon_map.hpp" #include "smc/secmon_smc_info.hpp" namespace ams::secmon { namespace { constexpr inline const uintptr_t BootCodeAddress = MemoryRegionVirtualTzramBootCode.GetAddress(); constexpr inline const size_t BootCodeSize = MemoryRegionVirtualTzramBootCode.GetSize(); constinit uintptr_t g_smc_user_page_physical_address = 0; constinit uintptr_t g_ams_iram_page_physical_address = 0; constinit uintptr_t g_ams_user_page_physical_address = 0; constinit SpinLockType g_ams_iram_page_spin_lock = {}; constinit SpinLockType g_ams_user_page_spin_lock = {}; using namespace ams::mmu; constexpr inline PageTableMappingAttribute MappingAttributesEl3NonSecureRwData = AddMappingAttributeIndex(PageTableMappingAttributes_El3NonSecureRwData, MemoryAttributeIndexNormal); constexpr inline PageTableMappingAttribute MappingAttributesEl3NonSecureDevice = AddMappingAttributeIndex(PageTableMappingAttributes_El3NonSecureRwData, MemoryAttributeIndexDevice); constexpr void UnmapBootCodeImpl(u64 *l1, u64 *l2, u64 *l3, uintptr_t boot_code, size_t boot_code_size) { /* Unmap the L3 entries corresponding to the boot code. */ AMS_UNUSED(l1, l2); InvalidateL3Entries(l3, boot_code, boot_code_size); } constexpr void UnmapTzramImpl(u64 *l1, u64 *l2, u64 *l3) { /* Unmap the L3 entries corresponding to tzram. */ InvalidateL3Entries(l3, MemoryRegionPhysicalTzram.GetAddress(), MemoryRegionPhysicalTzram.GetSize()); /* Unmap the L2 entries corresponding to those L3 entries. */ InvalidateL2Entries(l2, MemoryRegionPhysicalTzramL2.GetAddress(), MemoryRegionPhysicalTzramL2.GetSize()); /* Unmap the L1 entry corresponding to to those L2 entries. */ InvalidateL1Entries(l1, MemoryRegionPhysical.GetAddress(), MemoryRegionPhysical.GetSize()); } constexpr void MapSmcUserPageImpl(u64 *l3, uintptr_t address) { /* Set the L3 entry. */ SetL3BlockEntry(l3, MemoryRegionVirtualSmcUserPage.GetAddress(), address, MemoryRegionVirtualSmcUserPage.GetSize(), MappingAttributesEl3NonSecureRwData); } constexpr void UnmapSmcUserPageImpl(u64 *l3) { /* Unmap the L3 entry. */ InvalidateL3Entries(l3, MemoryRegionVirtualSmcUserPage.GetAddress(), MemoryRegionVirtualSmcUserPage.GetSize()); } constexpr void MapAtmosphereIramPageImpl(u64 *l3, uintptr_t address) { /* Set the L3 entry. */ SetL3BlockEntry(l3, MemoryRegionVirtualAtmosphereIramPage.GetAddress(), address, MemoryRegionVirtualAtmosphereIramPage.GetSize(), MappingAttributesEl3NonSecureDevice); } constexpr void UnmapAtmosphereIramPageImpl(u64 *l3) { /* Unmap the L3 entry. */ InvalidateL3Entries(l3, MemoryRegionVirtualAtmosphereIramPage.GetAddress(), MemoryRegionVirtualAtmosphereIramPage.GetSize()); } constexpr void MapAtmosphereUserPageImpl(u64 *l3, uintptr_t address) { /* Set the L3 entry. */ SetL3BlockEntry(l3, MemoryRegionVirtualAtmosphereUserPage.GetAddress(), address, MemoryRegionVirtualAtmosphereUserPage.GetSize(), MappingAttributesEl3NonSecureRwData); } constexpr void UnmapAtmosphereUserPageImpl(u64 *l3) { /* Unmap the L3 entry. */ InvalidateL3Entries(l3, MemoryRegionVirtualAtmosphereUserPage.GetAddress(), MemoryRegionVirtualAtmosphereUserPage.GetSize()); } constexpr void MapDramForMarikoProgramImpl(u64 *l1, u64 *l2, u64 *l3) { /* Map the L1 entry corresponding to the mariko program dram entry. */ AMS_UNUSED(l2, l3); SetL1BlockEntry(l1, MemoryRegionDramForMarikoProgram.GetAddress(), MemoryRegionDramForMarikoProgram.GetAddress(), MemoryRegionDramForMarikoProgram.GetSize(), MappingAttributesEl3NonSecureRwData); } void ClearLow(uintptr_t address, size_t size) { /* Clear the low part. */ util::ClearMemory(reinterpret_cast<void *>(address), size / 2); } void ClearHigh(uintptr_t address, size_t size) { /* Clear the high part. */ util::ClearMemory(reinterpret_cast<void *>(address + size / 2), size / 2); } } void ClearBootCodeHigh() { ClearHigh(BootCodeAddress, BootCodeSize); } void UnmapBootCode() { /* Get the tables. */ u64 * const l1 = MemoryRegionVirtualTzramL1PageTable.GetPointer<u64>(); u64 * const l2_l3 = MemoryRegionVirtualTzramL2L3PageTable.GetPointer<u64>(); /* Clear the low boot code region; high was already cleared by a previous call. */ ClearLow(BootCodeAddress, BootCodeSize); /* Unmap. */ UnmapBootCodeImpl(l1, l2_l3, l2_l3, BootCodeAddress, BootCodeSize); /* Ensure the mappings are consistent. */ secmon::EnsureMappingConsistency(); } size_t GetPhysicalMemorySize() { switch (smc::GetPhysicalMemorySize()) { case pkg1::MemorySize_4GB: return 4_GB; case pkg1::MemorySize_6GB: return 6_GB; case pkg1::MemorySize_8GB: return 8_GB; AMS_UNREACHABLE_DEFAULT_CASE(); } } bool IsPhysicalMemoryAddress(uintptr_t address) { return (address - MemoryRegionDram.GetAddress()) < GetPhysicalMemorySize(); } void UnmapTzram() { /* Get the tables. */ u64 * const l1 = MemoryRegionVirtualTzramL1PageTable.GetPointer<u64>(); u64 * const l2_l3 = MemoryRegionVirtualTzramL2L3PageTable.GetPointer<u64>(); /* Unmap. */ UnmapTzramImpl(l1, l2_l3, l2_l3); /* Ensure the mappings are consistent. */ secmon::EnsureMappingConsistency(); } uintptr_t MapSmcUserPage(uintptr_t address) { if (g_smc_user_page_physical_address == 0) { if (!IsPhysicalMemoryAddress(address)) { return 0; } if (!util::IsAligned(address, 4_KB)) { return 0; } g_smc_user_page_physical_address = address; u64 * const l2_l3 = MemoryRegionVirtualTzramL2L3PageTable.GetPointer<u64>(); MapSmcUserPageImpl(l2_l3, address); /* Ensure the mappings are consistent. */ secmon::EnsureMappingConsistency(MemoryRegionVirtualSmcUserPage.GetAddress()); } else { AMS_ABORT_UNLESS(address == g_smc_user_page_physical_address); } return MemoryRegionVirtualSmcUserPage.GetAddress(); } void UnmapSmcUserPage() { if (g_smc_user_page_physical_address == 0) { return; } /* Ensure that the page is no longer in cache. */ hw::FlushDataCache(MemoryRegionVirtualSmcUserPage.GetPointer<void>(), MemoryRegionVirtualSmcUserPage.GetSize()); hw::DataSynchronizationBarrierInnerShareable(); u64 * const l2_l3 = MemoryRegionVirtualTzramL2L3PageTable.GetPointer<u64>(); UnmapSmcUserPageImpl(l2_l3); /* Ensure the mappings are consistent. */ secmon::EnsureMappingConsistency(MemoryRegionVirtualSmcUserPage.GetAddress()); g_smc_user_page_physical_address = 0; } uintptr_t MapAtmosphereIramPage(uintptr_t address) { /* Acquire the ams iram spinlock. */ AcquireSpinLock(g_ams_iram_page_spin_lock); auto lock_guard = SCOPE_GUARD { ReleaseSpinLock(g_ams_iram_page_spin_lock); }; /* Validate that the page is an IRAM page. */ if (!MemoryRegionPhysicalIram.Contains(address, 1)) { return 0; } /* Validate that the page isn't a secure monitor debug page. */ if (MemoryRegionPhysicalIramSecureMonitorDebug.Contains(address, 1)) { return 0; } /* Validate that the page is aligned. */ if (!util::IsAligned(address, 4_KB)) { return 0; } /* Map the page. */ g_ams_iram_page_physical_address = address; u64 * const l2_l3 = MemoryRegionVirtualTzramL2L3PageTable.GetPointer<u64>(); MapAtmosphereIramPageImpl(l2_l3, address); /* Ensure the mappings are consistent. */ secmon::EnsureMappingConsistency(MemoryRegionVirtualAtmosphereIramPage.GetAddress()); /* Hold the lock. */ lock_guard.Cancel(); return MemoryRegionVirtualAtmosphereIramPage.GetAddress(); } void UnmapAtmosphereIramPage() { /* Can't unmap if nothing's unmapped. */ if (g_ams_iram_page_physical_address == 0) { return; } /* Ensure that the page is no longer in cache. */ hw::FlushDataCache(MemoryRegionVirtualAtmosphereIramPage.GetPointer<void>(), MemoryRegionVirtualAtmosphereIramPage.GetSize()); hw::DataSynchronizationBarrierInnerShareable(); /* Unmap the page. */ u64 * const l2_l3 = MemoryRegionVirtualTzramL2L3PageTable.GetPointer<u64>(); UnmapAtmosphereIramPageImpl(l2_l3); /* Ensure the mappings are consistent. */ secmon::EnsureMappingConsistency(MemoryRegionVirtualAtmosphereIramPage.GetAddress()); /* Release the page. */ g_ams_iram_page_physical_address = 0; ReleaseSpinLock(g_ams_iram_page_spin_lock); } uintptr_t MapAtmosphereUserPage(uintptr_t address) { /* Acquire the ams user spinlock. */ AcquireSpinLock(g_ams_user_page_spin_lock); auto lock_guard = SCOPE_GUARD { ReleaseSpinLock(g_ams_user_page_spin_lock); }; /* Validate that the page is a dram page. */ if (!IsPhysicalMemoryAddress(address)) { return 0; } /* Validate that the page is aligned. */ if (!util::IsAligned(address, 4_KB)) { return 0; } /* Map the page. */ g_ams_user_page_physical_address = address; u64 * const l2_l3 = MemoryRegionVirtualTzramL2L3PageTable.GetPointer<u64>(); MapAtmosphereUserPageImpl(l2_l3, address); /* Ensure the mappings are consistent. */ secmon::EnsureMappingConsistency(MemoryRegionVirtualAtmosphereUserPage.GetAddress()); /* Hold the lock. */ lock_guard.Cancel(); return MemoryRegionVirtualAtmosphereUserPage.GetAddress(); } void UnmapAtmosphereUserPage() { /* Can't unmap if nothing's unmapped. */ if (g_ams_user_page_physical_address == 0) { return; } /* Ensure that the page is no longer in cache. */ hw::FlushDataCache(MemoryRegionVirtualAtmosphereUserPage.GetPointer<void>(), MemoryRegionVirtualAtmosphereUserPage.GetSize()); hw::DataSynchronizationBarrierInnerShareable(); /* Unmap the page. */ u64 * const l2_l3 = MemoryRegionVirtualTzramL2L3PageTable.GetPointer<u64>(); UnmapAtmosphereUserPageImpl(l2_l3); /* Ensure the mappings are consistent. */ secmon::EnsureMappingConsistency(MemoryRegionVirtualAtmosphereUserPage.GetAddress()); /* Release the page. */ g_ams_user_page_physical_address = 0; ReleaseSpinLock(g_ams_user_page_spin_lock); } void MapDramForMarikoProgram() { /* Get the tables. */ u64 * const l1 = MemoryRegionVirtualTzramL1PageTable.GetPointer<u64>(); u64 * const l2_l3 = MemoryRegionVirtualTzramL2L3PageTable.GetPointer<u64>(); /* Map. */ MapDramForMarikoProgramImpl(l1, l2_l3, l2_l3); /* Ensure the mappings are consistent. */ secmon::EnsureMappingConsistency(); } }
12,451
C++
.cpp
241
42.568465
207
0.674911
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,338
secmon_key_storage.cpp
Atmosphere-NX_Atmosphere/exosphere/program/source/secmon_key_storage.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 <exosphere.hpp> #include "secmon_key_storage.hpp" namespace ams::secmon { namespace { constexpr const u8 RsaPublicKey[] = { 0x00, 0x01, 0x00, 0x01 }; constinit u8 g_rsa_moduli[ImportRsaKey_Count][se::RsaSize] = {}; constinit bool g_rsa_modulus_committed[ImportRsaKey_Count] = {}; ALWAYS_INLINE u8 *GetRsaKeyModulus(ImportRsaKey which) { return g_rsa_moduli[which]; } ALWAYS_INLINE u8 *GetRsaKeyPrivateExponent(ImportRsaKey which) { return ::ams::secmon::impl::GetRsaPrivateExponentStorage(static_cast<int>(which)); } ALWAYS_INLINE bool IsRsaKeyProvisional(ImportRsaKey which) { return g_rsa_modulus_committed[which] == false; } void ClearRsaKeyModulus(ImportRsaKey which) { g_rsa_modulus_committed[which] = false; std::memset(g_rsa_moduli[which], 0, se::RsaSize); } ALWAYS_INLINE u8 *GetMasterKeyStorage(int index) { return ::ams::secmon::impl::GetMasterKeyStorage(index); } ALWAYS_INLINE u8 *GetDeviceMasterKeyStorage(int index) { return ::ams::secmon::impl::GetDeviceMasterKeyStorage(index); } } void ImportRsaKeyExponent(ImportRsaKey which, const void *src, size_t size) { /* If we import an exponent, the modulus is not committed. */ ClearRsaKeyModulus(which); /* Copy the exponent. */ std::memcpy(GetRsaKeyPrivateExponent(which), src, size); } void ImportRsaKeyModulusProvisionally(ImportRsaKey which, const void *src, size_t size) { std::memcpy(GetRsaKeyModulus(which), src, std::min(static_cast<int>(size), se::RsaSize)); } void CommitRsaKeyModulus(ImportRsaKey which) { g_rsa_modulus_committed[which] = true; } bool LoadRsaKey(int slot, ImportRsaKey which) { /* If the key is still provisional, we can't load it. */ if (IsRsaKeyProvisional(which)) { return false; } se::SetRsaKey(slot, GetRsaKeyModulus(which), se::RsaSize, GetRsaKeyPrivateExponent(which), se::RsaSize); return true; } void LoadProvisionalRsaKey(int slot, ImportRsaKey which) { se::SetRsaKey(slot, GetRsaKeyModulus(which), se::RsaSize, GetRsaKeyPrivateExponent(which), se::RsaSize); } void LoadProvisionalRsaPublicKey(int slot, ImportRsaKey which) { se::SetRsaKey(slot, GetRsaKeyModulus(which), se::RsaSize, RsaPublicKey, sizeof(RsaPublicKey)); } void SetMasterKey(int generation, const void *src, size_t size) { const int index = generation - pkg1::KeyGeneration_Min; se::EncryptAes128(GetMasterKeyStorage(index), se::AesBlockSize, pkg1::AesKeySlot_RandomForKeyStorageWrap, src, size); } void LoadMasterKey(int slot, int generation) { const int index = std::max(0, generation - pkg1::KeyGeneration_Min); se::SetEncryptedAesKey128(slot, pkg1::AesKeySlot_RandomForKeyStorageWrap, GetMasterKeyStorage(index), se::AesBlockSize); } void SetDeviceMasterKey(int generation, const void *src, size_t size) { const int index = generation - pkg1::KeyGeneration_4_0_0; se::EncryptAes128(GetDeviceMasterKeyStorage(index), se::AesBlockSize, pkg1::AesKeySlot_RandomForKeyStorageWrap, src, size); } void LoadDeviceMasterKey(int slot, int generation) { const int index = std::max(0, generation - pkg1::KeyGeneration_4_0_0); se::SetEncryptedAesKey128(slot, pkg1::AesKeySlot_RandomForKeyStorageWrap, GetDeviceMasterKeyStorage(index), se::AesBlockSize); } }
4,253
C++
.cpp
85
43.047059
134
0.696743
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,339
secmon_smc_register_access.cpp
Atmosphere-NX_Atmosphere/exosphere/program/source/smc/secmon_smc_register_access.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 <exosphere.hpp> #include "../secmon_error.hpp" #include "secmon_smc_register_access.hpp" namespace ams::secmon::smc { namespace { template<size_t N> constexpr void SetRegisterTableAllowed(std::array<u8, N> &arr, uintptr_t reg) { /* All registers should be four byte aligned. */ AMS_ASSUME(reg % sizeof(u32) == 0); /* Reduce the register to an index. */ reg /= sizeof(u32); /* Get the index and mask. */ const auto index = reg / BITSIZEOF(u8); const auto mask = (1u << (reg % BITSIZEOF(u8))); /* Check that the permission bit isn't already set. */ AMS_ASSUME((arr[index] & mask) == 0); /* Set the permission bit. */ arr[index] |= mask; /* Ensure that indices are set in sorted order. */ for (auto i = (reg % BITSIZEOF(u8)) + 1; i < 8; ++i) { AMS_ASSUME((arr[index] & (1u << i)) == 0); } for (auto i = index + 1; i < arr.size(); ++i) { AMS_ASSUME(arr[i] == 0); } } template<size_t N> consteval std::pair<size_t, size_t> GetReducedAccessTableInfo(const std::array<u8, N> &arr) { for (int last = arr.size() - 1; last >= 0; --last) { if (arr[last] != 0) { const int end = last + 1; for (int start = 0; start < end; ++start) { if (arr[start] != 0) { return std::make_pair(static_cast<size_t>(start), static_cast<size_t>(end)); } } return std::make_pair(static_cast<size_t>(0), static_cast<size_t>(end)); } } /* All empty perm table is disallowed. */ AMS_ASSUME(false); } template<u32 _Address, auto RawTable> struct AccessTable { static constexpr inline auto ReducedAccessTableInfo = GetReducedAccessTableInfo(RawTable); static constexpr inline size_t ReducedAccessTableSize = ReducedAccessTableInfo.second - ReducedAccessTableInfo.first; static constexpr inline auto ReducedAccessTable = []() -> std::array<u8, ReducedAccessTableSize> { std::array<u8, ReducedAccessTableSize> reduced = {}; for (size_t i = ReducedAccessTableInfo.first; i < ReducedAccessTableInfo.second; ++i) { reduced[i - ReducedAccessTableInfo.first] = RawTable[i]; } return reduced; }(); static constexpr u32 Address = _Address + (ReducedAccessTableInfo.first * sizeof(u32) * BITSIZEOF(u8)); static constexpr u32 Size = static_cast<u32>(ReducedAccessTableSize * sizeof(u32) * BITSIZEOF(u8)); static_assert(Size <= 0x1000); }; struct AccessTableEntry { const u8 * const table; uintptr_t virtual_address; u32 address; u32 size; }; /* Include the access tables. */ #include "secmon_define_pmc_access_table.inc" #include "secmon_define_mc_access_table.inc" #include "secmon_define_mc01_access_table.inc" constexpr const AccessTableEntry AccessTables[] = { { PmcAccessTable::ReducedAccessTable.data(), MemoryRegionVirtualDevicePmc.GetAddress(), PmcAccessTable::Address, PmcAccessTable::Size, }, { McAccessTable::ReducedAccessTable.data(), MemoryRegionVirtualDeviceMemoryController.GetAddress(), McAccessTable::Address, McAccessTable::Size, }, { Mc01AccessTable::ReducedAccessTable.data(), MemoryRegionVirtualDeviceMemoryController0.GetAddress(), Mc01AccessTable::Address + MemoryRegionPhysicalDeviceMemoryController0.GetAddress(), Mc01AccessTable::Size, }, { Mc01AccessTable::ReducedAccessTable.data(), MemoryRegionVirtualDeviceMemoryController1.GetAddress(), Mc01AccessTable::Address + MemoryRegionPhysicalDeviceMemoryController1.GetAddress(), Mc01AccessTable::Size, }, }; constexpr bool IsAccessAllowed(const AccessTableEntry &entry, uintptr_t address) { /* Check if the address is within range. */ if (!(entry.address <= address && address < entry.address + entry.size)) { return false; } /* Get the offset. */ const auto offset = address - entry.address; /* Convert it to an index. */ const auto reg_index = offset / sizeof(u32); /* Get the bit fields. */ const auto index = reg_index / BITSIZEOF(u8); const auto mask = (1u << (reg_index % BITSIZEOF(u8))); /* Validate that we're not going out of bounds. */ if (index >= entry.size / sizeof(u32)) { return false; } return (entry.table[index] & mask) != 0; } constexpr const AccessTableEntry *GetAccessTableEntry(uintptr_t address) { for (const auto &entry : AccessTables) { if (IsAccessAllowed(entry, address)) { return std::addressof(entry); } } return nullptr; } } SmcResult SmcReadWriteRegister(SmcArguments &args) { /* Get the arguments. */ const uintptr_t address = args.r[1]; const u32 mask = args.r[2]; const u32 value = args.r[3]; /* Validate that the address is aligned. */ SMC_R_UNLESS(util::IsAligned(address, alignof(u32)), InvalidArgument); /* Find the access table. */ const AccessTableEntry * const entry = GetAccessTableEntry(address); /* Translate our entry into an address to access. */ uintptr_t virtual_address = 0; if (entry != nullptr) { /* Get the address to read or write. */ virtual_address = entry->virtual_address + (address - entry->address); } else { /* For no clearly discernable reason, SmcReadWriteRegister returns success despite not doing the read/write */ /* when accessing the SMMU controls for the BPMP and for APB-DMA. */ /* This is "probably" to fuck with hackers who got access to the SMC and are trying to get control of the */ /* BPMP to exploit jamais vu, deja vu, or other related DMA/wake-from-sleep vulnerabilities. */ constexpr uintptr_t MC = MemoryRegionPhysicalDeviceMemoryController.GetAddress(); SMC_R_UNLESS((address == (MC + MC_SMMU_AVPC_ASID) || address == (MC + MC_SMMU_PPCS1_ASID)), InvalidArgument); /* For backwards compatibility, we'll allow access to these devices on 1.0.0. */ if (GetTargetFirmware() < TargetFirmware_2_0_0) { virtual_address = MemoryRegionVirtualDeviceMemoryController.GetAddress() + (address - MC); } } /* Perform the read or write, if we should. */ if (virtual_address != 0) { u32 out = 0; if (mask != ~static_cast<u32>(0)) { out = reg::Read(virtual_address); } if (mask != static_cast<u32>(0)) { reg::Write(virtual_address, (out & ~mask) | (value & mask)); } args.r[1] = out; } return SmcResult::Success; } }
8,244
C++
.cpp
155
41.625806
225
0.580497
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,340
secmon_smc_result.cpp
Atmosphere-NX_Atmosphere/exosphere/program/source/smc/secmon_smc_result.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 <exosphere.hpp> #include "../secmon_error.hpp" #include "../secmon_page_mapper.hpp" #include "secmon_smc_result.hpp" namespace ams::secmon::smc { namespace { constinit u64 g_async_key = InvalidAsyncKey; constinit GetResultHandler g_async_handler = nullptr; u64 GenerateRandomU64() { /* NOTE: This is one of the only places where Nintendo does not do data flushing. */ /* to ensure coherency when doing random byte generation. */ /* It is not clear why it is necessary elsewhere but not here. */ /* TODO: Figure out why. */ u64 v; se::GenerateRandomBytes(std::addressof(v), sizeof(v)); return v; } } u64 BeginAsyncOperation(GetResultHandler handler) { /* Only allow one async operation at a time. */ if (g_async_key != InvalidAsyncKey) { return InvalidAsyncKey; } /* Generate a random async key. */ g_async_key = GenerateRandomU64(); g_async_handler = handler; return g_async_key; } void CancelAsyncOperation(u64 async_key) { if (async_key == g_async_key) { g_async_key = InvalidAsyncKey; } } void EndAsyncOperation() { gic::SetPending(SecurityEngineUserInterruptId); } SmcResult SmcGetResult(SmcArguments &args) { /* Decode arguments. */ const u64 async_key = args.r[1]; /* Validate arguments. */ SMC_R_UNLESS(g_async_key != InvalidAsyncKey, NoAsyncOperation); SMC_R_UNLESS(g_async_key == async_key, InvalidAsyncOperation); /* Call the handler. */ args.r[1] = static_cast<u64>(g_async_handler(nullptr, 0)); g_async_key = InvalidAsyncKey; return SmcResult::Success; } SmcResult SmcGetResultData(SmcArguments &args) { /* Decode arguments. */ const u64 async_key = args.r[1]; const uintptr_t user_phys_addr = args.r[2]; const size_t user_size = args.r[3]; /* Allocate a work buffer on the stack. */ alignas(8) u8 work_buffer[1_KB]; /* Validate arguments. */ SMC_R_UNLESS(g_async_key != InvalidAsyncKey, NoAsyncOperation); SMC_R_UNLESS(g_async_key == async_key, InvalidAsyncOperation); SMC_R_UNLESS(user_size <= sizeof(work_buffer), InvalidArgument); /* Call the handler. */ args.r[1] = static_cast<u64>(g_async_handler(work_buffer, user_size)); g_async_key = InvalidAsyncKey; /* Map the user buffer. */ { UserPageMapper mapper(user_phys_addr); SMC_R_UNLESS(mapper.Map(), InvalidArgument); SMC_R_UNLESS(mapper.CopyToUser(user_phys_addr, work_buffer, user_size), InvalidArgument); } return SmcResult::Success; } }
3,615
C++
.cpp
85
35.094118
101
0.616985
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,341
secmon_random_cache.cpp
Atmosphere-NX_Atmosphere/exosphere/program/source/smc/secmon_random_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 <exosphere.hpp> #include "secmon_smc_common.hpp" #include "secmon_random_cache.hpp" namespace ams::secmon::smc { namespace { constinit int g_random_offset_low = 0; constinit int g_random_offset_high = 0; void FillRandomCache(int offset, int size) { /* Get the cache. */ u8 * const random_cache_loc = GetRandomBytesCache() + offset; /* Flush the region we're about to fill to ensure consistency with the SE. */ hw::FlushDataCache(random_cache_loc, size); hw::DataSynchronizationBarrierInnerShareable(); /* Generate random bytes. */ se::GenerateRandomBytes(random_cache_loc, size); hw::DataSynchronizationBarrierInnerShareable(); /* Flush to ensure the CPU sees consistent data for the region. */ hw::FlushDataCache(random_cache_loc, size); hw::DataSynchronizationBarrierInnerShareable(); } } void FillRandomCache() { /* Fill the cache. */ FillRandomCache(0, GetRandomBytesCacheSize()); /* Set the extents. */ g_random_offset_low = 0; g_random_offset_high = GetRandomBytesCacheSize() - 1; } void RefillRandomCache() { /* Check that we need to do any refilling. */ if (const int used_start = (g_random_offset_high + 1) % GetRandomBytesCacheSize(); used_start != g_random_offset_low) { if (used_start < g_random_offset_low) { /* The region we need to fill is after used_start but before g_random_offset_low. */ const auto size = g_random_offset_low - used_start; FillRandomCache(used_start, size); g_random_offset_high += size; } else { /* We need to fill the space from high to the end and from low to start. */ const int high_size = GetRandomBytesCacheSize() - used_start; if (high_size > 0) { FillRandomCache(used_start, high_size); g_random_offset_high += high_size; } const int low_size = g_random_offset_low; if (low_size > 0) { FillRandomCache(0, low_size); g_random_offset_high += low_size; } } g_random_offset_high %= GetRandomBytesCacheSize(); } } void GetRandomFromCache(void *dst, size_t size) { /* Copy out the requested size. */ std::memcpy(dst, GetRandomBytesCache() + g_random_offset_low, size); /* Advance. */ g_random_offset_low += size; /* Ensure that at all times g_random_offset_low is not within 0x38 bytes of the end of the pool. */ if (g_random_offset_low + MaxRandomBytes >= GetRandomBytesCacheSize()) { g_random_offset_low = 0; } } }
3,553
C++
.cpp
78
36.038462
127
0.61267
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,342
secmon_smc_device_unique_data.cpp
Atmosphere-NX_Atmosphere/exosphere/program/source/smc/secmon_smc_device_unique_data.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 <exosphere.hpp> #include "../secmon_error.hpp" #include "secmon_smc_device_unique_data.hpp" namespace ams::secmon::smc { namespace { void GenerateIv(void *dst, size_t dst_size) { /* Flush the region we're about to fill to ensure consistency with the SE. */ hw::FlushDataCache(dst, dst_size); hw::DataSynchronizationBarrierInnerShareable(); /* Generate random bytes. */ se::GenerateRandomBytes(dst, dst_size); hw::DataSynchronizationBarrierInnerShareable(); /* Flush to ensure the CPU sees consistent data for the region. */ hw::FlushDataCache(dst, dst_size); hw::DataSynchronizationBarrierInnerShareable(); } void PrepareDeviceUniqueDataKey(const void *seal_key_source, size_t seal_key_source_size, const void *access_key, size_t access_key_size, const void *key_source, size_t key_source_size) { /* Derive the seal key. */ se::SetEncryptedAesKey128(pkg1::AesKeySlot_Smc, pkg1::AesKeySlot_RandomForUserWrap, seal_key_source, seal_key_source_size); /* Derive the device unique data kek. */ se::SetEncryptedAesKey128(pkg1::AesKeySlot_Smc, pkg1::AesKeySlot_Smc, access_key, access_key_size); /* Derive the actual device unique data key. */ se::SetEncryptedAesKey128(pkg1::AesKeySlot_Smc, pkg1::AesKeySlot_Smc, key_source, key_source_size); } void ComputeAes128Ctr(void *dst, size_t dst_size, int slot, const void *src, size_t src_size, const void *iv, size_t iv_size) { /* Ensure that the SE sees consistent data. */ hw::FlushDataCache(src, src_size); hw::FlushDataCache(dst, dst_size); hw::DataSynchronizationBarrierInnerShareable(); /* Use the security engine to transform the data. */ se::ComputeAes128Ctr(dst, dst_size, slot, src, src_size, iv, iv_size); hw::DataSynchronizationBarrierInnerShareable(); /* Ensure the CPU sees consistent data. */ hw::FlushDataCache(dst, dst_size); hw::DataSynchronizationBarrierInnerShareable(); } void ComputeGmac(void *dst, size_t dst_size, const void *data, size_t data_size, const void *iv, size_t iv_size) { /* Declare keyslot (as encryptor will need to take it by pointer/reference). */ constexpr int Slot = pkg1::AesKeySlot_Smc; /* Calculate the mac. */ crypto::Aes128GcmEncryptor gcm; gcm.Initialize(std::addressof(Slot), sizeof(Slot), iv, iv_size); gcm.UpdateAad(data, data_size); gcm.GetMac(dst, dst_size); } constexpr u64 GetDeviceIdLow(u64 device_id) { /* Mask out the top byte. */ constexpr u64 ByteMask = (static_cast<u64>(1) << BITSIZEOF(u8)) - 1; constexpr u64 LowMask = ~(ByteMask << (BITSIZEOF(u64) - BITSIZEOF(u8))); return device_id & LowMask; } constexpr u8 GetDeviceIdHigh(u64 device_id) { /* Get the top byte. */ return static_cast<u8>(device_id >> (BITSIZEOF(u64) - BITSIZEOF(u8))); } constexpr u64 EncodeDeviceId(u8 device_id_high, u64 device_id_low) { return (static_cast<u64>(device_id_high) << (BITSIZEOF(u64) - BITSIZEOF(u8))) | device_id_low; } } bool DecryptDeviceUniqueData(void *dst, size_t dst_size, u8 *out_device_id_high, const void *seal_key_source, size_t seal_key_source_size, const void *access_key, size_t access_key_size, const void *key_source, size_t key_source_size, const void *src, size_t src_size, bool enforce_device_unique) { /* Determine how much decrypted data there will be. */ const size_t enc_size = src_size - (enforce_device_unique ? DeviceUniqueDataOuterMetaSize : DeviceUniqueDataIvSize); const size_t dec_size = enc_size - DeviceUniqueDataInnerMetaSize; /* Ensure that our sizes are allowed. */ AMS_ABORT_UNLESS(src_size > (enforce_device_unique ? DeviceUniqueDataTotalMetaSize : DeviceUniqueDataIvSize)); AMS_ABORT_UNLESS(dst_size >= enc_size); /* Determine the extents of the data. */ const u8 * const iv = static_cast<const u8 *>(src); const u8 * const enc = iv + DeviceUniqueDataIvSize; const u8 * const mac = enc + enc_size; /* Decrypt the data. */ { /* Declare temporaries. */ u8 temp_iv[DeviceUniqueDataIvSize]; u8 calc_mac[DeviceUniqueDataMacSize]; ON_SCOPE_EXIT { crypto::ClearMemory(temp_iv, sizeof(temp_iv)); crypto::ClearMemory(calc_mac, sizeof(calc_mac)); }; /* Prepare the key used to decrypt the data. */ PrepareDeviceUniqueDataKey(seal_key_source, seal_key_source_size, access_key, access_key_size, key_source, key_source_size); /* Copy the iv to stack. */ std::memcpy(temp_iv, iv, sizeof(temp_iv)); /* Decrypt the data. */ ComputeAes128Ctr(dst, dst_size, pkg1::AesKeySlot_Smc, enc, enc_size, temp_iv, DeviceUniqueDataIvSize); /* If we're not enforcing device unique, there's no mac/device id. */ if (!enforce_device_unique) { return true; } /* Compute the gmac. */ ComputeGmac(calc_mac, DeviceUniqueDataMacSize, dst, enc_size, temp_iv, DeviceUniqueDataIvSize); /* Validate the gmac. */ if (!crypto::IsSameBytes(mac, calc_mac, sizeof(calc_mac))) { return false; } } /* Validate device id, output device id if needed. */ { /* Locate the device id in the decryption output. */ const u8 * const padding = static_cast<const u8 *>(dst) + dec_size; const u8 * const device_id = padding + DeviceUniqueDataPaddingSize; /* Load the big endian device id. */ const u64 device_id_val = util::LoadBigEndian(static_cast<const u64 *>(static_cast<const void *>(device_id))); /* Validate that the device id low matches the value in fuses. */ if (GetDeviceIdLow(device_id_val) != fuse::GetDeviceId()) { return false; } /* Set the output device id high, if needed. */ if (out_device_id_high != nullptr) { *out_device_id_high = GetDeviceIdHigh(device_id_val); } } return true; } void EncryptDeviceUniqueData(void *dst, size_t dst_size, const void *seal_key_source, size_t seal_key_source_size, const void *access_key, size_t access_key_size, const void *key_source, size_t key_source_size, const void *src, size_t src_size, u8 device_id_high) { /* Determine metadata locations. */ u8 * const dst_iv = static_cast<u8 *>(dst); u8 * const dst_data = dst_iv + DeviceUniqueDataIvSize; u8 * const dst_pad = dst_data + src_size; u8 * const dst_did = dst_pad + DeviceUniqueDataPaddingSize; u8 * const dst_mac = dst_did + DeviceUniqueDataDeviceIdSize; /* Verify that our sizes are okay. */ const size_t enc_size = src_size + DeviceUniqueDataInnerMetaSize; const size_t res_size = src_size + DeviceUniqueDataTotalMetaSize; AMS_ABORT_UNLESS(res_size <= dst_size); /* Layout the image as expected. */ { /* Generate a random iv. */ util::AlignedBuffer<hw::DataCacheLineSize, DeviceUniqueDataIvSize> iv; GenerateIv(iv, DeviceUniqueDataIvSize); /* Move the data to the output image. */ std::memmove(dst_data, src, src_size); /* Copy the iv. */ std::memcpy(dst_iv, iv, DeviceUniqueDataIvSize); /* Clear the padding. */ std::memset(dst_pad, 0, DeviceUniqueDataPaddingSize); /* Store the device id. */ util::StoreBigEndian(reinterpret_cast<u64 *>(dst_did), EncodeDeviceId(device_id_high, fuse::GetDeviceId())); } /* Encrypt and mac. */ { /* Prepare the key used to encrypt the data. */ PrepareDeviceUniqueDataKey(seal_key_source, seal_key_source_size, access_key, access_key_size, key_source, key_source_size); /* Compute the gmac. */ ComputeGmac(dst_mac, DeviceUniqueDataMacSize, dst_data, enc_size, dst_iv, DeviceUniqueDataIvSize); /* Encrypt the data. */ ComputeAes128Ctr(dst_data, enc_size, pkg1::AesKeySlot_Smc, dst_data, enc_size, dst_iv, DeviceUniqueDataIvSize); } } }
9,330
C++
.cpp
162
47.074074
302
0.62922
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,343
secmon_smc_aes.cpp
Atmosphere-NX_Atmosphere/exosphere/program/source/smc/secmon_smc_aes.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 <exosphere.hpp> #include "../secmon_error.hpp" #include "../secmon_key_storage.hpp" #include "../secmon_misc.hpp" #include "../secmon_page_mapper.hpp" #include "secmon_smc_aes.hpp" #include "secmon_smc_device_unique_data.hpp" #include "secmon_smc_se_lock.hpp" namespace ams::secmon::smc { namespace { constexpr inline auto AesKeySize = se::AesBlockSize; constexpr inline size_t CmacSizeMax = 1_KB; constexpr inline size_t DeviceUniqueDataSizeMin = 0x130; constexpr inline size_t DeviceUniqueDataSizeMax = 0x240; enum SealKey { SealKey_LoadAesKey = 0, SealKey_DecryptDeviceUniqueData = 1, SealKey_ImportLotusKey = 2, SealKey_ImportEsDeviceKey = 3, SealKey_ReencryptDeviceUniqueData = 4, SealKey_ImportSslKey = 5, SealKey_ImportEsClientCertKey = 6, SealKey_Count, }; enum KeyType { KeyType_Default = 0, KeyType_NormalOnly = 1, KeyType_RecoveryOnly = 2, KeyType_NormalAndRecovery = 3, KeyType_Count, }; enum CipherMode { CipherMode_CbcEncryption = 0, CipherMode_CbcDecryption = 1, CipherMode_Ctr = 2, CipherMode_Cmac = 3, }; enum SpecificAesKey { SpecificAesKey_CalibrationEncryption0 = 0, SpecificAesKey_CalibrationEncryption1 = 1, SpecificAesKey_Count, }; enum DeviceUniqueData { DeviceUniqueData_DecryptDeviceUniqueData = 0, DeviceUniqueData_ImportLotusKey = 1, DeviceUniqueData_ImportEsDeviceKey = 2, DeviceUniqueData_ImportSslKey = 3, DeviceUniqueData_ImportEsClientCertKey = 4, DeviceUniqueData_Count, }; /* Ensure that our "subtract one" simplification is valid for the cases we care about. */ static_assert(DeviceUniqueData_ImportLotusKey - 1 == ImportRsaKey_Lotus); static_assert(DeviceUniqueData_ImportEsDeviceKey - 1 == ImportRsaKey_EsDrmCert); static_assert(DeviceUniqueData_ImportSslKey - 1 == ImportRsaKey_Ssl); static_assert(DeviceUniqueData_ImportEsClientCertKey - 1 == ImportRsaKey_EsClientCert); constexpr ImportRsaKey ConvertToImportRsaKey(DeviceUniqueData data) { /* Not necessary, but if this is invoked at compile-time this will force a compile-time error. */ AMS_ASSUME(data != DeviceUniqueData_DecryptDeviceUniqueData); AMS_ASSUME(data < DeviceUniqueData_Count); return static_cast<ImportRsaKey>(static_cast<int>(data) - 1); } enum SecureData { SecureData_Calibration = 0, SecureData_SafeMode = 1, SecureData_UserSystemProperEncryption = 2, SecureData_UserSystem = 3, SecureData_Count, }; struct GenerateAesKekOption { using IsDeviceUnique = util::BitPack32::Field<0, 1, bool>; using KeyTypeIndex = util::BitPack32::Field<1, 4, KeyType>; using SealKeyIndex = util::BitPack32::Field<5, 3, SealKey>; using Reserved = util::BitPack32::Field<8, 24, u32>; }; struct ComputeAesOption { using KeySlot = util::BitPack32::Field<0, 3, int>; using CipherModeIndex = util::BitPack32::Field<4, 2, CipherMode>; }; struct DecryptDeviceUniqueDataOption { using DeviceUniqueDataIndex = util::BitPack32::Field<0, 3, DeviceUniqueData>; using Reserved = util::BitPack32::Field<3, 29, u32>; /* Legacy. */ using EnforceDeviceUnique = util::BitPack32::Field<0, 1, bool>; }; constexpr const u8 SealKeySources[SealKey_Count][AesKeySize] = { [SealKey_LoadAesKey] = { 0xF4, 0x0C, 0x16, 0x26, 0x0D, 0x46, 0x3B, 0xE0, 0x8C, 0x6A, 0x56, 0xE5, 0x82, 0xD4, 0x1B, 0xF6 }, [SealKey_DecryptDeviceUniqueData] = { 0x7F, 0x54, 0x2C, 0x98, 0x1E, 0x54, 0x18, 0x3B, 0xBA, 0x63, 0xBD, 0x4C, 0x13, 0x5B, 0xF1, 0x06 }, [SealKey_ImportLotusKey] = { 0xC7, 0x3F, 0x73, 0x60, 0xB7, 0xB9, 0x9D, 0x74, 0x0A, 0xF8, 0x35, 0x60, 0x1A, 0x18, 0x74, 0x63 }, [SealKey_ImportEsDeviceKey] = { 0x0E, 0xE0, 0xC4, 0x33, 0x82, 0x66, 0xE8, 0x08, 0x39, 0x13, 0x41, 0x7D, 0x04, 0x64, 0x2B, 0x6D }, [SealKey_ReencryptDeviceUniqueData] = { 0xE1, 0xA8, 0xAA, 0x6A, 0x2D, 0x9C, 0xDE, 0x43, 0x0C, 0xDE, 0xC6, 0x17, 0xF6, 0xC7, 0xF1, 0xDE }, [SealKey_ImportSslKey] = { 0x74, 0x20, 0xF6, 0x46, 0x77, 0xB0, 0x59, 0x2C, 0xE8, 0x1B, 0x58, 0x64, 0x47, 0x41, 0x37, 0xD9 }, [SealKey_ImportEsClientCertKey] = { 0xAA, 0x19, 0x0F, 0xFA, 0x4C, 0x30, 0x3B, 0x2E, 0xE6, 0xD8, 0x9A, 0xCF, 0xE5, 0x3F, 0xB3, 0x4B }, }; constexpr const u8 KeyTypeSources[KeyType_Count][AesKeySize] = { [KeyType_Default] = { 0x4D, 0x87, 0x09, 0x86, 0xC4, 0x5D, 0x20, 0x72, 0x2F, 0xBA, 0x10, 0x53, 0xDA, 0x92, 0xE8, 0xA9 }, [KeyType_NormalOnly] = { 0x25, 0x03, 0x31, 0xFB, 0x25, 0x26, 0x0B, 0x79, 0x8C, 0x80, 0xD2, 0x69, 0x98, 0xE2, 0x22, 0x77 }, [KeyType_RecoveryOnly] = { 0x76, 0x14, 0x1D, 0x34, 0x93, 0x2D, 0xE1, 0x84, 0x24, 0x7B, 0x66, 0x65, 0x55, 0x04, 0x65, 0x81 }, [KeyType_NormalAndRecovery] = { 0xAF, 0x3D, 0xB7, 0xF3, 0x08, 0xA2, 0xD8, 0xA2, 0x08, 0xCA, 0x18, 0xA8, 0x69, 0x46, 0xC9, 0x0B }, }; constexpr const u8 SealKeyMasks[SealKey_Count][AesKeySize] = { [SealKey_LoadAesKey] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, [SealKey_DecryptDeviceUniqueData] = { 0xA2, 0xAB, 0xBF, 0x9C, 0x92, 0x2F, 0xBB, 0xE3, 0x78, 0x79, 0x9B, 0xC0, 0xCC, 0xEA, 0xA5, 0x74 }, [SealKey_ImportLotusKey] = { 0x57, 0xE2, 0xD9, 0x45, 0xE4, 0x92, 0xF4, 0xFD, 0xC3, 0xF9, 0x86, 0x38, 0x89, 0x78, 0x9F, 0x3C }, [SealKey_ImportEsDeviceKey] = { 0xE5, 0x4D, 0x9A, 0x02, 0xF0, 0x4F, 0x5F, 0xA8, 0xAD, 0x76, 0x0A, 0xF6, 0x32, 0x95, 0x59, 0xBB }, [SealKey_ReencryptDeviceUniqueData] = { 0x59, 0xD9, 0x31, 0xF4, 0xA7, 0x97, 0xB8, 0x14, 0x40, 0xD6, 0xA2, 0x60, 0x2B, 0xED, 0x15, 0x31 }, [SealKey_ImportSslKey] = { 0xFD, 0x6A, 0x25, 0xE5, 0xD8, 0x38, 0x7F, 0x91, 0x49, 0xDA, 0xF8, 0x59, 0xA8, 0x28, 0xE6, 0x75 }, [SealKey_ImportEsClientCertKey] = { 0x89, 0x96, 0x43, 0x9A, 0x7C, 0xD5, 0x59, 0x55, 0x24, 0xD5, 0x24, 0x18, 0xAB, 0x6C, 0x04, 0x61 }, }; constexpr const SealKey DeviceUniqueDataToSealKey[DeviceUniqueData_Count] = { [DeviceUniqueData_DecryptDeviceUniqueData] = SealKey_DecryptDeviceUniqueData, [DeviceUniqueData_ImportLotusKey] = SealKey_ImportLotusKey, [DeviceUniqueData_ImportEsDeviceKey] = SealKey_ImportEsDeviceKey, [DeviceUniqueData_ImportSslKey] = SealKey_ImportSslKey, [DeviceUniqueData_ImportEsClientCertKey] = SealKey_ImportEsClientCertKey, }; constexpr const u8 CalibrationKeySource[AesKeySize] = { 0xE2, 0xD6, 0xB8, 0x7A, 0x11, 0x9C, 0xB8, 0x80, 0xE8, 0x22, 0x88, 0x8A, 0x46, 0xFB, 0xA1, 0x95 }; constexpr const u8 EsCommonKeySources[EsCommonKeyType_Count][AesKeySize] = { [EsCommonKeyType_TitleKey] = { 0x1E, 0xDC, 0x7B, 0x3B, 0x60, 0xE6, 0xB4, 0xD8, 0x78, 0xB8, 0x17, 0x15, 0x98, 0x5E, 0x62, 0x9B }, [EsCommonKeyType_ArchiveKey] = { 0x3B, 0x78, 0xF2, 0x61, 0x0F, 0x9D, 0x5A, 0xE2, 0x7B, 0x4E, 0x45, 0xAF, 0xCB, 0x0B, 0x67, 0x4D }, [EsCommonKeyType_Unknown2] = { 0x42, 0x64, 0x0B, 0xE3, 0x5F, 0xC6, 0xBE, 0x47, 0xC7, 0xB4, 0x84, 0xC5, 0xEB, 0x63, 0xAA, 0x02 }, }; constexpr const u8 EsSealKeySource[AesKeySize] = { 0xCB, 0xB7, 0x6E, 0x38, 0xA1, 0xCB, 0x77, 0x0F, 0xB2, 0xA5, 0xB2, 0x9D, 0xD8, 0x56, 0x9F, 0x76 }; constexpr const u8 SecureDataSource[AesKeySize] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; constexpr const u8 SecureDataCounters[][AesKeySize] = { [SecureData_Calibration] = { 0x3C, 0xD5, 0x92, 0xEC, 0x68, 0x31, 0x4A, 0x06, 0xD4, 0x1B, 0x0C, 0xD9, 0xF6, 0x2E, 0xD9, 0xE9 }, [SecureData_SafeMode] = { 0x50, 0x81, 0xCF, 0x77, 0x18, 0x11, 0xD7, 0x0D, 0x13, 0x29, 0x60, 0xED, 0x4B, 0x21, 0x3E, 0xFC }, [SecureData_UserSystemProperEncryption] = { 0x98, 0xCB, 0x4C, 0xEB, 0x15, 0xF1, 0x4A, 0x5A, 0x7A, 0x86, 0xB6, 0xF1, 0x94, 0x66, 0xF4, 0x9D }, }; constexpr const u8 SecureDataTweaks[][AesKeySize] = { [SecureData_Calibration] = { 0xAC, 0xCA, 0x9A, 0xCA, 0xFF, 0x2E, 0xB9, 0x22, 0xCC, 0x1F, 0x4F, 0xAD, 0xDD, 0x77, 0x21, 0x1E }, [SecureData_SafeMode] = { 0x6E, 0xF8, 0x2A, 0x1A, 0xE0, 0x4F, 0xC3, 0x20, 0x08, 0x7B, 0xBA, 0x50, 0xC0, 0xCD, 0x7B, 0x39 }, [SecureData_UserSystemProperEncryption] = { 0x6D, 0x02, 0x56, 0x2D, 0xF4, 0x3D, 0x0A, 0x15, 0xB1, 0x34, 0x5C, 0xC2, 0x84, 0x4C, 0xD4, 0x28 }, }; constexpr const u8 *GetSecureDataCounter(SecureData which) { switch (which) { case SecureData_Calibration: return SecureDataCounters[SecureData_Calibration]; case SecureData_SafeMode: return SecureDataCounters[SecureData_SafeMode]; case SecureData_UserSystem: case SecureData_UserSystemProperEncryption: return SecureDataCounters[SecureData_UserSystemProperEncryption]; default: return nullptr; } } constexpr const u8 *GetSecureDataTweak(SecureData which) { switch (which) { case SecureData_Calibration: return SecureDataTweaks[SecureData_Calibration]; case SecureData_SafeMode: return SecureDataTweaks[SecureData_SafeMode]; case SecureData_UserSystem: case SecureData_UserSystemProperEncryption: return SecureDataTweaks[SecureData_UserSystemProperEncryption]; default: return nullptr; } } constexpr uintptr_t LinkedListAddressMinimum = secmon::MemoryRegionDram.GetAddress(); constexpr size_t LinkedListAddressRangeSize = 4_MB - 2_KB; constexpr uintptr_t LinkedListAddressMaximum = LinkedListAddressMinimum + LinkedListAddressRangeSize; constexpr size_t LinkedListSize = 12; constexpr bool IsValidLinkedListAddress(uintptr_t address) { return LinkedListAddressMinimum <= address && address <= (LinkedListAddressMaximum - LinkedListSize); } constinit bool g_is_compute_aes_completed = false; void SecurityEngineDoneHandler() { /* Check that the compute succeeded. */ se::ValidateAesOperationResult(); /* End the asynchronous operation. */ g_is_compute_aes_completed = true; EndAsyncOperation(); } SmcResult GetComputeAesResult(void *dst, size_t size) { /* Arguments are unused. */ AMS_UNUSED(dst); AMS_UNUSED(size); /* Check that the operation is completed. */ SMC_R_UNLESS(g_is_compute_aes_completed, Busy); /* Unlock the security engine and succeed. */ UnlockSecurityEngine(); return SmcResult::Success; } int PrepareMasterKey(int generation) { if (generation == GetKeyGeneration()) { return pkg1::AesKeySlot_Master; } constexpr int Slot = pkg1::AesKeySlot_Smc; LoadMasterKey(Slot, generation); return Slot; } int PrepareDeviceMasterKey(int generation) { if (generation == pkg1::KeyGeneration_1_0_0 && GetSocType() == fuse::SocType_Erista) { return pkg1::AesKeySlot_Device; } if (generation == GetKeyGeneration()) { return pkg1::AesKeySlot_DeviceMaster; } constexpr int Slot = pkg1::AesKeySlot_Smc; LoadDeviceMasterKey(Slot, generation); return Slot; } void GetSecureDataImpl(u8 *dst, SecureData which, bool tweak) { /* Compute the appropriate AES-CTR. */ { /* Ensure that the SE sees consistent data. */ hw::FlushDataCache(dst, AesKeySize); hw::DataSynchronizationBarrierInnerShareable(); /* Perform the appropriate AES operation. */ se::ComputeAes128Ctr(dst, AesKeySize, pkg1::AesKeySlot_Device, SecureDataSource, AesKeySize, GetSecureDataCounter(which), AesKeySize); hw::DataSynchronizationBarrierInnerShareable(); /* Ensure the CPU sees consistent data. */ hw::FlushDataCache(dst, AesKeySize); hw::DataSynchronizationBarrierInnerShareable(); } /* Tweak, if we should. */ if (tweak) { const u8 * const tweak = GetSecureDataTweak(which); for (size_t i = 0; i < AesKeySize; ++i) { dst[i] ^= tweak[i]; } } } SmcResult GenerateAesKekImpl(SmcArguments &args) { /* Decode arguments. */ u8 kek_source[AesKeySize]; std::memcpy(kek_source, std::addressof(args.r[1]), AesKeySize); const int generation = std::max<int>(static_cast<int>(args.r[3]) - 1, pkg1::KeyGeneration_1_0_0); const util::BitPack32 option = { static_cast<u32>(args.r[4]) }; const bool is_device_unique = option.Get<GenerateAesKekOption::IsDeviceUnique>(); const auto key_type = option.Get<GenerateAesKekOption::KeyTypeIndex>(); const auto seal_key = option.Get<GenerateAesKekOption::SealKeyIndex>(); const u32 reserved = option.Get<GenerateAesKekOption::Reserved>(); /* Validate arguments. */ SMC_R_UNLESS(reserved == 0, InvalidArgument); if (is_device_unique) { SMC_R_UNLESS(pkg1::IsValidDeviceUniqueKeyGeneration(generation), InvalidArgument); } else { SMC_R_UNLESS(pkg1::IsValidKeyGeneration(generation), InvalidArgument); SMC_R_UNLESS(generation <= GetKeyGeneration(), InvalidArgument); } SMC_R_UNLESS(0 <= key_type && key_type < KeyType_Count, InvalidArgument); SMC_R_UNLESS(0 <= seal_key && seal_key < SealKey_Count, InvalidArgument); switch (key_type) { case KeyType_NormalOnly: SMC_R_UNLESS(!IsRecoveryBoot(), InvalidArgument); break; case KeyType_RecoveryOnly: SMC_R_UNLESS( IsRecoveryBoot(), InvalidArgument); break; default: break; } /* Declare temporary data storage. */ u8 static_source[AesKeySize]; u8 generated_key[AesKeySize]; u8 access_key[AesKeySize]; /* Derive the static source. */ for (size_t i = 0; i < sizeof(static_source); ++i) { static_source[i] = KeyTypeSources[key_type][i] ^ SealKeyMasks[seal_key][i]; } /* Get the seal key source. */ const u8 * const seal_key_source = SealKeySources[seal_key]; /* Get the key slot. */ const int slot = is_device_unique ? PrepareDeviceMasterKey(generation) : PrepareMasterKey(generation); /* Derive a static generation kek. */ se::SetEncryptedAesKey128(pkg1::AesKeySlot_Smc, slot, static_source, sizeof(static_source)); /* Decrypt the input with the static generation kek. */ se::DecryptAes128(generated_key, sizeof(generated_key), pkg1::AesKeySlot_Smc, kek_source, sizeof(kek_source)); /* Generate the seal key. */ se::SetEncryptedAesKey128(pkg1::AesKeySlot_Smc, pkg1::AesKeySlot_RandomForUserWrap, seal_key_source, AesKeySize); /* Seal the generated key. */ se::EncryptAes128(access_key, sizeof(access_key), pkg1::AesKeySlot_Smc, generated_key, sizeof(generated_key)); /* Copy the access key out. */ std::memcpy(std::addressof(args.r[1]), access_key, sizeof(access_key)); return SmcResult::Success; } SmcResult LoadAesKeyImpl(SmcArguments &args) { /* Decode arguments. */ const int slot = args.r[1]; u8 access_key[AesKeySize]; std::memcpy(access_key, std::addressof(args.r[2]), sizeof(access_key)); u8 key_source[AesKeySize]; std::memcpy(key_source, std::addressof(args.r[4]), sizeof(key_source)); /* Validate arguments. */ SMC_R_UNLESS(pkg1::IsUserAesKeySlot(slot), InvalidArgument); /* Get the seal key source. */ constexpr const u8 * const SealKeySource = SealKeySources[SealKey_LoadAesKey]; /* Derive the seal key. */ se::SetEncryptedAesKey128(pkg1::AesKeySlot_Smc, pkg1::AesKeySlot_RandomForUserWrap, SealKeySource, AesKeySize); /* Unseal the access key. */ se::SetEncryptedAesKey128(pkg1::AesKeySlot_Smc, pkg1::AesKeySlot_Smc, access_key, sizeof(access_key)); /* Derive the key. */ se::SetEncryptedAesKey128(slot, pkg1::AesKeySlot_Smc, key_source, sizeof(key_source)); return SmcResult::Success; } SmcResult ComputeAesImpl(SmcArguments &args) { /* Decode arguments. */ u8 iv[se::AesBlockSize]; const util::BitPack32 option = { static_cast<u32>(args.r[1]) }; std::memcpy(iv, std::addressof(args.r[2]), sizeof(iv)); const u32 input_address = args.r[4]; const u32 output_address = args.r[5]; const u32 size = args.r[6]; const int slot = option.Get<ComputeAesOption::KeySlot>(); const auto cipher_mode = option.Get<ComputeAesOption::CipherModeIndex>(); /* Validate arguments. */ SMC_R_UNLESS(pkg1::IsUserAesKeySlot(slot), InvalidArgument); SMC_R_UNLESS(util::IsAligned(size, se::AesBlockSize), InvalidArgument); SMC_R_UNLESS(IsValidLinkedListAddress(input_address), InvalidArgument); SMC_R_UNLESS(IsValidLinkedListAddress(output_address), InvalidArgument); /* We're starting an aes operation, so reset the completion status. */ g_is_compute_aes_completed = false; /* Dispatch the correct aes operation asynchronously. */ switch (cipher_mode) { case CipherMode_CbcEncryption: se::EncryptAes128CbcAsync(output_address, slot, input_address, size, iv, sizeof(iv), SecurityEngineDoneHandler); break; case CipherMode_CbcDecryption: se::DecryptAes128CbcAsync(output_address, slot, input_address, size, iv, sizeof(iv), SecurityEngineDoneHandler); break; case CipherMode_Ctr: se::ComputeAes128CtrAsync(output_address, slot, input_address, size, iv, sizeof(iv), SecurityEngineDoneHandler); break; case CipherMode_Cmac: return SmcResult::NotSupported; default: return SmcResult::InvalidArgument; } return SmcResult::Success; } SmcResult GenerateSpecificAesKeyImpl(SmcArguments &args) { /* Decode arguments. */ u8 key_source[AesKeySize]; std::memcpy(key_source, std::addressof(args.r[1]), sizeof(key_source)); const int generation = GetTargetFirmware() >= TargetFirmware_4_0_0 ? std::max<int>(static_cast<int>(args.r[3]) - 1, pkg1::KeyGeneration_1_0_0) : pkg1::KeyGeneration_1_0_0; const auto which = static_cast<SpecificAesKey>(args.r[4]); /* Validate arguments. */ SMC_R_UNLESS(pkg1::IsValidKeyGeneration(generation), InvalidArgument); SMC_R_UNLESS(which < SpecificAesKey_Count, InvalidArgument); /* Generate the specific aes key. */ u8 output_key[AesKeySize]; if (fuse::GetPatchVersion() >= fuse::PatchVersion_Odnx02A2) { const int slot = PrepareDeviceMasterKey(generation); se::SetEncryptedAesKey128(pkg1::AesKeySlot_Smc, slot, CalibrationKeySource, sizeof(CalibrationKeySource)); se::DecryptAes128(output_key, sizeof(output_key), pkg1::AesKeySlot_Smc, key_source, sizeof(key_source)); } else { GetSecureDataImpl(output_key, SecureData_Calibration, which == SpecificAesKey_CalibrationEncryption1); } /* Copy the key to output. */ std::memcpy(std::addressof(args.r[1]), output_key, sizeof(output_key)); return SmcResult::Success; } SmcResult ComputeCmacImpl(SmcArguments &args) { /* Decode arguments. */ const int slot = args.r[1]; const uintptr_t data_address = args.r[2]; const size_t data_size = args.r[3]; /* Declare buffer for user data. */ alignas(8) u8 user_data[CmacSizeMax]; /* Validate arguments. */ SMC_R_UNLESS(pkg1::IsUserAesKeySlot(slot), InvalidArgument); SMC_R_UNLESS(data_size <= sizeof(user_data), InvalidArgument); /* Map the user data, and copy to stack. */ { UserPageMapper mapper(data_address); SMC_R_UNLESS(mapper.Map(), InvalidArgument); SMC_R_UNLESS(mapper.CopyFromUser(user_data, data_address, data_size), InvalidArgument); } /* Ensure the SE sees consistent data. */ hw::FlushDataCache(user_data, data_size); hw::DataSynchronizationBarrierInnerShareable(); /* Compute the mac. */ { u8 mac[se::AesBlockSize]; se::ComputeAes128Cmac(mac, sizeof(mac), slot, user_data, data_size); std::memcpy(std::addressof(args.r[1]), mac, sizeof(mac)); } return SmcResult::Success; } SmcResult LoadPreparedAesKeyImpl(SmcArguments &args) { /* Decode arguments. */ u8 access_key[AesKeySize]; const int slot = args.r[1]; std::memcpy(access_key, std::addressof(args.r[2]), sizeof(access_key)); /* Validate arguments. */ SMC_R_UNLESS(pkg1::IsUserAesKeySlot(slot), InvalidArgument); /* Derive the seal key. */ se::SetEncryptedAesKey128(pkg1::AesKeySlot_Smc, pkg1::AesKeySlot_RandomForUserWrap, EsSealKeySource, sizeof(EsSealKeySource)); /* Unseal the key. */ se::SetEncryptedAesKey128(slot, pkg1::AesKeySlot_Smc, access_key, sizeof(access_key)); return SmcResult::Success; } SmcResult PrepareEsCommonTitleKeyImpl(SmcArguments &args) { /* Declare variables. */ u8 key_source[se::AesBlockSize]; u8 key[se::AesBlockSize]; u8 access_key[se::AesBlockSize]; /* Decode arguments. */ std::memcpy(key_source, std::addressof(args.r[1]), sizeof(key_source)); const int generation = GetTargetFirmware() >= TargetFirmware_3_0_0 ? std::max<int>(pkg1::KeyGeneration_1_0_0, static_cast<int>(args.r[3]) - 1) : pkg1::KeyGeneration_1_0_0; /* Validate arguments. */ SMC_R_UNLESS(pkg1::IsValidKeyGeneration(generation), InvalidArgument); SMC_R_UNLESS(generation <= GetKeyGeneration(), InvalidArgument); /* Derive the key. */ DecryptWithEsCommonKey(key, sizeof(key), key_source, sizeof(key_source), EsCommonKeyType_TitleKey, generation); /* Prepare the aes key. */ PrepareEsAesKey(access_key, sizeof(access_key), key, sizeof(key)); /* Copy the access key to output. */ std::memcpy(std::addressof(args.r[1]), access_key, sizeof(access_key)); return SmcResult::Success; } constexpr size_t GetDiscountedMinimumDeviceUniqueDataSize(bool enforce_device_unique) { if (enforce_device_unique) { return 0; } else { return DeviceUniqueDataTotalMetaSize - DeviceUniqueDataIvSize; } } SmcResult ValidateDeviceUniqueDataSize(DeviceUniqueData mode, size_t data_size, bool enforce_device_unique) { /* Determine the discounted size towards the minimum. */ const size_t discounted_size = GetDiscountedMinimumDeviceUniqueDataSize(enforce_device_unique); SMC_R_UNLESS(enforce_device_unique || fuse::GetPatchVersion() < fuse::PatchVersion_Odnx02A2, InvalidArgument); switch (mode) { case DeviceUniqueData_DecryptDeviceUniqueData: { SMC_R_UNLESS(DeviceUniqueDataTotalMetaSize - discounted_size < data_size && data_size <= DeviceUniqueDataSizeMax, InvalidArgument); } break; case DeviceUniqueData_ImportLotusKey: case DeviceUniqueData_ImportEsDeviceKey: case DeviceUniqueData_ImportSslKey: case DeviceUniqueData_ImportEsClientCertKey: { SMC_R_UNLESS(DeviceUniqueDataSizeMin - discounted_size <= data_size && data_size <= DeviceUniqueDataSizeMax, InvalidArgument); } break; default: return SmcResult::InvalidArgument; } return SmcResult::Success; } SmcResult DecryptDeviceUniqueDataImpl(const u8 *access_key, const u8 *key_source, const DeviceUniqueData mode, const uintptr_t data_address, const size_t data_size, bool enforce_device_unique) { /* Validate arguments. */ SMC_R_TRY(ValidateDeviceUniqueDataSize(mode, data_size, enforce_device_unique)); /* Decrypt the device unique data. */ alignas(8) u8 work_buffer[DeviceUniqueDataSizeMax]; ON_SCOPE_EXIT { crypto::ClearMemory(work_buffer, sizeof(work_buffer)); }; { /* Map and copy in the encrypted data. */ UserPageMapper mapper(data_address); SMC_R_UNLESS(mapper.Map(), InvalidArgument); SMC_R_UNLESS(mapper.CopyFromUser(work_buffer, data_address, data_size), InvalidArgument); /* Determine the seal key to use. */ const auto seal_key_type = DeviceUniqueDataToSealKey[mode]; const u8 * const seal_key_source = SealKeySources[seal_key_type]; /* Decrypt the data. */ if (!DecryptDeviceUniqueData(work_buffer, data_size, nullptr, seal_key_source, se::AesBlockSize, access_key, se::AesBlockSize, key_source, se::AesBlockSize, work_buffer, data_size, enforce_device_unique)) { return SmcResult::InvalidArgument; } /* Either output the key, or import it. */ switch (mode) { case DeviceUniqueData_DecryptDeviceUniqueData: { SMC_R_UNLESS(mapper.CopyToUser(data_address, work_buffer, data_size), InvalidArgument); } break; case DeviceUniqueData_ImportLotusKey: case DeviceUniqueData_ImportSslKey: ImportRsaKeyExponent(ConvertToImportRsaKey(mode), work_buffer, se::RsaSize); break; case DeviceUniqueData_ImportEsDeviceKey: case DeviceUniqueData_ImportEsClientCertKey: ImportRsaKeyExponent(ConvertToImportRsaKey(mode), work_buffer, se::RsaSize); ImportRsaKeyModulusProvisionally(ConvertToImportRsaKey(mode), work_buffer + se::RsaSize, se::RsaSize); CommitRsaKeyModulus(ConvertToImportRsaKey(mode)); break; AMS_UNREACHABLE_DEFAULT_CASE(); } } return SmcResult::Success; } SmcResult DecryptDeviceUniqueDataImpl(SmcArguments &args) { /* Decode arguments. */ u8 access_key[se::AesBlockSize]; u8 key_source[se::AesBlockSize]; std::memcpy(access_key, std::addressof(args.r[1]), sizeof(access_key)); const util::BitPack32 option = { static_cast<u32>(args.r[3]) }; const uintptr_t data_address = args.r[4]; const size_t data_size = args.r[5]; std::memcpy(key_source, std::addressof(args.r[6]), sizeof(key_source)); const auto mode = GetTargetFirmware() >= TargetFirmware_5_0_0 ? option.Get<DecryptDeviceUniqueDataOption::DeviceUniqueDataIndex>() : DeviceUniqueData_DecryptDeviceUniqueData; const auto reserved = option.Get<DecryptDeviceUniqueDataOption::Reserved>(); const bool enforce_device_unique = GetTargetFirmware() >= TargetFirmware_5_0_0 ? true : option.Get<DecryptDeviceUniqueDataOption::EnforceDeviceUnique>(); /* Validate arguments. */ SMC_R_UNLESS(reserved == 0, InvalidArgument); /* Decrypt the device unique data. */ return DecryptDeviceUniqueDataImpl(access_key, key_source, mode, data_address, data_size, enforce_device_unique); } SmcResult DecryptAndImportEsDeviceKeyImpl(SmcArguments &args) { /* Decode arguments. */ u8 access_key[se::AesBlockSize]; u8 key_source[se::AesBlockSize]; std::memcpy(access_key, std::addressof(args.r[1]), sizeof(access_key)); const util::BitPack32 option = { static_cast<u32>(args.r[3]) }; const uintptr_t data_address = args.r[4]; const size_t data_size = args.r[5]; std::memcpy(key_source, std::addressof(args.r[6]), sizeof(key_source)); const auto mode = DeviceUniqueData_ImportEsDeviceKey; const auto reserved = option.Get<DecryptDeviceUniqueDataOption::Reserved>(); const bool enforce_device_unique = option.Get<DecryptDeviceUniqueDataOption::EnforceDeviceUnique>(); /* Validate arguments. */ SMC_R_UNLESS(reserved == 0, InvalidArgument); /* Ensure that the key is exactly the correct size. */ if (enforce_device_unique) { SMC_R_UNLESS(data_size == util::AlignUp(2 * se::RsaSize + sizeof(u32), se::AesBlockSize) + DeviceUniqueDataTotalMetaSize, InvalidArgument); } else { SMC_R_UNLESS(data_size == util::AlignUp(2 * se::RsaSize + sizeof(u32), se::AesBlockSize) + DeviceUniqueDataIvSize, InvalidArgument); } /* Decrypt the device unique data. */ return DecryptDeviceUniqueDataImpl(access_key, key_source, mode, data_address, data_size, enforce_device_unique); } SmcResult DecryptAndImportLotusKeyImpl(SmcArguments &args) { /* Decode arguments. */ u8 access_key[se::AesBlockSize]; u8 key_source[se::AesBlockSize]; std::memcpy(access_key, std::addressof(args.r[1]), sizeof(access_key)); const util::BitPack32 option = { static_cast<u32>(args.r[3]) }; const uintptr_t data_address = args.r[4]; const size_t data_size = args.r[5]; std::memcpy(key_source, std::addressof(args.r[6]), sizeof(key_source)); const auto mode = DeviceUniqueData_ImportLotusKey; const auto reserved = option.Get<DecryptDeviceUniqueDataOption::Reserved>(); const bool enforce_device_unique = option.Get<DecryptDeviceUniqueDataOption::EnforceDeviceUnique>(); /* Validate arguments. */ SMC_R_UNLESS(reserved == 0, InvalidArgument); /* Ensure that the key is exactly the correct size. */ if (enforce_device_unique) { SMC_R_UNLESS(data_size == se::RsaSize + DeviceUniqueDataTotalMetaSize, InvalidArgument); } else { SMC_R_UNLESS(data_size == se::RsaSize + DeviceUniqueDataIvSize, InvalidArgument); } /* Decrypt the device unique data. */ return DecryptDeviceUniqueDataImpl(access_key, key_source, mode, data_address, data_size, enforce_device_unique); } SmcResult ReencryptDeviceUniqueDataImpl(SmcArguments &args) { /* Decode arguments. */ u8 access_key_dec[se::AesBlockSize]; u8 access_key_enc[se::AesBlockSize]; u8 key_source_dec[se::AesBlockSize]; u8 key_source_enc[se::AesBlockSize]; const uintptr_t access_key_dec_address = args.r[1]; const uintptr_t access_key_enc_address = args.r[2]; const util::BitPack32 option = { static_cast<u32>(args.r[3]) }; const uintptr_t data_address = args.r[4]; const size_t data_size = args.r[5]; const uintptr_t key_source_dec_address = args.r[6]; const uintptr_t key_source_enc_address = args.r[7]; const auto mode = option.Get<DecryptDeviceUniqueDataOption::DeviceUniqueDataIndex>(); const auto reserved = option.Get<DecryptDeviceUniqueDataOption::Reserved>(); const bool enforce_device_unique = true; /* Validate arguments. */ SMC_R_UNLESS(reserved == 0, InvalidArgument); SMC_R_TRY(ValidateDeviceUniqueDataSize(mode, data_size, enforce_device_unique)); /* Decrypt the device unique data. */ alignas(8) u8 work_buffer[DeviceUniqueDataSizeMax]; ON_SCOPE_EXIT { crypto::ClearMemory(work_buffer, sizeof(work_buffer)); }; { /* Map and copy in the encrypted data. */ UserPageMapper mapper(data_address); SMC_R_UNLESS(mapper.Map(), InvalidArgument); SMC_R_UNLESS(mapper.CopyFromUser(work_buffer, data_address, data_size), InvalidArgument); SMC_R_UNLESS(mapper.CopyFromUser(access_key_dec, access_key_dec_address, sizeof(access_key_dec)), InvalidArgument); SMC_R_UNLESS(mapper.CopyFromUser(access_key_enc, access_key_enc_address, sizeof(access_key_enc)), InvalidArgument); SMC_R_UNLESS(mapper.CopyFromUser(key_source_dec, key_source_dec_address, sizeof(key_source_dec)), InvalidArgument); SMC_R_UNLESS(mapper.CopyFromUser(key_source_enc, key_source_enc_address, sizeof(key_source_enc)), InvalidArgument); /* Decrypt the data. */ u8 device_id_high; { /* Determine the seal key to use. */ const u8 * const seal_key_source = SealKeySources[SealKey_ReencryptDeviceUniqueData]; if (!DecryptDeviceUniqueData(work_buffer, data_size, std::addressof(device_id_high), seal_key_source, se::AesBlockSize, access_key_dec, sizeof(access_key_dec), key_source_dec, sizeof(key_source_dec), work_buffer, data_size, enforce_device_unique)) { return SmcResult::InvalidArgument; } } /* Reencrypt the data. */ { /* Determine the seal key to use. */ const auto seal_key_type = DeviceUniqueDataToSealKey[mode]; const u8 * const seal_key_source = SealKeySources[seal_key_type]; /* Encrypt the data. */ EncryptDeviceUniqueData(work_buffer, data_size, seal_key_source, se::AesBlockSize, access_key_enc, sizeof(access_key_enc), key_source_enc, sizeof(key_source_enc), work_buffer, data_size - DeviceUniqueDataTotalMetaSize, device_id_high); } /* Copy the reencrypted data back to user. */ SMC_R_UNLESS(mapper.CopyToUser(data_address, work_buffer, data_size), InvalidArgument); } return SmcResult::Success; } SmcResult GetSecureDataImpl(SmcArguments &args) { /* Decode arguments. */ const auto which = static_cast<SecureData>(args.r[1]); /* Validate arguments/conditions. */ SMC_R_UNLESS(fuse::GetPatchVersion() < fuse::PatchVersion_Odnx02A2, NotSupported); SMC_R_UNLESS(which < SecureData_Count, NotSupported); /* Use a temporary buffer. */ u8 secure_data[AesKeySize]; GetSecureDataImpl(secure_data, which, false); /* Copy out. */ std::memcpy(std::addressof(args.r[1]), secure_data, sizeof(secure_data)); return SmcResult::Success; } } /* Aes functionality. */ SmcResult SmcGenerateAesKek(SmcArguments &args) { return LockSecurityEngineAndInvoke(args, GenerateAesKekImpl); } SmcResult SmcLoadAesKey(SmcArguments &args) { return LockSecurityEngineAndInvoke(args, LoadAesKeyImpl); } SmcResult SmcComputeAes(SmcArguments &args) { return LockSecurityEngineAndInvokeAsync(args, ComputeAesImpl, GetComputeAesResult); } SmcResult SmcGenerateSpecificAesKey(SmcArguments &args) { return LockSecurityEngineAndInvoke(args, GenerateSpecificAesKeyImpl); } SmcResult SmcComputeCmac(SmcArguments &args) { return LockSecurityEngineAndInvoke(args, ComputeCmacImpl); } SmcResult SmcLoadPreparedAesKey(SmcArguments &args) { return LockSecurityEngineAndInvoke(args, LoadPreparedAesKeyImpl); } SmcResult SmcPrepareEsCommonTitleKey(SmcArguments &args) { return LockSecurityEngineAndInvoke(args, PrepareEsCommonTitleKeyImpl); } /* Device unique data functionality. */ SmcResult SmcDecryptDeviceUniqueData(SmcArguments &args) { return LockSecurityEngineAndInvoke(args, DecryptDeviceUniqueDataImpl); } SmcResult SmcReencryptDeviceUniqueData(SmcArguments &args) { return LockSecurityEngineAndInvoke(args, ReencryptDeviceUniqueDataImpl); } /* Legacy APIs. */ SmcResult SmcDecryptAndImportEsDeviceKey(SmcArguments &args) { return LockSecurityEngineAndInvoke(args, DecryptAndImportEsDeviceKeyImpl); } SmcResult SmcDecryptAndImportLotusKey(SmcArguments &args) { return LockSecurityEngineAndInvoke(args, DecryptAndImportLotusKeyImpl); } /* Es encryption utilities. */ void DecryptWithEsCommonKey(void *dst, size_t dst_size, const void *src, size_t src_size, EsCommonKeyType type, int generation) { /* Validate pre-conditions. */ AMS_ABORT_UNLESS(dst_size == AesKeySize); AMS_ABORT_UNLESS(src_size == AesKeySize); AMS_ABORT_UNLESS(0 <= type && type < EsCommonKeyType_Count); /* Prepare the master key for the generation. */ const int slot = PrepareMasterKey(generation); /* Derive the es common key. */ se::SetEncryptedAesKey128(pkg1::AesKeySlot_Smc, slot, EsCommonKeySources[type], AesKeySize); /* Decrypt the input using the common key. */ se::DecryptAes128(dst, dst_size, pkg1::AesKeySlot_Smc, src, src_size); } void PrepareEsAesKey(void *dst, size_t dst_size, const void *src, size_t src_size) { /* Validate pre-conditions. */ AMS_ABORT_UNLESS(dst_size == AesKeySize); AMS_ABORT_UNLESS(src_size == AesKeySize); /* Derive the seal key. */ se::SetEncryptedAesKey128(pkg1::AesKeySlot_Smc, pkg1::AesKeySlot_RandomForUserWrap, EsSealKeySource, sizeof(EsSealKeySource)); /* Seal the key. */ se::EncryptAes128(dst, dst_size, pkg1::AesKeySlot_Smc, src, src_size); } /* 'Tis the last rose of summer, / Left blooming alone; */ /* Oh! who would inhabit / This bleak world alone? */ SmcResult SmcGetSecureData(SmcArguments &args) { return LockSecurityEngineAndInvoke(args, GetSecureDataImpl); } }
42,000
C++
.cpp
687
48.315866
269
0.607317
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,344
secmon_smc_power_management.cpp
Atmosphere-NX_Atmosphere/exosphere/program/source/smc/secmon_smc_power_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 <exosphere.hpp> #include "../secmon_cache.hpp" #include "../secmon_cpu_context.hpp" #include "../secmon_error.hpp" #include "../secmon_misc.hpp" #include "secmon_smc_power_management.hpp" #include "secmon_smc_se_lock.hpp" #include "sc7fw_bin.h" namespace ams::secmon { /* Declare assembly functionality. */ void *GetCoreExceptionStackVirtual(); } namespace ams::secmon::smc { /* Declare assembly power-management functionality. */ void PivotStackAndInvoke(void *stack, void (*function)()); void FinalizePowerOff(); namespace { constexpr inline const uintptr_t PMC = MemoryRegionVirtualDevicePmc.GetAddress(); constexpr inline const uintptr_t APB_MISC = MemoryRegionVirtualDeviceApbMisc.GetAddress(); constexpr inline const uintptr_t GPIO = MemoryRegionVirtualDeviceGpio.GetAddress(); constexpr inline const uintptr_t CLK_RST = MemoryRegionVirtualDeviceClkRst.GetAddress(); constexpr inline const uintptr_t EVP = secmon::MemoryRegionVirtualDeviceExceptionVectors.GetAddress(); constexpr inline const uintptr_t FLOW_CTLR = MemoryRegionVirtualDeviceFlowController.GetAddress(); constexpr inline const uintptr_t AHB_ARBC = MemoryRegionVirtualDeviceSystem.GetAddress(); constexpr inline uintptr_t CommonSmcStackTop = MemoryRegionVirtualTzramVolatileData.GetEndAddress() - (0x80 * (NumCores - 1)); enum PowerStateType { PowerStateType_StandBy = 0, PowerStateType_PowerDown = 1, }; enum PowerStateId { PowerStateId_Sc7 = 27, }; /* http://infocenter.arm.com/help/topic/com.arm.doc.den0022d/Power_State_Coordination_Interface_PDD_v1_1_DEN0022D.pdf Page 46 */ struct SuspendCpuPowerState { using StateId = util::BitPack32::Field< 0, 16, PowerStateId>; using StateType = util::BitPack32::Field<16, 1, PowerStateType>; using PowerLevel = util::BitPack32::Field<24, 2, u32>; }; constinit bool g_charger_hi_z_mode_enabled = false; constinit const reg::BitsMask CpuPowerGateStatusMasks[NumCores] = { PMC_REG_BITS_MASK(PWRGATE_STATUS_CE0), PMC_REG_BITS_MASK(PWRGATE_STATUS_CE1), PMC_REG_BITS_MASK(PWRGATE_STATUS_CE2), PMC_REG_BITS_MASK(PWRGATE_STATUS_CE3), }; constinit const APBDEV_PMC_PWRGATE_TOGGLE_PARTID CpuPowerGateTogglePartitionIds[NumCores] = { APBDEV_PMC_PWRGATE_TOGGLE_PARTID_CE0, APBDEV_PMC_PWRGATE_TOGGLE_PARTID_CE1, APBDEV_PMC_PWRGATE_TOGGLE_PARTID_CE2, APBDEV_PMC_PWRGATE_TOGGLE_PARTID_CE3, }; bool IsCpuPoweredOn(const reg::BitsMask mask) { return reg::HasValue(PMC + APBDEV_PMC_PWRGATE_STATUS, REG_BITS_VALUE_FROM_MASK(mask, APBDEV_PMC_PWRGATE_STATUS_STATUS_ON)); } void PowerOnCpu(const reg::BitsMask mask, u32 toggle_partid) { /* If the cpu is already on, we have nothing to do. */ if (IsCpuPoweredOn(mask)) { return; } /* Wait until nothing is being powergated. */ int timeout = 5000; while (true) { if (reg::HasValue(PMC + APBDEV_PMC_PWRGATE_TOGGLE, PMC_REG_BITS_ENUM(PWRGATE_TOGGLE_START, DISABLE))) { break; } util::WaitMicroSeconds(1); if ((--timeout) < 0) { /* NOTE: Nintendo doesn't do any error handling here... */ return; } } /* Toggle on the cpu partition. */ reg::Write(PMC + APBDEV_PMC_PWRGATE_TOGGLE, PMC_REG_BITS_ENUM (PWRGATE_TOGGLE_START, ENABLE), PMC_REG_BITS_VALUE(PWRGATE_TOGGLE_PARTID, toggle_partid)); /* Wait up to 5000 us for the powergate to complete. */ timeout = 5000; while (true) { if (IsCpuPoweredOn(mask)) { break; } util::WaitMicroSeconds(1); if ((--timeout) < 0) { /* NOTE: Nintendo doesn't do any error handling here... */ return; } } } void ResetCpu(int which_core) { reg::Write(CLK_RST + CLK_RST_CONTROLLER_RST_CPUG_CMPLX_SET, REG_BITS_VALUE(which_core + 0x00, 1, 1), /* CPURESETn */ REG_BITS_VALUE(which_core + 0x10, 1, 1)); /* CORERESETn */ } void StartCpu(int which_core) { reg::Write(CLK_RST + CLK_RST_CONTROLLER_RST_CPUG_CMPLX_CLR, REG_BITS_VALUE(which_core + 0x00, 1, 1), /* CPURESETn */ REG_BITS_VALUE(which_core + 0x10, 1, 1)); /* CORERESETn */ } void PowerOffCpuImpl() { /* Get the current core id. */ const auto core_id = hw::GetCurrentCoreId(); /* Configure the flow controller to prepare for shutting down the current core. */ flow::SetCpuCsr(core_id, FLOW_CTLR_CPUN_CSR_ENABLE_EXT_POWERGATE_CPU_ONLY); flow::SetHaltCpuEvents(core_id, false); flow::SetCc4Ctrl(core_id, 0); /* Save the core's context for restoration on next power-on. */ SaveDebugRegisters(); SetCoreOff(); /* Ensure there are no pending memory transactions prior to our power-down. */ FlushEntireDataCache(); /* Finalize our powerdown and wait for an interrupt. */ FinalizePowerOff(); } void ValidateSocStateForSuspend() { /* Validate that all other cores are off. */ AMS_ABORT_UNLESS(reg::HasValue(PMC + APBDEV_PMC_PWRGATE_STATUS, PMC_REG_BITS_VALUE(PWRGATE_STATUS_CE123, 0))); /* Validate that the bpmp is appropriately halted. */ const bool jtag = IsJtagEnabled(); AMS_ABORT_UNLESS(reg::Read(FLOW_CTLR + FLOW_CTLR_HALT_COP_EVENTS) == reg::Encode(FLOW_REG_BITS_ENUM (HALT_COP_EVENTS_MODE, FLOW_MODE_STOP), FLOW_REG_BITS_ENUM_SEL(HALT_COP_EVENTS_JTAG, jtag, ENABLED, DISABLED))); /* Further validations aren't guaranteed on < 6.0.0. */ if (GetTargetFirmware() < TargetFirmware_6_0_0) { return; } /* Validate that USB2, APB-DMA, AHB-DMA are held in reset. */ AMS_ABORT_UNLESS(reg::HasValue(CLK_RST + CLK_RST_CONTROLLER_RST_DEVICES_H, CLK_RST_REG_BITS_ENUM(RST_DEVICES_H_SWR_USB2_RST, ENABLE), CLK_RST_REG_BITS_ENUM(RST_DEVICES_H_SWR_APBDMA_RST, ENABLE), CLK_RST_REG_BITS_ENUM(RST_DEVICES_H_SWR_AHBDMA_RST, ENABLE))); /* Validate that USBD is held in reset. */ AMS_ABORT_UNLESS(reg::HasValue(CLK_RST + CLK_RST_CONTROLLER_RST_DEVICES_L, CLK_RST_REG_BITS_ENUM(RST_DEVICES_L_SWR_USBD_RST, ENABLE))); /* Validate that AHB-DMA, USB, USB2, COP are not allowed to arbitrate on the AHB. */ AMS_ABORT_UNLESS(reg::HasValue(AHB_ARBC + AHB_ARBITRATION_DISABLE, AHB_REG_BITS_ENUM(ARBITRATION_DISABLE_COP, DISABLE), AHB_REG_BITS_ENUM(ARBITRATION_DISABLE_AHBDMA, DISABLE), AHB_REG_BITS_ENUM(ARBITRATION_DISABLE_USB, DISABLE), AHB_REG_BITS_ENUM(ARBITRATION_DISABLE_USB2, DISABLE))); /* Validate that the GPIO controller has clock enabled. */ AMS_ABORT_UNLESS(reg::HasValue(CLK_RST + CLK_RST_CONTROLLER_CLK_OUT_ENB_L, CLK_RST_REG_BITS_ENUM(CLK_OUT_ENB_L_CLK_ENB_GPIO, ENABLE))); /* Validate that both FUSE and KFUSE have clock enabled. */ AMS_ABORT_UNLESS(reg::HasValue(CLK_RST + CLK_RST_CONTROLLER_CLK_OUT_ENB_H, CLK_RST_REG_BITS_ENUM(CLK_OUT_ENB_H_CLK_ENB_FUSE, ENABLE), CLK_RST_REG_BITS_ENUM(CLK_OUT_ENB_H_CLK_ENB_KFUSE, ENABLE))); /* Validate that all of IRAM has clock enabled. */ AMS_ABORT_UNLESS(reg::HasValue(CLK_RST + CLK_RST_CONTROLLER_CLK_OUT_ENB_U, CLK_RST_REG_BITS_ENUM(CLK_OUT_ENB_U_CLK_ENB_IRAMA, ENABLE), CLK_RST_REG_BITS_ENUM(CLK_OUT_ENB_U_CLK_ENB_IRAMB, ENABLE), CLK_RST_REG_BITS_ENUM(CLK_OUT_ENB_U_CLK_ENB_IRAMC, ENABLE), CLK_RST_REG_BITS_ENUM(CLK_OUT_ENB_U_CLK_ENB_IRAMD, ENABLE))); /* Validate that ACTMON has clock enabled. */ AMS_ABORT_UNLESS(reg::HasValue(CLK_RST + CLK_RST_CONTROLLER_CLK_OUT_ENB_V, CLK_RST_REG_BITS_ENUM(CLK_OUT_ENB_V_CLK_ENB_ACTMON, ENABLE))); /* Validate that ENTROPY has clock enabled. */ AMS_ABORT_UNLESS(reg::HasValue(CLK_RST + CLK_RST_CONTROLLER_CLK_OUT_ENB_W, CLK_RST_REG_BITS_ENUM(CLK_OUT_ENB_W_CLK_ENB_ENTROPY, ENABLE))); } void GenerateCryptographicallyRandomBytes(void * const dst, int size) { /* Flush the region we're about to fill to ensure consistency with the SE. */ hw::FlushDataCache(dst, size); hw::DataSynchronizationBarrierInnerShareable(); /* Generate random bytes. */ se::GenerateRandomBytes(dst, size); hw::DataSynchronizationBarrierInnerShareable(); /* Flush to ensure the CPU sees consistent data for the region. */ hw::FlushDataCache(dst, size); hw::DataSynchronizationBarrierInnerShareable(); } void SaveSecureContextForErista() { /* Generate a random key source. */ util::AlignedBuffer<hw::DataCacheLineSize, se::AesBlockSize> key_source; GenerateCryptographicallyRandomBytes(key_source, se::AesBlockSize); const u32 * const key_source_32 = reinterpret_cast<const u32 *>(static_cast<u8 *>(key_source)); /* Ensure that the key source registers are not locked. */ AMS_ABORT_UNLESS(pmc::GetSecureRegisterLockState(pmc::SecureRegister_KeySourceReadWrite) != pmc::LockState::Locked); /* Write the key source, lock writes to the key source, and verify that the key source is write-locked. */ reg::Write(PMC + APBDEV_PMC_SECURE_SCRATCH24, key_source_32[0]); reg::Write(PMC + APBDEV_PMC_SECURE_SCRATCH25, key_source_32[1]); reg::Write(PMC + APBDEV_PMC_SECURE_SCRATCH26, key_source_32[2]); reg::Write(PMC + APBDEV_PMC_SECURE_SCRATCH27, key_source_32[3]); pmc::LockSecureRegister(pmc::SecureRegister_KeySourceWrite); AMS_ABORT_UNLESS(pmc::GetSecureRegisterLockState(pmc::SecureRegister_KeySourceWrite) == pmc::LockState::Locked); /* Verify the key source is correct in registers, and read-lock the key source registers. */ AMS_ABORT_UNLESS(reg::Read(PMC + APBDEV_PMC_SECURE_SCRATCH24) == key_source_32[0]); AMS_ABORT_UNLESS(reg::Read(PMC + APBDEV_PMC_SECURE_SCRATCH25) == key_source_32[1]); AMS_ABORT_UNLESS(reg::Read(PMC + APBDEV_PMC_SECURE_SCRATCH26) == key_source_32[2]); AMS_ABORT_UNLESS(reg::Read(PMC + APBDEV_PMC_SECURE_SCRATCH27) == key_source_32[3]); pmc::LockSecureRegister(pmc::SecureRegister_KeySourceRead); /* Ensure that the key source registers are locked. */ AMS_ABORT_UNLESS(pmc::GetSecureRegisterLockState(pmc::SecureRegister_KeySourceReadWrite) == pmc::LockState::Locked); /* Generate a random kek into keyslot 2. */ se::SetRandomKey(pkg1::AesKeySlot_TzramSaveKek); /* Verify that the se is in a validate state, context save, and validate again. */ { se::ValidateErrStatus(); ON_SCOPE_EXIT { se::ValidateErrStatus(); }; { /* Transition to non-secure mode for the duration of the context save operation. */ se::SetSecure(false); ON_SCOPE_EXIT { se::SetSecure(true); }; /* Get a pointer to the context storage. */ se::Context * const context = MemoryRegionVirtualDramSecureDataStoreSecurityEngineState.GetPointer<se::Context>(); static_assert(MemoryRegionVirtualDramSecureDataStoreSecurityEngineState.GetSize() == sizeof(*context)); /* Save the context. */ se::SaveContext(context); /* Ensure that the cpu sees consistent data. */ hw::FlushDataCache(context, sizeof(*context)); hw::DataSynchronizationBarrierInnerShareable(); /* Write the context pointer to pmc scratch, so that the bootrom will restore it on wake. */ reg::Write(PMC + APBDEV_PMC_SCRATCH43, MemoryRegionPhysicalDramSecureDataStoreSecurityEngineState.GetAddress()); } } /* Clear keyslot 3, and then derive the save key. */ se::ClearAesKeySlot(pkg1::AesKeySlot_TzramSaveKey); se::SetEncryptedAesKey256(pkg1::AesKeySlot_TzramSaveKey, pkg1::AesKeySlot_TzramSaveKek, key_source, se::AesBlockSize); /* Declare a temporary block to be used as both iv and mac. */ u32 temp_block[se::AesBlockSize / sizeof(u32)] = {}; /* Ensure that the SE sees consistent data for tzram. */ const void * const tzram_save_src = MemoryRegionVirtualTzramReadOnlyAlias.GetPointer<u8>() + MemoryRegionVirtualTzramVolatileData.GetSize() + MemoryRegionVirtualTzramVolatileStack.GetSize(); void * const tzram_save_dst = MemoryRegionVirtualIramSc7Work.GetPointer<void>(); constexpr size_t TzramSaveSize = MemoryRegionVirtualDramSecureDataStoreTzram.GetSize(); hw::FlushDataCache(tzram_save_src, TzramSaveSize); hw::FlushDataCache(tzram_save_dst, TzramSaveSize); hw::DataSynchronizationBarrierInnerShareable(); /* Encrypt tzram using our random key. */ se::EncryptAes256Cbc(tzram_save_dst, TzramSaveSize, pkg1::AesKeySlot_TzramSaveKey, tzram_save_src, TzramSaveSize, temp_block, se::AesBlockSize); hw::FlushDataCache(tzram_save_dst, TzramSaveSize); hw::DataSynchronizationBarrierInnerShareable(); /* Copy the data from work space to the secure storage destination. */ void * const tzram_store_dst = MemoryRegionVirtualDramSecureDataStoreTzram.GetPointer<void>(); std::memcpy(tzram_store_dst, tzram_save_dst, TzramSaveSize); hw::FlushDataCache(tzram_store_dst, TzramSaveSize); hw::DataSynchronizationBarrierInnerShareable(); /* Compute cmac of tzram into our temporary block. */ se::ComputeAes256Cmac(temp_block, se::AesBlockSize, pkg1::AesKeySlot_TzramSaveKey, tzram_save_src, TzramSaveSize); /* Ensure that the cmac registers are not locked. */ AMS_ABORT_UNLESS(pmc::GetSecureRegisterLockState(pmc::SecureRegister_CmacReadWrite) != pmc::LockState::Locked); /* Write the cmac, lock writes to the cmac, and verify that the cmac is write-locked. */ reg::Write(PMC + APBDEV_PMC_SECURE_SCRATCH112, temp_block[0]); reg::Write(PMC + APBDEV_PMC_SECURE_SCRATCH113, temp_block[1]); reg::Write(PMC + APBDEV_PMC_SECURE_SCRATCH114, temp_block[2]); reg::Write(PMC + APBDEV_PMC_SECURE_SCRATCH115, temp_block[3]); pmc::LockSecureRegister(pmc::SecureRegister_CmacWrite); AMS_ABORT_UNLESS(pmc::GetSecureRegisterLockState(pmc::SecureRegister_CmacWrite) == pmc::LockState::Locked); /* Verify the key source is correct in registers, and read-lock the key source registers. */ AMS_ABORT_UNLESS(reg::Read(PMC + APBDEV_PMC_SECURE_SCRATCH112) == temp_block[0]); AMS_ABORT_UNLESS(reg::Read(PMC + APBDEV_PMC_SECURE_SCRATCH113) == temp_block[1]); AMS_ABORT_UNLESS(reg::Read(PMC + APBDEV_PMC_SECURE_SCRATCH114) == temp_block[2]); AMS_ABORT_UNLESS(reg::Read(PMC + APBDEV_PMC_SECURE_SCRATCH115) == temp_block[3]); pmc::LockSecureRegister(pmc::SecureRegister_CmacRead); /* Ensure that the key source registers are locked. */ AMS_ABORT_UNLESS(pmc::GetSecureRegisterLockState(pmc::SecureRegister_CmacReadWrite) == pmc::LockState::Locked); } void SaveSecureContextForMariko() { /* Save security engine context to TZRAM SE carveout (inaccessible to cpu). */ se::SaveContextAutomatic(); /* Save TZRAM to shadow-TZRAM in always-on power domain. */ se::SaveTzramAutomatic(); } void SaveSecureContext() { /* Save the appropriate secure context. */ const auto soc_type = GetSocType(); if (soc_type == fuse::SocType_Erista) { SaveSecureContextForErista(); } else /* if (soc_type == fuse::SocType_Mariko) */ { SaveSecureContextForMariko(); } /* Save the debug code. */ #if defined(AMS_BUILD_FOR_DEBUGGING) || defined(AMS_BUILD_FOR_AUDITING) { const void * const debug_code_src = MemoryRegionVirtualDebugCode.GetPointer<void>(); void * const debug_code_dst = MemoryRegionVirtualDramDebugDataStore.GetPointer<void>(); std::memcpy(debug_code_dst, debug_code_src, MemoryRegionVirtualDebugCode.GetSize()); hw::FlushDataCache(debug_code_dst, MemoryRegionVirtualDebugCode.GetSize()); hw::DataSynchronizationBarrierInnerShareable(); } #endif } void LoadAndStartSc7BpmpFirmware() { /* Set BPMP reset. */ reg::Write(CLK_RST + CLK_RST_CONTROLLER_RST_DEV_L_SET, CLK_RST_REG_BITS_ENUM(RST_DEV_L_SET_SET_COP_RST, ENABLE)); /* Set the PMC as insecure, so that the BPMP firmware can access it. */ reg::ReadWrite(APB_MISC + APB_MISC_SECURE_REGS_APB_SLAVE_SECURITY_ENABLE_REG0_0, SLAVE_SECURITY_REG_BITS_ENUM(0, PMC, DISABLE)); /* Set the exception vectors for the bpmp. RESET should point to RESET, all others should point to generic exception/panic. */ constexpr const u32 Sc7FirmwareResetVector = static_cast<u32>(MemoryRegionPhysicalIramSc7Firmware.GetAddress() + 0x0); constexpr const u32 Sc7FirmwarePanicVector = static_cast<u32>(MemoryRegionPhysicalIramSc7Firmware.GetAddress() + 0x4); reg::Write(EVP + EVP_COP_RESET_VECTOR, Sc7FirmwareResetVector); reg::Write(EVP + EVP_COP_UNDEF_VECTOR, Sc7FirmwarePanicVector); reg::Write(EVP + EVP_COP_SWI_VECTOR, Sc7FirmwarePanicVector); reg::Write(EVP + EVP_COP_PREFETCH_ABORT_VECTOR, Sc7FirmwarePanicVector); reg::Write(EVP + EVP_COP_DATA_ABORT_VECTOR, Sc7FirmwarePanicVector); reg::Write(EVP + EVP_COP_RSVD_VECTOR, Sc7FirmwarePanicVector); reg::Write(EVP + EVP_COP_IRQ_VECTOR, Sc7FirmwarePanicVector); reg::Write(EVP + EVP_COP_FIQ_VECTOR, Sc7FirmwarePanicVector); /* Disable activity monitor bpmp monitoring, so that we don't panic upon bpmp wake. */ actmon::StopMonitoringBpmp(); /* Load the bpmp firmware. */ void * const sc7fw_load_address = MemoryRegionVirtualIramSc7Firmware.GetPointer<void>(); std::memcpy(sc7fw_load_address, sc7fw_bin, sc7fw_bin_size); hw::FlushDataCache(sc7fw_load_address, sc7fw_bin_size); hw::DataSynchronizationBarrierInnerShareable(); /* Ensure that the bpmp firmware was loaded. */ AMS_ABORT_UNLESS(crypto::IsSameBytes(sc7fw_load_address, sc7fw_bin, sc7fw_bin_size)); /* Clear BPMP reset. */ reg::Write(CLK_RST + CLK_RST_CONTROLLER_RST_DEV_L_CLR, CLK_RST_REG_BITS_ENUM(RST_DEV_L_CLR_CLR_COP_RST, ENABLE)); /* Start the bpmp. */ reg::Write(FLOW_CTLR + FLOW_CTLR_HALT_COP_EVENTS, FLOW_REG_BITS_ENUM(HALT_COP_EVENTS_MODE, FLOW_MODE_NONE)); } void SaveSecureContextAndSuspend() { /* Ensure there are no pending memory transactions before we continue */ FlushEntireDataCache(); hw::DataSynchronizationBarrierInnerShareable(); /* Save all secure context (security engine state + tzram). */ SaveSecureContext(); /* Load and start the sc7 firmware on the bpmp. */ if (GetTargetFirmware() >= TargetFirmware_2_0_0) { LoadAndStartSc7BpmpFirmware(); } /* Log our suspension. */ /* NOTE: Nintendo only does this on dev, but we will always do it. */ if (true /* !pkg1::IsProduction() */) { log::Initialize(secmon::GetLogPort(), secmon::GetLogBaudRate(), secmon::GetLogFlags()); log::SendText("OYASUMI\n", 8); log::Flush(); } /* If we're on erista, configure the bootrom to allow our custom warmboot firmware. */ if (GetSocType() == fuse::SocType_Erista) { reg::Write(PMC + APBDEV_PMC_SCRATCH31, 0x2202E012); reg::Write(PMC + APBDEV_PMC_SCRATCH32, 0x6001DC28); } /* Finalize our powerdown and wait for an interrupt. */ FinalizePowerOff(); } SmcResult SuspendCpuImpl(SmcArguments &args) { /* Decode arguments. */ const util::BitPack32 power_state = { static_cast<u32>(args.r[1]) }; const uintptr_t entry_point = args.r[2]; const uintptr_t context_id = args.r[3]; const auto state_type = power_state.Get<SuspendCpuPowerState::StateType>(); const auto state_id = power_state.Get<SuspendCpuPowerState::StateId>(); const auto core_id = hw::GetCurrentCoreId(); /* Validate arguments. */ SMC_R_UNLESS(state_type == PowerStateType_PowerDown, PsciDenied); SMC_R_UNLESS(state_id == PowerStateId_Sc7, PsciDenied); /* Orchestrate charger transition to Hi-Z mode if needed. */ if (IsChargerHiZModeEnabled()) { /* Ensure we can do comms over i2c-1. */ clkrst::EnableI2c1Clock(); /* If the charger isn't in hi-z mode, perform a transition. */ if (!charger::IsHiZMode()) { charger::EnterHiZMode(); /* Wait up to 50ms for the transition to complete. */ const auto start_time = util::GetMicroSeconds(); auto current_time = start_time; while ((current_time - start_time) <= 50'000) { if (auto intr_status = reg::Read(GPIO + 0x634); (intr_status & 1) == 0) { /* Wait 256 us to ensure the transition completes. */ util::WaitMicroSeconds(256); break; } current_time = util::GetMicroSeconds(); } } /* Disable i2c-1, since we're done communicating over it. */ clkrst::DisableI2c1Clock(); } /* Enable wake event detection. */ pmc::EnableWakeEventDetection(); /* Ensure that i2c-5 is usable for communicating with the pmic. */ clkrst::EnableI2c5Clock(); i2c::Initialize(i2c::Port_5); /* Orchestrate sleep entry with the pmic. */ pmic::EnableSleep(); /* Ensure that the soc is in a state valid for us to suspend. */ if (GetTargetFirmware() >= TargetFirmware_2_0_0) { ValidateSocStateForSuspend(); } /* Configure the pmc for sc7 entry. */ pmc::ConfigureForSc7Entry(); /* Configure the flow controller for sc7 entry. */ flow::SetCc4Ctrl(core_id, 0); flow::SetHaltCpuEvents(core_id, false); flow::ClearL2FlushControl(); flow::SetCpuCsr(core_id, FLOW_CTLR_CPUN_CSR_ENABLE_EXT_POWERGATE_CPU_TURNOFF_CPURAIL); /* Save the entry context. */ SetEntryContext(core_id, entry_point, context_id); /* Configure the cpu context for reset. */ SaveDebugRegisters(); SetCoreOff(); SetResetExpected(true); /* Switch to use the common smc stack (all other cores are off), and perform suspension. */ PivotStackAndInvoke(reinterpret_cast<void *>(CommonSmcStackTop), SaveSecureContextAndSuspend); /* This code will never be reached. */ __builtin_unreachable(); } } void PowerOffCpu() { /* Get the current core id. */ const auto core_id = hw::GetCurrentCoreId(); /* Note that we're expecting a reset for the current core. */ SetResetExpected(true); /* If we're on the final core, shut down directly. Otherwise, invoke with special stack. */ if (core_id == NumCores - 1) { PowerOffCpuImpl(); } else { PivotStackAndInvoke(GetCoreExceptionStackVirtual(), PowerOffCpuImpl); } /* This code will never be reached. */ __builtin_unreachable(); } SmcResult SmcPowerOffCpu(SmcArguments &args) { AMS_UNUSED(args); PowerOffCpu(); } SmcResult SmcPowerOnCpu(SmcArguments &args) { /* Get and validate the core to power on. */ const int which_core = args.r[1]; SMC_R_UNLESS(0 <= which_core && which_core < NumCores, PsciInvalidParameters); /* Ensure the core isn't already on. */ SMC_R_UNLESS(!IsCoreOn(which_core), PsciAlreadyOn); /* Save the entry context. */ SetEntryContext(which_core, args.r[2], args.r[3]); /* Reset the cpu. */ ResetCpu(which_core); /* Turn on the core. */ PowerOnCpu(CpuPowerGateStatusMasks[which_core], CpuPowerGateTogglePartitionIds[which_core]); /* Start the core. */ StartCpu(which_core); return SmcResult::PsciSuccess; } SmcResult SmcSuspendCpu(SmcArguments &args) { return LockSecurityEngineAndInvoke(args, SuspendCpuImpl); } bool IsChargerHiZModeEnabled() { return g_charger_hi_z_mode_enabled; } void SetChargerHiZModeEnabled(bool en) { g_charger_hi_z_mode_enabled = en; } }
28,067
C++
.cpp
445
48.498876
202
0.599673
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,345
secmon_smc_memory_access.cpp
Atmosphere-NX_Atmosphere/exosphere/program/source/smc/secmon_smc_memory_access.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 <exosphere.hpp> #include "../secmon_error.hpp" #include "../secmon_page_mapper.hpp" #include "secmon_smc_memory_access.hpp" namespace ams::secmon::smc { namespace { enum IramCopyType { IramCopyType_FromIramToDram = 0, IramCopyType_FromDramToIram = 1, IramCopyType_Count, }; struct IramCopyOption { using CopyType = util::BitPack32::Field<0, 1, IramCopyType>; }; } /* This is an atmosphere extension smc. */ SmcResult SmcIramCopy(SmcArguments &args) { /* Decode arguments. */ const uintptr_t dram_address = args.r[1]; const uintptr_t iram_address = args.r[2]; const size_t size = args.r[3]; const util::BitPack32 option = { static_cast<u32>(args.r[4]) }; const auto copy_type = option.Get<IramCopyOption::CopyType>(); /* Validate arguments. */ SMC_R_UNLESS(copy_type < IramCopyType_Count, InvalidArgument); { /* Map the pages. */ AtmosphereUserPageMapper dram_mapper(dram_address); AtmosphereIramPageMapper iram_mapper(iram_address); SMC_R_UNLESS(dram_mapper.Map(), InvalidArgument); SMC_R_UNLESS(iram_mapper.Map(), InvalidArgument); /* Get the ranges we're copying. */ const void * const src = (copy_type == IramCopyType_FromIramToDram) ? iram_mapper.GetPointerTo(iram_address, size) : dram_mapper.GetPointerTo(dram_address, size); void * const dst = (copy_type == IramCopyType_FromIramToDram) ? dram_mapper.GetPointerTo(dram_address, size) : iram_mapper.GetPointerTo(iram_address, size); SMC_R_UNLESS(src != nullptr, InvalidArgument); SMC_R_UNLESS(dst != nullptr, InvalidArgument); /* Copy the data. */ std::memcpy(dst, src, size); } return SmcResult::Success; } SmcResult SmcWriteAddress(SmcArguments &args) { /* NOTE: This smc was deprecated in Atmosphère 0.13.0. */ AMS_UNUSED(args); return SmcResult::NotSupported; } }
2,764
C++
.cpp
62
37.129032
174
0.653388
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,346
secmon_smc_handler.cpp
Atmosphere-NX_Atmosphere/exosphere/program/source/smc/secmon_smc_handler.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 <exosphere.hpp> #include "../secmon_error.hpp" #include "../secmon_misc.hpp" #include "secmon_smc_common.hpp" #include "secmon_smc_handler.hpp" #include "secmon_smc_aes.hpp" #include "secmon_smc_carveout.hpp" #include "secmon_smc_device_unique_data.hpp" #include "secmon_smc_error.hpp" #include "secmon_smc_info.hpp" #include "secmon_smc_memory_access.hpp" #include "secmon_smc_power_management.hpp" #include "secmon_smc_random.hpp" #include "secmon_smc_register_access.hpp" #include "secmon_smc_result.hpp" #include "secmon_smc_rsa.hpp" namespace ams::secmon::smc { namespace { struct HandlerInfo { u32 function_id; u32 restriction_mask; SmcHandler handler; }; struct HandlerTable { const HandlerInfo *entries; size_t count; }; enum HandlerType : int { HandlerType_User = 0, HandlerType_Kern = 1, HandlerType_Count = 2, }; enum Restriction { Restriction_None = (0 << 0), Restriction_Normal = (1 << 0), Restriction_DeviceUniqueDataNotAllowed = (1 << 1), Restriction_SafeModeNotAllowed = (1 << 2), }; enum SmcCallRange { SmcCallRange_ArmArch = 0, SmcCallRange_Cpu = 1, SmcCallRange_Sip = 2, SmcCallRange_Oem = 3, SmcCallRange_Standard = 4, SmcCallRange_TrustedApp = 0x30, }; enum SmcArgumentType { ArgumentType_Integer = 0, ArgumentType_Pointer = 1, }; enum SmcConvention { Convention_Smc32 = 0, Convention_Smc64 = 1, }; enum SmcCallType { SmcCallType_YieldingCall = 0, SmcCallType_FastCall = 1, }; struct SmcFunctionId { using FunctionId = util::BitPack64::Field< 0, 8, u32>; using ArgumentType0 = util::BitPack64::Field< 8, 1, SmcArgumentType>; using ArgumentType1 = util::BitPack64::Field< 9, 1, SmcArgumentType>; using ArgumentType2 = util::BitPack64::Field<10, 1, SmcArgumentType>; using ArgumentType3 = util::BitPack64::Field<11, 1, SmcArgumentType>; using ArgumentType4 = util::BitPack64::Field<12, 1, SmcArgumentType>; using ArgumentType5 = util::BitPack64::Field<13, 1, SmcArgumentType>; using ArgumentType6 = util::BitPack64::Field<14, 1, SmcArgumentType>; using ArgumentType7 = util::BitPack64::Field<15, 1, SmcArgumentType>; using Reserved = util::BitPack64::Field<16, 8, u32>; using CallRange = util::BitPack64::Field<24, 6, SmcCallRange>; using Convention = util::BitPack64::Field<30, 1, SmcConvention>; using CallType = util::BitPack64::Field<31, 1, SmcCallType>; using Reserved2 = util::BitPack64::Field<32, 32, u32>; }; constinit HandlerInfo g_user_handlers[] = { { 0x00000000, Restriction_SafeModeNotAllowed, nullptr }, { 0xC3000401, Restriction_SafeModeNotAllowed, SmcSetConfig }, { 0xC3000002, Restriction_Normal, SmcGetConfigUser }, { 0xC3000003, Restriction_Normal, SmcGetResult }, { 0xC3000404, Restriction_Normal, SmcGetResultData }, { 0xC3000E05, Restriction_SafeModeNotAllowed, SmcModularExponentiate }, { 0xC3000006, Restriction_Normal, SmcGenerateRandomBytes }, { 0xC3000007, Restriction_Normal, SmcGenerateAesKek }, { 0xC3000008, Restriction_Normal, SmcLoadAesKey }, { 0xC3000009, Restriction_Normal, SmcComputeAes }, { 0xC300000A, Restriction_Normal, SmcGenerateSpecificAesKey }, { 0xC300040B, Restriction_Normal, SmcComputeCmac }, { 0xC300D60C, Restriction_Normal, SmcReencryptDeviceUniqueData }, { 0xC300100D, Restriction_DeviceUniqueDataNotAllowed, SmcDecryptDeviceUniqueData }, { 0xC300000E, Restriction_SafeModeNotAllowed, nullptr }, { 0xC300060F, Restriction_DeviceUniqueDataNotAllowed, SmcModularExponentiateByStorageKey }, { 0xC3000610, Restriction_SafeModeNotAllowed, SmcPrepareEsDeviceUniqueKey }, { 0xC3000011, Restriction_SafeModeNotAllowed, SmcLoadPreparedAesKey }, { 0xC3000012, Restriction_SafeModeNotAllowed, SmcPrepareEsCommonTitleKey } }; /* Deprecated handlerss. */ constexpr inline const HandlerInfo DecryptAndImportEsDeviceKeyHandlerInfo = { 0xC300100C, Restriction_Normal, SmcDecryptAndImportEsDeviceKey }; constexpr inline const HandlerInfo DecryptAndImportLotusKeyHandlerInfo = { 0xC300100E, Restriction_SafeModeNotAllowed, SmcDecryptAndImportLotusKey }; constinit HandlerInfo g_kern_handlers[] = { { 0x00000000, Restriction_SafeModeNotAllowed, nullptr }, { 0xC4000001, Restriction_SafeModeNotAllowed, SmcSuspendCpu }, { 0x84000002, Restriction_SafeModeNotAllowed, SmcPowerOffCpu }, { 0xC4000003, Restriction_SafeModeNotAllowed, SmcPowerOnCpu }, { 0xC3000004, Restriction_Normal, SmcGetConfigKern }, { 0xC3000005, Restriction_Normal, SmcGenerateRandomBytesNonBlocking }, { 0xC3000006, Restriction_Normal, SmcShowError }, { 0xC3000007, Restriction_Normal, SmcSetKernelCarveoutRegion }, { 0xC3000008, Restriction_Normal, SmcReadWriteRegister }, /* NOTE: Atmosphere extension for mesosphere. This ID is subject to change at any time. */ { 0xC3000409, Restriction_Normal, SmcSetConfig }, }; constinit HandlerInfo g_ams_handlers[] = { { 0x00000000, Restriction_SafeModeNotAllowed, nullptr }, { 0xF0000201, Restriction_None, SmcIramCopy }, { 0xF0000002, Restriction_None, SmcReadWriteRegister }, { 0xF0000003, Restriction_None, SmcWriteAddress }, { 0xF0000404, Restriction_None, SmcGetEmummcConfig }, }; constexpr const HandlerInfo GetSecureDataHandlerInfo = { 0x67891234, Restriction_None, SmcGetSecureData }; constinit HandlerTable g_handler_tables[] = { { g_user_handlers, util::size(g_user_handlers) }, { g_kern_handlers, util::size(g_kern_handlers) }, }; constinit HandlerTable g_ams_handler_table = { g_ams_handlers, util::size(g_ams_handlers) }; NORETURN void InvalidSmcError(u64 id) { SetError(pkg1::ErrorInfo_UnknownSmc); AMS_ABORT("Invalid SMC: %lx", id); } const HandlerTable &GetHandlerTable(HandlerType type, u64 id) { /* Ensure we have a valid handler type. */ if (AMS_UNLIKELY(!(0 <= type && type < HandlerType_Count))) { InvalidSmcError(id); } /* Provide support for legacy SmcGetSecureData. */ if (id == GetSecureDataHandlerInfo.function_id) { return g_handler_tables[HandlerType_User]; } /* Check if we're a user SMC. */ if (type == HandlerType_User) { /* Nintendo uses OEM SMCs. */ /* We will assign Atmosphere extension SMCs the TrustedApplication range. */ if (util::BitPack64{id}.Get<SmcFunctionId::CallRange>() == SmcCallRange_TrustedApp) { return g_ams_handler_table; } /* If we're not performing an atmosphere extension smc, require that we're being invoked by spl on core 3. */ if (AMS_UNLIKELY(hw::GetCurrentCoreId() != 3)) { InvalidSmcError(id); } } return g_handler_tables[type]; } const HandlerInfo &GetHandlerInfo(const HandlerTable &table, u64 id) { /* Provide support for legacy SmcGetSecureData. */ if (id == GetSecureDataHandlerInfo.function_id) { return GetSecureDataHandlerInfo; } /* Get and check the index. */ const auto index = util::BitPack64{id}.Get<SmcFunctionId::FunctionId>(); if (AMS_UNLIKELY(index >= table.count)) { InvalidSmcError(id); } /* Get and check the handler info. */ const auto &handler_info = table.entries[index]; /* Check that the handler isn't null. */ if (AMS_UNLIKELY(handler_info.handler == nullptr)) { InvalidSmcError(id); } /* Check that the handler's id matches. */ if (AMS_UNLIKELY(handler_info.function_id != id)) { InvalidSmcError(id); } return handler_info; } bool IsHandlerRestricted(const HandlerInfo &info) { return (info.restriction_mask & secmon::GetRestrictedSmcMask()) != 0; } SmcResult InvokeSmcHandler(const HandlerInfo &info, SmcArguments &args) { /* Check if the smc is restricted. */ if (GetTargetFirmware() >= TargetFirmware_8_0_0 && AMS_UNLIKELY(IsHandlerRestricted(info))) { return SmcResult::NotPermitted; } /* Invoke the smc. */ return info.handler(args); } } void ConfigureSmcHandlersForTargetFirmware() { const auto target_fw = GetTargetFirmware(); if (target_fw < TargetFirmware_5_0_0) { g_user_handlers[DecryptAndImportEsDeviceKeyHandlerInfo.function_id & 0xFF] = DecryptAndImportEsDeviceKeyHandlerInfo; g_user_handlers[DecryptAndImportLotusKeyHandlerInfo.function_id & 0xFF] = DecryptAndImportLotusKeyHandlerInfo; } } void HandleSmc(int type, SmcArguments &args) { /* Get the table. */ const auto &table = GetHandlerTable(static_cast<HandlerType>(type), args.r[0]); /* Get the handler info. */ const auto &info = GetHandlerInfo(table, args.r[0]); /* Set the invocation result. */ args.r[0] = static_cast<u64>(InvokeSmcHandler(info, args)); } }
11,838
C++
.cpp
224
42.200893
128
0.576528
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,347
secmon_smc_random.cpp
Atmosphere-NX_Atmosphere/exosphere/program/source/smc/secmon_smc_random.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 <exosphere.hpp> #include "../secmon_error.hpp" #include "secmon_smc_random.hpp" #include "secmon_random_cache.hpp" #include "secmon_smc_se_lock.hpp" namespace ams::secmon::smc { namespace { SmcResult GenerateRandomBytesImpl(SmcArguments &args) { /* Validate the input size. */ const size_t size = args.r[1]; SMC_R_UNLESS(size <= MaxRandomBytes, InvalidArgument); /* Create a buffer that the se can generate bytes into. */ util::AlignedBuffer<hw::DataCacheLineSize, MaxRandomBytes> buffer; hw::FlushDataCache(buffer, size); hw::DataSynchronizationBarrierInnerShareable(); /* Generate random bytes into the buffer. */ se::GenerateRandomBytes(buffer, size); /* Ensure that the cpu sees consistent data. */ hw::DataSynchronizationBarrierInnerShareable(); hw::FlushDataCache(buffer, size); hw::DataSynchronizationBarrierInnerShareable(); /* Copy the bytes to output. */ std::memcpy(std::addressof(args.r[1]), buffer, size); return SmcResult::Success; } } SmcResult SmcGenerateRandomBytes(SmcArguments &args) { return LockSecurityEngineAndInvoke(args, GenerateRandomBytesImpl); } SmcResult SmcGenerateRandomBytesNonBlocking(SmcArguments &args) { /* Try to lock the security engine, so that we can call the standard impl. */ if (TryLockSecurityEngine()) { /* Ensure we unlock the security engine when done. */ ON_SCOPE_EXIT { UnlockSecurityEngine(); }; /* Take advantage of our lock to refill lthe random cache. */ ON_SCOPE_EXIT { RefillRandomCache(); }; /* If we lock it successfully, we can just call the blocking impl. */ return GenerateRandomBytesImpl(args); } else { /* Otherwise, we'll retrieve some bytes from the cache. */ const size_t size = args.r[1]; SMC_R_UNLESS(size <= MaxRandomBytes, InvalidArgument); /* Get random bytes from the cache. */ GetRandomFromCache(std::addressof(args.r[1]), size); return SmcResult::Success; } } }
2,909
C++
.cpp
63
38.126984
85
0.658898
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,348
secmon_smc_rsa.cpp
Atmosphere-NX_Atmosphere/exosphere/program/source/smc/secmon_smc_rsa.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 <exosphere.hpp> #include "../secmon_error.hpp" #include "../secmon_key_storage.hpp" #include "../secmon_page_mapper.hpp" #include "secmon_smc_aes.hpp" #include "secmon_smc_rsa.hpp" #include "secmon_smc_se_lock.hpp" namespace ams::secmon::smc { namespace { struct ModularExponentiateByStorageKeyOption { using Mode = util::BitPack32::Field<0, 2, u32>; using Reserved = util::BitPack32::Field<2, 30, u32>; }; struct PrepareEsDeviceUniqueKeyOption { using KeyGeneration = util::BitPack32::Field<0, 6, int>; using Type = util::BitPack32::Field<6, 2, EsCommonKeyType>; using Reserved = util::BitPack32::Field<8, 24, u32>; }; constexpr const u8 ModularExponentiateByStorageKeyTable[] = { static_cast<u8>(ImportRsaKey_Lotus), static_cast<u8>(ImportRsaKey_Ssl), static_cast<u8>(ImportRsaKey_EsClientCert), }; constexpr size_t ModularExponentiateByStorageKeyTableSize = util::size(ModularExponentiateByStorageKeyTable); consteval u32 GetModeForImportRsaKey(ImportRsaKey import_key) { for (size_t i = 0; i < ModularExponentiateByStorageKeyTableSize; ++i) { if (static_cast<ImportRsaKey>(ModularExponentiateByStorageKeyTable[i]) == import_key) { return i; } } AMS_ASSUME(false); } class PrepareEsDeviceUniqueKeyAsyncArguments { private: int m_generation; EsCommonKeyType m_type; u8 m_label_digest[crypto::Sha256Generator::HashSize]; public: void Set(int gen, EsCommonKeyType t, const u8 ld[crypto::Sha256Generator::HashSize]) { m_generation = gen; m_type = t; std::memcpy(m_label_digest, ld, sizeof(m_label_digest)); } int GetKeyGeneration() const { return m_generation; } EsCommonKeyType GetCommonKeyType() const { return m_type; } void GetLabelDigest(u8 dst[crypto::Sha256Generator::HashSize]) const { std::memcpy(dst, m_label_digest, sizeof(m_label_digest)); } }; class ModularExponentiateByStorageKeyAsyncArguments { private: u8 m_msg[se::RsaSize]; public: void Set(const void *m, size_t m_size) { AMS_UNUSED(m_size); std::memcpy(m_msg, m, sizeof(m_msg)); } const u8 *GetMessage() const { return m_msg; } }; constinit SmcResult g_exp_mod_result = SmcResult::Success; constinit bool g_test_exp_mod_public = false; constinit int g_test_exp_mod_slot = pkg1::RsaKeySlot_Temporary; constinit ImportRsaKey g_test_exp_mod_key = {}; constinit union { ModularExponentiateByStorageKeyAsyncArguments modular_exponentiate_by_storage_key; PrepareEsDeviceUniqueKeyAsyncArguments prepare_es_device_unique_key; } g_async_arguments; ALWAYS_INLINE ModularExponentiateByStorageKeyAsyncArguments &GetModularExponentiateByStorageKeyAsyncArguments() { return g_async_arguments.modular_exponentiate_by_storage_key; } ALWAYS_INLINE PrepareEsDeviceUniqueKeyAsyncArguments &GetPrepareEsDeviceUniqueKeyAsyncArguments() { return g_async_arguments.prepare_es_device_unique_key; } void SecurityEngineDoneHandler() { /* End the asynchronous operation. */ g_exp_mod_result = SmcResult::Success; EndAsyncOperation(); } void TestRsaPublicKey(ImportRsaKey which, int slot, const void *mod, size_t mod_size, se::DoneHandler handler) { /* Declare a buffer for our test message. */ u8 msg[se::RsaSize]; std::memset(msg, 'D', sizeof(msg)); /* Provisionally import the modulus. */ ImportRsaKeyModulusProvisionally(which, mod, mod_size); /* Load the provisional public key into the slot. */ LoadProvisionalRsaPublicKey(slot, which); /* Perform the test exponentiation. */ se::ModularExponentiateAsync(slot, msg, sizeof(msg), handler); } void TestRsaPrivateKey(ImportRsaKey which, int slot, se::DoneHandler handler) { /* Get the result of the public key test. */ u8 msg[se::RsaSize]; se::GetRsaResult(msg, sizeof(msg)); /* Load the provisional private key into the slot. */ LoadProvisionalRsaKey(slot, which); /* Perform the test exponentiation. */ se::ModularExponentiateAsync(slot, msg, sizeof(msg), handler); } void VerifyTestRsaKeyResult(ImportRsaKey which) { /* Get the result of the test. */ u8 msg[se::RsaSize]; se::GetRsaResult(msg, sizeof(msg)); /* Validate the result. */ const bool is_valid = (msg[0] == 'D') & (crypto::IsSameBytes(msg, msg + 1, sizeof(msg) - 1)); /* If the test passes, the key is no longer provisional. */ if (is_valid) { CommitRsaKeyModulus(which); } } void TestRsaKeyDoneHandler() { if (g_test_exp_mod_public) { /* If we're testing the public key, we still have another exponentiation to do to test the private key. */ g_test_exp_mod_public = false; /* Test the private key. */ TestRsaPrivateKey(g_test_exp_mod_key, g_test_exp_mod_slot, TestRsaKeyDoneHandler); } else { /* We're testing the private key, so validate the result. */ VerifyTestRsaKeyResult(g_test_exp_mod_key); /* If the test passed, we can proceed to perform the intended exponentiation. */ if (LoadRsaKey(g_test_exp_mod_slot, g_test_exp_mod_key)) { se::ModularExponentiateAsync(pkg1::RsaKeySlot_Temporary, GetModularExponentiateByStorageKeyAsyncArguments().GetMessage(), se::RsaSize, SecurityEngineDoneHandler); } else { /* The test failed, so end the asynchronous operation. */ g_exp_mod_result = SmcResult::InvalidArgument; EndAsyncOperation(); } } } SmcResult ModularExponentiateImpl(SmcArguments &args) { /* Decode arguments. */ const uintptr_t msg_address = args.r[1]; const uintptr_t exp_address = args.r[2]; const uintptr_t mod_address = args.r[3]; const size_t exp_size = args.r[4]; /* Validate arguments. */ SMC_R_UNLESS(util::IsAligned(exp_size, sizeof(u32)), InvalidArgument); SMC_R_UNLESS(exp_size <= se::RsaSize, InvalidArgument); /* Copy the message and modulus from the user. */ alignas(8) u8 msg[se::RsaSize]; alignas(8) u8 exp[se::RsaSize]; alignas(8) u8 mod[se::RsaSize]; { UserPageMapper mapper(msg_address); SMC_R_UNLESS(mapper.Map(), InvalidArgument); SMC_R_UNLESS(mapper.CopyFromUser(msg, msg_address, sizeof(msg)), InvalidArgument); SMC_R_UNLESS(mapper.CopyFromUser(exp, exp_address, exp_size), InvalidArgument); SMC_R_UNLESS(mapper.CopyFromUser(mod, mod_address, sizeof(mod)), InvalidArgument); } /* We're performing an operation, so set the result to busy. */ g_exp_mod_result = SmcResult::Busy; /* Load the key into the temporary keyslot. */ se::SetRsaKey(pkg1::RsaKeySlot_Temporary, mod, sizeof(mod), exp, exp_size); /* Begin the asynchronous exponentiation. */ se::ModularExponentiateAsync(pkg1::RsaKeySlot_Temporary, msg, sizeof(msg), SecurityEngineDoneHandler); return SmcResult::Success; } SmcResult ModularExponentiateByStorageKeyImpl(SmcArguments &args) { /* Decode arguments. */ const uintptr_t msg_address = args.r[1]; const uintptr_t mod_address = args.r[2]; const util::BitPack32 option = { static_cast<u32>(args.r[3]) }; const auto mode = GetTargetFirmware() >= TargetFirmware_5_0_0 ? option.Get<ModularExponentiateByStorageKeyOption::Mode>() : GetModeForImportRsaKey(ImportRsaKey_Lotus); const auto reserved = option.Get<PrepareEsDeviceUniqueKeyOption::Reserved>(); /* Validate arguments. */ SMC_R_UNLESS(reserved == 0, InvalidArgument); SMC_R_UNLESS(mode < ModularExponentiateByStorageKeyTableSize, InvalidArgument); /* Convert the mode to an import key. */ const auto import_key = static_cast<ImportRsaKey>(ModularExponentiateByStorageKeyTable[mode]); /* Copy the message and modulus from the user. */ alignas(8) u8 msg[se::RsaSize]; alignas(8) u8 mod[se::RsaSize]; { UserPageMapper mapper(msg_address); SMC_R_UNLESS(mapper.Map(), InvalidArgument); SMC_R_UNLESS(mapper.CopyFromUser(msg, msg_address, sizeof(msg)), InvalidArgument); SMC_R_UNLESS(mapper.CopyFromUser(mod, mod_address, sizeof(mod)), InvalidArgument); } /* We're performing an operation, so set the result to busy. */ g_exp_mod_result = SmcResult::Busy; /* In the ideal case, the key pair is already verified. If it is, we can use it directly. */ if (LoadRsaKey(pkg1::RsaKeySlot_Temporary, import_key)) { se::ModularExponentiateAsync(pkg1::RsaKeySlot_Temporary, msg, sizeof(msg), SecurityEngineDoneHandler); } else { /* Set the async arguments. */ GetModularExponentiateByStorageKeyAsyncArguments().Set(msg, sizeof(msg)); /* Test the rsa key. */ g_test_exp_mod_slot = pkg1::RsaKeySlot_Temporary; g_test_exp_mod_key = import_key; g_test_exp_mod_public = true; TestRsaPublicKey(import_key, pkg1::RsaKeySlot_Temporary, mod, sizeof(mod), TestRsaKeyDoneHandler); } return SmcResult::Success; } SmcResult PrepareEsDeviceUniqueKeyImpl(SmcArguments &args) { /* Decode arguments. */ u8 label_digest[crypto::Sha256Generator::HashSize]; const uintptr_t msg_address = args.r[1]; const uintptr_t mod_address = args.r[2]; std::memcpy(label_digest, std::addressof(args.r[3]), sizeof(label_digest)); const util::BitPack32 option = { static_cast<u32>(args.r[7]) }; const auto generation = GetTargetFirmware() >= TargetFirmware_3_0_0 ? std::max<int>(pkg1::KeyGeneration_1_0_0, option.Get<PrepareEsDeviceUniqueKeyOption::KeyGeneration>() - 1) : pkg1::KeyGeneration_1_0_0; const auto type = option.Get<PrepareEsDeviceUniqueKeyOption::Type>(); const auto reserved = option.Get<PrepareEsDeviceUniqueKeyOption::Reserved>(); /* Validate arguments. */ SMC_R_UNLESS(reserved == 0, InvalidArgument); SMC_R_UNLESS(pkg1::IsValidKeyGeneration(generation), InvalidArgument); SMC_R_UNLESS(generation <= GetKeyGeneration(), InvalidArgument); SMC_R_UNLESS(type < EsCommonKeyType_Count, InvalidArgument); /* Copy the message and modulus from the user. */ alignas(8) u8 msg[se::RsaSize]; alignas(8) u8 mod[se::RsaSize]; { UserPageMapper mapper(msg_address); SMC_R_UNLESS(mapper.Map(), InvalidArgument); SMC_R_UNLESS(mapper.CopyFromUser(msg, msg_address, sizeof(msg)), InvalidArgument); SMC_R_UNLESS(mapper.CopyFromUser(mod, mod_address, sizeof(mod)), InvalidArgument); } /* We're performing an operation, so set the result to busy. */ g_exp_mod_result = SmcResult::Busy; /* Set the async arguments. */ GetPrepareEsDeviceUniqueKeyAsyncArguments().Set(generation, type, label_digest); /* Load the es drm key into the security engine. */ SMC_R_UNLESS(LoadRsaKey(pkg1::RsaKeySlot_Temporary, ImportRsaKey_EsDrmCert), NotInitialized); /* Trigger the asynchronous modular exponentiation. */ se::ModularExponentiateAsync(pkg1::RsaKeySlot_Temporary, msg, sizeof(msg), SecurityEngineDoneHandler); return SmcResult::Success; } SmcResult GetModularExponentiateResult(void *dst, size_t dst_size) { /* Validate state. */ SMC_R_TRY(g_exp_mod_result); SMC_R_UNLESS(dst_size == se::RsaSize, InvalidArgument); /* We want to relinquish our security engine lock at the end of scope. */ ON_SCOPE_EXIT { UnlockSecurityEngine(); }; /* Get the result of the exponentiation. */ se::GetRsaResult(dst, se::RsaSize); return SmcResult::Success; } SmcResult GetPrepareEsDeviceUniqueKeyResult(void *dst, size_t dst_size) { /* Declare variables. */ u8 key_source[se::AesBlockSize]; u8 key[se::AesBlockSize]; u8 access_key[se::AesBlockSize]; /* Validate state. */ SMC_R_TRY(g_exp_mod_result); SMC_R_UNLESS(dst_size == sizeof(access_key), InvalidArgument); /* We want to relinquish our security engine lock at the end of scope. */ ON_SCOPE_EXIT { UnlockSecurityEngine(); }; /* Get the async args. */ const auto &async_args = GetPrepareEsDeviceUniqueKeyAsyncArguments(); /* Get the exponentiation output. */ alignas(8) u8 msg[se::RsaSize]; se::GetRsaResult(msg, sizeof(msg)); /* Decode the key. */ { /* Get the label digest. */ u8 label_digest[crypto::Sha256Generator::HashSize]; async_args.GetLabelDigest(label_digest); /* Decode the key source. */ const size_t key_source_size = se::DecodeRsaOaepSha256(key_source, sizeof(key_source), msg, sizeof(msg), label_digest, sizeof(label_digest)); SMC_R_UNLESS(key_source_size == sizeof(key_source), InvalidArgument); } /* Decrypt the key. */ DecryptWithEsCommonKey(key, sizeof(key), key_source, sizeof(key_source), async_args.GetCommonKeyType(), async_args.GetKeyGeneration()); PrepareEsAesKey(access_key, sizeof(access_key), key, sizeof(key)); /* Copy the access key to output. */ std::memcpy(dst, access_key, sizeof(access_key)); return SmcResult::Success; } } SmcResult SmcModularExponentiate(SmcArguments &args) { return LockSecurityEngineAndInvokeAsync(args, ModularExponentiateImpl, GetModularExponentiateResult); } SmcResult SmcModularExponentiateByStorageKey(SmcArguments &args) { return LockSecurityEngineAndInvokeAsync(args, ModularExponentiateByStorageKeyImpl, GetModularExponentiateResult); } SmcResult SmcPrepareEsDeviceUniqueKey(SmcArguments &args) { return LockSecurityEngineAndInvokeAsync(args, PrepareEsDeviceUniqueKeyImpl, GetPrepareEsDeviceUniqueKeyResult); } }
16,558
C++
.cpp
292
44.246575
216
0.609203
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,349
secmon_smc_carveout.cpp
Atmosphere-NX_Atmosphere/exosphere/program/source/smc/secmon_smc_carveout.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 <exosphere.hpp> #include "../secmon_error.hpp" #include "../secmon_setup.hpp" #include "secmon_smc_carveout.hpp" namespace ams::secmon::smc { SmcResult SmcSetKernelCarveoutRegion(SmcArguments &args) { /* Decode arguments. */ const int index = args.r[1]; const uintptr_t address = args.r[2]; const size_t size = args.r[3]; /* Validate arguments. */ SMC_R_UNLESS(0 <= index && index < KernelCarveoutCount, InvalidArgument); SMC_R_UNLESS(util::IsAligned(address, 128_KB), InvalidArgument); SMC_R_UNLESS(util::IsAligned(size, 128_KB), InvalidArgument); SMC_R_UNLESS(size <= CarveoutSizeMax, InvalidArgument); /* Set the carveout. */ SetKernelCarveoutRegion(index, address, size); return SmcResult::Success; } }
1,514
C++
.cpp
35
38.714286
81
0.67685
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,350
secmon_smc_info.cpp
Atmosphere-NX_Atmosphere/exosphere/program/source/smc/secmon_smc_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 <exosphere.hpp> #include "../secmon_error.hpp" #include "../secmon_map.hpp" #include "../secmon_misc.hpp" #include "../secmon_page_mapper.hpp" #include "../secmon_user_power_management.hpp" #include "secmon_smc_info.hpp" #include "secmon_smc_power_management.hpp" namespace ams::secmon::smc { namespace { struct KernelConfiguration { /* Secure Monitor view. */ using Flags1 = util::BitPack32::Field< 0, 8>; using Flags0 = util::BitPack32::Field< 8, 8>; using PhysicalMemorySize = util::BitPack32::Field<16, 2>; /* Kernel view, from libmesosphere. */ using DebugFillMemory = util::BitPack32::Field<0, 1, bool>; using EnableUserExceptionHandlers = util::BitPack32::Field<DebugFillMemory::Next, 1, bool>; using EnableUserPmuAccess = util::BitPack32::Field<EnableUserExceptionHandlers::Next, 1, bool>; using IncreaseThreadResourceLimit = util::BitPack32::Field<EnableUserPmuAccess::Next, 1, bool>; using DisableDynamicResourceLimits = util::BitPack32::Field<IncreaseThreadResourceLimit::Next, 1, bool>; using Reserved5 = util::BitPack32::Field<DisableDynamicResourceLimits::Next, 3, u32>; using UseSecureMonitorPanicCall = util::BitPack32::Field<Reserved5::Next, 1, bool>; using Reserved9 = util::BitPack32::Field<UseSecureMonitorPanicCall::Next, 7, u32>; using MemorySize = util::BitPack32::Field<Reserved9::Next, 2, u32>; /* smc::MemorySize = pkg1::MemorySize */ }; constexpr const pkg1::MemorySize DramIdToMemorySize[fuse::DramId_Count] = { [fuse::DramId_IcosaSamsung4GB] = pkg1::MemorySize_4GB, [fuse::DramId_IcosaHynix4GB] = pkg1::MemorySize_4GB, [fuse::DramId_IcosaMicron4GB] = pkg1::MemorySize_4GB, [fuse::DramId_IowaHynix1y4GB] = pkg1::MemorySize_4GB, [fuse::DramId_IcosaSamsung6GB] = pkg1::MemorySize_6GB, [fuse::DramId_HoagHynix1y4GB] = pkg1::MemorySize_4GB, [fuse::DramId_AulaHynix1y4GB] = pkg1::MemorySize_4GB, [fuse::DramId_Deprecated7] = pkg1::MemorySize_4GB, [fuse::DramId_IowaSansung4GB] = pkg1::MemorySize_4GB, [fuse::DramId_IowaSamsung8GB] = pkg1::MemorySize_8GB, [fuse::DramId_IowaHynix4GB] = pkg1::MemorySize_4GB, [fuse::DramId_IowaMicron4GB] = pkg1::MemorySize_4GB, [fuse::DramId_HoagSamsung4GB] = pkg1::MemorySize_4GB, [fuse::DramId_HoagSamsung8GB] = pkg1::MemorySize_8GB, [fuse::DramId_HoagHynix4GB] = pkg1::MemorySize_4GB, [fuse::DramId_HoagMicron4GB] = pkg1::MemorySize_4GB, [fuse::DramId_Deprecated16] = pkg1::MemorySize_4GB, [fuse::DramId_IowaSamsung1y4GBX] = pkg1::MemorySize_4GB, [fuse::DramId_IowaSamsung1y8GBX] = pkg1::MemorySize_8GB, [fuse::DramId_HoagSamsung1y4GBX] = pkg1::MemorySize_4GB, [fuse::DramId_IowaSamsung1z4GB] = pkg1::MemorySize_4GB, [fuse::DramId_HoagSamsung1z4GB] = pkg1::MemorySize_4GB, [fuse::DramId_AulaSamsung1z4GB] = pkg1::MemorySize_4GB, [fuse::DramId_HoagSamsung1y8GBX] = pkg1::MemorySize_8GB, [fuse::DramId_AulaSamsung1y4GBX] = pkg1::MemorySize_4GB, [fuse::DramId_IowaMicron1y4GB] = pkg1::MemorySize_4GB, [fuse::DramId_HoagMicron1y4GB] = pkg1::MemorySize_4GB, [fuse::DramId_AulaMicron1y4GB] = pkg1::MemorySize_4GB, [fuse::DramId_AulaSamsung1y8GBX] = pkg1::MemorySize_8GB, [fuse::DramId_IowaX1X2Samsung4GB] = pkg1::MemorySize_4GB, [fuse::DramId_HoagX1X2Samsung4GB] = pkg1::MemorySize_4GB, [fuse::DramId_AulaX1X2Samsung4GB] = pkg1::MemorySize_4GB, [fuse::DramId_IowaSamsung4GBY] = pkg1::MemorySize_4GB, [fuse::DramId_HoagSamsung4GBY] = pkg1::MemorySize_4GB, [fuse::DramId_AulaSamsung4GBY] = pkg1::MemorySize_4GB, }; constexpr const pkg1::MemoryMode MemoryModes[] = { pkg1::MemoryMode_Auto, pkg1::MemoryMode_4GB, pkg1::MemoryMode_4GBAppletDev, pkg1::MemoryMode_4GBSystemDev, pkg1::MemoryMode_6GB, pkg1::MemoryMode_6GBAppletDev, pkg1::MemoryMode_8GB, }; constexpr bool IsValidMemoryMode(pkg1::MemoryMode mode) { for (const auto known_mode : MemoryModes) { if (mode == known_mode) { return true; } } return false; } pkg1::MemoryMode SanitizeMemoryMode(pkg1::MemoryMode mode) { if (IsValidMemoryMode(mode)) { return mode; } return pkg1::MemoryMode_Auto; } pkg1::MemorySize GetAvailableMemorySize(pkg1::MemorySize size) { return std::min(GetPhysicalMemorySize(), size); } pkg1::MemoryMode GetMemoryMode(pkg1::MemoryMode mode) { /* Sanitize the mode. */ mode = SanitizeMemoryMode(mode); /* If the mode is auto, construct the memory mode. */ if (mode == pkg1::MemoryMode_Auto) { return pkg1::MakeMemoryMode(GetPhysicalMemorySize(), pkg1::MemoryArrange_Normal); } else { const auto mode_size = GetMemorySize(mode); const auto mode_arrange = GetMemoryArrange(mode); const auto size = GetAvailableMemorySize(mode_size); const auto arrange = (size == mode_size) ? mode_arrange : pkg1::MemoryArrange_Normal; return pkg1::MakeMemoryMode(size, arrange); } } u32 GetMemoryMode() { /* Unless development function is enabled, we're 4 GB. */ u32 memory_mode = pkg1::MemoryMode_4GB; if (const auto &bcd = GetBootConfig().data; bcd.IsDevelopmentFunctionEnabled()) { memory_mode = GetMemoryMode(bcd.GetMemoryMode()); } return memory_mode; } u32 GetKernelConfiguration() { pkg1::MemorySize memory_size = pkg1::MemorySize_4GB; util::BitPack32 value = {}; if (const auto &bcd = GetBootConfig().data; bcd.IsDevelopmentFunctionEnabled()) { memory_size = GetMemorySize(GetMemoryMode(bcd.GetMemoryMode())); value.Set<KernelConfiguration::Flags1>(bcd.GetKernelFlags1()); value.Set<KernelConfiguration::Flags0>(bcd.GetKernelFlags0()); } value.Set<KernelConfiguration::PhysicalMemorySize>(memory_size); /* Exosphere extensions. */ const auto &sc = GetSecmonConfiguration(); if (!sc.DisableUserModeExceptionHandlers()) { value.Set<KernelConfiguration::EnableUserExceptionHandlers>(true); } if (sc.EnableUserModePerformanceCounterAccess()) { value.Set<KernelConfiguration::EnableUserPmuAccess>(true); } return value.value; } constinit u64 g_payload_address = 0; constinit bool g_set_true_target_firmware = false; SmcResult GetConfig(SmcArguments &args, bool kern) { switch (static_cast<ConfigItem>(args.r[1])) { case ConfigItem::DisableProgramVerification: args.r[1] = GetBootConfig().signed_data.IsProgramVerificationDisabled(); break; case ConfigItem::DramId: args.r[1] = fuse::GetDramId(); break; case ConfigItem::SecurityEngineInterruptNumber: args.r[1] = SecurityEngineUserInterruptId; break; case ConfigItem::FuseVersion: args.r[1] = fuse::GetExpectedFuseVersion(GetTargetFirmware()); break; case ConfigItem::HardwareType: args.r[1] = fuse::GetHardwareType(); break; case ConfigItem::HardwareState: args.r[1] = fuse::GetHardwareState(); break; case ConfigItem::IsRecoveryBoot: args.r[1] = IsRecoveryBoot(); break; case ConfigItem::DeviceId: args.r[1] = fuse::GetDeviceId(); break; case ConfigItem::BootReason: { /* This was removed in firmware 4.0.0. */ if (GetTargetFirmware() >= TargetFirmware_4_0_0) { return SmcResult::InvalidArgument; } args.r[1] = GetDeprecatedBootReason(); } break; case ConfigItem::MemoryMode: args.r[1] = GetMemoryMode(); break; case ConfigItem::IsDevelopmentFunctionEnabled: args.r[1] = GetSecmonConfiguration().IsDevelopmentFunctionEnabled(kern) || GetBootConfig().data.IsDevelopmentFunctionEnabled(); break; case ConfigItem::KernelConfiguration: args.r[1] = GetKernelConfiguration(); break; case ConfigItem::IsChargerHiZModeEnabled: args.r[1] = IsChargerHiZModeEnabled(); break; case ConfigItem::RetailInteractiveDisplayState: args.r[1] = fuse::GetRetailInteractiveDisplayState(); break; case ConfigItem::RegulatorType: args.r[1] = fuse::GetRegulator(); break; case ConfigItem::DeviceUniqueKeyGeneration: args.r[1] = fuse::GetDeviceUniqueKeyGeneration(); break; case ConfigItem::Package2Hash: { /* Only allow getting the package2 hash in recovery boot. */ if (!IsRecoveryBoot()) { return SmcResult::InvalidArgument; } /* Get the hash. */ se::Sha256Hash tmp_hash; GetPackage2Hash(std::addressof(tmp_hash)); /* Copy it out. */ static_assert(sizeof(args) - sizeof(args.r[0]) >= sizeof(tmp_hash)); std::memcpy(std::addressof(args.r[1]), std::addressof(tmp_hash), sizeof(tmp_hash)); } break; case ConfigItem::ExosphereApiVersion: /* Get information about the current exosphere version. */ if (kern || g_set_true_target_firmware) { args.r[1] = (static_cast<u64>(ATMOSPHERE_RELEASE_VERSION_MAJOR & 0xFF) << 56) | (static_cast<u64>(ATMOSPHERE_RELEASE_VERSION_MINOR & 0xFF) << 48) | (static_cast<u64>(ATMOSPHERE_RELEASE_VERSION_MICRO & 0xFF) << 40) | (static_cast<u64>(GetKeyGeneration()) << 32) | (static_cast<u64>(GetTargetFirmware()) << 0); } else { return SmcResult::NotInitialized; } break; case ConfigItem::ExosphereNeedsReboot: /* We are executing, so we aren't in the process of rebooting. */ args.r[1] = 0; break; case ConfigItem::ExosphereNeedsShutdown: /* We are executing, so we aren't in the process of shutting down. */ args.r[1] = 0; break; case ConfigItem::ExosphereGitCommitHash: /* Get information about the current exosphere git commit hash. */ args.r[1] = ATMOSPHERE_GIT_HASH; break; case ConfigItem::ExosphereHasRcmBugPatch: /* Get information about whether this unit has the RCM bug patched. */ args.r[1] = fuse::HasRcmVulnerabilityPatch(); break; case ConfigItem::ExosphereBlankProdInfo: /* Get whether this unit should simulate a "blanked" PRODINFO. */ args.r[1] = GetSecmonConfiguration().ShouldUseBlankCalibrationBinary(); break; case ConfigItem::ExosphereAllowCalWrites: /* Get whether this unit should allow writing to the calibration partition. */ args.r[1] = (GetEmummcConfiguration().IsEmummcActive() || GetSecmonConfiguration().AllowWritingToCalibrationBinarySysmmc()); break; case ConfigItem::ExosphereEmummcType: /* Get what kind of emummc this unit has active. */ /* NOTE: This may return values other than 1 in the future. */ args.r[1] = (GetEmummcConfiguration().IsEmummcActive() ? 1 : 0); break; case ConfigItem::ExospherePayloadAddress: /* Gets the physical address of the reboot payload buffer, if one exists. */ if (g_payload_address != 0) { args.r[1] = g_payload_address; } else { return SmcResult::NotInitialized; } break; case ConfigItem::ExosphereLogConfiguration: /* Get the log configuration. */ args.r[1] = (static_cast<u64>(static_cast<u8>(secmon::GetLogPort())) << 32) | static_cast<u64>(secmon::GetLogBaudRate()); break; case ConfigItem::ExosphereForceEnableUsb30: /* Get whether usb 3.0 should be force-enabled. */ args.r[1] = GetSecmonConfiguration().IsUsb30ForceEnabled(); break; case ConfigItem::ExosphereSupportedHosVersion: /* Get information about the supported hos version. */ args.r[1] = (static_cast<u64>(ATMOSPHERE_SUPPORTED_HOS_VERSION_MAJOR & 0xFF) << 24) | (static_cast<u64>(ATMOSPHERE_SUPPORTED_HOS_VERSION_MINOR & 0xFF) << 16) | (static_cast<u64>(ATMOSPHERE_SUPPORTED_HOS_VERSION_MICRO & 0xFF) << 8); break; case ConfigItem::ExosphereApproximateApiVersion: /* Get information about the current exosphere version. */ if (!g_set_true_target_firmware) { args.r[1] = (static_cast<u64>(ATMOSPHERE_RELEASE_VERSION_MAJOR & 0xFF) << 56) | (static_cast<u64>(ATMOSPHERE_RELEASE_VERSION_MINOR & 0xFF) << 48) | (static_cast<u64>(ATMOSPHERE_RELEASE_VERSION_MICRO & 0xFF) << 40) | (static_cast<u64>(GetKeyGeneration()) << 32) | (static_cast<u64>(GetTargetFirmware()) << 0); } else { return SmcResult::Busy; } break; default: return SmcResult::InvalidArgument; } return SmcResult::Success; } SmcResult SetConfig(SmcArguments &args) { const auto soc_type = GetSocType(); switch (static_cast<ConfigItem>(args.r[1])) { case ConfigItem::IsChargerHiZModeEnabled: /* Configure the HiZ mode. */ SetChargerHiZModeEnabled(static_cast<bool>(args.r[3])); break; case ConfigItem::ExosphereApiVersion: if (!g_set_true_target_firmware) { ::ams::secmon::impl::SetTargetFirmware(static_cast<ams::TargetFirmware>(args.r[3] & 0xFFFFFFFF)); g_set_true_target_firmware = true; } else { return SmcResult::Busy; } break; case ConfigItem::ExosphereNeedsReboot: if (soc_type == fuse::SocType_Erista) { switch (static_cast<UserRebootType>(args.r[3])) { case UserRebootType_None: break; case UserRebootType_ToRcm: PerformUserRebootToRcm(); break; case UserRebootType_ToPayload: PerformUserRebootToPayload(); break; case UserRebootType_ToFatalError: PerformUserRebootToFatalError(); break; case UserRebootType_ByPmic: PerformUserRebootByPmic(); break; default: return SmcResult::InvalidArgument; } } else /* if (soc_type == fuse::SocType_Mariko) */ { switch (static_cast<UserRebootType>(args.r[3])) { case UserRebootType_ToFatalError: PerformUserRebootToFatalError(); break; case UserRebootType_ByPmic: PerformUserRebootByPmic(); break; default: return SmcResult::InvalidArgument; } } break; case ConfigItem::ExosphereNeedsShutdown: if (args.r[3] != 0) { PerformUserShutDown(); } break; case ConfigItem::ExospherePayloadAddress: if (g_payload_address == 0) { if (secmon::IsPhysicalMemoryAddress(args.r[2])) { g_payload_address = args.r[2]; } else { return SmcResult::InvalidArgument; } } else { return SmcResult::Busy; } break; default: return SmcResult::InvalidArgument; } return SmcResult::Success; } } SmcResult SmcGetConfigUser(SmcArguments &args) { return GetConfig(args, false); } SmcResult SmcGetConfigKern(SmcArguments &args) { return GetConfig(args, true); } SmcResult SmcSetConfig(SmcArguments &args) { return SetConfig(args); } /* This is an atmosphere extension smc. */ SmcResult SmcGetEmummcConfig(SmcArguments &args) { /* Decode arguments. */ const auto mmc = static_cast<EmummcMmc>(args.r[1]); const uintptr_t user_address = args.r[2]; const uintptr_t user_offset = user_address % 4_KB; /* Validate arguments. */ /* NOTE: In the future, configuration for non-NAND storage may be implemented. */ SMC_R_UNLESS(mmc == EmummcMmc_Nand, NotSupported); SMC_R_UNLESS(user_offset + 2 * sizeof(EmummcFilePath) <= 4_KB, InvalidArgument); /* Get the emummc config. */ const auto &cfg = GetEmummcConfiguration(); static_assert(sizeof(cfg.file_cfg) == sizeof(EmummcFilePath)); static_assert(sizeof(cfg.emu_dir_path) == sizeof(EmummcFilePath)); /* Clear the output. */ constexpr size_t InlineOutputSize = sizeof(args) - sizeof(args.r[0]); u8 * const inline_output = static_cast<u8 *>(static_cast<void *>(std::addressof(args.r[1]))); std::memset(inline_output, 0, InlineOutputSize); /* Copy out the configuration. */ { /* Map the user output page. */ AtmosphereUserPageMapper mapper(user_address); SMC_R_UNLESS(mapper.Map(), InvalidArgument); /* Copy the base configuration. */ static_assert(sizeof(cfg.base_cfg) <= InlineOutputSize); std::memcpy(inline_output, std::addressof(cfg.base_cfg), sizeof(cfg.base_cfg)); /* Copy out type-specific data. */ switch (cfg.base_cfg.type) { case EmummcType_None: /* No additional configuration needs to be copied. */ break; case EmummcType_Partition: /* Copy the partition config. */ static_assert(sizeof(cfg.base_cfg) + sizeof(cfg.partition_cfg) <= InlineOutputSize); std::memcpy(inline_output + sizeof(cfg.base_cfg), std::addressof(cfg.partition_cfg), sizeof(cfg.partition_cfg)); break; case EmummcType_File: /* Copy the file config. */ SMC_R_UNLESS(mapper.CopyToUser(user_address, std::addressof(cfg.file_cfg), sizeof(cfg.file_cfg)), InvalidArgument); break; AMS_UNREACHABLE_DEFAULT_CASE(); } /* Copy the redirection directory path to the user page. */ SMC_R_UNLESS(mapper.CopyToUser(user_address + sizeof(EmummcFilePath), std::addressof(cfg.emu_dir_path), sizeof(cfg.emu_dir_path)), InvalidArgument); } return SmcResult::Success; } /* For exosphere's usage. */ pkg1::MemorySize GetPhysicalMemorySize() { const auto dram_id = fuse::GetDramId(); AMS_ABORT_UNLESS(dram_id < fuse::DramId_Count); return DramIdToMemorySize[dram_id]; } }
23,273
C++
.cpp
430
37.209302
160
0.529525
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,351
secmon_smc_error.cpp
Atmosphere-NX_Atmosphere/exosphere/program/source/smc/secmon_smc_error.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 <exosphere.hpp> #include "../secmon_error.hpp" #include "secmon_smc_error.hpp" namespace ams::secmon::smc { SmcResult SmcShowError(SmcArguments &args) { /* Decode arguments. */ const u32 r = ((args.r[1] >> 8) & 0xF); const u32 g = ((args.r[1] >> 4) & 0xF); const u32 b = ((args.r[1] >> 0) & 0xF); const u32 rgb = (b << 8) | (g << 4) | (r << 0); /* Set the error info. */ SetError(pkg1::MakeKernelPanicResetInfo(rgb)); /* Reboot. */ ErrorReboot(); /* This point will never be reached. */ __builtin_unreachable(); } }
1,263
C++
.cpp
33
33.727273
76
0.650859
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,352
secmon_smc_se_lock.cpp
Atmosphere-NX_Atmosphere/exosphere/program/source/smc/secmon_smc_se_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 <exosphere.hpp> #include "../secmon_error.hpp" #include "secmon_smc_se_lock.hpp" namespace ams::secmon::smc { namespace { constinit util::Atomic<bool> g_is_locked = false; ALWAYS_INLINE bool TryLockSecurityEngineImpl() { bool value = false; return g_is_locked.CompareExchangeStrong(value, true); } ALWAYS_INLINE void UnlockSecurityEngineImpl() { g_is_locked = false; } ALWAYS_INLINE bool IsSecurityEngineLockedImpl() { return g_is_locked.Load(); } } bool TryLockSecurityEngine() { return TryLockSecurityEngineImpl(); } void UnlockSecurityEngine() { return UnlockSecurityEngineImpl(); } bool IsSecurityEngineLocked() { return IsSecurityEngineLockedImpl(); } SmcResult LockSecurityEngineAndInvoke(SmcArguments &args, SmcHandler impl) { /* Try to lock the security engine. */ SMC_R_UNLESS(TryLockSecurityEngineImpl(), Busy); ON_SCOPE_EXIT { UnlockSecurityEngineImpl(); }; return impl(args); } SmcResult LockSecurityEngineAndInvokeAsync(SmcArguments &args, SmcHandler impl, GetResultHandler result_handler) { /* Try to lock the security engine. */ SMC_R_UNLESS(TryLockSecurityEngineImpl(), Busy); auto se_guard = SCOPE_GUARD { UnlockSecurityEngineImpl(); }; /* Try to start an async operation. */ const u64 async_key = BeginAsyncOperation(result_handler); SMC_R_UNLESS(async_key != InvalidAsyncKey, Busy); auto async_guard = SCOPE_GUARD { CancelAsyncOperation(async_key); }; /* Try to invoke the operation. */ SMC_R_TRY(impl(args)); /* We succeeded! Cancel our guards, and return the async key to our caller. */ async_guard.Cancel(); se_guard.Cancel(); args.r[1] = async_key; return SmcResult::Success; } }
2,585
C++
.cpp
64
33.890625
118
0.677986
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,353
secmon_boot_functions.cpp
Atmosphere-NX_Atmosphere/exosphere/program/source/boot/secmon_boot_functions.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 <exosphere.hpp> #include "../secmon_error.hpp" #include "secmon_boot.hpp" #include "secmon_boot_cache.hpp" #include "secmon_boot_functions.hpp" namespace ams::secmon::boot { namespace { constexpr inline uintptr_t SYSCTR0 = MemoryRegionVirtualDeviceSysCtr0.GetAddress(); NOINLINE void DecryptPayload(uintptr_t dst, uintptr_t src, size_t size, const void *iv, size_t iv_size, u8 key_generation) { secmon::boot::DecryptPackage2(reinterpret_cast<void *>(dst), size, reinterpret_cast<void *>(src), size, secmon::boot::GetPackage2AesKey(), crypto::AesEncryptor128::KeySize, iv, iv_size, key_generation); } u32 GetChipId() { constexpr u32 ChipIdErista = 0x210; constexpr u32 ChipIdMariko = 0x214; switch (GetSocType()) { case fuse::SocType_Erista: return ChipIdErista; case fuse::SocType_Mariko: return ChipIdMariko; AMS_UNREACHABLE_DEFAULT_CASE(); } } } void CheckVerifyResult(bool verify_result, pkg1::ErrorInfo error_info, const char *message) { if (!verify_result) { secmon::SetError(error_info); AMS_ABORT(message); } } void ClearIramBootCode() { /* Clear the boot code image from where it was loaded in IRAM. */ util::ClearMemory(MemoryRegionPhysicalIramBootCodeCode.GetPointer(), MemoryRegionPhysicalIramBootCodeCode.GetSize()); } void ClearIramBootKeys() { /* Clear the boot keys from where they were loaded in IRAM. */ util::ClearMemory(MemoryRegionPhysicalIramBootCodeKeys.GetPointer(), MemoryRegionPhysicalIramBootCodeKeys.GetSize()); } void ClearIramDebugCode() { /* Clear the boot code image from where it was loaded in IRAM. */ util::ClearMemory(MemoryRegionPhysicalDebugCode.GetPointer(), MemoryRegionPhysicalDebugCode.GetSize()); } void WaitForNxBootloader(const pkg1::SecureMonitorParameters &params, pkg1::BootloaderState state) { /* Check NX Bootloader's state once per microsecond until it's advanced enough. */ while (params.bootloader_state < state) { util::WaitMicroSeconds(1); } } void LoadBootConfig(const void *src) { pkg1::BootConfig * const dst = secmon::impl::GetBootConfigStorage(); if (pkg1::IsProduction()) { std::memset(dst, 0, sizeof(*dst)); } else { hw::FlushDataCache(src, sizeof(*dst)); hw::DataSynchronizationBarrierInnerShareable(); std::memcpy(dst, src, sizeof(*dst)); } } void VerifyOrClearBootConfig() { /* On production hardware, the boot config is already cleared. */ if (pkg1::IsProduction()) { return; } pkg1::BootConfig * const bc = secmon::impl::GetBootConfigStorage(); /* Determine if the bc is valid for the device. */ bool valid_for_device = false; { const bool valid_signature = secmon::boot::VerifyBootConfigSignature(*bc, secmon::boot::GetBootConfigRsaModulus(), se::RsaSize); if (valid_signature) { valid_for_device = secmon::boot::VerifyBootConfigEcid(*bc); } } /* If the boot config is not valid for the device, clear its signed data. */ if (!valid_for_device) { util::ClearMemory(std::addressof(bc->signed_data), sizeof(bc->signed_data)); } } void EnableTsc(u64 initial_tsc_value) { /* Write the initial value to the CNTCV registers. */ const u32 lo = static_cast<u32>(initial_tsc_value >> 0); const u32 hi = static_cast<u32>(initial_tsc_value >> 32); reg::Write(SYSCTR0 + SYSCTR0_CNTCV0, lo); reg::Write(SYSCTR0 + SYSCTR0_CNTCV1, hi); /* Configure the system counter control register. */ reg::Write(SYSCTR0 + SYSCTR0_CNTCR, SYSCTR0_REG_BITS_ENUM(CNTCR_HDBG, ENABLE), SYSCTR0_REG_BITS_ENUM(CNTCR_EN, ENABLE)); } void WriteGpuCarveoutMagicNumbers() { /* Define the magic numbers. */ constexpr u32 GpuMagicNumber = 0xC0EDBBCC; constexpr u32 SkuInfo = 0x83; constexpr u32 HdcpMicroCodeVersion = 0x2; /* Get our pointers. */ u32 *gpu_magic = MemoryRegionDramGpuCarveout.GetEndPointer<u32>() - (0x004 / sizeof(*gpu_magic)); u32 *tsec_magic = MemoryRegionDramGpuCarveout.GetEndPointer<u32>() - (0x100 / sizeof(*tsec_magic)); /* Write the gpu magic number. */ gpu_magic[0] = GpuMagicNumber; /* Write the tsec magic numbers. */ tsec_magic[0] = SkuInfo; tsec_magic[1] = HdcpMicroCodeVersion; tsec_magic[2] = GetChipId(); /* Flush the magic numbers. */ hw::FlushDataCache(gpu_magic, 1 * sizeof(u32)); hw::FlushDataCache(tsec_magic, 3 * sizeof(u32)); hw::DataSynchronizationBarrierInnerShareable(); } void UpdateBootConfigForPackage2Header(const pkg2::Package2Header &header) { /* Check for all-zeroes signature. */ const bool is_unsigned = header.signature[0] == 0 && crypto::IsSameBytes(header.signature, header.signature + 1, sizeof(header.signature) - 1); secmon::impl::GetBootConfigStorage()->signed_data.SetPackage2SignatureVerificationDisabled(is_unsigned); /* Check for valid magic. */ const bool is_decrypted = crypto::IsSameBytes(header.meta.magic, pkg2::Package2Meta::Magic::String, sizeof(header.meta.magic)); secmon::impl::GetBootConfigStorage()->signed_data.SetPackage2EncryptionDisabled(is_decrypted); } void VerifyPackage2HeaderSignature(pkg2::Package2Header &header, bool verify) { const u8 * const mod = secmon::boot::GetPackage2RsaModulus(pkg1::IsProductionForPublicKey()); const size_t mod_size = se::RsaSize; if (verify) { CheckVerifyResult(secmon::boot::VerifyPackage2Signature(header, mod, mod_size), pkg1::ErrorInfo_InvalidPackage2Signature, "pkg2 sign FAIL"); } } void DecryptPackage2Header(pkg2::Package2Meta *dst, const pkg2::Package2Meta &src, bool encrypted) { if (encrypted) { constexpr int IvSize = 0x10; /* Decrypt the header. */ DecryptPackage2(dst, sizeof(*dst), std::addressof(src), sizeof(src), secmon::boot::GetPackage2AesKey(), crypto::AesEncryptor128::KeySize, std::addressof(src), IvSize, src.GetKeyGeneration()); /* Copy back the iv, which encodes encrypted metadata. */ std::memcpy(dst, std::addressof(src), IvSize); } else { std::memcpy(dst, std::addressof(src), sizeof(*dst)); } } void VerifyPackage2Header(const pkg2::Package2Meta &meta) { /* Validate the metadata. */ CheckVerifyResult(VerifyPackage2Meta(meta), pkg1::ErrorInfo_InvalidPackage2Meta, "pkg2 meta FAIL"); /* Validate the version. */ CheckVerifyResult(VerifyPackage2Version(meta), pkg1::ErrorInfo_InvalidPackage2Version, "pkg2 version FAIL"); } void DecryptAndLoadPackage2Payloads(uintptr_t dst, const pkg2::Package2Meta &meta, uintptr_t src, bool encrypted) { /* Get the key generation for crypto. */ const u8 key_generation = meta.GetKeyGeneration(); /* Decrypt or load each payload in order. */ for (int i = 0; i < pkg2::PayloadCount; ++i) { AMS_SECMON_LOG("pkg2 payload[%d]: %09lx -> %09lx size=%08x\n", i, src, dst + meta.payload_offsets[i], meta.payload_sizes[i]); if (encrypted) { DecryptPayload(dst + meta.payload_offsets[i], src, meta.payload_sizes[i], meta.payload_ivs[i], sizeof(meta.payload_ivs[i]), key_generation); } else { std::memcpy(reinterpret_cast<void *>(dst + meta.payload_offsets[i]), reinterpret_cast<void *>(src), meta.payload_sizes[i]); } src += meta.payload_sizes[i]; } } }
8,698
C++
.cpp
165
43.981818
214
0.652737
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,354
secmon_boot_config.cpp
Atmosphere-NX_Atmosphere/exosphere/program/source/boot/secmon_boot_config.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 <exosphere.hpp> #include "secmon_boot.hpp" namespace ams::secmon::boot { bool VerifyBootConfigSignature(pkg1::BootConfig &bc, const void *mod, size_t mod_size) { return VerifySignature(std::addressof(bc.signature), sizeof(bc.signature), mod, mod_size, std::addressof(bc.signed_data), sizeof(bc.signed_data)); } bool VerifyBootConfigEcid(const pkg1::BootConfig &bc) { /* Get the ecid. */ br::BootEcid ecid; fuse::GetEcid(std::addressof(ecid)); /* Verify it matches. */ return crypto::IsSameBytes(std::addressof(ecid), bc.signed_data.ecid, sizeof(ecid)); } }
1,270
C++
.cpp
29
39.931034
154
0.718447
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,355
secmon_boot_rsa.cpp
Atmosphere-NX_Atmosphere/exosphere/program/source/boot/secmon_boot_rsa.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 <exosphere.hpp> #include "secmon_boot.hpp" namespace ams::secmon::boot { namespace { constinit const u8 RsaPublicKeyExponent[] = { 0x00, 0x01, 0x00, 0x01, }; constexpr inline u8 TailMagic = 0xBC; bool VerifyRsaPssSha256(const u8 *sig, const void *msg, size_t msg_size) { /* Define constants. */ constexpr int EmBits = 2047; constexpr int EmLen = util::DivideUp(EmBits, BITSIZEOF(u8)); constexpr int SaltLen = 0x20; constexpr int HashLen = se::Sha256HashSize; /* Define a work buffer. */ u8 work[EmLen]; ON_SCOPE_EXIT { util::ClearMemory(work, sizeof(work)); }; /* Calculate the message hash, first flushing cache to ensure SE sees correct data. */ se::Sha256Hash msg_hash; hw::FlushDataCache(msg, msg_size); hw::DataSynchronizationBarrierInnerShareable(); se::CalculateSha256(std::addressof(msg_hash), msg, msg_size); /* Verify the tail magic. */ bool is_valid = sig[EmLen - 1] == TailMagic; /* Determine extents of masked db and h. */ const u8 *masked_db = std::addressof(sig[0]); const u8 *h = std::addressof(sig[EmLen - HashLen - 1]); /* Verify the extra bits are zero. */ is_valid &= (masked_db[0] >> (BITSIZEOF(u8) - (BITSIZEOF(u8) * EmLen - EmBits))) == 0; /* Calculate the db mask. */ { constexpr int MaskLen = EmLen - HashLen - 1; constexpr int HashIters = util::DivideUp(MaskLen, HashLen); u8 mgf1_buf[sizeof(u32) + HashLen]; std::memcpy(std::addressof(mgf1_buf[0]), h, HashLen); std::memset(std::addressof(mgf1_buf[HashLen]), 0, sizeof(u32)); for (int i = 0; i < HashIters; ++i) { /* Set the counter for this iteration. */ mgf1_buf[sizeof(mgf1_buf) - 1] = i; /* Calculate the sha256 to the appropriate place in the work buffer. */ auto *mgf1_dst = reinterpret_cast<se::Sha256Hash *>(std::addressof(work[HashLen * i])); hw::FlushDataCache(mgf1_buf, sizeof(mgf1_buf)); hw::DataSynchronizationBarrierInnerShareable(); se::CalculateSha256(mgf1_dst, mgf1_buf, sizeof(mgf1_buf)); } } /* Decrypt masked db using the mask we just generated. */ for (int i = 0; i < EmLen - HashLen - 1; ++i) { work[i] ^= masked_db[i]; } /* Mask out the top bits. */ u8 *db = work; db[0] &= 0xFF >> (BITSIZEOF(u8) * EmLen - EmBits); /* Verify that DB is of the form 0000...0001 */ constexpr int DbLen = EmLen - HashLen - 1; int salt_ofs = 0; { int looking_for_one = 1; int invalid_db_padding = 0; int is_zero; int is_one; for (size_t i = 0; i < DbLen; /* ... */) { is_zero = (db[i] == 0); is_one = (db[i] == 1); salt_ofs += (looking_for_one & is_one) * (static_cast<s32>(++i)); looking_for_one &= ~is_one; invalid_db_padding |= (looking_for_one & ~is_zero); } is_valid &= (invalid_db_padding == 0); } /* Verify salt. */ is_valid &= (DbLen - salt_ofs) == SaltLen; /* Setup the message to verify. */ const u8 *salt = std::addressof(db[DbLen - SaltLen]); u8 verif_msg[8 + HashLen + SaltLen]; ON_SCOPE_EXIT { util::ClearMemory(verif_msg, sizeof(verif_msg)); }; util::ClearMemory(std::addressof(verif_msg[0]), 8); std::memcpy(std::addressof(verif_msg[8]), std::addressof(msg_hash), HashLen); std::memcpy(std::addressof(verif_msg[8 + HashLen]), salt, SaltLen); /* Verify the final hash. */ return VerifyHash(h, reinterpret_cast<uintptr_t>(std::addressof(verif_msg[0])), sizeof(verif_msg)); } bool VerifyRsaPssSha256(int slot, void *sig, size_t sig_size, const void *msg, size_t msg_size) { /* Exponentiate the signature, using the signature as the destination buffer. */ se::ModularExponentiate(sig, sig_size, slot, sig, sig_size); /* Verify the pss padding. */ return VerifyRsaPssSha256(static_cast<const u8 *>(sig), msg, msg_size); } } bool VerifySignature(void *sig, size_t sig_size, const void *mod, size_t mod_size, const void *msg, size_t msg_size) { /* Load the public key into a temporary keyslot. */ const int slot = pkg1::RsaKeySlot_Temporary; se::SetRsaKey(slot, mod, mod_size, RsaPublicKeyExponent, util::size(RsaPublicKeyExponent)); return VerifyRsaPssSha256(slot, sig, sig_size, msg, msg_size); } bool VerifyHash(const void *hash, uintptr_t msg, size_t msg_size) { /* Zero-sized messages are always valid. */ if (msg_size == 0) { return true; } /* Ensure that the SE sees correct data for the message. */ hw::FlushDataCache(reinterpret_cast<void *>(msg), msg_size); hw::DataSynchronizationBarrierInnerShareable(); /* Calculate the hash. */ se::Sha256Hash calc_hash; se::CalculateSha256(std::addressof(calc_hash), reinterpret_cast<void *>(msg), msg_size); /* Verify the result. */ return crypto::IsSameBytes(std::addressof(calc_hash), hash, sizeof(calc_hash)); } }
6,439
C++
.cpp
125
39.792
122
0.568471
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,356
secmon_boot_setup.cpp
Atmosphere-NX_Atmosphere/exosphere/program/source/boot/secmon_boot_setup.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 <exosphere.hpp> #include "secmon_boot.hpp" #include "secmon_boot_cache.hpp" #include "../secmon_setup.hpp" #include "../secmon_key_storage.hpp" namespace ams::secmon::boot { namespace { void ValidateSystemCounters() { const uintptr_t sysctr0 = MemoryRegionVirtualDeviceSysCtr0.GetAddress(); /* Validate the system counter frequency is as expected. */ AMS_ABORT_UNLESS(reg::Read(sysctr0 + SYSCTR0_CNTFID0) == 19'200'000u); /* Validate the system counters are as expected. */ AMS_ABORT_UNLESS(reg::Read(sysctr0 + SYSCTR0_COUNTERID( 0)) == 0); AMS_ABORT_UNLESS(reg::Read(sysctr0 + SYSCTR0_COUNTERID( 1)) == 0); AMS_ABORT_UNLESS(reg::Read(sysctr0 + SYSCTR0_COUNTERID( 2)) == 0); AMS_ABORT_UNLESS(reg::Read(sysctr0 + SYSCTR0_COUNTERID( 3)) == 0); AMS_ABORT_UNLESS(reg::Read(sysctr0 + SYSCTR0_COUNTERID( 4)) == 0); AMS_ABORT_UNLESS(reg::Read(sysctr0 + SYSCTR0_COUNTERID( 5)) == 0); AMS_ABORT_UNLESS(reg::Read(sysctr0 + SYSCTR0_COUNTERID( 6)) == 0); AMS_ABORT_UNLESS(reg::Read(sysctr0 + SYSCTR0_COUNTERID( 7)) == 0); AMS_ABORT_UNLESS(reg::Read(sysctr0 + SYSCTR0_COUNTERID( 8)) == 0); AMS_ABORT_UNLESS(reg::Read(sysctr0 + SYSCTR0_COUNTERID( 9)) == 0); AMS_ABORT_UNLESS(reg::Read(sysctr0 + SYSCTR0_COUNTERID(10)) == 0); AMS_ABORT_UNLESS(reg::Read(sysctr0 + SYSCTR0_COUNTERID(11)) == 0); } void SetupPmcRegisters() { const auto pmc = MemoryRegionVirtualDevicePmc.GetAddress(); /* Set the physical address of the warmboot binary to scratch 1. */ if (GetSocType() == fuse::SocType_Mariko) { reg::Write(pmc + APBDEV_PMC_SECURE_SCRATCH119, static_cast<u32>(MemoryRegionPhysicalDramSecureDataStoreWarmbootFirmware.GetAddress())); } else /* if (GetSocType() == fuse::SocType_Erista) */ { reg::Write(pmc + APBDEV_PMC_SCRATCH1, static_cast<u32>(MemoryRegionPhysicalDramSecureDataStoreWarmbootFirmware.GetAddress())); } /* Configure logging by setting bits 18-19 of scratch 20. */ reg::ReadWrite(pmc + APBDEV_PMC_SCRATCH20, REG_BITS_VALUE(18, 2, 0)); /* Clear the wdt reset flag. */ reg::ReadWrite(pmc + APBDEV_PMC_SCRATCH190, REG_BITS_VALUE(0, 1, 0)); /* Configure warmboot to set Set FUSE_PRIVATEKEYDISABLE to KEY_INVISIBLE. */ reg::ReadWrite(pmc + APBDEV_PMC_SECURE_SCRATCH21, REG_BITS_VALUE(4, 1, 1)); /* NOTE: Here, Nintendo writes the warmboot key. */ /* However, we rely on the bootloader (e.g. fusee/hekate) having already done this. */ /* reg::Write(pmc + APBDEV_PMC_SECURE_SCRATCH32, ...); */ } /* This function derives the master kek and device keys using the tsec root key. */ void DeriveMasterKekAndDeviceKeyErista(bool is_prod) { /* NOTE: Exosphere does not use this in practice, and expects the bootloader to set up keys already. */ /* NOTE: This function is currently not implemented. If implemented, it will only be a reference implementation. */ if constexpr (false) { /* TODO: Consider implementing this as a reference. */ } AMS_UNUSED(is_prod); } void DeriveMasterKekAndDeviceKeyMariko(bool is_prod) { /* Clear all keyslots other than KEK and SBK in SE1. */ for (int i = 0; i < pkg1::AesKeySlot_Count; ++i) { if (i != pkg1::AesKeySlot_MarikoKek && i != pkg1::AesKeySlot_SecureBoot) { se::ClearAesKeySlot(i); } } /* Clear all keyslots in SE2. */ for (int i = 0; i < pkg1::AesKeySlot_Count; ++i) { se::ClearAesKeySlot2(i); } /* Derive the master kek. */ se::SetEncryptedAesKey128(pkg1::AesKeySlot_MasterKek, pkg1::AesKeySlot_MarikoKek, GetMarikoMasterKekSource(is_prod), se::AesBlockSize); /* Derive the device master key source kek. */ se::SetEncryptedAesKey128(pkg1::AesKeySlot_DeviceMasterKeySourceKekMariko, pkg1::AesKeySlot_SecureBoot, GetDeviceMasterKeySourceKekSource(), se::AesBlockSize); /* Clear the KEK, now that we're done using it. */ se::ClearAesKeySlot(pkg1::AesKeySlot_MarikoKek); } void DeriveMasterKekAndDeviceKey(bool is_prod) { if (GetSocType() == fuse::SocType_Mariko) { DeriveMasterKekAndDeviceKeyMariko(is_prod); } else /* if (GetSocType() == fuse::SocType_Erista) */ { DeriveMasterKekAndDeviceKeyErista(is_prod); } } void DeriveMasterKey() { if (GetSocType() == fuse::SocType_Mariko) { se::SetEncryptedAesKey128(pkg1::AesKeySlot_Master, pkg1::AesKeySlot_MasterKek, GetMasterKeySource(), se::AesBlockSize); } else /* if (GetSocType() == fuse::SocType_Erista) */ { /* Nothing to do here; erista bootloader will have derived master key already. */ } } void SetupRandomKey(int slot, se::KeySlotLockFlags flags) { /* Create an aligned buffer to hold the key. */ constexpr size_t KeySize = se::AesBlockSize; util::AlignedBuffer<hw::DataCacheLineSize, KeySize> key; /* Ensure data is consistent before triggering the SE. */ hw::FlushDataCache(key, KeySize); hw::DataSynchronizationBarrierInnerShareable(); /* Generate random bytes into the key. */ se::GenerateRandomBytes(key, KeySize); /* Ensure that the CPU sees consistent data. */ hw::DataSynchronizationBarrierInnerShareable(); hw::FlushDataCache(key, KeySize); hw::DataSynchronizationBarrierInnerShareable(); /* Use the random bytes as a key source. */ se::SetEncryptedAesKey128(slot, pkg1::AesKeySlot_DeviceMaster, key, KeySize); /* Lock the keyslot. */ se::LockAesKeySlot(slot, flags); } bool TestKeyGeneration(int generation, bool is_prod) { /* Decrypt the vector chain from generation to start. */ int slot = pkg1::AesKeySlot_Master; for (int i = generation; i > 0; --i) { se::SetEncryptedAesKey128(pkg1::AesKeySlot_Temporary, slot, GetMasterKeyVector(is_prod, i), se::AesBlockSize); slot = pkg1::AesKeySlot_Temporary; } /* Decrypt the final vector. */ u8 test_vector[se::AesBlockSize]; se::DecryptAes128(test_vector, se::AesBlockSize, slot, GetMasterKeyVector(is_prod, 0), se::AesBlockSize); constexpr u8 ZeroBlock[se::AesBlockSize] = {}; return crypto::IsSameBytes(ZeroBlock, test_vector, se::AesBlockSize); } int DetermineKeyGeneration(bool is_prod) { /* Test each generation in order. */ for (int generation = 0; generation < pkg1::KeyGeneration_Count; ++generation) { if (TestKeyGeneration(generation, is_prod)) { return generation; } } /* We must have found a correct key generation. */ AMS_ABORT(); } void DeriveAllMasterKeys(bool is_prod, u8 * const work_block) { /* Determine the generation. */ const int generation = DetermineKeyGeneration(is_prod); AMS_SECMON_LOG("KeyGen: %02X\n", static_cast<unsigned int>(generation)); /* Set the global generation. */ ::ams::secmon::impl::SetKeyGeneration(generation); /* Derive all old keys. */ int slot = pkg1::AesKeySlot_Master; for (int i = generation; i > 0; --i) { /* Decrypt the old master key. */ se::DecryptAes128(work_block, se::AesBlockSize, slot, GetMasterKeyVector(is_prod, i), se::AesBlockSize); /* Set the old master key. */ SetMasterKey(i - 1, work_block, se::AesBlockSize); /* Set the old master key into a temporary keyslot. */ se::SetAesKey(pkg1::AesKeySlot_Temporary, work_block, se::AesBlockSize); /* Perform the next decryption with the older master key. */ slot = pkg1::AesKeySlot_Temporary; } } void DeriveAllDeviceMasterKeys(bool is_prod, u8 * const work_block) { /* Get the current key generation. */ const int current_generation = secmon::GetKeyGeneration(); /* Get the kek slot. */ const int kek_slot = GetSocType() == fuse::SocType_Mariko ? pkg1::AesKeySlot_DeviceMasterKeySourceKekMariko : pkg1::AesKeySlot_DeviceMasterKeySourceKekErista; /* Iterate for all generations. */ for (int i = 0; i < pkg1::OldDeviceMasterKeyCount; ++i) { const int generation = pkg1::KeyGeneration_4_0_0 + i; /* Load the first master key into the temporary keyslot keyslot. */ LoadMasterKey(pkg1::AesKeySlot_Temporary, pkg1::KeyGeneration_1_0_0); /* Decrypt the device master kek for the generation. */ se::SetEncryptedAesKey128(pkg1::AesKeySlot_Temporary, pkg1::AesKeySlot_Temporary, GetDeviceMasterKekSource(is_prod, i), se::AesBlockSize); /* Decrypt the device master key source into the work block. */ se::DecryptAes128(work_block, se::AesBlockSize, kek_slot, GetDeviceMasterKeySourceSource(i), se::AesBlockSize); /* If we're decrypting the current device master key, decrypt into the keyslot. */ if (generation == current_generation) { se::SetEncryptedAesKey128(pkg1::AesKeySlot_DeviceMaster, pkg1::AesKeySlot_Temporary, work_block, se::AesBlockSize); } else { /* Otherwise, decrypt the work block into itself and set the old device master key. */ se::DecryptAes128(work_block, se::AesBlockSize, pkg1::AesKeySlot_Temporary, work_block, se::AesBlockSize); /* Set the device master key. */ SetDeviceMasterKey(generation, work_block, se::AesBlockSize); } } /* Clear and lock the Device Master Key Source Kek. */ se::ClearAesKeySlot(pkg1::AesKeySlot_DeviceMasterKeySourceKekMariko); se::LockAesKeySlot(pkg1::AesKeySlot_DeviceMasterKeySourceKekMariko, se::KeySlotLockFlags_AllLockKek); } void DeriveAllKeys(bool is_prod) { /* Get the ephemeral work block. */ u8 * const work_block = se::GetEphemeralWorkBlock(); ON_SCOPE_EXIT { util::ClearMemory(work_block, se::AesBlockSize); }; /* Lock the master key as a key. */ se::LockAesKeySlot(pkg1::AesKeySlot_Master, se::KeySlotLockFlags_AllLockKey); /* Setup a random key to protect the old master and device master keys. */ SetupRandomKey(pkg1::AesKeySlot_RandomForKeyStorageWrap, se::KeySlotLockFlags_AllLockKey); /* Derive the master keys. */ DeriveAllMasterKeys(is_prod, work_block); /* Lock the master key as a kek. */ se::LockAesKeySlot(pkg1::AesKeySlot_Master, se::KeySlotLockFlags_AllLockKek); /* Derive the device master keys. */ DeriveAllDeviceMasterKeys(is_prod, work_block); /* Lock the device master key as a kek. */ se::LockAesKeySlot(pkg1::AesKeySlot_DeviceMaster, se::KeySlotLockFlags_AllLockKek); /* Setup a random key to protect user keys. */ SetupRandomKey(pkg1::AesKeySlot_RandomForUserWrap, se::KeySlotLockFlags_AllLockKek); } void InitializeKeys() { /* Read lock all aes keys. */ for (int i = 0; i < se::AesKeySlotCount; ++i) { se::LockAesKeySlot(i, se::KeySlotLockFlags_AllReadLock); } /* Lock the secure monitor aes keys to be secmon only and non-readable. */ for (int i = pkg1::AesKeySlot_SecmonStart; i < pkg1::AesKeySlot_SecmonEnd; ++i) { se::LockAesKeySlot(i, se::KeySlotLockFlags_KeyUse | se::KeySlotLockFlags_PerKey); } /* Lock the unused keyslots entirely. */ static_assert(pkg1::AesKeySlot_UserEnd <= pkg1::AesKeySlot_SecmonStart); for (int i = pkg1::AesKeySlot_UserEnd; i < pkg1::AesKeySlot_SecmonStart; ++i) { se::LockAesKeySlot(i, se::KeySlotLockFlags_AllLockKek); } /* Read lock all rsa keys. */ for (int i = 0; i < se::RsaKeySlotCount; ++i) { se::LockRsaKeySlot(i, se::KeySlotLockFlags_KeyUse | se::KeySlotLockFlags_PerKey | se::KeySlotLockFlags_KeyRead); } /* Initialize the rng. */ se::InitializeRandom(); /* Determine whether we're production. */ const bool is_prod = IsProduction(); /* Derive the master kek and device key. */ /* NOTE: This is a no-op on erista, because fusee will have set up keys. */ DeriveMasterKekAndDeviceKey(is_prod); /* Lock the device key as only usable as a kek. */ se::LockAesKeySlot(pkg1::AesKeySlot_Device, se::KeySlotLockFlags_AllLockKek); /* Derive the master key. */ DeriveMasterKey(); /* Derive all other keys. */ DeriveAllKeys(is_prod); } } namespace { using namespace ams::mmu; constexpr void UnmapPhysicalIdentityMappingImpl(u64 *l1, u64 *l2, u64 *l3) { /* Invalidate the L3 entries for the tzram and iram boot code regions. */ InvalidateL3Entries(l3, MemoryRegionPhysicalTzram.GetAddress(), MemoryRegionPhysicalTzram.GetSize()); InvalidateL3Entries(l3, MemoryRegionPhysicalIramBootCode.GetAddress(), MemoryRegionPhysicalIramBootCode.GetSize()); /* Unmap the L2 entries corresponding to those L3 entries. */ InvalidateL2Entries(l2, MemoryRegionPhysicalIramL2.GetAddress(), MemoryRegionPhysicalIramL2.GetSize()); InvalidateL2Entries(l2, MemoryRegionPhysicalTzramL2.GetAddress(), MemoryRegionPhysicalTzramL2.GetSize()); /* Unmap the L1 entry corresponding to to those L2 entries. */ InvalidateL1Entries(l1, MemoryRegionPhysical.GetAddress(), MemoryRegionPhysical.GetSize()); } constexpr void UnmapDramImpl(u64 *l1, u64 *l2, u64 *l3) { /* Unmap the L1 entry corresponding to to the Dram entries. */ AMS_UNUSED(l2, l3); InvalidateL1Entries(l1, MemoryRegionDram.GetAddress(), MemoryRegionDram.GetSize()); } constexpr void UnmapMarikoProgramImpl(u64 *l1, u64 *l2, u64 *l3) { /* Unmap the L1 entry corresponding to to the Dram entries. */ AMS_UNUSED(l1, l2); InvalidateL3Entries(l3, MemoryRegionVirtualTzramMarikoProgram.GetAddress(), MemoryRegionVirtualTzramMarikoProgram.GetSize()); } } void InitializeColdBoot() { /* Ensure that the system counters are valid. */ ValidateSystemCounters(); /* Set the security engine to Tzram Secure. */ se::SetTzramSecure(); /* Set the security engine to Per Key Secure. */ se::SetPerKeySecure(); /* Set the security engine to Context Save Secure. */ se::SetContextSaveSecure(); /* Setup the PMC registers. */ SetupPmcRegisters(); /* Lockout the scratch that we've just written. */ /* pmc::LockSecureRegisters(1); */ /* Generate a random srk. */ se::GenerateSrk(); /* Initialize the SE keyslots. */ InitializeKeys(); /* Save a test vector for the SE keyslots. */ SaveSecurityEngineAesKeySlotTestVector(); } void UnmapPhysicalIdentityMapping() { /* Get the tables. */ u64 * const l1 = MemoryRegionVirtualTzramL1PageTable.GetPointer<u64>(); u64 * const l2_l3 = MemoryRegionVirtualTzramL2L3PageTable.GetPointer<u64>(); /* Unmap. */ UnmapPhysicalIdentityMappingImpl(l1, l2_l3, l2_l3); /* Ensure the mappings are consistent. */ secmon::boot::EnsureMappingConsistency(); } void UnmapDram() { /* Get the tables. */ u64 * const l1 = MemoryRegionVirtualTzramL1PageTable.GetPointer<u64>(); u64 * const l2_l3 = MemoryRegionVirtualTzramL2L3PageTable.GetPointer<u64>(); /* Unmap. */ UnmapDramImpl(l1, l2_l3, l2_l3); /* Ensure the mappings are consistent. */ secmon::boot::EnsureMappingConsistency(); } void LoadMarikoProgram() { void * const mariko_program_dst = MemoryRegionVirtualTzramMarikoProgram.GetPointer<void>(); void * const mariko_program_src = MemoryRegionPhysicalMarikoProgramImage.GetPointer<void>(); const size_t mariko_program_size = MemoryRegionVirtualTzramMarikoProgram.GetSize(); if (fuse::GetSocType() == fuse::SocType_Mariko) { /* On Mariko, we want to load the mariko program image into mariko tzram. */ std::memcpy(mariko_program_dst, mariko_program_src, mariko_program_size); hw::FlushDataCache(mariko_program_dst, mariko_program_size); } else { /* On Erista, we don't have mariko-only-tzram, so unmap it. */ u64 * const l1 = MemoryRegionVirtualTzramL1PageTable.GetPointer<u64>(); u64 * const l2_l3 = MemoryRegionVirtualTzramL2L3PageTable.GetPointer<u64>(); UnmapMarikoProgramImpl(l1, l2_l3, l2_l3); } /* Clear the Mariko program image from DRAM. */ util::ClearMemory(mariko_program_src, mariko_program_size); hw::FlushDataCache(mariko_program_src, mariko_program_size); hw::DataSynchronizationBarrierInnerShareable(); /* Ensure the mappings are consistent. */ secmon::boot::EnsureMappingConsistency(); } }
18,954
C++
.cpp
322
46.978261
171
0.623779
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,357
secmon_main.cpp
Atmosphere-NX_Atmosphere/exosphere/program/source/boot/secmon_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 <exosphere.hpp> #include "secmon_boot.hpp" #include "secmon_boot_functions.hpp" #include "../smc/secmon_random_cache.hpp" #include "../smc/secmon_smc_handler.hpp" #include "../secmon_cache.hpp" #include "../secmon_cpu_context.hpp" #include "../secmon_misc.hpp" #include "../secmon_setup.hpp" namespace ams::secmon { namespace { constexpr inline const uintptr_t Package2LoadAddress = MemoryRegionDramPackage2Payloads.GetAddress(); } void Main() { /* Set library register addresses. */ actmon::SetRegisterAddress(MemoryRegionVirtualDeviceActivityMonitor.GetAddress()); clkrst::SetRegisterAddress(MemoryRegionVirtualDeviceClkRst.GetAddress()); flow::SetRegisterAddress(MemoryRegionVirtualDeviceFlowController.GetAddress()); fuse::SetRegisterAddress(MemoryRegionVirtualDeviceFuses.GetAddress()); gic::SetRegisterAddress(MemoryRegionVirtualDeviceGicDistributor.GetAddress(), MemoryRegionVirtualDeviceGicCpuInterface.GetAddress()); i2c::SetRegisterAddress(i2c::Port_1, MemoryRegionVirtualDeviceI2c1.GetAddress()); i2c::SetRegisterAddress(i2c::Port_5, MemoryRegionVirtualDeviceI2c5.GetAddress()); pinmux::SetRegisterAddress(MemoryRegionVirtualDeviceApbMisc.GetAddress(), MemoryRegionVirtualDeviceGpio.GetAddress()); pmc::SetRegisterAddress(MemoryRegionVirtualDevicePmc.GetAddress()); se::SetRegisterAddress(MemoryRegionVirtualDeviceSecurityEngine.GetAddress(), MemoryRegionVirtualDeviceSecurityEngine2.GetAddress()); uart::SetRegisterAddress(MemoryRegionVirtualDeviceUart.GetAddress()); wdt::SetRegisterAddress(MemoryRegionVirtualDeviceTimer.GetAddress()); util::SetRegisterAddress(MemoryRegionVirtualDeviceTimer.GetAddress()); /* Get the secure monitor parameters. */ auto &secmon_params = *reinterpret_cast<pkg1::SecureMonitorParameters *>(MemoryRegionVirtualDeviceBootloaderParams.GetAddress()); /* Perform initialization. */ { /* Perform initial setup. */ /* This checks the security engine's validity, and configures common interrupts in the GIC. */ /* This also initializes the global configuration context. */ secmon::Setup1(); AMS_SECMON_LOG("%s\n", "Boot begin."); /* Save the boot info. */ secmon::SaveBootInfo(secmon_params); /* Perform cold-boot specific init. */ secmon::boot::InitializeColdBoot(); /* Setup the SoC security measures. */ secmon::SetupSocSecurity(); /* Setup the Cpu core context. */ secmon::SetupCpuCoreContext(); /* Clear the crt0 code that was present in iram. */ secmon::boot::ClearIramBootCode(); /* Clear the debug code from iram, if we're not in debug config. */ #if !defined(AMS_BUILD_FOR_DEBUGGING) && !defined(AMS_BUILD_FOR_AUDITING) secmon::boot::ClearIramDebugCode(); #endif /* Alert the bootloader that we're initialized. */ secmon_params.secmon_state = pkg1::SecureMonitorState_Initialized; hw::FlushDataCache(std::addressof(secmon_params.secmon_state), sizeof(secmon_params.secmon_state)); hw::DataSynchronizationBarrierInnerShareable(); } /* Wait for NX Bootloader to finish loading the BootConfig. */ secmon::boot::WaitForNxBootloader(secmon_params, pkg1::BootloaderState_LoadedBootConfig); hw::DataSynchronizationBarrierInnerShareable(); /* Load the bootconfig. */ secmon::boot::LoadBootConfig(MemoryRegionPhysicalIramBootConfig.GetPointer()); /* Verify or clear the boot config. */ secmon::boot::VerifyOrClearBootConfig(); /* Get the boot config. */ const auto &bc = secmon::GetBootConfig(); /* Set the tsc value by the boot config. */ { constexpr u64 TscMask = (static_cast<u64>(1) << 55) - 1; secmon::boot::EnableTsc(bc.data.GetInitialTscValue() & TscMask); } /* Wait for NX Bootloader to initialize DRAM. */ secmon::boot::WaitForNxBootloader(secmon_params, pkg1::BootloaderState_InitializedDram); /* Secure the PMC and MC. */ secmon::SetupPmcAndMcSecure(); /* Copy warmboot to dram. */ { /* Define warmboot extents. */ const void * const src = MemoryRegionPhysicalIramWarmbootBin.GetPointer(); void * const dst = MemoryRegionVirtualDramSecureDataStoreWarmbootFirmware.GetPointer(); const size_t size = MemoryRegionPhysicalIramWarmbootBin.GetSize(); /* Ensure we copy the correct data. */ hw::FlushDataCache(src, size); hw::DataSynchronizationBarrierInnerShareable(); /* Copy warmboot.bin to its secure dram location. */ std::memcpy(dst, src, size); } /* Load the mariko program image. */ secmon::boot::LoadMarikoProgram(); /* Setup the GPU carveout's magic numbers. */ secmon::boot::WriteGpuCarveoutMagicNumbers(); /* Wait for NX bootloader to load Package2. */ secmon::boot::WaitForNxBootloader(secmon_params, pkg1::BootloaderState_LoadedPackage2); /* Parse and decrypt the package2 header. */ pkg2::Package2Meta &pkg2_meta = secmon::boot::GetEphemeralPackage2Meta(); const uintptr_t pkg2_payloads_start = MemoryRegionDramPackage2.GetAddress() + sizeof(pkg2::Package2Header); { /* Read the encrypred header. */ pkg2::Package2Header encrypted_header; const auto *dram_header = MemoryRegionDramPackage2.GetPointer<pkg2::Package2Header>(); hw::FlushDataCache(dram_header, sizeof(*dram_header)); hw::DataSynchronizationBarrierInnerShareable(); std::memcpy(std::addressof(encrypted_header), dram_header, sizeof(encrypted_header)); /* Atmosphere extension: support plaintext package2, identified by all-zeroes signature and decrypted header. */ secmon::boot::UpdateBootConfigForPackage2Header(encrypted_header); /* Verify the package2 header's signature. */ secmon::boot::VerifyPackage2HeaderSignature(encrypted_header, !bc.signed_data.IsPackage2SignatureVerificationDisabled()); /* Decrypt the package2 header. */ secmon::boot::DecryptPackage2Header(std::addressof(pkg2_meta), encrypted_header.meta, !bc.signed_data.IsPackage2EncryptionDisabled()); } /* Verify the package2 header. */ secmon::boot::VerifyPackage2Header(pkg2_meta); /* Save the package2 hash if in recovery boot. */ if (secmon::IsRecoveryBoot()) { se::Sha256Hash hash; secmon::boot::CalculatePackage2Hash(std::addressof(hash), pkg2_meta, MemoryRegionDramPackage2.GetAddress()); secmon::SetPackage2Hash(hash); } /* Verify the package2 payloads. */ secmon::boot::CheckVerifyResult(secmon::boot::VerifyPackage2Payloads(pkg2_meta, pkg2_payloads_start), pkg1::ErrorInfo_InvalidPackage2Payload, "pkg2 payload FAIL"); /* Decrypt/Move the package2 payloads to the right places. */ secmon::boot::DecryptAndLoadPackage2Payloads(Package2LoadAddress, pkg2_meta, pkg2_payloads_start, !bc.signed_data.IsPackage2EncryptionDisabled()); /* Ensure that the CPU sees correct package2 data. */ secmon::FlushEntireDataCache(); secmon::EnsureInstructionConsistency(); /* Set the core's entrypoint and argument. */ secmon::SetEntryContext(0, Package2LoadAddress + pkg2_meta.entrypoint, 0); /* Clear the boot keys from iram. */ secmon::boot::ClearIramBootKeys(); /* Unmap the identity mapping. */ secmon::boot::UnmapPhysicalIdentityMapping(); /* Unmap DRAM. */ secmon::boot::UnmapDram(); /* Wait for NX bootloader to be done. */ secmon::boot::WaitForNxBootloader(secmon_params, pkg1::BootloaderState_Done); /* Perform final initialization. */ secmon::SetupSocProtections(); secmon::SetupCpuSErrorDebug(); /* Configure the smc handler tables to reflect the current target firmware. */ secmon::smc::ConfigureSmcHandlersForTargetFirmware(); AMS_SECMON_LOG("%s\n", "Boot end."); } }
9,119
C++
.cpp
157
48.656051
171
0.682522
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,358
secmon_boot_cache.cpp
Atmosphere-NX_Atmosphere/exosphere/program/source/boot/secmon_boot_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 <exosphere.hpp> #include "secmon_boot_cache.hpp" namespace ams::secmon::boot { #include "../secmon_cache_impl.inc" }
767
C++
.cpp
20
36.35
76
0.751678
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,359
secmon_make_page_table.cpp
Atmosphere-NX_Atmosphere/exosphere/program/source/boot/secmon_make_page_table.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 <exosphere.hpp> #include "../secmon_setup.hpp" #include "secmon_boot.hpp" namespace ams::secmon::boot { namespace { using namespace ams::mmu; constexpr inline PageTableMappingAttribute MappingAttributesEl3SecureRoCode = AddMappingAttributeIndex(PageTableMappingAttributes_El3SecureRoCode, MemoryAttributeIndexNormal); constexpr inline PageTableMappingAttribute MappingAttributesEl3SecureRwCode = AddMappingAttributeIndex(PageTableMappingAttributes_El3SecureRwCode, MemoryAttributeIndexNormal); constexpr inline PageTableMappingAttribute MappingAttributesEl3SecureRoData = AddMappingAttributeIndex(PageTableMappingAttributes_El3SecureRoData, MemoryAttributeIndexNormal); constexpr inline PageTableMappingAttribute MappingAttributesEl3SecureRwData = AddMappingAttributeIndex(PageTableMappingAttributes_El3SecureRwData, MemoryAttributeIndexNormal); constexpr inline PageTableMappingAttribute MappingAttributesEl3NonSecureRwData = AddMappingAttributeIndex(PageTableMappingAttributes_El3NonSecureRwData, MemoryAttributeIndexNormal); constexpr inline PageTableMappingAttribute MappingAttributesEl3SecureDevice = AddMappingAttributeIndex(PageTableMappingAttributes_El3SecureRwData, MemoryAttributeIndexDevice); constexpr inline PageTableMappingAttribute MappingAttributesEl3NonSecureDevice = AddMappingAttributeIndex(PageTableMappingAttributes_El3NonSecureRwData, MemoryAttributeIndexDevice); constexpr void ClearMemory(volatile u64 *start, size_t size) { volatile u64 * const end = start + (size / sizeof(u64)); for (volatile u64 *cur = start; cur < end; ++cur) { *cur = 0; } } constexpr void MakePageTablesImpl(u64 *l1, u64 *l2, u64 *l3) { /* Setup the L1 table. */ { ClearMemory(l1, MemoryRegionPhysicalTzramL1PageTable.GetSize()); /* Create an L1 table entry for the physical region. */ SetL1TableEntry(l1, MemoryRegionPhysical.GetAddress(), MemoryRegionPhysicalTzramL2L3PageTable.GetAddress(), PageTableTableAttributes_El3SecureCode); static_assert(GetL1EntryIndex(MemoryRegionPhysical.GetAddress()) == 1); /* Create an L1 mapping entry for dram. */ SetL1BlockEntry(l1, MemoryRegionDram.GetAddress(), MemoryRegionDram.GetAddress(), MemoryRegionDram.GetSize(), MappingAttributesEl3NonSecureRwData); /* Create an L1 table entry for the virtual region. */ SetL1TableEntry(l1, MemoryRegionVirtual.GetAddress(), MemoryRegionPhysicalTzramL2L3PageTable.GetAddress(), PageTableTableAttributes_El3SecureCode); } /* Setup the L2 table. */ { ClearMemory(l2, MemoryRegionPhysicalTzramL2L3PageTable.GetSize()); /* Create an L2 table entry for the virtual region. */ SetL2TableEntry(l2, MemoryRegionVirtualL2.GetAddress(), MemoryRegionPhysicalTzramL2L3PageTable.GetAddress(), PageTableTableAttributes_El3SecureCode); /* Create an L2 table entry for the physical iram region. */ SetL2TableEntry(l2, MemoryRegionPhysicalIramL2.GetAddress(), MemoryRegionPhysicalTzramL2L3PageTable.GetAddress(), PageTableTableAttributes_El3SecureCode); /* Create an L2 table entry for the physical tzram region. */ SetL2TableEntry(l2, MemoryRegionPhysicalTzramL2.GetAddress(), MemoryRegionPhysicalTzramL2L3PageTable.GetAddress(), PageTableTableAttributes_El3SecureCode); } /* Setup the L3 table. */ { /* L2 and L3 share a page table. */ if (l2 != l3) { ClearMemory(l3, MemoryRegionPhysicalTzramL2L3PageTable.GetSize()); } /* Identity-map TZRAM as rwx. */ SetL3BlockEntry(l3, MemoryRegionPhysicalTzram.GetAddress(), MemoryRegionPhysicalTzram.GetAddress(), MemoryRegionPhysicalTzram.GetSize(), MappingAttributesEl3SecureRwCode); /* Identity-map IRAM boot code as rwx. */ SetL3BlockEntry(l3, MemoryRegionPhysicalIramBootCode.GetAddress(), MemoryRegionPhysicalIramBootCode.GetAddress(), MemoryRegionPhysicalIramBootCode.GetSize(), MappingAttributesEl3SecureRwCode); #if defined(AMS_BUILD_FOR_DEBUGGING) || defined(AMS_BUILD_FOR_AUDITING) { /* Map the debug code region as rwx. */ SetL3BlockEntry(l3, MemoryRegionVirtualDebugCode.GetAddress(), MemoryRegionPhysicalDebugCode.GetAddress(), MemoryRegionPhysicalDebugCode.GetSize(), MappingAttributesEl3SecureRwCode); /* Map the DRAM debug code store region as rw. */ SetL3BlockEntry(l3, MemoryRegionVirtualDramDebugDataStore.GetAddress(), MemoryRegionPhysicalDramDebugDataStore.GetAddress(), MemoryRegionPhysicalDramDebugDataStore.GetSize(), MappingAttributesEl3NonSecureRwData); } #endif /* Map all devices. */ { #define MAP_DEVICE_REGION(_NAME_, _PREV_, _ADDRESS_, _SIZE_, _SECURE_) \ SetL3BlockEntry(l3, MemoryRegionVirtualDevice##_NAME_.GetAddress(), MemoryRegionPhysicalDevice##_NAME_.GetAddress(), MemoryRegionVirtualDevice##_NAME_.GetSize(), _SECURE_ ? MappingAttributesEl3SecureDevice : MappingAttributesEl3NonSecureDevice); AMS_SECMON_FOREACH_DEVICE_REGION(MAP_DEVICE_REGION); #undef MAP_DEVICE_REGION } /* Map the IRAM SC7 work region. */ SetL3BlockEntry(l3, MemoryRegionVirtualIramSc7Work.GetAddress(), MemoryRegionPhysicalIramSc7Work.GetAddress(), MemoryRegionVirtualIramSc7Work.GetSize(), MappingAttributesEl3NonSecureDevice); /* Map the IRAM SC7 firmware region. */ SetL3BlockEntry(l3, MemoryRegionVirtualIramSc7Firmware.GetAddress(), MemoryRegionPhysicalIramSc7Firmware.GetAddress(), MemoryRegionVirtualIramSc7Firmware.GetSize(), MappingAttributesEl3NonSecureDevice); /* Map the Debug region. */ /* NOTE: This region is reserved for debug. By default it will be the last 0x8000 bytes of IRAM, but this is subject to change. */ /* If you are doing development work for exosphere, feel free to locally change this to whatever is useful. */ SetL3BlockEntry(l3, MemoryRegionVirtualDebug.GetAddress(), MemoryRegionPhysicalIram.GetEndAddress() - 0x8000, 0x8000, MappingAttributesEl3SecureDevice); /* Map the TZRAM ro alias region. */ SetL3BlockEntry(l3, MemoryRegionVirtualTzramReadOnlyAlias.GetAddress(), MemoryRegionPhysicalTzramReadOnlyAlias.GetAddress(), MemoryRegionVirtualTzramReadOnlyAlias.GetSize(), MappingAttributesEl3SecureRoData); /* Map the DRAM secure data store region. */ SetL3BlockEntry(l3, MemoryRegionVirtualDramSecureDataStore.GetAddress(), MemoryRegionPhysicalDramSecureDataStore.GetAddress(), MemoryRegionVirtualDramSecureDataStore.GetSize(), MappingAttributesEl3NonSecureDevice); /* Map the program region as rwx. */ SetL3BlockEntry(l3, MemoryRegionVirtualTzramProgram.GetAddress(), MemoryRegionPhysicalTzramProgram.GetAddress(), MemoryRegionVirtualTzramProgram.GetSize(), MappingAttributesEl3SecureRwCode); /* Map the mariko program region as rwx. */ SetL3BlockEntry(l3, MemoryRegionVirtualTzramMarikoProgram.GetAddress(), MemoryRegionPhysicalTzramMarikoProgram.GetAddress(), MemoryRegionPhysicalTzramMarikoProgram.GetSize(), MappingAttributesEl3SecureRwCode); /* Map the mariko program region as rwx. */ SetL3BlockEntry(l3, MemoryRegionVirtualTzramMarikoProgramStack.GetAddress(), MemoryRegionPhysicalTzramMarikoProgramStack.GetAddress(), MemoryRegionPhysicalTzramMarikoProgramStack.GetSize(), MappingAttributesEl3SecureRwData); /* Map the boot code region. */ SetL3BlockEntry(l3, MemoryRegionVirtualTzramBootCode.GetAddress(), MemoryRegionPhysicalTzramBootCode.GetAddress(), MemoryRegionVirtualTzramBootCode.GetSize(), MappingAttributesEl3SecureRwCode); /* Map the volatile data regions regions. */ SetL3BlockEntry(l3, MemoryRegionVirtualTzramVolatileData.GetAddress(), MemoryRegionPhysicalTzramVolatileData.GetAddress(), MemoryRegionVirtualTzramVolatileData.GetSize(), MappingAttributesEl3SecureRwData); SetL3BlockEntry(l3, MemoryRegionVirtualTzramVolatileStack.GetAddress(), MemoryRegionPhysicalTzramVolatileStack.GetAddress(), MemoryRegionVirtualTzramVolatileStack.GetSize(), MappingAttributesEl3SecureRwData); /* Map the configuration data. */ SetL3BlockEntry(l3, MemoryRegionVirtualTzramConfigurationData.GetAddress(), MemoryRegionPhysicalTzramConfigurationData.GetAddress(), MemoryRegionVirtualTzramConfigurationData.GetSize(), MappingAttributesEl3SecureRwData); /* Map the page tables. */ SetL3BlockEntry(l3, util::AlignDown(MemoryRegionVirtualTzramL1PageTable.GetAddress(), PageSize), util::AlignDown(MemoryRegionPhysicalTzramL1PageTable.GetAddress(), PageSize), PageSize, MappingAttributesEl3SecureRwData); SetL3BlockEntry(l3, MemoryRegionVirtualTzramL2L3PageTable.GetAddress(), MemoryRegionPhysicalTzramL2L3PageTable.GetAddress(), MemoryRegionVirtualTzramL2L3PageTable.GetSize(), MappingAttributesEl3SecureRwData); } } constexpr bool ValidateTzramPageTables() { u64 l1_table[MemoryRegionPhysicalTzramL1PageTable.GetSize() / sizeof(u64)] = {}; u64 l2_l3_table[MemoryRegionPhysicalTzramL2L3PageTable.GetSize() / sizeof(u64)] = {}; MakePageTablesImpl(l1_table, l2_l3_table, l2_l3_table); return true; } static_assert(ValidateTzramPageTables()); } void MakePageTable() { u64 * const l1 = MemoryRegionPhysicalTzramL1PageTable.GetPointer<u64>(); u64 * const l2_l3 = MemoryRegionPhysicalTzramL2L3PageTable.GetPointer<u64>(); MakePageTablesImpl(l1, l2_l3, l2_l3); } }
11,007
C++
.cpp
125
74.88
269
0.725503
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,360
secmon_crt0_cpp.cpp
Atmosphere-NX_Atmosphere/exosphere/program/source/boot/secmon_crt0_cpp.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 <exosphere.hpp> #include "secmon_boot.hpp" #include "../secmon_setup.hpp" extern "C" void __libc_init_array(); namespace ams::secmon::boot { void Initialize(uintptr_t bss_start, size_t bss_end, uintptr_t boot_bss_start, uintptr_t boot_bss_end) { /* Set our start time. */ auto &secmon_params = *MemoryRegionPhysicalDeviceBootloaderParams.GetPointer<pkg1::SecureMonitorParameters>(); secmon_params.secmon_start_time = *reinterpret_cast<volatile u32 *>(MemoryRegionPhysicalDeviceTimer.GetAddress() + 0x10); /* Setup DMA controllers. */ SetupSocDmaControllers(); /* Make the page table. */ MakePageTable(); /* Setup memory controllers the MMU. */ SetupCpuMemoryControllersEnableMmu(); /* Clear bss. */ std::memset(reinterpret_cast<void *>(bss_start), 0, bss_end - bss_start); std::memset(reinterpret_cast<void *>(boot_bss_start), 0, boot_bss_end - boot_bss_start); /* Call init array. */ __libc_init_array(); } }
1,687
C++
.cpp
37
40.756757
129
0.695493
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,361
secmon_package2.cpp
Atmosphere-NX_Atmosphere/exosphere/program/source/boot/secmon_package2.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 <exosphere.hpp> #include "../secmon_error.hpp" #include "../secmon_key_storage.hpp" #include "secmon_boot.hpp" namespace ams::secmon::boot { void CalculatePackage2Hash(se::Sha256Hash *dst, const pkg2::Package2Meta &meta, uintptr_t package2_start) { /* Determine the region to hash. */ const void *data = reinterpret_cast<const void *>(package2_start); const size_t size = meta.GetSize(); /* Flush to ensure the SE sees the correct data. */ hw::FlushDataCache(data, size); hw::DataSynchronizationBarrierInnerShareable(); /* Calculate the hash. */ se::CalculateSha256(dst, data, size); } bool VerifyPackage2Signature(pkg2::Package2Header &header, const void *mod, size_t mod_size) { return VerifySignature(header.signature, sizeof(header.signature), mod, mod_size, std::addressof(header.meta), sizeof(header.meta)); } int PrepareMasterKey(int key_generation) { if (key_generation == GetKeyGeneration()) { return pkg1::AesKeySlot_Master; } constexpr int Slot = pkg1::AesKeySlot_Temporary; LoadMasterKey(Slot, key_generation); return Slot; } void PreparePackage2Key(int pkg2_slot, int key_generation, const void *key, size_t key_size) { /* Get keyslot for the desired master key. */ const int master_slot = PrepareMasterKey(key_generation); /* Load the package2 key into the desired keyslot. */ se::SetEncryptedAesKey128(pkg2_slot, master_slot, key, key_size); } void DecryptPackage2(void *dst, size_t dst_size, const void *src, size_t src_size, const void *key, size_t key_size, const void *iv, size_t iv_size, u8 key_generation) { /* Ensure that the SE sees consistent data. */ hw::FlushDataCache(key, key_size); hw::FlushDataCache(src, src_size); hw::FlushDataCache(dst, dst_size); hw::DataSynchronizationBarrierInnerShareable(); /* Load the package2 key into the temporary keyslot. */ PreparePackage2Key(pkg1::AesKeySlot_Temporary, key_generation, key, key_size); /* Decrypt the data. */ se::ComputeAes128Ctr(dst, dst_size, pkg1::AesKeySlot_Temporary, src, src_size, iv, iv_size); /* Clear the keyslot we just used. */ se::ClearAesKeySlot(pkg1::AesKeySlot_Temporary); /* Ensure that the cpu sees consistent data. */ hw::DataSynchronizationBarrierInnerShareable(); hw::FlushDataCache(dst, dst_size); hw::DataSynchronizationBarrierInnerShareable(); } bool VerifyPackage2Meta(const pkg2::Package2Meta &meta) { /* Get the obfuscated metadata. */ const size_t size = meta.GetSize(); const u8 key_generation = meta.GetKeyGeneration(); /* Check that size is big enough for the header. */ if (size <= sizeof(pkg2::Package2Header)) { return false; } /* Check that the size isn't larger than what we allow. */ if (size > pkg2::Package2SizeMax) { return false; } /* Check that the key generation is one that we can use. */ static_assert(pkg1::KeyGeneration_Count == 19); if (key_generation >= pkg1::KeyGeneration_Count) { return false; } /* Check the magic number. */ if (!crypto::IsSameBytes(meta.magic, pkg2::Package2Meta::Magic::String, sizeof(meta.magic))) { return false; } /* Check the payload alignments. */ if ((meta.entrypoint % pkg2::PayloadAlignment) != 0) { return false; } for (int i = 0; i < pkg2::PayloadCount; ++i) { if ((meta.payload_sizes[i] % pkg2::PayloadAlignment) != 0) { return false; } } /* Check that the sizes sum to the total. */ if (size != sizeof(pkg2::Package2Header) + meta.payload_sizes[0] + meta.payload_sizes[1] + meta.payload_sizes[2]) { return false; } /* Check that the payloads do not overflow. */ for (int i = 0; i < pkg2::PayloadCount; ++i) { if (meta.payload_offsets[i] > meta.payload_offsets[i] + meta.payload_sizes[i]) { return false; } } /* Verify that no payloads overlap. */ for (int i = 0; i < pkg2::PayloadCount - 1; ++i) { for (int j = i + 1; j < pkg2::PayloadCount; ++j) { if (util::HasOverlap(meta.payload_offsets[i], meta.payload_sizes[i], meta.payload_offsets[j], meta.payload_sizes[j])) { return false; } } } /* Check whether any payload contains the entrypoint. */ for (int i = 0; i < pkg2::PayloadCount; ++i) { if (util::Contains(meta.payload_offsets[i], meta.payload_sizes[i], meta.entrypoint)) { return true; } } /* No payload contains the entrypoint, so we're not valid. */ return false; } bool VerifyPackage2Version(const pkg2::Package2Meta &meta) { return meta.bootloader_version <= pkg2::CurrentBootloaderVersion && meta.package2_version >= pkg2::MinimumValidDataVersion; } bool VerifyPackage2Payloads(const pkg2::Package2Meta &meta, uintptr_t payload_address) { /* Verify hashes match for all payloads. */ for (int i = 0; i < pkg2::PayloadCount; ++i) { /* Allow all-zero bytes to match any payload. */ if (!(meta.payload_hashes[i][0] == 0 && std::memcmp(meta.payload_hashes[i] + 0, meta.payload_hashes[i] + 1, sizeof(meta.payload_hashes[i]) - 1) == 0)) { if (!VerifyHash(meta.payload_hashes[i], payload_address, meta.payload_sizes[i])) { return false; } } payload_address += meta.payload_sizes[i]; } return true; } }
6,580
C++
.cpp
138
38.898551
173
0.622465
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,362
sc7fw_main.cpp
Atmosphere-NX_Atmosphere/exosphere/program/sc7fw/source/sc7fw_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 <exosphere.hpp> #include "sc7fw_util.hpp" #include "sc7fw_dram.hpp" namespace ams::sc7fw { namespace { constexpr inline const uintptr_t PMC = secmon::MemoryRegionPhysicalDevicePmc.GetAddress(); void DisableCrail() { /* Wait for CRAIL to be off. */ while (!reg::HasValue(PMC + APBDEV_PMC_PWRGATE_STATUS, PMC_REG_BITS_ENUM(PWRGATE_STATUS_CRAIL, OFF))) { /* ... */ } /* Set CRAIL to be clamped. */ reg::ReadWrite(PMC + APBDEV_PMC_SET_SW_CLAMP, PMC_REG_BITS_VALUE(SET_SW_CLAMP_CRAIL, 1)); /* Wait for CRAIL to be clamped. */ while (!reg::HasValue(PMC + APBDEV_PMC_CLAMP_STATUS, PMC_REG_BITS_ENUM(CLAMP_STATUS_CRAIL, ENABLE))) { /* ... */ } /* Spin loop for a short while, to allow time for the clamp to take effect. */ sc7fw::SpinLoop(10); /* Initialize i2c-5. */ i2c::Initialize(i2c::Port_5); /* Disable the voltage to CPU. */ pmic::DisableVddCpu(fuse::GetRegulator()); /* Wait 700 microseconds to ensure voltage is disabled. */ util::WaitMicroSeconds(700); } void DisableAllInterrupts() { /* Disable all interrupts for bpmp in all interrupt controllers. */ reg::Write(PRI_ICTLR(ICTLR_COP_IER_CLR), ~0u); reg::Write(SEC_ICTLR(ICTLR_COP_IER_CLR), ~0u); reg::Write(TRI_ICTLR(ICTLR_COP_IER_CLR), ~0u); reg::Write(QUAD_ICTLR(ICTLR_COP_IER_CLR), ~0u); reg::Write(PENTA_ICTLR(ICTLR_COP_IER_CLR), ~0u); reg::Write(HEXA_ICTLR(ICTLR_COP_IER_CLR), ~0u); } void EnterSc7() { /* Disable read buffering and write buffering in the BPMP cache. */ reg::ReadWrite(AVP_CACHE_ADDR(AVP_CACHE_CONFIG), AVP_CACHE_REG_BITS_ENUM(CONFIG_DISABLE_WB, TRUE), AVP_CACHE_REG_BITS_ENUM(CONFIG_DISABLE_RB, TRUE)); /* Ensure the CPU Rail is turned off. */ DisableCrail(); /* Disable all interrupts. */ DisableAllInterrupts(); /* Save the EMC FSP */ SaveEmcFsp(); /* Enable self-refresh for DRAM */ EnableSdramSelfRefresh(); /* Enable refresh for all EMC devices. */ EnableEmcAllSegmentsRefresh(); /* Enable deep power-down for ddr. */ EnableDdrDeepPowerDown(); /* Enable pad sampling during deep sleep. */ reg::ReadWrite(PMC + APBDEV_PMC_DPD_SAMPLE, PMC_REG_BITS_ENUM(DPD_SAMPLE_ON, ENABLE)); reg::Read(PMC + APBDEV_PMC_DPD_SAMPLE); /* Wait a while for pad sampling to be enabled. */ sc7fw::SpinLoop(0x128); /* Enter deep sleep. */ reg::ReadWrite(PMC + APBDEV_PMC_DPD_ENABLE, PMC_REG_BITS_ENUM(DPD_ENABLE_ON, ENABLE)); /* Wait forever until we're asleep. */ AMS_INFINITE_LOOP(); } } void Main() { EnterSc7(); } NORETURN void ExceptionHandler() { /* Write enable to MAIN_RESET. */ reg::Write(PMC + APBDEV_PMC_CNTRL, PMC_REG_BITS_ENUM(CNTRL_MAIN_RESET, ENABLE)); /* Wait forever until we're reset. */ AMS_INFINITE_LOOP(); } } namespace ams::diag { NORETURN void AbortImpl() { sc7fw::ExceptionHandler(); } #include <exosphere/diag/diag_detailed_assertion_impl.inc> }
4,140
C++
.cpp
89
36.820225
127
0.600995
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,363
sc7fw_dram.cpp
Atmosphere-NX_Atmosphere/exosphere/program/sc7fw/source/sc7fw_dram.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 <exosphere.hpp> #include "sc7fw_util.hpp" #include "sc7fw_dram.hpp" namespace ams::sc7fw { namespace { constexpr inline const uintptr_t PMC = secmon::MemoryRegionPhysicalDevicePmc.GetAddress(); void UpdateEmcTiming() { /* Enable timing update. */ reg::Write(EMC_ADDRESS(EMC_TIMING_CONTROL), EMC_REG_BITS_ENUM(TIMING_CONTROL_TIMING_UPDATE, ENABLED)); /* Wait for the timing update to complete. */ while (!reg::HasValue(EMC_ADDRESS(EMC_EMC_STATUS), EMC_REG_BITS_ENUM(EMC_STATUS_TIMING_UPDATE_STALLED, DONE))) { /* ... */ } } void RequestAllPadsPowerDown(uintptr_t addr, uintptr_t expected) { constexpr u32 DpdAllRequestValue = reg::Encode(PMC_REG_BITS_ENUM(IO_DPD_REQ_CODE, DPD_ON)) | 0x0FFFFFFF; const auto RequestAddress = addr; const auto StatusAddress = addr + 4; /* Request all pads enter power down. */ reg::Write(PMC + RequestAddress, DpdAllRequestValue); /* Wait until the status reflects our expectation (and all pads are shut down). */ while (reg::Read(PMC + StatusAddress) != expected) { /* ... */ } /* Wait a little while to allow the power down status to propagate. */ SpinLoop(0x20); }; } void SaveEmcFsp() { /* We require that the RAM is LPDDR4. */ AMS_ABORT_UNLESS(reg::HasValue(EMC_ADDRESS(EMC_FBIO_CFG5), EMC_REG_BITS_ENUM(FBIO_CFG5_DRAM_TYPE, LPDDR4))); /* Read the frequency set points from MRW3. */ constexpr u32 FspShift = 6; constexpr u32 FspBits = 2; constexpr u32 FspMask = ((1u << FspBits) - 1) << FspShift; static_assert(FspMask == 0x000000C0); const u32 fsp = (reg::Read(EMC_ADDRESS(EMC_MRW3)) & FspMask) >> FspShift; /* Write the fsp to PMC_SCRATCH18, where it will be restored to MRW3 by brom. */ reg::ReadWrite(PMC + APBDEV_PMC_SCRATCH18, REG_BITS_VALUE(FspShift, FspBits, fsp)); /* Write the fsp twice to PMC_SCRATCH12, where it will be restored to MRW12 by brom. */ reg::ReadWrite(PMC + APBDEV_PMC_SCRATCH12, REG_BITS_VALUE(FspShift, FspBits, fsp), REG_BITS_VALUE(FspShift + 8, FspBits, fsp)); /* Write the fsp twice to PMC_SCRATCH13, where it will be restored to MRW13 by brom. */ reg::ReadWrite(PMC + APBDEV_PMC_SCRATCH13, REG_BITS_VALUE(FspShift, FspBits, fsp), REG_BITS_VALUE(FspShift + 8, FspBits, fsp)); } void EnableSdramSelfRefresh() { /* We require that the RAM is dual-channel. */ AMS_ABORT_UNLESS(reg::HasValue(EMC_ADDRESS(EMC_FBIO_CFG7), EMC_REG_BITS_ENUM(FBIO_CFG7_CH1_ENABLE, ENABLE))); /* Disable RAM's ability to dynamically self-refresh, and to opportunistically perform powerdown. */ reg::Write(EMC_ADDRESS(EMC_CFG), EMC_REG_BITS_ENUM(CFG_DYN_SELF_REF, DISABLED), EMC_REG_BITS_ENUM(CFG_DRAM_ACPD, NO_POWERDOWN)); /* Update the EMC timing. */ UpdateEmcTiming(); /* Wait five microseconds. */ util::WaitMicroSeconds(5); /* Disable ZQ calibration. */ reg::Write(EMC_ADDRESS(EMC_ZCAL_INTERVAL), 0); /* Disable automatic calibration. */ reg::Write(EMC_ADDRESS(EMC_AUTO_CAL_CONFIG), EMC_REG_BITS_ENUM(AUTO_CAL_CONFIG_AUTO_CAL_MEASURE_STALL, ENABLE), EMC_REG_BITS_ENUM(AUTO_CAL_CONFIG_AUTO_CAL_UPDATE_STALL, ENABLE), EMC_REG_BITS_ENUM(AUTO_CAL_CONFIG_AUTO_CAL_START, DISABLE)); /* Get whether digital delay locked loops are enabled. */ const bool has_dll = reg::HasValue(EMC_ADDRESS(EMC_CFG_DIG_DLL), EMC_REG_BITS_ENUM(CFG_DIG_DLL_CFG_DLL_EN, ENABLED)); if (has_dll) { /* If they are, disable them. */ reg::ReadWrite(EMC_ADDRESS(EMC_CFG_DIG_DLL), EMC_REG_BITS_ENUM(CFG_DIG_DLL_CFG_DLL_EN, DISABLED)); } /* Update the EMC timing. */ UpdateEmcTiming(); /* If dll was enabled, wait until both EMC0 and EMC1 have dll disabled. */ if (has_dll) { while (!reg::HasValue(EMC0_ADDRESS(EMC_CFG_DIG_DLL), EMC_REG_BITS_ENUM(CFG_DIG_DLL_CFG_DLL_EN, DISABLED))) { /* ... */ } while (!reg::HasValue(EMC1_ADDRESS(EMC_CFG_DIG_DLL), EMC_REG_BITS_ENUM(CFG_DIG_DLL_CFG_DLL_EN, DISABLED))) { /* ... */ } } /* Stall all reads and writes. */ reg::Write(EMC_ADDRESS(EMC_REQ_CTRL), EMC_REG_BITS_VALUE(REQ_CTRL_STALL_ALL_READS, 1), EMC_REG_BITS_VALUE(REQ_CTRL_STALL_ALL_WRITES, 1)); /* Wait until both EMC0 and EMC1 have no outstanding transactions. */ while (!reg::HasValue(EMC0_ADDRESS(EMC_EMC_STATUS), EMC_REG_BITS_ENUM(EMC_STATUS_NO_OUTSTANDING_TRANSACTIONS, COMPLETED))) { /* ... */ } while (!reg::HasValue(EMC1_ADDRESS(EMC_EMC_STATUS), EMC_REG_BITS_ENUM(EMC_STATUS_NO_OUTSTANDING_TRANSACTIONS, COMPLETED))) { /* ... */ } /* Enable self-refresh. */ reg::Write(EMC_ADDRESS(EMC_SELF_REF), EMC_REG_BITS_ENUM(SELF_REF_SREF_DEV_SELECTN, BOTH), EMC_REG_BITS_ENUM(SELF_REF_SELF_REF_CMD, ENABLED)); /* Wait until both EMC and EMC1 are in self-refresh. */ const auto desired = reg::HasValue(EMC_ADDRESS(EMC_ADR_CFG), EMC_REG_BITS_ENUM(ADR_CFG_EMEM_NUMDEV, N2)) ? EMC_REG_BITS_ENUM(EMC_STATUS_DRAM_IN_SELF_REFRESH, BOTH_ENABLED) : EMC_REG_BITS_ENUM(EMC_STATUS_DRAM_DEV0_IN_SELF_REFRESH, ENABLED); /* NOTE: Nintendo's sc7 entry firmware has a bug here. */ /* Instead of waiting for both EMCs to report self-refresh, they just read the EMC_STATUS for each EMC. */ /* This is incorrect, per documentation. */ while (!reg::HasValue(EMC0_ADDRESS(EMC_EMC_STATUS), desired)) { /* ... */ } while (!reg::HasValue(EMC1_ADDRESS(EMC_EMC_STATUS), desired)) { /* ... */ } } void EnableEmcAllSegmentsRefresh() { constexpr int MR17_PASR_Segment = 17; /* Write zeros to MR17_PASR_Segment to enable refresh for all segments for dev0. */ reg::Write(EMC_ADDRESS(EMC_MRW), EMC_REG_BITS_ENUM (MRW_DEV_SELECTN, DEV0), EMC_REG_BITS_ENUM (MRW_CNT, EXT1), EMC_REG_BITS_VALUE(MRW_MA, MR17_PASR_Segment), EMC_REG_BITS_VALUE(MRW_OP, 0)); /* If dev1 exists, do the same for dev1. */ if (reg::HasValue(EMC_ADDRESS(EMC_ADR_CFG), EMC_REG_BITS_ENUM(ADR_CFG_EMEM_NUMDEV, N2))) { reg::Write(EMC_ADDRESS(EMC_MRW), EMC_REG_BITS_ENUM (MRW_DEV_SELECTN, DEV1), EMC_REG_BITS_ENUM (MRW_CNT, EXT1), EMC_REG_BITS_VALUE(MRW_MA, MR17_PASR_Segment), EMC_REG_BITS_VALUE(MRW_OP, 0)); } } void EnableDdrDeepPowerDown() { /* Read and decode the parameters Nintendo stores in EMC_PMC_SCRATCH3. */ const u32 scratch3 = reg::Read(EMC_ADDRESS(EMC_PMC_SCRATCH3)); const bool weak_bias = (scratch3 & reg::EncodeMask(EMC_REG_BITS_MASK(PMC_SCRATCH3_WEAK_BIAS))) == reg::EncodeValue(EMC_REG_BITS_ENUM(PMC_SCRATCH3_WEAK_BIAS, ENABLED)); const u32 ddr_cntrl = (scratch3 & reg::EncodeMask(EMC_REG_BITS_MASK(PMC_SCRATCH3_DDR_CNTRL))); /* Write the decoded value to PMC_DDR_CNTRL. */ reg::Write(PMC + APBDEV_PMC_DDR_CNTRL, ddr_cntrl); /* If weak bias is enabled, set all VTT_E_WB bits in APBDEV_PMC_WEAK_BIAS. */ if (weak_bias) { constexpr u32 WeakBiasVttEWbAll = 0x7FFF0000; reg::Write(PMC + APBDEV_PMC_WEAK_BIAS, WeakBiasVttEWbAll); } /* Request that DPD3 pads power down. */ constexpr u32 EristaDpd3Mask = 0x0FFFFFFF; constexpr u32 MarikoDpd3Mask = 0x0FFF9FFF; if (fuse::GetSocType() == fuse::SocType_Erista) { RequestAllPadsPowerDown(APBDEV_PMC_IO_DPD3_REQ, EristaDpd3Mask); } else { RequestAllPadsPowerDown(APBDEV_PMC_IO_DPD3_REQ, MarikoDpd3Mask); } /* Request that DPD4 pads power down. */ constexpr u32 Dpd4Mask = 0x0FFF1FFF; RequestAllPadsPowerDown(APBDEV_PMC_IO_DPD4_REQ, Dpd4Mask); } }
9,369
C++
.cpp
144
52.826389
185
0.598563
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,364
secmon_loader_main.cpp
Atmosphere-NX_Atmosphere/exosphere/loader_stub/source/secmon_loader_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 <exosphere.hpp> #include "secmon_loader_uncompress.hpp" #include "program_lz4.h" #include "boot_code_lz4.h" namespace ams::secmon::loader { NORETURN void UncompressAndExecute(const void *program, const void *boot_code) { /* Uncompress the program image. */ Uncompress(secmon::MemoryRegionPhysicalTzramFullProgramImage.GetPointer(), secmon::MemoryRegionPhysicalTzramFullProgramImage.GetSize(), program, program_lz4_size); /* Copy the boot image to the end of IRAM */ u8 *relocated_boot_code = secmon::MemoryRegionPhysicalIramBootCodeImage.GetEndPointer<u8>() - boot_code_lz4_size; std::memcpy(relocated_boot_code, boot_code, boot_code_lz4_size); /* Uncompress the boot image. */ Uncompress(secmon::MemoryRegionPhysicalIramBootCodeImage.GetPointer(), secmon::MemoryRegionPhysicalIramBootCodeImage.GetSize(), relocated_boot_code, boot_code_lz4_size); /* Jump to the boot image. */ reinterpret_cast<void (*)()>(secmon::MemoryRegionPhysicalIramBootCodeImage.GetAddress())(); /* We will never reach this point. */ __builtin_unreachable(); } }
1,783
C++
.cpp
34
48.029412
177
0.736661
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,365
secmon_loader_uncompress.cpp
Atmosphere-NX_Atmosphere/exosphere/loader_stub/source/secmon_loader_uncompress.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 <exosphere.hpp> #include "secmon_loader_uncompress.hpp" namespace ams::secmon::loader { namespace { class Lz4Uncompressor { private: const u8 *m_src; size_t m_src_size; size_t m_src_offset; u8 *m_dst; size_t m_dst_size; size_t m_dst_offset; public: Lz4Uncompressor(void *dst, size_t dst_size, const void *src, size_t src_size) : m_src(static_cast<const u8 *>(src)), m_src_size(src_size), m_src_offset(0), m_dst(static_cast<u8 *>(dst)), m_dst_size(dst_size), m_dst_offset(0) { /* ... */ } void Uncompress() { while (true) { /* Read a control byte. */ const u8 control = this->ReadByte(); /* Copy what it specifies we should copy. */ this->Copy(this->GetCopySize(control >> 4)); /* If we've exceeded size, we're done. */ if (m_src_offset >= m_src_size) { break; } /* Read the wide copy offset. */ u16 wide_offset = this->ReadByte(); AMS_ABORT_UNLESS(this->CanRead()); wide_offset |= (this->ReadByte() << 8); /* Determine the copy size. */ const size_t wide_copy_size = this->GetCopySize(control & 0xF); /* Copy bytes. */ const size_t end_offset = m_dst_offset + wide_copy_size + 4; for (size_t cur_offset = m_dst_offset; cur_offset < end_offset; m_dst_offset = (++cur_offset)) { AMS_ABORT_UNLESS(wide_offset <= cur_offset); m_dst[cur_offset] = m_dst[cur_offset - wide_offset]; } } } private: u8 ReadByte() { return m_src[m_src_offset++]; } bool CanRead() const { return m_src_offset < m_src_size; } size_t GetCopySize(u8 control) { size_t size = control; if (control >= 0xF) { do { AMS_ABORT_UNLESS(this->CanRead()); control = this->ReadByte(); size += control; } while (control == 0xFF); } return size; } void Copy(size_t size) { __builtin_memcpy(m_dst + m_dst_offset, m_src + m_src_offset, size); m_dst_offset += size; m_src_offset += size; } }; } void Uncompress(void *dst, size_t dst_size, const void *src, size_t src_size) { /* Create an execute a decompressor. */ Lz4Uncompressor(dst, dst_size, src, src_size).Uncompress(); } }
3,829
C++
.cpp
85
29.141176
242
0.474376
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,366
secmon_loader_error.cpp
Atmosphere-NX_Atmosphere/exosphere/loader_stub/source/secmon_loader_error.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 <exosphere.hpp> #include "secmon_loader_error.hpp" namespace ams::diag { NORETURN void AbortImpl(const char *expr, const char *func, const char *file, int line) { AMS_UNUSED(expr, func, line, file); ams::secmon::loader::ErrorReboot(); } NORETURN void AbortImpl(const char *expr, const char *func, const char *file, int line, const char *format, ...) { AMS_UNUSED(expr, func, line, file, format); ams::secmon::loader::ErrorReboot(); } NORETURN void AbortImpl() { ams::secmon::loader::ErrorReboot(); } } namespace ams::secmon::loader { NORETURN void ErrorReboot() { /* Invalidate the security engine. */ /* TODO */ /* Reboot. */ while (true) { wdt::Reboot(); } } }
1,439
C++
.cpp
40
31.325
118
0.673616
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,367
fatal_abort_impl.cpp
Atmosphere-NX_Atmosphere/exosphere/mariko_fatal/source/fatal_abort_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 <exosphere.hpp> namespace ams::diag { NORETURN void AbortImpl() { AMS_SECMON_LOG("AbortImpl was called\n"); AMS_LOG_FLUSH(); reg::Write(0x4, 0xAAAAAAAA); /* TODO: Reboot */ AMS_INFINITE_LOOP(); } #include <exosphere/diag/diag_detailed_assertion_impl.inc> }
958
C++
.cpp
26
33.115385
76
0.713053
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,368
fatal_sdmmc_c.cpp
Atmosphere-NX_Atmosphere/exosphere/mariko_fatal/source/fatal_sdmmc_c.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 <exosphere.hpp> #include "fatal_sdmmc_c.h" #include "fatal_sdmmc.hpp" bool sdmmc_read_sd_card(void *dst, size_t size, size_t sector_index, size_t sector_count) { return R_SUCCEEDED(ams::secmon::fatal::ReadSdCard(dst, size, sector_index, sector_count)); } bool sdmmc_write_sd_card(size_t sector_index, size_t sector_count, const void *src, size_t size) { return R_SUCCEEDED(ams::secmon::fatal::WriteSdCard(sector_index, sector_count, src, size)); }
1,102
C++
.cpp
24
43.916667
98
0.749071
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,369
fatal_sound.cpp
Atmosphere-NX_Atmosphere/exosphere/mariko_fatal/source/fatal_sound.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 <exosphere.hpp> #include "fatal_sound.hpp" namespace ams::secmon::fatal { namespace { constexpr inline int I2cAddressMaxAlc5639 = 0x1C; constexpr inline uintptr_t GPIO = secmon::MemoryRegionVirtualDeviceGpio.GetAddress(); constexpr size_t GPIO_PORT7_CNF_1 = 0x604; constexpr size_t GPIO_PORT7_OE_1 = 0x614; constexpr size_t GPIO_PORT7_OUT_1 = 0x624; void WriteAlc5639Register(int r, u16 val) { i2c::Send(i2c::Port_1, I2cAddressMaxAlc5639, r, std::addressof(val), sizeof(val)); } } void StopSound() { /* Mute output to the speaker, setting left/right volume to 0 DB. */ WriteAlc5639Register(0x01, 0xC8C8); /* Mute output to headphones, setting left/right volume to 0 DB. */ WriteAlc5639Register(0x02, 0xC8C8); /* Clear all Power Management Control registers by writing 0x0000 to them. */ for (int r = 0x61; r <= 0x66; ++r) { WriteAlc5639Register(r, 0x0000); } /* Configure CodecLdoEn as GPIO. */ reg::SetBits(GPIO + GPIO_PORT7_CNF_1, (1u << 4)); /* Configure CodecLdoEn as Output. */ reg::SetBits(GPIO + GPIO_PORT7_OE_1, (1u << 4)); /* Wait 200 milliseconds for config to take effect. */ util::WaitMicroSeconds(200'000ul); /* Pull CodecLdoEn low. */ reg::ClearBits(GPIO + GPIO_PORT7_OUT_1, (1u << 4)); } }
2,081
C++
.cpp
47
38.06383
94
0.666667
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,370
fatal_print.cpp
Atmosphere-NX_Atmosphere/exosphere/mariko_fatal/source/fatal_print.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 <exosphere.hpp> #include "fatal_display.hpp" #include "fatal_print.hpp" namespace ams::secmon::fatal { namespace { #include "fatal_font.inc" constexpr inline const u32 TextColor = 0xFFA0A0A0; constexpr inline const size_t ConsoleWidth = FrameBufferWidth / FontWidth; constexpr inline const size_t ConsoleHeight = FrameBufferHeight / FontHeight; constinit u32 *g_frame_buffer = nullptr; constinit size_t g_col = 1; constinit size_t g_row = 0; void SetPixel(size_t x, size_t y, u32 color) { g_frame_buffer[(FrameBufferWidth - x) * FrameBufferHeight + y] = color; } void PutCarriageReturn() { g_col = 1; } void PutNewLine() { g_col = 1; ++g_row; /* TODO: Support scrolling? */ } void PutCharImpl(const char c) { /* Get the character data for the font. */ const u8 * cdata = FontData + c * (FontHeight * util::DivideUp(FontWidth, BITSIZEOF(u8))); /* Determine where to start drawing. */ const size_t x = g_col * FontWidth; const size_t y = g_row * FontHeight; for (size_t cur_y = 0; cur_y < FontHeight; ++cur_y) { size_t cur_x = 0; int wbits = FontWidth; while (wbits > 0) { const auto bits = *(cdata++); SetPixel(x + cur_x + 0, y + cur_y, FontDrawTable[(bits >> 4) & 0xF][0] & TextColor); SetPixel(x + cur_x + 1, y + cur_y, FontDrawTable[(bits >> 4) & 0xF][1] & TextColor); SetPixel(x + cur_x + 2, y + cur_y, FontDrawTable[(bits >> 4) & 0xF][2] & TextColor); SetPixel(x + cur_x + 3, y + cur_y, FontDrawTable[(bits >> 4) & 0xF][3] & TextColor); SetPixel(x + cur_x + 4, y + cur_y, FontDrawTable[(bits >> 0) & 0xF][0] & TextColor); SetPixel(x + cur_x + 5, y + cur_y, FontDrawTable[(bits >> 0) & 0xF][1] & TextColor); SetPixel(x + cur_x + 6, y + cur_y, FontDrawTable[(bits >> 0) & 0xF][2] & TextColor); SetPixel(x + cur_x + 7, y + cur_y, FontDrawTable[(bits >> 0) & 0xF][3] & TextColor); cur_x += BITSIZEOF(u8); wbits -= BITSIZEOF(u8); } } } void PutChar(const char c) { switch (c) { case '\r': PutCarriageReturn(); break; case '\n': PutNewLine(); break; default: PutCharImpl(c); if ((++g_col) >= ConsoleWidth) { PutNewLine(); } } } } void InitializeConsole(u32 *frame_buffer) { /* Setup the console variables. */ g_frame_buffer = frame_buffer; g_col = 1; g_row = 0; /* Clear the console. */ std::memset(g_frame_buffer, 0, FrameBufferSize); } void Print(const char *fmt, ...) { /* Generate the string. */ char log_str[1_KB]; { std::va_list vl; va_start(vl, fmt); util::TVSNPrintf(log_str, sizeof(log_str), fmt, vl); va_end(vl); } /* Print each character. */ const size_t len = std::strlen(log_str); for (size_t i = 0; i < len; ++i) { PutChar(log_str[i]); } /* Flush the console. */ hw::FlushDataCache(g_frame_buffer, FrameBufferSize); } }
4,331
C++
.cpp
104
30.557692
104
0.523549
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,371
fatal_crt0_cpp.cpp
Atmosphere-NX_Atmosphere/exosphere/mariko_fatal/source/fatal_crt0_cpp.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 <exosphere.hpp> extern "C" void __libc_init_array(); namespace ams::secmon::fatal { void Initialize(uintptr_t bss_start, size_t bss_end) { /* Clear bss. */ std::memset(reinterpret_cast<void *>(bss_start), 0, bss_end - bss_start); /* Call init array. */ __libc_init_array(); } }
971
C++
.cpp
25
35.52
86
0.701699
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,372
fatal_sdmmc.cpp
Atmosphere-NX_Atmosphere/exosphere/mariko_fatal/source/fatal_sdmmc.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 <exosphere.hpp> #include "fatal_device_page_table.hpp" namespace ams::secmon::fatal { namespace { constexpr inline auto Port = sdmmc::Port_SdCard0; ALWAYS_INLINE u8 *GetSdCardWorkBuffer() { return MemoryRegionVirtualDramSdmmcMappedData.GetPointer<u8>() + MemoryRegionVirtualDramSdmmcMappedData.GetSize() - mmu::PageSize; } ALWAYS_INLINE u8 *GetSdCardDmaBuffer() { return MemoryRegionVirtualDramSdmmcMappedData.GetPointer<u8>(); } constexpr inline size_t SdCardDmaBufferSize = MemoryRegionVirtualDramSdmmcMappedData.GetSize() - mmu::PageSize; constexpr inline size_t SdCardDmaBufferSectors = SdCardDmaBufferSize / sdmmc::SectorSize; static_assert(util::IsAligned(SdCardDmaBufferSize, sdmmc::SectorSize)); } Result InitializeSdCard() { /* Map main memory for the sdmmc device. */ InitializeDevicePageTableForSdmmc1(); /* Initialize sdmmc library. */ sdmmc::Initialize(Port); sdmmc::SetSdCardWorkBuffer(Port, GetSdCardWorkBuffer(), sdmmc::SdCardWorkBufferSize); //sdmmc::Deactivate(Port); R_TRY(sdmmc::Activate(Port)); R_SUCCEED(); } Result CheckSdCardConnection(sdmmc::SpeedMode *out_sm, sdmmc::BusWidth *out_bw) { R_RETURN(sdmmc::CheckSdCardConnection(out_sm, out_bw, Port)); } Result ReadSdCard(void *dst, size_t size, size_t sector_index, size_t sector_count) { /* Validate that our buffer is valid. */ AMS_ASSERT(size >= sector_count * sdmmc::SectorSize); AMS_UNUSED(size); /* Repeatedly read sectors. */ u8 *dst_u8 = static_cast<u8 *>(dst); void * const dma_buffer = GetSdCardDmaBuffer(); while (sector_count > 0) { /* Read sectors into the DMA buffer. */ const size_t cur_sectors = std::min(sector_count, SdCardDmaBufferSectors); const size_t cur_size = cur_sectors * sdmmc::SectorSize; R_TRY(sdmmc::Read(dma_buffer, cur_size, Port, sector_index, cur_sectors)); /* Copy data from the DMA buffer to the output. */ std::memcpy(dst_u8, dma_buffer, cur_size); /* Advance. */ dst_u8 += cur_size; sector_index += cur_sectors; sector_count -= cur_sectors; } R_SUCCEED(); } Result WriteSdCard(size_t sector_index, size_t sector_count, const void *src, size_t size) { /* Validate that our buffer is valid. */ AMS_ASSERT(size >= sector_count * sdmmc::SectorSize); AMS_UNUSED(size); /* Repeatedly read sectors. */ const u8 *src_u8 = static_cast<const u8 *>(src); void * const dma_buffer = GetSdCardDmaBuffer(); while (sector_count > 0) { /* Copy sectors into the DMA buffer. */ const size_t cur_sectors = std::min(sector_count, SdCardDmaBufferSectors); const size_t cur_size = cur_sectors * sdmmc::SectorSize; std::memcpy(dma_buffer, src_u8, cur_size); /* Write sectors to the sd card. */ R_TRY(sdmmc::Write(Port, sector_index, cur_sectors, dma_buffer, cur_size)); /* Advance. */ src_u8 += cur_size; sector_index += cur_sectors; sector_count -= cur_sectors; } R_SUCCEED(); } }
4,040
C++
.cpp
86
38.744186
142
0.643003
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,373
fatal_device_page_table.cpp
Atmosphere-NX_Atmosphere/exosphere/mariko_fatal/source/fatal_device_page_table.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 <exosphere.hpp> namespace ams::secmon::fatal { namespace { /* Definitions. */ constexpr size_t PageDirectorySize = mmu::PageSize; constexpr size_t PageTableSize = mmu::PageSize; static_assert(PageDirectorySize == mmu::PageSize); using DeviceVirtualAddress = u64; constexpr size_t AsidCount = 0x80; constexpr size_t PhysicalAddressBits = 34; constexpr size_t PhysicalAddressMask = (1ul << PhysicalAddressBits) - 1ul; constexpr size_t DeviceVirtualAddressBits = 34; constexpr size_t DeviceVirtualAddressMask = (1ul << DeviceVirtualAddressBits) - 1ul; constexpr size_t DevicePageBits = 12; constexpr size_t DevicePageSize = (1ul << DevicePageBits); static_assert(DevicePageSize == mmu::PageSize); constexpr size_t DeviceLargePageBits = 22; constexpr size_t DeviceLargePageSize = (1ul << DeviceLargePageBits); static_assert(DeviceLargePageSize % DevicePageSize == 0); constexpr size_t DeviceRegionBits = 32; constexpr size_t DeviceRegionSize = (1ul << DeviceRegionBits); static_assert(DeviceRegionSize % DeviceLargePageSize == 0); constexpr const uintptr_t MC = secmon::MemoryRegionVirtualDeviceMemoryController.GetAddress(); constexpr size_t TableCount = (1ul << DeviceVirtualAddressBits) / DeviceRegionSize; consteval u32 EncodeAsidRegisterValue(u8 asid) { u32 value = 0x80000000u; for (size_t t = 0; t < TableCount; t++) { value |= (asid << (BITSIZEOF(u8) * t)); } return value; } constexpr u8 SdmmcAsid = 1; constexpr u8 DcAsid = 2; constexpr u32 SdmmcAsidRegisterValue = EncodeAsidRegisterValue(SdmmcAsid); constexpr u32 DcAsidRegisterValue = EncodeAsidRegisterValue(DcAsid); constexpr dd::PhysicalAddress DcL0PageTablePhysical = MemoryRegionPhysicalDramDcL0DevicePageTable.GetAddress(); constexpr dd::PhysicalAddress SdmmcL0PageTablePhysical = MemoryRegionPhysicalDramSdmmc1L0DevicePageTable.GetAddress(); constexpr dd::PhysicalAddress SdmmcL1PageTablePhysical = MemoryRegionPhysicalDramSdmmc1L1DevicePageTable.GetAddress(); /* Types. */ class EntryBase { protected: enum Bit : u32 { Bit_Table = 28, Bit_NonSecure = 29, Bit_Writeable = 30, Bit_Readable = 31, }; private: u32 m_value; protected: constexpr ALWAYS_INLINE u32 SelectBit(Bit n) const { return (m_value & (1u << n)); } constexpr ALWAYS_INLINE bool GetBit(Bit n) const { return this->SelectBit(n) != 0; } static constexpr ALWAYS_INLINE u32 EncodeBit(Bit n, bool en) { return en ? (1u << n) : 0; } static constexpr ALWAYS_INLINE u32 EncodeValue(bool r, bool w, bool ns, dd::PhysicalAddress addr, bool t) { return EncodeBit(Bit_Readable, r) | EncodeBit(Bit_Writeable, w) | EncodeBit(Bit_NonSecure, ns) | EncodeBit(Bit_Table, t) | static_cast<u32>(addr >> DevicePageBits); } ALWAYS_INLINE void SetValue(u32 v) { /* Prevent re-ordering around entry modifications. */ __asm__ __volatile__("" ::: "memory"); m_value = v; __asm__ __volatile__("" ::: "memory"); } public: static constexpr ALWAYS_INLINE u32 EncodePtbDataValue(dd::PhysicalAddress addr) { return EncodeValue(true, true, true, addr, false); } public: constexpr ALWAYS_INLINE bool IsNonSecure() const { return this->GetBit(Bit_NonSecure); } constexpr ALWAYS_INLINE bool IsWriteable() const { return this->GetBit(Bit_Writeable); } constexpr ALWAYS_INLINE bool IsReadable() const { return this->GetBit(Bit_Readable); } constexpr ALWAYS_INLINE bool IsValid() const { return this->IsWriteable() || this->IsReadable(); } constexpr ALWAYS_INLINE u32 GetAttributes() const { return this->SelectBit(Bit_NonSecure) | this->SelectBit(Bit_Writeable) | this->SelectBit(Bit_Readable); } constexpr ALWAYS_INLINE dd::PhysicalAddress GetPhysicalAddress() const { return (static_cast<u64>(m_value) << DevicePageBits) & PhysicalAddressMask; } ALWAYS_INLINE void Invalidate() { this->SetValue(0); } }; class PageDirectoryEntry : public EntryBase { public: constexpr ALWAYS_INLINE bool IsTable() const { return this->GetBit(Bit_Table); } ALWAYS_INLINE void SetTable(bool r, bool w, bool ns, dd::PhysicalAddress addr) { AMS_ASSERT(util::IsAligned(addr, DevicePageSize)); this->SetValue(EncodeValue(r, w, ns, addr, true)); } ALWAYS_INLINE void SetLargePage(bool r, bool w, bool ns, dd::PhysicalAddress addr) { AMS_ASSERT(util::IsAligned(addr, DeviceLargePageSize)); this->SetValue(EncodeValue(r, w, ns, addr, false)); } }; class PageTableEntry : public EntryBase { public: ALWAYS_INLINE void SetPage(bool r, bool w, bool ns, dd::PhysicalAddress addr) { AMS_ASSERT(util::IsAligned(addr, DevicePageSize)); this->SetValue(EncodeValue(r, w, ns, addr, true)); } }; /* Memory controller access functionality. */ void WriteMcRegister(size_t offset, u32 value) { reg::Write(MC + offset, value); } u32 ReadMcRegister(size_t offset) { return reg::Read(MC + offset); } /* Memory controller utilities. */ void SmmuSynchronizationBarrier() { ReadMcRegister(MC_SMMU_CONFIG); } void InvalidatePtc() { WriteMcRegister(MC_SMMU_PTC_FLUSH_0, 0); } void InvalidatePtc(dd::PhysicalAddress address) { WriteMcRegister(MC_SMMU_PTC_FLUSH_1, (static_cast<u64>(address) >> 32)); WriteMcRegister(MC_SMMU_PTC_FLUSH_0, (address & 0xFFFFFFF0u) | 1u); } enum TlbFlushVaMatch : u32 { TlbFlushVaMatch_All = 0, TlbFlushVaMatch_Section = 2, TlbFlushVaMatch_Group = 3, }; static constexpr ALWAYS_INLINE u32 EncodeTlbFlushValue(bool match_asid, u8 asid, dd::PhysicalAddress address, TlbFlushVaMatch match) { return ((match_asid ? 1u : 0u) << 31) | ((asid & 0x7F) << 24) | (((address & 0xFFC00000u) >> DevicePageBits)) | (match); } void InvalidateTlb() { return WriteMcRegister(MC_SMMU_TLB_FLUSH, EncodeTlbFlushValue(false, 0, 0, TlbFlushVaMatch_All)); } void InvalidateTlb(u8 asid) { return WriteMcRegister(MC_SMMU_TLB_FLUSH, EncodeTlbFlushValue(true, asid, 0, TlbFlushVaMatch_All)); } void InvalidateTlbSection(u8 asid, dd::PhysicalAddress address) { return WriteMcRegister(MC_SMMU_TLB_FLUSH, EncodeTlbFlushValue(true, asid, address, TlbFlushVaMatch_Section)); } void SetTable(u8 asid, dd::PhysicalAddress address) { /* Write the table address. */ { WriteMcRegister(MC_SMMU_PTB_ASID, asid); WriteMcRegister(MC_SMMU_PTB_DATA, EntryBase::EncodePtbDataValue(address)); SmmuSynchronizationBarrier(); } /* Ensure consistency. */ InvalidatePtc(); InvalidateTlb(asid); SmmuSynchronizationBarrier(); } void MapImpl(dd::PhysicalAddress phys_addr, size_t size, DeviceVirtualAddress address, u8 asid, void *l0_table, dd::PhysicalAddress l0_phys, void *l1_table, dd::PhysicalAddress l1_phys) { /* Validate L0. */ AMS_ABORT_UNLESS(l0_table != nullptr); AMS_ABORT_UNLESS(l0_phys != 0); /* Cache permissions. */ const bool read = true; const bool write = true; /* Walk the directory. */ u64 remaining = size; while (remaining > 0) { const size_t l1_index = (address % DeviceRegionSize) / DeviceLargePageSize; const size_t l2_index = (address % DeviceLargePageSize) / DevicePageSize; /* Get and validate l1. */ PageDirectoryEntry *l1 = static_cast<PageDirectoryEntry *>(l0_table); AMS_ASSERT(l1 != nullptr); /* Setup an l1 table/entry, if needed. */ if (!l1[l1_index].IsTable()) { /* Check that an entry doesn't already exist. */ AMS_ASSERT(!l1[l1_index].IsValid()); /* If we can make an l1 entry, do so. */ if (l2_index == 0 && util::IsAligned(phys_addr, DeviceLargePageSize) && remaining >= DeviceLargePageSize) { /* Set the large page. */ l1[l1_index].SetLargePage(read, write, true, phys_addr); hw::FlushDataCache(std::addressof(l1[l1_index]), sizeof(PageDirectoryEntry)); /* Synchronize. */ InvalidatePtc(l0_phys + l1_index * sizeof(PageDirectoryEntry)); InvalidateTlbSection(asid, address); SmmuSynchronizationBarrier(); /* Advance. */ phys_addr += DeviceLargePageSize; address += DeviceLargePageSize; remaining -= DeviceLargePageSize; continue; } else { /* Make an l1 table. */ AMS_ABORT_UNLESS(l1_table != nullptr); AMS_ABORT_UNLESS(l1_phys != 0); /* Clear the l1 table. */ std::memset(l1_table, 0, mmu::PageSize); hw::FlushDataCache(l1_table, mmu::PageSize); /* Set the l1 table. */ l1[l1_index].SetTable(true, true, true, l1_phys); hw::FlushDataCache(std::addressof(l1[l1_index]), sizeof(PageDirectoryEntry)); /* Synchronize. */ InvalidatePtc(l0_phys + l1_index * sizeof(PageDirectoryEntry)); InvalidateTlbSection(asid, address); SmmuSynchronizationBarrier(); } } /* If we get to this point, l1 must be a table. */ AMS_ASSERT(l1[l1_index].IsTable()); AMS_ABORT_UNLESS(l1_table != nullptr); AMS_ABORT_UNLESS(l1_phys != 0); /* Map l2 entries. */ { PageTableEntry *l2 = static_cast<PageTableEntry *>(l1_table); const size_t remaining_in_entry = (PageTableSize / sizeof(PageTableEntry)) - l2_index; const size_t map_count = std::min<size_t>(remaining_in_entry, remaining / DevicePageSize); /* Set the entries. */ for (size_t i = 0; i < map_count; ++i) { AMS_ASSERT(!l2[l2_index + i].IsValid()); l2[l2_index + i].SetPage(read, write, true, phys_addr + DevicePageSize * i); } hw::FlushDataCache(std::addressof(l2[l2_index]), map_count * sizeof(PageTableEntry)); /* Invalidate the page table cache. */ for (size_t i = util::AlignDown(l2_index, 4); i <= util::AlignDown(l2_index + map_count - 1, 4); i += 4) { InvalidatePtc(l1_phys + i * sizeof(PageTableEntry)); } /* Synchronize. */ InvalidateTlbSection(asid, address); SmmuSynchronizationBarrier(); /* Advance. */ phys_addr += map_count * DevicePageSize; address += map_count * DevicePageSize; remaining -= map_count * DevicePageSize; } } } } void InitializeDevicePageTableForSdmmc1() { /* Configure sdmmc to use our new page table. */ WriteMcRegister(MC_SMMU_SDMMC1A_ASID, SdmmcAsidRegisterValue); SmmuSynchronizationBarrier(); /* Ensure consistency. */ InvalidatePtc(); InvalidateTlb(); SmmuSynchronizationBarrier(); /* Clear the L0 Page Table. */ std::memset(MemoryRegionVirtualDramSdmmc1L0DevicePageTable.GetPointer<void>(), 0, mmu::PageSize); hw::FlushDataCache(MemoryRegionVirtualDramSdmmc1L0DevicePageTable.GetPointer<void>(), mmu::PageSize); /* Set the page table for the sdmmc asid. */ SetTable(SdmmcAsid, SdmmcL0PageTablePhysical); /* Map the appropriate region into the asid. */ MapImpl(MemoryRegionPhysicalDramSdmmcMappedData.GetAddress(), MemoryRegionPhysicalDramSdmmcMappedData.GetSize(), MemoryRegionVirtualDramSdmmcMappedData.GetAddress(), SdmmcAsid, MemoryRegionVirtualDramSdmmc1L0DevicePageTable.GetPointer<void>(), SdmmcL0PageTablePhysical, MemoryRegionVirtualDramSdmmc1L1DevicePageTable.GetPointer<void>(), SdmmcL1PageTablePhysical); } void InitializeDevicePageTableForDc() { /* Configure dc to use our new page table. */ WriteMcRegister(MC_SMMU_DC_ASID, DcAsidRegisterValue); SmmuSynchronizationBarrier(); /* Ensure consistency. */ InvalidatePtc(); InvalidateTlb(); SmmuSynchronizationBarrier(); /* Clear the L0 Page Table. */ std::memset(MemoryRegionVirtualDramDcL0DevicePageTable.GetPointer<void>(), 0, mmu::PageSize); hw::FlushDataCache(MemoryRegionVirtualDramDcL0DevicePageTable.GetPointer<void>(), mmu::PageSize); /* Set the page table for the dc asid. */ SetTable(DcAsid, DcL0PageTablePhysical); /* Map the appropriate region into the asid. */ static_assert(util::IsAligned(MemoryRegionDramDcFramebuffer.GetAddress(), DeviceLargePageSize)); static_assert(util::IsAligned(MemoryRegionDramDcFramebuffer.GetSize(), DeviceLargePageSize)); MapImpl(MemoryRegionDramDcFramebuffer.GetAddress(), MemoryRegionDramDcFramebuffer.GetSize(), MemoryRegionDramDcFramebuffer.GetAddress(), DcAsid, MemoryRegionVirtualDramDcL0DevicePageTable.GetPointer<void>(), DcL0PageTablePhysical, nullptr, 0); } }
15,742
C++
.cpp
282
41.631206
195
0.58694
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,374
fatal_main.cpp
Atmosphere-NX_Atmosphere/exosphere/mariko_fatal/source/fatal_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 <exosphere.hpp> #include "fatal_sdmmc.hpp" #include "fatal_save_context.hpp" #include "fatal_sound.hpp" #include "fatal_display.hpp" namespace ams::secmon::fatal { namespace { constexpr inline int I2cAddressMax77620Pmic = 0x3C; ALWAYS_INLINE const ams::impl::FatalErrorContext *GetFatalErrorContext() { return MemoryRegionVirtualTzramMarikoProgramFatalErrorContext.GetPointer<ams::impl::FatalErrorContext>(); } } void Main() { /* Set library register addresses. */ actmon::SetRegisterAddress(MemoryRegionVirtualDeviceActivityMonitor.GetAddress()); clkrst::SetRegisterAddress(MemoryRegionVirtualDeviceClkRst.GetAddress()); flow::SetRegisterAddress(MemoryRegionVirtualDeviceFlowController.GetAddress()); fuse::SetRegisterAddress(MemoryRegionVirtualDeviceFuses.GetAddress()); gic::SetRegisterAddress(MemoryRegionVirtualDeviceGicDistributor.GetAddress(), MemoryRegionVirtualDeviceGicCpuInterface.GetAddress()); i2c::SetRegisterAddress(i2c::Port_1, MemoryRegionVirtualDeviceI2c1.GetAddress()); i2c::SetRegisterAddress(i2c::Port_5, MemoryRegionVirtualDeviceI2c5.GetAddress()); pinmux::SetRegisterAddress(MemoryRegionVirtualDeviceApbMisc.GetAddress(), MemoryRegionVirtualDeviceGpio.GetAddress()); pmc::SetRegisterAddress(MemoryRegionVirtualDevicePmc.GetAddress()); se::SetRegisterAddress(MemoryRegionVirtualDeviceSecurityEngine.GetAddress(), MemoryRegionVirtualDeviceSecurityEngine2.GetAddress()); uart::SetRegisterAddress(MemoryRegionVirtualDeviceUart.GetAddress()); wdt::SetRegisterAddress(MemoryRegionVirtualDeviceTimer.GetAddress()); util::SetRegisterAddress(MemoryRegionVirtualDeviceTimer.GetAddress()); /* Ensure that the log library is initialized. */ log::Initialize(); AMS_SECMON_LOG("%s\n", "Fatal start."); /* Save the fatal error context. */ const auto *f_ctx = GetFatalErrorContext(); Result result = SaveFatalErrorContext(f_ctx); if (R_SUCCEEDED(result)) { AMS_SECMON_LOG("Saved fatal error context to /atmosphere/fatal_reports/report_%016" PRIx64 ".bin!\n", f_ctx->report_identifier); } else { AMS_SECMON_LOG("Failed to save fatal error context: %08x\n", result.GetValue()); } /* Ensure that i2c-1/i2c-5 are usable for communicating with the audio device/pmic. */ clkrst::EnableI2c1Clock(); clkrst::EnableI2c5Clock(); i2c::Initialize(i2c::Port_1); i2c::Initialize(i2c::Port_5); /* Shut down audio. */ { StopSound(); } /* Display the fatal error. */ { AMS_SECMON_LOG("Showing Display, LCD Vendor = %04x\n", GetLcdVendor()); InitializeDisplay(); ShowDisplay(f_ctx, result); } /* Ensure we have nothing waiting to be logged. */ AMS_LOG_FLUSH(); /* Wait for power button to be pressed. */ while (!pmic::IsPowerButtonPressed()) { util::WaitMicroSeconds(100); } /* Reboot. */ pmic::ShutdownSystem(true); /* Wait for our reboot to complete. */ AMS_INFINITE_LOOP(); } }
3,938
C++
.cpp
80
41.5
144
0.692268
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,375
fatal_save_context.cpp
Atmosphere-NX_Atmosphere/exosphere/mariko_fatal/source/fatal_save_context.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 <exosphere.hpp> #include "fatal_save_context.hpp" #include "fatal_sdmmc.hpp" #include "fs/fatal_fs_api.hpp" namespace ams::secmon::fatal { Result SaveFatalErrorContext(const ams::impl::FatalErrorContext *ctx) { /* Initialize the sdmmc driver. */ R_TRY(InitializeSdCard()); /* Get the connection status. */ #if defined(AMS_BUILD_FOR_DEBUGGING) || defined(AMS_BUILD_FOR_AUDITING) { sdmmc::SpeedMode speed_mode; sdmmc::BusWidth bus_width; R_TRY(CheckSdCardConnection(std::addressof(speed_mode), std::addressof(bus_width))); AMS_SECMON_LOG("Sd Card Connection:\n"); AMS_SECMON_LOG(" Speed Mode: %u\n", static_cast<u32>(speed_mode)); AMS_SECMON_LOG(" Bus Width: %u\n", static_cast<u32>(bus_width)); } #endif /* Mount the SD card. */ R_UNLESS(fs::MountSdCard(), fs::ResultPartitionNotFound()); /* Unmount the SD card once we're done. */ ON_SCOPE_EXIT { fs::UnmountSdCard(); }; /* Create and open the file. */ fs::FileHandle file; { /* Generate the file path. */ char path[0x40]; util::TSNPrintf(path, sizeof(path), "/atmosphere/fatal_errors/report_%016" PRIx64 ".bin", ctx->report_identifier); /* Create the file. */ R_TRY(fs::CreateFile(path, sizeof(*ctx))); /* Open the file. */ R_TRY(fs::OpenFile(std::addressof(file), path, fs::OpenMode_ReadWrite)); } /* Ensure we close the file when done with it. */ ON_SCOPE_EXIT { fs::CloseFile(file); }; /* Write the context to the file. */ R_TRY(fs::WriteFile(file, 0, ctx, sizeof(*ctx), fs::WriteOption::Flush)); R_SUCCEED(); } }
2,455
C++
.cpp
56
36.589286
126
0.63008
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,376
fatal_display.cpp
Atmosphere-NX_Atmosphere/exosphere/mariko_fatal/source/fatal_display.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 <exosphere.hpp> #include "fatal_device_page_table.hpp" #include "fatal_registers_di.hpp" #include "fatal_display.hpp" #include "fatal_print.hpp" namespace ams::secmon::fatal { namespace { #include "fatal_display_config.inc" } namespace { /* Helpful defines. */ constexpr int DsiWaitForCommandMilliSecondsMax = 250; constexpr int DsiWaitForCommandCompletionMilliSeconds = 5; constexpr int DsiWaitForHostControlMilliSecondsMax = 150; constexpr inline int I2cAddressMax77620Pmic = 0x3C; constexpr size_t GPIO_PORT3_CNF_0 = 0x200; constexpr size_t GPIO_PORT3_OE_0 = 0x210; constexpr size_t GPIO_PORT3_OUT_0 = 0x220; constexpr size_t GPIO_PORT6_CNF_1 = 0x504; constexpr size_t GPIO_PORT6_OE_1 = 0x514; constexpr size_t GPIO_PORT6_OUT_1 = 0x524; /* Globals. */ constexpr inline const uintptr_t PMC = secmon::MemoryRegionVirtualDevicePmc .GetAddress(); constexpr inline const uintptr_t g_disp1_regs = secmon::MemoryRegionVirtualDeviceDisp1 .GetAddress(); constexpr inline const uintptr_t g_dsi_regs = secmon::MemoryRegionVirtualDeviceDsi .GetAddress(); constexpr inline const uintptr_t g_clk_rst_regs = secmon::MemoryRegionVirtualDeviceClkRst .GetAddress(); constexpr inline const uintptr_t g_gpio_regs = secmon::MemoryRegionVirtualDeviceGpio .GetAddress(); constexpr inline const uintptr_t g_apb_misc_regs = secmon::MemoryRegionVirtualDeviceApbMisc.GetAddress(); constexpr inline const uintptr_t g_mipi_cal_regs = secmon::MemoryRegionVirtualDeviceMipiCal.GetAddress(); constinit u32 *g_frame_buffer = nullptr; inline void DoRegisterWrites(uintptr_t base_address, const RegisterWrite *reg_writes, size_t num_writes) { for (size_t i = 0; i < num_writes; i++) { reg::Write(base_address + reg_writes[i].offset, reg_writes[i].value); } } inline void DoSocDependentRegisterWrites(uintptr_t base_address, const RegisterWrite *reg_writes_erista, size_t num_writes_erista, const RegisterWrite *reg_writes_mariko, size_t num_writes_mariko) { switch (GetSocType()) { case fuse::SocType_Erista: DoRegisterWrites(base_address, reg_writes_erista, num_writes_erista); break; case fuse::SocType_Mariko: DoRegisterWrites(base_address, reg_writes_mariko, num_writes_mariko); break; AMS_UNREACHABLE_DEFAULT_CASE(); } } inline void DoSleepOrRegisterWrites(uintptr_t base_address, const SleepOrRegisterWrite *reg_writes, size_t num_writes) { for (size_t i = 0; i < num_writes; i++) { switch (reg_writes[i].kind) { case SleepOrRegisterWriteKind_Write: reg::Write(base_address + sizeof(u32) * reg_writes[i].offset, reg_writes[i].value); break; case SleepOrRegisterWriteKind_Sleep: util::WaitMicroSeconds(reg_writes[i].offset * UINT64_C(1000)); break; AMS_UNREACHABLE_DEFAULT_CASE(); } } } void WaitDsiTrigger() { const u32 timeout = util::GetMicroSeconds() + (DsiWaitForCommandMilliSecondsMax * 1000u); while (true) { if (util::GetMicroSeconds() >= timeout) { break; } if (reg::Read(g_dsi_regs + sizeof(u32) * DSI_TRIGGER) == 0) { break; } } util::WaitMicroSeconds(DsiWaitForCommandCompletionMilliSeconds * 1000u); } void WaitDsiHostControl() { const u32 timeout = util::GetMicroSeconds() + (DsiWaitForHostControlMilliSecondsMax * 1000u); while (true) { if (util::GetMicroSeconds() >= timeout) { break; } if ((reg::Read(g_dsi_regs + sizeof(u32) * DSI_HOST_CONTROL) & DSI_HOST_CONTROL_IMM_BTA) == 0) { break; } } } void EnableBacklightForVendor2050ForAula(int brightness) { /* Enable FRAME_END_INT */ reg::Write(g_disp1_regs + sizeof(u32) * DC_CMD_INT_ENABLE, 2); /* Configure DSI_LINE_TYPE as FOUR */ reg::Write(g_dsi_regs + sizeof(u32) * DSI_VIDEO_MODE_CONTROL, 1); reg::Write(g_dsi_regs + sizeof(u32) * DSI_VIDEO_MODE_CONTROL, 9); /* Set and wait for FRAME_END_INT */ reg::Write(g_disp1_regs + sizeof(u32) * DC_CMD_INT_STATUS, 2); while ((reg::Read(g_disp1_regs + sizeof(u32) * DC_CMD_INT_STATUS) & 2) != 0) { /* ... */ } /* Configure display brightness. */ const u32 brightness_val = ((0x7FF * brightness) / 100); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x339); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, (brightness_val & 0x700) | ((brightness_val & 0xFF) << 16) | 0x51); /* Set and wait for FRAME_END_INT */ reg::Write(g_disp1_regs + sizeof(u32) * DC_CMD_INT_STATUS, 2); while ((reg::Read(g_disp1_regs + sizeof(u32) * DC_CMD_INT_STATUS) & 2) != 0) { /* ... */ } /* Set client sync point block reset. */ reg::Write(g_dsi_regs + sizeof(u32) * DSI_INCR_SYNCPT_CNTRL, 1); util::WaitMicroSeconds(300'000ul); /* Clear client sync point block resest. */ reg::Write(g_dsi_regs + sizeof(u32) * DSI_INCR_SYNCPT_CNTRL, 0); util::WaitMicroSeconds(300'000ul); /* Clear DSI_LINE_TYPE config. */ reg::Write(g_dsi_regs + sizeof(u32) * DSI_VIDEO_MODE_CONTROL, 0); /* Disable FRAME_END_INT */ reg::Write(g_disp1_regs + sizeof(u32) * DC_CMD_INT_ENABLE, 0); reg::Write(g_disp1_regs + sizeof(u32) * DC_CMD_INT_STATUS, 2); } void EnableBacklightForGeneric(int brightness) { AMS_UNUSED(brightness); reg::SetBits(g_gpio_regs + GPIO_PORT6_OUT_1, 0x1); } #define DO_REGISTER_WRITES(base_address, writes) DoRegisterWrites(base_address, writes, util::size(writes)) #define DO_SOC_DEPENDENT_REGISTER_WRITES(base_address, writes) DoSocDependentRegisterWrites(base_address, writes##Erista, util::size(writes##Erista), writes##Mariko, util::size(writes##Mariko)) #define DO_SLEEP_OR_REGISTER_WRITES(base_address, writes) DoSleepOrRegisterWrites(base_address, writes, util::size(writes)) void InitializeFrameBuffer() { if (g_frame_buffer != nullptr) { std::memset(g_frame_buffer, 0, FrameBufferSize); hw::FlushDataCache(g_frame_buffer, FrameBufferSize); } else { /* Clear the frame buffer. */ g_frame_buffer = secmon::MemoryRegionDramDcFramebuffer.GetPointer<u32>(); std::memset(g_frame_buffer, 0, FrameBufferSize); hw::FlushDataCache(g_frame_buffer, FrameBufferSize); /* Attach the frame buffer to DC. */ InitializeDevicePageTableForDc(); } } [[maybe_unused]] void FinalizeFrameBuffer() { /* We don't actually support finalizing the framebuffer, so do nothing here. */ } constexpr const char *GetErrorDescription(u32 error_desc) { switch (error_desc) { case 0x100: return "Instruction Abort"; case 0x101: return "Data Abort"; case 0x102: return "PC Misalignment"; case 0x103: return "SP Misalignment"; case 0x104: return "Trap"; case 0x106: return "SError"; case 0x301: return "Bad SVC"; case 0xF00: return "Kernel Panic"; case 0xFFD: return "Stack overflow"; case 0xFFE: return "std::abort() called"; default: return "Unknown"; } } void PrintSuggestedErrorFix(const ams::impl::FatalErrorContext *f_ctx) { /* Try to recognize certain errors automatically, and suggest fixes for them. */ const char *suggestion = nullptr; constexpr u64 ProgramIdAmsMitm = UINT64_C(0x010041544D530000); constexpr u64 ProgramIdBoot = UINT64_C(0x0100000000000005); if (f_ctx->error_desc == 0xFFE) { if (f_ctx->program_id == ProgramIdAmsMitm) { /* When a user has archive bits set improperly, attempting to create an automatic backup will fail */ /* to create the file path with error 0x202 */ if (f_ctx->gprs[0] == fs::ResultPathNotFound().GetValue()) { /* When the archive bit error is occurring, it manifests as failure to create automatic backup. */ /* Thus, we can search the stack for the automatic backups path. */ const char * const automatic_backups_prefix = "automatic_backups/X" /* ..... */; const int prefix_len = std::strlen(automatic_backups_prefix); for (size_t i = 0; i + prefix_len < f_ctx->stack_dump_size; ++i) { if (std::memcmp(f_ctx->stack_dump + i, automatic_backups_prefix, prefix_len) == 0) { suggestion = "The atmosphere directory may improperly have archive bits set.\n" "Please try running an archive bit fixer tool (for example, the one in Hekate).\n"; break; } } } else if (f_ctx->gprs[0] == fs::ResultExFatUnavailable().GetValue()) { /* When a user installs non-exFAT firm but has an exFAT formatted SD card, this error will */ /* be returned on attempt to access the SD card. */ suggestion = "Your console has non-exFAT firmware installed, but your SD card\n" "is formatted as exFAT. Format your SD card as FAT32, or manually\n" "flash exFAT firmware to package2.\n"; } } else if (f_ctx->program_id == ProgramIdBoot) { /* 9.x -> 10.x updated the API for SvcQueryIoMapping. */ /* This can cause the kernel to reject incorrect-ABI calls by boot when a partial update is applied */ /* (older kernel in package2, for some reason). */ for (size_t i = 0; i < 8; ++i) { if (f_ctx->gprs[i] == svc::ResultNotFound().GetValue()) { suggestion = "A partial update may have been improperly performed.\n" "To fix, try manually flashing latest package2 to MMC.\n" "\n" "For help doing this, seek support in the ReSwitched or\n" "Nintendo Homebrew discord servers.\n"; break; } } } } else if (f_ctx->error_desc == 0xF00) { /* Kernel Panic */ suggestion = "Please contact SciresM#0524 on Discord, or create an issue on the Atmosphere\n" "GitHub issue tracker. Thank you very much for helping to test mesosphere.\n"; } /* If we found a suggestion, print it. */ if (suggestion != nullptr) { Print("%s", suggestion); } } void FinalizeDisplay() { /* TODO: What other configuration is needed, if any? */ /* Configure LCD pinmux tristate + passthrough. */ reg::ClearBits(g_apb_misc_regs + PINMUX_AUX_NFC_EN, reg::EncodeMask(PINMUX_REG_BITS_MASK(AUX_TRISTATE))); reg::ClearBits(g_apb_misc_regs + PINMUX_AUX_NFC_INT, reg::EncodeMask(PINMUX_REG_BITS_MASK(AUX_TRISTATE))); reg::ClearBits(g_apb_misc_regs + PINMUX_AUX_LCD_BL_PWM, reg::EncodeMask(PINMUX_REG_BITS_MASK(AUX_TRISTATE))); reg::ClearBits(g_apb_misc_regs + PINMUX_AUX_LCD_BL_EN, reg::EncodeMask(PINMUX_REG_BITS_MASK(AUX_TRISTATE))); reg::ClearBits(g_apb_misc_regs + PINMUX_AUX_LCD_RST, reg::EncodeMask(PINMUX_REG_BITS_MASK(AUX_TRISTATE))); if (fuse::GetHardwareType() == fuse::HardwareType_Aula) { /* Configure LCD backlight. */ reg::SetBits(g_gpio_regs + GPIO_PORT6_CNF_1, 0x4); reg::SetBits(g_gpio_regs + GPIO_PORT6_OE_1, 0x4); } else { /* Configure LCD power, VDD. */ reg::SetBits(g_gpio_regs + GPIO_PORT3_CNF_0, 0x3); reg::SetBits(g_gpio_regs + GPIO_PORT3_OE_0, 0x3); reg::SetBits(g_gpio_regs + GPIO_PORT3_OUT_0, 0x1); util::WaitMicroSeconds(10'000ul); reg::SetBits(g_gpio_regs + GPIO_PORT3_OUT_0, 0x2); util::WaitMicroSeconds(10'000ul); /* Configure LCD backlight. */ reg::SetBits(g_gpio_regs + GPIO_PORT6_CNF_1, 0x7); reg::SetBits(g_gpio_regs + GPIO_PORT6_OE_1, 0x7); reg::SetBits(g_gpio_regs + GPIO_PORT6_OUT_1, 0x2); } /* Disable the LCD backlight. */ if (GetLcdVendor() == 0x2050) { /* TODO: We're not sure display is alive. How to manage this? */ /* This is probably incorrect backlight disable for hw-type 5. */ reg::ClearBits(g_gpio_regs + GPIO_PORT6_OUT_1, 0x1); } else { reg::ClearBits(g_gpio_regs + GPIO_PORT6_OUT_1, 0x1); } /* Disable backlight RST/Voltage. */ reg::ClearBits(g_gpio_regs + GPIO_PORT6_OUT_1, 0x4); if (GetLcdVendor() == 0x2050) { util::WaitMicroSeconds(30'000ul); } else { util::WaitMicroSeconds(10'000ul); reg::ClearBits(g_gpio_regs + GPIO_PORT3_OUT_0, 0x2); util::WaitMicroSeconds(10'000ul); reg::ClearBits(g_gpio_regs + GPIO_PORT3_OUT_0, 0x1); util::WaitMicroSeconds(10'000ul); } /* Cut clock to DSI. */ reg::Write(g_clk_rst_regs + CLK_RST_CONTROLLER_RST_DEV_H_SET, CLK_RST_REG_BITS_ENUM(RST_DEV_H_SET_SET_MIPI_CAL_RST, ENABLE), CLK_RST_REG_BITS_ENUM(RST_DEV_H_SET_SET_DSI_RST, ENABLE)); reg::Write(g_clk_rst_regs + CLK_RST_CONTROLLER_CLK_ENB_H_CLR, CLK_RST_REG_BITS_ENUM(CLK_ENB_H_CLR_CLR_CLK_ENB_MIPI_CAL, ENABLE), CLK_RST_REG_BITS_ENUM(CLK_ENB_H_CLR_CLR_CLK_ENB_DSI, ENABLE)); reg::Write(g_clk_rst_regs + CLK_RST_CONTROLLER_RST_DEV_L_SET, CLK_RST_REG_BITS_ENUM(RST_DEV_L_SET_SET_HOST1X_RST, ENABLE), CLK_RST_REG_BITS_ENUM(RST_DEV_L_SET_SET_DISP1_RST, ENABLE)); reg::Write(g_clk_rst_regs + CLK_RST_CONTROLLER_CLK_ENB_L_CLR, CLK_RST_REG_BITS_ENUM(CLK_ENB_L_CLR_CLR_CLK_ENB_HOST1X, ENABLE), CLK_RST_REG_BITS_ENUM(CLK_ENB_L_CLR_CLR_CLK_ENB_DISP1, ENABLE)); reg::Write(g_dsi_regs + sizeof(u32) * DSI_PAD_CONTROL_0, (DSI_PAD_CONTROL_VS1_PULLDN_CLK | DSI_PAD_CONTROL_VS1_PULLDN(0xF) | DSI_PAD_CONTROL_VS1_PDIO_CLK | DSI_PAD_CONTROL_VS1_PDIO(0xF))); reg::Write(g_dsi_regs + sizeof(u32) * DSI_POWER_CONTROL, 0); } } void InitializeDisplay() { /* Ensure that the display is finalized. */ FinalizeDisplay(); /* Setup the framebuffer. */ InitializeFrameBuffer(); /* Get the hardware type. */ const auto hw_type = fuse::GetHardwareType(); /* Turn on DSI/voltage rail. */ { if (GetSocType() == fuse::SocType_Mariko) { i2c::SendByte(i2c::Port_5, I2cAddressMax77620Pmic, 0x18, 0x3A); i2c::SendByte(i2c::Port_5, I2cAddressMax77620Pmic, 0x18, 0x3A); } i2c::SendByte(i2c::Port_5, I2cAddressMax77620Pmic, 0x23, 0xD0); } /* Enable MIPI CAL, DSI, DISP1, HOST1X, UART_FST_MIPI_CAL, DSIA LP clocks. */ reg::Write(g_clk_rst_regs + CLK_RST_CONTROLLER_RST_DEV_H_CLR, CLK_RST_REG_BITS_ENUM(RST_DEV_H_CLR_CLR_MIPI_CAL_RST, ENABLE), CLK_RST_REG_BITS_ENUM(RST_DEV_H_CLR_CLR_DSI_RST, ENABLE)); reg::Write(g_clk_rst_regs + CLK_RST_CONTROLLER_CLK_ENB_H_SET, CLK_RST_REG_BITS_ENUM(CLK_ENB_H_SET_SET_CLK_ENB_MIPI_CAL, ENABLE), CLK_RST_REG_BITS_ENUM(CLK_ENB_H_SET_SET_CLK_ENB_DSI, ENABLE)); reg::Write(g_clk_rst_regs + CLK_RST_CONTROLLER_RST_DEV_L_CLR, CLK_RST_REG_BITS_ENUM(RST_DEV_L_CLR_CLR_HOST1X_RST, ENABLE), CLK_RST_REG_BITS_ENUM(RST_DEV_L_CLR_CLR_DISP1_RST, ENABLE)); reg::Write(g_clk_rst_regs + CLK_RST_CONTROLLER_CLK_ENB_L_SET, CLK_RST_REG_BITS_ENUM(CLK_ENB_L_SET_SET_CLK_ENB_HOST1X, ENABLE), CLK_RST_REG_BITS_ENUM(CLK_ENB_L_SET_SET_CLK_ENB_DISP1, ENABLE)); reg::Write(g_clk_rst_regs + CLK_RST_CONTROLLER_CLK_ENB_X_SET, CLK_RST_REG_BITS_ENUM(CLK_ENB_X_SET_SET_CLK_ENB_UART_FST_MIPI_CAL, ENABLE)); reg::Write(g_clk_rst_regs + CLK_RST_CONTROLLER_CLK_SOURCE_UART_FST_MIPI_CAL, CLK_RST_REG_BITS_VALUE(CLK_SOURCE_UART_FST_MIPI_CAL_UART_FST_MIPI_CAL_CLK_DIVISOR, 10), CLK_RST_REG_BITS_ENUM (CLK_SOURCE_UART_FST_MIPI_CAL_UART_FST_MIPI_CAL_CLK_SRC, PLLP_OUT3)); reg::Write(g_clk_rst_regs + CLK_RST_CONTROLLER_CLK_ENB_W_SET, CLK_RST_REG_BITS_ENUM(CLK_ENB_W_SET_SET_CLK_ENB_DSIA_LP, ENABLE)); reg::Write(g_clk_rst_regs + CLK_RST_CONTROLLER_CLK_SOURCE_DSIA_LP, CLK_RST_REG_BITS_VALUE(CLK_SOURCE_DSIA_LP_DSIA_LP_CLK_DIVISOR, 10), CLK_RST_REG_BITS_ENUM (CLK_SOURCE_DSIA_LP_DSIA_LP_CLK_SRC, PLLP_OUT0)); /* Set IO_DPD_REQ to DPD_OFF. */ reg::ReadWrite(PMC + APBDEV_PMC_IO_DPD_REQ, PMC_REG_BITS_ENUM(IO_DPD_REQ_CODE, DPD_OFF)); reg::ReadWrite(PMC + APBDEV_PMC_IO_DPD2_REQ, PMC_REG_BITS_ENUM(IO_DPD2_REQ_CODE, DPD_OFF)); /* Configure LCD pinmux tristate + passthrough. */ reg::ClearBits(g_apb_misc_regs + PINMUX_AUX_NFC_EN, reg::EncodeMask(PINMUX_REG_BITS_MASK(AUX_TRISTATE))); reg::ClearBits(g_apb_misc_regs + PINMUX_AUX_NFC_INT, reg::EncodeMask(PINMUX_REG_BITS_MASK(AUX_TRISTATE))); reg::ClearBits(g_apb_misc_regs + PINMUX_AUX_LCD_BL_PWM, reg::EncodeMask(PINMUX_REG_BITS_MASK(AUX_TRISTATE))); reg::ClearBits(g_apb_misc_regs + PINMUX_AUX_LCD_BL_EN, reg::EncodeMask(PINMUX_REG_BITS_MASK(AUX_TRISTATE))); reg::ClearBits(g_apb_misc_regs + PINMUX_AUX_LCD_RST, reg::EncodeMask(PINMUX_REG_BITS_MASK(AUX_TRISTATE))); if (hw_type == fuse::HardwareType_Aula) { /* Configure LCD backlight. */ reg::SetBits(g_gpio_regs + GPIO_PORT6_CNF_1, 0x4); reg::SetBits(g_gpio_regs + GPIO_PORT6_OE_1, 0x4); } else { /* Configure LCD power, VDD. */ reg::SetBits(g_gpio_regs + GPIO_PORT3_CNF_0, 0x3); reg::SetBits(g_gpio_regs + GPIO_PORT3_OE_0, 0x3); reg::SetBits(g_gpio_regs + GPIO_PORT3_OUT_0, 0x1); util::WaitMicroSeconds(10'000ul); reg::SetBits(g_gpio_regs + GPIO_PORT3_OUT_0, 0x2); util::WaitMicroSeconds(10'000ul); /* Configure LCD backlight. */ reg::SetBits(g_gpio_regs + GPIO_PORT6_CNF_1, 0x7); reg::SetBits(g_gpio_regs + GPIO_PORT6_OE_1, 0x7); reg::SetBits(g_gpio_regs + GPIO_PORT6_OUT_1, 0x2); } /* Configure display interface and display. */ reg::Write(g_mipi_cal_regs + MIPI_CAL_MIPI_BIAS_PAD_CFG2, 0); if (GetSocType() == fuse::SocType_Mariko) { reg::Write(g_mipi_cal_regs + MIPI_CAL_MIPI_BIAS_PAD_CFG0, 0); reg::Write(g_apb_misc_regs + APB_MISC_GP_DSI_PAD_CONTROL, 0); } /* Execute configs. */ DO_SOC_DEPENDENT_REGISTER_WRITES(g_clk_rst_regs, DisplayConfigPlld01); DO_SLEEP_OR_REGISTER_WRITES(g_disp1_regs, DisplayConfigDc01); DO_REGISTER_WRITES(g_dsi_regs, DisplayConfigDsi01Init01); DO_SOC_DEPENDENT_REGISTER_WRITES(g_dsi_regs, DisplayConfigDsi01Init02); DO_REGISTER_WRITES(g_dsi_regs, DisplayConfigDsi01Init03); DO_SOC_DEPENDENT_REGISTER_WRITES(g_dsi_regs, DisplayConfigDsi01Init04); DO_REGISTER_WRITES(g_dsi_regs, DisplayConfigDsi01Init05); DO_SOC_DEPENDENT_REGISTER_WRITES(g_dsi_regs, DisplayConfigDsiPhyTiming); DO_REGISTER_WRITES(g_dsi_regs, DisplayConfigDsi01Init06); DO_SOC_DEPENDENT_REGISTER_WRITES(g_dsi_regs, DisplayConfigDsiPhyTiming); DO_REGISTER_WRITES(g_dsi_regs, DisplayConfigDsi01Init07); util::WaitMicroSeconds(10'000ul); /* Enable backlight reset. */ reg::SetBits(g_gpio_regs + GPIO_PORT6_OUT_1, 0x4); util::WaitMicroSeconds(60'000ul); if (hw_type == fuse::HardwareType_Aula) { reg::Write(g_dsi_regs + sizeof(u32) * DSI_BTA_TIMING, 0x40103); } else { reg::Write(g_dsi_regs + sizeof(u32) * DSI_BTA_TIMING, 0x50204); } reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x337); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); WaitDsiTrigger(); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x406); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); WaitDsiTrigger(); reg::Write(g_dsi_regs + sizeof(u32) * DSI_HOST_CONTROL, DSI_HOST_CONTROL_TX_TRIG_HOST | DSI_HOST_CONTROL_IMM_BTA | DSI_HOST_CONTROL_CS | DSI_HOST_CONTROL_ECC); WaitDsiHostControl(); util::WaitMicroSeconds(5'000ul); /* Parse LCD vendor. */ { u32 host_response[3]; for (size_t i = 0; i < util::size(host_response); i++) { host_response[i] = reg::Read(g_dsi_regs + sizeof(u32) * DSI_RD_DATA); } /* The last word from host response is: Bits 0-7: FAB Bits 8-15: REV Bits 16-23: Minor REV */ u32 lcd_vendor; if ((host_response[2] & 0xFF) == 0x10) { lcd_vendor = 0; } else { lcd_vendor = (host_response[2] >> 8) & 0xFF00; } lcd_vendor = (lcd_vendor & 0xFFFFFF00) | (host_response[2] & 0xFF); AMS_ASSERT(lcd_vendor == GetLcdVendor()); } /* LCD vendor specific configuration. */ switch (GetLcdVendor()) { case 0x10: /* Japan Display Inc screens. */ DO_SLEEP_OR_REGISTER_WRITES(g_dsi_regs, DisplayConfigJdiSpecificInit01); break; case 0xF20: /* Innolux first revision screens. */ reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x1105); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); util::WaitMicroSeconds(180'000ul); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x439); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x9483FFB9); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); util::WaitMicroSeconds(5'000ul); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x739); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x751548B1); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x143209); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); util::WaitMicroSeconds(5'000ul); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x2905); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); break; case 0xF30: /* AUO first revision screens. */ reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x1105); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); util::WaitMicroSeconds(180'000ul); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x439); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x9483FFB9); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); util::WaitMicroSeconds(5'000ul); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x739); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x711148B1); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x143209); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); util::WaitMicroSeconds(5'000ul); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x2905); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); break; case 0x2050: /* Unknown (hardware type 5) screen. */ reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x1105); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); util::WaitMicroSeconds(180'000ul); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0xA015); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x205315); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x339); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x51); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); util::WaitMicroSeconds(5'000ul); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x2905); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); break; case 0x1020: /* Innolux second revision screen. */ case 0x1030: /* AUO second revision screen. */ case 0x1040: /* Unknown second revision screen. */ default: reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x1105); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); util::WaitMicroSeconds(120'000ul); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x2905); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); break; } util::WaitMicroSeconds(20'000ul); DO_SOC_DEPENDENT_REGISTER_WRITES(g_clk_rst_regs, DisplayConfigPlld02); DO_REGISTER_WRITES(g_dsi_regs, DisplayConfigDsi01Init08); DO_SOC_DEPENDENT_REGISTER_WRITES(g_dsi_regs, DisplayConfigDsiPhyTiming); DO_SLEEP_OR_REGISTER_WRITES(g_dsi_regs, DisplayConfigDsi01Init09); reg::Write(g_disp1_regs + sizeof(u32) * DC_DISP_DISP_CLOCK_CONTROL, SHIFT_CLK_DIVIDER(4)); DO_REGISTER_WRITES(g_dsi_regs, DisplayConfigDsi01Init10); util::WaitMicroSeconds(10'000ul); /* Configure MIPI CAL. */ DO_REGISTER_WRITES(g_mipi_cal_regs, DisplayConfigMipiCal01); DO_SOC_DEPENDENT_REGISTER_WRITES(g_mipi_cal_regs, DisplayConfigMipiCal02); DO_SOC_DEPENDENT_REGISTER_WRITES(g_dsi_regs, DisplayConfigDsi01Init11); DO_SOC_DEPENDENT_REGISTER_WRITES(g_mipi_cal_regs, DisplayConfigMipiCal03); DO_REGISTER_WRITES(g_mipi_cal_regs, DisplayConfigMipiCal04); if (GetSocType() == fuse::SocType_Mariko) { /* On Mariko the above configurations are executed twice, for some reason. */ DO_SOC_DEPENDENT_REGISTER_WRITES(g_mipi_cal_regs, DisplayConfigMipiCal02); DO_SOC_DEPENDENT_REGISTER_WRITES(g_dsi_regs, DisplayConfigDsi01Init11); DO_SOC_DEPENDENT_REGISTER_WRITES(g_mipi_cal_regs, DisplayConfigMipiCal03); DO_REGISTER_WRITES(g_mipi_cal_regs, DisplayConfigMipiCal04); } util::WaitMicroSeconds(10'000ul); /* Write DISP1, FrameBuffer config. */ DO_SLEEP_OR_REGISTER_WRITES(g_disp1_regs, DisplayConfigDc02); DO_SLEEP_OR_REGISTER_WRITES(g_disp1_regs, DisplayConfigFrameBuffer); if (GetLcdVendor() != 0x2050) { util::WaitMicroSeconds(35'000ul); } } void ShowDisplay(const ams::impl::FatalErrorContext *f_ctx, const Result save_result) { /* Initialize the console. */ InitializeConsole(g_frame_buffer); { Print("%s\n", "A fatal error occurred when running Atmosph\xe8re."); Print("Program ID: %016" PRIx64 "\n", f_ctx->program_id); Print("Error Desc: %s (0x%x)\n", GetErrorDescription(f_ctx->error_desc), f_ctx->error_desc); Print("\n"); if (R_SUCCEEDED(save_result)) { Print("Report saved to /atmosphere/fatal_errors/report_%016" PRIx64 ".bin", f_ctx->report_identifier); } else { Print("Failed to save report to the SD card! (%08x)\n", save_result.GetValue()); } PrintSuggestedErrorFix(f_ctx); Print("\nPress POWER to reboot.\n"); } /* Ensure the device will see consistent data. */ hw::FlushDataCache(g_frame_buffer, FrameBufferSize); /* Enable backlight. */ constexpr auto DisplayBrightness = 100; if (GetLcdVendor() == 0x2050) { EnableBacklightForVendor2050ForAula(DisplayBrightness); } else { EnableBacklightForGeneric(DisplayBrightness); } } }
31,601
C++
.cpp
510
46.966667
206
0.571018
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,377
fatal_fs_api.cpp
Atmosphere-NX_Atmosphere/exosphere/mariko_fatal/source/fs/fatal_fs_api.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 <exosphere.hpp> #include "../fatfs/ff.h" #include "fatal_fs_api.hpp" namespace ams::fs { namespace { constexpr size_t MaxFiles = 8; constinit bool g_is_sd_mounted = false; FATFS g_sd_fs; constinit FIL g_files[MaxFiles] = {}; constinit bool g_files_opened[MaxFiles] = {}; constinit int g_open_modes[MaxFiles] = {}; Result TranslateFatFsError(FRESULT res) { switch (res) { case FR_OK: R_SUCCEED(); case FR_DISK_ERR: R_THROW(fs::ResultMmcAccessFailed()); case FR_INT_ERR: R_THROW(fs::ResultPreconditionViolation()); case FR_NOT_READY: R_THROW(fs::ResultMmcAccessFailed()); case FR_NO_FILE: R_THROW(fs::ResultPathNotFound()); case FR_NO_PATH: R_THROW(fs::ResultPathNotFound()); case FR_INVALID_NAME: R_THROW(fs::ResultInvalidPath()); case FR_DENIED: R_THROW(fs::ResultPermissionDenied()); case FR_EXIST: R_THROW(fs::ResultPathAlreadyExists()); case FR_INVALID_OBJECT: R_THROW(fs::ResultInvalidArgument()); case FR_WRITE_PROTECTED: R_THROW(fs::ResultWriteNotPermitted()); case FR_INVALID_DRIVE: R_THROW(fs::ResultInvalidMountName()); case FR_NOT_ENABLED: R_THROW(fs::ResultInvalidMountName()); /* BAD/TODO */ case FR_NO_FILESYSTEM: R_THROW(fs::ResultInvalidMountName()); /* BAD/TODO */ case FR_TIMEOUT: R_THROW(fs::ResultTargetLocked()); /* BAD/TODO */ case FR_LOCKED: R_THROW(fs::ResultTargetLocked()); case FR_NOT_ENOUGH_CORE: R_THROW(fs::ResultPreconditionViolation()); /* BAD/TODO */ case FR_TOO_MANY_OPEN_FILES: R_THROW(fs::ResultPreconditionViolation()); /* BAD/TODO */ case FR_INVALID_PARAMETER: R_THROW(fs::ResultInvalidArgument()); default: R_THROW(fs::ResultInternal()); } } int TranslateToFatFsMode(int mode) { int fmode = FA_OPEN_EXISTING; if ((mode & OpenMode_Read) != 0) { fmode |= FA_READ; } if ((mode & OpenMode_Write) != 0) { fmode |= FA_WRITE; } if ((mode & OpenMode_AllowAppend) != 0) { fmode |= FA_OPEN_APPEND; } return fmode; } FIL *GetInternalFile(FileHandle handle) { return static_cast<FIL *>(handle._handle); } ALWAYS_INLINE size_t GetFileIndex(FIL *fp) { const size_t file_index = (fp - g_files); AMS_ASSERT(file_index < MaxFiles); return file_index; } } bool MountSdCard() { AMS_ASSERT(!g_is_sd_mounted); g_is_sd_mounted = f_mount(std::addressof(g_sd_fs), "sdmc", 1) == FR_OK; return g_is_sd_mounted; } void UnmountSdCard() { AMS_ASSERT(g_is_sd_mounted); f_unmount("sdmc"); g_is_sd_mounted = false; } Result CreateFile(const char *path, s64 size) { /* Create the file. */ FIL fp; R_TRY(TranslateFatFsError(f_open(std::addressof(fp), path, FA_CREATE_NEW | FA_READ | FA_WRITE))); /* Ensure that we close the file when we're done with it. */ ON_SCOPE_EXIT { f_close(std::addressof(fp)); }; /* Expand the file. */ R_TRY(TranslateFatFsError(f_expand(std::addressof(fp), size, 1))); R_SUCCEED(); } Result CreateDirectory(const char *path) { R_RETURN(TranslateFatFsError(f_mkdir(path))); } Result OpenFile(FileHandle *out_file, const char *path, int mode) { /* Find a free file. */ for (size_t i = 0; i < MaxFiles; ++i) { if (!g_files_opened[i]) { /* Open the file. */ FIL *fp = std::addressof(g_files[i]); R_TRY(TranslateFatFsError(f_open(fp, path, TranslateToFatFsMode(mode)))); /* Set the output. */ out_file->_handle = fp; g_files_opened[i] = true; g_open_modes[i] = mode; R_SUCCEED(); } } R_THROW(fs::ResultOpenCountLimit()); } Result ReadFile(FileHandle handle, s64 offset, void *buffer, size_t size, const fs::ReadOption &option) { /* Option is unused. */ AMS_UNUSED(option); /* Seek to the offset we're reading at. */ R_TRY(TranslateFatFsError(f_lseek(GetInternalFile(handle), offset))); /* Read the data. */ u32 br; R_TRY(TranslateFatFsError(f_read(GetInternalFile(handle), buffer, size, std::addressof(br)))); /* Check that we read the correct amount. */ R_UNLESS(br == size, fs::ResultOutOfRange()); R_SUCCEED(); } Result ReadFile(FileHandle handle, s64 offset, void *buffer, size_t size) { R_RETURN(ReadFile(handle, offset, buffer, size, fs::ReadOption::None)); } Result ReadFile(size_t *out, FileHandle handle, s64 offset, void *buffer, size_t size, const fs::ReadOption &option) { /* Option is unused. */ AMS_UNUSED(option); /* Seek to the offset we're reading at. */ R_TRY(TranslateFatFsError(f_lseek(GetInternalFile(handle), offset))); /* Read the data. */ u32 br; R_TRY(TranslateFatFsError(f_read(GetInternalFile(handle), buffer, size, std::addressof(br)))); /* Set the output size. */ *out = br; R_SUCCEED(); } Result ReadFile(size_t *out, FileHandle handle, s64 offset, void *buffer, size_t size) { R_RETURN(ReadFile(out, handle, offset, buffer, size, fs::ReadOption::None)); } Result GetFileSize(s64 *out, FileHandle handle) { FIL *fp = GetInternalFile(handle); *out = f_size(fp); R_SUCCEED(); } Result FlushFile(FileHandle handle) { R_RETURN(TranslateFatFsError(f_sync(GetInternalFile(handle)))); } Result WriteFile(FileHandle handle, s64 offset, const void *buffer, size_t size, const fs::WriteOption &option) { /* Seek to the offset we're writing at. */ R_TRY(TranslateFatFsError(f_lseek(GetInternalFile(handle), offset))); /* Write the data. */ u32 bw; R_TRY(TranslateFatFsError(f_write(GetInternalFile(handle), buffer, size, std::addressof(bw)))); /* Check that we wrote the correct amount. */ R_UNLESS(bw == size, fs::ResultOutOfRange()); /* If we should, flush the file. */ if (option.HasFlushFlag()) { R_TRY(FlushFile(handle)); } R_SUCCEED(); } Result SetFileSize(FileHandle handle, s64 size) { FIL *fp = GetInternalFile(handle); /* Check if we have nothing to do. */ const size_t fsize = f_size(fp); R_SUCCEED_IF(static_cast<FSIZE_t>(size) == fsize); /* NOTE/TODO: This may not preserve file data. Do this in a way that does? */ /* Truncate the file. */ R_TRY(TranslateFatFsError(f_truncate(fp))); /* Expand the file. */ R_TRY(TranslateFatFsError(f_expand(fp, size, 1))); /* Ensure the file is synchronized. */ R_TRY(FlushFile(handle)); /* Check that our expansion succeeded. */ AMS_ASSERT(f_size(fp) == static_cast<FSIZE_t>(size)); R_SUCCEED(); } int GetFileOpenMode(FileHandle handle) { return g_open_modes[GetFileIndex(GetInternalFile(handle))]; } void CloseFile(FileHandle handle) { const size_t index = GetFileIndex(GetInternalFile(handle)); f_close(std::addressof(g_files[index])); g_open_modes[index] = 0; g_files_opened[index] = false; } }
8,826
C++
.cpp
209
31.641148
122
0.568927
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,378
warmboot_cpu_cluster.cpp
Atmosphere-NX_Atmosphere/exosphere/warmboot/source/warmboot_cpu_cluster.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 <exosphere.hpp> #include "warmboot_clkrst.hpp" #include "warmboot_util.hpp" namespace ams::warmboot { namespace { constexpr inline const uintptr_t APB_MISC = secmon::MemoryRegionPhysicalDeviceApbMisc.GetAddress(); constexpr inline const uintptr_t CLKRST = secmon::MemoryRegionPhysicalDeviceClkRst.GetAddress(); constexpr inline const uintptr_t FLOW_CTLR = secmon::MemoryRegionPhysicalDeviceFlowController.GetAddress(); constexpr inline const uintptr_t GPIO = secmon::MemoryRegionPhysicalDeviceGpio.GetAddress(); constexpr inline const uintptr_t MSELECT = MSELECT(0); constexpr inline const uintptr_t PMC = secmon::MemoryRegionPhysicalDevicePmc.GetAddress(); constexpr inline const uintptr_t SYSTEM = secmon::MemoryRegionPhysicalDeviceSystem.GetAddress(); ALWAYS_INLINE void EnableClusterPartition(const reg::BitsValue value, APBDEV_PMC_PWRGATE_TOGGLE_PARTID part_id) { /* Toggle the partitions if necessary. */ if (!reg::HasValue(PMC + APBDEV_PMC_PWRGATE_STATUS, value)) { reg::Write(PMC + APBDEV_PMC_PWRGATE_TOGGLE, PMC_REG_BITS_ENUM (PWRGATE_TOGGLE_START, ENABLE), PMC_REG_BITS_VALUE(PWRGATE_TOGGLE_PARTID, part_id)); } /* Wait for the toggle to complete. */ while (!reg::HasValue(PMC + APBDEV_PMC_PWRGATE_STATUS, value)) { /* ... */ } /* Remove clamping. */ reg::Write(PMC + APBDEV_PMC_REMOVE_CLAMPING_CMD, value); /* Wait for clamping to be removed. */ while (reg::HasValue(PMC + APBDEV_PMC_CLAMP_STATUS, value)) { /* ... */ } } } void InitializeCpuCluster() { /* Set CoreSight reset. */ reg::Write(CLKRST + CLK_RST_CONTROLLER_RST_DEV_U_SET, CLK_RST_REG_BITS_ENUM(RST_DEV_U_SET_SET_CSITE_RST, ENABLE)); /* Restore PROD setting to CPU_SOFTRST_CTRL2 by clearing CAR2PMC_CPU_ACK_WIDTH. */ reg::ReadWrite(CLKRST + CLK_RST_CONTROLLER_CPU_SOFTRST_CTRL2, CLK_RST_REG_BITS_VALUE(CPU_SOFTRST_CTRL2_CAR2PMC_CPU_ACK_WIDTH, 0)); /* Restore the CPU reset vector from PMC scratch. */ reg::Write(SYSTEM + SB_AA64_RESET_LOW, reg::Read(PMC + APBDEV_PMC_SECURE_SCRATCH34) | 1); reg::Write(SYSTEM + SB_AA64_RESET_HIGH, reg::Read(PMC + APBDEV_PMC_SECURE_SCRATCH35)); /* Configure SUPER_CCLKG_DIVIDER. */ reg::Write(CLKRST + CLK_RST_CONTROLLER_SUPER_CCLKG_DIVIDER, CLK_RST_REG_BITS_ENUM (SUPER_CCLKG_DIVIDER_SUPER_CDIV_ENB, ENABLE), CLK_RST_REG_BITS_ENUM (SUPER_CCLK_DIVIDER_SUPER_CDIV_DIS_FROM_COP_FIQ, NO_IMPACT), CLK_RST_REG_BITS_ENUM (SUPER_CCLK_DIVIDER_SUPER_CDIV_DIS_FROM_CPU_FIQ, NO_IMPACT), CLK_RST_REG_BITS_ENUM (SUPER_CCLK_DIVIDER_SUPER_CDIV_DIS_FROM_COP_IRQ, NO_IMPACT), CLK_RST_REG_BITS_ENUM (SUPER_CCLK_DIVIDER_SUPER_CDIV_DIS_FROM_CPU_IRQ, NO_IMPACT), CLK_RST_REG_BITS_VALUE(SUPER_CCLK_DIVIDER_SUPER_CDIV_DIVIDEND, 0), CLK_RST_REG_BITS_VALUE(SUPER_CCLK_DIVIDER_SUPER_CDIV_DIVISOR, 0)); /* Configure SUPER_CCLKLP_DIVIDER. */ reg::Write(CLKRST + CLK_RST_CONTROLLER_SUPER_CCLKLP_DIVIDER, CLK_RST_REG_BITS_ENUM (SUPER_CCLKLP_DIVIDER_SUPER_CDIV_ENB, ENABLE), CLK_RST_REG_BITS_ENUM (SUPER_CCLK_DIVIDER_SUPER_CDIV_DIS_FROM_COP_FIQ, NO_IMPACT), CLK_RST_REG_BITS_ENUM (SUPER_CCLK_DIVIDER_SUPER_CDIV_DIS_FROM_CPU_FIQ, NO_IMPACT), CLK_RST_REG_BITS_ENUM (SUPER_CCLK_DIVIDER_SUPER_CDIV_DIS_FROM_COP_IRQ, NO_IMPACT), CLK_RST_REG_BITS_ENUM (SUPER_CCLK_DIVIDER_SUPER_CDIV_DIS_FROM_CPU_IRQ, NO_IMPACT), CLK_RST_REG_BITS_VALUE(SUPER_CCLK_DIVIDER_SUPER_CDIV_DIVIDEND, 0), CLK_RST_REG_BITS_VALUE(SUPER_CCLK_DIVIDER_SUPER_CDIV_DIVISOR, 0)); /* Enable CoreSight clock. */ reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_ENB_U_SET, CLK_RST_REG_BITS_ENUM(CLK_ENB_U_SET_SET_CLK_ENB_CSITE, ENABLE)); /* Clear CoreSight reset. */ reg::Write(CLKRST + CLK_RST_CONTROLLER_RST_DEV_U_CLR, CLK_RST_REG_BITS_ENUM(RST_DEV_U_CLR_CLR_CSITE_RST, ENABLE)); /* Select MSELECT clock source as PLLP_OUT0 with divider of 4. */ reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_SOURCE_MSELECT, CLK_RST_REG_BITS_ENUM (CLK_SOURCE_MSELECT_MSELECT_CLK_SRC, PLLP_OUT0), CLK_RST_REG_BITS_VALUE(CLK_SOURCE_MSELECT_MSELECT_CLK_DIVISOR, 6)); /* Enable clock to MSELECT. */ reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_ENB_V_SET, CLK_RST_REG_BITS_ENUM(CLK_ENB_V_SET_SET_CLK_ENB_MSELECT, ENABLE)); /* Wait two microseconds, then take MSELECT out of reset. */ util::WaitMicroSeconds(2); reg::Write(CLKRST + CLK_RST_CONTROLLER_RST_DEV_V_CLR, CLK_RST_REG_BITS_ENUM(RST_DEV_V_CLR_CLR_MSELECT_RST, ENABLE)); /* Workaround bug by disabling MSELECT error mechanism and enabling WRAP type conversion. */ reg::ReadWrite(MSELECT + MSELECT_CONFIG, MSELECT_REG_BITS_ENUM(CONFIG_ERR_RESP_EN_SLAVE1, DISABLE), MSELECT_REG_BITS_ENUM(CONFIG_ERR_RESP_EN_SLAVE2, DISABLE), MSELECT_REG_BITS_ENUM(CONFIG_WRAP_TO_INCR_SLAVE0, ENABLE), MSELECT_REG_BITS_ENUM(CONFIG_WRAP_TO_INCR_SLAVE1, ENABLE), MSELECT_REG_BITS_ENUM(CONFIG_WRAP_TO_INCR_SLAVE2, ENABLE)); /* Disable PLLX. */ reg::ReadWrite(CLKRST + CLK_RST_CONTROLLER_PLLX_BASE, CLK_RST_REG_BITS_ENUM(PLLX_BASE_PLLX_ENABLE, DISABLE)); /* Clear bit 0 of PMC Scratch 190. */ reg::ReadWrite(PMC + APBDEV_PMC_SCRATCH190, REG_BITS_VALUE(0, 1, 0)); /* Clear PMC_DPD_SAMPLE, and wait 10 us for clear to take effect. */ reg::Write(PMC + APBDEV_PMC_DPD_SAMPLE, 0); util::WaitMicroSeconds(10); /* Configure UART2_RTS low (GPIO controller 2 G). */ reg::ReadWrite(GPIO + 0x108, REG_BITS_VALUE(2, 1, 1)); /* GPIO_CNF */ reg::ReadWrite(GPIO + 0x118, REG_BITS_VALUE(2, 1, 1)); /* GPIO_OE */ reg::ReadWrite(GPIO + 0x128, REG_BITS_VALUE(2, 1, 0)); /* GPIO_OUT */ /* Tristate CLDVFS PWN. */ reg::Write(APB_MISC + PINMUX_AUX_DVFS_PWM, PINMUX_REG_BITS_ENUM(AUX_TRISTATE, TRISTATE), PINMUX_REG_BITS_ENUM(AUX_DVFS_PWM_PM, CLDVFS)); reg::Read(APB_MISC + PINMUX_AUX_DVFS_PWM); /* Restore PWR_I2C E_INPUT. */ reg::Write(APB_MISC + PINMUX_AUX_PWR_I2C_SCL, PINMUX_REG_BITS_ENUM(AUX_E_INPUT, ENABLE)); reg::Write(APB_MISC + PINMUX_AUX_PWR_I2C_SDA, PINMUX_REG_BITS_ENUM(AUX_E_INPUT, ENABLE)); /* Enable CLDVFS clock. */ reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_ENB_W_SET, CLK_RST_REG_BITS_ENUM(CLK_ENB_W_SET_SET_CLK_ENB_DVFS, ENABLE)); /* Set CLDVFS clock source/divider. */ reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_SOURCE_DVFS_REF, CLK_RST_REG_BITS_ENUM (CLK_SOURCE_DVFS_REF_DVFS_REF_CLK_SRC, PLLP_OUT0), CLK_RST_REG_BITS_VALUE(CLK_SOURCE_DVFS_REF_DVFS_REF_DIVISOR, 14)); reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_SOURCE_DVFS_SOC, CLK_RST_REG_BITS_ENUM (CLK_SOURCE_DVFS_SOC_DVFS_SOC_CLK_SRC, PLLP_OUT0), CLK_RST_REG_BITS_VALUE(CLK_SOURCE_DVFS_SOC_DVFS_SOC_DIVISOR, 14)); /* Enable PWR_I2C controller (I2C5). */ reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_ENB_H_SET, CLK_RST_REG_BITS_ENUM(CLK_ENB_H_SET_SET_CLK_ENB_I2C5, ENABLE)); reg::Write(CLKRST + CLK_RST_CONTROLLER_RST_DEV_H_SET, CLK_RST_REG_BITS_ENUM(RST_DEV_H_SET_SET_I2C5_RST, ENABLE)); util::WaitMicroSeconds(5); reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_SOURCE_I2C5, CLK_RST_REG_BITS_ENUM (CLK_SOURCE_I2C5_I2C5_CLK_SRC, PLLP_OUT0), CLK_RST_REG_BITS_VALUE(CLK_SOURCE_I2C5_I2C5_CLK_DIVISOR, 4)); reg::Write(CLKRST + CLK_RST_CONTROLLER_RST_DEV_H_CLR, CLK_RST_REG_BITS_ENUM(RST_DEV_H_CLR_CLR_I2C5_RST, ENABLE)); /* Set the EN bit in pmic regulator. */ pmic::SetEnBit(fuse::GetRegulator()); /* Wait 2ms. */ util::WaitMicroSeconds(2'000); /* Enable power to the CRAIL partition. */ EnableClusterPartition(PMC_REG_BITS_ENUM(PWRGATE_STATUS_CRAIL, ON), APBDEV_PMC_PWRGATE_TOGGLE_PARTID_CRAIL); /* Remove software clamp to CRAIL. */ reg::Write(PMC + APBDEV_PMC_SET_SW_CLAMP, 0); reg::Write(PMC + APBDEV_PMC_REMOVE_CLAMPING_CMD, PMC_REG_BITS_ENUM(REMOVE_CLAMPING_COMMAND_CRAIL, ENABLE)); while (reg::HasValue(PMC + APBDEV_PMC_CLAMP_STATUS, PMC_REG_BITS_ENUM(CLAMP_STATUS_CRAIL, ENABLE))) { /* ... */ } /* Spinloop 8 times, to add a little delay. */ SpinLoop(8); /* Disable PWR_I2C controller (I2C5). */ reg::Write(CLKRST + CLK_RST_CONTROLLER_RST_DEV_H_SET, CLK_RST_REG_BITS_ENUM(RST_DEV_H_SET_SET_I2C5_RST, ENABLE)); reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_ENB_H_CLR, CLK_RST_REG_BITS_ENUM(CLK_ENB_H_CLR_CLR_CLK_ENB_I2C5, ENABLE)); /* Disable CLDVFS clock. */ reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_ENB_W_CLR, CLK_RST_REG_BITS_ENUM(CLK_ENB_W_CLR_CLR_CLK_ENB_DVFS, ENABLE)); /* Perform fast cluster RAM repair if needed. */ if (!reg::HasValue(FLOW_CTLR + FLOW_CTLR_BPMP_CLUSTER_CONTROL, FLOW_REG_BITS_ENUM(BPMP_CLUSTER_CONTROL_ACTIVE_CLUSTER, SLOW))) { reg::Write(FLOW_CTLR + FLOW_CTLR_RAM_REPAIR, FLOW_REG_BITS_ENUM(RAM_REPAIR_REQ, ENABLE)); while (!reg::HasValue(FLOW_CTLR + FLOW_CTLR_RAM_REPAIR, FLOW_REG_BITS_ENUM(RAM_REPAIR_STS, DONE))) { /* ... */ } } /* Enable power to the non-cpu partition. */ EnableClusterPartition(PMC_REG_BITS_ENUM(PWRGATE_STATUS_C0NC, ON), APBDEV_PMC_PWRGATE_TOGGLE_PARTID_C0NC); /* Enable clock to PLLP_OUT_CPU. */ reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_ENB_Y_SET, CLK_RST_REG_BITS_ENUM(CLK_ENB_Y_SET_SET_CLK_ENB_PLLP_OUT_CPU, ENABLE)); util::WaitMicroSeconds(2); /* Enable clock to the cpu complex. */ reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_ENB_L_SET, CLK_RST_REG_BITS_ENUM(CLK_ENB_L_SET_SET_CLK_ENB_CPU, ENABLE)); reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_ENB_V_SET, CLK_RST_REG_BITS_ENUM(CLK_ENB_V_SET_SET_CLK_ENB_CPUG, ENABLE)); util::WaitMicroSeconds(10); /* Select cpu complex clock source. */ reg::Write(CLKRST + CLK_RST_CONTROLLER_CCLKG_BURST_POLICY, CLK_RST_REG_BITS_ENUM(CCLK_BURST_POLICY_CWAKEUP_IDLE_SOURCE, PLLP_OUT0), CLK_RST_REG_BITS_ENUM(CCLK_BURST_POLICY_CWAKEUP_RUN_SOURCE, PLLP_OUT0), CLK_RST_REG_BITS_ENUM(CCLK_BURST_POLICY_CWAKEUP_IRQ_SOURCE, PLLP_OUT0), CLK_RST_REG_BITS_ENUM(CCLK_BURST_POLICY_CWAKEUP_FIQ_SOURCE, PLLP_OUT0), CLK_RST_REG_BITS_ENUM(CCLK_BURST_POLICY_CPU_STATE, RUN)); reg::Write(CLKRST + CLK_RST_CONTROLLER_CCLKLP_BURST_POLICY, CLK_RST_REG_BITS_ENUM(CCLK_BURST_POLICY_CWAKEUP_IDLE_SOURCE, PLLP_OUT0), CLK_RST_REG_BITS_ENUM(CCLK_BURST_POLICY_CWAKEUP_RUN_SOURCE, PLLP_OUT0), CLK_RST_REG_BITS_ENUM(CCLK_BURST_POLICY_CWAKEUP_IRQ_SOURCE, PLLP_OUT0), CLK_RST_REG_BITS_ENUM(CCLK_BURST_POLICY_CWAKEUP_FIQ_SOURCE, PLLP_OUT0), CLK_RST_REG_BITS_ENUM(CCLK_BURST_POLICY_CPU_STATE, RUN)); util::WaitMicroSeconds(10); /* Wake non-cpu out of reset. */ reg::Write(CLKRST + CLK_RST_CONTROLLER_RST_CPUG_CMPLX_CLR, CLK_RST_REG_BITS_ENUM(RST_CPUG_CMPLX_CLR_CLR_NONCPURESET, ENABLE)); } void PowerOnCpu() { /* Enable power to the CE0 partition. */ EnableClusterPartition(PMC_REG_BITS_ENUM(PWRGATE_STATUS_CE0, ON), APBDEV_PMC_PWRGATE_TOGGLE_PARTID_CE0); /* Clear CPU reset. */ reg::Write(CLKRST + CLK_RST_CONTROLLER_RST_CPUG_CMPLX_CLR, CLK_RST_REG_BITS_ENUM(RST_CPUG_CMPLX_CLR_CLR_CPURESET0, ENABLE), CLK_RST_REG_BITS_ENUM(RST_CPUG_CMPLX_CLR_CLR_CORERESET0, ENABLE)); } }
14,342
C++
.cpp
171
64.923977
152
0.578985
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,379
warmboot_dram.cpp
Atmosphere-NX_Atmosphere/exosphere/warmboot/source/warmboot_dram.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 <exosphere.hpp> #include "warmboot_dram.hpp" namespace ams::warmboot { namespace { constexpr inline const uintptr_t APB_MISC = secmon::MemoryRegionPhysicalDeviceApbMisc.GetAddress(); constexpr inline const uintptr_t EMC = EMC_ADDRESS(0); constexpr inline const uintptr_t EMC0 = EMC0_ADDRESS(0); constexpr inline const uintptr_t EMC1 = EMC1_ADDRESS(0); constexpr inline const uintptr_t MC = secmon::MemoryRegionPhysicalDeviceMemoryController.GetAddress(); constexpr inline const uintptr_t MC0 = secmon::MemoryRegionPhysicalDeviceMemoryController0.GetAddress(); constexpr inline const uintptr_t MC1 = secmon::MemoryRegionPhysicalDeviceMemoryController1.GetAddress(); } void RestrictBpmpAccessToMainMemory() { /* Bpmp memory access is restricted by forcing internal access to an invalid carveout. */ constexpr u32 ForceInternalAccess0 = reg::Encode(MC_REG_BITS_ENUM(CLIENT_ACCESS0_AVPCARM7R, ENABLE)); constexpr u32 ForceInternalAccess1 = reg::Encode(MC_REG_BITS_ENUM(CLIENT_ACCESS1_AVPCARM7W, ENABLE)); constexpr u32 CarveoutConfig = reg::Encode(MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_IS_WPR, DISABLED), MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_FORCE_APERTURE_ID_MATCH, DISABLED), MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_ALLOW_APERTURE_ID_MISMATCH, DISABLED), MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_TZ_GLOBAL_RD_EN, DISABLED), MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_TZ_GLOBAL_WR_EN, DISABLED), MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_SEND_CFG_TO_GPU, DISABLED), MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_DISABLE_WRITE_CHECK_ACCESS_LEVEL3, ENABLE_CHECKS), MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_DISABLE_WRITE_CHECK_ACCESS_LEVEL2, ENABLE_CHECKS), MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_DISABLE_WRITE_CHECK_ACCESS_LEVEL1, ENABLE_CHECKS), MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_DISABLE_WRITE_CHECK_ACCESS_LEVEL0, ENABLE_CHECKS), MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_DISABLE_READ_CHECK_ACCESS_LEVEL3, ENABLE_CHECKS), MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_DISABLE_READ_CHECK_ACCESS_LEVEL2, ENABLE_CHECKS), MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_DISABLE_READ_CHECK_ACCESS_LEVEL1, ENABLE_CHECKS), MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_DISABLE_READ_CHECK_ACCESS_LEVEL0, ENABLE_CHECKS), MC_REG_BITS_VALUE(SECURITY_CARVEOUT_CFG0_APERTURE_ID, 0), MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_WRITE_ACCESS_LEVEL3, DISABLED), MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_WRITE_ACCESS_LEVEL2, DISABLED), MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_WRITE_ACCESS_LEVEL1, DISABLED), MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_WRITE_ACCESS_LEVEL0, ENABLED), MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_READ_ACCESS_LEVEL3, DISABLED), MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_READ_ACCESS_LEVEL2, DISABLED), MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_READ_ACCESS_LEVEL1, DISABLED), MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_READ_ACCESS_LEVEL0, ENABLED), MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_ADDRESS_TYPE, UNTRANSLATED_ONLY), MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_LOCK_MODE, LOCKED), MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_PROTECT_MODE, TZ_SECURE)); /* Specify a 128KB carveout at NULL with no clients allowed access, and bpmp forced to access. */ reg::Write(MC + MC_SECURITY_CARVEOUT4_BOM, 0); reg::Write(MC + MC_SECURITY_CARVEOUT4_BOM_HI, 0); reg::Write(MC + MC_SECURITY_CARVEOUT4_SIZE_128KB, 1); reg::Write(MC + MC_SECURITY_CARVEOUT4_CLIENT_ACCESS0, 0); reg::Write(MC + MC_SECURITY_CARVEOUT4_CLIENT_ACCESS1, 0); reg::Write(MC + MC_SECURITY_CARVEOUT4_CLIENT_ACCESS2, 0); reg::Write(MC + MC_SECURITY_CARVEOUT4_CLIENT_ACCESS3, 0); reg::Write(MC + MC_SECURITY_CARVEOUT4_CLIENT_ACCESS4, 0); reg::Write(MC + MC_SECURITY_CARVEOUT4_CLIENT_FORCE_INTERNAL_ACCESS0, ForceInternalAccess0); reg::Write(MC + MC_SECURITY_CARVEOUT4_CLIENT_FORCE_INTERNAL_ACCESS1, ForceInternalAccess1); reg::Write(MC + MC_SECURITY_CARVEOUT4_CLIENT_FORCE_INTERNAL_ACCESS2, 0); reg::Write(MC + MC_SECURITY_CARVEOUT4_CLIENT_FORCE_INTERNAL_ACCESS3, 0); reg::Write(MC + MC_SECURITY_CARVEOUT4_CLIENT_FORCE_INTERNAL_ACCESS4, 0); reg::Write(MC + MC_SECURITY_CARVEOUT4_CFG0, CarveoutConfig); } void RestoreRamSvop() { reg::ReadWrite(APB_MISC + APB_MISC_GP_ASDBGREG, APB_MISC_REG_BITS_VALUE(GP_ASDBGREG_CFG2TMC_RAM_SVOP_PDP, 2)); } void ConfigureEmcPmacroTraining() { /* Disable writes to BYTE0-7. */ reg::Write(EMC + EMC_PMACRO_CFG_PM_GLOBAL_0, EMC_REG_BITS_ENUM(PMACRO_CFG_PM_GLOBAL_0_DISABLE_CFG_BYTE0, ENABLE), EMC_REG_BITS_ENUM(PMACRO_CFG_PM_GLOBAL_0_DISABLE_CFG_BYTE1, ENABLE), EMC_REG_BITS_ENUM(PMACRO_CFG_PM_GLOBAL_0_DISABLE_CFG_BYTE2, ENABLE), EMC_REG_BITS_ENUM(PMACRO_CFG_PM_GLOBAL_0_DISABLE_CFG_BYTE3, ENABLE), EMC_REG_BITS_ENUM(PMACRO_CFG_PM_GLOBAL_0_DISABLE_CFG_BYTE4, ENABLE), EMC_REG_BITS_ENUM(PMACRO_CFG_PM_GLOBAL_0_DISABLE_CFG_BYTE5, ENABLE), EMC_REG_BITS_ENUM(PMACRO_CFG_PM_GLOBAL_0_DISABLE_CFG_BYTE6, ENABLE), EMC_REG_BITS_ENUM(PMACRO_CFG_PM_GLOBAL_0_DISABLE_CFG_BYTE7, ENABLE), EMC_REG_BITS_ENUM(PMACRO_CFG_PM_GLOBAL_0_DISABLE_CFG_CMD0, DISABLE), EMC_REG_BITS_ENUM(PMACRO_CFG_PM_GLOBAL_0_DISABLE_CFG_CMD1, DISABLE), EMC_REG_BITS_ENUM(PMACRO_CFG_PM_GLOBAL_0_DISABLE_CFG_CMD2, DISABLE), EMC_REG_BITS_ENUM(PMACRO_CFG_PM_GLOBAL_0_DISABLE_CFG_CMD3, DISABLE)); /* Set E_WRPTR on Channel 0. */ reg::Write(EMC + EMC_PMACRO_TRAINING_CTRL_0, EMC_REG_BITS_ENUM(PMACRO_TRAINING_CTRL_0_CH0_TRAINING_ENABLED, DISABLED), EMC_REG_BITS_ENUM(PMACRO_TRAINING_CTRL_0_CH0_TRAINING_TRAIN_QPOP, DISABLED), EMC_REG_BITS_ENUM(PMACRO_TRAINING_CTRL_0_CH0_TRAINING_RX_E_DIRECT_ZI, DISABLED), EMC_REG_BITS_ENUM(PMACRO_TRAINING_CTRL_0_CH0_TRAINING_E_WRPTR, ENABLED), EMC_REG_BITS_ENUM(PMACRO_TRAINING_CTRL_0_CH0_TRAINING_DRV_DQS, DISABLED)); /* Set E_WRPTR on Channel 1. */ reg::Write(EMC + EMC_PMACRO_TRAINING_CTRL_1, EMC_REG_BITS_ENUM(PMACRO_TRAINING_CTRL_1_CH1_TRAINING_ENABLED, DISABLED), EMC_REG_BITS_ENUM(PMACRO_TRAINING_CTRL_1_CH1_TRAINING_TRAIN_QPOP, DISABLED), EMC_REG_BITS_ENUM(PMACRO_TRAINING_CTRL_1_CH1_TRAINING_RX_E_DIRECT_ZI, DISABLED), EMC_REG_BITS_ENUM(PMACRO_TRAINING_CTRL_1_CH1_TRAINING_E_WRPTR, ENABLED), EMC_REG_BITS_ENUM(PMACRO_TRAINING_CTRL_1_CH1_TRAINING_DRV_DQS, DISABLED)); /* Re-enable writes to BYTE0-7. */ reg::Write(EMC + EMC_PMACRO_CFG_PM_GLOBAL_0, EMC_REG_BITS_ENUM(PMACRO_CFG_PM_GLOBAL_0_DISABLE_CFG_BYTE0, DISABLE), EMC_REG_BITS_ENUM(PMACRO_CFG_PM_GLOBAL_0_DISABLE_CFG_BYTE1, DISABLE), EMC_REG_BITS_ENUM(PMACRO_CFG_PM_GLOBAL_0_DISABLE_CFG_BYTE2, DISABLE), EMC_REG_BITS_ENUM(PMACRO_CFG_PM_GLOBAL_0_DISABLE_CFG_BYTE3, DISABLE), EMC_REG_BITS_ENUM(PMACRO_CFG_PM_GLOBAL_0_DISABLE_CFG_BYTE4, DISABLE), EMC_REG_BITS_ENUM(PMACRO_CFG_PM_GLOBAL_0_DISABLE_CFG_BYTE5, DISABLE), EMC_REG_BITS_ENUM(PMACRO_CFG_PM_GLOBAL_0_DISABLE_CFG_BYTE6, DISABLE), EMC_REG_BITS_ENUM(PMACRO_CFG_PM_GLOBAL_0_DISABLE_CFG_BYTE7, DISABLE), EMC_REG_BITS_ENUM(PMACRO_CFG_PM_GLOBAL_0_DISABLE_CFG_CMD0, DISABLE), EMC_REG_BITS_ENUM(PMACRO_CFG_PM_GLOBAL_0_DISABLE_CFG_CMD1, DISABLE), EMC_REG_BITS_ENUM(PMACRO_CFG_PM_GLOBAL_0_DISABLE_CFG_CMD2, DISABLE), EMC_REG_BITS_ENUM(PMACRO_CFG_PM_GLOBAL_0_DISABLE_CFG_CMD3, DISABLE)); } }
11,827
C++
.cpp
117
71.418803
149
0.502949
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,380
warmboot_main.cpp
Atmosphere-NX_Atmosphere/exosphere/warmboot/source/warmboot_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 <exosphere.hpp> #include "warmboot_bootrom_workaround.hpp" #include "warmboot_clkrst.hpp" #include "warmboot_cpu_cluster.hpp" #include "warmboot_dram.hpp" #include "warmboot_main.hpp" #include "warmboot_misc.hpp" #include "warmboot_secure_monitor.hpp" namespace ams::warmboot { namespace { constexpr inline const uintptr_t PMC = secmon::MemoryRegionPhysicalDevicePmc.GetAddress(); constexpr inline const uintptr_t FLOW_CTLR = secmon::MemoryRegionPhysicalDeviceFlowController.GetAddress(); constexpr inline const uintptr_t ExpectedMetadataAddress = 0x40010244; } void Main(const Metadata *metadata) { /* Ensure that we're running under vaguely sane conditions. */ AMS_ABORT_UNLESS(metadata->magic == Metadata::Magic); /* Restrict the bpmp's access to dram. */ if (metadata->target_firmware >= TargetFirmware_4_0_0) { RestrictBpmpAccessToMainMemory(); } /* Configure rtck-daisychaining/jtag. */ ConfigureMiscSystemDebug(); /* NOTE: Here, Nintendo checks that the number of burnt anti-downgrade fuses is valid. */ /* NOTE: Here, Nintendo validates that APBDEV_PMC_SECURE_SCRATCH32 contains the correct magic number for the current warmboot firmware revision. */ /* Validate that we're executing at the correct address. */ AMS_ABORT_UNLESS(reinterpret_cast<uintptr_t>(metadata) == ExpectedMetadataAddress); /* Validate that we're executing on the bpmp. */ AMS_ABORT_UNLESS(reg::Read(PG_UP(PG_UP_TAG)) == PG_UP_TAG_PID_COP); /* Configure fuse bypass. */ fuse::ConfigureFuseBypass(); /* Configure system oscillators. */ ConfigureOscillators(); /* Restore DRAM configuration. */ RestoreRamSvop(); ConfigureEmcPmacroTraining(); /* If on Erista, work around the bootrom mbist issue. */ if (fuse::GetSocType() == fuse::SocType_Erista) { ApplyMbistWorkaround(); } /* Initialize the cpu cluster. */ InitializeCpuCluster(); /* Restore the secure monitor to tzram. */ RestoreSecureMonitorToTzram(metadata->target_firmware); /* Power on the cpu. */ PowerOnCpu(); /* Halt ourselves. */ while (true) { reg::Write(secmon::MemoryRegionPhysicalDeviceFlowController.GetAddress() + FLOW_CTLR_HALT_COP_EVENTS, FLOW_REG_BITS_ENUM(HALT_COP_EVENTS_MODE, FLOW_MODE_STOP), FLOW_REG_BITS_ENUM(HALT_COP_EVENTS_JTAG, ENABLED)); } } NORETURN void ExceptionHandler() { /* Write enable to MAIN_RESET. */ reg::Write(PMC + APBDEV_PMC_CNTRL, PMC_REG_BITS_ENUM(CNTRL_MAIN_RESET, ENABLE)); /* Wait forever until we're reset. */ AMS_INFINITE_LOOP(); } } namespace ams::diag { NORETURN void AbortImpl() { warmboot::ExceptionHandler(); } #include <exosphere/diag/diag_detailed_assertion_impl.inc> }
3,747
C++
.cpp
80
39
172
0.663187
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,381
warmboot_bootrom_workaround.cpp
Atmosphere-NX_Atmosphere/exosphere/warmboot/source/warmboot_bootrom_workaround.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 <exosphere.hpp> #include "warmboot_clkrst.hpp" namespace ams::warmboot { namespace { constexpr inline const uintptr_t CLKRST = secmon::MemoryRegionPhysicalDeviceClkRst.GetAddress(); constexpr inline const uintptr_t EMC = EMC_ADDRESS(0); } void ApplyMbistWorkaround() { /* Clear all LVL2 clock gate overrides to zero. */ reg::Write(CLKRST + CLK_RST_CONTROLLER_LVL2_CLK_GATE_OVRA, 0); reg::Write(CLKRST + CLK_RST_CONTROLLER_LVL2_CLK_GATE_OVRB, 0); reg::Write(CLKRST + CLK_RST_CONTROLLER_LVL2_CLK_GATE_OVRC, 0); reg::Write(CLKRST + CLK_RST_CONTROLLER_LVL2_CLK_GATE_OVRD, 0); reg::Write(CLKRST + CLK_RST_CONTROLLER_LVL2_CLK_GATE_OVRE, 0); /* Clear clock enable for all but a select few devices. */ auto devices_to_clear_l = reg::Read(CLKRST + CLK_RST_CONTROLLER_CLK_OUT_ENB_L); reg::ClearBits(static_cast<volatile u32 &>(devices_to_clear_l), CLK_RST_REG_BITS_MASK(CLK_ENB_L_CLK_ENB_RTC ), CLK_RST_REG_BITS_MASK(CLK_ENB_L_CLK_ENB_TMR ), CLK_RST_REG_BITS_MASK(CLK_ENB_L_CLK_ENB_GPIO ), CLK_RST_REG_BITS_MASK(CLK_ENB_L_CLK_ENB_CACHE2)); reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_ENB_L_CLR, devices_to_clear_l); auto devices_to_clear_h = reg::Read(CLKRST + CLK_RST_CONTROLLER_CLK_OUT_ENB_H); reg::ClearBits(static_cast<volatile u32 &>(devices_to_clear_h), CLK_RST_REG_BITS_MASK(CLK_ENB_H_CLK_ENB_MEM ), CLK_RST_REG_BITS_MASK(CLK_ENB_H_CLK_ENB_PMC ), CLK_RST_REG_BITS_MASK(CLK_ENB_H_CLK_ENB_FUSE), CLK_RST_REG_BITS_MASK(CLK_ENB_H_CLK_ENB_EMC )); reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_ENB_H_CLR, devices_to_clear_h); auto devices_to_clear_u = reg::Read(CLKRST + CLK_RST_CONTROLLER_CLK_OUT_ENB_U); reg::ClearBits(static_cast<volatile u32 &>(devices_to_clear_u), CLK_RST_REG_BITS_MASK(CLK_ENB_U_CLK_ENB_CSITE), CLK_RST_REG_BITS_MASK(CLK_ENB_U_CLK_ENB_IRAMA), CLK_RST_REG_BITS_MASK(CLK_ENB_U_CLK_ENB_IRAMB), CLK_RST_REG_BITS_MASK(CLK_ENB_U_CLK_ENB_IRAMC), CLK_RST_REG_BITS_MASK(CLK_ENB_U_CLK_ENB_IRAMD), CLK_RST_REG_BITS_MASK(CLK_ENB_U_CLK_ENB_CRAM2)); reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_ENB_U_CLR, devices_to_clear_u); auto devices_to_clear_v = reg::Read(CLKRST + CLK_RST_CONTROLLER_CLK_OUT_ENB_V); reg::ClearBits(static_cast<volatile u32 &>(devices_to_clear_v), CLK_RST_REG_BITS_MASK(CLK_ENB_V_CLK_ENB_MSELECT ), CLK_RST_REG_BITS_MASK(CLK_ENB_V_CLK_ENB_SPDIF_DOUBLER), CLK_RST_REG_BITS_MASK(CLK_ENB_V_CLK_ENB_TZRAM ), CLK_RST_REG_BITS_MASK(CLK_ENB_V_CLK_ENB_SE )); reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_ENB_V_CLR, devices_to_clear_v); auto devices_to_clear_w = reg::Read(CLKRST + CLK_RST_CONTROLLER_CLK_OUT_ENB_W); reg::ClearBits(static_cast<volatile u32 &>(devices_to_clear_w), CLK_RST_REG_BITS_MASK(CLK_ENB_W_CLK_ENB_PCIERX0), CLK_RST_REG_BITS_MASK(CLK_ENB_W_CLK_ENB_PCIERX1), CLK_RST_REG_BITS_MASK(CLK_ENB_W_CLK_ENB_PCIERX2), CLK_RST_REG_BITS_MASK(CLK_ENB_W_CLK_ENB_PCIERX3), CLK_RST_REG_BITS_MASK(CLK_ENB_W_CLK_ENB_PCIERX4), CLK_RST_REG_BITS_MASK(CLK_ENB_W_CLK_ENB_PCIERX5), CLK_RST_REG_BITS_MASK(CLK_ENB_W_CLK_ENB_ENTROPY)); reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_ENB_W_CLR, devices_to_clear_w); auto devices_to_clear_x = reg::Read(CLKRST + CLK_RST_CONTROLLER_CLK_OUT_ENB_X); reg::ClearBits(static_cast<volatile u32 &>(devices_to_clear_x), CLK_RST_REG_BITS_MASK(CLK_ENB_X_CLK_ENB_MC_CAPA ), CLK_RST_REG_BITS_MASK(CLK_ENB_X_CLK_ENB_MC_CBPA ), CLK_RST_REG_BITS_MASK(CLK_ENB_X_CLK_ENB_MC_CPU ), CLK_RST_REG_BITS_MASK(CLK_ENB_X_CLK_ENB_MC_BBC ), CLK_RST_REG_BITS_MASK(CLK_ENB_X_CLK_ENB_EMC_DLL ), CLK_RST_REG_BITS_MASK(CLK_ENB_X_CLK_ENB_GPU ), CLK_RST_REG_BITS_MASK(CLK_ENB_X_CLK_ENB_DBGAPB ), CLK_RST_REG_BITS_MASK(CLK_ENB_X_CLK_ENB_PLLG_REF)); reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_ENB_X_CLR, devices_to_clear_x); auto devices_to_clear_y = reg::Read(CLKRST + CLK_RST_CONTROLLER_CLK_OUT_ENB_Y); reg::ClearBits(static_cast<volatile u32 &>(devices_to_clear_y), CLK_RST_REG_BITS_MASK(CLK_ENB_Y_CLK_ENB_MC_CCPA), CLK_RST_REG_BITS_MASK(CLK_ENB_Y_CLK_ENB_MC_CDPA)); reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_ENB_Y_CLR, devices_to_clear_y); /* If CH1 is enabled, enable clock to MC1. */ if (reg::HasValue(EMC + EMC_FBIO_CFG7, EMC_REG_BITS_ENUM(FBIO_CFG7_CH1_ENABLE, ENABLE))) { reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_ENB_W_SET, CLK_RST_REG_BITS_ENUM(CLK_ENB_W_CLK_ENB_MC1, ENABLE)); } } }
7,209
C++
.cpp
85
56.329412
128
0.497468
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,382
warmboot_clkrst.cpp
Atmosphere-NX_Atmosphere/exosphere/warmboot/source/warmboot_clkrst.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 <exosphere.hpp> #include "warmboot_clkrst.hpp" namespace ams::warmboot { namespace { constexpr inline const uintptr_t CLKRST = secmon::MemoryRegionPhysicalDeviceClkRst.GetAddress(); constexpr inline const uintptr_t PMC = secmon::MemoryRegionPhysicalDevicePmc.GetAddress(); constexpr inline const uintptr_t TIMER = secmon::MemoryRegionPhysicalDeviceTimer.GetAddress(); } void ConfigureOscillators() { /* Enable the crystal oscillator, and copy the drive strength from pmc. */ const auto xofs = reg::GetValue(PMC + APBDEV_PMC_OSC_EDPD_OVER, PMC_REG_BITS_MASK(OSC_EDPD_OVER_XOFS)); reg::ReadWrite(CLKRST + CLK_RST_CONTROLLER_OSC_CTRL, CLK_RST_REG_BITS_ENUM (OSC_CTRL_XOE, ENABLE), CLK_RST_REG_BITS_VALUE(OSC_CTRL_XOFS, xofs)); /* Configure CLK_M_DIVISOR to 2. */ reg::Write(CLKRST + CLK_RST_CONTROLLER_SPARE_REG0, CLK_RST_REG_BITS_ENUM(SPARE_REG0_CLK_M_DIVISOR, CLK_M_DIVISOR2)); reg::Read(CLKRST + CLK_RST_CONTROLLER_SPARE_REG0); /* Restore TIMERUS config to 19.2 MHz. */ reg::Write(TIMER + TIMERUS_USEC_CFG, TIMER_REG_BITS_VALUE(USEC_CFG_USEC_DIVIDEND, 5 - 1), TIMER_REG_BITS_VALUE(USEC_CFG_USEC_DIVISOR, 96 - 1)); } }
1,995
C++
.cpp
36
47.916667
124
0.678297
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,383
warmboot_misc.cpp
Atmosphere-NX_Atmosphere/exosphere/warmboot/source/warmboot_misc.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 <exosphere.hpp> #include "warmboot_misc.hpp" namespace ams::warmboot { namespace { constexpr inline const uintptr_t APB_MISC = secmon::MemoryRegionPhysicalDeviceApbMisc.GetAddress(); constexpr inline const uintptr_t PMC = secmon::MemoryRegionPhysicalDevicePmc.GetAddress(); constexpr inline const uintptr_t SYSTEM = secmon::MemoryRegionPhysicalDeviceSystem.GetAddress(); } void ConfigureMiscSystemDebug() { /* Enable RTCK daisy-chaining. */ reg::Write(APB_MISC + APB_MISC_PP_CONFIG_CTL, APB_MISC_REG_BITS_ENUM(PP_CONFIG_CTL_TBE, ENABLE)); /* If we're in production mode, perform JTAG configuration. */ /* NOTE: While this is what NVidia's code does, this is almost certainly a logic error. */ /* They intend to configure JTAG only when *not* in production mode. */ /* However, here we will do what they do, and not what they intend. */ const bool production_mode = fuse::IsOdmProductionMode(); if (production_mode) { const bool jtag_sts = reg::HasValue(PMC + APBDEV_PMC_STICKY_BITS, PMC_REG_BITS_ENUM(STICKY_BITS_JTAG_STS, ENABLE)); reg::ReadWrite(SYSTEM + SB_PFCFG, SB_REG_BITS_ENUM_SEL(PFCFG_DBGEN, jtag_sts, ENABLE, DISABLE), SB_REG_BITS_ENUM_SEL(PFCFG_SPNIDEN, jtag_sts, ENABLE, DISABLE), SB_REG_BITS_ENUM (PFCFG_NIDEN, ENABLE), SB_REG_BITS_ENUM (PFCFG_SPIDEN, DISABLE)); reg::ReadWrite(APB_MISC + APB_MISC_PP_CONFIG_CTL, APB_MISC_REG_BITS_ENUM_SEL(PP_CONFIG_CTL_JTAG, jtag_sts, ENABLE, DISABLE)); } /* Configure HDA codec disable. */ reg::ReadWrite(PMC + APBDEV_PMC_STICKY_BITS, PMC_REG_BITS_ENUM_SEL(STICKY_BITS_HDA_LPBK_DIS, production_mode, ENABLE, DISABLE)); /* Set E_INPUT in PINMUX_AUX_GPIO_PA6 (needed by the XUSB and SATA controllers). */ reg::ReadWrite(APB_MISC + PINMUX_AUX_GPIO_PA6, PINMUX_REG_BITS_ENUM(AUX_E_INPUT, ENABLE)); } }
2,738
C++
.cpp
45
52.222222
137
0.665548
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,384
warmboot_secure_monitor.cpp
Atmosphere-NX_Atmosphere/exosphere/warmboot/source/warmboot_secure_monitor.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 <exosphere.hpp> #include "warmboot_secure_monitor.hpp" namespace ams::warmboot { namespace { constexpr inline const uintptr_t PMC = secmon::MemoryRegionPhysicalDevicePmc.GetAddress(); constexpr inline const pkg1::AesKeySlot SavedAesKeySlots[] = { pkg1::AesKeySlot_TzramSaveKek, pkg1::AesKeySlot_RandomForUserWrap, pkg1::AesKeySlot_RandomForKeyStorageWrap, pkg1::AesKeySlot_DeviceMaster, pkg1::AesKeySlot_Master, pkg1::AesKeySlot_Device, }; constexpr ALWAYS_INLINE bool IsSavedAesKeySlot(int slot) { for (const auto SavedSlot : SavedAesKeySlots) { if (slot == SavedSlot) { return true; } } return false; } void ClearUnsavedSecurityEngineKeySlots() { /* Clear unsaved aes keys and all ivs. */ for (int slot = 0; slot < se::AesKeySlotCount; ++slot) { if (!IsSavedAesKeySlot(slot)) { se::ClearAesKeySlot(slot); } se::ClearAesKeyIv(slot); } /* Clear all rsa keys. */ for (int slot = 0; slot < se::RsaKeySlotCount; ++slot) { se::ClearRsaKeySlot(slot); } } void RestoreEncryptedTzram(void * const tzram_dst, const void * const tzram_src, size_t tzram_size) { /* Derive the save key from the save kek. */ const u32 key_source[se::AesBlockSize / sizeof(u32)] = { reg::Read(PMC + APBDEV_PMC_SECURE_SCRATCH24), reg::Read(PMC + APBDEV_PMC_SECURE_SCRATCH25), reg::Read(PMC + APBDEV_PMC_SECURE_SCRATCH26), reg::Read(PMC + APBDEV_PMC_SECURE_SCRATCH27)}; se::ClearAesKeySlot(pkg1::AesKeySlot_TzramSaveKey); se::SetEncryptedAesKey256(pkg1::AesKeySlot_TzramSaveKey, pkg1::AesKeySlot_TzramSaveKek, key_source, sizeof(key_source)); /* Decrypt tzram. */ const u8 tzram_iv[se::AesBlockSize] = {}; se::DecryptAes256Cbc(tzram_dst, tzram_size, pkg1::AesKeySlot_TzramSaveKey, tzram_src, tzram_size, tzram_iv, sizeof(tzram_iv)); /* Calculate the cmac of decrypted tzram. */ u8 tzram_mac[se::AesBlockSize] = {}; se::ComputeAes256Cmac(tzram_mac, sizeof(tzram_mac), pkg1::AesKeySlot_TzramSaveKey, tzram_dst, tzram_size); /* Get the expected mac from pmc scratch. */ const u32 expected_mac[sizeof(tzram_mac) / sizeof(u32)] = { reg::Read(PMC + APBDEV_PMC_SECURE_SCRATCH112), reg::Read(PMC + APBDEV_PMC_SECURE_SCRATCH113), reg::Read(PMC + APBDEV_PMC_SECURE_SCRATCH114), reg::Read(PMC + APBDEV_PMC_SECURE_SCRATCH115)}; /* Validate that the calculated mac is correct. */ AMS_ABORT_UNLESS(crypto::IsSameBytes(tzram_mac, expected_mac, sizeof(tzram_mac))); } void RestoreSecureMonitorToTzramErista(const TargetFirmware target_fw) { /* Clear all unsaved security engine keyslots. */ ClearUnsavedSecurityEngineKeySlots(); /* Restore encrypted tzram contents. */ void * const tzram_src = secmon::MemoryRegionPhysicalDramSecureDataStoreTzram.GetPointer<void>(); void * const tzram_dst = secmon::MemoryRegionPhysicalTzramNonVolatile.GetPointer<void>(); const size_t tzram_size = secmon::MemoryRegionPhysicalTzramNonVolatile.GetSize(); RestoreEncryptedTzram(tzram_dst, tzram_src, tzram_size); /* Clear the tzram kek registers. */ reg::Write(PMC + APBDEV_PMC_SECURE_SCRATCH24, 0); reg::Write(PMC + APBDEV_PMC_SECURE_SCRATCH25, 0); reg::Write(PMC + APBDEV_PMC_SECURE_SCRATCH26, 0); reg::Write(PMC + APBDEV_PMC_SECURE_SCRATCH27, 0); /* Clear the tzram cmac registers. */ reg::Write(PMC + APBDEV_PMC_SECURE_SCRATCH112, 0); reg::Write(PMC + APBDEV_PMC_SECURE_SCRATCH113, 0); reg::Write(PMC + APBDEV_PMC_SECURE_SCRATCH114, 0); reg::Write(PMC + APBDEV_PMC_SECURE_SCRATCH115, 0); /* Clear the keydata used to protect tzram. */ se::ClearAesKeySlot(pkg1::AesKeySlot_TzramSaveKek); se::ClearAesKeySlot(pkg1::AesKeySlot_TzramSaveKey); /* Clear the encrypted copy of tzram in dram. */ /* NOTE: This does not actually clear the encrypted copy, because BPMP access to main memory has been restricted. */ /* Nintendo seems to not realize this, though, so we'll do the same. */ std::memset(tzram_src, 0, tzram_size); /* Set Tzram to secure-world only. */ se::SetTzramSecure(); } } void RestoreSecureMonitorToTzram(const TargetFirmware target_fw) { /* If erista, perform restoration procedure. */ if (fuse::GetSocType() == fuse::SocType_Erista) { RestoreSecureMonitorToTzramErista(target_fw); } /* Lock secure scratch. */ pmc::LockSecureRegister(static_cast<pmc::SecureRegister>(pmc::SecureRegister_DramParameters | pmc::SecureRegister_Other)); /* Lockout fuses. */ fuse::Lockout(); } }
5,875
C++
.cpp
105
45.361905
260
0.636205
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,385
stratosphere.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere.hpp
/* * 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/>. */ #pragma once /* Ensure that on windows we use lean-windows headers. */ #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif /* libvapours (pulls in util, svc, results). */ #include <vapours.hpp> /* Libstratosphere diagnostics. */ #include <stratosphere/diag.hpp> /* Libstratosphere definitions. */ #include <stratosphere/ams/impl/ams_system_thread_definitions.hpp> /* Libstratosphere-only utility. */ #include <stratosphere/util.hpp> /* Sadly required shims. */ #include <stratosphere/svc/svc_stratosphere_shims.hpp> /* Critical modules with no dependencies. */ #include <stratosphere/ams.hpp> #include <stratosphere/os.hpp> #include <stratosphere/dd.hpp> #include <stratosphere/lmem.hpp> #include <stratosphere/mem.hpp> /* Pull in all ID definitions from NCM. */ #include <stratosphere/ncm/ncm_ids.hpp> /* At this point, just include the rest alphabetically. */ /* TODO: Figure out optimal order. */ #include <stratosphere/boot2.hpp> #include <stratosphere/cal.hpp> #include <stratosphere/capsrv.hpp> #include <stratosphere/cfg.hpp> #include <stratosphere/clkrst.hpp> #include <stratosphere/cs.hpp> #include <stratosphere/ddsf.hpp> #include <stratosphere/dmnt.hpp> #include <stratosphere/erpt.hpp> #include <stratosphere/err.hpp> #include <stratosphere/fatal.hpp> #include <stratosphere/gc.hpp> #include <stratosphere/gpio.hpp> #include <stratosphere/hid.hpp> #include <stratosphere/hos.hpp> #include <stratosphere/htc.hpp> #include <stratosphere/htcfs.hpp> #include <stratosphere/htclow.hpp> #include <stratosphere/htcs.hpp> #include <stratosphere/i2c.hpp> #include <stratosphere/init.hpp> #include <stratosphere/kvdb.hpp> #include <stratosphere/ldr.hpp> #include <stratosphere/lr.hpp> #include <stratosphere/lm.hpp> #include <stratosphere/mitm.hpp> #include <stratosphere/ncm.hpp> #include <stratosphere/nim.hpp> #include <stratosphere/ns.hpp> #include <stratosphere/nsd.hpp> #include <stratosphere/osdbg.hpp> #include <stratosphere/patcher.hpp> #include <stratosphere/pcv.hpp> #include <stratosphere/pgl.hpp> #include <stratosphere/pinmux.hpp> #include <stratosphere/powctl.hpp> #include <stratosphere/psc.hpp> #include <stratosphere/pm.hpp> #include <stratosphere/pwm.hpp> #include <stratosphere/regulator.hpp> #include <stratosphere/ro.hpp> #include <stratosphere/settings.hpp> #include <stratosphere/scs.hpp> #include <stratosphere/sf.hpp> #include <stratosphere/sm.hpp> #include <stratosphere/socket.hpp> #include <stratosphere/spl.hpp> #include <stratosphere/sprofile.hpp> #include <stratosphere/time.hpp> #include <stratosphere/tipc.hpp> #include <stratosphere/tma.hpp> #include <stratosphere/updater.hpp> #include <stratosphere/usb.hpp> #include <stratosphere/wec.hpp> /* Include FS last. */ #include <stratosphere/fs.hpp> #include <stratosphere/fssrv.hpp> #include <stratosphere/fssystem.hpp> /* External modules that we're including. */ #include <stratosphere/rapidjson.hpp>
3,544
C++
.h
100
34.19
76
0.789106
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,386
scs.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/scs.hpp
/* * 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/>. */ #pragma once #include <stratosphere/scs/scs_command_processor.hpp> #include <stratosphere/scs/scs_shell_server.hpp> #include <stratosphere/scs/scs_shell.hpp> #include <stratosphere/scs/scs_tenv.hpp> #include <stratosphere/scs/scs_server_manager.hpp>
888
C++
.h
21
40.47619
76
0.773148
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,387
updater.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/updater.hpp
/* * 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/>. */ #pragma once #include <stratosphere/updater/updater_types.hpp> #include <stratosphere/updater/updater_api.hpp>
748
C++
.h
18
39.666667
76
0.767857
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,388
i2c.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/i2c.hpp
/* * 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/>. */ #pragma once #include <stratosphere/i2c/i2c_types.hpp> #include <stratosphere/i2c/i2c_select_device_name.hpp> #include <stratosphere/i2c/i2c_command_list_formatter.hpp> #include <stratosphere/i2c/sf/i2c_sf_i_session.hpp> #include <stratosphere/i2c/sf/i2c_sf_i_manager.hpp> #include <stratosphere/i2c/server/i2c_server_api.hpp> #include <stratosphere/i2c/driver/i2c_select_driver_api.hpp> #include <stratosphere/i2c/driver/i2c_driver_service_api.hpp> #include <stratosphere/i2c/driver/i2c_driver_client_api.hpp> #include <stratosphere/i2c/driver/i2c_bus_api.hpp> #include <stratosphere/i2c/driver/impl/i2c_i2c_session_impl.hpp> #include <stratosphere/i2c/i2c_api.hpp> #include <stratosphere/i2c/i2c_bus_api.hpp> #include <stratosphere/i2c/i2c_register_accessor.hpp>
1,401
C++
.h
30
45.2
76
0.785401
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,389
osdbg.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/osdbg.hpp
/* * 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/>. */ #pragma once #include <stratosphere/osdbg/osdbg_thread.hpp>
697
C++
.h
17
39.058824
76
0.762537
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,390
nsd.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/nsd.hpp
/* * 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/>. */ #pragma once #include <stratosphere/nsd/nsd_types.hpp> #include <stratosphere/nsd/impl/device/nsd_device.hpp>
745
C++
.h
18
39.611111
76
0.764787
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,391
ldr.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/ldr.hpp
/* * 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/>. */ #pragma once #include <stratosphere/ldr/ldr_types.hpp> #include <stratosphere/ldr/ldr_shell_api.hpp> #include <stratosphere/ldr/ldr_pm_api.hpp> #include <stratosphere/ldr/impl/ldr_process_manager_interface.hpp> #include <stratosphere/ldr/impl/ldr_debug_monitor_interface.hpp> #include <stratosphere/ldr/impl/ldr_shell_interface.hpp>
969
C++
.h
22
42.363636
76
0.776956
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,392
ncm.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/ncm.hpp
/* * 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/>. */ #pragma once #include <stratosphere/ncm/ncm_ids.hpp> #include <stratosphere/ncm/ncm_max_count.hpp> #include <stratosphere/ncm/ncm_program_location.hpp> #include <stratosphere/ncm/ncm_auto_buffer.hpp> #include <stratosphere/ncm/ncm_make_path.hpp> #include <stratosphere/ncm/ncm_content_id_utils.hpp> #include <stratosphere/ncm/ncm_content_info_utils.hpp> #include <stratosphere/ncm/ncm_content_meta.hpp> #include <stratosphere/ncm/ncm_content_meta_extended_data.hpp> #include <stratosphere/ncm/ncm_content_meta_database.hpp> #include <stratosphere/ncm/ncm_content_storage.hpp> #include <stratosphere/ncm/ncm_content_manager_impl.hpp> #include <stratosphere/ncm/ncm_content_meta_utils.hpp> #include <stratosphere/ncm/ncm_firmware_variation.hpp> #include <stratosphere/ncm/ncm_install_task_base.hpp> #include <stratosphere/ncm/ncm_install_task_data.hpp> #include <stratosphere/ncm/ncm_install_task_occupied_size.hpp> #include <stratosphere/ncm/ncm_memory_report.hpp> #include <stratosphere/ncm/ncm_package_install_task_base.hpp> #include <stratosphere/ncm/ncm_package_install_task.hpp> #include <stratosphere/ncm/ncm_package_system_downgrade_task.hpp> #include <stratosphere/ncm/ncm_package_system_update_task.hpp> #include <stratosphere/ncm/ncm_registered_host_content.hpp> #include <stratosphere/ncm/ncm_submission_package_install_task.hpp> #include <stratosphere/ncm/ncm_storage_utils.hpp> #include <stratosphere/ncm/ncm_api.hpp>
2,067
C++
.h
42
47.833333
76
0.799308
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,393
init.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/init.hpp
/* * 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/>. */ #pragma once #include <stratosphere/init/init_malloc.hpp>
694
C++
.h
17
38.941176
76
0.761834
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,394
htclow.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/htclow.hpp
/* * 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/>. */ #pragma once #include <stratosphere/htclow/htclow_types.hpp> #include <stratosphere/htclow/impl/htclow_internal_types.hpp> #include <stratosphere/htclow/htclow_manager_holder.hpp>
815
C++
.h
19
41.157895
76
0.773869
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,395
os.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/os.hpp
/* * 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/>. */ #pragma once #include <stratosphere/os/os_common_types.hpp> #include <stratosphere/os/os_tick.hpp> #include <stratosphere/os/os_memory_common.hpp> #include <stratosphere/os/os_memory_fence.hpp> #include <stratosphere/os/os_memory_permission.hpp> #include <stratosphere/os/os_memory_attribute.hpp> #include <stratosphere/os/os_memory_heap.hpp> #include <stratosphere/os/os_virtual_address_memory.hpp> #include <stratosphere/os/os_native_handle.hpp> #include <stratosphere/os/os_process_handle_api.hpp> #include <stratosphere/os/os_process_memory_api.hpp> #include <stratosphere/os/os_process_code_memory_api.hpp> #include <stratosphere/os/os_insecure_memory_api.hpp> #include <stratosphere/os/os_unsafe_memory_api.hpp> #include <stratosphere/os/os_random.hpp> #include <stratosphere/os/os_mutex.hpp> #include <stratosphere/os/os_condition_variable.hpp> #include <stratosphere/os/os_sdk_mutex.hpp> #include <stratosphere/os/os_sdk_recursive_mutex.hpp> #include <stratosphere/os/os_sdk_condition_variable.hpp> #include <stratosphere/os/os_busy_mutex.hpp> #include <stratosphere/os/os_rw_busy_mutex.hpp> #include <stratosphere/os/os_rw_lock.hpp> #include <stratosphere/os/os_shared_memory.hpp> #include <stratosphere/os/os_transfer_memory.hpp> #include <stratosphere/os/os_semaphore.hpp> #include <stratosphere/os/os_event.hpp> #include <stratosphere/os/os_system_event.hpp> #include <stratosphere/os/os_interrupt_event.hpp> #include <stratosphere/os/os_timer_event.hpp> #include <stratosphere/os/os_thread_local_storage.hpp> #include <stratosphere/os/os_sdk_thread_local_storage.hpp> #include <stratosphere/os/os_sdk_reply_and_receive.hpp> #include <stratosphere/os/os_thread.hpp> #include <stratosphere/os/os_sdk_thread_api.hpp> #include <stratosphere/os/os_sdk_thread_info.hpp> #include <stratosphere/os/os_message_queue.hpp> #include <stratosphere/os/os_light_event.hpp> #include <stratosphere/os/os_light_message_queue.hpp> #include <stratosphere/os/os_light_semaphore.hpp> #include <stratosphere/os/os_barrier.hpp> #include <stratosphere/os/os_io_region.hpp> #include <stratosphere/os/os_multiple_wait.hpp> #include <stratosphere/os/os_argument.hpp> #include <stratosphere/os/os_cache.hpp> #include <stratosphere/os/os_debug.hpp>
2,869
C++
.h
62
45.016129
76
0.795009
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,396
wec.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/wec.hpp
/* * 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/>. */ #pragma once #include <stratosphere/wec/wec_types.hpp> #include <stratosphere/wec/wec_api.hpp>
731
C++
.h
18
38.777778
76
0.76264
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,397
nim.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/nim.hpp
/* * 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/>. */ #pragma once #include <stratosphere/nim/nim_network_install_manager_api.hpp>
714
C++
.h
17
40.058824
76
0.764029
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,398
cs.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/cs.hpp
/* * 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/>. */ #pragma once #include <stratosphere/cs/cs_audio_server.hpp> #include <stratosphere/cs/cs_hid_server.hpp> #include <stratosphere/cs/cs_remote_video_server.hpp> #include <stratosphere/cs/cs_target_io_server.hpp> #include <stratosphere/cs/cs_command_processor.hpp>
899
C++
.h
21
41.047619
76
0.771689
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,399
pm.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/pm.hpp
/* * 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/>. */ #pragma once #include <stratosphere/pm/pm_types.hpp> #include <stratosphere/pm/pm_boot_mode_api.hpp> #include <stratosphere/pm/pm_info_api.hpp> #include <stratosphere/pm/pm_shell_api.hpp> #include <stratosphere/pm/pm_dmnt_api.hpp> #include <stratosphere/pm/impl/pm_boot_mode_interface.hpp> #include <stratosphere/pm/impl/pm_debug_monitor_interface.hpp> #include <stratosphere/pm/impl/pm_information_interface.hpp> #include <stratosphere/pm/impl/pm_shell_interface.hpp>
1,106
C++
.h
25
42.6
76
0.777572
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,400
ns.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/ns.hpp
/* * 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/>. */ #pragma once #include <stratosphere/ns/impl/ns_i_async.hpp>
697
C++
.h
17
39.058824
76
0.759587
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,401
cal.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/cal.hpp
/* * 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/>. */ #pragma once #include <stratosphere/cal/cal_battery_api.hpp>
698
C++
.h
17
39.117647
76
0.761414
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,402
windows.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/windows.hpp
/* * 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/>. */ #pragma once #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #ifndef NOMINMAX #define NOMINMAX #endif #include <Windows.h> /* Collides with StandardUserSystemClock. */ #ifdef GetCurrentTime ALWAYS_INLINE auto WindowsGetCurrentTime() { return GetCurrentTime(); } #undef GetCurrentTime #endif /* Collides with several things. */ #ifdef FillMemory ALWAYS_INLINE auto WindowsFillMemory(PVOID p, SIZE_T l, BYTE v) { return FillMemory(p, l, v); } #undef FillMemory /* Should be provided by winerror.h, but isn't. */ #if !defined(ERROR_SPACES_NOT_ENOUGH_DRIVES) #define ERROR_SPACES_NOT_ENOUGH_DRIVES ((DWORD)0x80E7000Bu) #endif #endif
1,300
C++
.h
41
29.853659
76
0.772071
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,403
pgl.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/pgl.hpp
/* * 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/>. */ #pragma once #include <stratosphere/pgl/pgl_types.hpp> #include <stratosphere/pgl/pgl_event_observer.hpp> #include <stratosphere/pgl/pgl_shell_api.hpp> #include <stratosphere/pgl/pgl_shell_api.hpp> #include <stratosphere/pgl/srv/pgl_srv_api.hpp>
883
C++
.h
21
40.285714
76
0.769767
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,404
ro.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/ro.hpp
/* * 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/>. */ #pragma once #include <stratosphere/ro/ro_types.hpp> #include <stratosphere/ro/impl/ro_ro_interface.hpp> #include <stratosphere/ro/impl/ro_debug_monitor_interface.hpp> #include <stratosphere/ro/impl/ro_ro_exception_info.hpp> #include <stratosphere/rocrt/rocrt.hpp>
903
C++
.h
21
41.190476
76
0.772469
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,405
lm.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/lm.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/lm/lm_types.hpp> #include <stratosphere/lm/lm_api.hpp> #include <stratosphere/lm/lm_log_getter.hpp>
795
C++
.h
20
38
76
0.763566
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,406
capsrv.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/capsrv.hpp
/* * 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/>. */ #pragma once #include <stratosphere/capsrv/capsrv_screen_shot_decode_option.hpp> #include <stratosphere/capsrv/server/capsrv_server_config.hpp> #include <stratosphere/capsrv/server/capsrv_server_decoder_api.hpp> #include <stratosphere/capsrv/capsrv_screen_shot_control_api.hpp>
915
C++
.h
20
43.95
76
0.780515
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,407
lr.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/lr.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/lr/lr_types.hpp> #include <stratosphere/lr/lr_api.hpp> #include <stratosphere/lr/lr_location_resolver_manager_impl.hpp>
815
C++
.h
20
39
76
0.767003
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,408
usb.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/usb.hpp
/* * 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/>. */ #pragma once #include <stratosphere/usb/usb_limits.hpp> #include <stratosphere/usb/usb_types.hpp> #include <stratosphere/usb/usb_device_types.hpp> #include <stratosphere/usb/usb_device.hpp>
826
C++
.h
20
39.55
76
0.768944
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,409
fat.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fat.hpp
/* * 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/>. */ #pragma once #include <stratosphere/fat/fat_file_system.hpp>
695
C++
.h
17
39.117647
76
0.761414
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,410
tipc.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/tipc.hpp
/* * 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/>. */ #pragma once #include <stratosphere/tipc/tipc_service_object.hpp> #include <stratosphere/tipc/tipc_allocators.hpp> #include <stratosphere/tipc/impl/tipc_impl_command_serialization.hpp> #include <stratosphere/tipc/impl/tipc_autogen_interface_macros.hpp> #include <stratosphere/tipc/tipc_object_manager.hpp> #include <stratosphere/tipc/tipc_server_manager.hpp>
997
C++
.h
22
43.545455
76
0.783951
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,411
fssystem.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssystem.hpp
/* * 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/>. */ #pragma once #include <stratosphere/fssystem/fssystem_allocator_utility.hpp> #include <stratosphere/fssystem/fssystem_utility.hpp> #include <stratosphere/fssystem/fssystem_bitmap_utils.hpp> #include <stratosphere/fssystem/fssystem_speed_emulation_configuration.hpp> #include <stratosphere/fssystem/fssystem_external_code.hpp> #include <stratosphere/fssystem/fssystem_forwarding_file_system.hpp> #include <stratosphere/fssystem/fssystem_partition_file_system.hpp> #include <stratosphere/fssystem/fssystem_partition_file_system_meta.hpp> #include <stratosphere/fssystem/fssystem_thread_priority_changer.hpp> #include <stratosphere/fssystem/fssystem_aes_ctr_storage.hpp> #include <stratosphere/fssystem/fssystem_aes_xts_storage.hpp> #include <stratosphere/fssystem/fssystem_subdirectory_filesystem.hpp> #include <stratosphere/fssystem/fssystem_directory_redirection_filesystem.hpp> #include <stratosphere/fssystem/fssystem_directory_savedata_filesystem.hpp> #include <stratosphere/fssystem/fssystem_romfs_file_system.hpp> #include <stratosphere/fssystem/fssystem_bucket_tree.hpp> #include <stratosphere/fssystem/fssystem_bucket_tree_template_impl.hpp> #include <stratosphere/fssystem/fssystem_indirect_storage.hpp> #include <stratosphere/fssystem/fssystem_indirect_storage_template_impl.hpp> #include <stratosphere/fssystem/fssystem_sparse_storage.hpp> #include <stratosphere/fssystem/fssystem_nca_header.hpp> #include <stratosphere/fssystem/fssystem_nca_file_system_driver.hpp> #include <stratosphere/fssystem/fssystem_crypto_configuration.hpp> #include <stratosphere/fssystem/fssystem_compression_configuration.hpp> #include <stratosphere/fssystem/fssystem_aes_ctr_counter_extended_storage.hpp> #include <stratosphere/fssystem/fssystem_aes_ctr_storage_external.hpp> #include <stratosphere/fssystem/fssystem_aes_xts_storage_external.hpp> #include <stratosphere/fssystem/fssystem_switch_storage.hpp> #include <stratosphere/fssystem/buffers/fssystem_buffer_manager_utils.hpp> #include <stratosphere/fssystem/buffers/fssystem_file_system_buffer_manager.hpp> #include <stratosphere/fssystem/fssystem_pooled_buffer.hpp> #include <stratosphere/fssystem/fssystem_service_context.hpp> #include <stratosphere/fssystem/fssystem_alignment_matching_storage_impl.hpp> #include <stratosphere/fssystem/fssystem_alignment_matching_storage.hpp> #include <stratosphere/fssystem/fssystem_compressed_storage.hpp> #include <stratosphere/fssystem/fssystem_buffered_storage.hpp> #include <stratosphere/fssystem/fssystem_hierarchical_integrity_verification_storage.hpp> #include <stratosphere/fssystem/fssystem_integrity_romfs_storage.hpp> #include <stratosphere/fssystem/fssystem_sha_hash_generator.hpp> #include <stratosphere/fssystem/fssystem_local_file_system.hpp> #include <stratosphere/fssystem/fssystem_file_system_proxy_api.hpp>
3,446
C++
.h
57
59.210526
89
0.83476
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,412
hid.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/hid.hpp
/* * 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/>. */ #pragma once #include <stratosphere/hid/hid_api.hpp>
689
C++
.h
17
38.647059
76
0.76006
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,413
kvdb.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/kvdb.hpp
/* * 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/>. */ #pragma once #include <stratosphere/kvdb/kvdb_auto_buffer.hpp> #include <stratosphere/kvdb/kvdb_bounded_string.hpp> #include <stratosphere/kvdb/kvdb_archive.hpp> #include <stratosphere/kvdb/kvdb_memory_key_value_store.hpp> #include <stratosphere/kvdb/kvdb_file_key_value_store.hpp> #include <stratosphere/kvdb/kvdb_file_key_value_cache.hpp>
978
C++
.h
22
42.727273
76
0.777778
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,414
dmnt.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/dmnt.hpp
/* * 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/>. */ #pragma once #include <stratosphere/dmnt/dmnt_cheat_types.hpp>
700
C++
.h
17
39.235294
76
0.762115
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,415
patcher.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/patcher.hpp
/* * 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/>. */ #pragma once #include <stratosphere/patcher/patcher_api.hpp>
698
C++
.h
17
39.117647
76
0.762887
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,416
pcv.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/pcv.hpp
/* * 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/>. */ #pragma once #include <stratosphere/pcv/pcv_types.hpp> #include <stratosphere/pcv/pcv_api.hpp>
732
C++
.h
18
38.777778
76
0.76264
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,417
mem.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/mem.hpp
/* * 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/>. */ #pragma once #include <stratosphere/mem/mem_standard_allocator.hpp> #include <stratosphere/mem/impl/mem_impl_heap.hpp>
756
C++
.h
18
40.111111
76
0.766304
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,418
erpt.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/erpt.hpp
/* * 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/>. */ #pragma once #include <stratosphere/erpt/erpt_ids.autogen.hpp> #include <stratosphere/erpt/erpt_types.hpp> #include <stratosphere/erpt/erpt_multiple_category_context.hpp> #include <stratosphere/erpt/sf/erpt_sf_i_context.hpp> #include <stratosphere/erpt/sf/erpt_sf_i_session.hpp> #include <stratosphere/erpt/srv/erpt_srv_types.hpp> #include <stratosphere/erpt/srv/erpt_srv_api.hpp>
1,018
C++
.h
23
42.565217
76
0.776435
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,419
spl.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/spl.hpp
/* * 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/>. */ #pragma once #include <stratosphere/spl/spl_types.hpp> #include <stratosphere/spl/spl_api.hpp> #include <stratosphere/spl/smc/spl_secure_monitor_api.hpp> #include <stratosphere/spl/impl/spl_api_impl.hpp> #include <stratosphere/spl/impl/spl_random_interface.hpp> #include <stratosphere/spl/impl/spl_deprecated_general_interface.hpp> #include <stratosphere/spl/impl/spl_general_interface.hpp> #include <stratosphere/spl/impl/spl_crypto_interface.hpp> #include <stratosphere/spl/impl/spl_device_unique_data_interface.hpp> #include <stratosphere/spl/impl/spl_ssl_interface.hpp> #include <stratosphere/spl/impl/spl_es_interface.hpp> #include <stratosphere/spl/impl/spl_manu_interface.hpp> #include <stratosphere/spl/impl/spl_fs_interface.hpp>
1,375
C++
.h
29
45.862069
76
0.789435
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,420
fatal.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fatal.hpp
/* * 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/>. */ #pragma once #include <stratosphere/fatal/fatal_types.hpp> #include <stratosphere/fatal/impl/fatal_i_service.hpp> #include <stratosphere/fatal/impl/fatal_i_private_service.hpp>
815
C++
.h
19
41
76
0.770492
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,421
clkrst.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/clkrst.hpp
/* * 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/>. */ #pragma once #include <stratosphere/clkrst/clkrst_types.hpp> #include <stratosphere/clkrst/clkrst_api.hpp> #include <stratosphere/clkrst/clkrst_session_api.hpp>
798
C++
.h
19
40.157895
76
0.770914
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,422
lmem.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/lmem.hpp
/* * 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/>. */ #pragma once #include <stratosphere/lmem/lmem_common.hpp> #include <stratosphere/lmem/lmem_exp_heap.hpp> #include <stratosphere/lmem/lmem_unit_heap.hpp>
789
C++
.h
19
39.736842
76
0.76723
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,423
cfg.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/cfg.hpp
/* * 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/>. */ #pragma once #include <stratosphere/cfg/cfg_api.hpp>
690
C++
.h
17
38.647059
76
0.76006
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,424
mitm.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/mitm.hpp
/* * 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/>. */ #pragma once #include <stratosphere/mitm/impl/mitm_pm_interface.hpp> #include <stratosphere/mitm/mitm_pm_api.hpp>
751
C++
.h
18
39.833333
76
0.764706
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,425
pwm.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/pwm.hpp
/* * 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/>. */ #pragma once #include <stratosphere/pwm/pwm_types.hpp> #include <stratosphere/pwm/pwm_select_channel_name.hpp> #include <stratosphere/pwm/sf/pwm_sf_i_channel_session.hpp> #include <stratosphere/pwm/sf/pwm_sf_i_manager.hpp> #include <stratosphere/pwm/server/pwm_server_api.hpp> #include <stratosphere/pwm/driver/pwm_select_driver_api.hpp> #include <stratosphere/pwm/driver/pwm_driver_service_api.hpp> #include <stratosphere/pwm/driver/pwm_driver_client_api.hpp> #include <stratosphere/pwm/driver/pwm_channel_api.hpp> #include <stratosphere/pwm/pwm_api.hpp> #include <stratosphere/pwm/pwm_channel_api.hpp>
1,239
C++
.h
27
44.37037
76
0.782178
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,426
pinmux.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/pinmux.hpp
/* * 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/>. */ #pragma once #include <stratosphere/pinmux/pinmux_api.hpp> #include <stratosphere/pinmux/driver/pinmux_driver_api.hpp>
756
C++
.h
18
40.111111
76
0.767663
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,427
ddsf.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/ddsf.hpp
/* * 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/>. */ #pragma once #include <stratosphere/ddsf/ddsf_types.hpp> #include <stratosphere/ddsf/ddsf_i_castable.hpp> #include <stratosphere/ddsf/ddsf_i_session.hpp> #include <stratosphere/ddsf/ddsf_i_device.hpp> #include <stratosphere/ddsf/ddsf_i_driver.hpp> #include <stratosphere/ddsf/ddsf_device_code_entry.hpp> #include <stratosphere/ddsf/ddsf_device_code_entry_manager.hpp> #include <stratosphere/ddsf/ddsf_i_event_handler.hpp> #include <stratosphere/ddsf/ddsf_event_handler_manager.hpp> #include <stratosphere/ddsf/ddsf_memory_api.hpp>
1,167
C++
.h
26
43.307692
76
0.783333
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,428
ams.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/ams.hpp
/* * 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/>. */ #pragma once #include <stratosphere/ams/ams_types.hpp> #include <stratosphere/ams/ams_exosphere_api.hpp> #include <stratosphere/ams/ams_emummc_api.hpp> #include <stratosphere/ams/ams_environment.hpp>
837
C++
.h
20
40.05
76
0.770552
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,429
sf.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/sf.hpp
/* * 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/>. */ #pragma once #include <stratosphere/sf/sf_common.hpp> #include <stratosphere/sf/sf_allocation_policies.hpp> #include <stratosphere/sf/sf_lmem_utility.hpp> #include <stratosphere/sf/sf_mem_utility.hpp> #include <stratosphere/sf/sf_exp_heap_allocator.hpp> #include <stratosphere/sf/sf_standard_allocation_policy.hpp> #include <stratosphere/sf/sf_std_allocation_policy.hpp> #include <stratosphere/sf/sf_shared_object.hpp> #include <stratosphere/sf/sf_service_object.hpp> #include <stratosphere/sf/hipc/sf_hipc_server_session_manager.hpp> #include <stratosphere/sf/cmif/sf_cmif_inline_context.hpp> #include <stratosphere/sf/sf_fs_inline_context.hpp> #include <stratosphere/sf/sf_out.hpp> #include <stratosphere/sf/sf_native_handle.hpp> #include <stratosphere/sf/sf_buffers.hpp> #include <stratosphere/sf/impl/sf_impl_command_serialization.hpp> #include <stratosphere/sf/impl/sf_impl_autogen_interface_macros.hpp> #include <stratosphere/sf/impl/sf_impl_autogen_impl_macros.hpp> #include <stratosphere/sf/impl/sf_impl_template_base.hpp> #include <stratosphere/sf/sf_object_factory.hpp> #include <stratosphere/sf/hipc/sf_hipc_server_manager.hpp> #include <stratosphere/sf/sf_mitm_dispatch.h>
1,826
C++
.h
38
46.526316
76
0.792929
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,430
tma.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/tma.hpp
/* * 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/>. */ #pragma once #include <stratosphere/tma/tma_i_htc_manager.hpp> #include <stratosphere/tma/tma_i_htcs_manager.hpp> #include <stratosphere/tma/tma_i_file_manager.hpp>
801
C++
.h
19
40.368421
76
0.765685
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,431
boot2.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/boot2.hpp
/* * 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/>. */ #pragma once #include <stratosphere/boot2/boot2_api.hpp>
694
C++
.h
17
38.882353
76
0.761481
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,432
gc.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/gc.hpp
/* * 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/>. */ #pragma once #include <stratosphere/gc/impl/gc_types.hpp> #include <stratosphere/gc/impl/gc_gc_crypto.hpp> #include <stratosphere/gc/impl/gc_embedded_data_holder.hpp> #include <stratosphere/gc/gc.hpp>
837
C++
.h
20
40.1
76
0.767157
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