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,224
|
sysupdater_service.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/sysupdater/sysupdater_service.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "sysupdater_service.hpp"
#include "sysupdater_async_impl.hpp"
#include "sysupdater_fs_utils.hpp"
namespace ams::mitm::sysupdater {
namespace {
/* ExFat NCAs prior to 2.0.0 do not actually include the exfat driver, and don't boot. */
constexpr inline u32 MinimumVersionForExFatDriver = 65536;
bool IsExFatDriverSupported(const ncm::ContentMetaInfo &info) {
return info.version >= MinimumVersionForExFatDriver && ((info.attributes & ncm::ContentMetaAttribute_IncludesExFatDriver) != 0);
}
template<typename F>
Result ForEachFileInDirectory(const char *root_path, F f) {
/* Open the directory. */
fs::DirectoryHandle dir;
R_TRY(fs::OpenDirectory(std::addressof(dir), root_path, fs::OpenDirectoryMode_File));
ON_SCOPE_EXIT { fs::CloseDirectory(dir); };
while (true) {
/* Read the current entry. */
s64 count;
fs::DirectoryEntry entry;
R_TRY(fs::ReadDirectory(std::addressof(count), std::addressof(entry), dir, 1));
if (count == 0) {
break;
}
/* Invoke our handler on the entry. */
bool done;
R_TRY(f(std::addressof(done), entry));
R_SUCCEED_IF(done);
}
R_SUCCEED();
}
Result ConvertToFsCommonPath(char *dst, size_t dst_size, const char *package_root_path, const char *entry_path) {
char package_path[ams::fs::EntryNameLengthMax];
const size_t path_len = util::SNPrintf(package_path, sizeof(package_path), "%s%s", package_root_path, entry_path);
AMS_ABORT_UNLESS(path_len < ams::fs::EntryNameLengthMax);
R_RETURN(ams::fs::ConvertToFsCommonPath(dst, dst_size, package_path));
}
Result LoadContentMeta(ncm::AutoBuffer *out, const char *package_root_path, const fs::DirectoryEntry &entry) {
AMS_ABORT_UNLESS(PathView(entry.name).HasSuffix(".cnmt.nca"));
char path[ams::fs::EntryNameLengthMax];
R_TRY(ConvertToFsCommonPath(path, sizeof(path), package_root_path, entry.name));
R_RETURN(ncm::TryReadContentMetaPath(out, path, ncm::ReadContentMetaPathAlongWithExtendedDataAndDigest));
}
Result ReadContentMetaPath(ncm::AutoBuffer *out, const char *package_root, const ncm::ContentInfo &content_info) {
/* Get the .cnmt.nca path for the info. */
char cnmt_nca_name[ncm::ContentIdStringLength + 10];
ncm::GetStringFromContentId(cnmt_nca_name, sizeof(cnmt_nca_name), content_info.GetId());
std::memcpy(cnmt_nca_name + ncm::ContentIdStringLength, ".cnmt.nca", std::strlen(".cnmt.nca"));
cnmt_nca_name[sizeof(cnmt_nca_name) - 1] = '\x00';
/* Create a new path. */
ncm::Path content_path;
R_TRY(ConvertToFsCommonPath(content_path.str, sizeof(content_path.str), package_root, cnmt_nca_name));
/* Read the content meta path. */
R_RETURN(ncm::TryReadContentMetaPath(out, content_path.str, ncm::ReadContentMetaPathAlongWithExtendedDataAndDigest));
}
Result GetSystemUpdateUpdateContentInfoFromPackage(ncm::ContentInfo *out, const char *package_root) {
bool found_system_update = false;
/* Iterate over all files to find the system update meta. */
R_TRY(ForEachFileInDirectory(package_root, [&](bool *done, const fs::DirectoryEntry &entry) -> Result {
/* Don't early terminate by default. */
*done = false;
/* We have nothing to list if we're not looking at a meta. */
R_SUCCEED_IF(!PathView(entry.name).HasSuffix(".cnmt.nca"));
/* Read the content meta path, and build. */
ncm::AutoBuffer package_meta;
R_TRY(LoadContentMeta(std::addressof(package_meta), package_root, entry));
/* Create a reader. */
const auto reader = ncm::PackagedContentMetaReader(package_meta.Get(), package_meta.GetSize());
/* If we find a system update, we're potentially done. */
if (reader.GetHeader()->type == ncm::ContentMetaType::SystemUpdate) {
/* Try to parse a content id from the name. */
auto content_id = ncm::GetContentIdFromString(entry.name, sizeof(entry.name));
R_UNLESS(content_id, ncm::ResultInvalidPackageFormat());
/* We're done. */
*done = true;
found_system_update = true;
*out = ncm::ContentInfo::Make(*content_id, entry.file_size, ncm::ContentInfo::DefaultContentAttributes, ncm::ContentType::Meta);
}
R_SUCCEED();
}));
/* If we didn't find anything, error. */
R_UNLESS(found_system_update, ncm::ResultSystemUpdateNotFoundInPackage());
R_SUCCEED();
}
Result ValidateSystemUpdate(Result *out_result, Result *out_exfat_result, UpdateValidationInfo *out_info, const ncm::PackagedContentMetaReader &update_reader, const char *package_root) {
/* Clear output. */
*out_result = ResultSuccess();
*out_exfat_result = ResultSuccess();
/* We want to track all content the update requires. */
const size_t num_content_metas = update_reader.GetContentMetaCount();
bool content_meta_valid[num_content_metas] = {};
/* Allocate a buffer to use for validation. */
size_t data_buffer_size = 1_MB;
void *data_buffer;
do {
data_buffer = std::malloc(data_buffer_size);
if (data_buffer != nullptr) {
break;
}
data_buffer_size /= 2;
} while (data_buffer_size >= 16_KB);
R_UNLESS(data_buffer != nullptr, fs::ResultAllocationMemoryFailedNew());
ON_SCOPE_EXIT { std::free(data_buffer); };
/* Declare helper for result validation. */
auto ValidateResult = [&](Result result) ALWAYS_INLINE_LAMBDA -> Result {
*out_result = result;
R_RETURN(result);
};
/* Iterate over all files to find all content metas. */
R_TRY(ForEachFileInDirectory(package_root, [&](bool *done, const fs::DirectoryEntry &entry) -> Result {
/* Clear output. */
*out_info = {};
/* Don't early terminate by default. */
*done = false;
/* We have nothing to list if we're not looking at a meta. */
R_SUCCEED_IF(!PathView(entry.name).HasSuffix(".cnmt.nca"));
/* Read the content meta path, and build. */
ncm::AutoBuffer package_meta;
R_TRY(LoadContentMeta(std::addressof(package_meta), package_root, entry));
/* Create a reader. */
const auto reader = ncm::PackagedContentMetaReader(package_meta.Get(), package_meta.GetSize());
/* Get the key for the reader. */
const auto key = reader.GetKey();
/* Check if we need to validate this content. */
bool need_validate = false;
size_t validation_index = 0;
for (size_t i = 0; i < num_content_metas; ++i) {
if (update_reader.GetContentMetaInfo(i)->ToKey() == key) {
need_validate = true;
validation_index = i;
break;
}
}
/* If we don't need to validate, continue. */
R_SUCCEED_IF(!need_validate);
/* We're validating. */
out_info->invalid_key = key;
/* Validate all contents. */
for (size_t i = 0; i < reader.GetContentCount(); ++i) {
const auto *content_info = reader.GetContentInfo(i);
const auto &content_id = content_info->GetId();
const s64 content_size = content_info->info.GetSize();
out_info->invalid_content_id = content_id;
/* Get the content id string. */
auto content_id_str = ncm::GetContentIdString(content_id);
/* Open the file. */
fs::FileHandle file;
{
char path[fs::EntryNameLengthMax];
util::SNPrintf(path, sizeof(path), "%s%s%s", package_root, content_id_str.data, content_info->GetType() == ncm::ContentType::Meta ? ".cnmt.nca" : ".nca");
if (R_FAILED(ValidateResult(fs::OpenFile(std::addressof(file), path, ams::fs::OpenMode_Read)))) {
*done = true;
R_SUCCEED();
}
}
ON_SCOPE_EXIT { fs::CloseFile(file); };
/* Validate the file size is correct. */
s64 file_size;
if (R_FAILED(ValidateResult(fs::GetFileSize(std::addressof(file_size), file)))) {
*done = true;
R_SUCCEED();
}
if (file_size != content_size) {
*out_result = ncm::ResultInvalidContentHash();
*done = true;
R_SUCCEED();
}
/* Read and hash the file in chunks. */
crypto::Sha256Generator sha;
sha.Initialize();
s64 ofs = 0;
while (ofs < content_size) {
const size_t cur_size = std::min(static_cast<size_t>(content_size - ofs), data_buffer_size);
if (R_FAILED(ValidateResult(fs::ReadFile(file, ofs, data_buffer, cur_size)))) {
*done = true;
R_SUCCEED();
}
sha.Update(data_buffer, cur_size);
ofs += cur_size;
}
/* Get the hash. */
ncm::Digest calc_digest;
sha.GetHash(std::addressof(calc_digest), sizeof(calc_digest));
/* Validate the hash. */
if (std::memcmp(std::addressof(calc_digest), std::addressof(content_info->digest), sizeof(ncm::Digest)) != 0) {
*out_result = ncm::ResultInvalidContentHash();
*done = true;
R_SUCCEED();
}
}
/* Mark the relevant content as validated. */
content_meta_valid[validation_index] = true;
*out_info = {};
R_SUCCEED();
}));
/* If we're otherwise going to succeed, ensure that every content was found. */
if (R_SUCCEEDED(*out_result)) {
for (size_t i = 0; i < num_content_metas; ++i) {
if (!content_meta_valid[i]) {
const ncm::ContentMetaInfo *info = update_reader.GetContentMetaInfo(i);
*out_info = { .invalid_key = info->ToKey(), };
if (IsExFatDriverSupported(*info)) {
*out_exfat_result = fs::ResultPathNotFound();
/* Continue, in case there's a non-exFAT failure result. */
} else {
*out_result = fs::ResultPathNotFound();
break;
}
}
}
}
R_SUCCEED();
}
Result FormatUserPackagePath(ncm::Path *out, const ncm::Path &user_path) {
/* Ensure that the user path is valid. */
R_UNLESS(user_path.str[0] == '/', fs::ResultInvalidPath());
/* Print as @Sdcard:<user_path>/ */
util::SNPrintf(out->str, sizeof(out->str), "%s:%s/", ams::fs::impl::SdCardFileSystemMountName, user_path.str);
/* Normalize, if the user provided an ending / */
const size_t len = std::strlen(out->str);
if (out->str[len - 1] == '/' && out->str[len - 2] == '/') {
out->str[len - 1] = '\x00';
}
R_SUCCEED();
}
const char *GetFirmwareVariationSettingName(settings::system::PlatformRegion region) {
switch (region) {
case settings::system::PlatformRegion_Global: return "firmware_variation";
case settings::system::PlatformRegion_China: return "t_firmware_variation";
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
ncm::FirmwareVariationId GetFirmwareVariationId() {
/* Get the firmware variation setting name. */
const char * const setting_name = GetFirmwareVariationSettingName(settings::system::GetPlatformRegion());
/* Retrieve the firmware variation id. */
ncm::FirmwareVariationId id = {};
settings::fwdbg::GetSettingsItemValue(std::addressof(id.value), sizeof(u8), "ns.systemupdate", setting_name);
return id;
}
}
Result SystemUpdateService::GetUpdateInformation(sf::Out<UpdateInformation> out, const ncm::Path &path) {
/* Adjust the path. */
ncm::Path package_root;
R_TRY(FormatUserPackagePath(std::addressof(package_root), path));
/* Create a new update information. */
UpdateInformation update_info = {};
/* Parse the update. */
{
/* Get the content info for the system update. */
ncm::ContentInfo content_info;
R_TRY(GetSystemUpdateUpdateContentInfoFromPackage(std::addressof(content_info), package_root.str));
/* Read the content meta. */
ncm::AutoBuffer content_meta_buffer;
R_TRY(ReadContentMetaPath(std::addressof(content_meta_buffer), package_root.str, content_info));
/* Create a reader. */
const auto reader = ncm::PackagedContentMetaReader(content_meta_buffer.Get(), content_meta_buffer.GetSize());
/* Get the version from the header. */
update_info.version = reader.GetHeader()->version;
/* Iterate over infos to find the system update info. */
for (size_t i = 0; i < reader.GetContentMetaCount(); ++i) {
const auto &meta_info = *reader.GetContentMetaInfo(i);
switch (meta_info.type) {
case ncm::ContentMetaType::BootImagePackage:
/* Detect exFAT support. */
update_info.exfat_supported |= IsExFatDriverSupported(meta_info);
break;
default:
break;
}
}
/* Default to no firmware variations. */
update_info.firmware_variation_count = 0;
/* Parse firmware variations if relevant. */
if (reader.GetExtendedDataSize() != 0) {
/* Get the actual firmware variation count. */
ncm::SystemUpdateMetaExtendedDataReader extended_data_reader(reader.GetExtendedData(), reader.GetExtendedDataSize());
update_info.firmware_variation_count = extended_data_reader.GetFirmwareVariationCount();
/* NOTE: Update this if Nintendo ever actually releases an update with this many variations? */
R_UNLESS(update_info.firmware_variation_count <= FirmwareVariationCountMax, ncm::ResultInvalidFirmwareVariation());
for (size_t i = 0; i < update_info.firmware_variation_count; ++i) {
update_info.firmware_variation_ids[i] = *extended_data_reader.GetFirmwareVariationId(i);
}
}
}
/* Set the parsed update info. */
out.SetValue(update_info);
R_SUCCEED();
}
Result SystemUpdateService::ValidateUpdate(sf::Out<Result> out_validate_result, sf::Out<Result> out_validate_exfat_result, sf::Out<UpdateValidationInfo> out_validate_info, const ncm::Path &path) {
/* Adjust the path. */
ncm::Path package_root;
R_TRY(FormatUserPackagePath(std::addressof(package_root), path));
/* Parse the update. */
{
/* Get the content info for the system update. */
ncm::ContentInfo content_info;
R_TRY(GetSystemUpdateUpdateContentInfoFromPackage(std::addressof(content_info), package_root.str));
/* Read the content meta. */
ncm::AutoBuffer content_meta_buffer;
R_TRY(ReadContentMetaPath(std::addressof(content_meta_buffer), package_root.str, content_info));
/* Create a reader. */
const auto reader = ncm::PackagedContentMetaReader(content_meta_buffer.Get(), content_meta_buffer.GetSize());
/* Validate the update. */
R_TRY(ValidateSystemUpdate(out_validate_result.GetPointer(), out_validate_exfat_result.GetPointer(), out_validate_info.GetPointer(), reader, package_root.str));
}
R_SUCCEED();
};
Result SystemUpdateService::SetupUpdate(sf::CopyHandle &&transfer_memory, u64 transfer_memory_size, const ncm::Path &path, bool exfat) {
R_RETURN(this->SetupUpdateImpl(std::move(transfer_memory), transfer_memory_size, path, exfat, GetFirmwareVariationId()));
}
Result SystemUpdateService::SetupUpdateWithVariation(sf::CopyHandle &&transfer_memory, u64 transfer_memory_size, const ncm::Path &path, bool exfat, ncm::FirmwareVariationId firmware_variation_id) {
R_RETURN(this->SetupUpdateImpl(std::move(transfer_memory), transfer_memory_size, path, exfat, firmware_variation_id));
}
Result SystemUpdateService::RequestPrepareUpdate(sf::OutCopyHandle out_event_handle, sf::Out<sf::SharedPointer<ns::impl::IAsyncResult>> out_async) {
/* Ensure the update is setup but not prepared. */
R_UNLESS(m_setup_update, ns::ResultCardUpdateNotSetup());
R_UNLESS(!m_requested_update, ns::ResultPrepareCardUpdateAlreadyRequested());
/* Create the async result. */
auto async_result = sf::CreateSharedObjectEmplaced<ns::impl::IAsyncResult, AsyncPrepareSdCardUpdateImpl>(std::addressof(*m_update_task));
R_UNLESS(async_result != nullptr, ns::ResultOutOfMaxRunningTask());
/* Run the task. */
R_TRY(async_result.GetImpl().Run());
/* We prepared the task! */
m_requested_update = true;
out_event_handle.SetValue(async_result.GetImpl().GetEvent().GetReadableHandle(), false);
*out_async = std::move(async_result);
R_SUCCEED();
}
Result SystemUpdateService::GetPrepareUpdateProgress(sf::Out<SystemUpdateProgress> out) {
/* Ensure the update is setup. */
R_UNLESS(m_setup_update, ns::ResultCardUpdateNotSetup());
/* Get the progress. */
auto install_progress = m_update_task->GetProgress();
out.SetValue({ .current_size = install_progress.installed_size, .total_size = install_progress.total_size });
R_SUCCEED();
}
Result SystemUpdateService::HasPreparedUpdate(sf::Out<bool> out) {
/* Ensure the update is setup. */
R_UNLESS(m_setup_update, ns::ResultCardUpdateNotSetup());
out.SetValue(m_update_task->GetProgress().state == ncm::InstallProgressState::Downloaded);
R_SUCCEED();
}
Result SystemUpdateService::ApplyPreparedUpdate() {
/* Ensure the update is setup. */
R_UNLESS(m_setup_update, ns::ResultCardUpdateNotSetup());
/* Ensure the update is prepared. */
R_UNLESS(m_update_task->GetProgress().state == ncm::InstallProgressState::Downloaded, ns::ResultCardUpdateNotPrepared());
/* Apply the task. */
R_TRY(m_apply_manager.ApplyPackageTask(std::addressof(*m_update_task)));
R_SUCCEED();
}
Result SystemUpdateService::SetupUpdateImpl(sf::NativeHandle &&transfer_memory, u64 transfer_memory_size, const ncm::Path &path, bool exfat, ncm::FirmwareVariationId firmware_variation_id) {
/* Ensure we don't already have an update set up. */
R_UNLESS(!m_setup_update, ns::ResultCardUpdateAlreadySetup());
/* Destroy any existing update tasks. */
nim::SystemUpdateTaskId id;
auto count = nim::ListSystemUpdateTask(std::addressof(id), 1);
if (count > 0) {
R_TRY(nim::DestroySystemUpdateTask(id));
}
/* Initialize the update task. */
R_TRY(InitializeUpdateTask(std::move(transfer_memory), transfer_memory_size, path, exfat, firmware_variation_id));
/* The update is now set up. */
m_setup_update = true;
R_SUCCEED();
}
Result SystemUpdateService::InitializeUpdateTask(sf::NativeHandle &&transfer_memory, u64 transfer_memory_size, const ncm::Path &path, bool exfat, ncm::FirmwareVariationId firmware_variation_id) {
/* Map the transfer memory. */
const size_t tmem_buffer_size = static_cast<size_t>(transfer_memory_size);
m_update_transfer_memory.emplace(tmem_buffer_size, transfer_memory.GetOsHandle(), transfer_memory.IsManaged());
transfer_memory.Detach();
void *tmem_buffer;
R_TRY(m_update_transfer_memory->Map(std::addressof(tmem_buffer), os::MemoryPermission_None));
auto tmem_guard = SCOPE_GUARD {
m_update_transfer_memory->Unmap();
m_update_transfer_memory = util::nullopt;
};
/* Adjust the package root. */
ncm::Path package_root;
R_TRY(FormatUserPackagePath(std::addressof(package_root), path));
/* Ensure that we can create an update context. */
R_TRY(fs::EnsureDirectory("@Sdcard:/atmosphere/update/"));
const char *context_path = "@Sdcard:/atmosphere/update/cup.ctx";
/* Create and initialize the update task. */
m_update_task.emplace();
R_TRY(m_update_task->Initialize(package_root.str, context_path, tmem_buffer, tmem_buffer_size, exfat, firmware_variation_id));
/* We successfully setup the update. */
tmem_guard.Cancel();
R_SUCCEED();
}
}
| 23,297
|
C++
|
.cpp
| 408
| 43.090686
| 201
| 0.580724
|
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,225
|
sysupdater_thread_allocator.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/sysupdater/sysupdater_thread_allocator.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "sysupdater_thread_allocator.hpp"
namespace ams::mitm::sysupdater {
Result ThreadAllocator::Allocate(ThreadInfo *out) {
std::scoped_lock lk(m_mutex);
for (int i = 0; i < m_thread_count; ++i) {
const u64 mask = (static_cast<u64>(1) << i);
if ((m_bitmap & mask) == 0) {
*out = {
.thread = m_thread_list + i,
.priority = m_thread_priority,
.stack = m_stack_heap + (m_stack_size * i),
.stack_size = m_stack_size,
};
m_bitmap |= mask;
R_SUCCEED();
}
}
R_THROW(ns::ResultOutOfMaxRunningTask());
}
void ThreadAllocator::Free(const ThreadInfo &info) {
std::scoped_lock lk(m_mutex);
for (int i = 0; i < m_thread_count; ++i) {
if (info.thread == std::addressof(m_thread_list[i])) {
const u64 mask = (static_cast<u64>(1) << i);
m_bitmap &= ~mask;
return;
}
}
AMS_ABORT("Invalid thread passed to ThreadAllocator::Free");
}
}
| 1,836
|
C++
|
.cpp
| 47
| 30.531915
| 76
| 0.57945
|
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,226
|
sysupdater_async_thread_allocator.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/sysupdater/sysupdater_async_thread_allocator.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "sysupdater_async_thread_allocator.hpp"
namespace ams::mitm::sysupdater {
namespace {
constexpr inline int AsyncThreadCount = 1;
constexpr inline size_t AsyncThreadStackSize = 32_KB;
os::ThreadType g_async_threads[AsyncThreadCount];
alignas(os::ThreadStackAlignment) u8 g_async_thread_stack_heap[AsyncThreadCount * AsyncThreadStackSize];
constinit ThreadAllocator g_async_thread_allocator(g_async_threads, AsyncThreadCount, os::InvalidThreadPriority, g_async_thread_stack_heap, sizeof(g_async_thread_stack_heap), AsyncThreadStackSize);
}
ThreadAllocator *GetAsyncThreadAllocator() {
return std::addressof(g_async_thread_allocator);
}
}
| 1,381
|
C++
|
.cpp
| 29
| 43.62069
| 205
| 0.756515
|
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,227
|
sysupdater_apply_manager.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/sysupdater/sysupdater_apply_manager.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "sysupdater_apply_manager.hpp"
namespace ams::mitm::sysupdater {
namespace {
alignas(os::MemoryPageSize) u8 g_boot_image_update_buffer[64_KB];
updater::BootImageUpdateType GetBootImageUpdateType() {
/* NOTE: Here Nintendo uses the value of system setting systeminitializer!boot_image_update_type...but we prefer not to take the risk. */
return updater::GetBootImageUpdateType(spl::GetHardwareType());
}
Result MarkPreCommitForBootImages() {
/* Set verification required for both normal and safe mode. */
R_TRY(updater::MarkVerifyingRequired(updater::BootModeType::Normal, g_boot_image_update_buffer, sizeof(g_boot_image_update_buffer)));
R_TRY(updater::MarkVerifyingRequired(updater::BootModeType::Safe, g_boot_image_update_buffer, sizeof(g_boot_image_update_buffer)));
/* Pre-commit is now marked. */
R_SUCCEED();
}
Result UpdateBootImages() {
/* Define a helper to update the images. */
auto UpdateBootImageImpl = [](updater::BootModeType boot_mode, updater::BootImageUpdateType boot_image_update_type) -> Result {
/* Get the boot image package id. */
ncm::SystemDataId boot_image_package_id = {};
R_TRY_CATCH(updater::GetBootImagePackageId(std::addressof(boot_image_package_id), boot_mode, g_boot_image_update_buffer, sizeof(g_boot_image_update_buffer))) {
R_CATCH(updater::ResultBootImagePackageNotFound) {
/* Nintendo simply falls through when the package is not found. */
}
} R_END_TRY_CATCH;
/* Update the boot images. */
R_TRY_CATCH(updater::UpdateBootImagesFromPackage(boot_image_package_id, boot_mode, g_boot_image_update_buffer, sizeof(g_boot_image_update_buffer), boot_image_update_type)) {
R_CATCH(updater::ResultBootImagePackageNotFound) {
/* Nintendo simply falls through when the package is not found. */
}
} R_END_TRY_CATCH;
/* Mark the images verified. */
R_TRY(updater::MarkVerified(boot_mode, g_boot_image_update_buffer, sizeof(g_boot_image_update_buffer)));
/* The boot images are updated. */
R_SUCCEED();
};
/* Get the boot image update type. */
auto boot_image_update_type = GetBootImageUpdateType();
/* Update boot images for safe mode. */
R_TRY(UpdateBootImageImpl(updater::BootModeType::Safe, boot_image_update_type));
/* Update boot images for normal mode. */
R_TRY(UpdateBootImageImpl(updater::BootModeType::Normal, boot_image_update_type));
/* Both sets of images are updated. */
R_SUCCEED();
}
}
Result SystemUpdateApplyManager::ApplyPackageTask(ncm::PackageSystemDowngradeTask *task) {
/* Lock the apply mutex. */
std::scoped_lock lk(m_apply_mutex);
/* NOTE: Here, Nintendo creates a system report for the update. */
/* Mark boot images to note that we're updating. */
R_TRY(MarkPreCommitForBootImages());
/* Commit the task. */
R_TRY(task->Commit());
/* Update the boot images. */
R_TRY(UpdateBootImages());
R_SUCCEED();
}
}
| 4,124
|
C++
|
.cpp
| 75
| 44.533333
| 189
| 0.638847
|
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,228
|
sysupdater_module.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/sysupdater/sysupdater_module.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "../amsmitm_initialization.hpp"
#include "sysupdater_module.hpp"
#include "sysupdater_service.hpp"
#include "sysupdater_async_impl.hpp"
namespace ams::mitm::sysupdater {
namespace {
enum PortIndex {
PortIndex_Sysupdater,
PortIndex_Count,
};
constexpr sm::ServiceName SystemUpdateServiceName = sm::ServiceName::Encode("ams:su");
constexpr size_t SystemUpdateMaxSessions = 1;
constexpr size_t MaxSessions = SystemUpdateMaxSessions + 3;
struct ServerOptions {
static constexpr size_t PointerBufferSize = 1_KB;
static constexpr size_t MaxDomains = 0;
static constexpr size_t MaxDomainObjects = 0;
static constexpr bool CanDeferInvokeRequest = false;
static constexpr bool CanManageMitmServers = false;
};
sf::hipc::ServerManager<PortIndex_Count, ServerOptions, MaxSessions> g_server_manager;
constinit sf::UnmanagedServiceObject<sysupdater::impl::ISystemUpdateInterface, sysupdater::SystemUpdateService> g_system_update_service_object;
}
void MitmModule::ThreadFunction(void *) {
/* Wait until initialization is complete. */
mitm::WaitInitialized();
/* Connect to nim. */
nim::InitializeForNetworkInstallManager();
ON_SCOPE_EXIT { nim::FinalizeForNetworkInstallManager(); };
/* Register ams:su. */
R_ABORT_UNLESS(g_server_manager.RegisterObjectForServer(g_system_update_service_object.GetShared(), SystemUpdateServiceName, SystemUpdateMaxSessions));
/* Loop forever, servicing our services. */
g_server_manager.LoopProcess();
}
}
| 2,380
|
C++
|
.cpp
| 51
| 40.333333
| 159
| 0.704104
|
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,229
|
sysupdater_async_impl.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/sysupdater/sysupdater_async_impl.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "sysupdater_async_impl.hpp"
#include "sysupdater_async_thread_allocator.hpp"
namespace ams::mitm::sysupdater {
Result AsyncBase::ToAsyncResult(Result result) {
R_TRY_CATCH(result) {
R_CONVERT(nim::ResultHttpConnectionCanceled, ns::ResultCanceled());
R_CONVERT(ncm::ResultInstallTaskCancelled, ns::ResultCanceled());
} R_END_TRY_CATCH;
R_SUCCEED();
}
AsyncPrepareSdCardUpdateImpl::~AsyncPrepareSdCardUpdateImpl() {
if (m_thread_info) {
os::WaitThread(m_thread_info->thread);
os::DestroyThread(m_thread_info->thread);
GetAsyncThreadAllocator()->Free(*m_thread_info);
}
}
Result AsyncPrepareSdCardUpdateImpl::Run() {
/* Get a thread info. */
ThreadInfo info;
R_TRY(GetAsyncThreadAllocator()->Allocate(std::addressof(info)));
/* Set the thread info's priority. */
info.priority = AMS_GET_SYSTEM_THREAD_PRIORITY(mitm_sysupdater, AsyncPrepareSdCardUpdateTask);
/* Ensure that we clean up appropriately. */
ON_SCOPE_EXIT {
if (!m_thread_info) {
GetAsyncThreadAllocator()->Free(info);
}
};
/* Create a thread for the task. */
R_TRY(os::CreateThread(info.thread, [](void *arg) {
auto *async = reinterpret_cast<AsyncPrepareSdCardUpdateImpl *>(arg);
async->m_result = async->Execute();
async->m_event.Signal();
}, this, info.stack, info.stack_size, info.priority));
/* Set the thread name. */
os::SetThreadNamePointer(info.thread, AMS_GET_SYSTEM_THREAD_NAME(mitm_sysupdater, AsyncPrepareSdCardUpdateTask));
/* Start the thread. */
os::StartThread(info.thread);
/* Set our thread info. */
m_thread_info = info;
R_SUCCEED();
}
Result AsyncPrepareSdCardUpdateImpl::Execute() {
R_RETURN(m_task->PrepareAndExecute());
}
void AsyncPrepareSdCardUpdateImpl::CancelImpl() {
m_task->Cancel();
}
}
| 2,740
|
C++
|
.cpp
| 66
| 34.393939
| 121
| 0.657143
|
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,230
|
ns_web_mitm_service.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/ns_mitm/ns_web_mitm_service.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "../amsmitm_fs_utils.hpp"
#include "ns_web_mitm_service.hpp"
namespace ams::mitm::ns {
Result NsDocumentService::GetApplicationContentPath(const sf::OutBuffer &out_path, sf::Out<ams::fs::ContentAttributes> out_attr, ncm::ProgramId application_id, u8 content_type) {
static_assert(sizeof(*out_attr.GetPointer()) == sizeof(u8));
R_RETURN(nswebGetApplicationContentPath(m_srv.get(), out_path.GetPointer(), out_path.GetSize(), reinterpret_cast<u8 *>(out_attr.GetPointer()), static_cast<u64>(application_id), static_cast<NcmContentType>(content_type)));
}
Result NsDocumentService::ResolveApplicationContentPath(ncm::ProgramId application_id, u8 content_type) {
/* Always succeed for web applets asking about HBL to enable hbl_html, and applications with manual_html to allow custom manual data. */
bool is_hbl = false;
if ((R_SUCCEEDED(ams::pm::info::IsHblProgramId(std::addressof(is_hbl), application_id)) && is_hbl) || (static_cast<ncm::ContentType>(content_type) == ncm::ContentType::HtmlDocument && mitm::fs::HasSdManualHtmlContent(application_id))) {
nswebResolveApplicationContentPath(m_srv.get(), static_cast<u64>(application_id), static_cast<NcmContentType>(content_type));
R_SUCCEED();
}
R_RETURN(nswebResolveApplicationContentPath(m_srv.get(), static_cast<u64>(application_id), static_cast<NcmContentType>(content_type)));
}
Result NsDocumentService::GetRunningApplicationProgramId(sf::Out<ncm::ProgramId> out, ncm::ProgramId application_id) {
R_RETURN(nswebGetRunningApplicationProgramId(m_srv.get(), reinterpret_cast<u64 *>(out.GetPointer()), static_cast<u64>(application_id)));
}
Result NsDocumentService::GetApplicationContentPath2(const sf::OutBuffer &out_path, sf::Out<ncm::ProgramId> out_program_id, sf::Out<ams::fs::ContentAttributes> out_attr, ncm::ProgramId application_id, u8 content_type) {
static_assert(sizeof(*out_attr.GetPointer()) == sizeof(u8));
R_RETURN(nswebGetApplicationContentPath2(m_srv.get(), out_path.GetPointer(), out_path.GetSize(), reinterpret_cast<u64 *>(out_program_id.GetPointer()), reinterpret_cast<u8 *>(out_attr.GetPointer()), static_cast<u64>(application_id), static_cast<NcmContentType>(content_type)));
}
Result NsWebMitmService::GetDocumentInterface(sf::Out<sf::SharedPointer<impl::IDocumentInterface>> out) {
/* Open a document interface. */
NsDocumentInterface doc;
R_TRY(nsGetDocumentInterfaceFwd(m_forward_service.get(), std::addressof(doc)));
const sf::cmif::DomainObjectId target_object_id{serviceGetObjectId(std::addressof(doc.s))};
out.SetValue(sf::CreateSharedObjectEmplaced<impl::IDocumentInterface, NsDocumentService>(m_client_info, std::make_unique<NsDocumentInterface>(doc)), target_object_id);
R_SUCCEED();
}
}
| 3,542
|
C++
|
.cpp
| 48
| 68.333333
| 284
| 0.734366
|
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,231
|
nsmitm_module.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/ns_mitm/nsmitm_module.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "../amsmitm_initialization.hpp"
#include "nsmitm_module.hpp"
#include "ns_am_mitm_service.hpp"
#include "ns_web_mitm_service.hpp"
namespace ams::mitm::ns {
namespace {
enum PortIndex {
PortIndex_Mitm,
PortIndex_Count,
};
constexpr sm::ServiceName NsAmMitmServiceName = sm::ServiceName::Encode("ns:am");
constexpr sm::ServiceName NsWebMitmServiceName = sm::ServiceName::Encode("ns:web");
constexpr size_t MaxSessions = 5;
struct ServerOptions {
static constexpr size_t PointerBufferSize = sf::hipc::DefaultServerManagerOptions::PointerBufferSize;
static constexpr size_t MaxDomains = sf::hipc::DefaultServerManagerOptions::MaxDomains;
static constexpr size_t MaxDomainObjects = sf::hipc::DefaultServerManagerOptions::MaxDomainObjects;
static constexpr bool CanDeferInvokeRequest = sf::hipc::DefaultServerManagerOptions::CanDeferInvokeRequest;
static constexpr bool CanManageMitmServers = true;
};
class ServerManager final : public sf::hipc::ServerManager<PortIndex_Count, ServerOptions, MaxSessions> {
private:
virtual Result OnNeedsToAccept(int port_index, Server *server) override;
};
ServerManager g_server_manager;
Result ServerManager::OnNeedsToAccept(int port_index, Server *server) {
/* Acknowledge the mitm session. */
std::shared_ptr<::Service> fsrv;
sm::MitmProcessInfo client_info;
server->AcknowledgeMitmSession(std::addressof(fsrv), std::addressof(client_info));
switch (port_index) {
case PortIndex_Mitm:
if (hos::GetVersion() < hos::Version_3_0_0) {
R_RETURN(this->AcceptMitmImpl(server, sf::CreateSharedObjectEmplaced<impl::IAmMitmInterface, NsAmMitmService>(decltype(fsrv)(fsrv), client_info), fsrv));
} else {
R_RETURN(this->AcceptMitmImpl(server, sf::CreateSharedObjectEmplaced<impl::IWebMitmInterface, NsWebMitmService>(decltype(fsrv)(fsrv), client_info), fsrv));
}
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
}
void MitmModule::ThreadFunction(void *) {
/* Wait until initialization is complete. */
mitm::WaitInitialized();
/* Create mitm servers. */
if (hos::GetVersion() < hos::Version_3_0_0) {
R_ABORT_UNLESS((g_server_manager.RegisterMitmServer<NsAmMitmService>(PortIndex_Mitm, NsAmMitmServiceName)));
} else {
R_ABORT_UNLESS((g_server_manager.RegisterMitmServer<NsWebMitmService>(PortIndex_Mitm, NsWebMitmServiceName)));
}
/* Loop forever, servicing our services. */
g_server_manager.LoopProcess();
}
}
| 3,547
|
C++
|
.cpp
| 70
| 41.757143
| 179
| 0.667437
|
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,232
|
ns_am_mitm_service.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/ns_mitm/ns_am_mitm_service.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "../amsmitm_fs_utils.hpp"
#include "ns_am_mitm_service.hpp"
#include "ns_shim.h"
namespace ams::mitm::ns {
Result NsAmMitmService::GetApplicationContentPath(const sf::OutBuffer &out_path, ncm::ProgramId application_id, u8 content_type) {
R_RETURN(nsamGetApplicationContentPathFwd(m_forward_service.get(), out_path.GetPointer(), out_path.GetSize(), static_cast<u64>(application_id), static_cast<NcmContentType>(content_type)));
}
Result NsAmMitmService::ResolveApplicationContentPath(ncm::ProgramId application_id, u8 content_type) {
/* Always succeed for web applets asking about HBL to enable hbl_html, and applications with manual_html to allow custom manual data. */
bool is_hbl = false;
if ((R_SUCCEEDED(ams::pm::info::IsHblProgramId(std::addressof(is_hbl), application_id)) && is_hbl) || (static_cast<ncm::ContentType>(content_type) == ncm::ContentType::HtmlDocument && mitm::fs::HasSdManualHtmlContent(application_id))) {
nsamResolveApplicationContentPathFwd(m_forward_service.get(), static_cast<u64>(application_id), static_cast<NcmContentType>(content_type));
R_SUCCEED();
}
R_RETURN(nsamResolveApplicationContentPathFwd(m_forward_service.get(), static_cast<u64>(application_id), static_cast<NcmContentType>(content_type)));
}
Result NsAmMitmService::GetRunningApplicationProgramId(sf::Out<ncm::ProgramId> out, ncm::ProgramId application_id) {
R_RETURN(nsamGetRunningApplicationProgramIdFwd(m_forward_service.get(), reinterpret_cast<u64 *>(out.GetPointer()), static_cast<u64>(application_id)));
}
}
| 2,288
|
C++
|
.cpp
| 36
| 59.138889
| 244
| 0.742768
|
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,233
|
mitm_pm_module.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/mitm_pm/mitm_pm_module.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "../amsmitm_initialization.hpp"
#include "mitm_pm_module.hpp"
#include "mitm_pm_service.hpp"
namespace ams::mitm::pm {
namespace {
constexpr sm::ServiceName PmServiceName = sm::ServiceName::Encode("mitm:pm");
constexpr size_t PmMaxSessions = 1;
constexpr size_t MaxServers = 1;
constexpr size_t MaxSessions = PmMaxSessions;
using ServerOptions = sf::hipc::DefaultServerManagerOptions;
sf::hipc::ServerManager<MaxServers, ServerOptions, MaxSessions> g_server_manager;
constinit sf::UnmanagedServiceObject<mitm::pm::impl::IPmInterface, mitm::pm::PmService> g_pm_service_object;
}
void MitmModule::ThreadFunction(void *) {
/* Create bpc:ams. */
R_ABORT_UNLESS(g_server_manager.RegisterObjectForServer(g_pm_service_object.GetShared(), PmServiceName, PmMaxSessions));
/* Loop forever, servicing our services. */
g_server_manager.LoopProcess();
}
}
| 1,637
|
C++
|
.cpp
| 36
| 40.944444
| 128
| 0.721734
|
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,234
|
mitm_pm_service.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/mitm_pm/mitm_pm_service.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "../amsmitm_initialization.hpp"
#include "mitm_pm_service.hpp"
#include "mitm_pm_service.hpp"
#include "../fs_mitm/fsmitm_romfs.hpp"
namespace ams::mitm::pm {
Result PmService::PrepareLaunchProgram(sf::Out<u64> out, ncm::ProgramId program_id, const cfg::OverrideStatus &status, bool is_application) {
/* Default to zero heap. */
*out = 0;
/* Actually configure the required boost size for romfs. */
R_TRY(mitm::fs::romfs::ConfigureDynamicHeap(out.GetPointer(), program_id, status, is_application));
/* TODO: Is there anything else we should do, while we have the opportunity? */
R_SUCCEED();
}
}
| 1,329
|
C++
|
.cpp
| 30
| 40.8
| 145
| 0.72102
|
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,235
|
fs_main.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/fs/source/fs_main.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams {
namespace init {
void InitializeSystemModule() {
/* TODO? */
/* Initialize services we need. */
R_ABORT_UNLESS(sm::Initialize());
/* TODO? */
/* Verify that we can sanely execute. */
ams::CheckApiVersion();
}
void FinalizeSystemModule() { /* ... */ }
void Startup() { /* ... */ }
}
void NORETURN Exit(int rc) {
AMS_UNUSED(rc);
AMS_ABORT("Exit called by immortal process");
}
void Main() {
/* Initialize fssystem library for FS. */
fssystem::InitializeForFileSystemProxy();
}
}
| 1,328
|
C++
|
.cpp
| 38
| 29.052632
| 76
| 0.641628
|
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,236
|
cs_main.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/cs/source/cs_main.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams {
namespace cs {
namespace {
alignas(os::ThreadStackAlignment) constinit u8 g_shell_stack[4_KB];
alignas(os::ThreadStackAlignment) constinit u8 g_runner_stack[4_KB];
alignas(os::MemoryPageSize) constinit u8 g_heap_memory[32_KB];
alignas(0x40) constinit u8 g_htcs_buffer[2_KB];
constinit os::SdkMutex g_heap_mutex;
constinit lmem::HeapHandle g_heap_handle;
void *Allocate(size_t size) {
std::scoped_lock lk(g_heap_mutex);
void *mem = lmem::AllocateFromExpHeap(g_heap_handle, size);
return mem;
}
void Deallocate(void *p, size_t size) {
AMS_UNUSED(size);
std::scoped_lock lk(g_heap_mutex);
lmem::FreeToExpHeap(g_heap_handle, p);
}
void InitializeHeap() {
std::scoped_lock lk(g_heap_mutex);
g_heap_handle = lmem::CreateExpHeap(g_heap_memory, sizeof(g_heap_memory), lmem::CreateOption_None);
}
}
namespace {
constinit ::ams::cs::CommandProcessor g_command_processor;
constinit ::ams::scs::ShellServer g_shell_server;
constinit ::ams::scs::ShellServer g_runner_server;
constinit sf::UnmanagedServiceObject<htc::tenv::IServiceManager, htc::tenv::ServiceManager> g_tenv_service_manager;
void InitializeCommandProcessor() {
g_command_processor.Initialize();
}
void InitializeShellServers() {
g_shell_server.Initialize("iywys@$cs", g_shell_stack, sizeof(g_shell_stack), std::addressof(g_command_processor));
g_shell_server.Start();
g_runner_server.Initialize("iywys@$csForRunnerTools", g_runner_stack, sizeof(g_runner_stack), std::addressof(g_command_processor));
g_runner_server.Start();
}
}
}
namespace init {
void InitializeSystemModule() {
/* Initialize heap. */
cs::InitializeHeap();
/* Initialize our connection to sm. */
R_ABORT_UNLESS(sm::Initialize());
/* Initialize fs. */
fs::InitializeForSystem();
fs::SetAllocator(cs::Allocate, cs::Deallocate);
fs::SetEnabledAutoAbort(false);
/* Initialize other services we need. */
lr::Initialize();
R_ABORT_UNLESS(ldr::InitializeForShell());
R_ABORT_UNLESS(pgl::Initialize());
R_ABORT_UNLESS(setsysInitialize());
/* Verify that we can sanely execute. */
ams::CheckApiVersion();
}
void FinalizeSystemModule() { /* ... */ }
void Startup() { /* ... */ }
}
void Main() {
/* Set thread name. */
os::SetThreadNamePointer(os::GetCurrentThread(), AMS_GET_SYSTEM_THREAD_NAME(cs, Main));
AMS_ASSERT(os::GetThreadPriority(os::GetCurrentThread()) == AMS_GET_SYSTEM_THREAD_PRIORITY(cs, Main));
/* Initialize htcs. */
constexpr auto HtcsSocketCountMax = 6;
const size_t buffer_size = htcs::GetWorkingMemorySize(2 * HtcsSocketCountMax);
AMS_ABORT_UNLESS(sizeof(cs::g_htcs_buffer) >= buffer_size);
htcs::InitializeForSystem(cs::g_htcs_buffer, buffer_size, HtcsSocketCountMax);
/* Initialize audio server. */
cs::InitializeAudioServer();
/* Initialize remote video server. */
cs::InitializeRemoteVideoServer();
/* Initialize hid server. */
cs::InitializeHidServer();
/* Initialize target io server. */
cs::InitializeTargetIoServer();
/* Initialize command processor. */
cs::InitializeCommandProcessor();
/* Setup scs. */
scs::InitializeShell();
/* Setup target environment service. */
scs::InitializeTenvServiceManager();
/* Initialize the shell servers. */
cs::InitializeShellServers();
/* Register htc:tenv. */
R_ABORT_UNLESS(scs::GetServerManager()->RegisterObjectForServer(cs::g_tenv_service_manager.GetShared(), htc::tenv::ServiceName, scs::SessionCount[scs::Port_HtcTenv]));
/* Start the scs ipc server. */
scs::StartServer();
}
}
| 5,021
|
C++
|
.cpp
| 108
| 36.259259
| 175
| 0.614784
|
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,237
|
tio_sd_card_observer.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/TioServer/source/tio_sd_card_observer.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "tio_sd_card_observer.hpp"
namespace ams::tio {
void SdCardObserver::Initialize(void *thread_stack, size_t thread_stack_size) {
/* Setup our thread. */
R_ABORT_UNLESS(os::CreateThread(std::addressof(m_thread), ThreadEntry, this, thread_stack, thread_stack_size, AMS_GET_SYSTEM_THREAD_PRIORITY(TioServer, SdCardObserver)));
/* Set our thread name pointer. */
os::SetThreadNamePointer(std::addressof(m_thread), AMS_GET_SYSTEM_THREAD_NAME(TioServer, SdCardObserver));
/* Set our initial insertion state. */
m_inserted = fs::IsSdCardInserted();
}
void SdCardObserver::SetCallback(SdCardInsertionCallback callback) {
/* Check that we don't already have a callback. */
AMS_ABORT_UNLESS(m_callback == nullptr);
/* Set our callback. */
m_callback = callback;
}
void SdCardObserver::ThreadFunc() {
/* Open detection event notifier. */
std::unique_ptr<fs::IEventNotifier> notifier;
R_ABORT_UNLESS(fs::OpenSdCardDetectionEventNotifier(std::addressof(notifier)));
/* Bind the detection event. */
os::SystemEventType event;
R_ABORT_UNLESS(notifier->BindEvent(std::addressof(event), os::EventClearMode_AutoClear));
/* Loop, waiting for insertion events. */
while (true) {
/* Wait for an event. */
os::WaitSystemEvent(std::addressof(event));
/* Update our insertion state. */
m_inserted = fs::IsSdCardInserted();
/* Invoke our callback. */
if (m_callback) {
m_callback(m_inserted);
}
}
}
}
| 2,335
|
C++
|
.cpp
| 52
| 38.096154
| 178
| 0.667547
|
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,238
|
tio_file_server_processor.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/TioServer/source/tio_file_server_processor.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "tio_file_server_processor.hpp"
namespace ams::tio {
namespace {
constexpr inline int ProtocolVersion = 1;
}
void FileServerProcessor::Unmount() {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Close all our directories. */
if (m_open_directory_count > 0) {
for (size_t i = 0; i < util::size(m_directories); ++i) {
if (m_directories[i].handle != nullptr) {
fs::CloseDirectory(m_directories[i]);
m_directories[i] = {};
--m_open_directory_count;
}
}
}
AMS_ABORT_UNLESS(m_open_directory_count == 0);
/* Close all our files. */
if (m_open_file_count > 0) {
for (size_t i = 0; i < util::size(m_files); ++i) {
if (m_files[i].handle != nullptr) {
fs::CloseFile(m_files[i]);
m_files[i] = {};
--m_open_file_count;
}
}
}
AMS_ABORT_UNLESS(m_open_file_count == 0);
/* If we're mounted, unmount the sd card. */
if (m_is_mounted) {
m_is_mounted = false;
fs::Unmount("sd");
}
}
bool FileServerProcessor::ProcessRequest(FileServerRequestHeader *header, u8 *body, int socket) {
/* Declare a response header for us to use. */
FileServerResponseHeader response_header = {
.request_id = header->request_id,
.result = ResultSuccess(),
.body_size = 0,
};
/* Handle the special control commands. */
if (header->packet_type == PacketType::Connect) {
/* If the SD card isn't already mounted, try to mount it. */
if (!m_is_mounted) {
/* Mount the sd card. */
m_is_mounted = !fs::ResultSdCardAccessFailed::Includes(fs::MountSdCard("sd"));
/* Prepare the response. */
char *response_body = reinterpret_cast<char *>(body);
util::SNPrintf(response_body, 0x100, "{\"bufferSize\":%zu, \"sdcardMounted\":%s, \"sdcardInserted\":%s, \"version\":%d}",
m_request_buffer_size,
m_is_mounted ? "true" : "false",
m_is_inserted ? "true" : "false",
ProtocolVersion);
/* Get the response length. */
response_header.body_size = std::strlen(response_body);
}
return this->SendResponse(response_header, body, socket);
} else if (header->packet_type == PacketType::Disconnect) {
/* If we need to, unmount the sd card. */
if (m_is_mounted) {
this->Unmount();
}
/* Send the response. */
return this->SendResponse(response_header, body, socket);
}
/* The SD card must be inserted and mounted for us to process requests. */
if (m_is_inserted && m_is_mounted) {
switch (header->packet_type) {
case PacketType::CreateDirectory:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const CreateDirectoryParam *>(body);
if (header->body_size != sizeof(*param) + param->path_len) {
return false;
}
/* Create the directory. */
response_header.result = fs::CreateDirectory(param->path);
}
break;
case PacketType::DeleteDirectory:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const DeleteDirectoryParam *>(body);
if (header->body_size != sizeof(*param) + param->path_len) {
return false;
}
/* Delete the directory. */
response_header.result = fs::DeleteDirectory(param->path);
}
break;
case PacketType::DeleteDirectoryRecursively:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const DeleteDirectoryRecursivelyParam *>(body);
if (header->body_size != sizeof(*param) + param->path_len) {
return false;
}
/* Delete the directory. */
response_header.result = fs::DeleteDirectoryRecursively(param->path);
}
break;
case PacketType::OpenDirectory:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const OpenDirectoryParam *>(body);
if (header->body_size != sizeof(*param) + param->path_len) {
return false;
}
/* Open the directory. */
fs::DirectoryHandle handle;
response_header.result = fs::OpenDirectory(std::addressof(handle), param->path, param->open_mode);
if (R_SUCCEEDED(response_header.result)) {
std::scoped_lock lk(m_mutex);
if (m_open_directory_count < util::size(m_directories)) {
/* Insert the directory into our table. */
u64 index = std::numeric_limits<u64>::max();
for (size_t i = 0; i < util::size(m_directories); ++i) {
if (m_directories[i].handle == nullptr) {
m_directories[i] = handle;
index = i;
++m_open_directory_count;
break;
}
}
AMS_ABORT_UNLESS(index < util::size(m_directories));
/* Return the index. */
response_header.body_size = sizeof(index);
std::memcpy(body, std::addressof(index), sizeof(index));
} else {
/* We can't actually open the directory. */
fs::CloseDirectory(handle);
response_header.result = fs::ResultOpenCountLimit();
}
}
}
break;
case PacketType::CloseDirectory:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const CloseDirectoryParam *>(body);
if (header->body_size != sizeof(*param)) {
return false;
}
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that the directory handle is valid. */
if (param->handle >= util::size(m_directories) || m_directories[param->handle].handle == nullptr) {
response_header.result = fs::ResultDataCorrupted();
break;
}
/* Lock the filesystem. */
std::scoped_lock lk2(m_fs_mutex);
/* Close the directory. */
fs::CloseDirectory(m_directories[param->handle]);
m_directories[param->handle].handle = {};
--m_open_directory_count;
}
break;
case PacketType::RenameDirectory:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const RenameDirectoryParam *>(body);
if (header->body_size != sizeof(*param) + param->old_len + param->new_len) {
return false;
}
/* Delete the directory. */
const char *old_path = param->data + 0;
const char *new_path = param->data + param->old_len;
response_header.result = fs::RenameDirectory(old_path, new_path);
}
break;
case PacketType::CreateFile:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const CreateFileParam *>(body);
if (header->body_size != sizeof(*param) + param->path_len) {
return false;
}
/* Create the file. */
response_header.result = fs::CreateFile(param->path, param->size, static_cast<int>(param->option));
}
break;
case PacketType::DeleteFile:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const DeleteFileParam *>(body);
if (header->body_size != sizeof(*param) + param->path_len) {
return false;
}
/* Delete the file. */
response_header.result = fs::DeleteFile(param->path);
}
break;
case PacketType::OpenFile:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const OpenFileParam *>(body);
if (header->body_size != sizeof(*param) + param->path_len) {
return false;
}
/* Open the file. */
fs::FileHandle handle;
response_header.result = fs::OpenFile(std::addressof(handle), param->path, param->mode);
if (R_SUCCEEDED(response_header.result)) {
std::scoped_lock lk(m_mutex);
if (m_open_file_count < util::size(m_files)) {
/* Insert the file into our table. */
u64 index = std::numeric_limits<u64>::max();
for (size_t i = 0; i < util::size(m_files); ++i) {
if (m_files[i].handle == nullptr) {
m_files[i] = handle;
index = i;
++m_open_file_count;
break;
}
}
AMS_ABORT_UNLESS(index < util::size(m_files));
/* Return the index. */
response_header.body_size = sizeof(index);
std::memcpy(body, std::addressof(index), sizeof(index));
} else {
/* We can't actually open the file. */
fs::CloseFile(handle);
response_header.result = fs::ResultOpenCountLimit();
}
}
}
break;
case PacketType::FlushFile:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const FlushFileParam *>(body);
if (header->body_size != sizeof(*param)) {
return false;
}
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that the file handle is valid. */
if (param->handle >= util::size(m_files) || m_files[param->handle].handle == nullptr) {
response_header.result = fs::ResultDataCorrupted();
break;
}
/* Lock the filesystem. */
std::scoped_lock lk2(m_fs_mutex);
/* Flush the file. */
response_header.result = fs::FlushFile(m_files[param->handle]);
}
break;
case PacketType::CloseFile:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const CloseFileParam *>(body);
if (header->body_size != sizeof(*param)) {
return false;
}
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that the file handle is valid. */
if (param->handle >= util::size(m_files) || m_files[param->handle].handle == nullptr) {
response_header.result = fs::ResultDataCorrupted();
break;
}
/* Lock the filesystem. */
std::scoped_lock lk2(m_fs_mutex);
/* Close the directory. */
fs::CloseFile(m_files[param->handle]);
m_files[param->handle].handle = {};
--m_open_file_count;
}
break;
case PacketType::RenameFile:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const RenameFileParam *>(body);
if (header->body_size != sizeof(*param) + param->old_len + param->new_len) {
return false;
}
/* Delete the directory. */
const char *old_path = param->data + 0;
const char *new_path = param->data + param->old_len;
response_header.result = fs::RenameFile(old_path, new_path);
}
break;
case PacketType::ReadFile:
{
/* Get the parameters. */
const auto param = *reinterpret_cast<const ReadFileParam *>(body);
if (header->body_size != sizeof(param)) {
return false;
}
/* Check that the read is valid. */
if (param.size + sizeof(u64) > m_request_buffer_size) {
response_header.result = fs::ResultDataCorrupted();
break;
}
/* Prepare response variables. */
u64 *out_size = reinterpret_cast<u64 *>(body);
void *dst = out_size + 1;
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that the file handle is valid. */
if (param.handle >= util::size(m_files) || m_files[param.handle].handle == nullptr) {
response_header.result = fs::ResultDataCorrupted();
break;
}
/* Read the file. */
size_t read_size;
response_header.result = fs::ReadFile(std::addressof(read_size), m_files[param.handle], param.offset, dst, param.size);
if (R_SUCCEEDED(response_header.result)) {
*out_size = read_size;
response_header.body_size = sizeof(u64) + read_size;
}
}
break;
case PacketType::WriteFile:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const WriteFileParam *>(body);
if (header->body_size != sizeof(*param) + param->size) {
return false;
}
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that the file handle is valid. */
if (param->handle >= util::size(m_files) || m_files[param->handle].handle == nullptr) {
response_header.result = fs::ResultDataCorrupted();
break;
}
/* Lock the filesystem. */
std::scoped_lock lk2(m_fs_mutex);
/* Write the file. */
response_header.result = fs::WriteFile(m_files[param->handle], param->offset, body + sizeof(*param), param->size, param->option);
}
break;
case PacketType::GetEntryType:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const GetEntryTypeParam *>(body);
if (header->body_size != sizeof(*param) + param->path_len) {
return false;
}
/* Get the entry type. */
fs::DirectoryEntryType type;
response_header.result = fs::GetEntryType(std::addressof(type), param->path);
if (R_SUCCEEDED(response_header.result)) {
/* Return the type. */
response_header.body_size = sizeof(type);
std::memcpy(body, std::addressof(type), sizeof(type));
static_assert(sizeof(type) == sizeof(u32));
}
}
break;
case PacketType::ReadDirectory:
{
/* Get the parameters. */
const auto param = *reinterpret_cast<const ReadDirectoryParam *>(body);
if (header->body_size != sizeof(param)) {
return false;
}
/* Check that the read is valid. */
if (sizeof(s64) + param.count * sizeof(fs::DirectoryEntry) > m_request_buffer_size) {
response_header.result = fs::ResultDataCorrupted();
break;
}
/* Prepare response variables. */
s64 *out_count = reinterpret_cast<s64 *>(body);
fs::DirectoryEntry *dst = reinterpret_cast<fs::DirectoryEntry *>(out_count + 1);
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that the directory handle is valid. */
if (param.handle >= util::size(m_directories) || m_directories[param.handle].handle == nullptr) {
response_header.result = fs::ResultDataCorrupted();
break;
}
/* Read the directory. */
response_header.result = fs::ReadDirectory(out_count, dst, m_directories[param.handle], param.count);
if (R_SUCCEEDED(response_header.result)) {
response_header.body_size = sizeof(s64) + *out_count * sizeof(fs::DirectoryEntry);
}
}
break;
case PacketType::GetFileSize:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const GetFileSizeParam *>(body);
if (header->body_size != sizeof(*param)) {
return false;
}
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that the file handle is valid. */
if (param->handle >= util::size(m_files) || m_files[param->handle].handle == nullptr) {
response_header.result = fs::ResultDataCorrupted();
break;
}
/* Get the file size. */
response_header.result = fs::GetFileSize(reinterpret_cast<s64 *>(body), m_files[param->handle]);
if (R_SUCCEEDED(response_header.result)) {
response_header.body_size = sizeof(s64);
}
}
break;
case PacketType::SetFileSize:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const SetFileSizeParam *>(body);
if (header->body_size != sizeof(*param)) {
return false;
}
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that the file handle is valid. */
if (param->handle >= util::size(m_files) || m_files[param->handle].handle == nullptr) {
response_header.result = fs::ResultDataCorrupted();
break;
}
/* Lock the filesystem. */
std::scoped_lock lk2(m_fs_mutex);
/* Get the file size. */
response_header.result = fs::SetFileSize(m_files[param->handle], param->size);
}
break;
case PacketType::GetTotalSpaceSize:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const GetTotalSpaceSizeParam *>(body);
if (header->body_size != sizeof(*param) + param->path_len) {
return false;
}
/* Get the total space size. */
s64 size;
response_header.result = fs::GetTotalSpaceSize(std::addressof(size), param->path);
if (R_SUCCEEDED(response_header.result)) {
/* Return the size. */
response_header.body_size = sizeof(size);
std::memcpy(body, std::addressof(size), sizeof(size));
}
}
break;
case PacketType::GetFreeSpaceSize:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const GetFreeSpaceSizeParam *>(body);
if (header->body_size != sizeof(*param) + param->path_len) {
return false;
}
/* Get the free space size. */
s64 size;
response_header.result = fs::GetFreeSpaceSize(std::addressof(size), param->path);
if (R_SUCCEEDED(response_header.result)) {
/* Return the size. */
response_header.body_size = sizeof(size);
std::memcpy(body, std::addressof(size), sizeof(size));
}
}
break;
case PacketType::Stat:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const StatParam *>(body);
if (header->body_size != sizeof(*param) + param->path_len) {
return false;
}
/* Prepare a response stat structure. */
struct {
fs::DirectoryEntryType type;
s64 file_size;
fs::FileTimeStampRaw file_timestamp;
} out = {};
static_assert(sizeof(out) == 0x30);
/* Get the entry type. */
response_header.result = fs::GetEntryType(std::addressof(out.type), param->path);
if (R_FAILED(response_header.result)) {
break;
}
/* If the path is a file, get further information. */
if (out.type == fs::DirectoryEntryType_File) {
/* Try to get the file size. */
{
fs::FileHandle handle;
const auto open_result = fs::OpenFile(std::addressof(handle), param->path, fs::OpenMode_Read);
if (R_SUCCEEDED(open_result)) {
ON_SCOPE_EXIT { fs::CloseFile(handle); };
response_header.result = fs::GetFileSize(std::addressof(out.file_size), handle);
if (R_FAILED(response_header.result)) {
break;
}
} else {
if (fs::ResultTargetLocked::Includes(open_result)) {
out.file_size = 0;
} else {
response_header.result = open_result;
break;
}
}
}
/* Get the file timestamp. */
response_header.result = fs::impl::GetFileTimeStampRawForDebug(std::addressof(out.file_timestamp), param->path);
if (R_FAILED(response_header.result)) {
break;
}
}
/* If we successfully got the stat information, send it as response. */
if (R_SUCCEEDED(response_header.result)) {
response_header.body_size = sizeof(out);
std::memcpy(body, std::addressof(out), sizeof(out));
}
}
break;
case PacketType::ListDirectory:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const ListDirectoryParam *>(body);
if (header->body_size != sizeof(*param) + param->path_len) {
return false;
}
/* Open the directory. */
fs::DirectoryHandle handle;
response_header.result = fs::OpenDirectory(std::addressof(handle), param->path, fs::OpenDirectoryMode_All);
if (R_FAILED(response_header.result)) {
break;
}
/* When we're done, close the handle. */
ON_SCOPE_EXIT { fs::CloseDirectory(handle); };
/* Get the directory entry count. */
s64 count;
response_header.result = fs::GetDirectoryEntryCount(std::addressof(count), handle);
if (R_FAILED(response_header.result)) {
break;
}
/* Determine whether we can send the response in one go. */
const size_t needed_size = sizeof(s64) + sizeof(u64) + sizeof(fs::DirectoryEntry) * count;
if (needed_size <= m_request_buffer_size) {
/* We can perform the entire read in one send. */
struct {
s64 count;
u64 size;
fs::DirectoryEntry entries[];
} *out = reinterpret_cast<decltype(out)>(body);
s64 read_count;
response_header.result = fs::ReadDirectory(std::addressof(read_count), out->entries, handle, count);
if (R_FAILED(response_header.result)) {
break;
}
/* Set the output. */
out->count = read_count;
out->size = read_count * sizeof(fs::DirectoryEntry);
/* Set the response body size. */
response_header.body_size = sizeof(*out) + out->size;
} else {
/* We have to use multiple sends. */
/* Lock our server. */
std::scoped_lock lk(m_htcs_server.GetMutex());
/* Send the response header. */
response_header.body_size = needed_size;
if (m_htcs_server.Send(socket, std::addressof(header), sizeof(header), 0) != sizeof(header)) {
return false;
}
/* Send the body header. */
struct {
s64 count;
u64 size;
} out = { count, count * sizeof(fs::DirectoryEntry) };
if (m_htcs_server.Send(socket, std::addressof(out), sizeof(out), 0) != sizeof(out)) {
return false;
}
/* Loop sending entries. */
s64 remaining = count;
do {
/* Determine how many entries we can read. */
const s64 cur = std::min<s64>(remaining, static_cast<s64>(m_request_buffer_size / sizeof(fs::DirectoryEntry)));
/* NOTE: Nintendo does not check the output of this call. */
s64 read_count = 0;
fs::ReadDirectory(std::addressof(read_count), reinterpret_cast<fs::DirectoryEntry *>(body), handle, cur);
/* Send the current entries. */
const ssize_t cur_size = read_count * sizeof(fs::DirectoryEntry);
if (m_htcs_server.Send(socket, body, cur_size, 0) != cur_size) {
return false;
}
/* Advance. */
remaining -= read_count;
} while (remaining > 0);
/* We've sent the entirety of our response, so early return. */
return true;
}
}
break;
default:
/* Unsupported packet. */
return false;
}
/* Send the response. */
return this->SendResponse(response_header, body, socket);
} else if (m_is_mounted) {
/* The SD card is mounted but not inserted, so we should unmount it. */
this->Unmount();
}
/* We failed to process the request due to SD card not being inserted or mounted. */
response_header.result = fs::ResultSdCardAccessFailed();
return this->SendResponse(response_header, body, socket);
}
bool FileServerProcessor::SendResponse(const FileServerResponseHeader &header, const void *body, int socket) {
/* Lock our server. */
std::scoped_lock lk(m_htcs_server.GetMutex());
/* Send the response header. */
if (m_htcs_server.Send(socket, std::addressof(header), sizeof(header), 0) != sizeof(header)) {
return false;
}
/* If we don't have a body, we're done. */
if (header.body_size == 0) {
return true;
}
/* Send the body. */
return m_htcs_server.Send(socket, body, header.body_size, 0) == header.body_size;
}
}
| 34,475
|
C++
|
.cpp
| 635
| 30.447244
| 153
| 0.414701
|
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,239
|
tio_main.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/TioServer/source/tio_main.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "tio_file_server.hpp"
namespace ams {
namespace tio {
namespace {
alignas(0x40) constinit u8 g_fs_heap_buffer[64_KB];
alignas(0x40) constinit u8 g_htcs_buffer[1_KB];
lmem::HeapHandle g_fs_heap_handle;
void *AllocateForFs(size_t size) {
return lmem::AllocateFromExpHeap(g_fs_heap_handle, size);
}
void DeallocateForFs(void *p, size_t size) {
AMS_UNUSED(size);
return lmem::FreeToExpHeap(g_fs_heap_handle, p);
}
void InitializeFsHeap() {
/* Setup fs allocator. */
g_fs_heap_handle = lmem::CreateExpHeap(g_fs_heap_buffer, sizeof(g_fs_heap_buffer), lmem::CreateOption_ThreadSafe);
}
}
}
namespace init {
void InitializeSystemModule() {
/* Initialize heap. */
tio::InitializeFsHeap();
/* Initialize our connection to sm. */
R_ABORT_UNLESS(sm::Initialize());
/* Initialize fs. */
fs::InitializeForSystem();
fs::SetAllocator(tio::AllocateForFs, tio::DeallocateForFs);
fs::SetEnabledAutoAbort(false);
/* Verify that we can sanely execute. */
ams::CheckApiVersion();
}
void FinalizeSystemModule() { /* ... */ }
void Startup() { /* ... */ }
}
void Main() {
/* Set thread name. */
os::SetThreadNamePointer(os::GetCurrentThread(), AMS_GET_SYSTEM_THREAD_NAME(TioServer, Main));
AMS_ASSERT(os::GetThreadPriority(os::GetCurrentThread()) == AMS_GET_SYSTEM_THREAD_PRIORITY(TioServer, Main));
/* Initialize htcs. */
constexpr auto HtcsSocketCountMax = 2;
const size_t buffer_size = htcs::GetWorkingMemorySize(HtcsSocketCountMax);
AMS_ABORT_UNLESS(sizeof(tio::g_htcs_buffer) >= buffer_size);
htcs::InitializeForSystem(tio::g_htcs_buffer, buffer_size, HtcsSocketCountMax);
/* Initialize the file server. */
tio::InitializeFileServer();
/* Start the file server. */
tio::StartFileServer();
/* Wait for the file server to finish. */
tio::WaitFileServer();
}
}
| 2,926
|
C++
|
.cpp
| 69
| 33.724638
| 130
| 0.622661
|
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,240
|
tio_file_server.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/TioServer/source/tio_file_server.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "tio_file_server.hpp"
#include "tio_file_server_packet.hpp"
#include "tio_file_server_htcs_server.hpp"
#include "tio_file_server_processor.hpp"
#include "tio_sd_card_observer.hpp"
namespace ams::tio {
namespace {
constexpr inline auto NumDispatchThreads = 2;
constexpr inline auto DispatchThreadPriority = 21;
constexpr inline size_t RequestBufferSize = 1_MB + util::AlignUp(0x40 + fs::EntryNameLengthMax, 1_KB);
struct FileServerRequest {
int socket;
FileServerRequestHeader header;
u8 body[RequestBufferSize];
};
constexpr const char HtcsPortName[] = "iywys@$TioServer_FileServer";
alignas(os::ThreadStackAlignment) u8 g_server_stack[os::MemoryPageSize];
alignas(os::ThreadStackAlignment) u8 g_observer_stack[os::MemoryPageSize];
alignas(os::ThreadStackAlignment) u8 g_dispatch_stacks[NumDispatchThreads][os::MemoryPageSize];
constinit FileServerHtcsServer g_file_server_htcs_server;
constinit FileServerProcessor g_file_server_processor(g_file_server_htcs_server);
constinit SdCardObserver g_sd_card_observer;
constinit os::ThreadType g_file_server_dispatch_threads[NumDispatchThreads];
constinit FileServerRequest g_requests[NumDispatchThreads];
constinit os::MessageQueueType g_free_mq;
constinit os::MessageQueueType g_dispatch_mq;
constinit uintptr_t g_free_mq_storage[NumDispatchThreads];
constinit uintptr_t g_dispatch_mq_storage[NumDispatchThreads];
void OnSdCardInsertionChanged(bool inserted) {
g_file_server_processor.SetInserted(inserted);
}
void OnFileServerHtcsSocketAccepted(int fd) {
/* Service requests, while we can. */
while (true) {
/* Receive a free request. */
uintptr_t request_address;
os::ReceiveMessageQueue(std::addressof(request_address), std::addressof(g_free_mq));
/* Ensure we manage our request properly. */
auto req_guard = SCOPE_GUARD { os::SendMessageQueue(std::addressof(g_free_mq), request_address); };
/* Receive the request header. */
FileServerRequest *request = reinterpret_cast<FileServerRequest *>(request_address);
if (htcs::Recv(fd, std::addressof(request->header), sizeof(request->header), htcs::HTCS_MSG_WAITALL) != sizeof(request->header)) {
break;
}
/* Receive the request body, if necessary. */
if (request->header.body_size > 0) {
if (htcs::Recv(fd, request->body, request->header.body_size, htcs::HTCS_MSG_WAITALL) != request->header.body_size) {
break;
}
}
/* Dispatch the request. */
req_guard.Cancel();
request->socket = fd;
os::SendMessageQueue(std::addressof(g_dispatch_mq), request_address);
}
/* Our socket is no longer making requests, so close it. */
htcs::Close(fd);
/* Clean up any server resources. */
g_file_server_processor.Unmount();
}
void FileServerDispatchThreadFunction(void *) {
while (true) {
/* Receive a request. */
uintptr_t request_address;
os::ReceiveMessageQueue(std::addressof(request_address), std::addressof(g_dispatch_mq));
/* Process the request. */
FileServerRequest *request = reinterpret_cast<FileServerRequest *>(request_address);
if (!g_file_server_processor.ProcessRequest(std::addressof(request->header), request->body, request->socket)) {
htcs::Close(request->socket);
}
/* Free the request. */
os::SendMessageQueue(std::addressof(g_free_mq), request_address);
}
}
}
void InitializeFileServer() {
/* Initialize the htcs server. */
g_file_server_htcs_server.Initialize(HtcsPortName, g_server_stack, sizeof(g_server_stack), OnFileServerHtcsSocketAccepted);
/* Initialize SD card observer. */
g_sd_card_observer.Initialize(g_observer_stack, sizeof(g_observer_stack));
g_sd_card_observer.SetCallback(OnSdCardInsertionChanged);
/* Initialize the command processor. */
g_file_server_processor.SetInserted(g_sd_card_observer.IsSdCardInserted());
g_file_server_processor.SetRequestBufferSize(RequestBufferSize);
/* Initialize the dispatch message queues. */
os::InitializeMessageQueue(std::addressof(g_free_mq), g_free_mq_storage, util::size(g_free_mq_storage));
os::InitializeMessageQueue(std::addressof(g_dispatch_mq), g_dispatch_mq_storage, util::size(g_dispatch_mq_storage));
/* Begin with all requests free. */
for (auto i = 0; i < NumDispatchThreads; ++i) {
os::SendMessageQueue(std::addressof(g_free_mq), reinterpret_cast<uintptr_t>(g_requests + i));
}
/* Initialize the dispatch threads. */
/* NOTE: Nintendo does not name these threads. */
for (auto i = 0; i < NumDispatchThreads; ++i) {
R_ABORT_UNLESS(os::CreateThread(g_file_server_dispatch_threads + i, FileServerDispatchThreadFunction, nullptr, g_dispatch_stacks + i, sizeof(g_dispatch_stacks[i]), DispatchThreadPriority));
}
}
void StartFileServer() {
/* Start the htcs server. */
g_file_server_htcs_server.Start();
/* Start the dispatch threads. */
for (auto i = 0; i < NumDispatchThreads; ++i) {
os::StartThread(g_file_server_dispatch_threads + i);
}
}
void WaitFileServer() {
/* Wait for the htcs server to finish. */
g_file_server_htcs_server.Wait();
}
}
| 6,639
|
C++
|
.cpp
| 126
| 42.436508
| 201
| 0.64095
|
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,241
|
tio_file_server_htcs_server.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/TioServer/source/tio_file_server_htcs_server.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "tio_file_server_htcs_server.hpp"
namespace ams::tio {
void FileServerHtcsServer::Initialize(const char *port_name, void *thread_stack, size_t thread_stack_size, SocketAcceptedCallback on_socket_accepted) {
/* Set our port name. */
std::strcpy(m_port_name.name, port_name);
/* Set our callback. */
m_on_socket_accepted = on_socket_accepted;
/* Setup our thread. */
R_ABORT_UNLESS(os::CreateThread(std::addressof(m_thread), ThreadEntry, this, thread_stack, thread_stack_size, AMS_GET_SYSTEM_THREAD_PRIORITY(TioServer, FileServerHtcsServer)));
/* Set our thread name pointer. */
os::SetThreadNamePointer(std::addressof(m_thread), AMS_GET_SYSTEM_THREAD_NAME(TioServer, FileServerHtcsServer));
}
void FileServerHtcsServer::Start() {
os::StartThread(std::addressof(m_thread));
}
void FileServerHtcsServer::Wait() {
os::WaitThread(std::addressof(m_thread));
}
void FileServerHtcsServer::ThreadFunc() {
/* Loop forever, servicing sockets. */
while (true) {
/* Get a socket. */
int fd;
while ((fd = htcs::Socket()) == -1) {
os::SleepThread(TimeSpan::FromSeconds(1));
}
/* Ensure we cleanup the socket when we're done with it. */
ON_SCOPE_EXIT {
htcs::Close(fd);
os::SleepThread(TimeSpan::FromSeconds(1));
};
/* Create a sock addr for our server. */
htcs::SockAddrHtcs addr;
addr.family = htcs::HTCS_AF_HTCS;
addr.peer_name = htcs::GetPeerNameAny();
addr.port_name = m_port_name;
/* Bind. */
if (htcs::Bind(fd, std::addressof(addr)) == -1) {
continue;
}
/* Listen on our port. */
while (htcs::Listen(fd, 0) == 0) {
/* Continue accepting clients, so long as we can. */
int client_fd;
while (true) {
/* Try to accept a client. */
if (client_fd = htcs::Accept(fd, std::addressof(addr)); client_fd < 0) {
break;
}
/* Handle the client. */
m_on_socket_accepted(client_fd);
}
/* NOTE: This seems unnecessary (client_fd guaranteed < 0 here), but Nintendo does it. */
htcs::Close(client_fd);
}
}
}
ssize_t FileServerHtcsServer::Send(s32 desc, const void *buffer, size_t buffer_size, s32 flags) {
AMS_ASSERT(m_mutex.IsLockedByCurrentThread());
return htcs::Send(desc, buffer, buffer_size, flags);
}
}
| 3,433
|
C++
|
.cpp
| 78
| 34.179487
| 184
| 0.591018
|
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,242
|
boot2_main.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/boot2/source/boot2_main.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams {
namespace boot2 {
namespace {
constinit u8 g_fs_heap_memory[2_KB];
constinit lmem::HeapHandle g_fs_heap_handle;
void *AllocateForFs(size_t size) {
return lmem::AllocateFromExpHeap(g_fs_heap_handle, size);
}
void DeallocateForFs(void *p, size_t size) {
AMS_UNUSED(size);
return lmem::FreeToExpHeap(g_fs_heap_handle, p);
}
void InitializeFsHeap() {
g_fs_heap_handle = lmem::CreateExpHeap(g_fs_heap_memory, sizeof(g_fs_heap_memory), lmem::CreateOption_None);
}
}
}
namespace init {
void InitializeSystemModule() {
/* Initialize heap. */
boot2::InitializeFsHeap();
/* Initialize our connection to sm. */
R_ABORT_UNLESS(sm::Initialize());
/* Initialize fs. */
fs::InitializeForSystem();
fs::SetAllocator(boot2::AllocateForFs, boot2::DeallocateForFs);
fs::SetEnabledAutoAbort(false);
/* Initialize other services we need. */
R_ABORT_UNLESS(pmbmInitialize());
R_ABORT_UNLESS(pminfoInitialize());
R_ABORT_UNLESS(pmshellInitialize());
R_ABORT_UNLESS(setsysInitialize());
gpio::Initialize();
ncm::Initialize();
/* Mount the SD card. */
R_ABORT_UNLESS(fs::MountSdCard("sdmc"));
/* Verify that we can sanely execute. */
ams::CheckApiVersion();
}
void FinalizeSystemModule() { /* ... */ }
void Startup() { /* ... */ }
}
void Main() {
/* Set thread name. */
os::SetThreadNamePointer(os::GetCurrentThread(), AMS_GET_SYSTEM_THREAD_NAME(boot2, Main));
AMS_ASSERT(os::GetThreadPriority(os::GetCurrentThread()) == AMS_GET_SYSTEM_THREAD_PRIORITY(boot2, Main));
/* Launch all programs off of SYSTEM/the SD. */
boot2::LaunchPostSdCardBootPrograms();
}
}
| 2,733
|
C++
|
.cpp
| 66
| 32.287879
| 124
| 0.609452
|
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,243
|
erpt_main.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/erpt/source/erpt_main.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams {
namespace erpt {
namespace {
constexpr size_t MemoryHeapSize = 196_KB;
alignas(os::MemoryPageSize) u8 g_memory_heap[MemoryHeapSize];
}
int MakeProductModelString(char *dst, size_t dst_size, settings::system::ProductModel model) {
switch (model) {
case settings::system::ProductModel_Invalid: return util::Strlcpy(dst, "Invalid", static_cast<int>(dst_size));
case settings::system::ProductModel_Nx: return util::Strlcpy(dst, "NX", static_cast<int>(dst_size));
default: return util::SNPrintf(dst, dst_size, "%d", static_cast<int>(model));
}
}
const char *GetRegionString(settings::system::RegionCode code) {
switch (code) {
case settings::system::RegionCode_Japan: return "Japan";
case settings::system::RegionCode_Usa: return "Usa";
case settings::system::RegionCode_Europe: return "Europe";
case settings::system::RegionCode_Australia: return "Australia";
case settings::system::RegionCode_HongKongTaiwanKorea: return "HongKongTaiwanKorea";
case settings::system::RegionCode_China: return "China";
default: return "RegionUnknown";
}
}
}
namespace init {
void InitializeSystemModule() {
/* Initialize our connection to sm. */
R_ABORT_UNLESS(sm::Initialize());
/* Initialize services we need (which won't be initialized later). */
R_ABORT_UNLESS(setInitialize());
R_ABORT_UNLESS(setsysInitialize());
R_ABORT_UNLESS(pscmInitialize());
R_ABORT_UNLESS(time::Initialize());
if (hos::GetVersion() >= hos::Version_11_0_0) {
R_ABORT_UNLESS(ectxrInitialize());
}
/* Verify that we can sanely execute. */
ams::CheckApiVersion();
}
void FinalizeSystemModule() { /* ... */ }
void Startup() { /* ... */ }
}
void Main() {
/* Set thread name. */
os::SetThreadNamePointer(os::GetCurrentThread(), AMS_GET_SYSTEM_THREAD_NAME(erpt, Main));
AMS_ASSERT(os::GetThreadPriority(os::GetCurrentThread()) == AMS_GET_SYSTEM_THREAD_PRIORITY(erpt, Main));
/* Decide whether or not to clean up reports periodically. */
{
u8 disable_report_cleanup = 0;
if (settings::fwdbg::GetSettingsItemValue(std::addressof(disable_report_cleanup), sizeof(disable_report_cleanup), "erpt", "disable_automatic_report_cleanup") == sizeof(disable_report_cleanup)) {
erpt::srv::SetEnabledAutomaticReportCleanup(disable_report_cleanup == 0);
} else {
erpt::srv::SetEnabledAutomaticReportCleanup(true);
}
}
/* Set the memory heap for erpt::srv namespace, perform other service init/etc. */
R_ABORT_UNLESS(erpt::srv::Initialize(erpt::g_memory_heap, erpt::MemoryHeapSize));
/* Atmosphere always wants to redirect new reports to the SD card, to prevent them from being logged. */
erpt::srv::SetRedirectNewReportsToSdCard(true);
/* Configure the OS version. */
{
settings::system::FirmwareVersion firmware_version = {};
settings::system::SerialNumber serial_number = {};
settings::system::GetFirmwareVersion(std::addressof(firmware_version));
settings::system::GetSerialNumber(std::addressof(serial_number));
char os_private[0x60];
const auto os_priv_len = util::SNPrintf(os_private, sizeof(os_private), "%s (%.8s)", firmware_version.display_name, firmware_version.revision);
AMS_ASSERT(static_cast<size_t>(os_priv_len) < sizeof(os_private));
AMS_UNUSED(os_priv_len);
R_ABORT_UNLESS(erpt::srv::SetSerialNumberAndOsVersion(serial_number.str,
strnlen(serial_number.str, sizeof(serial_number.str) - 1) + 1,
firmware_version.display_version,
strnlen(firmware_version.display_version, sizeof(firmware_version.display_version) - 1) + 1,
os_private,
strnlen(os_private, sizeof(os_private) - 1) + 1));
}
/* Configure the product model. */
{
char product_model[0x10];
const auto pm_len = erpt::MakeProductModelString(product_model, sizeof(product_model), settings::system::GetProductModel());
AMS_ASSERT(static_cast<size_t>(pm_len) < sizeof(product_model));
AMS_UNUSED(pm_len);
R_ABORT_UNLESS(erpt::srv::SetProductModel(product_model, static_cast<u32>(std::strlen(product_model))));
}
/* Configure the region. */
{
settings::system::RegionCode code;
settings::system::GetRegionCode(std::addressof(code));
const char *region_str = erpt::GetRegionString(code);
R_ABORT_UNLESS(erpt::srv::SetRegionSetting(region_str, static_cast<u32>(std::strlen(region_str))));
}
/* Start the erpt server. */
R_ABORT_UNLESS(erpt::srv::InitializeAndStartService());
/* Launch sprofile on 13.0.0+ */
if (hos::GetVersion() >= hos::Version_13_0_0) {
/* Initialize the sprofile server. */
sprofile::srv::Initialize();
/* Start the sprofile ipc server. */
sprofile::srv::StartIpcServer();
}
/* Wait forever. */
erpt::srv::Wait();
}
}
| 6,671
|
C++
|
.cpp
| 121
| 42.479339
| 206
| 0.581442
|
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,244
|
eclct_stub.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/eclct.stub/source/eclct_stub.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams {
namespace init {
void InitializeSystemModule() { /* ... */ }
void FinalizeSystemModule() { /* ... */ }
void Startup() { /* ... */ }
}
void Main() {
/* ... */
}
}
| 898
|
C++
|
.cpp
| 26
| 30.807692
| 76
| 0.677868
|
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,245
|
ncm_main.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/ncm/source/ncm_main.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams {
namespace ncm {
namespace {
u8 g_heap_memory[1_MB];
lmem::HeapHandle g_heap_handle;
void *Allocate(size_t size) {
void *mem = lmem::AllocateFromExpHeap(g_heap_handle, size);
ncm::GetHeapState().Allocate(size);
return mem;
}
void Deallocate(void *p, size_t size) {
ncm::GetHeapState().Free(size != 0 ? size : lmem::GetExpHeapMemoryBlockSize(p));
lmem::FreeToExpHeap(g_heap_handle, p);
}
void InitializeHeap() {
g_heap_handle = lmem::CreateExpHeap(g_heap_memory, sizeof(g_heap_memory), lmem::CreateOption_ThreadSafe);
ncm::GetHeapState().Initialize(g_heap_handle);
}
}
namespace {
struct ContentManagerServerOptions {
static constexpr size_t PointerBufferSize = 0x400;
static constexpr size_t MaxDomains = 0;
static constexpr size_t MaxDomainObjects = 0;
static constexpr bool CanDeferInvokeRequest = false;
static constexpr bool CanManageMitmServers = false;
};
constexpr inline size_t ContentManagerNumServers = 1;
constexpr inline size_t ContentManagerManagerSessions = 16;
constexpr inline size_t ContentManagerExtraSessions = 16;
constexpr inline size_t ContentManagerMaxSessions = ContentManagerManagerSessions + ContentManagerExtraSessions;
constexpr inline sm::ServiceName ContentManagerServiceName = sm::ServiceName::Encode("ncm");
alignas(os::ThreadStackAlignment) u8 g_content_manager_thread_stack[16_KB];
alignas(os::ThreadStackAlignment) u8 g_location_resolver_thread_stack[16_KB];
class ContentManagerServerManager : public sf::hipc::ServerManager<ContentManagerNumServers, ContentManagerServerOptions, ContentManagerMaxSessions> {
private:
using ServiceImpl = ncm::ContentManagerImpl;
private:
os::ThreadType m_thread;
sf::SharedPointer<ncm::IContentManager> m_manager;
private:
static void ThreadFunction(void *_this) {
reinterpret_cast<ContentManagerServerManager *>(_this)->LoopProcess();
}
public:
explicit ContentManagerServerManager(sf::SharedPointer<ncm::IContentManager> manager) : m_manager(manager) { /* ... */ }
ams::Result Initialize() {
R_RETURN(this->RegisterObjectForServer(m_manager, ContentManagerServiceName, ContentManagerManagerSessions));
}
ams::Result StartThreads() {
R_TRY(os::CreateThread(std::addressof(m_thread), ThreadFunction, this, g_content_manager_thread_stack, sizeof(g_content_manager_thread_stack), AMS_GET_SYSTEM_THREAD_PRIORITY(ncm, ContentManagerServerIpcSession)));
os::SetThreadNamePointer(std::addressof(m_thread), AMS_GET_SYSTEM_THREAD_NAME(ncm, ContentManagerServerIpcSession));
os::StartThread(std::addressof(m_thread));
R_SUCCEED();
}
void Wait() {
os::WaitThread(std::addressof(m_thread));
}
};
struct LocationResolverServerOptions {
static constexpr size_t PointerBufferSize = 0x400;
static constexpr size_t MaxDomains = 0;
static constexpr size_t MaxDomainObjects = 0;
static constexpr bool CanDeferInvokeRequest = false;
static constexpr bool CanManageMitmServers = false;
};
constexpr inline size_t LocationResolverNumServers = 1;
constexpr inline size_t LocationResolverManagerSessions = 16;
constexpr inline size_t LocationResolverExtraSessions = 16;
constexpr inline size_t LocationResolverMaxSessions = LocationResolverManagerSessions + LocationResolverExtraSessions;
constexpr inline sm::ServiceName LocationResolverServiceName = sm::ServiceName::Encode("lr");
class LocationResolverServerManager : public sf::hipc::ServerManager<LocationResolverNumServers, LocationResolverServerOptions, LocationResolverMaxSessions> {
private:
using ServiceImpl = lr::LocationResolverManagerImpl;
private:
os::ThreadType m_thread;
sf::SharedPointer<lr::ILocationResolverManager> m_manager;
private:
static void ThreadFunction(void *_this) {
reinterpret_cast<LocationResolverServerManager *>(_this)->LoopProcess();
}
public:
LocationResolverServerManager(sf::SharedPointer<lr::ILocationResolverManager> manager) : m_manager(manager) { /* ... */ }
ams::Result Initialize() {
R_RETURN(this->RegisterObjectForServer(m_manager, LocationResolverServiceName, LocationResolverManagerSessions));
}
ams::Result StartThreads() {
R_TRY(os::CreateThread(std::addressof(m_thread), ThreadFunction, this, g_location_resolver_thread_stack, sizeof(g_location_resolver_thread_stack), AMS_GET_SYSTEM_THREAD_PRIORITY(ncm, LocationResolverServerIpcSession)));
os::SetThreadNamePointer(std::addressof(m_thread), AMS_GET_SYSTEM_THREAD_NAME(ncm, LocationResolverServerIpcSession));
os::StartThread(std::addressof(m_thread));
R_SUCCEED();
}
void Wait() {
os::WaitThread(std::addressof(m_thread));
}
};
sf::UnmanagedServiceObject<ncm::IContentManager, ncm::ContentManagerImpl> g_ncm_manager_service_object;
ContentManagerServerManager g_ncm_server_manager(g_ncm_manager_service_object.GetShared());
sf::UnmanagedServiceObject<lr::ILocationResolverManager, lr::LocationResolverManagerImpl> g_lr_manager_service_object;
LocationResolverServerManager g_lr_server_manager(g_lr_manager_service_object.GetShared());
/* Compile-time configuration. */
#ifdef NCM_BUILD_FOR_INTITIALIZE
constexpr inline bool BuildSystemDatabase = true;
#else
constexpr inline bool BuildSystemDatabase = false;
#endif
#ifdef NCM_BUILD_FOR_SAFEMODE
constexpr inline bool ImportSystemDatabaseFromSignedSystemPartitionOnSdCard = true;
#else
constexpr inline bool ImportSystemDatabaseFromSignedSystemPartitionOnSdCard = false;
#endif
static_assert(!(BuildSystemDatabase && ImportSystemDatabaseFromSignedSystemPartitionOnSdCard), "Invalid NCM build configuration!");
constexpr inline ncm::ContentManagerConfig ManagerConfig = { BuildSystemDatabase, ImportSystemDatabaseFromSignedSystemPartitionOnSdCard };
}
void NcmMain() {
/* Initialize spl. */
spl::Initialize();
ON_SCOPE_EXIT { spl::Finalize(); };
/* Initialize fs. */
fs::InitializeWithMultiSessionForSystem();
fs::SetAllocator(Allocate, Deallocate);
fs::SetEnabledAutoAbort(false);
/* Initialize ncm api. */
/* NOTE: Nintendo does this after initializing and starting threads. */
ncm::InitializeWithObject(g_ncm_manager_service_object.GetShared());
/* Create and initialize the content manager. */
R_ABORT_UNLESS(g_ncm_manager_service_object.GetImpl().Initialize(ManagerConfig));
/* Initialize ncm's server and start threads. */
R_ABORT_UNLESS(g_ncm_server_manager.Initialize());
R_ABORT_UNLESS(g_ncm_server_manager.StartThreads());
/* Initialize lr's server and start threads. */
R_ABORT_UNLESS(g_lr_server_manager.Initialize());
R_ABORT_UNLESS(g_lr_server_manager.StartThreads());
/* Wait indefinitely. */
g_ncm_server_manager.Wait();
g_lr_server_manager.Wait();
}
}
namespace init {
void InitializeSystemModule() {
/* Initialize heap. */
ncm::InitializeHeap();
/* Initialize our connection to sm. */
R_ABORT_UNLESS(sm::Initialize());
}
void FinalizeSystemModule() { /* ... */ }
void Startup() { /* ... */ }
}
void NORETURN Exit(int rc) {
AMS_UNUSED(rc);
AMS_ABORT("Exit called by immortal process");
}
void Main() {
/* Set thread name. */
os::SetThreadNamePointer(os::GetCurrentThread(), AMS_GET_SYSTEM_THREAD_NAME(ncm, MainWaitThreads));
AMS_ASSERT(os::GetThreadPriority(os::GetCurrentThread()) == AMS_GET_SYSTEM_THREAD_PRIORITY(ncm, MainWaitThreads));
/* Invoke NCM main. */
ncm::NcmMain();
/* This can never be reached. */
AMS_ASSUME(false);
}
}
/* Override operator new. */
void *operator new(size_t size) {
return ams::ncm::Allocate(size);
}
void *operator new(size_t size, const std::nothrow_t &) {
return ams::ncm::Allocate(size);
}
void operator delete(void *p) {
return ams::ncm::Deallocate(p, 0);
}
void operator delete(void *p, size_t size) {
return ams::ncm::Deallocate(p, size);
}
void *operator new[](size_t size) {
return ams::ncm::Allocate(size);
}
void *operator new[](size_t size, const std::nothrow_t &) {
return ams::ncm::Allocate(size);
}
void operator delete[](void *p) {
return ams::ncm::Deallocate(p, 0);
}
void operator delete[](void *p, size_t size) {
return ams::ncm::Deallocate(p, size);
}
| 10,810
|
C++
|
.cpp
| 203
| 40.817734
| 243
| 0.622393
|
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,246
|
pm_info_service.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/pm/source/pm_info_service.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "pm_info_service.hpp"
#include "impl/pm_process_manager.hpp"
#include "impl/pm_spec.hpp"
namespace ams::pm {
/* Overrides for libstratosphere pm::info commands. */
namespace info {
Result HasLaunchedBootProgram(bool *out, ncm::ProgramId program_id) {
R_RETURN(ldr::pm::HasLaunchedBootProgram(out, program_id));
}
}
/* Actual command implementations. */
Result InformationService::GetProgramId(sf::Out<ncm::ProgramId> out, os::ProcessId process_id) {
R_RETURN(impl::GetProgramId(out.GetPointer(), process_id));
}
Result InformationService::GetAppletResourceLimitCurrentValue(sf::Out<pm::ResourceLimitValue> out) {
R_RETURN(impl::GetResourceLimitCurrentValue(out.GetPointer(), ResourceLimitGroup_Applet));
}
Result InformationService::GetAppletResourceLimitPeakValue(sf::Out<pm::ResourceLimitValue> out) {
R_RETURN(impl::GetResourceLimitPeakValue(out.GetPointer(), ResourceLimitGroup_Applet));
}
/* Atmosphere extension commands. */
Result InformationService::AtmosphereGetProcessId(sf::Out<os::ProcessId> out, ncm::ProgramId program_id) {
R_RETURN(impl::GetProcessId(out.GetPointer(), program_id));
}
Result InformationService::AtmosphereHasLaunchedBootProgram(sf::Out<bool> out, ncm::ProgramId program_id) {
R_RETURN(pm::info::HasLaunchedBootProgram(out.GetPointer(), program_id));
}
Result InformationService::AtmosphereGetProcessInfo(sf::Out<ncm::ProgramLocation> out_loc, sf::Out<cfg::OverrideStatus> out_status, os::ProcessId process_id) {
/* NOTE: We don't need to worry about closing this handle, because it's an in-process copy, not a newly allocated handle. */
os::NativeHandle dummy_handle;
R_RETURN(impl::AtmosphereGetProcessInfo(&dummy_handle, out_loc.GetPointer(), out_status.GetPointer(), process_id));
}
}
| 2,563
|
C++
|
.cpp
| 49
| 47.530612
| 163
| 0.735118
|
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,247
|
pm_boot_mode_service.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/pm/source/pm_boot_mode_service.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "pm_boot_mode_service.hpp"
namespace ams::pm {
namespace {
/* Global bootmode. */
constinit BootMode g_boot_mode = BootMode::Normal;
constinit u32 g_unknown = 0;
}
/* Override of weakly linked boot_mode_api functions. */
namespace bm {
BootMode GetBootMode() {
return g_boot_mode;
}
void SetMaintenanceBoot() {
g_boot_mode = BootMode::Maintenance;
}
}
/* Service command implementations. */
void BootModeService::GetBootMode(sf::Out<u32> out) {
out.SetValue(static_cast<u32>(pm::bm::GetBootMode()));
}
void BootModeService::SetMaintenanceBoot() {
pm::bm::SetMaintenanceBoot();
}
void BootModeService::GetUnknown(sf::Out<u32> out) {
out.SetValue(g_unknown);
}
Result BootModeService::SetUnknown(u32 val) {
R_UNLESS(val <= 3, pm::ResultUnknown7());
g_unknown = val;
R_SUCCEED();
}
}
| 1,650
|
C++
|
.cpp
| 48
| 28.979167
| 76
| 0.668974
|
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,248
|
pm_shell_service.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/pm/source/pm_shell_service.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "pm_shell_service.hpp"
#include "impl/pm_process_manager.hpp"
#include "impl/pm_spec.hpp"
namespace ams::pm {
/* Overrides for libstratosphere pm::shell commands. */
namespace shell {
Result LaunchProgram(os::ProcessId *out_process_id, const ncm::ProgramLocation &loc, u32 launch_flags) {
R_RETURN(impl::LaunchProgram(out_process_id, loc, launch_flags));
}
}
/* Service command implementations. */
Result ShellService::LaunchProgram(sf::Out<os::ProcessId> out_process_id, const ncm::ProgramLocation &loc, u32 flags) {
R_RETURN(pm::shell::LaunchProgram(out_process_id.GetPointer(), loc, flags));
}
Result ShellService::TerminateProcess(os::ProcessId process_id) {
R_RETURN(impl::TerminateProcess(process_id));
}
Result ShellService::TerminateProgram(ncm::ProgramId program_id) {
R_RETURN(impl::TerminateProgram(program_id));
}
void ShellService::GetProcessEventHandle(sf::OutCopyHandle out) {
os::NativeHandle event_handle;
R_ABORT_UNLESS(impl::GetProcessEventHandle(std::addressof(event_handle)));
out.SetValue(event_handle, false);
}
void ShellService::GetProcessEventInfo(sf::Out<ProcessEventInfo> out) {
R_ABORT_UNLESS(impl::GetProcessEventInfo(out.GetPointer()));
}
Result ShellService::CleanupProcess(os::ProcessId process_id) {
R_RETURN(impl::CleanupProcess(process_id));
}
Result ShellService::ClearExceptionOccurred(os::ProcessId process_id) {
R_RETURN(impl::ClearExceptionOccurred(process_id));
}
void ShellService::NotifyBootFinished() {
R_ABORT_UNLESS(impl::NotifyBootFinished());
}
Result ShellService::GetApplicationProcessIdForShell(sf::Out<os::ProcessId> out) {
R_RETURN(impl::GetApplicationProcessId(out.GetPointer()));
}
Result ShellService::BoostSystemMemoryResourceLimit(u64 boost_size) {
R_RETURN(impl::BoostSystemMemoryResourceLimit(boost_size));
}
Result ShellService::BoostApplicationThreadResourceLimit() {
R_RETURN(impl::BoostApplicationThreadResourceLimit());
}
void ShellService::GetBootFinishedEventHandle(sf::OutCopyHandle out) {
os::NativeHandle event_handle;
R_ABORT_UNLESS(impl::GetBootFinishedEventHandle(std::addressof(event_handle)));
out.SetValue(event_handle, false);
}
Result ShellService::BoostSystemThreadResourceLimit() {
R_RETURN(impl::BoostSystemThreadResourceLimit());
}
}
| 3,193
|
C++
|
.cpp
| 71
| 39.492958
| 123
| 0.724371
|
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,249
|
pm_main.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/pm/source/pm_main.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "pm_boot_mode_service.hpp"
#include "pm_debug_monitor_service.hpp"
#include "pm_info_service.hpp"
#include "pm_shell_service.hpp"
#include "impl/pm_process_manager.hpp"
namespace ams {
namespace pm {
namespace {
constexpr u32 PrivilegedFileAccessHeader[0x1C / sizeof(u32)] = {0x00000001, 0x00000000, 0x80000000, 0x0000001C, 0x00000000, 0x0000001C, 0x00000000};
constexpr u32 PrivilegedFileAccessControl[0x2C / sizeof(u32)] = {0x00000001, 0x00000000, 0x80000000, 0x00000000, 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF};
constexpr u8 PrivilegedServiceAccessControl[] = {0x80, '*', 0x00, '*'};
constexpr size_t ProcessCountMax = 0x40;
/* This uses debugging SVCs to retrieve a process's program id. */
ncm::ProgramId GetProcessProgramId(os::ProcessId process_id) {
/* Get a debug handle. */
svc::Handle debug_handle;
R_ABORT_UNLESS(svc::DebugActiveProcess(std::addressof(debug_handle), process_id.value));
ON_SCOPE_EXIT { R_ABORT_UNLESS(svc::CloseHandle(debug_handle)); };
/* Loop until we get the event that tells us about the process. */
svc::DebugEventInfo d;
while (true) {
R_ABORT_UNLESS(svc::GetDebugEvent(std::addressof(d), debug_handle));
if (d.type == svc::DebugEvent_CreateProcess) {
return ncm::ProgramId{d.info.create_process.program_id};
}
}
}
/* This works around a bug fixed by FS in 4.0.0. */
/* Not doing so will cause KIPs with higher process IDs than 7 to be unable to use filesystem services. */
/* It also registers privileged processes with SM, so that their program ids can be known. */
void RegisterPrivilegedProcess(os::ProcessId process_id, ncm::ProgramId program_id) {
fsprUnregisterProgram(process_id.value);
fsprRegisterProgram(process_id.value, process_id.value, NcmStorageId_BuiltInSystem, PrivilegedFileAccessHeader, sizeof(PrivilegedFileAccessHeader), PrivilegedFileAccessControl, sizeof(PrivilegedFileAccessControl));
sm::manager::UnregisterProcess(process_id);
sm::manager::RegisterProcess(process_id, program_id, cfg::OverrideStatus{}, PrivilegedServiceAccessControl, sizeof(PrivilegedServiceAccessControl), PrivilegedServiceAccessControl, sizeof(PrivilegedServiceAccessControl));
}
void RegisterPrivilegedProcesses() {
/* Get privileged process range. */
os::ProcessId min_priv_process_id, max_priv_process_id;
R_ABORT_UNLESS(svc::GetSystemInfo(std::addressof(min_priv_process_id.value), svc::SystemInfoType_InitialProcessIdRange, svc::InvalidHandle, svc::InitialProcessIdRangeInfo_Minimum));
R_ABORT_UNLESS(svc::GetSystemInfo(std::addressof(max_priv_process_id.value), svc::SystemInfoType_InitialProcessIdRange, svc::InvalidHandle, svc::InitialProcessIdRangeInfo_Maximum));
/* Get current process id/program id. */
const auto cur_process_id = os::GetCurrentProcessId();
const auto cur_program_id = os::GetCurrentProgramId();
/* Get list of processes, register all privileged ones. */
s32 num_pids;
os::ProcessId pids[ProcessCountMax];
R_ABORT_UNLESS(svc::GetProcessList(std::addressof(num_pids), reinterpret_cast<u64 *>(pids), ProcessCountMax));
for (s32 i = 0; i < num_pids; i++) {
if (min_priv_process_id <= pids[i] && pids[i] <= max_priv_process_id) {
RegisterPrivilegedProcess(pids[i], pids[i] == cur_process_id ? cur_program_id : GetProcessProgramId(pids[i]));
}
}
}
}
namespace {
/* pm:shell, pm:dmnt, pm:bm, pm:info. */
enum PortIndex {
PortIndex_Shell,
PortIndex_DebugMonitor,
PortIndex_BootMode,
PortIndex_Information,
PortIndex_Count,
};
using ServerOptions = sf::hipc::DefaultServerManagerOptions;
constexpr sm::ServiceName ShellServiceName = sm::ServiceName::Encode("pm:shell");
constexpr size_t ShellMaxSessions = 8; /* Official maximum is 3. */
constexpr sm::ServiceName DebugMonitorServiceName = sm::ServiceName::Encode("pm:dmnt");
constexpr size_t DebugMonitorMaxSessions = 16;
constexpr sm::ServiceName BootModeServiceName = sm::ServiceName::Encode("pm:bm");
constexpr size_t BootModeMaxSessions = 8; /* Official maximum is 4. */
constexpr sm::ServiceName InformationServiceName = sm::ServiceName::Encode("pm:info");
constexpr size_t InformationMaxSessions = 48 - (ShellMaxSessions + DebugMonitorMaxSessions + BootModeMaxSessions);
static_assert(InformationMaxSessions >= 16, "InformationMaxSessions");
constexpr size_t MaxSessions = ShellMaxSessions + DebugMonitorMaxSessions + BootModeMaxSessions + InformationMaxSessions;
static_assert(MaxSessions == 48, "MaxSessions");
class ServerManager final : public sf::hipc::ServerManager<PortIndex_Count, ServerOptions, MaxSessions> {
private:
virtual ams::Result OnNeedsToAccept(int port_index, Server *server) override;
};
ServerManager g_server_manager;
/* NOTE: Nintendo only uses an unmanaged object for boot mode service, but no pm service has any class members/state, so we'll do it for all. */
sf::UnmanagedServiceObject<pm::impl::IShellInterface, pm::ShellService> g_shell_service;
sf::UnmanagedServiceObject<pm::impl::IDeprecatedShellInterface, pm::ShellService> g_deprecated_shell_service;
sf::UnmanagedServiceObject<pm::impl::IDebugMonitorInterface, pm::DebugMonitorService> g_dmnt_service;
sf::UnmanagedServiceObject<pm::impl::IDeprecatedDebugMonitorInterface, pm::DebugMonitorService> g_deprecated_dmnt_service;
sf::UnmanagedServiceObject<pm::impl::IBootModeInterface, pm::BootModeService> g_boot_mode_service;
sf::UnmanagedServiceObject<pm::impl::IInformationInterface, pm::InformationService> g_information_service;
ams::Result ServerManager::OnNeedsToAccept(int port_index, Server *server) {
switch (port_index) {
case PortIndex_Shell:
if (hos::GetVersion() >= hos::Version_5_0_0) {
R_RETURN(this->AcceptImpl(server, g_shell_service.GetShared()));
} else {
R_RETURN(this->AcceptImpl(server, g_deprecated_shell_service.GetShared()));
}
case PortIndex_DebugMonitor:
if (hos::GetVersion() >= hos::Version_5_0_0) {
R_RETURN(this->AcceptImpl(server, g_dmnt_service.GetShared()));
} else {
R_RETURN(this->AcceptImpl(server, g_deprecated_dmnt_service.GetShared()));
}
case PortIndex_BootMode:
R_RETURN(this->AcceptImpl(server, g_boot_mode_service.GetShared()));
case PortIndex_Information:
R_RETURN(this->AcceptImpl(server, g_information_service.GetShared()));
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
void RegisterServices() {
/* NOTE: Extra sessions have been added to pm:bm and pm:info to facilitate access by the rest of stratosphere. */
R_ABORT_UNLESS(g_server_manager.RegisterServer(PortIndex_Shell, ShellServiceName, ShellMaxSessions));
R_ABORT_UNLESS(g_server_manager.RegisterServer(PortIndex_DebugMonitor, DebugMonitorServiceName, DebugMonitorMaxSessions));
R_ABORT_UNLESS(g_server_manager.RegisterServer(PortIndex_BootMode, BootModeServiceName, BootModeMaxSessions));
R_ABORT_UNLESS(g_server_manager.RegisterServer(PortIndex_Information, InformationServiceName, InformationMaxSessions));
}
void LoopProcess() {
g_server_manager.LoopProcess();
}
}
}
namespace hos {
void InitializeVersionInternal(bool allow_approximate);
}
namespace init {
void InitializeSystemModule() {
/* Initialize our connection to sm. */
R_ABORT_UNLESS(sm::Initialize());
/* Initialize manager interfaces for fs and sm. */
R_ABORT_UNLESS(fsprInitialize());
R_ABORT_UNLESS(smManagerInitialize());
/* Work around a bug with process permissions on < 4.0.0. */
/* This registers all initial processes explicitly with both fs and sm. */
pm::RegisterPrivilegedProcesses();
/* Use our manager extension to tell SM that the FS bug has been worked around. */
R_ABORT_UNLESS(sm::manager::EndInitialDefers());
/* Wait for the true hos version to be available. */
hos::InitializeVersionInternal(false);
/* Now that the true hos version is available, we should once more end defers (alerting sm to the available hos version). */
R_ABORT_UNLESS(sm::manager::EndInitialDefers());
/* Initialize remaining services we need. */
R_ABORT_UNLESS(ldrPmInitialize());
spl::Initialize();
/* Verify that we can sanely execute. */
ams::CheckApiVersion();
}
void FinalizeSystemModule() { /* ... */ }
void Startup() { /* ... */ }
}
void NORETURN Exit(int rc) {
AMS_UNUSED(rc);
AMS_ABORT("Exit called by immortal process");
}
void Main() {
/* Set thread name. */
os::SetThreadNamePointer(os::GetCurrentThread(), AMS_GET_SYSTEM_THREAD_NAME(pm, Main));
AMS_ASSERT(os::GetThreadPriority(os::GetCurrentThread()) == AMS_GET_SYSTEM_THREAD_PRIORITY(pm, Main));
/* Initialize process manager implementation. */
R_ABORT_UNLESS(pm::impl::InitializeProcessManager());
/* Create Services. */
pm::RegisterServices();
/* Loop forever, servicing our services. */
pm::LoopProcess();
/* This can never be reached. */
AMS_ASSUME(false);
}
}
| 11,487
|
C++
|
.cpp
| 183
| 49.497268
| 236
| 0.62851
|
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,250
|
pm_debug_monitor_service.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/pm/source/pm_debug_monitor_service.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "pm_debug_monitor_service.hpp"
#include "impl/pm_process_manager.hpp"
#include "impl/pm_spec.hpp"
namespace ams::pm {
/* Actual command implementations. */
Result DebugMonitorService::GetModuleIdList(sf::Out<u32> out_count, const sf::OutBuffer &out_buf, u64 unused) {
R_UNLESS(out_buf.GetSize() <= std::numeric_limits<s32>::max(), pm::ResultInvalidSize());
R_RETURN(impl::GetModuleIdList(out_count.GetPointer(), out_buf.GetPointer(), out_buf.GetSize(), unused));
}
Result DebugMonitorService::GetExceptionProcessIdList(sf::Out<u32> out_count, const sf::OutArray<os::ProcessId> &out_process_ids) {
R_UNLESS(out_process_ids.GetSize() <= std::numeric_limits<s32>::max(), pm::ResultInvalidSize());
R_RETURN(impl::GetExceptionProcessIdList(out_count.GetPointer(), out_process_ids.GetPointer(), out_process_ids.GetSize()));
}
Result DebugMonitorService::StartProcess(os::ProcessId process_id) {
R_RETURN(impl::StartProcess(process_id));
}
Result DebugMonitorService::GetProcessId(sf::Out<os::ProcessId> out, ncm::ProgramId program_id) {
R_RETURN(impl::GetProcessId(out.GetPointer(), program_id));
}
Result DebugMonitorService::HookToCreateProcess(sf::OutCopyHandle out_hook, ncm::ProgramId program_id) {
os::NativeHandle event_handle;
R_TRY(impl::HookToCreateProcess(std::addressof(event_handle), program_id));
out_hook.SetValue(event_handle, false);
R_SUCCEED();
}
Result DebugMonitorService::GetApplicationProcessId(sf::Out<os::ProcessId> out) {
R_RETURN(impl::GetApplicationProcessId(out.GetPointer()));
}
Result DebugMonitorService::HookToCreateApplicationProcess(sf::OutCopyHandle out_hook) {
os::NativeHandle event_handle;
R_TRY(impl::HookToCreateApplicationProcess(std::addressof(event_handle)));
out_hook.SetValue(event_handle, false);
R_SUCCEED();
}
Result DebugMonitorService::ClearHook(u32 which) {
R_RETURN(impl::ClearHook(which));
}
Result DebugMonitorService::GetProgramId(sf::Out<ncm::ProgramId> out, os::ProcessId process_id) {
R_RETURN(impl::GetProgramId(out.GetPointer(), process_id));
}
/* Atmosphere extension commands. */
Result DebugMonitorService::AtmosphereGetProcessInfo(sf::OutCopyHandle out_process_handle, sf::Out<ncm::ProgramLocation> out_loc, sf::Out<cfg::OverrideStatus> out_status, os::ProcessId process_id) {
os::NativeHandle process_handle;
R_TRY(impl::AtmosphereGetProcessInfo(std::addressof(process_handle), out_loc.GetPointer(), out_status.GetPointer(), process_id));
out_process_handle.SetValue(process_handle, false);
R_SUCCEED();
}
Result DebugMonitorService::AtmosphereGetCurrentLimitInfo(sf::Out<s64> out_cur_val, sf::Out<s64> out_lim_val, u32 group, u32 resource) {
R_RETURN(impl::GetResourceLimitValues(out_cur_val.GetPointer(), out_lim_val.GetPointer(), static_cast<ResourceLimitGroup>(group), static_cast<svc::LimitableResource>(resource)));
}
}
| 3,746
|
C++
|
.cpp
| 67
| 50.402985
| 202
| 0.723724
|
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,251
|
pm_process_manager.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/pm/source/impl/pm_process_manager.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "pm_process_manager.hpp"
#include "pm_process_tracker.hpp"
#include "pm_process_info.hpp"
#include "pm_spec.hpp"
namespace ams::pm::impl {
namespace {
/* Types. */
enum HookType {
HookType_ProgramId = (1 << 0),
HookType_Application = (1 << 1),
};
#define GET_FLAG_MASK(flag) (hos_version >= hos::Version_5_0_0 ? static_cast<u32>(LaunchFlags_##flag) : static_cast<u32>(LaunchFlagsDeprecated_##flag))
inline bool ShouldSignalOnExit(u32 launch_flags) {
const auto hos_version = hos::GetVersion();
return launch_flags & GET_FLAG_MASK(SignalOnExit);
}
inline bool ShouldSignalOnStart(u32 launch_flags) {
const auto hos_version = hos::GetVersion();
if (hos_version < hos::Version_2_0_0) {
return false;
}
return launch_flags & GET_FLAG_MASK(SignalOnStart);
}
inline bool ShouldSignalOnException(u32 launch_flags) {
const auto hos_version = hos::GetVersion();
return launch_flags & GET_FLAG_MASK(SignalOnException);
}
inline bool ShouldSignalOnDebugEvent(u32 launch_flags) {
const auto hos_version = hos::GetVersion();
return launch_flags & GET_FLAG_MASK(SignalOnDebugEvent);
}
inline bool ShouldStartSuspended(u32 launch_flags) {
const auto hos_version = hos::GetVersion();
return launch_flags & GET_FLAG_MASK(StartSuspended);
}
inline bool ShouldDisableAslr(u32 launch_flags) {
const auto hos_version = hos::GetVersion();
return launch_flags & GET_FLAG_MASK(DisableAslr);
}
#undef GET_FLAG_MASK
/* Process Tracking globals. */
constinit ProcessTracker g_process_tracker;
alignas(os::ThreadStackAlignment) constinit u8 g_process_track_thread_stack[8_KB];
/* Global events. */
constinit os::SystemEventType g_hook_to_create_process_event;
constinit os::SystemEventType g_hook_to_create_application_process_event;
constinit os::SystemEventType g_boot_finished_event;
/* Hook globals. */
constinit std::atomic<ncm::ProgramId> g_program_id_hook;
constinit std::atomic<bool> g_application_hook;
/* Helpers. */
void CreateDebuggerEvent() {
/* Create debugger hook events. */
R_ABORT_UNLESS(os::CreateSystemEvent(std::addressof(g_hook_to_create_process_event), os::EventClearMode_AutoClear, true));
R_ABORT_UNLESS(os::CreateSystemEvent(std::addressof(g_hook_to_create_application_process_event), os::EventClearMode_AutoClear, true));
}
inline u32 GetLoaderCreateProcessFlags(u32 launch_flags) {
u32 ldr_flags = 0;
if (ShouldSignalOnException(launch_flags) || (hos::GetVersion() >= hos::Version_2_0_0 && !ShouldStartSuspended(launch_flags))) {
ldr_flags |= ldr::CreateProcessFlag_EnableDebug;
}
if (ShouldDisableAslr(launch_flags)) {
ldr_flags |= ldr::CreateProcessFlag_DisableAslr;
}
return ldr_flags;
}
bool HasApplicationProcess() {
auto list = GetProcessList();
for (auto &process : *list) {
if (process.IsApplication()) {
return true;
}
}
return false;
}
Result StartProcess(ProcessInfo *process_info, const ldr::ProgramInfo *program_info) {
R_TRY(svc::StartProcess(process_info->GetHandle(), program_info->main_thread_priority, program_info->default_cpu_id, program_info->main_thread_stack_size));
process_info->SetState(svc::ProcessState_Running);
R_SUCCEED();
}
Result LaunchProgramImpl(ProcessInfo **out_process_info, os::ProcessId *out_process_id, const ncm::ProgramLocation &loc, u32 flags) {
/* Set the output to nullptr, if we fail. */
*out_process_info = nullptr;
/* Get Program Info. */
ldr::ProgramInfo program_info;
cfg::OverrideStatus override_status;
R_TRY(ldr::pm::AtmosphereGetProgramInfo(std::addressof(program_info), std::addressof(override_status), loc));
const bool is_application = (program_info.flags & ldr::ProgramInfoFlag_ApplicationTypeMask) == ldr::ProgramInfoFlag_Application;
const bool allow_debug = (program_info.flags & ldr::ProgramInfoFlag_AllowDebug) || hos::GetVersion() < hos::Version_2_0_0;
/* Ensure we only try to run one application. */
R_UNLESS(!is_application || !HasApplicationProcess(), pm::ResultApplicationRunning());
/* Fix the program location to use the right program id. */
const ncm::ProgramLocation fixed_location = ncm::ProgramLocation::Make(program_info.program_id, static_cast<ncm::StorageId>(loc.storage_id));
/* Pin and create the process. */
os::NativeHandle process_handle;
ldr::PinId pin_id;
{
/* Pin the program with loader. */
R_TRY(ldr::pm::AtmospherePinProgram(std::addressof(pin_id), fixed_location, override_status));
/* If we fail after now, unpin. */
ON_RESULT_FAILURE { ldr::pm::UnpinProgram(pin_id); };
/* Ensure we can talk to mitm services. */
{
AMS_FUNCTION_LOCAL_STATIC_CONSTINIT(bool, s_initialized_mitm, false);
if (!s_initialized_mitm) {
mitm::pm::Initialize();
s_initialized_mitm = true;
}
}
/* Determine boost size for mitm. */
u64 mitm_boost_size = 0;
R_TRY(mitm::pm::PrepareLaunchProgram(std::addressof(mitm_boost_size), program_info.program_id, override_status, is_application));
if (mitm_boost_size > 0 || is_application) {
R_ABORT_UNLESS(BoostSystemMemoryResourceLimitForMitm(mitm_boost_size));
}
ON_RESULT_FAILURE_2 { if (mitm_boost_size > 0 || is_application) { R_ABORT_UNLESS(BoostSystemMemoryResourceLimitForMitm(0)); } };
/* Ensure resources are available. */
WaitResourceAvailable(std::addressof(program_info));
/* Actually create the process. */
R_TRY(ldr::pm::CreateProcess(std::addressof(process_handle), pin_id, GetLoaderCreateProcessFlags(flags), GetResourceLimitHandle(std::addressof(program_info))));
}
/* Get the process id. */
os::ProcessId process_id = os::GetProcessId(process_handle);
/* Make new process info. */
ProcessInfo *process_info = AllocateProcessInfo(process_handle, process_id, pin_id, fixed_location, override_status);
AMS_ABORT_UNLESS(process_info != nullptr);
/* Add the new process info to the process list. */
{
auto list = GetProcessList();
list->push_back(*process_info);
}
/* Prevent resource leakage if register fails. */
ON_RESULT_FAILURE {
auto list = GetProcessList();
process_info->Cleanup();
CleanupProcessInfo(list, process_info);
};
const u8 *acid_sac = program_info.ac_buffer;
const u8 *aci_sac = acid_sac + program_info.acid_sac_size;
const u8 *acid_fac = aci_sac + program_info.aci_sac_size;
const u8 *aci_fah = acid_fac + program_info.acid_fac_size;
/* Register with FS and SM. */
R_TRY(fsprRegisterProgram(static_cast<u64>(process_id), static_cast<u64>(fixed_location.program_id), static_cast<NcmStorageId>(fixed_location.storage_id), aci_fah, program_info.aci_fah_size, acid_fac, program_info.acid_fac_size));
R_TRY(sm::manager::RegisterProcess(process_id, fixed_location.program_id, override_status, acid_sac, program_info.acid_sac_size, aci_sac, program_info.aci_sac_size));
/* Set flags. */
if (is_application) {
process_info->SetApplication();
}
if (ShouldSignalOnStart(flags) && allow_debug) {
process_info->SetSignalOnStart();
}
if (ShouldSignalOnExit(flags)) {
process_info->SetSignalOnExit();
}
if (ShouldSignalOnDebugEvent(flags) && allow_debug) {
process_info->SetSignalOnDebugEvent();
}
/* Process hooks/signaling. */
if (fixed_location.program_id == g_program_id_hook) {
os::SignalSystemEvent(std::addressof(g_hook_to_create_process_event));
g_program_id_hook = ncm::InvalidProgramId;
} else if (is_application && g_application_hook) {
os::SignalSystemEvent(std::addressof(g_hook_to_create_application_process_event));
g_application_hook = false;
} else if (!ShouldStartSuspended(flags)) {
R_TRY(StartProcess(process_info, std::addressof(program_info)));
}
*out_process_id = process_id;
*out_process_info = process_info;
R_SUCCEED();
}
}
/* Initialization. */
Result InitializeProcessManager() {
/* Create events. */
CreateProcessEvent();
CreateDebuggerEvent();
R_ABORT_UNLESS(os::CreateSystemEvent(std::addressof(g_boot_finished_event), os::EventClearMode_AutoClear, true));
/* Initialize resource limits. */
R_TRY(InitializeSpec());
/* Initialize the process tracker. */
g_process_tracker.Initialize(g_process_track_thread_stack, sizeof(g_process_track_thread_stack));
/* Start the process tracker thread. */
g_process_tracker.StartThread();
R_SUCCEED();
}
/* Process Management. */
Result LaunchProgram(os::ProcessId *out_process_id, const ncm::ProgramLocation &loc, u32 flags) {
/* Launch the program. */
ProcessInfo *process_info = nullptr;
R_TRY(LaunchProgramImpl(std::addressof(process_info), out_process_id, loc, flags));
/* Register the process info with the tracker. */
g_process_tracker.QueueEntry(process_info);
R_SUCCEED();
}
Result StartProcess(os::ProcessId process_id) {
auto list = GetProcessList();
auto process_info = list->Find(process_id);
R_UNLESS(process_info != nullptr, pm::ResultProcessNotFound());
R_UNLESS(!process_info->HasStarted(), pm::ResultAlreadyStarted());
ldr::ProgramInfo program_info;
R_TRY(ldr::pm::GetProgramInfo(std::addressof(program_info), process_info->GetProgramLocation()));
R_RETURN(StartProcess(process_info, std::addressof(program_info)));
}
Result TerminateProcess(os::ProcessId process_id) {
auto list = GetProcessList();
auto process_info = list->Find(process_id);
R_UNLESS(process_info != nullptr, pm::ResultProcessNotFound());
R_RETURN(svc::TerminateProcess(process_info->GetHandle()));
}
Result TerminateProgram(ncm::ProgramId program_id) {
auto list = GetProcessList();
auto process_info = list->Find(program_id);
R_UNLESS(process_info != nullptr, pm::ResultProcessNotFound());
R_RETURN(svc::TerminateProcess(process_info->GetHandle()));
}
Result GetProcessEventInfo(ProcessEventInfo *out) {
/* Check for event from current process. */
{
auto list = GetProcessList();
for (auto &process : *list) {
if (process.HasStarted() && process.HasStartedStateChanged()) {
process.ClearStartedStateChanged();
out->event = GetProcessEventValue(ProcessEvent::Started);
out->process_id = process.GetProcessId();
R_SUCCEED();
}
if (process.HasSuspendedStateChanged()) {
process.ClearSuspendedStateChanged();
if (process.IsSuspended()) {
out->event = GetProcessEventValue(ProcessEvent::DebugBreak);
} else {
out->event = GetProcessEventValue(ProcessEvent::DebugRunning);
}
out->process_id = process.GetProcessId();
R_SUCCEED();
}
if (process.HasExceptionOccurred()) {
process.ClearExceptionOccurred();
out->event = GetProcessEventValue(ProcessEvent::Exception);
out->process_id = process.GetProcessId();
R_SUCCEED();
}
if (hos::GetVersion() < hos::Version_5_0_0 && process.ShouldSignalOnExit() && process.HasTerminated()) {
out->event = GetProcessEventValue(ProcessEvent::Exited);
out->process_id = process.GetProcessId();
R_SUCCEED();
}
}
}
/* Check for event from exited process. */
if (hos::GetVersion() >= hos::Version_5_0_0) {
auto exit_list = GetExitList();
if (!exit_list->empty()) {
auto &process_info = exit_list->front();
out->event = GetProcessEventValue(ProcessEvent::Exited);
out->process_id = process_info.GetProcessId();
CleanupProcessInfo(exit_list, std::addressof(process_info));
R_SUCCEED();
}
}
out->process_id = os::ProcessId{};
out->event = GetProcessEventValue(ProcessEvent::None);
R_SUCCEED();
}
Result CleanupProcess(os::ProcessId process_id) {
auto list = GetProcessList();
auto process_info = list->Find(process_id);
R_UNLESS(process_info != nullptr, pm::ResultProcessNotFound());
R_UNLESS(process_info->HasTerminated(), pm::ResultNotTerminated());
CleanupProcessInfo(list, process_info);
R_SUCCEED();
}
Result ClearExceptionOccurred(os::ProcessId process_id) {
auto list = GetProcessList();
auto process_info = list->Find(process_id);
R_UNLESS(process_info != nullptr, pm::ResultProcessNotFound());
process_info->ClearExceptionOccurred();
R_SUCCEED();
}
/* Information Getters. */
Result GetModuleIdList(u32 *out_count, u8 *out_buf, size_t max_out_count, u64 unused) {
/* This function was always stubbed... */
AMS_UNUSED(out_buf, max_out_count, unused);
*out_count = 0;
R_SUCCEED();
}
Result GetExceptionProcessIdList(u32 *out_count, os::ProcessId *out_process_ids, size_t max_out_count) {
auto list = GetProcessList();
size_t count = 0;
if (max_out_count > 0) {
for (auto &process : *list) {
if (process.HasExceptionWaitingAttach()) {
out_process_ids[count++] = process.GetProcessId();
if (count >= max_out_count) {
break;
}
}
}
}
*out_count = static_cast<u32>(count);
R_SUCCEED();
}
Result GetProcessId(os::ProcessId *out, ncm::ProgramId program_id) {
auto list = GetProcessList();
auto process_info = list->Find(program_id);
R_UNLESS(process_info != nullptr, pm::ResultProcessNotFound());
*out = process_info->GetProcessId();
R_SUCCEED();
}
Result GetProgramId(ncm::ProgramId *out, os::ProcessId process_id) {
auto list = GetProcessList();
auto process_info = list->Find(process_id);
R_UNLESS(process_info != nullptr, pm::ResultProcessNotFound());
*out = process_info->GetProgramLocation().program_id;
R_SUCCEED();
}
Result GetApplicationProcessId(os::ProcessId *out_process_id) {
auto list = GetProcessList();
for (auto &process : *list) {
if (process.IsApplication()) {
*out_process_id = process.GetProcessId();
R_SUCCEED();
}
}
R_THROW(pm::ResultProcessNotFound());
}
Result AtmosphereGetProcessInfo(os::NativeHandle *out_process_handle, ncm::ProgramLocation *out_loc, cfg::OverrideStatus *out_status, os::ProcessId process_id) {
auto list = GetProcessList();
auto process_info = list->Find(process_id);
R_UNLESS(process_info != nullptr, pm::ResultProcessNotFound());
*out_process_handle = process_info->GetHandle();
*out_loc = process_info->GetProgramLocation();
*out_status = process_info->GetOverrideStatus();
R_SUCCEED();
}
/* Hook API. */
Result HookToCreateProcess(os::NativeHandle *out_hook, ncm::ProgramId program_id) {
*out_hook = os::InvalidNativeHandle;
{
ncm::ProgramId old_value = ncm::InvalidProgramId;
R_UNLESS(g_program_id_hook.compare_exchange_strong(old_value, program_id), pm::ResultDebugHookInUse());
}
*out_hook = os::GetReadableHandleOfSystemEvent(std::addressof(g_hook_to_create_process_event));
R_SUCCEED();
}
Result HookToCreateApplicationProcess(os::NativeHandle *out_hook) {
*out_hook = os::InvalidNativeHandle;
{
bool old_value = false;
R_UNLESS(g_application_hook.compare_exchange_strong(old_value, true), pm::ResultDebugHookInUse());
}
*out_hook = os::GetReadableHandleOfSystemEvent(std::addressof(g_hook_to_create_application_process_event));
R_SUCCEED();
}
Result ClearHook(u32 which) {
if (which & HookType_ProgramId) {
g_program_id_hook = ncm::InvalidProgramId;
}
if (which & HookType_Application) {
g_application_hook = false;
}
R_SUCCEED();
}
/* Boot API. */
Result NotifyBootFinished() {
AMS_FUNCTION_LOCAL_STATIC_CONSTINIT(bool, s_has_boot_finished, false);
if (!s_has_boot_finished) {
/* Set program verification disabled, if we should. */
/* NOTE: Nintendo does not check the result of this. */
if (spl::IsDisabledProgramVerification()) {
if (hos::GetVersion() >= hos::Version_10_0_0) {
ldr::pm::SetEnabledProgramVerification(false);
} else {
fsprSetEnabledProgramVerification(false);
}
}
boot2::LaunchPreSdCardBootProgramsAndBoot2();
s_has_boot_finished = true;
os::SignalSystemEvent(std::addressof(g_boot_finished_event));
}
R_SUCCEED();
}
Result GetBootFinishedEventHandle(os::NativeHandle *out) {
/* In 8.0.0, Nintendo added this command, which signals that the boot sysmodule has finished. */
/* Nintendo only signals it in safe mode FIRM, and this function aborts on normal FIRM. */
/* We will signal it always, but only allow this function to succeed on safe mode. */
AMS_ABORT_UNLESS(spl::IsRecoveryBoot());
*out = os::GetReadableHandleOfSystemEvent(std::addressof(g_boot_finished_event));
R_SUCCEED();
}
}
| 20,268
|
C++
|
.cpp
| 408
| 38.127451
| 242
| 0.60082
|
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,252
|
pm_process_tracker.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/pm/source/impl/pm_process_tracker.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "pm_process_tracker.hpp"
#include "pm_process_info.hpp"
#include "pm_spec.hpp"
namespace ams::pm::impl {
namespace {
/* Global process event. */
constinit os::SystemEventType g_process_event;
}
void ProcessTracker::Initialize(void *stack, size_t stack_size) {
/* Initialize our events. */
os::InitializeEvent(std::addressof(m_request_event), false, os::EventClearMode_AutoClear);
os::InitializeEvent(std::addressof(m_reply_event), false, os::EventClearMode_AutoClear);
/* Our process count should initially be zero. */
m_process_count = 0;
/* Create the process tracking thread. */
R_ABORT_UNLESS(os::CreateThread(std::addressof(m_thread), ProcessTracker::ThreadFunction, this, stack, stack_size, AMS_GET_SYSTEM_THREAD_PRIORITY(pm, ProcessTrack)));
os::SetThreadNamePointer(std::addressof(m_thread), AMS_GET_SYSTEM_THREAD_NAME(pm, ProcessTrack));
}
void ProcessTracker::StartThread() {
/* Start thread. */
os::StartThread(std::addressof(m_thread));
}
void ProcessTracker::ThreadBody() {
/* This is the main loop of the process tracking thread. */
/* Setup multi wait/holders. */
os::MultiWaitType process_multi_wait;
os::MultiWaitHolderType enqueue_event_holder;
os::InitializeMultiWait(std::addressof(process_multi_wait));
os::InitializeMultiWaitHolder(std::addressof(enqueue_event_holder), std::addressof(m_request_event));
os::LinkMultiWaitHolder(std::addressof(process_multi_wait), std::addressof(enqueue_event_holder));
while (true) {
auto signaled_holder = os::WaitAny(std::addressof(process_multi_wait));
if (signaled_holder == std::addressof(enqueue_event_holder)) {
/* TryWait will clear signaled, preventing duplicate notifications. */
if (os::TryWaitEvent(std::addressof(m_request_event))) {
/* Link the process to our multi-wait. */
os::LinkMultiWaitHolder(std::addressof(process_multi_wait), m_queued_process_info->GetMultiWaitHolder());
m_queued_process_info = nullptr;
/* Increment our process count. */
++m_process_count;
/* Reply. */
os::SignalEvent(std::addressof(m_reply_event));
}
} else {
/* Some process was signaled. */
this->OnProcessSignaled(reinterpret_cast<ProcessInfo *>(os::GetMultiWaitHolderUserData(signaled_holder)));
}
}
}
void ProcessTracker::QueueEntry(ProcessInfo *process_info) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Request to enqueue the process info. */
m_queued_process_info = process_info;
os::SignalEvent(std::addressof(m_request_event));
/* Wait for acknowledgement. */
os::WaitEvent(std::addressof(m_reply_event));
}
void ProcessTracker::OnProcessSignaled(ProcessInfo *process_info) {
/* Get the process list. */
auto list = GetProcessList();
/* Reset the process's signal. */
svc::ResetSignal(process_info->GetHandle());
/* Update the process's state. */
const svc::ProcessState old_state = process_info->GetState();
{
s64 tmp = 0;
R_ABORT_UNLESS(svc::GetProcessInfo(std::addressof(tmp), process_info->GetHandle(), svc::ProcessInfoType_ProcessState));
process_info->SetState(static_cast<svc::ProcessState>(tmp));
}
const svc::ProcessState new_state = process_info->GetState();
/* If we're transitioning away from crashed, clear waiting attached. */
if (old_state == svc::ProcessState_Crashed && new_state != svc::ProcessState_Crashed) {
process_info->ClearExceptionWaitingAttach();
}
switch (new_state) {
case svc::ProcessState_Created:
case svc::ProcessState_CreatedAttached:
case svc::ProcessState_Terminating:
break;
case svc::ProcessState_Running:
if (process_info->ShouldSignalOnDebugEvent()) {
process_info->ClearSuspended();
process_info->SetSuspendedStateChanged();
os::SignalSystemEvent(std::addressof(g_process_event));
} else if (hos::GetVersion() >= hos::Version_2_0_0 && process_info->ShouldSignalOnStart()) {
process_info->SetStartedStateChanged();
process_info->ClearSignalOnStart();
os::SignalSystemEvent(std::addressof(g_process_event));
}
process_info->ClearUnhandledException();
break;
case svc::ProcessState_Crashed:
if (!process_info->HasUnhandledException()) {
process_info->SetExceptionOccurred();
os::SignalSystemEvent(std::addressof(g_process_event));
}
process_info->SetExceptionWaitingAttach();
break;
case svc::ProcessState_RunningAttached:
if (process_info->ShouldSignalOnDebugEvent()) {
process_info->ClearSuspended();
process_info->SetSuspendedStateChanged();
os::SignalSystemEvent(std::addressof(g_process_event));
}
process_info->ClearUnhandledException();
break;
case svc::ProcessState_Terminated:
/* Unlink from multi wait. */
os::UnlinkMultiWaitHolder(process_info->GetMultiWaitHolder());
/* Free process resources. */
process_info->Cleanup();
if (hos::GetVersion() < hos::Version_5_0_0 && process_info->ShouldSignalOnExit()) {
os::SignalSystemEvent(std::addressof(g_process_event));
} else {
/* Handle the case where we need to keep the process alive some time longer. */
if (hos::GetVersion() >= hos::Version_5_0_0 && process_info->ShouldSignalOnExit()) {
/* Remove from the living list. */
list->Remove(process_info);
/* Add the process to the list of dead processes. */
{
GetExitList()->push_back(*process_info);
}
/* Signal. */
os::SignalSystemEvent(std::addressof(g_process_event));
} else {
/* Actually delete process. */
CleanupProcessInfo(list, process_info);
}
}
break;
case svc::ProcessState_DebugBreak:
if (process_info->ShouldSignalOnDebugEvent()) {
process_info->SetSuspended();
process_info->SetSuspendedStateChanged();
os::SignalSystemEvent(std::addressof(g_process_event));
}
break;
}
}
void CreateProcessEvent() {
/* Create process event. */
R_ABORT_UNLESS(os::CreateSystemEvent(std::addressof(g_process_event), os::EventClearMode_AutoClear, true));
}
Result GetProcessEventHandle(os::NativeHandle *out) {
*out = os::GetReadableHandleOfSystemEvent(std::addressof(g_process_event));
R_SUCCEED();
}
}
| 8,287
|
C++
|
.cpp
| 165
| 37.648485
| 174
| 0.592414
|
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,253
|
pm_spec.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/pm/source/impl/pm_spec.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "pm_spec.hpp"
namespace ams::pm::impl {
namespace {
constexpr svc::LimitableResource LimitableResources[] = {
svc::LimitableResource_PhysicalMemoryMax,
svc::LimitableResource_ThreadCountMax,
svc::LimitableResource_EventCountMax,
svc::LimitableResource_TransferMemoryCountMax,
svc::LimitableResource_SessionCountMax,
};
/* Definitions for limit differences over time. */
constexpr size_t ExtraSystemMemorySize400 = 10_MB;
constexpr size_t ReservedMemorySize600 = 5_MB;
/* Atmosphere always allocates extra memory for system usage. */
constexpr size_t ExtraSystemMemorySizeAtmosphere = 32_MB;
/* Desired extra threads. */
constexpr u64 BaseApplicationThreads = 96;
constexpr u64 BaseAppletThreads = 96;
constexpr u64 BaseSystemThreads = 800 - BaseAppletThreads - BaseApplicationThreads;
constexpr s64 ExtraSystemThreads = 1024 - BaseSystemThreads;
constexpr s64 ExtraApplicationThreads = 256 - BaseApplicationThreads;
constexpr s64 ExtraAppletThreads = 256 - BaseAppletThreads;
static_assert(ExtraSystemThreads >= 0);
static_assert(ExtraApplicationThreads >= 0);
static_assert(ExtraAppletThreads >= 0);
/* Globals. */
constinit os::SdkMutex g_resource_limit_lock;
constinit os::NativeHandle g_resource_limit_handles[ResourceLimitGroup_Count];
constinit spl::MemoryArrangement g_memory_arrangement = spl::MemoryArrangement_Standard;
constinit u64 g_extra_threads_available[ResourceLimitGroup_Count];
constinit os::SdkMutex g_system_memory_boost_lock;
constinit u64 g_system_memory_boost_size = 0;
constinit u64 g_system_memory_boost_size_for_mitm = 0;
ALWAYS_INLINE u64 GetCurrentSystemMemoryBoostSize() {
return g_system_memory_boost_size + g_system_memory_boost_size_for_mitm;
}
constinit u64 g_resource_limits[ResourceLimitGroup_Count][svc::LimitableResource_Count] = {
[ResourceLimitGroup_System] = {
[svc::LimitableResource_PhysicalMemoryMax] = 0, /* Initialized dynamically later. */
[svc::LimitableResource_ThreadCountMax] = BaseSystemThreads,
[svc::LimitableResource_EventCountMax] = 0, /* Initialized dynamically later. */
[svc::LimitableResource_TransferMemoryCountMax] = 0, /* Initialized dynamically later. */
[svc::LimitableResource_SessionCountMax] = 0, /* Initialized dynamically later. */
},
[ResourceLimitGroup_Application] = {
[svc::LimitableResource_PhysicalMemoryMax] = 0, /* Initialized dynamically later. */
[svc::LimitableResource_ThreadCountMax] = BaseApplicationThreads,
[svc::LimitableResource_EventCountMax] = 0,
[svc::LimitableResource_TransferMemoryCountMax] = 32,
[svc::LimitableResource_SessionCountMax] = 1,
},
[ResourceLimitGroup_Applet] = {
[svc::LimitableResource_PhysicalMemoryMax] = 0, /* Initialized dynamically later. */
[svc::LimitableResource_ThreadCountMax] = BaseAppletThreads,
[svc::LimitableResource_EventCountMax] = 0,
[svc::LimitableResource_TransferMemoryCountMax] = 32,
[svc::LimitableResource_SessionCountMax] = 5,
},
};
constinit u64 g_memory_resource_limits[spl::MemoryArrangement_Count][ResourceLimitGroup_Count] = {
[spl::MemoryArrangement_Standard] = {
[ResourceLimitGroup_System] = 269_MB,
[ResourceLimitGroup_Application] = 3285_MB,
[ResourceLimitGroup_Applet] = 535_MB,
},
[spl::MemoryArrangement_StandardForAppletDev] = {
[ResourceLimitGroup_System] = 481_MB,
[ResourceLimitGroup_Application] = 2048_MB,
[ResourceLimitGroup_Applet] = 1560_MB,
},
[spl::MemoryArrangement_StandardForSystemDev] = {
[ResourceLimitGroup_System] = 328_MB,
[ResourceLimitGroup_Application] = 3285_MB,
[ResourceLimitGroup_Applet] = 476_MB,
},
[spl::MemoryArrangement_Expanded] = {
[ResourceLimitGroup_System] = 653_MB,
[ResourceLimitGroup_Application] = 4916_MB,
[ResourceLimitGroup_Applet] = 568_MB,
},
[spl::MemoryArrangement_ExpandedForAppletDev] = {
[ResourceLimitGroup_System] = 653_MB,
[ResourceLimitGroup_Application] = 3285_MB,
[ResourceLimitGroup_Applet] = 2199_MB,
},
};
/* Helpers. */
Result SetMemoryResourceLimitLimitValue(ResourceLimitGroup group, u64 new_memory_limit) {
const u64 old_memory_limit = g_resource_limits[group][svc::LimitableResource_PhysicalMemoryMax];
g_resource_limits[group][svc::LimitableResource_PhysicalMemoryMax] = new_memory_limit;
/* Restore the old memory limit if we fail. */
ON_RESULT_FAILURE { g_resource_limits[group][svc::LimitableResource_PhysicalMemoryMax] = old_memory_limit; };
/* Set the resource limit. */
R_RETURN(svc::SetResourceLimitLimitValue(GetResourceLimitHandle(group), svc::LimitableResource_PhysicalMemoryMax, g_resource_limits[group][svc::LimitableResource_PhysicalMemoryMax]));
}
Result SetResourceLimitLimitValues(ResourceLimitGroup group, u64 new_memory_limit) {
/* First, set memory limit. */
R_TRY(SetMemoryResourceLimitLimitValue(group, new_memory_limit));
/* Set other limit values. */
for (size_t i = 0; i < svc::LimitableResource_Count; i++) {
const auto resource = LimitableResources[i];
if (resource == svc::LimitableResource_PhysicalMemoryMax) {
continue;
}
R_TRY(svc::SetResourceLimitLimitValue(GetResourceLimitHandle(group), resource, g_resource_limits[group][resource]));
}
R_SUCCEED();
}
inline ResourceLimitGroup GetResourceLimitGroup(const ldr::ProgramInfo *info) {
switch (info->flags & ldr::ProgramInfoFlag_ApplicationTypeMask) {
case ldr::ProgramInfoFlag_Application:
return ResourceLimitGroup_Application;
case ldr::ProgramInfoFlag_Applet:
return ResourceLimitGroup_Applet;
default:
return ResourceLimitGroup_System;
}
}
void WaitResourceAvailable(ResourceLimitGroup group) {
const auto reslimit_hnd = GetResourceLimitHandle(group);
for (size_t i = 0; i < svc::LimitableResource_Count; i++) {
const auto resource = LimitableResources[i];
s64 value = 0;
while (true) {
R_ABORT_UNLESS(svc::GetResourceLimitCurrentValue(&value, reslimit_hnd, resource));
if (value == 0) {
break;
}
os::SleepThread(TimeSpan::FromMilliSeconds(1));
}
}
}
void WaitApplicationMemoryAvailable() {
/* Get firmware version. */
const auto fw_ver = hos::GetVersion();
/* On 15.0.0+, pm considers application memory to be available if there is exactly 96 MB outstanding. */
/* This is probably because this corresponds to the gameplay-recording memory. */
constexpr u64 AllowedUsedApplicationMemory = 96_MB;
/* Wait for memory to be available. */
u64 value = 0;
while (true) {
R_ABORT_UNLESS(svc::GetSystemInfo(&value, svc::SystemInfoType_UsedPhysicalMemorySize, svc::InvalidHandle, svc::PhysicalMemorySystemInfo_Application));
if (value == 0 || (fw_ver >= hos::Version_15_0_0 && value == AllowedUsedApplicationMemory)) {
break;
}
os::SleepThread(TimeSpan::FromMilliSeconds(1));
}
}
bool IsKTraceEnabled() {
u64 value = 0;
R_ABORT_UNLESS(svc::GetInfo(std::addressof(value), svc::InfoType_MesosphereMeta, svc::InvalidHandle, svc::MesosphereMetaInfo_IsKTraceEnabled));
return value != 0;
}
ALWAYS_INLINE Result BoostThreadResourceLimitLocked(ResourceLimitGroup group) {
AMS_ASSERT(g_resource_limit_lock.IsLockedByCurrentThread());
/* Set new limit. */
const s64 new_thread_count = g_resource_limits[group][svc::LimitableResource_ThreadCountMax] + g_extra_threads_available[group];
R_TRY(svc::SetResourceLimitLimitValue(GetResourceLimitHandle(group), svc::LimitableResource_ThreadCountMax, new_thread_count));
/* Record that we did so. */
g_resource_limits[group][svc::LimitableResource_ThreadCountMax] = new_thread_count;
g_extra_threads_available[group] = 0;
R_SUCCEED();
}
template<auto ImplFunction>
ALWAYS_INLINE Result GetResourceLimitValueImpl(pm::ResourceLimitValue *out, ResourceLimitGroup group) {
/* Sanity check group. */
AMS_ABORT_UNLESS(group < ResourceLimitGroup_Count);
/* Get handle. */
const auto handle = GetResourceLimitHandle(group);
/* Get values. */
int64_t values[svc::LimitableResource_Count];
R_ABORT_UNLESS(ImplFunction(std::addressof(values[svc::LimitableResource_PhysicalMemoryMax]), handle, svc::LimitableResource_PhysicalMemoryMax));
R_ABORT_UNLESS(ImplFunction(std::addressof(values[svc::LimitableResource_ThreadCountMax]), handle, svc::LimitableResource_ThreadCountMax));
R_ABORT_UNLESS(ImplFunction(std::addressof(values[svc::LimitableResource_EventCountMax]), handle, svc::LimitableResource_EventCountMax));
R_ABORT_UNLESS(ImplFunction(std::addressof(values[svc::LimitableResource_TransferMemoryCountMax]), handle, svc::LimitableResource_TransferMemoryCountMax));
R_ABORT_UNLESS(ImplFunction(std::addressof(values[svc::LimitableResource_SessionCountMax]), handle, svc::LimitableResource_SessionCountMax));
/* Set to output. */
out->physical_memory = values[svc::LimitableResource_PhysicalMemoryMax];
out->thread_count = values[svc::LimitableResource_ThreadCountMax];
out->event_count = values[svc::LimitableResource_EventCountMax];
out->transfer_memory_count = values[svc::LimitableResource_TransferMemoryCountMax];
out->session_count = values[svc::LimitableResource_SessionCountMax];
R_SUCCEED();
}
Result BoostSystemMemoryResourceLimitLocked(u64 normal_boost, u64 mitm_boost) {
/* Check pre-conditions. */
AMS_ASSERT(g_system_memory_boost_lock.IsLockedByCurrentThread());
/* Determine total boost. */
const u64 boost_size = normal_boost + mitm_boost;
/* Don't allow all application memory to be taken away. */
R_UNLESS(boost_size < g_memory_resource_limits[g_memory_arrangement][ResourceLimitGroup_Application], pm::ResultInvalidSize());
const u64 new_app_size = g_memory_resource_limits[g_memory_arrangement][ResourceLimitGroup_Application] - boost_size;
{
std::scoped_lock lk(g_resource_limit_lock);
const auto cur_boost_size = GetCurrentSystemMemoryBoostSize();
if (hos::GetVersion() >= hos::Version_5_0_0) {
/* Starting in 5.0.0, PM does not allow for only one of the sets to fail. */
if (boost_size < cur_boost_size) {
R_TRY(svc::SetUnsafeLimit(boost_size));
R_ABORT_UNLESS(SetMemoryResourceLimitLimitValue(ResourceLimitGroup_Application, new_app_size));
} else if (boost_size > cur_boost_size) {
R_TRY(SetMemoryResourceLimitLimitValue(ResourceLimitGroup_Application, new_app_size));
R_ABORT_UNLESS(svc::SetUnsafeLimit(boost_size));
} else {
/* If the boost size is equal, there's nothing to do. */
}
} else {
const u64 new_sys_size = g_memory_resource_limits[g_memory_arrangement][ResourceLimitGroup_System] + boost_size;
if (boost_size < cur_boost_size) {
R_TRY(SetMemoryResourceLimitLimitValue(ResourceLimitGroup_System, new_sys_size));
R_TRY(SetMemoryResourceLimitLimitValue(ResourceLimitGroup_Application, new_app_size));
} else if (boost_size > cur_boost_size) {
R_TRY(SetMemoryResourceLimitLimitValue(ResourceLimitGroup_Application, new_app_size));
R_TRY(SetMemoryResourceLimitLimitValue(ResourceLimitGroup_System, new_sys_size));
} else {
/* If the boost size is equal, there's nothing to do. */
}
}
g_system_memory_boost_size = normal_boost;
g_system_memory_boost_size_for_mitm = mitm_boost;
}
R_SUCCEED();
}
}
Result InitializeSpec() {
/* Create resource limit handles. */
for (size_t i = 0; i < ResourceLimitGroup_Count; i++) {
if (i == ResourceLimitGroup_System) {
u64 value = 0;
R_ABORT_UNLESS(svc::GetInfo(&value, svc::InfoType_ResourceLimit, svc::InvalidHandle, 0));
g_resource_limit_handles[i] = static_cast<svc::Handle>(value);
} else {
R_ABORT_UNLESS(svc::CreateResourceLimit(g_resource_limit_handles + i));
}
}
/* Adjust memory limits based on hos firmware version. */
const auto hos_version = hos::GetVersion();
if (hos_version >= hos::Version_4_0_0) {
/* 4.0.0 took memory away from applet and gave it to system, for the Standard and StandardForSystemDev profiles. */
g_memory_resource_limits[spl::MemoryArrangement_Standard][ResourceLimitGroup_System] += ExtraSystemMemorySize400;
g_memory_resource_limits[spl::MemoryArrangement_Standard][ResourceLimitGroup_Applet] -= ExtraSystemMemorySize400;
g_memory_resource_limits[spl::MemoryArrangement_StandardForSystemDev][ResourceLimitGroup_System] += ExtraSystemMemorySize400;
g_memory_resource_limits[spl::MemoryArrangement_StandardForSystemDev][ResourceLimitGroup_Applet] -= ExtraSystemMemorySize400;
}
/* Determine system resource counts. */
{
/* Get the total resource counts. */
s64 total_events, total_transfer_memories, total_sessions;
R_ABORT_UNLESS(svc::GetResourceLimitLimitValue(std::addressof(total_events), GetResourceLimitHandle(ResourceLimitGroup_System), svc::LimitableResource_EventCountMax));
R_ABORT_UNLESS(svc::GetResourceLimitLimitValue(std::addressof(total_transfer_memories), GetResourceLimitHandle(ResourceLimitGroup_System), svc::LimitableResource_TransferMemoryCountMax));
R_ABORT_UNLESS(svc::GetResourceLimitLimitValue(std::addressof(total_sessions), GetResourceLimitHandle(ResourceLimitGroup_System), svc::LimitableResource_SessionCountMax));
/* Determine system counts. */
const s64 sys_events = total_events - (g_resource_limits[ResourceLimitGroup_Application][svc::LimitableResource_EventCountMax] + g_resource_limits[ResourceLimitGroup_Applet][svc::LimitableResource_EventCountMax]);
const s64 sys_transfer_memories = total_transfer_memories - (g_resource_limits[ResourceLimitGroup_Application][svc::LimitableResource_TransferMemoryCountMax] + g_resource_limits[ResourceLimitGroup_Applet][svc::LimitableResource_TransferMemoryCountMax]);
const s64 sys_sessions = total_sessions - (g_resource_limits[ResourceLimitGroup_Application][svc::LimitableResource_SessionCountMax] + g_resource_limits[ResourceLimitGroup_Applet][svc::LimitableResource_SessionCountMax]);
/* Check system counts. */
AMS_ABORT_UNLESS(sys_events >= 0);
AMS_ABORT_UNLESS(sys_transfer_memories >= 0);
AMS_ABORT_UNLESS(sys_sessions >= 0);
/* Set system counts. */
g_resource_limits[ResourceLimitGroup_System][svc::LimitableResource_EventCountMax] = sys_events;
g_resource_limits[ResourceLimitGroup_System][svc::LimitableResource_TransferMemoryCountMax] = sys_transfer_memories;
g_resource_limits[ResourceLimitGroup_System][svc::LimitableResource_SessionCountMax] = sys_sessions;
}
/* Determine extra application threads. */
{
/* Get total threads available. */
s64 total_threads;
R_ABORT_UNLESS(svc::GetResourceLimitLimitValue(std::addressof(total_threads), GetResourceLimitHandle(ResourceLimitGroup_System), svc::LimitableResource_ThreadCountMax));
/* Check that we have enough threads. */
const s64 required_threads = g_resource_limits[ResourceLimitGroup_System][svc::LimitableResource_ThreadCountMax] + g_resource_limits[ResourceLimitGroup_Application][svc::LimitableResource_ThreadCountMax] + g_resource_limits[ResourceLimitGroup_Applet][svc::LimitableResource_ThreadCountMax];
AMS_ABORT_UNLESS(total_threads >= required_threads);
/* Set the number of extra threads. */
const s64 extra_threads = total_threads - required_threads;
if constexpr (true /* TODO: Should we expose the old "all extra threads are application" behavior? Seems pointless. */) {
if (extra_threads > 0) {
/* If we have any extra threads at all, require that we have enough. */
AMS_ABORT_UNLESS(extra_threads >= (ExtraSystemThreads + ExtraApplicationThreads + ExtraAppletThreads));
g_extra_threads_available[ResourceLimitGroup_System] += ExtraSystemThreads;
g_extra_threads_available[ResourceLimitGroup_Application] += ExtraApplicationThreads;
g_extra_threads_available[ResourceLimitGroup_Applet] += ExtraAppletThreads;
}
} else {
g_extra_threads_available[ResourceLimitGroup_Application] = extra_threads;
}
}
/* Choose and initialize memory arrangement. */
const bool use_dynamic_memory_arrangement = (hos_version >= hos::Version_5_0_0);
if (use_dynamic_memory_arrangement) {
/* 6.0.0 retrieves memory limit information from the kernel, rather than using a hardcoded profile. */
g_memory_arrangement = spl::MemoryArrangement_Dynamic;
/* Get total memory available. */
s64 total_memory = 0;
R_ABORT_UNLESS(svc::GetResourceLimitLimitValue(&total_memory, GetResourceLimitHandle(ResourceLimitGroup_System), svc::LimitableResource_PhysicalMemoryMax));
/* Get and save application + applet memory. */
R_ABORT_UNLESS(svc::GetSystemInfo(std::addressof(g_memory_resource_limits[spl::MemoryArrangement_Dynamic][ResourceLimitGroup_Application]), svc::SystemInfoType_TotalPhysicalMemorySize, svc::InvalidHandle, svc::PhysicalMemorySystemInfo_Application));
R_ABORT_UNLESS(svc::GetSystemInfo(std::addressof(g_memory_resource_limits[spl::MemoryArrangement_Dynamic][ResourceLimitGroup_Applet]), svc::SystemInfoType_TotalPhysicalMemorySize, svc::InvalidHandle, svc::PhysicalMemorySystemInfo_Applet));
const s64 application_size = g_memory_resource_limits[spl::MemoryArrangement_Dynamic][ResourceLimitGroup_Application];
const s64 applet_size = g_memory_resource_limits[spl::MemoryArrangement_Dynamic][ResourceLimitGroup_Applet];
const s64 reserved_non_system_size = (application_size + applet_size + ReservedMemorySize600);
/* Ensure there's enough memory for the system region. */
AMS_ABORT_UNLESS(reserved_non_system_size < total_memory);
g_memory_resource_limits[spl::MemoryArrangement_Dynamic][ResourceLimitGroup_System] = total_memory - reserved_non_system_size;
} else {
/* Older system versions retrieve memory arrangement from spl, and use hardcoded profiles. */
g_memory_arrangement = spl::GetMemoryArrangement();
/* Adjust memory limits for atmosphere. */
/* We take memory away from applet normally, but away from application on < 3.0.0 to avoid a rare hang on boot. */
const size_t extra_memory_size = ExtraSystemMemorySizeAtmosphere;
const auto src_group = hos_version >= hos::Version_3_0_0 ? ResourceLimitGroup_Applet : ResourceLimitGroup_Application;
for (size_t i = 0; i < spl::MemoryArrangement_Count; i++) {
g_memory_resource_limits[i][ResourceLimitGroup_System] += extra_memory_size;
g_memory_resource_limits[i][src_group] -= extra_memory_size;
}
/* If KTrace is enabled, account for that by subtracting the memory from the applet pool. */
if (IsKTraceEnabled()) {
constexpr size_t KTraceBufferSize = 16_MB;
for (size_t i = 0; i < spl::MemoryArrangement_Count; i++) {
g_memory_resource_limits[i][ResourceLimitGroup_Applet] -= KTraceBufferSize;
}
}
}
/* Actually set resource limits. */
{
std::scoped_lock lk(g_resource_limit_lock);
for (size_t group = 0; group < ResourceLimitGroup_Count; group++) {
R_ABORT_UNLESS(SetResourceLimitLimitValues(static_cast<ResourceLimitGroup>(group), g_memory_resource_limits[g_memory_arrangement][group]));
}
}
R_SUCCEED();
}
Result BoostSystemMemoryResourceLimit(u64 boost_size) {
/* Ensure only one boost change happens at a time. */
std::scoped_lock lk(g_system_memory_boost_lock);
/* Boost to the appropriate total amount. */
R_RETURN(BoostSystemMemoryResourceLimitLocked(boost_size, g_system_memory_boost_size_for_mitm));
}
Result BoostSystemMemoryResourceLimitForMitm(u64 boost_size) {
/* Ensure only one boost change happens at a time. */
std::scoped_lock lk(g_system_memory_boost_lock);
/* Boost to the appropriate total amount. */
R_RETURN(BoostSystemMemoryResourceLimitLocked(g_system_memory_boost_size, boost_size));
}
Result BoostApplicationThreadResourceLimit() {
std::scoped_lock lk(g_resource_limit_lock);
/* Boost the limit. */
R_TRY(BoostThreadResourceLimitLocked(ResourceLimitGroup_Application));
R_SUCCEED();
}
Result BoostSystemThreadResourceLimit() {
std::scoped_lock lk(g_resource_limit_lock);
/* Boost the limits. */
R_TRY(BoostThreadResourceLimitLocked(ResourceLimitGroup_Applet));
R_TRY(BoostThreadResourceLimitLocked(ResourceLimitGroup_System));
R_SUCCEED();
}
os::NativeHandle GetResourceLimitHandle(ResourceLimitGroup group) {
return g_resource_limit_handles[group];
}
os::NativeHandle GetResourceLimitHandle(const ldr::ProgramInfo *info) {
return GetResourceLimitHandle(GetResourceLimitGroup(info));
}
void WaitResourceAvailable(const ldr::ProgramInfo *info) {
if (GetResourceLimitGroup(info) == ResourceLimitGroup_Application) {
WaitResourceAvailable(ResourceLimitGroup_Application);
if (hos::GetVersion() >= hos::Version_5_0_0) {
WaitApplicationMemoryAvailable();
}
}
}
Result GetResourceLimitCurrentValue(pm::ResourceLimitValue *out, ResourceLimitGroup group) {
R_RETURN(GetResourceLimitValueImpl<::ams::svc::GetResourceLimitCurrentValue>(out, group));
}
Result GetResourceLimitPeakValue(pm::ResourceLimitValue *out, ResourceLimitGroup group) {
R_RETURN(GetResourceLimitValueImpl<::ams::svc::GetResourceLimitPeakValue>(out, group));
}
Result GetResourceLimitLimitValue(pm::ResourceLimitValue *out, ResourceLimitGroup group) {
R_RETURN(GetResourceLimitValueImpl<::ams::svc::GetResourceLimitLimitValue>(out, group));
}
Result GetResourceLimitValues(s64 *out_cur, s64 *out_lim, ResourceLimitGroup group, svc::LimitableResource resource) {
/* Do not allow out of bounds access. */
AMS_ABORT_UNLESS(group < ResourceLimitGroup_Count);
AMS_ABORT_UNLESS(resource < svc::LimitableResource_Count);
const auto reslimit_hnd = GetResourceLimitHandle(group);
R_TRY(svc::GetResourceLimitCurrentValue(out_cur, reslimit_hnd, resource));
R_TRY(svc::GetResourceLimitLimitValue(out_lim, reslimit_hnd, resource));
R_SUCCEED();
}
}
| 26,359
|
C++
|
.cpp
| 405
| 52.469136
| 302
| 0.648098
|
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,254
|
pm_process_info.cpp
|
Atmosphere-NX_Atmosphere/stratosphere/pm/source/impl/pm_process_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 <stratosphere.hpp>
#include "pm_process_info.hpp"
namespace ams::pm::impl {
namespace {
template<size_t MaxProcessInfos>
class ProcessInfoAllocator {
NON_COPYABLE(ProcessInfoAllocator);
NON_MOVEABLE(ProcessInfoAllocator);
static_assert(MaxProcessInfos >= 0x40, "MaxProcessInfos is too small.");
private:
util::TypedStorage<ProcessInfo> m_process_info_storages[MaxProcessInfos]{};
bool m_process_info_allocated[MaxProcessInfos]{};
os::SdkMutex m_lock{};
private:
constexpr inline size_t GetProcessInfoIndex(ProcessInfo *process_info) const {
return process_info - GetPointer(m_process_info_storages[0]);
}
public:
constexpr ProcessInfoAllocator() = default;
template<typename... Args>
ProcessInfo *AllocateProcessInfo(Args &&... args) {
std::scoped_lock lk(m_lock);
for (size_t i = 0; i < MaxProcessInfos; i++) {
if (!m_process_info_allocated[i]) {
m_process_info_allocated[i] = true;
std::memset(m_process_info_storages + i, 0, sizeof(m_process_info_storages[i]));
return util::ConstructAt(m_process_info_storages[i], std::forward<Args>(args)...);
}
}
return nullptr;
}
void FreeProcessInfo(ProcessInfo *process_info) {
std::scoped_lock lk(m_lock);
const size_t index = this->GetProcessInfoIndex(process_info);
AMS_ABORT_UNLESS(index < MaxProcessInfos);
AMS_ABORT_UNLESS(m_process_info_allocated[index]);
util::DestroyAt(m_process_info_storages[index]);
m_process_info_allocated[index] = false;
}
};
/* Process lists. */
constinit ProcessList g_process_list;
constinit ProcessList g_exit_list;
/* Process Info Allocation. */
/* Note: The kernel slabheap is size 0x50 -- we allow slightly larger to account for the dead process list. */
constexpr size_t MaxProcessCount = 0x60;
constinit ProcessInfoAllocator<MaxProcessCount> g_process_info_allocator;
}
ProcessInfo::ProcessInfo(os::NativeHandle h, os::ProcessId pid, ldr::PinId pin, const ncm::ProgramLocation &l, const cfg::OverrideStatus &s) : m_process_id(pid), m_pin_id(pin), m_loc(l), m_status(s), m_handle(h), m_state(svc::ProcessState_Created), m_flags(0) {
os::InitializeMultiWaitHolder(std::addressof(m_multi_wait_holder), m_handle);
os::SetMultiWaitHolderUserData(std::addressof(m_multi_wait_holder), reinterpret_cast<uintptr_t>(this));
}
ProcessInfo::~ProcessInfo() {
this->Cleanup();
}
void ProcessInfo::Cleanup() {
if (m_handle != os::InvalidNativeHandle) {
/* Unregister the process. */
fsprUnregisterProgram(m_process_id.value);
sm::manager::UnregisterProcess(m_process_id);
ldr::pm::UnpinProgram(m_pin_id);
/* Close the process's handle. */
os::CloseNativeHandle(m_handle);
m_handle = os::InvalidNativeHandle;
}
}
ProcessListAccessor GetProcessList() {
return ProcessListAccessor(g_process_list);
}
ProcessListAccessor GetExitList() {
return ProcessListAccessor(g_exit_list);
}
ProcessInfo *AllocateProcessInfo(svc::Handle process_handle, os::ProcessId process_id, ldr::PinId pin_id, const ncm::ProgramLocation &location, const cfg::OverrideStatus &override_status) {
return g_process_info_allocator.AllocateProcessInfo(process_handle, process_id, pin_id, location, override_status);
}
void CleanupProcessInfo(ProcessListAccessor &list, ProcessInfo *process_info) {
/* Remove the process from the list. */
list->Remove(process_info);
/* Delete the process. */
g_process_info_allocator.FreeProcessInfo(process_info);
}
}
| 4,878
|
C++
|
.cpp
| 97
| 39.371134
| 265
| 0.626235
|
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,255
|
ptp_responder_mtp_operations.cpp
|
Atmosphere-NX_Atmosphere/troposphere/haze/source/ptp_responder_mtp_operations.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <haze.hpp>
#include <haze/ptp_data_builder.hpp>
#include <haze/ptp_data_parser.hpp>
#include <haze/ptp_responder_types.hpp>
namespace haze {
Result PtpResponder::GetObjectPropsSupported(PtpDataParser &dp) {
R_TRY(dp.Finalize());
PtpDataBuilder db(m_buffers->usb_bulk_write_buffer, std::addressof(m_usb_server));
/* Write information about all object properties we can support. */
R_TRY(db.WriteVariableLengthData(m_request_header, [&] {
R_RETURN(db.AddArray(SupportedObjectProperties, util::size(SupportedObjectProperties)));
}));
/* Write the success response. */
R_RETURN(this->WriteResponse(PtpResponseCode_Ok));
}
Result PtpResponder::GetObjectPropDesc(PtpDataParser &dp) {
PtpObjectPropertyCode property_code;
u16 object_format;
R_TRY(dp.Read(std::addressof(property_code)));
R_TRY(dp.Read(std::addressof(object_format)));
R_TRY(dp.Finalize());
/* Ensure we have a valid property code before continuing. */
R_UNLESS(IsSupportedObjectPropertyCode(property_code), haze::ResultUnknownPropertyCode());
/* Begin writing information about the property code. */
PtpDataBuilder db(m_buffers->usb_bulk_write_buffer, std::addressof(m_usb_server));
R_TRY(db.WriteVariableLengthData(m_request_header, [&] {
R_TRY(db.Add(property_code));
/* Each property code corresponds to a different pattern, which contains the data type, */
/* whether the property can be set for an object, and the default value of the property. */
switch (property_code) {
case PtpObjectPropertyCode_PersistentUniqueObjectIdentifier:
{
R_TRY(db.Add(PtpDataTypeCode_U128));
R_TRY(db.Add(PtpPropertyGetSetFlag_Get));
R_TRY(db.Add<u128>(0));
}
case PtpObjectPropertyCode_ObjectSize:
{
R_TRY(db.Add(PtpDataTypeCode_U64));
R_TRY(db.Add(PtpPropertyGetSetFlag_Get));
R_TRY(db.Add<u64>(0));
}
break;
case PtpObjectPropertyCode_StorageId:
case PtpObjectPropertyCode_ParentObject:
{
R_TRY(db.Add(PtpDataTypeCode_U32));
R_TRY(db.Add(PtpPropertyGetSetFlag_Get));
R_TRY(db.Add(StorageId_SdmcFs));
}
break;
case PtpObjectPropertyCode_ObjectFormat:
{
R_TRY(db.Add(PtpDataTypeCode_U16));
R_TRY(db.Add(PtpPropertyGetSetFlag_Get));
R_TRY(db.Add(PtpObjectFormatCode_Undefined));
}
break;
case PtpObjectPropertyCode_ObjectFileName:
{
R_TRY(db.Add(PtpDataTypeCode_String));
R_TRY(db.Add(PtpPropertyGetSetFlag_GetSet));
R_TRY(db.AddString(""));
}
break;
HAZE_UNREACHABLE_DEFAULT_CASE();
}
/* Group code is a required part of the response, but doesn't seem to be used for anything. */
R_TRY(db.Add(PtpPropertyGroupCode_Default));
/* We don't use the form flag. */
R_TRY(db.Add(PtpPropertyFormFlag_None));
R_SUCCEED();
}));
/* Write the success response. */
R_RETURN(this->WriteResponse(PtpResponseCode_Ok));
}
Result PtpResponder::GetObjectPropValue(PtpDataParser &dp) {
u32 object_id;
PtpObjectPropertyCode property_code;
R_TRY(dp.Read(std::addressof(object_id)));
R_TRY(dp.Read(std::addressof(property_code)));
R_TRY(dp.Finalize());
/* Ensure we have a valid property code before continuing. */
R_UNLESS(IsSupportedObjectPropertyCode(property_code), haze::ResultUnknownPropertyCode());
/* Check if we know about the object. If we don't, it's an error. */
auto * const obj = m_object_database.GetObjectById(object_id);
R_UNLESS(obj != nullptr, haze::ResultInvalidObjectId());
/* Define helper for getting the object type. */
const auto GetObjectType = [&] (FsDirEntryType *out_entry_type) {
R_RETURN(m_fs.GetEntryType(obj->GetName(), out_entry_type));
};
/* Define helper for getting the object size. */
const auto GetObjectSize = [&] (s64 *out_size) {
*out_size = 0;
/* Check if this is a directory. */
FsDirEntryType entry_type;
R_TRY(GetObjectType(std::addressof(entry_type)));
/* If it is, we're done. */
R_SUCCEED_IF(entry_type == FsDirEntryType_Dir);
/* Otherwise, open as a file. */
FsFile file;
R_TRY(m_fs.OpenFile(obj->GetName(), FsOpenMode_Read, std::addressof(file)));
/* Ensure we maintain a clean state on exit. */
ON_SCOPE_EXIT { m_fs.CloseFile(std::addressof(file)); };
R_RETURN(m_fs.GetFileSize(std::addressof(file), out_size));
};
/* Begin writing the requested object property. */
PtpDataBuilder db(m_buffers->usb_bulk_write_buffer, std::addressof(m_usb_server));
R_TRY(db.WriteVariableLengthData(m_request_header, [&] {
switch (property_code) {
case PtpObjectPropertyCode_PersistentUniqueObjectIdentifier:
{
R_TRY(db.Add<u128>(object_id));
}
break;
case PtpObjectPropertyCode_ObjectSize:
{
s64 size;
R_TRY(GetObjectSize(std::addressof(size)));
R_TRY(db.Add<u64>(size));
}
break;
case PtpObjectPropertyCode_StorageId:
{
R_TRY(db.Add(StorageId_SdmcFs));
}
break;
case PtpObjectPropertyCode_ParentObject:
{
R_TRY(db.Add(obj->GetParentId()));
}
break;
case PtpObjectPropertyCode_ObjectFormat:
{
FsDirEntryType entry_type;
R_TRY(GetObjectType(std::addressof(entry_type)));
R_TRY(db.Add(entry_type == FsDirEntryType_File ? PtpObjectFormatCode_Undefined : PtpObjectFormatCode_Association));
}
break;
case PtpObjectPropertyCode_ObjectFileName:
{
R_TRY(db.AddString(std::strrchr(obj->GetName(), '/') + 1));
}
break;
HAZE_UNREACHABLE_DEFAULT_CASE();
}
R_SUCCEED();
}));
/* Write the success response. */
R_RETURN(this->WriteResponse(PtpResponseCode_Ok));
}
Result PtpResponder::GetObjectPropList(PtpDataParser &dp) {
u32 object_id;
u32 object_format;
s32 property_code;
s32 group_code;
s32 depth;
R_TRY(dp.Read(std::addressof(object_id)));
R_TRY(dp.Read(std::addressof(object_format)));
R_TRY(dp.Read(std::addressof(property_code)));
R_TRY(dp.Read(std::addressof(group_code)));
R_TRY(dp.Read(std::addressof(depth)));
R_TRY(dp.Finalize());
/* Ensure format is unspecified. */
R_UNLESS(object_format == 0, haze::ResultInvalidArgument());
/* Ensure we have a valid property code. */
R_UNLESS(property_code == -1 || IsSupportedObjectPropertyCode(PtpObjectPropertyCode(property_code)), haze::ResultUnknownPropertyCode());
/* Ensure group code is the default. */
R_UNLESS(group_code == PtpPropertyGroupCode_Default, haze::ResultGroupSpecified());
/* Ensure depth is 0. */
R_UNLESS(depth == 0, haze::ResultDepthSpecified());
/* Check if we know about the object. If we don't, it's an error. */
auto * const obj = m_object_database.GetObjectById(object_id);
R_UNLESS(obj != nullptr, haze::ResultInvalidObjectId());
/* Define helper for getting the object type. */
const auto GetObjectType = [&] (FsDirEntryType *out_entry_type) {
R_RETURN(m_fs.GetEntryType(obj->GetName(), out_entry_type));
};
/* Define helper for getting the object size. */
const auto GetObjectSize = [&] (s64 *out_size) {
*out_size = 0;
/* Check if this is a directory. */
FsDirEntryType entry_type;
R_TRY(GetObjectType(std::addressof(entry_type)));
/* If it is, we're done. */
R_SUCCEED_IF(entry_type == FsDirEntryType_Dir);
/* Otherwise, open as a file. */
FsFile file;
R_TRY(m_fs.OpenFile(obj->GetName(), FsOpenMode_Read, std::addressof(file)));
/* Ensure we maintain a clean state on exit. */
ON_SCOPE_EXIT { m_fs.CloseFile(std::addressof(file)); };
R_RETURN(m_fs.GetFileSize(std::addressof(file), out_size));
};
/* Define helper for determining if the property should be included. */
const auto ShouldIncludeProperty = [&] (PtpObjectPropertyCode code) {
/* If all properties were requested, or it was the requested property, we should include the property. */
return property_code == -1 || code == property_code;
};
/* Determine how many output elements we will report. */
u32 num_output_elements = 0;
for (const auto obj_property : SupportedObjectProperties) {
if (ShouldIncludeProperty(obj_property)) {
num_output_elements++;
}
}
/* Begin writing the requested object properties. */
PtpDataBuilder db(m_buffers->usb_bulk_write_buffer, std::addressof(m_usb_server));
R_TRY(db.WriteVariableLengthData(m_request_header, [&] {
/* Report the number of elements. */
R_TRY(db.Add(num_output_elements));
for (const auto obj_property : SupportedObjectProperties) {
if (!ShouldIncludeProperty(obj_property)) {
continue;
}
/* Write the object handle. */
R_TRY(db.Add<u32>(object_id));
/* Write the property code. */
R_TRY(db.Add<u16>(obj_property));
/* Write the property value. */
switch (obj_property) {
case PtpObjectPropertyCode_PersistentUniqueObjectIdentifier:
{
R_TRY(db.Add(PtpDataTypeCode_U128));
R_TRY(db.Add<u128>(object_id));
}
break;
case PtpObjectPropertyCode_ObjectSize:
{
s64 size;
R_TRY(GetObjectSize(std::addressof(size)));
R_TRY(db.Add(PtpDataTypeCode_U64));
R_TRY(db.Add<u64>(size));
}
break;
case PtpObjectPropertyCode_StorageId:
{
R_TRY(db.Add(PtpDataTypeCode_U32));
R_TRY(db.Add(StorageId_SdmcFs));
}
break;
case PtpObjectPropertyCode_ParentObject:
{
R_TRY(db.Add(PtpDataTypeCode_U32));
R_TRY(db.Add(obj->GetParentId()));
}
break;
case PtpObjectPropertyCode_ObjectFormat:
{
FsDirEntryType entry_type;
R_TRY(GetObjectType(std::addressof(entry_type)));
R_TRY(db.Add(PtpDataTypeCode_U16));
R_TRY(db.Add(entry_type == FsDirEntryType_File ? PtpObjectFormatCode_Undefined : PtpObjectFormatCode_Association));
}
break;
case PtpObjectPropertyCode_ObjectFileName:
{
R_TRY(db.Add(PtpDataTypeCode_String));
R_TRY(db.AddString(std::strrchr(obj->GetName(), '/') + 1));
}
break;
HAZE_UNREACHABLE_DEFAULT_CASE();
}
}
R_SUCCEED();
}));
/* Write the success response. */
R_RETURN(this->WriteResponse(PtpResponseCode_Ok));
}
Result PtpResponder::SetObjectPropValue(PtpDataParser &rdp) {
u32 object_id;
PtpObjectPropertyCode property_code;
R_TRY(rdp.Read(std::addressof(object_id)));
R_TRY(rdp.Read(std::addressof(property_code)));
R_TRY(rdp.Finalize());
PtpDataParser dp(m_buffers->usb_bulk_read_buffer, std::addressof(m_usb_server));
/* Ensure we have a data header. */
PtpUsbBulkContainer data_header;
R_TRY(dp.Read(std::addressof(data_header)));
R_UNLESS(data_header.type == PtpUsbBulkContainerType_Data, haze::ResultUnknownRequestType());
R_UNLESS(data_header.code == m_request_header.code, haze::ResultOperationNotSupported());
R_UNLESS(data_header.trans_id == m_request_header.trans_id, haze::ResultOperationNotSupported());
/* Ensure we have a valid property code before continuing. */
R_UNLESS(property_code == PtpObjectPropertyCode_ObjectFileName, haze::ResultUnknownPropertyCode());
/* Check if we know about the object. If we don't, it's an error. */
auto * const obj = m_object_database.GetObjectById(object_id);
R_UNLESS(obj != nullptr, haze::ResultInvalidObjectId());
/* We are reading a file name. */
R_TRY(dp.ReadString(m_buffers->filename_string_buffer));
R_TRY(dp.Finalize());
/* Ensure we can actually process the new name. */
const bool is_empty = m_buffers->filename_string_buffer[0] == '\x00';
const bool contains_slashes = std::strchr(m_buffers->filename_string_buffer, '/') != nullptr;
R_UNLESS(!is_empty && !contains_slashes, haze::ResultInvalidPropertyValue());
/* Add a new object in the database with the new name. */
PtpObject *newobj;
{
/* Find the last path separator in the existing object name. */
char *pathsep = std::strrchr(obj->m_name, '/');
HAZE_ASSERT(pathsep != nullptr);
/* Temporarily mark the path separator as null to facilitate processing. */
*pathsep = '\x00';
ON_SCOPE_EXIT { *pathsep = '/'; };
R_TRY(m_object_database.CreateOrFindObject(obj->GetName(), m_buffers->filename_string_buffer, obj->GetParentId(), std::addressof(newobj)));
}
{
/* Ensure we maintain a clean state on failure. */
ON_RESULT_FAILURE {
if (!newobj->GetIsRegistered()) {
/* Only delete if the object was not registered. */
/* Otherwise, we would remove an object that still exists. */
m_object_database.DeleteObject(newobj);
}
};
/* Get the old object type. */
FsDirEntryType entry_type;
R_TRY(m_fs.GetEntryType(obj->GetName(), std::addressof(entry_type)));
/* Attempt to rename the object on the filesystem. */
if (entry_type == FsDirEntryType_Dir) {
R_TRY(m_fs.RenameDirectory(obj->GetName(), newobj->GetName()));
} else {
R_TRY(m_fs.RenameFile(obj->GetName(), newobj->GetName()));
}
}
/* Unregister and free the old object. */
m_object_database.DeleteObject(obj);
/* Register the new object. */
m_object_database.RegisterObject(newobj, object_id);
/* Write the success response. */
R_RETURN(this->WriteResponse(PtpResponseCode_Ok));
}
}
| 17,292
|
C++
|
.cpp
| 346
| 35.514451
| 151
| 0.553633
|
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,256
|
event_reactor.cpp
|
Atmosphere-NX_Atmosphere/troposphere/haze/source/event_reactor.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 <haze.hpp>
namespace haze {
bool EventReactor::AddConsumer(EventConsumer *consumer, Waiter waiter) {
HAZE_ASSERT(m_num_wait_objects + 1 <= svc::ArgumentHandleCountMax);
/* Add to the end of the list. */
m_consumers[m_num_wait_objects] = consumer;
m_waiters[m_num_wait_objects] = waiter;
m_num_wait_objects++;
return true;
}
void EventReactor::RemoveConsumer(EventConsumer *consumer) {
s32 output_index = 0;
/* Remove the consumer. */
for (s32 input_index = 0; input_index < m_num_wait_objects; input_index++) {
if (m_consumers[input_index] == consumer) {
continue;
}
if (output_index != input_index) {
m_consumers[output_index] = m_consumers[input_index];
m_waiters[output_index] = m_waiters[input_index];
}
output_index++;
}
m_num_wait_objects = output_index;
}
Result EventReactor::WaitForImpl(s32 *out_arg_waiter, const Waiter *arg_waiters, s32 num_arg_waiters) {
HAZE_ASSERT(0 < num_arg_waiters && num_arg_waiters <= svc::ArgumentHandleCountMax);
HAZE_ASSERT(m_num_wait_objects + num_arg_waiters <= svc::ArgumentHandleCountMax);
while (true) {
/* Check if we should wait for an event. */
R_TRY(m_result);
/* Insert waiters from argument list. */
for (s32 i = 0; i < num_arg_waiters; i++) {
m_waiters[i + m_num_wait_objects] = arg_waiters[i];
}
s32 idx;
HAZE_R_ABORT_UNLESS(waitObjects(std::addressof(idx), m_waiters, m_num_wait_objects + num_arg_waiters, svc::WaitInfinite));
/* If a waiter in the argument list was signaled, return it. */
if (idx >= m_num_wait_objects) {
*out_arg_waiter = idx - m_num_wait_objects;
R_SUCCEED();
}
/* Otherwise, process the event as normal. */
m_consumers[idx]->ProcessEvent();
}
}
}
| 2,730
|
C++
|
.cpp
| 62
| 35.387097
| 134
| 0.613122
|
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,257
|
ptp_object_database.cpp
|
Atmosphere-NX_Atmosphere/troposphere/haze/source/ptp_object_database.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 <haze.hpp>
namespace haze {
void PtpObjectDatabase::Initialize(PtpObjectHeap *object_heap) {
m_object_heap = object_heap;
m_object_heap->Initialize();
std::construct_at(std::addressof(m_name_tree));
std::construct_at(std::addressof(m_object_id_tree));
m_next_object_id = 1;
}
void PtpObjectDatabase::Finalize() {
std::destroy_at(std::addressof(m_object_id_tree));
std::destroy_at(std::addressof(m_name_tree));
m_next_object_id = 0;
m_object_heap->Finalize();
m_object_heap = nullptr;
}
Result PtpObjectDatabase::CreateOrFindObject(const char *parent_name, const char *name, u32 parent_id, PtpObject **out_object) {
constexpr auto separator = "/";
/* Calculate length of the new name with null terminator. */
const size_t parent_name_len = util::Strlen(parent_name);
const size_t separator_len = util::Strlen(separator);
const size_t name_len = util::Strlen(name);
const size_t terminator_len = 1;
const size_t alloc_len = sizeof(PtpObject) + parent_name_len + separator_len + name_len + terminator_len;
/* Allocate memory for the object. */
PtpObject * const object = m_object_heap->Allocate<PtpObject>(alloc_len);
R_UNLESS(object != nullptr, haze::ResultOutOfMemory());
/* Build the object name. */
std::strncpy(object->m_name, parent_name, parent_name_len + terminator_len);
std::strncpy(object->m_name + parent_name_len, separator, separator_len + terminator_len);
std::strncpy(object->m_name + parent_name_len + separator_len, name, name_len + terminator_len);
{
/* Ensure we maintain a clean state on failure. */
auto guard = SCOPE_GUARD { m_object_heap->Deallocate(object, alloc_len); };
/* Check if an object with this name already exists. If it does, we can just return it here. */
if (auto * const existing = this->GetObjectByName(object->GetName()); existing != nullptr) {
*out_object = existing;
R_SUCCEED();
}
/* Persist the reference to the object. */
guard.Cancel();
}
/* Set object properties. */
object->m_parent_id = parent_id;
object->m_object_id = 0;
/* Set output. */
*out_object = object;
/* We succeeded. */
R_SUCCEED();
}
void PtpObjectDatabase::RegisterObject(PtpObject *object, u32 desired_id) {
/* If the object is already registered, skip registration. */
if (object->GetIsRegistered()) {
return;
}
/* Set desired object ID. */
if (desired_id == 0) {
desired_id = m_next_object_id++;
}
/* Insert object into trees. */
object->Register(desired_id);
m_object_id_tree.insert(*object);
m_name_tree.insert(*object);
}
void PtpObjectDatabase::UnregisterObject(PtpObject *object) {
/* If the object is not registered, skip trying to unregister. */
if (!object->GetIsRegistered()) {
return;
}
/* Remove object from trees. */
m_object_id_tree.erase(m_object_id_tree.iterator_to(*object));
m_name_tree.erase(m_name_tree.iterator_to(*object));
object->Unregister();
}
void PtpObjectDatabase::DeleteObject(PtpObject *object) {
/* Unregister the object as required. */
this->UnregisterObject(object);
/* Free the object. */
m_object_heap->Deallocate(object, sizeof(PtpObject) + std::strlen(object->GetName()) + 1);
}
Result PtpObjectDatabase::CreateAndRegisterObjectId(const char *parent_name, const char *name, u32 parent_id, u32 *out_object_id) {
/* Try to create the object. */
PtpObject *object;
R_TRY(this->CreateOrFindObject(parent_name, name, parent_id, std::addressof(object)));
/* We succeeded, so register it. */
this->RegisterObject(object);
/* Set the output ID. */
*out_object_id = object->GetObjectId();
R_SUCCEED();
}
PtpObject *PtpObjectDatabase::GetObjectById(u32 object_id) {
/* Find in ID mapping. */
if (auto it = m_object_id_tree.find_key(object_id); it != m_object_id_tree.end()) {
return std::addressof(*it);
} else {
return nullptr;
}
}
PtpObject *PtpObjectDatabase::GetObjectByName(const char *name) {
/* Find in name mapping. */
if (auto it = m_name_tree.find_key(name); it != m_name_tree.end()) {
return std::addressof(*it);
} else {
return nullptr;
}
}
}
| 5,478
|
C++
|
.cpp
| 122
| 36.721311
| 135
| 0.61303
|
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,258
|
main.cpp
|
Atmosphere-NX_Atmosphere/troposphere/haze/source/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 <haze.hpp>
#include <haze/console_main_loop.hpp>
int main(int argc, char **argv) {
/* Load device firmware version and serial number. */
HAZE_R_ABORT_UNLESS(haze::LoadDeviceProperties());
/* Run the application. */
haze::ConsoleMainLoop::RunApplication();
/* Return to the loader. */
return 0;
}
| 967
|
C++
|
.cpp
| 25
| 36.04
| 76
| 0.732694
|
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,259
|
ptp_object_heap.cpp
|
Atmosphere-NX_Atmosphere/troposphere/haze/source/ptp_object_heap.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 <haze.hpp>
namespace haze {
namespace {
/* Allow 30MiB for use by libnx. */
static constexpr size_t LibnxReservedMemorySize = 30_MB;
}
void PtpObjectHeap::Initialize() {
/* If we're already initialized, skip re-initialization. */
if (m_heap_block_size != 0) {
return;
}
/* Estimate how much memory we can reserve. */
size_t mem_used = 0;
HAZE_R_ABORT_UNLESS(svcGetInfo(std::addressof(mem_used), InfoType_UsedMemorySize, svc::CurrentProcess, 0));
HAZE_ASSERT(mem_used > LibnxReservedMemorySize);
mem_used -= LibnxReservedMemorySize;
/* Calculate size of blocks. */
m_heap_block_size = mem_used / NumHeapBlocks;
HAZE_ASSERT(m_heap_block_size > 0);
/* Allocate the memory. */
for (size_t i = 0; i < NumHeapBlocks; i++) {
m_heap_blocks[i] = std::malloc(m_heap_block_size);
HAZE_ASSERT(m_heap_blocks[i] != nullptr);
}
/* Set the address to allocate from. */
m_next_address = m_heap_blocks[0];
}
void PtpObjectHeap::Finalize() {
if (m_heap_block_size == 0) {
return;
}
/* Tear down the heap, allowing a subsequent call to Initialize() if desired. */
for (size_t i = 0; i < NumHeapBlocks; i++) {
std::free(m_heap_blocks[i]);
m_heap_blocks[i] = nullptr;
}
m_next_address = nullptr;
m_heap_block_size = 0;
m_current_heap_block = 0;
}
}
| 2,197
|
C++
|
.cpp
| 56
| 32.321429
| 115
| 0.62453
|
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,260
|
async_usb_server.cpp
|
Atmosphere-NX_Atmosphere/troposphere/haze/source/async_usb_server.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <haze.hpp>
namespace haze {
namespace {
constinit UsbSession g_usb_session;
}
Result AsyncUsbServer::Initialize(const UsbCommsInterfaceInfo *interface_info, u16 id_vendor, u16 id_product, EventReactor *reactor) {
m_reactor = reactor;
/* Set up a new USB session. */
R_TRY(g_usb_session.Initialize(interface_info, id_vendor, id_product));
R_SUCCEED();
}
void AsyncUsbServer::Finalize() {
g_usb_session.Finalize();
}
Result AsyncUsbServer::TransferPacketImpl(bool read, void *page, u32 size, u32 *out_size_transferred) const {
u32 urb_id;
s32 waiter_idx;
/* If we're not configured yet, wait to become configured first. */
if (!g_usb_session.GetConfigured()) {
R_TRY(m_reactor->WaitFor(std::addressof(waiter_idx), waiterForEvent(usbDsGetStateChangeEvent())));
R_TRY(eventClear(usbDsGetStateChangeEvent()));
R_THROW(haze::ResultNotConfigured());
}
/* Select the appropriate endpoint and begin a transfer. */
UsbSessionEndpoint ep = read ? UsbSessionEndpoint_Read : UsbSessionEndpoint_Write;
R_TRY(g_usb_session.TransferAsync(ep, page, size, std::addressof(urb_id)));
/* Try to wait for the event. */
R_TRY(m_reactor->WaitFor(std::addressof(waiter_idx), waiterForEvent(g_usb_session.GetCompletionEvent(ep))));
/* Return what we transferred. */
R_RETURN(g_usb_session.GetTransferResult(ep, urb_id, out_size_transferred));
}
}
| 2,192
|
C++
|
.cpp
| 47
| 40.510638
| 138
| 0.69108
|
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,261
|
ptp_responder_android_operations.cpp
|
Atmosphere-NX_Atmosphere/troposphere/haze/source/ptp_responder_android_operations.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <haze.hpp>
#include <haze/ptp_data_builder.hpp>
#include <haze/ptp_data_parser.hpp>
#include <haze/ptp_responder_types.hpp>
namespace haze {
Result PtpResponder::GetPartialObject64(PtpDataParser &dp) {
PtpDataBuilder db(m_buffers->usb_bulk_write_buffer, std::addressof(m_usb_server));
/* Get the object ID, offset, and size for the file we want to read. */
u32 object_id, size;
u64 offset;
R_TRY(dp.Read(std::addressof(object_id)));
R_TRY(dp.Read(std::addressof(offset)));
R_TRY(dp.Read(std::addressof(size)));
R_TRY(dp.Finalize());
/* Check if we know about the object. If we don't, it's an error. */
auto * const obj = m_object_database.GetObjectById(object_id);
R_UNLESS(obj != nullptr, haze::ResultInvalidObjectId());
/* Lock the object as a file. */
FsFile file;
R_TRY(m_fs.OpenFile(obj->GetName(), FsOpenMode_Read, std::addressof(file)));
/* Ensure we maintain a clean state on exit. */
ON_SCOPE_EXIT { m_fs.CloseFile(std::addressof(file)); };
/* Get the file's size. */
s64 file_size = 0;
R_TRY(m_fs.GetFileSize(std::addressof(file), std::addressof(file_size)));
/* Ensure the requested offset and size are within range. */
R_UNLESS(offset + size > offset, haze::ResultInvalidArgument());
R_UNLESS(static_cast<u64>(file_size) <= offset + size, haze::ResultInvalidArgument());
/* Send the header and data size. */
R_TRY(db.AddDataHeader(m_request_header, size));
/* Begin reading the file, writing data to the builder as we progress. */
s64 size_remaining = size;
while (true) {
/* Get the next batch. */
u64 bytes_to_read = std::min<s64>(FsBufferSize, size_remaining);
u64 bytes_read;
R_TRY(m_fs.ReadFile(std::addressof(file), offset, m_buffers->file_system_data_buffer, bytes_to_read, FsReadOption_None, std::addressof(bytes_read)));
size_remaining -= bytes_read;
offset += bytes_read;
/* Write to output. */
R_TRY(db.AddBuffer(m_buffers->file_system_data_buffer, bytes_read));
/* If we read fewer bytes than the batch size, or have read enough data, we're done. */
if (bytes_read < FsBufferSize || size_remaining == 0) {
break;
}
}
/* Flush the data response. */
R_TRY(db.Commit());
/* Write the success response. */
R_RETURN(this->WriteResponse(PtpResponseCode_Ok));
}
Result PtpResponder::SendPartialObject(PtpDataParser &rdp) {
/* Get the object ID, offset, and size for the file we want to write. */
u32 object_id, size;
u64 offset;
R_TRY(rdp.Read(std::addressof(object_id)));
R_TRY(rdp.Read(std::addressof(size)));
R_TRY(rdp.Read(std::addressof(offset)));
R_TRY(rdp.Finalize());
/* Check if we know about the object. If we don't, it's an error. */
auto * const obj = m_object_database.GetObjectById(m_send_object_id);
R_UNLESS(obj != nullptr, haze::ResultInvalidObjectId());
/* Lock the object as a file. */
FsFile file;
R_TRY(m_fs.OpenFile(obj->GetName(), FsOpenMode_Write | FsOpenMode_Append, std::addressof(file)));
/* Ensure we maintain a clean state on exit. */
ON_SCOPE_EXIT { m_fs.CloseFile(std::addressof(file)); };
/* Get the file's size. */
s64 file_size = 0;
R_TRY(m_fs.GetFileSize(std::addressof(file), std::addressof(file_size)));
/* Ensure the requested offset and size are within range. */
R_UNLESS(offset + size > offset, haze::ResultInvalidArgument());
R_UNLESS(static_cast<u64>(file_size) <= offset, haze::ResultInvalidArgument());
/* Prepare a data parser for the data we are about to receive. */
PtpDataParser dp(m_buffers->usb_bulk_read_buffer, std::addressof(m_usb_server));
/* Ensure we have a data header. */
PtpUsbBulkContainer data_header;
R_TRY(dp.Read(std::addressof(data_header)));
R_UNLESS(data_header.type == PtpUsbBulkContainerType_Data, haze::ResultUnknownRequestType());
R_UNLESS(data_header.code == m_request_header.code, haze::ResultOperationNotSupported());
R_UNLESS(data_header.trans_id == m_request_header.trans_id, haze::ResultOperationNotSupported());
/* Begin writing to the filesystem. */
s64 size_remaining = size;
while (true) {
/* Read as many bytes as we can. */
u32 bytes_received;
const Result read_res = dp.ReadBuffer(m_buffers->file_system_data_buffer, FsBufferSize, std::addressof(bytes_received));
/* Write to the file. */
u32 bytes_to_write = std::min<s64>(size_remaining, bytes_received);
R_TRY(m_fs.WriteFile(std::addressof(file), offset, m_buffers->file_system_data_buffer, bytes_to_write, 0));
size_remaining -= bytes_to_write;
offset += bytes_to_write;
/* If we received fewer bytes than the batch size, or have written enough data, we're done. */
if (haze::ResultEndOfTransmission::Includes(read_res) || size_remaining == 0) {
break;
}
R_TRY(read_res);
}
/* Write the success response. */
R_RETURN(this->WriteResponse(PtpResponseCode_Ok));
}
Result PtpResponder::TruncateObject(PtpDataParser &dp) {
/* Get the object ID and size for the file we want to truncate. */
u32 object_id;
u64 size;
R_TRY(dp.Read(std::addressof(object_id)));
R_TRY(dp.Read(std::addressof(size)));
R_TRY(dp.Finalize());
/* Check if we know about the object. If we don't, it's an error. */
auto * const obj = m_object_database.GetObjectById(object_id);
R_UNLESS(obj != nullptr, haze::ResultInvalidObjectId());
/* Lock the object as a file. */
FsFile file;
R_TRY(m_fs.OpenFile(obj->GetName(), FsOpenMode_Write, std::addressof(file)));
/* Ensure we maintain a clean state on exit. */
ON_SCOPE_EXIT { m_fs.CloseFile(std::addressof(file)); };
/* Truncate the file. */
R_TRY(m_fs.SetFileSize(std::addressof(file), size));
/* Write the success response. */
R_RETURN(this->WriteResponse(PtpResponseCode_Ok));
}
Result PtpResponder::BeginEditObject(PtpDataParser &dp) {
/* Get the object ID we are going to begin editing. */
u32 object_id;
R_TRY(dp.Read(std::addressof(object_id)));
R_TRY(dp.Finalize());
/* Check if we know about the object. If we don't, it's an error. */
auto * const obj = m_object_database.GetObjectById(object_id);
R_UNLESS(obj != nullptr, haze::ResultInvalidObjectId());
/* We don't implement transactions, so write the success response. */
R_RETURN(this->WriteResponse(PtpResponseCode_Ok));
}
Result PtpResponder::EndEditObject(PtpDataParser &dp) {
/* Get the object ID we are going to finish editing. */
u32 object_id;
R_TRY(dp.Read(std::addressof(object_id)));
R_TRY(dp.Finalize());
/* Check if we know about the object. If we don't, it's an error. */
auto * const obj = m_object_database.GetObjectById(object_id);
R_UNLESS(obj != nullptr, haze::ResultInvalidObjectId());
/* We don't implement transactions, so write the success response. */
R_RETURN(this->WriteResponse(PtpResponseCode_Ok));
}
}
| 8,331
|
C++
|
.cpp
| 159
| 43.660377
| 161
| 0.631275
|
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,262
|
usb_session.cpp
|
Atmosphere-NX_Atmosphere/troposphere/haze/source/usb_session.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <haze.hpp>
namespace haze {
namespace {
constexpr const u32 DefaultInterfaceNumber = 0;
}
Result UsbSession::Initialize1x(const UsbCommsInterfaceInfo *info) {
struct usb_interface_descriptor interface_descriptor = {
.bLength = USB_DT_INTERFACE_SIZE,
.bDescriptorType = USB_DT_INTERFACE,
.bInterfaceNumber = DefaultInterfaceNumber,
.bInterfaceClass = info->bInterfaceClass,
.bInterfaceSubClass = info->bInterfaceSubClass,
.bInterfaceProtocol = info->bInterfaceProtocol,
};
struct usb_endpoint_descriptor endpoint_descriptor_in = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_ENDPOINT_IN,
.bmAttributes = USB_TRANSFER_TYPE_BULK,
.wMaxPacketSize = PtpUsbBulkHighSpeedMaxPacketLength,
};
struct usb_endpoint_descriptor endpoint_descriptor_out = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_ENDPOINT_OUT,
.bmAttributes = USB_TRANSFER_TYPE_BULK,
.wMaxPacketSize = PtpUsbBulkHighSpeedMaxPacketLength,
};
struct usb_endpoint_descriptor endpoint_descriptor_interrupt = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_ENDPOINT_IN,
.bmAttributes = USB_TRANSFER_TYPE_INTERRUPT,
.wMaxPacketSize = 0x18,
.bInterval = 0x4,
};
/* Set up interface. */
R_TRY(usbDsGetDsInterface(std::addressof(m_interface), std::addressof(interface_descriptor), "usb"));
/* Set up endpoints. */
R_TRY(usbDsInterface_GetDsEndpoint(m_interface, std::addressof(m_endpoints[UsbSessionEndpoint_Write]), std::addressof(endpoint_descriptor_in)));
R_TRY(usbDsInterface_GetDsEndpoint(m_interface, std::addressof(m_endpoints[UsbSessionEndpoint_Read]), std::addressof(endpoint_descriptor_out)));
R_TRY(usbDsInterface_GetDsEndpoint(m_interface, std::addressof(m_endpoints[UsbSessionEndpoint_Interrupt]), std::addressof(endpoint_descriptor_interrupt)));
R_RETURN(usbDsInterface_EnableInterface(m_interface));
}
Result UsbSession::Initialize5x(const UsbCommsInterfaceInfo *info) {
struct usb_interface_descriptor interface_descriptor = {
.bLength = USB_DT_INTERFACE_SIZE,
.bDescriptorType = USB_DT_INTERFACE,
.bInterfaceNumber = DefaultInterfaceNumber,
.bNumEndpoints = 3,
.bInterfaceClass = info->bInterfaceClass,
.bInterfaceSubClass = info->bInterfaceSubClass,
.bInterfaceProtocol = info->bInterfaceProtocol,
};
struct usb_endpoint_descriptor endpoint_descriptor_in = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_ENDPOINT_IN,
.bmAttributes = USB_TRANSFER_TYPE_BULK,
.wMaxPacketSize = PtpUsbBulkHighSpeedMaxPacketLength,
};
struct usb_endpoint_descriptor endpoint_descriptor_out = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_ENDPOINT_OUT,
.bmAttributes = USB_TRANSFER_TYPE_BULK,
.wMaxPacketSize = PtpUsbBulkHighSpeedMaxPacketLength,
};
struct usb_endpoint_descriptor endpoint_descriptor_interrupt = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_ENDPOINT_IN,
.bmAttributes = USB_TRANSFER_TYPE_INTERRUPT,
.wMaxPacketSize = 0x18,
.bInterval = 0x6,
};
struct usb_ss_endpoint_companion_descriptor endpoint_companion = {
.bLength = sizeof(struct usb_ss_endpoint_companion_descriptor),
.bDescriptorType = USB_DT_SS_ENDPOINT_COMPANION,
.bMaxBurst = 0x0f,
.bmAttributes = 0x00,
.wBytesPerInterval = 0x00,
};
struct usb_ss_endpoint_companion_descriptor endpoint_companion_interrupt = {
.bLength = sizeof(struct usb_ss_endpoint_companion_descriptor),
.bDescriptorType = USB_DT_SS_ENDPOINT_COMPANION,
.bMaxBurst = 0x00,
.bmAttributes = 0x00,
.wBytesPerInterval = 0x00,
};
R_TRY(usbDsRegisterInterface(std::addressof(m_interface)));
u8 iInterface;
R_TRY(usbDsAddUsbStringDescriptor(std::addressof(iInterface), "MTP"));
interface_descriptor.bInterfaceNumber = m_interface->interface_index;
interface_descriptor.iInterface = iInterface;
endpoint_descriptor_in.bEndpointAddress += interface_descriptor.bInterfaceNumber + 1;
endpoint_descriptor_out.bEndpointAddress += interface_descriptor.bInterfaceNumber + 1;
endpoint_descriptor_interrupt.bEndpointAddress += interface_descriptor.bInterfaceNumber + 2;
/* High speed config. */
R_TRY(usbDsInterface_AppendConfigurationData(m_interface, UsbDeviceSpeed_High, std::addressof(interface_descriptor), USB_DT_INTERFACE_SIZE));
R_TRY(usbDsInterface_AppendConfigurationData(m_interface, UsbDeviceSpeed_High, std::addressof(endpoint_descriptor_in), USB_DT_ENDPOINT_SIZE));
R_TRY(usbDsInterface_AppendConfigurationData(m_interface, UsbDeviceSpeed_High, std::addressof(endpoint_descriptor_out), USB_DT_ENDPOINT_SIZE));
R_TRY(usbDsInterface_AppendConfigurationData(m_interface, UsbDeviceSpeed_High, std::addressof(endpoint_descriptor_interrupt), USB_DT_ENDPOINT_SIZE));
/* Super speed config. */
endpoint_descriptor_in.wMaxPacketSize = PtpUsbBulkSuperSpeedMaxPacketLength;
endpoint_descriptor_out.wMaxPacketSize = PtpUsbBulkSuperSpeedMaxPacketLength;
R_TRY(usbDsInterface_AppendConfigurationData(m_interface, UsbDeviceSpeed_Super, std::addressof(interface_descriptor), USB_DT_INTERFACE_SIZE));
R_TRY(usbDsInterface_AppendConfigurationData(m_interface, UsbDeviceSpeed_Super, std::addressof(endpoint_descriptor_in), USB_DT_ENDPOINT_SIZE));
R_TRY(usbDsInterface_AppendConfigurationData(m_interface, UsbDeviceSpeed_Super, std::addressof(endpoint_companion), USB_DT_SS_ENDPOINT_COMPANION_SIZE));
R_TRY(usbDsInterface_AppendConfigurationData(m_interface, UsbDeviceSpeed_Super, std::addressof(endpoint_descriptor_out), USB_DT_ENDPOINT_SIZE));
R_TRY(usbDsInterface_AppendConfigurationData(m_interface, UsbDeviceSpeed_Super, std::addressof(endpoint_companion), USB_DT_SS_ENDPOINT_COMPANION_SIZE));
R_TRY(usbDsInterface_AppendConfigurationData(m_interface, UsbDeviceSpeed_Super, std::addressof(endpoint_descriptor_interrupt), USB_DT_ENDPOINT_SIZE));
R_TRY(usbDsInterface_AppendConfigurationData(m_interface, UsbDeviceSpeed_Super, std::addressof(endpoint_companion_interrupt), USB_DT_SS_ENDPOINT_COMPANION_SIZE));
/* Set up endpoints. */
R_TRY(usbDsInterface_RegisterEndpoint(m_interface, std::addressof(m_endpoints[UsbSessionEndpoint_Write]), endpoint_descriptor_in.bEndpointAddress));
R_TRY(usbDsInterface_RegisterEndpoint(m_interface, std::addressof(m_endpoints[UsbSessionEndpoint_Read]), endpoint_descriptor_out.bEndpointAddress));
R_TRY(usbDsInterface_RegisterEndpoint(m_interface, std::addressof(m_endpoints[UsbSessionEndpoint_Interrupt]), endpoint_descriptor_interrupt.bEndpointAddress));
R_RETURN(usbDsInterface_EnableInterface(m_interface));
}
Result UsbSession::Initialize(const UsbCommsInterfaceInfo *info, u16 id_vendor, u16 id_product) {
R_TRY(usbDsInitialize());
if (hosversionAtLeast(5, 0, 0)) {
/* Report language as US English. */
static const u16 supported_langs[1] = { 0x0409 };
R_TRY(usbDsAddUsbLanguageStringDescriptor(nullptr, supported_langs, util::size(supported_langs)));
/* Report strings. */
u8 iManufacturer, iProduct, iSerialNumber;
R_TRY(usbDsAddUsbStringDescriptor(std::addressof(iManufacturer), "Nintendo"));
R_TRY(usbDsAddUsbStringDescriptor(std::addressof(iProduct), "Nintendo Switch"));
R_TRY(usbDsAddUsbStringDescriptor(std::addressof(iSerialNumber), GetSerialNumber()));
/* Send device descriptors */
struct usb_device_descriptor device_descriptor = {
.bLength = USB_DT_DEVICE_SIZE,
.bDescriptorType = USB_DT_DEVICE,
.bcdUSB = 0x0200,
.bDeviceClass = 0x00,
.bDeviceSubClass = 0x00,
.bDeviceProtocol = 0x00,
.bMaxPacketSize0 = 0x40,
.idVendor = id_vendor,
.idProduct = id_product,
.bcdDevice = 0x0100,
.iManufacturer = iManufacturer,
.iProduct = iProduct,
.iSerialNumber = iSerialNumber,
.bNumConfigurations = 0x01
};
R_TRY(usbDsSetUsbDeviceDescriptor(UsbDeviceSpeed_High, std::addressof(device_descriptor)));
device_descriptor.bcdUSB = 0x0300;
device_descriptor.bMaxPacketSize0 = 0x09;
R_TRY(usbDsSetUsbDeviceDescriptor(UsbDeviceSpeed_Super, std::addressof(device_descriptor)));
/* Binary Object Store */
u8 bos[0x16] = {
0x05, /* .bLength */
USB_DT_BOS, /* .bDescriptorType */
0x16, 0x00, /* .wTotalLength */
0x02, /* .bNumDeviceCaps */
/* USB 2.0 */
0x07, /* .bLength */
USB_DT_DEVICE_CAPABILITY, /* .bDescriptorType */
0x02, /* .bDevCapabilityType */
0x02, 0x00, 0x00, 0x00, /* .bmAttributes */
/* USB 3.0 */
0x0a, /* .bLength */
USB_DT_DEVICE_CAPABILITY, /* .bDescriptorType */
0x03, /* .bDevCapabilityType */
0x00, /* .bmAttributes */
0x0c, 0x00, /* .wSpeedSupported */
0x03, /* .bFunctionalitySupport */
0x00, /* .bU1DevExitLat */
0x00, 0x00 /* .bU2DevExitLat */
};
R_TRY(usbDsSetBinaryObjectStore(bos, sizeof(bos)));
}
if (hosversionAtLeast(5, 0, 0)) {
R_TRY(this->Initialize5x(info));
R_TRY(usbDsEnable());
} else {
R_TRY(this->Initialize1x(info));
}
R_SUCCEED();
}
void UsbSession::Finalize() {
usbDsExit();
}
bool UsbSession::GetConfigured() const {
UsbState usb_state;
HAZE_R_ABORT_UNLESS(usbDsGetState(std::addressof(usb_state)));
return usb_state == UsbState_Configured;
}
Event *UsbSession::GetCompletionEvent(UsbSessionEndpoint ep) const {
return std::addressof(m_endpoints[ep]->CompletionEvent);
}
Result UsbSession::TransferAsync(UsbSessionEndpoint ep, void *buffer, u32 size, u32 *out_urb_id) {
R_RETURN(usbDsEndpoint_PostBufferAsync(m_endpoints[ep], buffer, size, out_urb_id));
}
Result UsbSession::GetTransferResult(UsbSessionEndpoint ep, u32 urb_id, u32 *out_transferred_size) {
UsbDsReportData report_data;
R_TRY(eventClear(std::addressof(m_endpoints[ep]->CompletionEvent)));
R_TRY(usbDsEndpoint_GetReportData(m_endpoints[ep], std::addressof(report_data)));
R_TRY(usbDsParseReportData(std::addressof(report_data), urb_id, nullptr, out_transferred_size));
R_SUCCEED();
}
}
| 12,855
|
C++
|
.cpp
| 219
| 47.844749
| 170
| 0.637706
|
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,263
|
device_properties.cpp
|
Atmosphere-NX_Atmosphere/troposphere/haze/source/device_properties.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 <haze.hpp>
namespace haze {
namespace {
constinit SetSysSerialNumber g_serial_number = {};
constinit SetSysFirmwareVersion g_firmware_version = {};
}
Result LoadDeviceProperties() {
/* Initialize set:sys. */
R_TRY(setsysInitialize());
/* Ensure we maintain a clean state on exit. */
ON_SCOPE_EXIT { setsysExit(); };
/* Get the serial number and firmware version. */
R_TRY(setsysGetSerialNumber(std::addressof(g_serial_number)));
R_TRY(setsysGetFirmwareVersion(std::addressof(g_firmware_version)));
/* We succeeded. */
R_SUCCEED();
}
const char *GetSerialNumber() {
return g_serial_number.number;
}
const char *GetFirmwareVersion() {
return g_firmware_version.display_version;
}
}
| 1,471
|
C++
|
.cpp
| 39
| 32.589744
| 76
| 0.689655
|
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,264
|
ptp_responder_ptp_operations.cpp
|
Atmosphere-NX_Atmosphere/troposphere/haze/source/ptp_responder_ptp_operations.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <haze.hpp>
#include <haze/ptp_data_builder.hpp>
#include <haze/ptp_data_parser.hpp>
#include <haze/ptp_responder_types.hpp>
namespace haze {
Result PtpResponder::GetDeviceInfo(PtpDataParser &dp) {
PtpDataBuilder db(m_buffers->usb_bulk_write_buffer, std::addressof(m_usb_server));
/* Write the device info data. */
R_TRY(db.WriteVariableLengthData(m_request_header, [&] () {
R_TRY(db.Add(MtpStandardVersion));
R_TRY(db.Add(MtpVendorExtensionId));
R_TRY(db.Add(MtpStandardVersion));
R_TRY(db.AddString(MtpVendorExtensionDesc));
R_TRY(db.Add(MtpFunctionalModeDefault));
R_TRY(db.AddArray(SupportedOperationCodes, util::size(SupportedOperationCodes)));
R_TRY(db.AddArray(SupportedEventCodes, util::size(SupportedEventCodes)));
R_TRY(db.AddArray(SupportedDeviceProperties, util::size(SupportedDeviceProperties)));
R_TRY(db.AddArray(SupportedCaptureFormats, util::size(SupportedCaptureFormats)));
R_TRY(db.AddArray(SupportedPlaybackFormats, util::size(SupportedPlaybackFormats)));
R_TRY(db.AddString(MtpDeviceManufacturer));
R_TRY(db.AddString(MtpDeviceModel));
R_TRY(db.AddString(GetFirmwareVersion()));
R_TRY(db.AddString(GetSerialNumber()));
R_SUCCEED();
}));
/* Write the success response. */
R_RETURN(this->WriteResponse(PtpResponseCode_Ok));
}
Result PtpResponder::OpenSession(PtpDataParser &dp) {
R_TRY(dp.Finalize());
/* Close, if we're already open. */
this->ForceCloseSession();
/* Initialize the database. */
m_session_open = true;
m_object_database.Initialize(m_object_heap);
/* Create the root storages. */
PtpObject *object;
R_TRY(m_object_database.CreateOrFindObject("", "", PtpGetObjectHandles_RootParent, std::addressof(object)));
/* Register the root storages. */
m_object_database.RegisterObject(object, StorageId_SdmcFs);
/* Write the success response. */
R_RETURN(this->WriteResponse(PtpResponseCode_Ok));
}
Result PtpResponder::CloseSession(PtpDataParser &dp) {
R_TRY(dp.Finalize());
this->ForceCloseSession();
/* Write the success response. */
R_RETURN(this->WriteResponse(PtpResponseCode_Ok));
}
Result PtpResponder::GetStorageIds(PtpDataParser &dp) {
R_TRY(dp.Finalize());
PtpDataBuilder db(m_buffers->usb_bulk_write_buffer, std::addressof(m_usb_server));
/* Write the storage ID array. */
R_TRY(db.WriteVariableLengthData(m_request_header, [&] {
R_RETURN(db.AddArray(SupportedStorageIds, util::size(SupportedStorageIds)));
}));
/* Write the success response. */
R_RETURN(this->WriteResponse(PtpResponseCode_Ok));
}
Result PtpResponder::GetStorageInfo(PtpDataParser &dp) {
PtpDataBuilder db(m_buffers->usb_bulk_write_buffer, std::addressof(m_usb_server));
PtpStorageInfo storage_info(DefaultStorageInfo);
/* Get the storage ID the client requested information for. */
u32 storage_id;
R_TRY(dp.Read(std::addressof(storage_id)));
R_TRY(dp.Finalize());
/* Get the info from fs. */
switch (storage_id) {
case StorageId_SdmcFs:
{
s64 total_space, free_space;
R_TRY(m_fs.GetTotalSpace("/", std::addressof(total_space)));
R_TRY(m_fs.GetFreeSpace("/", std::addressof(free_space)));
storage_info.max_capacity = total_space;
storage_info.free_space_in_bytes = free_space;
storage_info.free_space_in_images = 0;
storage_info.storage_description = "SD Card";
}
break;
default:
R_THROW(haze::ResultInvalidStorageId());
}
/* Write the storage info data. */
R_TRY(db.WriteVariableLengthData(m_request_header, [&] () {
R_TRY(db.Add(storage_info.storage_type));
R_TRY(db.Add(storage_info.filesystem_type));
R_TRY(db.Add(storage_info.access_capability));
R_TRY(db.Add(storage_info.max_capacity));
R_TRY(db.Add(storage_info.free_space_in_bytes));
R_TRY(db.Add(storage_info.free_space_in_images));
R_TRY(db.AddString(storage_info.storage_description));
R_TRY(db.AddString(storage_info.volume_label));
R_SUCCEED();
}));
/* Write the success response. */
R_RETURN(this->WriteResponse(PtpResponseCode_Ok));
}
Result PtpResponder::GetObjectHandles(PtpDataParser &dp) {
PtpDataBuilder db(m_buffers->usb_bulk_write_buffer, std::addressof(m_usb_server));
/* Get the object ID the client requested enumeration for. */
u32 storage_id, object_format_code, association_object_handle;
R_TRY(dp.Read(std::addressof(storage_id)));
R_TRY(dp.Read(std::addressof(object_format_code)));
R_TRY(dp.Read(std::addressof(association_object_handle)));
R_TRY(dp.Finalize());
/* Handle top-level requests. */
if (storage_id == PtpGetObjectHandles_AllStorage) {
storage_id = StorageId_SdmcFs;
}
/* Rewrite requests for enumerating storage directories. */
if (association_object_handle == PtpGetObjectHandles_RootParent) {
association_object_handle = storage_id;
}
/* Check if we know about the object. If we don't, it's an error. */
auto * const obj = m_object_database.GetObjectById(association_object_handle);
R_UNLESS(obj != nullptr, haze::ResultInvalidObjectId());
/* Try to read the object as a directory. */
FsDir dir;
R_TRY(m_fs.OpenDirectory(obj->GetName(), FsDirOpenMode_ReadDirs | FsDirOpenMode_ReadFiles, std::addressof(dir)));
/* Ensure we maintain a clean state on exit. */
ON_SCOPE_EXIT { m_fs.CloseDirectory(std::addressof(dir)); };
/* Count how many entries are in the directory. */
s64 entry_count = 0;
R_TRY(m_fs.GetDirectoryEntryCount(std::addressof(dir), std::addressof(entry_count)));
/* Begin writing. */
R_TRY(db.AddDataHeader(m_request_header, sizeof(u32) + (entry_count * sizeof(u32))));
R_TRY(db.Add(static_cast<u32>(entry_count)));
/* Enumerate the directory, writing results to the data builder as we progress. */
/* TODO: How should we handle the directory contents changing during enumeration? */
/* Is this even feasible to handle? */
while (true) {
/* Get the next batch. */
s64 read_count = 0;
R_TRY(m_fs.ReadDirectory(std::addressof(dir), std::addressof(read_count), DirectoryReadSize, m_buffers->file_system_entry_buffer));
/* Write to output. */
for (s64 i = 0; i < read_count; i++) {
const char *name = m_buffers->file_system_entry_buffer[i].name;
u32 handle;
R_TRY(m_object_database.CreateAndRegisterObjectId(obj->GetName(), name, obj->GetObjectId(), std::addressof(handle)));
R_TRY(db.Add(handle));
}
/* If we read fewer than the batch size, we're done. */
if (read_count < DirectoryReadSize) {
break;
}
}
/* Flush the data response. */
R_TRY(db.Commit());
/* Write the success response. */
R_RETURN(this->WriteResponse(PtpResponseCode_Ok));
}
Result PtpResponder::GetObjectInfo(PtpDataParser &dp) {
PtpDataBuilder db(m_buffers->usb_bulk_write_buffer, std::addressof(m_usb_server));
/* Get the object ID the client requested info for. */
u32 object_id;
R_TRY(dp.Read(std::addressof(object_id)));
R_TRY(dp.Finalize());
/* Check if we know about the object. If we don't, it's an error. */
auto * const obj = m_object_database.GetObjectById(object_id);
R_UNLESS(obj != nullptr, haze::ResultInvalidObjectId());
/* Build info about the object. */
PtpObjectInfo object_info(DefaultObjectInfo);
if (object_id == StorageId_SdmcFs) {
/* The SD Card directory has some special properties. */
object_info.object_format = PtpObjectFormatCode_Association;
object_info.association_type = PtpAssociationType_GenericFolder;
object_info.filename = "SD Card";
} else {
/* Figure out what type of object this is. */
FsDirEntryType entry_type;
R_TRY(m_fs.GetEntryType(obj->GetName(), std::addressof(entry_type)));
/* Get the size, if we are requesting info about a file. */
s64 size = 0;
if (entry_type == FsDirEntryType_File) {
FsFile file;
R_TRY(m_fs.OpenFile(obj->GetName(), FsOpenMode_Read, std::addressof(file)));
/* Ensure we maintain a clean state on exit. */
ON_SCOPE_EXIT { m_fs.CloseFile(std::addressof(file)); };
R_TRY(m_fs.GetFileSize(std::addressof(file), std::addressof(size)));
}
object_info.filename = std::strrchr(obj->GetName(), '/') + 1;
object_info.object_compressed_size = size;
object_info.parent_object = obj->GetParentId();
if (entry_type == FsDirEntryType_Dir) {
object_info.object_format = PtpObjectFormatCode_Association;
object_info.association_type = PtpAssociationType_GenericFolder;
} else {
object_info.object_format = PtpObjectFormatCode_Undefined;
object_info.association_type = PtpAssociationType_Undefined;
}
}
/* Write the object info data. */
R_TRY(db.WriteVariableLengthData(m_request_header, [&] () {
R_TRY(db.Add(object_info.storage_id));
R_TRY(db.Add(object_info.object_format));
R_TRY(db.Add(object_info.protection_status));
R_TRY(db.Add(object_info.object_compressed_size));
R_TRY(db.Add(object_info.thumb_format));
R_TRY(db.Add(object_info.thumb_compressed_size));
R_TRY(db.Add(object_info.thumb_width));
R_TRY(db.Add(object_info.thumb_height));
R_TRY(db.Add(object_info.image_width));
R_TRY(db.Add(object_info.image_height));
R_TRY(db.Add(object_info.image_depth));
R_TRY(db.Add(object_info.parent_object));
R_TRY(db.Add(object_info.association_type));
R_TRY(db.Add(object_info.association_desc));
R_TRY(db.Add(object_info.sequence_number));
R_TRY(db.AddString(object_info.filename));
R_TRY(db.AddString(object_info.capture_date));
R_TRY(db.AddString(object_info.modification_date));
R_TRY(db.AddString(object_info.keywords));
R_SUCCEED();
}));
/* Write the success response. */
R_RETURN(this->WriteResponse(PtpResponseCode_Ok));
}
Result PtpResponder::GetObject(PtpDataParser &dp) {
PtpDataBuilder db(m_buffers->usb_bulk_write_buffer, std::addressof(m_usb_server));
/* Get the object ID the client requested. */
u32 object_id;
R_TRY(dp.Read(std::addressof(object_id)));
R_TRY(dp.Finalize());
/* Check if we know about the object. If we don't, it's an error. */
auto * const obj = m_object_database.GetObjectById(object_id);
R_UNLESS(obj != nullptr, haze::ResultInvalidObjectId());
/* Lock the object as a file. */
FsFile file;
R_TRY(m_fs.OpenFile(obj->GetName(), FsOpenMode_Read, std::addressof(file)));
/* Ensure we maintain a clean state on exit. */
ON_SCOPE_EXIT { m_fs.CloseFile(std::addressof(file)); };
/* Get the file's size. */
s64 size = 0;
R_TRY(m_fs.GetFileSize(std::addressof(file), std::addressof(size)));
/* Send the header and file size. */
R_TRY(db.AddDataHeader(m_request_header, size));
/* Begin reading the file, writing data to the builder as we progress. */
s64 offset = 0;
while (true) {
/* Get the next batch. */
u64 bytes_read;
R_TRY(m_fs.ReadFile(std::addressof(file), offset, m_buffers->file_system_data_buffer, FsBufferSize, FsReadOption_None, std::addressof(bytes_read)));
offset += bytes_read;
/* Write to output. */
R_TRY(db.AddBuffer(m_buffers->file_system_data_buffer, bytes_read));
/* If we read fewer bytes than the batch size, we're done. */
if (bytes_read < FsBufferSize) {
break;
}
}
/* Flush the data response. */
R_TRY(db.Commit());
/* Write the success response. */
R_RETURN(this->WriteResponse(PtpResponseCode_Ok));
}
Result PtpResponder::SendObjectInfo(PtpDataParser &rdp) {
/* Get the storage ID and parent object and flush the request packet. */
u32 storage_id, parent_object;
R_TRY(rdp.Read(std::addressof(storage_id)));
R_TRY(rdp.Read(std::addressof(parent_object)));
R_TRY(rdp.Finalize());
PtpDataParser dp(m_buffers->usb_bulk_read_buffer, std::addressof(m_usb_server));
PtpObjectInfo info(DefaultObjectInfo);
/* Ensure we have a data header. */
PtpUsbBulkContainer data_header;
R_TRY(dp.Read(std::addressof(data_header)));
R_UNLESS(data_header.type == PtpUsbBulkContainerType_Data, haze::ResultUnknownRequestType());
R_UNLESS(data_header.code == m_request_header.code, haze::ResultOperationNotSupported());
R_UNLESS(data_header.trans_id == m_request_header.trans_id, haze::ResultOperationNotSupported());
/* Read in the object info. */
R_TRY(dp.Read(std::addressof(info.storage_id)));
R_TRY(dp.Read(std::addressof(info.object_format)));
R_TRY(dp.Read(std::addressof(info.protection_status)));
R_TRY(dp.Read(std::addressof(info.object_compressed_size)));
R_TRY(dp.Read(std::addressof(info.thumb_format)));
R_TRY(dp.Read(std::addressof(info.thumb_compressed_size)));
R_TRY(dp.Read(std::addressof(info.thumb_width)));
R_TRY(dp.Read(std::addressof(info.thumb_height)));
R_TRY(dp.Read(std::addressof(info.image_width)));
R_TRY(dp.Read(std::addressof(info.image_height)));
R_TRY(dp.Read(std::addressof(info.image_depth)));
R_TRY(dp.Read(std::addressof(info.parent_object)));
R_TRY(dp.Read(std::addressof(info.association_type)));
R_TRY(dp.Read(std::addressof(info.association_desc)));
R_TRY(dp.Read(std::addressof(info.sequence_number)));
R_TRY(dp.ReadString(m_buffers->filename_string_buffer));
R_TRY(dp.ReadString(m_buffers->capture_date_string_buffer));
R_TRY(dp.ReadString(m_buffers->modification_date_string_buffer));
R_TRY(dp.ReadString(m_buffers->keywords_string_buffer));
R_TRY(dp.Finalize());
/* Rewrite requests for creating in storage directories. */
if (parent_object == PtpGetObjectHandles_RootParent) {
parent_object = storage_id;
}
/* Check if we know about the parent object. If we don't, it's an error. */
auto * const parentobj = m_object_database.GetObjectById(parent_object);
R_UNLESS(parentobj != nullptr, haze::ResultInvalidObjectId());
/* Make a new object with the intended name. */
PtpNewObjectInfo new_object_info;
new_object_info.storage_id = StorageId_SdmcFs;
new_object_info.parent_object_id = parent_object == storage_id ? 0 : parent_object;
/* Create the object in the database. */
PtpObject *obj;
R_TRY(m_object_database.CreateOrFindObject(parentobj->GetName(), m_buffers->filename_string_buffer, parentobj->GetObjectId(), std::addressof(obj)));
/* Ensure we maintain a clean state on failure. */
ON_RESULT_FAILURE { m_object_database.DeleteObject(obj); };
/* Register the object with a new ID. */
m_object_database.RegisterObject(obj);
new_object_info.object_id = obj->GetObjectId();
/* Create the object on the filesystem. */
if (info.object_format == PtpObjectFormatCode_Association) {
R_TRY(m_fs.CreateDirectory(obj->GetName()));
m_send_object_id = 0;
} else {
R_TRY(m_fs.CreateFile(obj->GetName(), 0, 0));
m_send_object_id = new_object_info.object_id;
}
/* Write the success response. */
R_RETURN(this->WriteResponse(PtpResponseCode_Ok, new_object_info));
}
Result PtpResponder::SendObject(PtpDataParser &rdp) {
/* Reset SendObject object ID on exit. */
ON_SCOPE_EXIT { m_send_object_id = 0; };
R_TRY(rdp.Finalize());
PtpDataParser dp(m_buffers->usb_bulk_read_buffer, std::addressof(m_usb_server));
/* Ensure we have a data header. */
PtpUsbBulkContainer data_header;
R_TRY(dp.Read(std::addressof(data_header)));
R_UNLESS(data_header.type == PtpUsbBulkContainerType_Data, haze::ResultUnknownRequestType());
R_UNLESS(data_header.code == m_request_header.code, haze::ResultOperationNotSupported());
R_UNLESS(data_header.trans_id == m_request_header.trans_id, haze::ResultOperationNotSupported());
/* Check if we know about the object. If we don't, it's an error. */
auto * const obj = m_object_database.GetObjectById(m_send_object_id);
R_UNLESS(obj != nullptr, haze::ResultInvalidObjectId());
/* Lock the object as a file. */
FsFile file;
R_TRY(m_fs.OpenFile(obj->GetName(), FsOpenMode_Write | FsOpenMode_Append, std::addressof(file)));
/* Ensure we maintain a clean state on exit. */
ON_SCOPE_EXIT { m_fs.CloseFile(std::addressof(file)); };
/* Truncate the file after locking for write. */
s64 offset = 0;
R_TRY(m_fs.SetFileSize(std::addressof(file), 0));
/* Expand to the needed size. */
if (data_header.length > sizeof(PtpUsbBulkContainer)) {
R_TRY(m_fs.SetFileSize(std::addressof(file), data_header.length - sizeof(PtpUsbBulkContainer)));
}
/* Begin writing to the filesystem. */
while (true) {
/* Read as many bytes as we can. */
u32 bytes_received;
const Result read_res = dp.ReadBuffer(m_buffers->file_system_data_buffer, FsBufferSize, std::addressof(bytes_received));
/* Write to the file. */
R_TRY(m_fs.WriteFile(std::addressof(file), offset, m_buffers->file_system_data_buffer, bytes_received, 0));
offset += bytes_received;
/* If we received fewer bytes than the batch size, we're done. */
if (haze::ResultEndOfTransmission::Includes(read_res)) {
break;
}
R_TRY(read_res);
}
/* Truncate the file to the received size. */
R_TRY(m_fs.SetFileSize(std::addressof(file), offset));
/* Write the success response. */
R_RETURN(this->WriteResponse(PtpResponseCode_Ok));
}
Result PtpResponder::DeleteObject(PtpDataParser &dp) {
/* Get the object ID and flush the request packet. */
u32 object_id;
R_TRY(dp.Read(std::addressof(object_id)));
R_TRY(dp.Finalize());
/* Disallow deleting the storage root. */
R_UNLESS(object_id != StorageId_SdmcFs, haze::ResultInvalidObjectId());
/* Check if we know about the object. If we don't, it's an error. */
auto * const obj = m_object_database.GetObjectById(object_id);
R_UNLESS(obj != nullptr, haze::ResultInvalidObjectId());
/* Figure out what type of object this is. */
FsDirEntryType entry_type;
R_TRY(m_fs.GetEntryType(obj->GetName(), std::addressof(entry_type)));
/* Remove the object from the filesystem. */
if (entry_type == FsDirEntryType_Dir) {
R_TRY(m_fs.DeleteDirectoryRecursively(obj->GetName()));
} else {
R_TRY(m_fs.DeleteFile(obj->GetName()));
}
/* Remove the object from the database. */
m_object_database.DeleteObject(obj);
/* Write the success response. */
R_RETURN(this->WriteResponse(PtpResponseCode_Ok));
}
}
| 21,441
|
C++
|
.cpp
| 405
| 42.676543
| 160
| 0.620856
|
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,265
|
ptp_responder.cpp
|
Atmosphere-NX_Atmosphere/troposphere/haze/source/ptp_responder.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 <haze.hpp>
#include <haze/ptp_data_builder.hpp>
#include <haze/ptp_data_parser.hpp>
#include <haze/ptp_responder_types.hpp>
namespace haze {
namespace {
PtpBuffers *GetBuffers() {
static constinit PtpBuffers buffers = {};
return std::addressof(buffers);
}
}
Result PtpResponder::Initialize(EventReactor *reactor, PtpObjectHeap *object_heap) {
m_object_heap = object_heap;
m_buffers = GetBuffers();
/* Configure fs proxy. */
m_fs.Initialize(reactor, fsdevGetDeviceFileSystem("sdmc"));
R_RETURN(m_usb_server.Initialize(std::addressof(MtpInterfaceInfo), SwitchMtpIdVendor, SwitchMtpIdProduct, reactor));
}
void PtpResponder::Finalize() {
m_usb_server.Finalize();
m_fs.Finalize();
}
Result PtpResponder::LoopProcess() {
while (true) {
/* Try to handle a request. */
R_TRY_CATCH(this->HandleRequest()) {
R_CATCH(haze::ResultStopRequested, haze::ResultFocusLost) {
/* If we encountered a stop condition, we're done.*/
R_THROW(R_CURRENT_RESULT);
}
R_CATCH_ALL() {
/* On other failures, try to handle another request. */
continue;
}
} R_END_TRY_CATCH;
/* Otherwise, handle the next request. */
/* ... */
}
}
Result PtpResponder::HandleRequest() {
ON_RESULT_FAILURE {
/* For general failure modes, the failure is unrecoverable. Close the session. */
this->ForceCloseSession();
};
R_TRY_CATCH(this->HandleRequestImpl()) {
R_CATCH(haze::ResultUnknownRequestType) {
R_TRY(this->WriteResponse(PtpResponseCode_GeneralError));
}
R_CATCH(haze::ResultSessionNotOpen) {
R_TRY(this->WriteResponse(PtpResponseCode_SessionNotOpen));
}
R_CATCH(haze::ResultOperationNotSupported) {
R_TRY(this->WriteResponse(PtpResponseCode_OperationNotSupported));
}
R_CATCH(haze::ResultInvalidStorageId) {
R_TRY(this->WriteResponse(PtpResponseCode_InvalidStorageId));
}
R_CATCH(haze::ResultInvalidObjectId) {
R_TRY(this->WriteResponse(PtpResponseCode_InvalidObjectHandle));
}
R_CATCH(haze::ResultUnknownPropertyCode) {
R_TRY(this->WriteResponse(PtpResponseCode_MtpObjectPropNotSupported));
}
R_CATCH(haze::ResultInvalidPropertyValue) {
R_TRY(this->WriteResponse(PtpResponseCode_MtpInvalidObjectPropValue));
}
R_CATCH(haze::ResultGroupSpecified) {
R_TRY(this->WriteResponse(PtpResponseCode_MtpSpecificationByGroupUnsupported));
}
R_CATCH(haze::ResultDepthSpecified) {
R_TRY(this->WriteResponse(PtpResponseCode_MtpSpecificationByDepthUnsupported));
}
R_CATCH(haze::ResultInvalidArgument) {
R_TRY(this->WriteResponse(PtpResponseCode_GeneralError));
}
R_CATCH_MODULE(fs) {
/* Errors from fs are typically recoverable. */
R_TRY(this->WriteResponse(PtpResponseCode_GeneralError));
}
} R_END_TRY_CATCH;
R_SUCCEED();
}
Result PtpResponder::HandleRequestImpl() {
PtpDataParser dp(m_buffers->usb_bulk_read_buffer, std::addressof(m_usb_server));
R_TRY(dp.Read(std::addressof(m_request_header)));
switch (m_request_header.type) {
case PtpUsbBulkContainerType_Command: R_RETURN(this->HandleCommandRequest(dp));
default: R_THROW(haze::ResultUnknownRequestType());
}
}
Result PtpResponder::HandleCommandRequest(PtpDataParser &dp) {
if (!m_session_open && m_request_header.code != PtpOperationCode_OpenSession && m_request_header.code != PtpOperationCode_GetDeviceInfo) {
R_THROW(haze::ResultSessionNotOpen());
}
switch (m_request_header.code) {
case PtpOperationCode_GetDeviceInfo: R_RETURN(this->GetDeviceInfo(dp)); break;
case PtpOperationCode_OpenSession: R_RETURN(this->OpenSession(dp)); break;
case PtpOperationCode_CloseSession: R_RETURN(this->CloseSession(dp)); break;
case PtpOperationCode_GetStorageIds: R_RETURN(this->GetStorageIds(dp)); break;
case PtpOperationCode_GetStorageInfo: R_RETURN(this->GetStorageInfo(dp)); break;
case PtpOperationCode_GetObjectHandles: R_RETURN(this->GetObjectHandles(dp)); break;
case PtpOperationCode_GetObjectInfo: R_RETURN(this->GetObjectInfo(dp)); break;
case PtpOperationCode_GetObject: R_RETURN(this->GetObject(dp)); break;
case PtpOperationCode_SendObjectInfo: R_RETURN(this->SendObjectInfo(dp)); break;
case PtpOperationCode_SendObject: R_RETURN(this->SendObject(dp)); break;
case PtpOperationCode_DeleteObject: R_RETURN(this->DeleteObject(dp)); break;
case PtpOperationCode_MtpGetObjectPropsSupported: R_RETURN(this->GetObjectPropsSupported(dp)); break;
case PtpOperationCode_MtpGetObjectPropDesc: R_RETURN(this->GetObjectPropDesc(dp)); break;
case PtpOperationCode_MtpGetObjectPropValue: R_RETURN(this->GetObjectPropValue(dp)); break;
case PtpOperationCode_MtpSetObjectPropValue: R_RETURN(this->SetObjectPropValue(dp)); break;
case PtpOperationCode_MtpGetObjPropList: R_RETURN(this->GetObjectPropList(dp)); break;
case PtpOperationCode_AndroidGetPartialObject64: R_RETURN(this->GetPartialObject64(dp)); break;
case PtpOperationCode_AndroidSendPartialObject: R_RETURN(this->SendPartialObject(dp)); break;
case PtpOperationCode_AndroidTruncateObject: R_RETURN(this->TruncateObject(dp)); break;
case PtpOperationCode_AndroidBeginEditObject: R_RETURN(this->BeginEditObject(dp)); break;
case PtpOperationCode_AndroidEndEditObject: R_RETURN(this->EndEditObject(dp)); break;
default: R_THROW(haze::ResultOperationNotSupported());
}
}
void PtpResponder::ForceCloseSession() {
if (m_session_open) {
m_session_open = false;
m_object_database.Finalize();
}
}
Result PtpResponder::WriteResponse(PtpResponseCode code, const void* data, size_t size) {
PtpDataBuilder db(m_buffers->usb_bulk_write_buffer, std::addressof(m_usb_server));
R_TRY(db.AddResponseHeader(m_request_header, code, size));
R_TRY(db.AddBuffer(reinterpret_cast<const u8*>(data), size));
R_RETURN(db.Commit());
}
Result PtpResponder::WriteResponse(PtpResponseCode code) {
PtpDataBuilder db(m_buffers->usb_bulk_write_buffer, std::addressof(m_usb_server));
R_TRY(db.AddResponseHeader(m_request_header, code, 0));
R_RETURN(db.Commit());
}
}
| 8,170
|
C++
|
.cpp
| 152
| 43.467105
| 147
| 0.616606
|
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,266
|
ui.cpp
|
Atmosphere-NX_Atmosphere/troposphere/daybreak/source/ui.cpp
|
/*
* Copyright (c) Adubbz
*
* 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 <algorithm>
#include <cstdarg>
#include <cstdio>
#include <cstring>
#include <limits>
#include <dirent.h>
#include "ui.hpp"
#include "ui_util.hpp"
#include "assert.hpp"
namespace dbk {
namespace {
static constexpr u32 ExosphereApiVersionConfigItem = 65000;
static constexpr u32 ExosphereHasRcmBugPatch = 65004;
static constexpr u32 ExosphereEmummcType = 65007;
static constexpr u32 ExosphereSupportedHosVersion = 65011;
/* Insets of content within windows. */
static constexpr float HorizontalInset = 20.0f;
static constexpr float BottomInset = 20.0f;
/* Insets of content within text areas. */
static constexpr float TextHorizontalInset = 8.0f;
static constexpr float TextVerticalInset = 8.0f;
static constexpr float ButtonHeight = 60.0f;
static constexpr float ButtonHorizontalGap = 10.0f;
static constexpr float VerticalGap = 10.0f;
u32 g_screen_width;
u32 g_screen_height;
constinit u32 g_supported_version = std::numeric_limits<u32>::max();
std::shared_ptr<Menu> g_current_menu;
bool g_initialized = false;
bool g_exit_requested = false;
PadState g_pad;
u32 g_prev_touch_count = -1;
HidTouchScreenState g_start_touch;
bool g_started_touching = false;
bool g_tapping = false;
bool g_touches_moving = false;
bool g_finished_touching = false;
/* Update install state. */
char g_update_path[FS_MAX_PATH];
bool g_reset_to_factory = false;
bool g_exfat_supported = false;
bool g_use_exfat = false;
constexpr u32 MaxTapMovement = 20;
void UpdateInput() {
/* Scan for input and update touch state. */
padUpdate(&g_pad);
HidTouchScreenState current_touch;
hidGetTouchScreenStates(¤t_touch, 1);
const u32 touch_count = current_touch.count;
if (g_prev_touch_count == 0 && touch_count > 0) {
hidGetTouchScreenStates(&g_start_touch, 1);
g_started_touching = true;
g_tapping = true;
} else {
g_started_touching = false;
}
if (g_prev_touch_count > 0 && touch_count == 0) {
g_finished_touching = true;
g_tapping = false;
} else {
g_finished_touching = false;
}
/* Check if currently moving. */
if (g_prev_touch_count > 0 && touch_count > 0) {
if ((abs(current_touch.touches[0].x - g_start_touch.touches[0].x) > MaxTapMovement || abs(current_touch.touches[0].y - g_start_touch.touches[0].y) > MaxTapMovement)) {
g_touches_moving = true;
g_tapping = false;
} else {
g_touches_moving = false;
}
} else {
g_touches_moving = false;
}
/* Update the previous touch count. */
g_prev_touch_count = current_touch.count;
}
void ChangeMenu(std::shared_ptr<Menu> menu) {
g_current_menu = menu;
}
void ReturnToPreviousMenu() {
/* Go to the previous menu if there is one. */
if (g_current_menu->GetPrevMenu() != nullptr) {
g_current_menu = g_current_menu->GetPrevMenu();
}
}
Result IsPathBottomLevel(const char *path, bool *out) {
Result rc = 0;
FsFileSystem *fs;
char translated_path[FS_MAX_PATH] = {};
DBK_ABORT_UNLESS(fsdevTranslatePath(path, &fs, translated_path) != -1);
FsDir dir;
if (R_FAILED(rc = fsFsOpenDirectory(fs, translated_path, FsDirOpenMode_ReadDirs, &dir))) {
return rc;
}
s64 entry_count;
if (R_FAILED(rc = fsDirGetEntryCount(&dir, &entry_count))) {
return rc;
}
*out = entry_count == 0;
fsDirClose(&dir);
return rc;
}
u32 EncodeVersion(u32 major, u32 minor, u32 micro, u32 relstep = 0) {
return ((major & 0xFF) << 24) | ((minor & 0xFF) << 16) | ((micro & 0xFF) << 8) | ((relstep & 0xFF) << 8);
}
}
void Menu::AddButton(u32 id, const char *text, float x, float y, float w, float h) {
DBK_ABORT_UNLESS(id < MaxButtons);
Button button = {
.id = id,
.selected = false,
.enabled = true,
.x = x,
.y = y,
.w = w,
.h = h,
};
strncpy(button.text, text, sizeof(button.text)-1);
m_buttons[id] = button;
}
void Menu::SetButtonSelected(u32 id, bool selected) {
DBK_ABORT_UNLESS(id < MaxButtons);
auto &button = m_buttons[id];
if (button) {
button->selected = selected;
}
}
void Menu::DeselectAllButtons() {
for (auto &button : m_buttons) {
/* Ensure button is present. */
if (!button) {
continue;
}
button->selected = false;
}
}
void Menu::SetButtonEnabled(u32 id, bool enabled) {
DBK_ABORT_UNLESS(id < MaxButtons);
auto &button = m_buttons[id];
button->enabled = enabled;
}
Button *Menu::GetButton(u32 id) {
DBK_ABORT_UNLESS(id < MaxButtons);
return !m_buttons[id] ? nullptr : &(*m_buttons[id]);
}
Button *Menu::GetSelectedButton() {
for (auto &button : m_buttons) {
if (button && button->enabled && button->selected) {
return &(*button);
}
}
return nullptr;
}
Button *Menu::GetClosestButtonToSelection(Direction direction) {
const Button *selected_button = this->GetSelectedButton();
if (selected_button == nullptr || direction == Direction::Invalid) {
return nullptr;
}
Button *closest_button = nullptr;
float closest_distance = 0.0f;
for (auto &button : m_buttons) {
/* Skip absent button. */
if (!button || !button->enabled) {
continue;
}
/* Skip buttons that are in the wrong direction. */
if ((direction == Direction::Down && button->y <= selected_button->y) ||
(direction == Direction::Up && button->y >= selected_button->y) ||
(direction == Direction::Right && button->x <= selected_button->x) ||
(direction == Direction::Left && button->x >= selected_button->x)) {
continue;
}
const float x_dist = button->x - selected_button->x;
const float y_dist = button->y - selected_button->y;
const float sq_dist = x_dist * x_dist + y_dist * y_dist;
/* If we don't already have a closest button, set it. */
if (closest_button == nullptr) {
closest_button = &(*button);
closest_distance = sq_dist;
continue;
}
/* Update the closest button if this one is closer. */
if (sq_dist < closest_distance) {
closest_button = &(*button);
closest_distance = sq_dist;
}
}
return closest_button;
}
Button *Menu::GetTouchedButton() {
HidTouchScreenState current_touch;
hidGetTouchScreenStates(¤t_touch, 1);
const u32 touch_count = current_touch.count;
for (u32 i = 0; i < touch_count && g_started_touching; i++) {
for (auto &button : m_buttons) {
if (button && button->enabled && button->IsPositionInBounds(current_touch.touches[i].x, current_touch.touches[i].y)) {
return &(*button);
}
}
}
return nullptr;
}
Button *Menu::GetActivatedButton() {
Button *selected_button = this->GetSelectedButton();
if (selected_button == nullptr) {
return nullptr;
}
const u64 k_down = padGetButtonsDown(&g_pad);
if (k_down & HidNpadButton_A || this->GetTouchedButton() == selected_button) {
return selected_button;
}
return nullptr;
}
void Menu::UpdateButtons() {
const u64 k_down = padGetButtonsDown(&g_pad);
Direction direction = Direction::Invalid;
if (k_down & HidNpadButton_AnyDown) {
direction = Direction::Down;
} else if (k_down & HidNpadButton_AnyUp) {
direction = Direction::Up;
} else if (k_down & HidNpadButton_AnyLeft) {
direction = Direction::Left;
} else if (k_down & HidNpadButton_AnyRight) {
direction = Direction::Right;
}
/* Select the closest button. */
if (const Button *closest_button = this->GetClosestButtonToSelection(direction); closest_button != nullptr) {
this->DeselectAllButtons();
this->SetButtonSelected(closest_button->id, true);
}
/* Select the touched button. */
if (const Button *touched_button = this->GetTouchedButton(); touched_button != nullptr) {
this->DeselectAllButtons();
this->SetButtonSelected(touched_button->id, true);
}
}
void Menu::DrawButtons(NVGcontext *vg, u64 ns) {
for (auto &button : m_buttons) {
/* Ensure button is present. */
if (!button) {
continue;
}
/* Set the button style. */
auto style = ButtonStyle::StandardDisabled;
if (button->enabled) {
style = button->selected ? ButtonStyle::StandardSelected : ButtonStyle::Standard;
}
DrawButton(vg, button->text, button->x, button->y, button->w, button->h, style, ns);
}
}
void Menu::LogText(const char *format, ...) {
/* Create a temporary string. */
char tmp[0x100];
va_list args;
va_start(args, format);
vsnprintf(tmp, sizeof(tmp), format, args);
va_end(args);
/* Append the text to the log buffer. */
strncat(m_log_buffer, tmp, sizeof(m_log_buffer)-1);
}
std::shared_ptr<Menu> Menu::GetPrevMenu() {
return m_prev_menu;
}
AlertMenu::AlertMenu(std::shared_ptr<Menu> prev_menu, const char *text, const char *subtext, Result rc) : Menu(prev_menu), m_text{}, m_subtext{}, m_result_text{}, m_rc(rc){
/* Copy the input text. */
strncpy(m_text, text, sizeof(m_text)-1);
strncpy(m_subtext, subtext, sizeof(m_subtext)-1);
/* Copy result text if there is a result. */
if (R_FAILED(rc)) {
snprintf(m_result_text, sizeof(m_result_text), "Result: 0x%08x", rc);
}
}
void AlertMenu::Draw(NVGcontext *vg, u64 ns) {
const float window_height = WindowHeight + (R_FAILED(m_rc) ? SubTextHeight : 0.0f);
const float x = g_screen_width / 2.0f - WindowWidth / 2.0f;
const float y = g_screen_height / 2.0f - window_height / 2.0f;
DrawWindow(vg, m_text, x, y, WindowWidth, window_height);
DrawText(vg, x + HorizontalInset, y + TitleGap, WindowWidth - HorizontalInset * 2.0f, m_subtext);
/* Draw the result if there is one. */
if (R_FAILED(m_rc)) {
DrawText(vg, x + HorizontalInset, y + TitleGap + SubTextHeight, WindowWidth - HorizontalInset * 2.0f, m_result_text);
}
this->DrawButtons(vg, ns);
}
ErrorMenu::ErrorMenu(const char *text, const char *subtext, Result rc) : AlertMenu(nullptr, text, subtext, rc) {
const float window_height = WindowHeight + (R_FAILED(m_rc) ? SubTextHeight : 0.0f);
const float x = g_screen_width / 2.0f - WindowWidth / 2.0f;
const float y = g_screen_height / 2.0f - window_height / 2.0f;
const float button_y = y + TitleGap + SubTextHeight + VerticalGap * 2.0f + (R_FAILED(m_rc) ? SubTextHeight : 0.0f);
const float button_width = WindowWidth - HorizontalInset * 2.0f;
/* Add buttons. */
this->AddButton(ExitButtonId, "Exit", x + HorizontalInset, button_y, button_width, ButtonHeight);
this->SetButtonSelected(ExitButtonId, true);
}
void ErrorMenu::Update(u64 ns) {
u64 k_down = padGetButtonsDown(&g_pad);
/* Go back if B is pressed. */
if (k_down & HidNpadButton_B) {
g_exit_requested = true;
return;
}
/* Take action if a button has been activated. */
if (const Button *activated_button = this->GetActivatedButton(); activated_button != nullptr) {
switch (activated_button->id) {
case ExitButtonId:
g_exit_requested = true;
break;
}
}
this->UpdateButtons();
/* Fallback on selecting the exfat button. */
if (const Button *selected_button = this->GetSelectedButton(); k_down && selected_button == nullptr) {
this->SetButtonSelected(ExitButtonId, true);
}
}
WarningMenu::WarningMenu(std::shared_ptr<Menu> prev_menu, std::shared_ptr<Menu> next_menu, const char *text, const char *subtext, Result rc) : AlertMenu(prev_menu, text, subtext, rc), m_next_menu(next_menu) {
const float window_height = WindowHeight + (R_FAILED(m_rc) ? SubTextHeight : 0.0f);
const float x = g_screen_width / 2.0f - WindowWidth / 2.0f;
const float y = g_screen_height / 2.0f - window_height / 2.0f;
const float button_y = y + TitleGap + SubTextHeight + VerticalGap * 2.0f + (R_FAILED(m_rc) ? SubTextHeight : 0.0f);
const float button_width = (WindowWidth - HorizontalInset * 2.0f) / 2.0f - ButtonHorizontalGap;
this->AddButton(BackButtonId, "Back", x + HorizontalInset, button_y, button_width, ButtonHeight);
this->AddButton(ContinueButtonId, "Continue", x + HorizontalInset + button_width + ButtonHorizontalGap, button_y, button_width, ButtonHeight);
this->SetButtonSelected(ContinueButtonId, true);
}
void WarningMenu::Update(u64 ns) {
u64 k_down = padGetButtonsDown(&g_pad);
/* Go back if B is pressed. */
if (k_down & HidNpadButton_B) {
ReturnToPreviousMenu();
return;
}
/* Take action if a button has been activated. */
if (const Button *activated_button = this->GetActivatedButton(); activated_button != nullptr) {
switch (activated_button->id) {
case BackButtonId:
ReturnToPreviousMenu();
return;
case ContinueButtonId:
ChangeMenu(m_next_menu);
return;
}
}
this->UpdateButtons();
/* Fallback on selecting the exfat button. */
if (const Button *selected_button = this->GetSelectedButton(); k_down && selected_button == nullptr) {
this->SetButtonSelected(ContinueButtonId, true);
}
}
MainMenu::MainMenu() : Menu(nullptr) {
const float x = g_screen_width / 2.0f - WindowWidth / 2.0f;
const float y = g_screen_height / 2.0f - WindowHeight / 2.0f;
this->AddButton(InstallButtonId, "Install", x + HorizontalInset, y + TitleGap, WindowWidth - HorizontalInset * 2, ButtonHeight);
this->AddButton(ExitButtonId, "Exit", x + HorizontalInset, y + TitleGap + ButtonHeight + VerticalGap, WindowWidth - HorizontalInset * 2, ButtonHeight);
this->SetButtonSelected(InstallButtonId, true);
}
void MainMenu::Update(u64 ns) {
u64 k_down = padGetButtonsDown(&g_pad);
if (k_down & HidNpadButton_B) {
g_exit_requested = true;
}
/* Take action if a button has been activated. */
if (const Button *activated_button = this->GetActivatedButton(); activated_button != nullptr) {
switch (activated_button->id) {
case InstallButtonId:
{
const auto file_menu = std::make_shared<FileMenu>(g_current_menu, "/");
Result rc = 0;
u64 hardware_type;
u64 has_rcm_bug_patch;
u64 is_emummc;
if (R_FAILED(rc = splGetConfig(SplConfigItem_HardwareType, &hardware_type))) {
ChangeMenu(std::make_shared<ErrorMenu>("An error has occurred", "Failed to get hardware type.", rc));
return;
}
if (R_FAILED(rc = splGetConfig(static_cast<SplConfigItem>(ExosphereHasRcmBugPatch), &has_rcm_bug_patch))) {
ChangeMenu(std::make_shared<ErrorMenu>("An error has occurred", "Failed to check RCM bug status.", rc));
return;
}
if (R_FAILED(rc = splGetConfig(static_cast<SplConfigItem>(ExosphereEmummcType), &is_emummc))) {
ChangeMenu(std::make_shared<ErrorMenu>("An error has occurred", "Failed to check emuMMC status.", rc));
return;
}
/* Warn if we're working with a patched unit. */
const bool is_erista = hardware_type == 0 || hardware_type == 1;
if (is_erista && has_rcm_bug_patch && !is_emummc) {
ChangeMenu(std::make_shared<WarningMenu>(g_current_menu, file_menu, "Warning: Patched unit detected", "You may burn fuses or render your switch inoperable."));
} else {
ChangeMenu(file_menu);
}
return;
}
case ExitButtonId:
g_exit_requested = true;
return;
}
}
this->UpdateButtons();
/* Fallback on selecting the install button. */
if (const Button *selected_button = this->GetSelectedButton(); k_down && selected_button == nullptr) {
this->SetButtonSelected(InstallButtonId, true);
}
}
void MainMenu::Draw(NVGcontext *vg, u64 ns) {
DrawWindow(vg, "Daybreak", g_screen_width / 2.0f - WindowWidth / 2.0f, g_screen_height / 2.0f - WindowHeight / 2.0f, WindowWidth, WindowHeight);
this->DrawButtons(vg, ns);
}
FileMenu::FileMenu(std::shared_ptr<Menu> prev_menu, const char *root) : Menu(prev_menu), m_current_index(0), m_scroll_offset(0), m_touch_start_scroll_offset(0), m_touch_finalize_selection(false) {
Result rc = 0;
strncpy(m_root, root, sizeof(m_root)-1);
if (R_FAILED(rc = this->PopulateFileEntries())) {
fatalThrow(rc);
}
}
Result FileMenu::PopulateFileEntries() {
/* Open the directory. */
DIR *dir = opendir(m_root);
if (dir == nullptr) {
return fsdevGetLastResult();
}
/* Add file entries to the list. */
struct dirent *ent;
while ((ent = readdir(dir)) != nullptr) {
if (ent->d_type == DT_DIR) {
FileEntry file_entry = {};
strncpy(file_entry.name, ent->d_name, sizeof(file_entry.name));
m_file_entries.push_back(file_entry);
}
}
/* Close the directory. */
closedir(dir);
/* Sort the file entries. */
std::sort(m_file_entries.begin(), m_file_entries.end(), [](const FileEntry &a, const FileEntry &b) {
return strncmp(a.name, b.name, sizeof(a.name)) < 0;
});
return 0;
}
bool FileMenu::IsSelectionVisible() {
const float visible_start = m_scroll_offset;
const float visible_end = visible_start + FileListHeight;
const float entry_start = static_cast<float>(m_current_index) * (FileRowHeight + FileRowGap);
const float entry_end = entry_start + (FileRowHeight + FileRowGap);
return entry_start >= visible_start && entry_end <= visible_end;
}
void FileMenu::ScrollToSelection() {
const float visible_start = m_scroll_offset;
const float visible_end = visible_start + FileListHeight;
const float entry_start = static_cast<float>(m_current_index) * (FileRowHeight + FileRowGap);
const float entry_end = entry_start + (FileRowHeight + FileRowGap);
if (entry_end > visible_end) {
m_scroll_offset += entry_end - visible_end;
} else if (entry_end < visible_end) {
m_scroll_offset = entry_start;
}
}
bool FileMenu::IsEntryTouched(u32 i) {
const float x = g_screen_width / 2.0f - WindowWidth / 2.0f;
const float y = g_screen_height / 2.0f - WindowHeight / 2.0f;
HidTouchScreenState current_touch;
hidGetTouchScreenStates(¤t_touch, 1);
/* Check if the tap is within the x bounds. */
if (current_touch.touches[0].x >= x + TextBackgroundOffset + FileRowHorizontalInset && current_touch.touches[0].x <= WindowWidth - (TextBackgroundOffset + FileRowHorizontalInset) * 2.0f) {
const float y_min = y + TitleGap + FileRowGap + i * (FileRowHeight + FileRowGap) - m_scroll_offset;
const float y_max = y_min + FileRowHeight;
/* Check if the tap is within the y bounds. */
if (current_touch.touches[0].y >= y_min && current_touch.touches[0].y <= y_max) {
return true;
}
}
return false;
}
void FileMenu::UpdateTouches() {
/* Setup values on initial touch. */
if (g_started_touching) {
m_touch_start_scroll_offset = m_scroll_offset;
/* We may potentially finalize the selection later if we start off touching it. */
if (this->IsEntryTouched(m_current_index)) {
m_touch_finalize_selection = true;
}
}
/* Scroll based on touch movement. */
if (g_touches_moving) {
HidTouchScreenState current_touch;
hidGetTouchScreenStates(¤t_touch, 1);
const int dist_y = current_touch.touches[0].y - g_start_touch.touches[0].y;
float new_scroll_offset = m_touch_start_scroll_offset - static_cast<float>(dist_y);
float max_scroll = (FileRowHeight + FileRowGap) * static_cast<float>(m_file_entries.size()) - FileListHeight;
/* Don't allow scrolling if there is not enough elements. */
if (max_scroll < 0.0f) {
max_scroll = 0.0f;
}
/* Don't allow scrolling before the first element. */
if (new_scroll_offset < 0.0f) {
new_scroll_offset = 0.0f;
}
/* Don't allow scrolling past the last element. */
if (new_scroll_offset > max_scroll) {
new_scroll_offset = max_scroll;
}
m_scroll_offset = new_scroll_offset;
}
/* Select any tapped entries. */
if (g_tapping) {
for (u32 i = 0; i < m_file_entries.size(); i++) {
if (this->IsEntryTouched(i)) {
/* The current index is checked later. */
if (i == m_current_index) {
continue;
}
m_current_index = i;
/* Don't finalize selection if we touch something else. */
m_touch_finalize_selection = false;
break;
}
}
}
/* Don't finalize selection if we aren't finished and we've either stopped tapping or are no longer touching the selection. */
if (!g_finished_touching && (!g_tapping || !this->IsEntryTouched(m_current_index))) {
m_touch_finalize_selection = false;
}
/* Finalize selection if the currently selected entry is touched for the second time. */
if (g_finished_touching && m_touch_finalize_selection) {
this->FinalizeSelection();
m_touch_finalize_selection = false;
}
}
void FileMenu::FinalizeSelection() {
DBK_ABORT_UNLESS(m_current_index < m_file_entries.size());
FileEntry &entry = m_file_entries[m_current_index];
/* Determine the selected path. */
char current_path[FS_MAX_PATH] = {};
const int path_len = snprintf(current_path, sizeof(current_path), "%s%s/", m_root, entry.name);
DBK_ABORT_UNLESS(path_len >= 0 && path_len < static_cast<int>(sizeof(current_path)));
/* Determine if the chosen path is the bottom level. */
Result rc = 0;
bool bottom_level;
if (R_FAILED(rc = IsPathBottomLevel(current_path, &bottom_level))) {
fatalThrow(rc);
}
/* Show exfat settings or the next file menu. */
if (bottom_level) {
/* Set the update path. */
snprintf(g_update_path, sizeof(g_update_path), "%s", current_path);
/* Change the menu. */
ChangeMenu(std::make_shared<ValidateUpdateMenu>(g_current_menu));
} else {
ChangeMenu(std::make_shared<FileMenu>(g_current_menu, current_path));
}
}
void FileMenu::Update(u64 ns) {
u64 k_down = padGetButtonsDown(&g_pad);
/* Go back if B is pressed. */
if (k_down & HidNpadButton_B) {
ReturnToPreviousMenu();
return;
}
/* Finalize selection on pressing A. */
if (k_down & HidNpadButton_A) {
this->FinalizeSelection();
}
/* Update touch input. */
this->UpdateTouches();
const u32 prev_index = m_current_index;
if (k_down & HidNpadButton_AnyDown) {
/* Scroll down. */
if (m_current_index >= (m_file_entries.size() - 1)) {
m_current_index = 0;
} else {
m_current_index++;
}
} else if (k_down & HidNpadButton_AnyUp) {
/* Scroll up. */
if (m_current_index == 0) {
m_current_index = m_file_entries.size() - 1;
} else {
m_current_index--;
}
}
/* Scroll to the selection if it isn't visible. */
if (prev_index != m_current_index && !this->IsSelectionVisible()) {
this->ScrollToSelection();
}
}
void FileMenu::Draw(NVGcontext *vg, u64 ns) {
const float x = g_screen_width / 2.0f - WindowWidth / 2.0f;
const float y = g_screen_height / 2.0f - WindowHeight / 2.0f;
DrawWindow(vg, "Select an update directory", x, y, WindowWidth, WindowHeight);
DrawTextBackground(vg, x + TextBackgroundOffset, y + TitleGap, WindowWidth - TextBackgroundOffset * 2.0f, (FileRowHeight + FileRowGap) * MaxFileRows + FileRowGap);
nvgSave(vg);
nvgScissor(vg, x + TextBackgroundOffset, y + TitleGap, WindowWidth - TextBackgroundOffset * 2.0f, (FileRowHeight + FileRowGap) * MaxFileRows + FileRowGap);
for (u32 i = 0; i < m_file_entries.size(); i++) {
FileEntry &entry = m_file_entries[i];
auto style = ButtonStyle::FileSelect;
if (i == m_current_index) {
style = ButtonStyle::FileSelectSelected;
}
DrawButton(vg, entry.name, x + TextBackgroundOffset + FileRowHorizontalInset, y + TitleGap + FileRowGap + i * (FileRowHeight + FileRowGap) - m_scroll_offset, WindowWidth - (TextBackgroundOffset + FileRowHorizontalInset) * 2.0f, FileRowHeight, style, ns);
}
nvgRestore(vg);
}
ValidateUpdateMenu::ValidateUpdateMenu(std::shared_ptr<Menu> prev_menu) : Menu(prev_menu), m_has_drawn(false), m_has_info(false), m_has_validated(false) {
const float x = g_screen_width / 2.0f - WindowWidth / 2.0f;
const float y = g_screen_height / 2.0f - WindowHeight / 2.0f;
const float button_width = (WindowWidth - HorizontalInset * 2.0f) / 2.0f - ButtonHorizontalGap;
/* Add buttons. */
this->AddButton(BackButtonId, "Back", x + HorizontalInset, y + WindowHeight - BottomInset - ButtonHeight, button_width, ButtonHeight);
this->AddButton(ContinueButtonId, "Continue", x + HorizontalInset + button_width + ButtonHorizontalGap, y + WindowHeight - BottomInset - ButtonHeight, button_width, ButtonHeight);
this->SetButtonEnabled(BackButtonId, false);
this->SetButtonEnabled(ContinueButtonId, false);
/* Obtain update information. */
if (R_FAILED(this->GetUpdateInformation())) {
this->SetButtonEnabled(BackButtonId, true);
this->SetButtonSelected(BackButtonId, true);
} else {
/* Log this early so it is printed out before validation causes stalling. */
this->LogText("Validating update, this may take a moment...\n");
}
}
Result ValidateUpdateMenu::GetUpdateInformation() {
Result rc = 0;
this->LogText("Directory %s\n", g_update_path);
/* Attempt to get the update information. */
if (R_FAILED(rc = amssuGetUpdateInformation(&m_update_info, g_update_path))) {
if (rc == 0x1a405) {
this->LogText("No update found in folder.\nEnsure your ncas are named correctly!\nResult: 0x%08x\n", rc);
} else {
this->LogText("Failed to get update information.\nResult: 0x%08x\n", rc);
}
return rc;
}
/* Print update information. */
this->LogText("- Version: %d.%d.%d\n", (m_update_info.version >> 26) & 0x1f, (m_update_info.version >> 20) & 0x1f, (m_update_info.version >> 16) & 0xf);
if (m_update_info.exfat_supported) {
this->LogText("- exFAT: Supported\n");
} else {
this->LogText("- exFAT: Unsupported\n");
}
this->LogText("- Firmware variations: %d\n", m_update_info.num_firmware_variations);
/* Mark as having obtained update info. */
m_has_info = true;
return rc;
}
void ValidateUpdateMenu::ValidateUpdate() {
Result rc = 0;
/* Validate the update. */
if (R_FAILED(rc = amssuValidateUpdate(&m_validation_info, g_update_path))) {
this->LogText("Failed to validate update.\nResult: 0x%08x\n", rc);
return;
}
/* Check the result. */
if (R_SUCCEEDED(m_validation_info.result)) {
this->LogText("Update is valid!\n");
if (R_FAILED(m_validation_info.exfat_result)) {
const u32 version = m_validation_info.invalid_key.version;
this->LogText("exFAT Validation failed with result: 0x%08x\n", m_validation_info.exfat_result);
this->LogText("Missing content:\n- Program id: %016lx\n- Version: %d.%d.%d\n", m_validation_info.invalid_key.id, (version >> 26) & 0x1f, (version >> 20) & 0x1f, (version >> 16) & 0xf);
/* Log the missing content id. */
this->LogText("- Content id: ");
for (size_t i = 0; i < sizeof(NcmContentId); i++) {
this->LogText("%02x", m_validation_info.invalid_content_id.c[i]);
}
this->LogText("\n");
}
/* Enable the back and continue buttons and select the continue button. */
this->SetButtonEnabled(BackButtonId, true);
this->SetButtonEnabled(ContinueButtonId, true);
this->SetButtonSelected(ContinueButtonId, true);
} else {
/* Log the missing content info. */
const u32 version = m_validation_info.invalid_key.version;
this->LogText("Validation failed with result: 0x%08x\n", m_validation_info.result);
this->LogText("Missing content:\n- Program id: %016lx\n- Version: %d.%d.%d\n", m_validation_info.invalid_key.id, (version >> 26) & 0x1f, (version >> 20) & 0x1f, (version >> 16) & 0xf);
/* Log the missing content id. */
this->LogText("- Content id: ");
for (size_t i = 0; i < sizeof(NcmContentId); i++) {
this->LogText("%02x", m_validation_info.invalid_content_id.c[i]);
}
this->LogText("\n");
/* Enable the back button and select it. */
this->SetButtonEnabled(BackButtonId, true);
this->SetButtonSelected(BackButtonId, true);
}
/* Mark validation as being complete. */
m_has_validated = true;
}
void ValidateUpdateMenu::Update(u64 ns) {
/* Perform validation if it hasn't been done already. */
if (m_has_info && m_has_drawn && !m_has_validated) {
this->ValidateUpdate();
}
u64 k_down = padGetButtonsDown(&g_pad);
/* Go back if B is pressed. */
if (k_down & HidNpadButton_B) {
ReturnToPreviousMenu();
return;
}
/* Take action if a button has been activated. */
if (const Button *activated_button = this->GetActivatedButton(); activated_button != nullptr) {
switch (activated_button->id) {
case BackButtonId:
ReturnToPreviousMenu();
return;
case ContinueButtonId:
/* Don't continue if validation hasn't been done or has failed. */
if (!m_has_validated || R_FAILED(m_validation_info.result)) {
break;
}
/* Check if exfat is supported. */
g_exfat_supported = m_update_info.exfat_supported && R_SUCCEEDED(m_validation_info.exfat_result);
if (!g_exfat_supported) {
g_use_exfat = false;
}
/* Create the next menu. */
std::shared_ptr<Menu> next_menu = std::make_shared<ChooseResetMenu>(g_current_menu);
/* Warn the user if they're updating with exFAT supposed to be supported but not present/corrupted. */
if (m_update_info.exfat_supported && R_FAILED(m_validation_info.exfat_result)) {
next_menu = std::make_shared<WarningMenu>(g_current_menu, next_menu, "Warning: exFAT firmware is missing or corrupt", "Are you sure you want to proceed?");
}
/* Warn the user if they're updating to a version higher than supported. */
const u32 version = m_validation_info.invalid_key.version;
if (EncodeVersion((version >> 26) & 0x1f, (version >> 20) & 0x1f, (version >> 16) & 0xf) > g_supported_version) {
next_menu = std::make_shared<WarningMenu>(g_current_menu, next_menu, "Warning: firmware is too new and not known to be supported", "Are you sure you want to proceed?");
}
/* Change to the next menu. */
ChangeMenu(next_menu);
return;
}
}
this->UpdateButtons();
}
void ValidateUpdateMenu::Draw(NVGcontext *vg, u64 ns) {
const float x = g_screen_width / 2.0f - WindowWidth / 2.0f;
const float y = g_screen_height / 2.0f - WindowHeight / 2.0f;
DrawWindow(vg, "Update information", x, y, WindowWidth, WindowHeight);
DrawTextBackground(vg, x + HorizontalInset, y + TitleGap, WindowWidth - HorizontalInset * 2.0f, TextAreaHeight);
DrawTextBlock(vg, m_log_buffer, x + HorizontalInset + TextHorizontalInset, y + TitleGap + TextVerticalInset, WindowWidth - (HorizontalInset + TextHorizontalInset) * 2.0f, TextAreaHeight - TextVerticalInset * 2.0f);
this->DrawButtons(vg, ns);
m_has_drawn = true;
}
ChooseResetMenu::ChooseResetMenu(std::shared_ptr<Menu> prev_menu) : Menu(prev_menu) {
const float x = g_screen_width / 2.0f - WindowWidth / 2.0f;
const float y = g_screen_height / 2.0f - WindowHeight / 2.0f;
const float button_width = (WindowWidth - HorizontalInset * 2.0f) / 2.0f - ButtonHorizontalGap;
/* Add buttons. */
this->AddButton(ResetToFactorySettingsButtonId, "Reset to factory settings", x + HorizontalInset, y + TitleGap, button_width, ButtonHeight);
this->AddButton(PreserveSettingsButtonId, "Preserve settings", x + HorizontalInset + button_width + ButtonHorizontalGap, y + TitleGap, button_width, ButtonHeight);
this->SetButtonSelected(PreserveSettingsButtonId, true);
}
void ChooseResetMenu::Update(u64 ns) {
u64 k_down = padGetButtonsDown(&g_pad);
/* Go back if B is pressed. */
if (k_down & HidNpadButton_B) {
ReturnToPreviousMenu();
return;
}
/* Take action if a button has been activated. */
if (const Button *activated_button = this->GetActivatedButton(); activated_button != nullptr) {
switch (activated_button->id) {
case ResetToFactorySettingsButtonId:
g_reset_to_factory = true;
break;
case PreserveSettingsButtonId:
g_reset_to_factory = false;
break;
}
std::shared_ptr<Menu> next_menu;
if (g_exfat_supported) {
next_menu = std::make_shared<ChooseExfatMenu>(g_current_menu);
} else {
next_menu = std::make_shared<WarningMenu>(g_current_menu, std::make_shared<InstallUpdateMenu>(g_current_menu), "Ready to begin update installation", "Are you sure you want to proceed?");
}
if (g_reset_to_factory) {
ChangeMenu(std::make_shared<WarningMenu>(g_current_menu, next_menu, "Warning: Factory reset selected", "Saves and installed games will be permanently deleted."));
} else {
ChangeMenu(next_menu);
}
}
this->UpdateButtons();
/* Fallback on selecting the exfat button. */
if (const Button *selected_button = this->GetSelectedButton(); k_down && selected_button == nullptr) {
this->SetButtonSelected(PreserveSettingsButtonId, true);
}
}
void ChooseResetMenu::Draw(NVGcontext *vg, u64 ns) {
const float x = g_screen_width / 2.0f - WindowWidth / 2.0f;
const float y = g_screen_height / 2.0f - WindowHeight / 2.0f;
DrawWindow(vg, "Select settings mode", x, y, WindowWidth, WindowHeight);
this->DrawButtons(vg, ns);
}
ChooseExfatMenu::ChooseExfatMenu(std::shared_ptr<Menu> prev_menu) : Menu(prev_menu) {
const float x = g_screen_width / 2.0f - WindowWidth / 2.0f;
const float y = g_screen_height / 2.0f - WindowHeight / 2.0f;
const float button_width = (WindowWidth - HorizontalInset * 2.0f) / 2.0f - ButtonHorizontalGap;
/* Add buttons. */
this->AddButton(Fat32ButtonId, "Install (FAT32)", x + HorizontalInset, y + TitleGap, button_width, ButtonHeight);
this->AddButton(ExFatButtonId, "Install (FAT32 + exFAT)", x + HorizontalInset + button_width + ButtonHorizontalGap, y + TitleGap, button_width, ButtonHeight);
/* Set the default selected button based on the user's current install. We aren't particularly concerned if fsIsExFatSupported fails. */
bool exfat_supported = false;
fsIsExFatSupported(&exfat_supported);
if (exfat_supported) {
this->SetButtonSelected(ExFatButtonId, true);
} else {
this->SetButtonSelected(Fat32ButtonId, true);
}
}
void ChooseExfatMenu::Update(u64 ns) {
u64 k_down = padGetButtonsDown(&g_pad);
/* Go back if B is pressed. */
if (k_down & HidNpadButton_B) {
ReturnToPreviousMenu();
return;
}
/* Take action if a button has been activated. */
if (const Button *activated_button = this->GetActivatedButton(); activated_button != nullptr) {
switch (activated_button->id) {
case Fat32ButtonId:
g_use_exfat = false;
break;
case ExFatButtonId:
g_use_exfat = true;
break;
}
ChangeMenu(std::make_shared<WarningMenu>(g_current_menu, std::make_shared<InstallUpdateMenu>(g_current_menu), "Ready to begin update installation", "Are you sure you want to proceed?"));
}
this->UpdateButtons();
/* Fallback on selecting the exfat button. */
if (const Button *selected_button = this->GetSelectedButton(); k_down && selected_button == nullptr) {
this->SetButtonSelected(ExFatButtonId, true);
}
}
void ChooseExfatMenu::Draw(NVGcontext *vg, u64 ns) {
const float x = g_screen_width / 2.0f - WindowWidth / 2.0f;
const float y = g_screen_height / 2.0f - WindowHeight / 2.0f;
DrawWindow(vg, "Select driver variant", x, y, WindowWidth, WindowHeight);
this->DrawButtons(vg, ns);
}
InstallUpdateMenu::InstallUpdateMenu(std::shared_ptr<Menu> prev_menu) : Menu(prev_menu), m_install_state(InstallState::NeedsDraw), m_progress_percent(0.0f) {
const float x = g_screen_width / 2.0f - WindowWidth / 2.0f;
const float y = g_screen_height / 2.0f - WindowHeight / 2.0f;
const float button_width = (WindowWidth - HorizontalInset * 2.0f) / 2.0f - ButtonHorizontalGap;
/* Add buttons. */
this->AddButton(ShutdownButtonId, "Shutdown", x + HorizontalInset, y + WindowHeight - BottomInset - ButtonHeight, button_width, ButtonHeight);
this->AddButton(RebootButtonId, "Reboot", x + HorizontalInset + button_width + ButtonHorizontalGap, y + WindowHeight - BottomInset - ButtonHeight, button_width, ButtonHeight);
this->SetButtonEnabled(ShutdownButtonId, false);
this->SetButtonEnabled(RebootButtonId, false);
/* Prevent the home button from being pressed during installation. */
hiddbgDeactivateHomeButton();
}
void InstallUpdateMenu::MarkForReboot() {
this->SetButtonEnabled(ShutdownButtonId, true);
this->SetButtonEnabled(RebootButtonId, true);
this->SetButtonSelected(RebootButtonId, true);
m_install_state = InstallState::AwaitingReboot;
}
Result InstallUpdateMenu::TransitionUpdateState() {
Result rc = 0;
if (m_install_state == InstallState::NeedsSetup) {
/* Setup the update. */
if (R_FAILED(rc = amssuSetupUpdate(nullptr, UpdateTaskBufferSize, g_update_path, g_use_exfat))) {
this->LogText("Failed to setup update.\nResult: 0x%08x\n", rc);
this->MarkForReboot();
return rc;
}
/* Log setup completion. */
this->LogText("Update setup complete.\n");
m_install_state = InstallState::NeedsPrepare;
} else if (m_install_state == InstallState::NeedsPrepare) {
/* Request update preparation. */
if (R_FAILED(rc = amssuRequestPrepareUpdate(&m_prepare_result))) {
this->LogText("Failed to request update preparation.\nResult: 0x%08x\n", rc);
this->MarkForReboot();
return rc;
}
/* Log awaiting prepare. */
this->LogText("Preparing update...\n");
m_install_state = InstallState::AwaitingPrepare;
} else if (m_install_state == InstallState::AwaitingPrepare) {
/* Check if preparation has a result. */
if (R_FAILED(rc = asyncResultWait(&m_prepare_result, 0)) && rc != 0xea01) {
this->LogText("Failed to check update preparation result.\nResult: 0x%08x\n", rc);
this->MarkForReboot();
return rc;
} else if (R_SUCCEEDED(rc)) {
if (R_FAILED(rc = asyncResultGet(&m_prepare_result))) {
this->LogText("Failed to prepare update.\nResult: 0x%08x\n", rc);
this->MarkForReboot();
return rc;
}
}
/* Check if the update has been prepared. */
bool prepared;
if (R_FAILED(rc = amssuHasPreparedUpdate(&prepared))) {
this->LogText("Failed to check if update has been prepared.\nResult: 0x%08x\n", rc);
this->MarkForReboot();
return rc;
}
/* Mark for application if preparation complete. */
if (prepared) {
this->LogText("Update preparation complete.\nApplying update...\n");
m_install_state = InstallState::NeedsApply;
return rc;
}
/* Check update progress. */
NsSystemUpdateProgress update_progress = {};
if (R_FAILED(rc = amssuGetPrepareUpdateProgress(&update_progress))) {
this->LogText("Failed to check update progress.\nResult: 0x%08x\n", rc);
this->MarkForReboot();
return rc;
}
/* Update progress percent. */
if (update_progress.total_size > 0.0f) {
m_progress_percent = static_cast<float>(update_progress.current_size) / static_cast<float>(update_progress.total_size);
} else {
m_progress_percent = 0.0f;
}
} else if (m_install_state == InstallState::NeedsApply) {
/* Apply the prepared update. */
if (R_FAILED(rc = amssuApplyPreparedUpdate())) {
this->LogText("Failed to apply update.\nResult: 0x%08x\n", rc);
} else {
/* Log success. */
this->LogText("Update applied successfully.\n");
if (g_reset_to_factory) {
if (R_FAILED(rc = nsResetToFactorySettingsForRefurbishment())) {
/* Fallback on ResetToFactorySettings. */
if (rc == MAKERESULT(Module_Libnx, LibnxError_IncompatSysVer)) {
if (R_FAILED(rc = nsResetToFactorySettings())) {
this->LogText("Failed to reset to factory settings.\nResult: 0x%08x\n", rc);
this->MarkForReboot();
return rc;
}
} else {
this->LogText("Failed to reset to factory settings for refurbishment.\nResult: 0x%08x\n", rc);
this->MarkForReboot();
return rc;
}
}
this->LogText("Successfully reset to factory settings.\n", rc);
}
}
this->MarkForReboot();
return rc;
}
return rc;
}
void InstallUpdateMenu::Update(u64 ns) {
/* Transition to the next update state. */
if (m_install_state != InstallState::NeedsDraw && m_install_state != InstallState::AwaitingReboot) {
this->TransitionUpdateState();
}
/* Take action if a button has been activated. */
if (const Button *activated_button = this->GetActivatedButton(); activated_button != nullptr) {
switch (activated_button->id) {
case ShutdownButtonId:
if (R_FAILED(appletRequestToShutdown())) {
spsmShutdown(false);
}
break;
case RebootButtonId:
if (R_FAILED(appletRequestToReboot())) {
spsmShutdown(true);
}
break;
}
}
this->UpdateButtons();
}
void InstallUpdateMenu::Draw(NVGcontext *vg, u64 ns) {
const float x = g_screen_width / 2.0f - WindowWidth / 2.0f;
const float y = g_screen_height / 2.0f - WindowHeight / 2.0f;
DrawWindow(vg, "Installing update", x, y, WindowWidth, WindowHeight);
DrawProgressText(vg, x + HorizontalInset, y + TitleGap, m_progress_percent);
DrawProgressBar(vg, x + HorizontalInset, y + TitleGap + ProgressTextHeight, WindowWidth - HorizontalInset * 2.0f, ProgressBarHeight, m_progress_percent);
DrawTextBackground(vg, x + HorizontalInset, y + TitleGap + ProgressTextHeight + ProgressBarHeight + VerticalGap, WindowWidth - HorizontalInset * 2.0f, TextAreaHeight);
DrawTextBlock(vg, m_log_buffer, x + HorizontalInset + TextHorizontalInset, y + TitleGap + ProgressTextHeight + ProgressBarHeight + VerticalGap + TextVerticalInset, WindowWidth - (HorizontalInset + TextHorizontalInset) * 2.0f, TextAreaHeight - TextVerticalInset * 2.0f);
this->DrawButtons(vg, ns);
/* We have drawn now, allow setup to occur. */
if (m_install_state == InstallState::NeedsDraw) {
this->LogText("Beginning update setup...\n");
m_install_state = InstallState::NeedsSetup;
}
}
bool InitializeMenu(u32 screen_width, u32 screen_height) {
Result rc = 0;
/* Configure and initialize the gamepad. */
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
padInitializeDefault(&g_pad);
/* Initialize the touch screen. */
hidInitializeTouchScreen();
/* Set the screen width and height. */
g_screen_width = screen_width;
g_screen_height = screen_height;
/* Mark as initialized. */
g_initialized = true;
/* Attempt to get the exosphere version. */
u64 version;
if (R_FAILED(rc = splGetConfig(static_cast<SplConfigItem>(ExosphereApiVersionConfigItem), &version))) {
ChangeMenu(std::make_shared<ErrorMenu>("Atmosphere not found", "Daybreak requires Atmosphere to be installed.", rc));
return false;
}
const u32 version_micro = (version >> 40) & 0xff;
const u32 version_minor = (version >> 48) & 0xff;
const u32 version_major = (version >> 56) & 0xff;
/* Validate the exosphere version. */
const bool ams_supports_sysupdate_api = EncodeVersion(version_major, version_minor, version_micro) >= EncodeVersion(0, 14, 0);
if (!ams_supports_sysupdate_api) {
ChangeMenu(std::make_shared<ErrorMenu>("Outdated Atmosphere version", "Daybreak requires Atmosphere 0.14.0 or later.", rc));
return false;
}
/* Ensure DayBreak is ran as a NRO. */
if (envIsNso()) {
ChangeMenu(std::make_shared<ErrorMenu>("Unsupported Environment", "Please launch Daybreak via the Homebrew menu.", rc));
return false;
}
/* Attempt to get the supported version. */
if (R_SUCCEEDED(rc = splGetConfig(static_cast<SplConfigItem>(ExosphereSupportedHosVersion), &version))) {
g_supported_version = static_cast<u32>(version);
}
/* Initialize ams:su. */
if (R_FAILED(rc = amssuInitialize())) {
fatalThrow(rc);
}
/* Change the current menu to the main menu. */
g_current_menu = std::make_shared<MainMenu>();
return true;
}
bool InitializeMenu(u32 screen_width, u32 screen_height, const char *update_path) {
if (InitializeMenu(screen_width, screen_height)) {
/* Set the update path. */
strncpy(g_update_path, update_path, sizeof(g_update_path));
/* Change the menu. */
ChangeMenu(std::make_shared<ValidateUpdateMenu>(g_current_menu));
return true;
}
return false;
}
void UpdateMenu(u64 ns) {
DBK_ABORT_UNLESS(g_initialized);
DBK_ABORT_UNLESS(g_current_menu != nullptr);
UpdateInput();
g_current_menu->Update(ns);
}
void RenderMenu(NVGcontext *vg, u64 ns) {
DBK_ABORT_UNLESS(g_initialized);
DBK_ABORT_UNLESS(g_current_menu != nullptr);
/* Draw background. */
DrawBackground(vg, g_screen_width, g_screen_height);
/* Draw stars. */
DrawStar(vg, 40.0f, 64.0f, 3.0f);
DrawStar(vg, 110.0f, 300.0f, 3.0f);
DrawStar(vg, 200.0f, 150.0f, 4.0f);
DrawStar(vg, 370.0f, 280.0f, 3.0f);
DrawStar(vg, 450.0f, 40.0f, 3.5f);
DrawStar(vg, 710.0f, 90.0f, 3.0f);
DrawStar(vg, 900.0f, 240.0f, 3.0f);
DrawStar(vg, 970.0f, 64.0f, 4.0f);
DrawStar(vg, 1160.0f, 160.0f, 3.5f);
DrawStar(vg, 1210.0f, 350.0f, 3.0f);
g_current_menu->Draw(vg, ns);
}
bool IsExitRequested() {
return g_exit_requested;
}
}
| 53,613
|
C++
|
.cpp
| 1,079
| 37.963855
| 277
| 0.578305
|
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,276
|
kern_loader_panic.cpp
|
Atmosphere-NX_Atmosphere/mesosphere/kernel_ldr/source/kern_loader_panic.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <mesosphere.hpp>
namespace ams::kern {
/* This overrides the panic implementation from the kernel, to prevent linking debug print into kldr. */
NORETURN void PanicImpl(const char *file, int line, const char *format, ...) {
MESOSPHERE_UNUSED(file, line, format);
MESOSPHERE_INIT_ABORT();
}
NORETURN void PanicImpl() {
MESOSPHERE_INIT_ABORT();
}
}
| 1,039
|
C++
|
.cpp
| 26
| 36.538462
| 108
| 0.72619
|
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,277
|
kern_init_loader.cpp
|
Atmosphere-NX_Atmosphere/mesosphere/kernel_ldr/source/kern_init_loader.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <mesosphere.hpp>
#include "kern_init_loader_board_setup.hpp"
/* Necessary for calculating kernelldr size/base for initial identity mapping */
extern "C" {
extern const u8 __bin_start__[];
extern const u8 __bin_end__[];
}
namespace ams::kern::init::loader {
namespace {
constexpr uintptr_t KernelBaseAlignment = 0x200000;
constexpr uintptr_t KernelBaseRangeStart = 0xFFFFFF8000000000;
constexpr uintptr_t KernelBaseRangeEnd = 0xFFFFFFFFFFE00000;
constexpr uintptr_t KernelBaseRangeLast = KernelBaseRangeEnd - 1;
static_assert(util::IsAligned(KernelBaseRangeStart, KernelBaseAlignment));
static_assert(util::IsAligned(KernelBaseRangeEnd, KernelBaseAlignment));
static_assert(KernelBaseRangeStart <= KernelBaseRangeLast);
static_assert(InitialProcessBinarySizeMax <= KernelResourceSize);
constexpr size_t InitialPageTableRegionSizeMax = 2_MB;
static_assert(InitialPageTableRegionSizeMax < KernelPageTableHeapSize + KernelInitialPageHeapSize);
/* Global Allocator. */
constinit KInitialPageAllocator g_initial_page_allocator;
constinit KInitialPageAllocator::State g_final_page_allocator_state;
constinit InitialProcessBinaryLayoutWithSize g_initial_process_binary_meta;
constinit void *g_final_state[2];
void RelocateKernelPhysically(uintptr_t &base_address, KernelLayout *&layout) {
/* Adjust layout to be correct. */
{
const ptrdiff_t layout_offset = reinterpret_cast<uintptr_t>(layout) - base_address;
layout->rx_offset += layout_offset;
layout->rx_end_offset += layout_offset;
layout->ro_offset += layout_offset;
layout->ro_end_offset += layout_offset;
layout->rw_offset += layout_offset;
layout->rw_end_offset += layout_offset;
layout->bss_offset += layout_offset;
layout->bss_end_offset += layout_offset;
layout->resource_offset += layout_offset;
layout->dynamic_offset += layout_offset;
layout->init_array_offset += layout_offset;
layout->init_array_end_offset += layout_offset;
layout->sysreg_offset += layout_offset;
}
/* Relocate the kernel if necessary. */
KPhysicalAddress correct_base = KSystemControl::Init::GetKernelPhysicalBaseAddress(base_address);
if (correct_base != base_address) {
const uintptr_t diff = GetInteger(correct_base) - base_address;
const size_t size = layout->rw_end_offset;
/* Conversion from KPhysicalAddress to void * is safe here, because MMU is not set up yet. */
std::memmove(reinterpret_cast<void *>(GetInteger(correct_base)), reinterpret_cast<void *>(base_address), size);
base_address += diff;
layout = reinterpret_cast<KernelLayout *>(reinterpret_cast<uintptr_t>(layout) + diff);
}
}
void SetupInitialIdentityMapping(KInitialPageTable &init_pt, uintptr_t base_address, uintptr_t kernel_size, uintptr_t page_table_region, size_t page_table_region_size, KInitialPageAllocator &allocator, KernelSystemRegisters *sysregs) {
/* Map in an RWX identity mapping for the kernel. */
constexpr PageTableEntry KernelRWXIdentityAttribute(PageTableEntry::Permission_KernelRWX, PageTableEntry::PageAttribute_NormalMemory, PageTableEntry::Shareable_InnerShareable, PageTableEntry::MappingFlag_Mapped);
init_pt.Map(base_address, kernel_size, base_address, KernelRWXIdentityAttribute, allocator, 0);
/* Map in an RWX identity mapping for ourselves. */
constexpr PageTableEntry KernelLdrRWXIdentityAttribute(PageTableEntry::Permission_KernelRWX, PageTableEntry::PageAttribute_NormalMemory, PageTableEntry::Shareable_InnerShareable, PageTableEntry::MappingFlag_Mapped);
const uintptr_t kernel_ldr_base = util::AlignDown(reinterpret_cast<uintptr_t>(__bin_start__), PageSize);
const uintptr_t kernel_ldr_size = util::AlignUp(reinterpret_cast<uintptr_t>(__bin_end__), PageSize) - kernel_ldr_base;
init_pt.Map(kernel_ldr_base, kernel_ldr_size, kernel_ldr_base, KernelRWXIdentityAttribute, allocator, 0);
/* Map in the page table region as RW- for ourselves. */
constexpr PageTableEntry PageTableRegionRWAttribute(PageTableEntry::Permission_KernelRW, PageTableEntry::PageAttribute_NormalMemory, PageTableEntry::Shareable_InnerShareable, PageTableEntry::MappingFlag_Mapped);
init_pt.Map(page_table_region, page_table_region_size, page_table_region, KernelRWXIdentityAttribute, allocator, 0);
/* Place the L1 table addresses in the relevant system registers. */
cpu::SetTtbr0El1(init_pt.GetTtbr0L1TableAddress());
cpu::SetTtbr1El1(init_pt.GetTtbr1L1TableAddress());
/* Setup MAIR_EL1, TCR_EL1. */
/* TODO: Define these bits properly elsewhere, document exactly what each bit set is doing .*/
constexpr u64 MairValue = 0x0000000044FF0400ul;
constexpr u64 TcrValue = 0x00000011B5193519ul;
cpu::MemoryAccessIndirectionRegisterAccessor(MairValue).Store();
cpu::TranslationControlRegisterAccessor(TcrValue).Store();
/* Ensure that our configuration takes before proceeding. */
cpu::EnsureInstructionConsistency();
/* Perform board-specific setup. */
PerformBoardSpecificSetup();
/* Setup SCTLR_EL1. */
/* TODO: Define these bits properly elsewhere, document exactly what each bit set is doing .*/
constexpr u64 SctlrValue = 0x0000000034D5D92Dul;
cpu::SetSctlrEl1(SctlrValue);
cpu::InstructionMemoryBarrier();
/* Setup the system registers for other cores. */
/* NOTE: sctlr_el1 on other cores has the WXN bit set (0x80000); this will be set before KernelMain() on this core. */
sysregs->ttbr0_el1 = init_pt.GetTtbr0L1TableAddress();
sysregs->ttbr1_el1 = init_pt.GetTtbr1L1TableAddress();
sysregs->tcr_el1 = TcrValue;
sysregs->mair_el1 = MairValue;
sysregs->sctlr_el1 = SctlrValue | 0x80000;
}
KVirtualAddress GetRandomKernelBaseAddress(KInitialPageTable &page_table, KPhysicalAddress phys_base_address, size_t kernel_size) {
/* Define useful values for random generation. */
const uintptr_t kernel_offset = GetInteger(phys_base_address) % KernelBaseAlignment;
/* Repeatedly generate a random virtual address until we get one that's unmapped in the destination page table. */
while (true) {
const uintptr_t random_kaslr_slide = KSystemControl::Init::GenerateRandomRange(KernelBaseRangeStart / KernelBaseAlignment, KernelBaseRangeLast / KernelBaseAlignment);
const KVirtualAddress kernel_region_start = random_kaslr_slide * KernelBaseAlignment;
const KVirtualAddress kernel_region_end = kernel_region_start + util::AlignUp(kernel_offset + kernel_size, KernelBaseAlignment);
const size_t kernel_region_size = GetInteger(kernel_region_end) - GetInteger(kernel_region_start);
/* Make sure the region has not overflowed */
if (kernel_region_start >= kernel_region_end) {
continue;
}
/* Make sure that the region stays within our intended bounds. */
if (kernel_region_end > KernelBaseRangeEnd) {
continue;
}
/* Validate we can map the range we've selected. */
if (!page_table.IsFree(kernel_region_start, kernel_region_size)) {
continue;
}
/* Our range is valid! */
return kernel_region_start + kernel_offset;
}
}
}
uintptr_t Main(uintptr_t base_address, KernelLayout *layout, uintptr_t ini_base_address) {
/* Relocate the kernel to the correct physical base address. */
/* Base address and layout are passed by reference and modified. */
RelocateKernelPhysically(base_address, layout);
/* Validate kernel layout. */
const uintptr_t rx_offset = layout->rx_offset;
const uintptr_t rx_end_offset = layout->rx_end_offset;
const uintptr_t ro_offset = layout->ro_offset;
const uintptr_t ro_end_offset = layout->ro_end_offset;
const uintptr_t rw_offset = layout->rw_offset;
/* UNUSED: const uintptr_t rw_end_offset = layout->rw_end_offset; */
const uintptr_t bss_end_offset = layout->bss_end_offset;
MESOSPHERE_INIT_ABORT_UNLESS(util::IsAligned(rx_offset, PageSize));
MESOSPHERE_INIT_ABORT_UNLESS(util::IsAligned(rx_end_offset, PageSize));
MESOSPHERE_INIT_ABORT_UNLESS(util::IsAligned(ro_offset, PageSize));
MESOSPHERE_INIT_ABORT_UNLESS(util::IsAligned(ro_end_offset, PageSize));
MESOSPHERE_INIT_ABORT_UNLESS(util::IsAligned(rw_offset, PageSize));
MESOSPHERE_INIT_ABORT_UNLESS(util::IsAligned(bss_end_offset, PageSize));
const uintptr_t bss_offset = layout->bss_offset;
const uintptr_t resource_offset = layout->resource_offset;
const uintptr_t dynamic_offset = layout->dynamic_offset;
const uintptr_t init_array_offset = layout->init_array_offset;
const uintptr_t init_array_end_offset = layout->init_array_end_offset;
const uintptr_t sysreg_offset = layout->sysreg_offset;
/* Determine the size of the resource region. */
const size_t resource_region_size = KMemoryLayout::GetResourceRegionSizeForInit(KSystemControl::Init::ShouldIncreaseThreadResourceLimit());
const uintptr_t resource_end_address = base_address + resource_offset + resource_region_size;
/* Setup the INI1 header in memory for the kernel. */
{
/* Get the kernel layout. */
KSystemControl::Init::GetInitialProcessBinaryLayout(std::addressof(g_initial_process_binary_meta.layout), base_address);
/* If there's no desired base address, use the ini in place. */
if (g_initial_process_binary_meta.layout.address == 0) {
g_initial_process_binary_meta.layout.address = ini_base_address;
}
/* Validate and potentially relocate the INI. */
const InitialProcessBinaryHeader *ini_header = reinterpret_cast<const InitialProcessBinaryHeader *>(ini_base_address);
size_t ini_size = 0;
if (ini_header->magic == InitialProcessBinaryMagic && (ini_size = ini_header->size) <= InitialProcessBinarySizeMax) {
/* INI is valid, relocate it if necessary. */
if (ini_base_address != g_initial_process_binary_meta.layout.address) {
std::memmove(reinterpret_cast<void *>(g_initial_process_binary_meta.layout.address), ini_header, ini_size);
}
} else {
/* INI is invalid. Make the destination header invalid. */
std::memset(reinterpret_cast<void *>(g_initial_process_binary_meta.layout.address), 0, sizeof(InitialProcessBinaryHeader));
}
/* Set the INI size in layout. */
g_initial_process_binary_meta.size = util::AlignUp(ini_size, PageSize);
}
/* We want to start allocating page tables at the end of the resource region. */
g_initial_page_allocator.Initialize(resource_end_address);
/* Make a new page table for TTBR1_EL1. */
KInitialPageTable init_pt(KernelBaseRangeStart, KernelBaseRangeLast, g_initial_page_allocator);
/* Setup initial identity mapping. TTBR1 table passed by reference. */
SetupInitialIdentityMapping(init_pt, base_address, bss_end_offset, resource_end_address, InitialPageTableRegionSizeMax, g_initial_page_allocator, reinterpret_cast<KernelSystemRegisters *>(base_address + sysreg_offset));
/* Generate a random slide for the kernel's base address. */
const KVirtualAddress virtual_base_address = GetRandomKernelBaseAddress(init_pt, base_address, bss_end_offset);
/* Map kernel .text as R-X. */
constexpr PageTableEntry KernelTextAttribute(PageTableEntry::Permission_KernelRX, PageTableEntry::PageAttribute_NormalMemory, PageTableEntry::Shareable_InnerShareable, PageTableEntry::MappingFlag_Mapped);
init_pt.Map(virtual_base_address + rx_offset, rx_end_offset - rx_offset, base_address + rx_offset, KernelTextAttribute, g_initial_page_allocator, 0);
/* Map kernel .rodata and .rwdata as RW-. */
/* Note that we will later reprotect .rodata as R-- */
constexpr PageTableEntry KernelRoDataAttribute(PageTableEntry::Permission_KernelR, PageTableEntry::PageAttribute_NormalMemory, PageTableEntry::Shareable_InnerShareable, PageTableEntry::MappingFlag_Mapped);
constexpr PageTableEntry KernelRwDataAttribute(PageTableEntry::Permission_KernelRW, PageTableEntry::PageAttribute_NormalMemory, PageTableEntry::Shareable_InnerShareable, PageTableEntry::MappingFlag_Mapped);
init_pt.Map(virtual_base_address + ro_offset, ro_end_offset - ro_offset, base_address + ro_offset, KernelRwDataAttribute, g_initial_page_allocator, 0);
init_pt.Map(virtual_base_address + rw_offset, bss_end_offset - rw_offset, base_address + rw_offset, KernelRwDataAttribute, g_initial_page_allocator, 0);
/* Physically randomize the kernel region. */
/* NOTE: Nintendo does this only on 10.0.0+ */
init_pt.PhysicallyRandomize(virtual_base_address + rx_offset, bss_end_offset - rx_offset, true);
/* Apply relocations to the kernel. */
const Elf::Dyn *kernel_dynamic = reinterpret_cast<const Elf::Dyn *>(GetInteger(virtual_base_address) + dynamic_offset);
Elf::ApplyRelocations(GetInteger(virtual_base_address), kernel_dynamic);
/* Clear kernel .bss. */
/* NOTE: The kernel does this before applying relocations, but we do it after. */
/* This allows us to place our relocations in space overlapping with .bss...and thereby reclaim the memory that would otherwise be wasted. */
std::memset(GetVoidPointer(virtual_base_address + bss_offset), 0, bss_end_offset - bss_offset);
/* Call the kernel's init array functions. */
/* NOTE: The kernel does this after reprotecting .rodata, but we do it before. */
/* This allows our global constructors to edit .rodata, which is valuable for editing the SVC tables to support older firmwares' ABIs. */
Elf::CallInitArrayFuncs(GetInteger(virtual_base_address) + init_array_offset, GetInteger(virtual_base_address) + init_array_end_offset);
/* Reprotect .rodata as R-- */
init_pt.Reprotect(virtual_base_address + ro_offset, ro_end_offset - ro_offset, KernelRwDataAttribute, KernelRoDataAttribute);
/* Return the difference between the random virtual base and the physical base. */
return GetInteger(virtual_base_address) - base_address;
}
KPhysicalAddress AllocateKernelInitStack() {
return g_initial_page_allocator.Allocate(PageSize) + PageSize;
}
void **GetFinalState() {
/* Get final page allocator state. */
g_initial_page_allocator.GetFinalState(std::addressof(g_final_page_allocator_state));
/* Setup final kernel loader state. */
g_final_state[0] = std::addressof(g_final_page_allocator_state);
g_final_state[1] = std::addressof(g_initial_process_binary_meta);
return g_final_state;
}
}
| 16,696
|
C++
|
.cpp
| 230
| 61.547826
| 243
| 0.674426
|
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,278
|
kern_init_loader_board_default_setup.arch.arm64.cpp
|
Atmosphere-NX_Atmosphere/mesosphere/kernel_ldr/source/kern_init_loader_board_default_setup.arch.arm64.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <mesosphere.hpp>
#include "kern_init_loader_asm.hpp"
#include "kern_init_loader_board_setup.hpp"
namespace ams::kern::init::loader {
void PerformDefaultAarch64SpecificSetup() {
SavedRegisterState saved_registers;
SaveRegistersToTpidrEl1(std::addressof(saved_registers));
ON_SCOPE_EXIT { VerifyAndClearTpidrEl1(std::addressof(saved_registers)); };
/* Main ID specific setup. */
cpu::MainIdRegisterAccessor midr_el1;
if (midr_el1.GetImplementer() == cpu::MainIdRegisterAccessor::Implementer::ArmLimited) {
/* ARM limited specific setup. */
const auto cpu_primary_part = midr_el1.GetPrimaryPartNumber();
const auto cpu_variant = midr_el1.GetVariant();
const auto cpu_revision = midr_el1.GetRevision();
if (cpu_primary_part == cpu::MainIdRegisterAccessor::PrimaryPartNumber::CortexA57) {
/* Cortex-A57 specific setup. */
/* Non-cacheable load forwarding enabled. */
u64 cpuactlr_value = 0x1000000;
/* Enable the processor to receive instruction cache and TLB maintenance */
/* operations broadcast from other processors in the cluster; */
/* set the L2 load/store data prefetch distance to 8 requests; */
/* set the L2 instruction fetch prefetch distance to 3 requests. */
u64 cpuectlr_value = 0x1B00000040;
/* Disable load-pass DMB on certain hardware variants. */
if (cpu_variant == 0 || (cpu_variant == 1 && cpu_revision <= 1)) {
cpuactlr_value |= 0x800000000000000;
}
/* Set actlr and ectlr. */
if (cpu::GetCpuActlrEl1() != cpuactlr_value) {
cpu::SetCpuActlrEl1(cpuactlr_value);
}
if (cpu::GetCpuEctlrEl1() != cpuectlr_value) {
cpu::SetCpuEctlrEl1(cpuectlr_value);
}
} else if (cpu_primary_part == cpu::MainIdRegisterAccessor::PrimaryPartNumber::CortexA53) {
/* Cortex-A53 specific setup. */
/* Set L1 data prefetch control to allow 5 outstanding prefetches; */
/* enable device split throttle; */
/* set the number of independent data prefetch streams to 2; */
/* disable transient and no-read-allocate hints for loads; */
/* set write streaming no-allocate threshold so the 128th consecutive streaming */
/* cache line does not allocate in the L1 or L2 cache. */
u64 cpuactlr_value = 0x90CA000;
/* Enable hardware management of data coherency with other cores in the cluster. */
u64 cpuectlr_value = 0x40;
/* If supported, enable data cache clean as data cache clean/invalidate. */
if (cpu_variant != 0 || (cpu_variant == 0 && cpu_revision > 2)) {
cpuactlr_value |= 0x100000000000;
}
/* Set actlr and ectlr. */
if (cpu::GetCpuActlrEl1() != cpuactlr_value) {
cpu::SetCpuActlrEl1(cpuactlr_value);
}
if (cpu::GetCpuEctlrEl1() != cpuectlr_value) {
cpu::SetCpuEctlrEl1(cpuectlr_value);
}
}
}
}
/* This is a default implementation, which should be overridden in a source file in board/ */
WEAK_SYMBOL void PerformBoardSpecificSetup() {
return PerformDefaultAarch64SpecificSetup();
}
}
| 4,280
|
C++
|
.cpp
| 80
| 41.7625
| 103
| 0.607595
|
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,279
|
kern_init_loader_board_setup.cpp
|
Atmosphere-NX_Atmosphere/mesosphere/kernel_ldr/source/board/nintendo/nx/kern_init_loader_board_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 <mesosphere.hpp>
#include "../../../kern_init_loader_board_setup.hpp"
namespace ams::kern::init::loader {
void PerformBoardSpecificSetup() {
/* ... */
}
}
| 818
|
C++
|
.cpp
| 22
| 34.681818
| 76
| 0.728878
|
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,280
|
kern_kernel_instantiations.cpp
|
Atmosphere-NX_Atmosphere/mesosphere/kernel/source/kern_kernel_instantiations.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <mesosphere.hpp>
namespace ams::kern {
/* Declare kernel data members in kernel TU. */
constinit Kernel::State Kernel::s_state = Kernel::State::Invalid;
constinit KResourceLimit Kernel::s_system_resource_limit{util::ConstantInitialize};
KMemoryManager Kernel::s_memory_manager;
constinit KSupervisorPageTable Kernel::s_supervisor_page_table;
constinit KUnsafeMemory Kernel::s_unsafe_memory;
constinit KWorkerTaskManager Kernel::s_worker_task_managers[KWorkerTaskManager::WorkerType_Count];
constinit KInterruptManager Kernel::s_interrupt_manager;
constinit KScheduler Kernel::s_schedulers[cpu::NumCores];
constinit KInterruptTaskManager Kernel::s_interrupt_task_managers[cpu::NumCores];
constinit KHardwareTimer Kernel::s_hardware_timers[cpu::NumCores];
constinit KPageTableSlabHeap Kernel::s_page_table_heap;
constinit KMemoryBlockSlabHeap Kernel::s_app_memory_block_heap;
constinit KMemoryBlockSlabHeap Kernel::s_sys_memory_block_heap;
constinit KBlockInfoSlabHeap Kernel::s_block_info_heap;
constinit KPageTableManager Kernel::s_app_page_table_manager{util::ConstantInitialize};
constinit KPageTableManager Kernel::s_sys_page_table_manager{util::ConstantInitialize};
constinit KMemoryBlockSlabManager Kernel::s_app_memory_block_manager;
constinit KMemoryBlockSlabManager Kernel::s_sys_memory_block_manager;
constinit KBlockInfoManager Kernel::s_app_block_info_manager;
constinit KBlockInfoManager Kernel::s_sys_block_info_manager;
constinit KSystemResource Kernel::s_app_system_resource{util::ConstantInitialize};
constinit KSystemResource Kernel::s_sys_system_resource{util::ConstantInitialize};
namespace {
template<size_t N> requires (N > 0)
union KThreadArray {
struct RecursiveHolder {
KThread m_thread;
KThreadArray<N - 1> m_next;
consteval RecursiveHolder() : m_thread{util::ConstantInitialize}, m_next() { /* ... */ }
} m_holder;
KThread m_arr[N];
consteval KThreadArray() : m_holder() { /* ... */ }
};
template<>
union KThreadArray<1>{
struct RecursiveHolder {
KThread m_thread;
consteval RecursiveHolder() : m_thread{util::ConstantInitialize} { /* ... */ }
} m_holder;
KThread m_arr[1];
consteval KThreadArray() : m_holder() { /* ... */ }
};
template<size_t Ix>
consteval bool IsKThreadArrayValid(const KThreadArray<Ix> &v, const KThread *thread) {
if (std::addressof(v.m_holder.m_thread) != thread) {
return false;
}
if constexpr (Ix == 1) {
return true;
} else {
return IsKThreadArrayValid(v.m_holder.m_next, thread + 1);
}
}
template<size_t N>
consteval bool IsKThreadArrayValid() {
const KThreadArray<N> v{};
if (!IsKThreadArrayValid(v, v.m_arr)) {
return false;
}
if constexpr (N == 1) {
return true;
} else {
return IsKThreadArrayValid<N - 1>();
}
}
static_assert(IsKThreadArrayValid<cpu::NumCores>());
constinit KThreadArray<cpu::NumCores> g_main_threads;
constinit KThreadArray<cpu::NumCores> g_idle_threads;
static_assert(sizeof(g_main_threads) == cpu::NumCores * sizeof(KThread));
static_assert(sizeof(g_main_threads.m_holder) == sizeof(g_main_threads.m_arr));
}
KThread &Kernel::GetMainThread(s32 core_id) { return g_main_threads.m_arr[core_id]; }
KThread &Kernel::GetIdleThread(s32 core_id) { return g_idle_threads.m_arr[core_id]; }
__attribute__((constructor)) void ConfigureKTargetSystem() {
KSystemControl::ConfigureKTargetSystem();
}
}
| 4,738
|
C++
|
.cpp
| 95
| 41.389474
| 107
| 0.647403
|
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,281
|
kern_env.cpp
|
Atmosphere-NX_Atmosphere/mesosphere/kernel/source/libc/kern_env.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <mesosphere.hpp>
void operator delete (void *deleted) throw() {
MESOSPHERE_PANIC("operator delete(void *) was called: %p", deleted);
}
void operator delete (void *deleted, size_t size) throw() {
MESOSPHERE_PANIC("operator delete(void *, size_t) was called: %p %zu", deleted, size);
}
void operator delete (void *deleted, size_t size, std::align_val_t align) throw() {
MESOSPHERE_PANIC("operator delete(void *, size_t, std::align_val_t) was called: %p %zu, %zu", deleted, size, static_cast<size_t>(align));
}
extern "C" void abort() {
MESOSPHERE_PANIC("abort() was called");
}
| 1,240
|
C++
|
.cpp
| 28
| 42.071429
| 141
| 0.725993
|
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,282
|
kern_init_core.cpp
|
Atmosphere-NX_Atmosphere/mesosphere/kernel/source/arch/arm64/init/kern_init_core.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <mesosphere.hpp>
extern "C" void __rodata_start();
extern "C" void __rodata_end();
extern "C" void __bin_start__();
extern "C" void __bin_end__();
namespace ams::kern {
void ExceptionVectors();
}
namespace ams::kern::init {
/* Prototypes for functions declared in ASM that we need to reference. */
void StartOtherCore(const ams::kern::init::KInitArguments *init_args);
void IdentityMappedFunctionAreaBegin();
void IdentityMappedFunctionAreaEnd();
size_t GetMiscUnknownDebugRegionSize();
size_t GetSecureUnknownRegionSize();
void InitializeDebugRegisters();
void InitializeExceptionVectors();
namespace {
/* Global Allocator. */
constinit KInitialPageAllocator g_initial_page_allocator;
constinit KInitArguments g_init_arguments[cpu::NumCores];
/* Globals for passing data between InitializeCorePhase1 and InitializeCorePhase2. */
constinit InitialProcessBinaryLayoutWithSize g_phase2_initial_process_binary_meta{};
constinit KPhysicalAddress g_phase2_resource_end_phys_addr = Null<KPhysicalAddress>;
constinit u64 g_phase2_linear_region_phys_to_virt_diff = 0;
/* Page table attributes. */
constexpr PageTableEntry KernelTextAttribute(PageTableEntry::Permission_KernelRX, PageTableEntry::PageAttribute_NormalMemory, PageTableEntry::Shareable_InnerShareable, PageTableEntry::MappingFlag_Mapped);
constexpr PageTableEntry KernelRoDataAttribute(PageTableEntry::Permission_KernelR, PageTableEntry::PageAttribute_NormalMemory, PageTableEntry::Shareable_InnerShareable, PageTableEntry::MappingFlag_Mapped);
constexpr PageTableEntry KernelRwDataAttribute(PageTableEntry::Permission_KernelRW, PageTableEntry::PageAttribute_NormalMemory, PageTableEntry::Shareable_InnerShareable, PageTableEntry::MappingFlag_Mapped);
constexpr PageTableEntry KernelMmioAttribute(PageTableEntry::Permission_KernelRW, PageTableEntry::PageAttribute_Device_nGnRE, PageTableEntry::Shareable_OuterShareable, PageTableEntry::MappingFlag_Mapped);
constexpr PageTableEntry KernelRwDataUncachedAttribute(PageTableEntry::Permission_KernelRW, PageTableEntry::PageAttribute_NormalMemoryNotCacheable, PageTableEntry::Shareable_InnerShareable, PageTableEntry::MappingFlag_Mapped);
void TurnOnAllCores() {
cpu::MultiprocessorAffinityRegisterAccessor mpidr;
const auto arg = mpidr.GetCpuOnArgument();
const auto current_core = mpidr.GetAff0();
for (s32 i = 0; i < static_cast<s32>(cpu::NumCores); i++) {
if (static_cast<s32>(current_core) != i) {
KSystemControl::Init::TurnOnCpu(arg | i, g_init_arguments + i);
}
}
}
void InvokeMain(u64 core_id) {
/* Clear cpacr_el1. */
cpu::SetCpacrEl1(0);
cpu::InstructionMemoryBarrier();
/* Initialize registers. */
InitializeDebugRegisters();
InitializeExceptionVectors();
/* Set exception stack. */
cpu::SetCntvCvalEl0(GetInteger(KMemoryLayout::GetExceptionStackTopAddress(static_cast<s32>(core_id))) - sizeof(KThread::StackParameters));
/* Call main. */
HorizonKernelMain(static_cast<s32>(core_id));
}
void SetupInitialArguments() {
/* Determine whether we're running on a cortex-a53 or a-57. */
cpu::MainIdRegisterAccessor midr_el1;
const auto implementer = midr_el1.GetImplementer();
const auto primary_part = midr_el1.GetPrimaryPartNumber();
const bool needs_cpu_ctlr = (implementer == cpu::MainIdRegisterAccessor::Implementer::ArmLimited) && (primary_part == cpu::MainIdRegisterAccessor::PrimaryPartNumber::CortexA57 || primary_part == cpu::MainIdRegisterAccessor::PrimaryPartNumber::CortexA53);
/* Get parameters for initial arguments. */
const u64 cpuactlr = needs_cpu_ctlr ? cpu::GetCpuActlrEl1() : 0;
const u64 cpuectlr = needs_cpu_ctlr ? cpu::GetCpuEctlrEl1() : 0;
for (s32 i = 0; i < static_cast<s32>(cpu::NumCores); ++i) {
/* Get the arguments. */
KInitArguments *init_args = g_init_arguments + i;
/* Set the arguments. */
init_args->cpuactlr = cpuactlr;
init_args->cpuectlr = cpuectlr;
init_args->sp = GetInteger(KMemoryLayout::GetMainStackTopAddress(i)) - sizeof(KThread::StackParameters);
init_args->entrypoint = reinterpret_cast<uintptr_t>(::ams::kern::init::InvokeMain);
init_args->argument = static_cast<u64>(i);
}
}
KVirtualAddress GetRandomAlignedRegionWithGuard(size_t size, size_t alignment, KInitialPageTable &pt, KMemoryRegionTree &tree, u32 type_id, size_t guard_size) {
/* Check that the size is valid. */
MESOSPHERE_INIT_ABORT_UNLESS(size > 0);
/* We want to find the total extents of the type id. */
const auto extents = tree.GetDerivedRegionExtents(type_id);
/* Ensure that our alignment is correct. */
MESOSPHERE_INIT_ABORT_UNLESS(util::IsAligned(extents.GetAddress(), alignment));
const uintptr_t first_address = extents.GetAddress();
const uintptr_t last_address = extents.GetLastAddress();
const uintptr_t first_index = first_address / alignment;
const uintptr_t last_index = last_address / alignment;
while (true) {
const uintptr_t candidate_start = KSystemControl::Init::GenerateRandomRange(first_index, last_index) * alignment;
const uintptr_t candidate_end = candidate_start + size + guard_size;
/* Ensure that the candidate doesn't overflow with the size/guard. */
if (!(candidate_start < candidate_end) || !(candidate_start >= guard_size)) {
continue;
}
const uintptr_t candidate_last = candidate_end - 1;
/* Ensure that the candidate fits within the region. */
if (candidate_last > last_address) {
continue;
}
/* Ensure that the candidate range is free. */
if (!pt.IsFree(candidate_start, size)) {
continue;
}
/* Locate the candidate's guard start, and ensure the whole range fits/has the correct type id. */
if (const auto &candidate_region = *tree.Find(candidate_start - guard_size); !(candidate_last <= candidate_region.GetLastAddress() && candidate_region.GetType() == type_id)) {
continue;
}
return candidate_start;
}
}
KVirtualAddress GetRandomAlignedRegion(size_t size, size_t alignment, KInitialPageTable &pt, KMemoryRegionTree &tree, u32 type_id) {
return GetRandomAlignedRegionWithGuard(size, alignment, pt, tree, type_id, 0);
}
void MapStackForCore(KInitialPageTable &page_table, KMemoryRegionType type, u32 core_id) {
constexpr size_t StackSize = PageSize;
constexpr size_t StackAlign = PageSize;
const KVirtualAddress stack_start_virt = GetRandomAlignedRegionWithGuard(StackSize, StackAlign, page_table, KMemoryLayout::GetVirtualMemoryRegionTree(), KMemoryRegionType_KernelMisc, PageSize);
const KPhysicalAddress stack_start_phys = g_initial_page_allocator.Allocate(PageSize);
MESOSPHERE_INIT_ABORT_UNLESS(KMemoryLayout::GetVirtualMemoryRegionTree().Insert(GetInteger(stack_start_virt), StackSize, type, core_id));
page_table.Map(stack_start_virt, StackSize, stack_start_phys, KernelRwDataAttribute, g_initial_page_allocator, 0);
}
class KInitialPageAllocatorForFinalizeIdentityMapping final {
private:
struct FreeListEntry {
FreeListEntry *next;
};
private:
FreeListEntry *m_free_list_head;
u64 m_phys_to_virt_offset;
public:
template<kern::arch::arm64::init::IsInitialPageAllocator PageAllocator>
KInitialPageAllocatorForFinalizeIdentityMapping(PageAllocator &allocator, u64 phys_to_virt) : m_free_list_head(nullptr), m_phys_to_virt_offset(phys_to_virt) {
/* Allocate and free two pages. */
for (size_t i = 0; i < 2; ++i) {
KPhysicalAddress page = allocator.Allocate(PageSize);
MESOSPHERE_INIT_ABORT_UNLESS(page != Null<KPhysicalAddress>);
/* Free the pages. */
this->Free(page, PageSize);
}
}
public:
KPhysicalAddress Allocate(size_t size) {
/* Check that the size is correct. */
MESOSPHERE_INIT_ABORT_UNLESS(size == PageSize);
/* Check that we have a free page. */
FreeListEntry *head = m_free_list_head;
MESOSPHERE_INIT_ABORT_UNLESS(head != nullptr);
/* Update the free list. */
m_free_list_head = head->next;
/* Return the page. */
return KPhysicalAddress(reinterpret_cast<uintptr_t>(head) - m_phys_to_virt_offset);
}
void Free(KPhysicalAddress phys_addr, size_t size) {
/* Check that the size is correct. */
MESOSPHERE_INIT_ABORT_UNLESS(size == PageSize);
/* Convert to a free list entry. */
FreeListEntry *fl = reinterpret_cast<FreeListEntry *>(GetInteger(phys_addr) + m_phys_to_virt_offset);
/* Insert into free list. */
fl->next = m_free_list_head;
m_free_list_head = fl;
}
};
static_assert(kern::arch::arm64::init::IsInitialPageAllocator<KInitialPageAllocatorForFinalizeIdentityMapping>);
void SetupAllTtbr0Entries(KInitialPageTable &init_pt, KInitialPageAllocator &allocator) {
/* Validate that the ttbr0 array is in rodata. */
const uintptr_t rodata_start = reinterpret_cast<uintptr_t>(__rodata_start);
const uintptr_t rodata_end = reinterpret_cast<uintptr_t>(__rodata_end);
MESOSPHERE_INIT_ABORT_UNLESS(rodata_start < rodata_end);
MESOSPHERE_INIT_ABORT_UNLESS(rodata_start <= reinterpret_cast<uintptr_t>(std::addressof(KPageTable::GetTtbr0Entry(0))));
MESOSPHERE_INIT_ABORT_UNLESS(reinterpret_cast<uintptr_t>(std::addressof(KPageTable::GetTtbr0Entry(KPageTable::NumTtbr0Entries))) < rodata_end);
/* Allocate pages for all ttbr0 entries. */
for (size_t i = 0; i < KPageTable::NumTtbr0Entries; ++i) {
/* Allocate a page. */
KPhysicalAddress page = allocator.Allocate(PageSize);
MESOSPHERE_INIT_ABORT_UNLESS(page != Null<KPhysicalAddress>);
/* Check that the page is allowed to be a ttbr0 entry. */
MESOSPHERE_INIT_ABORT_UNLESS((GetInteger(page) & UINT64_C(0xFFFF000000000001)) == 0);
/* Get the physical address of the ttbr0 entry. */
const auto ttbr0_phys_ptr = init_pt.GetPhysicalAddress(KVirtualAddress(std::addressof(KPageTable::GetTtbr0Entry(i))));
/* Set the entry to the newly allocated page. */
*reinterpret_cast<volatile u64 *>(GetInteger(ttbr0_phys_ptr)) = (static_cast<u64>(i) << 48) | GetInteger(page);
}
}
void FinalizeIdentityMapping(KInitialPageTable &init_pt, KInitialPageAllocator &allocator, u64 phys_to_virt_offset) {
/* Create an allocator for identity mapping finalization. */
KInitialPageAllocatorForFinalizeIdentityMapping finalize_allocator(allocator, phys_to_virt_offset);
/* Get the physical address of crt0. */
const KPhysicalAddress start_phys_addr = init_pt.GetPhysicalAddress(reinterpret_cast<uintptr_t>(::ams::kern::init::IdentityMappedFunctionAreaBegin));
/* Unmap the entire identity mapping. */
init_pt.UnmapTtbr0Entries(phys_to_virt_offset);
/* Re-map only the first page of code. */
const size_t size = util::AlignUp<size_t>(reinterpret_cast<uintptr_t>(::ams::kern::init::IdentityMappedFunctionAreaEnd) - reinterpret_cast<uintptr_t>(::ams::kern::init::IdentityMappedFunctionAreaBegin), PageSize);
init_pt.Map(KVirtualAddress(GetInteger(start_phys_addr)), size, start_phys_addr, KernelTextAttribute, finalize_allocator, phys_to_virt_offset);
}
}
void InitializeCorePhase1(uintptr_t misc_unk_debug_phys_addr, void **initial_state) {
/* Ensure our first argument is page aligned. */
MESOSPHERE_INIT_ABORT_UNLESS(util::IsAligned(misc_unk_debug_phys_addr, PageSize));
/* Decode the initial state. */
const auto initial_page_allocator_state = *static_cast<KInitialPageAllocator::State *>(initial_state[0]);
g_phase2_initial_process_binary_meta = *static_cast<InitialProcessBinaryLayoutWithSize *>(initial_state[1]);
/* Restore the page allocator state setup by kernel loader. */
g_initial_page_allocator.InitializeFromState(std::addressof(initial_page_allocator_state));
/* Ensure that the T1SZ is correct (and what we expect). */
MESOSPHERE_INIT_ABORT_UNLESS((cpu::TranslationControlRegisterAccessor().GetT1Size() / arch::arm64::L1BlockSize) == arch::arm64::MaxPageTableEntries);
/* Create page table object for use during initialization. */
KInitialPageTable init_pt;
/* Initialize the slab allocator counts. */
InitializeSlabResourceCounts();
/* Insert the root region for the virtual memory tree, from which all other regions will derive. */
KMemoryLayout::GetVirtualMemoryRegionTree().InsertDirectly(KernelVirtualAddressSpaceBase, KernelVirtualAddressSpaceBase + KernelVirtualAddressSpaceSize - 1);
/* Insert the root region for the physical memory tree, from which all other regions will derive. */
KMemoryLayout::GetPhysicalMemoryRegionTree().InsertDirectly(KernelPhysicalAddressSpaceBase, KernelPhysicalAddressSpaceBase + KernelPhysicalAddressSpaceSize - 1);
/* Save start and end for ease of use. */
const uintptr_t code_start_virt_addr = reinterpret_cast<uintptr_t>(__bin_start__);
const uintptr_t code_end_virt_addr = reinterpret_cast<uintptr_t>(__bin_end__);
/* Setup the containing kernel region. */
constexpr size_t KernelRegionSize = 1_GB;
constexpr size_t KernelRegionAlign = 1_GB;
const KVirtualAddress kernel_region_start = util::AlignDown(code_start_virt_addr, KernelRegionAlign);
size_t kernel_region_size = KernelRegionSize;
if (!(kernel_region_start + KernelRegionSize - 1 <= KernelVirtualAddressSpaceLast)) {
kernel_region_size = KernelVirtualAddressSpaceEnd - GetInteger(kernel_region_start);
}
MESOSPHERE_INIT_ABORT_UNLESS(KMemoryLayout::GetVirtualMemoryRegionTree().Insert(GetInteger(kernel_region_start), kernel_region_size, KMemoryRegionType_Kernel));
/* Setup the code region. */
constexpr size_t CodeRegionAlign = PageSize;
const KVirtualAddress code_region_start = util::AlignDown(code_start_virt_addr, CodeRegionAlign);
const KVirtualAddress code_region_end = util::AlignUp(code_end_virt_addr, CodeRegionAlign);
const size_t code_region_size = GetInteger(code_region_end) - GetInteger(code_region_start);
MESOSPHERE_INIT_ABORT_UNLESS(KMemoryLayout::GetVirtualMemoryRegionTree().Insert(GetInteger(code_region_start), code_region_size, KMemoryRegionType_KernelCode));
/* Setup board-specific device physical regions. */
SetupDevicePhysicalMemoryRegions();
/* Determine the amount of space needed for the misc region. */
size_t misc_region_needed_size;
{
/* Each core has a one page stack for all three stack types (Main, Idle, Exception). */
misc_region_needed_size = cpu::NumCores * (3 * (PageSize + PageSize));
/* Account for each auto-map device. */
for (const auto ®ion : KMemoryLayout::GetPhysicalMemoryRegionTree()) {
if (region.HasTypeAttribute(KMemoryRegionAttr_ShouldKernelMap)) {
/* Check that the region is valid. */
MESOSPHERE_INIT_ABORT_UNLESS(region.GetEndAddress() != 0);
/* Account for the region. */
const auto aligned_start = util::AlignDown(region.GetAddress(), PageSize);
const auto aligned_end = util::AlignUp(region.GetLastAddress(), PageSize);
const size_t cur_region_size = aligned_end - aligned_start;
misc_region_needed_size += cur_region_size;
/* Account for alignment requirements. */
const size_t min_align = std::min<size_t>(util::GetAlignment(cur_region_size), util::GetAlignment(aligned_start));
misc_region_needed_size += min_align >= KernelAslrAlignment ? KernelAslrAlignment : PageSize;
}
}
/* Account for the unknown debug region. */
misc_region_needed_size += GetMiscUnknownDebugRegionSize();
/* Multiply the needed size by three, to account for the need for guard space. */
misc_region_needed_size *= 3;
}
/* Decide on the actual size for the misc region. */
constexpr size_t MiscRegionAlign = KernelAslrAlignment;
constexpr size_t MiscRegionMinimumSize = 32_MB;
const size_t misc_region_size = util::AlignUp(std::max(misc_region_needed_size, MiscRegionMinimumSize), MiscRegionAlign);
MESOSPHERE_INIT_ABORT_UNLESS(misc_region_size > 0);
/* Setup the misc region. */
const KVirtualAddress misc_region_start = GetRandomAlignedRegion(misc_region_size, MiscRegionAlign, init_pt, KMemoryLayout::GetVirtualMemoryRegionTree(), KMemoryRegionType_Kernel);
MESOSPHERE_INIT_ABORT_UNLESS(KMemoryLayout::GetVirtualMemoryRegionTree().Insert(GetInteger(misc_region_start), misc_region_size, KMemoryRegionType_KernelMisc));
/* Determine if we'll use extra thread resources. */
const bool use_extra_resources = KSystemControl::Init::ShouldIncreaseThreadResourceLimit();
/* Setup the stack region. */
const size_t stack_region_size = use_extra_resources ? 24_MB : 14_MB;
constexpr size_t StackRegionAlign = KernelAslrAlignment;
const KVirtualAddress stack_region_start = GetRandomAlignedRegion(stack_region_size, StackRegionAlign, init_pt, KMemoryLayout::GetVirtualMemoryRegionTree(), KMemoryRegionType_Kernel);
MESOSPHERE_INIT_ABORT_UNLESS(KMemoryLayout::GetVirtualMemoryRegionTree().Insert(GetInteger(stack_region_start), stack_region_size, KMemoryRegionType_KernelStack));
/* Determine the size of the resource region. */
const size_t resource_region_size = KMemoryLayout::GetResourceRegionSizeForInit(use_extra_resources);
/* Determine the size of the slab region. */
const size_t slab_region_size = util::AlignUp(CalculateTotalSlabHeapSize(), PageSize);
MESOSPHERE_INIT_ABORT_UNLESS(slab_region_size <= resource_region_size);
/* Setup the slab region. */
const KPhysicalAddress code_start_phys_addr = g_phase2_initial_process_binary_meta.layout.kern_address;
const KPhysicalAddress code_end_phys_addr = code_start_phys_addr + code_region_size;
const KPhysicalAddress slab_start_phys_addr = code_end_phys_addr;
const KPhysicalAddress slab_end_phys_addr = slab_start_phys_addr + slab_region_size;
constexpr size_t SlabRegionAlign = KernelAslrAlignment;
const size_t slab_region_needed_size = util::AlignUp(GetInteger(code_end_phys_addr) + slab_region_size, SlabRegionAlign) - util::AlignDown(GetInteger(code_end_phys_addr), SlabRegionAlign);
const KVirtualAddress slab_region_start = GetRandomAlignedRegion(slab_region_needed_size, SlabRegionAlign, init_pt, KMemoryLayout::GetVirtualMemoryRegionTree(), KMemoryRegionType_Kernel) + (GetInteger(code_end_phys_addr) % SlabRegionAlign);
MESOSPHERE_INIT_ABORT_UNLESS(KMemoryLayout::GetVirtualMemoryRegionTree().Insert(GetInteger(slab_region_start), slab_region_size, KMemoryRegionType_KernelSlab));
/* Setup the temp region. */
constexpr size_t TempRegionSize = 128_MB;
constexpr size_t TempRegionAlign = KernelAslrAlignment;
const KVirtualAddress temp_region_start = GetRandomAlignedRegion(TempRegionSize, TempRegionAlign, init_pt, KMemoryLayout::GetVirtualMemoryRegionTree(), KMemoryRegionType_Kernel);
MESOSPHERE_INIT_ABORT_UNLESS(KMemoryLayout::GetVirtualMemoryRegionTree().Insert(GetInteger(temp_region_start), TempRegionSize, KMemoryRegionType_KernelTemp));
/* Automatically map in devices that have auto-map attributes, from largest region to smallest region. */
{
/* We want to map the regions from largest to smallest. */
KMemoryRegion *largest;
do {
/* Begin with no knowledge of the largest region. */
largest = nullptr;
for (auto ®ion : KMemoryLayout::GetPhysicalMemoryRegionTree()) {
/* We only care about kernel regions. */
if (!region.IsDerivedFrom(KMemoryRegionType_Kernel)) {
continue;
}
/* Check whether we should map the region. */
if (!region.HasTypeAttribute(KMemoryRegionAttr_ShouldKernelMap)) {
continue;
}
/* If this region has already been mapped, no need to consider it. */
if (region.HasTypeAttribute(KMemoryRegionAttr_DidKernelMap)) {
continue;
}
/* Check that the region is valid. */
MESOSPHERE_INIT_ABORT_UNLESS(region.GetEndAddress() != 0);
/* Update the largest region. */
if (largest == nullptr || largest->GetSize() < region.GetSize()) {
largest = std::addressof(region);
}
}
/* If we found a region, map it. */
if (largest != nullptr) {
/* Set the attribute to note we've mapped this region. */
largest->SetTypeAttribute(KMemoryRegionAttr_DidKernelMap);
/* Create a virtual pair region and insert it into the tree. */
const KPhysicalAddress map_phys_addr = util::AlignDown(largest->GetAddress(), PageSize);
const size_t map_size = util::AlignUp(largest->GetEndAddress(), PageSize) - GetInteger(map_phys_addr);
const size_t min_align = std::min<size_t>(util::GetAlignment(map_size), util::GetAlignment(GetInteger(map_phys_addr)));
const size_t map_align = min_align >= KernelAslrAlignment ? KernelAslrAlignment : PageSize;
const KVirtualAddress map_virt_addr = GetRandomAlignedRegionWithGuard(map_size, map_align, init_pt, KMemoryLayout::GetVirtualMemoryRegionTree(), KMemoryRegionType_KernelMisc, PageSize);
MESOSPHERE_INIT_ABORT_UNLESS(KMemoryLayout::GetVirtualMemoryRegionTree().Insert(GetInteger(map_virt_addr), map_size, KMemoryRegionType_KernelMiscMappedDevice));
largest->SetPairAddress(GetInteger(map_virt_addr) + largest->GetAddress() - GetInteger(map_phys_addr));
/* Map the page in to our page table. */
init_pt.Map(map_virt_addr, map_size, map_phys_addr, KernelMmioAttribute, g_initial_page_allocator, 0);
}
} while (largest != nullptr);
}
/* Setup the basic DRAM regions. */
SetupDramPhysicalMemoryRegions();
/* Automatically map in reserved physical memory that has auto-map attributes. */
{
/* We want to map the regions from largest to smallest. */
KMemoryRegion *largest;
do {
/* Begin with no knowledge of the largest region. */
largest = nullptr;
for (auto ®ion : KMemoryLayout::GetPhysicalMemoryRegionTree()) {
/* We only care about reserved memory. */
if (!region.IsDerivedFrom(KMemoryRegionType_DramReservedBase)) {
continue;
}
/* Check whether we should map the region. */
if (!region.HasTypeAttribute(KMemoryRegionAttr_ShouldKernelMap)) {
continue;
}
/* If this region has already been mapped, no need to consider it. */
if (region.HasTypeAttribute(KMemoryRegionAttr_DidKernelMap)) {
continue;
}
/* Check that the region is valid. */
MESOSPHERE_INIT_ABORT_UNLESS(region.GetEndAddress() != 0);
/* Update the largest region. */
if (largest == nullptr || largest->GetSize() < region.GetSize()) {
largest = std::addressof(region);
}
}
/* If we found a region, map it. */
if (largest != nullptr) {
/* Set the attribute to note we've mapped this region. */
largest->SetTypeAttribute(KMemoryRegionAttr_DidKernelMap);
/* Create a virtual pair region and insert it into the tree. */
const KPhysicalAddress map_phys_addr = util::AlignDown(largest->GetAddress(), PageSize);
const size_t map_size = util::AlignUp(largest->GetEndAddress(), PageSize) - GetInteger(map_phys_addr);
const size_t min_align = std::min<size_t>(util::GetAlignment(map_size), util::GetAlignment(GetInteger(map_phys_addr)));
const size_t map_align = min_align >= KernelAslrAlignment ? KernelAslrAlignment : PageSize;
const KVirtualAddress map_virt_addr = GetRandomAlignedRegionWithGuard(map_size, map_align, init_pt, KMemoryLayout::GetVirtualMemoryRegionTree(), KMemoryRegionType_KernelMisc, PageSize);
MESOSPHERE_INIT_ABORT_UNLESS(KMemoryLayout::GetVirtualMemoryRegionTree().Insert(GetInteger(map_virt_addr), map_size, KMemoryRegionType_KernelMiscUnknownDebug));
largest->SetPairAddress(GetInteger(map_virt_addr) + largest->GetAddress() - GetInteger(map_phys_addr));
/* Map the page in to our page table. */
const auto attribute = largest->HasTypeAttribute(KMemoryRegionAttr_Uncached) ? KernelRwDataUncachedAttribute : KernelRwDataAttribute;
init_pt.Map(map_virt_addr, map_size, map_phys_addr, attribute, g_initial_page_allocator, 0);
}
} while (largest != nullptr);
}
/* Insert a physical region for the kernel code region. */
MESOSPHERE_INIT_ABORT_UNLESS(KMemoryLayout::GetPhysicalMemoryRegionTree().Insert(GetInteger(code_start_phys_addr), code_region_size, KMemoryRegionType_DramKernelCode));
/* Insert a physical region for the kernel slab region. */
MESOSPHERE_INIT_ABORT_UNLESS(KMemoryLayout::GetPhysicalMemoryRegionTree().Insert(GetInteger(slab_start_phys_addr), slab_region_size, KMemoryRegionType_DramKernelSlab));
/* Map the slab region. */
init_pt.Map(slab_region_start, slab_region_size, slab_start_phys_addr, KernelRwDataAttribute, g_initial_page_allocator, 0);
/* Physically randomize the slab region. */
/* NOTE: Nintendo does this only on 10.0.0+ */
init_pt.PhysicallyRandomize(slab_region_start, slab_region_size, false);
/* Insert a physical region for the secure applet memory. */
const auto secure_applet_end_phys_addr = slab_end_phys_addr + KSystemControl::SecureAppletMemorySize;
if constexpr (KSystemControl::SecureAppletMemorySize > 0) {
MESOSPHERE_INIT_ABORT_UNLESS(KMemoryLayout::GetPhysicalMemoryRegionTree().Insert(GetInteger(slab_end_phys_addr), KSystemControl::SecureAppletMemorySize, KMemoryRegionType_DramKernelSecureAppletMemory));
}
/* Insert a physical region for the unknown debug2 region. */
const size_t secure_unknown_size = GetSecureUnknownRegionSize();
const auto secure_unknown_end_phys_addr = secure_applet_end_phys_addr + secure_unknown_size;
if (secure_unknown_size > 0) {
MESOSPHERE_INIT_ABORT_UNLESS(KMemoryLayout::GetPhysicalMemoryRegionTree().Insert(GetInteger(secure_applet_end_phys_addr), secure_unknown_size, KMemoryRegionType_DramKernelSecureUnknown));
}
/* Determine size available for kernel page table heaps. */
const KPhysicalAddress resource_end_phys_addr = slab_start_phys_addr + resource_region_size;
g_phase2_resource_end_phys_addr = resource_end_phys_addr;
const size_t page_table_heap_size = GetInteger(resource_end_phys_addr) - GetInteger(secure_unknown_end_phys_addr);
/* Insert a physical region for the kernel page table heap region */
MESOSPHERE_INIT_ABORT_UNLESS(KMemoryLayout::GetPhysicalMemoryRegionTree().Insert(GetInteger(secure_unknown_end_phys_addr), page_table_heap_size, KMemoryRegionType_DramKernelPtHeap));
/* All DRAM regions that we haven't tagged by this point will be mapped under the linear mapping. Tag them. */
for (auto ®ion : KMemoryLayout::GetPhysicalMemoryRegionTree()) {
if (region.GetType() == KMemoryRegionType_Dram) {
/* Check that the region is valid. */
MESOSPHERE_INIT_ABORT_UNLESS(region.GetEndAddress() != 0);
/* Set the linear map attribute. */
region.SetTypeAttribute(KMemoryRegionAttr_LinearMapped);
}
}
/* Get the linear region extents. */
const auto linear_extents = KMemoryLayout::GetPhysicalMemoryRegionTree().GetDerivedRegionExtents(KMemoryRegionAttr_LinearMapped);
MESOSPHERE_INIT_ABORT_UNLESS(linear_extents.GetEndAddress() != 0);
/* Setup the linear mapping region. */
constexpr size_t LinearRegionAlign = 1_GB;
const KPhysicalAddress aligned_linear_phys_start = util::AlignDown(linear_extents.GetAddress(), LinearRegionAlign);
const size_t linear_region_size = util::AlignUp(linear_extents.GetEndAddress(), LinearRegionAlign) - GetInteger(aligned_linear_phys_start);
const KVirtualAddress linear_region_start = GetRandomAlignedRegionWithGuard(linear_region_size, LinearRegionAlign, init_pt, KMemoryLayout::GetVirtualMemoryRegionTree(), KMemoryRegionType_None, LinearRegionAlign);
const uintptr_t linear_region_phys_to_virt_diff = GetInteger(linear_region_start) - GetInteger(aligned_linear_phys_start);
/* Map and create regions for all the linearly-mapped data. */
{
uintptr_t cur_phys_addr = 0;
uintptr_t cur_size = 0;
for (auto ®ion : KMemoryLayout::GetPhysicalMemoryRegionTree()) {
if (!region.HasTypeAttribute(KMemoryRegionAttr_LinearMapped)) {
continue;
}
MESOSPHERE_INIT_ABORT_UNLESS(region.GetEndAddress() != 0);
if (cur_size == 0) {
cur_phys_addr = region.GetAddress();
cur_size = region.GetSize();
} else if (cur_phys_addr + cur_size == region.GetAddress()) {
cur_size += region.GetSize();
} else {
const uintptr_t cur_virt_addr = cur_phys_addr + linear_region_phys_to_virt_diff;
init_pt.Map(cur_virt_addr, cur_size, cur_phys_addr, KernelRwDataAttribute, g_initial_page_allocator, 0);
cur_phys_addr = region.GetAddress();
cur_size = region.GetSize();
}
const uintptr_t region_virt_addr = region.GetAddress() + linear_region_phys_to_virt_diff;
if (!region.HasTypeAttribute(KMemoryRegionAttr_ShouldKernelMap)) {
region.SetPairAddress(region_virt_addr);
}
MESOSPHERE_INIT_ABORT_UNLESS(KMemoryLayout::GetVirtualMemoryRegionTree().Insert(region_virt_addr, region.GetSize(), GetTypeForVirtualLinearMapping(region.GetType())));
KMemoryRegion *virt_region = KMemoryLayout::GetVirtualMemoryRegionTree().FindModifiable(region_virt_addr);
MESOSPHERE_INIT_ABORT_UNLESS(virt_region != nullptr);
virt_region->SetPairAddress(region.GetAddress());
}
/* Map the last block, which we may have skipped. */
if (cur_size != 0) {
const uintptr_t cur_virt_addr = cur_phys_addr + linear_region_phys_to_virt_diff;
init_pt.Map(cur_virt_addr, cur_size, cur_phys_addr, KernelRwDataAttribute, g_initial_page_allocator, 0);
}
}
/* NOTE: Unknown function is called here which is ifdef'd out on retail kernel. */
/* The unknown function is immediately before the function which gets an unknown debug region size, inside this translation unit. */
/* It's likely that this is some kind of initializer for this unknown debug region. */
/* Create regions for and map all core-specific stacks. */
for (size_t i = 0; i < cpu::NumCores; i++) {
MapStackForCore(init_pt, KMemoryRegionType_KernelMiscMainStack, i);
MapStackForCore(init_pt, KMemoryRegionType_KernelMiscIdleStack, i);
MapStackForCore(init_pt, KMemoryRegionType_KernelMiscExceptionStack, i);
}
/* Setup the initial arguments. */
SetupInitialArguments();
/* Set linear difference for Phase2. */
g_phase2_linear_region_phys_to_virt_diff = linear_region_phys_to_virt_diff;
}
void InitializeCorePhase2() {
/* Create page table object for use during remaining initialization. */
KInitialPageTable init_pt;
/* Setup all ttbr0 pages. */
SetupAllTtbr0Entries(init_pt, g_initial_page_allocator);
/* Unmap the identity mapping. */
FinalizeIdentityMapping(init_pt, g_initial_page_allocator, g_phase2_linear_region_phys_to_virt_diff);
/* Finalize the page allocator, we're done allocating at this point. */
KInitialPageAllocator::State final_init_page_table_state;
g_initial_page_allocator.GetFinalState(std::addressof(final_init_page_table_state));
const KPhysicalAddress final_init_page_table_end_address = final_init_page_table_state.end_address;
const size_t init_page_table_region_size = GetInteger(final_init_page_table_end_address) - GetInteger(g_phase2_resource_end_phys_addr);
/* Insert regions for the initial page table region. */
MESOSPHERE_INIT_ABORT_UNLESS(KMemoryLayout::GetPhysicalMemoryRegionTree().Insert(GetInteger(g_phase2_resource_end_phys_addr), init_page_table_region_size, KMemoryRegionType_DramKernelInitPt));
MESOSPHERE_INIT_ABORT_UNLESS(KMemoryLayout::GetVirtualMemoryRegionTree().Insert(GetInteger(g_phase2_resource_end_phys_addr) + g_phase2_linear_region_phys_to_virt_diff, init_page_table_region_size, KMemoryRegionType_VirtualDramKernelInitPt));
/* Insert a physical region for the kernel trace buffer */
if constexpr (IsKTraceEnabled) {
const KPhysicalAddress ktrace_buffer_phys_addr = GetInteger(g_phase2_resource_end_phys_addr) + init_page_table_region_size;
MESOSPHERE_INIT_ABORT_UNLESS(KMemoryLayout::GetPhysicalMemoryRegionTree().Insert(GetInteger(ktrace_buffer_phys_addr), KTraceBufferSize, KMemoryRegionType_KernelTraceBuffer));
MESOSPHERE_INIT_ABORT_UNLESS(KMemoryLayout::GetPhysicalMemoryRegionTree().Insert(GetInteger(ktrace_buffer_phys_addr) + g_phase2_linear_region_phys_to_virt_diff, KTraceBufferSize, GetTypeForVirtualLinearMapping(KMemoryRegionType_KernelTraceBuffer)));
}
/* All linear-mapped DRAM regions that we haven't tagged by this point will be allocated to some pool partition. Tag them. */
for (auto ®ion : KMemoryLayout::GetPhysicalMemoryRegionTree()) {
constexpr auto UntaggedLinearDram = util::FromUnderlying<KMemoryRegionType>(util::ToUnderlying<KMemoryRegionType>(KMemoryRegionType_Dram) | util::ToUnderlying(KMemoryRegionAttr_LinearMapped));
if (region.GetType() == UntaggedLinearDram) {
region.SetType(KMemoryRegionType_DramPoolPartition);
}
}
/* Set the linear memory offsets, to enable conversion between physical and virtual addresses. */
KMemoryLayout::InitializeLinearMemoryAddresses(g_phase2_linear_region_phys_to_virt_diff);
/* Set the initial process binary physical address. */
/* NOTE: Nintendo does this after pool partition setup, but it's a requirement that we do it before */
/* to retain compatibility with < 5.0.0. */
const KPhysicalAddress ini_address = g_phase2_initial_process_binary_meta.layout.address;
const size_t ini_size = g_phase2_initial_process_binary_meta.size;
MESOSPHERE_INIT_ABORT_UNLESS(ini_address != Null<KPhysicalAddress>);
SetInitialProcessBinaryPhysicalAddress(ini_address, ini_size);
/* Setup all other memory regions needed to arrange the pool partitions. */
SetupPoolPartitionMemoryRegions();
/* Validate the initial process binary address. */
{
const KMemoryRegion *ini_region = KMemoryLayout::Find(ini_address);
/* Check that the region is non-kernel dram. */
MESOSPHERE_INIT_ABORT_UNLESS(ini_region->IsDerivedFrom(KMemoryRegionType_DramUserPool));
/* Check that the region contains the ini. */
MESOSPHERE_INIT_ABORT_UNLESS(ini_region->GetAddress() <= GetInteger(ini_address));
MESOSPHERE_INIT_ABORT_UNLESS(GetInteger(ini_address) + ini_size <= ini_region->GetEndAddress());
MESOSPHERE_INIT_ABORT_UNLESS(ini_region->GetEndAddress() != 0);
}
/* Cache all linear regions in their own trees for faster access, later. */
KMemoryLayout::InitializeLinearMemoryRegionTrees();
/* Turn on all other cores. */
TurnOnAllCores();
}
KInitArguments *GetInitArguments(s32 core_id) {
return g_init_arguments + core_id;
}
void InitializeDebugRegisters() {
/* Determine how many watchpoints and breakpoints we have */
cpu::DebugFeatureRegisterAccessor aa64dfr0;
const auto num_watchpoints = aa64dfr0.GetNumWatchpoints();
const auto num_breakpoints = aa64dfr0.GetNumBreakpoints();
cpu::EnsureInstructionConsistencyFullSystem();
/* Clear the debug monitor register and the os lock access register. */
cpu::MonitorDebugSystemControlRegisterAccessor(0).Store();
cpu::EnsureInstructionConsistencyFullSystem();
cpu::OsLockAccessRegisterAccessor(0).Store();
cpu::EnsureInstructionConsistencyFullSystem();
/* Clear all debug watchpoints/breakpoints. */
#define FOR_I_IN_15_TO_1(HANDLER, ...) \
HANDLER(15, ## __VA_ARGS__) HANDLER(14, ## __VA_ARGS__) HANDLER(13, ## __VA_ARGS__) HANDLER(12, ## __VA_ARGS__) \
HANDLER(11, ## __VA_ARGS__) HANDLER(10, ## __VA_ARGS__) HANDLER(9, ## __VA_ARGS__) HANDLER(8, ## __VA_ARGS__) \
HANDLER(7, ## __VA_ARGS__) HANDLER(6, ## __VA_ARGS__) HANDLER(5, ## __VA_ARGS__) HANDLER(4, ## __VA_ARGS__) \
HANDLER(3, ## __VA_ARGS__) HANDLER(2, ## __VA_ARGS__) HANDLER(1, ## __VA_ARGS__)
#define MESOSPHERE_INITIALIZE_WATCHPOINT_CASE(ID, ...) \
case ID: \
cpu::SetDbgWcr##ID##El1(__VA_ARGS__); \
cpu::SetDbgWvr##ID##El1(__VA_ARGS__); \
[[fallthrough]];
#define MESOSPHERE_INITIALIZE_BREAKPOINT_CASE(ID, ...) \
case ID: \
cpu::SetDbgBcr##ID##El1(__VA_ARGS__); \
cpu::SetDbgBvr##ID##El1(__VA_ARGS__); \
[[fallthrough]];
switch (num_watchpoints) {
FOR_I_IN_15_TO_1(MESOSPHERE_INITIALIZE_WATCHPOINT_CASE, 0)
case 0:
cpu::SetDbgWcr0El1(0);
cpu::SetDbgWvr0El1(0);
[[fallthrough]];
default:
break;
}
switch (num_breakpoints) {
FOR_I_IN_15_TO_1(MESOSPHERE_INITIALIZE_BREAKPOINT_CASE, 0)
default:
break;
}
cpu::SetDbgBcr0El1(0);
cpu::SetDbgBvr0El1(0);
#undef MESOSPHERE_INITIALIZE_WATCHPOINT_CASE
#undef MESOSPHERE_INITIALIZE_BREAKPOINT_CASE
#undef FOR_I_IN_15_TO_1
cpu::EnsureInstructionConsistencyFullSystem();
/* Initialize the context id register to all 1s. */
cpu::ContextIdRegisterAccessor(0).SetProcId(std::numeric_limits<u32>::max()).Store();
cpu::EnsureInstructionConsistencyFullSystem();
/* Configure the debug monitor register. */
cpu::MonitorDebugSystemControlRegisterAccessor(0).SetMde(true).SetTdcc(true).Store();
cpu::EnsureInstructionConsistencyFullSystem();
}
void InitializeExceptionVectors() {
cpu::SetVbarEl1(reinterpret_cast<uintptr_t>(::ams::kern::ExceptionVectors));
cpu::SetTpidrEl1(0);
cpu::SetExceptionThreadStackTop(0);
cpu::EnsureInstructionConsistencyFullSystem();
}
size_t GetMiscUnknownDebugRegionSize() {
return 0;
}
size_t GetSecureUnknownRegionSize() {
return 0;
}
}
| 43,346
|
C++
|
.cpp
| 612
| 57.79902
| 266
| 0.650734
|
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,283
|
test.cpp
|
Atmosphere-NX_Atmosphere/tests/TestStack/source/test.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams {
void Main() {
printf("Getting thread stack\n");
{
uintptr_t stack = 0;
size_t stack_size = 0;
os::GetCurrentStackInfo(std::addressof(stack), std::addressof(stack_size));
printf("Got thread stack: %p-%p\n", reinterpret_cast<void *>(stack), reinterpret_cast<void *>(stack + stack_size));
const uintptr_t stack_var_addr = reinterpret_cast<uintptr_t>(std::addressof(stack));
printf("&stack variable address: %p\n", reinterpret_cast<void *>(stack_var_addr));
AMS_ASSERT(stack <= stack_var_addr && stack_var_addr < stack + stack_size);
}
printf("All tests completed!\n");
}
}
| 1,377
|
C++
|
.cpp
| 31
| 38.83871
| 127
| 0.673621
|
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,284
|
test.cpp
|
Atmosphere-NX_Atmosphere/tests/TestFs/source/test.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams {
namespace fssrv::impl {
const char *GetExecutionDirectoryPath();
}
namespace {
void GetPath(char *dst, size_t dst_size, const char *src) {
if (fs::IsPathAbsolute(src)) {
util::SNPrintf(dst, dst_size, "%s", src);
} else {
util::SNPrintf(dst, dst_size, "%s%s", fssrv::impl::GetExecutionDirectoryPath(), src);
}
}
#define TEST_R_EXPECT(__EXPR__, __EXPECTED__) \
({ \
const Result __test_result = (__EXPR__); \
if (!(__EXPECTED__ ::Includes(__test_result))) { \
printf("Unexpected result: %s gave 0x%08x (2%03d-%04d)\n", # __EXPR__, __test_result.GetValue(), __test_result.GetModule(), __test_result.GetDescription()); \
return; \
} \
__test_result; \
})
#define TEST_R_TRY(__EXPR__) \
({ \
const Result __test_result = (__EXPR__); \
if (R_FAILED(__test_result)) { \
printf("Unexpected result: %s gave 0x%08x (2%03d-%04d)\n", # __EXPR__, __test_result.GetValue(), __test_result.GetModule(), __test_result.GetDescription()); \
return; \
} \
__test_result; \
})
u8 g_buffer[64_KB];
void DoFsTests() {
/* Declare buffer to hold any work paths we have. */
char path_buf[fs::EntryNameLengthMax + 1];
char path_buf2[fs::EntryNameLengthMax + 1];
#define FORMAT_PATH(S) ({ GetPath(path_buf, sizeof(path_buf), S); path_buf; })
#define FORMAT_PATH2(S) ({ GetPath(path_buf2, sizeof(path_buf2), S); path_buf2; })
AMS_UNUSED(path_buf);
AMS_UNUSED(path_buf2);
/* Clear anything from a previous test run, no obligation for this to succeed. */
fs::DeleteDirectoryRecursively(FORMAT_PATH("./test_dir/"));
/* Verify that the test directory does not exist. */
fs::DirectoryEntryType entry_type;
TEST_R_EXPECT(fs::GetEntryType(std::addressof(entry_type), FORMAT_PATH("./test_dir/")), fs::ResultPathNotFound);
/* Create the subdirectory. */
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/")));
/* Verify the test directory exists and is a directory. */
TEST_R_TRY(fs::GetEntryType(std::addressof(entry_type), FORMAT_PATH("./test_dir/")));
AMS_ABORT_UNLESS(entry_type == fs::DirectoryEntryType_Directory);
/* ==================================================================================================================== */
/* Create File */
/* ==================================================================================================================== */
/* Create a file. */
TEST_R_EXPECT(fs::GetEntryType(std::addressof(entry_type), FORMAT_PATH("./test_dir/test_rand.bin")), fs::ResultPathNotFound);
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/test_rand.bin"), sizeof(g_buffer)));
/* Check the file has correct entry type. */
TEST_R_TRY(fs::GetEntryType(std::addressof(entry_type), FORMAT_PATH("./test_dir/test_rand.bin")));
AMS_ABORT_UNLESS(entry_type == fs::DirectoryEntryType_File);
/* Create already existing file -> fs::ResultPathAlreadyExists(). */
TEST_R_EXPECT(fs::CreateFile(FORMAT_PATH("./test_dir/test_rand.bin"), sizeof(g_buffer)), fs::ResultPathAlreadyExists);
/* Create already existing dir -> fs::ResultPathAlreadyExists(). */
TEST_R_EXPECT(fs::CreateFile(FORMAT_PATH("./test_dir/"), sizeof(g_buffer)), fs::ResultPathAlreadyExists);
/* Create file without parent existing -> fs::ResultPathNotFound(). */
TEST_R_EXPECT(fs::CreateFile(FORMAT_PATH("./test_dir/aaa/bbb.bin"), sizeof(g_buffer)), fs::ResultPathNotFound);
/* ==================================================================================================================== */
/* Create Directory */
/* ==================================================================================================================== */
/* Create the subdirectory. */
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/test_subdir/")));
/* Verify the test directory exists and is a directory. */
TEST_R_TRY(fs::GetEntryType(std::addressof(entry_type), FORMAT_PATH("./test_dir/test_subdir/")));
AMS_ABORT_UNLESS(entry_type == fs::DirectoryEntryType_Directory);
/* Create already existing file -> fs::ResultPathAlreadyExists(). */
TEST_R_EXPECT(fs::CreateDirectory(FORMAT_PATH("./test_dir/test_rand.bin")), fs::ResultPathAlreadyExists);
/* Create already existing dir -> fs::ResultPathAlreadyExists(). */
TEST_R_EXPECT(fs::CreateDirectory(FORMAT_PATH("./test_dir/")), fs::ResultPathAlreadyExists);
/* Create dir without parent existing -> fs::ResultPathAlreadyExists(). */
TEST_R_EXPECT(fs::CreateDirectory(FORMAT_PATH("./test_dir/aaa/bbb/")), fs::ResultPathNotFound);
/* ==================================================================================================================== */
/* Delete File */
/* ==================================================================================================================== */
/* Delete file succeeds. */
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/tmp_for_delete.bin"), sizeof(g_buffer)));
TEST_R_TRY(fs::DeleteFile(FORMAT_PATH("./test_dir/tmp_for_delete.bin")));
/* Delete on invalid path -> fs::ResultPathNotFound(). */
TEST_R_EXPECT(fs::DeleteFile(FORMAT_PATH("./test_dir/invalid")), fs::ResultPathNotFound);
/* Delete on directory -> fs::ResultPathNotFound(). */
TEST_R_EXPECT(fs::DeleteFile(FORMAT_PATH("./test_dir/test_subdir/")), fs::ResultPathNotFound);
/* ==================================================================================================================== */
/* Delete Directory */
/* ==================================================================================================================== */
/* Delete dir succeeds. */
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/tmp_for_delete/")));
TEST_R_TRY(fs::DeleteDirectory(FORMAT_PATH("./test_dir/tmp_for_delete/")));
/* Delete on invalid path -> fs::ResultPathNotFound(). */
TEST_R_EXPECT(fs::DeleteDirectory(FORMAT_PATH("./test_dir/invalid/")), fs::ResultPathNotFound);
/* Delete on file -> fs::ResultPathNotFound(). */
TEST_R_EXPECT(fs::DeleteDirectory(FORMAT_PATH("./test_dir/test_rand.bin")), fs::ResultPathNotFound);
/* Delete on non-empty directory -> fs::ResultDirectoryNotEmpty(). */
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/tmp_for_delete/")));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/tmp_for_delete/tmp_for_delete.bin"), sizeof(g_buffer)));
TEST_R_EXPECT(fs::DeleteDirectory(FORMAT_PATH("./test_dir/tmp_for_delete/")), fs::ResultDirectoryNotEmpty);
TEST_R_TRY(fs::DeleteFile(FORMAT_PATH("./test_dir/tmp_for_delete/tmp_for_delete.bin")));
TEST_R_TRY(fs::DeleteDirectory(FORMAT_PATH("./test_dir/tmp_for_delete/")));
/* ==================================================================================================================== */
/* Delete Directory Recursively */
/* ==================================================================================================================== */
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/0/")));
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/0/0/")));
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/0/0/0/")));
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/0/0/0/0/")));
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/0/0/0/0/0/")));
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/0/0/0/0/0/0/")));
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/")));
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/")));
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/")));
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/0/")));
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/1/")));
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/1/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/")));
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/1/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/000/")));
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/1/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/000/b/")));
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/1/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/000/b/0/")));
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/1/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/000/b/0/0/")));
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/1/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/000/b/0/0/0/")));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/0/x.bin"), 0));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/0/0/x.bin"), 0));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/0/0/0/x.bin"), 0));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/0/0/0/0/x.bin"), 0));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/0/0/0/0/0/x.bin"), 0));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/0/0/0/0/0/0/x.bin"), 0));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/x.bin"), 0));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/x.bin"), 0));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/x.bin"), 0));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/0/x.bin"), 0));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/0/y.bin"), 0));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/0/z.bin"), 0));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/1/x.bin"), 0));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/1/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/x.bin"), 0));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/1/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/000/x.bin"), 0));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/1/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/000/b/x.bin"), 0));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/1/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/000/b/0/x.bin"), 0));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/1/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/000/b/0/0/x.bin"), 0));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/1/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/000/b/0/0/0/x.bin"), 0));
TEST_R_TRY(fs::DeleteDirectoryRecursively(FORMAT_PATH("./test_dir/0/")));
/* Verify the test directory still exists and is a directory. */
TEST_R_TRY(fs::GetEntryType(std::addressof(entry_type), FORMAT_PATH("./test_dir/")));
AMS_ABORT_UNLESS(entry_type == fs::DirectoryEntryType_Directory);
/* Verify the recursive directory doesn't. */
TEST_R_EXPECT(fs::GetEntryType(std::addressof(entry_type), FORMAT_PATH("./test_dir/0/")), fs::ResultPathNotFound);
/* Delete recursive on invalid path -> fs::ResultPathNotFound(). */
TEST_R_EXPECT(fs::DeleteDirectoryRecursively(FORMAT_PATH("./test_dir/invalid/")), fs::ResultPathNotFound);
/* Delete recursive on file -> fs::ResultPathNotFound(). */
TEST_R_EXPECT(fs::DeleteDirectoryRecursively(FORMAT_PATH("./test_dir/test_rand.bin")), fs::ResultPathNotFound);
/* ==================================================================================================================== */
/* Clean Directory Recursively */
/* ==================================================================================================================== */
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/0/")));
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/0/0/")));
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/0/0/0/")));
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/0/0/0/0/")));
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/0/0/0/0/0/")));
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/0/0/0/0/0/0/")));
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/")));
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/")));
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/")));
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/0/")));
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/1/")));
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/1/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/")));
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/1/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/000/")));
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/1/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/000/b/")));
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/1/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/000/b/0/")));
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/1/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/000/b/0/0/")));
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/1/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/000/b/0/0/0/")));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/0/x.bin"), 0));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/0/0/x.bin"), 0));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/0/0/0/x.bin"), 0));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/0/0/0/0/x.bin"), 0));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/0/0/0/0/0/x.bin"), 0));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/0/0/0/0/0/0/x.bin"), 0));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/x.bin"), 0));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/x.bin"), 0));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/x.bin"), 0));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/0/x.bin"), 0));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/0/y.bin"), 0));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/0/z.bin"), 0));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/1/x.bin"), 0));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/1/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/x.bin"), 0));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/1/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/000/x.bin"), 0));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/1/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/000/b/x.bin"), 0));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/1/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/000/b/0/x.bin"), 0));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/1/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/000/b/0/0/x.bin"), 0));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/0/0/0/0/0/0/0/0/0/1/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/000/b/0/0/0/x.bin"), 0));
TEST_R_TRY(fs::CleanDirectoryRecursively(FORMAT_PATH("./test_dir/0/")));
/* Verify the recursive directory still exists and is a directory. */
TEST_R_TRY(fs::GetEntryType(std::addressof(entry_type), FORMAT_PATH("./test_dir/0/")));
AMS_ABORT_UNLESS(entry_type == fs::DirectoryEntryType_Directory);
/* Delete the recursive directory. */
TEST_R_TRY(fs::DeleteDirectory(FORMAT_PATH("./test_dir/0/")));
/* Clean recursive on invalid path -> fs::ResultPathNotFound(). */
TEST_R_EXPECT(fs::CleanDirectoryRecursively(FORMAT_PATH("./test_dir/invalid/")), fs::ResultPathNotFound);
/* Clean recursive on file -> fs::ResultPathNotFound(). */
TEST_R_EXPECT(fs::CleanDirectoryRecursively(FORMAT_PATH("./test_dir/test_rand.bin")), fs::ResultPathNotFound);
/* ==================================================================================================================== */
/* Rename File */
/* ==================================================================================================================== */
/* Rename succeeds. */
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/a.bin"), 1_KB));
TEST_R_TRY(fs::RenameFile(FORMAT_PATH("./test_dir/a.bin"), FORMAT_PATH2("./test_dir/b.bin")));
TEST_R_EXPECT(fs::GetEntryType(std::addressof(entry_type), FORMAT_PATH("./test_dir/a.bin")), fs::ResultPathNotFound);
TEST_R_TRY(fs::GetEntryType(std::addressof(entry_type), FORMAT_PATH("./test_dir/b.bin")));
AMS_ABORT_UNLESS(entry_type == fs::DirectoryEntryType_File);
/* Rename non-existing -> fs::ResultPathNotFound */
TEST_R_EXPECT(fs::RenameFile(FORMAT_PATH("./test_dir/invalid"), FORMAT_PATH2("./test_dir/invalid2")), fs::ResultPathNotFound);
/* Rename valid -> already existing gives fs::ResultPathAlreadyExists */
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/a.bin"), 1_KB));
TEST_R_EXPECT(fs::RenameFile(FORMAT_PATH("./test_dir/a.bin"), FORMAT_PATH2("./test_dir/b.bin")), fs::ResultPathAlreadyExists);
/* Rename valid -> directory gives fs::ResultPathAlreadyExists */
TEST_R_EXPECT(fs::RenameFile(FORMAT_PATH("./test_dir/a.bin"), FORMAT_PATH2("./test_dir/test_subdir/")), fs::ResultPathAlreadyExists);
/* Rename directory -> fs::ResultPathNotFound */
TEST_R_EXPECT(fs::RenameFile(FORMAT_PATH("./test_dir/test_subdir/"), FORMAT_PATH2("./test_dir/c.bin")), fs::ResultPathNotFound);
/* Invalid doesn't affect the file/dir. */
TEST_R_TRY(fs::GetEntryType(std::addressof(entry_type), FORMAT_PATH("./test_dir/a.bin")));
AMS_ABORT_UNLESS(entry_type == fs::DirectoryEntryType_File);
TEST_R_TRY(fs::GetEntryType(std::addressof(entry_type), FORMAT_PATH("./test_dir/test_subdir/")));
AMS_ABORT_UNLESS(entry_type == fs::DirectoryEntryType_Directory);
/* ==================================================================================================================== */
/* Rename Directory */
/* ==================================================================================================================== */
/* Rename succeeds. */
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/dir_a/")));
TEST_R_TRY(fs::RenameDirectory(FORMAT_PATH("./test_dir/dir_a/"), FORMAT_PATH2("./test_dir/dir_b/")));
TEST_R_EXPECT(fs::GetEntryType(std::addressof(entry_type), FORMAT_PATH("./test_dir/dir_a/")), fs::ResultPathNotFound);
TEST_R_TRY(fs::GetEntryType(std::addressof(entry_type), FORMAT_PATH("./test_dir/dir_b/")));
AMS_ABORT_UNLESS(entry_type == fs::DirectoryEntryType_Directory);
/* Rename non-existing -> fs::ResultPathNotFound */
TEST_R_EXPECT(fs::RenameDirectory(FORMAT_PATH("./test_dir/invalid"), FORMAT_PATH2("./test_dir/invalid2")), fs::ResultPathNotFound);
/* Rename valid -> already existing gives fs::ResultPathAlreadyExists */
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/dir_a/")));
TEST_R_EXPECT(fs::RenameDirectory(FORMAT_PATH("./test_dir/dir_a/"), FORMAT_PATH2("./test_dir/dir_b/")), fs::ResultPathAlreadyExists);
/* Rename valid -> file gives fs::ResultPathAlreadyExists */
TEST_R_EXPECT(fs::RenameDirectory(FORMAT_PATH("./test_dir/dir_a/"), FORMAT_PATH2("./test_dir/a.bin")), fs::ResultPathAlreadyExists);
/* Rename file -> fs::ResultPathNotFound */
TEST_R_EXPECT(fs::RenameDirectory(FORMAT_PATH("./test_dir/a.bin"), FORMAT_PATH2("./test_dir/dir_c/")), fs::ResultPathNotFound);
/* Invalid doesn't affect the file/dir. */
TEST_R_TRY(fs::GetEntryType(std::addressof(entry_type), FORMAT_PATH("./test_dir/a.bin")));
AMS_ABORT_UNLESS(entry_type == fs::DirectoryEntryType_File);
TEST_R_TRY(fs::GetEntryType(std::addressof(entry_type), FORMAT_PATH("./test_dir/dir_a/")));
AMS_ABORT_UNLESS(entry_type == fs::DirectoryEntryType_Directory);
/* ==================================================================================================================== */
/* Get Entry Type */
/* ==================================================================================================================== */
/* File -> file. */
TEST_R_TRY(fs::GetEntryType(std::addressof(entry_type), FORMAT_PATH("./test_dir/a.bin")));
AMS_ABORT_UNLESS(entry_type == fs::DirectoryEntryType_File);
/* Dir -> dir */
TEST_R_TRY(fs::GetEntryType(std::addressof(entry_type), FORMAT_PATH("./test_dir/dir_a/")));
AMS_ABORT_UNLESS(entry_type == fs::DirectoryEntryType_Directory);
/* Invalid -> fs::ResultPathNotFound */
TEST_R_EXPECT(fs::GetEntryType(std::addressof(entry_type), FORMAT_PATH("./test_dir/invalid")), fs::ResultPathNotFound);
/* ==================================================================================================================== */
/* Get Free Space Size */
/* ==================================================================================================================== */
s64 free_size = 0;
TEST_R_TRY(fs::GetFreeSpaceSize(std::addressof(free_size), FORMAT_PATH("./test_dir/")));
AMS_ABORT_UNLESS(free_size > 0);
/* ==================================================================================================================== */
/* Get Total Space Size */
/* ==================================================================================================================== */
s64 total_size = 0;
TEST_R_TRY(fs::GetTotalSpaceSize(std::addressof(total_size), FORMAT_PATH("./test_dir/")));
AMS_ABORT_UNLESS(total_size >= free_size);
/* ==================================================================================================================== */
/* Get File Time Stamp */
/* ==================================================================================================================== */
/* Get timestamp succeeds. */
fs::FileTimeStamp timestamp;
TEST_R_TRY(fs::GetFileTimeStamp(std::addressof(timestamp), FORMAT_PATH("./test_dir/a.bin")));
AMS_ABORT_UNLESS(timestamp.create.value > 0);
AMS_ABORT_UNLESS(timestamp.access.value > 0);
AMS_ABORT_UNLESS(timestamp.modify.value > 0);
AMS_ABORT_UNLESS(!timestamp.is_local_time);
/* Invalid -> fs::ResultPathNotFound */
TEST_R_EXPECT(fs::GetFileTimeStamp(std::addressof(timestamp), FORMAT_PATH("./test_dir/invalid")), fs::ResultPathNotFound);
/* Directory -> fs::ResultPathNotFound */
TEST_R_EXPECT(fs::GetFileTimeStamp(std::addressof(timestamp), FORMAT_PATH("./test_dir/dir_a/")), fs::ResultPathNotFound);
/* ==================================================================================================================== */
/* Query Entry */
/* ==================================================================================================================== */
TEST_R_EXPECT(fs::SetConcatenationFileAttribute(FORMAT_PATH("./test_dir/")), fs::ResultUnsupportedOperation);
/* ==================================================================================================================== */
/* Open File */
/* ==================================================================================================================== */
/* Open valid succeeds. */
fs::FileHandle file;
TEST_R_TRY(fs::OpenFile(std::addressof(file), FORMAT_PATH("./test_dir/a.bin"), fs::OpenMode_ReadWrite | fs::OpenMode_AllowAppend));
fs::CloseFile(file);
/* Open invalid -> path not found. */
TEST_R_EXPECT(fs::OpenFile(std::addressof(file), FORMAT_PATH("./test_dir/invalid"), fs::OpenMode_ReadWrite | fs::OpenMode_AllowAppend), fs::ResultPathNotFound);
/* Open directory -> path not found. */
TEST_R_EXPECT(fs::OpenFile(std::addressof(file), FORMAT_PATH("./test_dir/dir_a/"), fs::OpenMode_ReadWrite | fs::OpenMode_AllowAppend), fs::ResultPathNotFound);
/* Open with invalid mode -> fs::ResultInvalidOpenMode */
TEST_R_EXPECT(fs::OpenFile(std::addressof(file), FORMAT_PATH("./test_dir/a.bin"), static_cast<fs::OpenMode>(~0u)), fs::ResultInvalidOpenMode);
/* Read only file is read only. */
{
s64 file_size;
u8 buf[1_KB];
{
TEST_R_TRY(fs::OpenFile(std::addressof(file), FORMAT_PATH("./test_dir/a.bin"), fs::OpenMode_Read));
ON_SCOPE_EXIT { fs::CloseFile(file); };
/* File size matches create. */
TEST_R_TRY(fs::GetFileSize(std::addressof(file_size), file));
AMS_ABORT_UNLESS(file_size == 1_KB);
/* Read succeeds. */
TEST_R_TRY(fs::ReadFile(file, 0, buf, sizeof(buf)));
/* Completely empty read ok. */
TEST_R_TRY(fs::ReadFile(file, 0, nullptr, 0));
/* Flush succeeds. */
TEST_R_TRY(fs::FlushFile(file));
}
/* Incorrect arguments return incorrect results. */
{
TEST_R_TRY(fs::OpenFile(std::addressof(file), FORMAT_PATH("./test_dir/a.bin"), fs::OpenMode_Read));
ON_SCOPE_EXIT { fs::CloseFile(file); };
TEST_R_EXPECT(fs::ReadFile(file, -1, buf, sizeof(buf)), fs::ResultOutOfRange);
}
{
TEST_R_TRY(fs::OpenFile(std::addressof(file), FORMAT_PATH("./test_dir/a.bin"), fs::OpenMode_Read));
ON_SCOPE_EXIT { fs::CloseFile(file); };
TEST_R_EXPECT(fs::ReadFile(file, 0, buf, -1), fs::ResultOutOfRange);
}
{
TEST_R_TRY(fs::OpenFile(std::addressof(file), FORMAT_PATH("./test_dir/a.bin"), fs::OpenMode_Read));
ON_SCOPE_EXIT { fs::CloseFile(file); };
TEST_R_EXPECT(fs::ReadFile(file, 0, nullptr, sizeof(buf)), fs::ResultNullptrArgument);
}
/* Write fails. */
{
TEST_R_TRY(fs::OpenFile(std::addressof(file), FORMAT_PATH("./test_dir/a.bin"), fs::OpenMode_Read));
ON_SCOPE_EXIT { fs::CloseFile(file); };
TEST_R_EXPECT(fs::WriteFile(file, 0, g_buffer, sizeof(g_buffer), fs::WriteOption::None), fs::ResultWriteNotPermitted);
}
/* Set size fails. */
{
TEST_R_TRY(fs::OpenFile(std::addressof(file), FORMAT_PATH("./test_dir/a.bin"), fs::OpenMode_Read));
ON_SCOPE_EXIT { fs::CloseFile(file); };
TEST_R_EXPECT(fs::SetFileSize(file, 2_KB), fs::ResultWriteNotPermitted);
}
/* File size unchanged by bad set size. */
{
TEST_R_TRY(fs::OpenFile(std::addressof(file), FORMAT_PATH("./test_dir/a.bin"), fs::OpenMode_Read));
ON_SCOPE_EXIT { fs::CloseFile(file); };
TEST_R_TRY(fs::GetFileSize(std::addressof(file_size), file));
AMS_ABORT_UNLESS(file_size == 1_KB);
}
}
/* Write only file is writable but not readable. */
{
s64 file_size;
u8 buf[1_KB];
{
TEST_R_TRY(fs::OpenFile(std::addressof(file), FORMAT_PATH("./test_dir/a.bin"), fs::OpenMode_Write));
ON_SCOPE_EXIT { fs::CloseFile(file); };
/* Write succeeds. */
std::memset(buf, 0xcc, sizeof(buf));
TEST_R_TRY(fs::WriteFile(file, 0, buf, sizeof(buf), fs::WriteOption::None));
/* Flush succeeds. */
TEST_R_TRY(fs::FlushFile(file));
/* Write with flush succeeds. */
TEST_R_TRY(fs::WriteFile(file, 0, buf, sizeof(buf), fs::WriteOption::Flush));
/* Get size succeeds. */
TEST_R_TRY(fs::GetFileSize(std::addressof(file_size), file));
AMS_ABORT_UNLESS(file_size == 1_KB);
/* Set size succeeds. */
TEST_R_TRY(fs::SetFileSize(file, 2_KB));
TEST_R_TRY(fs::GetFileSize(std::addressof(file_size), file));
AMS_ABORT_UNLESS(file_size == 2_KB);
/* Write at updated size works. */
TEST_R_TRY(fs::WriteFile(file, 1_KB, buf, sizeof(buf), fs::WriteOption::Flush));
/* Truncate down succeeds. */
TEST_R_TRY(fs::SetFileSize(file, 1_KB));
TEST_R_TRY(fs::GetFileSize(std::addressof(file_size), file));
AMS_ABORT_UNLESS(file_size == 1_KB);
/* Completely empty write ok. */
TEST_R_TRY(fs::WriteFile(file, 0, nullptr, 0, fs::WriteOption::Flush));
}
/* Incorrect arguments return incorrect results. */
{
TEST_R_TRY(fs::OpenFile(std::addressof(file), FORMAT_PATH("./test_dir/a.bin"), fs::OpenMode_Write));
ON_SCOPE_EXIT { fs::CloseFile(file); };
TEST_R_EXPECT(fs::WriteFile(file, -1, buf, sizeof(buf), fs::WriteOption::None), fs::ResultOutOfRange);
}
{
TEST_R_TRY(fs::OpenFile(std::addressof(file), FORMAT_PATH("./test_dir/a.bin"), fs::OpenMode_Write));
ON_SCOPE_EXIT { fs::CloseFile(file); };
TEST_R_EXPECT(fs::WriteFile(file, 0, buf, -1, fs::WriteOption::None), fs::ResultOutOfRange);
}
{
TEST_R_TRY(fs::OpenFile(std::addressof(file), FORMAT_PATH("./test_dir/a.bin"), fs::OpenMode_Write));
ON_SCOPE_EXIT { fs::CloseFile(file); };
TEST_R_EXPECT(fs::WriteFile(file, 0, nullptr, sizeof(buf), fs::WriteOption::None), fs::ResultNullptrArgument);
}
{
TEST_R_TRY(fs::OpenFile(std::addressof(file), FORMAT_PATH("./test_dir/a.bin"), fs::OpenMode_Write));
ON_SCOPE_EXIT { fs::CloseFile(file); };
TEST_R_EXPECT(fs::WriteFile(file, 1_KB, buf, sizeof(buf), fs::WriteOption::None), fs::ResultFileExtensionWithoutOpenModeAllowAppend);
}
/* Read fails. */
{
TEST_R_TRY(fs::OpenFile(std::addressof(file), FORMAT_PATH("./test_dir/a.bin"), fs::OpenMode_Write));
ON_SCOPE_EXIT { fs::CloseFile(file); };
TEST_R_EXPECT(fs::ReadFile(file, 0, buf, sizeof(buf)), fs::ResultReadNotPermitted);
}
/* Appending works with OpenMode_AllowAppend. */
{
TEST_R_TRY(fs::OpenFile(std::addressof(file), FORMAT_PATH("./test_dir/a.bin"), fs::OpenMode_Write | fs::OpenMode_AllowAppend));
ON_SCOPE_EXIT { fs::CloseFile(file); };
TEST_R_TRY(fs::GetFileSize(std::addressof(file_size), file));
AMS_ABORT_UNLESS(file_size == 1_KB);
for (size_t i = 0; i < sizeof(buf); ++i) {
buf[i] = static_cast<u8>(i);
}
TEST_R_TRY(fs::WriteFile(file, 1_KB, buf, sizeof(buf), fs::WriteOption::Flush));
TEST_R_TRY(fs::GetFileSize(std::addressof(file_size), file));
AMS_ABORT_UNLESS(file_size == 2_KB);
}
/* Data is persistent. */
{
TEST_R_TRY(fs::OpenFile(std::addressof(file), FORMAT_PATH("./test_dir/a.bin"), fs::OpenMode_ReadWrite));
ON_SCOPE_EXIT { fs::CloseFile(file); };
TEST_R_TRY(fs::ReadFile(file, 0, buf, sizeof(buf)));
for (size_t i = 0; i < 1_KB; ++i) {
AMS_ABORT_UNLESS(buf[i] == 0xCC);
}
TEST_R_TRY(fs::ReadFile(file, 1_KB, buf, sizeof(buf)));
for (size_t i = 0; i < 1_KB; ++i) {
AMS_ABORT_UNLESS(buf[i] == static_cast<u8>(i));
}
TEST_R_TRY(fs::WriteFile(file, 0, buf, sizeof(buf), fs::WriteOption::Flush));
TEST_R_TRY(fs::SetFileSize(file, 1_KB));
TEST_R_TRY(fs::GetFileSize(std::addressof(file_size), file));
AMS_ABORT_UNLESS(file_size == 1_KB);
TEST_R_TRY(fs::ReadFile(file, 0, buf, sizeof(buf)));
for (size_t i = 0; i < 1_KB; ++i) {
AMS_ABORT_UNLESS(buf[i] == static_cast<u8>(i));
}
}
}
/* More involved file data test using random buffer. */
{
u8 buf[1_KB];
/* Write random data. */
{
TEST_R_TRY(fs::OpenFile(std::addressof(file), FORMAT_PATH("./test_dir/test_rand.bin"), fs::OpenMode_Write));
ON_SCOPE_EXIT { fs::CloseFile(file); };
/* Get a bunch of random data. */
os::GenerateRandomBytes(g_buffer, sizeof(g_buffer));
/* Write it to disk. */
TEST_R_TRY(fs::WriteFile(file, 0, g_buffer, sizeof(g_buffer), fs::WriteOption::None));
TEST_R_TRY(fs::FlushFile(file));
}
/* Read and verify random data. */
{
TEST_R_TRY(fs::OpenFile(std::addressof(file), FORMAT_PATH("./test_dir/test_rand.bin"), fs::OpenMode_Read));
ON_SCOPE_EXIT { fs::CloseFile(file); };
u32 ofs;
for (size_t i = 0; i < 1000; ++i) {
os::GenerateRandomBytes(std::addressof(ofs), sizeof(ofs));
ofs %= (sizeof(g_buffer) - sizeof(buf));
TEST_R_TRY(fs::ReadFile(file, ofs, buf, sizeof(buf)));
AMS_ABORT_UNLESS(std::memcmp(buf, g_buffer + ofs, sizeof(buf)) == 0);
}
}
}
/* ==================================================================================================================== */
/* Open Directory */
/* ==================================================================================================================== */
fs::DirectoryHandle dir;
TEST_R_TRY(fs::OpenDirectory(std::addressof(dir), FORMAT_PATH("./test_dir/dir_a/"), fs::OpenDirectoryMode_All | fs::OpenDirectoryMode_NotRequireFileSize));
fs::CloseDirectory(dir);
/* Open invalid -> path not found. */
TEST_R_EXPECT(fs::OpenDirectory(std::addressof(dir), FORMAT_PATH("./test_dir/invalid"), fs::OpenDirectoryMode_All | fs::OpenDirectoryMode_NotRequireFileSize), fs::ResultPathNotFound);
/* Open file -> path not found. */
TEST_R_EXPECT(fs::OpenDirectory(std::addressof(dir), FORMAT_PATH("./test_dir/a.bin"), fs::OpenDirectoryMode_All | fs::OpenDirectoryMode_NotRequireFileSize), fs::ResultPathNotFound);
/* Open with invalid mode -> fs::ResultInvalidOpenMode */
TEST_R_EXPECT(fs::OpenDirectory(std::addressof(dir), FORMAT_PATH("./test_dir/dir_a/"), static_cast<fs::OpenDirectoryMode>(~0u)), fs::ResultInvalidOpenMode);
/* Populate test directory with three files and two dirs. */
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/dir_a/f0"), 0));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/dir_a/f1"), 1_KB));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/dir_a/f2"), 0x42069));
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/dir_a/d0")));
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/dir_a/d1")));
TEST_R_TRY(fs::CreateFile(FORMAT_PATH("./test_dir/dir_a/d0/file"), 0));
TEST_R_TRY(fs::CreateDirectory(FORMAT_PATH("./test_dir/dir_a/d0/dir/")));
/* Directory tests. */
{
bool seen_file[3];
bool seen_dir[2];
constexpr s64 NumFiles = util::size(seen_file);
constexpr s64 NumDirs = util::size(seen_dir);
constexpr s64 NumAll = NumFiles + NumDirs;
fs::DirectoryEntry entries[2 * NumAll];
s64 entry_count;
auto ResetSeenFiles = [&] () { for (auto &b : seen_file) { b = false; } };
auto ResetSeenDirs = [&] () { for (auto &b : seen_dir) { b = false; } };
auto ResetSeenAll = [&] () { ResetSeenFiles(); ResetSeenDirs(); };
auto CheckSeenFiles = [&] () { for (const auto b : seen_file) { AMS_ABORT_UNLESS(b); } };
auto CheckSeenDirs = [&] () { for (const auto b : seen_dir) { AMS_ABORT_UNLESS(b); } };
auto CheckSeenAll = [&] () { CheckSeenFiles(); CheckSeenDirs(); };
auto CheckNotSeenFiles = [&] () { for (const auto b : seen_file) { AMS_ABORT_UNLESS(!b); } };
auto CheckNotSeenDirs = [&] () { for (const auto b : seen_dir) { AMS_ABORT_UNLESS(!b); } };
auto CheckDirectoryEntry = [&] (const fs::DirectoryEntry &entry) {
/* Check name. */
AMS_ABORT_UNLESS(entry.name[0] == 'f' || entry.name[0] == 'd');
AMS_ABORT_UNLESS('0' <= entry.name[1] && entry.name[1] <= '9');
AMS_ABORT_UNLESS(entry.name[2] == 0);
/* Check type. */
if (entry.name[0] == 'f') {
AMS_ABORT_UNLESS(entry.type == fs::DirectoryEntryType_File);
/* If file, check size. */
switch (entry.name[1]) {
case '0': AMS_ABORT_UNLESS(entry.file_size == 0); break;
case '1': AMS_ABORT_UNLESS(entry.file_size == 1_KB); break;
case '2': AMS_ABORT_UNLESS(entry.file_size == 0x42069); break;
}
AMS_ABORT_UNLESS(!seen_file[(entry.name[1] - '0')]);
seen_file[(entry.name[1] - '0')] = true;
} else {
AMS_ABORT_UNLESS(entry.type == fs::DirectoryEntryType_Directory);
AMS_ABORT_UNLESS(!seen_dir[(entry.name[1] - '0')]);
seen_dir[(entry.name[1] - '0')] = true;
}
};
/* Get EntryCount is correct. */
{
/* All returns all entries. */
{
TEST_R_TRY(fs::OpenDirectory(std::addressof(dir), FORMAT_PATH("./test_dir/dir_a/"), fs::OpenDirectoryMode_All));
ON_SCOPE_EXIT { fs::CloseDirectory(dir); };
TEST_R_TRY(fs::GetDirectoryEntryCount(std::addressof(entry_count), dir));
AMS_ABORT_UNLESS(entry_count == NumAll);
}
/* File returns only files, and does not count things in subdirectories. */
{
TEST_R_TRY(fs::OpenDirectory(std::addressof(dir), FORMAT_PATH("./test_dir/dir_a/"), fs::OpenDirectoryMode_File));
ON_SCOPE_EXIT { fs::CloseDirectory(dir); };
TEST_R_TRY(fs::GetDirectoryEntryCount(std::addressof(entry_count), dir));
AMS_ABORT_UNLESS(entry_count == NumFiles);
}
/* Dir returns only dirs, and does not count things in subdirectories. */
{
TEST_R_TRY(fs::OpenDirectory(std::addressof(dir), FORMAT_PATH("./test_dir/dir_a/"), fs::OpenDirectoryMode_Directory));
ON_SCOPE_EXIT { fs::CloseDirectory(dir); };
TEST_R_TRY(fs::GetDirectoryEntryCount(std::addressof(entry_count), dir));
AMS_ABORT_UNLESS(entry_count == NumDirs);
}
}
/* Read is correct, N at a time. */
for (s64 at_a_time = 1; at_a_time <= 2 * NumAll; ++at_a_time) {
/* All returns all entries. */
{
ResetSeenAll();
TEST_R_TRY(fs::OpenDirectory(std::addressof(dir), FORMAT_PATH("./test_dir/dir_a/"), fs::OpenDirectoryMode_All));
ON_SCOPE_EXIT { fs::CloseDirectory(dir); };
TEST_R_TRY(fs::GetDirectoryEntryCount(std::addressof(entry_count), dir));
AMS_ABORT_UNLESS(entry_count == NumAll);
s64 remaining = entry_count;
while (remaining > 0) {
s64 cur;
TEST_R_TRY(fs::ReadDirectory(std::addressof(cur), entries, dir, at_a_time));
AMS_ABORT_UNLESS(cur <= remaining);
AMS_ABORT_UNLESS(cur == std::min<s64>(at_a_time, remaining));
for (s64 i = 0; i < cur; ++i) {
CheckDirectoryEntry(entries[i]);
}
remaining -= cur;
}
CheckSeenAll();
/* Read succeeds at end of dir. */
s64 cur;
TEST_R_TRY(fs::ReadDirectory(std::addressof(cur), entries, dir, at_a_time));
AMS_ABORT_UNLESS(cur == 0);
/* Get entry count still shows correct value. */
s64 entry_count2;
TEST_R_TRY(fs::GetDirectoryEntryCount(std::addressof(entry_count2), dir));
AMS_ABORT_UNLESS(entry_count2 == entry_count);
}
/* File returns only files. */
{
ResetSeenAll();
TEST_R_TRY(fs::OpenDirectory(std::addressof(dir), FORMAT_PATH("./test_dir/dir_a/"), fs::OpenDirectoryMode_File));
ON_SCOPE_EXIT { fs::CloseDirectory(dir); };
TEST_R_TRY(fs::GetDirectoryEntryCount(std::addressof(entry_count), dir));
AMS_ABORT_UNLESS(entry_count == NumFiles);
s64 remaining = entry_count;
while (remaining > 0) {
s64 cur;
TEST_R_TRY(fs::ReadDirectory(std::addressof(cur), entries, dir, at_a_time));
AMS_ABORT_UNLESS(cur <= remaining);
AMS_ABORT_UNLESS(cur == std::min<s64>(at_a_time, remaining));
for (s64 i = 0; i < cur; ++i) {
CheckDirectoryEntry(entries[i]);
}
remaining -= cur;
}
CheckSeenFiles();
CheckNotSeenDirs();
/* Read succeeds at end of dir. */
s64 cur;
TEST_R_TRY(fs::ReadDirectory(std::addressof(cur), entries, dir, at_a_time));
AMS_ABORT_UNLESS(cur == 0);
/* Get entry count still shows correct value. */
s64 entry_count2;
TEST_R_TRY(fs::GetDirectoryEntryCount(std::addressof(entry_count2), dir));
AMS_ABORT_UNLESS(entry_count2 == entry_count);
}
/* Directory returns only dirs. */
{
ResetSeenAll();
TEST_R_TRY(fs::OpenDirectory(std::addressof(dir), FORMAT_PATH("./test_dir/dir_a/"), fs::OpenDirectoryMode_Directory));
ON_SCOPE_EXIT { fs::CloseDirectory(dir); };
TEST_R_TRY(fs::GetDirectoryEntryCount(std::addressof(entry_count), dir));
AMS_ABORT_UNLESS(entry_count == NumDirs);
s64 remaining = entry_count;
while (remaining > 0) {
s64 cur;
TEST_R_TRY(fs::ReadDirectory(std::addressof(cur), entries, dir, at_a_time));
AMS_ABORT_UNLESS(cur <= remaining);
AMS_ABORT_UNLESS(cur == std::min<s64>(at_a_time, remaining));
for (s64 i = 0; i < cur; ++i) {
CheckDirectoryEntry(entries[i]);
}
remaining -= cur;
}
CheckSeenDirs();
CheckNotSeenFiles();
/* Read succeeds at end of dir. */
s64 cur;
TEST_R_TRY(fs::ReadDirectory(std::addressof(cur), entries, dir, at_a_time));
AMS_ABORT_UNLESS(cur == 0);
/* Get entry count still shows correct value. */
s64 entry_count2;
TEST_R_TRY(fs::GetDirectoryEntryCount(std::addressof(entry_count2), dir));
AMS_ABORT_UNLESS(entry_count2 == entry_count);
}
}
}
/* ==================================================================================================================== */
/* Cleanup */
/* ==================================================================================================================== */
TEST_R_TRY(fs::DeleteDirectoryRecursively(FORMAT_PATH("./test_dir/")));
}
}
void Main() {
fs::SetEnabledAutoAbort(false);
printf("Doing FS test!\n");
DoFsTests();
printf("All tests completed!\n");
}
}
| 53,056
|
C++
|
.cpp
| 675
| 61.642963
| 195
| 0.463575
|
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,285
|
test.cpp
|
Atmosphere-NX_Atmosphere/tests/TestSocket/source/test.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams {
namespace {
constinit u8 g_socket_config_memory[2_MB];
alignas(os::MemoryPageSize) constinit u8 g_server_thread_stack[16_KB];
constexpr const u8 TestMessage[0x10] = {
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF,
};
void TestServerThread(void *arg) {
os::EventType *server_ready_event = reinterpret_cast<os::EventType *>(arg);
s32 listen_fd = socket::Socket(socket::Family::Af_Inet, socket::Type::Sock_Stream, socket::Protocol::IpProto_Ip);
AMS_ABORT_UNLESS(listen_fd >= 0);
printf("[Server]: Listen fd=%d\n", static_cast<int>(listen_fd));
socket::SockAddrIn s_addr = {};
s_addr.sin_family = socket::Family::Af_Inet;
s_addr.sin_addr.s_addr = socket::InAddr_Any;
s_addr.sin_port = socket::InetHtons(23337);
/* Bind. */
const auto bind_res = socket::Bind(listen_fd, reinterpret_cast<socket::SockAddr *>(std::addressof(s_addr)), sizeof(s_addr));
printf("[Server]: Bind=%d\n", static_cast<int>(bind_res));
AMS_ABORT_UNLESS(bind_res == 0);
/* Listen. */
const auto listen_res = socket::Listen(listen_fd, 1);
printf("[Server]: Listen=%d\n", static_cast<int>(listen_res));
AMS_ABORT_UNLESS(listen_res >= 0);
printf("[Server]: Ready\n");
os::SignalEvent(server_ready_event);
/* Accept. */
s32 conn_fd = socket::Accept(listen_fd, nullptr, nullptr);
AMS_ABORT_UNLESS(conn_fd >= 0);
printf("[Server]: Conn fd=%d\n", conn_fd);
/* Receive. */
u8 received[sizeof(TestMessage)] = {};
AMS_ABORT_UNLESS(socket::Recv(conn_fd, received, sizeof(received), socket::MsgFlag::Msg_None) == sizeof(received));
printf("[Server]: Received\n");
AMS_ABORT_UNLESS(std::memcmp(received, TestMessage, sizeof(TestMessage)) == 0);
/* Calculate hash. */
u8 hash[crypto::Sha256Generator::HashSize];
crypto::GenerateSha256(hash, sizeof(hash), received, sizeof(received));
/* Send hash. */
AMS_ABORT_UNLESS(socket::Send(conn_fd, hash, sizeof(hash), socket::MsgFlag::Msg_None) == sizeof(hash));
printf("[Server]: Sent\n");
/* Close sockets. */
AMS_ABORT_UNLESS(socket::Close(conn_fd) == 0);
AMS_ABORT_UNLESS(socket::Close(listen_fd) == 0);
printf("[Server]: Closed\n");
}
}
void Main() {
auto cfg = socket::SystemConfigDefault(g_socket_config_memory, sizeof(g_socket_config_memory) / 2, sizeof(g_socket_config_memory) / 2);
R_ABORT_UNLESS(socket::Initialize(cfg));
{
/* Set up for the server thread. */
os::EventType server_ready_event;
os::InitializeEvent(std::addressof(server_ready_event), false, os::EventClearMode_AutoClear);
ON_SCOPE_EXIT { os::FinalizeEvent(std::addressof(server_ready_event)); };
/* Wait for the server thread to be ready */
os::ThreadType server_thread;
R_ABORT_UNLESS(os::CreateThread(std::addressof(server_thread), TestServerThread, std::addressof(server_ready_event), g_server_thread_stack, sizeof(g_server_thread_stack), os::DefaultThreadPriority));
os::SetThreadNamePointer(std::addressof(server_thread), "ServerThread");
os::StartThread(std::addressof(server_thread));
/* Wait for the server thread to be ready. */
os::WaitEvent(std::addressof(server_ready_event));
{
/* Create socket. */
s32 conn_fd = socket::Socket(socket::Family::Af_Inet, socket::Type::Sock_Stream, socket::Protocol::IpProto_Ip);
AMS_ABORT_UNLESS(conn_fd >= 0);
printf("[Client]: Conn fd=%d\n", static_cast<int>(conn_fd));
socket::SockAddrIn s_addr = {};
s_addr.sin_family = socket::Family::Af_Inet;
s_addr.sin_addr.s_addr = socket::InAddr_Loopback;
s_addr.sin_port = socket::InetHtons(23337);
/* Connect. */
const auto connect_res = socket::Connect(conn_fd, reinterpret_cast<socket::SockAddr *>(std::addressof(s_addr)), sizeof(s_addr));
printf("[Client]: Connect=%d, last_err=%d\n", connect_res, static_cast<int>(socket::GetLastError()));
AMS_ABORT_UNLESS(connect_res == 0);
/* Send test. */
AMS_ABORT_UNLESS(socket::Send(conn_fd, TestMessage, sizeof(TestMessage), socket::MsgFlag::Msg_None) == sizeof(TestMessage));
printf("[Client]: Sent\n");
/* Receive. */
u8 received[crypto::Sha256Generator::HashSize] = {};
AMS_ABORT_UNLESS(socket::Recv(conn_fd, received, sizeof(received), socket::MsgFlag::Msg_None) == sizeof(received));
printf("[Client]: Received\n");
/* Calculate hash. */
u8 hash[crypto::Sha256Generator::HashSize];
crypto::GenerateSha256(hash, sizeof(hash), TestMessage, sizeof(TestMessage));
AMS_ABORT_UNLESS(std::memcmp(received, hash, sizeof(hash)) == 0);
/* Close sockets. */
AMS_ABORT_UNLESS(socket::Close(conn_fd) == 0);
printf("[Client]: Closed\n");
}
/* Wait for the server thread to complete. */
os::WaitThread(std::addressof(server_thread));
}
printf("Successfully performed socket test!\n");
socket::Finalize();
}
}
| 6,452
|
C++
|
.cpp
| 113
| 45.39823
| 211
| 0.593056
|
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,286
|
test_thread_pinning.cpp
|
Atmosphere-NX_Atmosphere/tests/TestSvc/source/test_thread_pinning.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "util_common.hpp"
#include "util_scoped_heap.hpp"
namespace ams::test {
DOCTEST_TEST_CASE( "Setting a thread's disable count will cause it to become pinned." ) {
DoWithThreadPinning([]() {
__asm__ __volatile__("" ::: "memory");
});
}
}
| 946
|
C++
|
.cpp
| 25
| 34.76
| 93
| 0.711643
|
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,287
|
test_set_memory_permission.cpp
|
Atmosphere-NX_Atmosphere/tests/TestSvc/source/test_set_memory_permission.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "util_common.hpp"
#include "util_check_memory.hpp"
#include "util_scoped_heap.hpp"
namespace ams::test {
namespace {
bool CanSetMemoryPermission(u8 state) {
return state == svc::MemoryState_CodeData || state == svc::MemoryState_AliasCodeData || state == svc::MemoryState_Normal;
}
}
alignas(os::MemoryPageSize) constinit u8 g_memory_permission_buffer[2 * os::MemoryPageSize];
DOCTEST_TEST_CASE("svc::SetMemoryPermission invalid arguments") {
const uintptr_t buffer = reinterpret_cast<uintptr_t>(g_memory_permission_buffer);
for (size_t i = 1; i < os::MemoryPageSize; ++i) {
DOCTEST_CHECK(svc::ResultInvalidAddress::Includes(svc::SetMemoryPermission(buffer + i, os::MemoryPageSize, svc::MemoryPermission_Read)));
DOCTEST_CHECK(svc::ResultInvalidSize::Includes(svc::SetMemoryPermission(buffer, os::MemoryPageSize + i, svc::MemoryPermission_Read)));
}
DOCTEST_CHECK(svc::ResultInvalidSize::Includes(svc::SetMemoryPermission(buffer, 0, svc::MemoryPermission_Read)));
{
const u64 vmem_end = util::AlignDown(std::numeric_limits<u64>::max(), os::MemoryPageSize);
DOCTEST_CHECK(svc::ResultInvalidCurrentMemory::Includes(svc::SetMemoryPermission(vmem_end, 2 * os::MemoryPageSize, svc::MemoryPermission_Read)));
}
DOCTEST_CHECK(svc::ResultInvalidCurrentMemory::Includes(svc::SetMemoryPermission(svc::AddressMap39End, os::MemoryPageSize, svc::MemoryPermission_Read)));
for (size_t i = 0; i < 0x100; ++i) {
const auto perm = static_cast<svc::MemoryPermission>(i);
if (perm == svc::MemoryPermission_None || perm == svc::MemoryPermission_Read || perm == svc::MemoryPermission_ReadWrite) {
continue;
}
DOCTEST_CHECK(svc::ResultInvalidNewMemoryPermission::Includes(svc::SetMemoryPermission(buffer, os::MemoryPageSize, perm)));
}
DOCTEST_CHECK(svc::ResultInvalidNewMemoryPermission::Includes(svc::SetMemoryPermission(buffer, os::MemoryPageSize, svc::MemoryPermission_ReadExecute)));
DOCTEST_CHECK(svc::ResultInvalidNewMemoryPermission::Includes(svc::SetMemoryPermission(buffer, os::MemoryPageSize, svc::MemoryPermission_Write)));
DOCTEST_CHECK(svc::ResultInvalidNewMemoryPermission::Includes(svc::SetMemoryPermission(buffer, os::MemoryPageSize, svc::MemoryPermission_DontCare)));
}
DOCTEST_TEST_CASE("svc::SetMemoryPermission works on specific states") {
/* Check that we have CodeData. */
const uintptr_t bss_buffer = reinterpret_cast<uintptr_t>(g_memory_permission_buffer);
TestMemory(bss_buffer, sizeof(g_memory_permission_buffer), svc::MemoryState_CodeData, svc::MemoryPermission_ReadWrite, 0);
/* Create a heap. */
ScopedHeap scoped_heap(2 * svc::HeapSizeAlignment);
TestMemory(scoped_heap.GetAddress(), scoped_heap.GetSize(), svc::MemoryState_Normal, svc::MemoryPermission_ReadWrite, 0);
/* TODO: Ensure we have alias code data? */
uintptr_t addr = 0;
while (true) {
/* Get current mapping. */
svc::MemoryInfo mem_info;
svc::PageInfo page_info;
DOCTEST_CHECK(R_SUCCEEDED(svc::QueryMemory(std::addressof(mem_info), std::addressof(page_info), addr)));
/* Try to set permission. */
if (CanSetMemoryPermission(mem_info.state) && mem_info.attribute == 0) {
DOCTEST_CHECK(R_SUCCEEDED(svc::SetMemoryPermission(mem_info.base_address, mem_info.size, svc::MemoryPermission_ReadWrite)));
TestMemory(mem_info.base_address, mem_info.size, mem_info.state, svc::MemoryPermission_ReadWrite, mem_info.attribute);
DOCTEST_CHECK(R_SUCCEEDED(svc::SetMemoryPermission(mem_info.base_address, mem_info.size, mem_info.permission)));
} else {
DOCTEST_CHECK(svc::ResultInvalidCurrentMemory::Includes(svc::SetMemoryPermission(mem_info.base_address, mem_info.size, svc::MemoryPermission_Read)));
}
const uintptr_t next_address = mem_info.base_address + mem_info.size;
if (next_address <= addr) {
break;
}
addr = next_address;
}
}
DOCTEST_TEST_CASE("svc::SetMemoryPermission allows for free movement between RW-, R--, ---") {
/* Define helper. */
auto test_set_memory_permission = [](uintptr_t address, size_t size){
/* Get the permission. */
svc::MemoryInfo mem_info;
svc::PageInfo page_info;
DOCTEST_CHECK(R_SUCCEEDED(svc::QueryMemory(std::addressof(mem_info), std::addressof(page_info), address)));
const svc::MemoryPermission legal_states[] = { svc::MemoryPermission_None, svc::MemoryPermission_Read, svc::MemoryPermission_ReadWrite };
for (const auto src_state : legal_states) {
for (const auto dst_state : legal_states) {
DOCTEST_CHECK(R_SUCCEEDED(svc::SetMemoryPermission(address, size, svc::MemoryPermission_None)));
DOCTEST_CHECK(R_SUCCEEDED(svc::SetMemoryPermission(address, size, src_state)));
DOCTEST_CHECK(R_SUCCEEDED(svc::SetMemoryPermission(address, size, dst_state)));
DOCTEST_CHECK(R_SUCCEEDED(svc::SetMemoryPermission(address, size, svc::MemoryPermission_None)));
}
}
DOCTEST_CHECK(R_SUCCEEDED(svc::SetMemoryPermission(address, size, mem_info.permission)));
};
/* Test that we can freely move about .bss buffers. */
test_set_memory_permission(reinterpret_cast<uintptr_t>(g_memory_permission_buffer), sizeof(g_memory_permission_buffer));
/* Create a heap. */
ScopedHeap scoped_heap(svc::HeapSizeAlignment);
TestMemory(scoped_heap.GetAddress(), scoped_heap.GetSize(), svc::MemoryState_Normal, svc::MemoryPermission_ReadWrite, 0);
/* Test that we can freely move about heap. */
test_set_memory_permission(scoped_heap.GetAddress(), scoped_heap.GetSize());
/* TODO: AliasCodeData */
}
DOCTEST_TEST_CASE("svc::SetMemoryPermission fails when the memory has non-zero attribute") {
const uintptr_t bss_buffer = reinterpret_cast<uintptr_t>(g_memory_permission_buffer);
TestMemory(bss_buffer, sizeof(g_memory_permission_buffer), svc::MemoryState_CodeData, svc::MemoryPermission_ReadWrite, 0);
DOCTEST_CHECK(R_SUCCEEDED(svc::SetMemoryPermission(bss_buffer, sizeof(g_memory_permission_buffer), svc::MemoryPermission_None)));
DOCTEST_CHECK(R_SUCCEEDED(svc::SetMemoryPermission(bss_buffer, sizeof(g_memory_permission_buffer), svc::MemoryPermission_Read)));
DOCTEST_CHECK(R_SUCCEEDED(svc::SetMemoryPermission(bss_buffer, sizeof(g_memory_permission_buffer), svc::MemoryPermission_ReadWrite)));
DOCTEST_CHECK(R_SUCCEEDED(svc::SetMemoryAttribute(bss_buffer, sizeof(g_memory_permission_buffer), svc::MemoryAttribute_Uncached, svc::MemoryAttribute_Uncached)));
TestMemory(bss_buffer, sizeof(g_memory_permission_buffer), svc::MemoryState_CodeData, svc::MemoryPermission_ReadWrite, svc::MemoryAttribute_Uncached);
DOCTEST_CHECK(svc::ResultInvalidCurrentMemory::Includes(svc::SetMemoryPermission(bss_buffer, sizeof(g_memory_permission_buffer), svc::MemoryPermission_None)));
DOCTEST_CHECK(svc::ResultInvalidCurrentMemory::Includes(svc::SetMemoryPermission(bss_buffer, sizeof(g_memory_permission_buffer), svc::MemoryPermission_Read)));
DOCTEST_CHECK(svc::ResultInvalidCurrentMemory::Includes(svc::SetMemoryPermission(bss_buffer, sizeof(g_memory_permission_buffer), svc::MemoryPermission_ReadWrite)));
DOCTEST_CHECK(R_SUCCEEDED(svc::SetMemoryAttribute(bss_buffer, sizeof(g_memory_permission_buffer), svc::MemoryAttribute_Uncached, 0)));
TestMemory(bss_buffer, sizeof(g_memory_permission_buffer), svc::MemoryState_CodeData, svc::MemoryPermission_ReadWrite, 0);
DOCTEST_CHECK(R_SUCCEEDED(svc::SetMemoryPermission(bss_buffer, sizeof(g_memory_permission_buffer), svc::MemoryPermission_None)));
DOCTEST_CHECK(R_SUCCEEDED(svc::SetMemoryPermission(bss_buffer, sizeof(g_memory_permission_buffer), svc::MemoryPermission_Read)));
DOCTEST_CHECK(R_SUCCEEDED(svc::SetMemoryPermission(bss_buffer, sizeof(g_memory_permission_buffer), svc::MemoryPermission_ReadWrite)));
}
}
| 9,115
|
C++
|
.cpp
| 123
| 64.601626
| 172
| 0.700335
|
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,288
|
test_set_heap_size.cpp
|
Atmosphere-NX_Atmosphere/tests/TestSvc/source/test_set_heap_size.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "util_common.hpp"
#include "util_check_memory.hpp"
namespace ams::test {
namespace {
size_t GetPhysicalMemorySizeMax() {
u64 v;
R_ABORT_UNLESS(svc::GetInfo(std::addressof(v), svc::InfoType_ResourceLimit, svc::InvalidHandle, 0));
const svc::Handle resource_limit = v;
ON_SCOPE_EXIT { svc::CloseHandle(resource_limit); };
s64 size;
R_ABORT_UNLESS(svc::GetResourceLimitLimitValue(std::addressof(size), resource_limit, svc::LimitableResource_PhysicalMemoryMax));
return static_cast<size_t>(size);
}
size_t GetPhysicalMemorySizeAvailable() {
u64 v;
R_ABORT_UNLESS(svc::GetInfo(std::addressof(v), svc::InfoType_ResourceLimit, svc::InvalidHandle, 0));
const svc::Handle resource_limit = v;
ON_SCOPE_EXIT { svc::CloseHandle(resource_limit); };
s64 total;
R_ABORT_UNLESS(svc::GetResourceLimitLimitValue(std::addressof(total), resource_limit, svc::LimitableResource_PhysicalMemoryMax));
s64 current;
R_ABORT_UNLESS(svc::GetResourceLimitCurrentValue(std::addressof(current), resource_limit, svc::LimitableResource_PhysicalMemoryMax));
return static_cast<size_t>(total - current);
}
}
DOCTEST_TEST_CASE("svc::SetHeapSize") {
svc::MemoryInfo mem_info;
svc::PageInfo page_info;
uintptr_t dummy;
/* Reset the heap. */
uintptr_t addr;
DOCTEST_CHECK(R_SUCCEEDED(svc::SetHeapSize(std::addressof(addr), 0)));
/* Ensure that we don't leak memory. */
const size_t initial_memory = GetPhysicalMemorySizeAvailable();
ON_SCOPE_EXIT { DOCTEST_CHECK(initial_memory == GetPhysicalMemorySizeAvailable()); };
DOCTEST_SUBCASE("Unaligned and too big sizes fail") {
for (size_t i = 1; i < svc::HeapSizeAlignment; i = util::AlignUp(i + 1, os::MemoryPageSize)){
DOCTEST_CHECK(svc::ResultInvalidSize::Includes(svc::SetHeapSize(std::addressof(dummy), i)));
}
DOCTEST_CHECK(svc::ResultInvalidSize::Includes(svc::SetHeapSize(std::addressof(dummy), 64_GB)));
}
DOCTEST_SUBCASE("Larger size than address space fails") {
DOCTEST_CHECK(svc::ResultOutOfMemory::Includes(svc::SetHeapSize(std::addressof(dummy), util::AlignUp(svc::AddressMemoryRegionHeap39Size + 1, svc::HeapSizeAlignment))));
}
DOCTEST_SUBCASE("Bounded by resource limit") {
DOCTEST_CHECK(svc::ResultLimitReached::Includes(svc::SetHeapSize(std::addressof(dummy), util::AlignUp(GetPhysicalMemorySizeMax() + 1, svc::HeapSizeAlignment))));
DOCTEST_CHECK(svc::ResultLimitReached::Includes(svc::SetHeapSize(std::addressof(dummy), util::AlignUp(GetPhysicalMemorySizeAvailable() + 1, svc::HeapSizeAlignment))));
}
DOCTEST_SUBCASE("SetHeapSize gives heap memory") {
DOCTEST_CHECK(R_SUCCEEDED(svc::SetHeapSize(std::addressof(addr), svc::HeapSizeAlignment)));
TestMemory(addr, svc::HeapSizeAlignment, svc::MemoryState_Normal, svc::MemoryPermission_ReadWrite, 0);
DOCTEST_CHECK(R_SUCCEEDED(svc::SetHeapSize(std::addressof(addr), 0)));
}
DOCTEST_SUBCASE("SetHeapSize cannot remove read-only heap") {
DOCTEST_CHECK(R_SUCCEEDED(svc::SetHeapSize(std::addressof(addr), svc::HeapSizeAlignment)));
DOCTEST_CHECK(R_SUCCEEDED(svc::QueryMemory(std::addressof(mem_info), std::addressof(page_info), addr)));
TestMemory(addr, svc::HeapSizeAlignment, svc::MemoryState_Normal, svc::MemoryPermission_ReadWrite, 0);
DOCTEST_CHECK(R_SUCCEEDED(svc::SetMemoryPermission(addr, svc::HeapSizeAlignment, svc::MemoryPermission_Read)));
TestMemory(addr, svc::HeapSizeAlignment, svc::MemoryState_Normal, svc::MemoryPermission_Read, 0);
DOCTEST_CHECK(svc::ResultInvalidCurrentMemory::Includes(svc::SetHeapSize(std::addressof(dummy), 0)));
DOCTEST_CHECK(R_SUCCEEDED(svc::SetMemoryPermission(addr, svc::HeapSizeAlignment, svc::MemoryPermission_ReadWrite)));
TestMemory(addr, svc::HeapSizeAlignment, svc::MemoryState_Normal, svc::MemoryPermission_ReadWrite, 0);
DOCTEST_CHECK(R_SUCCEEDED(svc::SetHeapSize(std::addressof(addr), 0)));
}
DOCTEST_SUBCASE("Heap memory does not survive unmap/re-map") {
DOCTEST_CHECK(R_SUCCEEDED(svc::SetHeapSize(std::addressof(addr), 2 * svc::HeapSizeAlignment)));
u8 * const heap = reinterpret_cast<u8 *>(addr);
std::memset(heap, 0xAA, svc::HeapSizeAlignment);
std::memset(heap + svc::HeapSizeAlignment, 0xBB, svc::HeapSizeAlignment);
DOCTEST_CHECK(heap[svc::HeapSizeAlignment] == 0xBB);
DOCTEST_CHECK(std::memcmp(heap + svc::HeapSizeAlignment, heap + svc::HeapSizeAlignment + 1, svc::HeapSizeAlignment - 1) == 0);
DOCTEST_CHECK(R_SUCCEEDED(svc::SetHeapSize(std::addressof(addr), svc::HeapSizeAlignment)));
DOCTEST_CHECK(heap[0] == 0xAA);
DOCTEST_CHECK(std::memcmp(heap, heap + 1, svc::HeapSizeAlignment - 1) == 0);
DOCTEST_CHECK(R_SUCCEEDED(svc::SetHeapSize(std::addressof(addr), 2 * svc::HeapSizeAlignment)));
DOCTEST_CHECK(heap[svc::HeapSizeAlignment] == 0x00);
DOCTEST_CHECK(std::memcmp(heap + svc::HeapSizeAlignment, heap + svc::HeapSizeAlignment + 1, svc::HeapSizeAlignment - 1) == 0);
DOCTEST_CHECK(R_SUCCEEDED(svc::SetHeapSize(std::addressof(addr), 0)));
}
}
}
| 6,283
|
C++
|
.cpp
| 97
| 55.061856
| 180
| 0.675012
|
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,289
|
test_preemption_priority.cpp
|
Atmosphere-NX_Atmosphere/tests/TestSvc/source/test_preemption_priority.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "util_common.hpp"
#include "util_scoped_heap.hpp"
namespace ams::test {
namespace {
constinit volatile bool g_spinloop;
void TestPreemptionPriorityThreadFunction(volatile bool *executed) {
/* While we should, note that we're executing. */
while (g_spinloop) {
__asm__ __volatile__("" ::: "memory");
*executed = true;
__asm__ __volatile__("" ::: "memory");
}
/* Exit the thread. */
svc::ExitThread();
}
}
DOCTEST_TEST_CASE( "The scheduler is preemptive at the preemptive priority and cooperative for all other priorities" ) {
/* Create heap. */
ScopedHeap heap(3 * os::MemoryPageSize);
DOCTEST_CHECK(R_SUCCEEDED(svc::SetMemoryPermission(heap.GetAddress() + os::MemoryPageSize, os::MemoryPageSize, svc::MemoryPermission_None)));
ON_SCOPE_EXIT {
DOCTEST_CHECK(R_SUCCEEDED(svc::SetMemoryPermission(heap.GetAddress() + os::MemoryPageSize, os::MemoryPageSize, svc::MemoryPermission_ReadWrite)));
};
const uintptr_t sp_0 = heap.GetAddress() + 1 * os::MemoryPageSize;
const uintptr_t sp_1 = heap.GetAddress() + 3 * os::MemoryPageSize;
for (s32 core = 0; core < NumCores; ++core) {
for (s32 priority = HighestTestPriority; priority <= LowestTestPriority; ++priority) {
svc::Handle thread_handles[2];
volatile bool thread_executed[2] = { false, false };
/* Start spinlooping. */
g_spinloop = true;
/* Create threads. */
DOCTEST_CHECK(R_SUCCEEDED(svc::CreateThread(thread_handles + 0, reinterpret_cast<uintptr_t>(&TestPreemptionPriorityThreadFunction), reinterpret_cast<uintptr_t>(thread_executed + 0), sp_0, priority, core)));
DOCTEST_CHECK(R_SUCCEEDED(svc::CreateThread(thread_handles + 1, reinterpret_cast<uintptr_t>(&TestPreemptionPriorityThreadFunction), reinterpret_cast<uintptr_t>(thread_executed + 1), sp_1, priority, core)));
/* Start threads. */
DOCTEST_CHECK(R_SUCCEEDED(svc::StartThread(thread_handles[0])));
DOCTEST_CHECK(R_SUCCEEDED(svc::StartThread(thread_handles[1])));
/* Wait long enough that we can be confident the threads have been balanced. */
svc::SleepThread(PreemptionTimeSpan.GetNanoSeconds() * 10);
/* Check that we're in a coherent state. */
if (IsPreemptionPriority(core, priority)) {
DOCTEST_CHECK((thread_executed[0] & thread_executed[1]));
} else {
DOCTEST_CHECK((thread_executed[0] ^ thread_executed[1]));
}
/* Stop spinlooping. */
g_spinloop = false;
/* Wait for threads to exit. */
s32 dummy;
DOCTEST_CHECK(R_SUCCEEDED(svc::WaitSynchronization(std::addressof(dummy), thread_handles + 0, 1, -1)));
DOCTEST_CHECK(R_SUCCEEDED(svc::WaitSynchronization(std::addressof(dummy), thread_handles + 1, 1, -1)));
/* Close thread handles. */
DOCTEST_CHECK(R_SUCCEEDED(svc::CloseHandle(thread_handles[0])));
DOCTEST_CHECK(R_SUCCEEDED(svc::CloseHandle(thread_handles[1])));
}
}
}
}
| 4,183
|
C++
|
.cpp
| 74
| 44.256757
| 226
| 0.602492
|
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,290
|
test_main.cpp
|
Atmosphere-NX_Atmosphere/tests/TestSvc/source/test_main.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#define DOCTEST_CONFIG_IMPLEMENT
#include "util_test_framework.hpp"
namespace ams {
namespace {
constexpr size_t MallocBufferSize = 16_MB;
alignas(os::MemoryPageSize) constinit u8 g_malloc_buffer[MallocBufferSize];
}
namespace hos {
bool IsUnitTestProgramForSetVersion() { return true; }
}
namespace init {
void InitializeSystemModuleBeforeConstructors() {
/* Catch has global-ctors which allocate, so we need to do this earlier than normal. */
init::InitializeAllocator(g_malloc_buffer, sizeof(g_malloc_buffer));
}
void InitializeSystemModule() { /* ... */ }
void FinalizeSystemModule() { /* ... */ }
void Startup() { /* ... */ }
}
void NORETURN Exit(int rc) {
AMS_UNUSED(rc);
AMS_ABORT("Exit called by immortal process");
}
void Main() {
/* Ensure our thread priority and core mask is correct. */
{
auto * const cur_thread = os::GetCurrentThread();
os::SetThreadCoreMask(cur_thread, 3, (1ul << 3));
os::ChangeThreadPriority(cur_thread, 0);
}
/* Run tests. */
{
doctest::Context ctx;
ctx.applyCommandLine(os::GetHostArgc(), os::GetHostArgv());
ctx.run();
}
AMS_INFINITE_LOOP();
/* This can never be reached. */
AMS_ASSUME(false);
}
}
namespace doctest {
namespace {
class OutputDebugStringStream : public std::stringbuf {
public:
OutputDebugStringStream() = default;
~OutputDebugStringStream() { pubsync(); }
int sync() override {
const auto message = str();
return R_SUCCEEDED(ams::svc::OutputDebugString(message.c_str(), message.length())) ? 0 : -1;
}
};
}
std::ostream& get_cout() {
static std::ostream ret(new OutputDebugStringStream);
return ret;
}
std::ostream& get_cerr() {
return get_cout();
}
}
| 2,765
|
C++
|
.cpp
| 77
| 28.272727
| 112
| 0.616773
|
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,291
|
test_thread_creation.cpp
|
Atmosphere-NX_Atmosphere/tests/TestSvc/source/test_thread_creation.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "util_common.hpp"
#include "util_scoped_heap.hpp"
namespace ams::test {
void TestThreadCreateRegistersOnFunctionEntry(void *ctx);
DOCTEST_TEST_CASE( "Creating a thread results in fixed register contents." ) {
/* Create heap. */
ScopedHeap heap(os::MemoryPageSize);
/* Create register buffer. */
u64 thread_registers[32];
std::memset(thread_registers, 0xCC, sizeof(thread_registers));
/* Create thread. */
svc::Handle thread_handle;
DOCTEST_CHECK(R_SUCCEEDED(svc::CreateThread(std::addressof(thread_handle), reinterpret_cast<uintptr_t>(&TestThreadCreateRegistersOnFunctionEntry), reinterpret_cast<uintptr_t>(thread_registers), heap.GetAddress() + os::MemoryPageSize, HighestTestPriority, NumCores - 1)));
/* Start thread. */
DOCTEST_CHECK(R_SUCCEEDED(svc::StartThread(thread_handle)));
/* Wait for thread to exit. */
s32 dummy;
DOCTEST_CHECK(R_SUCCEEDED(svc::WaitSynchronization(std::addressof(dummy), std::addressof(thread_handle), 1, -1)));
/* Close thread handle. */
DOCTEST_CHECK(R_SUCCEEDED(svc::CloseHandle(thread_handle)));
/* Check thread initial registers. */
for (size_t i = 0; i < util::size(thread_registers); ++i) {
if (i == 0) {
/* X0 is argument. */
DOCTEST_CHECK(thread_registers[i] == reinterpret_cast<uintptr_t>(thread_registers));
} else if (i == 18) {
/* X18 is an odd cfi value. */
DOCTEST_CHECK(thread_registers[i] != 0);
DOCTEST_CHECK((thread_registers[i] & 0x1) != 0);
} else if (i == 31) {
/* SP is user-provided sp. */
DOCTEST_CHECK(thread_registers[i] == (heap.GetAddress() + os::MemoryPageSize));
} else {
/* All other registers are zero. */
DOCTEST_CHECK(thread_registers[i] == 0);
}
}
}
}
| 2,659
|
C++
|
.cpp
| 55
| 40.381818
| 279
| 0.63815
|
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,292
|
test_sleep_thread.cpp
|
Atmosphere-NX_Atmosphere/tests/TestSvc/source/test_sleep_thread.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "util_common.hpp"
#include "util_scoped_heap.hpp"
namespace ams::test {
namespace {
constinit svc::Handle g_read_handles[3] = { svc::InvalidHandle, svc::InvalidHandle, svc::InvalidHandle };
constinit svc::Handle g_write_handles[3] = { svc::InvalidHandle, svc::InvalidHandle, svc::InvalidHandle };
constinit s64 g_thread_wait_ns;
constinit bool g_should_switch_threads;
constinit bool g_switched_threads;
constinit bool g_correct_switch_threads;
void WaitSynchronization(svc::Handle handle) {
s32 dummy;
R_ABORT_UNLESS(svc::WaitSynchronization(std::addressof(dummy), std::addressof(handle), 1, -1));
}
void TestYieldHigherOrSamePriorityThread() {
/* Wait to run. */
WaitSynchronization(g_read_handles[0]);
/* Reset our event. */
R_ABORT_UNLESS(svc::ClearEvent(g_read_handles[0]));
/* Signal the other thread's event. */
R_ABORT_UNLESS(svc::SignalEvent(g_write_handles[1]));
/* Wait, potentially yielding to the lower/same priority thread. */
g_switched_threads = false;
svc::SleepThread(g_thread_wait_ns);
/* Check whether we switched correctly. */
g_correct_switch_threads = g_should_switch_threads == g_switched_threads;
/* Exit. */
svc::ExitThread();
}
void TestYieldLowerOrSamePriorityThread() {
/* Signal thread the higher/same priority thread to run. */
R_ABORT_UNLESS(svc::SignalEvent(g_write_handles[0]));
/* Wait to run. */
WaitSynchronization(g_read_handles[1]);
/* Reset our event. */
R_ABORT_UNLESS(svc::ClearEvent(g_read_handles[1]));
/* We've switched to the lower/same priority thread. */
g_switched_threads = true;
/* Wait to be instructed to exit. */
WaitSynchronization(g_read_handles[2]);
/* Reset the exit signal. */
R_ABORT_UNLESS(svc::ClearEvent(g_read_handles[2]));
/* Exit. */
svc::ExitThread();
}
void TestYieldSamePriority(uintptr_t sp_higher, uintptr_t sp_lower) {
/* Test each core. */
for (s32 core = 0; core < NumCores; ++core) {
for (s32 priority = HighestTestPriority; priority <= LowestTestPriority && !IsPreemptionPriority(core, priority); ++priority) {
svc::Handle thread_handles[2];
/* Create threads. */
DOCTEST_CHECK(R_SUCCEEDED(svc::CreateThread(thread_handles + 0, reinterpret_cast<uintptr_t>(&TestYieldHigherOrSamePriorityThread), 0, sp_higher, priority, core)));
DOCTEST_CHECK(R_SUCCEEDED(svc::CreateThread(thread_handles + 1, reinterpret_cast<uintptr_t>(&TestYieldLowerOrSamePriorityThread), 0, sp_lower, priority, core)));
/* Start threads. */
DOCTEST_CHECK(R_SUCCEEDED(svc::StartThread(thread_handles[1])));
DOCTEST_CHECK(R_SUCCEEDED(svc::StartThread(thread_handles[0])));
/* Wait for higher priority thread. */
WaitSynchronization(thread_handles[0]);
DOCTEST_CHECK(R_SUCCEEDED(svc::CloseHandle(thread_handles[0])));
/* Signal the lower priority thread to exit. */
DOCTEST_CHECK(R_SUCCEEDED(svc::SignalEvent(g_write_handles[2])));
/* Wait for the lower priority thread. */
WaitSynchronization(thread_handles[1]);
DOCTEST_CHECK(R_SUCCEEDED(svc::CloseHandle(thread_handles[1])));
/* Check that the switch was correct. */
DOCTEST_CHECK(g_correct_switch_threads);
}
}
}
void TestYieldDifferentPriority(uintptr_t sp_higher, uintptr_t sp_lower) {
/* Test each core. */
for (s32 core = 0; core < NumCores; ++core) {
for (s32 priority = HighestTestPriority; priority < LowestTestPriority && !IsPreemptionPriority(core, priority); ++priority) {
svc::Handle thread_handles[2];
/* Create threads. */
DOCTEST_CHECK(R_SUCCEEDED(svc::CreateThread(thread_handles + 0, reinterpret_cast<uintptr_t>(&TestYieldHigherOrSamePriorityThread), 0, sp_higher, priority, core)));
DOCTEST_CHECK(R_SUCCEEDED(svc::CreateThread(thread_handles + 1, reinterpret_cast<uintptr_t>(&TestYieldLowerOrSamePriorityThread), 0, sp_lower, priority + 1, core)));
/* Start threads. */
DOCTEST_CHECK(R_SUCCEEDED(svc::StartThread(thread_handles[1])));
DOCTEST_CHECK(R_SUCCEEDED(svc::StartThread(thread_handles[0])));
/* Wait for higher priority thread. */
WaitSynchronization(thread_handles[0]);
DOCTEST_CHECK(R_SUCCEEDED(svc::CloseHandle(thread_handles[0])));
/* Signal the lower priority thread to exit. */
DOCTEST_CHECK(R_SUCCEEDED(svc::SignalEvent(g_write_handles[2])));
/* Wait for the lower priority thread. */
WaitSynchronization(thread_handles[1]);
DOCTEST_CHECK(R_SUCCEEDED(svc::CloseHandle(thread_handles[1])));
/* Check that the switch was correct. */
DOCTEST_CHECK(g_correct_switch_threads);
}
}
}
}
DOCTEST_TEST_CASE( "svc::SleepThread: Thread sleeps for time specified" ) {
for (s64 ns = 1; ns < TimeSpan::FromSeconds(1).GetNanoSeconds(); ns *= 2) {
const auto start = os::GetSystemTickOrdered();
svc::SleepThread(ns);
const auto end = os::GetSystemTickOrdered();
const s64 taken_ns = (end - start).ToTimeSpan().GetNanoSeconds();
DOCTEST_CHECK( taken_ns >= ns );
}
}
DOCTEST_TEST_CASE( "svc::SleepThread: Yield is behaviorally correct" ) {
/* Create events. */
for (size_t i = 0; i < util::size(g_write_handles); ++i) {
g_read_handles[i] = svc::InvalidHandle;
g_write_handles[i] = svc::InvalidHandle;
DOCTEST_CHECK(R_SUCCEEDED(svc::CreateEvent(g_write_handles + i, g_read_handles + i)));
}
ON_SCOPE_EXIT {
for (size_t i = 0; i < util::size(g_write_handles); ++i) {
DOCTEST_CHECK(R_SUCCEEDED(svc::CloseHandle(g_read_handles[i])));
DOCTEST_CHECK(R_SUCCEEDED(svc::CloseHandle(g_write_handles[i])));
g_read_handles[i] = svc::InvalidHandle;
g_write_handles[i] = svc::InvalidHandle;
}
};
/* Create heap. */
ScopedHeap heap(3 * os::MemoryPageSize);
DOCTEST_CHECK(R_SUCCEEDED(svc::SetMemoryPermission(heap.GetAddress() + os::MemoryPageSize, os::MemoryPageSize, svc::MemoryPermission_None)));
ON_SCOPE_EXIT {
DOCTEST_CHECK(R_SUCCEEDED(svc::SetMemoryPermission(heap.GetAddress() + os::MemoryPageSize, os::MemoryPageSize, svc::MemoryPermission_ReadWrite)));
};
const uintptr_t sp_higher = heap.GetAddress() + 1 * os::MemoryPageSize;
const uintptr_t sp_lower = heap.GetAddress() + 3 * os::MemoryPageSize;
DOCTEST_SUBCASE("svc::SleepThread: Yields do not switch to a thread of lower priority.") {
/* Test yield without migration. */
{
/* Configure for yield test. */
g_should_switch_threads = false;
g_thread_wait_ns = static_cast<s64>(svc::YieldType_WithoutCoreMigration);
TestYieldDifferentPriority(sp_higher, sp_lower);
}
/* Test yield with migration. */
{
/* Configure for yield test. */
g_should_switch_threads = false;
g_thread_wait_ns = static_cast<s64>(svc::YieldType_WithoutCoreMigration);
TestYieldDifferentPriority(sp_higher, sp_lower);
}
}
DOCTEST_SUBCASE("svc::SleepThread: ToAnyThread switches to a thread of same or lower priority.") {
/* Test to same priority. */
{
/* Configure for yield test. */
g_should_switch_threads = true;
g_thread_wait_ns = static_cast<s64>(svc::YieldType_ToAnyThread);
TestYieldSamePriority(sp_higher, sp_lower);
}
/* Test to lower priority. */
{
/* Configure for yield test. */
g_should_switch_threads = true;
g_thread_wait_ns = static_cast<s64>(svc::YieldType_ToAnyThread);
TestYieldDifferentPriority(sp_higher, sp_lower);
}
}
DOCTEST_SUBCASE("svc::SleepThread: Yield switches to another thread of same priority.") {
/* Test yield without migration. */
{
/* Configure for yield test. */
g_should_switch_threads = true;
g_thread_wait_ns = static_cast<s64>(svc::YieldType_WithoutCoreMigration);
TestYieldSamePriority(sp_higher, sp_lower);
}
/* Test yield with migration. */
{
/* Configure for yield test. */
g_should_switch_threads = true;
g_thread_wait_ns = static_cast<s64>(svc::YieldType_WithCoreMigration);
TestYieldSamePriority(sp_higher, sp_lower);
}
}
DOCTEST_SUBCASE("svc::SleepThread: Yield with bogus timeout does not switch to another thread same priority") {
/* Configure for yield test. */
g_should_switch_threads = false;
g_thread_wait_ns = INT64_C(-5);
TestYieldSamePriority(sp_higher, sp_lower);
}
}
}
| 10,774
|
C++
|
.cpp
| 198
| 41.272727
| 185
| 0.583349
|
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,293
|
test.cpp
|
Atmosphere-NX_Atmosphere/tests/TestOsEvents/source/test.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams {
namespace {
struct InterThreadSync {
util::Atomic<int> reader_state;
util::Atomic<int> writer_state;
os::EventType writer_ready_event;
os::EventType reader_ready_event;
union {
struct {
os::SystemEventType system_event_as_manual_clear_event;
os::SystemEventType system_event_as_manual_clear_interprocess_event;
os::SystemEventType system_event_as_auto_clear_event;
os::SystemEventType system_event_as_auto_clear_interprocess_event;
};
os::SystemEventType system_events[4];
};
};
bool IsManualClearEventIndex(size_t i) {
return i == 0 || i == 1;
}
alignas(os::MemoryPageSize) constinit u8 g_writer_thread_stack[16_KB];
alignas(os::MemoryPageSize) constinit u8 g_reader_thread_stack[16_KB];
void TestWriterThread(void *arg) {
/* Get the synchronization arguments. */
auto &sync = *static_cast<InterThreadSync *>(arg);
AMS_UNUSED(sync);
/* Wait for reader to be ready. */
os::WaitEvent(std::addressof(sync.reader_ready_event));
AMS_ABORT_UNLESS(sync.reader_state == 1);
/* Verify that all events can be signaled. */
for (size_t i = 0; i < util::size(sync.system_events); ++i) {
/* Set the event for this go. */
os::SignalSystemEvent(sync.system_events + i);
sync.writer_state = 1;
os::SignalEvent(std::addressof(sync.writer_ready_event));
/* Wait for the reader to finish. */
os::WaitEvent(std::addressof(sync.reader_ready_event));
AMS_ABORT_UNLESS(sync.reader_state == 1);
}
/* Verify that all events can be signaled (for TimedWait 0). */
for (size_t i = 0; i < util::size(sync.system_events); ++i) {
/* Set the event for this go. */
os::SignalSystemEvent(sync.system_events + i);
sync.writer_state = 2;
os::SignalEvent(std::addressof(sync.writer_ready_event));
/* Wait for the reader to finish. */
os::WaitEvent(std::addressof(sync.reader_ready_event));
AMS_ABORT_UNLESS(sync.reader_state == 2);
}
/* Verify that all events can be signaled (for TimedWait 2). */
for (size_t i = 0; i < util::size(sync.system_events); ++i) {
/* Set the event for this go. */
os::SignalSystemEvent(sync.system_events + i);
sync.writer_state = 3;
os::SignalEvent(std::addressof(sync.writer_ready_event));
/* Wait for the reader to finish. */
os::WaitEvent(std::addressof(sync.reader_ready_event));
AMS_ABORT_UNLESS(sync.reader_state == 3);
}
/* Verify that all events can be signaled (for True Wait). */
for (size_t i = 0; i < util::size(sync.system_events); ++i) {
/* Set the event for this go. */
os::SignalSystemEvent(sync.system_events + i);
sync.writer_state = 4;
os::SignalEvent(std::addressof(sync.writer_ready_event));
/* Wait for the reader to finish. */
os::WaitEvent(std::addressof(sync.reader_ready_event));
AMS_ABORT_UNLESS(sync.reader_state == 4);
}
/* Verify that all events can be signaled (TryWaitAny). */
for (size_t i = 0; i < util::size(sync.system_events); ++i) {
/* Set the event for this go. */
os::SignalSystemEvent(sync.system_events + i);
sync.writer_state = 5;
os::SignalEvent(std::addressof(sync.writer_ready_event));
/* Wait for the reader to finish. */
os::WaitEvent(std::addressof(sync.reader_ready_event));
AMS_ABORT_UNLESS(sync.reader_state == 5);
}
/* Verify that all events can be signaled (TimedWaitAny 0). */
for (size_t i = 0; i < util::size(sync.system_events); ++i) {
/* Set the event for this go. */
os::SignalSystemEvent(sync.system_events + i);
sync.writer_state = 6;
os::SignalEvent(std::addressof(sync.writer_ready_event));
/* Wait for the reader to finish. */
os::WaitEvent(std::addressof(sync.reader_ready_event));
AMS_ABORT_UNLESS(sync.reader_state == 6);
}
/* Verify that all events can be signaled (TimedWaitAny 2). */
for (size_t i = 0; i < util::size(sync.system_events); ++i) {
/* Set the event for this go. */
os::SignalSystemEvent(sync.system_events + i);
sync.writer_state = 7;
os::SignalEvent(std::addressof(sync.writer_ready_event));
/* Wait for the reader to finish. */
os::WaitEvent(std::addressof(sync.reader_ready_event));
AMS_ABORT_UNLESS(sync.reader_state == 7);
}
/* Verify that all events can be signaled (TrueWaitAny). */
for (size_t i = 0; i < util::size(sync.system_events); ++i) {
/* Set the event for this go. */
os::SignalSystemEvent(sync.system_events + i);
sync.writer_state = 8;
os::SignalEvent(std::addressof(sync.writer_ready_event));
/* Wait for the reader to finish. */
os::WaitEvent(std::addressof(sync.reader_ready_event));
AMS_ABORT_UNLESS(sync.reader_state == 8);
}
/* Verify that reader can receive without explicit sync. */
for (size_t i = 0; i < util::size(sync.system_events); ++i) {
/* Set the event for this go. */
os::SignalSystemEvent(sync.system_events + i);
sync.writer_state = 9;
}
/* Wait for the reader to finish. */
os::WaitEvent(std::addressof(sync.reader_ready_event));
AMS_ABORT_UNLESS(sync.reader_state == 9);
}
void TestReaderThread(void *arg) {
/* Get the synchronization arguments. */
auto &sync = *static_cast<InterThreadSync *>(arg);
AMS_UNUSED(sync);
/* Set up multi-wait objects. */
os::MultiWaitType mw;
os::MultiWaitHolderType holders[util::size(sync.system_events)];
os::InitializeMultiWait(std::addressof(mw));
for (size_t i = 0; i < util::size(sync.system_events); ++i) {
os::InitializeMultiWaitHolder(holders + i, sync.system_events + i);
os::LinkMultiWaitHolder(std::addressof(mw), holders + i);
}
ON_SCOPE_EXIT {
for (size_t i = 0; i < util::size(sync.system_events); ++i) {
os::UnlinkMultiWaitHolder(holders + i);
os::FinalizeMultiWaitHolder(holders + i);
}
os::FinalizeMultiWait(std::addressof(mw));
};
/* Sanity check: all events are non-signaled. */
for (size_t i = 0; i < util::size(sync.system_events); ++i) {
AMS_ABORT_UNLESS(os::TryWaitSystemEvent(sync.system_events + i) == false);
AMS_ABORT_UNLESS(os::TimedWaitSystemEvent(sync.system_events + i, TimeSpan::FromNanoSeconds(0)) == false);
AMS_ABORT_UNLESS(os::TimedWaitSystemEvent(sync.system_events + i, TimeSpan::FromMilliSeconds(2)) == false);
}
/* Sanity check that wait any does the right thing when nothing is signaled. */
AMS_ABORT_UNLESS(os::TryWaitAny(std::addressof(mw)) == nullptr);
AMS_ABORT_UNLESS(os::TimedWaitAny(std::addressof(mw), TimeSpan::FromNanoSeconds(0)) == nullptr);
AMS_ABORT_UNLESS(os::TimedWaitAny(std::addressof(mw), TimeSpan::FromNanoSeconds(2)) == nullptr);
/* Let writer know that we're ready. */
sync.reader_state = 1;
os::SignalEvent(std::addressof(sync.reader_ready_event));
/* Verify that we can receive signal on each event. */
for (size_t i = 0; i < util::size(sync.system_events); ++i) {
/* Wait for writer to do the relevant work */
os::WaitEvent(std::addressof(sync.writer_ready_event));
AMS_ABORT_UNLESS(sync.writer_state == 1);
/* Test all events. */
for (size_t n = 0; n < util::size(sync.system_events); ++n) {
if (i == n) {
AMS_ABORT_UNLESS(os::TryWaitSystemEvent(sync.system_events + n) == true);
if (IsManualClearEventIndex(n)) {
AMS_ABORT_UNLESS(os::TryWaitSystemEvent(sync.system_events + n) == true);
os::ClearSystemEvent(sync.system_events + n);
AMS_ABORT_UNLESS(os::TryWaitSystemEvent(sync.system_events + n) == false);
} else {
AMS_ABORT_UNLESS(os::TryWaitSystemEvent(sync.system_events + n) == false);
}
} else {
AMS_ABORT_UNLESS(os::TryWaitSystemEvent(sync.system_events + n) == false);
}
}
/* Let writer know we're done. */
sync.reader_state = 1;
os::SignalEvent(std::addressof(sync.reader_ready_event));
}
/* Verify that we can receive signal on each event (Timed Wait 0). */
for (size_t i = 0; i < util::size(sync.system_events); ++i) {
/* Wait for writer to do the relevant work */
os::WaitEvent(std::addressof(sync.writer_ready_event));
AMS_ABORT_UNLESS(sync.writer_state == 2);
/* Test all events. */
for (size_t n = 0; n < util::size(sync.system_events); ++n) {
if (i == n) {
AMS_ABORT_UNLESS(os::TimedWaitSystemEvent(sync.system_events + n, TimeSpan::FromMilliSeconds(0)) == true);
if (IsManualClearEventIndex(n)) {
AMS_ABORT_UNLESS(os::TimedWaitSystemEvent(sync.system_events + n, TimeSpan::FromMilliSeconds(0)) == true);
os::ClearSystemEvent(sync.system_events + n);
AMS_ABORT_UNLESS(os::TimedWaitSystemEvent(sync.system_events + n, TimeSpan::FromMilliSeconds(0)) == false);
} else {
AMS_ABORT_UNLESS(os::TimedWaitSystemEvent(sync.system_events + n, TimeSpan::FromMilliSeconds(0)) == false);
}
} else {
AMS_ABORT_UNLESS(os::TimedWaitSystemEvent(sync.system_events + n, TimeSpan::FromMilliSeconds(0)) == false);
}
}
/* Let writer know we're done. */
sync.reader_state = 2;
os::SignalEvent(std::addressof(sync.reader_ready_event));
}
/* Verify that we can receive signal on each event (Timed Wait 2). */
for (size_t i = 0; i < util::size(sync.system_events); ++i) {
/* Wait for writer to do the relevant work */
os::WaitEvent(std::addressof(sync.writer_ready_event));
AMS_ABORT_UNLESS(sync.writer_state == 3);
/* Test all events. */
for (size_t n = 0; n < util::size(sync.system_events); ++n) {
if (i == n) {
AMS_ABORT_UNLESS(os::TimedWaitSystemEvent(sync.system_events + n, TimeSpan::FromMilliSeconds(2)) == true);
if (IsManualClearEventIndex(n)) {
AMS_ABORT_UNLESS(os::TimedWaitSystemEvent(sync.system_events + n, TimeSpan::FromMilliSeconds(2)) == true);
os::ClearSystemEvent(sync.system_events + n);
AMS_ABORT_UNLESS(os::TimedWaitSystemEvent(sync.system_events + n, TimeSpan::FromMilliSeconds(2)) == false);
} else {
AMS_ABORT_UNLESS(os::TimedWaitSystemEvent(sync.system_events + n, TimeSpan::FromMilliSeconds(2)) == false);
}
} else {
AMS_ABORT_UNLESS(os::TimedWaitSystemEvent(sync.system_events + n, TimeSpan::FromMilliSeconds(2)) == false);
}
}
/* Let writer know we're done. */
sync.reader_state = 3;
os::SignalEvent(std::addressof(sync.reader_ready_event));
}
/* Verify that we can receive signal on each event. */
for (size_t i = 0; i < util::size(sync.system_events); ++i) {
/* Wait for writer to do the relevant work */
os::WaitEvent(std::addressof(sync.writer_ready_event));
AMS_ABORT_UNLESS(sync.writer_state == 4);
/* Test all events. */
for (size_t n = 0; n < util::size(sync.system_events); ++n) {
if (i == n) {
os::WaitSystemEvent(sync.system_events + n);
if (IsManualClearEventIndex(n)) {
AMS_ABORT_UNLESS(os::TryWaitSystemEvent(sync.system_events + n) == true);
os::WaitSystemEvent(sync.system_events + n);
os::ClearSystemEvent(sync.system_events + n);
AMS_ABORT_UNLESS(os::TryWaitSystemEvent(sync.system_events + n) == false);
} else {
AMS_ABORT_UNLESS(os::TryWaitSystemEvent(sync.system_events + n) == false);
}
} else {
AMS_ABORT_UNLESS(os::TryWaitSystemEvent(sync.system_events + n) == false);
}
}
/* Let writer know we're done. */
sync.reader_state = 4;
os::SignalEvent(std::addressof(sync.reader_ready_event));
}
/* Verify that we can receive signal on each event (TryWaitAny) */
for (size_t i = 0; i < util::size(sync.system_events); ++i) {
/* Wait for writer to do the relevant work */
os::WaitEvent(std::addressof(sync.writer_ready_event));
AMS_ABORT_UNLESS(sync.writer_state == 5);
/* Get the signaled holder. */
auto *signaled = os::TryWaitAny(std::addressof(mw));
AMS_ABORT_UNLESS(signaled == holders + i);
/* Test all events. */
for (size_t n = 0; n < util::size(sync.system_events); ++n) {
AMS_ABORT_UNLESS(os::TryWaitSystemEvent(sync.system_events + n) == (i == n));
os::ClearSystemEvent(sync.system_events + n);
AMS_ABORT_UNLESS(os::TryWaitSystemEvent(sync.system_events + n) == false);
}
/* Let writer know we're done. */
sync.reader_state = 5;
os::SignalEvent(std::addressof(sync.reader_ready_event));
}
/* Verify that we can receive signal on each event (TimedWaitAny 0) */
for (size_t i = 0; i < util::size(sync.system_events); ++i) {
/* Wait for writer to do the relevant work */
os::WaitEvent(std::addressof(sync.writer_ready_event));
AMS_ABORT_UNLESS(sync.writer_state == 6);
/* Get the signaled holder. */
auto *signaled = os::TimedWaitAny(std::addressof(mw), TimeSpan::FromMilliSeconds(0));
AMS_ABORT_UNLESS(signaled == holders + i);
/* Test all events. */
for (size_t n = 0; n < util::size(sync.system_events); ++n) {
AMS_ABORT_UNLESS(os::TryWaitSystemEvent(sync.system_events + n) == (i == n));
os::ClearSystemEvent(sync.system_events + n);
AMS_ABORT_UNLESS(os::TryWaitSystemEvent(sync.system_events + n) == false);
}
/* Let writer know we're done. */
sync.reader_state = 6;
os::SignalEvent(std::addressof(sync.reader_ready_event));
}
/* Verify that we can receive signal on each event (TimedWaitAny 2) */
for (size_t i = 0; i < util::size(sync.system_events); ++i) {
/* Wait for writer to do the relevant work */
os::WaitEvent(std::addressof(sync.writer_ready_event));
AMS_ABORT_UNLESS(sync.writer_state == 7);
/* Get the signaled holder. */
auto *signaled = os::TimedWaitAny(std::addressof(mw), TimeSpan::FromMilliSeconds(2));
AMS_ABORT_UNLESS(signaled == holders + i);
/* Test all events. */
for (size_t n = 0; n < util::size(sync.system_events); ++n) {
AMS_ABORT_UNLESS(os::TryWaitSystemEvent(sync.system_events + n) == (i == n));
os::ClearSystemEvent(sync.system_events + n);
AMS_ABORT_UNLESS(os::TryWaitSystemEvent(sync.system_events + n) == false);
}
/* Let writer know we're done. */
sync.reader_state = 7;
os::SignalEvent(std::addressof(sync.reader_ready_event));
}
/* Verify that we can receive signal on each event (True WaitAny) */
for (size_t i = 0; i < util::size(sync.system_events); ++i) {
/* Wait for writer to do the relevant work */
os::WaitEvent(std::addressof(sync.writer_ready_event));
AMS_ABORT_UNLESS(sync.writer_state == 8);
/* Get the signaled holder. */
auto *signaled = os::WaitAny(std::addressof(mw));
AMS_ABORT_UNLESS(signaled == holders + i);
/* Test all events. */
for (size_t n = 0; n < util::size(sync.system_events); ++n) {
AMS_ABORT_UNLESS(os::TryWaitSystemEvent(sync.system_events + n) == (i == n));
os::ClearSystemEvent(sync.system_events + n);
AMS_ABORT_UNLESS(os::TryWaitSystemEvent(sync.system_events + n) == false);
}
/* Let writer know we're done. */
sync.reader_state = 8;
os::SignalEvent(std::addressof(sync.reader_ready_event));
}
/* Verify that we can receive wait-any signals without sync. */
for (size_t i = 0; i < util::size(sync.system_events); ++i) {
auto *signaled = os::WaitAny(std::addressof(mw));
AMS_ABORT_UNLESS(signaled != nullptr);
const size_t n = signaled - holders;
AMS_ABORT_UNLESS(n < util::size(sync.system_events));
AMS_ABORT_UNLESS(os::TryWaitSystemEvent(sync.system_events + n) == true);
os::ClearSystemEvent(sync.system_events + n);
AMS_ABORT_UNLESS(os::TryWaitSystemEvent(sync.system_events + n) == false);
}
AMS_ABORT_UNLESS(os::TryWaitAny(std::addressof(mw)) == nullptr);
/* Let writer know we're done. */
sync.reader_state = 9;
os::SignalEvent(std::addressof(sync.reader_ready_event));
}
}
void Main() {
printf("Doing OS Event tests!\n");
{
/* Create the synchronization state. */
InterThreadSync sync_state;
sync_state.reader_state = 0;
sync_state.writer_state = 0;
os::InitializeEvent(std::addressof(sync_state.writer_ready_event), false, os::EventClearMode_AutoClear);
os::InitializeEvent(std::addressof(sync_state.reader_ready_event), false, os::EventClearMode_AutoClear);
R_ABORT_UNLESS(os::CreateSystemEvent(std::addressof(sync_state.system_event_as_manual_clear_event), os::EventClearMode_ManualClear, false));
R_ABORT_UNLESS(os::CreateSystemEvent(std::addressof(sync_state.system_event_as_manual_clear_interprocess_event), os::EventClearMode_ManualClear, true));
R_ABORT_UNLESS(os::CreateSystemEvent(std::addressof(sync_state.system_event_as_auto_clear_event), os::EventClearMode_AutoClear, false));
R_ABORT_UNLESS(os::CreateSystemEvent(std::addressof(sync_state.system_event_as_auto_clear_interprocess_event), os::EventClearMode_AutoClear, true));
/* Ensure we clean up the sync-state when done. */
ON_SCOPE_EXIT {
os::FinalizeEvent(std::addressof(sync_state.writer_ready_event));
os::FinalizeEvent(std::addressof(sync_state.reader_ready_event));
os::DestroySystemEvent(std::addressof(sync_state.system_event_as_manual_clear_event));
os::DestroySystemEvent(std::addressof(sync_state.system_event_as_manual_clear_interprocess_event));
os::DestroySystemEvent(std::addressof(sync_state.system_event_as_auto_clear_event));
os::DestroySystemEvent(std::addressof(sync_state.system_event_as_auto_clear_interprocess_event));
};
/* Create the threads. */
os::ThreadType reader_thread, writer_thread;
R_ABORT_UNLESS(os::CreateThread(std::addressof(reader_thread), TestReaderThread, std::addressof(sync_state), g_reader_thread_stack, sizeof(g_reader_thread_stack), os::DefaultThreadPriority));
R_ABORT_UNLESS(os::CreateThread(std::addressof(writer_thread), TestWriterThread, std::addressof(sync_state), g_writer_thread_stack, sizeof(g_writer_thread_stack), os::DefaultThreadPriority));
os::SetThreadNamePointer(std::addressof(reader_thread), "ReaderThread");
os::SetThreadNamePointer(std::addressof(writer_thread), "WriterThread");
/* Start the threads. */
os::StartThread(std::addressof(reader_thread));
os::StartThread(std::addressof(writer_thread));
/* Wait for the threads to complete. */
os::WaitThread(std::addressof(reader_thread));
os::WaitThread(std::addressof(writer_thread));
/* Destroy the threads. */
os::WaitThread(std::addressof(reader_thread));
os::WaitThread(std::addressof(writer_thread));
}
printf("All tests completed!\n");
}
}
| 23,576
|
C++
|
.cpp
| 393
| 43.905852
| 203
| 0.547812
|
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,294
|
fusee_main.cpp
|
Atmosphere-NX_Atmosphere/fusee/program/source/fusee_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 "fusee_display.hpp"
#include "sein/fusee_secure_initialize.hpp"
#include "sdram/fusee_sdram.hpp"
#include "mtc/fusee_mtc.hpp"
#include "fs/fusee_fs_api.hpp"
#include "fusee_overlay_manager.hpp"
#include "fusee_sd_card.hpp"
#include "fusee_fatal.hpp"
#include "fusee_external_package.hpp"
#include "fusee_setup_horizon.hpp"
#include "fusee_secmon_sync.hpp"
namespace ams::nxboot {
namespace {
constexpr const char ExternalPackageFilePath[] = "sdmc:/atmosphere/package3";
constinit fs::FileHandle g_package_file;
void OpenExternalPackage() {
Result result;
/* Open external package. */
if (R_FAILED((result = fs::OpenFile(std::addressof(g_package_file), ExternalPackageFilePath, fs::OpenMode_Read)))) {
ShowFatalError("Failed to open %s!\n", ExternalPackageFilePath);
}
/* Get file size. */
s64 file_size;
if (R_FAILED((result = fs::GetFileSize(std::addressof(file_size), g_package_file)))) {
ShowFatalError("Failed to get package3 size: 0x%08" PRIx32 "\n", result.GetValue());
}
/* Check file size. */
if (static_cast<size_t>(file_size) != ExternalPackageSize) {
ShowFatalError("package3 seems corrupted (size 0x%zx != 0x%zx)", static_cast<size_t>(file_size), ExternalPackageSize);
}
}
void ReadFullExternalPackage() {
Result result;
if (R_FAILED((result = fs::ReadFile(g_package_file, 0, const_cast<void *>(static_cast<const void *>(std::addressof(GetExternalPackage()))), ExternalPackageSize)))) {
ShowFatalError("Failed to read %s!\n", ExternalPackageFilePath);
}
}
void CloseExternalPackage() {
fs::CloseFile(g_package_file);
}
}
void Main() {
/* Perform secure hardware initialization. */
SecureInitialize(true);
/* Overclock the bpmp. */
clkrst::SetBpmpClockRate(fuse::GetSocType() == fuse::SocType_Mariko ? clkrst::BpmpClockRate_589MHz : clkrst::BpmpClockRate_576MHz);
/* Initialize Sdram. */
InitializeSdram();
/* Initialize cache. */
hw::InitializeDataCache();
/* Initialize SD card. */
{
Result result = InitializeSdCard();
if (R_FAILED(result)) {
ShowFatalError("Failed to initialize the SD card: 0x%08" PRIx32 "\n", result.GetValue());
}
}
/* Mount SD card. */
if (!fs::MountSdCard()) {
ShowFatalError("Failed to mount the SD card.");
}
/* If we have a fatal error, save and display it. */
SaveAndShowFatalError();
/* Open the external package. */
OpenExternalPackage();
/* Load the memory training overlay. */
LoadOverlay(g_package_file, OverlayId_MemoryTraining);
/* Do memory training. */
DoMemoryTraining();
/* Read the rest of the archive file. */
ReadFullExternalPackage();
/* Save the memory training overlay. */
SaveMemoryTrainingOverlay();
/* Initialize display (splash screen will be visible from this point onwards). */
InitializeDisplay();
ShowDisplay();
/* Close the external package. */
CloseExternalPackage();
/* Perform rest of the boot process. */
SetupAndStartHorizon();
/* Restore the memory training overlay. */
RestoreMemoryTrainingOverlay();
/* Restore memory clock rate. */
RestoreMemoryClockRate();
/* Restore secure monitor code. */
RestoreSecureMonitorOverlay();
/* Finalize display. */
FinalizeDisplay();
/* Finalize sd card. */
FinalizeSdCard();
/* Finalize the data cache. */
hw::FinalizeDataCache();
/* Downclock the bpmp. */
clkrst::SetBpmpClockRate(clkrst::BpmpClockRate_408MHz);
/* Signal to the secure monitor that we're done. */
SetBootloaderState(pkg1::BootloaderState_Done);
/* 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));
}
}
}
| 5,221
|
C++
|
.cpp
| 119
| 34.630252
| 177
| 0.617572
|
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,295
|
fusee_fatal.cpp
|
Atmosphere-NX_Atmosphere/fusee/program/source/fusee_fatal.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 "fusee_fatal.hpp"
#include "fusee_external_package.hpp"
#include "fs/fusee_fs_api.hpp"
namespace ams::nxboot {
namespace {
constexpr inline const uintptr_t PMC = secmon::MemoryRegionPhysicalDevicePmc.GetAddress();
Result SaveFatalErrorContext(const ams::impl::FatalErrorContext *ctx) {
/* Create and open the file. */
fs::FileHandle file;
{
/* Generate the file path. */
char path[0x40];
util::TSNPrintf(path, sizeof(path), "sdmc:/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();
}
}
NORETURN void RebootToSelf() {
/* Patch SDRAM init to perform an SVC immediately after second write. */
reg::Write(PMC + APBDEV_PMC_SCRATCH45, 0x2E38DFFF);
reg::Write(PMC + APBDEV_PMC_SCRATCH46, 0x6001DC28);
/* Set SVC handler to jump to reboot stub in IRAM. */
reg::Write(PMC + APBDEV_PMC_SCRATCH33, 0x4003F000);
reg::Write(PMC + APBDEV_PMC_SCRATCH40, 0x6000F208);
/* Set boot as warmboot. */
reg::Write(PMC + APBDEV_PMC_SCRATCH0, (1 << 0));
/* Copy reboot stub into high IRAM. */
std::memcpy(reinterpret_cast<void *>(0x4003F000), GetExternalPackage().reboot_stub, sizeof(GetExternalPackage().reboot_stub));
/* Copy our main payload into low IRAM. */
std::memcpy(reinterpret_cast<void *>(0x40010000), GetExternalPackage().fusee, sizeof(GetExternalPackage().fusee));
/* Reboot. */
reg::Write(PMC + APBDEV_PMC_CNTRL, PMC_REG_BITS_ENUM(CNTRL_MAIN_RESET, ENABLE));
/* Wait for the reboot to take. */
AMS_INFINITE_LOOP();
}
void SaveAndShowFatalError() {
/* Get the context (at static location in memory). */
ams::impl::FatalErrorContext *f_ctx = reinterpret_cast<ams::impl::FatalErrorContext *>(0x4003E000);
/* Check for valid magic. */
if (f_ctx->magic != ams::impl::FatalErrorContext::Magic) {
return;
}
/* Show the fatal error. */
ShowFatalError(f_ctx, SaveFatalErrorContext(f_ctx));
/* Clear the magic. */
f_ctx->magic = ~f_ctx->magic;
/* Wait for reboot. */
WaitForReboot();
}
void WaitForReboot() {
/* Wait for power button to be pressed. */
while (!pmic::IsPowerButtonPressed()) {
util::WaitMicroSeconds(100);
}
/* If not erista, just do a normal reboot. */
if (fuse::GetSocType() != fuse::SocType_Erista) {
/* Reboot. */
pmic::ShutdownSystem(true);
/* Wait for our reboot to complete. */
AMS_INFINITE_LOOP();
}
/* Reboot to self, if we can. */
if (GetExternalPackage().header.magic == ExternalPackageHeader::Magic) {
RebootToSelf();
} else {
/* Just do a normal reboot. */
pmic::ShutdownSystem(true);
/* Wait for our reboot to complete. */
AMS_INFINITE_LOOP();
}
}
}
| 4,261
|
C++
|
.cpp
| 96
| 35.614583
| 135
| 0.60817
|
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,296
|
fusee_malloc.cpp
|
Atmosphere-NX_Atmosphere/fusee/program/source/fusee_malloc.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 "fusee_malloc.hpp"
#include "fusee_fatal.hpp"
namespace ams::nxboot {
namespace {
constinit uintptr_t g_heap_address = 0xC1000000;
}
void *AllocateMemory(size_t size) {
/* Get the current heap address. */
void * const allocated = reinterpret_cast<void *>(g_heap_address);
/* Advance the current heap address. */
g_heap_address += size;
/* Return the allocated chunk. */
return allocated;
}
}
| 1,141
|
C++
|
.cpp
| 31
| 32.774194
| 76
| 0.705082
|
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,297
|
fusee_print.cpp
|
Atmosphere-NX_Atmosphere/fusee/program/source/fusee_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 "fusee_display.hpp"
#include "fusee_print.hpp"
namespace ams::nxboot {
namespace {
#include "fusee_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 VPrint(const char *fmt, std::va_list vl) {
/* Generate the string. */
char log_str[1_KB];
util::TVSNPrintf(log_str, sizeof(log_str), fmt, vl);
/* Print each character. */
const size_t len = std::strlen(log_str);
for (size_t i = 0; i < len; ++i) {
PutChar(log_str[i]);
}
}
void Print(const char *fmt, ...) {
std::va_list vl;
va_start(vl, fmt);
VPrint(fmt, vl);
va_end(vl);
}
}
| 4,277
|
C++
|
.cpp
| 103
| 30.650485
| 104
| 0.525656
|
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,298
|
fusee_key_derivation.cpp
|
Atmosphere-NX_Atmosphere/fusee/program/source/fusee_key_derivation.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 "fusee_key_derivation.hpp"
#include "fusee_fatal.hpp"
namespace ams::nxboot {
namespace {
alignas(se::AesBlockSize) constexpr inline const u8 MarikoMasterKekSource[se::AesBlockSize] = {
/* TODO: Update on next change of keys. */
0x31, 0xBE, 0x25, 0xFB, 0xDB, 0xB4, 0xEE, 0x49, 0x5C, 0x77, 0x05, 0xC2, 0x36, 0x9F, 0x34, 0x80
};
alignas(se::AesBlockSize) constexpr inline const u8 MarikoMasterKekSourceDev[se::AesBlockSize] = {
/* TODO: Update on next change of keys. */
0x65, 0x7B, 0x11, 0x46, 0x0E, 0xC2, 0x22, 0x5D, 0xB9, 0xF1, 0xF5, 0x00, 0xF9, 0x3E, 0x1F, 0x70
};
alignas(se::AesBlockSize) constexpr inline const u8 EristaMasterKekSource[se::AesBlockSize] = {
/* TODO: Update on next change of keys. */
0xD7, 0x63, 0x74, 0x46, 0x4E, 0xBA, 0x78, 0x0A, 0x7C, 0x9D, 0xB3, 0xE8, 0x7A, 0x3D, 0x71, 0xE3
};
alignas(se::AesBlockSize) constexpr inline const u8 KeyblobKeySource[se::AesBlockSize] = {
0xDF, 0x20, 0x6F, 0x59, 0x44, 0x54, 0xEF, 0xDC, 0x70, 0x74, 0x48, 0x3B, 0x0D, 0xED, 0x9F, 0xD3
};
alignas(se::AesBlockSize) constexpr inline const u8 MasterKeySource[se::AesBlockSize] = {
0xD8, 0xA2, 0x41, 0x0A, 0xC6, 0xC5, 0x90, 0x01, 0xC6, 0x1D, 0x6A, 0x26, 0x7C, 0x51, 0x3F, 0x3C
};
alignas(se::AesBlockSize) constexpr inline const u8 DeviceKeySource[se::AesBlockSize] = {
0x4F, 0x02, 0x5F, 0x0E, 0xB6, 0x6D, 0x11, 0x0E, 0xDC, 0x32, 0x7D, 0x41, 0x86, 0xC2, 0xF4, 0x78
};
alignas(se::AesBlockSize) constexpr inline const u8 DeviceMasterKeySourceKekSource[se::AesBlockSize] = {
0x0C, 0x91, 0x09, 0xDB, 0x93, 0x93, 0x07, 0x81, 0x07, 0x3C, 0xC4, 0x16, 0x22, 0x7C, 0x6C, 0x28
};
alignas(se::AesBlockSize) constexpr inline const u8 DeviceMasterKekSource[se::AesBlockSize] = {
0x2D, 0xC1, 0xF4, 0x8D, 0xF3, 0x5B, 0x69, 0x33, 0x42, 0x10, 0xAC, 0x65, 0xDA, 0x90, 0x46, 0x66
};
alignas(se::AesBlockSize) constexpr inline const u8 DeviceMasterKeySourceSources[pkg1::OldDeviceMasterKeyCount][se::AesBlockSize] = {
{ 0x8B, 0x4E, 0x1C, 0x22, 0x42, 0x07, 0xC8, 0x73, 0x56, 0x94, 0x08, 0x8B, 0xCC, 0x47, 0x0F, 0x5D }, /* 4.x Device Master Key Source Source. */
{ 0x6C, 0xEF, 0xC6, 0x27, 0x8B, 0xEC, 0x8A, 0x91, 0x99, 0xAB, 0x24, 0xAC, 0x4F, 0x1C, 0x8F, 0x1C }, /* 5.x Device Master Key Source Source. */
{ 0x70, 0x08, 0x1B, 0x97, 0x44, 0x64, 0xF8, 0x91, 0x54, 0x9D, 0xC6, 0x84, 0x8F, 0x1A, 0xB2, 0xE4 }, /* 6.x Device Master Key Source Source. */
{ 0x8E, 0x09, 0x1F, 0x7A, 0xBB, 0xCA, 0x6A, 0xFB, 0xB8, 0x9B, 0xD5, 0xC1, 0x25, 0x9C, 0xA9, 0x17 }, /* 6.2.0 Device Master Key Source Source. */
{ 0x8F, 0x77, 0x5A, 0x96, 0xB0, 0x94, 0xFD, 0x8D, 0x28, 0xE4, 0x19, 0xC8, 0x16, 0x1C, 0xDB, 0x3D }, /* 7.0.0 Device Master Key Source Source. */
{ 0x67, 0x62, 0xD4, 0x8E, 0x55, 0xCF, 0xFF, 0x41, 0x31, 0x15, 0x3B, 0x24, 0x0C, 0x7C, 0x07, 0xAE }, /* 8.1.0 Device Master Key Source Source. */
{ 0x4A, 0xC3, 0x4E, 0x14, 0x8B, 0x96, 0x4A, 0xD5, 0xD4, 0x99, 0x73, 0xC4, 0x45, 0xAB, 0x8B, 0x49 }, /* 9.0.0 Device Master Key Source Source. */
{ 0x14, 0xB8, 0x74, 0x12, 0xCB, 0xBD, 0x0B, 0x8F, 0x20, 0xFB, 0x30, 0xDA, 0x27, 0xE4, 0x58, 0x94 }, /* 9.1.0 Device Master Key Source Source. */
{ 0xAA, 0xFD, 0xBC, 0xBB, 0x25, 0xC3, 0xA4, 0xEF, 0xE3, 0xEE, 0x58, 0x53, 0xB7, 0xF8, 0xDD, 0xD6 }, /* 12.1.0 Device Master Key Source Source. */
{ 0xE4, 0xF3, 0x45, 0x6F, 0x18, 0xA1, 0x89, 0xF8, 0xDA, 0x4C, 0x64, 0x75, 0x68, 0xE6, 0xBD, 0x4F }, /* 13.0.0 Device Master Key Source Source. */
{ 0x5B, 0x94, 0x63, 0xF7, 0xAD, 0x96, 0x1B, 0xA6, 0x23, 0x30, 0x06, 0x4D, 0x01, 0xE4, 0xCE, 0x1D }, /* 14.0.0 Device Master Key Source Source. */
{ 0x5E, 0xC9, 0xC5, 0x0A, 0xD0, 0x5F, 0x8B, 0x7B, 0xA7, 0x39, 0xEA, 0xBC, 0x60, 0x0F, 0x74, 0xE6 }, /* 15.0.0 Device Master Key Source Source. */
{ 0xEA, 0x90, 0x6E, 0xA8, 0xAE, 0x92, 0x99, 0x64, 0x36, 0xC1, 0xF3, 0x1C, 0xC6, 0x32, 0x83, 0x8C }, /* 16.0.0 Device Master Key Source Source. */
{ 0xDA, 0xB9, 0xD6, 0x77, 0x52, 0x2D, 0x1F, 0x78, 0x73, 0xC9, 0x98, 0x5B, 0x06, 0xFE, 0xA0, 0x52 }, /* 17.0.0 Device Master Key Source Source. */
{ 0x14, 0xF5, 0xA5, 0xD0, 0x73, 0x6D, 0x44, 0x80, 0x5F, 0x31, 0x5A, 0x8F, 0x1E, 0xD4, 0x0D, 0x63 }, /* 18.0.0 Device Master Key Source Source. */
{ 0x07, 0x38, 0x9A, 0xEC, 0x9C, 0xBD, 0x50, 0x4A, 0x4C, 0x1F, 0x04, 0xDA, 0x40, 0x68, 0x29, 0xE3 }, /* 19.0.0 Device Master Key Source Source. */
};
alignas(se::AesBlockSize) constexpr inline const u8 DeviceMasterKekSources[pkg1::OldDeviceMasterKeyCount][se::AesBlockSize] = {
{ 0x88, 0x62, 0x34, 0x6E, 0xFA, 0xF7, 0xD8, 0x3F, 0xE1, 0x30, 0x39, 0x50, 0xF0, 0xB7, 0x5D, 0x5D }, /* 4.x Device Master Kek Source. */
{ 0x06, 0x1E, 0x7B, 0xE9, 0x6D, 0x47, 0x8C, 0x77, 0xC5, 0xC8, 0xE7, 0x94, 0x9A, 0xA8, 0x5F, 0x2E }, /* 5.x Device Master Kek Source. */
{ 0x99, 0xFA, 0x98, 0xBD, 0x15, 0x1C, 0x72, 0xFD, 0x7D, 0x9A, 0xD5, 0x41, 0x00, 0xFD, 0xB2, 0xEF }, /* 6.x Device Master Kek Source. */
{ 0x81, 0x3C, 0x6C, 0xBF, 0x5D, 0x21, 0xDE, 0x77, 0x20, 0xD9, 0x6C, 0xE3, 0x22, 0x06, 0xAE, 0xBB }, /* 6.2.0 Device Master Kek Source. */
{ 0x86, 0x61, 0xB0, 0x16, 0xFA, 0x7A, 0x9A, 0xEA, 0xF6, 0xF5, 0xBE, 0x1A, 0x13, 0x5B, 0x6D, 0x9E }, /* 7.0.0 Device Master Kek Source. */
{ 0xA6, 0x81, 0x71, 0xE7, 0xB5, 0x23, 0x74, 0xB0, 0x39, 0x8C, 0xB7, 0xFF, 0xA0, 0x62, 0x9F, 0x8D }, /* 8.1.0 Device Master Kek Source. */
{ 0x03, 0xE7, 0xEB, 0x43, 0x1B, 0xCF, 0x5F, 0xB5, 0xED, 0xDC, 0x97, 0xAE, 0x21, 0x8D, 0x19, 0xED }, /* 9.0.0 Device Master Kek Source. */
{ 0xCE, 0xFE, 0x41, 0x0F, 0x46, 0x9A, 0x30, 0xD6, 0xF2, 0xE9, 0x0C, 0x6B, 0xB7, 0x15, 0x91, 0x36 }, /* 9.1.0 Device Master Kek Source. */
{ 0xC2, 0x65, 0x34, 0x6E, 0xC7, 0xC6, 0x5D, 0x97, 0x3E, 0x34, 0x5C, 0x6B, 0xB3, 0x7E, 0xC6, 0xE3 }, /* 12.1.0 Device Master Kek Source. */
{ 0x77, 0x52, 0x92, 0xF0, 0xAA, 0xE3, 0xFB, 0xE0, 0x60, 0x16, 0xB3, 0x78, 0x68, 0x53, 0xF7, 0xA8 }, /* 13.0.0 Device Master Kek Source. */
{ 0x67, 0xD5, 0xD6, 0x0C, 0x08, 0xF5, 0xA3, 0x11, 0xBD, 0x6D, 0x5A, 0xEB, 0x96, 0x24, 0xB0, 0xD2 }, /* 14.0.0 Device Master Kek Source. */
{ 0x7C, 0x30, 0xED, 0x8B, 0x39, 0x25, 0x2C, 0x08, 0x8F, 0x48, 0xDC, 0x28, 0xE6, 0x1A, 0x6B, 0x49 }, /* 15.0.0 Device Master Kek Source. */
{ 0xF0, 0xF3, 0xFF, 0x52, 0x75, 0x2F, 0xBA, 0x4D, 0x09, 0x72, 0x30, 0x89, 0xA9, 0xDF, 0xFE, 0x1F }, /* 16.0.0 Device Master Kek Source. */
{ 0x21, 0xD6, 0x35, 0xF1, 0x0F, 0x7A, 0xF0, 0x5D, 0xDF, 0x79, 0x1C, 0x7A, 0xE4, 0x32, 0x82, 0x9E }, /* 17.0.0 Device Master Kek Source. */
{ 0xE7, 0x85, 0x8C, 0xA2, 0xF4, 0x49, 0xCB, 0x07, 0xD1, 0x8E, 0x48, 0x1B, 0xE8, 0x1E, 0x28, 0x3B }, /* 18.0.0 Device Master Kek Source. */
{ 0x9B, 0xA5, 0xFD, 0x74, 0x7F, 0xCD, 0x23, 0xD1, 0xD9, 0xBD, 0x6C, 0x51, 0x72, 0x5F, 0x3D, 0x1F }, /* 19.0.0 Device Master Kek Source. */
};
alignas(se::AesBlockSize) constexpr inline const u8 DeviceMasterKekSourcesDev[pkg1::OldDeviceMasterKeyCount][se::AesBlockSize] = {
{ 0xD6, 0xBD, 0x9F, 0xC6, 0x18, 0x09, 0xE1, 0x96, 0x20, 0x39, 0x60, 0xD2, 0x89, 0x83, 0x31, 0x34 }, /* 4.x Device Master Kek Source. */
{ 0x59, 0x2D, 0x20, 0x69, 0x33, 0xB5, 0x17, 0xBA, 0xCF, 0xB1, 0x4E, 0xFD, 0xE4, 0xC2, 0x7B, 0xA8 }, /* 5.x Device Master Kek Source. */
{ 0xF6, 0xD8, 0x59, 0x63, 0x8F, 0x47, 0xCB, 0x4A, 0xD8, 0x74, 0x05, 0x7F, 0x88, 0x92, 0x33, 0xA5 }, /* 6.x Device Master Kek Source. */
{ 0x20, 0xAB, 0xF2, 0x0F, 0x05, 0xE3, 0xDE, 0x2E, 0xA1, 0xFB, 0x37, 0x5E, 0x8B, 0x22, 0x1A, 0x38 }, /* 6.2.0 Device Master Kek Source. */
{ 0x60, 0xAE, 0x56, 0x68, 0x11, 0xE2, 0x0C, 0x99, 0xDE, 0x05, 0xAE, 0x68, 0x78, 0x85, 0x04, 0xAE }, /* 7.0.0 Device Master Kek Source. */
{ 0x94, 0xD6, 0xA8, 0xC0, 0x95, 0xAF, 0xD0, 0xA6, 0x27, 0x53, 0x5E, 0xE5, 0x8E, 0x70, 0x1F, 0x87 }, /* 8.1.0 Device Master Kek Source. */
{ 0x61, 0x6A, 0x88, 0x21, 0xA3, 0x52, 0xB0, 0x19, 0x16, 0x25, 0xA4, 0xE3, 0x4C, 0x54, 0x02, 0x0F }, /* 9.0.0 Device Master Kek Source. */
{ 0x9D, 0xB1, 0xAE, 0xCB, 0xF6, 0xF6, 0xE3, 0xFE, 0xAB, 0x6F, 0xCB, 0xAF, 0x38, 0x03, 0xFC, 0x7B }, /* 9.1.0 Device Master Kek Source. */
{ 0xC4, 0xBB, 0xF3, 0x9F, 0xA3, 0xAA, 0x00, 0x99, 0x7C, 0x97, 0xAD, 0x91, 0x8F, 0xE8, 0x45, 0xCB }, /* 12.1.0 Device Master Kek Source. */
{ 0x20, 0x20, 0xAA, 0xFB, 0x89, 0xC2, 0xF0, 0x70, 0xB5, 0xE0, 0xA3, 0x11, 0x8A, 0x29, 0x8D, 0x0F }, /* 13.0.0 Device Master Kek Source. */
{ 0xCE, 0x14, 0x74, 0x66, 0x98, 0xA8, 0x6D, 0x7D, 0xBD, 0x54, 0x91, 0x68, 0x5F, 0x1D, 0x0E, 0xEA }, /* 14.0.0 Device Master Kek Source. */
{ 0xAE, 0x05, 0x48, 0x65, 0xAB, 0x17, 0x9D, 0x3D, 0x51, 0xB7, 0x56, 0xBD, 0x9B, 0x0B, 0x5B, 0x6E }, /* 15.0.0 Device Master Kek Source. */
{ 0xFF, 0xF6, 0x4B, 0x0F, 0xFF, 0x0D, 0xC0, 0x4F, 0x56, 0x8A, 0x40, 0x74, 0x67, 0xC5, 0xFE, 0x9F }, /* 16.0.0 Device Master Kek Source. */
{ 0x4E, 0xCE, 0x7B, 0x2A, 0xEA, 0x2E, 0x3D, 0x16, 0xD5, 0x2A, 0xDE, 0xF6, 0xF8, 0x6A, 0x7D, 0x43 }, /* 17.0.0 Device Master Kek Source. */
{ 0x3B, 0x00, 0x89, 0xD7, 0xA9, 0x9E, 0xB7, 0x70, 0x86, 0x00, 0xC3, 0x49, 0x52, 0x8C, 0xA4, 0xAF }, /* 18.0.0 Device Master Kek Source. */
{ 0xAE, 0x78, 0x36, 0xB6, 0x91, 0xEB, 0xAF, 0x9C, 0x18, 0xF1, 0xC0, 0xD5, 0x8A, 0x0C, 0x7C, 0xA1 }, /* 19.0.0 Device Master Kek Source. */
};
alignas(se::AesBlockSize) constexpr inline const u8 MasterKeySources[pkg1::KeyGeneration_Count][se::AesBlockSize] = {
{ 0x0C, 0xF0, 0x59, 0xAC, 0x85, 0xF6, 0x26, 0x65, 0xE1, 0xE9, 0x19, 0x55, 0xE6, 0xF2, 0x67, 0x3D }, /* Zeroes encrypted with Master Key 00. */
{ 0x29, 0x4C, 0x04, 0xC8, 0xEB, 0x10, 0xED, 0x9D, 0x51, 0x64, 0x97, 0xFB, 0xF3, 0x4D, 0x50, 0xDD }, /* Master key 00 encrypted with Master key 01. */
{ 0xDE, 0xCF, 0xEB, 0xEB, 0x10, 0xAE, 0x74, 0xD8, 0xAD, 0x7C, 0xF4, 0x9E, 0x62, 0xE0, 0xE8, 0x72 }, /* Master key 01 encrypted with Master key 02. */
{ 0x0A, 0x0D, 0xDF, 0x34, 0x22, 0x06, 0x6C, 0xA4, 0xE6, 0xB1, 0xEC, 0x71, 0x85, 0xCA, 0x4E, 0x07 }, /* Master key 02 encrypted with Master key 03. */
{ 0x6E, 0x7D, 0x2D, 0xC3, 0x0F, 0x59, 0xC8, 0xFA, 0x87, 0xA8, 0x2E, 0xD5, 0x89, 0x5E, 0xF3, 0xE9 }, /* Master key 03 encrypted with Master key 04. */
{ 0xEB, 0xF5, 0x6F, 0x83, 0x61, 0x9E, 0xF8, 0xFA, 0xE0, 0x87, 0xD7, 0xA1, 0x4E, 0x25, 0x36, 0xEE }, /* Master key 04 encrypted with Master key 05. */
{ 0x1E, 0x1E, 0x22, 0xC0, 0x5A, 0x33, 0x3C, 0xB9, 0x0B, 0xA9, 0x03, 0x04, 0xBA, 0xDB, 0x07, 0x57 }, /* Master key 05 encrypted with Master key 06. */
{ 0xA4, 0xD4, 0x52, 0x6F, 0xD1, 0xE4, 0x36, 0xAA, 0x9F, 0xCB, 0x61, 0x27, 0x1C, 0x67, 0x65, 0x1F }, /* Master key 06 encrypted with Master key 07. */
{ 0xEA, 0x60, 0xB3, 0xEA, 0xCE, 0x8F, 0x24, 0x46, 0x7D, 0x33, 0x9C, 0xD1, 0xBC, 0x24, 0x98, 0x29 }, /* Master key 07 encrypted with Master key 08. */
{ 0x4D, 0xD9, 0x98, 0x42, 0x45, 0x0D, 0xB1, 0x3C, 0x52, 0x0C, 0x9A, 0x44, 0xBB, 0xAD, 0xAF, 0x80 }, /* Master key 08 encrypted with Master key 09. */
{ 0xB8, 0x96, 0x9E, 0x4A, 0x00, 0x0D, 0xD6, 0x28, 0xB3, 0xD1, 0xDB, 0x68, 0x5F, 0xFB, 0xE1, 0x2A }, /* Master key 09 encrypted with Master key 0A. */
{ 0xC1, 0x8D, 0x16, 0xBB, 0x2A, 0xE4, 0x1D, 0xD4, 0xC2, 0xC1, 0xB6, 0x40, 0x94, 0x35, 0x63, 0x98 }, /* Master key 0A encrypted with Master key 0B. */
{ 0xA3, 0x24, 0x65, 0x75, 0xEA, 0xCC, 0x6E, 0x8D, 0xFB, 0x5A, 0x16, 0x50, 0x74, 0xD2, 0x15, 0x06 }, /* Master key 0B encrypted with Master key 0C. */
{ 0x83, 0x67, 0xAF, 0x01, 0xCF, 0x93, 0xA1, 0xAB, 0x80, 0x45, 0xF7, 0x3F, 0x72, 0xFD, 0x3B, 0x38 }, /* Master key 0C encrypted with Master key 0D. */
{ 0xB1, 0x81, 0xA6, 0x0D, 0x72, 0xC7, 0xEE, 0x15, 0x21, 0xF3, 0xC0, 0xB5, 0x6B, 0x61, 0x6D, 0xE7 }, /* Master key 0D encrypted with Master key 0E. */
{ 0xAF, 0x11, 0x4C, 0x67, 0x17, 0x7A, 0x52, 0x43, 0xF7, 0x70, 0x2F, 0xC7, 0xEF, 0x81, 0x72, 0x16 }, /* Master key 0E encrypted with Master key 0F. */
{ 0x25, 0x12, 0x8B, 0xCB, 0xB5, 0x46, 0xA1, 0xF8, 0xE0, 0x52, 0x15, 0xB7, 0x0B, 0x57, 0x00, 0xBD }, /* Master key 0F encrypted with Master key 10. */
{ 0x58, 0x15, 0xD2, 0xF6, 0x8A, 0xE8, 0x19, 0xAB, 0xFB, 0x2D, 0x52, 0x9D, 0xE7, 0x55, 0xF3, 0x93 }, /* Master key 10 encrypted with Master key 11. */
{ 0x4A, 0x01, 0x3B, 0xC7, 0x44, 0x6E, 0x45, 0xBD, 0xE6, 0x5E, 0x2B, 0xEC, 0x07, 0x37, 0x52, 0x86 }, /* Master key 11 encrypted with Master key 12. */
};
alignas(se::AesBlockSize) constexpr inline const u8 MasterKeySourcesDev[pkg1::KeyGeneration_Count][se::AesBlockSize] = {
{ 0x46, 0x22, 0xB4, 0x51, 0x9A, 0x7E, 0xA7, 0x7F, 0x62, 0xA1, 0x1F, 0x8F, 0xC5, 0x3A, 0xDB, 0xFE }, /* Zeroes encrypted with Master Key 00. */
{ 0x39, 0x33, 0xF9, 0x31, 0xBA, 0xE4, 0xA7, 0x21, 0x2C, 0xDD, 0xB7, 0xD8, 0xB4, 0x4E, 0x37, 0x23 }, /* Master key 00 encrypted with Master key 01. */
{ 0x97, 0x29, 0xB0, 0x32, 0x43, 0x14, 0x8C, 0xA6, 0x85, 0xE9, 0x5A, 0x94, 0x99, 0x39, 0xAC, 0x5D }, /* Master key 01 encrypted with Master key 02. */
{ 0x2C, 0xCA, 0x9C, 0x31, 0x1E, 0x07, 0xB0, 0x02, 0x97, 0x0A, 0xD8, 0x03, 0xA2, 0x76, 0x3F, 0xA3 }, /* Master key 02 encrypted with Master key 03. */
{ 0x9B, 0x84, 0x76, 0x14, 0x72, 0x94, 0x52, 0xCB, 0x54, 0x92, 0x9B, 0xC4, 0x8C, 0x5B, 0x0F, 0xBA }, /* Master key 03 encrypted with Master key 04. */
{ 0x78, 0xD5, 0xF1, 0x20, 0x3D, 0x16, 0xE9, 0x30, 0x32, 0x27, 0x34, 0x6F, 0xCF, 0xE0, 0x27, 0xDC }, /* Master key 04 encrypted with Master key 05. */
{ 0x6F, 0xD2, 0x84, 0x1D, 0x05, 0xEC, 0x40, 0x94, 0x5F, 0x18, 0xB3, 0x81, 0x09, 0x98, 0x8D, 0x4E }, /* Master key 05 encrypted with Master key 06. */
{ 0x37, 0xAF, 0xAB, 0x35, 0x79, 0x09, 0xD9, 0x48, 0x29, 0xD2, 0xDB, 0xA5, 0xA5, 0xF5, 0x30, 0x19 }, /* Master key 06 encrypted with Master key 07. */
{ 0xEC, 0xE1, 0x46, 0x89, 0x37, 0xFD, 0xD2, 0x15, 0x8C, 0x3F, 0x24, 0x82, 0xEF, 0x49, 0x68, 0x04 }, /* Master key 07 encrypted with Master key 08. */
{ 0x43, 0x3D, 0xC5, 0x3B, 0xEF, 0x91, 0x02, 0x21, 0x61, 0x54, 0x63, 0x8A, 0x35, 0xE7, 0xCA, 0xEE }, /* Master key 08 encrypted with Master key 09. */
{ 0x6C, 0x2E, 0xCD, 0xB3, 0x34, 0x61, 0x77, 0xF5, 0xF9, 0xB1, 0xDD, 0x61, 0x98, 0x19, 0x3E, 0xD4 }, /* Master key 09 encrypted with Master key 0A. */
{ 0x21, 0x88, 0x6B, 0x10, 0x9E, 0x83, 0xD6, 0x52, 0xAB, 0x08, 0xDB, 0x6D, 0x39, 0xFF, 0x1C, 0x9C }, /* Master key 0A encrypted with Master key 0B. */
{ 0x8A, 0xCE, 0xC4, 0x7F, 0xBE, 0x08, 0x61, 0x88, 0xD3, 0x73, 0x64, 0x51, 0xE2, 0xB6, 0x53, 0x15 }, /* Master key 0B encrypted with Master key 0C. */
{ 0x08, 0xE0, 0xF4, 0xBE, 0xAA, 0x6E, 0x5A, 0xC3, 0xA6, 0xBC, 0xFE, 0xB9, 0xE2, 0xA3, 0x24, 0x12 }, /* Master key 0C encrypted with Master key 0D. */
{ 0xD6, 0x80, 0x98, 0xC0, 0xFA, 0xC7, 0x13, 0xCB, 0x93, 0xD2, 0x0B, 0x82, 0x4C, 0xA1, 0x7B, 0x8D }, /* Master key 0D encrypted with Master key 0E. */
{ 0x78, 0x66, 0x19, 0xBD, 0x86, 0xE7, 0xC1, 0x09, 0x9B, 0x6F, 0x92, 0xB2, 0x58, 0x7D, 0xCF, 0x26 }, /* Master key 0E encrypted with Master key 0F. */
{ 0x39, 0x1E, 0x7E, 0xF8, 0x7E, 0x73, 0xEA, 0x6F, 0xAF, 0x00, 0x3A, 0xB4, 0xAA, 0xB8, 0xB7, 0x59 }, /* Master key 0F encrypted with Master key 10. */
{ 0x0C, 0x75, 0x39, 0x15, 0x53, 0xEA, 0x81, 0x11, 0xA3, 0xE0, 0xDC, 0x3D, 0x0E, 0x76, 0xC6, 0xB8 }, /* Master key 10 encrypted with Master key 11. */
{ 0x90, 0x64, 0xF9, 0x08, 0x29, 0x88, 0xD4, 0xDC, 0x73, 0xA4, 0xA1, 0x13, 0x9E, 0x59, 0x85, 0xA0 }, /* Master key 11 encrypted with Master key 12. */
};
alignas(se::AesBlockSize) constinit u8 MasterKeys[pkg1::OldMasterKeyCount][se::AesBlockSize] = {};
alignas(se::AesBlockSize) constinit u8 DeviceMasterKeys[pkg1::OldDeviceMasterKeyCount][se::AesBlockSize] = {};
void DeriveMasterKeys(bool is_prod) {
/* Decrypt the vector chain from current generation to start. */
int slot = pkg1::AesKeySlot_BootloaderMaster;
for (int i = pkg1::KeyGeneration_Current; i > pkg1::KeyGeneration_1_0_0; --i) {
/* Decrypt the old master key. */
se::DecryptAes128(MasterKeys[i - 1], se::AesBlockSize, slot, is_prod ? MasterKeySources[i] : MasterKeySourcesDev[i], se::AesBlockSize);
/* Set the old master key into a temporary keyslot. */
se::SetAesKey(pkg1::AesKeySlot_BootloaderTemporary, MasterKeys[i - 1], se::AesBlockSize);
/* Perform the next decryption with the older master key. */
slot = pkg1::AesKeySlot_BootloaderTemporary;
}
/* Decrypt the final vector. */
alignas(se::AesBlockSize) u8 test_vector[se::AesBlockSize];
se::DecryptAes128(test_vector, se::AesBlockSize, pkg1::AesKeySlot_BootloaderTemporary, is_prod ? MasterKeySources[pkg1::KeyGeneration_1_0_0] : MasterKeySourcesDev[pkg1::KeyGeneration_1_0_0], se::AesBlockSize);
/* Verify the vector chain. */
alignas(se::AesBlockSize) constexpr u8 ZeroBlock[se::AesBlockSize] = {};
if (!crypto::IsSameBytes(ZeroBlock, test_vector, se::AesBlockSize)) {
ShowFatalError("Failed to derive master keys!\n");
}
}
void DeriveDeviceMasterKeys(fuse::SocType soc_type, bool is_prod) {
alignas(se::AesBlockSize) u8 work_block[se::AesBlockSize];
/* 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. */
se::SetAesKey(pkg1::AesKeySlot_BootloaderTemporary, MasterKeys[pkg1::KeyGeneration_1_0_0], se::AesBlockSize);
/* Decrypt the device master kek for the generation. */
se::SetEncryptedAesKey128(pkg1::AesKeySlot_BootloaderTemporary, pkg1::AesKeySlot_BootloaderTemporary, is_prod ? DeviceMasterKekSources[i] : DeviceMasterKekSourcesDev[i], se::AesBlockSize);
/* Decrypt the device master key source into the work block. */
se::DecryptAes128(work_block, se::AesBlockSize, pkg1::AesKeySlot_DeviceMasterKeySourceKekErista, DeviceMasterKeySourceSources[i], se::AesBlockSize);
if (generation == pkg1::KeyGeneration_Current) {
se::SetEncryptedAesKey128(pkg1::AesKeySlot_BootloaderDeviceMaster, pkg1::AesKeySlot_BootloaderTemporary, work_block, se::AesBlockSize);
/* If on erista, derive the current device master key into the DeviceMaster key slot. */
if (soc_type == fuse::SocType_Erista) {
se::SetEncryptedAesKey128(pkg1::AesKeySlot_DeviceMaster, pkg1::AesKeySlot_BootloaderTemporary, work_block, se::AesBlockSize);
}
} else {
/* Decrypt the device master key. */
se::DecryptAes128(DeviceMasterKeys[i], se::AesBlockSize, pkg1::AesKeySlot_BootloaderTemporary, work_block, se::AesBlockSize);
/* If on mariko, ensure that we derive device key 0 here. */
if (soc_type == fuse::SocType_Mariko && i == 0) {
se::SetAesKey(pkg1::AesKeySlot_Device, DeviceMasterKeys[i], se::AesBlockSize);
}
}
}
}
alignas(se::AesBlockSize) constexpr inline const u8 GeneratePersonalizedAesKeyKekKekSource[se::AesBlockSize] = {
0x4D, 0x87, 0x09, 0x86, 0xC4, 0x5D, 0x20, 0x72, 0x2F, 0xBA, 0x10, 0x53, 0xDA, 0x92, 0xE8, 0xA9
};
alignas(se::AesBlockSize) constexpr inline const u8 GeneratePersonalizedAesKeyKeyKekSource[se::AesBlockSize] = {
0x89, 0x61, 0x5E, 0xE0, 0x5C, 0x31, 0xB6, 0x80, 0x5F, 0xE5, 0x8F, 0x3D, 0xA2, 0x4F, 0x7A, 0xA8
};
void GeneratePersonalizedAesKeyForBis(int slot, const void *kek_source, const void *key_source, int generation) {
/* Derive kek. */
se::SetEncryptedAesKey128(pkg1::AesKeySlot_BootloaderTemporary, PrepareDeviceMasterKey(generation), GeneratePersonalizedAesKeyKekKekSource, se::AesBlockSize);
se::SetEncryptedAesKey128(pkg1::AesKeySlot_BootloaderTemporary, pkg1::AesKeySlot_BootloaderTemporary, kek_source, se::AesBlockSize);
/* Derive key. */
se::SetEncryptedAesKey128(pkg1::AesKeySlot_BootloaderTemporary, pkg1::AesKeySlot_BootloaderTemporary, GeneratePersonalizedAesKeyKeyKekSource, se::AesBlockSize);
se::SetEncryptedAesKey128(slot, pkg1::AesKeySlot_BootloaderTemporary, key_source, se::AesBlockSize);
}
alignas(se::AesBlockSize) constexpr inline const u8 BisKekSource[se::AesBlockSize] = {
0x34, 0xC1, 0xA0, 0xC4, 0x82, 0x58, 0xF8, 0xB4, 0xFA, 0x9E, 0x5E, 0x6A, 0xDA, 0xFC, 0x7E, 0x4F
};
alignas(se::AesBlockSize) constexpr inline const u8 BisPartitionSystemKeySources[2][se::AesBlockSize] = {
{ 0x52, 0xC2, 0xE9, 0xEB, 0x09, 0xE3, 0xEE, 0x29, 0x32, 0xA1, 0x0C, 0x1F, 0xB6, 0xA0, 0x92, 0x6C },
{ 0x4D, 0x12, 0xE1, 0x4B, 0x2A, 0x47, 0x4C, 0x1C, 0x09, 0xCB, 0x03, 0x59, 0xF0, 0x15, 0xF4, 0xE4 },
};
void DeriveBisPartitionSystemKeys() {
/* Determine key generation. */
const int key_generation = std::max<int>(0, static_cast<int>(fuse::GetDeviceUniqueKeyGeneration()) - 1);
/* Generate desired keys. */
GeneratePersonalizedAesKeyForBis(pkg1::AesKeySlot_BootloaderSystem0, BisKekSource, BisPartitionSystemKeySources[0], key_generation);
GeneratePersonalizedAesKeyForBis(pkg1::AesKeySlot_BootloaderSystem1, BisKekSource, BisPartitionSystemKeySources[1], key_generation);
}
}
void DeriveKeysErista() {
/* Get work buffer. */
alignas(se::AesBlockSize) u8 work_buffer[se::AesBlockSize];
/* Get whether we're using dev keys. */
const bool is_prod = fuse::GetHardwareState() == fuse::HardwareState_Production;
/* Derive Keyblob Key. */
se::DecryptAes128(work_buffer, se::AesBlockSize, pkg1::AesKeySlot_Tsec, KeyblobKeySource, se::AesBlockSize);
se::SetEncryptedAesKey128(pkg1::AesKeySlot_Device, pkg1::AesKeySlot_SecureBoot, work_buffer, se::AesBlockSize);
/* Derive Master Kek. */
se::SetEncryptedAesKey128(pkg1::AesKeySlot_MasterKek, is_prod ? pkg1::AesKeySlot_TsecRoot : pkg1::AesKeySlot_TsecRootDev, EristaMasterKekSource, se::AesBlockSize);
/* Derive Master Key. */
se::SetEncryptedAesKey128(pkg1::AesKeySlot_BootloaderMaster, pkg1::AesKeySlot_MasterKek, MasterKeySource, se::AesBlockSize);
se::SetEncryptedAesKey128(pkg1::AesKeySlot_Master, pkg1::AesKeySlot_MasterKek, MasterKeySource, se::AesBlockSize);
/* Derive Device Master Key Source Kek, Device Key. */
se::SetEncryptedAesKey128(pkg1::AesKeySlot_DeviceMasterKeySourceKekErista, pkg1::AesKeySlot_Device, DeviceMasterKeySourceKekSource, se::AesBlockSize);
se::SetEncryptedAesKey128(pkg1::AesKeySlot_Device, pkg1::AesKeySlot_Device, DeviceKeySource, se::AesBlockSize);
/* Derive all master keys. */
DeriveMasterKeys(is_prod);
/* Derive all device master keys. */
DeriveDeviceMasterKeys(fuse::SocType_Erista, is_prod);
/* Derive system partition keys. */
DeriveBisPartitionSystemKeys();
}
void DeriveKeysMariko() {
/* Get whether we're using dev keys. */
const bool is_prod = fuse::GetHardwareState() == fuse::HardwareState_Production;
/* Derive Device Master Key Source Kek, Master Key. */
se::SetEncryptedAesKey128(pkg1::AesKeySlot_DeviceMasterKeySourceKekErista, pkg1::AesKeySlot_SecureBoot, DeviceMasterKeySourceKekSource, se::AesBlockSize);
se::SetEncryptedAesKey128(pkg1::AesKeySlot_BootloaderMaster, pkg1::AesKeySlot_MarikoKek, is_prod ? MarikoMasterKekSource : MarikoMasterKekSourceDev, se::AesBlockSize);
se::SetEncryptedAesKey128(pkg1::AesKeySlot_BootloaderMaster, pkg1::AesKeySlot_BootloaderMaster, MasterKeySource, se::AesBlockSize);
/* Derive all master keys. */
DeriveMasterKeys(is_prod);
/* Derive all device master keys. */
DeriveDeviceMasterKeys(fuse::SocType_Mariko, is_prod);
/* Derive system partition keys. */
DeriveBisPartitionSystemKeys();
}
int PrepareMasterKey(int generation) {
if (generation == pkg1::KeyGeneration_Current) {
return pkg1::AesKeySlot_BootloaderMaster;
}
se::SetAesKey(pkg1::AesKeySlot_BootloaderTemporary, MasterKeys[generation], se::AesBlockSize);
return pkg1::AesKeySlot_BootloaderTemporary;
}
int PrepareDeviceMasterKey(int generation) {
if (generation == pkg1::KeyGeneration_1_0_0) {
return pkg1::AesKeySlot_Device;
}
if (generation == pkg1::KeyGeneration_Current) {
return pkg1::AesKeySlot_BootloaderDeviceMaster;
}
const int index = std::max(0, generation - pkg1::KeyGeneration_4_0_0);
se::SetAesKey(pkg1::AesKeySlot_BootloaderTemporary, DeviceMasterKeys[index], se::AesBlockSize);
return pkg1::AesKeySlot_BootloaderTemporary;
}
}
| 26,708
|
C++
|
.cpp
| 277
| 84.98556
| 221
| 0.637329
|
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,299
|
fusee_exception_handler.cpp
|
Atmosphere-NX_Atmosphere/fusee/program/source/fusee_exception_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 "fusee_exception_handler.hpp"
#include "fusee_fatal.hpp"
namespace ams::nxboot {
NORETURN void ExceptionHandlerImpl(s32 which, u32 lr, u32 svc_lr) {
ShowFatalError("Exception: which=%" PRId32 ", lr=%p, svc_lr=%p\n", which, reinterpret_cast<void *>(lr), reinterpret_cast<void *>(svc_lr));
}
}
namespace ams::diag {
NORETURN void AbortImpl(const char *expr, const char *func, const char *file, int line) {
AMS_UNUSED(expr, func, line, file);
u32 lr;
__asm__ __volatile__("mov %0, lr" : "=r"(lr) :: "memory");
nxboot::ShowFatalError("Abort called, lr=%p\n", reinterpret_cast<void *>(lr));
}
NORETURN void AbortImpl(const char *expr, const char *func, const char *file, int line, const char *format, ...) {
AMS_UNUSED(expr, func, line, file, format);
u32 lr;
__asm__ __volatile__("mov %0, lr" : "=r"(lr) :: "memory");
nxboot::ShowFatalError("Abort called, lr=%p\n", reinterpret_cast<void *>(lr));
}
NORETURN void AbortImpl(const char *expr, const char *func, const char *file, int line, const ::ams::Result *result, const char *format, ...) {
AMS_UNUSED(expr, func, line, file, result, format);
u32 lr;
__asm__ __volatile__("mov %0, lr" : "=r"(lr) :: "memory");
nxboot::ShowFatalError("Abort called, lr=%p, result=0x%08" PRIX32 "\n", reinterpret_cast<void *>(lr), result != nullptr ? result->GetValue() : 0);
}
NORETURN void AbortImpl(const char *expr, const char *func, const char *file, int line, const ::ams::Result *result, const ::ams::os::UserExceptionInfo *exception_info, const char *format, ...) {
AMS_UNUSED(expr, func, line, file, result, exception_info, format);
u32 lr;
__asm__ __volatile__("mov %0, lr" : "=r"(lr) :: "memory");
nxboot::ShowFatalError("Abort called, lr=%p, result=0x%08" PRIX32 "\n", reinterpret_cast<void *>(lr), result != nullptr ? result->GetValue() : 0);
}
NORETURN void AbortImpl() {
u32 lr;
__asm__ __volatile__("mov %0, lr" : "=r"(lr) :: "memory");
nxboot::ShowFatalError("Abort called, lr=%p\n", reinterpret_cast<void *>(lr));
}
NORETURN void OnAssertionFailure(AssertionType type, const char *expr, const char *func, const char *file, int line) {
AMS_UNUSED(type, expr, func, file, line);
u32 lr;
__asm__ __volatile__("mov %0, lr" : "=r"(lr) :: "memory");
nxboot::ShowFatalError("Assert called, lr=%p\n", reinterpret_cast<void *>(lr));
}
NORETURN void OnAssertionFailure(AssertionType type, const char *expr, const char *func, const char *file, int line, const char *format, ...) {
AMS_UNUSED(type, expr, func, file, line, format);
u32 lr;
__asm__ __volatile__("mov %0, lr" : "=r"(lr) :: "memory");
nxboot::ShowFatalError("Assert called, lr=%p\n", reinterpret_cast<void *>(lr));
}
}
| 3,592
|
C++
|
.cpp
| 66
| 48.590909
| 199
| 0.638826
|
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,300
|
fusee_package2.cpp
|
Atmosphere-NX_Atmosphere/fusee/program/source/fusee_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 "fusee_package2.hpp"
#include "fusee_key_derivation.hpp"
#include "fusee_fatal.hpp"
namespace ams::nxboot {
namespace {
alignas(se::AesBlockSize) constexpr inline const u8 Package2KeySource[se::AesBlockSize] = {
0xFB, 0x8B, 0x6A, 0x9C, 0x79, 0x00, 0xC8, 0x49, 0xEF, 0xD2, 0x4D, 0x85, 0x4D, 0x30, 0xA0, 0xC7
};
void PreparePackage2Key(int pkg2_slot, int key_generation) {
/* 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, Package2KeySource, sizeof(Package2KeySource));
}
void DecryptPackage2(void *dst, size_t dst_size, const void *src, size_t src_size, const void *iv, size_t iv_size, u8 key_generation) {
/* Ensure that the SE sees consistent data. */
hw::FlushDataCache(src, src_size);
if (src != dst) {
hw::FlushDataCache(dst, dst_size);
}
/* Load the package2 key into the temporary keyslot. */
PreparePackage2Key(pkg1::AesKeySlot_Temporary, key_generation);
/* 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::InvalidateDataCache(dst, dst_size);
}
void DecryptPackage2Header(pkg2::Package2Meta *dst, const pkg2::Package2Meta &src) {
constexpr int IvSize = 0x10;
/* Decrypt the header. */
DecryptPackage2(dst, sizeof(*dst), std::addressof(src), sizeof(src), std::addressof(src), IvSize, src.GetKeyGeneration());
/* Copy back the iv, which encodes encrypted metadata. */
std::memcpy(dst, std::addressof(src), IvSize);
}
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;
}
}
void DecryptPackage2(u8 *package2) {
/* Decrypt package2 header. */
pkg2::Package2Header *header = reinterpret_cast<pkg2::Package2Header *>(package2);
{
pkg2::Package2Header tmp = *header;
DecryptPackage2Header(std::addressof(header->meta), tmp.meta);
}
/* Check package2 magic. */
if (!VerifyPackage2Meta(header->meta)) {
ShowFatalError("Package2 meta is invalid!\n");
}
/* Decrypt package2 payloads. */
u8 *payload = package2 + sizeof(*header);
const u8 key_generation = header->meta.GetKeyGeneration();
for (int i = 0; i < pkg2::PayloadCount; ++i) {
if (header->meta.payload_sizes[i] == 0) {
continue;
}
DecryptPackage2(payload, header->meta.payload_sizes[i], payload, header->meta.payload_sizes[i], header->meta.payload_ivs[i], sizeof(header->meta.payload_ivs[i]), key_generation);
payload += header->meta.payload_sizes[i];
}
}
}
| 6,457
|
C++
|
.cpp
| 133
| 37.12782
| 190
| 0.578036
|
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,301
|
fusee_overlay_manager.cpp
|
Atmosphere-NX_Atmosphere/fusee/program/source/fusee_overlay_manager.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <exosphere.hpp>
#include "fusee_overlay_manager.hpp"
#include "fusee_external_package.hpp"
#include "fusee_fatal.hpp"
namespace ams::nxboot {
namespace {
constinit u8 g_secmon_debug_storage[secmon::MemoryRegionPhysicalIramSecureMonitorDebug.GetSize()];
ALWAYS_INLINE void *GetOverlayDestination() {
return reinterpret_cast<void *>(0x4002C000);
}
void LoadMemoryTrainingOverlay(fs::FileHandle archive_file) {
Result result;
u32 verif_hash;
u32 store_hash;
if (fuse::GetSocType() == fuse::SocType_Erista) {
result = fs::ReadFile(archive_file, AMS_OFFSETOF(ExternalPackage, ovl_mtc_erista), GetOverlayDestination(), sizeof(ExternalPackage{}.ovl_mtc_erista));
verif_hash = reinterpret_cast<const u32 *>(GetOverlayDestination())[-2];
store_hash = reinterpret_cast<const u32 *>(GetOverlayDestination())[(sizeof(ExternalPackage{}.ovl_mtc_erista) / sizeof(u32)) - 1];
} else /* if (fuse::GetSocType() == fuse::SocType_Mariko) */ {
result = fs::ReadFile(archive_file, AMS_OFFSETOF(ExternalPackage, ovl_mtc_mariko), GetOverlayDestination(), sizeof(ExternalPackage{}.ovl_mtc_mariko));
verif_hash = reinterpret_cast<const u32 *>(GetOverlayDestination())[-1];
store_hash = reinterpret_cast<const u32 *>(GetOverlayDestination())[(sizeof(ExternalPackage{}.ovl_mtc_mariko) / sizeof(u32)) - 1];
}
if (R_FAILED(result)) {
ShowFatalError("Failed to load MTC overlay: 0x%08" PRIx32 "\n", result.GetValue());
}
if (verif_hash != store_hash) {
ShowFatalError("Incorrect fusee version! (program=0x%08" PRIx32 ", mtc=0x%08" PRIx32 ")\n", verif_hash, store_hash);
}
}
}
void LoadOverlay(fs::FileHandle archive_file, OverlayId ovl) {
switch (ovl) {
case OverlayId_MemoryTraining:
LoadMemoryTrainingOverlay(archive_file);
break;
}
}
void SaveMemoryTrainingOverlay() {
if (fuse::GetSocType() == fuse::SocType_Erista) {
/* NOTE: Erista does not do memory clock restoration. */
/* std::memcpy(const_cast<u8 *>(GetExternalPackage().ovl_mtc_erista), GetOverlayDestination(), sizeof(ExternalPackage{}.ovl_mtc_erista)); */
} else /* if (fuse::GetSocType() == fuse::SocType_Mariko) */ {
std::memcpy(const_cast<u8 *>(GetExternalPackage().ovl_mtc_mariko), GetOverlayDestination(), sizeof(ExternalPackage{}.ovl_mtc_mariko) - 0x2000);
}
}
void RestoreMemoryTrainingOverlay() {
if (fuse::GetSocType() == fuse::SocType_Erista) {
/* NOTE: Erista does not do memory clock restoration. */
/* std::memcpy(GetOverlayDestination(), GetExternalPackage().ovl_mtc_erista, sizeof(ExternalPackage{}.ovl_mtc_erista)); */
} else /* if (fuse::GetSocType() == fuse::SocType_Mariko) */ {
std::memcpy(g_secmon_debug_storage, secmon::MemoryRegionPhysicalIramSecureMonitorDebug.GetPointer<void>(), sizeof(g_secmon_debug_storage));
std::memcpy(GetOverlayDestination(), GetExternalPackage().ovl_mtc_mariko, sizeof(ExternalPackage{}.ovl_mtc_mariko) - 0x2000);
}
}
void RestoreSecureMonitorOverlay() {
if (fuse::GetSocType() == fuse::SocType_Erista) {
/* NOTE: Erista does not do memory clock restoration. */
} else /* if (fuse::GetSocType() == fuse::SocType_Mariko) */ {
std::memcpy(secmon::MemoryRegionPhysicalIramSecureMonitorDebug.GetPointer<void>(), g_secmon_debug_storage, sizeof(g_secmon_debug_storage));
}
}
}
| 4,391
|
C++
|
.cpp
| 78
| 47.512821
| 166
| 0.654651
|
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,302
|
fusee_sd_card.cpp
|
Atmosphere-NX_Atmosphere/fusee/program/source/fusee_sd_card.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <exosphere.hpp>
#include "fusee_sd_card.hpp"
namespace ams::nxboot {
namespace {
constexpr inline auto SdCardPort = sdmmc::Port_SdCard0;
constexpr inline const uintptr_t APB = secmon::MemoryRegionPhysicalDeviceApbMisc.GetAddress();
alignas(0x10) constinit u8 g_sd_work_buffer[sdmmc::SdCardWorkBufferSize];
void ConfigureInitialSdCardPinmux() {
/* Normally, these pints get configured by boot sysmodule during initial pinmux config. */
/* However, they're required to access the SD card, so we must do them ahead of time. */
reg::ReadWrite(APB + PINMUX_AUX_SDMMC1_CLK, PINMUX_REG_BITS_ENUM(AUX_E_INPUT, ENABLE),
PINMUX_REG_BITS_ENUM(AUX_TRISTATE, PASSTHROUGH),
PINMUX_REG_BITS_ENUM(AUX_PUPD, PULL_DOWN),
PINMUX_REG_BITS_ENUM(AUX_SDMMC1_CLK_PM, SDMMC1));
reg::ReadWrite(APB + PINMUX_AUX_SDMMC1_CMD, PINMUX_REG_BITS_ENUM(AUX_E_INPUT, ENABLE),
PINMUX_REG_BITS_ENUM(AUX_TRISTATE, PASSTHROUGH),
PINMUX_REG_BITS_ENUM(AUX_PUPD, PULL_UP),
PINMUX_REG_BITS_ENUM(AUX_SDMMC1_CMD_PM, SDMMC1));
reg::ReadWrite(APB + PINMUX_AUX_SDMMC1_DAT3, PINMUX_REG_BITS_ENUM(AUX_E_INPUT, ENABLE),
PINMUX_REG_BITS_ENUM(AUX_TRISTATE, PASSTHROUGH),
PINMUX_REG_BITS_ENUM(AUX_PUPD, PULL_UP),
PINMUX_REG_BITS_ENUM(AUX_SDMMC1_DAT3_PM, SDMMC1));
reg::ReadWrite(APB + PINMUX_AUX_SDMMC1_DAT2, PINMUX_REG_BITS_ENUM(AUX_E_INPUT, ENABLE),
PINMUX_REG_BITS_ENUM(AUX_TRISTATE, PASSTHROUGH),
PINMUX_REG_BITS_ENUM(AUX_PUPD, PULL_UP),
PINMUX_REG_BITS_ENUM(AUX_SDMMC1_DAT2_PM, SDMMC1));
reg::ReadWrite(APB + PINMUX_AUX_SDMMC1_DAT1, PINMUX_REG_BITS_ENUM(AUX_E_INPUT, ENABLE),
PINMUX_REG_BITS_ENUM(AUX_TRISTATE, PASSTHROUGH),
PINMUX_REG_BITS_ENUM(AUX_PUPD, PULL_UP),
PINMUX_REG_BITS_ENUM(AUX_SDMMC1_DAT1_PM, SDMMC1));
reg::ReadWrite(APB + PINMUX_AUX_SDMMC1_DAT0, PINMUX_REG_BITS_ENUM(AUX_E_INPUT, ENABLE),
PINMUX_REG_BITS_ENUM(AUX_TRISTATE, PASSTHROUGH),
PINMUX_REG_BITS_ENUM(AUX_PUPD, PULL_UP),
PINMUX_REG_BITS_ENUM(AUX_SDMMC1_DAT0_PM, SDMMC1));
reg::ReadWrite(APB + PINMUX_AUX_DMIC3_CLK, PINMUX_REG_BITS_ENUM(AUX_E_OD, DISABLE),
PINMUX_REG_BITS_ENUM(AUX_E_INPUT, DISABLE),
PINMUX_REG_BITS_ENUM(AUX_TRISTATE, PASSTHROUGH),
PINMUX_REG_BITS_ENUM(AUX_SDMMC1_DAT0_PM, RSVD2));
}
}
Result InitializeSdCard() {
/* Perform initial pinmux config to enable sd card access. */
ConfigureInitialSdCardPinmux();
/* Initialize the SD card. */
sdmmc::Initialize(SdCardPort);
/* Set the SD card work buffer. */
sdmmc::SetSdCardWorkBuffer(SdCardPort, g_sd_work_buffer, sizeof(g_sd_work_buffer));
/* Activate the SD card. */
R_RETURN(sdmmc::Activate(SdCardPort));
}
void FinalizeSdCard() {
/* Deactivate the SD card. */
sdmmc::Deactivate(SdCardPort);
/* Finalize the SD card. */
sdmmc::Finalize(SdCardPort);
}
Result CheckSdCardConnection(sdmmc::SpeedMode *out_sm, sdmmc::BusWidth *out_bw) {
R_RETURN(sdmmc::CheckSdCardConnection(out_sm, out_bw, SdCardPort));
}
Result GetSdCardMemoryCapacity(u32 *out_num_sectors) {
R_RETURN(sdmmc::GetDeviceMemoryCapacity(out_num_sectors, SdCardPort));
}
Result ReadSdCard(void *dst, size_t size, size_t sector_index, size_t sector_count) {
R_RETURN(sdmmc::Read(dst, size, SdCardPort, sector_index, sector_count));
}
Result WriteSdCard(size_t sector_index, size_t sector_count, const void *src, size_t size) {
R_RETURN(sdmmc::Write(SdCardPort, sector_index, sector_count, src, size));
}
}
| 5,715
|
C++
|
.cpp
| 84
| 48.392857
| 112
| 0.523538
|
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,303
|
fusee_stratosphere.cpp
|
Atmosphere-NX_Atmosphere/fusee/program/source/fusee_stratosphere.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 "fusee_stratosphere.hpp"
#include "fusee_fatal.hpp"
#include "fusee_malloc.hpp"
#include "fusee_external_package.hpp"
#include "fs/fusee_fs_api.hpp"
namespace ams::nxboot {
namespace {
constexpr u32 MesoshereMetadataLayout0Magic = util::FourCC<'M','S','S','0'>::Code;
constexpr u32 MesoshereMetadataLayout1Magic = util::FourCC<'M','S','S','1'>::Code;
struct InitialProcessBinaryHeader {
static constexpr u32 Magic = util::FourCC<'I','N','I','1'>::Code;
u32 magic;
u32 size;
u32 num_processes;
u32 reserved;
};
struct InitialProcessHeader {
static constexpr u32 Magic = util::FourCC<'K','I','P','1'>::Code;
u32 magic;
u8 name[12];
u64 program_id;
u32 version;
u8 priority;
u8 ideal_core_id;
u8 _1E;
u8 flags;
u32 rx_address;
u32 rx_size;
u32 rx_compressed_size;
u32 affinity_mask;
u32 ro_address;
u32 ro_size;
u32 ro_compressed_size;
u32 stack_size;
u32 rw_address;
u32 rw_size;
u32 rw_compressed_size;
u32 _4C;
u32 bss_address;
u32 bss_size;
u32 pad[(0x80 - 0x58) / sizeof(u32)];
u32 capabilities[0x80 / sizeof(u32)];
};
static_assert(sizeof(InitialProcessHeader) == 0x100);
struct PatchMeta {
PatchMeta *next;
bool is_memset;
u32 start_segment;
u32 rel_offset;
const void *data;
u32 size;
};
struct alignas(0x10) InitialProcessMeta {
InitialProcessMeta *next = nullptr;
const InitialProcessHeader *kip;
u32 kip_size;
PatchMeta *patches_head;
PatchMeta *patches_tail;
u32 patch_segments;
u64 program_id;
se::Sha256Hash kip_hash;
};
static_assert(sizeof(InitialProcessMeta) == 0x40);
static_assert(alignof(InitialProcessMeta) == 0x10);
constexpr inline const u64 FsProgramId = 0x0100000000000000;
enum FsVersion {
FsVersion_1_0_0 = 0,
FsVersion_2_0_0,
FsVersion_2_0_0_Exfat,
FsVersion_2_1_0,
FsVersion_2_1_0_Exfat,
FsVersion_3_0_0,
FsVersion_3_0_0_Exfat,
FsVersion_3_0_1,
FsVersion_3_0_1_Exfat,
FsVersion_4_0_0,
FsVersion_4_0_0_Exfat,
FsVersion_4_1_0,
FsVersion_4_1_0_Exfat,
FsVersion_5_0_0,
FsVersion_5_0_0_Exfat,
FsVersion_5_1_0,
FsVersion_5_1_0_Exfat,
FsVersion_6_0_0,
FsVersion_6_0_0_Exfat,
FsVersion_7_0_0,
FsVersion_7_0_0_Exfat,
FsVersion_8_0_0,
FsVersion_8_0_0_Exfat,
FsVersion_8_1_0,
FsVersion_8_1_0_Exfat,
FsVersion_9_0_0,
FsVersion_9_0_0_Exfat,
FsVersion_9_1_0,
FsVersion_9_1_0_Exfat,
FsVersion_10_0_0,
FsVersion_10_0_0_Exfat,
FsVersion_10_2_0,
FsVersion_10_2_0_Exfat,
FsVersion_11_0_0,
FsVersion_11_0_0_Exfat,
FsVersion_12_0_0,
FsVersion_12_0_0_Exfat,
FsVersion_12_0_3,
FsVersion_12_0_3_Exfat,
FsVersion_13_0_0,
FsVersion_13_0_0_Exfat,
FsVersion_13_1_0,
FsVersion_13_1_0_Exfat,
FsVersion_14_0_0,
FsVersion_14_0_0_Exfat,
FsVersion_15_0_0,
FsVersion_15_0_0_Exfat,
FsVersion_16_0_0,
FsVersion_16_0_0_Exfat,
FsVersion_16_0_3,
FsVersion_16_0_3_Exfat,
FsVersion_17_0_0,
FsVersion_17_0_0_Exfat,
FsVersion_18_0_0,
FsVersion_18_0_0_Exfat,
FsVersion_18_1_0,
FsVersion_18_1_0_Exfat,
FsVersion_19_0_0,
FsVersion_19_0_0_Exfat,
FsVersion_Count,
};
constexpr const u8 FsHashes[FsVersion_Count][8] = {
{ 0xDE, 0x9F, 0xDD, 0xA4, 0x08, 0x5D, 0xD5, 0xFE }, /* FsVersion_1_0_0 */
{ 0xCD, 0x7B, 0xBE, 0x18, 0xD6, 0x13, 0x0B, 0x28 }, /* FsVersion_2_0_0 */
{ 0xE7, 0x66, 0x92, 0xDF, 0xAA, 0x04, 0x20, 0xE9 }, /* FsVersion_2_0_0_Exfat */
{ 0x0D, 0x70, 0x05, 0x62, 0x7B, 0x07, 0x76, 0x7C }, /* FsVersion_2_1_0 */
{ 0xDB, 0xD8, 0x5F, 0xCA, 0xCC, 0x19, 0x3D, 0xA8 }, /* FsVersion_2_1_0_Exfat */
{ 0xA8, 0x6D, 0xA5, 0xE8, 0x7E, 0xF1, 0x09, 0x7B }, /* FsVersion_3_0_0 */
{ 0x98, 0x1C, 0x57, 0xE7, 0xF0, 0x2F, 0x70, 0xF7 }, /* FsVersion_3_0_0_Exfat */
{ 0x57, 0x39, 0x7C, 0x06, 0x3F, 0x10, 0xB6, 0x31 }, /* FsVersion_3_0_1 */
{ 0x07, 0x30, 0x99, 0xD7, 0xC6, 0xAD, 0x7D, 0x89 }, /* FsVersion_3_0_1_Exfat */
{ 0x06, 0xE9, 0x07, 0x19, 0x59, 0x5A, 0x01, 0x0C }, /* FsVersion_4_0_0 */
{ 0x54, 0x9B, 0x0F, 0x8D, 0x6F, 0x72, 0xC4, 0xE9 }, /* FsVersion_4_0_0_Exfat */
{ 0x80, 0x96, 0xAF, 0x7C, 0x6A, 0x35, 0xAA, 0x82 }, /* FsVersion_4_1_0 */
{ 0x02, 0xD5, 0xAB, 0xAA, 0xFD, 0x20, 0xC8, 0xB0 }, /* FsVersion_4_1_0_Exfat */
{ 0xA6, 0xF2, 0x7A, 0xD9, 0xAC, 0x7C, 0x73, 0xAD }, /* FsVersion_5_0_0 */
{ 0xCE, 0x3E, 0xCB, 0xA2, 0xF2, 0xF0, 0x62, 0xF5 }, /* FsVersion_5_0_0_Exfat */
{ 0x76, 0xF8, 0x74, 0x02, 0xC9, 0x38, 0x7C, 0x0F }, /* FsVersion_5_1_0 */
{ 0x10, 0xB2, 0xD8, 0x16, 0x05, 0x48, 0x85, 0x99 }, /* FsVersion_5_1_0_Exfat */
{ 0x3A, 0x57, 0x4D, 0x43, 0x61, 0x86, 0x19, 0x1D }, /* FsVersion_6_0_0 */
{ 0x33, 0x05, 0x53, 0xF6, 0xB5, 0xFB, 0x55, 0xC4 }, /* FsVersion_6_0_0_Exfat */
{ 0x2A, 0xDB, 0xE9, 0x7E, 0x9B, 0x5F, 0x41, 0x77 }, /* FsVersion_7_0_0 */
{ 0x2C, 0xCE, 0x65, 0x9C, 0xEC, 0x53, 0x6A, 0x8E }, /* FsVersion_7_0_0_Exfat */
{ 0xB2, 0xF5, 0x17, 0x6B, 0x35, 0x48, 0x36, 0x4D }, /* FsVersion_8_0_0 */
{ 0xDB, 0xD9, 0x41, 0xC0, 0xC5, 0x3C, 0x52, 0xCC }, /* FsVersion_8_0_0_Exfat */
{ 0x6B, 0x09, 0xB6, 0x7B, 0x29, 0xC0, 0x20, 0x24 }, /* FsVersion_8_1_0 */
{ 0xB4, 0xCA, 0xE1, 0xF2, 0x49, 0x65, 0xD9, 0x2E }, /* FsVersion_8_1_0_Exfat */
{ 0x46, 0x87, 0x40, 0x76, 0x1E, 0x19, 0x3E, 0xB7 }, /* FsVersion_9_0_0 */
{ 0x7C, 0x95, 0x13, 0x76, 0xE5, 0xC1, 0x2D, 0xF8 }, /* FsVersion_9_0_0_Exfat */
{ 0xB5, 0xE7, 0xA6, 0x4C, 0x6F, 0x5C, 0x4F, 0xE3 }, /* FsVersion_9_1_0 */
{ 0xF1, 0x96, 0xD1, 0x44, 0xD0, 0x44, 0x45, 0xB6 }, /* FsVersion_9_1_0_Exfat */
{ 0x3E, 0xEB, 0xD9, 0xB7, 0xBC, 0xD1, 0xB5, 0xE0 }, /* FsVersion_10_0_0 */
{ 0x81, 0x7E, 0xA2, 0xB0, 0xB7, 0x02, 0xC1, 0xF3 }, /* FsVersion_10_0_0_Exfat */
{ 0xA9, 0x52, 0xB6, 0x57, 0xAD, 0xF9, 0xC2, 0xBA }, /* FsVersion_10_2_0 */
{ 0x16, 0x0D, 0x3E, 0x10, 0x4E, 0xAD, 0x61, 0x76 }, /* FsVersion_10_2_0_Exfat */
{ 0xE3, 0x99, 0x15, 0x6E, 0x84, 0x4E, 0xB0, 0xAA }, /* FsVersion_11_0_0 */
{ 0x0B, 0xA1, 0x5B, 0xB3, 0x04, 0xB5, 0x05, 0x63 }, /* FsVersion_11_0_0_Exfat */
{ 0xDC, 0x2A, 0x08, 0x49, 0x96, 0xBB, 0x3C, 0x01 }, /* FsVersion_12_0_0 */
{ 0xD5, 0xA5, 0xBF, 0x36, 0x64, 0x0C, 0x49, 0xEA }, /* FsVersion_12_0_0_Exfat */
{ 0xC8, 0x67, 0x62, 0xBE, 0x19, 0xA5, 0x1F, 0xA0 }, /* FsVersion_12_0_3 */
{ 0xE1, 0xE8, 0xD3, 0xD6, 0xA2, 0xFE, 0x0B, 0x10 }, /* FsVersion_12_0_3_Exfat */
{ 0x7D, 0x20, 0x05, 0x47, 0x17, 0x8A, 0x83, 0x6A }, /* FsVersion_13_0_0 */
{ 0x51, 0xEB, 0xFA, 0x9C, 0xCF, 0x66, 0xC0, 0x9E }, /* FsVersion_13_0_0_Exfat */
{ 0x91, 0xBA, 0x65, 0xA2, 0x1C, 0x1D, 0x50, 0xAE }, /* FsVersion_13_1_0 */
{ 0x76, 0x38, 0x27, 0xEE, 0x9C, 0x20, 0x7E, 0x5B }, /* FsVersion_13_1_0_Exfat */
{ 0x88, 0x7A, 0xC1, 0x50, 0x80, 0x6C, 0x75, 0xCC }, /* FsVersion_14_0_0 */
{ 0xD4, 0x88, 0xD1, 0xF2, 0x92, 0x17, 0x35, 0x5C }, /* FsVersion_14_0_0_Exfat */
{ 0xD0, 0xD4, 0x49, 0x18, 0x14, 0xB5, 0x62, 0xAF }, /* FsVersion_15_0_0 */
{ 0x34, 0xC0, 0xD9, 0xED, 0x6A, 0xD1, 0x87, 0x3D }, /* FsVersion_15_0_0_Exfat */
{ 0x56, 0xE8, 0x56, 0x56, 0x6C, 0x38, 0xD8, 0xBE }, /* FsVersion_16_0_0 */
{ 0xCF, 0xAB, 0x45, 0x0C, 0x2C, 0x53, 0x9D, 0xA9 }, /* FsVersion_16_0_0_Exfat */
{ 0x39, 0xEE, 0x1F, 0x1E, 0x0E, 0xA7, 0x32, 0x5D }, /* FsVersion_16_0_3 */
{ 0x62, 0xC6, 0x5E, 0xFD, 0x9A, 0xBF, 0x7C, 0x43 }, /* FsVersion_16_0_3_Exfat */
{ 0x27, 0x07, 0x3B, 0xF0, 0xA1, 0xB8, 0xCE, 0x61 }, /* FsVersion_17_0_0 */
{ 0xEE, 0x0F, 0x4B, 0xAC, 0x6D, 0x1F, 0xFC, 0x4B }, /* FsVersion_17_0_0_Exfat */
{ 0x79, 0x5F, 0x5A, 0x5E, 0xB0, 0xC6, 0x77, 0x9E }, /* FsVersion_18_0_0 */
{ 0x1E, 0x2C, 0x64, 0xB1, 0xCC, 0xE2, 0x78, 0x24 }, /* FsVersion_18_0_0_Exfat */
{ 0xA3, 0x39, 0xF0, 0x1C, 0x95, 0xBF, 0xA7, 0x68 }, /* FsVersion_18_1_0 */
{ 0x20, 0x4C, 0xBA, 0x86, 0xDE, 0x08, 0x44, 0x6A }, /* FsVersion_18_1_0_Exfat */
{ 0xD9, 0x4C, 0x68, 0x15, 0xF8, 0xF5, 0x0A, 0x20 }, /* FsVersion_19_0_0 */
{ 0xED, 0xA8, 0x78, 0x68, 0xA4, 0x49, 0x07, 0x50 }, /* FsVersion_19_0_0_Exfat */
};
const InitialProcessBinaryHeader *FindInitialProcessBinary(const pkg2::Package2Header *header, const u8 *data, ams::TargetFirmware target_firmware) {
if (target_firmware >= ams::TargetFirmware_17_0_0) {
const u32 *data_32 = reinterpret_cast<const u32 *>(data);
const u32 branch_target = (data_32[0] & 0x00FFFFFF);
for (size_t i = branch_target; i < branch_target + 0x1000 / sizeof(u32); ++i) {
const u32 ini_offset = (i * sizeof(u32)) + data_32[i];
if (data_32[i + 1] == 0 && ini_offset <= header->meta.payload_sizes[0] && std::memcmp(data + ini_offset, "INI1", 4) == 0) {
return reinterpret_cast<const InitialProcessBinaryHeader *>(data + ini_offset);
}
}
return nullptr;
} else if (target_firmware >= ams::TargetFirmware_8_0_0) {
/* Try to find initial process binary. */
const u32 *data_32 = reinterpret_cast<const u32 *>(data);
for (size_t i = 0; i < 0x1000 / sizeof(u32); ++i) {
if (data_32[i] == 0 && data_32[i + 8] <= header->meta.payload_sizes[0] && std::memcmp(data + data_32[i + 8], "INI1", 4) == 0) {
return reinterpret_cast<const InitialProcessBinaryHeader *>(data + data_32[i + 8]);
}
}
return nullptr;
} else {
return reinterpret_cast<const InitialProcessBinaryHeader *>(data + header->meta.payload_sizes[0]);
}
}
constexpr size_t GetInitialProcessSize(const InitialProcessHeader *kip) {
return sizeof(*kip) + kip->rx_compressed_size + kip->ro_compressed_size + kip->rw_compressed_size;
}
const InitialProcessHeader *FindInitialProcessInBinary(const InitialProcessBinaryHeader *ini, u64 program_id) {
const u8 *data = reinterpret_cast<const u8 *>(ini + 1);
for (u32 i = 0; i < ini->num_processes; ++i) {
const InitialProcessHeader *kip = reinterpret_cast<const InitialProcessHeader *>(data);
if (kip->magic != InitialProcessHeader::Magic) {
return nullptr;
}
if (kip->program_id == program_id) {
return kip;
}
data += GetInitialProcessSize(kip);
}
return nullptr;
}
FsVersion GetFsVersion(const se::Sha256Hash &fs_hash) {
for (size_t i = 0; i < util::size(FsHashes); ++i) {
if (std::memcmp(fs_hash.bytes, FsHashes[i], sizeof(FsHashes[i])) == 0) {
return static_cast<FsVersion>(i);
}
}
return FsVersion_Count;
}
constinit InitialProcessMeta g_initial_process_meta = {};
constinit size_t g_initial_process_binary_size = 0;
void AddInitialProcessImpl(InitialProcessMeta *meta, const InitialProcessHeader *kip, const se::Sha256Hash *hash) {
/* Set the meta's fields. */
meta->next = nullptr;
meta->program_id = kip->program_id;
meta->kip = kip;
meta->kip_size = GetInitialProcessSize(kip);
/* Copy or calculate hash. */
if (hash != nullptr) {
std::memcpy(std::addressof(meta->kip_hash), hash, sizeof(meta->kip_hash));
} else {
se::CalculateSha256(std::addressof(meta->kip_hash), kip, meta->kip_size);
}
/* Clear patches. */
meta->patches_head = nullptr;
meta->patches_tail = nullptr;
meta->patch_segments = 0;
/* Increase the initial process binary's size. */
g_initial_process_binary_size += meta->kip_size;
}
bool AddInitialProcess(const InitialProcessHeader *kip, const se::Sha256Hash *hash = nullptr) {
/* Check kip magic. */
if (kip->magic != InitialProcessHeader::Magic) {
ShowFatalError("KIP seems corrupted!\n");
}
/* Handle the initial case. */
if (g_initial_process_binary_size == 0) {
AddInitialProcessImpl(std::addressof(g_initial_process_meta), kip, hash);
return true;
}
/* Check if we've already added the program id. */
InitialProcessMeta *cur = std::addressof(g_initial_process_meta);
while (true) {
if (cur->program_id == kip->program_id) {
return false;
}
if (cur->next != nullptr) {
cur = cur->next;
} else {
break;
}
}
/* Allocate an initial process meta. */
auto *new_meta = static_cast<InitialProcessMeta *>(AllocateAligned(sizeof(InitialProcessMeta), alignof(InitialProcessMeta)));
/* Insert the new meta. */
cur->next = new_meta;
AddInitialProcessImpl(new_meta, kip, hash);
return true;
}
InitialProcessMeta *FindInitialProcess(u64 program_id) {
for (InitialProcessMeta *cur = std::addressof(g_initial_process_meta); cur != nullptr; cur = cur->next) {
if (cur->program_id == program_id) {
return cur;
}
}
return nullptr;
}
u32 GetPatchSegments(const InitialProcessHeader *kip, u32 offset, size_t size) {
/* Create segment mask. */
u32 segments = 0;
/* Get the segment extents. */
const u32 rx_start = kip->rx_address;
const u32 ro_start = kip->ro_address;
const u32 rw_start = kip->rw_address;
const u32 rx_end = ro_start;
const u32 ro_end = rw_start;
const u32 rw_end = rw_start + kip->rw_size;
/* If the offset is below the kip header, ignore it. */
if (offset < sizeof(*kip)) {
return segments;
}
/* Adjust the offset in bounds. */
offset -= sizeof(*kip);
/* Check if the offset strays out of bounds. */
if (offset + size > rw_end) {
return segments;
}
/* Set bits for the affected segments. */
if (util::HasOverlap(offset, size, rx_start, rx_end - rx_start)) {
segments |= (1 << 0);
}
if (util::HasOverlap(offset, size, ro_start, ro_end - ro_start)) {
segments |= (1 << 1);
}
if (util::HasOverlap(offset, size, rw_start, rw_end - rw_start)) {
segments |= (1 << 2);
}
return segments;
}
void AddPatch(InitialProcessMeta *meta, u32 offset, const void *data, size_t data_size, bool is_memset = false) {
/* Determine the segment. */
const u32 segments = GetPatchSegments(meta->kip, offset, data_size);
/* If the patch hits no segments, we don't need it. */
if (segments == 0) {
return;
}
/* Update patch segments. */
meta->patch_segments |= segments;
/* Adjust offset. */
const u32 start_segment = util::CountTrailingZeros(segments);
offset -= sizeof(*meta->kip);
switch (start_segment) {
case 0: offset -= meta->kip->rx_address; break;
case 1: offset -= meta->kip->ro_address; break;
case 2: offset -= meta->kip->rw_address; break;
}
/* Create patch. */
auto *new_patch = static_cast<PatchMeta *>(AllocateAligned(sizeof(PatchMeta), alignof(PatchMeta)));
new_patch->next = nullptr;
new_patch->is_memset = is_memset;
new_patch->start_segment = start_segment;
new_patch->rel_offset = offset;
new_patch->data = data;
new_patch->size = data_size;
/* Add the patch. */
if (meta->patches_head == nullptr) {
meta->patches_head = new_patch;
} else {
meta->patches_tail->next = new_patch;
}
meta->patches_tail = new_patch;
}
constexpr const u8 NogcPatch0[] = {
0x80
};
constexpr const u8 NogcPatch1[] = {
0xE0, 0x03, 0x1F, 0x2A, 0xC0, 0x03, 0x5F, 0xD6,
};
void AddNogcPatches(InitialProcessMeta *fs_meta, FsVersion fs_version) {
switch (fs_version) {
case FsVersion_1_0_0:
case FsVersion_2_0_0:
case FsVersion_2_0_0_Exfat:
case FsVersion_2_1_0:
case FsVersion_2_1_0_Exfat:
case FsVersion_3_0_0:
case FsVersion_3_0_0_Exfat:
case FsVersion_3_0_1:
case FsVersion_3_0_1_Exfat:
/* There were no lotus firmware updates prior to 4.0.0. */
/* TODO: Implement patches, regardless? */
break;
case FsVersion_4_0_0:
case FsVersion_4_0_0_Exfat:
AddPatch(fs_meta, 0x0A3539, NogcPatch0, sizeof(NogcPatch0));
AddPatch(fs_meta, 0x0AAC44, NogcPatch1, sizeof(NogcPatch1));
break;
case FsVersion_4_1_0:
case FsVersion_4_1_0_Exfat:
AddPatch(fs_meta, 0x0A35BD, NogcPatch0, sizeof(NogcPatch0));
AddPatch(fs_meta, 0x0AACA8, NogcPatch1, sizeof(NogcPatch1));
break;
case FsVersion_5_0_0:
case FsVersion_5_0_0_Exfat:
AddPatch(fs_meta, 0x0CF4C5, NogcPatch0, sizeof(NogcPatch0));
AddPatch(fs_meta, 0x0D74A0, NogcPatch1, sizeof(NogcPatch1));
break;
case FsVersion_5_1_0:
case FsVersion_5_1_0_Exfat:
AddPatch(fs_meta, 0x0CF895, NogcPatch0, sizeof(NogcPatch0));
AddPatch(fs_meta, 0x0D7870, NogcPatch1, sizeof(NogcPatch1));
break;
case FsVersion_6_0_0:
AddPatch(fs_meta, 0x1539F5, NogcPatch0, sizeof(NogcPatch0));
AddPatch(fs_meta, 0x12CD20, NogcPatch1, sizeof(NogcPatch1));
break;
case FsVersion_6_0_0_Exfat:
AddPatch(fs_meta, 0x15F0F5, NogcPatch0, sizeof(NogcPatch0));
AddPatch(fs_meta, 0x138420, NogcPatch1, sizeof(NogcPatch1));
break;
case FsVersion_7_0_0:
AddPatch(fs_meta, 0x15C005, NogcPatch0, sizeof(NogcPatch0));
AddPatch(fs_meta, 0x134260, NogcPatch1, sizeof(NogcPatch1));
break;
case FsVersion_7_0_0_Exfat:
AddPatch(fs_meta, 0x1675B5, NogcPatch0, sizeof(NogcPatch0));
AddPatch(fs_meta, 0x13F810, NogcPatch1, sizeof(NogcPatch1));
break;
case FsVersion_8_0_0:
case FsVersion_8_1_0:
AddPatch(fs_meta, 0x15EC95, NogcPatch0, sizeof(NogcPatch0));
AddPatch(fs_meta, 0x136900, NogcPatch1, sizeof(NogcPatch1));
break;
case FsVersion_8_0_0_Exfat:
case FsVersion_8_1_0_Exfat:
AddPatch(fs_meta, 0x16A245, NogcPatch0, sizeof(NogcPatch0));
AddPatch(fs_meta, 0x141EB0, NogcPatch1, sizeof(NogcPatch1));
break;
case FsVersion_9_0_0:
case FsVersion_9_0_0_Exfat:
AddPatch(fs_meta, 0x143369, NogcPatch0, sizeof(NogcPatch0));
AddPatch(fs_meta, 0x129520, NogcPatch1, sizeof(NogcPatch1));
break;
case FsVersion_9_1_0:
case FsVersion_9_1_0_Exfat:
AddPatch(fs_meta, 0x143379, NogcPatch0, sizeof(NogcPatch0));
AddPatch(fs_meta, 0x129530, NogcPatch1, sizeof(NogcPatch1));
break;
case FsVersion_10_0_0:
case FsVersion_10_0_0_Exfat:
AddPatch(fs_meta, 0x14DF09, NogcPatch0, sizeof(NogcPatch0));
AddPatch(fs_meta, 0x13BF90, NogcPatch1, sizeof(NogcPatch1));
break;
case FsVersion_10_2_0:
case FsVersion_10_2_0_Exfat:
AddPatch(fs_meta, 0x14E369, NogcPatch0, sizeof(NogcPatch0));
AddPatch(fs_meta, 0x13C3F0, NogcPatch1, sizeof(NogcPatch1));
break;
case FsVersion_11_0_0:
case FsVersion_11_0_0_Exfat:
AddPatch(fs_meta, 0x156FB9, NogcPatch0, sizeof(NogcPatch0));
AddPatch(fs_meta, 0x1399B4, NogcPatch1, sizeof(NogcPatch1));
break;
case FsVersion_12_0_0:
case FsVersion_12_0_0_Exfat:
AddPatch(fs_meta, 0x155469, NogcPatch0, sizeof(NogcPatch0));
AddPatch(fs_meta, 0x13EB24, NogcPatch1, sizeof(NogcPatch1));
break;
case FsVersion_12_0_3:
case FsVersion_12_0_3_Exfat:
AddPatch(fs_meta, 0x155579, NogcPatch0, sizeof(NogcPatch0));
AddPatch(fs_meta, 0x13EC34, NogcPatch1, sizeof(NogcPatch1));
case FsVersion_13_0_0:
case FsVersion_13_0_0_Exfat:
AddPatch(fs_meta, 0x159119, NogcPatch0, sizeof(NogcPatch0));
AddPatch(fs_meta, 0x1426D0, NogcPatch1, sizeof(NogcPatch1));
break;
case FsVersion_13_1_0:
case FsVersion_13_1_0_Exfat:
AddPatch(fs_meta, 0x1590B9, NogcPatch0, sizeof(NogcPatch0));
AddPatch(fs_meta, 0x142670, NogcPatch1, sizeof(NogcPatch1));
break;
case FsVersion_14_0_0:
AddPatch(fs_meta, 0x18A3E9, NogcPatch0, sizeof(NogcPatch0));
AddPatch(fs_meta, 0x164330, NogcPatch1, sizeof(NogcPatch1));
break;
case FsVersion_14_0_0_Exfat:
AddPatch(fs_meta, 0x195769, NogcPatch0, sizeof(NogcPatch0));
AddPatch(fs_meta, 0x16F6B0, NogcPatch1, sizeof(NogcPatch1));
break;
case FsVersion_15_0_0:
AddPatch(fs_meta, 0x184259, NogcPatch0, sizeof(NogcPatch0));
AddPatch(fs_meta, 0x15EDE4, NogcPatch1, sizeof(NogcPatch1));
break;
case FsVersion_15_0_0_Exfat:
AddPatch(fs_meta, 0x18F1E9, NogcPatch0, sizeof(NogcPatch0));
AddPatch(fs_meta, 0x169D74, NogcPatch1, sizeof(NogcPatch1));
break;
case FsVersion_16_0_0:
AddPatch(fs_meta, 0x1866D9, NogcPatch0, sizeof(NogcPatch0));
AddPatch(fs_meta, 0x160C70, NogcPatch1, sizeof(NogcPatch1));
break;
case FsVersion_16_0_0_Exfat:
AddPatch(fs_meta, 0x1913B9, NogcPatch0, sizeof(NogcPatch0));
AddPatch(fs_meta, 0x16B950, NogcPatch1, sizeof(NogcPatch1));
break;
case FsVersion_16_0_3:
AddPatch(fs_meta, 0x186729, NogcPatch0, sizeof(NogcPatch0));
AddPatch(fs_meta, 0x160CC0, NogcPatch1, sizeof(NogcPatch1));
break;
case FsVersion_16_0_3_Exfat:
AddPatch(fs_meta, 0x191409, NogcPatch0, sizeof(NogcPatch0));
AddPatch(fs_meta, 0x16B9A0, NogcPatch1, sizeof(NogcPatch1));
break;
case FsVersion_17_0_0:
AddPatch(fs_meta, 0x18B149, NogcPatch0, sizeof(NogcPatch0));
AddPatch(fs_meta, 0x165200, NogcPatch1, sizeof(NogcPatch1));
break;
case FsVersion_17_0_0_Exfat:
AddPatch(fs_meta, 0x195FA9, NogcPatch0, sizeof(NogcPatch0));
AddPatch(fs_meta, 0x170060, NogcPatch1, sizeof(NogcPatch1));
break;
case FsVersion_18_0_0:
AddPatch(fs_meta, 0x18AF49, NogcPatch0, sizeof(NogcPatch0));
AddPatch(fs_meta, 0x164B50, NogcPatch1, sizeof(NogcPatch1));
break;
case FsVersion_18_0_0_Exfat:
AddPatch(fs_meta, 0x195FD9, NogcPatch0, sizeof(NogcPatch0));
AddPatch(fs_meta, 0x16FBE0, NogcPatch1, sizeof(NogcPatch1));
break;
case FsVersion_18_1_0:
AddPatch(fs_meta, 0x18AF49, NogcPatch0, sizeof(NogcPatch0));
AddPatch(fs_meta, 0x164B50, NogcPatch1, sizeof(NogcPatch1));
break;
case FsVersion_18_1_0_Exfat:
AddPatch(fs_meta, 0x195FD9, NogcPatch0, sizeof(NogcPatch0));
AddPatch(fs_meta, 0x16FBE0, NogcPatch1, sizeof(NogcPatch1));
break;
case FsVersion_19_0_0:
AddPatch(fs_meta, 0x195C75, NogcPatch0, sizeof(NogcPatch0));
AddPatch(fs_meta, 0x195E75, NogcPatch0, sizeof(NogcPatch0));
AddPatch(fs_meta, 0x16F170, NogcPatch1, sizeof(NogcPatch1));
break;
case FsVersion_19_0_0_Exfat:
AddPatch(fs_meta, 0x1A14A5, NogcPatch0, sizeof(NogcPatch0));
AddPatch(fs_meta, 0x1A16A5, NogcPatch0, sizeof(NogcPatch0));
AddPatch(fs_meta, 0x17A9A0, NogcPatch1, sizeof(NogcPatch1));
break;
default:
break;
}
}
struct BlzSegmentFlags {
using Offset = util::BitPack16::Field<0, 12, u32>;
using Size = util::BitPack16::Field<Offset::Next, 4, u32>;
};
void BlzUncompress(void *_end) {
/* Parse the footer, endian agnostic. */
static_assert(sizeof(u32) == 4);
static_assert(sizeof(u16) == 2);
static_assert(sizeof(u8) == 1);
u8 *end = static_cast<u8 *>(_end);
const u32 total_size = (end[-12] << 0) | (end[-11] << 8) | (end[-10] << 16) | (end[- 9] << 24);
const u32 footer_size = (end[- 8] << 0) | (end[- 7] << 8) | (end[- 6] << 16) | (end[- 5] << 24);
const u32 additional_size = (end[- 4] << 0) | (end[- 3] << 8) | (end[- 2] << 16) | (end[- 1] << 24);
/* Prepare to decompress. */
u8 *cmp_start = end - total_size;
u32 cmp_ofs = total_size - footer_size;
u32 out_ofs = total_size + additional_size;
/* Decompress. */
while (out_ofs) {
u8 control = cmp_start[--cmp_ofs];
/* Each bit in the control byte is a flag indicating compressed or not compressed. */
for (size_t i = 0; i < 8 && out_ofs; ++i, control <<= 1) {
if (control & 0x80) {
/* NOTE: Nintendo does not check if it's possible to decompress. */
/* As such, we will leave the following as a debug assertion, and not a release assertion. */
AMS_AUDIT(cmp_ofs >= sizeof(u16));
cmp_ofs -= sizeof(u16);
/* Extract segment bounds. */
const util::BitPack16 seg_flags{static_cast<u16>((cmp_start[cmp_ofs] << 0) | (cmp_start[cmp_ofs + 1] << 8))};
const u32 seg_ofs = seg_flags.Get<BlzSegmentFlags::Offset>() + 3;
const u32 seg_size = std::min(seg_flags.Get<BlzSegmentFlags::Size>() + 3, out_ofs);
AMS_AUDIT(out_ofs + seg_ofs <= total_size + additional_size);
/* Copy the data. */
out_ofs -= seg_size;
for (size_t j = 0; j < seg_size; j++) {
cmp_start[out_ofs + j] = cmp_start[out_ofs + seg_ofs + j];
}
} else {
/* NOTE: Nintendo does not check if it's possible to copy. */
/* As such, we will leave the following as a debug assertion, and not a release assertion. */
AMS_AUDIT(cmp_ofs >= sizeof(u8));
cmp_start[--out_ofs] = cmp_start[--cmp_ofs];
}
}
}
}
void *ReadFile(s64 *out_size, const char *path, size_t align = 0x10) {
fs::FileHandle file;
if (R_SUCCEEDED(fs::OpenFile(std::addressof(file), path, fs::OpenMode_Read))) {
ON_SCOPE_EXIT { fs::CloseFile(file); };
Result result;
/* Get the kip size. */
if (R_FAILED((result = fs::GetFileSize(out_size, file)))) {
ShowFatalError("Failed to get size (0x%08" PRIx32 ") of %s!\n", result.GetValue(), path);
}
/* Allocate file. */
void *data = AllocateAligned(*out_size, std::max<size_t>(align, 0x10));
/* Read the file. */
if (R_FAILED((result = fs::ReadFile(file, 0, data, *out_size)))) {
ShowFatalError("Failed to read (0x%08" PRIx32 ") %s!\n", result.GetValue(), path);
}
return data;
} else {
return nullptr;
}
}
}
u32 ConfigureStratosphere(const u8 *nn_package2, ams::TargetFirmware target_firmware, bool emummc_enabled, bool nogc_enabled) {
/* Load KIPs off the SD card. */
{
/* Create kip dir path. */
char kip_path[0x120];
std::memcpy(kip_path, "sdmc:/atmosphere/kips", 0x16);
fs::DirectoryHandle kip_dir;
if (R_SUCCEEDED(fs::OpenDirectory(std::addressof(kip_dir), kip_path))) {
ON_SCOPE_EXIT { fs::CloseDirectory(kip_dir); };
s64 count;
fs::DirectoryEntry entries[1];
while (R_SUCCEEDED(fs::ReadDirectory(std::addressof(count), entries, kip_dir, util::size(entries))) && count > 0) {
/* Check that file is a file. */
if (fs::GetEntryType(entries[0]) != fs::DirectoryEntryType_File) {
continue;
}
/* Get filename length. */
const int name_len = std::strlen(entries[0].file_name);
/* Adjust kip path. */
kip_path[0x15] = '/';
std::memcpy(kip_path + 0x16, entries[0].file_name, name_len + 1);
/* Check that file is ".kip" or ".kip1" file. */
const int path_len = 0x16 + name_len;
if (std::memcmp(kip_path + path_len - 4, ".kip", 5) != 0 && std::memcmp(kip_path + path_len - 5, ".kip1", 6) != 0) {
continue;
}
/* Read the kip. */
s64 file_size;
if (InitialProcessHeader *kip = static_cast<InitialProcessHeader *>(ReadFile(std::addressof(file_size), kip_path, alignof(InitialProcessHeader))); kip != nullptr) {
/* If the kip is valid, add it. */
if (kip->magic == InitialProcessHeader::Magic && file_size == GetInitialProcessSize(kip)) {
AddInitialProcess(kip);
}
}
}
}
}
/* Add the stratosphere kips. */
{
const auto &external_package = GetExternalPackage();
for (u32 i = 0; i < external_package.header.num_kips; ++i) {
const auto &meta = external_package.header.kip_metas[i];
AddInitialProcess(reinterpret_cast<const InitialProcessHeader *>(external_package.kips + meta.offset), std::addressof(meta.hash));
}
}
/* Get meta for FS process. */
auto *fs_meta = FindInitialProcess(FsProgramId);
if (fs_meta == nullptr) {
/* Get nintendo header/data. */
const pkg2::Package2Header *nn_header = reinterpret_cast<const pkg2::Package2Header *>(nn_package2);
const u8 *nn_data = nn_package2 + sizeof(*nn_header);
/* Get Nintendo INI1. */
const InitialProcessBinaryHeader *nn_ini = FindInitialProcessBinary(nn_header, nn_data, target_firmware);
if (nn_ini == nullptr || nn_ini->magic != InitialProcessBinaryHeader::Magic) {
ShowFatalError("Failed to find INI1!\n");
}
/* Find FS KIP. */
const InitialProcessHeader *nn_fs_kip = FindInitialProcessInBinary(nn_ini, FsProgramId);
if (nn_fs_kip == nullptr) {
ShowFatalError("Failed to find FS!\n");
}
/* Add to binary. */
AddInitialProcess(nn_fs_kip);
/* Re-find meta. */
fs_meta = FindInitialProcess(FsProgramId);
}
/* Check that we found FS. */
if (fs_meta == nullptr) {
ShowFatalError("Failed to find FS!\n");
}
/* Get FS version. */
const auto fs_version = GetFsVersion(fs_meta->kip_hash);
if (fs_version >= FsVersion_Count) {
if (emummc_enabled || nogc_enabled) {
ShowFatalError("Failed to identify FS!\n");
}
}
/* If emummc is enabled, we need to decompress fs .text. */
if (emummc_enabled) {
fs_meta->patch_segments |= (1 << 0);
}
/* Parse/prepare relevant nogc/kip patches. */
{
/* Add nogc patches. */
if (nogc_enabled) {
AddNogcPatches(fs_meta, fs_version);
}
/* TODO ams.tma2: add mount_host patches. */
}
/* Return the fs version we're using. */
return static_cast<u32>(fs_version);
}
void RebuildPackage2(ams::TargetFirmware target_firmware, bool emummc_enabled) {
/* Get the external package. */
const auto &external_package = GetExternalPackage();
/* Clear package2 header. */
auto *package2 = secmon::MemoryRegionDramPackage2.GetPointer<pkg2::Package2Header>();
std::memset(package2, 0, sizeof(*package2));
/* Get payload data pointer. */
u8 * const payload_data = reinterpret_cast<u8 *>(package2 + 1);
/* Useful values. */
constexpr u32 KernelPayloadBase = 0x60000;
/* Set fields. */
package2->meta.key_generation = pkg1::KeyGeneration_Current;
std::memcpy(package2->meta.magic, pkg2::Package2Meta::Magic::String, sizeof(package2->meta.magic));
package2->meta.entrypoint = KernelPayloadBase;
package2->meta.bootloader_version = pkg2::CurrentBootloaderVersion;
package2->meta.package2_version = pkg2::MinimumValidDataVersion;
/* Load mesosphere. */
s64 meso_size;
if (void *sd_meso = ReadFile(std::addressof(meso_size), "sdmc:/atmosphere/mesosphere.bin"); sd_meso != nullptr) {
std::memcpy(payload_data, sd_meso, meso_size);
} else {
meso_size = external_package.header.meso_size;
std::memcpy(payload_data, external_package.mesosphere, meso_size);
}
/* Read emummc, if needed. */
const InitialProcessHeader *emummc;
s64 emummc_size;
if (emummc_enabled) {
emummc = static_cast<const InitialProcessHeader *>(ReadFile(std::addressof(emummc_size), "sdmc:/atmosphere/emummc.kip"));
if (emummc == nullptr) {
emummc = reinterpret_cast<const InitialProcessHeader *>(external_package.kips + external_package.header.emummc_meta.offset);
emummc_size = external_package.header.emummc_meta.size;
}
}
/* Set the embedded ini pointer. */
const u32 magic = *reinterpret_cast<const u32 *>(payload_data + 4);
if (magic == MesoshereMetadataLayout0Magic) {
std::memcpy(payload_data + 8, std::addressof(meso_size), sizeof(meso_size));
} else if (magic == MesoshereMetadataLayout1Magic) {
if (const u32 meta_offset = *reinterpret_cast<const u32 *>(payload_data + 8); meta_offset <= meso_size - sizeof(meso_size)) {
s64 relative_offset = meso_size - meta_offset;
std::memcpy(payload_data + meta_offset, std::addressof(relative_offset), sizeof(relative_offset));
} else {
ShowFatalError("Invalid mesosphere metadata layout!\n");
}
} else {
ShowFatalError("Unknown mesosphere metadata version!\n");
}
/* Get the ini pointer. */
InitialProcessBinaryHeader * const ini = reinterpret_cast<InitialProcessBinaryHeader *>(payload_data + meso_size);
/* Set ini fields. */
ini->magic = InitialProcessBinaryHeader::Magic;
ini->num_processes = 0;
ini->reserved = 0;
/* Iterate all processes. */
u8 * const dst_kip_start = reinterpret_cast<u8 *>(ini + 1);
u8 * dst_kip_cur = dst_kip_start;
for (InitialProcessMeta *meta = std::addressof(g_initial_process_meta); meta != nullptr; meta = meta->next) {
/* Get the current kip. */
const auto *src_kip = meta->kip;
auto *dst_kip = reinterpret_cast<InitialProcessHeader *>(dst_kip_cur);
/* Copy the kip header */
std::memcpy(dst_kip, src_kip, sizeof(*src_kip));
const u8 *src_kip_data = reinterpret_cast<const u8 *>(src_kip + 1);
u8 *dst_kip_data = reinterpret_cast< u8 *>(dst_kip + 1);
/* If necessary, inject emummc. */
u32 addl_text_offset = 0;
if (dst_kip->program_id == FsProgramId && emummc_enabled) {
/* Get emummc extents. */
addl_text_offset = emummc->bss_address + emummc->bss_size;
if ((emummc->flags & 7) || !util::IsAligned(addl_text_offset, 0x1000)) {
ShowFatalError("Invalid emummc kip!\n");
}
/* Copy emummc capabilities. */
{
std::memcpy(dst_kip->capabilities, emummc->capabilities, sizeof(emummc->capabilities));
if (target_firmware <= ams::TargetFirmware_1_0_0) {
for (size_t i = 0; i < util::size(dst_kip->capabilities); ++i) {
if (dst_kip->capabilities[i] == 0xFFFFFFFF) {
dst_kip->capabilities[i] = 0x07000E7F;
break;
}
}
}
}
/* Update section headers. */
dst_kip->ro_address += addl_text_offset;
dst_kip->rw_address += addl_text_offset;
dst_kip->bss_address += addl_text_offset;
/* Get emummc sections. */
const u8 *emummc_data = reinterpret_cast<const u8 *>(emummc + 1);
/* Copy emummc sections. */
std::memcpy(dst_kip_data + emummc->rx_address, emummc_data, emummc->rx_compressed_size);
std::memcpy(dst_kip_data + emummc->ro_address, emummc_data + emummc->rx_compressed_size, emummc->ro_compressed_size);
std::memcpy(dst_kip_data + emummc->rw_address, emummc_data + emummc->rx_compressed_size + emummc->ro_compressed_size, emummc->rw_compressed_size);
std::memset(dst_kip_data + emummc->bss_address, 0, emummc->bss_size);
/* Advance. */
dst_kip_data += addl_text_offset;
}
/* Prepare to process segments. */
u8 *dst_rx_data, *dst_ro_data, *dst_rw_data;
/* Process .text. */
{
dst_rx_data = dst_kip_data;
std::memcpy(dst_kip_data, src_kip_data, src_kip->rx_compressed_size);
/* Uncompress, if necessary. */
if ((meta->patch_segments & src_kip->flags) & (1 << 0)) {
BlzUncompress(dst_kip_data + dst_kip->rx_compressed_size);
dst_kip->rx_compressed_size = dst_kip->rx_size;
}
/* Advance. */
dst_kip_data += dst_kip->rx_compressed_size;
src_kip_data += src_kip->rx_compressed_size;
/* Account for potential emummc. */
dst_kip->rx_size += addl_text_offset;
dst_kip->rx_compressed_size += addl_text_offset;
}
/* Process .rodata. */
{
dst_ro_data = dst_kip_data;
std::memcpy(dst_kip_data, src_kip_data, src_kip->ro_compressed_size);
/* Uncompress, if necessary. */
if ((meta->patch_segments & src_kip->flags) & (1 << 1)) {
BlzUncompress(dst_kip_data + dst_kip->ro_compressed_size);
dst_kip->ro_compressed_size = dst_kip->ro_size;
}
/* Advance. */
dst_kip_data += dst_kip->ro_compressed_size;
src_kip_data += src_kip->ro_compressed_size;
}
/* Process .rwdata. */
{
dst_rw_data = dst_kip_data;
std::memcpy(dst_kip_data, src_kip_data, src_kip->rw_compressed_size);
/* Uncompress, if necessary. */
if ((meta->patch_segments & src_kip->flags) & (1 << 2)) {
BlzUncompress(dst_kip_data + dst_kip->rw_compressed_size);
dst_kip->rw_compressed_size = dst_kip->rw_size;
}
/* Advance. */
dst_kip_data += dst_kip->rw_compressed_size;
src_kip_data += src_kip->rw_compressed_size;
}
/* Adjust flags. */
dst_kip->flags &= ~meta->patch_segments;
/* Apply patches. */
for (auto *patch = meta->patches_head; patch != nullptr; patch = patch->next) {
/* Get the destination segment. */
u8 *patch_dst_segment;
switch (patch->start_segment) {
case 0: patch_dst_segment = dst_rx_data; break;
case 1: patch_dst_segment = dst_ro_data; break;
case 2: patch_dst_segment = dst_rw_data; break;
default: ShowFatalError("Unknown patch segment %" PRIu32 "\n", patch->start_segment); break;
}
/* Get the destination. */
u8 * const patch_dst = patch_dst_segment + patch->rel_offset;
/* Apply the patch. */
if (patch->is_memset) {
const u8 val = *static_cast<const u8 *>(patch->data);
std::memset(patch_dst, val, patch->size);
} else {
std::memcpy(patch_dst, patch->data, patch->size);
}
}
/* Advance. */
dst_kip_cur += GetInitialProcessSize(dst_kip);
/* Increment num kips. */
++ini->num_processes;
}
/* Set INI size. */
ini->size = sizeof(*ini) + (dst_kip_cur - dst_kip_start);
if (ini->size > 12_MB) {
ShowFatalError("INI is too big! (0x%08" PRIx32 ")\n", ini->size);
}
/* Set the payload size/offset. */
package2->meta.payload_offsets[0] = KernelPayloadBase;
package2->meta.payload_sizes[0] = util::AlignUp(meso_size + ini->size, 0x10);
/* Set total size. */
package2->meta.package2_size = sizeof(*package2) + package2->meta.payload_sizes[0];
}
}
| 46,907
|
C++
|
.cpp
| 897
| 37.22631
| 184
| 0.521696
|
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,304
|
fusee_mmc.cpp
|
Atmosphere-NX_Atmosphere/fusee/program/source/fusee_mmc.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <exosphere.hpp>
#include "fusee_mmc.hpp"
namespace ams::nxboot {
namespace {
constexpr inline auto MmcPort = sdmmc::Port_Mmc0;
alignas(0x10) constinit u8 g_mmc_work_buffer[sdmmc::MmcWorkBufferSize];
constinit inline auto g_mmc_partition = sdmmc::MmcPartition_Unknown;
Result SelectMmcPartition(sdmmc::MmcPartition partition) {
/* Change partition, if we need to. */
if (partition != g_mmc_partition) {
R_TRY(sdmmc::SelectMmcPartition(MmcPort, partition));
g_mmc_partition = partition;
}
R_SUCCEED();
}
}
Result InitializeMmc() {
/* Initialize the mmc. */
sdmmc::Initialize(MmcPort);
/* Set the mmc work buffer. */
sdmmc::SetMmcWorkBuffer(MmcPort, g_mmc_work_buffer, sizeof(g_mmc_work_buffer));
/* Activate the mmc. */
R_RETURN(sdmmc::Activate(MmcPort));
}
Result CheckMmcConnection(sdmmc::SpeedMode *out_sm, sdmmc::BusWidth *out_bw) {
R_RETURN(sdmmc::CheckMmcConnection(out_sm, out_bw, MmcPort));
}
Result GetMmcMemoryCapacity(u32 *out_num_sectors, sdmmc::MmcPartition partition) {
if (partition == sdmmc::MmcPartition_UserData) {
R_RETURN(sdmmc::GetDeviceMemoryCapacity(out_num_sectors, MmcPort));
} else {
R_RETURN(sdmmc::GetMmcBootPartitionCapacity(out_num_sectors, MmcPort));
}
}
Result ReadMmc(void *dst, size_t size, sdmmc::MmcPartition partition, size_t sector_index, size_t sector_count) {
R_TRY(SelectMmcPartition(partition));
R_RETURN(sdmmc::Read(dst, size, MmcPort, sector_index, sector_count));
}
Result WriteMmc(sdmmc::MmcPartition partition, size_t sector_index, size_t sector_count, const void *src, size_t size) {
R_TRY(SelectMmcPartition(partition));
R_RETURN(sdmmc::Write(MmcPort, sector_index, sector_count, src, size));
}
}
| 2,608
|
C++
|
.cpp
| 58
| 38.206897
| 124
| 0.676401
|
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,305
|
fusee_emummc.cpp
|
Atmosphere-NX_Atmosphere/fusee/program/source/fusee_emummc.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 "fusee_emummc.hpp"
#include "fusee_mmc.hpp"
#include "fusee_sd_card.hpp"
#include "fusee_fatal.hpp"
#include "fusee_malloc.hpp"
#include "fs/fusee_fs_api.hpp"
#include "fs/fusee_fs_storage.hpp"
namespace ams::nxboot {
namespace {
class SdCardStorage : public fs::IStorage {
public:
virtual Result Read(s64 offset, void *buffer, size_t size) override {
if (!util::IsAligned(offset, sdmmc::SectorSize) || !util::IsAligned(size, sdmmc::SectorSize)) {
ShowFatalError("SdCard: unaligned access to %" PRIx64 ", size=%" PRIx64"\n", static_cast<u64>(offset), static_cast<u64>(size));
}
R_RETURN(ReadSdCard(buffer, size, offset / sdmmc::SectorSize, size / sdmmc::SectorSize));
}
virtual Result Flush() override {
R_SUCCEED();
}
virtual Result GetSize(s64 *out) override {
u32 num_sectors;
R_TRY(GetSdCardMemoryCapacity(std::addressof(num_sectors)));
*out = static_cast<s64>(num_sectors) * static_cast<s64>(sdmmc::SectorSize);
R_SUCCEED();
}
virtual Result Write(s64 offset, const void *buffer, size_t size) override {
R_THROW(fs::ResultUnsupportedOperation());
}
virtual Result SetSize(s64 size) override {
R_THROW(fs::ResultUnsupportedOperation());
}
};
template<sdmmc::MmcPartition Partition>
class MmcPartitionStorage : public fs::IStorage {
public:
constexpr MmcPartitionStorage() { /* ... */ }
virtual Result Read(s64 offset, void *buffer, size_t size) override {
if (!util::IsAligned(offset, sdmmc::SectorSize) || !util::IsAligned(size, sdmmc::SectorSize)) {
ShowFatalError("SdCard: unaligned access to %" PRIx64 ", size=%" PRIx64"\n", static_cast<u64>(offset), static_cast<u64>(size));
}
R_RETURN(ReadMmc(buffer, size, Partition, offset / sdmmc::SectorSize, size / sdmmc::SectorSize));
}
virtual Result Flush() override {
R_SUCCEED();
}
virtual Result GetSize(s64 *out) override {
u32 num_sectors;
R_TRY(GetMmcMemoryCapacity(std::addressof(num_sectors), Partition));
*out = num_sectors * sdmmc::SectorSize;
R_SUCCEED();
}
virtual Result Write(s64 offset, const void *buffer, size_t size) override {
R_THROW(fs::ResultUnsupportedOperation());
}
virtual Result SetSize(s64 size) override {
R_THROW(fs::ResultUnsupportedOperation());
}
};
using MmcBoot0Storage = MmcPartitionStorage<sdmmc::MmcPartition_BootPartition1>;
using MmcUserStorage = MmcPartitionStorage<sdmmc::MmcPartition_UserData>;
constinit char g_emummc_path[0x300];
class EmummcFileStorage : public fs::IStorage {
private:
s64 m_file_size;
fs::FileHandle m_handles[64];
bool m_open[64];
int m_file_path_ofs;
private:
void EnsureFile(int id) {
if (!m_open[id]) {
/* Update path. */
g_emummc_path[m_file_path_ofs + 1] = '0' + (id % 10);
g_emummc_path[m_file_path_ofs + 0] = '0' + (id / 10);
/* Open new file. */
const Result result = fs::OpenFile(m_handles + id, g_emummc_path, fs::OpenMode_Read);
if (R_FAILED(result)) {
ShowFatalError("Failed to open emummc user %02d file: 0x%08" PRIx32 "!\n", id, result.GetValue());
}
m_open[id] = true;
}
}
public:
EmummcFileStorage(fs::FileHandle user00, int ofs) : m_file_path_ofs(ofs) {
const Result result = fs::GetFileSize(std::addressof(m_file_size), user00);
if (R_FAILED(result)) {
ShowFatalError("Failed to get emummc file size: 0x%08" PRIx32 "!\n", result.GetValue());
}
for (size_t i = 0; i < util::size(m_handles); ++i) {
m_open[i] = false;
}
m_handles[0] = user00;
m_open[0] = true;
}
virtual Result Read(s64 offset, void *buffer, size_t size) override {
int file = offset / m_file_size;
s64 subofs = offset % m_file_size;
u8 *cur_dst = static_cast<u8 *>(buffer);
for (/* ... */; size > 0; ++file) {
/* Ensure the current file is open. */
EnsureFile(file);
/* Perform the current read. */
const size_t cur_size = std::min<size_t>(m_file_size - subofs, size);
R_TRY(fs::ReadFile(m_handles[file], subofs, cur_dst, cur_size));
/* Advance. */
cur_dst += cur_size;
size -= cur_size;
subofs = 0;
}
R_SUCCEED();
}
virtual Result Flush() override {
R_THROW(fs::ResultUnsupportedOperation());
}
virtual Result GetSize(s64 *out) override {
R_THROW(fs::ResultUnsupportedOperation());
}
virtual Result Write(s64 offset, const void *buffer, size_t size) override {
R_THROW(fs::ResultUnsupportedOperation());
}
virtual Result SetSize(s64 size) override {
R_THROW(fs::ResultUnsupportedOperation());
}
};
constinit SdCardStorage g_sd_card_storage;
constinit MmcBoot0Storage g_mmc_boot0_storage;
constinit MmcUserStorage g_mmc_user_storage;
constinit fs::IStorage *g_boot0_storage = nullptr;
constinit fs::IStorage *g_user_storage = nullptr;
constinit fs::SubStorage *g_package2_storage = nullptr;
struct Guid {
u32 data1;
u16 data2;
u16 data3;
u8 data4[8];
};
static_assert(sizeof(Guid) == 0x10);
struct GptHeader {
char signature[8];
u32 revision;
u32 header_size;
u32 header_crc32;
u32 reserved0;
u64 my_lba;
u64 alt_lba;
u64 first_usable_lba;
u64 last_usable_lba;
Guid disk_guid;
u64 partition_entry_lba;
u32 number_of_partition_entries;
u32 size_of_partition_entry;
u32 partition_entry_array_crc32;
u32 reserved1;
};
static_assert(sizeof(GptHeader) == 0x60);
struct GptPartitionEntry {
Guid partition_type_guid;
Guid unique_partition_guid;
u64 starting_lba;
u64 ending_lba;
u64 attributes;
char partition_name[0x48];
};
static_assert(sizeof(GptPartitionEntry) == 0x80);
struct Gpt {
GptHeader header;
u8 padding[0x1A0];
GptPartitionEntry entries[128];
};
static_assert(sizeof(Gpt) == 16_KB + 0x200);
constexpr const u16 Package2PartitionName[] = {
'B', 'C', 'P', 'K', 'G', '2', '-', '1', '-', 'N', 'o', 'r', 'm', 'a', 'l', '-', 'M', 'a', 'i', 'n', 0
};
}
void InitializeEmummc(bool emummc_enabled, const secmon::EmummcConfiguration &emummc_cfg) {
Result result;
if (emummc_enabled) {
/* Get sd card size. */
s64 sd_card_size;
if (R_FAILED((result = g_sd_card_storage.GetSize(std::addressof(sd_card_size))))) {
ShowFatalError("Failed to get sd card size: 0x%08" PRIx32 "!\n", result.GetValue());
}
if (emummc_cfg.base_cfg.type == secmon::EmummcType_Partition) {
const s64 partition_start = emummc_cfg.partition_cfg.start_sector * sdmmc::SectorSize;
g_boot0_storage = AllocateObject<fs::SubStorage>(g_sd_card_storage, partition_start, 4_MB);
g_user_storage = AllocateObject<fs::SubStorage>(g_sd_card_storage, partition_start + 8_MB, sd_card_size - (partition_start + 8_MB));
} else if (emummc_cfg.base_cfg.type == secmon::EmummcType_File) {
/* Get the base emummc path. */
std::memcpy(g_emummc_path, emummc_cfg.file_cfg.path.str, sizeof(emummc_cfg.file_cfg.path.str));
/* Get path length. */
auto len = std::strlen(g_emummc_path);
/* Append emmc. */
std::memcpy(g_emummc_path + len, "/eMMC", 6);
len += 5;
/* Open boot0. */
fs::FileHandle boot0_file;
std::memcpy(g_emummc_path + len, "/boot0", 7);
if (R_FAILED((result = fs::OpenFile(std::addressof(boot0_file), g_emummc_path, fs::OpenMode_Read)))) {
ShowFatalError("Failed to open emummc boot0 file: 0x%08" PRIx32 "!\n", result.GetValue());
}
/* Open boot1. */
g_emummc_path[len + 5] = '1';
{
fs::DirectoryEntryType entry_type;
bool is_archive;
if (R_FAILED((result = fs::GetEntryType(std::addressof(entry_type), std::addressof(is_archive), g_emummc_path)))) {
ShowFatalError("Failed to find emummc boot1 file: 0x%08" PRIx32 "!\n", result.GetValue());
}
if (entry_type != fs::DirectoryEntryType_File) {
ShowFatalError("emummc boot1 file is not a file!\n");
}
}
/* Open userdata. */
std::memcpy(g_emummc_path + len, "/00", 4);
fs::FileHandle user00_file;
if (R_FAILED((result = fs::OpenFile(std::addressof(user00_file), g_emummc_path, fs::OpenMode_Read)))) {
ShowFatalError("Failed to open emummc user %02d file: 0x%08" PRIx32 "!\n", 0, result.GetValue());
}
/* Create partitions. */
g_boot0_storage = AllocateObject<fs::FileHandleStorage>(boot0_file);
g_user_storage = AllocateObject<EmummcFileStorage>(user00_file, len + 1);
} else {
ShowFatalError("Unknown emummc type %d\n", static_cast<int>(emummc_cfg.base_cfg.type));
}
} else {
/* Initialize access to mmc. */
{
const Result result = InitializeMmc();
if (R_FAILED(result)) {
ShowFatalError("Failed to initialize mmc: 0x%08" PRIx32 "\n", result.GetValue());
}
}
/* Create storages. */
g_boot0_storage = std::addressof(g_mmc_boot0_storage);
g_user_storage = std::addressof(g_mmc_user_storage);
}
if (g_boot0_storage == nullptr) {
ShowFatalError("Failed to initialize BOOT0\n");
}
if (g_user_storage == nullptr) {
ShowFatalError("Failed to initialize Raw EMMC\n");
}
/* Read the GPT. */
Gpt *gpt = static_cast<Gpt *>(AllocateAligned(sizeof(Gpt), 0x200));
{
const Result result = g_user_storage->Read(0x200, gpt, sizeof(*gpt));
if (R_FAILED(result)) {
ShowFatalError("Failed to read GPT: 0x%08" PRIx32 "\n", result.GetValue());
}
}
/* Check the GPT. */
if (std::memcmp(gpt->header.signature, "EFI PART", 8) != 0) {
ShowFatalError("Invalid GPT signature\n");
}
if (gpt->header.number_of_partition_entries > util::size(gpt->entries)) {
ShowFatalError("Too many GPT entries\n");
}
/* Create system storage. */
for (u32 i = 0; i < gpt->header.number_of_partition_entries; ++i) {
if (gpt->entries[i].starting_lba < gpt->header.first_usable_lba) {
continue;
}
const s64 offset = INT64_C(0x200) * gpt->entries[i].starting_lba;
const u64 size = UINT64_C(0x200) * (gpt->entries[i].ending_lba + 1 - gpt->entries[i].starting_lba);
if (std::memcmp(gpt->entries[i].partition_name, Package2PartitionName, sizeof(Package2PartitionName)) == 0) {
g_package2_storage = AllocateObject<fs::SubStorage>(*g_user_storage, offset, size);
}
}
/* Check that we created package2 storage. */
if (g_package2_storage == nullptr) {
ShowFatalError("Failed to initialize Package2\n");
}
}
Result ReadBoot0(s64 offset, void *dst, size_t size) {
R_RETURN(g_boot0_storage->Read(offset, dst, size));
}
Result ReadPackage2(s64 offset, void *dst, size_t size) {
R_RETURN(g_package2_storage->Read(offset, dst, size));
}
}
| 14,366
|
C++
|
.cpp
| 296
| 33.962838
| 151
| 0.52488
|
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,306
|
fusee_uncompress.cpp
|
Atmosphere-NX_Atmosphere/fusee/program/source/fusee_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 "fusee_uncompress.hpp"
namespace ams::nxboot {
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,813
|
C++
|
.cpp
| 85
| 28.952941
| 242
| 0.472918
|
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,307
|
fusee_cpu.cpp
|
Atmosphere-NX_Atmosphere/fusee/program/source/fusee_cpu.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 "fusee_cpu.hpp"
namespace ams::nxboot {
namespace {
constexpr inline const uintptr_t CLKRST = secmon::MemoryRegionPhysicalDeviceClkRst.GetAddress();
constexpr inline const uintptr_t PMC = secmon::MemoryRegionPhysicalDevicePmc.GetAddress();
constexpr inline const uintptr_t FLOW = secmon::MemoryRegionPhysicalDeviceFlowController.GetAddress();
constexpr inline const uintptr_t EVP = secmon::MemoryRegionPhysicalDeviceExceptionVectors.GetAddress();
constexpr inline const uintptr_t SYSTEM = secmon::MemoryRegionPhysicalDeviceSystem.GetAddress();
bool IsPartitionPowered(u32 mask) {
return (reg::Read(PMC + APBDEV_PMC_PWRGATE_STATUS) & mask) == mask;
}
void PowerOnPartition(u32 status_mask, u32 toggle_mask) {
/* Check if the partition is already powered on. */
if (IsPartitionPowered(status_mask)) {
return;
}
/* Wait for PWRGATE_TOGGLE to be idle. */
auto 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) {
return;
}
}
/* Toggle on the desired partition. */
reg::SetField(toggle_mask, PMC_REG_BITS_ENUM(PWRGATE_TOGGLE_START, ENABLE));
reg::Write(PMC + APBDEV_PMC_PWRGATE_TOGGLE, toggle_mask);
/* Wait for the partition to be powered. */
timeout = 5000;
while (true) {
if (IsPartitionPowered(status_mask)) {
break;
}
util::WaitMicroSeconds(1);
if ((--timeout) < 0) {
return;
}
}
}
}
void SetupCpu(uintptr_t entrypoint) {
/* Set ACTIVE_CLUSTER to FAST. */
reg::ReadWrite(FLOW + FLOW_CTLR_BPMP_CLUSTER_CONTROL, FLOW_REG_BITS_ENUM(BPMP_CLUSTER_CONTROL_ACTIVE_CLUSTER, FAST));
/* Enable VDD_CPU. */
pmic::EnableVddCpu(fuse::GetRegulator());
/* Enable clock to the cpu. */
{
/* Initialize PllX */
if (!reg::HasValue(CLKRST + CLK_RST_CONTROLLER_PLLX_BASE, CLK_RST_REG_BITS_ENUM(PLLX_BASE_PLLX_ENABLE, ENABLE))) {
/* Disable IDDQ. */
reg::ReadWrite(CLKRST + CLK_RST_CONTROLLER_PLLX_MISC3, CLK_RST_REG_BITS_VALUE(PLLX_MISC3_PLLX_IDDQ, 0));
/* Wait two microseconds. */
util::WaitMicroSeconds(2);
/* Configure PLLX dividers. */
reg::Write(CLKRST + CLK_RST_CONTROLLER_PLLX_BASE, 0x80404E02);
reg::Write(CLKRST + CLK_RST_CONTROLLER_PLLX_BASE, 0x00404E02);
/* Set PLLX_LOCK_ENABLE. */
reg::ReadWrite(CLKRST + CLK_RST_CONTROLLER_PLLX_MISC, CLK_RST_REG_BITS_ENUM(PLLX_MISC_PLLX_LOCK_ENABLE, ENABLE));
/* Enable PLLX. */
reg::Write(CLKRST + CLK_RST_CONTROLLER_PLLX_BASE, 0x40404E02);
}
/* Wait for PLLX to be locked. */
while (!reg::HasValue(CLKRST + CLK_RST_CONTROLLER_PLLX_BASE, CLK_RST_REG_BITS_ENUM(PLLX_BASE_PLLX_LOCK, LOCK))) {
/* ... */
}
/* Select MSELECT clock source as PLLP_OUT0 with divider of 4. */
reg::ReadWrite(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::ReadWrite(CLKRST + CLK_RST_CONTROLLER_CLK_OUT_ENB_V, CLK_RST_REG_BITS_ENUM(CLK_OUT_ENB_V_CLK_ENB_MSELECT, ENABLE));
/* Configure CCLK_BURST_POLICY. */
reg::Write(CLKRST + CLK_RST_CONTROLLER_CCLK_BURST_POLICY, CLK_RST_REG_BITS_ENUM(CCLK_BURST_POLICY_CWAKEUP_IDLE_SOURCE, PLLX_OUT0_LJ),
CLK_RST_REG_BITS_ENUM(CCLK_BURST_POLICY_CWAKEUP_RUN_SOURCE, PLLX_OUT0_LJ),
CLK_RST_REG_BITS_ENUM(CCLK_BURST_POLICY_CWAKEUP_IRQ_SOURCE, PLLX_OUT0_LJ),
CLK_RST_REG_BITS_ENUM(CCLK_BURST_POLICY_CWAKEUP_FIQ_SOURCE, PLLX_OUT0_LJ),
CLK_RST_REG_BITS_ENUM(CCLK_BURST_POLICY_CPU_STATE, RUN));
/* Configure SUPER_CCLK_DIVIDER. */
reg::Write(CLKRST + CLK_RST_CONTROLLER_SUPER_CCLK_DIVIDER, CLK_RST_REG_BITS_ENUM (SUPER_CCLK_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 CPUG. */
reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_ENB_V_SET, CLK_RST_REG_BITS_ENUM(CLK_ENB_V_SET_SET_CLK_ENB_CPUG, ENABLE));
}
/* Enable coresight. */
clkrst::EnableCsiteClock();
/* 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));
/* Power on cpu rails. */
{
PowerOnPartition(reg::EncodeValue(PMC_REG_BITS_ENUM(PWRGATE_STATUS_CRAIL, ON)), reg::EncodeValue(PMC_REG_BITS_ENUM(PWRGATE_TOGGLE_PARTID, CRAIL)));
PowerOnPartition(reg::EncodeValue(PMC_REG_BITS_ENUM(PWRGATE_STATUS_C0NC, ON)), reg::EncodeValue(PMC_REG_BITS_ENUM(PWRGATE_TOGGLE_PARTID, C0NC)));
PowerOnPartition(reg::EncodeValue(PMC_REG_BITS_ENUM(PWRGATE_STATUS_CE0, ON)), reg::EncodeValue(PMC_REG_BITS_ENUM(PWRGATE_TOGGLE_PARTID, CE0)));
}
/* Do RAM Repair. */
{
reg::Write(FLOW + FLOW_CTLR_RAM_REPAIR, FLOW_REG_BITS_ENUM(RAM_REPAIR_REQ, ENABLE));
while (!reg::HasValue(FLOW + FLOW_CTLR_RAM_REPAIR, FLOW_REG_BITS_ENUM(RAM_REPAIR_STS, DONE))) {
/* ... */
}
}
/* Configure CPU reset vector. */
reg::Write(EVP + EVP_CPU_RESET_VECTOR, 0);
reg::Write(SYSTEM + SB_AA64_RESET_LOW, entrypoint | 0x1);
reg::Write(SYSTEM + SB_AA64_RESET_HIGH, 0);
reg::Write(SYSTEM + SB_CSR, SB_REG_BITS_ENUM(CSR_NS_RST_VEC_WR_DIS, DISABLE));
reg::Read(SYSTEM + SB_CSR);
}
void StartCpu() {
/* NOTE: Here nintendo sets CPU_STRICT_TZ_APERTURE_CHECK, which we will not set. */
/* Clear MSELECT reset. */
reg::ReadWrite(CLKRST + CLK_RST_CONTROLLER_RST_DEVICES_V, CLK_RST_REG_BITS_ENUM(RST_DEVICES_V_SWR_MSELECT_RST, DISABLE));
/* Take 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));
/* 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),
CLK_RST_REG_BITS_ENUM(RST_CPUG_CMPLX_CLR_CLR_PRESETDBG, ENABLE),
CLK_RST_REG_BITS_ENUM(RST_CPUG_CMPLX_CLR_CLR_L2RESET, ENABLE));
}
}
| 9,250
|
C++
|
.cpp
| 143
| 47.755245
| 159
| 0.558827
|
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,308
|
fusee_crt0.cpp
|
Atmosphere-NX_Atmosphere/fusee/program/source/fusee_crt0.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 "fusee_exception_handler.hpp"
extern "C" void __libc_init_array();
namespace ams::nxboot::crt0 {
namespace {
ALWAYS_INLINE void SetExceptionVector(u32 which, uintptr_t impl) {
reg::Write(secmon::MemoryRegionPhysicalDeviceExceptionVectors.GetAddress() + 0x200 + sizeof(u32) * which, static_cast<u32>(impl));
}
}
void Initialize() {
/* TODO: Collect timing information? */
/* Setup exception vectors. */
{
SetExceptionVector(0, reinterpret_cast<uintptr_t>(::ams::nxboot::ExceptionHandler0));
SetExceptionVector(1, reinterpret_cast<uintptr_t>(::ams::nxboot::ExceptionHandler1));
SetExceptionVector(2, reinterpret_cast<uintptr_t>(::ams::nxboot::ExceptionHandler2));
SetExceptionVector(3, reinterpret_cast<uintptr_t>(::ams::nxboot::ExceptionHandler3));
SetExceptionVector(4, reinterpret_cast<uintptr_t>(::ams::nxboot::ExceptionHandler4));
SetExceptionVector(5, reinterpret_cast<uintptr_t>(::ams::nxboot::ExceptionHandler5));
SetExceptionVector(6, reinterpret_cast<uintptr_t>(::ams::nxboot::ExceptionHandler6));
SetExceptionVector(7, reinterpret_cast<uintptr_t>(::ams::nxboot::ExceptionHandler7));
}
/* Call init array. */
__libc_init_array();
}
}
| 2,008
|
C++
|
.cpp
| 41
| 42.829268
| 142
| 0.696118
|
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,309
|
fusee_ini.cpp
|
Atmosphere-NX_Atmosphere/fusee/program/source/fusee_ini.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 "fusee_ini.hpp"
#include "fusee_malloc.hpp"
#include "fs/fusee_fs_api.hpp"
namespace ams::nxboot {
namespace {
constexpr s64 IniFileSizeMax = 64_KB;
constexpr bool IsWhiteSpace(char c) {
return c == ' ' || c == '\r';
}
}
ParseIniResult ParseIniFile(IniSectionList &out_sections, const char *ini_path) {
/* Open the ini file. */
fs::FileHandle file;
if (R_FAILED(fs::OpenFile(std::addressof(file), ini_path, fs::OpenMode_Read))) {
return ParseIniResult_NoFile;
}
ON_SCOPE_EXIT { fs::CloseFile(file); };
/* Get file size. */
s64 file_size;
if (R_FAILED(fs::GetFileSize(std::addressof(file_size), file))) {
return ParseIniResult_NoFile;
}
/* Cap file size. */
file_size = std::min(IniFileSizeMax, file_size);
/* Allocate memory for file. */
char *buffer = static_cast<char *>(AllocateAligned(util::AlignUp(file_size + 1, 0x10), 0x10));
buffer[file_size] = '\x00';
/* Read file. */
if (R_FAILED(fs::ReadFile(file, 0, buffer, file_size))) {
return ParseIniResult_NoFile;
}
/* Parse the file. */
enum class State {
Newline,
Comment,
SectionName,
Key,
KvSpace,
KvSpace2,
Value,
TrailingSpace,
};
char *sec_start, *key_start, *val_start, *val_end;
IniSection *cur_sec = nullptr;
State state = State::Newline;
for (int i = 0; i < file_size; ++i) {
const char c = buffer[i];
switch (state) {
case State::Newline:
if (c == '[') {
sec_start = buffer + i + 1;
state = State::SectionName;
} else if (c == ';' || c == '#') {
state = State::Comment;
} else if (IsWhiteSpace(c) || c == '\n') {
state = State::Newline;
} else if (cur_sec != nullptr) {
key_start = buffer + i;
state = State::Key;
} else {
return ParseIniResult_InvalidFormat;
}
break;
case State::Comment:
if (c == '\n') {
state = State::Newline;
}
break;
case State::SectionName:
if (c == '\n') {
return ParseIniResult_InvalidFormat;
} else if (c == ']') {
cur_sec = AllocateObject<IniSection>();
cur_sec->name = sec_start;
buffer[i] = '\x00';
out_sections.push_back(*cur_sec);
state = State::TrailingSpace;
}
break;
case State::Key:
if (c == '\n') {
return ParseIniResult_InvalidFormat;
} else if (IsWhiteSpace(c)) {
buffer[i] = '\x00';
state = State::KvSpace;
} else if (c == '=') {
buffer[i] = '\x00';
state = State::KvSpace2;
}
break;
case State::KvSpace:
if (c == '=') {
state = State::KvSpace2;
} else if (!IsWhiteSpace(c)) {
return ParseIniResult_InvalidFormat;
}
break;
case State::KvSpace2:
if (c == '\n') {
buffer[i] = '\x00';
auto *entry = AllocateObject<IniKeyValueEntry>();
entry->key = key_start;
entry->value = buffer + i;
cur_sec->kv_list.push_back(*entry);
state = State::Newline;
} else if (!IsWhiteSpace(c)) {
val_start = buffer + i;
val_end = buffer + i + 1;
state = State::Value;
}
break;
case State::Value:
if (c == '\r' || c == '\n') {
buffer[i] = '\x00';
*val_end = '\x00';
auto *entry = AllocateObject<IniKeyValueEntry>();
entry->key = key_start;
entry->value = val_start;
cur_sec->kv_list.push_back(*entry);
state = (c == '\n') ? State::Newline : State::TrailingSpace;
} else if (c != ' ') {
val_end = buffer + i + 1;
}
break;
case State::TrailingSpace:
if (c == '\n') {
state = State::Newline;
} else if (!IsWhiteSpace(c)) {
return ParseIniResult_InvalidFormat;
}
break;
}
}
/* Accept value-state. */
if (state == State::Value) {
auto *entry = AllocateObject<IniKeyValueEntry>();
entry->key = key_start;
entry->value = val_start;
cur_sec->kv_list.push_back(*entry);
return ParseIniResult_Success;
} else if (state == State::TrailingSpace || state == State::Comment || state == State::Newline) {
return ParseIniResult_Success;
} else {
return ParseIniResult_InvalidFormat;
}
}
}
| 6,597
|
C++
|
.cpp
| 163
| 24.877301
| 105
| 0.442431
|
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,310
|
fusee_display.cpp
|
Atmosphere-NX_Atmosphere/fusee/program/source/fusee_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 "fusee_registers_di.hpp"
#include "fusee_display.hpp"
#include "fusee_print.hpp"
#include "fusee_fatal.hpp"
namespace ams::nxboot {
namespace {
#include "fusee_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::MemoryRegionPhysicalDevicePmc .GetAddress();
constexpr inline const uintptr_t g_disp1_regs = secmon::MemoryRegionPhysicalDeviceDisp1 .GetAddress();
constexpr inline const uintptr_t g_dsi_regs = secmon::MemoryRegionPhysicalDeviceDsi .GetAddress();
constexpr inline const uintptr_t g_clk_rst_regs = secmon::MemoryRegionPhysicalDeviceClkRst .GetAddress();
constexpr inline const uintptr_t g_gpio_regs = secmon::MemoryRegionPhysicalDeviceGpio .GetAddress();
constexpr inline const uintptr_t g_apb_misc_regs = secmon::MemoryRegionPhysicalDeviceApbMisc.GetAddress();
constexpr inline const uintptr_t g_mipi_cal_regs = secmon::MemoryRegionPhysicalDeviceMipiCal.GetAddress();
constinit u32 *g_frame_buffer = nullptr;
constinit u32 g_lcd_vendor = 0;
constinit bool g_display_initialized = false;
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 (fuse::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) {
g_frame_buffer = reinterpret_cast<u32 *>(0xC0400000);
}
hw::FlushDataCache(g_frame_buffer, FrameBufferSize);
}
[[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);
}
}
}
bool IsDisplayInitialized() {
return g_display_initialized;
}
void InitializeDisplay() {
if (IsDisplayInitialized()) {
return;
}
/* Setup the framebuffer. */
InitializeFrameBuffer();
/* Get the hardware type. */
const auto hw_type = fuse::GetHardwareType();
/* Turn on DSI/voltage rail. */
{
if (fuse::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 (fuse::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;
}
g_lcd_vendor = (lcd_vendor & 0xFFFFFF00) | (host_response[2] & 0xFF);
}
/* LCD vendor specific configuration. */
switch (g_lcd_vendor) {
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 (fuse::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 (g_lcd_vendor != 0x2050) {
util::WaitMicroSeconds(35'000ul);
}
g_display_initialized = true;
}
void FinalizeDisplay() {
if (!IsDisplayInitialized()) {
return;
}
/* 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 (g_lcd_vendor == 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 (g_lcd_vendor == 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);
g_display_initialized = false;
}
void ShowDisplay() {
/* Enable backlight. */
constexpr auto DisplayBrightness = 100;
if (g_lcd_vendor == 0x2050) {
EnableBacklightForVendor2050ForAula(DisplayBrightness);
} else {
EnableBacklightForGeneric(DisplayBrightness);
}
}
u16 GetDisplayLcdVendor() {
return g_lcd_vendor;
}
void ShowFatalError(const ams::impl::FatalErrorContext *f_ctx, const Result save_result) {
/* If needed, initialize the display. */
if (!IsDisplayInitialized()) {
InitializeDisplay();
}
/* 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%" PRIx32 ")\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! (%08" PRIx32 ")\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);
/* Show the console. */
ShowDisplay();
}
void ShowFatalError(const char *fmt, ...) {
/* If needed, initialize the display. */
if (!IsDisplayInitialized()) {
InitializeDisplay();
}
/* Initialize the console. */
InitializeConsole(g_frame_buffer);
{
Print("%s\n", "A fatal error occurred when running Fus" "\xe9" "e.");
{
std::va_list vl;
va_start(vl, fmt);
VPrint(fmt, vl);
va_end(vl);
}
Print("\n");
Print("\nPress POWER to reboot.\n");
}
/* Ensure the device will see consistent data. */
hw::FlushDataCache(g_frame_buffer, FrameBufferSize);
/* Show the console. */
ShowDisplay();
WaitForReboot();
}
}
| 32,357
|
C++
|
.cpp
| 548
| 44.894161
| 206
| 0.572767
|
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,311
|
fusee_setup_horizon.cpp
|
Atmosphere-NX_Atmosphere/fusee/program/source/fusee_setup_horizon.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <exosphere.hpp>
#include <exosphere/secmon/secmon_monitor_context.hpp>
#include "fusee_key_derivation.hpp"
#include "fusee_external_package.hpp"
#include "fusee_setup_horizon.hpp"
#include "fusee_ini.hpp"
#include "fusee_emummc.hpp"
#include "fusee_mmc.hpp"
#include "fusee_cpu.hpp"
#include "fusee_fatal.hpp"
#include "fusee_package2.hpp"
#include "fusee_malloc.hpp"
#include "fusee_secmon_sync.hpp"
#include "fusee_stratosphere.hpp"
#include "fs/fusee_fs_api.hpp"
namespace ams::nxboot {
namespace {
constexpr inline const uintptr_t CLKRST = secmon::MemoryRegionPhysicalDeviceClkRst.GetAddress();
constexpr inline const uintptr_t PMC = secmon::MemoryRegionPhysicalDevicePmc.GetAddress();
constexpr inline const uintptr_t MC = secmon::MemoryRegionPhysicalDeviceMemoryController.GetAddress();
constinit secmon::EmummcConfiguration g_emummc_cfg = {};
void DeriveAllKeys(const fuse::SocType soc_type) {
/* If on erista, run the TSEC keygen firmware. */
if (soc_type == fuse::SocType_Erista) {
clkrst::SetBpmpClockRate(clkrst::BpmpClockRate_408MHz);
if (!tsec::RunTsecFirmware(GetExternalPackage().tsec_keygen, sizeof(GetExternalPackage().tsec_keygen))) {
ShowFatalError("Failed to run tsec_keygen firmware!\n");
}
clkrst::SetBpmpClockRate(clkrst::BpmpClockRate_576MHz);
}
/* Derive master/device keys. */
if (soc_type == fuse::SocType_Erista) {
DeriveKeysErista();
} else /* if (soc_type == fuse::SocType_Mariko) */ {
DeriveKeysMariko();
}
}
bool ParseIniSafe(IniSectionList &out_sections, const char *ini_path) {
const auto result = ParseIniFile(out_sections, ini_path);
if (result == ParseIniResult_Success) {
return true;
} else if (result == ParseIniResult_NoFile) {
return false;
} else {
ShowFatalError("Failed to parse %s!\n", ini_path);
}
}
u32 ParseHexInteger(const char *s) {
u32 x = 0;
if (s[0] == '0' && s[1] == 'x') {
s += 2;
}
while (true) {
const char c = *(s++);
if (c == '\x00') {
return x;
} else {
x <<= 4;
if ('0' <= c && c <= '9') {
x |= (c - '0');
} else if ('a' <= c && c <= 'f') {
x |= (c - 'a') + 10;
} else if ('A' <= c && c <= 'F') {
x |= (c - 'A') + 10;
}
}
}
}
u32 ParseDecimalInteger(const char *s) {
u32 x = 0;
while (true) {
const char c = *(s++);
if (c == '\x00') {
return x;
} else {
x *= 10;
if ('0' <= c && c <= '9') {
x += c - '0';
}
}
}
}
bool IsDirectoryExist(const char *path) {
fs::DirectoryEntryType entry_type;
bool archive;
return R_SUCCEEDED(fs::GetEntryType(std::addressof(entry_type), std::addressof(archive), path)) && entry_type == fs::DirectoryEntryType_Directory;
}
bool IsFileExist(const char *path) {
fs::DirectoryEntryType entry_type;
bool archive;
return R_SUCCEEDED(fs::GetEntryType(std::addressof(entry_type), std::addressof(archive), path)) && entry_type == fs::DirectoryEntryType_File;
}
bool ConfigureEmummc() {
/* Set magic. */
g_emummc_cfg.base_cfg.magic = secmon::EmummcBaseConfiguration::Magic;
/* Parse ini. */
bool enabled = false;
u32 id = 0;
u32 sector = 0;
const char *path = "";
const char *n_path = "";
{
IniSectionList sections;
if (ParseIniSafe(sections, "sdmc:/emummc/emummc.ini")) {
for (const auto §ion : sections) {
/* We only care about the [emummc] section. */
if (std::strcmp(section.name, "emummc")) {
continue;
}
/* Handle individual fields. */
for (const auto &entry : section.kv_list) {
if (std::strcmp(entry.key, "enabled") == 0) {
enabled = entry.value[0] != '0';
} else if (std::strcmp(entry.key, "id") == 0) {
id = ParseHexInteger(entry.value);
} else if (std::strcmp(entry.key, "sector") == 0) {
sector = ParseHexInteger(entry.value);
} else if (std::strcmp(entry.key, "path") == 0) {
path = entry.value;
} else if (std::strcmp(entry.key, "nintendo_path") == 0) {
n_path = entry.value;
}
}
}
}
}
/* Set values parsed from config. */
g_emummc_cfg.base_cfg.id = id;
std::strncpy(g_emummc_cfg.emu_dir_path.str, n_path, sizeof(g_emummc_cfg.emu_dir_path.str));
g_emummc_cfg.emu_dir_path.str[sizeof(g_emummc_cfg.emu_dir_path.str) - 1] = '\x00';
if (enabled) {
if (sector > 0) {
g_emummc_cfg.base_cfg.type = secmon::EmummcType_Partition;
g_emummc_cfg.partition_cfg.start_sector = sector;
} else if (path[0] != '\x00' && IsDirectoryExist(path)) {
g_emummc_cfg.base_cfg.type = secmon::EmummcType_File;
std::strncpy(g_emummc_cfg.file_cfg.path.str, path, sizeof(g_emummc_cfg.file_cfg.path.str));
g_emummc_cfg.file_cfg.path.str[sizeof(g_emummc_cfg.file_cfg.path.str) - 1] = '\x00';
} else {
ShowFatalError("Invalid emummc setting!\n");
}
}
return enabled;
}
u8 *LoadPackage1(fuse::SocType soc_type) {
u8 *package1 = static_cast<u8 *>(AllocateAligned(0x40000, 0x1000));
const Result result = ReadBoot0(0x100000, package1, 0x40000);
if (R_FAILED(result)) {
ShowFatalError("Failed to read boot0: 0x%08" PRIx32 "!\n", result.GetValue());
}
if (soc_type == fuse::SocType_Mariko) {
package1 += 0x170;
se::DecryptAes128Cbc(package1 + 0x20, 0x40000 - (0x20 + 0x170), pkg1::AesKeySlot_MarikoBek, package1 + 0x20, 0x40000 - (0x20 + 0x170), package1 + 0x10, se::AesBlockSize);
hw::InvalidateDataCache(package1 + 0x20, 0x40000 - (0x20 + 0x170));
if (std::memcmp(package1, package1 + 0x20, 0x20) != 0) {
ShowFatalError("Package1 seems corrupt!\n");
}
}
return package1;
}
ams::TargetFirmware GetApproximateTargetFirmware(const u8 *package1) {
/* Get an approximation of the target firmware. */
switch (package1[0x1F]) {
case 0x01:
return ams::TargetFirmware_1_0_0;
case 0x02:
return ams::TargetFirmware_2_0_0;
case 0x04:
return ams::TargetFirmware_3_0_0;
case 0x07:
return ams::TargetFirmware_4_0_0;
case 0x0B:
return ams::TargetFirmware_5_0_0;
case 0x0E:
if (std::memcmp(package1 + 0x10, "20180802", 8) == 0) {
return ams::TargetFirmware_6_0_0;
} else if (std::memcmp(package1 + 0x10, "20181107", 8) == 0) {
return ams::TargetFirmware_6_2_0;
}
break;
case 0x0F:
return ams::TargetFirmware_7_0_0;
case 0x10:
if (std::memcmp(package1 + 0x10, "20190314", 8) == 0) {
return ams::TargetFirmware_8_0_0;
} else if (std::memcmp(package1 + 0x10, "20190531", 8) == 0) {
return ams::TargetFirmware_8_1_0;
} else if (std::memcmp(package1 + 0x10, "20190809", 8) == 0) {
return ams::TargetFirmware_9_0_0;
} else if (std::memcmp(package1 + 0x10, "20191021", 8) == 0) {
return ams::TargetFirmware_9_1_0;
} else if (std::memcmp(package1 + 0x10, "20200303", 8) == 0) {
return ams::TargetFirmware_10_0_0;
} else if (std::memcmp(package1 + 0x10, "20201030", 8) == 0) {
return ams::TargetFirmware_11_0_0;
} else if (std::memcmp(package1 + 0x10, "20210129", 8) == 0) {
return ams::TargetFirmware_12_0_0;
} else if (std::memcmp(package1 + 0x10, "20210422", 8) == 0) {
return ams::TargetFirmware_12_0_2;
} else if (std::memcmp(package1 + 0x10, "20210607", 8) == 0) {
return ams::TargetFirmware_12_1_0;
} else if (std::memcmp(package1 + 0x10, "20210805", 8) == 0) {
return ams::TargetFirmware_13_0_0;
} else if (std::memcmp(package1 + 0x10, "20220105", 8) == 0) {
return ams::TargetFirmware_13_2_1;
} else if (std::memcmp(package1 + 0x10, "20220209", 8) == 0) {
return ams::TargetFirmware_14_0_0;
} else if (std::memcmp(package1 + 0x10, "20220801", 8) == 0) {
return ams::TargetFirmware_15_0_0;
} else if (std::memcmp(package1 + 0x10, "20230111", 8) == 0) {
return ams::TargetFirmware_16_0_0;
} else if (std::memcmp(package1 + 0x10, "20230906", 8) == 0) {
return ams::TargetFirmware_17_0_0;
} else if (std::memcmp(package1 + 0x10, "20240207", 8) == 0) {
return ams::TargetFirmware_18_0_0;
} else if (std::memcmp(package1 + 0x10, "20240808", 8) == 0) {
return ams::TargetFirmware_19_0_0;
}
break;
default:
break;
}
ShowFatalError("Unable to identify package1!\n");
}
u8 *LoadBootConfigAndPackage2() {
Result result;
/* Load boot config. */
if (R_FAILED((result = ReadPackage2(0, secmon::MemoryRegionPhysicalIramBootConfig.GetPointer<void>(), secmon::MemoryRegionPhysicalIramBootConfig.GetSize())))) {
ShowFatalError("Failed to read boot config: 0x%08" PRIx32 "!\n", result.GetValue());
}
/* Read package2 header. */
u8 *package2;
size_t package2_size;
{
constexpr s64 Package2Offset = AMS_OFFSETOF(pkg2::StorageLayout, package2_header);
pkg2::Package2Header header;
if (R_FAILED((result = ReadPackage2(Package2Offset, std::addressof(header), sizeof(header))))) {
ShowFatalError("Failed to read package2 header: 0x%08" PRIx32 "!\n", result.GetValue());
}
package2_size = header.meta.GetSize();
package2 = static_cast<u8 *>(AllocateAligned(util::AlignUp(package2_size, 0x4000), 0x4000));
if (R_FAILED((result = ReadPackage2(Package2Offset, package2, util::AlignUp(package2_size, 0x4000))))) {
ShowFatalError("Failed to read package2: 0x%08" PRIx32 "!\n", result.GetValue());
}
}
/* Decrypt package2. */
DecryptPackage2(package2);
return package2;
}
constexpr inline const u8 PkcModulusErista[0x100] = {
0xF7, 0x86, 0x47, 0xAB, 0x71, 0x89, 0x81, 0xB5, 0xCF, 0x0C, 0xB0, 0xE8, 0x48, 0xA7, 0xFD, 0xAD,
0xCB, 0x4E, 0x4A, 0x52, 0x0B, 0x1A, 0x8E, 0xDE, 0x41, 0x87, 0x6F, 0xB7, 0x31, 0x05, 0x5F, 0xAA,
0xEA, 0x97, 0x76, 0x21, 0x20, 0x2B, 0x40, 0x48, 0x76, 0x55, 0x35, 0x03, 0xFE, 0x7F, 0x67, 0x62,
0xFD, 0x4E, 0xE1, 0x22, 0xF8, 0xF0, 0x97, 0x39, 0xEF, 0xEA, 0x47, 0x89, 0x3C, 0xDB, 0xF0, 0x02,
0xAD, 0x0C, 0x96, 0xCA, 0x82, 0xAB, 0xB3, 0xCB, 0x98, 0xC8, 0xDC, 0xC6, 0xAC, 0x5C, 0x93, 0x3B,
0x84, 0x3D, 0x51, 0x91, 0x9E, 0xC1, 0x29, 0x22, 0x95, 0xF0, 0xA1, 0x51, 0xBA, 0xAF, 0x5D, 0xC3,
0xAB, 0x04, 0x1B, 0x43, 0x61, 0x7D, 0xEA, 0x65, 0x95, 0x24, 0x3C, 0x51, 0x3E, 0x8F, 0xDB, 0xDB,
0xC1, 0xC4, 0x2D, 0x04, 0x29, 0x5A, 0xD7, 0x34, 0x6B, 0xCC, 0xF1, 0x06, 0xF9, 0xC9, 0xE1, 0xF9,
0x61, 0x52, 0xE2, 0x05, 0x51, 0xB1, 0x3D, 0x88, 0xF9, 0xA9, 0x27, 0xA5, 0x6F, 0x4D, 0xE7, 0x22,
0x48, 0xA5, 0xF8, 0x12, 0xA2, 0xC2, 0x5A, 0xA0, 0xBF, 0xC8, 0x76, 0x4B, 0x66, 0xFE, 0x1C, 0x73,
0x00, 0x29, 0x26, 0xCD, 0x18, 0x4F, 0xC2, 0xB0, 0x51, 0x77, 0x2E, 0x91, 0x09, 0x1B, 0x41, 0x5D,
0x89, 0x5E, 0xEE, 0x24, 0x22, 0x47, 0xE5, 0xE5, 0xF1, 0x86, 0x99, 0x67, 0x08, 0x28, 0x42, 0xF0,
0x58, 0x62, 0x54, 0xC6, 0x5B, 0xDC, 0xE6, 0x80, 0x85, 0x6F, 0xE2, 0x72, 0xB9, 0x7E, 0x36, 0x64,
0x48, 0x85, 0x10, 0xA4, 0x75, 0x38, 0x79, 0x76, 0x8B, 0x51, 0xD5, 0x87, 0xC3, 0x02, 0xC9, 0x1B,
0x93, 0x22, 0x49, 0xEA, 0xAB, 0xA0, 0xB5, 0xB1, 0x3C, 0x10, 0xC4, 0x71, 0xF0, 0xF1, 0x81, 0x1A,
0x3A, 0x9C, 0xFC, 0x51, 0x61, 0xB1, 0x4B, 0x18, 0xB2, 0x3D, 0xAA, 0xD6, 0xAC, 0x72, 0x26, 0xB7
};
constexpr inline const u8 PkcModulusDevelopmentErista[0x100] = {
0x37, 0x84, 0x14, 0xB3, 0x78, 0xA4, 0x7F, 0xD8, 0x71, 0x45, 0xCD, 0x90, 0x51, 0x51, 0xBF, 0x2C,
0x27, 0x03, 0x30, 0x46, 0xBE, 0x8F, 0x99, 0x3E, 0x9F, 0x36, 0x4D, 0xEB, 0xF7, 0x0E, 0x81, 0x7F,
0xE4, 0x6B, 0xA8, 0x42, 0x8A, 0xA5, 0x4F, 0x76, 0xCC, 0xCB, 0xC5, 0x31, 0xA8, 0x5A, 0x70, 0x51,
0x34, 0xBF, 0x1E, 0x8D, 0x6E, 0xCF, 0x05, 0x84, 0xCF, 0x8B, 0xE5, 0x9C, 0x3A, 0xA5, 0xCD, 0x1A,
0x9C, 0xAC, 0x59, 0x30, 0x09, 0x21, 0x3C, 0xBE, 0x07, 0x5C, 0x8D, 0x1C, 0xD1, 0xA3, 0xC9, 0x8F,
0x26, 0xE2, 0x99, 0xB2, 0x3C, 0x28, 0xAD, 0x63, 0x0F, 0xF5, 0xA0, 0x1C, 0xA2, 0x34, 0xC4, 0x0E,
0xDB, 0xD7, 0xE1, 0xA9, 0x5E, 0xE9, 0xA5, 0xA8, 0x64, 0x3A, 0xFC, 0x48, 0xB5, 0x97, 0xDF, 0x55,
0x7C, 0x9A, 0xD2, 0x8C, 0x32, 0x36, 0x1D, 0xC5, 0xA0, 0xC5, 0x66, 0xDF, 0x8A, 0xAD, 0x76, 0x18,
0x46, 0x3E, 0xDF, 0xD8, 0xEF, 0xB9, 0xE5, 0xDC, 0xCD, 0x08, 0x59, 0xBC, 0x36, 0x68, 0xD6, 0xFC,
0x3F, 0xFA, 0x11, 0x00, 0x0D, 0x50, 0xE0, 0x69, 0x0F, 0x70, 0x78, 0x7E, 0xD1, 0xA5, 0x85, 0xCD,
0x13, 0xBC, 0x42, 0x74, 0x33, 0x0C, 0x11, 0x24, 0x1E, 0x33, 0xD5, 0x31, 0xB7, 0x3E, 0x48, 0x94,
0xCC, 0x81, 0x29, 0x1E, 0xB1, 0xCF, 0x4C, 0x36, 0x7F, 0xE1, 0x1C, 0x15, 0xD4, 0x3F, 0xFB, 0x12,
0xC2, 0x73, 0x22, 0x16, 0x52, 0xE0, 0x5C, 0x4C, 0x94, 0xE0, 0x87, 0x47, 0xEA, 0xD0, 0x9F, 0x42,
0x9B, 0xAC, 0xB6, 0xB5, 0xB6, 0x34, 0xE4, 0x55, 0x49, 0xD7, 0xC0, 0xAE, 0xD4, 0x22, 0xB3, 0x5C,
0x87, 0x64, 0x42, 0xEC, 0x11, 0x6D, 0xBC, 0x09, 0xC0, 0x80, 0x07, 0xD0, 0xBD, 0xBA, 0x45, 0xFE,
0xD5, 0x52, 0xDA, 0xEC, 0x41, 0xA4, 0xAD, 0x7B, 0x36, 0x86, 0x18, 0xB4, 0x5B, 0xD1, 0x30, 0xBB
};
void LoadWarmbootFirmware(fuse::SocType soc_type, ams::TargetFirmware target_firmware, const u8 *package1) {
u8 *warmboot_dst = secmon::MemoryRegionPhysicalIramWarmbootBin.GetPointer<u8>();
size_t warmboot_size = std::min(sizeof(GetExternalPackage().warmboot), secmon::MemoryRegionPhysicalIramWarmbootBin.GetSize());
if (soc_type == fuse::SocType_Erista) {
/* Copy the ams warmboot binary. */
std::memcpy(warmboot_dst, GetExternalPackage().warmboot, warmboot_size);
/* Set the rsa modulus. */
if (fuse::GetHardwareState() == fuse::HardwareState_Production) {
std::memcpy(warmboot_dst + 0x10, PkcModulusErista, sizeof(PkcModulusErista));
} else {
std::memcpy(warmboot_dst + 0x10, PkcModulusDevelopmentErista, sizeof(PkcModulusDevelopmentErista));
}
/* Set the target firmware. */
std::memcpy(warmboot_dst + 0x248, std::addressof(target_firmware), sizeof(target_firmware));
} else /* if (soc_type == fuse::SocType_Mariko) */ {
/* Declare path for mariko warmboot files. */
char warmboot_path[0x80] = "sdmc:/warmboot_mariko/wb_xx.bin";
auto UpdateWarmbootPath = [&warmboot_path](u8 fuses) {
warmboot_path[0x19] = "0123456789abcdef"[(fuses >> 4) & 0xF];
warmboot_path[0x1A] = "0123456789abcdef"[(fuses >> 0) & 0xF];
};
/* Get expected/burnt fuse counts. */
const u32 expected_fuses = fuse::GetExpectedFuseVersion(target_firmware);
const u32 burnt_fuses = fuse::GetFuseVersion();
u32 used_fuses = expected_fuses;
/* Get warmboot from package1. */
const u8 *warmboot_src = nullptr;
size_t warmboot_src_size = 0;
{
const u32 *package1_pk11 = reinterpret_cast<const u32 *>(package1 + (target_firmware >= ams::TargetFirmware_6_2_0 ? 0x7000 : 0x4000));
if (std::memcmp(package1_pk11, "PK11", 4) != 0) {
ShowFatalError("Invalid package1 magic!\n");
}
const u32 *package1_pk11_data = reinterpret_cast<const u32 *>(package1_pk11 + (0x20 / sizeof(u32)));
for (size_t i = 0; i < 3; ++i) {
switch (*package1_pk11_data) {
case 0xD5034FDF:
package1_pk11_data += package1_pk11[6] / sizeof(u32);
break;
case 0xE328F0C0:
case 0xF0C0A7F0:
package1_pk11_data += package1_pk11[4] / sizeof(u32);
break;
default:
warmboot_src = reinterpret_cast<const u8 *>(package1_pk11_data);
i = 3;
break;
}
}
warmboot_src_size = *package1_pk11_data;
if (!(0x800 <= warmboot_src_size && warmboot_src_size < 0x1000)) {
ShowFatalError("Package1 warmboot firmware seems invalid!\n");
}
/* If we should, save the current warmboot firmware. */
UpdateWarmbootPath(expected_fuses);
if (!IsFileExist(warmboot_path)) {
fs::CreateDirectory("sdmc:/warmboot_mariko");
fs::CreateFile(warmboot_path, warmboot_src_size);
Result result;
fs::FileHandle file;
if (R_FAILED((result = fs::OpenFile(std::addressof(file), warmboot_path, fs::OpenMode_ReadWrite)))) {
ShowFatalError("Failed to save %s!\n", warmboot_path);
}
ON_SCOPE_EXIT { fs::CloseFile(file); };
if (R_FAILED((result = fs::WriteFile(file, 0, warmboot_src, warmboot_src_size, fs::WriteOption::Flush)))) {
ShowFatalError("Failed to save %s!\n", warmboot_path);
}
}
/* If we need to, find a cached warmboot firmware that we can use. */
if (burnt_fuses > expected_fuses) {
warmboot_src = nullptr;
warmboot_src_size = 0;
for (u32 attempt = burnt_fuses; attempt <= 32; ++attempt) {
/* Open the current cache file. */
UpdateWarmbootPath(attempt);
fs::FileHandle file;
if (R_FAILED(fs::OpenFile(std::addressof(file), warmboot_path, fs::OpenMode_Read))) {
continue;
}
ON_SCOPE_EXIT { fs::CloseFile(file); };
/* Get the size. */
s64 size;
if (R_FAILED(fs::GetFileSize(std::addressof(size), file)) || !(0x800 <= size && size < 0x1000)) {
continue;
}
/* Allocate memory. */
warmboot_src_size = static_cast<size_t>(size);
void *tmp = AllocateAligned(warmboot_src_size, 0x10);
/* Read the file. */
if (R_FAILED(fs::ReadFile(file, 0, tmp, warmboot_src_size))) {
continue;
}
/* Use the cached file. */
used_fuses = attempt;
warmboot_src = static_cast<const u8 *>(tmp);
break;
}
}
/* Check that we found a firmware. */
if (warmboot_src == nullptr) {
ShowFatalError("Failed to locate warmboot firmware!\n");
}
/* Copy the warmboot firmware. */
std::memcpy(warmboot_dst, warmboot_src, std::min(warmboot_size, warmboot_src_size));
/* Set the warmboot firmware magic. */
switch (used_fuses) {
case 7:
reg::Write(PMC + APBDEV_PMC_SECURE_SCRATCH32, 0x87);
case 8:
reg::Write(PMC + APBDEV_PMC_SECURE_SCRATCH32, 0xA8);
default:
reg::Write(PMC + APBDEV_PMC_SECURE_SCRATCH32, (0x108 + 0x21 * (used_fuses - 8)));
break;
}
reg::SetBits(PMC + APBDEV_PMC_SEC_DISABLE3, (1 << 16));
}
}
}
void ConfigureExosphere(fuse::SocType soc_type, ams::TargetFirmware target_firmware, bool emummc_enabled, u32 fs_version) {
/* Get monitor configuration. */
auto &storage_ctx = *secmon::MemoryRegionPhysicalDramMonitorConfiguration.GetPointer<secmon::SecureMonitorStorageConfiguration>();
std::memset(std::addressof(storage_ctx), 0, sizeof(storage_ctx));
/* Set magic. */
storage_ctx.magic = secmon::SecureMonitorStorageConfiguration::Magic;
/* Set some defaults. */
storage_ctx.target_firmware = target_firmware;
storage_ctx.lcd_vendor = GetDisplayLcdVendor();
storage_ctx.emummc_cfg = g_emummc_cfg;
storage_ctx.flags[0] = secmon::SecureMonitorConfigurationFlag_Default;
storage_ctx.flags[1] = secmon::SecureMonitorConfigurationFlag_None;
storage_ctx.log_port = uart::Port_ReservedDebug;
storage_ctx.log_baud_rate = 115200;
/* Set the fs version. */
storage_ctx.emummc_cfg.base_cfg.fs_version = fs_version;
/* Parse fields from exosphere.ini */
{
IniSectionList sections;
if (ParseIniSafe(sections, "sdmc:/exosphere.ini")) {
for (const auto §ion : sections) {
/* We only care about the [exosphere] section. */
if (std::strcmp(section.name, "exosphere")) {
continue;
}
/* Handle individual fields. */
for (const auto &entry : section.kv_list) {
if (std::strcmp(entry.key, "debugmode") == 0) {
if (entry.value[0] == '1') {
storage_ctx.flags[0] |= secmon::SecureMonitorConfigurationFlag_IsDevelopmentFunctionEnabledForKernel;
} else {
storage_ctx.flags[0] &= ~secmon::SecureMonitorConfigurationFlag_IsDevelopmentFunctionEnabledForKernel;
}
} else if (std::strcmp(entry.key, "debugmode_user") == 0) {
if (entry.value[0] == '1') {
storage_ctx.flags[0] |= secmon::SecureMonitorConfigurationFlag_IsDevelopmentFunctionEnabledForUser;
} else {
storage_ctx.flags[0] &= ~secmon::SecureMonitorConfigurationFlag_IsDevelopmentFunctionEnabledForUser;
}
} else if (std::strcmp(entry.key, "disable_user_exception_handlers") == 0) {
if (entry.value[0] == '1') {
storage_ctx.flags[0] |= secmon::SecureMonitorConfigurationFlag_DisableUserModeExceptionHandlers;
} else {
storage_ctx.flags[0] &= ~secmon::SecureMonitorConfigurationFlag_DisableUserModeExceptionHandlers;
}
} else if (std::strcmp(entry.key, "enable_user_pmu_access") == 0) {
if (entry.value[0] == '1') {
storage_ctx.flags[0] |= secmon::SecureMonitorConfigurationFlag_EnableUserModePerformanceCounterAccess;
} else {
storage_ctx.flags[0] &= ~secmon::SecureMonitorConfigurationFlag_EnableUserModePerformanceCounterAccess;
}
} else if (std::strcmp(entry.key, "blank_prodinfo_sysmmc") == 0) {
if (!emummc_enabled) {
if (entry.value[0] == '1') {
storage_ctx.flags[0] |= secmon::SecureMonitorConfigurationFlag_ShouldUseBlankCalibrationBinary;
} else {
storage_ctx.flags[0] &= ~secmon::SecureMonitorConfigurationFlag_ShouldUseBlankCalibrationBinary;
}
}
} else if (std::strcmp(entry.key, "blank_prodinfo_emummc") == 0) {
if (emummc_enabled) {
if (entry.value[0] == '1') {
storage_ctx.flags[0] |= secmon::SecureMonitorConfigurationFlag_ShouldUseBlankCalibrationBinary;
} else {
storage_ctx.flags[0] &= ~secmon::SecureMonitorConfigurationFlag_ShouldUseBlankCalibrationBinary;
}
}
} else if (std::strcmp(entry.key, "allow_writing_to_cal_sysmmc") == 0) {
if (entry.value[0] == '1') {
storage_ctx.flags[0] |= secmon::SecureMonitorConfigurationFlag_AllowWritingToCalibrationBinarySysmmc;
} else {
storage_ctx.flags[0] &= ~secmon::SecureMonitorConfigurationFlag_AllowWritingToCalibrationBinarySysmmc;
}
} else if (std::strcmp(entry.key, "log_port") == 0) {
const u32 log_port = ParseDecimalInteger(entry.value);
if (0 <= log_port && log_port < 4) {
storage_ctx.log_port = log_port;
}
} else if (std::strcmp(entry.key, "log_baud_rate") == 0) {
storage_ctx.log_baud_rate = ParseDecimalInteger(entry.value);
} else if (std::strcmp(entry.key, "log_inverted") == 0) {
if (entry.value[0] == '1') {
storage_ctx.log_flags |= uart::Flag_Inverted;
}
}
}
}
}
}
/* Parse usb setting from system_settings.ini */
{
IniSectionList sections;
if (ParseIniSafe(sections, "sdmc:/atmosphere/config/system_settings.ini")) {
for (const auto §ion : sections) {
/* We only care about the [usb] section. */
if (std::strcmp(section.name, "usb")) {
continue;
}
/* Handle individual fields. */
for (const auto &entry : section.kv_list) {
if (std::strcmp(entry.key, "usb30_force_enabled") == 0) {
if (std::strcmp(entry.value, "u8!0x1") == 0) {
storage_ctx.flags[0] |= secmon::SecureMonitorConfigurationFlag_ForceEnableUsb30;
}
}
}
}
}
}
/* Copy exosphere. */
void *exosphere_dst = reinterpret_cast<void *>(0x40030000);
bool use_sd_exo = false;
{
/* Try to use an sd card file, if present. */
fs::FileHandle exo_file;
if (R_SUCCEEDED(fs::OpenFile(std::addressof(exo_file), "sdmc:/atmosphere/exosphere.bin", fs::OpenMode_Read))) {
ON_SCOPE_EXIT { fs::CloseFile(exo_file); };
/* Note that we're using sd_exo. */
use_sd_exo = true;
Result result;
/* Get the size. */
s64 size;
if (R_FAILED((result = fs::GetFileSize(std::addressof(size), exo_file))) || size > sizeof(GetExternalPackage().exosphere)) {
ShowFatalError("Invalid SD exosphere size: 0x%08" PRIx32 ", %" PRIx64 "!\n", result.GetValue(), static_cast<u64>(size));
}
/* Read the file. */
if (R_FAILED((result = fs::ReadFile(exo_file, 0, exosphere_dst, size)))) {
ShowFatalError("Failed to read SD exosphere: 0x%08" PRIx32 "!\n", result.GetValue());
}
}
}
if (!use_sd_exo) {
std::memcpy(exosphere_dst, GetExternalPackage().exosphere, sizeof(GetExternalPackage().exosphere));
}
/* Copy mariko fatal. */
if (soc_type == fuse::SocType_Mariko) {
u8 *mariko_fatal_dst = secmon::MemoryRegionPhysicalMarikoProgramImage.GetPointer<u8>();
bool use_sd_mariko_fatal = false;
{
/* Try to use an sd card file, if present. */
fs::FileHandle mariko_program_file;
if (R_SUCCEEDED(fs::OpenFile(std::addressof(mariko_program_file), "sdmc:/atmosphere/mariko_fatal.bin", fs::OpenMode_Read))) {
ON_SCOPE_EXIT { fs::CloseFile(mariko_program_file); };
/* Note that we're using sd mariko fatal. */
use_sd_mariko_fatal = true;
Result result;
/* Get the size. */
s64 size;
if (R_FAILED((result = fs::GetFileSize(std::addressof(size), mariko_program_file))) || size > sizeof(GetExternalPackage().mariko_fatal)) {
ShowFatalError("Invalid SD mariko_fatal size: 0x%08" PRIx32 ", %" PRIx64 "!\n", result.GetValue(), static_cast<u64>(size));
}
/* Read the file. */
if (R_FAILED((result = fs::ReadFile(mariko_program_file, 0, mariko_fatal_dst, size)))) {
ShowFatalError("Failed to read SD mariko_fatal: 0x%08" PRIx32 "!\n", result.GetValue());
}
/* Clear the remainder. */
std::memset(mariko_fatal_dst + size, 0, sizeof(GetExternalPackage().mariko_fatal) - size);
}
}
if (!use_sd_mariko_fatal) {
std::memcpy(mariko_fatal_dst, GetExternalPackage().mariko_fatal, sizeof(GetExternalPackage().mariko_fatal));
}
}
/* Setup the CPU to boot exosphere. */
SetupCpu(reinterpret_cast<uintptr_t>(exosphere_dst));
/* Initialize bootloader parameters. */
InitializeSecureMonitorMailbox();
/* Set our bootloader state. */
SetBootloaderState(pkg1::BootloaderState_LoadedBootConfig);
/* Ensure that the CPU will see consistent data. */
hw::FlushEntireDataCache();
}
bool IsNogcEnabled(ams::TargetFirmware target_firmware) {
/* First parse from ini. */
{
IniSectionList sections;
if (ParseIniSafe(sections, "sdmc:/atmosphere/config/stratosphere.ini")) {
for (const auto §ion : sections) {
/* We only care about the [stratosphere] section. */
if (std::strcmp(section.name, "stratosphere")) {
continue;
}
/* Handle individual fields. */
for (const auto &entry : section.kv_list) {
if (std::strcmp(entry.key, "nogc") == 0) {
return entry.value[0] == '1';
}
}
}
}
}
/* That failed, so try to decide automatically. */
const auto fuse_version = fuse::GetFuseVersion();
if (target_firmware >= ams::TargetFirmware_12_0_2 && fuse_version < fuse::GetExpectedFuseVersion(ams::TargetFirmware_12_0_2)) {
return true;
}
if (target_firmware >= ams::TargetFirmware_11_0_0 && fuse_version < fuse::GetExpectedFuseVersion(ams::TargetFirmware_11_0_0)) {
return true;
}
if (target_firmware >= ams::TargetFirmware_9_0_0 && fuse_version < fuse::GetExpectedFuseVersion(ams::TargetFirmware_9_0_0)) {
return true;
}
if (target_firmware >= ams::TargetFirmware_4_0_0 && fuse_version < fuse::GetExpectedFuseVersion(ams::TargetFirmware_4_0_0)) {
return true;
}
return false;
}
}
void SetupAndStartHorizon() {
/* Get soc type. */
const auto soc_type = fuse::GetSocType();
/* Derive all keys. */
DeriveAllKeys(soc_type);
/* Determine whether we're using emummc. */
const bool emummc_enabled = ConfigureEmummc();
/* Initialize emummc. */
/* NOTE: SYSTEM:/ accessible past this point. */
InitializeEmummc(emummc_enabled, g_emummc_cfg);
/* Read bootloader. */
const u8 * const package1 = LoadPackage1(soc_type);
/* Get target firmware. */
const auto target_firmware = GetApproximateTargetFirmware(package1);
/* Read/decrypt package2. */
u8 * const package2 = LoadBootConfigAndPackage2();
/* Setup warmboot firmware. */
LoadWarmbootFirmware(soc_type, target_firmware, package1);
/* Decide whether to use nogc patches. */
const bool nogc_enabled = IsNogcEnabled(target_firmware);
/* Decide what KIPs/patches we're loading. */
const auto fs_version = ConfigureStratosphere(package2, target_firmware, emummc_enabled, nogc_enabled);
/* Setup exosphere. */
ConfigureExosphere(soc_type, target_firmware, emummc_enabled, fs_version);
/* Start CPU. */
StartCpu();
/* Build modified package2. */
RebuildPackage2(target_firmware, emummc_enabled);
/* Wait for confirmation that exosphere is ready. */
WaitSecureMonitorState(pkg1::SecureMonitorState_Initialized);
}
}
| 38,358
|
C++
|
.cpp
| 658
| 39.220365
| 186
| 0.496555
|
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,312
|
fusee_secmon_sync.cpp
|
Atmosphere-NX_Atmosphere/fusee/program/source/fusee_secmon_sync.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 "fusee_secmon_sync.hpp"
namespace ams::nxboot {
namespace {
ALWAYS_INLINE pkg1::SecureMonitorParameters &GetSecureMonitorParameters() {
return *secmon::MemoryRegionPhysicalDeviceBootloaderParams.GetPointer<pkg1::SecureMonitorParameters>();
}
}
void InitializeSecureMonitorMailbox() {
std::memset(std::addressof(GetSecureMonitorParameters()), 0, sizeof(GetSecureMonitorParameters()));
}
void WaitSecureMonitorState(pkg1::SecureMonitorState state) {
auto &secmon_params = GetSecureMonitorParameters();
while (secmon_params.secmon_state != state) {
hw::InvalidateDataCache(std::addressof(secmon_params.secmon_state), sizeof(secmon_params.secmon_state));
util::WaitMicroSeconds(1);
}
}
void SetBootloaderState(pkg1::BootloaderState state) {
auto &secmon_params = GetSecureMonitorParameters();
secmon_params.bootloader_state = state;
hw::FlushDataCache(std::addressof(secmon_params.bootloader_state), sizeof(secmon_params.bootloader_state));
}
}
| 1,758
|
C++
|
.cpp
| 39
| 39.923077
| 116
| 0.731736
|
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,313
|
fusee_secure_initialize.cpp
|
Atmosphere-NX_Atmosphere/fusee/program/source/sein/fusee_secure_initialize.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 "fusee_secure_initialize.hpp"
#include "../fusee_registers_di.hpp"
namespace ams::nxboot {
namespace {
constexpr inline const uintptr_t CLKRST = secmon::MemoryRegionPhysicalDeviceClkRst.GetAddress();
constexpr inline const uintptr_t PMC = secmon::MemoryRegionPhysicalDevicePmc.GetAddress();
constexpr inline const uintptr_t MC = secmon::MemoryRegionPhysicalDeviceMemoryController.GetAddress();
constexpr inline const uintptr_t APB = secmon::MemoryRegionPhysicalDeviceApbMisc.GetAddress();
constexpr inline const uintptr_t AHB = AHB_ARBC(0);
constexpr inline const uintptr_t I2S = I2S_REG(0);
constexpr inline const uintptr_t DISP1 = secmon::MemoryRegionPhysicalDeviceDisp1.GetAddress();
constexpr inline const uintptr_t VIC = secmon::MemoryRegionPhysicalDeviceDsi.GetAddress() + 0x40000;
constexpr inline const uintptr_t TIMER = secmon::MemoryRegionPhysicalDeviceTimer.GetAddress();
constexpr inline const uintptr_t SYSCTR0 = secmon::MemoryRegionPhysicalDeviceSysCtr0.GetAddress();
void DoRcmWorkaround(const void *sbk, size_t sbk_size) {
/* Set the SBK inside the security engine. */
se::SetAesKey(pkg1::AesKeySlot_SecureBoot, sbk, sbk_size);
/* Lock the SBK/SSK as unreadable. */
se::LockAesKeySlot(pkg1::AesKeySlot_SecureBoot, se::KeySlotLockFlags_KeyRead);
se::LockAesKeySlot(pkg1::AesKeySlot_SecureStorage, se::KeySlotLockFlags_KeyRead);
/* Clear TZRAM. */
std::memset(secmon::MemoryRegionPhysicalTzram.GetPointer(), 0, secmon::MemoryRegionPhysicalTzram.GetSize());
/* Clear APBDEV_PMC_CRYPTO_OP. */
reg::Write(PMC + APBDEV_PMC_CRYPTO_OP, 0);
/* Clear the boot reason. */
reg::Write(PMC + APBDEV_PMC_SCRATCH200, 0);
reg::Write(PMC + APBDEV_PMC_CRYPTO_OP, 0);
/* Clear OBS_OVERRIDE/APB2JTAG_OVERRIDE */
reg::ReadWrite(AHB + AHB_AHB_SPARE_REG, AHB_REG_BITS_ENUM(AHB_SPARE_REG_OBS_OVERRIDE_EN, DISABLE),
AHB_REG_BITS_ENUM(AHB_SPARE_REG_APB2JTAG_OVERRIDE_EN, DISABLE));
/* Clear low bits of APBDEV_PMC_SCRATCH49 */
reg::ClearBits(PMC + APBDEV_PMC_SCRATCH49, 0x3);
}
void DoMbistWorkaround() {
/* Enable AHUB/APE clock prior to I2S accesses. */
reg::ReadWrite(CLKRST + CLK_RST_CONTROLLER_CLK_OUT_ENB_V, CLK_RST_REG_BITS_ENUM(CLK_ENB_V_CLK_ENB_AHUB, ENABLE));
reg::ReadWrite(CLKRST + CLK_RST_CONTROLLER_CLK_OUT_ENB_Y, CLK_RST_REG_BITS_ENUM(CLK_ENB_Y_CLK_ENB_APE, ENABLE));
/* Configure CLK_RST_CONTROLLER_CLK_SOURCE_SOR1. */
reg::ReadWrite(CLKRST + CLK_RST_CONTROLLER_CLK_SOURCE_SOR1, CLK_RST_REG_BITS_ENUM(CLK_SOURCE_SOR1_SOR1_CLK_SEL0, MUX),
CLK_RST_REG_BITS_ENUM(CLK_SOURCE_SOR1_SOR1_CLK_SEL1, SOR1_CLOCK_SWITCH));
/* Set CSI clock source as PLLD. */
reg::ReadWrite(CLKRST + CLK_RST_CONTROLLER_PLLD_BASE, CLK_RST_REG_BITS_ENUM(PLLD_BASE_PLLD_ENABLE, ENABLE),
CLK_RST_REG_BITS_ENUM(PLLD_BASE_CSI_CLK_SRC, PLL_D));
/* Clear APE, VIC, HOST1X, DISP1 reset. */
reg::Write(CLKRST + CLK_RST_CONTROLLER_RST_DEV_Y_CLR, CLK_RST_REG_BITS_ENUM(RST_DEV_Y_APE_RST, ENABLE));
reg::Write(CLKRST + CLK_RST_CONTROLLER_RST_DEV_X_CLR, CLK_RST_REG_BITS_ENUM(RST_DEV_X_VIC_RST, ENABLE));
reg::Write(CLKRST + CLK_RST_CONTROLLER_RST_DEV_L_CLR, CLK_RST_REG_BITS_ENUM(RST_DEV_L_DISP1_RST, ENABLE), CLK_RST_REG_BITS_ENUM(RST_DEV_L_HOST1X_RST, ENABLE));
/* Wait two microseconds for the devices to come out of reset. */
util::WaitMicroSeconds(2);
/* Set I2S_CTRL.MASTER and clear I2S_CG.SCLG_ENABLE for all I2S registers. */
reg::ReadWrite(I2S + I2S0_I2S_CTRL, I2S_REG_BITS_ENUM(I2S_CTRL_MASTER, ENABLE));
reg::ReadWrite(I2S + I2S0_I2S_CG, I2S_REG_BITS_ENUM(I2S_CG_SLCG_ENABLE, FALSE));
reg::ReadWrite(I2S + I2S1_I2S_CTRL, I2S_REG_BITS_ENUM(I2S_CTRL_MASTER, ENABLE));
reg::ReadWrite(I2S + I2S1_I2S_CG, I2S_REG_BITS_ENUM(I2S_CG_SLCG_ENABLE, FALSE));
reg::ReadWrite(I2S + I2S2_I2S_CTRL, I2S_REG_BITS_ENUM(I2S_CTRL_MASTER, ENABLE));
reg::ReadWrite(I2S + I2S2_I2S_CG, I2S_REG_BITS_ENUM(I2S_CG_SLCG_ENABLE, FALSE));
reg::ReadWrite(I2S + I2S3_I2S_CTRL, I2S_REG_BITS_ENUM(I2S_CTRL_MASTER, ENABLE));
reg::ReadWrite(I2S + I2S3_I2S_CG, I2S_REG_BITS_ENUM(I2S_CG_SLCG_ENABLE, FALSE));
reg::ReadWrite(I2S + I2S4_I2S_CTRL, I2S_REG_BITS_ENUM(I2S_CTRL_MASTER, ENABLE));
reg::ReadWrite(I2S + I2S4_I2S_CG, I2S_REG_BITS_ENUM(I2S_CG_SLCG_ENABLE, FALSE));
/* Set DC_COM_DSC_TOP_CTL.DSC_SLG_OVERRIDE */
reg::SetBits(DISP1 + DC_COM_DSC_TOP_CTL * sizeof(u32), 0x4);
/* Set NV_PVIC_THI_SLCG_OVERRIDE_LOW_A */
reg::SetBits(VIC + NV_PVIC_THI_SLCG_OVERRIDE_LOW_A, 0xFFFFFFFF);
/* Wait two microseconds for configuration to take. */
util::WaitMicroSeconds(2);
/* Set APE, VIC, HOST1X, DISP1 reset. */
reg::Write(CLKRST + CLK_RST_CONTROLLER_RST_DEV_Y_SET, CLK_RST_REG_BITS_ENUM(RST_DEV_Y_APE_RST, ENABLE));
reg::Write(CLKRST + CLK_RST_CONTROLLER_RST_DEV_L_SET, CLK_RST_REG_BITS_ENUM(RST_DEV_L_DISP1_RST, ENABLE), CLK_RST_REG_BITS_ENUM(RST_DEV_L_HOST1X_RST, ENABLE));
reg::Write(CLKRST + CLK_RST_CONTROLLER_RST_DEV_X_SET, CLK_RST_REG_BITS_ENUM(RST_DEV_X_VIC_RST, ENABLE));
/* Set clock enable for a select few devices. */
reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_OUT_ENB_H, CLK_RST_REG_BITS_ENUM(CLK_ENB_H_CLK_ENB_FUSE, ENABLE),
CLK_RST_REG_BITS_ENUM(CLK_ENB_H_CLK_ENB_PMC, ENABLE));
reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_OUT_ENB_L, CLK_RST_REG_BITS_ENUM(CLK_ENB_L_CLK_ENB_CACHE2, ENABLE),
CLK_RST_REG_BITS_ENUM(CLK_ENB_L_CLK_ENB_GPIO, ENABLE),
CLK_RST_REG_BITS_ENUM(CLK_ENB_L_CLK_ENB_TMR, ENABLE),
CLK_RST_REG_BITS_ENUM(CLK_ENB_L_CLK_ENB_RTC, ENABLE));
reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_OUT_ENB_U, CLK_RST_REG_BITS_ENUM(CLK_ENB_U_CLK_ENB_CRAM2, ENABLE),
CLK_RST_REG_BITS_ENUM(CLK_ENB_U_CLK_ENB_IRAMD, ENABLE),
CLK_RST_REG_BITS_ENUM(CLK_ENB_U_CLK_ENB_IRAMC, ENABLE),
CLK_RST_REG_BITS_ENUM(CLK_ENB_U_CLK_ENB_IRAMB, ENABLE),
CLK_RST_REG_BITS_ENUM(CLK_ENB_U_CLK_ENB_IRAMA, ENABLE),
CLK_RST_REG_BITS_ENUM(CLK_ENB_U_CLK_ENB_CSITE, ENABLE));
reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_OUT_ENB_V, CLK_RST_REG_BITS_ENUM(CLK_ENB_V_CLK_ENB_SE, ENABLE),
CLK_RST_REG_BITS_ENUM(CLK_ENB_V_CLK_ENB_SPDIF_DOUBLER, ENABLE),
CLK_RST_REG_BITS_ENUM(CLK_ENB_V_CLK_ENB_APB2APE, ENABLE),
CLK_RST_REG_BITS_ENUM(CLK_ENB_V_CLK_ENB_MSELECT, ENABLE));
reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_OUT_ENB_W, CLK_RST_REG_BITS_ENUM(CLK_ENB_W_CLK_ENB_MC1, ENABLE),
CLK_RST_REG_BITS_ENUM(CLK_ENB_W_CLK_ENB_ENTROPY, ENABLE),
CLK_RST_REG_BITS_ENUM(CLK_ENB_W_CLK_ENB_PCIERX5, ENABLE),
CLK_RST_REG_BITS_ENUM(CLK_ENB_W_CLK_ENB_PCIERX4, ENABLE),
CLK_RST_REG_BITS_ENUM(CLK_ENB_W_CLK_ENB_PCIERX3, ENABLE),
CLK_RST_REG_BITS_ENUM(CLK_ENB_W_CLK_ENB_PCIERX2, ENABLE),
CLK_RST_REG_BITS_ENUM(CLK_ENB_W_CLK_ENB_PCIERX1, ENABLE),
CLK_RST_REG_BITS_ENUM(CLK_ENB_W_CLK_ENB_PCIERX0, ENABLE));
reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_OUT_ENB_X, CLK_RST_REG_BITS_ENUM(CLK_ENB_X_CLK_ENB_PLLG_REF, ENABLE),
CLK_RST_REG_BITS_ENUM(CLK_ENB_X_CLK_ENB_DBGAPB, ENABLE),
CLK_RST_REG_BITS_ENUM(CLK_ENB_X_CLK_ENB_GPU, ENABLE),
CLK_RST_REG_BITS_ENUM(CLK_ENB_X_CLK_ENB_MC_BBC, ENABLE),
CLK_RST_REG_BITS_ENUM(CLK_ENB_X_CLK_ENB_MC_CPU, ENABLE),
CLK_RST_REG_BITS_ENUM(CLK_ENB_X_CLK_ENB_MC_CBPA, ENABLE),
CLK_RST_REG_BITS_ENUM(CLK_ENB_X_CLK_ENB_MC_CAPA, ENABLE));
reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_OUT_ENB_Y, CLK_RST_REG_BITS_ENUM(CLK_ENB_Y_CLK_ENB_MC_CDPA, ENABLE),
CLK_RST_REG_BITS_ENUM(CLK_ENB_Y_CLK_ENB_MC_CCPA, ENABLE));
/* 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);
/* Reset CSI clock source. */
reg::ReadWrite(CLKRST + CLK_RST_CONTROLLER_PLLD_BASE, CLK_RST_REG_BITS_ENUM(PLLD_BASE_PLLD_BYPASS, DISABLE),
CLK_RST_REG_BITS_ENUM(PLLD_BASE_PLLD_ENABLE, DISABLE),
CLK_RST_REG_BITS_ENUM(PLLD_BASE_PLLD_REF_DIS, REF_ENABLE),
CLK_RST_REG_BITS_ENUM(PLLD_BASE_CSI_CLK_SRC, BRICK));
/* Configure CLK_RST_CONTROLLER_CLK_SOURCE_SOR1. */
reg::ReadWrite(CLKRST + CLK_RST_CONTROLLER_CLK_SOURCE_SOR1, CLK_RST_REG_BITS_ENUM(CLK_SOURCE_SOR1_SOR1_CLK_SEL0, MUX),
CLK_RST_REG_BITS_ENUM(CLK_SOURCE_SOR1_SOR1_CLK_SEL1, SAFE_CLOCK));
/* Configure VI, HOST1X, NVENC clock sources. */
reg::ReadWrite(CLKRST + CLK_RST_CONTROLLER_CLK_SOURCE_VI, CLK_RST_REG_BITS_ENUM(CLK_SOURCE_VI_VI_CLK_SRC, PLLP_OUT0));
reg::ReadWrite(CLKRST + CLK_RST_CONTROLLER_CLK_SOURCE_HOST1X, CLK_RST_REG_BITS_ENUM(CLK_SOURCE_HOST1X_HOST1X_CLK_SRC, PLLP_OUT0));
reg::ReadWrite(CLKRST + CLK_RST_CONTROLLER_CLK_SOURCE_NVENC, CLK_RST_REG_BITS_ENUM(CLK_SOURCE_NVENC_NVENC_CLK_SRC, PLLP_OUT0));
}
void EnableArc() {
/* Enable clocks for EMC/MC, using PLLP_OUT0. */
reg::ReadWrite(CLKRST + CLK_RST_CONTROLLER_CLK_SOURCE_EMC, CLK_RST_REG_BITS_ENUM(CLK_SOURCE_EMC_EMC_2X_CLK_SRC, PLLP_OUT0));
reg::ReadWrite(CLKRST + CLK_RST_CONTROLLER_CLK_ENB_H_SET, CLK_RST_REG_BITS_ENUM(CLK_ENB_H_CLK_ENB_EMC, ENABLE));
reg::ReadWrite(CLKRST + CLK_RST_CONTROLLER_CLK_ENB_H_SET, CLK_RST_REG_BITS_ENUM(CLK_ENB_H_CLK_ENB_MEM, ENABLE));
reg::ReadWrite(CLKRST + CLK_RST_CONTROLLER_CLK_ENB_X_SET, CLK_RST_REG_BITS_ENUM(CLK_ENB_X_CLK_ENB_EMC_DLL, ENABLE));
/* Clear reset for MEM/EMC. */
reg::Write(CLKRST + CLK_RST_CONTROLLER_RST_DEV_H_CLR, CLK_RST_REG_BITS_ENUM(RST_DEV_H_EMC_RST, ENABLE),
CLK_RST_REG_BITS_ENUM(RST_DEV_H_MEM_RST, ENABLE));
/* Wait 5 microseconds for configuration to take. */
util::WaitMicroSeconds(5);
/* Enable ARC_CLK_OVR_ON. */
reg::ReadWrite(CLKRST + CLK_RST_CONTROLLER_LVL2_CLK_GATE_OVRD, CLK_RST_REG_BITS_ENUM(LVL2_CLK_GATE_OVRD_ARC_CLK_OVR_ON, ON));
/* Enable the ARC. */
reg::ReadWrite(MC + MC_IRAM_REG_CTRL, MC_REG_BITS_ENUM(IRAM_REG_CTRL_IRAM_CFG_WRITE_ACCESS, ENABLED));
/* Set IRAM BOM/TOP to open up access to all mmio. */
reg::Write(MC + MC_IRAM_BOM, 0x40000000);
reg::Write(MC + MC_IRAM_TOM, 0x80000000);
/* Read to ensure our configuration takes. */
reg::Read(MC + MC_IRAM_REG_CTRL);
}
void InitializeClock() {
/* Set SPARE_REG0 clock divisor 2. */
reg::ReadWrite(CLKRST + CLK_RST_CONTROLLER_SPARE_REG0, CLK_RST_REG_BITS_ENUM(SPARE_REG0_CLK_M_DIVISOR, CLK_M_DIVISOR2));
/* Set system counter frequency. */
reg::Write(SYSCTR0 + SYSCTR0_CNTFID0, 19'200'000);
/* 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));
/* Enable the crystal oscillator, and copy the drive strength from pmc. */
reg::Write(CLKRST + CLK_RST_CONTROLLER_OSC_CTRL, CLK_RST_REG_BITS_ENUM (OSC_CTRL_OSC_FREQ, OSC38P4),
CLK_RST_REG_BITS_ENUM (OSC_CTRL_XOE, ENABLE),
CLK_RST_REG_BITS_VALUE(OSC_CTRL_XOFS, 7));
/* Set the crystal oscillator value in PMC. */
reg::ReadWrite(PMC + APBDEV_PMC_OSC_EDPD_OVER, PMC_REG_BITS_VALUE(OSC_EDPD_OVER_XOFS, 7));
/* Configure the crystal oscillator to use PMC value on warmboot. */
reg::ReadWrite(PMC + APBDEV_PMC_OSC_EDPD_OVER, PMC_REG_BITS_ENUM(OSC_EDPD_OVER_OSC_CTRL_SELECT, PMC));
/* Set HOLD_CKE_LOW_EN. */
reg::ReadWrite(PMC + APBDEV_PMC_CNTRL2, PMC_REG_BITS_ENUM(CNTRL2_HOLD_CKE_LOW_EN, ENABLE));
/* Set CFG2TMC_RAM_SVOP_PDP to 2. */
/* NOTE: Nintendo acidentally writes this to the PMC instead of the APB due to a bug. */
reg::ReadWrite(APB + APB_MISC_GP_ASDBGREG, APB_MISC_REG_BITS_VALUE(GP_ASDBGREG_CFG2TMC_RAM_SVOP_PDP, 2));
/* Set CLK_SYSTEM_RATE. */
reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_SYSTEM_RATE, CLK_RST_REG_BITS_VALUE(CLK_SYSTEM_RATE_HCLK_DIS, 0),
CLK_RST_REG_BITS_VALUE(CLK_SYSTEM_RATE_AHB_RATE, 1),
CLK_RST_REG_BITS_VALUE(CLK_SYSTEM_RATE_PCLK_DIS, 0),
CLK_RST_REG_BITS_VALUE(CLK_SYSTEM_RATE_APB_RATE, 0));
/* Configure PLLMB_BASE. */
reg::ReadWrite(CLKRST + CLK_RST_CONTROLLER_PLLMB_BASE, CLK_RST_REG_BITS_ENUM(PLLMB_BASE_PLLMB_ENABLE, DISABLE));
/* Configure TSC_MULT. */
constexpr u32 TscMultValue = 19'200'000 * 16 / 32768;
reg::ReadWrite(PMC + APBDEV_PMC_TSC_MULT, PMC_REG_BITS_VALUE(TSC_MULT_MULT_VAL, TscMultValue));
/* Configure SCLK_BURST_POLICY */
reg::Write(CLKRST + CLK_RST_CONTROLLER_SCLK_BURST_POLICY, CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_SYS_STATE, RUN),
CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_COP_AUTO_SWAKEUP_FROM_FIQ, NOP),
CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_CPU_AUTO_SWAKEUP_FROM_FIQ, NOP),
CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_COP_AUTO_SWAKEUP_FROM_IRQ, NOP),
CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_CPU_AUTO_SWAKEUP_FROM_IRQ, NOP),
CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_SWAKEUP_FIQ_SOURCE, PLLP_OUT2),
CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_SWAKEUP_IRQ_SOURCE, PLLP_OUT2),
CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_SWAKEUP_RUN_SOURCE, PLLP_OUT2),
CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_SWAKEUP_IDLE_SOURCE, PLLP_OUT2));
/* Configure SUPER_SCLK_DIVIDER */
reg::Write(CLKRST + CLK_RST_CONTROLLER_SUPER_SCLK_DIVIDER, CLK_RST_REG_BITS_ENUM (SUPER_SCLK_DIVIDER_SUPER_SDIV_ENB, ENABLE),
CLK_RST_REG_BITS_ENUM (SUPER_SCLK_DIVIDER_SUPER_SDIV_DIS_FROM_COP_FIQ, NOP),
CLK_RST_REG_BITS_ENUM (SUPER_SCLK_DIVIDER_SUPER_SDIV_DIS_FROM_CPU_FIQ, NOP),
CLK_RST_REG_BITS_ENUM (SUPER_SCLK_DIVIDER_SUPER_SDIV_DIS_FROM_COP_IRQ, NOP),
CLK_RST_REG_BITS_ENUM (SUPER_SCLK_DIVIDER_SUPER_SDIV_DIS_FROM_CPU_IRQ, NOP),
CLK_RST_REG_BITS_VALUE(SUPER_SCLK_DIVIDER_SUPER_SDIV_DIVIDEND, 0),
CLK_RST_REG_BITS_VALUE(SUPER_SCLK_DIVIDER_SUPER_SDIV_DIVISOR, 0));
/* Set CLK_SYSTEM_RATE */
reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_SYSTEM_RATE, CLK_RST_REG_BITS_VALUE(CLK_SYSTEM_RATE_HCLK_DIS, 0),
CLK_RST_REG_BITS_VALUE(CLK_SYSTEM_RATE_AHB_RATE, 0),
CLK_RST_REG_BITS_VALUE(CLK_SYSTEM_RATE_PCLK_DIS, 0),
CLK_RST_REG_BITS_VALUE(CLK_SYSTEM_RATE_APB_RATE, 2));
}
void InitializePinmux(fuse::HardwareType hw_type) {
/* Clear global pinmux control register */
reg::Write(APB + APB_MISC_PP_PINMUX_GLOBAL_0, 0);
/* Perform initial pinmux setup. */
pinmux::SetupFirst(hw_type);
/* Setup important pinmux devices. */
pinmux::SetupI2c1();
pinmux::SetupI2c5();
pinmux::SetupUartA();
pinmux::SetupVolumeButton();
pinmux::SetupHomeButton();
}
}
void SecureInitialize(bool enable_log) {
/* Get SoC type/hardware type. */
const auto soc_type = fuse::GetSocType();
const auto hw_type = fuse::GetHardwareType();
/* If Erista, perform bootrom logic (to compensate for RCM exploit) and MBIST workaround. */
if (soc_type == fuse::SocType_Erista) {
/* Potentially perform bootrom compensation. */
{
u32 sbk[4];
if (fuse::GetSecureBootKey(sbk)) {
DoRcmWorkaround(sbk, sizeof(sbk));
}
}
DoMbistWorkaround();
}
/* Initialize security engine clock. */
clkrst::EnableSeClock();
/* Set fuse visibility. */
clkrst::SetFuseVisibility(true);
/* Disable fuse programming. */
fuse::Lockout();
/* Initialize the security engine. */
se::Initialize();
/* Enable the arc. */
EnableArc();
/* Setup initial clocks. */
InitializeClock();
/* Setup initial pinmux. */
InitializePinmux(hw_type);
/* Initialize logging. */
if (enable_log) {
clkrst::EnableUartAClock();
}
/* Enable various clocks. */
clkrst::EnableCldvfsClock();
clkrst::EnableI2c1Clock();
clkrst::EnableI2c5Clock();
clkrst::EnableTzramClock();
/* Ensure avp cache is enabled, since we'll be using it. */
clkrst::EnableCache2Clock();
clkrst::EnableCram2Clock();
/* Initialize I2C5. */
i2c::Initialize(i2c::Port_5);
/* Configure pmic system setting. */
pmic::SetSystemSetting(soc_type);
/* Enable VDD core */
pmic::EnableVddCore(soc_type);
/* On hoag, enable Ldo8 */
if (hw_type == fuse::HardwareType_Hoag) {
pmic::EnableLdo8();
}
/* Initialize I2C1. */
i2c::Initialize(i2c::Port_1);
/* Configure SCLK_BURST_POLICY. */
reg::ReadWrite(CLKRST + CLK_RST_CONTROLLER_SCLK_BURST_POLICY, CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_SWAKEUP_FIQ_SOURCE, PLLP_OUT0),
CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_SWAKEUP_IRQ_SOURCE, PLLP_OUT0),
CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_SWAKEUP_RUN_SOURCE, PLLP_OUT0),
CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_SWAKEUP_IDLE_SOURCE, PLLP_OUT0));
/* Do mariko-only TZRAM configuration. */
if (soc_type == fuse::SocType_Mariko) {
reg::ReadWrite(PMC + APBDEV_PMC_TZRAM_PWR_CNTRL, PMC_REG_BITS_VALUE(TZRAM_PWR_CNTRL_TZRAM_SD, 0));
reg::Write(PMC + APBDEV_PMC_TZRAM_NON_SEC_DISABLE, PMC_REG_BITS_ENUM(TZRAM_NON_SEC_DISABLE_SD_WRITE, ON),
PMC_REG_BITS_ENUM(TZRAM_NON_SEC_DISABLE_SD_READ, ON));
reg::Write(PMC + APBDEV_PMC_TZRAM_SEC_DISABLE, PMC_REG_BITS_ENUM(TZRAM_SEC_DISABLE_SD_WRITE, ON),
PMC_REG_BITS_ENUM(TZRAM_SEC_DISABLE_SD_READ, ON));
}
/* Hold certain devices in reset. */
reg::ReadWrite(CLKRST + CLK_RST_CONTROLLER_RST_DEVICES_L, CLK_RST_REG_BITS_ENUM(RST_DEVICES_L_SWR_USBD_RST, ENABLE));
}
}
| 23,788
|
C++
|
.cpp
| 298
| 56.892617
| 171
| 0.532869
|
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,314
|
fusee_diskio.cpp
|
Atmosphere-NX_Atmosphere/fusee/program/source/fatfs/fusee_diskio.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 "diskio_cpp.h"
#include "../fusee_sd_card.hpp"
#include "../fusee_emummc.hpp"
bool diskio_read_sd_card(void *dst, size_t size, size_t sector_index, size_t sector_count) {
return R_SUCCEEDED(::ams::nxboot::ReadSdCard(dst, size, sector_index, sector_count));
}
bool diskio_write_sd_card(size_t sector_index, size_t sector_count, const void *src, size_t size) {
return R_SUCCEEDED(::ams::nxboot::WriteSdCard(sector_index, sector_count, src, size));
}
bool diskio_read_system(void *dst, size_t size, size_t sector_index, size_t sector_count) {
return false;
}
bool diskio_write_system(size_t sector_index, size_t sector_count, const void *src, size_t size) {
return false;
}
| 1,359
|
C++
|
.cpp
| 31
| 41.774194
| 99
| 0.741132
|
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,315
|
fusee_mtc.cpp
|
Atmosphere-NX_Atmosphere/fusee/program/source/mtc/fusee_mtc.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::nxboot {
void DoMemoryTrainingErista(int index, void *mtc_tables_buffer);
void DoMemoryTrainingMariko(bool *out_did_training, int index, void *mtc_tables_buffer);
void RestoreMemoryClockRateMariko(void *mtc_tables_buffer);
namespace {
alignas(4) constinit u8 g_mtc_tables_buffer[0x26C0];
constinit bool g_did_training_mariko = false;
constexpr const u8 MemoryTrainingTableIndex_Invalid = std::numeric_limits<u8>::max();
constexpr const u8 MemoryTrainingTableIndices[] = {
/* DramId_EristaIcosaSamsung4gb */ 0x00,
/* DramId_EristaIcosaHynix4gb */ 0x02,
/* DramId_EristaIcosaMicron4gb */ 0x03,
/* DramId_MarikoIowaHynix1y4gb */ 0x10,
/* DramId_EristaIcosaSamsung6gb */ 0x01,
/* DramId_MarikoHoagHynix1y4gb */ 0x10,
/* DramId_MarikoAulaHynix1y4gb */ 0x10,
/* DramId_MarikoIowax1x2Samsung4gb */ 0x00,
/* DramId_MarikoIowaSamsung4gb */ 0x05,
/* DramId_MarikoIowaSamsung8gb */ 0x06,
/* DramId_MarikoIowaHynix4gb */ 0x07,
/* DramId_MarikoIowaMicron4gb */ 0x08,
/* DramId_MarikoHoagSamsung4gb */ 0x05,
/* DramId_MarikoHoagSamsung8gb */ 0x06,
/* DramId_MarikoHoagHynix4gb */ 0x07,
/* DramId_MarikoHoagMicron4gb */ 0x08,
/* DramId_MarikoIowaSamsung4gbY */ 0x09,
/* DramId_MarikoIowaSamsung1y4gbX */ 0x0C,
/* DramId_MarikoIowaSamsung1y8gbX */ 0x0D,
/* DramId_MarikoHoagSamsung1y4gbX */ 0x0C,
/* DramId_MarikoIowaSamsung1z4gb */ 0x12,
/* DramId_MarikoHoagSamsung1z4gb */ 0x12,
/* DramId_MarikoAulaSamsung1z4gb */ 0x12,
/* DramId_MarikoHoagSamsung1y8gbX */ 0x0D,
/* DramId_MarikoAulaSamsung1y4gbX */ 0x0C,
/* DramId_MarikoIowaMicron1y4gb */ 0x0F,
/* DramId_MarikoHoagMicron1y4gb */ 0x0F,
/* DramId_MarikoAulaMicron1y4gb */ 0x0F,
/* DramId_MarikoAulaSamsung1y8gbX */ 0x0D,
/* DramId_MarikoIowaHynix1a4gb */ 0x13,
/* DramId_MarikoHoagHynix1a4gb */ 0x13,
/* DramId_MarikoAulaHynix1a4gb */ 0x13,
/* DramId_MarikoIowaMicron1a4gb */ 0x14,
/* DramId_MarikoHoagMicron1a4gb */ 0x14,
/* DramId_MarikoAulaMicron1a4gb */ 0x14,
};
int GetMemoryTrainingTableIndex() {
if (const auto dram_id = fuse::GetDramId(); dram_id < util::size(MemoryTrainingTableIndices) && MemoryTrainingTableIndices[dram_id] != MemoryTrainingTableIndex_Invalid) {
return static_cast<int>(MemoryTrainingTableIndices[dram_id]);
} else {
return -1;
}
}
}
void DoMemoryTraining() {
const auto index = GetMemoryTrainingTableIndex();
if (fuse::GetSocType() == fuse::SocType_Erista) {
DoMemoryTrainingErista(index, g_mtc_tables_buffer);
} else {
DoMemoryTrainingMariko(std::addressof(g_did_training_mariko), index, g_mtc_tables_buffer);
}
}
void RestoreMemoryClockRate() {
/* NOTE: This resolves an off-by-one issue in PCV's detection of memory clock rate on Mariko. */
if (fuse::GetSocType() == fuse::SocType_Mariko && g_did_training_mariko) {
RestoreMemoryClockRateMariko(g_mtc_tables_buffer);
}
}
}
| 4,214
|
C++
|
.cpp
| 84
| 40.833333
| 182
| 0.628766
|
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,316
|
fusee_mtc_mariko.cpp
|
Atmosphere-NX_Atmosphere/fusee/program/source/mtc/fusee_mtc_mariko.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 "../fusee_fatal.hpp"
#include "../fusee_uncompress.hpp"
#include "fusee_mtc.hpp"
#include "fusee_mtc_timing_table_mariko.hpp"
namespace ams::nxboot {
namespace {
constexpr inline const uintptr_t CLKRST = secmon::MemoryRegionPhysicalDeviceClkRst.GetAddress();
constexpr inline const uintptr_t MC = MC_BASE;
constexpr inline const uintptr_t EMC = EMC_BASE;
constexpr inline const uintptr_t EMC0 = EMC0_BASE;
constexpr inline const uintptr_t EMC1 = EMC1_BASE;
static constinit bool g_next_pll = false;
static constinit bool g_did_first_training = false;
static constinit bool g_fsp_for_next_freq = false;
#include "fusee_mtc_tables_mariko.inc"
#include "fusee_mtc_ram_training_pattern.inc"
#define DECLARE_REGISTER_HANDLER(BASE, REG, NAME) BASE + REG,
constexpr inline const u32 BurstRegisters[] = {
FOREACH_BURST_REG(DECLARE_REGISTER_HANDLER)
};
constexpr inline const u32 TrimRegisters[] = {
FOREACH_TRIM_REG(DECLARE_REGISTER_HANDLER)
};
constexpr inline const u32 BurstMcRegisters[] = {
FOREACH_BURST_MC_REG(DECLARE_REGISTER_HANDLER)
};
constexpr inline const u32 LaScaleRegisters[] = {
FOREACH_LA_SCALE_REG(DECLARE_REGISTER_HANDLER)
};
constexpr inline const u32 PerChannelTrimRegisters[] = {
FOREACH_PER_CHANNEL_TRIM_REG(DECLARE_REGISTER_HANDLER)
};
constexpr inline const u32 PerChannelBurstRegisters[] = {
FOREACH_PER_CHANNEL_BURST_REG(DECLARE_REGISTER_HANDLER)
};
constexpr inline const u32 PerChannelVrefRegisters[] = {
FOREACH_PER_CHANNEL_VREF_REG(DECLARE_REGISTER_HANDLER)
};
constexpr inline const u32 PerChannelTrainingModRegisters[] = {
FOREACH_PER_CHANNEL_TRAINING_MOD_REG(DECLARE_REGISTER_HANDLER)
};
using EmcDvfsTimingTable = mariko::EmcDvfsTimingTable;
EmcDvfsTimingTable *GetEmcDvfsTimingTables(int index, void *mtc_tables_buffer) {
/* Get the compressed table. */
const u8 *cmp_table;
size_t cmp_table_size;
switch (index) {
#define HANDLE_CASE(N, TABLE) \
case N: \
cmp_table = TABLE; \
cmp_table_size = sizeof(TABLE); \
break;
HANDLE_CASE(0x00, T210b01SdevEmcDvfsTableS4gb01)
HANDLE_CASE(0x05, T210b01SdevEmcDvfsTableS4gb03)
HANDLE_CASE(0x06, T210b01SdevEmcDvfsTableS8gb03)
HANDLE_CASE(0x07, T210b01SdevEmcDvfsTableH4gb03)
HANDLE_CASE(0x08, T210b01SdevEmcDvfsTableM4gb03)
HANDLE_CASE(0x09, T210b01SdevEmcDvfsTableS4gbY01)
HANDLE_CASE(0x0A, T210b01SdevEmcDvfsTableS1y4gbY01)
HANDLE_CASE(0x0B, T210b01SdevEmcDvfsTableS1y8gbY01)
HANDLE_CASE(0x0C, T210b01SdevEmcDvfsTableS1y4gbX03)
HANDLE_CASE(0x0D, T210b01SdevEmcDvfsTableS1y8gbX03)
HANDLE_CASE(0x0E, T210b01SdevEmcDvfsTableS1y4gb01)
HANDLE_CASE(0x0F, T210b01SdevEmcDvfsTableM1y4gb01)
HANDLE_CASE(0x10, T210b01SdevEmcDvfsTableH1y4gb01)
HANDLE_CASE(0x11, T210b01SdevEmcDvfsTableS1y8gb04)
HANDLE_CASE(0x12, T210b01SdevEmcDvfsTableS1z4gb01)
HANDLE_CASE(0x13, T210b01SdevEmcDvfsTableH1a4gb01)
HANDLE_CASE(0x14, T210b01SdevEmcDvfsTableM1a4gb01)
default:
ShowFatalError("Unknown EmcDvfsTimingTableIndex: %d\n", index);
}
/* Uncompress the table. */
EmcDvfsTimingTable *out_tables = reinterpret_cast<EmcDvfsTimingTable *>(mtc_tables_buffer);
Uncompress(out_tables, 2 * sizeof(EmcDvfsTimingTable), cmp_table, cmp_table_size);
return out_tables;
}
bool IsSamePll(u32 next_2x, u32 prev_2x) {
if (next_2x == prev_2x) {
return true;
} else if ((next_2x == PLLM_OUT0 || next_2x == PLLM_UD) && (prev_2x == PLLM_OUT0 || prev_2x == PLLM_UD)) {
return true;
} else {
return false;
}
}
bool PllReprogram(u32 next_rate_khz, u32 next_clk_src, u32 prev_rate_khz, u32 prev_clk_src) {
/* Get current divp value. */
u32 pll_p;
switch (reg::GetValue(CLKRST + CLK_RST_CONTROLLER_CLK_SOURCE_EMC, CLK_RST_REG_BITS_MASK(CLK_SOURCE_EMC_EMC_2X_CLK_SRC))) {
case PLLM_UD:
case PLLM_OUT0:
pll_p = reg::GetValue(CLKRST + CLK_RST_CONTROLLER_PLLM_BASE, CLK_RST_REG_BITS_MASK(PLLM_BASE_PLLM_DIVP_B01));
break;
case PLLMB_UD:
case PLLMB_OUT0:
pll_p = reg::GetValue(CLKRST + CLK_RST_CONTROLLER_PLLMB_BASE, CLK_RST_REG_BITS_MASK(PLLMB_BASE_PLLMB_DIVP_B01));
break;
default:
pll_p = 0;
break;
}
/* Get clk src/divisor. */
const u32 next_2x = reg::GetField(next_clk_src, CLK_RST_REG_BITS_MASK(CLK_SOURCE_EMC_EMC_2X_CLK_SRC));
const u32 prev_2x = reg::GetField(prev_clk_src, CLK_RST_REG_BITS_MASK(CLK_SOURCE_EMC_EMC_2X_CLK_SRC));
u32 next_div = reg::GetField(next_clk_src, CLK_RST_REG_BITS_MASK(CLK_SOURCE_EMC_EMC_2X_CLK_DIVISOR));
u32 prev_div = reg::GetField(prev_clk_src, CLK_RST_REG_BITS_MASK(CLK_SOURCE_EMC_EMC_2X_CLK_DIVISOR));
/* Update divisor, if necessary. */
if (next_2x == PLLM_UD || next_2x == PLLMB_UD) {
next_div = 0;
}
if (prev_2x == PLLM_UD || prev_2x == PLLMB_UD) {
prev_div = 0;
}
/* If the pll is different, reprogramming is necessary. */
if (!IsSamePll(next_2x, prev_2x)) {
return true;
}
/* Return whether the ratios are different. */
const float next_freq = next_rate_khz * (1 + (next_div >> 1) + (0.5 * (next_div & 1))) * (pll_p + 1);
const float prev_freq = prev_rate_khz * (1 + (prev_div >> 1) + (0.5 * (prev_div & 1))) * (pll_p + 1);
const float ratio = prev_freq / next_freq;
return ratio > 1.01 || ratio < 0.99;
}
u32 ProgramPllm(u32 next_rate_khz, u32 next_clk_src, u32 ret_clk_src, bool is_pllmb, EmcDvfsTimingTable *timing) {
u32 ret = ret_clk_src;
const uint32_t base = ((timing->pllmb_divm & 0xFF) | ((timing->pllmb_divn & 0xFF) << 8) | ((timing->pllmb_divp & 1) << 20));
if (is_pllmb) {
reg::Write(CLKRST + CLK_RST_CONTROLLER_PLLMB_BASE, base);
reg::Read(CLKRST + CLK_RST_CONTROLLER_PLLMB_BASE);
reg::SetBits(CLKRST + CLK_RST_CONTROLLER_PLLMB_MISC1, 0x10000000);
if (timing->pll_en_ssc & 1) {
reg::Write(CLKRST + CLK_RST_CONTROLLER_PLLMB_SS_CFG, timing->pllmb_ss_cfg);
reg::Write(CLKRST + CLK_RST_CONTROLLER_PLLMB_SS_CTRL1, timing->pllmb_ss_ctrl1);
reg::Write(CLKRST + CLK_RST_CONTROLLER_PLLMB_SS_CTRL2, timing->pllmb_ss_ctrl2);
} else {
reg::Write(CLKRST + CLK_RST_CONTROLLER_PLLMB_SS_CFG, timing->pllmb_ss_cfg & 0xBFFFFFFF);
reg::Write(CLKRST + CLK_RST_CONTROLLER_PLLMB_SS_CTRL2, timing->pllmb_ss_ctrl2 & 0x0000FFFF);
}
reg::SetBits(CLKRST + CLK_RST_CONTROLLER_PLLMB_BASE, 0x40000000);
switch (reg::GetField(ret, CLK_RST_REG_BITS_MASK(CLK_SOURCE_EMC_EMC_2X_CLK_SRC))) {
case PLLM_OUT0:
reg::SetField(ret, CLK_RST_REG_BITS_VALUE(CLK_SOURCE_EMC_EMC_2X_CLK_SRC, PLLMB_OUT0));
break;
case PLLM_UD:
reg::SetField(ret, CLK_RST_REG_BITS_VALUE(CLK_SOURCE_EMC_EMC_2X_CLK_SRC, PLLMB_UD));
break;
}
while ((reg::Read(CLKRST + CLK_RST_CONTROLLER_PLLMB_BASE) & 0x8000000) == 0) { /* ... */ }
return ret;
} else {
reg::Write(CLKRST + CLK_RST_CONTROLLER_PLLM_BASE, base);
reg::Read(CLKRST + CLK_RST_CONTROLLER_PLLM_BASE);
reg::SetBits(CLKRST + CLK_RST_CONTROLLER_PLLM_MISC2, 0x10);
if (timing->pll_en_ssc & 1) {
reg::Write(CLKRST + CLK_RST_CONTROLLER_PLLM_SS_CFG, timing->pllm_ss_cfg);
reg::Write(CLKRST + CLK_RST_CONTROLLER_PLLM_SS_CTRL1, timing->pllm_ss_ctrl1);
reg::Write(CLKRST + CLK_RST_CONTROLLER_PLLM_SS_CTRL2, timing->pllm_ss_ctrl2);
} else {
reg::Write(CLKRST + CLK_RST_CONTROLLER_PLLM_SS_CFG, timing->pllm_ss_cfg & 0xBFFFFFFF);
reg::Write(CLKRST + CLK_RST_CONTROLLER_PLLM_SS_CTRL2, timing->pllm_ss_ctrl2 & 0x0000FFFF);
}
reg::SetBits(CLKRST + CLK_RST_CONTROLLER_PLLM_BASE, 0x40000000);
switch (reg::GetField(ret, CLK_RST_REG_BITS_MASK(CLK_SOURCE_EMC_EMC_2X_CLK_SRC))) {
case PLLM_OUT0:
reg::SetField(ret, CLK_RST_REG_BITS_VALUE(CLK_SOURCE_EMC_EMC_2X_CLK_SRC, PLLM_OUT0));
break;
case PLLM_UD:
reg::SetField(ret, CLK_RST_REG_BITS_VALUE(CLK_SOURCE_EMC_EMC_2X_CLK_SRC, PLLM_UD));
break;
}
while ((reg::Read(CLKRST + CLK_RST_CONTROLLER_PLLM_BASE) & 0x8000000) == 0) { /* ... */ }
return ret;
}
}
u32 GetDllState(EmcDvfsTimingTable *timing) {
return (!(timing->emc_emrs & 0x1)) ? DLL_ON : DLL_OFF;
}
int WaitForUpdate(u32 reg_offset, u32 mask, bool updated, u32 fbio_cfg7) {
constexpr int StatusUpdateTimeout = 1000;
int result = 0;
if (reg::GetField(fbio_cfg7, EMC_REG_BITS_MASK(FBIO_CFG7_CH0_ENABLE)) == EMC_FBIO_CFG7_CH0_ENABLE_ENABLE) {
bool success = false;
for (int i = 0; i < StatusUpdateTimeout; ++i) {
if (((reg::Read(EMC0 + reg_offset) & mask) != 0) == updated) {
success = true;
break;
}
util::WaitMicroSeconds(1);
}
result |= success ? 0 : 4;
}
if (reg::GetField(fbio_cfg7, EMC_REG_BITS_MASK(FBIO_CFG7_CH1_ENABLE)) == EMC_FBIO_CFG7_CH1_ENABLE_ENABLE) {
bool success = false;
for (int i = 0; i < StatusUpdateTimeout; ++i) {
if (((reg::Read(EMC1 + reg_offset) & mask) != 0) == updated) {
success = true;
break;
}
util::WaitMicroSeconds(1);
}
result |= success ? 0 : 4;
}
return result;
}
void TimingUpdate(u32 fbio_cfg7) {
/* Trigger the timing update event. */
reg::Write(EMC + EMC_TIMING_CONTROL, 1);
/* Wait for the update to finish. */
WaitForUpdate(EMC_EMC_STATUS, 0x800000, false, fbio_cfg7);
}
void CcfifoWrite(u32 addr, u32 data, u32 wait) {
reg::Write(EMC + EMC_CCFIFO_DATA, data);
reg::Write(EMC + EMC_CCFIFO_ADDR, (addr & 0xFFFF) | ((wait & 0x7FFF) << 16) | 0x80000000);
}
u32 ActualOscClocks(u32 in) {
if (in < 0x40) {
return in * 0x10;
} else if (in < 0x80) {
return 0x800;
} else if (in < 0xC0) {
return 0x1000;
} else {
return 0x2000;
}
}
u32 DivideUpFloat(u32 a, u32 b) {
const float res = a / b;
const u32 floor = static_cast<u32>(res);
return floor + ((static_cast<float>(floor) + 0.01 < res) ? 1 : 0);
}
void StartPeriodicCompensation() {
reg::Write(EMC + EMC_MPC, 0x4B);
reg::Read(EMC + EMC_MPC);
}
u32 SetShadowBypass(u32 val, u32 emc_dbg) {
reg::SetField(emc_dbg, EMC_REG_BITS_VALUE(DBG_WRITE_MUX, val));
return emc_dbg;
}
constinit uint32_t g_periodic_timmer_compensation_intermediates[9 * 0x10] = {};
uint32_t ApplyPeriodicCompensationTrimmer(EmcDvfsTimingTable *timing, uint32_t trim_reg) {
/* Initialize variables. */
uint32_t rate_mhz = timing->rate_khz / 1000;
uint32_t adj[0x10] = { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 };
int tree_delta[4] = {0};
uint32_t tree_delta_taps[4] = {0};
/* Generate the intermediate array. */
#define SET_TRIM_INTERMEDIATE(_arr_, _emc_, _rank_, _byte_) \
({ \
const uint32_t shft = timing->trim_perch_regs.emc## _emc_ ##_data_brlshft_## _rank_; \
const uint32_t base = ((shft >> (3 * _byte_)) & 7) << 6; \
const uint32_t val0 = timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank ## _rank_ ## _byte ## _byte_ ## _0; \
const uint32_t val1 = timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank ## _rank_ ## _byte ## _byte_ ## _1; \
const uint32_t val2 = timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank ## _rank_ ## _byte ## _byte_ ## _2; \
_arr_[9 * (8 * _rank_ + _byte_) + 0] = base + ((val0 >> 0) & 0xFF); \
_arr_[9 * (8 * _rank_ + _byte_) + 1] = base + ((val0 >> 8) & 0xFF); \
_arr_[9 * (8 * _rank_ + _byte_) + 2] = base + ((val0 >> 16) & 0xFF); \
_arr_[9 * (8 * _rank_ + _byte_) + 3] = base + ((val0 >> 24) & 0xFF); \
_arr_[9 * (8 * _rank_ + _byte_) + 4] = base + ((val1 >> 0) & 0xFF); \
_arr_[9 * (8 * _rank_ + _byte_) + 5] = base + ((val1 >> 8) & 0xFF); \
_arr_[9 * (8 * _rank_ + _byte_) + 6] = base + ((val1 >> 16) & 0xFF); \
_arr_[9 * (8 * _rank_ + _byte_) + 7] = base + ((val1 >> 24) & 0xFF); \
_arr_[9 * (8 * _rank_ + _byte_) + 8] = base + ((val2 >> 0) & 0xFF); \
})
{
SET_TRIM_INTERMEDIATE(g_periodic_timmer_compensation_intermediates, 0, 0, 0);
SET_TRIM_INTERMEDIATE(g_periodic_timmer_compensation_intermediates, 0, 0, 1);
SET_TRIM_INTERMEDIATE(g_periodic_timmer_compensation_intermediates, 0, 0, 2);
SET_TRIM_INTERMEDIATE(g_periodic_timmer_compensation_intermediates, 0, 0, 3);
SET_TRIM_INTERMEDIATE(g_periodic_timmer_compensation_intermediates, 1, 0, 4);
SET_TRIM_INTERMEDIATE(g_periodic_timmer_compensation_intermediates, 1, 0, 5);
SET_TRIM_INTERMEDIATE(g_periodic_timmer_compensation_intermediates, 1, 0, 6);
SET_TRIM_INTERMEDIATE(g_periodic_timmer_compensation_intermediates, 1, 0, 7);
SET_TRIM_INTERMEDIATE(g_periodic_timmer_compensation_intermediates, 0, 1, 0);
SET_TRIM_INTERMEDIATE(g_periodic_timmer_compensation_intermediates, 0, 1, 1);
SET_TRIM_INTERMEDIATE(g_periodic_timmer_compensation_intermediates, 0, 1, 2);
SET_TRIM_INTERMEDIATE(g_periodic_timmer_compensation_intermediates, 0, 1, 3);
SET_TRIM_INTERMEDIATE(g_periodic_timmer_compensation_intermediates, 1, 1, 4);
SET_TRIM_INTERMEDIATE(g_periodic_timmer_compensation_intermediates, 1, 1, 5);
SET_TRIM_INTERMEDIATE(g_periodic_timmer_compensation_intermediates, 1, 1, 6);
SET_TRIM_INTERMEDIATE(g_periodic_timmer_compensation_intermediates, 1, 1, 7);
}
#undef SET_TRIM_INTERMEDIATE
switch (trim_reg) {
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE0_0:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE0_1:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE0_2:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE1_0:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE1_1:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE1_2:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE2_0:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE2_1:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE2_2:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE3_0:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE3_1:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE3_2:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE4_0:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE4_1:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE4_2:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE5_0:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE5_1:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE5_2:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE6_0:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE6_1:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE6_2:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE7_0:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE7_1:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE7_2:
case EMC0_BASE + EMC_DATA_BRLSHFT_0:
case EMC1_BASE + EMC_DATA_BRLSHFT_0:
{
tree_delta[0] = 128 * (timing->current_dram_clktree_c0d0u0 - timing->trained_dram_clktree_c0d0u0);
tree_delta[1] = 128 * (timing->current_dram_clktree_c0d0u1 - timing->trained_dram_clktree_c0d0u1);
tree_delta[2] = 128 * (timing->current_dram_clktree_c1d0u0 - timing->trained_dram_clktree_c1d0u0);
tree_delta[3] = 128 * (timing->current_dram_clktree_c1d0u1 - timing->trained_dram_clktree_c1d0u1);
tree_delta_taps[0] = (tree_delta[0] * (int)rate_mhz) / 1000000;
tree_delta_taps[1] = (tree_delta[1] * (int)rate_mhz) / 1000000;
tree_delta_taps[2] = (tree_delta[2] * (int)rate_mhz) / 1000000;
tree_delta_taps[3] = (tree_delta[3] * (int)rate_mhz) / 1000000;
for (int i = 0; i < 4; ++i) {
const uint32_t sum = (tree_delta_taps[i] <= timing->tree_margin) ? 0 : tree_delta_taps[i];
for (int j = 0; j < 18; ++j) {
const uint32_t v = (g_periodic_timmer_compensation_intermediates[18 * i + j] += sum);
if (v < (adj[2 * i + (j < 9)] << 6)) {
adj[2 * i + (j < 9)] = v >> 6;
}
}
for (int j = 0; j < 18; ++j) {
g_periodic_timmer_compensation_intermediates[18 * i + j] -= (adj[2 * i + (j < 9)] << 6);
}
}
}
break;
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE0_0:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE0_1:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE0_2:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE1_0:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE1_1:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE1_2:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE2_0:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE2_1:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE2_2:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE3_0:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE3_1:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE3_2:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE4_0:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE4_1:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE4_2:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE5_0:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE5_1:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE5_2:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE6_0:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE6_1:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE6_2:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE7_0:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE7_1:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE7_2:
case EMC0_BASE + EMC_DATA_BRLSHFT_1:
case EMC1_BASE + EMC_DATA_BRLSHFT_1:
{
tree_delta[0] = 128 * (timing->current_dram_clktree_c0d1u0 - timing->trained_dram_clktree_c0d1u0);
tree_delta[1] = 128 * (timing->current_dram_clktree_c0d1u1 - timing->trained_dram_clktree_c0d1u1);
tree_delta[2] = 128 * (timing->current_dram_clktree_c1d1u0 - timing->trained_dram_clktree_c1d1u0);
tree_delta[3] = 128 * (timing->current_dram_clktree_c1d1u1 - timing->trained_dram_clktree_c1d1u1);
tree_delta_taps[0] = (tree_delta[0] * (int)rate_mhz) / 1000000;
tree_delta_taps[1] = (tree_delta[1] * (int)rate_mhz) / 1000000;
tree_delta_taps[2] = (tree_delta[2] * (int)rate_mhz) / 1000000;
tree_delta_taps[3] = (tree_delta[3] * (int)rate_mhz) / 1000000;
for (int i = 0; i < 4; ++i) {
const uint32_t sum = (tree_delta_taps[i] <= timing->tree_margin) ? 0 : tree_delta_taps[i];
for (int j = 0; j < 18; ++j) {
const uint32_t v = (g_periodic_timmer_compensation_intermediates[72 + 18 * i + j] += sum);
if (v < (adj[8 + 2 * i + (j < 9)] << 6)) {
adj[8 + 2 * i + (j < 9)] = v >> 6;
}
}
for (int j = 0; j < 18; ++j) {
g_periodic_timmer_compensation_intermediates[72 + 18 * i + j] -= (adj[8 + 2 * i + (j < 9)] << 6);
}
}
}
break;
}
uint32_t result = 0;
switch (trim_reg) {
case EMC0_BASE + EMC_DATA_BRLSHFT_0:
result = ((adj[ 0] & 7) << 0) | ((adj[ 1] & 7) << 3) | ((adj[ 2] & 7) << 6) | ((adj[ 3] & 7) << 9);
break;
case EMC1_BASE + EMC_DATA_BRLSHFT_0:
result = ((adj[ 4] & 7) << 12) | ((adj[ 5] & 7) << 15) | ((adj[ 6] & 7) << 18) | ((adj[ 7] & 7) << 21);
break;
case EMC0_BASE + EMC_DATA_BRLSHFT_1:
result = ((adj[ 8] & 7) << 0) | ((adj[ 9] & 7) << 3) | ((adj[10] & 7) << 6) | ((adj[11] & 7) << 9);
break;
case EMC1_BASE + EMC_DATA_BRLSHFT_1:
result = ((adj[12] & 7) << 12) | ((adj[13] & 7) << 15) | ((adj[14] & 7) << 18) | ((adj[15] & 7) << 21);
break;
#define ADD_TRIM_CASE(_ARR_, _RANK_, _BYTE_) \
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK ## _RANK_ ## _BYTE ## _BYTE_ ##_0: \
result = ((_ARR_[9 * (8 * _RANK_ + _BYTE_) + 0] & 0xFF) << 0) | ((_ARR_[9 * (8 * _RANK_ + _BYTE_) + 1] & 0xFF) << 8) | ((_ARR_[9 * (8 * _RANK_ + _BYTE_) + 2] & 0xFF) << 16) | ((_ARR_[9 * (8 * _RANK_ + _BYTE_) + 3] & 0xFF) << 24); \
break; \
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK ## _RANK_ ## _BYTE ## _BYTE_ ##_1: \
result = ((_ARR_[9 * (8 * _RANK_ + _BYTE_) + 4] & 0xFF) << 0) | ((_ARR_[9 * (8 * _RANK_ + _BYTE_) + 5] & 0xFF) << 8) | ((_ARR_[9 * (8 * _RANK_ + _BYTE_) + 6] & 0xFF) << 16) | ((_ARR_[9 * (8 * _RANK_ + _BYTE_) + 7] & 0xFF) << 24); \
break; \
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK ## _RANK_ ## _BYTE ## _BYTE_ ##_2: \
result = ((_ARR_[9 * (8 * _RANK_ + _BYTE_) + 8] & 0xFF) << 0); \
break;
ADD_TRIM_CASE(g_periodic_timmer_compensation_intermediates, 0, 0);
ADD_TRIM_CASE(g_periodic_timmer_compensation_intermediates, 0, 1);
ADD_TRIM_CASE(g_periodic_timmer_compensation_intermediates, 0, 2);
ADD_TRIM_CASE(g_periodic_timmer_compensation_intermediates, 0, 3);
ADD_TRIM_CASE(g_periodic_timmer_compensation_intermediates, 0, 4);
ADD_TRIM_CASE(g_periodic_timmer_compensation_intermediates, 0, 5);
ADD_TRIM_CASE(g_periodic_timmer_compensation_intermediates, 0, 6);
ADD_TRIM_CASE(g_periodic_timmer_compensation_intermediates, 0, 7);
ADD_TRIM_CASE(g_periodic_timmer_compensation_intermediates, 1, 0);
ADD_TRIM_CASE(g_periodic_timmer_compensation_intermediates, 1, 1);
ADD_TRIM_CASE(g_periodic_timmer_compensation_intermediates, 1, 2);
ADD_TRIM_CASE(g_periodic_timmer_compensation_intermediates, 1, 3);
ADD_TRIM_CASE(g_periodic_timmer_compensation_intermediates, 1, 4);
ADD_TRIM_CASE(g_periodic_timmer_compensation_intermediates, 1, 5);
ADD_TRIM_CASE(g_periodic_timmer_compensation_intermediates, 1, 6);
ADD_TRIM_CASE(g_periodic_timmer_compensation_intermediates, 1, 7);
#undef ADD_TRIM_CASE
}
return result;
}
u32 UpdateClockTreeDelay(EmcDvfsTimingTable *src_timing, EmcDvfsTimingTable *dst_timing, u32 dram_dev_num, u32 mode, int type) {
uint32_t mrr_req = 0, mrr_data = 0;
uint32_t temp0_0 = 0, temp0_1 = 0, temp1_0 = 0, temp1_1 = 0;
int tdel = 0, tmdel = 0, adel = 0;
uint32_t current_timing_rate_mhz = src_timing->rate_khz / 1000;
uint32_t next_timing_rate_mhz = dst_timing->rate_khz / 1000;
uint32_t fbio_cfg7 = dst_timing->emc_fbio_cfg7;
const bool ch0_enable = reg::GetField(fbio_cfg7, EMC_REG_BITS_MASK(FBIO_CFG7_CH0_ENABLE)) == EMC_FBIO_CFG7_CH0_ENABLE_ENABLE;
const bool ch1_enable = reg::GetField(fbio_cfg7, EMC_REG_BITS_MASK(FBIO_CFG7_CH1_ENABLE)) == EMC_FBIO_CFG7_CH1_ENABLE_ENABLE;
bool dvfs_pt1 = (type == DVFS_PT1);
bool training_pt1 = (type == TRAINING_PT1);
bool dvfs_update = (type == DVFS_UPDATE);
bool training_update = (type == TRAINING_UPDATE);
bool periodic_training_update = (type == PERIODIC_TRAINING_UPDATE);
/* Dev0 MSB. */
if (dvfs_pt1 || training_pt1 || periodic_training_update) {
mrr_req = ((2 << 30) | (19 << 16));
reg::Write(EMC + EMC_MRR, mrr_req);
WaitForUpdate(EMC_EMC_STATUS, (1 << 20), true, fbio_cfg7);
if (ch0_enable) {
mrr_data = (reg::Read(EMC0 + EMC_MRR) & 0xFFFF);
temp0_0 = ((mrr_data & 0xff) << 8);
temp0_1 = (mrr_data & 0xff00);
} else {
temp0_0 = temp0_1 = 0;
}
if (ch1_enable) {
mrr_data = (reg::Read(EMC1 + EMC_MRR) & 0xFFFF);
temp1_0 = ((mrr_data & 0xff) << 8);
temp1_1 = (mrr_data & 0xff00);
} else {
temp1_0 = temp1_1 = 0;
}
/* Dev0 LSB. */
mrr_req = ((mrr_req & ~(0xFF << 16)) | (18 << 16));
reg::Write(EMC + EMC_MRR, mrr_req);
WaitForUpdate(EMC_EMC_STATUS, (1 << 20), true, fbio_cfg7);
if (ch0_enable) {
mrr_data = (reg::Read(EMC0 + EMC_MRR) & 0xFFFF);
temp0_0 |= (mrr_data & 0xff);
temp0_1 |= (mrr_data & 0xff00) >> 8;
}
if (ch1_enable) {
mrr_data = (reg::Read(EMC1 + EMC_MRR) & 0xFFFF);
temp1_0 |= (mrr_data & 0xff);
temp1_1 |= (mrr_data & 0xff00) >> 8;
}
}
#define CVAL(v) ((uint32_t)((1000 * ((1000 * ActualOscClocks(src_timing->run_clocks)) / current_timing_rate_mhz)) / (2 * v)))
if (ch0_enable) {
if (dvfs_pt1 || training_pt1)
__INCREMENT_PTFV(c0d0u0, CVAL(temp0_0));
else if (dvfs_update)
__AVERAGE_PTFV(c0d0u0);
else if (training_update)
__AVERAGE_WRITE_PTFV(c0d0u0);
else if (periodic_training_update)
__WEIGHTED_UPDATE_PTFV(c0d0u0, CVAL(temp0_0));
if (dvfs_update || training_update || periodic_training_update) {
tdel = (dst_timing->current_dram_clktree_c0d0u0 - __MOVAVG_AC(dst_timing, c0d0u0));
tmdel = (tdel < 0) ? ~tdel : tdel;
adel = tmdel;
if (mode == 1 || ((adel * 128 * next_timing_rate_mhz) / 1000000) > dst_timing->tree_margin)
dst_timing->current_dram_clktree_c0d0u0 = __MOVAVG_AC(dst_timing, c0d0u0);
}
if (dvfs_pt1 || training_pt1)
__INCREMENT_PTFV(c0d0u1, CVAL(temp0_1));
else if (dvfs_update)
__AVERAGE_PTFV(c0d0u1);
else if (training_update)
__AVERAGE_WRITE_PTFV(c0d0u1);
else if (periodic_training_update)
__WEIGHTED_UPDATE_PTFV(c0d0u1, CVAL(temp0_1));
if (dvfs_update || training_update || periodic_training_update) {
tdel = (dst_timing->current_dram_clktree_c0d0u1 - __MOVAVG_AC(dst_timing, c0d0u1));
tmdel = (tdel < 0) ? -1 * tdel : tdel;
if (tmdel > adel)
adel = tmdel;
if (mode == 1 || (tmdel * 128 * next_timing_rate_mhz / 1000000) > dst_timing->tree_margin)
dst_timing->current_dram_clktree_c0d0u1 = __MOVAVG_AC(dst_timing, c0d0u1);
}
} else {
adel = 0;
}
if (ch1_enable) {
if (dvfs_pt1 || training_pt1)
__INCREMENT_PTFV(c1d0u0, CVAL(temp1_0));
else if (dvfs_update)
__AVERAGE_PTFV(c1d0u0);
else if (training_update)
__AVERAGE_WRITE_PTFV(c1d0u0);
else if (periodic_training_update)
__WEIGHTED_UPDATE_PTFV(c1d0u0, CVAL(temp1_0));
if (dvfs_update || training_update || periodic_training_update) {
tdel = (dst_timing->current_dram_clktree_c1d0u0 - __MOVAVG_AC(dst_timing, c1d0u0));
tmdel = (tdel < 0) ? -1 * tdel : tdel;
if (tmdel > adel)
adel = tmdel;
if (mode == 1 || (tmdel * 128 * next_timing_rate_mhz / 1000000) > dst_timing->tree_margin)
dst_timing->current_dram_clktree_c1d0u0 = __MOVAVG_AC(dst_timing, c1d0u0);
}
if (dvfs_pt1 || training_pt1)
__INCREMENT_PTFV(c1d0u1, CVAL(temp1_1));
else if (dvfs_update)
__AVERAGE_PTFV(c1d0u1);
else if (training_update)
__AVERAGE_WRITE_PTFV(c1d0u1);
else if (periodic_training_update)
__WEIGHTED_UPDATE_PTFV(c1d0u1, CVAL(temp1_1));
if (dvfs_update || training_update || periodic_training_update) {
tdel = (dst_timing->current_dram_clktree_c1d0u1 - __MOVAVG_AC(dst_timing, c1d0u1));
tmdel = (tdel < 0) ? -1 * tdel : tdel;
if (tmdel > adel)
adel = tmdel;
if (mode == 1 || (tmdel * 128 * next_timing_rate_mhz / 1000000) > dst_timing->tree_margin)
dst_timing->current_dram_clktree_c1d0u1 = __MOVAVG_AC(dst_timing, c1d0u1);
}
}
if (dram_dev_num == TWO_RANK) {
/* Dev1 MSB. */
if (dvfs_pt1 || training_pt1 || periodic_training_update) {
mrr_req = ((1 << 30) | (19 << 16));
reg::Write(EMC + EMC_MRR, mrr_req);
WaitForUpdate(EMC_EMC_STATUS, (1 << 20), true, fbio_cfg7);
if (ch0_enable) {
mrr_data = (reg::Read(EMC0 + EMC_MRR) & 0xFFFF);
temp0_0 = ((mrr_data & 0xff) << 8);
temp0_1 = (mrr_data & 0xff00);
}
if (ch1_enable) {
mrr_data = (reg::Read(EMC1 + EMC_MRR) & 0xFFFF);
temp1_0 = ((mrr_data & 0xff) << 8);
temp1_1 = (mrr_data & 0xff00);
}
/* Dev1 LSB. */
mrr_req = ((mrr_req & ~(0xFF << 16)) | (18 << 16));
reg::Write(EMC + EMC_MRR, mrr_req);
WaitForUpdate(EMC_EMC_STATUS, (1 << 20), true, fbio_cfg7);
if (ch0_enable) {
mrr_data = (reg::Read(EMC0 + EMC_MRR) & 0xFFFF);
temp0_0 |= ((mrr_data & 0xff) << 8);
temp0_1 |= (mrr_data & 0xff00);
}
if (ch1_enable) {
mrr_data = (reg::Read(EMC1 + EMC_MRR) & 0xFFFF);
temp1_0 |= ((mrr_data & 0xff) << 8);
temp1_1 |= (mrr_data & 0xff00);
}
}
if (ch0_enable) {
if (dvfs_pt1 || training_pt1)
__INCREMENT_PTFV(c0d1u0, CVAL(temp0_0));
else if (dvfs_update)
__AVERAGE_PTFV(c0d1u0);
else if (training_update)
__AVERAGE_WRITE_PTFV(c0d1u0);
else if (periodic_training_update)
__WEIGHTED_UPDATE_PTFV(c0d1u0, CVAL(temp0_0));
if (dvfs_update || training_update || periodic_training_update) {
tdel = (dst_timing->current_dram_clktree_c0d1u0 - __MOVAVG_AC(dst_timing, c0d1u0));
tmdel = (tdel < 0) ? -1 * tdel : tdel;
if (tmdel > adel)
adel = tmdel;
if (mode == 1 || (tmdel * 128 * next_timing_rate_mhz / 1000000) > dst_timing->tree_margin)
dst_timing->current_dram_clktree_c0d1u0 = __MOVAVG_AC(dst_timing, c0d1u0);
}
if (dvfs_pt1 || training_pt1)
__INCREMENT_PTFV(c0d1u1, CVAL(temp0_1));
else if (dvfs_update)
__AVERAGE_PTFV(c0d1u1);
else if (training_update)
__AVERAGE_WRITE_PTFV(c0d1u1);
else if (periodic_training_update)
__WEIGHTED_UPDATE_PTFV(c0d1u1, CVAL(temp0_1));
if (dvfs_update || training_update || periodic_training_update) {
tdel = (dst_timing->current_dram_clktree_c0d1u1 - __MOVAVG_AC(dst_timing, c0d1u1));
tmdel = (tdel < 0) ? -1 * tdel : tdel;
if (tmdel > adel)
adel = tmdel;
if (mode == 1 || (tmdel * 128 * next_timing_rate_mhz / 1000000) > dst_timing->tree_margin)
dst_timing->current_dram_clktree_c0d1u1 = __MOVAVG_AC(dst_timing, c0d1u1);
}
}
if (ch1_enable) {
if (dvfs_pt1 || training_pt1)
__INCREMENT_PTFV(c1d1u0, CVAL(temp1_0));
else if (dvfs_update)
__AVERAGE_PTFV(c1d1u0);
else if (training_update)
__AVERAGE_WRITE_PTFV(c1d1u0);
else if (periodic_training_update)
__WEIGHTED_UPDATE_PTFV(c1d1u0, CVAL(temp1_0));
if (dvfs_update || training_update || periodic_training_update) {
tdel = (dst_timing->current_dram_clktree_c1d1u0 - __MOVAVG_AC(dst_timing, c1d1u0));
tmdel = (tdel < 0) ? -1 * tdel : tdel;
if (tmdel > adel)
adel = tmdel;
if (mode == 1 || (tmdel * 128 * next_timing_rate_mhz / 1000000) > dst_timing->tree_margin)
dst_timing->current_dram_clktree_c1d1u0 = __MOVAVG_AC(dst_timing, c1d1u0);
}
if (dvfs_pt1 || training_pt1)
__INCREMENT_PTFV(c1d1u1, CVAL(temp1_1));
else if (dvfs_update)
__AVERAGE_PTFV(c1d1u1);
else if (training_update)
__AVERAGE_WRITE_PTFV(c1d1u1);
else if (periodic_training_update)
__WEIGHTED_UPDATE_PTFV(c1d1u1, CVAL(temp1_1));
if (dvfs_update || training_update || periodic_training_update) {
tdel = (dst_timing->current_dram_clktree_c1d1u1 - __MOVAVG_AC(dst_timing, c1d1u1));
tmdel = (tdel < 0) ? -1 * tdel : tdel;
if (tmdel > adel)
adel = tmdel;
if (mode == 1 || (tmdel * 128 * next_timing_rate_mhz / 1000000) > dst_timing->tree_margin)
dst_timing->current_dram_clktree_c1d1u1 = __MOVAVG_AC(dst_timing, c1d1u1);
}
}
}
#undef CVAL
if (mode == 1) {
dst_timing->trained_dram_clktree_c0d0u0 = dst_timing->current_dram_clktree_c0d0u0;
dst_timing->trained_dram_clktree_c0d0u1 = dst_timing->current_dram_clktree_c0d0u1;
dst_timing->trained_dram_clktree_c0d1u0 = dst_timing->current_dram_clktree_c0d1u0;
dst_timing->trained_dram_clktree_c0d1u1 = dst_timing->current_dram_clktree_c0d1u1;
dst_timing->trained_dram_clktree_c1d0u0 = dst_timing->current_dram_clktree_c1d0u0;
dst_timing->trained_dram_clktree_c1d0u1 = dst_timing->current_dram_clktree_c1d0u1;
dst_timing->trained_dram_clktree_c1d1u0 = dst_timing->current_dram_clktree_c1d1u0;
dst_timing->trained_dram_clktree_c1d1u1 = dst_timing->current_dram_clktree_c1d1u1;
}
return adel;
}
u32 PeriodicCompensationHandler(int type, u32 dram_dev_num, EmcDvfsTimingTable *src_timing, EmcDvfsTimingTable *dst_timing) {
if (!dst_timing->periodic_training) {
return 0;
}
uint32_t adel = 0;
uint32_t samples = dst_timing->ptfv_dvfs_samples;
uint32_t samples_write = dst_timing->ptfv_write_samples;
uint32_t delay = 2 + (1000 * ActualOscClocks(src_timing->run_clocks) / src_timing->rate_khz);
if (type == DVFS_SEQUENCE) {
if (src_timing->periodic_training && (dst_timing->ptfv_config_ctrl & 1)) {
/* If the previous frequency was using periodic calibration then we can reuse the previous frequencies EMA data. */
dst_timing->ptfv_dqsosc_movavg_c0d0u0 = src_timing->ptfv_dqsosc_movavg_c0d0u0 * samples;
dst_timing->ptfv_dqsosc_movavg_c0d0u1 = src_timing->ptfv_dqsosc_movavg_c0d0u1 * samples;
dst_timing->ptfv_dqsosc_movavg_c1d0u0 = src_timing->ptfv_dqsosc_movavg_c1d0u0 * samples;
dst_timing->ptfv_dqsosc_movavg_c1d0u1 = src_timing->ptfv_dqsosc_movavg_c1d0u1 * samples;
dst_timing->ptfv_dqsosc_movavg_c0d1u0 = src_timing->ptfv_dqsosc_movavg_c0d1u0 * samples;
dst_timing->ptfv_dqsosc_movavg_c0d1u1 = src_timing->ptfv_dqsosc_movavg_c0d1u1 * samples;
dst_timing->ptfv_dqsosc_movavg_c1d1u0 = src_timing->ptfv_dqsosc_movavg_c1d1u0 * samples;
dst_timing->ptfv_dqsosc_movavg_c1d1u1 = src_timing->ptfv_dqsosc_movavg_c1d1u1 * samples;
} else {
/* Reset the EMA. */
dst_timing->ptfv_dqsosc_movavg_c0d0u0 = 0;
dst_timing->ptfv_dqsosc_movavg_c0d0u1 = 0;
dst_timing->ptfv_dqsosc_movavg_c0d1u0 = 0;
dst_timing->ptfv_dqsosc_movavg_c0d1u1 = 0;
dst_timing->ptfv_dqsosc_movavg_c1d0u0 = 0;
dst_timing->ptfv_dqsosc_movavg_c1d0u1 = 0;
dst_timing->ptfv_dqsosc_movavg_c1d1u0 = 0;
dst_timing->ptfv_dqsosc_movavg_c1d1u1 = 0;
for (uint32_t i = 0; i < samples; ++i) {
StartPeriodicCompensation();
util::WaitMicroSeconds(delay);
/* Generate next sample of data. */
adel = UpdateClockTreeDelay(src_timing, dst_timing, dram_dev_num, 0, DVFS_PT1);
}
}
adel = UpdateClockTreeDelay(src_timing, dst_timing, dram_dev_num, 0, DVFS_UPDATE);
} else if (type == WRITE_TRAINING_SEQUENCE) {
/* Reset the EMA. */
dst_timing->ptfv_dqsosc_movavg_c0d0u0 = 0;
dst_timing->ptfv_dqsosc_movavg_c0d0u1 = 0;
dst_timing->ptfv_dqsosc_movavg_c0d1u0 = 0;
dst_timing->ptfv_dqsosc_movavg_c0d1u1 = 0;
dst_timing->ptfv_dqsosc_movavg_c1d0u0 = 0;
dst_timing->ptfv_dqsosc_movavg_c1d0u1 = 0;
dst_timing->ptfv_dqsosc_movavg_c1d1u0 = 0;
dst_timing->ptfv_dqsosc_movavg_c1d1u1 = 0;
for (uint32_t i = 0; i < samples_write; ++i) {
StartPeriodicCompensation();
util::WaitMicroSeconds(delay);
/* Generate next sample of data. */
adel = UpdateClockTreeDelay(src_timing, dst_timing, dram_dev_num, 1, TRAINING_PT1);
}
adel = UpdateClockTreeDelay(src_timing, dst_timing, dram_dev_num, 1, TRAINING_UPDATE);
} else if (type == PERIODIC_TRAINING_SEQUENCE) {
StartPeriodicCompensation();
util::WaitMicroSeconds(delay);
adel = UpdateClockTreeDelay(src_timing, dst_timing, dram_dev_num, 0, PERIODIC_TRAINING_UPDATE);
}
return adel;
}
void ChangeDllSrc(EmcDvfsTimingTable *dst_timing, u32 next_clk_src) {
u32 dll_setting = ((next_clk_src & 0xE00000FF) | (dst_timing->dll_clk_src & 0x1FFFFF00)) & 0xFFFFF3FF;
switch (reg::GetField(next_clk_src, CLK_RST_REG_BITS_MASK(CLK_SOURCE_EMC_EMC_2X_CLK_SRC))) {
case PLLMB_UD:
dll_setting |= 0x400; /* PLLM_VCOB */
break;
case PLLM_UD:
dll_setting |= 0x000; /* PLLM_VCOA */
break;
default:
dll_setting |= 0x800; /* EMC_DLL_SWITCH_OUT */
break;
}
reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_SOURCE_EMC_DLL, dll_setting);
reg::ReadWrite(CLKRST + CLK_RST_CONTROLLER_CLK_OUT_ENB_X, CLK_RST_REG_BITS_ENUM_SEL(CLK_ENB_X_CLK_ENB_EMC_DLL, (dst_timing->clk_out_enb_x_0_clk_enb_emc_dll & 1), ENABLE, DISABLE));
reg::Read(CLKRST + CLK_RST_CONTROLLER_CLK_OUT_ENB_X);
}
void DllPrelock(EmcDvfsTimingTable *dst_timing, EmcDvfsTimingTable *src_timing, bool training_enabled, u32 next_clk_src) {
/* Update EMC_CFG_DIG_DLL */
reg::Write(EMC + EMC_CFG_DIG_DLL, (reg::Read(EMC + EMC_CFG_DIG_DLL) & 0xFFFFFFE4) | 0x00000008);
/* Request a timing update event */
TimingUpdate(dst_timing->emc_fbio_cfg7);
/* Update EMC_CFG_DIG_DLL */
reg::Write(EMC + EMC_CFG_DIG_DLL, (reg::Read(EMC + EMC_CFG_DIG_DLL) & 0xFFFFF824) | 0x000003C8);
/* Request a timing update event */
TimingUpdate(dst_timing->emc_fbio_cfg7);
/* Wait until CFG_DLL_EN is cleared. */
WaitForUpdate(EMC_CFG_DIG_DLL, (1 << 0), false, dst_timing->emc_fbio_cfg7);
/* Configure PMACRO_DLL_CFG */
reg::Write(EMC + EMC_PMACRO_DLL_CFG_0, dst_timing->burst_regs.emc_pmacro_dll_cfg_0);
reg::Read(EMC + EMC_PMACRO_DLL_CFG_1);
reg::Write(EMC + EMC_PMACRO_DLL_CFG_1, (dst_timing->burst_regs.emc_pmacro_dll_cfg_1 & 0xFFFFDFFF) | (reg::Read(EMC + EMC_PMACRO_DLL_CFG_1) & 0x00002000));
/* Request a timing update event */
TimingUpdate(dst_timing->emc_fbio_cfg7);
/* Change the dll clock source. */
ChangeDllSrc(dst_timing, next_clk_src);
/* Wait 2 us. */
util::WaitMicroSeconds(2);
/* Enable dll. */
reg::SetBits(EMC + EMC_CFG_DIG_DLL, 0x1);
/* Request a timing update event */
TimingUpdate(dst_timing->emc_fbio_cfg7);
/* Wait until CFG_DLL_EN is set. */
WaitForUpdate(EMC_CFG_DIG_DLL, (1 << 0), true, dst_timing->emc_fbio_cfg7);
/* Wait for DLL_LOCK to be set */
WaitForUpdate(EMC_DIG_DLL_STATUS, (1 << 2), true, dst_timing->emc_fbio_cfg7);
if (training_enabled) {
/* Disable dll. */
reg::SetBits(EMC + EMC_DBG, 0x2);
reg::ClearBits(EMC + EMC_CFG_DIG_DLL, 0x1);
reg::ClearBits(EMC + EMC_DBG, 0x2);
/* Wait until CFG_DLL_EN is cleared. */
WaitForUpdate(EMC_CFG_DIG_DLL, (1 << 0), false, dst_timing->emc_fbio_cfg7);
}
reg::Read(EMC + EMC_PMACRO_DIG_DLL_STATUS_0);
}
void DllDisable(u32 fbio_cfg7) {
/* Disable dll. */
reg::ClearBits(EMC + EMC_CFG_DIG_DLL, 0x1);
/* Request a timing update event */
TimingUpdate(fbio_cfg7);
/* Wait until CFG_DLL_EN is cleared. */
WaitForUpdate(EMC_CFG_DIG_DLL, (1 << 0), false, fbio_cfg7);
}
void PllDisable(u32 dst_clk_src) {
switch (reg::GetField(dst_clk_src, CLK_RST_REG_BITS_MASK(CLK_SOURCE_EMC_EMC_2X_CLK_SRC))) {
case PLLM_OUT0:
case PLLM_UD:
reg::ClearBits(CLKRST + CLK_RST_CONTROLLER_PLLMB_BASE, 0x40000000);
break;
case PLLMB_OUT0:
case PLLMB_UD:
reg::ClearBits(CLKRST + CLK_RST_CONTROLLER_PLLM_BASE, 0x40000000);
break;
default:
reg::ClearBits(CLKRST + CLK_RST_CONTROLLER_PLLMB_BASE, 0x40000000);
reg::ClearBits(CLKRST + CLK_RST_CONTROLLER_PLLM_BASE, 0x40000000);
break;
}
}
void DvfsPowerRampDown(EmcDvfsTimingTable *src_timing, EmcDvfsTimingTable *dst_timing, bool flip_backward, u32 vtt_vdda_channel) {
auto *from_table = (flip_backward ? dst_timing : src_timing);
auto *to_table = (flip_backward ? src_timing : dst_timing);
uint32_t from_rate_khz = from_table->rate_khz;
uint32_t from_period = 1000000000 / from_rate_khz;
uint32_t to_rate_khz = to_table->rate_khz;
uint32_t clk_div = 1000 * dst_timing->src_clock_div;
uint32_t delay = util::DivideUp(clk_div, from_period);
if (from_rate_khz >= 407997 || to_rate_khz <= 407996) {
if (from_rate_khz >= 407997 && to_rate_khz <= 407996) {
uint32_t pmacro_vttgen_ctrl_1 = reg::Read(EMC + EMC_PMACRO_VTTGEN_CTRL_1);
if (dst_timing->vtt_vdda_dual_channel) {
if (vtt_vdda_channel != 1) {
return;
}
CcfifoWrite(EMC_PMACRO_VTTGEN_CTRL_1, (pmacro_vttgen_ctrl_1 & 0xFFFF03FF) | ((to_table->vtt_vdda_ctrl_4 & 0x3F) << 10), delay);
CcfifoWrite(EMC_PMACRO_VTTGEN_CTRL_1, (pmacro_vttgen_ctrl_1 & 0xFFFF03FF) | ((to_table->vtt_vdda_ctrl_0 & 0x3F) << 10), delay * 2);
} else {
CcfifoWrite(EMC_PMACRO_VTTGEN_CTRL_1, (pmacro_vttgen_ctrl_1 & 0xFFFF03FF) | ((dst_timing->vtt_vdda_ctrl_0 & 0x3F) << 10), 0);
}
}
} else {
uint32_t pmacro_vttgen_ctrl_1 = reg::Read(EMC + EMC_PMACRO_VTTGEN_CTRL_1);
if (dst_timing->vtt_vdda_dual_channel) {
if (vtt_vdda_channel == 1) {
CcfifoWrite(EMC_PMACRO_VTTGEN_CTRL_1, (pmacro_vttgen_ctrl_1 & 0xFFFF03FF) | ((dst_timing->vtt_vdda_ctrl_3 & 0x3F) << 10), delay);
CcfifoWrite(EMC_PMACRO_VTTGEN_CTRL_1, (pmacro_vttgen_ctrl_1 & 0xFFFF03FF) | ((dst_timing->vtt_vdda_ctrl_0 & 0x3F) << 10), delay);
} else if (vtt_vdda_channel == 0) {
CcfifoWrite(EMC_PMACRO_VTTGEN_CTRL_1, (pmacro_vttgen_ctrl_1 & 0xFFFF03FF) | ((dst_timing->vtt_vdda_ctrl_1 & 0x3F) << 10), delay);
CcfifoWrite(EMC_PMACRO_VTTGEN_CTRL_1, (pmacro_vttgen_ctrl_1 & 0xFFFF03FF) | ((dst_timing->vtt_vdda_ctrl_2 & 0x3F) << 10), delay);
}
} else {
CcfifoWrite(EMC_PMACRO_VTTGEN_CTRL_1, (pmacro_vttgen_ctrl_1 & 0xFFFF03FF) | ((dst_timing->vtt_vdda_ctrl_0 & 0x3F) << 10), 0);
}
}
}
u32 DvfsPowerRampUp(u32 dst_clock_period, bool flip_backward, EmcDvfsTimingTable *src_timing, EmcDvfsTimingTable *dst_timing, u32 training) {
uint32_t misc_cfg_1 = flip_backward ? src_timing->misc_cfg_1 : dst_timing->misc_cfg_1;
uint32_t emc_pmacro_cmd_pad_tx_ctrl, emc_pmacro_brick_ctrl_rfu1, emc_fbio_cfg5;
if (flip_backward) {
emc_pmacro_cmd_pad_tx_ctrl = src_timing->burst_regs.emc_pmacro_cmd_pad_tx_ctrl;
emc_pmacro_brick_ctrl_rfu1 = src_timing->burst_regs.emc_pmacro_brick_ctrl_rfu1;
emc_fbio_cfg5 = src_timing->burst_regs.emc_fbio_cfg5;
} else if (training & (CA_TRAINING | CA_VREF_TRAINING)) {
emc_pmacro_cmd_pad_tx_ctrl = dst_timing->shadow_regs_ca_train.emc_pmacro_cmd_pad_tx_ctrl;
emc_pmacro_brick_ctrl_rfu1 = dst_timing->shadow_regs_ca_train.emc_pmacro_brick_ctrl_rfu1;
emc_fbio_cfg5 = dst_timing->shadow_regs_ca_train.emc_fbio_cfg5;
} else if (training & (WRITE_TRAINING | WRITE_VREF_TRAINING | READ_TRAINING | READ_VREF_TRAINING)) {
emc_pmacro_cmd_pad_tx_ctrl = dst_timing->shadow_regs_rdwr_train.emc_pmacro_cmd_pad_tx_ctrl;
emc_pmacro_brick_ctrl_rfu1 = dst_timing->shadow_regs_rdwr_train.emc_pmacro_brick_ctrl_rfu1;
emc_fbio_cfg5 = dst_timing->shadow_regs_rdwr_train.emc_fbio_cfg5;
} else {
emc_pmacro_cmd_pad_tx_ctrl = dst_timing->burst_regs.emc_pmacro_cmd_pad_tx_ctrl;
emc_pmacro_brick_ctrl_rfu1 = dst_timing->burst_regs.emc_pmacro_brick_ctrl_rfu1;
emc_fbio_cfg5 = dst_timing->burst_regs.emc_fbio_cfg5;
}
bool misc_flag = (misc_cfg_1 & 3) == 3;
uint32_t timescale = 100000 << ((misc_cfg_1 >> 2) & 7);
uint32_t delay = (timescale / dst_clock_period);
if (dst_clock_period < 869 || misc_flag) {
CcfifoWrite(EMC_PMACRO_BRICK_CTRL_RFU1, emc_pmacro_brick_ctrl_rfu1 & 0xFE40FE40, delay + 1);
CcfifoWrite(EMC_PMACRO_BRICK_CTRL_RFU1, emc_pmacro_brick_ctrl_rfu1 & 0xFEEDFEED, delay + 1);
CcfifoWrite(EMC_PMACRO_BRICK_CTRL_RFU1, emc_pmacro_brick_ctrl_rfu1 & 0xFFFFFFFF, delay + 1);
CcfifoWrite(EMC_FBIO_CFG5, emc_fbio_cfg5 & 0xFFFFFEFF, delay + 10);
CcfifoWrite(EMC_PMACRO_CMD_PAD_TX_CTRL, emc_pmacro_cmd_pad_tx_ctrl & 0xFBFFFFFF, 5);
return timescale + 10 * dst_clock_period + 3 * timescale;
} else if (dst_clock_period > 1665) {
CcfifoWrite(EMC_PMACRO_BRICK_CTRL_RFU1, emc_pmacro_brick_ctrl_rfu1 | 0x00000600, 0);
CcfifoWrite(EMC_FBIO_CFG5, emc_fbio_cfg5 & 0xFFFFFEFF, 12);
CcfifoWrite(EMC_PMACRO_CMD_PAD_TX_CTRL, emc_pmacro_cmd_pad_tx_ctrl & 0xFBFFFFFF, 5);
return 12 * dst_clock_period;
} else {
CcfifoWrite(EMC_PMACRO_BRICK_CTRL_RFU1, emc_pmacro_brick_ctrl_rfu1 | 0x06000600, delay + 1);
CcfifoWrite(EMC_FBIO_CFG5, emc_fbio_cfg5 & 0xFFFFFEFF, delay + 10);
CcfifoWrite(EMC_PMACRO_CMD_PAD_TX_CTRL, emc_pmacro_cmd_pad_tx_ctrl & 0xFBFFFFFF, 5);
return timescale + 10 * dst_clock_period;
}
}
void FreqChange(EmcDvfsTimingTable *src_timing, EmcDvfsTimingTable *dst_timing, u32 training, u32 dst_clk_src) {
/* Extract training values */
const bool train_ca = (training & CA_TRAINING);
const bool train_ca_vref = (training & CA_VREF_TRAINING);
//const bool train_quse = (training & QUSE_TRAINING);
//const bool train_quse_vref = (training & QUSE_VREF_TRAINING);
const bool train_wr = (training & WRITE_TRAINING);
const bool train_wr_vref = (training & WRITE_VREF_TRAINING);
const bool train_rd = (training & READ_TRAINING);
const bool train_rd_vref = (training & READ_VREF_TRAINING);
const bool train_second_rank = (training & TRAIN_SECOND_RANK);
const bool train_bit_level = (training & BIT_LEVEL_TRAINING);
/* Check if we should do training. */
const bool training_enabled = (training & (CA_TRAINING | CA_VREF_TRAINING | WRITE_TRAINING | WRITE_VREF_TRAINING | READ_TRAINING | READ_VREF_TRAINING));
uint32_t dst_emc_fbio_cfg7 = dst_timing->emc_fbio_cfg7;
uint32_t dst_misc_cfg_0 = dst_timing->misc_cfg_0;
uint32_t dst_misc_cfg_1 = dst_timing->misc_cfg_1;
uint32_t dst_misc_cfg_2 = dst_timing->misc_cfg_2;
uint32_t src_misc_cfg_0 = src_timing->misc_cfg_0;
uint32_t src_misc_cfg_1 = src_timing->misc_cfg_1;
uint32_t src_t_rp = src_timing->dram_timings.t_rp;
uint32_t src_t_rfc = src_timing->dram_timings.t_rfc;
uint32_t dst_t_pdex = dst_timing->dram_timings.t_pdex;
uint32_t dst_t_fc_lpddr4 = dst_timing->dram_timings.t_fc_lpddr4;
const bool ch0_enable = reg::GetField(dst_emc_fbio_cfg7, EMC_REG_BITS_MASK(FBIO_CFG7_CH0_ENABLE)) == EMC_FBIO_CFG7_CH0_ENABLE_ENABLE;
const bool ch1_enable = reg::GetField(dst_emc_fbio_cfg7, EMC_REG_BITS_MASK(FBIO_CFG7_CH1_ENABLE)) == EMC_FBIO_CFG7_CH1_ENABLE_ENABLE;
g_fsp_for_next_freq = !g_fsp_for_next_freq;
const int dram_type = reg::GetValue(EMC + EMC_FBIO_CFG5, EMC_REG_BITS_MASK(FBIO_CFG5_DRAM_TYPE));
uint32_t src_emc_zcal_wait_cnt = src_timing->burst_regs.emc_zcal_wait_cnt;
bool shared_zq_resistor = (src_emc_zcal_wait_cnt >> 31) & 1;
bool opt_zcal_en_cc = (dst_timing->burst_regs.emc_zcal_interval && !src_timing->burst_regs.emc_zcal_interval) || (dram_type == DRAM_TYPE_LPDDR4);
uint32_t dst_t_fc_lpddr4_hz = 1000 * dst_t_fc_lpddr4;
bool is_lpddr2 = (dram_type == DRAM_TYPE_LPDDR2);
bool is_lpddr3 = is_lpddr2 && ((dst_timing->burst_regs.emc_fbio_cfg5 >> 25) & 1);
uint32_t opt_dll_mode = (dram_type == DRAM_TYPE_DDR4) ? GetDllState(dst_timing) : DLL_OFF;
int dram_dev_num = ((reg::Read(MC + MC_EMEM_ADR_CFG) & 1) + 1);
uint32_t tZQCAL_lpddr4 = dst_timing->tZQCAL_lpddr4;
uint32_t zqcal_before_cc_cutoff = dst_timing->zqcal_before_cc_cutoff;
uint32_t opt_cc_short_zcal = dst_timing->opt_cc_short_zcal;
uint32_t opt_short_zcal = dst_timing->opt_short_zcal;
uint32_t opt_do_sw_qrst = dst_timing->opt_do_sw_qrst;
uint32_t save_restore_clkstop_pd = dst_timing->save_restore_clkstop_pd;
// uint32_t opt_E90 = dst_timing->opt_E90;
uint32_t cya_allow_ref_cc = dst_timing->cya_allow_ref_cc;
uint32_t ref_b4_sref_en = dst_timing->ref_b4_sref_en;
uint32_t cya_issue_pc_ref = dst_timing->cya_issue_pc_ref;
uint32_t src_rate_khz = src_timing->rate_khz;
uint32_t dst_rate_khz = dst_timing->rate_khz;
uint32_t src_clock_period = 1000000000 / src_rate_khz;
uint32_t dst_clock_period = 1000000000 / dst_rate_khz;
uint32_t emc_auto_cal_config = reg::Read(EMC + EMC_AUTO_CAL_CONFIG);
uint32_t adj_dst_t_fc_lpddr4 = (dst_clock_period <= zqcal_before_cc_cutoff) ? dst_t_fc_lpddr4_hz : 0;
uint32_t emc_dbg_o = reg::Read(EMC + EMC_DBG);
uint32_t emc_pin_o = reg::Read(EMC + EMC_PIN);
uint32_t emc_cfg_pipe_clk_o = reg::Read(EMC + EMC_CFG_PIPE_CLK);
uint32_t emc_dbg = emc_dbg_o;
uint32_t emc_cfg = dst_timing->burst_regs.emc_cfg;
uint32_t emc_sel_dpd_ctrl = dst_timing->emc_sel_dpd_ctrl;
uint32_t next_push, next_dq_e_ivref, next_dqs_e_ivref;
/* Step 1:
* Pre DVFS SW sequence.
*/
/* Step 1.1: Disable DLL. */
uint32_t tmp = reg::Read(EMC + EMC_CFG_DIG_DLL);
tmp &= ~(1 << 0);
reg::Write(EMC + EMC_CFG_DIG_DLL, tmp);
/* Calculate 14000 / dst_period. */
uint32_t div_14000_by_dst_period = std::max<u32>(util::DivideUp(14000, dst_clock_period), 10);
/* Request a timing update. */
TimingUpdate(dst_emc_fbio_cfg7);
/* Wait for DLL to be disabled. */
WaitForUpdate(EMC_CFG_DIG_DLL, (1 << 0), false, dst_emc_fbio_cfg7);
/* Step 1.2: Disable AUTOCAL. */
emc_auto_cal_config = (dst_timing->emc_auto_cal_config & 0x7FFFF9FF) | 0x600;
reg::Write(EMC + EMC_AUTO_CAL_CONFIG, emc_auto_cal_config);
reg::Read(EMC + EMC_AUTO_CAL_CONFIG);
/* Step 1.3: Disable other power features. */
emc_dbg = SetShadowBypass(ACTIVE, emc_dbg_o);
reg::Write(EMC + EMC_DBG, emc_dbg);
reg::Write(EMC + EMC_CFG, emc_cfg & 0x0FFFFFFF);
reg::Write(EMC + EMC_SEL_DPD_CTRL, emc_sel_dpd_ctrl & 0xFFFFFEC3);
reg::Write(EMC + EMC_DBG, emc_dbg_o);
/* Skip this if dvfs_with_training is set. */
bool compensate_trimmer_applicable = false;
uint32_t adel = 0;
if (!training_enabled && dst_timing->periodic_training) {
/* Wait for DRAM to get out of power down. */
WaitForUpdate(EMC_EMC_STATUS, dram_dev_num == TWO_RANK ? 0x30 : 0x10, false, dst_emc_fbio_cfg7);
/* Wait for DRAM to get out of self refresh. */
WaitForUpdate(EMC_EMC_STATUS, 0x300, false, dst_emc_fbio_cfg7);
if (dst_timing->periodic_training) {
/* Reset all clock tree values. */
dst_timing->current_dram_clktree_c0d0u0 = dst_timing->trained_dram_clktree_c0d0u0;
dst_timing->current_dram_clktree_c0d0u1 = dst_timing->trained_dram_clktree_c0d0u1;
dst_timing->current_dram_clktree_c0d1u0 = dst_timing->trained_dram_clktree_c0d1u0;
dst_timing->current_dram_clktree_c0d1u1 = dst_timing->trained_dram_clktree_c0d1u1;
dst_timing->current_dram_clktree_c1d0u0 = dst_timing->trained_dram_clktree_c1d0u0;
dst_timing->current_dram_clktree_c1d0u1 = dst_timing->trained_dram_clktree_c1d0u1;
dst_timing->current_dram_clktree_c1d1u0 = dst_timing->trained_dram_clktree_c1d1u0;
dst_timing->current_dram_clktree_c1d1u1 = dst_timing->trained_dram_clktree_c1d1u1;
/* Do DVFS_SEQUENCE. */
adel = PeriodicCompensationHandler(DVFS_SEQUENCE, dram_dev_num, src_timing, dst_timing);
/* Check if we should use compensate trimmer. */
compensate_trimmer_applicable = dst_timing->periodic_training && ((adel * 128 * (dst_rate_khz / 1000)) / 1000000) > dst_timing->tree_margin;
}
}
reg::Write(EMC + EMC_INTSTATUS, (1 << 4));
emc_dbg = SetShadowBypass(ACTIVE, emc_dbg);
reg::Write(EMC + EMC_DBG, emc_dbg);
reg::Write(EMC + EMC_CFG, emc_cfg & 0x0FFFFFFF);
reg::Write(EMC + EMC_SEL_DPD_CTRL, emc_sel_dpd_ctrl & 0xFFFFFEC3);
reg::Write(EMC + EMC_CFG_PIPE_CLK, emc_cfg_pipe_clk_o | (1 << 0));
reg::Write(EMC + EMC_FDPD_CTRL_CMD_NO_RAMP, dst_timing->emc_fdpd_ctrl_cmd_no_ramp & ~(1 << 0));
/* Adjust pllm_misc1 as needed. */
if (dst_timing->pllm_misc1_0_pllm_clamp_ph90) {
reg::ClearBits(CLKRST + CLK_RST_CONTROLLER_PLLM_MISC1, 0x80000000);
}
/* Check if we need to turn on VREF generator. */
if (((!(src_timing->burst_regs.emc_pmacro_data_pad_tx_ctrl &
(1 << 0))) &&
((dst_timing->burst_regs.emc_pmacro_data_pad_tx_ctrl &
(1 << 0)))) ||
((!(src_timing->burst_regs.emc_pmacro_data_pad_tx_ctrl &
(1 << 10))) &&
((dst_timing->burst_regs.emc_pmacro_data_pad_tx_ctrl &
(1 << 10)))))
{
uint32_t pad_tx_ctrl = dst_timing->burst_regs.emc_pmacro_data_pad_tx_ctrl;
uint32_t last_pad_tx_ctrl = src_timing->burst_regs.emc_pmacro_data_pad_tx_ctrl;
next_dqs_e_ivref = pad_tx_ctrl & (1 << 10);
next_dq_e_ivref = pad_tx_ctrl & (1 << 0);
next_push = (last_pad_tx_ctrl & ~(1 << 0) & ~(1 << 10)) | next_dq_e_ivref | next_dqs_e_ivref;
reg::Write(EMC + EMC_PMACRO_DATA_PAD_TX_CTRL, next_push);
reg::Write(EMC + EMC_DBG, emc_dbg_o);
util::WaitMicroSeconds(1);
} else {
reg::Write(EMC + EMC_DBG, emc_dbg_o);
}
/* Check if we need to fixup xm2comppadctrl */
if ((dst_misc_cfg_1 & 0x20) == 0) {
reg::Write(EMC + EMC_DBG, SetShadowBypass(ACTIVE, emc_dbg_o));
uint32_t xm2comppadctrl = reg::Read(EMC + EMC_XM2COMPPADCTRL);
reg::Write(EMC + EMC_XM2COMPPADCTRL, xm2comppadctrl | 0x08000000);
util::WaitMicroSeconds(1);
reg::Write(EMC + EMC_XM2COMPPADCTRL, xm2comppadctrl | 0x18000000);
util::WaitMicroSeconds(1);
reg::Write(EMC + EMC_XM2COMPPADCTRL, xm2comppadctrl | 0x38000000);
util::WaitMicroSeconds(1);
reg::Write(EMC + EMC_DBG, SetShadowBypass(ASSEMBLY, emc_dbg_o));
}
/* Step 2:
* Prelock the DLL.
*/
if (dst_timing->burst_regs.emc_cfg_dig_dll & (1 << 0)) {
reg::Write(EMC + EMC_DBG, SetShadowBypass(ACTIVE, emc_dbg_o));
reg::ClearBits(EMC + EMC_PMACRO_DLL_CFG_1, 0x2000);
reg::Read(EMC + EMC_PMACRO_DLL_CFG_1);
reg::Write(EMC + EMC_DBG, SetShadowBypass(ASSEMBLY, emc_dbg_o));
reg::Read(EMC + EMC_DBG);
DllPrelock(dst_timing, src_timing, training_enabled, dst_clk_src);
} else {
DllDisable(dst_emc_fbio_cfg7);
}
/* Step 3:
* Prepare autocal for the clock change.
*/
/* Disable AUTOCAL. */
emc_auto_cal_config = (dst_timing->emc_auto_cal_config & 0x7FFFF9FF) | 0x600;
reg::Write(EMC + EMC_AUTO_CAL_CONFIG, emc_auto_cal_config);
reg::Write(EMC + EMC_DBG, SetShadowBypass(ACTIVE, emc_dbg_o));
reg::Write(EMC + EMC_AUTO_CAL_CONFIG2, dst_timing->emc_auto_cal_config2);
if (ch0_enable || ch1_enable) {
reg::Write(EMC0 + EMC_AUTO_CAL_CONFIG3, dst_timing->emc_auto_cal_config3);
reg::Write(EMC0 + EMC_AUTO_CAL_CONFIG4, dst_timing->emc_auto_cal_config4);
reg::Write(EMC0 + EMC_AUTO_CAL_CONFIG5, dst_timing->emc_auto_cal_config5);
reg::Write(EMC0 + EMC_AUTO_CAL_CONFIG6, dst_timing->emc_auto_cal_config6);
reg::Write(EMC0 + EMC_AUTO_CAL_CONFIG7, dst_timing->emc_auto_cal_config7);
reg::Write(EMC0 + EMC_AUTO_CAL_CONFIG8, dst_timing->emc_auto_cal_config8);
}
reg::Write(EMC + EMC_DBG, emc_dbg_o);
emc_auto_cal_config = (dst_timing->emc_auto_cal_config & 0x7FFFF9FE) | 0x601;
reg::Write(EMC + EMC_AUTO_CAL_CONFIG, emc_auto_cal_config);
/* Step 4:
* Update EMC_CFG.
*/
reg::ClearBits(EMC + EMC_CFG, 0x10000000);
reg::Write(EMC + EMC_CFG_2, dst_timing->emc_cfg_2);
/* Step 5:
* Prepare reference variables for ZQCAL regs.
*/
//print(SCREEN_LOG_LEVEL_DEBUG, "[MTC]: freq_change - step 5\n");
//mdelay(500);
uint32_t emc_zcal_interval = src_timing->burst_regs.emc_zcal_interval & 0xFF000000;
uint32_t dst_emc_zcal_wait_cnt = dst_timing->burst_regs.emc_zcal_wait_cnt;
uint32_t zq_wait_long, zq_wait_short;
if (dram_type == DRAM_TYPE_LPDDR4) {
zq_wait_long = std::max<u32>(util::DivideUp(1000000, dst_clock_period), 1);
zq_wait_short = std::max<u32>(util::DivideUp(30000, dst_clock_period), 8) + 1;
} else if (is_lpddr2 || is_lpddr3) {
zq_wait_long = std::max<u32>(util::DivideUp(360000, dst_clock_period), dst_timing->min_mrs_wait) + 4;
zq_wait_short = 0;
} else if (dram_type == DRAM_TYPE_DDR4) {
zq_wait_long = std::max<u32>(util::DivideUp(320000, dst_clock_period), 256);
zq_wait_short = 0;
} else {
zq_wait_long = 0;
zq_wait_short = 0;
}
/* Step 6:
* Training code.
*/
{
uint32_t pintemp = reg::Read(EMC + EMC_PIN);
if ((train_ca || train_ca_vref) && (dram_dev_num == TWO_RANK)) {
reg::Write(EMC + EMC_PIN, pintemp | 0x7);
}
}
/* Step 7:
* Program FSP reference registers and send MRWs to new FSPWR.
*/
uint32_t mr13_flip_fspop, mr13_flip_fspwr;
if (!g_fsp_for_next_freq) {
mr13_flip_fspwr = (dst_timing->emc_mrw3 & 0xffffff3f) | 0x80;
mr13_flip_fspop = (dst_timing->emc_mrw3 & 0xffffff3f) | 0x00;
} else {
mr13_flip_fspwr = (dst_timing->emc_mrw3 & 0xffffff3f) | 0x40;
mr13_flip_fspop = (dst_timing->emc_mrw3 & 0xffffff3f) | 0xc0;
}
uint32_t mr13_catr_enable = mr13_flip_fspwr | 1;
if (dram_dev_num == TWO_RANK) {
if (train_ca || train_ca_vref) {
mr13_flip_fspop = (mr13_flip_fspop & 0x3FFFFFFF) | (train_second_rank ? 0x80000000 : 0x40000000);
}
mr13_catr_enable = (mr13_catr_enable & 0x3FFFFFFF) | (train_second_rank ? 0x40000000 : 0x80000000);
}
if (dram_type == DRAM_TYPE_LPDDR4) {
reg::Write(EMC + EMC_MRW3, mr13_flip_fspwr);
reg::Write(EMC + EMC_MRW, dst_timing->emc_mrw);
reg::Write(EMC + EMC_MRW2, dst_timing->emc_mrw2);
}
/* Step 8:
* Program the shadow registers.
*/
/* Set burst registers. */
{
uint32_t pmacro_vttgen_ctrl_1 = reg::Read(EMC + EMC_PMACRO_VTTGEN_CTRL_1);
uint32_t xm2comppadctrl = reg::Read(EMC + EMC_XM2COMPPADCTRL);
for (u32 i = 0; i < dst_timing->num_burst; ++i) {
if (!BurstRegisters[i]) {
continue;
}
const u32 reg_addr = BurstRegisters[i];
uint32_t wval;
if (train_ca || train_ca_vref) {
wval = dst_timing->shadow_regs_ca_train_arr[i];
} else if (train_wr || train_wr_vref || train_rd || train_rd_vref) {
wval = dst_timing->shadow_regs_rdwr_train_arr[i];
} else {
wval = dst_timing->burst_regs_arr[i];
}
/* Adjust the value to write. */
switch (reg_addr) {
case EMC_BASE + EMC_CFG:
wval &= (dram_type == DRAM_TYPE_LPDDR4) ? 0x0FFFFFFF : 0xCFFFFFFF;
break;
case EMC_BASE + EMC_MRS_WAIT_CNT:
if (opt_zcal_en_cc && is_lpddr2 && (opt_cc_short_zcal == 0) && (opt_short_zcal != 0)) {
wval = (wval & 0xFFFFFC00) | (zq_wait_long & 0x3FF);
}
break;
case EMC_BASE + EMC_ZCAL_WAIT_CNT:
if ((opt_short_zcal != 0) && opt_zcal_en_cc && (opt_cc_short_zcal == 0) && (dram_type == DRAM_TYPE_DDR4)) {
wval = (wval & 0xFFFFF800) | (zq_wait_long & 0x7FF);
}
break;
case EMC_BASE + EMC_ZCAL_INTERVAL:
if (opt_zcal_en_cc) {
wval = 0;
}
break;
case EMC_BASE + EMC_PMACRO_BRICK_CTRL_RFU1:
wval &= 0xF800F800;
break;
case EMC_BASE + EMC_PMACRO_CMD_PAD_TX_CTRL:
wval |= 0x04000000;
break;
case EMC_BASE + EMC_PMACRO_AUTOCAL_CFG_COMMON:
wval |= 0x00010000;
break;
case EMC_BASE + EMC_TRAINING_CTRL:
if (train_second_rank) {
wval |= 0x4000;
}
break;
case EMC_BASE + EMC_REFRESH:
case EMC_BASE + EMC_TREFBW:
wval >>= 0;
break;
case EMC_BASE + EMC_XM2COMPPADCTRL:
if ((dst_misc_cfg_1 & 0x20) == 0) {
wval = (wval & 0x00FFFFFF) | (xm2comppadctrl & 0xFF000000);
}
break;
case EMC_BASE + EMC_DLL_CFG_1:
wval = (wval & 0xFFFFDFFF) | (reg::Read(EMC + EMC_PMACRO_DLL_CFG_1) & 0x00002000);
break;
case EMC_BASE + EMC_PMACRO_VTTGEN_CTRL_1:
wval = (wval & 0xFFFF03FF) | (pmacro_vttgen_ctrl_1 & 0xFC00);
break;
case EMC_BASE + EMC_MRW6:
case EMC_BASE + EMC_MRW7:
case EMC_BASE + EMC_MRW8:
case EMC_BASE + EMC_MRW9:
case EMC_BASE + EMC_MRW14:
case EMC_BASE + EMC_MRW15:
case EMC0_BASE + EMC_MRW10:
case EMC0_BASE + EMC_MRW11:
case EMC0_BASE + EMC_MRW12:
case EMC0_BASE + EMC_MRW13:
case EMC1_BASE + EMC_MRW10:
case EMC1_BASE + EMC_MRW11:
case EMC1_BASE + EMC_MRW12:
case EMC1_BASE + EMC_MRW13:
if (dram_type != DRAM_TYPE_LPDDR4) {
continue;
}
break;
}
/* Write the value. */
reg::Write(reg_addr, wval);
}
}
if (dram_type == DRAM_TYPE_LPDDR4) {
/* Use the current timing when training. */
uint32_t mrw_req;
if (training_enabled)
mrw_req = (23 << 16) | (src_timing->run_clocks & (0xFF << 0));
else
mrw_req = (23 << 16) | (dst_timing->run_clocks & (0xFF << 0));
reg::Write(EMC + EMC_MRW, mrw_req);
}
/* Per channel burst registers. */
if (dram_type == DRAM_TYPE_LPDDR4) {
for (u32 i = 0; i < dst_timing->num_burst_per_ch; i++) {
if (!PerChannelBurstRegisters[i]) {
continue;
}
const u32 addr = PerChannelBurstRegisters[i];
const u32 base = addr & ~0xFFF;
/* Filter out channels. */
if ((!ch0_enable && base == EMC0) || (!ch1_enable && base == EMC1)) {
continue;
}
/* Write the value. */
reg::Write(addr, dst_timing->burst_perch_regs_arr[i]);
}
}
/* Vref regs. */
for (u32 i = 0; i < dst_timing->vref_num; i++) {
if (!PerChannelVrefRegisters[i]) {
continue;
}
const u32 addr = PerChannelVrefRegisters[i];
const u32 base = addr & ~0xFFF;
/* Filter out channels. */
if ((!ch0_enable && base == EMC0) || (!ch1_enable && base == EMC1)) {
continue;
}
/* Write the value. */
reg::Write(addr, dst_timing->vref_perch_regs_arr[i]);
}
/* Training regs. */
if (training_enabled) {
for (u32 i = 0; i < dst_timing->training_mod_num; i++) {
if (!PerChannelTrainingModRegisters[i]) {
continue;
}
const u32 addr = PerChannelTrainingModRegisters[i];
const u32 base = addr & ~0xFFF;
/* Filter out channels. */
if ((!ch0_enable && base == EMC0) || (!ch1_enable && base == EMC1)) {
continue;
}
/* Write the value. */
reg::Write(addr, dst_timing->training_mod_regs_arr[i]);
}
}
/* Per channel trimmers. */
for (u32 i = 0; i < dst_timing->num_trim_per_ch; i++) {
if (!PerChannelTrimRegisters[i]) {
continue;
}
const u32 addr = PerChannelTrimRegisters[i];
const u32 base = addr & ~0xFFF;
/* Filter out channels. */
if ((!ch0_enable && base == EMC0) || (!ch1_enable && base == EMC1)) {
continue;
}
uint32_t wval = dst_timing->trim_perch_regs_arr[i];
if (compensate_trimmer_applicable) {
switch (addr) {
case EMC0_BASE + EMC_DATA_BRLSHFT_0:
case EMC1_BASE + EMC_DATA_BRLSHFT_0:
case EMC0_BASE + EMC_DATA_BRLSHFT_1:
case EMC1_BASE + EMC_DATA_BRLSHFT_1:
wval = ApplyPeriodicCompensationTrimmer(dst_timing, addr);
break;
}
}
/* Write the value. */
reg::Write(addr, wval);
}
/* Trimmers. */
for (u32 i = 0; i < dst_timing->num_trim; ++i) {
if (!TrimRegisters[i]) {
continue;
}
const u32 addr = TrimRegisters[i];
u32 wval = dst_timing->trim_regs_arr[i];
if (compensate_trimmer_applicable) {
switch (addr) {
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE0_0:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE0_1:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE0_2:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE1_0:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE1_1:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE1_2:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE2_0:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE2_1:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE2_2:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE3_0:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE3_1:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE3_2:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE4_0:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE4_1:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE4_2:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE5_0:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE5_1:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE5_2:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE6_0:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE6_1:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE6_2:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE7_0:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE7_1:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE7_2:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE0_0:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE0_1:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE0_2:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE1_0:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE1_1:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE1_2:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE2_0:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE2_1:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE2_2:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE3_0:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE3_1:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE3_2:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE4_0:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE4_1:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE4_2:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE5_0:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE5_1:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE5_2:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE6_0:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE6_1:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE6_2:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE7_0:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE7_1:
case EMC_BASE + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE7_2:
wval = ApplyPeriodicCompensationTrimmer(dst_timing, addr);
break;
}
}
/* Write the value. */
reg::Write(addr, wval);
}
if (training_enabled) {
if (train_wr && dst_timing->periodic_training) {
PeriodicCompensationHandler(WRITE_TRAINING_SEQUENCE, dram_dev_num, src_timing, dst_timing);
}
} else {
/* Write burst_mc_regs. */
for (u32 i = 0; i < dst_timing->num_mc_regs; i++) {
reg::Write(BurstMcRegisters[i], dst_timing->burst_mc_regs_arr[i]);
}
/* Registers to be programmed on the faster clock. */
if (dst_timing->rate_khz < src_timing->rate_khz) {
for (u32 i = 0; i < dst_timing->num_up_down; i++) {
reg::Write(LaScaleRegisters[i], dst_timing->la_scale_regs_arr[i]);
}
}
}
if ((dst_misc_cfg_1 & 2) != 0 && (dst_misc_cfg_1 & 1) == 0) {
reg::Write(EMC + EMC_PMACRO_BRICK_CTRL_RFU1, dst_timing->burst_regs.emc_pmacro_brick_ctrl_rfu1);
reg::Write(EMC + EMC_PMACRO_CMD_PAD_TX_CTRL, dst_timing->burst_regs.emc_pmacro_cmd_pad_tx_ctrl);
}
reg::Write(EMC + EMC_CFG_PIPE_CLK, (1 << 0));
reg::Write(EMC + EMC_FDPD_CTRL_CMD_NO_RAMP, dst_timing->emc_fdpd_ctrl_cmd_no_ramp & ~(1 << 0));
/* Step 9:
* LPDDR4 section A.
*/
uint32_t emc_dbg_write_active = emc_dbg_o;
if (dram_type == DRAM_TYPE_LPDDR4) {
reg::Write(EMC + EMC_ZCAL_INTERVAL, emc_zcal_interval);
reg::Write(EMC + EMC_ZCAL_WAIT_CNT, (dst_emc_zcal_wait_cnt & 0xFFFFF800) | 1);
reg::Write(EMC + EMC_DBG, emc_dbg_o | ((1 << 1) | (1 << 30)));
reg::Write(EMC + EMC_ZCAL_INTERVAL, emc_zcal_interval);
reg::Write(EMC + EMC_DBG, emc_dbg_o);
if (training_enabled) {
reg::Write(EMC + EMC_DBG, SetShadowBypass(ACTIVE, emc_dbg_o));
reg::Write(EMC + EMC_PMACRO_AUTOCAL_CFG_COMMON, dst_timing->burst_regs.emc_pmacro_autocal_cfg_common | (1 << 16));
if (train_ca || train_ca_vref) {
reg::Write(EMC + EMC_FBIO_CFG5, src_timing->burst_regs.emc_fbio_cfg5 | (1 << 27));
}
reg::Write(EMC + EMC_DBG, emc_dbg_o);
if (dst_emc_fbio_cfg7 == 0x6) {
CcfifoWrite(EMC_CFG_SYNC, 1, 0);
}
/* Change CFG_SWAP. */
CcfifoWrite(EMC_DBG, ((emc_dbg_o & 0xF3FFFFFF) | 0x4000000), 0);
}
CcfifoWrite(EMC_SELF_REF, 0x101, 0);
if (!(train_ca || train_ca_vref) && dst_clock_period <= zqcal_before_cc_cutoff) {
CcfifoWrite(EMC_MRW3, mr13_flip_fspwr ^ 0x40, 0);
CcfifoWrite(EMC_MRW6, (src_timing->burst_regs.emc_mrw6 & 0x0000C0C0) | (dst_timing->burst_regs.emc_mrw6 & 0xFFFF3F3F), 0);
CcfifoWrite(EMC_MRW14, (src_timing->burst_regs.emc_mrw14 & 0x00003838) | (dst_timing->burst_regs.emc_mrw14 & 0xFFFF0707), 0);
if (dram_dev_num == TWO_RANK) {
CcfifoWrite(EMC_MRW7, (src_timing->burst_regs.emc_mrw7 & 0x0000C0C0) | (dst_timing->burst_regs.emc_mrw7 & 0xFFFF3F3F), 0);
CcfifoWrite(EMC_MRW15, (src_timing->burst_regs.emc_mrw15 & 0x00003838) | (dst_timing->burst_regs.emc_mrw15 & 0xFFFF0707), 0);
}
if (opt_zcal_en_cc) {
if (dram_dev_num == ONE_RANK || shared_zq_resistor) {
CcfifoWrite(EMC_ZQ_CAL, (2 << 30) | (1 << 0), 0);
} else {
CcfifoWrite(EMC_ZQ_CAL, (1 << 0), 0);
}
}
}
if (training_enabled) {
emc_dbg_write_active = (emc_dbg_o & 0xF7FFFFFF) | 0x4000000 | (1 << 30);
CcfifoWrite(EMC_DBG, emc_dbg_write_active, 0);
}
if (train_ca || train_ca_vref) {
CcfifoWrite(EMC_PMACRO_DATA_RX_TERM_MODE, src_timing->burst_regs.emc_pmacro_data_rx_term_mode & 0xFFFFFCCC, 0);
if (dram_dev_num == TWO_RANK && train_second_rank) {
CcfifoWrite(EMC_MRW3, mr13_flip_fspop | 0x8, (1000 * src_t_rp) / src_clock_period);
CcfifoWrite(EMC_MRW3, mr13_catr_enable | 0x8, 0);
} else {
CcfifoWrite(EMC_MRW3, mr13_catr_enable | 0x8, (1000 * src_t_rp) / src_clock_period);
}
CcfifoWrite(EMC_TR_CTRL_0, (dst_timing->emc_tr_ctrl_0 & 0x3F1000) | 0x100012A, 0);
CcfifoWrite(EMC_INTSTATUS, 0, 1000000 / src_clock_period);
} else {
CcfifoWrite(EMC_MRW3, mr13_flip_fspop | 0x8, (1000 * src_t_rp) / src_clock_period);
CcfifoWrite(EMC_INTSTATUS, 0, std::max<u32>(DivideUpFloat(dst_t_fc_lpddr4_hz, src_clock_period), std::max<u32>(DivideUpFloat(14000, src_clock_period), 10)));
}
uint32_t t = 30 + (cya_allow_ref_cc ? ((4000 * src_t_rfc + 1000 * src_t_rp) / src_clock_period) : 0);
CcfifoWrite(EMC_PIN, emc_pin_o & 0xFFFFFFF8, t);
} else {
CcfifoWrite(EMC_SELF_REF, 0x1, 0);
}
uint32_t ref_delay_mult = 1;
if (ref_b4_sref_en) ++ref_delay_mult;
if (cya_allow_ref_cc) ++ref_delay_mult;
if (cya_issue_pc_ref) ++ref_delay_mult;
uint32_t ref_delay = 20 + ref_delay_mult * (((1000 * src_t_rfc) / src_clock_period) + ((1000 * src_t_rp) / src_clock_period));
/* Step 11:
* Ramp down.
*/
CcfifoWrite(EMC_CFG_SYNC, 1, (dram_type == DRAM_TYPE_LPDDR4) ? 0 : ref_delay);
bool do_ramp_up = (dst_misc_cfg_1 & 2) == 0 || (dst_misc_cfg_1 & 1) != 0;
if (!do_ramp_up) {
CcfifoWrite(EMC_FBIO_CFG5, reg::Read(EMC + EMC_FBIO_CFG5) & 0xF7FFFFFF, 12);
}
CcfifoWrite(EMC_DBG, SetShadowBypass(ACTIVE, emc_dbg_write_active & 0xBFFFFFFF), 0);
if ((dst_misc_cfg_2 & 0x10) == 0) {
DvfsPowerRampDown(src_timing, dst_timing, false, 0);
}
CcfifoWrite(EMC_DBG, SetShadowBypass(ACTIVE, emc_dbg_write_active | 0x40000000), 0);
uint32_t ramp_down_wait = 0;
if (do_ramp_up) {
CcfifoWrite(EMC_PMACRO_CMD_PAD_TX_CTRL, src_timing->burst_regs.emc_pmacro_cmd_pad_tx_ctrl | (1 << 26), 0);
CcfifoWrite(EMC_FBIO_CFG5, src_timing->burst_regs.emc_fbio_cfg5 | 0x100, 12);
bool misc_flag = (dst_misc_cfg_1 & 3) == 3;
uint32_t timescale = (100000 << ((dst_misc_cfg_1 >> 2) & 7));
uint32_t delay = (timescale / src_clock_period);
if (src_rate_khz > 1150747 || misc_flag) {
CcfifoWrite(EMC_PMACRO_BRICK_CTRL_RFU1, src_timing->burst_regs.emc_pmacro_brick_ctrl_rfu1 & 0xFEEDFEED, delay + 1);
CcfifoWrite(EMC_PMACRO_BRICK_CTRL_RFU1, src_timing->burst_regs.emc_pmacro_brick_ctrl_rfu1 & 0xFE40FE40, delay + 1);
CcfifoWrite(EMC_PMACRO_BRICK_CTRL_RFU1, src_timing->burst_regs.emc_pmacro_brick_ctrl_rfu1 & 0xF800F800, delay + 1);
ramp_down_wait = 3 * timescale + 12 * src_clock_period;
} else {
CcfifoWrite(EMC_PMACRO_BRICK_CTRL_RFU1, src_timing->burst_regs.emc_pmacro_brick_ctrl_rfu1 & 0xF800F800, delay + 20);
ramp_down_wait = timescale + 32 * src_clock_period;
}
if (src_rate_khz > 600240 || misc_flag) {
CcfifoWrite(EMC_INTSTATUS, 0, delay + 1);
ramp_down_wait += 2 * timescale;
}
}
/* Step 12:
* Trigger the clock change.
*/
CcfifoWrite(EMC_STALL_THEN_EXE_AFTER_CLKCHANGE, 1, 0);
CcfifoWrite(EMC_INTSTATUS, 0, dst_timing->clkchange_delay);
CcfifoWrite(EMC_DBG, SetShadowBypass(ACTIVE, emc_dbg_write_active & 0xBFFFFFFF), 0);
if ((dst_misc_cfg_2 & 0x10) == 0) {
DvfsPowerRampDown(src_timing, dst_timing, false, 1);
}
if (training_enabled) {
CcfifoWrite(EMC_DBG, SetShadowBypass(ACTIVE, emc_dbg_write_active | 0x40000000), 0);
}
/* Step 13:
* Ramp up.
*/
uint32_t ramp_up_wait = 0;
if (do_ramp_up) {
ramp_up_wait = DvfsPowerRampUp(dst_clock_period, false, src_timing, dst_timing, training);
}
if (ramp_up_wait < 1001000 && src_timing->ramp_wait != dst_timing->ramp_wait) {
CcfifoWrite(EMC_INTSTATUS, 0, 1 + ((1001000 - ramp_up_wait) / dst_clock_period));
}
if (do_ramp_up) {
CcfifoWrite(EMC_DBG, emc_dbg_write_active, 0);
} else {
CcfifoWrite(EMC_FBIO_CFG5, reg::Read(EMC + EMC_FBIO_CFG5), 0);
CcfifoWrite(EMC_DBG, emc_dbg_write_active, 12);
}
/* Step 14:
* Bringup CKE pins.
*/
if (dram_type == DRAM_TYPE_LPDDR4) {
uint32_t pin_val;
if (train_ca || train_ca_vref) {
pin_val = (dst_misc_cfg_0 & 1) ? ((emc_pin_o & 0xFFFCFFF8) | (((dst_misc_cfg_0 >> 1) & 3) << 16)) : emc_pin_o;
pin_val &= 0xFFFFFFF8;
if (dram_dev_num == TWO_RANK) {
if (train_second_rank) {
pin_val |= 5;
} else {
pin_val |= 6;
}
}
} else {
pin_val = (dst_misc_cfg_0 & 1) ? ((emc_pin_o & 0xFFFCFFFF) | (((dst_misc_cfg_0 >> 1) & 3) << 16)) : emc_pin_o;
pin_val &= 0xFFFFFFF8;
if (dram_dev_num == TWO_RANK) {
pin_val |= 7;
} else {
pin_val |= 1;
}
}
CcfifoWrite(EMC_PIN, pin_val, 0);
}
/* Step 15:
* Calculate zqlatch wait time; has dependency on ramping times.
*/
uint32_t dst_t_pdex_hz = 1000 * dst_t_pdex;
uint32_t zq_latch_dvfs_wait_time;
if (dst_clock_period <= zqcal_before_cc_cutoff) {
zq_latch_dvfs_wait_time = (ramp_up_wait + ramp_down_wait) / dst_clock_period;
} else {
zq_latch_dvfs_wait_time = util::DivideUp(dst_t_pdex_hz, dst_clock_period);
}
if (!(train_ca || train_ca_vref) && (dram_type == DRAM_TYPE_LPDDR4) && opt_zcal_en_cc) {
int offset = (int)((tZQCAL_lpddr4 - adj_dst_t_fc_lpddr4) / dst_clock_period) - (int)zq_latch_dvfs_wait_time;
int addl_wait = (int)util::DivideUp(dst_t_pdex_hz, dst_clock_period);
if (dram_dev_num == TWO_RANK) {
if (shared_zq_resistor) {
if (dst_clock_period > zqcal_before_cc_cutoff) {
CcfifoWrite(EMC_ZQ_CAL, (2 << 30) | (1 << 0), std::max<int>(0, addl_wait));
}
CcfifoWrite(EMC_ZQ_CAL, (2 << 30) | (1 << 1), std::max<int>(0, offset + addl_wait));
CcfifoWrite(EMC_ZQ_CAL, (1 << 30) | (1 << 0), 0);
if (!training_enabled) {
CcfifoWrite(EMC_MRW3, (mr13_flip_fspop & 0xFFFFFFF7) | 0xC000000 | (dst_misc_cfg_2 & 8), 0);
CcfifoWrite(EMC_SELF_REF, 0, 0);
CcfifoWrite(EMC_REF, 0, 0);
}
CcfifoWrite(EMC_ZQ_CAL, (1 << 30) | (1 << 1), zq_wait_short + div_14000_by_dst_period + (tZQCAL_lpddr4 / dst_clock_period));
} else {
if (dst_clock_period > zqcal_before_cc_cutoff) {
CcfifoWrite(EMC_ZQ_CAL, (0 << 30) | (1 << 0), std::max<int>(0, addl_wait));
}
if (!training_enabled) {
CcfifoWrite(EMC_MRW3, (mr13_flip_fspop & 0xFFFFFFF7) | 0xC000000 | (dst_misc_cfg_2 & 8), std::max<int>(0, addl_wait));
CcfifoWrite(EMC_SELF_REF, 0, 0);
CcfifoWrite(EMC_REF, 0, 0);
}
CcfifoWrite(EMC_ZQ_CAL, (0 << 30) | (1 << 1), div_14000_by_dst_period + std::max<int>(0, offset));
}
} else {
if (dst_clock_period > zqcal_before_cc_cutoff) {
CcfifoWrite(EMC_ZQ_CAL, (2 << 30) | (1 << 0), std::max<int>(0, addl_wait));
}
if (!training_enabled) {
CcfifoWrite(EMC_MRW3, (mr13_flip_fspop & 0xFFFFFFF7) | 0xC000000 | (dst_misc_cfg_2 & 8), std::max<int>(0, addl_wait));
CcfifoWrite(EMC_SELF_REF, 0, 0);
CcfifoWrite(EMC_REF, 0x80000000, 0);
}
CcfifoWrite(EMC_ZQ_CAL, (2 << 30) | (1 << 1), div_14000_by_dst_period + std::max<int>(0, offset));
}
}
/* WAR: delay for zqlatch */
CcfifoWrite(EMC_INTSTATUS, 0, 10);
/* Step 16:
* LPDDR4 Conditional Training Kickoff.
*/
if (training_enabled && dram_type == DRAM_TYPE_LPDDR4) {
if (opt_do_sw_qrst) {
CcfifoWrite(EMC_ISSUE_QRST, 1, 0);
CcfifoWrite(EMC_ISSUE_QRST, 0, 2);
}
CcfifoWrite(EMC_INTSTATUS, 0, (1020000 / dst_clock_period));
{
uint32_t train_cmd = 0;
if (train_ca) {
train_cmd |= (1 << 1); /* CA */
}
if (train_ca_vref) {
train_cmd |= (1 << 5); /* CA_VREF */
}
if (train_wr) {
train_cmd |= (1 << 3); /* WR */
}
if (train_wr_vref) {
train_cmd |= (1 << 6); /* WR_VREF */
}
if (train_rd) {
train_cmd |= (1 << 2); /* RD */
}
if (train_rd_vref) {
train_cmd |= (1 << 7); /* RD_VREF */
}
train_cmd |= (1 << 31); /* GO */
CcfifoWrite(EMC_TRAINING_CMD, train_cmd, 0);
}
CcfifoWrite(EMC_SWITCH_BACK_CTRL, 1, 0);
if (!(train_ca || train_ca_vref) || train_second_rank) {
CcfifoWrite(EMC_MRW3, mr13_flip_fspop ^ 0xC0, 0);
CcfifoWrite(EMC_INTSTATUS, 0, (1000000 / dst_clock_period));
}
{
uint32_t pin_val = (dst_misc_cfg_0 & 1) ? ((emc_pin_o & 0xFFFCFFFF) | (((dst_misc_cfg_0 >> 1) & 3) << 16)) : emc_pin_o;
CcfifoWrite(EMC_PIN, pin_val & 0xFFFFFFF8, 0);
}
CcfifoWrite(EMC_CFG_SYNC, 1, 0);
if ((src_misc_cfg_1 & 3) != 2) {
CcfifoWrite(EMC_DBG, SetShadowBypass(ACTIVE, emc_dbg_write_active | 0x40000000), 0);
CcfifoWrite(EMC_PMACRO_CMD_PAD_TX_CTRL, dst_timing->burst_regs.emc_pmacro_cmd_pad_tx_ctrl | (1 << 26), 0);
CcfifoWrite(EMC_FBIO_CFG5, dst_timing->burst_regs.emc_fbio_cfg5 | 0x100, 12);
bool misc_flag = (src_misc_cfg_1 & 3) == 3;
uint32_t timescale = (100000 << ((src_misc_cfg_1 >> 2) & 7));
uint32_t delay = (timescale / dst_clock_period);
if (dst_rate_khz > 1150747 || misc_flag) {
CcfifoWrite(EMC_PMACRO_BRICK_CTRL_RFU1, dst_timing->burst_regs.emc_pmacro_brick_ctrl_rfu1 & 0xFEEDFEED, delay + 1);
CcfifoWrite(EMC_PMACRO_BRICK_CTRL_RFU1, dst_timing->burst_regs.emc_pmacro_brick_ctrl_rfu1 & 0xFE40FE40, delay + 1);
CcfifoWrite(EMC_PMACRO_BRICK_CTRL_RFU1, dst_timing->burst_regs.emc_pmacro_brick_ctrl_rfu1 & 0xF800F800, delay + 1);
} else {
CcfifoWrite(EMC_PMACRO_BRICK_CTRL_RFU1, dst_timing->burst_regs.emc_pmacro_brick_ctrl_rfu1 & 0xF800F800, delay + 20);
}
if (dst_rate_khz > 600240 || misc_flag) {
CcfifoWrite(EMC_INTSTATUS, 0, delay + 1);
}
} else {
CcfifoWrite(EMC_FBIO_CFG5, reg::Read(EMC + EMC_FBIO_CFG5) & 0xF7FFFFFF, 12);
CcfifoWrite(EMC_DBG, SetShadowBypass(ACTIVE, emc_dbg_write_active | 0x40000000), 0);
}
CcfifoWrite(EMC_STALL_THEN_EXE_AFTER_CLKCHANGE, 1, 0);
CcfifoWrite(EMC_DBG, SetShadowBypass(ACTIVE, emc_dbg_write_active & 0xBFFFFFFF), 0);
if ((dst_misc_cfg_2 & 0x10) == 0) {
DvfsPowerRampDown(src_timing, dst_timing, true, 1);
}
if ((src_misc_cfg_1 & 3) != 2) {
DvfsPowerRampUp(src_clock_period, true, src_timing, dst_timing, training);
if (ramp_up_wait < 1001000 && src_timing->ramp_wait != dst_timing->ramp_wait) {
CcfifoWrite(EMC_INTSTATUS, 0, 1 + ((1001000 - ramp_up_wait) / dst_clock_period));
}
CcfifoWrite(EMC_DBG, emc_dbg_write_active, 0);
} else {
if (ramp_up_wait < 1001000 && src_timing->ramp_wait != dst_timing->ramp_wait) {
CcfifoWrite(EMC_INTSTATUS, 0, 1 + ((1001000 - ramp_up_wait) / dst_clock_period));
}
CcfifoWrite(EMC_FBIO_CFG5, reg::Read(EMC + EMC_FBIO_CFG5), 0);
CcfifoWrite(EMC_DBG, emc_dbg_write_active, 12);
}
{
uint32_t pin_val = (src_misc_cfg_0 & 1) ? ((emc_pin_o & 0xFFFCFFFF) | (((src_misc_cfg_0 >> 1) & 3) << 16)) : emc_pin_o;
pin_val &= 0xFFFFFFF8;
pin_val |= (dram_dev_num == TWO_RANK) ? 7 : 1;
CcfifoWrite(EMC_PIN, pin_val, 0);
}
if (train_ca || train_ca_vref) {
CcfifoWrite(EMC_TR_CTRL_0, 0x2A, (200000 / src_clock_period));
CcfifoWrite(EMC_TR_CTRL_0, 0x20, (1000000 / src_clock_period));
CcfifoWrite(EMC_MRW3, mr13_catr_enable & 0xFFFFFFFE, 0);
CcfifoWrite(EMC_INTSTATUS, 0, (1000000 / src_clock_period));
CcfifoWrite(EMC_PMACRO_DATA_RX_TERM_MODE, src_timing->burst_regs.emc_pmacro_data_rx_term_mode, 0);
}
CcfifoWrite(EMC_DBG, emc_dbg_o, 0);
if (opt_zcal_en_cc) {
if (shared_zq_resistor) {
CcfifoWrite(EMC_ZQ_CAL, (2 << 30) | (1 << 0), 0);
CcfifoWrite(EMC_ZQ_CAL, (2 << 30) | (1 << 1), 1 + util::DivideUp(1000000, src_clock_period));
if ((!(train_ca || train_ca_vref) || train_second_rank) && dram_dev_num == TWO_RANK) {
CcfifoWrite(EMC_ZQ_CAL, (1 << 30) | (1 << 0), 0);
CcfifoWrite(EMC_ZQ_CAL, (1 << 30) | (1 << 1), 1 + util::DivideUp(1000000, src_clock_period));
}
} else {
CcfifoWrite(EMC_ZQ_CAL, (dram_dev_num == ONE_RANK ? (2 << 30) : (0 << 30)) | (1 << 0), 0);
CcfifoWrite(EMC_ZQ_CAL, (dram_dev_num == ONE_RANK ? (2 << 30) : (0 << 30)) | (1 << 1), 1 + util::DivideUp(1000000, src_clock_period));
}
}
if (!(train_ca || train_ca_vref)) {
CcfifoWrite(EMC_MRW3, ((mr13_flip_fspop & 0xF3FFFFF7) | (dst_misc_cfg_2 & 8)) ^ 0x0C0000C0, 0);
}
CcfifoWrite(EMC_SELF_REF, 0x0, 0);
}
/* Step 17:
* exit self refresh.
*/
if (dram_type != DRAM_TYPE_LPDDR4) {
CcfifoWrite(EMC_SELF_REF, 0, 0);
}
/* Step 18:
* Send MRWs to LPDDR3/DDR3.
*/
if (is_lpddr2) {
CcfifoWrite(EMC_MRW2, dst_timing->emc_mrw2, 0);
CcfifoWrite(EMC_MRW, dst_timing->emc_mrw, 0);
if (is_lpddr3) {
CcfifoWrite(EMC_MRW4, dst_timing->emc_mrw4, 0);
}
} else if (dram_type == DRAM_TYPE_DDR4) {
if (opt_dll_mode) {
CcfifoWrite(EMC_EMRS, dst_timing->emc_emrs & ~(1 << 26), 0);
}
CcfifoWrite(EMC_EMRS2, dst_timing->emc_emrs2 & ~(1 << 26), 0);
CcfifoWrite(EMC_MRS, dst_timing->emc_mrs | (1 << 26), 0);
}
/* Step 19:
* ZQCAL for LPDDR3/DDR3
*/
if (opt_zcal_en_cc) {
if (is_lpddr2) {
uint32_t zq_op = opt_cc_short_zcal ? dst_timing->zq_op_cc_short_zcal : dst_timing->zq_op_cc_long_zcal;
uint32_t zcal_wait_time_ps = opt_cc_short_zcal ? dst_timing->zcal_wait_time_ps_cc_short_zcal : dst_timing->zcal_wait_time_ps_cc_long_zcal;
uint32_t zcal_wait_time_clocks = util::DivideUp(zcal_wait_time_ps, dst_clock_period);
CcfifoWrite(EMC_MRS_WAIT_CNT2, (zcal_wait_time_clocks & 0x3FF) | ((zcal_wait_time_clocks & 0x7FF) << 16), 0);
CcfifoWrite(EMC_MRW, (zq_op | 0x880C0000) - 0x20000, 0);
if (dram_dev_num == TWO_RANK) {
CcfifoWrite(EMC_MRW, zq_op | 0x480A0000, 0);
}
} else if (dram_type == DRAM_TYPE_DDR4) {
CcfifoWrite(EMC_ZQ_CAL, (2 << 30) | (1 << 0) | (opt_cc_short_zcal ? 0 : (1 << 4)), 0);
if (dram_dev_num == TWO_RANK) {
CcfifoWrite(EMC_ZQ_CAL, (1 << 30) | (1 << 0) | (opt_cc_short_zcal ? 0 : (1 << 4)), 0);
}
}
}
/* Step 20:
* Issue ref and optional QRST.
*/
if (training_enabled || dram_type != DRAM_TYPE_LPDDR4) {
CcfifoWrite(EMC_REF, dram_dev_num == ONE_RANK ? 0x80000000 : 0x00000000, 0);
}
if (opt_do_sw_qrst) {
CcfifoWrite(EMC_ISSUE_QRST, 1, 0);
CcfifoWrite(EMC_ISSUE_QRST, 0, 2);
}
/* Step 21:
* Restore ZCAL and ZCAL interval.
*/
if (save_restore_clkstop_pd || opt_zcal_en_cc || (training_enabled && dram_type == DRAM_TYPE_LPDDR4)) {
CcfifoWrite(EMC_DBG, SetShadowBypass(ACTIVE, emc_dbg_o), 0);
if (opt_zcal_en_cc) {
if (training_enabled) {
CcfifoWrite(EMC_ZCAL_INTERVAL, (dst_misc_cfg_2 & 2) ? 0 : src_timing->burst_regs.emc_zcal_interval, 0);
} else if (dram_type != DRAM_TYPE_LPDDR4) {
CcfifoWrite(EMC_ZCAL_INTERVAL, (dst_misc_cfg_2 & 2) ? 0 : dst_timing->burst_regs.emc_zcal_interval, 0);
}
}
if (save_restore_clkstop_pd || (training_enabled && dram_type == DRAM_TYPE_LPDDR4)) {
CcfifoWrite(EMC_CFG, dst_timing->burst_regs.emc_cfg & ~(1 << 28), 0);
}
if (training_enabled && dram_type == DRAM_TYPE_LPDDR4) {
CcfifoWrite(EMC_SEL_DPD_CTRL, src_timing->emc_sel_dpd_ctrl, 0);
}
CcfifoWrite(EMC_DBG, emc_dbg_o, 0);
}
/* Step 22:
* Restore EMC_CFG_PIPE_CLK.
*/
CcfifoWrite(EMC_CFG_PIPE_CLK, emc_cfg_pipe_clk_o, 0);
CcfifoWrite(EMC_INTSTATUS, 0, dst_timing->pipe_clk_delay);
/* Step 23:
* Do clock change.
*/
if (training_enabled) {
uint32_t clk_source_emc;
if (ch0_enable || ch1_enable) {
clk_source_emc = reg::Read(CLKRST + CLK_RST_CONTROLLER_CLK_SOURCE_EMC);
reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_SOURCE_EMC_SAFE, clk_source_emc);
} else {
clk_source_emc = 0;
}
ChangeDllSrc(src_timing, clk_source_emc);
}
{
uint32_t dig_dll = (reg::Read(EMC + EMC_CFG_DIG_DLL) & 0xFFFFFFE4) | 8;
if ((dst_misc_cfg_2 & 1) == 0) {
dig_dll = (dig_dll & 0xFFFFFF3F) | 0x80;
}
reg::Write(EMC + EMC_CFG_DIG_DLL, dig_dll);
reg::Read(EMC + EMC_CFG_DIG_DLL);
}
reg::Read(MC + MC_EMEM_ADR_CFG);
reg::Read(EMC + EMC_INTSTATUS);
if (ch0_enable || ch1_enable) {
reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_SOURCE_EMC, dst_clk_src);
reg::Read(CLKRST + CLK_RST_CONTROLLER_CLK_SOURCE_EMC);
}
if (WaitForUpdate(EMC_INTSTATUS, (1 << 4), true, dst_emc_fbio_cfg7)) {
return;
}
/* Step 24:
* Save training results.
*/
if (training_enabled) {
uint32_t tmp_emem_numdev = reg::Read(MC + MC_EMEM_ADR_CFG) & 1;
uint32_t emc_dbg_tmp = reg::Read(EMC + EMC_DBG);
reg::Write(EMC + EMC_DBG, emc_dbg_tmp | 1); /* Set READ_MUX to ASSEMBLY. */
uint32_t tmp_dram_dev_num = 1 + tmp_emem_numdev;
/* Save CA results. */
if (train_ca) {
dst_timing->trim_perch_regs.emc0_cmd_brlshft_0 = reg::Read(EMC0 + EMC_CMD_BRLSHFT_0);
dst_timing->trim_perch_regs.emc1_cmd_brlshft_1 = reg::Read(EMC1 + EMC_CMD_BRLSHFT_1);
dst_timing->trim_regs.emc_pmacro_ob_ddll_long_dq_rank0_4 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_4);
dst_timing->trim_regs.emc_pmacro_ob_ddll_long_dq_rank0_5 = reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_5);
if (train_bit_level) {
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_cmd0_0 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_CMD0_0);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_cmd0_1 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_CMD0_1);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_cmd0_2 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_CMD0_2);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_cmd1_0 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_CMD1_0);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_cmd1_1 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_CMD1_1);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_cmd1_2 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_CMD1_2);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_cmd2_0 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_CMD2_0);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_cmd2_1 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_CMD2_1);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_cmd2_2 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_CMD2_2);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_cmd3_0 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_CMD3_0);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_cmd3_1 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_CMD3_1);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_cmd3_2 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_CMD3_2);
}
}
/* Save CA_VREF results. */
if (train_ca_vref) {
uint32_t emc0_training_opt_ca_vref = reg::Read(EMC0 + EMC_TRAINING_OPT_CA_VREF);
uint32_t emc1_training_opt_ca_vref = reg::Read(EMC1 + EMC_TRAINING_OPT_CA_VREF);
uint32_t rank_mask = tmp_dram_dev_num == TWO_RANK ? 0x480C0000 : 0xC80C0000;
dst_timing->burst_perch_regs.emc0_mrw10 = (emc0_training_opt_ca_vref & 0xFFFF) | 0x880C0000;
dst_timing->burst_perch_regs.emc1_mrw10 = (emc1_training_opt_ca_vref & 0xFFFF) | 0x880C0000;
dst_timing->burst_perch_regs.emc0_mrw11 = (rank_mask & 0xFFFFFF00) | ((emc0_training_opt_ca_vref >> 16) & 0xFFFF);
dst_timing->burst_perch_regs.emc1_mrw11 = (rank_mask & 0xFFFFFF00) | ((emc1_training_opt_ca_vref >> 16) & 0xFFFF);
}
/* Save RD results. */
if (train_rd) {
dst_timing->trim_regs.emc_pmacro_ib_ddll_long_dqs_rank0_0 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_LONG_DQS_RANK0_0);
dst_timing->trim_regs.emc_pmacro_ib_ddll_long_dqs_rank0_1 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_LONG_DQS_RANK0_1);
dst_timing->trim_regs.emc_pmacro_ib_ddll_long_dqs_rank0_2 = reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_LONG_DQS_RANK0_2);
dst_timing->trim_regs.emc_pmacro_ib_ddll_long_dqs_rank0_3 = reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_LONG_DQS_RANK0_3);
if (tmp_dram_dev_num == TWO_RANK) {
dst_timing->trim_regs.emc_pmacro_ib_ddll_long_dqs_rank1_0 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_LONG_DQS_RANK1_0);
dst_timing->trim_regs.emc_pmacro_ib_ddll_long_dqs_rank1_1 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_LONG_DQS_RANK1_1);
dst_timing->trim_regs.emc_pmacro_ib_ddll_long_dqs_rank1_2 = reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_LONG_DQS_RANK1_2);
dst_timing->trim_regs.emc_pmacro_ib_ddll_long_dqs_rank1_3 = reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_LONG_DQS_RANK1_3);
}
if (train_bit_level) {
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte0_0 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE0_0);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte0_1 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE0_1);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte0_2 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE0_2);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte1_0 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE1_0);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte1_1 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE1_1);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte1_2 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE1_2);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte2_0 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE2_0);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte2_1 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE2_1);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte2_2 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE2_2);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte3_0 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE3_0);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte3_1 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE3_1);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte3_2 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE3_2);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte4_0 = reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE4_0);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte4_1 = reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE4_1);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte4_2 = reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE4_2);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte5_0 = reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE5_0);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte5_1 = reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE5_1);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte5_2 = reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE5_2);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte6_0 = reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE6_0);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte6_1 = reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE6_1);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte6_2 = reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE6_2);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte7_0 = reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE7_0);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte7_1 = reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE7_1);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte7_2 = reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE7_2);
if (tmp_dram_dev_num == TWO_RANK) {
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte0_0 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE0_0);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte0_1 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE0_1);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte0_2 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE0_2);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte1_0 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE1_0);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte1_1 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE1_1);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte1_2 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE1_2);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte2_0 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE2_0);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte2_1 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE2_1);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte2_2 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE2_2);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte3_0 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE3_0);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte3_1 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE3_1);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte3_2 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE3_2);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte4_0 = reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE4_0);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte4_1 = reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE4_1);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte4_2 = reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE4_2);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte5_0 = reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE5_0);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte5_1 = reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE5_1);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte5_2 = reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE5_2);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte6_0 = reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE6_0);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte6_1 = reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE6_1);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte6_2 = reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE6_2);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte7_0 = reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE7_0);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte7_1 = reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE7_1);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte7_2 = reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE7_2);
}
}
/* Save RD_VREF results. */
if (train_rd_vref) {
uint32_t emc_pmacro_ib_vref_dq_0 = reg::Read(EMC0 + EMC_PMACRO_IB_VREF_DQ_0);
uint32_t emc_pmacro_ib_vref_dq_1 = reg::Read(EMC0 + EMC_PMACRO_IB_VREF_DQ_1);
#define GET_SAVE_RESTORE_MOD_REG(n) ((dst_timing->save_restore_mod_regs[n] & 0x80000000) ? (~dst_timing->save_restore_mod_regs[n]) : (dst_timing->save_restore_mod_regs[n]))
uint8_t ib_vref_dq_byte0_icr = ((emc_pmacro_ib_vref_dq_0 >> 0) & 0x7F) + (GET_SAVE_RESTORE_MOD_REG(0) & 0x7F);
uint8_t ib_vref_dq_byte1_icr = ((emc_pmacro_ib_vref_dq_0 >> 8) & 0x7F) + (GET_SAVE_RESTORE_MOD_REG(1) & 0x7F);
uint8_t ib_vref_dq_byte2_icr = ((emc_pmacro_ib_vref_dq_0 >> 16) & 0x7F) + (GET_SAVE_RESTORE_MOD_REG(2) & 0x7F);
uint8_t ib_vref_dq_byte3_icr = ((emc_pmacro_ib_vref_dq_0 >> 24) & 0x7F) + (GET_SAVE_RESTORE_MOD_REG(3) & 0x7F);
uint8_t ib_vref_dq_byte4_icr = ((emc_pmacro_ib_vref_dq_1 >> 0) & 0x7F) + (GET_SAVE_RESTORE_MOD_REG(4) & 0x7F);
uint8_t ib_vref_dq_byte5_icr = ((emc_pmacro_ib_vref_dq_1 >> 8) & 0x7F) + (GET_SAVE_RESTORE_MOD_REG(5) & 0x7F);
uint8_t ib_vref_dq_byte6_icr = ((emc_pmacro_ib_vref_dq_1 >> 16) & 0x7F) + (GET_SAVE_RESTORE_MOD_REG(6) & 0x7F);
uint8_t ib_vref_dq_byte7_icr = ((emc_pmacro_ib_vref_dq_1 >> 24) & 0x7F) + (GET_SAVE_RESTORE_MOD_REG(7) & 0x7F);
dst_timing->trim_regs.emc_pmacro_ib_vref_dq_0 = ((ib_vref_dq_byte0_icr & 0x7F) | (ib_vref_dq_byte1_icr & 0x7F) << 8) | ((ib_vref_dq_byte2_icr & 0x7F) << 16) | ((ib_vref_dq_byte3_icr & 0x7F) << 24);
dst_timing->trim_regs.emc_pmacro_ib_vref_dq_1 = ((ib_vref_dq_byte4_icr & 0x7F) | (ib_vref_dq_byte5_icr & 0x7F) << 8) | ((ib_vref_dq_byte6_icr & 0x7F) << 16) | ((ib_vref_dq_byte7_icr & 0x7F) << 24);
#undef GET_SAVE_RESTORE_MOD_REG
}
}
/* Save WR results. */
if (train_wr) {
dst_timing->trim_perch_regs.emc0_data_brlshft_0 = reg::Read(EMC0 + EMC_DATA_BRLSHFT_0);
dst_timing->trim_perch_regs.emc1_data_brlshft_0 = reg::Read(EMC1 + EMC_DATA_BRLSHFT_0);
if (tmp_dram_dev_num == TWO_RANK) {
dst_timing->trim_perch_regs.emc0_data_brlshft_1 = reg::Read(EMC0 + EMC_DATA_BRLSHFT_1);
dst_timing->trim_perch_regs.emc1_data_brlshft_1 = reg::Read(EMC1 + EMC_DATA_BRLSHFT_1);
}
dst_timing->trim_regs.emc_pmacro_ob_ddll_long_dq_rank0_0 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_0);
dst_timing->trim_regs.emc_pmacro_ob_ddll_long_dq_rank0_1 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_1);
dst_timing->trim_regs.emc_pmacro_ob_ddll_long_dq_rank0_2 = reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_2);
dst_timing->trim_regs.emc_pmacro_ob_ddll_long_dq_rank0_3 = reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_3);
if (tmp_dram_dev_num == TWO_RANK) {
dst_timing->trim_regs.emc_pmacro_ob_ddll_long_dq_rank1_0 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_0);
dst_timing->trim_regs.emc_pmacro_ob_ddll_long_dq_rank1_1 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_1);
dst_timing->trim_regs.emc_pmacro_ob_ddll_long_dq_rank1_2 = reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_2);
dst_timing->trim_regs.emc_pmacro_ob_ddll_long_dq_rank1_3 = reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_3);
}
if (train_bit_level) {
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte0_0 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE0_0);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte0_1 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE0_1);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte0_2 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE0_2);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte1_0 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE1_0);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte1_1 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE1_1);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte1_2 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE1_2);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte2_0 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE2_0);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte2_1 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE2_1);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte2_2 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE2_2);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte3_0 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE3_0);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte3_1 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE3_1);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte3_2 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE3_2);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte4_0 = reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE4_0);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte4_1 = reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE4_1);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte4_2 = reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE4_2);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte5_0 = reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE5_0);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte5_1 = reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE5_1);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte5_2 = reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE5_2);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte6_0 = reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE6_0);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte6_1 = reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE6_1);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte6_2 = reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE6_2);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte7_0 = reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE7_0);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte7_1 = reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE7_1);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte7_2 = reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE7_2);
if (tmp_dram_dev_num == TWO_RANK) {
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte0_0 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE0_0);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte0_1 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE0_1);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte0_2 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE0_2);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte1_0 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE1_0);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte1_1 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE1_1);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte1_2 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE1_2);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte2_0 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE2_0);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte2_1 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE2_1);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte2_2 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE2_2);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte3_0 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE3_0);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte3_1 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE3_1);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte3_2 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE3_2);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte4_0 = reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE4_0);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte4_1 = reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE4_1);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte4_2 = reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE4_2);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte5_0 = reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE5_0);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte5_1 = reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE5_1);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte5_2 = reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE5_2);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte6_0 = reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE6_0);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte6_1 = reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE6_1);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte6_2 = reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE6_2);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte7_0 = reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE7_0);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte7_1 = reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE7_1);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte7_2 = reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE7_2);
}
}
/* Save WR_VREF results. */
if (train_wr_vref) {
uint32_t emc0_training_opt_dq_ob_vref = reg::Read(EMC0 + EMC_TRAINING_OPT_DQ_OB_VREF);
uint32_t emc1_training_opt_dq_ob_vref = reg::Read(EMC1 + EMC_TRAINING_OPT_DQ_OB_VREF);
#define GET_SAVE_RESTORE_MOD_REG(n) ((dst_timing->save_restore_mod_regs[n] & 0x80000000) ? (~dst_timing->save_restore_mod_regs[n]) : (dst_timing->save_restore_mod_regs[n]))
uint8_t mod_reg_8 = GET_SAVE_RESTORE_MOD_REG( 8);
uint8_t mod_reg_9 = GET_SAVE_RESTORE_MOD_REG( 9);
uint8_t mod_reg_10 = GET_SAVE_RESTORE_MOD_REG(10);
uint8_t mod_reg_11 = GET_SAVE_RESTORE_MOD_REG(11);
#undef GET_SAVE_RESTORE_MOD_REG
uint32_t rank_mask = tmp_dram_dev_num == TWO_RANK ? 0x480E0000 : 0xC80E0000;
uint8_t emc0_mrw12_byte0 = (mod_reg_8 + ((emc0_training_opt_dq_ob_vref >> 0) & 0xFF));
uint8_t emc0_mrw12_byte1 = (mod_reg_9 + ((emc0_training_opt_dq_ob_vref >> 8) & 0xFF));
uint8_t emc0_mrw13_byte0 = (mod_reg_8 + ((emc0_training_opt_dq_ob_vref >> 16) & 0xFF));
uint8_t emc0_mrw13_byte1 = (mod_reg_9 + ((emc0_training_opt_dq_ob_vref >> 24) & 0xFF));
uint8_t emc1_mrw12_byte0 = (mod_reg_10 + ((emc1_training_opt_dq_ob_vref >> 0) & 0xFF));
uint8_t emc1_mrw12_byte1 = (mod_reg_11 + ((emc1_training_opt_dq_ob_vref >> 8) & 0xFF));
uint8_t emc1_mrw13_byte0 = (mod_reg_10 + ((emc1_training_opt_dq_ob_vref >> 16) & 0xFF));
uint8_t emc1_mrw13_byte1 = (mod_reg_11 + ((emc1_training_opt_dq_ob_vref >> 24) & 0xFF));
dst_timing->burst_perch_regs.emc0_mrw12 = (emc0_mrw12_byte0 << 0) | (emc0_mrw12_byte1 << 8) | 0x880E0000;
dst_timing->burst_perch_regs.emc1_mrw12 = (emc1_mrw12_byte0 << 0) | (emc1_mrw12_byte1 << 8) | 0x880E0000;
dst_timing->burst_perch_regs.emc1_mrw13 = (emc1_mrw13_byte0 << 0) | (emc1_mrw13_byte1 << 8) | rank_mask;
dst_timing->burst_perch_regs.emc0_mrw13 = (emc0_mrw13_byte0 << 0) | (emc0_mrw13_byte1 << 8) | rank_mask;
}
}
reg::Write(EMC + EMC_DBG, emc_dbg_tmp);
}
/* Step 25:
* Program MC updown registers.
*/
if (dst_timing->rate_khz > src_timing->rate_khz && !training_enabled) {
for (u32 i = 0; i < dst_timing->num_up_down; i++) {
reg::Write(LaScaleRegisters[i], dst_timing->la_scale_regs_arr[i]);
}
/* Request a timing update. */
TimingUpdate(dst_emc_fbio_cfg7);
}
/* Step 26:
* Restore ZCAL registers.
*/
if (dram_type == DRAM_TYPE_LPDDR4 && !training_enabled) {
reg::Write(EMC + EMC_DBG, SetShadowBypass(ACTIVE, emc_dbg_o));
reg::Write(EMC + EMC_ZCAL_WAIT_CNT, dst_timing->burst_regs.emc_zcal_wait_cnt);
reg::Write(EMC + EMC_ZCAL_INTERVAL, (dst_misc_cfg_2 & 2) ? 0 : dst_timing->burst_regs.emc_zcal_interval);
reg::Write(EMC + EMC_DBG, emc_dbg_o);
}
if (dram_type != DRAM_TYPE_LPDDR4 && opt_cc_short_zcal && opt_zcal_en_cc && !opt_short_zcal) {
util::WaitMicroSeconds(2);
if (is_lpddr2) {
reg::Write(EMC + EMC_DBG, SetShadowBypass(ACTIVE, emc_dbg_o));
reg::Write(EMC + EMC_MRS_WAIT_CNT, dst_timing->burst_regs.emc_mrs_wait_cnt);
reg::Write(EMC + EMC_DBG, emc_dbg_o);
} else if (dram_type == DRAM_TYPE_DDR4) {
reg::Write(EMC + EMC_DBG, SetShadowBypass(ACTIVE, emc_dbg_o));
reg::Write(EMC + EMC_ZCAL_WAIT_CNT, dst_timing->burst_regs.emc_zcal_wait_cnt);
reg::Write(EMC + EMC_DBG, emc_dbg_o);
}
}
if (training_enabled) {
if (!src_timing->pllm_misc1_0_pllm_clamp_ph90) {
reg::SetBits(CLKRST + CLK_RST_CONTROLLER_PLLM_MISC1, 0x80000000);
}
} else {
if (!dst_timing->pllm_misc1_0_pllm_clamp_ph90) {
reg::SetBits(CLKRST + CLK_RST_CONTROLLER_PLLM_MISC1, 0x80000000);
}
}
/* Step 27:
* Restore EMC_CFG, FDPD registers.
*/
reg::Write(EMC + EMC_DBG, SetShadowBypass(ACTIVE, emc_dbg_o));
reg::Write(EMC + EMC_CFG, dst_timing->burst_regs.emc_cfg);
reg::Write(EMC + EMC_DBG, emc_dbg_o);
reg::Write(EMC + EMC_FDPD_CTRL_CMD_NO_RAMP, dst_timing->emc_fdpd_ctrl_cmd_no_ramp);
reg::Write(EMC + EMC_SEL_DPD_CTRL, dst_timing->emc_sel_dpd_ctrl);
/* Step 28:
* Training recover.
*/
if (training_enabled && dram_type == DRAM_TYPE_LPDDR4) {
reg::Write(EMC + EMC_DBG, SetShadowBypass(ACTIVE, emc_dbg_o));
reg::Write(EMC + EMC_CFG, dst_timing->burst_regs.emc_cfg);
reg::Write(EMC + EMC_SEL_DPD_CTRL, dst_timing->emc_sel_dpd_ctrl);
reg::Write(EMC + EMC_ZCAL_WAIT_CNT, src_timing->burst_regs.emc_zcal_wait_cnt);
reg::Write(EMC + EMC_ZCAL_INTERVAL, (dst_misc_cfg_2 & 2) ? 0 : dst_timing->burst_regs.emc_zcal_interval);
reg::Write(EMC + EMC_AUTO_CAL_CONFIG2, dst_timing->emc_auto_cal_config2);
if (ch0_enable || ch1_enable) {
reg::Write(EMC0 + EMC_AUTO_CAL_CONFIG3, dst_timing->emc_auto_cal_config3);
reg::Write(EMC0 + EMC_AUTO_CAL_CONFIG4, dst_timing->emc_auto_cal_config4);
reg::Write(EMC0 + EMC_AUTO_CAL_CONFIG5, dst_timing->emc_auto_cal_config5);
reg::Write(EMC0 + EMC_AUTO_CAL_CONFIG6, dst_timing->emc_auto_cal_config6);
reg::Write(EMC0 + EMC_AUTO_CAL_CONFIG7, dst_timing->emc_auto_cal_config7);
reg::Write(EMC0 + EMC_AUTO_CAL_CONFIG8, dst_timing->emc_auto_cal_config8);
}
reg::Write(EMC + EMC_DBG, emc_dbg_o);
reg::Write(EMC + EMC_TR_DVFS, dst_timing->burst_regs.emc_tr_dvfs & ~(1 << 0));
}
/* Step 29:
* Power fix WAR.
*/
reg::Write(EMC + EMC_DBG, SetShadowBypass(ACTIVE, emc_dbg_o));
reg::Write(EMC + EMC_PMACRO_AUTOCAL_CFG_COMMON, dst_timing->burst_regs.emc_pmacro_autocal_cfg_common);
reg::Write(EMC + EMC_DBG, emc_dbg_o);
reg::Write(EMC + EMC_PMACRO_CFG_PM_GLOBAL_0, 0xFF0000);
reg::Write(EMC + EMC_PMACRO_TRAINING_CTRL_0, 0x8);
reg::Write(EMC + EMC_PMACRO_TRAINING_CTRL_1, 0x8);
reg::Write(EMC + EMC_PMACRO_CFG_PM_GLOBAL_0, 0);
reg::Write(EMC + EMC_DBG, SetShadowBypass(ACTIVE, emc_dbg_o));
/* Fixup xm2comppadctrl */
if ((dst_misc_cfg_1 & 0x20) == 0) {
uint32_t xm2comppadctrl = reg::Read(EMC + EMC_XM2COMPPADCTRL);
reg::Write(EMC + EMC_XM2COMPPADCTRL, xm2comppadctrl & 0x1CFFFFFF);
util::WaitMicroSeconds(1);
reg::Write(EMC + EMC_XM2COMPPADCTRL, xm2comppadctrl & 0x0CFFFFFF);
util::WaitMicroSeconds(1);
reg::Write(EMC + EMC_XM2COMPPADCTRL, xm2comppadctrl & 0x04FFFFFF);
util::WaitMicroSeconds(1);
}
reg::SetBits(EMC + EMC_PMACRO_DLL_CFG_1, 0x2000);
reg::Read(EMC + EMC_PMACRO_DLL_CFG_1);
util::WaitMicroSeconds(2);
/* Select EMC DLL clock source. */
{
reg::SetBits(CLKRST + CLK_RST_CONTROLLER_CLK_SOURCE_EMC_DLL, 0xC00);
reg::Read(CLKRST + CLK_RST_CONTROLLER_CLK_SOURCE_EMC_DLL);
}
reg::Write(EMC + EMC_DBG, SetShadowBypass(ASSEMBLY, emc_dbg_o));
reg::Read(EMC + EMC_DBG);
/* Step 30:
* Re-enable autocal.
*/
if (!training_enabled) {
if (dst_timing->burst_regs.emc_cfg_dig_dll & 1) {
uint32_t dig_dll = (reg::Read(EMC + EMC_CFG_DIG_DLL) & 0xFFFFFFE4) | 9;
if ((dst_misc_cfg_2 & 1) == 0) {
dig_dll = (dig_dll & 0xFFFFFF3F) | 0x80;
}
reg::Write(EMC + EMC_CFG_DIG_DLL, dig_dll);
/* Request a timing update. */
TimingUpdate(dst_emc_fbio_cfg7);
}
}
if (!(training_enabled && dram_type == DRAM_TYPE_LPDDR4)) {
reg::Write(EMC + EMC_AUTO_CAL_CONFIG, training_enabled ? src_timing->emc_auto_cal_config : dst_timing->emc_auto_cal_config);
}
if (training_enabled) {
g_fsp_for_next_freq = !g_fsp_for_next_freq;
}
if (src_timing->periodic_training) {
/* Reset all clock tree values. */
src_timing->current_dram_clktree_c0d0u0 = src_timing->trained_dram_clktree_c0d0u0;
src_timing->current_dram_clktree_c0d0u1 = src_timing->trained_dram_clktree_c0d0u1;
src_timing->current_dram_clktree_c0d1u0 = src_timing->trained_dram_clktree_c0d1u0;
src_timing->current_dram_clktree_c0d1u1 = src_timing->trained_dram_clktree_c0d1u1;
src_timing->current_dram_clktree_c1d0u0 = src_timing->trained_dram_clktree_c1d0u0;
src_timing->current_dram_clktree_c1d0u1 = src_timing->trained_dram_clktree_c1d0u1;
src_timing->current_dram_clktree_c1d1u0 = src_timing->trained_dram_clktree_c1d1u0;
src_timing->current_dram_clktree_c1d1u1 = src_timing->trained_dram_clktree_c1d1u1;
}
/* Disable pll. */
PllDisable(dst_clk_src);
}
void CleanupActiveShadowCopy(EmcDvfsTimingTable *src_timing, EmcDvfsTimingTable *dst_timing) {
/* Change CFG_SWAP to ASSEMBLY_ONLY */
uint32_t emc_dbg = reg::Read(EMC + EMC_DBG);
emc_dbg = ((emc_dbg & 0xF3FFFFFF) | 0x8000000);
reg::Write(EMC + EMC_DBG, emc_dbg);
/* Wait for update. */
TimingUpdate(src_timing->emc_fbio_cfg7);
/* Change CFG_SWAP to ACTIVE_ONLY */
emc_dbg = reg::Read(EMC + EMC_DBG);
emc_dbg &= 0xF3FFFFFF;
reg::Write(EMC + EMC_DBG, emc_dbg);
/* Set PMACRO_DLL_CFG_1, preserving MDDLL_SEL_CLK_SRC */
reg::Write(EMC + EMC_PMACRO_DLL_CFG_1, (reg::Read(EMC + EMC_PMACRO_DLL_CFG_1) & 0x00002000) | (src_timing->burst_regs.emc_pmacro_dll_cfg_1 & 0xFFFFDFFF));
/* Update CFG_DIG_DLL */
uint32_t emc_cfg_dig_dll = reg::Read(EMC + EMC_CFG_DIG_DLL);
emc_cfg_dig_dll = (dst_timing->misc_cfg_2 & 1) ? (emc_cfg_dig_dll & 0xFFFFFFFE) : ((emc_cfg_dig_dll & 0xFFFFFF3E) | 0x80);
reg::Write(EMC + EMC_CFG_DIG_DLL, emc_cfg_dig_dll);
/* Wait for update. */
TimingUpdate(src_timing->emc_fbio_cfg7);
/* Disable or enable DLL */
emc_cfg_dig_dll = reg::Read(EMC + EMC_CFG_DIG_DLL);
if (src_timing->burst_regs.emc_cfg_dig_dll & 1) {
emc_cfg_dig_dll |= 0x01;
} else {
emc_cfg_dig_dll &= 0xFFFFFFFE;
}
if ((dst_timing->misc_cfg_2 & 1) == 0) {
emc_cfg_dig_dll = ((emc_cfg_dig_dll & 0xFFFFFF3F) | 0x80);
}
reg::Write(EMC + EMC_CFG_DIG_DLL, emc_cfg_dig_dll);
/* Wait for update. */
TimingUpdate(src_timing->emc_fbio_cfg7);
/* Wait for DLL_LOCK to be set */
WaitForUpdate(EMC_DIG_DLL_STATUS, (1 << 2), true, src_timing->emc_fbio_cfg7);
/* Wait for update. */
TimingUpdate(src_timing->emc_fbio_cfg7);
/* Set AUTO_CAL_CONFIG. */
uint32_t emc_auto_cal_config = reg::Read(EMC + EMC_AUTO_CAL_CONFIG);
emc_auto_cal_config = (dst_timing->misc_cfg_2 & 4) ? (emc_auto_cal_config & 0xDFFFF9FF) : ((emc_auto_cal_config & 0x5FFFF9FF) | 0x80000000);
reg::Write(EMC + EMC_AUTO_CAL_CONFIG, emc_auto_cal_config | 0x20000000);
}
void TrainFreq(EmcDvfsTimingTable *src_timing, EmcDvfsTimingTable *dst_timing, u32 next_clk_src) {
/* Get dram dev num. */
const u32 dram_dev_num = (reg::Read(MC + MC_EMEM_ADR_CFG) & 1) + 1;
/* Write RAM patterns, if first training. */
if (!g_did_first_training) {
const auto * const pattern = GetEmcRamTrainingPattern();
for (u32 i = 0; i < 0x100; ++i) {
reg::Write(EMC + EMC_TRAINING_PATRAM_DQ, pattern[dst_timing->training_pattern].dq[i]);
reg::Write(EMC + EMC_TRAINING_PATRAM_DMI, pattern[dst_timing->training_pattern].dmi[i]);
reg::Write(EMC + EMC_TRAINING_PATRAM_CTRL, 0x80000000 | i);
}
g_did_first_training = true;
}
reg::Write(EMC + EMC_TRAINING_QUSE_CTRL_MISC, (dst_timing->burst_regs.emc_training_read_ctrl_misc & 0xFFFF0000) | 0x00001000);
/* Do training, if we need to. */
const u32 needed_training = dst_timing->needs_training;
if (needed_training && !dst_timing->trained) {
/* Determine what training to do. */
u32 training_params[4];
u32 num_params = 0;
if (needed_training & (CA_TRAINING | CA_VREF_TRAINING)) {
training_params[num_params++] = (needed_training & (CA_TRAINING | CA_VREF_TRAINING | BIT_LEVEL_TRAINING));
if (dram_dev_num == TWO_RANK) {
training_params[num_params++] = (needed_training & (CA_TRAINING | CA_VREF_TRAINING | TRAIN_SECOND_RANK | BIT_LEVEL_TRAINING));
}
}
if (needed_training & (WRITE_TRAINING | WRITE_VREF_TRAINING | READ_TRAINING | READ_VREF_TRAINING)) {
training_params[num_params++] = (needed_training & (WRITE_TRAINING | WRITE_VREF_TRAINING | READ_TRAINING | READ_VREF_TRAINING | BIT_LEVEL_TRAINING));
}
/* Apply all training. */
for (u32 i = 0; i < num_params; ++i) {
FreqChange(src_timing, dst_timing, training_params[i], next_clk_src);
CleanupActiveShadowCopy(src_timing, dst_timing);
}
/* Set tables as trained. */
dst_timing->trained = 1;
}
}
void Dvfs(EmcDvfsTimingTable *dst_timing, EmcDvfsTimingTable *src_timing, bool train) {
/* Get the clock sources/rates. */
u32 clk_src_emc_from = src_timing->clk_src_emc;
u32 clk_src_emc_to = dst_timing->clk_src_emc;
u32 rate_from = src_timing->rate_khz;
u32 rate_to = dst_timing->rate_khz;
/* Get channel enables. */
const bool ch0_enable = reg::GetField(dst_timing->emc_fbio_cfg7, EMC_REG_BITS_MASK(FBIO_CFG7_CH0_ENABLE)) == EMC_FBIO_CFG7_CH0_ENABLE_ENABLE;
const bool ch1_enable = reg::GetField(dst_timing->emc_fbio_cfg7, EMC_REG_BITS_MASK(FBIO_CFG7_CH1_ENABLE)) == EMC_FBIO_CFG7_CH1_ENABLE_ENABLE;
/* Reprogram pll. */
const u32 prev_2x_clk_src = reg::GetField(clk_src_emc_from, CLK_RST_REG_BITS_MASK(CLK_SOURCE_EMC_EMC_2X_CLK_SRC));
const u32 next_2x_clk_src = reg::GetField(clk_src_emc_to, CLK_RST_REG_BITS_MASK(CLK_SOURCE_EMC_EMC_2X_CLK_SRC));
if (next_2x_clk_src != PLLP_OUT0 && next_2x_clk_src != PLLP_UD) {
if (ch0_enable || ch1_enable) {
if (PllReprogram(rate_to, clk_src_emc_to, rate_from, clk_src_emc_from)) {
if (prev_2x_clk_src == PLLMB_UD || prev_2x_clk_src == PLLMB_OUT0) {
g_next_pll = 0;
} else if (prev_2x_clk_src == PLLM_UD || prev_2x_clk_src == PLLM_OUT0) {
g_next_pll = !g_next_pll;
}
clk_src_emc_to = ProgramPllm(rate_to, clk_src_emc_to, clk_src_emc_to, g_next_pll, dst_timing);
} else {
if (next_2x_clk_src == PLLM_UD || next_2x_clk_src == PLLMB_UD) {
if (g_next_pll) {
reg::SetField(clk_src_emc_to, CLK_RST_REG_BITS_VALUE(CLK_SOURCE_EMC_EMC_2X_CLK_SRC, PLLMB_UD));
}
} else if (next_2x_clk_src == PLLM_OUT0 || next_2x_clk_src == PLLMB_OUT0) {
if (g_next_pll) {
reg::SetField(clk_src_emc_to, CLK_RST_REG_BITS_VALUE(CLK_SOURCE_EMC_EMC_2X_CLK_SRC, PLLMB_OUT0));
}
}
}
}
}
if (train) {
TrainFreq(src_timing, dst_timing, clk_src_emc_to);
if (ch0_enable || ch1_enable) {
if (PllReprogram(dst_timing->rate_khz, dst_timing->clk_src_emc, src_timing->rate_khz, src_timing->clk_src_emc)) {
g_next_pll = !g_next_pll;
}
}
} else {
FreqChange(src_timing, dst_timing, 0, clk_src_emc_to);
}
}
}
void DoMemoryTrainingMariko(bool *out_did_training, int index, void *mtc_tables_buffer) {
/* Get timing tables. */
auto *timing = GetEmcDvfsTimingTables(index, mtc_tables_buffer);
auto *src_timing = timing + 0;
auto *dst_timing = timing + 1;
/* Check timing tables. */
if (src_timing->rate_khz != 204000 || dst_timing->rate_khz != 1600000) {
ShowFatalError("EmcDvfsTimingTables seem corrupted %" PRIu32 " %" PRIu32 "?\n", src_timing->rate_khz, dst_timing->rate_khz);
}
/* Check that we should do training. */
if (src_timing->clk_src_emc != reg::Read(CLKRST + CLK_RST_CONTROLLER_CLK_SOURCE_EMC)) {
/* Our clock source isn't what's expected, so presumably training has already been done? */
/* Either way, the safe bet is to skip it. */
*out_did_training = false;
return;
}
/* Train 1600MHz. */
Dvfs(dst_timing, src_timing, true);
/* Switch to 1600MHz. */
Dvfs(dst_timing, src_timing, false);
/* Set ourselves as having done training */
*out_did_training = true;
}
void RestoreMemoryClockRateMariko(void *mtc_tables_buffer) {
/* Get timing tables. */
auto *timing_tables = reinterpret_cast<EmcDvfsTimingTable *>(mtc_tables_buffer);
auto *src_timing = timing_tables + 0;
auto *dst_timing = timing_tables + 1;
/* Check timing tables. */
if (src_timing->rate_khz != 204000 || dst_timing->rate_khz != 1600000) {
ShowFatalError("EmcDvfsTimingTables seem corrupted %" PRIu32 " %" PRIu32 "?\n", src_timing->rate_khz, dst_timing->rate_khz);
}
/* Switch to 204MHz */
Dvfs(src_timing, dst_timing, false);
}
}
| 155,372
|
C++
|
.cpp
| 2,331
| 48.266409
| 255
| 0.51105
|
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,317
|
fusee_mtc_erista.cpp
|
Atmosphere-NX_Atmosphere/fusee/program/source/mtc/fusee_mtc_erista.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 "../fusee_fatal.hpp"
#include "fusee_mtc.hpp"
#include "fusee_mtc_timing_table_erista.hpp"
namespace ams::nxboot {
namespace {
constexpr inline const uintptr_t CLKRST = secmon::MemoryRegionPhysicalDeviceClkRst.GetAddress();
constexpr inline const uintptr_t MC = MC_BASE;
constexpr inline const uintptr_t EMC = EMC_BASE;
constexpr inline const uintptr_t EMC0 = EMC0_BASE;
constexpr inline const uintptr_t EMC1 = EMC1_BASE;
static constinit bool g_next_pll = false;
static constinit bool g_did_first_training = false;
static constinit bool g_fsp_for_next_freq = false;
#include "fusee_mtc_tables_erista.inc"
#include "fusee_mtc_ram_training_pattern.inc"
#define DECLARE_OFFSET_HANDLER(BASE, REG, NAME) REG,
#define DECLARE_REGISTER_HANDLER(BASE, REG, NAME) BASE + REG,
constexpr inline const u16 BurstRegistersOffsets[] = {
FOREACH_BURST_REG(DECLARE_OFFSET_HANDLER)
};
constexpr inline const u32 TrimRegisters[] = {
FOREACH_TRIM_REG(DECLARE_REGISTER_HANDLER)
};
constexpr inline const u32 BurstMcRegisters[] = {
FOREACH_BURST_MC_REG(DECLARE_REGISTER_HANDLER)
};
constexpr inline const u32 LaScaleRegisters[] = {
FOREACH_LA_SCALE_REG(DECLARE_REGISTER_HANDLER)
};
constexpr inline const u32 PerChannelTrimRegisters[] = {
FOREACH_PER_CHANNEL_TRIM_REG(DECLARE_REGISTER_HANDLER)
};
constexpr inline const u32 PerChannelBurstRegisters[] = {
FOREACH_PER_CHANNEL_BURST_REG(DECLARE_REGISTER_HANDLER)
};
constexpr inline const u32 PerChannelVrefRegisters[] = {
FOREACH_PER_CHANNEL_VREF_REG(DECLARE_REGISTER_HANDLER)
};
constexpr inline const u32 PerChannelTrainingModRegisters[] = {
FOREACH_PER_CHANNEL_TRAINING_MOD_REG(DECLARE_REGISTER_HANDLER)
};
using EmcDvfsTimingTable = erista::EmcDvfsTimingTable;
EmcDvfsTimingTable *GetEmcDvfsTimingTables(int index, void *mtc_tables_buffer) {
switch (index) {
case 0:
case 3:
//std::memcpy(mtc_tables_buffer, T210SdevEmcDvfsTableS4gb01, sizeof(T210SdevEmcDvfsTableS4gb01));
return reinterpret_cast<EmcDvfsTimingTable *>(const_cast<u8 *>(T210SdevEmcDvfsTableS4gb01));
case 1:
//std::memcpy(mtc_tables_buffer, T210SdevEmcDvfsTableS6gb01, sizeof(T210SdevEmcDvfsTableS6gb01));
return reinterpret_cast<EmcDvfsTimingTable *>(const_cast<u8 *>(T210SdevEmcDvfsTableS6gb01));
case 2:
//std::memcpy(mtc_tables_buffer, T210SdevEmcDvfsTableH4gb01, sizeof(T210SdevEmcDvfsTableH4gb01));
return reinterpret_cast<EmcDvfsTimingTable *>(const_cast<u8 *>(T210SdevEmcDvfsTableH4gb01));
default:
ShowFatalError("Unknown EmcDvfsTimingTableIndex: %d\n", index);
}
}
bool IsSamePll(u32 next_2x, u32 prev_2x) {
if (next_2x == prev_2x) {
return true;
} else if ((next_2x == PLLM_OUT0 || next_2x == PLLM_UD) && (prev_2x == PLLM_OUT0 || prev_2x == PLLM_UD)) {
return true;
} else {
return false;
}
}
bool PllReprogram(u32 next_rate_khz, u32 next_clk_src, u32 prev_rate_khz, u32 prev_clk_src) {
/* Get current pll/divp value. */
u32 pll_base, pll_p;
switch (reg::GetValue(CLKRST + CLK_RST_CONTROLLER_CLK_SOURCE_EMC, CLK_RST_REG_BITS_MASK(CLK_SOURCE_EMC_EMC_2X_CLK_SRC))) {
case PLLM_UD:
case PLLM_OUT0:
pll_base = reg::Read(CLKRST + CLK_RST_CONTROLLER_PLLM_BASE);
pll_p = reg::GetField(pll_base, CLK_RST_REG_BITS_MASK(PLLM_BASE_PLLM_DIVP));
break;
case PLLMB_UD:
case PLLMB_OUT0:
pll_base = reg::Read(CLKRST + CLK_RST_CONTROLLER_PLLMB_BASE);
pll_p = reg::GetField(pll_base, CLK_RST_REG_BITS_MASK(PLLMB_BASE_PLLMB_DIVP));
break;
default:
pll_base = 0;
pll_p = 0;
}
/* Check pll divp. */
if (pll_p > 5) {
ShowFatalError("Invalid PLL divp: %" PRIu32 "\n", pll_p);
}
/* Get clk src/divisor. */
const u32 next_2x = reg::GetField(next_clk_src, CLK_RST_REG_BITS_MASK(CLK_SOURCE_EMC_EMC_2X_CLK_SRC));
const u32 prev_2x = reg::GetField(prev_clk_src, CLK_RST_REG_BITS_MASK(CLK_SOURCE_EMC_EMC_2X_CLK_SRC));
u32 next_div = reg::GetField(next_clk_src, CLK_RST_REG_BITS_MASK(CLK_SOURCE_EMC_EMC_2X_CLK_DIVISOR));
u32 prev_div = reg::GetField(prev_clk_src, CLK_RST_REG_BITS_MASK(CLK_SOURCE_EMC_EMC_2X_CLK_DIVISOR));
/* Update divisor, if necessary. */
if (next_2x == PLLM_UD || next_2x == PLLMB_UD) {
next_div = 0;
}
if (prev_2x == PLLM_UD || prev_2x == PLLMB_UD) {
prev_div = 0;
}
/* If the pll is different, reprogramming is necessary. */
if (!IsSamePll(next_2x, prev_2x)) {
return true;
}
/* Return whether the ratios are different. */
const float next_freq = next_rate_khz * (1 + (next_div >> 1) + (0.5 * (next_div & 1))) * (pll_p + 1);
const float prev_freq = prev_rate_khz * (1 + (prev_div >> 1) + (0.5 * (prev_div & 1))) * (pll_p + 1);
const float ratio = prev_freq / next_freq;
return ratio > 1.01 || ratio < 0.99;
}
u32 ProgramPllm(u32 next_rate_khz, u32 next_clk_src, bool is_pllmb) {
/* Hardcode values for 1600MHz. */
u32 divn, divm, divp;
if (next_rate_khz == 1600000) {
divn = 0x7D;
divm = 0x03;
divp = 0x00;
} else if (next_rate_khz == 800000) {
divn = 0x7D;
divm = 0x03;
divp = 0x01;
} else {
ShowFatalError("Unexpected ProgramPllm next rate %" PRIu32 "\n", next_rate_khz);
}
const auto next_2x = reg::GetField(next_clk_src, CLK_RST_REG_BITS_MASK(CLK_SOURCE_EMC_EMC_2X_CLK_SRC));
if (is_pllmb) {
/* Set divisors. */
reg::Write(CLKRST + CLK_RST_CONTROLLER_PLLMB_BASE, CLK_RST_REG_BITS_VALUE(PLLMB_BASE_PLLMB_DIVM, divm),
CLK_RST_REG_BITS_VALUE(PLLMB_BASE_PLLMB_DIVN, divn),
CLK_RST_REG_BITS_VALUE(PLLMB_BASE_PLLMB_DIVP, divp));
reg::Read(CLKRST + CLK_RST_CONTROLLER_PLLMB_BASE);
/* Set enable. */
reg::ReadWrite(CLKRST + CLK_RST_CONTROLLER_PLLMB_BASE, CLK_RST_REG_BITS_ENUM(PLLMB_BASE_PLLMB_ENABLE, ENABLE));
/* Adjust next clock source. */
if (next_2x == PLLM_UD) {
reg::SetField(next_clk_src, CLK_RST_REG_BITS_VALUE(CLK_SOURCE_EMC_EMC_2X_CLK_SRC, PLLMB_UD));
} else if (next_2x == PLLM_OUT0) {
reg::SetField(next_clk_src, CLK_RST_REG_BITS_VALUE(CLK_SOURCE_EMC_EMC_2X_CLK_SRC, PLLMB_OUT0));
}
/* Wait for pll to lock. */
while (!reg::HasValue(CLKRST + CLK_RST_CONTROLLER_PLLMB_BASE, CLK_RST_REG_BITS_ENUM(PLLMB_BASE_PLLMB_LOCK, LOCK))) {
/* ... */
}
} else {
/* Set divisors. */
reg::Write(CLKRST + CLK_RST_CONTROLLER_PLLM_BASE, CLK_RST_REG_BITS_VALUE(PLLM_BASE_PLLM_DIVM, divm),
CLK_RST_REG_BITS_VALUE(PLLM_BASE_PLLM_DIVN, divn),
CLK_RST_REG_BITS_VALUE(PLLM_BASE_PLLM_DIVP, divp));
reg::Read(CLKRST + CLK_RST_CONTROLLER_PLLM_BASE);
/* Set LKCDET. */
reg::ReadWrite(CLKRST + CLK_RST_CONTROLLER_PLLM_MISC2, CLK_RST_REG_BITS_ENUM(PLLM_MISC2_PLLM_EN_LCKDET, ENABLE));
/* Set enable. */
reg::ReadWrite(CLKRST + CLK_RST_CONTROLLER_PLLM_BASE, CLK_RST_REG_BITS_ENUM(PLLM_BASE_PLLM_ENABLE, ENABLE));
/* Adjust next clock source. */
if (next_2x == PLLM_UD) {
reg::SetField(next_clk_src, CLK_RST_REG_BITS_VALUE(CLK_SOURCE_EMC_EMC_2X_CLK_SRC, PLLM_UD));
} else if (next_2x == PLLM_OUT0) {
reg::SetField(next_clk_src, CLK_RST_REG_BITS_VALUE(CLK_SOURCE_EMC_EMC_2X_CLK_SRC, PLLM_OUT0));
}
/* Wait for pll to lock. */
while (!reg::HasValue(CLKRST + CLK_RST_CONTROLLER_PLLM_BASE, CLK_RST_REG_BITS_ENUM(PLLM_BASE_PLLM_LOCK, LOCK))) {
/* ... */
}
}
return next_clk_src;
}
u32 GetDllState(EmcDvfsTimingTable *timing) {
return (!(timing->emc_emrs & 0x1)) ? DLL_ON : DLL_OFF;
}
int WaitForUpdate(u32 reg_offset, u32 mask, bool updated, u32 fbio_cfg7) {
constexpr int StatusUpdateTimeout = 1000;
int result = 0;
if (true /* reg::HasValue(fbio_cfg7, EMC_REG_BITS_ENUM(FBIO_CFG7_CH0_ENABLE, ENABLE)) */) {
bool success = false;
for (int i = 0; i < StatusUpdateTimeout; ++i) {
if (((reg::Read(EMC + reg_offset) & mask) != 0) == updated) {
success = true;
break;
}
util::WaitMicroSeconds(1);
}
result |= success ? 0 : 4;
}
if (reg::GetField(fbio_cfg7, EMC_REG_BITS_MASK(FBIO_CFG7_CH1_ENABLE)) == EMC_FBIO_CFG7_CH1_ENABLE_ENABLE) {
bool success = false;
for (int i = 0; i < StatusUpdateTimeout; ++i) {
if (((reg::Read(EMC1 + reg_offset) & mask) != 0) == updated) {
success = true;
break;
}
util::WaitMicroSeconds(1);
}
result |= success ? 0 : 4;
}
return result;
}
void TimingUpdate(u32 fbio_cfg7) {
/* Trigger the timing update event. */
reg::Write(EMC + EMC_TIMING_CONTROL, 1);
/* Wait for the update to finish. */
WaitForUpdate(EMC_EMC_STATUS, 0x800000, false, fbio_cfg7);
}
void DllDisable(u32 fbio_cfg7) {
/* Disable dll. */
reg::ClearBits(EMC + EMC_CFG_DIG_DLL, 0x1);
/* Request a timing update event */
TimingUpdate(fbio_cfg7);
/* Wait until CFG_DLL_EN is cleared. */
WaitForUpdate(EMC_CFG_DIG_DLL, 0x1, false, fbio_cfg7);
}
void DllEnableStall(u32 fbio_cfg7) {
/* Enable DLL */
uint32_t emc_cfg_dig_dll = (reg::Read(EMC + EMC_CFG_DIG_DLL) & 0xFFFFFF24) | 0x89;
reg::Write(EMC + EMC_CFG_DIG_DLL, emc_cfg_dig_dll);
/* Request a timing update event */
TimingUpdate(fbio_cfg7);
/* Wait until CFG_DLL_EN is set for EMC */
WaitForUpdate(EMC_CFG_DIG_DLL, 0x1, true, fbio_cfg7);
}
void ChangeDllSrc(EmcDvfsTimingTable *dst_timing, u32 next_clk_src) {
u32 dll_setting = ((next_clk_src & 0xE00000FF) | (dst_timing->dll_clk_src & 0x1FFFFF00)) & 0xFFFFF3FF;
switch (reg::GetField(next_clk_src, CLK_RST_REG_BITS_MASK(CLK_SOURCE_EMC_EMC_2X_CLK_SRC))) {
case PLLMB_UD:
dll_setting |= 0x400; /* PLLM_VCOB */
break;
case PLLM_UD:
dll_setting |= 0x000; /* PLLM_VCOA */
break;
default:
dll_setting |= 0x800; /* EMC_DLL_SWITCH_OUT */
break;
}
reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_SOURCE_EMC_DLL, dll_setting);
reg::Read(CLKRST + CLK_RST_CONTROLLER_CLK_OUT_ENB_X);
util::WaitMicroSeconds(2);
if (dst_timing->clk_out_enb_x_0_clk_enb_emc_dll) {
reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_ENB_X_SET, CLK_RST_REG_BITS_ENUM(CLK_ENB_X_CLK_ENB_EMC_DLL, ENABLE));
} else {
reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_ENB_X_CLR, CLK_RST_REG_BITS_ENUM(CLK_ENB_X_CLK_ENB_EMC_DLL, ENABLE));
}
reg::Read(CLKRST + CLK_RST_CONTROLLER_CLK_OUT_ENB_X);
util::WaitMicroSeconds(2);
}
void SetShadowBypass(u32 val) {
reg::ReadWrite(EMC + EMC_DBG, EMC_REG_BITS_VALUE(DBG_WRITE_MUX, val));
}
u32 DllPrelock(EmcDvfsTimingTable *dst_timing, bool training_enabled, u32 next_clk_src) {
/* Check for dual channel LPDDR4 */
u32 fbio_cfg7 = reg::Read(EMC + EMC_FBIO_CFG7);
uint32_t emc_dig_dll_status = 0;
uint32_t emc_cfg_dig_dll = (reg::Read(EMC1 + EMC_CFG_DIG_DLL) & 0xFFFFF824) | 0x3C8;
/* Update EMC_CFG_DIG_DLL_0 */
reg::Write(EMC + EMC_CFG_DIG_DLL, emc_cfg_dig_dll);
/* Request a timing update event */
TimingUpdate(fbio_cfg7);
/* Wait until CFG_DLL_EN is cleared for EMC */
WaitForUpdate(EMC_CFG_DIG_DLL, 0x1, false, fbio_cfg7);
reg::Write(EMC + EMC_DLL_CFG_0, dst_timing->burst_regs.emc_dll_cfg_0);
reg::Write(EMC + EMC_DLL_CFG_1, dst_timing->burst_regs.emc_dll_cfg_1);
/* Configure the clock and reset controller for EMC DLL */
ChangeDllSrc(dst_timing, next_clk_src);
/* Enable DLL */
reg::SetBits(EMC + EMC_CFG_DIG_DLL, 0x1);
/* Request a timing update event */
TimingUpdate(fbio_cfg7);
/* Wait until CFG_DLL_EN is set for EMC */
WaitForUpdate(EMC_CFG_DIG_DLL, 0x1, true, fbio_cfg7);
/* Wait until DLL_PRIV_UPDATED or DLL_LOCK have been cleared */
do {
emc_dig_dll_status = reg::Read(EMC + EMC_DIG_DLL_STATUS);
} while ((~emc_dig_dll_status & 0x28000) != 0);
if (training_enabled) {
/* Set WRITE_MUX to ACTIVE */
SetShadowBypass(ACTIVE);
/* Disable DLL */
reg::ClearBits(EMC + EMC_CFG_DIG_DLL, 0x1);
/* Set WRITE_MUX to ASSEMBLY */
SetShadowBypass(ASSEMBLY);
/* Wait until CFG_DLL_EN is cleared for EMC */
WaitForUpdate(EMC_CFG_DIG_DLL, 0x1, false, fbio_cfg7);
}
/* Return the DLL_OUT value */
return (reg::Read(EMC1 + EMC_DIG_DLL_STATUS) & 0x7FF);
}
void CcfifoWrite(u32 addr, u32 data, u32 wait) {
reg::Write(EMC + EMC_CCFIFO_DATA, data);
reg::Write(EMC + EMC_CCFIFO_ADDR, (addr & 0xFFFF) | ((wait & 0x7FFF) << 16) | 0x80000000);
}
u32 ActualOscClocks(u32 in) {
if (in < 0x40) {
return in * 0x10;
} else if (in < 0x80) {
return 0x800;
} else if (in < 0xC0) {
return 0x1000;
} else {
return 0x2000;
}
}
void StartPeriodicCompensation() {
reg::Write(EMC + EMC_MPC, 0x4B);
reg::Read(EMC + EMC_MPC);
}
u32 UpdateClockTreeDelay(EmcDvfsTimingTable *src_timing, EmcDvfsTimingTable *dst_timing, u32 dram_dev_num, u32 fbio_cfg7, int type) {
uint32_t mrr_req = 0, mrr_data = 0;
uint32_t temp0_0 = 0, temp0_1 = 0, temp1_0 = 0, temp1_1 = 0;
int tdel = 0, tmdel = 0, adel = 0;
uint32_t cval;
uint32_t src_timing_rate_mhz = (src_timing->rate_khz / 1000);
uint32_t dst_timing_rate_mhz = (dst_timing->rate_khz / 1000);
bool dvfs_pt1 = (type == DVFS_PT1);
bool training_pt1 = (type == TRAINING_PT1);
bool dvfs_update = (type == DVFS_UPDATE);
bool training_update = (type == TRAINING_UPDATE);
bool periodic_training_update = (type == PERIODIC_TRAINING_UPDATE);
const bool dual_channel = reg::GetField(fbio_cfg7, EMC_REG_BITS_MASK(FBIO_CFG7_CH1_ENABLE)) == EMC_FBIO_CFG7_CH1_ENABLE_ENABLE;
/* Dev0 MSB. */
if (dvfs_pt1 || training_pt1 || periodic_training_update) {
mrr_req = ((2 << 30) | (19 << 16));
reg::Write(EMC + EMC_MRR, mrr_req);
WaitForUpdate(EMC_EMC_STATUS, 0x100000, true, fbio_cfg7);
mrr_data = ((reg::Read(EMC + EMC_MRR) & 0xFFFF) << 0);
temp0_0 = ((mrr_data & 0xff) << 8);
temp0_1 = (mrr_data & 0xff00);
if (dual_channel) {
mrr_data = ((reg::Read(EMC1 + EMC_MRR) & 0xFFFF) << 0);
temp1_0 = ((mrr_data & 0xff) << 8);
temp1_1 = (mrr_data & 0xff00);
}
/* Dev0 LSB. */
mrr_req = ((mrr_req & ~0xFF0000) | (18 << 16));
reg::Write(EMC + EMC_MRR, mrr_req);
WaitForUpdate(EMC_EMC_STATUS, 0x100000, true, fbio_cfg7);
mrr_data = ((reg::Read(EMC + EMC_MRR) & 0xFFFF) << 0);
temp0_0 |= (mrr_data & 0xff);
temp0_1 |= ((mrr_data & 0xff00) >> 8);
if (dual_channel) {
mrr_data = ((reg::Read(EMC1 + EMC_MRR) & 0xFFFF) << 0);
temp1_0 |= (mrr_data & 0xff);
temp1_1 |= ((mrr_data & 0xff00) >> 8);
}
}
cval = ((1000000 * ActualOscClocks(src_timing->run_clocks)) / (src_timing_rate_mhz * 2 * temp0_0));
if (dvfs_pt1 || training_pt1)
__INCREMENT_PTFV(c0d0u0, cval);
else if (dvfs_update)
__AVERAGE_PTFV(c0d0u0);
else if (training_update)
__AVERAGE_WRITE_PTFV(c0d0u0);
else if (periodic_training_update)
__WEIGHTED_UPDATE_PTFV(c0d0u0, cval);
if (dvfs_update || training_update || periodic_training_update) {
tdel = (dst_timing->current_dram_clktree_c0d0u0 - __MOVAVG_AC(dst_timing, c0d0u0));
tmdel = (tdel < 0) ? -1 * tdel : tdel;
adel = tmdel;
if ((tmdel * 128 * dst_timing_rate_mhz / 1000000) > dst_timing->tree_margin)
dst_timing->current_dram_clktree_c0d0u0 = __MOVAVG_AC(dst_timing, c0d0u0);
}
cval = ((1000000 * ActualOscClocks(src_timing->run_clocks)) /
(src_timing_rate_mhz * 2 * temp0_1));
if (dvfs_pt1 || training_pt1)
__INCREMENT_PTFV(c0d0u1, cval);
else if (dvfs_update)
__AVERAGE_PTFV(c0d0u1);
else if (training_update)
__AVERAGE_WRITE_PTFV(c0d0u1);
else if (periodic_training_update)
__WEIGHTED_UPDATE_PTFV(c0d0u1, cval);
if (dvfs_update || training_update || periodic_training_update) {
tdel = dst_timing->current_dram_clktree_c0d0u1 - __MOVAVG_AC(dst_timing, c0d0u1);
tmdel = (tdel < 0) ? -1 * tdel : tdel;
if (tmdel > adel)
adel = tmdel;
if ((tmdel * 128 * dst_timing_rate_mhz / 1000000) > dst_timing->tree_margin)
dst_timing->current_dram_clktree_c0d0u1 = __MOVAVG_AC(dst_timing, c0d0u1);
}
if (dual_channel) {
cval = ((1000000 * ActualOscClocks(src_timing->run_clocks)) / (src_timing_rate_mhz * 2 * temp1_0));
if (dvfs_pt1 || training_pt1)
__INCREMENT_PTFV(c1d0u0, cval);
else if (dvfs_update)
__AVERAGE_PTFV(c1d0u0);
else if (training_update)
__AVERAGE_WRITE_PTFV(c1d0u0);
else if (periodic_training_update)
__WEIGHTED_UPDATE_PTFV(c1d0u0, cval);
if (dvfs_update || training_update || periodic_training_update) {
tdel = dst_timing->current_dram_clktree_c1d0u0 - __MOVAVG_AC(dst_timing, c1d0u0);
tmdel = (tdel < 0) ? -1 * tdel : tdel;
if (tmdel > adel)
adel = tmdel;
if ((tmdel * 128 * dst_timing_rate_mhz / 1000000) > dst_timing->tree_margin)
dst_timing->current_dram_clktree_c1d0u0 = __MOVAVG_AC(dst_timing, c1d0u0);
}
cval = ((1000000 * ActualOscClocks(src_timing->run_clocks)) / (src_timing_rate_mhz * 2 * temp1_1));
if (dvfs_pt1 || training_pt1)
__INCREMENT_PTFV(c1d0u1, cval);
else if (dvfs_update)
__AVERAGE_PTFV(c1d0u1);
else if (training_update)
__AVERAGE_WRITE_PTFV(c1d0u1);
else if (periodic_training_update)
__WEIGHTED_UPDATE_PTFV(c1d0u1, cval);
if (dvfs_update || training_update || periodic_training_update) {
tdel = dst_timing->current_dram_clktree_c1d0u1 - __MOVAVG_AC(dst_timing, c1d0u1);
tmdel = (tdel < 0) ? -1 * tdel : tdel;
if (tmdel > adel)
adel = tmdel;
if ((tmdel * 128 * dst_timing_rate_mhz / 1000000) > dst_timing->tree_margin)
dst_timing->current_dram_clktree_c1d0u1 = __MOVAVG_AC(dst_timing, c1d0u1);
}
}
if (dram_dev_num != TWO_RANK)
return adel;
/* Dev1 MSB. */
if (dvfs_pt1 || training_pt1 || periodic_training_update) {
mrr_req = ((1 << 30) | (19 << 16));
reg::Write(EMC + EMC_MRR, mrr_req);
WaitForUpdate(EMC_EMC_STATUS, 0x100000, true, fbio_cfg7);
mrr_data = ((reg::Read(EMC + EMC_MRR) & 0xFFFF) << 0);
temp0_0 = ((mrr_data & 0xff) << 8);
temp0_1 = (mrr_data & 0xff00);
if (dual_channel) {
mrr_data = ((reg::Read(EMC1 + EMC_MRR) & 0xFFFF) << 0);
temp1_0 = ((mrr_data & 0xff) << 8);
temp1_1 = (mrr_data & 0xff00);
}
/* Dev1 LSB. */
mrr_req = ((mrr_req & ~0xFF0000) | (18 << 16));
reg::Write(EMC + EMC_MRR, mrr_req);
WaitForUpdate(EMC_EMC_STATUS, 0x100000, true, fbio_cfg7);
mrr_data = ((reg::Read(EMC + EMC_MRR) & 0xFFFF) << 0);
temp0_0 |= (mrr_data & 0xff);
temp0_1 |= ((mrr_data & 0xff00) >> 8);
if (dual_channel) {
mrr_data = ((reg::Read(EMC1 + EMC_MRR) & 0xFFFF) << 0);
temp1_0 |= (mrr_data & 0xff);
temp1_1 |= ((mrr_data & 0xff00) >> 8);
}
}
cval = ((1000000 * ActualOscClocks(src_timing->run_clocks)) / (src_timing_rate_mhz * 2 * temp0_0));
if (dvfs_pt1 || training_pt1)
__INCREMENT_PTFV(c0d1u0, cval);
else if (dvfs_update)
__AVERAGE_PTFV(c0d1u0);
else if (training_update)
__AVERAGE_WRITE_PTFV(c0d1u0);
else if (periodic_training_update)
__WEIGHTED_UPDATE_PTFV(c0d1u0, cval);
if (dvfs_update || training_update || periodic_training_update) {
tdel = dst_timing->current_dram_clktree_c0d1u0 - __MOVAVG_AC(dst_timing, c0d1u0);
tmdel = (tdel < 0) ? -1 * tdel : tdel;
if (tmdel > adel)
adel = tmdel;
if ((tmdel * 128 * dst_timing_rate_mhz / 1000000) > dst_timing->tree_margin)
dst_timing->current_dram_clktree_c0d1u0 = __MOVAVG_AC(dst_timing, c0d1u0);
}
cval = ((1000000 * ActualOscClocks(src_timing->run_clocks)) / (src_timing_rate_mhz * 2 * temp0_1));
if (dvfs_pt1 || training_pt1)
__INCREMENT_PTFV(c0d1u1, cval);
else if (dvfs_update)
__AVERAGE_PTFV(c0d1u1);
else if (training_update)
__AVERAGE_WRITE_PTFV(c0d1u1);
else if (periodic_training_update)
__WEIGHTED_UPDATE_PTFV(c0d1u1, cval);
if (dvfs_update || training_update || periodic_training_update) {
tdel = dst_timing->current_dram_clktree_c0d1u1 - __MOVAVG_AC(dst_timing, c0d1u1);
tmdel = (tdel < 0) ? -1 * tdel : tdel;
if (tmdel > adel)
adel = tmdel;
if ((tmdel * 128 * dst_timing_rate_mhz / 1000000) > dst_timing->tree_margin)
dst_timing->current_dram_clktree_c0d1u1 = __MOVAVG_AC(dst_timing, c0d1u1);
}
if (dual_channel) {
cval = ((1000000 * ActualOscClocks(src_timing->run_clocks)) / (src_timing_rate_mhz * 2 * temp1_0));
if (dvfs_pt1 || training_pt1)
__INCREMENT_PTFV(c1d1u0, cval);
else if (dvfs_update)
__AVERAGE_PTFV(c1d1u0);
else if (training_update)
__AVERAGE_WRITE_PTFV(c1d1u0);
else if (periodic_training_update)
__WEIGHTED_UPDATE_PTFV(c1d1u0, cval);
if (dvfs_update || training_update || periodic_training_update) {
tdel = dst_timing->current_dram_clktree_c1d1u0 - __MOVAVG_AC(dst_timing, c1d1u0);
tmdel = (tdel < 0) ? -1 * tdel : tdel;
if (tmdel > adel)
adel = tmdel;
if ((tmdel * 128 * dst_timing_rate_mhz / 1000000) > dst_timing->tree_margin)
dst_timing->current_dram_clktree_c1d1u0 = __MOVAVG_AC(dst_timing, c1d1u0);
}
cval = ((1000000 * ActualOscClocks(src_timing->run_clocks)) / (src_timing_rate_mhz * 2 * temp1_1));
if (dvfs_pt1 || training_pt1)
__INCREMENT_PTFV(c1d1u1, cval);
else if (dvfs_update)
__AVERAGE_PTFV(c1d1u1);
else if (training_update)
__AVERAGE_WRITE_PTFV(c1d1u1);
else if (periodic_training_update)
__WEIGHTED_UPDATE_PTFV(c1d1u1, cval);
if (dvfs_update || training_update || periodic_training_update) {
tdel = dst_timing->current_dram_clktree_c1d1u1 - __MOVAVG_AC(dst_timing, c1d1u1);
tmdel = (tdel < 0) ? -1 * tdel : tdel;
if (tmdel > adel)
adel = tmdel;
if ((tmdel * 128 * dst_timing_rate_mhz / 1000000) > dst_timing->tree_margin)
dst_timing->current_dram_clktree_c1d1u1 = __MOVAVG_AC(dst_timing, c1d1u1);
}
}
if (training_update) {
dst_timing->trained_dram_clktree_c0d0u0 = dst_timing->current_dram_clktree_c0d0u0;
dst_timing->trained_dram_clktree_c0d0u1 = dst_timing->current_dram_clktree_c0d0u1;
dst_timing->trained_dram_clktree_c0d1u0 = dst_timing->current_dram_clktree_c0d1u0;
dst_timing->trained_dram_clktree_c0d1u1 = dst_timing->current_dram_clktree_c0d1u1;
dst_timing->trained_dram_clktree_c1d0u0 = dst_timing->current_dram_clktree_c1d0u0;
dst_timing->trained_dram_clktree_c1d0u1 = dst_timing->current_dram_clktree_c1d0u1;
dst_timing->trained_dram_clktree_c1d1u0 = dst_timing->current_dram_clktree_c1d1u0;
dst_timing->trained_dram_clktree_c1d1u1 = dst_timing->current_dram_clktree_c1d1u1;
}
return adel;
}
u32 PeriodicCompensationHandler(int type, u32 dram_dev_num, u32 fbio_cfg7, EmcDvfsTimingTable *src_timing, EmcDvfsTimingTable *dst_timing) {
#define __COPY_EMA(nt, lt, dev) \
({ __MOVAVG(nt, dev) = __MOVAVG(lt, dev) * \
(nt)->ptfv_dvfs_samples; })
uint32_t adel = 0;
uint32_t samples = dst_timing->ptfv_dvfs_samples;
uint32_t samples_write = dst_timing->ptfv_write_samples;
uint32_t delay = 2 + (1000 * ActualOscClocks(src_timing->run_clocks) / src_timing->rate_khz);
if (!dst_timing->periodic_training)
return 0;
if (type == DVFS_SEQUENCE) {
if (src_timing->periodic_training && (dst_timing->ptfv_config_ctrl & 1)) {
/*
* If the previous frequency was using periodic
* calibration then we can reuse the previous
* frequencies EMA data.
*/
__COPY_EMA(dst_timing, src_timing, c0d0u0);
__COPY_EMA(dst_timing, src_timing, c0d0u1);
__COPY_EMA(dst_timing, src_timing, c1d0u0);
__COPY_EMA(dst_timing, src_timing, c1d0u1);
__COPY_EMA(dst_timing, src_timing, c0d1u0);
__COPY_EMA(dst_timing, src_timing, c0d1u1);
__COPY_EMA(dst_timing, src_timing, c1d1u0);
__COPY_EMA(dst_timing, src_timing, c1d1u1);
} else {
/* Reset the EMA.*/
__MOVAVG(dst_timing, c0d0u0) = 0;
__MOVAVG(dst_timing, c0d0u1) = 0;
__MOVAVG(dst_timing, c1d0u0) = 0;
__MOVAVG(dst_timing, c1d0u1) = 0;
__MOVAVG(dst_timing, c0d1u0) = 0;
__MOVAVG(dst_timing, c0d1u1) = 0;
__MOVAVG(dst_timing, c1d1u0) = 0;
__MOVAVG(dst_timing, c1d1u1) = 0;
for (uint32_t i = 0; i < samples; i++) {
StartPeriodicCompensation();
util::WaitMicroSeconds(delay);
/* Generate next sample of data. */
adel = UpdateClockTreeDelay(src_timing, dst_timing, dram_dev_num, fbio_cfg7, DVFS_PT1);
}
}
adel = UpdateClockTreeDelay(src_timing, dst_timing, dram_dev_num, fbio_cfg7, DVFS_UPDATE);
} else if (type == WRITE_TRAINING_SEQUENCE) {
/* Reset the EMA.*/
__MOVAVG(dst_timing, c0d0u0) = 0;
__MOVAVG(dst_timing, c0d0u1) = 0;
__MOVAVG(dst_timing, c1d0u0) = 0;
__MOVAVG(dst_timing, c1d0u1) = 0;
__MOVAVG(dst_timing, c0d1u0) = 0;
__MOVAVG(dst_timing, c0d1u1) = 0;
__MOVAVG(dst_timing, c1d1u0) = 0;
__MOVAVG(dst_timing, c1d1u1) = 0;
for (uint32_t i = 0; i < samples_write; i++) {
StartPeriodicCompensation();
util::WaitMicroSeconds(delay);
/* Generate next sample of data. */
UpdateClockTreeDelay(src_timing, dst_timing, dram_dev_num, fbio_cfg7, TRAINING_PT1);
}
adel = UpdateClockTreeDelay(src_timing, dst_timing, dram_dev_num, fbio_cfg7, TRAINING_UPDATE);
} else if (type == PERIODIC_TRAINING_SEQUENCE) {
StartPeriodicCompensation();
util::WaitMicroSeconds(delay);
adel = UpdateClockTreeDelay(src_timing, dst_timing, dram_dev_num, fbio_cfg7, PERIODIC_TRAINING_UPDATE);
}
return adel;
}
uint32_t ApplyPeriodicCompensationTrimmer(EmcDvfsTimingTable *dst_timing, uint32_t offset) {
#define TRIM_REG(chan, rank, reg, byte) \
((EMC_PMACRO_OB_DDLL_LONG_DQ_RANK ## rank ## _ ## reg ## \
_OB_DDLL_LONG_DQ_RANK ## rank ## _BYTE ## byte ## _MASK & \
dst_timing->trim_regs.emc_pmacro_ob_ddll_long_dq_rank ## rank ## _ ## reg ) >> \
EMC_PMACRO_OB_DDLL_LONG_DQ_RANK ## rank ## _ ## reg ## \
_OB_DDLL_LONG_DQ_RANK ## rank ## _BYTE ## byte ## _SHIFT) \
+ \
(((EMC_DATA_BRLSHFT_ ## rank ## _RANK ## rank ## _BYTE ## \
byte ## _DATA_BRLSHFT_MASK & \
dst_timing->trim_perch_regs.emc ## chan ## _data_brlshft_ ## rank ) >> \
EMC_DATA_BRLSHFT_ ## rank ## _RANK ## rank ## _BYTE ## \
byte ## _DATA_BRLSHFT_SHIFT) * 64)
#define CALC_TEMP(rank, reg, byte1, byte2, n) \
((adj[n] << EMC_PMACRO_OB_DDLL_LONG_DQ_RANK ## rank ## _ ## \
reg ## _OB_DDLL_LONG_DQ_RANK ## rank ## _BYTE ## byte1 ## _SHIFT) & \
EMC_PMACRO_OB_DDLL_LONG_DQ_RANK ## rank ## _ ## reg ## \
_OB_DDLL_LONG_DQ_RANK ## rank ## _BYTE ## byte1 ## _MASK) \
| \
((adj[n + 1] << EMC_PMACRO_OB_DDLL_LONG_DQ_RANK ## rank ## _ ## \
reg ## _OB_DDLL_LONG_DQ_RANK ## rank ## _BYTE ## byte2 ## _SHIFT) & \
EMC_PMACRO_OB_DDLL_LONG_DQ_RANK ## rank ## _ ## reg ## \
_OB_DDLL_LONG_DQ_RANK ## rank ## _BYTE ## byte2 ## _MASK) \
uint32_t temp = 0;
uint32_t dst_rate_mhz = dst_timing->rate_khz / 1000;
int tree_delta[4] = {0};
u32 tree_delta_taps[4] = {0};
int adj[] = {
static_cast<int>(TRIM_REG(0, 0, 0, 0)),
static_cast<int>(TRIM_REG(0, 0, 0, 1)),
static_cast<int>(TRIM_REG(0, 0, 1, 2)),
static_cast<int>(TRIM_REG(0, 0, 1, 3)),
static_cast<int>(TRIM_REG(1, 0, 2, 4)),
static_cast<int>(TRIM_REG(1, 0, 2, 5)),
static_cast<int>(TRIM_REG(1, 0, 3, 6)),
static_cast<int>(TRIM_REG(1, 0, 3, 7)),
static_cast<int>(TRIM_REG(0, 1, 0, 0)),
static_cast<int>(TRIM_REG(0, 1, 0, 1)),
static_cast<int>(TRIM_REG(0, 1, 1, 2)),
static_cast<int>(TRIM_REG(0, 1, 1, 3)),
static_cast<int>(TRIM_REG(1, 1, 2, 4)),
static_cast<int>(TRIM_REG(1, 1, 2, 5)),
static_cast<int>(TRIM_REG(1, 1, 3, 6)),
static_cast<int>(TRIM_REG(1, 1, 3, 7))
};
switch (offset) {
case EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_0:
case EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_1:
case EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_2:
case EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_3:
case EMC_DATA_BRLSHFT_0:
tree_delta[0] = 128 * (dst_timing->current_dram_clktree_c0d0u0 - dst_timing->trained_dram_clktree_c0d0u0);
tree_delta[1] = 128 * (dst_timing->current_dram_clktree_c0d0u1 - dst_timing->trained_dram_clktree_c0d0u1);
tree_delta[2] = 128 * (dst_timing->current_dram_clktree_c1d0u0 - dst_timing->trained_dram_clktree_c1d0u0);
tree_delta[3] = 128 * (dst_timing->current_dram_clktree_c1d0u1 - dst_timing->trained_dram_clktree_c1d0u1);
tree_delta_taps[0] = (tree_delta[0] * static_cast<int>(dst_rate_mhz)) / 1000000;
tree_delta_taps[1] = (tree_delta[1] * static_cast<int>(dst_rate_mhz)) / 1000000;
tree_delta_taps[2] = (tree_delta[2] * static_cast<int>(dst_rate_mhz)) / 1000000;
tree_delta_taps[3] = (tree_delta[3] * static_cast<int>(dst_rate_mhz)) / 1000000;
for (int i = 0; i < 4; i++) {
if ((tree_delta_taps[i] > dst_timing->tree_margin) || (tree_delta_taps[i] < (-1 * dst_timing->tree_margin))) {
adj[i * 2] = adj[i * 2] + tree_delta_taps[i];
adj[i * 2 + 1] = adj[i * 2 + 1] + tree_delta_taps[i];
}
}
if (offset == EMC_DATA_BRLSHFT_0) {
for (int i = 0; i < 8; i++) {
adj[i] = adj[i] / 64;
}
} else {
for (int i = 0; i < 8; i++) {
adj[i] = adj[i] % 64;
}
}
break;
case EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_0:
case EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_1:
case EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_2:
case EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_3:
case EMC_DATA_BRLSHFT_1:
tree_delta[0] = 128 * (dst_timing->current_dram_clktree_c0d1u0 - dst_timing->trained_dram_clktree_c0d1u0);
tree_delta[1] = 128 * (dst_timing->current_dram_clktree_c0d1u1 - dst_timing->trained_dram_clktree_c0d1u1);
tree_delta[2] = 128 * (dst_timing->current_dram_clktree_c1d1u0 - dst_timing->trained_dram_clktree_c1d1u0);
tree_delta[3] = 128 * (dst_timing->current_dram_clktree_c1d1u1 - dst_timing->trained_dram_clktree_c1d1u1);
tree_delta_taps[0] = (tree_delta[0] * static_cast<int>(dst_rate_mhz)) / 1000000;
tree_delta_taps[1] = (tree_delta[1] * static_cast<int>(dst_rate_mhz)) / 1000000;
tree_delta_taps[2] = (tree_delta[2] * static_cast<int>(dst_rate_mhz)) / 1000000;
tree_delta_taps[3] = (tree_delta[3] * static_cast<int>(dst_rate_mhz)) / 1000000;
for (int i = 0; i < 4; i++) {
if ((tree_delta_taps[i] > dst_timing->tree_margin) || (tree_delta_taps[i] < (-1 * dst_timing->tree_margin))) {
adj[8 + i * 2] = adj[8 + i * 2] + tree_delta_taps[i];
adj[8 + i * 2 + 1] = adj[8 + i * 2 + 1] + tree_delta_taps[i];
}
}
if (offset == EMC_DATA_BRLSHFT_1) {
for (int i = 0; i < 8; i++) {
adj[i + 8] = adj[i + 8] / 64;
}
} else {
for (int i = 0; i < 8; i++) {
adj[i + 8] = adj[i + 8] % 64;
}
}
break;
}
switch (offset) {
case EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_0:
temp = CALC_TEMP(0, 0, 0, 1, 0);
break;
case EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_1:
temp = CALC_TEMP(0, 1, 2, 3, 2);
break;
case EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_2:
temp = CALC_TEMP(0, 2, 4, 5, 4);
break;
case EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_3:
temp = CALC_TEMP(0, 3, 6, 7, 6);
break;
case EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_0:
temp = CALC_TEMP(1, 0, 0, 1, 8);
break;
case EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_1:
temp = CALC_TEMP(1, 1, 2, 3, 10);
break;
case EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_2:
temp = CALC_TEMP(1, 2, 4, 5, 12);
break;
case EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_3:
temp = CALC_TEMP(1, 3, 6, 7, 14);
break;
case EMC_DATA_BRLSHFT_0:
temp = ((adj[0] <<
EMC_DATA_BRLSHFT_0_RANK0_BYTE0_DATA_BRLSHFT_SHIFT) &
EMC_DATA_BRLSHFT_0_RANK0_BYTE0_DATA_BRLSHFT_MASK) |
((adj[1] <<
EMC_DATA_BRLSHFT_0_RANK0_BYTE1_DATA_BRLSHFT_SHIFT) &
EMC_DATA_BRLSHFT_0_RANK0_BYTE1_DATA_BRLSHFT_MASK) |
((adj[2] <<
EMC_DATA_BRLSHFT_0_RANK0_BYTE2_DATA_BRLSHFT_SHIFT) &
EMC_DATA_BRLSHFT_0_RANK0_BYTE2_DATA_BRLSHFT_MASK) |
((adj[3] <<
EMC_DATA_BRLSHFT_0_RANK0_BYTE3_DATA_BRLSHFT_SHIFT) &
EMC_DATA_BRLSHFT_0_RANK0_BYTE3_DATA_BRLSHFT_MASK) |
((adj[4] <<
EMC_DATA_BRLSHFT_0_RANK0_BYTE4_DATA_BRLSHFT_SHIFT) &
EMC_DATA_BRLSHFT_0_RANK0_BYTE4_DATA_BRLSHFT_MASK) |
((adj[5] <<
EMC_DATA_BRLSHFT_0_RANK0_BYTE5_DATA_BRLSHFT_SHIFT) &
EMC_DATA_BRLSHFT_0_RANK0_BYTE5_DATA_BRLSHFT_MASK) |
((adj[6] <<
EMC_DATA_BRLSHFT_0_RANK0_BYTE6_DATA_BRLSHFT_SHIFT) &
EMC_DATA_BRLSHFT_0_RANK0_BYTE6_DATA_BRLSHFT_MASK) |
((adj[7] <<
EMC_DATA_BRLSHFT_0_RANK0_BYTE7_DATA_BRLSHFT_SHIFT) &
EMC_DATA_BRLSHFT_0_RANK0_BYTE7_DATA_BRLSHFT_MASK);
break;
case EMC_DATA_BRLSHFT_1:
temp = ((adj[8] <<
EMC_DATA_BRLSHFT_1_RANK1_BYTE0_DATA_BRLSHFT_SHIFT) &
EMC_DATA_BRLSHFT_1_RANK1_BYTE0_DATA_BRLSHFT_MASK) |
((adj[9] <<
EMC_DATA_BRLSHFT_1_RANK1_BYTE1_DATA_BRLSHFT_SHIFT) &
EMC_DATA_BRLSHFT_1_RANK1_BYTE1_DATA_BRLSHFT_MASK) |
((adj[10] <<
EMC_DATA_BRLSHFT_1_RANK1_BYTE2_DATA_BRLSHFT_SHIFT) &
EMC_DATA_BRLSHFT_1_RANK1_BYTE2_DATA_BRLSHFT_MASK) |
((adj[11] <<
EMC_DATA_BRLSHFT_1_RANK1_BYTE3_DATA_BRLSHFT_SHIFT) &
EMC_DATA_BRLSHFT_1_RANK1_BYTE3_DATA_BRLSHFT_MASK) |
((adj[12] <<
EMC_DATA_BRLSHFT_1_RANK1_BYTE4_DATA_BRLSHFT_SHIFT) &
EMC_DATA_BRLSHFT_1_RANK1_BYTE4_DATA_BRLSHFT_MASK) |
((adj[13] <<
EMC_DATA_BRLSHFT_1_RANK1_BYTE5_DATA_BRLSHFT_SHIFT) &
EMC_DATA_BRLSHFT_1_RANK1_BYTE5_DATA_BRLSHFT_MASK) |
((adj[14] <<
EMC_DATA_BRLSHFT_1_RANK1_BYTE6_DATA_BRLSHFT_SHIFT) &
EMC_DATA_BRLSHFT_1_RANK1_BYTE6_DATA_BRLSHFT_MASK) |
((adj[15] <<
EMC_DATA_BRLSHFT_1_RANK1_BYTE7_DATA_BRLSHFT_SHIFT) &
EMC_DATA_BRLSHFT_1_RANK1_BYTE7_DATA_BRLSHFT_MASK);
break;
default:
break;
}
#undef TRIM_REG
#undef CALC_TEMP
return temp;
}
uint32_t DvfsPowerRampDown(bool flip_backward, EmcDvfsTimingTable *src_timing, EmcDvfsTimingTable *dst_timing, uint32_t clk) {
uint32_t ramp_down_wait = 0;
uint32_t seq_wait = 0;
uint32_t pmacro_cmd_pad = 0;
uint32_t pmacro_dq_pad = 0;
uint32_t pmacro_cfg5 = 0;
uint32_t pmacro_rfu1 = 0;
uint32_t pmacro_common_tx = 0;
if (flip_backward) {
pmacro_cmd_pad = dst_timing->burst_regs.emc_pmacro_cmd_pad_tx_ctrl;
pmacro_dq_pad = dst_timing->burst_regs.emc_pmacro_data_pad_tx_ctrl;
pmacro_rfu1 = dst_timing->burst_regs.emc_pmacro_brick_ctrl_rfu1;
pmacro_cfg5 = dst_timing->burst_regs.emc_fbio_cfg5;
pmacro_common_tx = dst_timing->burst_regs.emc_pmacro_common_pad_tx_ctrl;
} else {
pmacro_cmd_pad = src_timing->burst_regs.emc_pmacro_cmd_pad_tx_ctrl;
pmacro_dq_pad = ((dst_timing->burst_regs.emc_pmacro_data_pad_tx_ctrl & 0x101) | src_timing->burst_regs.emc_pmacro_data_pad_tx_ctrl);
pmacro_rfu1 = src_timing->burst_regs.emc_pmacro_brick_ctrl_rfu1;
pmacro_cfg5 = src_timing->burst_regs.emc_fbio_cfg5;
pmacro_common_tx = src_timing->burst_regs.emc_pmacro_common_pad_tx_ctrl;
}
pmacro_cmd_pad |= (1 << 26);
CcfifoWrite(EMC_PMACRO_CMD_PAD_TX_CTRL, pmacro_cmd_pad, 0);
CcfifoWrite(EMC_FBIO_CFG5, pmacro_cfg5 | (1 << 8), 12);
ramp_down_wait = clk * 12;
seq_wait = (100000 / clk) + 1;
if (clk < (1000000 / 1000)) {
if (clk < (1000000 / 2400)) {
pmacro_cmd_pad &= ~((1 << 1) | (1 << 24));
pmacro_cmd_pad |= (1 << 9) | (1 << 16);
CcfifoWrite(EMC_PMACRO_CMD_PAD_TX_CTRL, pmacro_cmd_pad, seq_wait);
ramp_down_wait += 100000;
pmacro_dq_pad &= ~((1 << 1) | (1 << 24));
pmacro_dq_pad |= (1 << 9) | (1 << 16);
CcfifoWrite(EMC_PMACRO_DATA_PAD_TX_CTRL, pmacro_dq_pad, 0);
CcfifoWrite(EMC_PMACRO_BRICK_CTRL_RFU1, pmacro_rfu1 & ~0x01120112, 0);
} else {
CcfifoWrite(EMC_PMACRO_BRICK_CTRL_RFU1, pmacro_rfu1 & ~0x01120112, seq_wait);
ramp_down_wait += 100000;
}
CcfifoWrite(EMC_PMACRO_BRICK_CTRL_RFU1, pmacro_rfu1 & ~0x01bf01bf, seq_wait);
ramp_down_wait += 100000;
if (clk < (1000000 / 2400)) {
pmacro_cmd_pad &= ~((1 << 1) | (1 << 24) | (1 << 9) | (1 << 16));
CcfifoWrite(EMC_PMACRO_CMD_PAD_TX_CTRL, pmacro_cmd_pad, seq_wait);
ramp_down_wait += 100000;
pmacro_dq_pad &= ~((1 << 1) | (1 << 24) | (1 << 9) | (1 << 16));
CcfifoWrite(EMC_PMACRO_DATA_PAD_TX_CTRL, pmacro_dq_pad, 0);
CcfifoWrite(EMC_PMACRO_BRICK_CTRL_RFU1, pmacro_rfu1 & ~0x07ff07ff, 0);
} else {
CcfifoWrite(EMC_PMACRO_BRICK_CTRL_RFU1, pmacro_rfu1 & ~0x07ff07ff, seq_wait);
ramp_down_wait += 100000;
}
} else {
CcfifoWrite(EMC_PMACRO_BRICK_CTRL_RFU1, pmacro_rfu1 & ~0x07ff07ff, seq_wait + 19);
ramp_down_wait += (100000 + (20 * clk));
}
if (clk < (1000000 / 600)) {
ramp_down_wait += 100000;
CcfifoWrite(EMC_PMACRO_COMMON_PAD_TX_CTRL, pmacro_common_tx & ~0x5, seq_wait);
ramp_down_wait += 100000;
CcfifoWrite(EMC_PMACRO_COMMON_PAD_TX_CTRL, pmacro_common_tx & ~0xf, seq_wait);
ramp_down_wait += 100000;
CcfifoWrite(0, 0, seq_wait);
ramp_down_wait += 100000;
} else {
CcfifoWrite(EMC_PMACRO_COMMON_PAD_TX_CTRL, pmacro_common_tx & ~0xf, seq_wait);
}
return ramp_down_wait;
}
uint32_t DvfsPowerRampUp(bool flip_backward, EmcDvfsTimingTable *src_timing, EmcDvfsTimingTable *dst_timing, uint32_t training, uint32_t clk) {
uint32_t ramp_up_wait = 0;
uint32_t pmacro_cmd_pad = 0;
uint32_t pmacro_dq_pad = 0;
uint32_t pmacro_cfg5 = 0;
uint32_t pmacro_rfu1 = 0;
uint32_t pmacro_common_tx = 0;
if (flip_backward) {
pmacro_cmd_pad = src_timing->burst_regs.emc_pmacro_cmd_pad_tx_ctrl;
pmacro_dq_pad = src_timing->burst_regs.emc_pmacro_data_pad_tx_ctrl;
pmacro_rfu1 = src_timing->burst_regs.emc_pmacro_brick_ctrl_rfu1;
pmacro_cfg5 = src_timing->burst_regs.emc_fbio_cfg5;
pmacro_common_tx = src_timing->burst_regs.emc_pmacro_common_pad_tx_ctrl;
} else if (training & 3) {
pmacro_cmd_pad = dst_timing->shadow_regs_ca_train.emc_pmacro_cmd_pad_tx_ctrl;
pmacro_dq_pad = dst_timing->shadow_regs_ca_train.emc_pmacro_data_pad_tx_ctrl;
pmacro_rfu1 = dst_timing->shadow_regs_ca_train.emc_pmacro_brick_ctrl_rfu1;
pmacro_cfg5 = dst_timing->shadow_regs_ca_train.emc_fbio_cfg5;
pmacro_common_tx = dst_timing->shadow_regs_ca_train.emc_pmacro_common_pad_tx_ctrl;
} else if (training & 0xC) {
pmacro_cmd_pad = dst_timing->shadow_regs_quse_train.emc_pmacro_cmd_pad_tx_ctrl;
pmacro_dq_pad = dst_timing->shadow_regs_quse_train.emc_pmacro_data_pad_tx_ctrl;
pmacro_rfu1 = dst_timing->shadow_regs_quse_train.emc_pmacro_brick_ctrl_rfu1;
pmacro_cfg5 = dst_timing->shadow_regs_quse_train.emc_fbio_cfg5;
pmacro_common_tx = dst_timing->shadow_regs_quse_train.emc_pmacro_common_pad_tx_ctrl;
} else if (training & 0xF0) {
pmacro_cmd_pad = dst_timing->shadow_regs_rdwr_train.emc_pmacro_cmd_pad_tx_ctrl;
pmacro_dq_pad = dst_timing->shadow_regs_rdwr_train.emc_pmacro_data_pad_tx_ctrl;
pmacro_rfu1 = dst_timing->shadow_regs_rdwr_train.emc_pmacro_brick_ctrl_rfu1;
pmacro_cfg5 = dst_timing->shadow_regs_rdwr_train.emc_fbio_cfg5;
pmacro_common_tx = dst_timing->shadow_regs_rdwr_train.emc_pmacro_common_pad_tx_ctrl;
} else {
pmacro_cmd_pad = dst_timing->burst_regs.emc_pmacro_cmd_pad_tx_ctrl;
pmacro_dq_pad = dst_timing->burst_regs.emc_pmacro_data_pad_tx_ctrl;
pmacro_rfu1 = dst_timing->burst_regs.emc_pmacro_brick_ctrl_rfu1;
pmacro_cfg5 = dst_timing->burst_regs.emc_fbio_cfg5;
pmacro_common_tx = dst_timing->burst_regs.emc_pmacro_common_pad_tx_ctrl;
}
pmacro_cmd_pad |= (1 << 26);
if (clk < 1000000 / 600) {
CcfifoWrite(EMC_PMACRO_COMMON_PAD_TX_CTRL, pmacro_common_tx & 0xa, 0);
CcfifoWrite(EMC_PMACRO_COMMON_PAD_TX_CTRL, pmacro_common_tx & 0xf, (100000 / clk) + 1);
ramp_up_wait += 100000;
} else {
CcfifoWrite(EMC_PMACRO_COMMON_PAD_TX_CTRL, pmacro_common_tx | 0x8, 0);
}
if (clk < 1000000 / 1000) {
if (clk < 1000000 / 2400) {
pmacro_cmd_pad |= ((1 << 9) | (1 << 16));
pmacro_cmd_pad &= ~((1 << 1) | (1 << 24));
CcfifoWrite(EMC_PMACRO_CMD_PAD_TX_CTRL, pmacro_cmd_pad, (100000 / clk) + 1);
ramp_up_wait += 100000;
pmacro_dq_pad |= ((1 << 9) | (1 << 16));
pmacro_dq_pad &= ~((1 << 1) | (1 << 24));
CcfifoWrite(EMC_PMACRO_DATA_PAD_TX_CTRL, pmacro_dq_pad, 0);
CcfifoWrite(EMC_PMACRO_BRICK_CTRL_RFU1, pmacro_rfu1 & 0xfe40fe40, 0);
} else {
CcfifoWrite(EMC_PMACRO_BRICK_CTRL_RFU1, pmacro_rfu1 & 0xfe40fe40, (100000 / clk) + 1);
ramp_up_wait += 100000;
}
CcfifoWrite(EMC_PMACRO_BRICK_CTRL_RFU1, pmacro_rfu1 & 0xfeedfeed, (100000 / clk) + 1);
ramp_up_wait += 100000;
if (clk < 1000000 / 2400) {
pmacro_cmd_pad |= ((1 << 9) | (1 << 16) | (1 << 1) | (1 << 24));
CcfifoWrite(EMC_PMACRO_CMD_PAD_TX_CTRL, pmacro_cmd_pad, (100000 / clk) + 1);
ramp_up_wait += 100000;
pmacro_dq_pad |= ((1 << 9) | (1 << 16) | (1 << 1) | (1 << 24));
CcfifoWrite(EMC_PMACRO_DATA_PAD_TX_CTRL, pmacro_dq_pad, 0);
CcfifoWrite(EMC_PMACRO_BRICK_CTRL_RFU1, pmacro_rfu1, 0);
} else {
CcfifoWrite(EMC_PMACRO_BRICK_CTRL_RFU1, pmacro_rfu1, (100000 / clk) + 1);
ramp_up_wait += 100000;
}
CcfifoWrite(EMC_FBIO_CFG5, pmacro_cfg5 & ~(1 << 8), (100000 / clk) + 10);
ramp_up_wait += (100000 + (10 * clk));
} else if (clk < 1000000 / 600) {
CcfifoWrite(EMC_PMACRO_BRICK_CTRL_RFU1, pmacro_rfu1 | 0x06000600, (100000 / clk) + 1);
CcfifoWrite(EMC_FBIO_CFG5, pmacro_cfg5 & ~(1 << 8), (100000 / clk) + 10);
ramp_up_wait += (100000 + 10 * clk);
} else {
CcfifoWrite(EMC_PMACRO_BRICK_CTRL_RFU1, pmacro_rfu1 | 0x00000600, 0);
CcfifoWrite(EMC_FBIO_CFG5, pmacro_cfg5 & ~(1 << 8), 12);
ramp_up_wait += (12 * clk);
}
pmacro_cmd_pad &= ~(1 << 26);
CcfifoWrite(EMC_PMACRO_CMD_PAD_TX_CTRL, pmacro_cmd_pad, 5);
return ramp_up_wait;
}
void FreqChange(EmcDvfsTimingTable *src_timing, EmcDvfsTimingTable *dst_timing, u32 training, u32 next_clk_src) {
/* Extract training values. */
const bool train_ca = (training & CA_TRAINING);
const bool train_ca_vref = (training & CA_VREF_TRAINING);
const bool train_quse = (training & QUSE_TRAINING);
const bool train_quse_vref = (training & QUSE_VREF_TRAINING);
const bool train_wr = (training & WRITE_TRAINING);
const bool train_wr_vref = (training & WRITE_VREF_TRAINING);
const bool train_rd = (training & READ_TRAINING);
const bool train_rd_vref = (training & READ_VREF_TRAINING);
const bool train_second_rank = (training & TRAIN_SECOND_RANK);
const bool train_bit_level = (training & BIT_LEVEL_TRAINING);
/* Check if we should do training. */
const bool training_enabled = (training & (CA_TRAINING | CA_VREF_TRAINING | QUSE_TRAINING | WRITE_TRAINING | WRITE_VREF_TRAINING | READ_TRAINING | READ_VREF_TRAINING));
/* Declare variables. */
bool skip_zqcal = false;
bool compensate_trimmer_applicable = false;
uint32_t zqcal_before_cc_cutoff = 2400; /* In picoseconds */
int zq_latch_dvfs_wait_time;
uint32_t mr13_catr_enable;
uint32_t mr13_flip_fspwr;
uint32_t mr13_flip_fspop;
int next_push, next_dq_e_ivref, next_dqs_e_ivref;
uint32_t zq_wait_long;
uint32_t zq_wait_short;
uint32_t tRTM;
uint32_t RP_war;
uint32_t R2P_war;
uint32_t TRPab_war;
int nRTP;
uint32_t deltaTWATM;
uint32_t W2P_war;
uint32_t tRPST;
uint32_t mrw_req;
uint32_t adel = 0;
uint32_t dst_rate_mhz = dst_timing->rate_khz / 1000;
/* Set some common values needed. */
const int dram_type = reg::GetValue(EMC + EMC_FBIO_CFG5, EMC_REG_BITS_MASK(FBIO_CFG5_DRAM_TYPE));
const int dram_dev_num = (reg::Read(MC + MC_EMEM_ADR_CFG) & 1) + 1;
const bool shared_zq_resistor = ((src_timing->burst_regs.emc_zcal_wait_cnt >> 31) & 1);
const u32 fbio_cfg7 = src_timing->burst_regs.emc_fbio_cfg7;
const bool is_lpddr3 = (dram_type == DRAM_TYPE_LPDDR2) && ((dst_timing->burst_regs.emc_fbio_cfg5 >> 25) & 1);
bool opt_zcal_en_cc = ((dst_timing->burst_regs.emc_zcal_interval && !src_timing->burst_regs.emc_zcal_interval) || (dram_type == DRAM_TYPE_LPDDR4));
bool opt_war_200024907 = (dram_type == DRAM_TYPE_LPDDR4);
bool opt_do_sw_qrst = false;
bool opt_cc_short_zcal = true;
bool opt_short_zcal = true;
bool save_restore_clkstop_pd = true;
uint32_t opt_dll_mode = (dram_type == DRAM_TYPE_DDR4) ? GetDllState(dst_timing) : DLL_OFF;
uint32_t opt_dvfs_mode = MAN_SR;
uint32_t emc_auto_cal_config = reg::Read(EMC + EMC_AUTO_CAL_CONFIG);
/* In picoseconds. */
uint32_t source_clock_period = 1000000000 / src_timing->rate_khz;
uint32_t destination_clock_period = 1000000000 / dst_timing->rate_khz;
uint32_t tFC_lpddr4 = 1000 * dst_timing->dram_timings.t_fc_lpddr4;
uint32_t tZQCAL_lpddr4 = 1000000;
int tZQCAL_lpddr4_fc_adj = (source_clock_period > zqcal_before_cc_cutoff) ? tZQCAL_lpddr4 / destination_clock_period : (tZQCAL_lpddr4 - tFC_lpddr4) / destination_clock_period;
g_fsp_for_next_freq = !g_fsp_for_next_freq;
uint32_t emc_dbg_o = reg::Read(EMC + EMC_DBG);
uint32_t emc_pin_o = reg::Read(EMC + EMC_PIN);
uint32_t emc_cfg_pipe_clk_o = reg::Read(EMC + EMC_CFG_PIPE_CLK);
uint32_t emc_dbg = emc_dbg_o;
uint32_t emc_cfg = dst_timing->burst_regs.emc_cfg & 0x0FFFFFFF;
uint32_t emc_sel_dpd_ctrl = dst_timing->emc_sel_dpd_ctrl & 0xFFFFFEC3;
/* Step 1.1: Disable DLL. */
DllDisable(fbio_cfg7);
/* Step 1.2: Disable AUTOCAL. */
emc_auto_cal_config = dst_timing->emc_auto_cal_config;
u32 auto_cal_en = (emc_auto_cal_config & (1 << 29));
emc_auto_cal_config &= 0x7FFFF9FF;
emc_auto_cal_config |= 0x600;
reg::Write(EMC + EMC_AUTO_CAL_CONFIG, emc_auto_cal_config);
/* Step 1.3: Disable other power features. */
SetShadowBypass(ACTIVE);
reg::Write(EMC + EMC_CFG, emc_cfg);
reg::Write(EMC + EMC_SEL_DPD_CTRL, emc_sel_dpd_ctrl);
SetShadowBypass(ASSEMBLY);
/* Skip this if training_enabled is set. */
if (!training_enabled && dst_timing->periodic_training) {
/* Wait for DRAM to get out of power down. */
if (dram_dev_num == TWO_RANK) {
WaitForUpdate(EMC_EMC_STATUS, 0x30, false, fbio_cfg7);
} else {
WaitForUpdate(EMC_EMC_STATUS, 0x10, false, fbio_cfg7);
}
/* Wait for DRAM to get out of self refresh. */
WaitForUpdate(EMC_EMC_STATUS, 0x300, false, fbio_cfg7);
/* Reset all clock tree values. */
dst_timing->current_dram_clktree_c0d0u0 = dst_timing->trained_dram_clktree_c0d0u0;
dst_timing->current_dram_clktree_c0d0u1 = dst_timing->trained_dram_clktree_c0d0u1;
dst_timing->current_dram_clktree_c0d1u0 = dst_timing->trained_dram_clktree_c0d1u0;
dst_timing->current_dram_clktree_c0d1u1 = dst_timing->trained_dram_clktree_c0d1u1;
dst_timing->current_dram_clktree_c1d0u0 = dst_timing->trained_dram_clktree_c1d0u0;
dst_timing->current_dram_clktree_c1d0u1 = dst_timing->trained_dram_clktree_c1d0u1;
dst_timing->current_dram_clktree_c1d1u0 = dst_timing->trained_dram_clktree_c1d1u0;
dst_timing->current_dram_clktree_c1d1u1 = dst_timing->trained_dram_clktree_c1d1u1;
/* Do DVFS_SEQUENCE. */
adel = PeriodicCompensationHandler(DVFS_SEQUENCE, dram_dev_num, fbio_cfg7, src_timing, dst_timing);
/* Check if we should use compensate trimmer. */
compensate_trimmer_applicable = dst_timing->periodic_training && ((adel * 128 * dst_rate_mhz) / 1000000) > dst_timing->tree_margin;
}
reg::Write(EMC + EMC_INTSTATUS, 0x10);
SetShadowBypass(ACTIVE);
reg::Write(EMC + EMC_CFG, emc_cfg);
reg::Write(EMC + EMC_SEL_DPD_CTRL, emc_sel_dpd_ctrl);
reg::Write(EMC + EMC_CFG_PIPE_CLK, emc_cfg_pipe_clk_o | 0x1);
reg::Write(EMC + EMC_FDPD_CTRL_CMD_NO_RAMP, dst_timing->emc_fdpd_ctrl_cmd_no_ramp & ~0x1);
uint32_t bg_regulator_mode_change = ((dst_timing->burst_regs.emc_pmacro_bg_bias_ctrl_0 & (1 << 2)) ^ (src_timing->burst_regs.emc_pmacro_bg_bias_ctrl_0 & (1 << 2))) || ((dst_timing->burst_regs.emc_pmacro_bg_bias_ctrl_0 & (1 << 0)) ^ (src_timing->burst_regs.emc_pmacro_bg_bias_ctrl_0 & (1 << 0)));
uint32_t enable_bg_regulator = (dst_timing->burst_regs.emc_pmacro_bg_bias_ctrl_0 & (1 << 0)) == 0;
/* Check if we need to change BG the regulator. */
if (bg_regulator_mode_change) {
if (enable_bg_regulator) {
reg::Write(EMC + EMC_PMACRO_BG_BIAS_CTRL_0, src_timing->burst_regs.emc_pmacro_bg_bias_ctrl_0 & ~(1 << 0));
} else {
reg::Write(EMC + EMC_PMACRO_BG_BIAS_CTRL_0, src_timing->burst_regs.emc_pmacro_bg_bias_ctrl_0 & ~(1 << 2));
}
}
/* Check if we need to turn on VREF generator. */
if ((((!(src_timing->burst_regs.emc_pmacro_data_pad_tx_ctrl & (1 << 0)))) &&
((dst_timing->burst_regs.emc_pmacro_data_pad_tx_ctrl & (1 << 0)))) ||
((!(src_timing->burst_regs.emc_pmacro_data_pad_tx_ctrl & (1 << 8))) &&
((dst_timing->burst_regs.emc_pmacro_data_pad_tx_ctrl & (1 << 8)))))
{
uint32_t pad_tx_ctrl = dst_timing->burst_regs.emc_pmacro_data_pad_tx_ctrl;
uint32_t last_pad_tx_ctrl = src_timing->burst_regs.emc_pmacro_data_pad_tx_ctrl;
next_dqs_e_ivref = pad_tx_ctrl & (1 << 8);
next_dq_e_ivref = pad_tx_ctrl & (1 << 0);
next_push = (last_pad_tx_ctrl & ~(1 << 0) & ~(1 << 8)) | next_dq_e_ivref | next_dqs_e_ivref;
reg::Write(EMC + EMC_PMACRO_DATA_PAD_TX_CTRL, next_push);
util::WaitMicroSeconds(1);
} else if (bg_regulator_mode_change) {
util::WaitMicroSeconds(1);
}
SetShadowBypass(ASSEMBLY);
/* Step 2:
* Prelock the DLL.
*/
if (dst_timing->burst_regs.emc_cfg_dig_dll & 0x1) {
DllPrelock(dst_timing, training_enabled, next_clk_src);
} else {
ChangeDllSrc(dst_timing, next_clk_src);
DllDisable(fbio_cfg7);
}
/* Step 3:
* Prepare autocal for the clock change.
*/
SetShadowBypass(ACTIVE);
reg::Write(EMC + EMC_AUTO_CAL_CONFIG2, dst_timing->emc_auto_cal_config2);
reg::Write(EMC + EMC_AUTO_CAL_CONFIG3, dst_timing->emc_auto_cal_config3);
reg::Write(EMC + EMC_AUTO_CAL_CONFIG4, dst_timing->emc_auto_cal_config4);
reg::Write(EMC + EMC_AUTO_CAL_CONFIG5, dst_timing->emc_auto_cal_config5);
reg::Write(EMC + EMC_AUTO_CAL_CONFIG6, dst_timing->emc_auto_cal_config6);
reg::Write(EMC + EMC_AUTO_CAL_CONFIG7, dst_timing->emc_auto_cal_config7);
reg::Write(EMC + EMC_AUTO_CAL_CONFIG8, dst_timing->emc_auto_cal_config8);
SetShadowBypass(ASSEMBLY);
emc_auto_cal_config |= (0x1 | auto_cal_en);
reg::Write(EMC + EMC_AUTO_CAL_CONFIG, emc_auto_cal_config);
/* Step 4:
* Update EMC_CFG.
*/
if ((source_clock_period > 50000) && (dram_type == DRAM_TYPE_LPDDR4)) {
CcfifoWrite(EMC_SELF_REF, 1, 0);
} else {
reg::Write(EMC + EMC_CFG_2, dst_timing->emc_cfg_2);
}
/* Step 5:
* Prepare reference variables for ZQCAL regs.
*/
uint32_t emc_zcal_interval = src_timing->burst_regs.emc_zcal_interval;
emc_zcal_interval &= 0xFF000000;
uint32_t emc_zcal_wait_cnt_old = src_timing->burst_regs.emc_zcal_wait_cnt;
uint32_t emc_zcal_wait_cnt_new = dst_timing->burst_regs.emc_zcal_wait_cnt;
emc_zcal_wait_cnt_old &= ~0x7ff;
emc_zcal_wait_cnt_new &= ~0x7ff;
if (dram_type == DRAM_TYPE_LPDDR4) {
zq_wait_long = std::max<u32>(1, util::DivideUp(1000000, destination_clock_period));
} else if (dram_type == DRAM_TYPE_LPDDR2 || is_lpddr3) {
zq_wait_long = std::max<u32>(dst_timing->min_mrs_wait, util::DivideUp(360000, destination_clock_period)) + 4;
} else if (dram_type == DRAM_TYPE_DDR4) {
zq_wait_long = std::max<u32>(256, util::DivideUp(320000, destination_clock_period) + 2);
} else {
zq_wait_long = 0;
}
if (dram_type == DRAM_TYPE_LPDDR2 || is_lpddr3) {
zq_wait_short = std::max<u32>(std::max<u32>(dst_timing->min_mrs_wait, 6), util::DivideUp(90000, destination_clock_period)) + 4;
} else if (dram_type == DRAM_TYPE_DDR4) {
zq_wait_short = std::max<u32>(64, util::DivideUp(80000, destination_clock_period)) + 2;
} else {
zq_wait_short = 0;
}
/* TODO: Actually use the reference variables. */
AMS_UNUSED(zq_wait_long, zq_wait_short);
/* Step 6:
* Training code.
*/
if ((train_ca || train_ca_vref) && (dram_dev_num == TWO_RANK)) {
reg::Write(EMC + EMC_PIN, 0x107);
}
/* Step 7:
* Program FSP reference registers and send MRWs to new FSPWR.
*/
/* Step 7.1: Bug 200024907 - Patch RP R2P */
if (opt_war_200024907) {
nRTP = 16;
if (source_clock_period >= 1000000/1866) /* 535.91 ps */
nRTP = 14;
if (source_clock_period >= 1000000/1600) /* 625.00 ps */
nRTP = 12;
if (source_clock_period >= 1000000/1333) /* 750.19 ps */
nRTP = 10;
if (source_clock_period >= 1000000/1066) /* 938.09 ps */
nRTP = 8;
deltaTWATM = std::max<u32>(util::DivideUp(7500, source_clock_period), 8);
/*
* Originally there was a + .5 in the tRPST calculation.
* However since we can't do FP in the kernel and the tRTM
* computation was in a floating point ceiling function, adding
* one to tRTP should be ok. There is no other source of non
* integer values, so the result was always going to be
* something for the form: f_ceil(N + .5) = N + 1;
*/
tRPST = ((src_timing->emc_mrw & 0x80) >> 7);
tRTM = src_timing->dram_timings.rl + util::DivideUp(3600, source_clock_period) + std::max<u32>(util::DivideUp(7500, source_clock_period), 8) + tRPST + 1 + nRTP;
if (src_timing->burst_regs.emc_rp < tRTM) {
if (tRTM > (src_timing->burst_regs.emc_r2p + src_timing->burst_regs.emc_rp)) {
R2P_war = tRTM - src_timing->burst_regs.emc_rp;
RP_war = src_timing->burst_regs.emc_rp;
TRPab_war = src_timing->burst_regs.emc_trpab;
if (R2P_war > 63) {
RP_war = R2P_war + src_timing->burst_regs.emc_rp - 63;
if (TRPab_war < RP_war)
TRPab_war = RP_war;
R2P_war = 63;
}
} else {
R2P_war = src_timing-> burst_regs.emc_r2p;
RP_war = src_timing->burst_regs.emc_rp;
TRPab_war = src_timing->burst_regs.emc_trpab;
}
if (RP_war < deltaTWATM) {
W2P_war = src_timing->burst_regs.emc_w2p + deltaTWATM - RP_war;
if (W2P_war > 63) {
RP_war = RP_war + W2P_war - 63;
if (TRPab_war < RP_war)
TRPab_war = RP_war;
W2P_war = 63;
}
} else {
W2P_war = src_timing->burst_regs.emc_w2p;
}
if ((src_timing->burst_regs.emc_w2p != W2P_war)
|| (src_timing->burst_regs.emc_r2p != R2P_war)
|| (src_timing->burst_regs.emc_rp != RP_war)
|| (src_timing->burst_regs.emc_trpab != TRPab_war))
{
SetShadowBypass(ACTIVE);
reg::Write(EMC + EMC_RP, RP_war);
reg::Write(EMC + EMC_R2P, R2P_war);
reg::Write(EMC + EMC_W2P, W2P_war);
reg::Write(EMC + EMC_TRPAB, TRPab_war);
SetShadowBypass(ASSEMBLY);
util::WaitMicroSeconds(1);
}
}
}
if (!g_fsp_for_next_freq) {
mr13_flip_fspwr = (dst_timing->emc_mrw3 & 0xffffff3f) | 0x80;
mr13_flip_fspop = (dst_timing->emc_mrw3 & 0xffffff3f) | 0x00;
} else {
mr13_flip_fspwr = (dst_timing->emc_mrw3 & 0xffffff3f) | 0x40;
mr13_flip_fspop = (dst_timing->emc_mrw3 & 0xffffff3f) | 0xc0;
}
mr13_catr_enable = (mr13_flip_fspwr & 0xFFFFFFFE) | 0x01;
if (dram_dev_num == TWO_RANK) {
if (train_ca || train_ca_vref) {
if (train_second_rank) {
mr13_flip_fspop = (mr13_flip_fspop & 0x3FFFFFFF) | 0x80000000;
mr13_catr_enable = (mr13_catr_enable & 0x3FFFFFFF)| 0x40000000;
} else {
mr13_flip_fspop = (mr13_flip_fspop & 0x3FFFFFFF) | 0x40000000;
mr13_catr_enable = (mr13_catr_enable & 0x3FFFFFFF) | 0x80000000;
}
} else {
if (train_second_rank) {
mr13_catr_enable = (mr13_catr_enable & 0x3FFFFFFF) | 0x40000000;
} else {
mr13_catr_enable = (mr13_catr_enable & 0x3FFFFFFF) | 0x80000000;
}
}
}
if (dram_type == DRAM_TYPE_LPDDR4) {
reg::Write(EMC + EMC_MRW3, mr13_flip_fspwr);
reg::Write(EMC + EMC_MRW, dst_timing->emc_mrw);
reg::Write(EMC + EMC_MRW2, dst_timing->emc_mrw2);
}
/* Step 8:
* Program the shadow registers.
*/
/* Set burst registers. */
for (u32 i = 0; i < dst_timing->num_burst; i++) {
uint32_t var = 0;
uint32_t wval = 0;
if (!BurstRegistersOffsets[i]) {
continue;
}
var = BurstRegistersOffsets[i];
if (train_ca || train_ca_vref) {
wval = dst_timing->shadow_regs_ca_train_arr[i];
} else if (train_quse || train_quse_vref) {
wval = dst_timing->shadow_regs_quse_train_arr[i];
} else if (train_wr || train_wr_vref || train_rd || train_rd_vref) {
wval = dst_timing->shadow_regs_rdwr_train_arr[i];
} else {
wval = dst_timing->burst_regs_arr[i];
}
if (dram_type != DRAM_TYPE_LPDDR4 &&
(var == EMC_MRW6 || var == EMC_MRW7 ||
var == EMC_MRW8 || var == EMC_MRW9 ||
var == EMC_MRW10 || var == EMC_MRW11 ||
var == EMC_MRW12 || var == EMC_MRW13 ||
var == EMC_MRW14 || var == EMC_MRW15 ||
var == EMC_TRAINING_CTRL))
{
continue;
}
if (var == EMC_CFG) {
wval &= (dram_type == DRAM_TYPE_LPDDR4) ? 0x0FFFFFFF : 0xCFFFFFFF;
} else if ((var == EMC_ZCAL_INTERVAL) && opt_zcal_en_cc) {
wval = 0; /* EMC_ZCAL_INTERVAL reset value. */
} else if (var == EMC_PMACRO_AUTOCAL_CFG_COMMON) {
wval |= (1 << 16);
} else if (var == EMC_PMACRO_DATA_PAD_TX_CTRL) {
wval &= 0xFEFEFDFD;
} else if (var == EMC_PMACRO_CMD_PAD_TX_CTRL) {
wval &= 0xFAFEFDFD;
wval |= 0x04000000;
} else if (var == EMC_PMACRO_BRICK_CTRL_RFU1) {
wval &= 0xf800f800;
} else if (var == EMC_PMACRO_COMMON_PAD_TX_CTRL) {
wval &= 0xfffffff0;
} else if (var == EMC_TRAINING_CTRL) {
wval |= train_second_rank ? (1 << 14) : 0;
}
reg::Write(EMC + var, wval);
}
if (dram_type == DRAM_TYPE_LPDDR4) {
/* Use the current timing when training. */
if (training_enabled) {
mrw_req = (23 << 16) | (src_timing->run_clocks & 0xFF);
} else {
mrw_req = (23 << 16) | (dst_timing->run_clocks & 0xFF);
}
reg::Write(EMC + EMC_MRW, mrw_req);
}
/* Per channel burst registers. */
const bool dual_channel = reg::GetField(fbio_cfg7, EMC_REG_BITS_MASK(FBIO_CFG7_CH1_ENABLE)) == EMC_FBIO_CFG7_CH1_ENABLE_ENABLE;
for (u32 i = 0; i < dst_timing->num_burst_per_ch; i++) {
if (!PerChannelBurstRegisters[i]) {
continue;
}
const u32 addr = PerChannelBurstRegisters[i];
const u32 base = addr & ~0xFFF;
const u32 off = addr & 0xFFF;
if (dram_type != DRAM_TYPE_LPDDR4 &&
(off == EMC_MRW6 ||
off == EMC_MRW7 ||
off == EMC_MRW8 ||
off == EMC_MRW9 ||
off == EMC_MRW10 ||
off == EMC_MRW11 ||
off == EMC_MRW12 ||
off == EMC_MRW13 ||
off == EMC_MRW14 ||
off == EMC_MRW15)
)
{
continue;
}
/* Filter out second channel if not in DUAL_CHANNEL mode. */
if (!dual_channel && base == EMC1) {
continue;
}
/* Write the value. */
reg::Write(addr, dst_timing->burst_perch_regs_arr[i]);
}
/* Vref regs. */
for (u32 i = 0; i < dst_timing->vref_num; i++) {
if (!PerChannelVrefRegisters[i]) {
continue;
}
const u32 addr = PerChannelVrefRegisters[i];
const u32 base = addr & ~0xFFF;
/* Filter out second channel if not in DUAL_CHANNEL mode. */
if (!dual_channel && base == EMC1) {
continue;
}
/* Write the value. */
reg::Write(addr, dst_timing->vref_perch_regs_arr[i]);
}
/* Training regs. */
if (training_enabled) {
for (u32 i = 0; i < dst_timing->training_mod_num; i++) {
if (!PerChannelTrainingModRegisters[i]) {
continue;
}
const u32 addr = PerChannelTrainingModRegisters[i];
const u32 base = addr & ~0xFFF;
/* Filter out second channel if not in DUAL_CHANNEL mode. */
if (!dual_channel && base == EMC1) {
continue;
}
/* Write the value. */
reg::Write(addr, dst_timing->training_mod_regs_arr[i]);
}
}
/* Trimmers. */
for (u32 i = 0; i < dst_timing->num_trim; i++) {
if (!TrimRegisters[i]) {
continue;
}
const u32 addr = TrimRegisters[i];
const u32 ofs = addr & 0xFFF;
u32 wval = dst_timing->trim_regs_arr[i];
if (compensate_trimmer_applicable &&
(ofs == EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_0 ||
ofs == EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_1 ||
ofs == EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_2 ||
ofs == EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_3 ||
ofs == EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_0 ||
ofs == EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_1 ||
ofs == EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_2 ||
ofs == EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_3 ||
ofs == EMC_DATA_BRLSHFT_0 ||
ofs == EMC_DATA_BRLSHFT_1))
{
wval = ApplyPeriodicCompensationTrimmer(dst_timing, ofs);
}
/* Write the value. */
reg::Write(addr, wval);
}
/* Per-channel trimmers. */
for (u32 i = 0; i < dst_timing->num_trim_per_ch; i++) {
if (!PerChannelTrimRegisters[i]) {
continue;
}
const u32 addr = PerChannelTrimRegisters[i];
const u32 base = addr & ~0xFFF;
const u32 ofs = addr & 0xFFF;
/* Filter out second channel if not in DUAL_CHANNEL mode. */
if (!dual_channel && base == EMC1) {
continue;
}
u32 wval = dst_timing->trim_perch_regs_arr[i];
if (compensate_trimmer_applicable &&
(ofs == EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_0 ||
ofs == EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_1 ||
ofs == EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_2 ||
ofs == EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_3 ||
ofs == EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_0 ||
ofs == EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_1 ||
ofs == EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_2 ||
ofs == EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_3 ||
ofs == EMC_DATA_BRLSHFT_0 ||
ofs == EMC_DATA_BRLSHFT_1))
{
wval = ApplyPeriodicCompensationTrimmer(dst_timing, ofs);
}
/* Write the value. */
reg::Write(addr, wval);
}
if (training_enabled) {
if (train_wr && dst_timing->periodic_training && (dram_type == DRAM_TYPE_LPDDR4)) {
PeriodicCompensationHandler(WRITE_TRAINING_SEQUENCE, dram_dev_num, fbio_cfg7, src_timing, dst_timing);
}
} else {
/* Write burst_mc_regs. */
for (u32 i = 0; i < dst_timing->num_mc_regs; i++) {
reg::Write(BurstMcRegisters[i], dst_timing->burst_mc_regs_arr[i]);
}
}
/* Registers to be programmed on the faster clock. */
if (!training_enabled && (dst_timing->rate_khz < src_timing->rate_khz)) {
for (u32 i = 0; i < dst_timing->num_up_down; i++) {
reg::Write(LaScaleRegisters[i], dst_timing->la_scale_regs_arr[i]);
}
}
/* Step 9:
* LPDDR4 section A.
*/
if (dram_type == DRAM_TYPE_LPDDR4) {
reg::Write(EMC + EMC_ZCAL_INTERVAL, emc_zcal_interval);
reg::Write(EMC + EMC_ZCAL_WAIT_CNT, emc_zcal_wait_cnt_new);
reg::Write(EMC + EMC_DBG, emc_dbg_o | 0x40000002);
reg::Write(EMC + EMC_ZCAL_INTERVAL, emc_zcal_interval);
reg::Write(EMC + EMC_DBG, emc_dbg_o);
if (training_enabled) {
SetShadowBypass(ACTIVE);
reg::Write(EMC + EMC_PMACRO_AUTOCAL_CFG_COMMON, dst_timing->burst_regs.emc_pmacro_autocal_cfg_common | (1 << 16));
if (train_ca || train_ca_vref) {
reg::Write(EMC + EMC_FBIO_CFG5, src_timing->burst_regs.emc_fbio_cfg5 | (1 << 27));
}
SetShadowBypass(ASSEMBLY);
if (dual_channel) {
CcfifoWrite(EMC_CFG_SYNC, 0, 0);
}
/* Change CFG_SWAP. */
CcfifoWrite(EMC_DBG, ((emc_dbg_o & 0xF3FFFFFF) | 0x4000000), 0);
}
}
/* Step 10:
* LPDDR4 and DDR3 common section.
*/
if (opt_dvfs_mode == MAN_SR || dram_type == DRAM_TYPE_LPDDR4) {
if (dram_type == DRAM_TYPE_LPDDR4) {
CcfifoWrite(EMC_SELF_REF, 0x101, 0);
} else {
CcfifoWrite(EMC_SELF_REF, 0x1, 0);
}
if (!(train_ca || train_ca_vref) && (dram_type == DRAM_TYPE_LPDDR4) && (source_clock_period <= zqcal_before_cc_cutoff)) {
CcfifoWrite(EMC_MRW3, mr13_flip_fspwr ^ 0x40, 0);
CcfifoWrite(EMC_MRW6, (dst_timing->burst_regs.emc_mrw6 & 0xFFFF3F3F) | (src_timing->burst_regs.emc_mrw6 & 0x0000C0C0), 0);
CcfifoWrite(EMC_MRW14, (dst_timing->burst_regs.emc_mrw14 & 0xFFFF0707) | (src_timing->burst_regs.emc_mrw14 & 0x00003838), 0);
if (dram_dev_num == TWO_RANK) {
CcfifoWrite(EMC_MRW7, (dst_timing->burst_regs.emc_mrw7 & 0xFFFF3F3F) | (src_timing->burst_regs.emc_mrw7 & 0x0000C0C0), 0);
CcfifoWrite(EMC_MRW15, (dst_timing->burst_regs.emc_mrw15 & 0xFFFF0707) | (src_timing->burst_regs.emc_mrw15 & 0x00003838), 0);
}
if (opt_zcal_en_cc) {
if ((dram_dev_num == ONE_RANK) || shared_zq_resistor) {
CcfifoWrite(EMC_ZQ_CAL, 2 << 30 | (1 << 0), 0);
} else {
CcfifoWrite(EMC_ZQ_CAL, (1 << 0), 0);
}
}
}
}
emc_dbg = emc_dbg_o;
if (dram_type == DRAM_TYPE_LPDDR4) {
if (training_enabled) {
/* Change CFG_SWAP. */
emc_dbg = ((emc_dbg_o & 0xF3FFFFFF) | 0x4000000 | (1 << 30));
CcfifoWrite(EMC_DBG, emc_dbg, 0);
}
if (train_ca || train_ca_vref) {
CcfifoWrite(EMC_PMACRO_DATA_RX_TERM_MODE, src_timing->burst_regs.emc_pmacro_data_rx_term_mode & 0xFFFFFCCC, 0);
if ((dram_dev_num == TWO_RANK) && train_second_rank) {
CcfifoWrite(EMC_MRW3, mr13_flip_fspop | 0x8, (1000 * src_timing->dram_timings.t_rp) / source_clock_period);
CcfifoWrite(EMC_MRW3, mr13_catr_enable | 0x8, 0);
} else {
CcfifoWrite(EMC_MRW3, mr13_catr_enable | 0x8, (1000 * src_timing->dram_timings.t_rp) / source_clock_period);
}
CcfifoWrite(EMC_TR_CTRL_0, 0x15A, 0);
CcfifoWrite(EMC_INTSTATUS, 0, 1000000 / source_clock_period);
} else {
CcfifoWrite(EMC_MRW3, mr13_flip_fspop | 0x8, (1000 * src_timing->dram_timings.t_rp) / source_clock_period);
CcfifoWrite(EMC_INTSTATUS, 0, tFC_lpddr4 / source_clock_period);
}
}
bool ref_b4_sref_en = false;
bool cya_issue_pc_ref = false;
bool cya_allow_ref_cc = false;
if ((dram_type == DRAM_TYPE_LPDDR4) || (opt_dvfs_mode != MAN_SR)) {
uint32_t t = 30 + (cya_allow_ref_cc ? (4000 * src_timing->dram_timings.t_rfc) + ((1000 * src_timing->dram_timings.t_rp) / source_clock_period) : 0);
CcfifoWrite(EMC_PIN, emc_pin_o & 0xFFFFFFF8, t);
}
uint32_t ref_delay_mult = 1;
ref_delay_mult += ref_b4_sref_en ? 1 : 0;
ref_delay_mult += cya_allow_ref_cc ? 1 : 0;
ref_delay_mult += cya_issue_pc_ref ? 1 : 0;
uint32_t ref_delay = ref_delay_mult * ((1000 * src_timing->dram_timings.t_rp / source_clock_period) + (1000 * src_timing->dram_timings.t_rfc / source_clock_period)) + 20;
/* Step 11:
* Ramp down.
*/
CcfifoWrite(EMC_CFG_SYNC, 0, (dram_type == DRAM_TYPE_LPDDR4) ? 0 : ref_delay);
CcfifoWrite(EMC_DBG, emc_dbg | ((1 << 1) | (1 << 30)), 0);
uint32_t ramp_down_wait = DvfsPowerRampDown(false, src_timing, dst_timing, source_clock_period);
/* Step 12:
* Trigger the clock change.
*/
CcfifoWrite(EMC_STALL_THEN_EXE_AFTER_CLKCHANGE, 1, 0);
if (!training_enabled) {
CcfifoWrite(EMC_DBG, (emc_dbg & ~(1 << 30)) | (1 << 1), 0);
}
/* Step 13:
* Ramp up.
*/
uint32_t ramp_up_wait = DvfsPowerRampUp(false, src_timing, dst_timing, training, destination_clock_period);
CcfifoWrite(EMC_DBG, emc_dbg, 0);
/* Step 14:
* Bringup CKE pins.
*/
if ((dram_type == DRAM_TYPE_LPDDR4)) {
uint32_t r = emc_pin_o & 0xFFFFFFF8;
if (train_ca || train_ca_vref) {
if (dram_dev_num == TWO_RANK) {
if (train_second_rank) {
CcfifoWrite(EMC_PIN, r | 5, 0);
} else {
CcfifoWrite(EMC_PIN, r | 6, 0);
}
} else {
CcfifoWrite(EMC_PIN, r, 0);
}
} else if (dram_dev_num == TWO_RANK) {
CcfifoWrite(EMC_PIN, r | 7, 0);
} else {
CcfifoWrite(EMC_PIN, r | 1, 0);
}
}
/* Step 15:
* Calculate zqlatch wait time; has dependency on ramping times.
*/
if (source_clock_period <= zqcal_before_cc_cutoff) {
int t = (int)(ramp_up_wait + ramp_down_wait) / (int)destination_clock_period;
zq_latch_dvfs_wait_time = (int)tZQCAL_lpddr4_fc_adj - t;
} else {
zq_latch_dvfs_wait_time = tZQCAL_lpddr4_fc_adj - util::DivideUp(1000 * dst_timing->dram_timings.t_pdex, destination_clock_period);
}
if (!(train_ca || train_ca_vref) && (dram_type == DRAM_TYPE_LPDDR4) && opt_zcal_en_cc) {
if (dram_dev_num == ONE_RANK) {
if (source_clock_period > zqcal_before_cc_cutoff) {
CcfifoWrite(EMC_ZQ_CAL, (2 << 30) | (1 << 0), util::DivideUp(1000 * dst_timing->dram_timings.t_pdex, destination_clock_period));
}
if (!training_enabled) {
CcfifoWrite(EMC_MRW3, (mr13_flip_fspop & 0xF3FFFFF7) | 0xC000000, util::DivideUp(1000 * dst_timing->dram_timings.t_pdex, destination_clock_period));
CcfifoWrite(EMC_SELF_REF, 0x100, 0);
CcfifoWrite(EMC_REF, 0, 0);
}
CcfifoWrite(EMC_ZQ_CAL, (2 << 30) | (1 << 1), std::max<int>(0, zq_latch_dvfs_wait_time));
} else if (shared_zq_resistor) {
if (source_clock_period > zqcal_before_cc_cutoff) {
CcfifoWrite(EMC_ZQ_CAL, (2 << 30) | (1 << 0), util::DivideUp(1000 * dst_timing->dram_timings.t_pdex, destination_clock_period));
}
CcfifoWrite(EMC_ZQ_CAL, (2 << 30) | (1 << 1), std::max<int>(0, zq_latch_dvfs_wait_time) + util::DivideUp(1000 * dst_timing->dram_timings.t_pdex, destination_clock_period));
CcfifoWrite(EMC_ZQ_CAL, (1 << 30) | (1 << 1), 0);
if (!training_enabled) {
CcfifoWrite(EMC_MRW3, (mr13_flip_fspop & 0xF3FFFFF7) | 0xC000000, 0);
CcfifoWrite(EMC_SELF_REF, 0x100, 0);
CcfifoWrite(EMC_REF, 0, 0);
}
CcfifoWrite(EMC_ZQ_CAL, (1 << 30) | (1 << 1), tZQCAL_lpddr4 / destination_clock_period);
} else {
if (source_clock_period > zqcal_before_cc_cutoff) {
CcfifoWrite(EMC_ZQ_CAL, (1 << 0), util::DivideUp(1000 * dst_timing->dram_timings.t_pdex, destination_clock_period));
}
if (!training_enabled) {
CcfifoWrite(EMC_MRW3, (mr13_flip_fspop & 0xF3FFFFF7) | 0xC000000, util::DivideUp(1000 * dst_timing->dram_timings.t_pdex, destination_clock_period));
CcfifoWrite(EMC_SELF_REF, 0x100, 0);
CcfifoWrite(EMC_REF, 0, 0);
}
CcfifoWrite(EMC_ZQ_CAL, (1 << 1), std::max<int>(0, zq_latch_dvfs_wait_time));
}
}
/* WAR: delay for zqlatch */
CcfifoWrite(EMC_INTSTATUS, 0, 10);
/* Step 16:
* LPDDR4 Conditional Training Kickoff.
*/
if (training_enabled && (dram_type == DRAM_TYPE_LPDDR4)) {
CcfifoWrite(EMC_INTSTATUS, 0, (1020000 / destination_clock_period));
uint32_t train_cmd = 0;
if (train_ca)
train_cmd |= (1 << 1); /* CA */
if (train_ca_vref)
train_cmd |= (1 << 5); /* CA_VREF */
if (train_quse)
train_cmd |= (1 << 4); /* QUSE */
if (train_quse_vref)
train_cmd |= (1 << 8); /* QUSE_VREF */
if (train_wr)
train_cmd |= (1 << 3); /* WR */
if (train_wr_vref)
train_cmd |= (1 << 6); /* WR_VREF */
if (train_rd)
train_cmd |= (1 << 2); /* RD */
if (train_rd_vref)
train_cmd |= (1 << 7); /* RD_VREF */
train_cmd |= (1 << 31); /* GO */
CcfifoWrite(EMC_TRAINING_CMD, train_cmd, 0);
if (bg_regulator_mode_change) {
if (enable_bg_regulator)
CcfifoWrite(EMC_PMACRO_BG_BIAS_CTRL_0, src_timing->burst_regs.emc_pmacro_bg_bias_ctrl_0 & ~(1 << 0), 0);
else
CcfifoWrite(EMC_PMACRO_BG_BIAS_CTRL_0, src_timing->burst_regs.emc_pmacro_bg_bias_ctrl_0 & ~(1 << 2), 0);
}
CcfifoWrite(EMC_SWITCH_BACK_CTRL, 1, 0);
if (!(train_ca || train_ca_vref) || train_second_rank) {
CcfifoWrite(EMC_MRW3, mr13_flip_fspop ^ 0xC0, 0);
CcfifoWrite(EMC_INTSTATUS, 0, (1000000 / destination_clock_period));
}
CcfifoWrite(EMC_PIN, emc_pin_o & 0xFFFFFFF8, 0);
CcfifoWrite(EMC_CFG_SYNC, 0, 0);
CcfifoWrite(EMC_DBG, emc_dbg | ((1 << 30) | (1 << 1)), 0);
DvfsPowerRampDown(true, src_timing, dst_timing, destination_clock_period);
CcfifoWrite(EMC_STALL_THEN_EXE_AFTER_CLKCHANGE, 1, 0);
CcfifoWrite(EMC_DBG, (emc_dbg & ~(1 << 30)) | (1 << 1), 0);
DvfsPowerRampUp(true, src_timing, dst_timing, training, source_clock_period);
CcfifoWrite(EMC_DBG, emc_dbg, 0);
if (dram_dev_num == TWO_RANK) {
CcfifoWrite(EMC_PIN, emc_pin_o | 7, 0);
} else {
CcfifoWrite(EMC_PIN, ((emc_pin_o & 0xFFFFFFF8) | 1), 0);
}
if (train_ca || train_ca_vref) {
CcfifoWrite(EMC_TR_CTRL_0, 0x4A, (200000 / source_clock_period));
CcfifoWrite(EMC_TR_CTRL_0, 0x40, (1000000 / source_clock_period));
CcfifoWrite(EMC_MRW3, mr13_catr_enable & 0xFFFFFFFE, 0);
CcfifoWrite(EMC_INTSTATUS, 0, (1000000 / source_clock_period));
CcfifoWrite(EMC_PMACRO_DATA_RX_TERM_MODE, src_timing->burst_regs.emc_pmacro_data_rx_term_mode, 0);
}
CcfifoWrite(EMC_DBG, emc_dbg_o, 0);
if (opt_zcal_en_cc) {
CcfifoWrite(EMC_ZQ_CAL, (2 << 30) | (1 << 0), 0);
CcfifoWrite(EMC_ZQ_CAL, (2 << 30) | (1 << 1), (1000000 / source_clock_period));
if (dram_dev_num == TWO_RANK) {
if (shared_zq_resistor) {
if (!(train_ca || train_ca_vref) || train_second_rank) {
CcfifoWrite(EMC_ZQ_CAL, (1 << 30) | (1 << 0), 0);
CcfifoWrite(EMC_ZQ_CAL, (1 << 30) | (1 << 1), (1000000 / source_clock_period));
if (!(train_ca || train_ca_vref))
CcfifoWrite(EMC_MRW3, ((mr13_flip_fspop ^ 0xC0) & 0xF3FFFFF7) | 0xC000000, 0);
}
CcfifoWrite(EMC_SELF_REF, 0x100, 0);
skip_zqcal = true;
} else {
if ((train_ca || train_ca_vref) && !train_second_rank) {
CcfifoWrite(EMC_SELF_REF, 0x100, 0);
skip_zqcal = true;
} else {
CcfifoWrite(EMC_ZQ_CAL, (1 << 30) | (1 << 0), 0);
CcfifoWrite(EMC_ZQ_CAL, (1 << 30) | (1 << 1), (1000000 / source_clock_period));
}
}
}
}
if (!skip_zqcal) {
if (!(train_ca || train_ca_vref))
CcfifoWrite(EMC_MRW3, ((mr13_flip_fspop ^ 0xC0) & 0xF3FFFFF7) | 0xC000000, 0);
CcfifoWrite(EMC_SELF_REF, 0x100, 0);
}
}
if (!skip_zqcal) {
/* Step 17:
* MANSR exit self refresh.
*/
if ((opt_dvfs_mode == MAN_SR) && (dram_type != DRAM_TYPE_LPDDR4))
CcfifoWrite(EMC_SELF_REF, 0, 0);
/* Step 18:
* Send MRWs to LPDDR3/DDR3.
*/
if (dram_type == DRAM_TYPE_LPDDR2) {
CcfifoWrite(EMC_MRW2, dst_timing->emc_mrw2, 0);
CcfifoWrite(EMC_MRW, dst_timing->emc_mrw, 0);
if (is_lpddr3) {
CcfifoWrite(EMC_MRW4, dst_timing->emc_mrw4, 0);
}
} else if (dram_type == DRAM_TYPE_DDR4) {
if (opt_dll_mode == DLL_ON) {
CcfifoWrite(EMC_EMRS, dst_timing->emc_emrs & ~(1 << 26), 0);
}
CcfifoWrite(EMC_EMRS2, dst_timing->emc_emrs2 & ~(1 << 26), 0);
CcfifoWrite(EMC_MRS, dst_timing->emc_mrs | (1 << 26), 0);
}
/* Step 19:
* ZQCAL for LPDDR3/DDR3
*/
if (opt_zcal_en_cc) {
if (dram_type == DRAM_TYPE_LPDDR2) {
uint32_t r;
uint32_t zq_op = opt_cc_short_zcal ? 0x56 : 0xAB;
uint32_t zcal_wait_time_ps = opt_cc_short_zcal ? 90000 : 360000;
uint32_t zcal_wait_time_clocks = util::DivideUp(zcal_wait_time_ps, destination_clock_period);
r = (zcal_wait_time_clocks << 16) | (zcal_wait_time_clocks << 0);
CcfifoWrite(EMC_MRS_WAIT_CNT2, r, 0);
CcfifoWrite(EMC_MRW, (2 << 30) | (1 << 27) | (10 << 16) | (zq_op << 0), 0);
if (dram_dev_num == TWO_RANK) {
r = (1 << 30) | (1 << 27) | (10 << 16) | (zq_op << 0);
CcfifoWrite(EMC_MRW, r, 0);
}
} else if (dram_type == DRAM_TYPE_DDR4) {
uint32_t zq_op = opt_cc_short_zcal ? 0 : (1 << 4);
CcfifoWrite(EMC_ZQ_CAL, zq_op | (2 << 30) | (1 << 0), 0);
if (dram_dev_num == TWO_RANK) {
CcfifoWrite(EMC_ZQ_CAL, zq_op | (1 << 30) | (1 << 0), 0);
}
}
}
}
if (bg_regulator_mode_change) {
SetShadowBypass(ACTIVE);
uint32_t bg_regulator_switch_complete_wait_clks = ramp_up_wait > 1250000 ? 0 : (1250000 - ramp_up_wait) / destination_clock_period;
if (training_enabled) {
bg_regulator_switch_complete_wait_clks = (1250000 / source_clock_period);
CcfifoWrite(EMC_PMACRO_BG_BIAS_CTRL_0, src_timing->burst_regs.emc_pmacro_bg_bias_ctrl_0, bg_regulator_switch_complete_wait_clks);
} else {
CcfifoWrite(EMC_PMACRO_BG_BIAS_CTRL_0, dst_timing->burst_regs.emc_pmacro_bg_bias_ctrl_0, bg_regulator_switch_complete_wait_clks);
}
SetShadowBypass(ASSEMBLY);
}
/* Step 20:
* Issue ref and optional QRST.
*/
if (training_enabled || (dram_type != DRAM_TYPE_LPDDR4)) {
CcfifoWrite(EMC_REF, 0, 0);
}
if (opt_do_sw_qrst) {
CcfifoWrite(EMC_ISSUE_QRST, 1, 0);
CcfifoWrite(EMC_ISSUE_QRST, 0, 2);
}
/* Step 21:
* Restore ZCAL and ZCAL interval.
*/
if (save_restore_clkstop_pd || opt_zcal_en_cc) {
SetShadowBypass(ACTIVE);
if (opt_zcal_en_cc) {
if (training_enabled) {
CcfifoWrite(EMC_ZCAL_INTERVAL, src_timing->burst_regs.emc_zcal_interval, 0);
} else if (dram_type != DRAM_TYPE_LPDDR4) {
CcfifoWrite(EMC_ZCAL_INTERVAL, dst_timing->burst_regs.emc_zcal_interval, 0);
}
}
if (save_restore_clkstop_pd) {
CcfifoWrite(EMC_CFG, dst_timing->burst_regs.emc_cfg & ~(1 << 28), 0);
}
if (training_enabled && (dram_type == DRAM_TYPE_LPDDR4)) {
CcfifoWrite(EMC_SEL_DPD_CTRL, src_timing->emc_sel_dpd_ctrl, 0);
}
SetShadowBypass(ASSEMBLY);
}
/* Step 22:
* Restore EMC_CFG_PIPE_CLK.
*/
CcfifoWrite(EMC_CFG_PIPE_CLK, emc_cfg_pipe_clk_o, 0);
if (bg_regulator_mode_change) {
if (enable_bg_regulator) {
reg::Write(EMC + EMC_PMACRO_BG_BIAS_CTRL_0, dst_timing->burst_regs.emc_pmacro_bg_bias_ctrl_0 & ~(1 << 2));
} else {
reg::Write(EMC + EMC_PMACRO_BG_BIAS_CTRL_0, dst_timing->burst_regs.emc_pmacro_bg_bias_ctrl_0 & ~(1 << 0));
}
}
/* Step 23:
* Do clock change.
*/
if (training_enabled) {
u32 cur_clk_src = reg::Read(CLKRST + CLK_RST_CONTROLLER_CLK_SOURCE_EMC);
reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_SOURCE_EMC_SAFE, cur_clk_src);
ChangeDllSrc(src_timing, cur_clk_src);
}
uint32_t cfg_dig_dll_tmp = (reg::Read(EMC + EMC_CFG_DIG_DLL) & 0xFFFFFF24) | 0x88;
reg::Write(EMC + EMC_CFG_DIG_DLL, cfg_dig_dll_tmp);
reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_SOURCE_EMC, next_clk_src);
WaitForUpdate(EMC_INTSTATUS, 0x10, true, fbio_cfg7);
/* Step 24:
* Save training results.
*/
if (training_enabled) {
uint32_t emc_dbg_tmp = reg::Read(EMC + EMC_DBG);
reg::Write(EMC + EMC_DBG, emc_dbg_tmp | 1); /* Set READ_MUX to ASSEMBLY. */
/* Save CA results. */
if (train_ca) {
dst_timing->trim_perch_regs.emc0_cmd_brlshft_0 = reg::Read(EMC0 + EMC_CMD_BRLSHFT_0);
dst_timing->trim_perch_regs.emc1_cmd_brlshft_1 = dual_channel ? reg::Read(EMC1 + EMC_CMD_BRLSHFT_1): 0;
dst_timing->trim_regs.emc_pmacro_ob_ddll_long_dq_rank0_4 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_4);
dst_timing->trim_regs.emc_pmacro_ob_ddll_long_dq_rank0_5 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_5) : 0;
if (train_bit_level) {
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_cmd0_0 = reg::Read(EMC + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_CMD0_0);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_cmd0_1 = reg::Read(EMC + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_CMD0_1);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_cmd0_2 = reg::Read(EMC + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_CMD0_2);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_cmd1_0 = reg::Read(EMC + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_CMD1_0);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_cmd1_1 = reg::Read(EMC + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_CMD1_1);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_cmd1_2 = reg::Read(EMC + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_CMD1_2);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_cmd2_0 = reg::Read(EMC + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_CMD2_0);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_cmd2_1 = reg::Read(EMC + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_CMD2_1);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_cmd2_2 = reg::Read(EMC + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_CMD2_2);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_cmd3_0 = reg::Read(EMC + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_CMD3_0);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_cmd3_1 = reg::Read(EMC + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_CMD3_1);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_cmd3_2 = reg::Read(EMC + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_CMD3_2);
}
}
/* Save CA_VREF results. */
if (train_ca_vref) {
dst_timing->burst_perch_regs.emc0_mrw10 = (reg::Read(EMC0 + EMC_TRAINING_OPT_CA_VREF) & 0xFFFF) | 0x880C0000;
dst_timing->burst_perch_regs.emc1_mrw10 = (dual_channel ? reg::Read(EMC1 + EMC_TRAINING_OPT_CA_VREF) & 0xFFFF : 0) | 0x880C0000;
if (dram_dev_num == TWO_RANK) {
dst_timing->burst_perch_regs.emc0_mrw11 = ((reg::Read(EMC0 + EMC_TRAINING_OPT_CA_VREF) >> 16) & 0xFF) | (reg::Read(EMC0 + EMC_TRAINING_OPT_CA_VREF) >> 24 << 8) | (0x480C0000 & 0xFFFFFF00);
dst_timing->burst_perch_regs.emc1_mrw11 = (((dual_channel ? reg::Read(EMC1 + EMC_TRAINING_OPT_CA_VREF) : 0) >> 16) & 0xFF) | ((dual_channel ? reg::Read(EMC1 + EMC_TRAINING_OPT_CA_VREF) : 0) >> 24 << 8) | (0x480C0000 & 0xFFFFFF00);
} else {
dst_timing->burst_perch_regs.emc0_mrw11 = ((reg::Read(EMC0 + EMC_TRAINING_OPT_CA_VREF) >> 16) & 0xFF) | (reg::Read(EMC0 + EMC_TRAINING_OPT_CA_VREF) >> 24 << 8) | (0xC80C0000 & 0xFFFFFF00);
dst_timing->burst_perch_regs.emc1_mrw11 = (((dual_channel ? reg::Read(EMC1 + EMC_TRAINING_OPT_CA_VREF) : 0) >> 16) & 0xFF) | ((dual_channel ? reg::Read(EMC1 + EMC_TRAINING_OPT_CA_VREF) : 0) >> 24 << 8) | (0xC80C0000 & 0xFFFFFF00);
}
}
/* Save QUSE results. */
if (train_quse || train_rd) {
dst_timing->trim_perch_regs.emc0_quse_brlshft_0 = reg::Read(EMC0 + EMC_QUSE_BRLSHFT_0);
dst_timing->trim_perch_regs.emc1_quse_brlshft_1 = dual_channel ? reg::Read(EMC1 + EMC_QUSE_BRLSHFT_1) : 0;
dst_timing->trim_regs.emc_pmacro_quse_ddll_rank0_0 = reg::Read(EMC0 + EMC_PMACRO_QUSE_DDLL_RANK0_0);
dst_timing->trim_regs.emc_pmacro_quse_ddll_rank0_1= reg::Read(EMC0 + EMC_PMACRO_QUSE_DDLL_RANK0_1);
dst_timing->trim_regs.emc_pmacro_quse_ddll_rank0_2 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_QUSE_DDLL_RANK0_2) : 0;
dst_timing->trim_regs.emc_pmacro_quse_ddll_rank0_3 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_QUSE_DDLL_RANK0_3) : 0;
if (dram_dev_num == TWO_RANK) {
dst_timing->trim_perch_regs.emc0_quse_brlshft_2 = reg::Read(EMC0 + EMC_QUSE_BRLSHFT_2);
dst_timing->trim_perch_regs.emc1_quse_brlshft_3 = dual_channel ? reg::Read(EMC1 + EMC_QUSE_BRLSHFT_3) : 0;
dst_timing->trim_regs.emc_pmacro_quse_ddll_rank1_0 = reg::Read(EMC0 + EMC_PMACRO_QUSE_DDLL_RANK1_0);
dst_timing->trim_regs.emc_pmacro_quse_ddll_rank1_1 = reg::Read(EMC0 + EMC_PMACRO_QUSE_DDLL_RANK1_1);
dst_timing->trim_regs.emc_pmacro_quse_ddll_rank1_2 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_QUSE_DDLL_RANK1_2) : 0;
dst_timing->trim_regs.emc_pmacro_quse_ddll_rank1_3 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_QUSE_DDLL_RANK1_3) : 0;
}
}
/* Save QUSE_VREF results. */
if (train_quse_vref) {
if (dram_dev_num == TWO_RANK) {
uint32_t emc0_opt_dqs_array[4] = {0};
uint32_t emc1_opt_dqs_array[4] = {0};
uint32_t emc1_training_opt_dqs_ib_vref_rank0_val = dual_channel ? reg::Read(EMC1 + EMC_TRAINING_OPT_DQS_IB_VREF_RANK0) : 0;
uint32_t emc1_training_opt_dqs_ib_vref_rank1_val = dual_channel ? reg::Read(EMC1 + EMC_TRAINING_OPT_DQS_IB_VREF_RANK1) : 0;
for (int i = 0; i < 4; i++) {
emc0_opt_dqs_array[i] = (reg::Read(EMC0 + EMC_TRAINING_OPT_DQS_IB_VREF_RANK0) >> (8 * i)) & 0xFF;
emc1_opt_dqs_array[i] = (emc1_training_opt_dqs_ib_vref_rank0_val >> (8 * i)) & 0xFF;
}
uint32_t ib_vref_dqs_0 = 0;
uint32_t ib_vref_dqs_1 = 0;
for (int i = 0; i < 4; i++)
{
ib_vref_dqs_0 |= (emc0_opt_dqs_array[i] + ((reg::Read(EMC0 + EMC_TRAINING_OPT_DQS_IB_VREF_RANK1) >> (8 * i)) & 0xFF)) >> 1 << (8 * i);
ib_vref_dqs_1 |= (emc1_opt_dqs_array[i] + ((emc1_training_opt_dqs_ib_vref_rank1_val >> (8 * i)) & 0xFF)) >> 1 << (8 * i);
}
dst_timing->trim_regs.emc_pmacro_ib_vref_dqs_0 = ib_vref_dqs_0;
dst_timing->trim_regs.emc_pmacro_ib_vref_dqs_1 = ib_vref_dqs_1;
}
else
{
dst_timing->trim_regs.emc_pmacro_ib_vref_dqs_0 = reg::Read(EMC + EMC_PMACRO_IB_VREF_DQS_0);
dst_timing->trim_regs.emc_pmacro_ib_vref_dqs_1 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_IB_VREF_DQS_1) : 0;
}
}
/* Save RD results. */
if (train_rd) {
dst_timing->trim_regs.emc_pmacro_ib_ddll_long_dqs_rank0_0 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_LONG_DQS_RANK0_0);
dst_timing->trim_regs.emc_pmacro_ib_ddll_long_dqs_rank0_1 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_LONG_DQS_RANK0_1);
dst_timing->trim_regs.emc_pmacro_ib_ddll_long_dqs_rank0_2 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_LONG_DQS_RANK0_2) : 0;
dst_timing->trim_regs.emc_pmacro_ib_ddll_long_dqs_rank0_3 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_LONG_DQS_RANK0_3) : 0;
if (dram_dev_num == TWO_RANK) {
dst_timing->trim_regs.emc_pmacro_ib_ddll_long_dqs_rank1_0 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_LONG_DQS_RANK1_0);
dst_timing->trim_regs.emc_pmacro_ib_ddll_long_dqs_rank1_1 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_LONG_DQS_RANK1_1);
dst_timing->trim_regs.emc_pmacro_ib_ddll_long_dqs_rank1_2 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_LONG_DQS_RANK1_2) : 0;
dst_timing->trim_regs.emc_pmacro_ib_ddll_long_dqs_rank1_3 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_LONG_DQS_RANK1_3) : 0;
}
if (train_bit_level) {
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte0_0 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE0_0);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte0_1 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE0_1);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte0_2 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE0_2);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte1_0 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE1_0);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte1_1 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE1_1);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte1_2 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE1_2);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte2_0 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE2_0);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte2_1 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE2_1);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte2_2 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE2_2);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte3_0 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE3_0);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte3_1 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE3_1);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte3_2 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE3_2);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte4_0 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE4_0) : 0;
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte4_1 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE4_1) : 0;
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte4_2 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE4_2) : 0;
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte5_0 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE5_0) : 0;
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte5_1 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE5_1) : 0;
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte5_2 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE5_2) : 0;
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte6_0 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE6_0) : 0;
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte6_1 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE6_1) : 0;
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte6_2 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE6_2) : 0;
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte7_0 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE7_0) : 0;
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte7_1 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE7_1) : 0;
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank0_byte7_2 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK0_BYTE7_2) : 0;
if (dram_dev_num == TWO_RANK) {
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte0_0 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE0_0);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte0_1 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE0_1);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte0_2 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE0_2);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte1_0 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE1_0);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte1_1 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE1_1);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte1_2 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE1_2);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte2_0 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE2_0);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte2_1 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE2_1);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte2_2 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE2_2);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte3_0 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE3_0);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte3_1 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE3_1);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte3_2 = reg::Read(EMC0 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE3_2);
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte4_0 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE4_0) : 0;
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte4_1 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE4_1) : 0;
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte4_2 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE4_2) : 0;
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte5_0 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE5_0) : 0;
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte5_1 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE5_1) : 0;
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte5_2 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE5_2) : 0;
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte6_0 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE6_0) : 0;
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte6_1 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE6_1) : 0;
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte6_2 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE6_2) : 0;
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte7_0 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE7_0) : 0;
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte7_1 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE7_1) : 0;
dst_timing->trim_regs.emc_pmacro_ib_ddll_short_dq_rank1_byte7_2 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_IB_DDLL_SHORT_DQ_RANK1_BYTE7_2) : 0;
}
}
/* Save RD_VREF results. */
if (train_rd_vref) {
uint8_t ib_vref_dq_byte0_icr = (reg::Read(EMC + EMC_PMACRO_IB_VREF_DQ_0) & 0x7F) + (dst_timing->save_restore_mod_regs[0] & 0x7F);
if (dst_timing->save_restore_mod_regs[0] & 0x80000000)
ib_vref_dq_byte0_icr = (reg::Read(EMC + EMC_PMACRO_IB_VREF_DQ_0) & 0x7F) - (dst_timing->save_restore_mod_regs[0] & 0x7F);
uint8_t ib_vref_dq_byte1_icr = ((reg::Read(EMC + EMC_PMACRO_IB_VREF_DQ_0) >> 8) & 0x7F) + (dst_timing->save_restore_mod_regs[1] & 0x7F);
if (dst_timing->save_restore_mod_regs[1] & 0x80000000)
ib_vref_dq_byte1_icr = ((reg::Read(EMC + EMC_PMACRO_IB_VREF_DQ_0) >> 8) & 0x7F) - (dst_timing->save_restore_mod_regs[1] & 0x7F);
uint8_t ib_vref_dq_byte2_icr = ((reg::Read(EMC + EMC_PMACRO_IB_VREF_DQ_0) >> 16) & 0x7F) + (dst_timing->save_restore_mod_regs[2] & 0x7F);
if (dst_timing->save_restore_mod_regs[2] & 0x80000000)
ib_vref_dq_byte2_icr = ((reg::Read(EMC + EMC_PMACRO_IB_VREF_DQ_0) >> 16) & 0x7F) - (dst_timing->save_restore_mod_regs[2] & 0x7F);
uint8_t ib_vref_dq_byte3_icr = ((reg::Read(EMC + EMC_PMACRO_IB_VREF_DQ_0) >> 24) & 0x7F) + (dst_timing->save_restore_mod_regs[3] & 0x7F);
if (dst_timing->save_restore_mod_regs[3] & 0x80000000)
ib_vref_dq_byte3_icr = ((reg::Read(EMC + EMC_PMACRO_IB_VREF_DQ_0) >> 24) & 0x7F) - (dst_timing->save_restore_mod_regs[3] & 0x7F);
dst_timing->trim_regs.emc_pmacro_ib_vref_dq_0 = ((ib_vref_dq_byte0_icr & 0x7F) | (ib_vref_dq_byte1_icr & 0x7F) << 8) | ((ib_vref_dq_byte2_icr & 0x7F) << 16) | ((ib_vref_dq_byte3_icr & 0x7F) << 24);
uint8_t ib_vref_dq_byte4_icr = (reg::Read(EMC + EMC_PMACRO_IB_VREF_DQ_1) & 0x7F) + (dst_timing->save_restore_mod_regs[4] & 0x7F);
if (dst_timing->save_restore_mod_regs[4] & 0x80000000)
ib_vref_dq_byte4_icr = (reg::Read(EMC + EMC_PMACRO_IB_VREF_DQ_1) & 0x7F) - (dst_timing->save_restore_mod_regs[4] & 0x7F);
uint8_t ib_vref_dq_byte5_icr = ((reg::Read(EMC + EMC_PMACRO_IB_VREF_DQ_1) >> 8) & 0x7F) + (dst_timing->save_restore_mod_regs[5] & 0x7F);
if (dst_timing->save_restore_mod_regs[5] & 0x80000000)
ib_vref_dq_byte5_icr = ((reg::Read(EMC + EMC_PMACRO_IB_VREF_DQ_1) >> 8) & 0x7F) - (dst_timing->save_restore_mod_regs[5] & 0x7F);
uint8_t ib_vref_dq_byte6_icr = ((reg::Read(EMC + EMC_PMACRO_IB_VREF_DQ_1) >> 16) & 0x7F) + (dst_timing->save_restore_mod_regs[6] & 0x7F);
if (dst_timing->save_restore_mod_regs[6] & 0x80000000)
ib_vref_dq_byte6_icr = ((reg::Read(EMC + EMC_PMACRO_IB_VREF_DQ_1) >> 16) & 0x7F) - (dst_timing->save_restore_mod_regs[6] & 0x7F);
uint8_t ib_vref_dq_byte7_icr = ((reg::Read(EMC + EMC_PMACRO_IB_VREF_DQ_1) >> 24) & 0x7F) + (dst_timing->save_restore_mod_regs[7] & 0x7F);
if (dst_timing->save_restore_mod_regs[7] & 0x80000000)
ib_vref_dq_byte7_icr = ((reg::Read(EMC + EMC_PMACRO_IB_VREF_DQ_1) >> 24) & 0x7F) - (dst_timing->save_restore_mod_regs[7] & 0x7F);
dst_timing->trim_regs.emc_pmacro_ib_vref_dq_1 = ((ib_vref_dq_byte4_icr & 0x7F) | (ib_vref_dq_byte5_icr & 0x7F) << 8) | ((ib_vref_dq_byte6_icr & 0x7F) << 16) | ((ib_vref_dq_byte7_icr & 0x7F) << 24);
}
}
/* Save WR results. */
if (train_wr) {
dst_timing->trim_perch_regs.emc0_data_brlshft_0 = reg::Read(EMC0 + EMC_DATA_BRLSHFT_0);
dst_timing->trim_perch_regs.emc1_data_brlshft_0 = dual_channel ? reg::Read(EMC1 + EMC_DATA_BRLSHFT_0) : 0;
if (dram_dev_num == TWO_RANK) {
dst_timing->trim_perch_regs.emc0_data_brlshft_1 = reg::Read(EMC0 + EMC_DATA_BRLSHFT_1);
dst_timing->trim_perch_regs.emc1_data_brlshft_1 = dual_channel ? reg::Read(EMC1 + EMC_DATA_BRLSHFT_1) : 0;
}
dst_timing->trim_regs.emc_pmacro_ob_ddll_long_dq_rank0_0 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_0);
dst_timing->trim_regs.emc_pmacro_ob_ddll_long_dq_rank0_1 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_1);
dst_timing->trim_regs.emc_pmacro_ob_ddll_long_dq_rank0_2 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_2) : 0;
dst_timing->trim_regs.emc_pmacro_ob_ddll_long_dq_rank0_3 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_3) : 0;
if (dram_dev_num == TWO_RANK) {
dst_timing->trim_regs.emc_pmacro_ob_ddll_long_dq_rank1_0 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_0);
dst_timing->trim_regs.emc_pmacro_ob_ddll_long_dq_rank1_1 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_1);
dst_timing->trim_regs.emc_pmacro_ob_ddll_long_dq_rank1_2 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_2) : 0;
dst_timing->trim_regs.emc_pmacro_ob_ddll_long_dq_rank1_3 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_3) : 0;
}
if (train_bit_level) {
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte0_0 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE0_0);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte0_1 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE0_1);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte0_2 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE0_2);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte1_0 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE1_0);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte1_1 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE1_1);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte1_2 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE1_2);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte2_0 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE2_0);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte2_1 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE2_1);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte2_2 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE2_2);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte3_0 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE3_0);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte3_1 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE3_1);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte3_2 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE3_2);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte4_0 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE4_0) : 0;
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte4_1 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE4_1) : 0;
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte4_2 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE4_2) : 0;
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte5_0 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE5_0) : 0;
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte5_1 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE5_1) : 0;
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte5_2 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE5_2) : 0;
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte6_0 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE6_0) : 0;
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte6_1 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE6_1) : 0;
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte6_2 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE6_2) : 0;
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte7_0 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE7_0) : 0;
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte7_1 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE7_1) : 0;
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank0_byte7_2 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK0_BYTE7_2) : 0;
if (dram_dev_num == TWO_RANK) {
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte0_0 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE0_0);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte0_1 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE0_1);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte0_2 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE0_2);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte1_0 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE1_0);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte1_1 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE1_1);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte1_2 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE1_2);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte2_0 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE2_0);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte2_1 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE2_1);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte2_2 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE2_2);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte3_0 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE3_0);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte3_1 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE3_1);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte3_2 = reg::Read(EMC0 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE3_2);
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte4_0 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE4_0) : 0;
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte4_1 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE4_1) : 0;
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte4_2 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE4_2) : 0;
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte5_0 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE5_0) : 0;
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte5_1 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE5_1) : 0;
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte5_2 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE5_2) : 0;
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte6_0 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE6_0) : 0;
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte6_1 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE6_1) : 0;
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte6_2 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE6_2) : 0;
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte7_0 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE7_0) : 0;
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte7_1 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE7_1) : 0;
dst_timing->trim_regs.emc_pmacro_ob_ddll_short_dq_rank1_byte7_2 = dual_channel ? reg::Read(EMC1 + EMC_PMACRO_OB_DDLL_SHORT_DQ_RANK1_BYTE7_2) : 0;
}
}
/* Save WR_VREF results. */
if (train_wr_vref) {
uint32_t emc1_ranks_sub_partitions = dual_channel ? reg::Read(EMC1 + EMC_TRAINING_OPT_DQ_OB_VREF) : 0;
uint8_t emc0_ib_vref_dq_byte8_modded_plus = dst_timing->save_restore_mod_regs[8] + reg::Read(EMC0 + EMC_TRAINING_OPT_DQ_OB_VREF);
if (dst_timing->save_restore_mod_regs[8] & 0x80000000)
emc0_ib_vref_dq_byte8_modded_plus = reg::Read(EMC0 + EMC_TRAINING_OPT_DQ_OB_VREF) - dst_timing->save_restore_mod_regs[8];
uint8_t emc0_mrw12_op_sp1 = ((reg::Read(EMC0 + EMC_TRAINING_OPT_DQ_OB_VREF) & 0xFFFF) >> 8) + dst_timing->save_restore_mod_regs[9];
if (dst_timing->save_restore_mod_regs[9] & 0x80000000)
emc0_mrw12_op_sp1 = ((reg::Read(EMC0 + EMC_TRAINING_OPT_DQ_OB_VREF) & 0xFFFF) >> 8) - dst_timing->save_restore_mod_regs[9];
uint8_t emc0_mrw13_op_sp0 = ((reg::Read(EMC0 + EMC_TRAINING_OPT_DQ_OB_VREF) >> 16) & 0xFF) + dst_timing->save_restore_mod_regs[8];
if (dst_timing->save_restore_mod_regs[8] & 0x80000000)
emc0_mrw13_op_sp0 = ((reg::Read(EMC0 + EMC_TRAINING_OPT_DQ_OB_VREF) >> 16) & 0xFF) - dst_timing->save_restore_mod_regs[8];
uint8_t emc0_ib_vref_dq_byte9_modded_a_plus = dst_timing->save_restore_mod_regs[9] + (reg::Read(EMC0 + EMC_TRAINING_OPT_DQ_OB_VREF) >> 24);
if (dst_timing->save_restore_mod_regs[9] & 0x80000000)
emc0_ib_vref_dq_byte9_modded_a_plus = (reg::Read(EMC0 + EMC_TRAINING_OPT_DQ_OB_VREF) >> 24) - (uint8_t)dst_timing->save_restore_mod_regs[9];
uint8_t emc0_ib_vref_dq_byte10_modded_plus = emc1_ranks_sub_partitions + dst_timing->save_restore_mod_regs[10];
if (dst_timing->save_restore_mod_regs[10] & 0x80000000)
emc0_ib_vref_dq_byte10_modded_plus = emc1_ranks_sub_partitions - dst_timing->save_restore_mod_regs[10];
uint8_t emc0_ib_vref_dq_byte11_modded_plus = ((emc1_ranks_sub_partitions & 0xFFFF) >> 8) + dst_timing->save_restore_mod_regs[11];
if (dst_timing->save_restore_mod_regs[11] & 0x80000000)
emc0_ib_vref_dq_byte11_modded_plus = ((emc1_ranks_sub_partitions & 0xFFFF) >> 8) - dst_timing->save_restore_mod_regs[11];
uint8_t emc1_mrw13_op_sp0 = ((emc1_ranks_sub_partitions >> 16) & 0xFF) + dst_timing->save_restore_mod_regs[10];
if (dst_timing->save_restore_mod_regs[10] & 0x80000000)
emc1_mrw13_op_sp0 = ((emc1_ranks_sub_partitions >> 16) & 0xFF) - dst_timing->save_restore_mod_regs[10];
uint8_t emc1_mrw13_op_sp1 = (emc1_ranks_sub_partitions >> 24) + dst_timing->save_restore_mod_regs[11];
if (dst_timing->save_restore_mod_regs[11] & 0x80000000)
emc1_mrw13_op_sp1 = (emc1_ranks_sub_partitions >> 24) - dst_timing->save_restore_mod_regs[11];
dst_timing->burst_perch_regs.emc1_mrw12 = (uint8_t)emc0_ib_vref_dq_byte10_modded_plus | 0x880E0000 | (emc0_ib_vref_dq_byte11_modded_plus << 8);
dst_timing->burst_perch_regs.emc0_mrw12 = emc0_ib_vref_dq_byte8_modded_plus | 0x880E0000 | (emc0_mrw12_op_sp1 << 8);
if (dram_dev_num == TWO_RANK) {
dst_timing->burst_perch_regs.emc0_mrw13 = emc0_ib_vref_dq_byte9_modded_a_plus << 8 | emc0_mrw13_op_sp0 | 0x480E0000;
dst_timing->burst_perch_regs.emc1_mrw13 = (emc1_mrw13_op_sp1 << 8) | emc1_mrw13_op_sp0 | 0x480E0000;
} else {
dst_timing->burst_perch_regs.emc0_mrw13 = emc0_ib_vref_dq_byte9_modded_a_plus << 8 | emc0_mrw13_op_sp0 | 0xC80E0000;
dst_timing->burst_perch_regs.emc1_mrw13 = (emc1_mrw13_op_sp1 << 8) | emc1_mrw13_op_sp0 | 0xC80E0000;
}
}
}
reg::Write(EMC + EMC_DBG, emc_dbg_tmp);
}
/* Step 25:
* Program MC updown registers.
*/
if ((dst_timing->rate_khz > src_timing->rate_khz) && !training_enabled) {
for (u32 i = 0; i < dst_timing->num_up_down; i++) {
reg::Write(LaScaleRegisters[i], dst_timing->la_scale_regs_arr[i]);
}
/* Request a timing update. */
TimingUpdate(fbio_cfg7);
}
/* Step 26:
* Restore ZCAL registers.
*/
if (dram_type == DRAM_TYPE_LPDDR4) {
SetShadowBypass(ACTIVE);
reg::Write(EMC + EMC_ZCAL_WAIT_CNT, dst_timing->burst_regs.emc_zcal_wait_cnt);
reg::Write(EMC + EMC_ZCAL_INTERVAL, dst_timing->burst_regs.emc_zcal_interval);
SetShadowBypass(ASSEMBLY);
}
if ((dram_type != DRAM_TYPE_LPDDR4)
&& opt_zcal_en_cc
&& !opt_short_zcal
&& opt_cc_short_zcal)
{
util::WaitMicroSeconds(2);
SetShadowBypass(ACTIVE);
if (dram_type == DRAM_TYPE_LPDDR2) {
reg::Write(EMC + EMC_MRS_WAIT_CNT, dst_timing->burst_regs.emc_mrs_wait_cnt);
} else if (dram_type == DRAM_TYPE_DDR4) {
reg::Write(EMC + EMC_ZCAL_WAIT_CNT, dst_timing->burst_regs.emc_zcal_wait_cnt);
}
SetShadowBypass(ASSEMBLY);
}
/* Step 27:
* Restore EMC_CFG, FDPD registers.
*/
SetShadowBypass(ACTIVE);
reg::Write(EMC + EMC_CFG, dst_timing->burst_regs.emc_cfg);
SetShadowBypass(ASSEMBLY);
reg::Write(EMC + EMC_FDPD_CTRL_CMD_NO_RAMP, dst_timing->emc_fdpd_ctrl_cmd_no_ramp);
reg::Write(EMC + EMC_SEL_DPD_CTRL, dst_timing->emc_sel_dpd_ctrl);
/* Step 28:
* Training recover.
*/
if (training_enabled && (dram_type == DRAM_TYPE_LPDDR4)) {
SetShadowBypass(ACTIVE);
reg::Write(EMC + EMC_CFG, dst_timing->burst_regs.emc_cfg);
reg::Write(EMC + EMC_SEL_DPD_CTRL, dst_timing->emc_sel_dpd_ctrl);
reg::Write(EMC + EMC_ZCAL_WAIT_CNT, src_timing->burst_regs.emc_zcal_wait_cnt);
reg::Write(EMC + EMC_ZCAL_INTERVAL, src_timing->burst_regs.emc_zcal_interval);
reg::Write(EMC + EMC_AUTO_CAL_CONFIG2, src_timing->emc_auto_cal_config2);
reg::Write(EMC + EMC_AUTO_CAL_CONFIG3, src_timing->emc_auto_cal_config3);
reg::Write(EMC + EMC_AUTO_CAL_CONFIG4, src_timing->emc_auto_cal_config4);
reg::Write(EMC + EMC_AUTO_CAL_CONFIG5, src_timing->emc_auto_cal_config5);
reg::Write(EMC + EMC_AUTO_CAL_CONFIG6, src_timing->emc_auto_cal_config6);
reg::Write(EMC + EMC_AUTO_CAL_CONFIG7, src_timing->emc_auto_cal_config7);
reg::Write(EMC + EMC_AUTO_CAL_CONFIG8, src_timing->emc_auto_cal_config8);
SetShadowBypass(ASSEMBLY);
reg::Write(EMC + EMC_TR_DVFS, dst_timing->burst_regs.emc_tr_dvfs & ~(1 << 0));
}
SetShadowBypass(ACTIVE);
reg::Write(EMC + EMC_PMACRO_AUTOCAL_CFG_COMMON, dst_timing->burst_regs.emc_pmacro_autocal_cfg_common);
SetShadowBypass(ASSEMBLY);
/* Step 29:
* Power fix WAR.
*/
reg::Write(EMC + EMC_PMACRO_CFG_PM_GLOBAL_0, 0xFF0000);
reg::Write(EMC + EMC_PMACRO_TRAINING_CTRL_0, 0x8);
reg::Write(EMC + EMC_PMACRO_TRAINING_CTRL_1, 0x8);
reg::Write(EMC + EMC_PMACRO_CFG_PM_GLOBAL_0, 0);
/* Step 30:
* Re-enable autocal.
*/
if (training_enabled) {
emc_auto_cal_config = src_timing->emc_auto_cal_config;
/* Restore FSP to account for switch back. Only needed in training. */
g_fsp_for_next_freq = !g_fsp_for_next_freq;
} else {
emc_auto_cal_config = dst_timing->emc_auto_cal_config;
if (dst_timing->burst_regs.emc_cfg_dig_dll & 0x1) {
DllEnableStall(fbio_cfg7);
}
}
reg::Write(EMC + EMC_AUTO_CAL_CONFIG, emc_auto_cal_config);
}
void CleanupActiveShadowCopy(EmcDvfsTimingTable *src_timing, EmcDvfsTimingTable *dst_timing) {
const int dram_type = reg::GetValue(EMC + EMC_FBIO_CFG5, EMC_REG_BITS_MASK(FBIO_CFG5_DRAM_TYPE));
const u32 fbio_cfg7 = reg::Read(EMC + EMC_FBIO_CFG7);
/* Change CFG_SWAP to ASSEMBLY_ONLY */
uint32_t emc_dbg = reg::Read(EMC + EMC_DBG);
emc_dbg = ((emc_dbg & 0xF3FFFFFF) | 0x8000000);
reg::Write(EMC + EMC_DBG, emc_dbg);
/* Change UPDATE_AUTO_CAL_IN_UPDATE to ALWAYS */
uint32_t emc_cfg_update = reg::Read(EMC + EMC_CFG_UPDATE);
emc_cfg_update = ((emc_cfg_update & 0xFFFFFFF9) | 0x04);
reg::Write(EMC + EMC_CFG_UPDATE, emc_cfg_update);
/* Request a timing update event */
TimingUpdate(fbio_cfg7);
/* Change UPDATE_AUTO_CAL_IN_UPDATE to NEVER */
emc_cfg_update = reg::Read(EMC + EMC_CFG_UPDATE);
emc_cfg_update &= 0xFFFFFFF9;
reg::Write(EMC + EMC_CFG_UPDATE, emc_cfg_update);
/* Change CFG_SWAP to ACTIVE_ONLY */
emc_dbg = reg::Read(EMC + EMC_DBG);
emc_dbg &= 0xF3FFFFFF;
reg::Write(EMC + EMC_DBG, emc_dbg);
/* Disable DLL and change CFG_DLL_MODE to RUN_PERIODIC */
uint32_t emc_cfg_dig_dll = reg::Read(EMC + EMC_CFG_DIG_DLL);
emc_cfg_dig_dll = ((emc_cfg_dig_dll & 0xFFFFFF3E) | 0x80);
reg::Write(EMC + EMC_CFG_DIG_DLL, emc_cfg_dig_dll);
/* Request a timing update event */
TimingUpdate(fbio_cfg7);
/* Disable or enable DLL */
emc_cfg_dig_dll = reg::Read(EMC + EMC_CFG_DIG_DLL);
if (dst_timing->burst_regs.emc_cfg_dig_dll == 0x01) {
emc_cfg_dig_dll |= 0x01;
} else {
emc_cfg_dig_dll &= 0xFFFFFFFE;
}
/* Change CFG_DLL_MODE to RUN_PERIODIC */
emc_cfg_dig_dll = ((emc_cfg_dig_dll & 0xFFFFFF3F) | 0x80);
reg::Write(EMC + EMC_CFG_DIG_DLL, emc_cfg_dig_dll);
/* Request a timing update event */
TimingUpdate(fbio_cfg7);
/* Wait for DLL_LOCK to be set */
uint32_t emc_dig_dll_status = 0;
do {
emc_dig_dll_status = reg::Read(EMC + EMC_DIG_DLL_STATUS);
} while (!(emc_dig_dll_status & (1 << 15)));
/* Check if DRAM is LPDDR4 */
if (dram_type == DRAM_TYPE_LPDDR4) {
reg::Write(EMC + EMC_RP, src_timing->burst_regs.emc_rp);
reg::Write(EMC + EMC_R2P, src_timing->burst_regs.emc_r2p);
reg::Write(EMC + EMC_W2P, src_timing->burst_regs.emc_w2p);
reg::Write(EMC + EMC_TRPAB, src_timing->burst_regs.emc_trpab);
}
/* Request a timing update event */
TimingUpdate(fbio_cfg7);
}
void TrainFreq(EmcDvfsTimingTable *src_timing, EmcDvfsTimingTable *dst_timing, u32 next_clk_src) {
/* Get dram dev num. */
const u32 dram_dev_num = (reg::Read(MC + MC_EMEM_ADR_CFG) & 1) + 1;
/* Write RAM patterns, if first training. */
if (!g_did_first_training) {
const auto * const pattern = GetEmcRamTrainingPattern();
for (u32 i = 0; i < 0x100; ++i) {
reg::Write(EMC + EMC_TRAINING_PATRAM_DQ, pattern[dst_timing->training_pattern].dq[i]);
reg::Write(EMC + EMC_TRAINING_PATRAM_DMI, pattern[dst_timing->training_pattern].dmi[i]);
reg::Write(EMC + EMC_TRAINING_PATRAM_CTRL, 0x80000000 | i);
}
g_did_first_training = true;
}
/* Do training, if we need to. */
const u32 needed_training = dst_timing->needs_training;
if (needed_training && !dst_timing->trained) {
/* Determine what training to do. */
u32 training_params[8];
u32 num_params = 0;
if (needed_training & (CA_TRAINING | CA_VREF_TRAINING)) {
training_params[num_params++] = (needed_training & (CA_TRAINING | CA_VREF_TRAINING | BIT_LEVEL_TRAINING));
}
if (dram_dev_num == TWO_RANK) {
if (needed_training & (CA_TRAINING | CA_VREF_TRAINING)) {
training_params[num_params++] = (needed_training & (CA_TRAINING | CA_VREF_TRAINING | TRAIN_SECOND_RANK | BIT_LEVEL_TRAINING));
}
if (needed_training & (QUSE_TRAINING | QUSE_VREF_TRAINING)) {
training_params[num_params++] = (needed_training & (QUSE_TRAINING | QUSE_VREF_TRAINING | BIT_LEVEL_TRAINING));
training_params[num_params++] = (needed_training & (QUSE_TRAINING | BIT_LEVEL_TRAINING));
}
} else {
if (needed_training & (QUSE_TRAINING | QUSE_VREF_TRAINING)) {
training_params[num_params++] = (needed_training & (QUSE_TRAINING | QUSE_VREF_TRAINING | BIT_LEVEL_TRAINING));
}
}
if (needed_training & (WRITE_TRAINING | WRITE_VREF_TRAINING | READ_TRAINING | READ_VREF_TRAINING)) {
training_params[num_params++] = (needed_training & (WRITE_TRAINING | WRITE_VREF_TRAINING | READ_TRAINING | READ_VREF_TRAINING | BIT_LEVEL_TRAINING));
}
/* Apply all training. */
for (u32 i = 0; i < num_params; ++i) {
FreqChange(src_timing, dst_timing, training_params[i], next_clk_src);
CleanupActiveShadowCopy(src_timing, dst_timing);
}
/* Set tables as trained. */
dst_timing->trained = 1;
}
}
constexpr inline const u16 PeriodicCompensationRegisters[] = {
EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_0,
EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_1,
EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_2,
EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_3,
EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_0,
EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_1,
EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_2,
EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_3,
EMC_DATA_BRLSHFT_0,
EMC_DATA_BRLSHFT_1
};
void PeriodicCompensationRoutine(EmcDvfsTimingTable *timing) {
if (timing->periodic_training) {
const int dram_dev_num = (reg::Read(MC + MC_EMEM_ADR_CFG) & 1) + 1;
const u32 fbio_cfg7 = timing->burst_regs.emc_fbio_cfg7;
uint32_t emc_cfg_o = reg::Read(EMC + EMC_CFG);
uint32_t emc_cfg_dig_dll_o = reg::Read(EMC + EMC_CFG_DIG_DLL);
uint32_t emc_cfg_update_o = reg::Read(EMC + EMC_CFG_UPDATE);
/*
* 1. Power optimizations should be off.
*/
reg::Write(EMC + EMC_CFG_DIG_DLL, emc_cfg_dig_dll_o & 0xFFFFFFFE);
reg::Write(EMC + EMC_CFG_UPDATE, (emc_cfg_update_o & 0xFFFFF9FF) | 0x400);
reg::Write(EMC + EMC_CFG, emc_cfg_o & 0x0FFFFFFF);
/* Do timing update. */
TimingUpdate(fbio_cfg7);
if (dram_dev_num == TWO_RANK) {
WaitForUpdate(EMC_EMC_STATUS, 0x30, false, fbio_cfg7);
} else {
WaitForUpdate(EMC_EMC_STATUS, 0x10, false, fbio_cfg7);
}
WaitForUpdate(EMC_EMC_STATUS, 0x300, false, fbio_cfg7);
WaitForUpdate(EMC_EMC_STATUS, 0x01, false, fbio_cfg7);
/*
* 2. osc kick off - this assumes training and dvfs have set
* correct MR23.
*/
StartPeriodicCompensation();
/*
* 3. Let dram capture its clock tree delays.
*/
util::WaitMicroSeconds(2 + ((ActualOscClocks(timing->run_clocks) * 1000) / timing->rate_khz));
/*
* 4. Check delta wrt previous values (save value if margin
* exceeds what is set in table).
*/
uint32_t del = UpdateClockTreeDelay(timing, timing, dram_dev_num, fbio_cfg7, PERIODIC_TRAINING_UPDATE);
/*
* 5. Apply compensation w.r.t. trained values (if clock tree
* has drifted more than the set margin).
*/
if (timing->tree_margin < ((del * 128 * (timing->rate_khz / 1000)) / 1000000)) {
for (u32 i = 0; i < util::size(PeriodicCompensationRegisters); ++i) {
reg::Write(EMC + PeriodicCompensationRegisters[i], ApplyPeriodicCompensationTrimmer(timing, PeriodicCompensationRegisters[i]));
}
}
/* Restore register values. */
reg::Write(EMC + EMC_CFG, emc_cfg_o);
reg::Write(EMC + EMC_CFG_DIG_DLL, emc_cfg_dig_dll_o);
reg::Write(EMC + EMC_TIMING_CONTROL, 1);
reg::Write(EMC + EMC_CFG_UPDATE, emc_cfg_update_o);
}
}
void Dvfs(EmcDvfsTimingTable *dst_timing, EmcDvfsTimingTable *src_timing, bool train) {
/* Get the old 2x clock source. */
const u32 prev_2x_clk_src = reg::GetValue(CLKRST + CLK_RST_CONTROLLER_CLK_SOURCE_EMC, CLK_RST_REG_BITS_MASK(CLK_SOURCE_EMC_EMC_2X_CLK_SRC));
/* Set g_next_pll. */
g_next_pll = prev_2x_clk_src == PLLMB_UD || prev_2x_clk_src == PLLMB_OUT0;
/* Reprogram pll. */
u32 next_clk_src;
if (PllReprogram(dst_timing->rate_khz, dst_timing->clk_src_emc, src_timing->rate_khz, src_timing->clk_src_emc)) {
if (prev_2x_clk_src == PLLMB_UD || prev_2x_clk_src == PLLMB_OUT0) {
g_next_pll = 0;
} else if (prev_2x_clk_src == PLLM_UD || prev_2x_clk_src == PLLM_OUT0) {
g_next_pll = !g_next_pll;
}
next_clk_src = ProgramPllm(dst_timing->rate_khz, dst_timing->clk_src_emc, g_next_pll);
} else {
next_clk_src = dst_timing->clk_src_emc;
const u32 next_2x_clk_src = reg::GetField(next_clk_src, CLK_RST_REG_BITS_MASK(CLK_SOURCE_EMC_EMC_2X_CLK_SRC));
if (next_2x_clk_src == PLLM_UD || next_2x_clk_src == PLLMB_UD) {
if (g_next_pll) {
reg::SetField(next_clk_src, CLK_RST_REG_BITS_VALUE(CLK_SOURCE_EMC_EMC_2X_CLK_SRC, PLLMB_UD));
}
} else if (next_2x_clk_src == PLLM_OUT0 || next_2x_clk_src == PLLMB_OUT0) {
if (g_next_pll) {
reg::SetField(next_clk_src, CLK_RST_REG_BITS_VALUE(CLK_SOURCE_EMC_EMC_2X_CLK_SRC, PLLMB_OUT0));
}
}
}
if (train) {
TrainFreq(src_timing, dst_timing, next_clk_src);
if (PllReprogram(dst_timing->rate_khz, dst_timing->clk_src_emc, src_timing->rate_khz, src_timing->clk_src_emc)) {
g_next_pll = !g_next_pll;
}
} else {
FreqChange(src_timing, dst_timing, 0, next_clk_src);
PeriodicCompensationRoutine(dst_timing);
}
}
}
void DoMemoryTrainingErista(int index, void *mtc_tables_buffer) {
/* Get timing tables. */
auto *timing_tables = GetEmcDvfsTimingTables(index, mtc_tables_buffer);
auto *timing_204 = timing_tables + 0;
auto *timing_800 = timing_tables + 1;
auto *timing_1600 = timing_tables + 2;
/* Check timing tables. */
if (timing_204->rate_khz != 204000 || timing_1600->rate_khz != 1600000) {
ShowFatalError("EmcDvfsTimingTables seem corrupted %" PRIu32 " %" PRIu32 " %" PRIu32 "?\n", timing_204->rate_khz, timing_800->rate_khz, timing_1600->rate_khz);
}
/* Check that we should do training. */
if (timing_204->clk_src_emc != reg::Read(CLKRST + CLK_RST_CONTROLLER_CLK_SOURCE_EMC)) {
/* Our clock source isn't what's expected, so presumably training has already been done? */
/* Either way, the safe bet is to skip it. */
return;
}
/* Train 800MHz. */
Dvfs(timing_800, timing_204, true);
/* Train 1600MHz. */
Dvfs(timing_1600, timing_204, true);
/* Switch to 800MHz. */
Dvfs(timing_800, timing_204, false);
/* Switch to 1600MHz. */
Dvfs(timing_1600, timing_800, false);
/* Wait 100ms. */
util::WaitMicroSeconds(100000);
/* Do Periodic compensation */
PeriodicCompensationRoutine(timing_1600);
}
}
| 154,050
|
C++
|
.cpp
| 2,409
| 45.830635
| 307
| 0.51324
|
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,318
|
fusee_sdram.cpp
|
Atmosphere-NX_Atmosphere/fusee/program/source/sdram/fusee_sdram.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 "fusee_sdram.hpp"
#include "../fusee_uncompress.hpp"
namespace ams::nxboot {
namespace {
template<fuse::SocType SocType>
struct SdramParamsImpl;
template<> struct SdramParamsImpl<fuse::SocType_Erista> { using Type = br::erista::BootSdramParams; };
template<> struct SdramParamsImpl<fuse::SocType_Mariko> { using Type = br::mariko::BootSdramParams; };
template<fuse::SocType SocType>
using BootSdramParams = SdramParamsImpl<SocType>::Type;
constexpr inline const uintptr_t CLKRST = secmon::MemoryRegionPhysicalDeviceClkRst.GetAddress();
constexpr inline const uintptr_t PMC = secmon::MemoryRegionPhysicalDevicePmc.GetAddress();
constexpr inline const uintptr_t APB = secmon::MemoryRegionPhysicalDeviceApbMisc.GetAddress();
constexpr inline const uintptr_t MC = secmon::MemoryRegionPhysicalDeviceMemoryController.GetAddress();
constexpr inline const uintptr_t EMC = EMC_ADDRESS(0);
constexpr inline const uintptr_t AHB = AHB_ARBC(0);
#include "fusee_sdram_params.inc"
#include "fusee_sdram_params_lp0_erista.inc"
#include "fusee_sdram_params_lp0_mariko.inc"
void *GetSdramParams(fuse::SocType soc_type) {
/* Get DRAM Id. */
const auto dram_id = fuse::GetDramId();
/* Extract to work buffer. */
void *sdram_params_work_buffer;
if (soc_type == fuse::SocType_Erista) {
sdram_params_work_buffer = reinterpret_cast<void *>(0x4003E000 - 2 * sizeof(BootSdramParams<fuse::SocType_Erista>));
#define HANDLE_DRAM_CASE(_DRAM_ID_, _INDEX_) \
case _DRAM_ID_: \
Uncompress(sdram_params_work_buffer, 2 * sizeof(BootSdramParams<fuse::SocType_Erista>), SdramParamsErista##_INDEX_, SdramParamsSizeErista##_INDEX_); \
if (_INDEX_ & 1) { \
sdram_params_work_buffer = reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(sdram_params_work_buffer) + sizeof(BootSdramParams<fuse::SocType_Erista>)); \
} \
break;
switch (dram_id) {
HANDLE_DRAM_CASE(0, 0)
HANDLE_DRAM_CASE(1, 1)
HANDLE_DRAM_CASE(2, 2)
HANDLE_DRAM_CASE(3, 3)
HANDLE_DRAM_CASE(4, 4)
HANDLE_DRAM_CASE(5, 5)
HANDLE_DRAM_CASE(6, 6)
default:
AMS_ABORT("Invalid DRAM id");
}
#undef HANDLE_DRAM_CASE
return static_cast<BootSdramParams<fuse::SocType_Erista> *>(sdram_params_work_buffer);
} else /* if (soc_type == fuse::SocType_Mariko) */ {
sdram_params_work_buffer = reinterpret_cast<void *>(0x4003E000 - 2 * sizeof(BootSdramParams<fuse::SocType_Mariko>));
#define HANDLE_DRAM_CASE(_DRAM_ID_, _INDEX_) \
case _DRAM_ID_: \
Uncompress(sdram_params_work_buffer, 2 * sizeof(BootSdramParams<fuse::SocType_Mariko>), SdramParamsMariko##_INDEX_, SdramParamsSizeMariko##_INDEX_); \
if (_INDEX_ & 1) { \
sdram_params_work_buffer = reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(sdram_params_work_buffer) + sizeof(BootSdramParams<fuse::SocType_Mariko>)); \
} \
break;
switch (dram_id) {
HANDLE_DRAM_CASE( 3, 12)
HANDLE_DRAM_CASE( 5, 12)
HANDLE_DRAM_CASE( 6, 12)
HANDLE_DRAM_CASE( 8, 1)
HANDLE_DRAM_CASE( 9, 2)
HANDLE_DRAM_CASE(10, 3)
HANDLE_DRAM_CASE(11, 4)
HANDLE_DRAM_CASE(12, 1)
HANDLE_DRAM_CASE(13, 2)
HANDLE_DRAM_CASE(14, 3)
HANDLE_DRAM_CASE(15, 4)
HANDLE_DRAM_CASE(17, 6)
HANDLE_DRAM_CASE(18, 7)
HANDLE_DRAM_CASE(19, 6)
HANDLE_DRAM_CASE(20, 10)
HANDLE_DRAM_CASE(21, 10)
HANDLE_DRAM_CASE(22, 10)
HANDLE_DRAM_CASE(23, 7)
HANDLE_DRAM_CASE(24, 6)
HANDLE_DRAM_CASE(25, 11)
HANDLE_DRAM_CASE(26, 11)
HANDLE_DRAM_CASE(27, 11)
HANDLE_DRAM_CASE(28, 7)
HANDLE_DRAM_CASE(29, 0)
HANDLE_DRAM_CASE(30, 0)
HANDLE_DRAM_CASE(31, 0)
HANDLE_DRAM_CASE(32, 5)
HANDLE_DRAM_CASE(33, 5)
HANDLE_DRAM_CASE(34, 5)
default:
AMS_ABORT("Invalid DRAM id");
}
#undef HANDLE_DRAM_CASE
return static_cast<BootSdramParams<fuse::SocType_Mariko> *>(sdram_params_work_buffer);
}
}
template<fuse::SocType SocType>
void SpareWrite(u32 reg, u32 value) {
if (reg) {
if constexpr (SocType == fuse::SocType_Erista) {
reg::Write(reinterpret_cast<volatile u32 *>(reg), value);
} else if constexpr (SocType == fuse::SocType_Mariko) {
/* TODO: Validate the write. */
reg::Write(reinterpret_cast<volatile u32 *>(reg), value);
}
}
}
template<fuse::SocType SocType>
void InitializeSdramImpl(BootSdramParams<SocType> *params) {
/* Perform initial soc-specific setup. */
if constexpr (SocType == fuse::SocType_Erista) {
/* Enable sel_dpd on unused pins. */
reg::Write(PMC + APBDEV_PMC_IO_DPD3_REQ, (((params->EmcPmcScratch1 & 0x3FFFFFFF) | 0x80000000) ^ 0xFFFF) & 0xC000FFFF);
util::WaitMicroSeconds(params->PmcIoDpd3ReqWait);
/* Disable e_dpd_vttgen. */
u32 dpd4 = (params->EmcPmcScratch2 & 0x3FFFFFFF) | 0x80000000;
reg::Write(PMC + APBDEV_PMC_IO_DPD4_REQ, (dpd4 ^ 0x3FFF0000) & 0xFFFF0000);
util::WaitMicroSeconds(params->PmcIoDpd4ReqWait);
/* Disable e_dpd_bg. */
reg::Write(PMC + APBDEV_PMC_IO_DPD4_REQ, (dpd4 ^ 0x0000FFFF) & 0xC000FFFF);
util::WaitMicroSeconds(params->PmcIoDpd4ReqWait);
reg::Write(PMC + APBDEV_PMC_WEAK_BIAS, 0);
util::WaitMicroSeconds(1);
/* Enable memory clock. */
{
/* Initialize pllm. */
{
reg::Write(CLKRST + CLK_RST_CONTROLLER_PLLM_MISC1, params->PllMSetupControl);
reg::Write(CLKRST + CLK_RST_CONTROLLER_PLLM_MISC2, 0);
reg::Write(CLKRST + CLK_RST_CONTROLLER_PLLM_BASE, CLK_RST_REG_BITS_ENUM (PLLM_BASE_PLLM_ENABLE, DISABLE),
CLK_RST_REG_BITS_VALUE(PLLM_BASE_PLLM_DIVP, params->PllMPostDivider),
CLK_RST_REG_BITS_VALUE(PLLM_BASE_PLLM_DIVN, params->PllMFeedbackDivider),
CLK_RST_REG_BITS_VALUE(PLLM_BASE_PLLM_DIVM, params->PllMInputDivider));
reg::Write(CLKRST + CLK_RST_CONTROLLER_PLLM_BASE, CLK_RST_REG_BITS_ENUM (PLLM_BASE_PLLM_ENABLE, ENABLE),
CLK_RST_REG_BITS_VALUE(PLLM_BASE_PLLM_DIVP, params->PllMPostDivider),
CLK_RST_REG_BITS_VALUE(PLLM_BASE_PLLM_DIVN, params->PllMFeedbackDivider),
CLK_RST_REG_BITS_VALUE(PLLM_BASE_PLLM_DIVM, params->PllMInputDivider));
/* Wait 300us for stability. */
const auto stable_time = util::GetMicroSeconds() + 300;
while (true) {
if (reg::HasValue(CLKRST + CLK_RST_CONTROLLER_PLLM_BASE, CLK_RST_REG_BITS_ENUM(PLLM_BASE_PLLM_LOCK, LOCK))) {
util::WaitMicroSeconds(10);
break;
}
if (util::GetMicroSeconds() >= stable_time) {
break;
}
}
}
/* Set CLK_SOURCE_EMC, using McEmcmArbMisc0 as MC_EMC_SAME_FREQ. */
reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_SOURCE_EMC, (params->EmcClockSource & ~0x10000) | ((params->McEmemArbMisc0 >> 11) & 0x10000));
if (params->EmcClockSourceDll) {
reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_SOURCE_EMC_DLL, params->EmcClockSourceDll);
}
if (params->ClearClk2Mc1) {
reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_ENB_W_CLR, CLK_RST_REG_BITS_ENUM(CLK_ENB_W_CLK_ENB_MC1, ENABLE));
}
/* Enable EMC/Mem. */
reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_ENB_H_SET, CLK_RST_REG_BITS_ENUM(CLK_ENB_H_CLK_ENB_EMC, ENABLE),
CLK_RST_REG_BITS_ENUM(CLK_ENB_H_CLK_ENB_MEM, ENABLE));
/* Enable EMC DLL. */
reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_ENB_X_SET, CLK_RST_REG_BITS_ENUM(CLK_ENB_X_CLK_ENB_EMC_DLL, ENABLE));
}
/* Clear reset for MEM/EMC. */
reg::Write(CLKRST + CLK_RST_CONTROLLER_RST_DEV_H_CLR, CLK_RST_REG_BITS_ENUM(RST_DEV_H_EMC_RST, ENABLE),
CLK_RST_REG_BITS_ENUM(RST_DEV_H_MEM_RST, ENABLE));
/* Set pad macros. */
reg::Write(EMC + EMC_PMACRO_VTTGEN_CTRL_0, params->EmcPmacroVttgenCtrl0);
reg::Write(EMC + EMC_PMACRO_VTTGEN_CTRL_1, params->EmcPmacroVttgenCtrl1);
reg::Write(EMC + EMC_PMACRO_VTTGEN_CTRL_2, params->EmcPmacroVttgenCtrl2);
reg::Write(EMC + EMC_TIMING_CONTROL, 1);
util::WaitMicroSeconds(1);
/* Select EMC write mux. */
reg::Write(EMC + EMC_DBG, params->EmcDbg | reg::EncodeValue(EMC_REG_BITS_VALUE(DBG_WRITE_MUX, params->EmcDbgWriteMux)));
/* Patch 2. */
SpareWrite<SocType>(params->EmcBctSpare2, params->EmcBctSpare3);
} else if constexpr (SocType == fuse::SocType_Mariko) {
/* Patch 1 */
SpareWrite<SocType>(params->EmcBctSpare0, params->EmcBctSpare1);
if (params->ClkRstControllerPllmMisc2OverrideEnable) {
reg::Write(CLKRST + CLK_RST_CONTROLLER_PLLM_MISC2, params->ClkRstControllerPllmMisc2Override);
}
/* Enable sel_dpd on unused pins. */
{
u32 val = (~params->EmcPmcScratch1 & 0x00000FFF) << 18;
val |= ((~params->EmcPmcScratch1 & 0x00001000) << 19) | ((~params->EmcPmcScratch1 & 0x00008000) << 15);
reg::Write(PMC + APBDEV_PMC_WEAK_BIAS, val);
}
reg::Write(PMC + APBDEV_PMC_IO_DPD3_REQ, 0x80000000 | (~params->EmcPmcScratch1 & 0x00009FFF));
util::WaitMicroSeconds(params->PmcIoDpd3ReqWait);
/* Disable e_dpd_vttgen. */
reg::Write(PMC + APBDEV_PMC_IO_DPD4_REQ, 0x80000000 | (~params->EmcPmcScratch2 & 0x3FFF0000));
util::WaitMicroSeconds(params->PmcIoDpd4ReqWait);
/* Disable e_dpd_bg. */
reg::Write(PMC + APBDEV_PMC_IO_DPD4_REQ, 0x80000000 | (~params->EmcPmcScratch2 & 0x00001FFF));
util::WaitMicroSeconds(1);
}
/* Common phase 1. */
/* Program CMD mapping. */
reg::Write(EMC + EMC_FBIO_CFG7, params->EmcFbioCfg7);
reg::Write(EMC + EMC_CMD_MAPPING_CMD0_0, params->EmcCmdMappingCmd0_0);
reg::Write(EMC + EMC_CMD_MAPPING_CMD0_1, params->EmcCmdMappingCmd0_1);
reg::Write(EMC + EMC_CMD_MAPPING_CMD0_2, params->EmcCmdMappingCmd0_2);
reg::Write(EMC + EMC_CMD_MAPPING_CMD1_0, params->EmcCmdMappingCmd1_0);
reg::Write(EMC + EMC_CMD_MAPPING_CMD1_1, params->EmcCmdMappingCmd1_1);
reg::Write(EMC + EMC_CMD_MAPPING_CMD1_2, params->EmcCmdMappingCmd1_2);
reg::Write(EMC + EMC_CMD_MAPPING_CMD2_0, params->EmcCmdMappingCmd2_0);
reg::Write(EMC + EMC_CMD_MAPPING_CMD2_1, params->EmcCmdMappingCmd2_1);
reg::Write(EMC + EMC_CMD_MAPPING_CMD2_2, params->EmcCmdMappingCmd2_2);
reg::Write(EMC + EMC_CMD_MAPPING_CMD3_0, params->EmcCmdMappingCmd3_0);
reg::Write(EMC + EMC_CMD_MAPPING_CMD3_1, params->EmcCmdMappingCmd3_1);
reg::Write(EMC + EMC_CMD_MAPPING_CMD3_2, params->EmcCmdMappingCmd3_2);
reg::Write(EMC + EMC_CMD_MAPPING_BYTE, params->EmcCmdMappingByte);
/* Program brick mapping. */
reg::Write(EMC + EMC_PMACRO_BRICK_MAPPING_0, params->EmcPmacroBrickMapping0);
reg::Write(EMC + EMC_PMACRO_BRICK_MAPPING_1, params->EmcPmacroBrickMapping1);
reg::Write(EMC + EMC_PMACRO_BRICK_MAPPING_2, params->EmcPmacroBrickMapping2);
/* Specific phase 2. */
if constexpr (SocType == fuse::SocType_Erista) {
reg::Write(EMC + EMC_PMACRO_BRICK_CTRL_RFU1, (params->EmcPmacroBrickCtrlRfu1 | ~0x01120112) & 0x1FFF1FFF);
} else if constexpr (SocType == fuse::SocType_Mariko) {
/* Set pad macros. */
reg::Write(EMC + EMC_PMACRO_VTTGEN_CTRL_0, params->EmcPmacroVttgenCtrl0);
reg::Write(EMC + EMC_PMACRO_VTTGEN_CTRL_1, params->EmcPmacroVttgenCtrl1);
reg::Write(EMC + EMC_PMACRO_VTTGEN_CTRL_2, params->EmcPmacroVttgenCtrl2);
/* Set pad macro bias. */
reg::Write(EMC + EMC_PMACRO_BG_BIAS_CTRL_0, params->EmcPmacroBgBiasCtrl0);
SpareWrite<SocType>(params->EmcBctSpareSecure0, params->EmcBctSpareSecure1);
SpareWrite<SocType>(params->EmcBctSpareSecure2, params->EmcBctSpareSecure3);
SpareWrite<SocType>(params->EmcBctSpareSecure4, params->EmcBctSpareSecure5);
/* Trigger timing update. */
reg::Write(EMC + EMC_TIMING_CONTROL, 1);
util::WaitMicroSeconds(params->PmcVddpSelWait + 2);
/* Set clock sources. */
reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_SOURCE_EMC, params->EmcClockSource);
reg::Write(CLKRST + CLK_RST_CONTROLLER_CLK_SOURCE_EMC_DLL, params->EmcClockSourceDll);
/* Select EMC write mux. */
reg::Write(EMC + EMC_DBG, params->EmcDbg | reg::EncodeValue(EMC_REG_BITS_VALUE(DBG_WRITE_MUX, params->EmcDbgWriteMux)));
/* Patch 2. */
SpareWrite<SocType>(params->EmcBctSpare2, params->EmcBctSpare3);
}
/* Common phase 2. */
reg::Write(EMC + EMC_CONFIG_SAMPLE_DELAY, params->EmcConfigSampleDelay);
reg::Write(EMC + EMC_FBIO_CFG8, params->EmcFbioCfg8);
/* Program swizzle registers. */
reg::Write(EMC + EMC_SWIZZLE_RANK0_BYTE0, params->EmcSwizzleRank0Byte0);
reg::Write(EMC + EMC_SWIZZLE_RANK0_BYTE1, params->EmcSwizzleRank0Byte1);
reg::Write(EMC + EMC_SWIZZLE_RANK0_BYTE2, params->EmcSwizzleRank0Byte2);
reg::Write(EMC + EMC_SWIZZLE_RANK0_BYTE3, params->EmcSwizzleRank0Byte3);
reg::Write(EMC + EMC_SWIZZLE_RANK1_BYTE0, params->EmcSwizzleRank1Byte0);
reg::Write(EMC + EMC_SWIZZLE_RANK1_BYTE1, params->EmcSwizzleRank1Byte1);
reg::Write(EMC + EMC_SWIZZLE_RANK1_BYTE2, params->EmcSwizzleRank1Byte2);
reg::Write(EMC + EMC_SWIZZLE_RANK1_BYTE3, params->EmcSwizzleRank1Byte3);
/* Patch 3. */
SpareWrite<SocType>(params->EmcBctSpare6, params->EmcBctSpare7);
/* Program pad controls. */
reg::Write(EMC + EMC_XM2COMPPADCTRL, params->EmcXm2CompPadCtrl);
reg::Write(EMC + EMC_XM2COMPPADCTRL2, params->EmcXm2CompPadCtrl2);
reg::Write(EMC + EMC_XM2COMPPADCTRL3, params->EmcXm2CompPadCtrl3);
/* Program autocal controls with shadowed register fields. */
reg::Write(EMC + EMC_AUTO_CAL_CONFIG2, params->EmcAutoCalConfig2);
reg::Write(EMC + EMC_AUTO_CAL_CONFIG3, params->EmcAutoCalConfig3);
reg::Write(EMC + EMC_AUTO_CAL_CONFIG4, params->EmcAutoCalConfig4);
reg::Write(EMC + EMC_AUTO_CAL_CONFIG5, params->EmcAutoCalConfig5);
reg::Write(EMC + EMC_AUTO_CAL_CONFIG6, params->EmcAutoCalConfig6);
reg::Write(EMC + EMC_AUTO_CAL_CONFIG7, params->EmcAutoCalConfig7);
reg::Write(EMC + EMC_AUTO_CAL_CONFIG8, params->EmcAutoCalConfig8);
reg::Write(EMC + EMC_PMACRO_RX_TERM, params->EmcPmacroRxTerm);
reg::Write(EMC + EMC_PMACRO_DQ_TX_DRV, params->EmcPmacroDqTxDrv);
reg::Write(EMC + EMC_PMACRO_CA_TX_DRV, params->EmcPmacroCaTxDrv);
reg::Write(EMC + EMC_PMACRO_CMD_TX_DRV, params->EmcPmacroCmdTxDrv);
reg::Write(EMC + EMC_PMACRO_AUTOCAL_CFG_COMMON, params->EmcPmacroAutocalCfgCommon);
reg::Write(EMC + EMC_AUTO_CAL_CHANNEL, params->EmcAutoCalChannel);
reg::Write(EMC + EMC_PMACRO_ZCTRL, params->EmcPmacroZctrl);
if constexpr (SocType == fuse::SocType_Erista) {
reg::Write(EMC + EMC_DLL_CFG_0, params->EmcDllCfg0);
reg::Write(EMC + EMC_DLL_CFG_1, params->EmcDllCfg1);
} else if constexpr (SocType == fuse::SocType_Mariko) {
reg::Write(EMC + EMC_PMACRO_DLL_CFG_0, params->EmcPmacroDllCfg0);
reg::Write(EMC + EMC_PMACRO_DLL_CFG_1, params->EmcPmacroDllCfg1);
}
reg::Write(EMC + EMC_CFG_DIG_DLL_1, params->EmcCfgDigDll_1);
reg::Write(EMC + EMC_DATA_BRLSHFT_0, params->EmcDataBrlshft0);
reg::Write(EMC + EMC_DATA_BRLSHFT_1, params->EmcDataBrlshft1);
reg::Write(EMC + EMC_DQS_BRLSHFT_0, params->EmcDqsBrlshft0);
reg::Write(EMC + EMC_DQS_BRLSHFT_1, params->EmcDqsBrlshft1);
reg::Write(EMC + EMC_CMD_BRLSHFT_0, params->EmcCmdBrlshft0);
reg::Write(EMC + EMC_CMD_BRLSHFT_1, params->EmcCmdBrlshft1);
reg::Write(EMC + EMC_CMD_BRLSHFT_2, params->EmcCmdBrlshft2);
reg::Write(EMC + EMC_CMD_BRLSHFT_3, params->EmcCmdBrlshft3);
reg::Write(EMC + EMC_QUSE_BRLSHFT_0, params->EmcQuseBrlshft0);
reg::Write(EMC + EMC_QUSE_BRLSHFT_1, params->EmcQuseBrlshft1);
reg::Write(EMC + EMC_QUSE_BRLSHFT_2, params->EmcQuseBrlshft2);
reg::Write(EMC + EMC_QUSE_BRLSHFT_3, params->EmcQuseBrlshft3);
if constexpr (SocType == fuse::SocType_Erista) {
reg::Write(EMC + EMC_PMACRO_BRICK_CTRL_RFU1, (params->EmcPmacroBrickCtrlRfu1 | ~0x01BF01BF) & 0x1FFF1FFF);
} else if constexpr (SocType == fuse::SocType_Mariko) {
reg::Write(EMC + EMC_PMACRO_BRICK_CTRL_RFU1, params->EmcPmacroBrickCtrlRfu1);
}
reg::Write(EMC + EMC_PMACRO_PAD_CFG_CTRL, params->EmcPmacroPadCfgCtrl);
reg::Write(EMC + EMC_PMACRO_CMD_BRICK_CTRL_FDPD, params->EmcPmacroCmdBrickCtrlFdpd);
if constexpr (SocType == fuse::SocType_Erista) {
reg::Write(EMC + EMC_PMACRO_BRICK_CTRL_RFU2, params->EmcPmacroBrickCtrlRfu2 & 0xFF7FFF7F);
} else if constexpr (SocType == fuse::SocType_Mariko) {
reg::Write(EMC + EMC_PMACRO_BRICK_CTRL_RFU2, params->EmcPmacroBrickCtrlRfu2);
}
reg::Write(EMC + EMC_PMACRO_DATA_BRICK_CTRL_FDPD, params->EmcPmacroDataBrickCtrlFdpd);
if constexpr (SocType == fuse::SocType_Erista) {
reg::Write(EMC + EMC_PMACRO_BG_BIAS_CTRL_0, params->EmcPmacroBgBiasCtrl0);
}
reg::Write(EMC + EMC_PMACRO_DATA_PAD_RX_CTRL, params->EmcPmacroDataPadRxCtrl);
reg::Write(EMC + EMC_PMACRO_CMD_PAD_RX_CTRL, params->EmcPmacroCmdPadRxCtrl);
reg::Write(EMC + EMC_PMACRO_DATA_PAD_TX_CTRL, params->EmcPmacroDataPadTxCtrl);
reg::Write(EMC + EMC_PMACRO_DATA_RX_TERM_MODE, params->EmcPmacroDataRxTermMode);
reg::Write(EMC + EMC_PMACRO_CMD_RX_TERM_MODE, params->EmcPmacroCmdRxTermMode);
if constexpr (SocType == fuse::SocType_Erista) {
reg::Write(EMC + EMC_PMACRO_CMD_PAD_TX_CTRL, params->EmcPmacroCmdPadTxCtrl);
} else if constexpr (SocType == fuse::SocType_Mariko) {
reg::Write(EMC + EMC_PMACRO_CMD_PAD_TX_CTRL, params->EmcPmacroCmdPadTxCtrl & 0xEFFFFFFF);
}
reg::Write(EMC + EMC_CFG_3, params->EmcCfg3);
reg::Write(EMC + EMC_PMACRO_TX_PWRD_0, params->EmcPmacroTxPwrd0);
reg::Write(EMC + EMC_PMACRO_TX_PWRD_1, params->EmcPmacroTxPwrd1);
reg::Write(EMC + EMC_PMACRO_TX_PWRD_2, params->EmcPmacroTxPwrd2);
reg::Write(EMC + EMC_PMACRO_TX_PWRD_3, params->EmcPmacroTxPwrd3);
reg::Write(EMC + EMC_PMACRO_TX_PWRD_4, params->EmcPmacroTxPwrd4);
reg::Write(EMC + EMC_PMACRO_TX_PWRD_5, params->EmcPmacroTxPwrd5);
reg::Write(EMC + EMC_PMACRO_TX_SEL_CLK_SRC_0, params->EmcPmacroTxSelClkSrc0);
reg::Write(EMC + EMC_PMACRO_TX_SEL_CLK_SRC_1, params->EmcPmacroTxSelClkSrc1);
reg::Write(EMC + EMC_PMACRO_TX_SEL_CLK_SRC_2, params->EmcPmacroTxSelClkSrc2);
reg::Write(EMC + EMC_PMACRO_TX_SEL_CLK_SRC_3, params->EmcPmacroTxSelClkSrc3);
reg::Write(EMC + EMC_PMACRO_TX_SEL_CLK_SRC_4, params->EmcPmacroTxSelClkSrc4);
reg::Write(EMC + EMC_PMACRO_TX_SEL_CLK_SRC_5, params->EmcPmacroTxSelClkSrc5);
if constexpr (SocType == fuse::SocType_Mariko) {
reg::Write(EMC + EMC_PMACRO_PERBIT_FGCG_CTRL_0, params->EmcPmacroPerbitFgcgCtrl0);
reg::Write(EMC + EMC_PMACRO_PERBIT_FGCG_CTRL_1, params->EmcPmacroPerbitFgcgCtrl1);
reg::Write(EMC + EMC_PMACRO_PERBIT_FGCG_CTRL_2, params->EmcPmacroPerbitFgcgCtrl2);
reg::Write(EMC + EMC_PMACRO_PERBIT_FGCG_CTRL_3, params->EmcPmacroPerbitFgcgCtrl3);
reg::Write(EMC + EMC_PMACRO_PERBIT_FGCG_CTRL_4, params->EmcPmacroPerbitFgcgCtrl4);
reg::Write(EMC + EMC_PMACRO_PERBIT_FGCG_CTRL_5, params->EmcPmacroPerbitFgcgCtrl5);
reg::Write(EMC + EMC_PMACRO_PERBIT_RFU_CTRL_0, params->EmcPmacroPerbitRfuCtrl0);
reg::Write(EMC + EMC_PMACRO_PERBIT_RFU_CTRL_1, params->EmcPmacroPerbitRfuCtrl1);
reg::Write(EMC + EMC_PMACRO_PERBIT_RFU_CTRL_2, params->EmcPmacroPerbitRfuCtrl2);
reg::Write(EMC + EMC_PMACRO_PERBIT_RFU_CTRL_3, params->EmcPmacroPerbitRfuCtrl3);
reg::Write(EMC + EMC_PMACRO_PERBIT_RFU_CTRL_4, params->EmcPmacroPerbitRfuCtrl4);
reg::Write(EMC + EMC_PMACRO_PERBIT_RFU_CTRL_5, params->EmcPmacroPerbitRfuCtrl5);
reg::Write(EMC + EMC_PMACRO_PERBIT_RFU1_CTRL_0, params->EmcPmacroPerbitRfu1Ctrl0);
reg::Write(EMC + EMC_PMACRO_PERBIT_RFU1_CTRL_1, params->EmcPmacroPerbitRfu1Ctrl1);
reg::Write(EMC + EMC_PMACRO_PERBIT_RFU1_CTRL_2, params->EmcPmacroPerbitRfu1Ctrl2);
reg::Write(EMC + EMC_PMACRO_PERBIT_RFU1_CTRL_3, params->EmcPmacroPerbitRfu1Ctrl3);
reg::Write(EMC + EMC_PMACRO_PERBIT_RFU1_CTRL_4, params->EmcPmacroPerbitRfu1Ctrl4);
reg::Write(EMC + EMC_PMACRO_PERBIT_RFU1_CTRL_5, params->EmcPmacroPerbitRfu1Ctrl5);
reg::Write(EMC + EMC_PMACRO_DATA_PI_CTRL, params->EmcPmacroDataPiCtrl);
reg::Write(EMC + EMC_PMACRO_CMD_PI_CTRL, params->EmcPmacroCmdPiCtrl);
}
reg::Write(EMC + EMC_PMACRO_DDLL_BYPASS, params->EmcPmacroDdllBypass);
reg::Write(EMC + EMC_PMACRO_DDLL_PWRD_0, params->EmcPmacroDdllPwrd0);
reg::Write(EMC + EMC_PMACRO_DDLL_PWRD_1, params->EmcPmacroDdllPwrd1);
reg::Write(EMC + EMC_PMACRO_DDLL_PWRD_2, params->EmcPmacroDdllPwrd2);
reg::Write(EMC + EMC_PMACRO_CMD_CTRL_0, params->EmcPmacroCmdCtrl0);
reg::Write(EMC + EMC_PMACRO_CMD_CTRL_1, params->EmcPmacroCmdCtrl1);
reg::Write(EMC + EMC_PMACRO_CMD_CTRL_2, params->EmcPmacroCmdCtrl2);
reg::Write(EMC + EMC_PMACRO_IB_VREF_DQ_0, params->EmcPmacroIbVrefDq_0);
reg::Write(EMC + EMC_PMACRO_IB_VREF_DQ_1, params->EmcPmacroIbVrefDq_1);
reg::Write(EMC + EMC_PMACRO_IB_VREF_DQS_0, params->EmcPmacroIbVrefDqs_0);
reg::Write(EMC + EMC_PMACRO_IB_VREF_DQS_1, params->EmcPmacroIbVrefDqs_1);
reg::Write(EMC + EMC_PMACRO_IB_RXRT, params->EmcPmacroIbRxrt);
reg::Write(EMC + EMC_PMACRO_QUSE_DDLL_RANK0_0, params->EmcPmacroQuseDdllRank0_0);
reg::Write(EMC + EMC_PMACRO_QUSE_DDLL_RANK0_1, params->EmcPmacroQuseDdllRank0_1);
reg::Write(EMC + EMC_PMACRO_QUSE_DDLL_RANK0_2, params->EmcPmacroQuseDdllRank0_2);
reg::Write(EMC + EMC_PMACRO_QUSE_DDLL_RANK0_3, params->EmcPmacroQuseDdllRank0_3);
reg::Write(EMC + EMC_PMACRO_QUSE_DDLL_RANK0_4, params->EmcPmacroQuseDdllRank0_4);
reg::Write(EMC + EMC_PMACRO_QUSE_DDLL_RANK0_5, params->EmcPmacroQuseDdllRank0_5);
reg::Write(EMC + EMC_PMACRO_QUSE_DDLL_RANK1_0, params->EmcPmacroQuseDdllRank1_0);
reg::Write(EMC + EMC_PMACRO_QUSE_DDLL_RANK1_1, params->EmcPmacroQuseDdllRank1_1);
reg::Write(EMC + EMC_PMACRO_QUSE_DDLL_RANK1_2, params->EmcPmacroQuseDdllRank1_2);
reg::Write(EMC + EMC_PMACRO_QUSE_DDLL_RANK1_3, params->EmcPmacroQuseDdllRank1_3);
reg::Write(EMC + EMC_PMACRO_QUSE_DDLL_RANK1_4, params->EmcPmacroQuseDdllRank1_4);
reg::Write(EMC + EMC_PMACRO_QUSE_DDLL_RANK1_5, params->EmcPmacroQuseDdllRank1_5);
if constexpr (SocType == fuse::SocType_Erista) {
reg::Write(EMC + EMC_PMACRO_BRICK_CTRL_RFU1, params->EmcPmacroBrickCtrlRfu1);
}
reg::Write(EMC + EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_0, params->EmcPmacroObDdllLongDqRank0_0);
reg::Write(EMC + EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_1, params->EmcPmacroObDdllLongDqRank0_1);
reg::Write(EMC + EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_2, params->EmcPmacroObDdllLongDqRank0_2);
reg::Write(EMC + EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_3, params->EmcPmacroObDdllLongDqRank0_3);
reg::Write(EMC + EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_4, params->EmcPmacroObDdllLongDqRank0_4);
reg::Write(EMC + EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_5, params->EmcPmacroObDdllLongDqRank0_5);
reg::Write(EMC + EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_0, params->EmcPmacroObDdllLongDqRank1_0);
reg::Write(EMC + EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_1, params->EmcPmacroObDdllLongDqRank1_1);
reg::Write(EMC + EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_2, params->EmcPmacroObDdllLongDqRank1_2);
reg::Write(EMC + EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_3, params->EmcPmacroObDdllLongDqRank1_3);
reg::Write(EMC + EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_4, params->EmcPmacroObDdllLongDqRank1_4);
reg::Write(EMC + EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_5, params->EmcPmacroObDdllLongDqRank1_5);
reg::Write(EMC + EMC_PMACRO_OB_DDLL_LONG_DQS_RANK0_0, params->EmcPmacroObDdllLongDqsRank0_0);
reg::Write(EMC + EMC_PMACRO_OB_DDLL_LONG_DQS_RANK0_1, params->EmcPmacroObDdllLongDqsRank0_1);
reg::Write(EMC + EMC_PMACRO_OB_DDLL_LONG_DQS_RANK0_2, params->EmcPmacroObDdllLongDqsRank0_2);
reg::Write(EMC + EMC_PMACRO_OB_DDLL_LONG_DQS_RANK0_3, params->EmcPmacroObDdllLongDqsRank0_3);
reg::Write(EMC + EMC_PMACRO_OB_DDLL_LONG_DQS_RANK0_4, params->EmcPmacroObDdllLongDqsRank0_4);
reg::Write(EMC + EMC_PMACRO_OB_DDLL_LONG_DQS_RANK0_5, params->EmcPmacroObDdllLongDqsRank0_5);
reg::Write(EMC + EMC_PMACRO_OB_DDLL_LONG_DQS_RANK1_0, params->EmcPmacroObDdllLongDqsRank1_0);
reg::Write(EMC + EMC_PMACRO_OB_DDLL_LONG_DQS_RANK1_1, params->EmcPmacroObDdllLongDqsRank1_1);
reg::Write(EMC + EMC_PMACRO_OB_DDLL_LONG_DQS_RANK1_2, params->EmcPmacroObDdllLongDqsRank1_2);
reg::Write(EMC + EMC_PMACRO_OB_DDLL_LONG_DQS_RANK1_3, params->EmcPmacroObDdllLongDqsRank1_3);
reg::Write(EMC + EMC_PMACRO_OB_DDLL_LONG_DQS_RANK1_4, params->EmcPmacroObDdllLongDqsRank1_4);
reg::Write(EMC + EMC_PMACRO_OB_DDLL_LONG_DQS_RANK1_5, params->EmcPmacroObDdllLongDqsRank1_5);
reg::Write(EMC + EMC_PMACRO_IB_DDLL_LONG_DQS_RANK0_0, params->EmcPmacroIbDdllLongDqsRank0_0);
reg::Write(EMC + EMC_PMACRO_IB_DDLL_LONG_DQS_RANK0_1, params->EmcPmacroIbDdllLongDqsRank0_1);
reg::Write(EMC + EMC_PMACRO_IB_DDLL_LONG_DQS_RANK0_2, params->EmcPmacroIbDdllLongDqsRank0_2);
reg::Write(EMC + EMC_PMACRO_IB_DDLL_LONG_DQS_RANK0_3, params->EmcPmacroIbDdllLongDqsRank0_3);
reg::Write(EMC + EMC_PMACRO_IB_DDLL_LONG_DQS_RANK1_0, params->EmcPmacroIbDdllLongDqsRank1_0);
reg::Write(EMC + EMC_PMACRO_IB_DDLL_LONG_DQS_RANK1_1, params->EmcPmacroIbDdllLongDqsRank1_1);
reg::Write(EMC + EMC_PMACRO_IB_DDLL_LONG_DQS_RANK1_2, params->EmcPmacroIbDdllLongDqsRank1_2);
reg::Write(EMC + EMC_PMACRO_IB_DDLL_LONG_DQS_RANK1_3, params->EmcPmacroIbDdllLongDqsRank1_3);
reg::Write(EMC + EMC_PMACRO_DDLL_LONG_CMD_0, params->EmcPmacroDdllLongCmd_0);
reg::Write(EMC + EMC_PMACRO_DDLL_LONG_CMD_1, params->EmcPmacroDdllLongCmd_1);
reg::Write(EMC + EMC_PMACRO_DDLL_LONG_CMD_2, params->EmcPmacroDdllLongCmd_2);
reg::Write(EMC + EMC_PMACRO_DDLL_LONG_CMD_3, params->EmcPmacroDdllLongCmd_3);
reg::Write(EMC + EMC_PMACRO_DDLL_LONG_CMD_4, params->EmcPmacroDdllLongCmd_4);
reg::Write(EMC + EMC_PMACRO_DDLL_SHORT_CMD_0, params->EmcPmacroDdllShortCmd_0);
reg::Write(EMC + EMC_PMACRO_DDLL_SHORT_CMD_1, params->EmcPmacroDdllShortCmd_1);
reg::Write(EMC + EMC_PMACRO_DDLL_SHORT_CMD_2, params->EmcPmacroDdllShortCmd_2);
if constexpr (SocType == fuse::SocType_Erista) {
reg::Write(EMC + EMC_PMACRO_COMMON_PAD_TX_CTRL, (params->EmcPmacroCommonPadTxCtrl | ~0x1) & 0xF);
} else if constexpr (SocType == fuse::SocType_Mariko) {
reg::Write(EMC + EMC_PMACRO_DDLL_PERIODIC_OFFSET, params->EmcPmacroDdllPeriodicOffset);
}
if constexpr (SocType == fuse::SocType_Erista) {
SpareWrite<SocType>(params->EmcBctSpare4, params->EmcBctSpare5);
} else if constexpr (SocType == fuse::SocType_Mariko) {
SpareWrite<SocType>(params->EmcBctSpare4, params->EmcBctSpare5);
SpareWrite<SocType>(params->EmcBctSpareSecure6, params->EmcBctSpareSecure7);
SpareWrite<SocType>(params->EmcBctSpareSecure8, params->EmcBctSpareSecure9);
SpareWrite<SocType>(params->EmcBctSpareSecure10, params->EmcBctSpareSecure11);
}
reg::Write(EMC + EMC_TIMING_CONTROL, 1);
/* Initialize MC VPR settings. */
reg::Write(MC + MC_VIDEO_PROTECT_BOM, params->McVideoProtectBom);
reg::Write(MC + MC_VIDEO_PROTECT_BOM_ADR_HI, params->McVideoProtectBomAdrHi);
reg::Write(MC + MC_VIDEO_PROTECT_SIZE_MB, params->McVideoProtectSizeMb);
reg::Write(MC + MC_VIDEO_PROTECT_VPR_OVERRIDE, params->McVideoProtectVprOverride);
reg::Write(MC + MC_VIDEO_PROTECT_VPR_OVERRIDE1, params->McVideoProtectVprOverride1);
reg::Write(MC + MC_VIDEO_PROTECT_GPU_OVERRIDE_0, params->McVideoProtectGpuOverride0);
reg::Write(MC + MC_VIDEO_PROTECT_GPU_OVERRIDE_1, params->McVideoProtectGpuOverride1);
/* Program SDRAM geometry parameters. */
reg::Write(MC + MC_EMEM_ADR_CFG, params->McEmemAdrCfg);
reg::Write(MC + MC_EMEM_ADR_CFG_DEV0, params->McEmemAdrCfgDev0);
reg::Write(MC + MC_EMEM_ADR_CFG_DEV1, params->McEmemAdrCfgDev1);
reg::Write(MC + MC_EMEM_ADR_CFG_CHANNEL_MASK, params->McEmemAdrCfgChannelMask);
/* Program bank swizzling. */
reg::Write(MC + MC_EMEM_ADR_CFG_BANK_MASK_0, params->McEmemAdrCfgBankMask0);
reg::Write(MC + MC_EMEM_ADR_CFG_BANK_MASK_1, params->McEmemAdrCfgBankMask1);
reg::Write(MC + MC_EMEM_ADR_CFG_BANK_MASK_2, params->McEmemAdrCfgBankMask2);
/* Program external memory aperture (base and size). */
reg::Write(MC + MC_EMEM_CFG, params->McEmemCfg);
/* Program SEC carveout (base and size). */
reg::Write(MC + MC_SEC_CARVEOUT_BOM, params->McSecCarveoutBom);
reg::Write(MC + MC_SEC_CARVEOUT_ADR_HI, params->McSecCarveoutAdrHi);
reg::Write(MC + MC_SEC_CARVEOUT_SIZE_MB, params->McSecCarveoutSizeMb);
/* Program MTS carveout (base and size). */
reg::Write(MC + MC_MTS_CARVEOUT_BOM, params->McMtsCarveoutBom);
reg::Write(MC + MC_MTS_CARVEOUT_ADR_HI, params->McMtsCarveoutAdrHi);
reg::Write(MC + MC_MTS_CARVEOUT_SIZE_MB, params->McMtsCarveoutSizeMb);
/* Program the memory arbiter. */
reg::Write(MC + MC_EMEM_ARB_CFG, params->McEmemArbCfg);
reg::Write(MC + MC_EMEM_ARB_OUTSTANDING_REQ, params->McEmemArbOutstandingReq);
reg::Write(MC + MC_EMEM_ARB_REFPB_HP_CTRL, params->McEmemArbRefpbHpCtrl);
reg::Write(MC + MC_EMEM_ARB_REFPB_BANK_CTRL, params->McEmemArbRefpbBankCtrl);
reg::Write(MC + MC_EMEM_ARB_TIMING_RCD, params->McEmemArbTimingRcd);
reg::Write(MC + MC_EMEM_ARB_TIMING_RP, params->McEmemArbTimingRp);
reg::Write(MC + MC_EMEM_ARB_TIMING_RC, params->McEmemArbTimingRc);
reg::Write(MC + MC_EMEM_ARB_TIMING_RAS, params->McEmemArbTimingRas);
reg::Write(MC + MC_EMEM_ARB_TIMING_FAW, params->McEmemArbTimingFaw);
reg::Write(MC + MC_EMEM_ARB_TIMING_RRD, params->McEmemArbTimingRrd);
reg::Write(MC + MC_EMEM_ARB_TIMING_RAP2PRE, params->McEmemArbTimingRap2Pre);
reg::Write(MC + MC_EMEM_ARB_TIMING_WAP2PRE, params->McEmemArbTimingWap2Pre);
reg::Write(MC + MC_EMEM_ARB_TIMING_R2R, params->McEmemArbTimingR2R);
reg::Write(MC + MC_EMEM_ARB_TIMING_W2W, params->McEmemArbTimingW2W);
reg::Write(MC + MC_EMEM_ARB_TIMING_CCDMW, params->McEmemArbTimingCcdmw);
reg::Write(MC + MC_EMEM_ARB_TIMING_R2W, params->McEmemArbTimingR2W);
reg::Write(MC + MC_EMEM_ARB_TIMING_W2R, params->McEmemArbTimingW2R);
reg::Write(MC + MC_EMEM_ARB_TIMING_RFCPB, params->McEmemArbTimingRFCPB);
reg::Write(MC + MC_EMEM_ARB_DA_TURNS, params->McEmemArbDaTurns);
reg::Write(MC + MC_EMEM_ARB_DA_COVERS, params->McEmemArbDaCovers);
reg::Write(MC + MC_EMEM_ARB_MISC0, params->McEmemArbMisc0);
reg::Write(MC + MC_EMEM_ARB_MISC1, params->McEmemArbMisc1);
reg::Write(MC + MC_EMEM_ARB_MISC2, params->McEmemArbMisc2);
reg::Write(MC + MC_EMEM_ARB_RING1_THROTTLE, params->McEmemArbRing1Throttle);
reg::Write(MC + MC_EMEM_ARB_OVERRIDE, params->McEmemArbOverride);
reg::Write(MC + MC_EMEM_ARB_OVERRIDE_1, params->McEmemArbOverride1);
reg::Write(MC + MC_EMEM_ARB_RSV, params->McEmemArbRsv);
reg::Write(MC + MC_DA_CONFIG0, params->McDaCfg0);
/* Trigger MC timing update. */
reg::Write(MC + MC_TIMING_CONTROL, 1);
/* Program second-level clock enable overrides. */
reg::Write(MC + MC_CLKEN_OVERRIDE, params->McClkenOverride);
/* Program statistics gathering. */
reg::Write(MC + MC_STAT_CONTROL, params->McStatControl);
/* Program SDRAM geometry parameters. */
reg::Write(EMC + EMC_ADR_CFG, params->EmcAdrCfg);
/* Program second-level clock enable overrides. */
reg::Write(EMC + EMC_CLKEN_OVERRIDE, params->EmcClkenOverride);
/* Program EMC pad auto calibration. */
reg::Write(EMC + EMC_PMACRO_AUTOCAL_CFG_0, params->EmcPmacroAutocalCfg0);
reg::Write(EMC + EMC_PMACRO_AUTOCAL_CFG_1, params->EmcPmacroAutocalCfg1);
reg::Write(EMC + EMC_PMACRO_AUTOCAL_CFG_2, params->EmcPmacroAutocalCfg2);
reg::Write(EMC + EMC_AUTO_CAL_VREF_SEL_0, params->EmcAutoCalVrefSel0);
reg::Write(EMC + EMC_AUTO_CAL_VREF_SEL_1, params->EmcAutoCalVrefSel1);
reg::Write(EMC + EMC_AUTO_CAL_INTERVAL, params->EmcAutoCalInterval);
reg::Write(EMC + EMC_AUTO_CAL_CONFIG, params->EmcAutoCalConfig);
util::WaitMicroSeconds(params->EmcAutoCalWait);
/* Patch 5. */
if constexpr (SocType == fuse::SocType_Erista) {
SpareWrite<SocType>(params->EmcBctSpare8, params->EmcBctSpare9);
} else if constexpr (SocType == fuse::SocType_Mariko) {
SpareWrite<SocType>(params->EmcBctSpare8, params->EmcBctSpare9);
reg::Write(EMC + EMC_AUTO_CAL_CONFIG9, params->EmcAutoCalConfig9);
}
/* Program EMC timing configuration. */
reg::Write(EMC + EMC_CFG_2, params->EmcCfg2);
reg::Write(EMC + EMC_CFG_PIPE, params->EmcCfgPipe);
reg::Write(EMC + EMC_CFG_PIPE_1, params->EmcCfgPipe1);
reg::Write(EMC + EMC_CFG_PIPE_2, params->EmcCfgPipe2);
reg::Write(EMC + EMC_CMDQ, params->EmcCmdQ);
reg::Write(EMC + EMC_MC2EMCQ, params->EmcMc2EmcQ);
reg::Write(EMC + EMC_MRS_WAIT_CNT, params->EmcMrsWaitCnt);
reg::Write(EMC + EMC_MRS_WAIT_CNT2, params->EmcMrsWaitCnt2);
reg::Write(EMC + EMC_FBIO_CFG5, params->EmcFbioCfg5);
reg::Write(EMC + EMC_RC, params->EmcRc);
reg::Write(EMC + EMC_RFC, params->EmcRfc);
reg::Write(EMC + EMC_RFCPB, params->EmcRfcPb);
reg::Write(EMC + EMC_REFCTRL2, params->EmcRefctrl2);
reg::Write(EMC + EMC_RFC_SLR, params->EmcRfcSlr);
reg::Write(EMC + EMC_RAS, params->EmcRas);
reg::Write(EMC + EMC_RP, params->EmcRp);
reg::Write(EMC + EMC_TPPD, params->EmcTppd);
if constexpr (SocType == fuse::SocType_Mariko) {
reg::Write(EMC + EMC_TRTM, params->EmcTrtm);
reg::Write(EMC + EMC_TWTM, params->EmcTwtm);
reg::Write(EMC + EMC_TRATM, params->EmcTratm);
reg::Write(EMC + EMC_TWATM, params->EmcTwatm);
reg::Write(EMC + EMC_TR2REF, params->EmcTr2ref);
}
reg::Write(EMC + EMC_R2R, params->EmcR2r);
reg::Write(EMC + EMC_W2W, params->EmcW2w);
reg::Write(EMC + EMC_R2W, params->EmcR2w);
reg::Write(EMC + EMC_W2R, params->EmcW2r);
reg::Write(EMC + EMC_R2P, params->EmcR2p);
reg::Write(EMC + EMC_W2P, params->EmcW2p);
reg::Write(EMC + EMC_CCDMW, params->EmcCcdmw);
reg::Write(EMC + EMC_RD_RCD, params->EmcRdRcd);
reg::Write(EMC + EMC_WR_RCD, params->EmcWrRcd);
reg::Write(EMC + EMC_RRD, params->EmcRrd);
reg::Write(EMC + EMC_REXT, params->EmcRext);
reg::Write(EMC + EMC_WEXT, params->EmcWext);
reg::Write(EMC + EMC_WDV, params->EmcWdv);
reg::Write(EMC + EMC_WDV_CHK, params->EmcWdvChk);
reg::Write(EMC + EMC_WSV, params->EmcWsv);
reg::Write(EMC + EMC_WEV, params->EmcWev);
reg::Write(EMC + EMC_WDV_MASK, params->EmcWdvMask);
reg::Write(EMC + EMC_WS_DURATION, params->EmcWsDuration);
reg::Write(EMC + EMC_WE_DURATION, params->EmcWeDuration);
reg::Write(EMC + EMC_QUSE, params->EmcQUse);
reg::Write(EMC + EMC_QUSE_WIDTH, params->EmcQuseWidth);
reg::Write(EMC + EMC_IBDLY, params->EmcIbdly);
reg::Write(EMC + EMC_OBDLY, params->EmcObdly);
reg::Write(EMC + EMC_EINPUT, params->EmcEInput);
reg::Write(EMC + EMC_EINPUT_DURATION, params->EmcEInputDuration);
reg::Write(EMC + EMC_PUTERM_EXTRA, params->EmcPutermExtra);
reg::Write(EMC + EMC_PUTERM_WIDTH, params->EmcPutermWidth);
if constexpr (SocType == fuse::SocType_Erista) {
reg::Write(EMC + EMC_PMACRO_COMMON_PAD_TX_CTRL, params->EmcPmacroCommonPadTxCtrl);
}
reg::Write(EMC + EMC_DBG, params->EmcDbg);
reg::Write(EMC + EMC_QRST, params->EmcQRst);
reg::Write(EMC + EMC_ISSUE_QRST, 1);
reg::Write(EMC + EMC_ISSUE_QRST, 0);
reg::Write(EMC + EMC_QSAFE, params->EmcQSafe);
reg::Write(EMC + EMC_RDV, params->EmcRdv);
reg::Write(EMC + EMC_RDV_MASK, params->EmcRdvMask);
reg::Write(EMC + EMC_RDV_EARLY, params->EmcRdvEarly);
reg::Write(EMC + EMC_RDV_EARLY_MASK, params->EmcRdvEarlyMask);
reg::Write(EMC + EMC_QPOP, params->EmcQpop);
reg::Write(EMC + EMC_REFRESH, params->EmcRefresh);
reg::Write(EMC + EMC_BURST_REFRESH_NUM, params->EmcBurstRefreshNum);
reg::Write(EMC + EMC_PRE_REFRESH_REQ_CNT, params->EmcPreRefreshReqCnt);
reg::Write(EMC + EMC_PDEX2WR, params->EmcPdEx2Wr);
reg::Write(EMC + EMC_PDEX2RD, params->EmcPdEx2Rd);
reg::Write(EMC + EMC_PCHG2PDEN, params->EmcPChg2Pden);
reg::Write(EMC + EMC_ACT2PDEN, params->EmcAct2Pden);
reg::Write(EMC + EMC_AR2PDEN, params->EmcAr2Pden);
reg::Write(EMC + EMC_RW2PDEN, params->EmcRw2Pden);
reg::Write(EMC + EMC_CKE2PDEN, params->EmcCke2Pden);
reg::Write(EMC + EMC_PDEX2CKE, params->EmcPdex2Cke);
reg::Write(EMC + EMC_PDEX2MRR, params->EmcPdex2Mrr);
reg::Write(EMC + EMC_TXSR, params->EmcTxsr);
reg::Write(EMC + EMC_TXSRDLL, params->EmcTxsrDll);
reg::Write(EMC + EMC_TCKE, params->EmcTcke);
reg::Write(EMC + EMC_TCKESR, params->EmcTckesr);
reg::Write(EMC + EMC_TPD, params->EmcTpd);
reg::Write(EMC + EMC_TFAW, params->EmcTfaw);
reg::Write(EMC + EMC_TRPAB, params->EmcTrpab);
reg::Write(EMC + EMC_TCLKSTABLE, params->EmcTClkStable);
reg::Write(EMC + EMC_TCLKSTOP, params->EmcTClkStop);
reg::Write(EMC + EMC_TREFBW, params->EmcTRefBw);
reg::Write(EMC + EMC_ODT_WRITE, params->EmcOdtWrite);
reg::Write(EMC + EMC_CFG_DIG_DLL, params->EmcCfgDigDll);
reg::Write(EMC + EMC_CFG_DIG_DLL_PERIOD, params->EmcCfgDigDllPeriod);
/* Lock bit written later for CFG_ADR_EN. */
reg::Write(EMC + EMC_FBIO_SPARE, params->EmcFbioSpare & 0xFFFFFFFD);
reg::Write(EMC + EMC_CFG_RSV, params->EmcCfgRsv);
reg::Write(EMC + EMC_PMC_SCRATCH1, params->EmcPmcScratch1);
reg::Write(EMC + EMC_PMC_SCRATCH2, params->EmcPmcScratch2);
reg::Write(EMC + EMC_PMC_SCRATCH3, params->EmcPmcScratch3);
reg::Write(EMC + EMC_ACPD_CONTROL, params->EmcAcpdControl);
reg::Write(EMC + EMC_TXDSRVTTGEN, params->EmcTxdsrvttgen);
if constexpr (SocType == fuse::SocType_Mariko) {
reg::Write(EMC + EMC_PMACRO_DSR_VTTGEN_CTRL_0, params->EmcPmacroDsrVttgenCtrl0);
}
/* Set pipe bypass enable bits before sending any DRAM commands. */
reg::Write(EMC + EMC_CFG, (params->EmcCfg * 0xE) | 0x03C00000);
/* Perform bootrom patch. */
if constexpr (SocType == fuse::SocType_Erista) {
if (params->BootRomPatchControl & 0x80000000) {
reg::Write(APB + ((params->BootRomPatchControl & 0x3FFFFFFF) << 2), params->BootRomPatchData);
reg::Write(MC + MC_TIMING_CONTROL, 1);
}
} else if constexpr (SocType == fuse::SocType_Mariko) {
if (params->BootRomPatchControl) {
SpareWrite<SocType>(params->BootRomPatchControl, params->BootRomPatchData);
reg::Write(MC + MC_TIMING_CONTROL, 1);
}
SpareWrite<SocType>(params->EmcBctSpareSecure12, params->EmcBctSpareSecure13);
SpareWrite<SocType>(params->EmcBctSpareSecure14, params->EmcBctSpareSecure15);
SpareWrite<SocType>(params->EmcBctSpareSecure16, params->EmcBctSpareSecure17);
}
/* Release SEL_DPD_CMD. */
reg::Write(PMC + APBDEV_PMC_IO_DPD3_REQ, ((params->EmcPmcScratch1 & 0x3FFFFFFF) | 0x40000000) & 0xCFFF0000);
util::WaitMicroSeconds(params->PmcIoDpd3ReqWait);
if constexpr (SocType == fuse::SocType_Erista) {
if (params->EmcAutoCalInterval == 0) {
reg::Write(EMC + EMC_AUTO_CAL_CONFIG, params->EmcAutoCalConfig | 0x200);
}
reg::Write(EMC + EMC_PMACRO_BRICK_CTRL_RFU2, params->EmcPmacroBrickCtrlRfu2);
} else if constexpr (SocType == fuse::SocType_Mariko) {
reg::Write(EMC + EMC_PMACRO_CMD_PAD_TX_CTRL, params->EmcPmacroCmdPadTxCtrl);
}
/* ZQ CAL setup */
if (params->EmcZcalWarmColdBootEnables & 1) {
if (params->MemoryType == br::BootMemoryType_Ddr3) {
reg::Write(EMC + EMC_ZCAL_WAIT_CNT, params->EmcZcalWaitCnt << 3);
} else if (params->MemoryType == br::BootMemoryType_LpDdr4) {
reg::Write(EMC + EMC_ZCAL_WAIT_CNT, params->EmcZcalWaitCnt);
reg::Write(EMC + EMC_ZCAL_MRW_CMD, params->EmcZcalMrwCmd);
}
}
/* Trigger timing update. */
reg::Write(EMC + EMC_TIMING_CONTROL, 1);
util::WaitMicroSeconds(params->EmcTimingControlWait);
/* Deassert HOLD_CKE_LOW. */
if constexpr (SocType == fuse::SocType_Erista) {
reg::ClearBits(PMC + APBDEV_PMC_DDR_CNTRL, ~0xFFF8007F);
} else if constexpr (SocType == fuse::SocType_Mariko) {
reg::ClearBits(PMC + APBDEV_PMC_DDR_CNTRL, ~0xFF78007F);
}
util::WaitMicroSeconds(params->PmcDdrCntrlWait);
/* Set clock enable signal. */
const u32 pin_gpio_cfg = (params->EmcPinGpioEn << 16) | (params->EmcPinGpio << 12);
if (params->MemoryType == br::BootMemoryType_Ddr3 || params->MemoryType == br::BootMemoryType_LpDdr4) {
reg::Write(EMC + EMC_PIN, pin_gpio_cfg);
reg::Read(EMC + EMC_PIN);
util::WaitMicroSeconds(200 + params->EmcPinExtraWait);
reg::Write(EMC + EMC_PIN, pin_gpio_cfg | 0x100);
reg::Read(EMC + EMC_PIN);
const u32 wait = params->MemoryType == br::BootMemoryType_Ddr3 ? 500 : 2000;
util::WaitMicroSeconds(wait + params->EmcPinExtraWait);
}
/* Set clock enable signal. */
reg::Write(EMC + EMC_PIN, pin_gpio_cfg | 0x101);
reg::Read(EMC + EMC_PIN);
util::WaitMicroSeconds(params->EmcPinProgramWait);
/* Send NOP */
if (params->MemoryType != br::BootMemoryType_LpDdr4) {
reg::Write(EMC + EMC_NOP, (params->EmcDevSelect << 30) | 1);
}
/* On coldboot with LPDDR2/3, wait 200us after asserting CKE high. */
if (params->MemoryType != br::BootMemoryType_LpDdr2) {
util::WaitMicroSeconds(200 + params->EmcPinExtraWait);
}
/* Init ZQ calibration. */
if (params->MemoryType == br::BootMemoryType_LpDdr4) {
SpareWrite<SocType>(params->EmcBctSpare10, params->EmcBctSpare11);
reg::Write(EMC + EMC_MRW2, params->EmcMrw2);
reg::Write(EMC + EMC_MRW, params->EmcMrw1);
reg::Write(EMC + EMC_MRW3, params->EmcMrw3);
reg::Write(EMC + EMC_MRW4, params->EmcMrw4);
reg::Write(EMC + EMC_MRW6, params->EmcMrw6);
reg::Write(EMC + EMC_MRW14, params->EmcMrw14);
reg::Write(EMC + EMC_MRW8, params->EmcMrw8);
reg::Write(EMC + EMC_MRW12, params->EmcMrw12);
reg::Write(EMC + EMC_MRW9, params->EmcMrw9);
reg::Write(EMC + EMC_MRW13, params->EmcMrw13);
if (params->EmcZcalWarmColdBootEnables & 1) {
/* Issue ZQCAL start, device 0. */
reg::Write(EMC + EMC_ZQ_CAL, params->EmcZcalInitDev0);
util::WaitMicroSeconds(params->EmcZcalInitWait);
/* Issue ZQCAL latch. */
reg::Write(EMC + EMC_ZQ_CAL, params->EmcZcalInitDev0 ^ 0x3);
/* Do the same for device 1. */
if ((params->EmcDevSelect & 2) == 0) {
reg::Write(EMC + EMC_ZQ_CAL, params->EmcZcalInitDev1);
util::WaitMicroSeconds(params->EmcZcalInitWait);
reg::Write(EMC + EMC_ZQ_CAL, params->EmcZcalInitDev1 ^ 0x3);
}
}
}
/* Patches 10-12. */
if constexpr (SocType == fuse::SocType_Mariko) {
SpareWrite<SocType>(params->EmcBctSpareSecure18, params->EmcBctSpareSecure19);
SpareWrite<SocType>(params->EmcBctSpareSecure20, params->EmcBctSpareSecure21);
SpareWrite<SocType>(params->EmcBctSpareSecure22, params->EmcBctSpareSecure23);
}
/* Set package and DPD pad control. */
reg::Write(PMC + APBDEV_PMC_DDR_CFG, params->PmcDdrCfg);
/* Start periodic ZQ calibration. */
if (params->MemoryType == br::BootMemoryType_LpDdr2 || params->MemoryType == br::BootMemoryType_Ddr3 || params->MemoryType == br::BootMemoryType_LpDdr4) {
reg::Write(EMC + EMC_ZCAL_INTERVAL, params->EmcZcalInterval);
reg::Write(EMC + EMC_ZCAL_WAIT_CNT, params->EmcZcalWaitCnt);
reg::Write(EMC + EMC_ZCAL_MRW_CMD, params->EmcZcalMrwCmd);
}
SpareWrite<SocType>(params->EmcBctSpare12, params->EmcBctSpare13);
/* Trigger timing update. */
reg::Write(EMC + EMC_TIMING_CONTROL, 1);
if (params->EmcExtraRefreshNum) {
reg::Write(EMC + EMC_REF, (params->EmcDevSelect << 30) | (((1 << params->EmcExtraRefreshNum) - 1) << 8) | 3);
}
/* Enable refresh. */
reg::Write(EMC + EMC_REFCTRL, params->EmcDevSelect | 0x80000000);
reg::Write(EMC + EMC_DYN_SELF_REF_CONTROL, params->EmcDynSelfRefControl);
if constexpr (SocType == fuse::SocType_Erista) {
reg::Write(EMC + EMC_CFG_UPDATE, params->EmcCfgUpdate);
}
reg::Write(EMC + EMC_CFG, params->EmcCfg);
reg::Write(EMC + EMC_FDPD_CTRL_DQ, params->EmcFdpdCtrlDq);
reg::Write(EMC + EMC_FDPD_CTRL_CMD, params->EmcFdpdCtrlCmd);
reg::Write(EMC + EMC_SEL_DPD_CTRL, params->EmcSelDpdCtrl);
/* Write addr swizzle lock bit. */
reg::Write(EMC + EMC_FBIO_SPARE, params->EmcFbioSpare | 2);
/* Trigger timing update. */
reg::Write(EMC + EMC_TIMING_CONTROL, 1);
if constexpr (SocType == fuse::SocType_Mariko) {
reg::Write(EMC + EMC_CFG_UPDATE, params->EmcCfgUpdate);
}
/* Enable EMC pipe clock gating. */
reg::Write(EMC + EMC_CFG_PIPE_CLK, params->EmcCfgPipeClk);
/* Depending on freqency, enable CMD/CLK fdpd. */
reg::Write(EMC + EMC_FDPD_CTRL_CMD_NO_RAMP, params->EmcFdpdCtrlCmdNoRamp);
if constexpr (SocType == fuse::SocType_Erista) {
reg::ReadWrite(AHB + AHB_ARBITRATION_XBAR_CTRL, AHB_REG_BITS_VALUE(ARBITRATION_XBAR_CTRL_MEM_INIT_DONE, params->AhbArbitrationXbarCtrlMemInitDone));
}
if constexpr (SocType == fuse::SocType_Mariko) {
reg::Write(MC + MC_UNTRANSLATED_REGION_CHECK, params->McUntranslatedRegionCheck);
}
/* Lock carveouts. */
reg::Write(MC + MC_VIDEO_PROTECT_REG_CTRL, params->McVideoProtectWriteAccess);
reg::Write(MC + MC_SEC_CARVEOUT_REG_CTRL, params->McSecCarveoutProtectWriteAccess);
reg::Write(MC + MC_MTS_CARVEOUT_REG_CTRL, params->McMtsCarveoutRegCtrl);
reg::Write(MC + MC_EMEM_CFG_ACCESS_CTRL, 1);
if constexpr (SocType == fuse::SocType_Mariko) {
reg::ReadWrite(AHB + AHB_ARBITRATION_XBAR_CTRL, AHB_REG_BITS_VALUE(ARBITRATION_XBAR_CTRL_MEM_INIT_DONE, params->AhbArbitrationXbarCtrlMemInitDone));
}
}
consteval u32 GetBitMask32(u32 range) {
if (range == BITSIZEOF(u32)) {
return 0xFFFFFFFF;
} else {
return (1u << range) - 1;
}
}
template<fuse::SocType SocType>
void SaveSdramParamsToScratch(BootSdramParams<SocType> *params) {
/* Clear the carveout parameters. */
params->McGeneralizedCarveout1Cfg0 = 0;
params->McGeneralizedCarveout2Cfg0 = 0;
params->McGeneralizedCarveout3Cfg0 = 0;
params->McGeneralizedCarveout4Cfg0 = 0;
params->McGeneralizedCarveout5Cfg0 = 0;
/* Patch spare write. */
{
/* TODO: Clean this up? */
u32 t0 = params->EmcSwizzleRank0Byte0 << 5 >> 29 > params->EmcSwizzleRank0Byte0 << 1 >> 29;
u32 t1 = (t0 & 0xFFFFFFEF) | ((params->EmcSwizzleRank1Byte0 << 5 >> 29 > params->EmcSwizzleRank1Byte0 << 1 >> 29) << 4);
u32 t2 = (t1 & 0xFFFFFFFD) | ((params->EmcSwizzleRank0Byte1 << 5 >> 29 > params->EmcSwizzleRank0Byte1 << 1 >> 29) << 1);
u32 t3 = (t2 & 0xFFFFFFDF) | ((params->EmcSwizzleRank1Byte1 << 5 >> 29 > params->EmcSwizzleRank1Byte1 << 1 >> 29) << 5);
u32 t4 = (t3 & 0xFFFFFFFB) | ((params->EmcSwizzleRank0Byte2 << 5 >> 29 > params->EmcSwizzleRank0Byte2 << 1 >> 29) << 2);
u32 t5 = (t4 & 0xFFFFFFBF) | ((params->EmcSwizzleRank1Byte2 << 5 >> 29 > params->EmcSwizzleRank1Byte2 << 1 >> 29) << 6);
u32 t6 = (t5 & 0xFFFFFFF7) | ((params->EmcSwizzleRank0Byte3 << 5 >> 29 > params->EmcSwizzleRank0Byte3 << 1 >> 29) << 3);
u32 t7 = (t6 & 0xFFFFFF7F) | ((params->EmcSwizzleRank1Byte3 << 5 >> 29 > params->EmcSwizzleRank1Byte3 << 1 >> 29) << 7);
params->SwizzleRankByteEncode = t7;
params->EmcBctSpare2 = 0x40000DD8;
params->EmcBctSpare3 = params->SwizzleRankByteEncode;
}
/* Save parameters to scratch. */
{
u32 cur_reg_offset = APBDEV_PMC_SCRATCH6;
u32 cur_reg_value = reg::Read(PMC + cur_reg_offset);
#define RANGE_HIGH(RANGE) (1 ? RANGE)
#define RANGE_LOW(RANGE) (0 ? RANGE)
static_assert(RANGE_HIGH(31:0) - RANGE_LOW(31:0) + 1 == BITSIZEOF(u32));
#define PROCESS_IMPL(PARAM, SCRATCH, SRC_RANGE, DST_RANGE, DO_READ) \
{ \
constexpr u32 RegisterOffset = APBDEV_PMC_##SCRATCH; \
\
if (RegisterOffset != cur_reg_offset) { \
reg::Write(PMC + cur_reg_offset, cur_reg_value); \
cur_reg_offset = RegisterOffset; \
if constexpr (DO_READ) { \
cur_reg_value = reg::Read(PMC + RegisterOffset); \
} else { \
cur_reg_value = 0; \
} \
} \
\
constexpr u32 SrcRange = RANGE_HIGH(SRC_RANGE) - RANGE_LOW(SRC_RANGE) + 1; \
constexpr u32 DstRange = RANGE_HIGH(DST_RANGE) - RANGE_LOW(DST_RANGE) + 1; \
static_assert(SrcRange == DstRange); \
static_assert(SrcRange <= BITSIZEOF(u32)); \
\
const u32 src_value = params->PARAM; \
if constexpr (SrcRange == BITSIZEOF(u32)) { \
cur_reg_value = src_value; \
} else if constexpr (SrcRange < BITSIZEOF(u32)) { \
constexpr u32 Mask = GetBitMask32(SrcRange) << RANGE_LOW(DST_RANGE); \
\
constexpr u32 SrcLow = RANGE_LOW(SRC_RANGE); \
constexpr u32 DstLow = RANGE_LOW(DST_RANGE); \
constexpr auto Shift = (SrcLow < DstLow) ? (DstLow - SrcLow) \
: (SrcLow - DstLow); \
\
cur_reg_value &= ~Mask; \
if constexpr (SrcLow == DstLow) { \
cur_reg_value |= (src_value & Mask); \
} else if constexpr (SrcLow < DstLow) { \
cur_reg_value |= ((src_value << Shift) & Mask); \
} else { \
cur_reg_value |= ((src_value >> Shift) & Mask); \
} \
} \
}
#define PROCESS_SCRATCH(PARAM, S, SRC_RANGE, DST_RANGE) PROCESS_IMPL(PARAM, SCRATCH##S, SRC_RANGE, DST_RANGE, true)
#define PROCESS_SECURE_SCRATCH(PARAM, S, SRC_RANGE, DST_RANGE) PROCESS_IMPL(PARAM, SECURE_SCRATCH##S, SRC_RANGE, DST_RANGE, true)
#define PROCESS_COMMON_SCRATCH(PARAM, S, SRC_RANGE, DST_RANGE) PROCESS_IMPL(PARAM, SCRATCH##S, SRC_RANGE, DST_RANGE, false)
if constexpr (SocType == fuse::SocType_Erista) {
FOREACH_SDRAM_SCRATCH_REGISTER_ERISTA(PROCESS_SCRATCH);
FOREACH_SDRAM_SECURE_SCRATCH_REGISTER_ERISTA(PROCESS_SECURE_SCRATCH);
} else /* if constexpr (SocType == fuse::SocType_Mariko) */ {
FOREACH_SDRAM_SCRATCH_REGISTER_MARIKO(PROCESS_SCRATCH);
FOREACH_SDRAM_SECURE_SCRATCH_REGISTER_MARIKO(PROCESS_SECURE_SCRATCH);
}
/* Manually process final fields. */
PROCESS_COMMON_SCRATCH(PllMInputDivider, 2, 7:0, 7:0);
PROCESS_COMMON_SCRATCH(PllMFeedbackDivider, 2, 7:0, 15:8);
PROCESS_COMMON_SCRATCH(PllMPostDivider, 2, 4:0, 20:16);
PROCESS_COMMON_SCRATCH(PllMKVCO, 2, 0:0, 17:17);
PROCESS_COMMON_SCRATCH(PllMKCP, 2, 1:0, 19:18);
PROCESS_COMMON_SCRATCH(PllMSetupControl, 35, 15:0, 15:0);
PROCESS_COMMON_SCRATCH(PllMInputDivider, 3, 7:0, 7:0);
cur_reg_value |= 0x3E << 8;
PROCESS_COMMON_SCRATCH(PllMKVCO, 3, 0:0, 21:21);
PROCESS_COMMON_SCRATCH(PllMKCP, 3, 1:0, 23:22);
PROCESS_COMMON_SCRATCH(PllMSetupControl, 36, 23:0, 23:0);
PROCESS_COMMON_SCRATCH(PllMStableTime, 4, 9:0, 9:0);
PROCESS_COMMON_SCRATCH(PllMStableTime, 4, 21:0, 31:10);
/* Write the final field value. */
reg::Write(PMC + cur_reg_offset, cur_reg_value);
#undef PROCESS_COMMON_SCRATCH
#undef PROCESS_SECURE_SCRATCH
#undef PROCESS_SCRATCH
#undef PROCESS_IMPL
#undef RANGE_LOW
#undef RANGE_HIGH
}
}
template<fuse::SocType SocType>
void InitializeSdram(void *generic_params) {
/* Get converted parameters. */
auto *sdram_params = static_cast<BootSdramParams<SocType> *>(generic_params);
/* Enable VDD Memory */
pmic::EnableVddMemory(SocType);
/* Set VDDP select. */
reg::Write(PMC + APBDEV_PMC_VDDP_SEL, sdram_params->PmcVddpSel);
util::WaitMicroSeconds(sdram_params->PmcVddpSelWait);
/* If Erista, Set DDR pad voltage. */
if constexpr (SocType == fuse::SocType_Erista) {
reg::Write(PMC + APBDEV_PMC_DDR_PWR, reg::Read(PMC + APBDEV_PMC_DDR_PWR));
}
/* Turn on MEM IO power. */
reg::Write(PMC + APBDEV_PMC_NO_IOPOWER, sdram_params->PmcNoIoPower);
reg::Write(PMC + APBDEV_PMC_REG_SHORT, sdram_params->PmcRegShort);
reg::Write(PMC + APBDEV_PMC_DDR_CNTRL, sdram_params->PmcDdrCntrl);
/* Apply patch 1. */
*reinterpret_cast<volatile u32 *>(sdram_params->EmcBctSpare0) = sdram_params->EmcBctSpare1;
/* Do main init. */
InitializeSdramImpl<SocType>(sdram_params);
/* Save parameters to scratch. */
SaveSdramParamsToScratch<SocType>(sdram_params);
}
}
void InitializeSdram() {
/* Get soc type. */
const auto soc_type = fuse::GetSocType();
/* Get Sdram params. */
void *sdram_params = GetSdramParams(soc_type);
/* Perform SoC-specific init. */
if (soc_type == fuse::SocType_Erista) {
InitializeSdram<fuse::SocType_Erista>(sdram_params);
} else /* if (soc_type == fuse::SocType_Mariko) */ {
InitializeSdram<fuse::SocType_Mariko>(sdram_params);
}
/* Lock DRAM scratch. */
pmc::LockSecureRegister(pmc::SecureRegister_DramParameters);
}
}
| 65,876
|
C++
|
.cpp
| 935
| 54.197861
| 185
| 0.55972
|
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,319
|
fusee_fs_api.cpp
|
Atmosphere-NX_Atmosphere/fusee/program/source/fs/fusee_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 "fusee_fs_api.hpp"
namespace ams::fs {
static_assert(sizeof(DirectoryEntry) == sizeof(FILINFO));
namespace {
constexpr size_t MaxFiles = 8 + 64;
constexpr size_t MaxDirectories = 2;
constinit bool g_is_sd_mounted = false;
alignas(0x10) constinit FATFS g_sd_fs = {};
alignas(0x10) constinit FIL g_files[MaxFiles] = {};
alignas(0x10) constinit DIR g_dirs[MaxDirectories] = {};
constinit bool g_files_opened[MaxFiles] = {};
constinit bool g_dirs_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);
}
DIR *GetInternalDirectory(DirectoryHandle handle) {
return static_cast<DIR *>(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;
}
ALWAYS_INLINE size_t GetDirectoryIndex(DIR *dp) {
const size_t dir_index = (dp - g_dirs);
AMS_ASSERT(dir_index < MaxDirectories);
return dir_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 GetEntryType(DirectoryEntryType *out_entry_type, bool *out_archive, const char *path) {
/* Get the file info. */
FILINFO info;
R_TRY(TranslateFatFsError(f_stat(path, std::addressof(info))));
/* Handle the file. */
*out_entry_type = (info.fattrib & AM_DIR) ? DirectoryEntryType_Directory : DirectoryEntryType_File;
*out_archive = (info.fattrib & AM_ARC);
R_SUCCEED();
}
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 OpenDirectory(DirectoryHandle *out_dir, const char *path) {
/* Find a free directory. */
for (size_t i = 0; i < MaxDirectories; ++i) {
if (!g_dirs_opened[i]) {
/* Open the file. */
DIR *dp = std::addressof(g_dirs[i]);
R_TRY(TranslateFatFsError(f_opendir(dp, path)));
/* Set the output. */
out_dir->_handle = dp;
g_dirs_opened[i] = true;
R_SUCCEED();
}
}
R_THROW(fs::ResultOpenCountLimit());
}
Result ReadDirectory(s64 *out_count, DirectoryEntry *out_entries, DirectoryHandle handle, s64 max_entries) {
DIR * const dp = GetInternalDirectory(handle);
s64 count = 0;
while (count < max_entries) {
R_TRY(TranslateFatFsError(f_readdir(dp, reinterpret_cast<FILINFO *>(out_entries + count))));
if (out_entries[count].file_name[0] == '\x00') {
break;
}
++count;
}
*out_count = count;
R_SUCCEED();
}
void CloseDirectory(DirectoryHandle handle) {
const size_t index = GetDirectoryIndex(GetInternalDirectory(handle));
f_closedir(std::addressof(g_dirs[index]));
g_dirs_opened[index] = false;
}
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. */
UINT 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. */
UINT 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. */
UINT 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;
}
}
| 11,205
|
C++
|
.cpp
| 263
| 32.030418
| 122
| 0.570509
|
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,320
|
fusee_fs_file_storage.cpp
|
Atmosphere-NX_Atmosphere/fusee/program/source/fs/fusee_fs_file_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 "fusee_fs_storage.hpp"
namespace ams::fs {
Result FileHandleStorage::UpdateSize() {
R_SUCCEED_IF(m_size != InvalidSize);
R_RETURN(GetFileSize(std::addressof(m_size), m_handle));
}
Result FileHandleStorage::Read(s64 offset, void *buffer, size_t size) {
/* Immediately succeed if there's nothing to read. */
R_SUCCEED_IF(size == 0);
/* Validate buffer. */
R_UNLESS(buffer != nullptr, fs::ResultNullptrArgument());
/* Ensure our size is valid. */
R_TRY(this->UpdateSize());
/* Ensure our access is valid. */
R_TRY(IStorage::CheckAccessRange(offset, size, m_size));
R_RETURN(ReadFile(m_handle, offset, buffer, size, fs::ReadOption()));
}
Result FileHandleStorage::Write(s64 offset, const void *buffer, size_t size) {
/* Immediately succeed if there's nothing to write. */
R_SUCCEED_IF(size == 0);
/* Validate buffer. */
R_UNLESS(buffer != nullptr, fs::ResultNullptrArgument());
/* Ensure our size is valid. */
R_TRY(this->UpdateSize());
/* Ensure our access is valid. */
R_TRY(IStorage::CheckAccessRange(offset, size, m_size));
R_RETURN(WriteFile(m_handle, offset, buffer, size, fs::WriteOption()));
}
Result FileHandleStorage::Flush() {
R_RETURN(FlushFile(m_handle));
}
Result FileHandleStorage::GetSize(s64 *out_size) {
R_TRY(this->UpdateSize());
*out_size = m_size;
R_SUCCEED();
}
Result FileHandleStorage::SetSize(s64 size) {
m_size = InvalidSize;
R_RETURN(SetFileSize(m_handle, size));
}
}
| 2,332
|
C++
|
.cpp
| 57
| 34.894737
| 82
| 0.657371
|
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,321
|
fusee_loader_uncompress.cpp
|
Atmosphere-NX_Atmosphere/fusee/loader_stub/source/fusee_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 "fusee_loader_uncompress.hpp"
namespace ams::nxboot::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 and 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,322
|
fusee_loader_main.cpp
|
Atmosphere-NX_Atmosphere/fusee/loader_stub/source/fusee_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 "fusee_loader_uncompress.hpp"
#include "program_lz4.h"
namespace ams::nxboot::loader {
namespace {
constexpr uintptr_t ProgramImageBase = 0x40001000;
constexpr uintptr_t ProgramImageEnd = 0x4003D000;
constexpr size_t ProgramImageSizeMax = ProgramImageEnd - ProgramImageBase;
void CopyBackwards(void *dst, const void *src, size_t size) {
u8 *dst_8 = static_cast<u8 *>(dst) + size;
const u8 *src_8 = static_cast<const u8 *>(src) + size;
for (size_t i = 0; i < size; ++i) {
*(--dst_8) = *(--src_8);
}
}
}
NORETURN void UncompressAndExecute(const void *program, size_t program_size) {
/* Relocate the compressed binary to a place where we can safely decompress it. */
void *relocated_program = reinterpret_cast<void *>(ProgramImageEnd - program_size);
if (relocated_program != program) {
CopyBackwards(relocated_program, program, program_size);
}
/* Uncompress the program image. */
Uncompress(reinterpret_cast<void *>(ProgramImageBase), ProgramImageSizeMax, relocated_program, program_size);
/* Jump to the boot image. */
reinterpret_cast<void (*)()>(ProgramImageBase)();
/* We will never reach this point. */
__builtin_unreachable();
}
}
| 2,034
|
C++
|
.cpp
| 45
| 38.822222
| 117
| 0.669025
|
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,323
|
fusee_loader_error.cpp
|
Atmosphere-NX_Atmosphere/fusee/loader_stub/source/fusee_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 "fusee_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::nxboot::loader::ErrorStop();
}
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::nxboot::loader::ErrorStop();
}
NORETURN void AbortImpl() {
ams::nxboot::loader::ErrorStop();
}
}
namespace ams::nxboot::loader {
NORETURN void ErrorStop() {
/* 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));
}
}
}
| 1,692
|
C++
|
.cpp
| 39
| 36.102564
| 172
| 0.646594
|
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,324
|
sdmmc_test_main.cpp
|
Atmosphere-NX_Atmosphere/exosphere/sdmmc_test/source/sdmmc_test_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>
namespace ams::sdmmc_test {
namespace {
constexpr inline const uintptr_t PMC = secmon::MemoryRegionPhysicalDevicePmc.GetAddress();
constexpr inline auto Port = sdmmc::Port_SdCard0;
alignas(8) constinit u8 g_sd_work_buffer[sdmmc::SdCardWorkBufferSize];
constexpr inline u32 SectorIndex = 0;
constexpr inline u32 SectorCount = 2;
NORETURN void PmcMainReboot() {
/* 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();
}
void CheckResult(const Result result) {
volatile u32 * const DEBUG = reinterpret_cast<volatile u32 *>(0x4003C000);
if (R_FAILED(result)) {
DEBUG[1] = result.GetValue();
PmcMainReboot();
}
}
}
void Main() {
/* Perform butchered hwinit. */
/* TODO: replace with simpler, non-C logic. */
/* nx_hwinit(); */
/* Clear output buffer for debug. */
std::memset((void *)0x40038000, 0xAA, 0x400);
/* Normally, these pins get configured by boot sysmodule during initial pinmux config. */
/* However, they're required to access the SD card. */
{
const uintptr_t apb_misc = dd::QueryIoMapping(0x70000000, 0x4000);
reg::ReadWrite(apb_misc + PINMUX_AUX_SDMMC1_CLK, PINMUX_REG_BITS_ENUM(AUX_E_INPUT, ENABLE),
PINMUX_REG_BITS_ENUM(AUX_TRISTATE, PASSTHROUGH),
PINMUX_REG_BITS_ENUM(AUX_PUPD, PULL_DOWN),
PINMUX_REG_BITS_ENUM(AUX_SDMMC1_CLK_PM, SDMMC1));
reg::ReadWrite(apb_misc + PINMUX_AUX_SDMMC1_CMD, PINMUX_REG_BITS_ENUM(AUX_E_INPUT, ENABLE),
PINMUX_REG_BITS_ENUM(AUX_TRISTATE, PASSTHROUGH),
PINMUX_REG_BITS_ENUM(AUX_PUPD, PULL_UP),
PINMUX_REG_BITS_ENUM(AUX_SDMMC1_CMD_PM, SDMMC1));
reg::ReadWrite(apb_misc + PINMUX_AUX_SDMMC1_DAT3, PINMUX_REG_BITS_ENUM(AUX_E_INPUT, ENABLE),
PINMUX_REG_BITS_ENUM(AUX_TRISTATE, PASSTHROUGH),
PINMUX_REG_BITS_ENUM(AUX_PUPD, PULL_UP),
PINMUX_REG_BITS_ENUM(AUX_SDMMC1_DAT3_PM, SDMMC1));
reg::ReadWrite(apb_misc + PINMUX_AUX_SDMMC1_DAT2, PINMUX_REG_BITS_ENUM(AUX_E_INPUT, ENABLE),
PINMUX_REG_BITS_ENUM(AUX_TRISTATE, PASSTHROUGH),
PINMUX_REG_BITS_ENUM(AUX_PUPD, PULL_UP),
PINMUX_REG_BITS_ENUM(AUX_SDMMC1_DAT2_PM, SDMMC1));
reg::ReadWrite(apb_misc + PINMUX_AUX_SDMMC1_DAT1, PINMUX_REG_BITS_ENUM(AUX_E_INPUT, ENABLE),
PINMUX_REG_BITS_ENUM(AUX_TRISTATE, PASSTHROUGH),
PINMUX_REG_BITS_ENUM(AUX_PUPD, PULL_UP),
PINMUX_REG_BITS_ENUM(AUX_SDMMC1_DAT1_PM, SDMMC1));
reg::ReadWrite(apb_misc + PINMUX_AUX_SDMMC1_DAT0, PINMUX_REG_BITS_ENUM(AUX_E_INPUT, ENABLE),
PINMUX_REG_BITS_ENUM(AUX_TRISTATE, PASSTHROUGH),
PINMUX_REG_BITS_ENUM(AUX_PUPD, PULL_UP),
PINMUX_REG_BITS_ENUM(AUX_SDMMC1_DAT0_PM, SDMMC1));
reg::ReadWrite(apb_misc + PINMUX_AUX_DMIC3_CLK, PINMUX_REG_BITS_ENUM(AUX_E_OD, DISABLE),
PINMUX_REG_BITS_ENUM(AUX_E_INPUT, DISABLE),
PINMUX_REG_BITS_ENUM(AUX_TRISTATE, PASSTHROUGH),
PINMUX_REG_BITS_ENUM(AUX_SDMMC1_DAT0_PM, RSVD2));
}
/* Debug signaler. */
volatile u32 * const DEBUG = reinterpret_cast<volatile u32 *>(0x4003C000);
DEBUG[0] = 0;
DEBUG[1] = 0xAAAAAAAA;
/* Initialize sdmmc library. */
sdmmc::Initialize(Port);
DEBUG[0] = 1;
sdmmc::SetSdCardWorkBuffer(Port, g_sd_work_buffer, sizeof(g_sd_work_buffer));
DEBUG[0] = 2;
Result result = sdmmc::Activate(Port);
DEBUG[0] = 3;
CheckResult(result);
/* Read the first two sectors from disk. */
void * const sector_dst = reinterpret_cast<void *>(0x40038000);
result = sdmmc::Read(sector_dst, SectorCount * sdmmc::SectorSize, Port, SectorIndex, SectorCount);
DEBUG[0] = 4;
CheckResult(result);
/* Get the connection status. */
sdmmc::SpeedMode speed_mode;
sdmmc::BusWidth bus_width;
result = sdmmc::CheckSdCardConnection(std::addressof(speed_mode), std::addressof(bus_width), Port);
/* Save status for debug. */
DEBUG[0] = 5;
DEBUG[1] = result.GetValue();
DEBUG[2] = static_cast<u32>(speed_mode);
DEBUG[3] = static_cast<u32>(bus_width);
/* Perform a reboot. */
PmcMainReboot();
}
NORETURN void ExceptionHandler() {
PmcMainReboot();
}
}
namespace ams::diag {
void AbortImpl() {
sdmmc_test::ExceptionHandler();
}
}
| 6,790
|
C++
|
.cpp
| 114
| 41.22807
| 117
| 0.505268
|
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,325
|
rebootstub_power_off.cpp
|
Atmosphere-NX_Atmosphere/exosphere/program/rebootstub/source/rebootstub_power_off.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::rebootstub {
NORETURN void Halt() {
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));
}
__builtin_unreachable();
}
NORETURN void PowerOff() {
/* Ensure that i2c5 is usable. */
clkrst::EnableI2c5Clock();
/* Initialize i2c5. */
i2c::Initialize(i2c::Port_5);
/* Stop rtc alarms. */
rtc::StopAlarm();
/* Perform a pmic power off. */
pmic::PowerOff();
/* Halt the bpmp. */
Halt();
/* This can never be reached. */
__builtin_unreachable();
}
}
namespace ams::diag {
NORETURN void AbortImpl() {
/* Halt the bpmp. */
rebootstub::Halt();
/* This can never be reached. */
__builtin_unreachable();
}
#include <exosphere/diag/diag_detailed_assertion_impl.inc>
}
| 1,830
|
C++
|
.cpp
| 48
| 30.145833
| 172
| 0.61064
|
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,326
|
secmon_setup.cpp
|
Atmosphere-NX_Atmosphere/exosphere/program/source/secmon_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_setup.hpp"
#include "secmon_error.hpp"
#include "secmon_map.hpp"
#include "secmon_cpu_context.hpp"
#include "secmon_mariko_fatal_error.hpp"
#include "secmon_interrupt_handler.hpp"
#include "secmon_misc.hpp"
#include "smc/secmon_random_cache.hpp"
#include "smc/secmon_smc_power_management.hpp"
#include "smc/secmon_smc_se_lock.hpp"
namespace ams::secmon {
namespace {
constexpr inline const uintptr_t TIMER = secmon::MemoryRegionVirtualDeviceTimer.GetAddress();
constexpr inline const uintptr_t SYSTEM = secmon::MemoryRegionVirtualDeviceSystem.GetAddress();
constexpr inline const uintptr_t APB_MISC = secmon::MemoryRegionVirtualDeviceApbMisc.GetAddress();
constexpr inline const uintptr_t FLOW_CTLR = secmon::MemoryRegionVirtualDeviceFlowController.GetAddress();
constexpr inline const uintptr_t PMC = secmon::MemoryRegionVirtualDevicePmc.GetAddress();
constexpr inline const uintptr_t MC = secmon::MemoryRegionVirtualDeviceMemoryController.GetAddress();
constexpr inline const uintptr_t EVP = secmon::MemoryRegionVirtualDeviceExceptionVectors.GetAddress();
constexpr inline const uintptr_t CLK_RST = secmon::MemoryRegionVirtualDeviceClkRst.GetAddress();
alignas(8) constinit u8 g_se_aes_key_slot_test_vector[se::AesBlockSize] = {};
struct Carveout {
uintptr_t address;
size_t size;
};
constinit Carveout g_kernel_carveouts[KernelCarveoutCount] = {
{ secmon::MemoryRegionDramDefaultKernelCarveout.GetAddress(), secmon::MemoryRegionDramDefaultKernelCarveout.GetSize(), },
{ 0, 0, },
};
constinit bool g_is_cold_boot = true;
constinit se::StickyBits ExpectedSeStickyBits = {
.se_security = (1 << 0), /* SE_HARD_SETTING */
.tzram_security = 0,
.crypto_security_perkey = (1 << pkg1::AesKeySlot_UserEnd) - 1,
.crypto_keytable_access = {
(0 << 7) | (1 << 6) | (1 << 5) | (0 << 4) | (1 << 3) | (0 << 2) | (1 << 1) | (0 << 0), /* 0: User keyslot. KEY. KEYUSE, UIVUPDATE, OIVUPDATE, KEYUPDATE enabled. UIVREAD, OIVREAD, KEYREAD disabled. */
(0 << 7) | (1 << 6) | (1 << 5) | (0 << 4) | (1 << 3) | (0 << 2) | (1 << 1) | (0 << 0), /* 1: User keyslot. KEY. KEYUSE, UIVUPDATE, OIVUPDATE, KEYUPDATE enabled. UIVREAD, OIVREAD, KEYREAD disabled. */
(0 << 7) | (1 << 6) | (1 << 5) | (0 << 4) | (1 << 3) | (0 << 2) | (1 << 1) | (0 << 0), /* 2: User keyslot. KEY. KEYUSE, UIVUPDATE, OIVUPDATE, KEYUPDATE enabled. UIVREAD, OIVREAD, KEYREAD disabled. */
(0 << 7) | (1 << 6) | (1 << 5) | (0 << 4) | (1 << 3) | (0 << 2) | (1 << 1) | (0 << 0), /* 3: User keyslot. KEY. KEYUSE, UIVUPDATE, OIVUPDATE, KEYUPDATE enabled. UIVREAD, OIVREAD, KEYREAD disabled. */
(0 << 7) | (1 << 6) | (1 << 5) | (0 << 4) | (1 << 3) | (0 << 2) | (1 << 1) | (0 << 0), /* 4: User keyslot. KEY. KEYUSE, UIVUPDATE, OIVUPDATE, KEYUPDATE enabled. UIVREAD, OIVREAD, KEYREAD disabled. */
(0 << 7) | (1 << 6) | (1 << 5) | (0 << 4) | (1 << 3) | (0 << 2) | (1 << 1) | (0 << 0), /* 5: User keyslot. KEY. KEYUSE, UIVUPDATE, OIVUPDATE, KEYUPDATE enabled. UIVREAD, OIVREAD, KEYREAD disabled. */
(1 << 7) | (0 << 6) | (0 << 5) | (0 << 4) | (0 << 3) | (0 << 2) | (0 << 1) | (0 << 0), /* 6: Unused keyslot. KEK. KEYUSE, UIVUPDATE, UIVREAD, OIVUPDATE, OIVREAD, KEYUPDATE, KEYREAD disabled. */
(1 << 7) | (0 << 6) | (0 << 5) | (0 << 4) | (0 << 3) | (0 << 2) | (0 << 1) | (0 << 0), /* 7: Unused keyslot. KEK. KEYUSE, UIVUPDATE, UIVREAD, OIVUPDATE, OIVREAD, KEYUPDATE, KEYREAD disabled. */
(0 << 7) | (0 << 6) | (1 << 5) | (0 << 4) | (1 << 3) | (0 << 2) | (1 << 1) | (0 << 0), /* 8: Temp keyslot. KEY. UIVUPDATE, OIVUPDATE, KEYUPDATE enabled. KEYUSE, UIVREAD, OIVREAD, KEYREAD disabled. */
(0 << 7) | (0 << 6) | (1 << 5) | (0 << 4) | (1 << 3) | (0 << 2) | (1 << 1) | (0 << 0), /* 9: SmcTemp keyslot. KEY. UIVUPDATE, OIVUPDATE, KEYUPDATE enabled. KEYUSE, UIVREAD, OIVREAD, KEYREAD disabled. */
(1 << 7) | (0 << 6) | (0 << 5) | (0 << 4) | (0 << 3) | (0 << 2) | (0 << 1) | (0 << 0), /* 10: Wrap1 keyslot. KEK. KEYUSE, UIVUPDATE, UIVREAD, OIVUPDATE, OIVREAD, KEYUPDATE, KEYREAD disabled. */
(0 << 7) | (0 << 6) | (0 << 5) | (0 << 4) | (0 << 3) | (0 << 2) | (0 << 1) | (0 << 0), /* 11: Wrap2 keyslot. KEY. KEYUSE, UIVUPDATE, UIVREAD, OIVUPDATE, OIVREAD, KEYUPDATE, KEYREAD disabled. */
(1 << 7) | (0 << 6) | (0 << 5) | (0 << 4) | (0 << 3) | (0 << 2) | (0 << 1) | (0 << 0), /* 12: DMaster keyslot. KEK. KEYUSE, UIVUPDATE, UIVREAD, OIVUPDATE, OIVREAD, KEYUPDATE, KEYREAD disabled. */
(1 << 7) | (0 << 6) | (0 << 5) | (0 << 4) | (0 << 3) | (0 << 2) | (0 << 1) | (0 << 0), /* 13: Master keyslot. KEK. KEYUSE, UIVUPDATE, UIVREAD, OIVUPDATE, OIVREAD, KEYUPDATE, KEYREAD disabled. */
(1 << 7) | (0 << 6) | (0 << 5) | (0 << 4) | (0 << 3) | (0 << 2) | (0 << 1) | (0 << 0), /* 14: Unused keyslot. KEK. KEYUSE, UIVUPDATE, UIVREAD, OIVUPDATE, OIVREAD, KEYUPDATE, KEYREAD disabled. */
(1 << 7) | (0 << 6) | (0 << 5) | (0 << 4) | (0 << 3) | (0 << 2) | (0 << 1) | (0 << 0), /* 13: Device keyslot. KEK. KEYUSE, UIVUPDATE, UIVREAD, OIVUPDATE, OIVREAD, KEYUPDATE, KEYREAD disabled. */
},
.rsa_security_perkey = 0,
.rsa_keytable_access = {
(0 << 2) | (1 << 1) | (0 << 0), /* KEYUSE/KEYREAD disabled, KEYUPDATE enabled. */
(0 << 2) | (1 << 1) | (0 << 0), /* KEYUSE/KEYREAD disabled, KEYUPDATE enabled. */
},
};
void InitializeConfigurationContext() {
/* Get the global context. */
auto &ctx = ::ams::secmon::impl::GetConfigurationContext();
/* Clear the context to zero. */
std::memset(std::addressof(ctx), 0, sizeof(ctx));
/* If the storage context is valid, we want to copy it to the global context. */
if (const auto &storage_ctx = *MemoryRegionPhysicalDramMonitorConfiguration.GetPointer<const SecureMonitorStorageConfiguration>(); storage_ctx.IsValid()) {
ctx.secmon_cfg.CopyFrom(storage_ctx);
ctx.emummc_cfg = storage_ctx.emummc_cfg;
} else {
/* If we don't have a valid storage context, we can just use the default one. */
ctx.secmon_cfg = DefaultSecureMonitorConfiguration;
}
/* Cache the fuse info for quick access. */
ctx.secmon_cfg.SetFuseInfo();
}
void GenerateSecurityEngineAesKeySlotTestVector(void *dst, size_t size) {
/* Clear the output. */
AMS_ABORT_UNLESS(size == se::AesBlockSize);
std::memset(dst, 0, se::AesBlockSize);
/* Ensure output is seen as cleared by the se. */
hw::FlushDataCache(dst, se::AesBlockSize);
hw::DataSynchronizationBarrierInnerShareable();
/* Declare a block. */
alignas(8) u8 empty_block[se::AesBlockSize];
/* Iteratively transform an empty block. */
#define TRANSFORM_WITH_KEY(key) \
__builtin_memset(empty_block, 0, sizeof(empty_block)); \
se::SetEncryptedAesKey256(pkg1::AesKeySlot_Temporary, key, empty_block, sizeof(empty_block)); \
se::DecryptAes128(dst, se::AesBlockSize, pkg1::AesKeySlot_Temporary, dst, se::AesBlockSize)
TRANSFORM_WITH_KEY(pkg1::AesKeySlot_RandomForUserWrap);
TRANSFORM_WITH_KEY(pkg1::AesKeySlot_RandomForKeyStorageWrap);
TRANSFORM_WITH_KEY(pkg1::AesKeySlot_Master);
TRANSFORM_WITH_KEY(pkg1::AesKeySlot_DeviceMaster);
TRANSFORM_WITH_KEY(pkg1::AesKeySlot_Device);
TRANSFORM_WITH_KEY(pkg1::AesKeySlot_RandomForUserWrap);
TRANSFORM_WITH_KEY(pkg1::AesKeySlot_RandomForKeyStorageWrap);
TRANSFORM_WITH_KEY(pkg1::AesKeySlot_Master);
TRANSFORM_WITH_KEY(pkg1::AesKeySlot_DeviceMaster);
TRANSFORM_WITH_KEY(pkg1::AesKeySlot_Device);
/* Ensure output is seen correctly by the cpu. */
hw::FlushDataCache(dst, se::AesBlockSize);
hw::DataSynchronizationBarrierInnerShareable();
/* Clear the temporary key slot. */
se::ClearAesKeySlot(pkg1::AesKeySlot_Temporary);
}
void VerifySecurityEngineStickyBits() {
/* On mariko, an extra sticky bit is set. */
if (GetSocType() == fuse::SocType_Mariko) {
ExpectedSeStickyBits.se_security |= (1 << 5);
} else /* if (GetSocType() == fuse::SocType_Erista) */ {
/* Erista does not support DST_KEYTABLE_ONLY, and so all keys will have the bit clear. */
for (size_t i = 0; i < util::size(ExpectedSeStickyBits.crypto_keytable_access); ++i) {
ExpectedSeStickyBits.crypto_keytable_access[i] &= ~(1 << 7);
}
}
if (!se::ValidateStickyBits(ExpectedSeStickyBits)) {
SetError(pkg1::ErrorInfo_InvalidSecurityEngineStickyBits);
AMS_ABORT("Invalid sticky bits");
}
}
void VerifySecurityEngineAesKeySlotTestVector() {
alignas(8) u8 test_vector[se::AesBlockSize];
GenerateSecurityEngineAesKeySlotTestVector(test_vector, sizeof(test_vector));
AMS_ABORT_UNLESS(crypto::IsSameBytes(g_se_aes_key_slot_test_vector, test_vector, se::AesBlockSize));
}
void ClearAesKeySlots() {
/* Clear all non-secure monitor keys. */
for (int i = 0; i < pkg1::AesKeySlot_SecmonStart; ++i) {
se::ClearAesKeySlot(i);
}
/* Clear the secure-monitor temporary keys. */
se::ClearAesKeySlot(pkg1::AesKeySlot_Temporary);
se::ClearAesKeySlot(pkg1::AesKeySlot_Smc);
}
void ClearRsaKeySlots() {
/* Clear all rsa keyslots. */
for (int i = 0; i < se::RsaKeySlotCount; ++i) {
se::ClearRsaKeySlot(i);
}
}
void SetupKernelCarveouts() {
#define MC_ENABLE_CLIENT_ACCESS(INDEX, WHICH) MC_REG_BITS_ENUM(CLIENT_ACCESS##INDEX##_##WHICH, ENABLE)
constexpr u32 ClientAccess0 = reg::Encode(MC_ENABLE_CLIENT_ACCESS(0, PTCR),
MC_ENABLE_CLIENT_ACCESS(0, DISPLAY0A),
MC_ENABLE_CLIENT_ACCESS(0, DISPLAY0AB),
MC_ENABLE_CLIENT_ACCESS(0, DISPLAY0B),
MC_ENABLE_CLIENT_ACCESS(0, DISPLAY0BB),
MC_ENABLE_CLIENT_ACCESS(0, DISPLAY0C),
MC_ENABLE_CLIENT_ACCESS(0, DISPLAY0CB),
MC_ENABLE_CLIENT_ACCESS(0, AFIR),
MC_ENABLE_CLIENT_ACCESS(0, DISPLAYHC),
MC_ENABLE_CLIENT_ACCESS(0, DISPLAYHCB),
MC_ENABLE_CLIENT_ACCESS(0, HDAR),
MC_ENABLE_CLIENT_ACCESS(0, HOST1XDMAR),
MC_ENABLE_CLIENT_ACCESS(0, HOST1XR),
MC_ENABLE_CLIENT_ACCESS(0, NVENCSRD),
MC_ENABLE_CLIENT_ACCESS(0, PPCSAHBDMAR),
MC_ENABLE_CLIENT_ACCESS(0, PPCSAHBSLVR));
constexpr u32 ClientAccess1 = reg::Encode(MC_ENABLE_CLIENT_ACCESS(1, MPCORER),
MC_ENABLE_CLIENT_ACCESS(1, NVENCSWR),
MC_ENABLE_CLIENT_ACCESS(1, AFIW),
MC_ENABLE_CLIENT_ACCESS(1, HDAW),
MC_ENABLE_CLIENT_ACCESS(1, HOST1XW),
MC_ENABLE_CLIENT_ACCESS(1, MPCOREW),
MC_ENABLE_CLIENT_ACCESS(1, PPCSAHBDMAW),
MC_ENABLE_CLIENT_ACCESS(1, PPCSAHBSLVW));
constexpr u32 ClientAccess2 = reg::Encode(MC_ENABLE_CLIENT_ACCESS(2, XUSB_HOSTR),
MC_ENABLE_CLIENT_ACCESS(2, XUSB_HOSTW),
MC_ENABLE_CLIENT_ACCESS(2, XUSB_DEVR),
MC_ENABLE_CLIENT_ACCESS(2, XUSB_DEVW));
constexpr u32 ClientAccess2_100 = reg::Encode(MC_ENABLE_CLIENT_ACCESS(2, XUSB_HOSTR),
MC_ENABLE_CLIENT_ACCESS(2, XUSB_HOSTW),
MC_ENABLE_CLIENT_ACCESS(2, XUSB_DEVR),
MC_ENABLE_CLIENT_ACCESS(2, XUSB_DEVW),
MC_ENABLE_CLIENT_ACCESS(2, TSECSRD),
MC_ENABLE_CLIENT_ACCESS(2, TSECSWR));
constexpr u32 ClientAccess3 = reg::Encode(MC_ENABLE_CLIENT_ACCESS(3, SDMMCRA),
MC_ENABLE_CLIENT_ACCESS(3, SDMMCRAA),
MC_ENABLE_CLIENT_ACCESS(3, SDMMCRAB),
MC_ENABLE_CLIENT_ACCESS(3, SDMMCWA),
MC_ENABLE_CLIENT_ACCESS(3, SDMMCWAA),
MC_ENABLE_CLIENT_ACCESS(3, SDMMCWAB),
MC_ENABLE_CLIENT_ACCESS(3, VICSRD),
MC_ENABLE_CLIENT_ACCESS(3, VICSWR),
MC_ENABLE_CLIENT_ACCESS(3, DISPLAYD),
MC_ENABLE_CLIENT_ACCESS(3, APER),
MC_ENABLE_CLIENT_ACCESS(3, APEW),
MC_ENABLE_CLIENT_ACCESS(3, NVJPGSRD),
MC_ENABLE_CLIENT_ACCESS(3, NVJPGSWR));
constexpr u32 ClientAccess3_100 = reg::Encode(MC_ENABLE_CLIENT_ACCESS(3, SDMMCRA),
MC_ENABLE_CLIENT_ACCESS(3, SDMMCRAA),
MC_ENABLE_CLIENT_ACCESS(3, SDMMCRAB),
MC_ENABLE_CLIENT_ACCESS(3, SDMMCWA),
MC_ENABLE_CLIENT_ACCESS(3, SDMMCWAA),
MC_ENABLE_CLIENT_ACCESS(3, SDMMCWAB),
MC_ENABLE_CLIENT_ACCESS(3, VICSRD),
MC_ENABLE_CLIENT_ACCESS(3, VICSWR),
MC_ENABLE_CLIENT_ACCESS(3, DISPLAYD),
MC_ENABLE_CLIENT_ACCESS(3, NVDECSRD),
MC_ENABLE_CLIENT_ACCESS(3, NVDECSWR),
MC_ENABLE_CLIENT_ACCESS(3, APER),
MC_ENABLE_CLIENT_ACCESS(3, APEW),
MC_ENABLE_CLIENT_ACCESS(3, NVJPGSRD),
MC_ENABLE_CLIENT_ACCESS(3, NVJPGSWR));
constexpr u32 ClientAccess4 = reg::Encode(MC_ENABLE_CLIENT_ACCESS(4, SESRD),
MC_ENABLE_CLIENT_ACCESS(4, SESWR));
constexpr u32 ClientAccess4_800 = reg::Encode(MC_ENABLE_CLIENT_ACCESS(4, SESRD),
MC_ENABLE_CLIENT_ACCESS(4, SESWR),
MC_ENABLE_CLIENT_ACCESS(4, TSECRDB),
MC_ENABLE_CLIENT_ACCESS(4, TSECWRB));
constexpr u32 ClientAccess4_100 = reg::Encode(MC_ENABLE_CLIENT_ACCESS(4, SESRD),
MC_ENABLE_CLIENT_ACCESS(4, SESWR));
#undef MC_ENABLE_CLIENT_ACCESS
constexpr u32 ForceInternalAccess0 = reg::Encode(MC_REG_BITS_ENUM(CLIENT_ACCESS0_AVPCARM7R, ENABLE));
constexpr u32 ForceInternalAccess0_100 = 0;
constexpr u32 ForceInternalAccess1 = reg::Encode(MC_REG_BITS_ENUM(CLIENT_ACCESS1_AVPCARM7W, ENABLE));
constexpr u32 ForceInternalAccess1_100 = 0;
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, ENABLED),
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, ENABLED),
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, ANY_ADDRESS),
MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_LOCK_MODE, LOCKED),
MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_PROTECT_MODE, TZ_SECURE));
constexpr u32 CarveoutConfig_100 = 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, ANY_ADDRESS),
MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_LOCK_MODE, LOCKED),
MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_PROTECT_MODE, TZ_SECURE));
const u32 target_fw = GetTargetFirmware();
u32 client_access_2;
u32 client_access_3;
u32 client_access_4;
u32 carveout_config;
if (target_fw >= TargetFirmware_8_1_0) {
client_access_2 = ClientAccess2;
client_access_3 = ClientAccess3;
client_access_4 = ClientAccess4;
carveout_config = CarveoutConfig;
} else if (target_fw >= TargetFirmware_8_0_0) {
client_access_2 = ClientAccess2;
client_access_3 = ClientAccess3;
client_access_4 = ClientAccess4_800;
carveout_config = CarveoutConfig;
} else {
client_access_2 = ClientAccess2_100;
client_access_3 = ClientAccess3_100;
client_access_4 = ClientAccess4_100;
carveout_config = CarveoutConfig_100;
}
/* Configure carveout 4. */
reg::Write(MC + MC_SECURITY_CARVEOUT4_BOM, g_kernel_carveouts[0].address >> 0);
reg::Write(MC + MC_SECURITY_CARVEOUT4_BOM_HI, g_kernel_carveouts[0].address >> 32);
reg::Write(MC + MC_SECURITY_CARVEOUT4_SIZE_128KB, g_kernel_carveouts[0].size / 128_KB);
reg::Write(MC + MC_SECURITY_CARVEOUT4_CLIENT_ACCESS0, ClientAccess0);
reg::Write(MC + MC_SECURITY_CARVEOUT4_CLIENT_ACCESS1, ClientAccess1);
reg::Write(MC + MC_SECURITY_CARVEOUT4_CLIENT_ACCESS2, client_access_2);
reg::Write(MC + MC_SECURITY_CARVEOUT4_CLIENT_ACCESS3, client_access_3);
reg::Write(MC + MC_SECURITY_CARVEOUT4_CLIENT_ACCESS4, client_access_4);
reg::Write(MC + MC_SECURITY_CARVEOUT4_CLIENT_FORCE_INTERNAL_ACCESS0, (target_fw >= TargetFirmware_4_0_0) ? ForceInternalAccess0 : ForceInternalAccess0_100);
reg::Write(MC + MC_SECURITY_CARVEOUT4_CLIENT_FORCE_INTERNAL_ACCESS1, (target_fw >= TargetFirmware_4_0_0) ? ForceInternalAccess1 : ForceInternalAccess1_100);
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, carveout_config);
/* Configure carveout 5. */
reg::Write(MC + MC_SECURITY_CARVEOUT5_BOM, g_kernel_carveouts[1].address >> 0);
reg::Write(MC + MC_SECURITY_CARVEOUT5_BOM_HI, g_kernel_carveouts[1].address >> 32);
reg::Write(MC + MC_SECURITY_CARVEOUT5_SIZE_128KB, g_kernel_carveouts[1].size / 128_KB);
reg::Write(MC + MC_SECURITY_CARVEOUT5_CLIENT_ACCESS0, ClientAccess0);
reg::Write(MC + MC_SECURITY_CARVEOUT5_CLIENT_ACCESS1, ClientAccess1);
reg::Write(MC + MC_SECURITY_CARVEOUT5_CLIENT_ACCESS2, client_access_2);
reg::Write(MC + MC_SECURITY_CARVEOUT5_CLIENT_ACCESS3, client_access_3);
reg::Write(MC + MC_SECURITY_CARVEOUT5_CLIENT_ACCESS4, client_access_4);
reg::Write(MC + MC_SECURITY_CARVEOUT5_CLIENT_FORCE_INTERNAL_ACCESS0, 0);
reg::Write(MC + MC_SECURITY_CARVEOUT5_CLIENT_FORCE_INTERNAL_ACCESS1, 0);
reg::Write(MC + MC_SECURITY_CARVEOUT5_CLIENT_FORCE_INTERNAL_ACCESS2, 0);
reg::Write(MC + MC_SECURITY_CARVEOUT5_CLIENT_FORCE_INTERNAL_ACCESS3, 0);
reg::Write(MC + MC_SECURITY_CARVEOUT5_CLIENT_FORCE_INTERNAL_ACCESS4, 0);
reg::Write(MC + MC_SECURITY_CARVEOUT5_CFG0, carveout_config);
}
void ConfigureSlaveSecurity() {
u32 reg0, reg1, reg2;
if (GetTargetFirmware() > TargetFirmware_1_0_0) {
reg0 = reg::Encode(SLAVE_SECURITY_REG_BITS_ENUM(0, SATA_AUX, ENABLE),
SLAVE_SECURITY_REG_BITS_ENUM(0, DTV, ENABLE),
SLAVE_SECURITY_REG_BITS_ENUM(0, QSPI, ENABLE),
SLAVE_SECURITY_REG_BITS_ENUM(0, SE, ENABLE),
SLAVE_SECURITY_REG_BITS_ENUM(0, SATA, ENABLE),
SLAVE_SECURITY_REG_BITS_ENUM(0, LA, ENABLE));
reg1 = reg::Encode(SLAVE_SECURITY_REG_BITS_ENUM(1, SPI1, ENABLE),
SLAVE_SECURITY_REG_BITS_ENUM(1, SPI2, ENABLE),
SLAVE_SECURITY_REG_BITS_ENUM(1, SPI3, ENABLE),
SLAVE_SECURITY_REG_BITS_ENUM(1, SPI5, ENABLE),
SLAVE_SECURITY_REG_BITS_ENUM(1, SPI6, ENABLE),
SLAVE_SECURITY_REG_BITS_ENUM(1, I2C6, ENABLE));
reg2 = reg::Encode(SLAVE_SECURITY_REG_BITS_ENUM(2, SDMMC3, ENABLE),
SLAVE_SECURITY_REG_BITS_ENUM(2, DDS, ENABLE),
SLAVE_SECURITY_REG_BITS_ENUM(2, DP2, ENABLE));
const auto hw_type = GetHardwareType();
/* Switch Lite can't use HDMI, so set CEC to secure on hoag. */
if (hw_type == fuse::HardwareType_Hoag) {
reg0 |= reg::Encode(SLAVE_SECURITY_REG_BITS_ENUM(0, CEC, ENABLE));
}
/* Icosa, Iowa, and Aula all set I2C4 to be secure. */
if (hw_type == fuse::HardwareType_Icosa && hw_type == fuse::HardwareType_Iowa && hw_type == fuse::HardwareType_Aula) {
reg1 |= reg::Encode(SLAVE_SECURITY_REG_BITS_ENUM(1, I2C4, ENABLE));
}
/* Hoag additionally sets UART_B to secure. */
if (hw_type == fuse::HardwareType_Hoag) {
reg1 |= reg::Encode(SLAVE_SECURITY_REG_BITS_ENUM(1, UART_B, ENABLE));
}
/* Copper and Calcio lack a lot of hardware, so set the corresponding registers to secure for them. */
if (hw_type == fuse::HardwareType_Calcio || hw_type == fuse::HardwareType_Copper) {
reg1 |= reg::Encode(SLAVE_SECURITY_REG_BITS_ENUM(1, UART_B, ENABLE),
SLAVE_SECURITY_REG_BITS_ENUM(1, UART_C, ENABLE),
SLAVE_SECURITY_REG_BITS_ENUM(1, SPI4, ENABLE),
SLAVE_SECURITY_REG_BITS_ENUM(1, I2C2, ENABLE),
SLAVE_SECURITY_REG_BITS_ENUM(1, I2C3, ENABLE));
/* Copper/Calcio have no gamecard reader, and thus set SDMMC2 as secure. */
reg2 |= reg::Encode(SLAVE_SECURITY_REG_BITS_ENUM(2, SDMMC2, ENABLE));
}
/* Mariko hardware types (not Icosa or Copper) additionally set mariko-only mmio (SE2, PKA1, FEK) as secure. */
if (hw_type != fuse::HardwareType_Icosa && hw_type != fuse::HardwareType_Copper) {
reg2 |= reg::Encode(SLAVE_SECURITY_REG_BITS_ENUM(2, SE2, ENABLE),
SLAVE_SECURITY_REG_BITS_ENUM(2, PKA1, ENABLE),
SLAVE_SECURITY_REG_BITS_ENUM(2, FEK, ENABLE));
}
} else {
reg0 = reg::Encode(SLAVE_SECURITY_REG_BITS_ENUM(0, SATA_AUX, ENABLE),
SLAVE_SECURITY_REG_BITS_ENUM(0, DTV, ENABLE),
SLAVE_SECURITY_REG_BITS_ENUM(0, QSPI, ENABLE),
SLAVE_SECURITY_REG_BITS_ENUM(0, SATA, ENABLE),
SLAVE_SECURITY_REG_BITS_ENUM(0, LA, ENABLE));
reg1 = reg::Encode(SLAVE_SECURITY_REG_BITS_ENUM(1, SPI1, ENABLE),
SLAVE_SECURITY_REG_BITS_ENUM(1, SPI2, ENABLE),
SLAVE_SECURITY_REG_BITS_ENUM(1, SPI3, ENABLE),
SLAVE_SECURITY_REG_BITS_ENUM(1, SPI5, ENABLE),
SLAVE_SECURITY_REG_BITS_ENUM(1, SPI6, ENABLE),
SLAVE_SECURITY_REG_BITS_ENUM(1, I2C6, ENABLE));
reg2 = reg::Encode(SLAVE_SECURITY_REG_BITS_ENUM(2, DDS, ENABLE),
REG_BITS_VALUE(5, 1, 1), /* Note: Bit 5 is not documented in TRM. */
REG_BITS_VALUE(4, 1, 1)); /* Note: Bit 4 is not documented in TRM. */
}
reg::Write(APB_MISC + APB_MISC_SECURE_REGS_APB_SLAVE_SECURITY_ENABLE_REG0_0, reg0);
reg::Write(APB_MISC + APB_MISC_SECURE_REGS_APB_SLAVE_SECURITY_ENABLE_REG1_0, reg1);
reg::Write(APB_MISC + APB_MISC_SECURE_REGS_APB_SLAVE_SECURITY_ENABLE_REG2_0, reg2);
}
void SetupSecureRegisters() {
/* Configure timers 5-8 and watchdog timers 0-3 as secure. */
reg::Write(TIMER + TIMER_SHARED_TIMER_SECURE_CFG, TIMER_REG_BITS_ENUM(SHARED_TIMER_SECURE_CFG_TMR5, ENABLE),
TIMER_REG_BITS_ENUM(SHARED_TIMER_SECURE_CFG_TMR6, ENABLE),
TIMER_REG_BITS_ENUM(SHARED_TIMER_SECURE_CFG_TMR7, ENABLE),
TIMER_REG_BITS_ENUM(SHARED_TIMER_SECURE_CFG_TMR8, ENABLE),
TIMER_REG_BITS_ENUM(SHARED_TIMER_SECURE_CFG_WDT0, ENABLE),
TIMER_REG_BITS_ENUM(SHARED_TIMER_SECURE_CFG_WDT1, ENABLE),
TIMER_REG_BITS_ENUM(SHARED_TIMER_SECURE_CFG_WDT2, ENABLE),
TIMER_REG_BITS_ENUM(SHARED_TIMER_SECURE_CFG_WDT3, ENABLE));
/* Lock cluster switching, to prevent usage of the A53 cores. */
reg::Write(FLOW_CTLR + FLOW_CTLR_BPMP_CLUSTER_CONTROL, FLOW_REG_BITS_ENUM(BPMP_CLUSTER_CONTROL_ACTIVE_CLUSTER_LOCK, ENABLE),
FLOW_REG_BITS_ENUM(BPMP_CLUSTER_CONTROL_CLUSTER_SWITCH_ENABLE, DISABLE),
FLOW_REG_BITS_ENUM(BPMP_CLUSTER_CONTROL_ACTIVE_CLUSTER, FAST));
/* Enable flow controller debug qualifier for legacy FIQs. */
reg::Write(FLOW_CTLR + FLOW_CTLR_FLOW_DBG_QUAL, FLOW_REG_BITS_ENUM(FLOW_DBG_QUAL_FIQ2CCPLEX_ENABLE, ENABLE));
/* Configure the PMC to disable deep power-down. */
reg::Write(PMC + APBDEV_PMC_DPD_ENABLE, PMC_REG_BITS_ENUM(DPD_ENABLE_TSC_MULT_EN, DISABLE),
PMC_REG_BITS_ENUM(DPD_ENABLE_ON, DISABLE));
/* Configure the video protect region. */
reg::Write(MC + MC_VIDEO_PROTECT_GPU_OVERRIDE_0, 1);
reg::Write(MC + MC_VIDEO_PROTECT_GPU_OVERRIDE_1, 0);
reg::Write(MC + MC_VIDEO_PROTECT_BOM, 0);
reg::Write(MC + MC_VIDEO_PROTECT_SIZE_MB, 0);
reg::Write(MC + MC_VIDEO_PROTECT_REG_CTRL, MC_REG_BITS_ENUM(VIDEO_PROTECT_REG_CTRL_VIDEO_PROTECT_ALLOW_TZ_WRITE, DISABLED),
MC_REG_BITS_ENUM(VIDEO_PROTECT_REG_CTRL_VIDEO_PROTECT_WRITE_ACCESS, DISABLED));
/* Configure the SEC carveout. */
reg::Write(MC + MC_SEC_CARVEOUT_BOM, 0);
reg::Write(MC + MC_SEC_CARVEOUT_SIZE_MB, 0);
reg::Write(MC + MC_SEC_CARVEOUT_REG_CTRL, MC_REG_BITS_ENUM(SEC_CARVEOUT_REG_CTRL_SEC_CARVEOUT_WRITE_ACCESS, DISABLED));
/* Configure the MTS carveout. */
reg::Write(MC + MC_MTS_CARVEOUT_BOM, 0);
reg::Write(MC + MC_MTS_CARVEOUT_SIZE_MB, 0);
reg::Write(MC + MC_MTS_CARVEOUT_ADR_HI, 0);
reg::Write(MC + MC_MTS_CARVEOUT_REG_CTRL, MC_REG_BITS_ENUM(MTS_CARVEOUT_REG_CTRL_MTS_CARVEOUT_WRITE_ACCESS, DISABLED));
/* Configure the security carveout. */
reg::Write(MC + MC_SECURITY_CFG0, MC_REG_BITS_VALUE(SECURITY_CFG0_SECURITY_BOM, 0));
reg::Write(MC + MC_SECURITY_CFG1, MC_REG_BITS_VALUE(SECURITY_CFG1_SECURITY_SIZE, 0));
reg::Write(MC + MC_SECURITY_CFG3, MC_REG_BITS_VALUE(SECURITY_CFG3_SECURITY_BOM_HI, 3));
/* Configure security carveout 1. */
reg::Write(MC + MC_SECURITY_CARVEOUT1_BOM, 0);
reg::Write(MC + MC_SECURITY_CARVEOUT1_BOM_HI, 0);
reg::Write(MC + MC_SECURITY_CARVEOUT1_SIZE_128KB, 0);
reg::Write(MC + MC_SECURITY_CARVEOUT1_CLIENT_ACCESS0, 0);
reg::Write(MC + MC_SECURITY_CARVEOUT1_CLIENT_ACCESS1, 0);
reg::Write(MC + MC_SECURITY_CARVEOUT1_CLIENT_ACCESS2, 0);
reg::Write(MC + MC_SECURITY_CARVEOUT1_CLIENT_ACCESS3, 0);
reg::Write(MC + MC_SECURITY_CARVEOUT1_CLIENT_ACCESS4, 0);
reg::Write(MC + MC_SECURITY_CARVEOUT1_CLIENT_FORCE_INTERNAL_ACCESS0, 0);
reg::Write(MC + MC_SECURITY_CARVEOUT1_CLIENT_FORCE_INTERNAL_ACCESS1, 0);
reg::Write(MC + MC_SECURITY_CARVEOUT1_CLIENT_FORCE_INTERNAL_ACCESS2, 0);
reg::Write(MC + MC_SECURITY_CARVEOUT1_CLIENT_FORCE_INTERNAL_ACCESS3, 0);
reg::Write(MC + MC_SECURITY_CARVEOUT1_CLIENT_FORCE_INTERNAL_ACCESS4, 0);
reg::Write(MC + MC_SECURITY_CARVEOUT1_CFG0, MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_IS_WPR, DISABLED),
MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_FORCE_APERTURE_ID_MATCH, ENABLED),
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, DISABLED),
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, DISABLED),
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, LOCKBIT_SECURE));
/* Security carveout 2 will be configured later by SetupGpuCarveout, after magic values are written to configure gpu/tsec. */
/* Configure carveout 3. */
reg::Write(MC + MC_SECURITY_CARVEOUT3_BOM, 0);
reg::Write(MC + MC_SECURITY_CARVEOUT3_BOM_HI, 0);
reg::Write(MC + MC_SECURITY_CARVEOUT3_SIZE_128KB, 0);
reg::Write(MC + MC_SECURITY_CARVEOUT3_CLIENT_ACCESS0, 0);
reg::Write(MC + MC_SECURITY_CARVEOUT3_CLIENT_ACCESS1, 0);
reg::Write(MC + MC_SECURITY_CARVEOUT3_CLIENT_ACCESS2, MC_REG_BITS_ENUM (CLIENT_ACCESS2_GPUSRD, ENABLE),
MC_REG_BITS_ENUM (CLIENT_ACCESS2_GPUSWR, ENABLE));
reg::Write(MC + MC_SECURITY_CARVEOUT3_CLIENT_ACCESS3, 0);
reg::Write(MC + MC_SECURITY_CARVEOUT3_CLIENT_ACCESS4, MC_REG_BITS_ENUM (CLIENT_ACCESS4_GPUSRD2, ENABLE),
MC_REG_BITS_ENUM (CLIENT_ACCESS4_GPUSWR2, ENABLE));
reg::Write(MC + MC_SECURITY_CARVEOUT3_CLIENT_FORCE_INTERNAL_ACCESS0, 0);
reg::Write(MC + MC_SECURITY_CARVEOUT3_CLIENT_FORCE_INTERNAL_ACCESS1, 0);
reg::Write(MC + MC_SECURITY_CARVEOUT3_CLIENT_FORCE_INTERNAL_ACCESS2, 0);
reg::Write(MC + MC_SECURITY_CARVEOUT3_CLIENT_FORCE_INTERNAL_ACCESS3, 0);
reg::Write(MC + MC_SECURITY_CARVEOUT3_CLIENT_FORCE_INTERNAL_ACCESS4, 0);
reg::Write(MC + MC_SECURITY_CARVEOUT3_CFG0, MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_IS_WPR, DISABLED),
MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_FORCE_APERTURE_ID_MATCH, ENABLED),
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, ENABLED),
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, 3),
MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_WRITE_ACCESS_LEVEL3, ENABLED),
MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_WRITE_ACCESS_LEVEL2, ENABLED),
MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_WRITE_ACCESS_LEVEL1, DISABLED),
MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_WRITE_ACCESS_LEVEL0, DISABLED),
MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_READ_ACCESS_LEVEL3, ENABLED),
MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_READ_ACCESS_LEVEL2, ENABLED),
MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_READ_ACCESS_LEVEL1, ENABLED),
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, LOCKBIT_SECURE));
/* If we're cold-booting and on 1.0.0, alter the default carveout size. */
if (g_is_cold_boot && GetTargetFirmware() <= TargetFirmware_1_0_0) {
g_kernel_carveouts[0].size = 200 * 128_KB;
}
/* NOTE: Here Nintendo configures the two kernel carveouts; we will do this later, to allow fusee to continue using AVP_CACHE. */
/* SetupKernelCarveouts(); */
/* Configure slave register security. */
ConfigureSlaveSecurity();
}
void SetupSmmu() {
/* Turn on SMMU translation for all devices. */
reg::Write(MC + MC_SMMU_TRANSLATION_ENABLE_0, ~0u);
reg::Write(MC + MC_SMMU_TRANSLATION_ENABLE_1, ~0u);
reg::Write(MC + MC_SMMU_TRANSLATION_ENABLE_2, ~0u);
reg::Write(MC + MC_SMMU_TRANSLATION_ENABLE_3, ~0u);
reg::Write(MC + MC_SMMU_TRANSLATION_ENABLE_4, ~0u);
/* On modern firmware, configure ASIDs 1-3 as secure, and all others as non-secure. */
if (GetTargetFirmware() >= TargetFirmware_4_0_0) {
reg::Write(MC + MC_SMMU_ASID_SECURITY, MC_REG_BITS_ENUM(SMMU_ASID_SECURITY_SECURE_ASIDS_1, SECURE),
MC_REG_BITS_ENUM(SMMU_ASID_SECURITY_SECURE_ASIDS_2, SECURE),
MC_REG_BITS_ENUM(SMMU_ASID_SECURITY_SECURE_ASIDS_3, SECURE));
} else {
/* Legacy firmware accesses the MC directly, though, and so correspondingly we must allow ASIDs to be edited by non-secure world. */
reg::Write(MC + MC_SMMU_ASID_SECURITY, 0);
}
reg::Write(MC + MC_SMMU_ASID_SECURITY_1, 0);
reg::Write(MC + MC_SMMU_ASID_SECURITY_2, 0);
reg::Write(MC + MC_SMMU_ASID_SECURITY_3, 0);
reg::Write(MC + MC_SMMU_ASID_SECURITY_4, 0);
reg::Write(MC + MC_SMMU_ASID_SECURITY_5, 0);
reg::Write(MC + MC_SMMU_ASID_SECURITY_6, 0);
reg::Write(MC + MC_SMMU_ASID_SECURITY_7, 0);
/* Initialize the PTB registers to zero .*/
reg::Write(MC + MC_SMMU_PTB_ASID, 0);
reg::Write(MC + MC_SMMU_PTB_DATA, 0);
/* Configure the TLB and PTC, then read TLB_CONFIG to ensure configuration takes. */
reg::Write(MC + MC_SMMU_TLB_CONFIG, MC_REG_BITS_ENUM (SMMU_TLB_CONFIG_TLB_HIT_UNDER_MISS, ENABLE),
MC_REG_BITS_ENUM (SMMU_TLB_CONFIG_TLB_ROUND_ROBIN_ARBITRATION, ENABLE),
MC_REG_BITS_VALUE(SMMU_TLB_CONFIG_TLB_ACTIVE_LINES, 0x30));
reg::Write(MC + MC_SMMU_PTC_CONFIG, MC_REG_BITS_ENUM (SMMU_PTC_CONFIG_PTC_CACHE_ENABLE, ENABLE),
MC_REG_BITS_VALUE(SMMU_PTC_CONFIG_PTC_REQ_LIMIT, 8),
MC_REG_BITS_VALUE(SMMU_PTC_CONFIG_PTC_INDEX_MAP, 0x3F));
reg::Read (MC + MC_SMMU_TLB_CONFIG);
/* Flush the entire page table cache, and read TLB_CONFIG to ensure the flush takes. */
reg::Write(MC + MC_SMMU_PTC_FLUSH_0, 0);
reg::Read (MC + MC_SMMU_TLB_CONFIG);
/* Flush the entire translation lookaside buffer, and read TLB_CONFIG to ensure the flush takes. */
reg::Write(MC + MC_SMMU_TLB_FLUSH, 0);
reg::Read (MC + MC_SMMU_TLB_CONFIG);
/* Enable the SMMU, and read TLB_CONFIG to ensure the enable takes. */
reg::Write(MC + MC_SMMU_CONFIG, MC_REG_BITS_ENUM (SMMU_CONFIG_SMMU_ENABLE, ENABLE));
reg::Read (MC + MC_SMMU_TLB_CONFIG);
}
void SetupSecureEl2AndEl1SystemRegisters() {
/* Setup actlr_el2 and actlr_el3. */
{
util::BitPack32 actlr = {};
actlr.Set<hw::ActlrCortexA57::Cpuactlr>(1); /* Enable access to cpuactlr from lower EL. */
actlr.Set<hw::ActlrCortexA57::Cpuectlr>(1); /* Enable access to cpuectlr from lower EL. */
actlr.Set<hw::ActlrCortexA57::L2ctlr>(1); /* Enable access to l2ctlr from lower EL. */
actlr.Set<hw::ActlrCortexA57::L2actlr>(1); /* Enable access to l2actlr from lower EL. */
actlr.Set<hw::ActlrCortexA57::L2ectlr>(1); /* Enable access to l2ectlr from lower EL. */
HW_CPU_SET_ACTLR_EL3(actlr);
HW_CPU_SET_ACTLR_EL2(actlr);
}
/* Setup hcr_el2. */
{
util::BitPack64 hcr = {};
hcr.Set<hw::HcrEl2::Rw>(1); /* EL1 is aarch64 mode. */
HW_CPU_SET_HCR_EL2(hcr);
}
/* Configure all domain access permissions as manager. */
HW_CPU_SET_DACR32_EL2(~0u);
/* Setup sctlr_el1. */
{
util::BitPack64 sctlr = { hw::SctlrEl1::Res1 };
sctlr.Set<hw::SctlrEl1::M>(0); /* Globally disable the MMU. */
sctlr.Set<hw::SctlrEl1::A>(0); /* Disable alignment fault checking. */
sctlr.Set<hw::SctlrEl1::C>(0); /* Globally disable the data and unified caches. */
sctlr.Set<hw::SctlrEl1::Sa>(1); /* Enable stack alignment checking. */
sctlr.Set<hw::SctlrEl1::Sa0>(1); /* Enable el0 stack alignment checking. */
sctlr.Set<hw::SctlrEl1::Cp15BEn>(1); /* Enable cp15 barrier operations. */
sctlr.Set<hw::SctlrEl1::Thee>(0); /* Disable ThumbEE. */
sctlr.Set<hw::SctlrEl1::Itd>(0); /* Enable itd instructions. */
sctlr.Set<hw::SctlrEl1::Sed>(0); /* Enable setend instruction. */
sctlr.Set<hw::SctlrEl1::Uma>(0); /* Disable el0 interrupt mask access. */
sctlr.Set<hw::SctlrEl1::I>(0); /* Globally disable the instruction cache. */
sctlr.Set<hw::SctlrEl1::Dze>(0); /* Disable el0 access to dc zva instruction. */
sctlr.Set<hw::SctlrEl1::Ntwi>(1); /* wfi instructions in el0 trap. */
sctlr.Set<hw::SctlrEl1::Ntwe>(1); /* wfe instructions in el0 trap. */
sctlr.Set<hw::SctlrEl1::Wxn>(0); /* Do not force writable pages to be ExecuteNever. */
sctlr.Set<hw::SctlrEl1::E0e>(0); /* Data accesses in el0 are little endian. */
sctlr.Set<hw::SctlrEl1::Ee>(0); /* Exceptions should be little endian. */
sctlr.Set<hw::SctlrEl1::Uci>(0); /* Disable el0 access to dc cvau, dc civac, dc cvac, ic ivau. */
HW_CPU_SET_SCTLR_EL1(sctlr);
}
/* Setup sctlr_el2. */
{
util::BitPack64 sctlr = { hw::SctlrEl2::Res1 };
sctlr.Set<hw::SctlrEl2::M>(0); /* Globally disable the MMU. */
sctlr.Set<hw::SctlrEl2::A>(0); /* Disable alignment fault checking. */
sctlr.Set<hw::SctlrEl2::C>(0); /* Globally disable the data and unified caches. */
sctlr.Set<hw::SctlrEl2::Sa>(1); /* Enable stack alignment checking. */
sctlr.Set<hw::SctlrEl2::I>(0); /* Globally disable the instruction cache. */
sctlr.Set<hw::SctlrEl2::Wxn>(0); /* Do not force writable pages to be ExecuteNever. */
sctlr.Set<hw::SctlrEl2::Ee>(0); /* Exceptions should be little endian. */
HW_CPU_SET_SCTLR_EL2(sctlr);
}
/* Ensure instruction consistency. */
hw::InstructionSynchronizationBarrier();
}
void SetupNonSecureSystemRegisters(u32 tsc_frequency) {
/* Set cntfrq_el0. */
HW_CPU_SET_CNTFRQ_EL0(tsc_frequency);
/* Set cnthctl_el2. */
{
util::BitPack32 cnthctl = {};
cnthctl.Set<hw::CnthctlEl2::El1PctEn>(1); /* Do not trap accesses to cntpct_el0. */
cnthctl.Set<hw::CnthctlEl2::El1PcEn>(1); /* Do not trap accesses to cntp_ctl_el0, cntp_cval_el0, and cntp_tval_el0. */
cnthctl.Set<hw::CnthctlEl2::EvntEn>(0); /* Disable the event stream. */
cnthctl.Set<hw::CnthctlEl2::EvntDir>(0); /* Trigger events on 0 -> 1 transition. */
cnthctl.Set<hw::CnthctlEl2::EvntI>(0); /* Select bit0 of cntpct_el0 as the event stream trigger. */
HW_CPU_SET_CNTHCTL_EL2(cnthctl);
}
/* Ensure instruction consistency. */
hw::InstructionSynchronizationBarrier();
}
void SetupGpuCarveout() {
/* Configure carveout 2. */
reg::Write(MC + MC_SECURITY_CARVEOUT2_BOM, static_cast<u32>(MemoryRegionDramGpuCarveout.GetAddress() >> 0));
reg::Write(MC + MC_SECURITY_CARVEOUT2_BOM_HI, static_cast<u32>(MemoryRegionDramGpuCarveout.GetAddress() >> BITSIZEOF(u32)));
reg::Write(MC + MC_SECURITY_CARVEOUT2_SIZE_128KB, MemoryRegionDramGpuCarveout.GetSize() / 128_KB);
reg::Write(MC + MC_SECURITY_CARVEOUT2_CLIENT_ACCESS0, 0);
reg::Write(MC + MC_SECURITY_CARVEOUT2_CLIENT_ACCESS1, 0);
reg::Write(MC + MC_SECURITY_CARVEOUT2_CLIENT_ACCESS2, MC_REG_BITS_ENUM (CLIENT_ACCESS2_GPUSRD, ENABLE),
MC_REG_BITS_ENUM (CLIENT_ACCESS2_GPUSWR, ENABLE),
MC_REG_BITS_ENUM (CLIENT_ACCESS2_TSECSRD, ENABLE));
reg::Write(MC + MC_SECURITY_CARVEOUT2_CLIENT_ACCESS3, 0);
reg::Write(MC + MC_SECURITY_CARVEOUT2_CLIENT_ACCESS4, MC_REG_BITS_ENUM (CLIENT_ACCESS4_GPUSRD2, ENABLE),
MC_REG_BITS_ENUM (CLIENT_ACCESS4_GPUSWR2, ENABLE));
reg::Write(MC + MC_SECURITY_CARVEOUT2_CLIENT_FORCE_INTERNAL_ACCESS0, 0);
reg::Write(MC + MC_SECURITY_CARVEOUT2_CLIENT_FORCE_INTERNAL_ACCESS1, 0);
reg::Write(MC + MC_SECURITY_CARVEOUT2_CLIENT_FORCE_INTERNAL_ACCESS2, 0);
reg::Write(MC + MC_SECURITY_CARVEOUT2_CLIENT_FORCE_INTERNAL_ACCESS3, 0);
reg::Write(MC + MC_SECURITY_CARVEOUT2_CLIENT_FORCE_INTERNAL_ACCESS4, 0);
reg::Write(MC + MC_SECURITY_CARVEOUT2_CFG0, MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_IS_WPR, DISABLED),
MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_FORCE_APERTURE_ID_MATCH, ENABLED),
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, ENABLED),
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, 2),
MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_WRITE_ACCESS_LEVEL3, ENABLED),
MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_WRITE_ACCESS_LEVEL2, ENABLED),
MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_WRITE_ACCESS_LEVEL1, DISABLED),
MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_WRITE_ACCESS_LEVEL0, DISABLED),
MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_READ_ACCESS_LEVEL3, ENABLED),
MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_READ_ACCESS_LEVEL2, ENABLED),
MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_READ_ACCESS_LEVEL1, ENABLED),
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, LOCKBIT_SECURE));
}
void DisableArc() {
/* Configure IRAM top/bottom to point to memory ends (disabling redirection). */
reg::Write(MC + MC_IRAM_BOM, MC_REG_BITS_VALUE(IRAM_BOM_IRAM_BOM, (~0u)));
reg::Write(MC + MC_IRAM_TOM, MC_REG_BITS_VALUE(IRAM_TOM_IRAM_TOM, ( 0u)));
/* Lock the IRAM aperture. */
reg::ReadWrite(MC + MC_IRAM_REG_CTRL, MC_REG_BITS_ENUM(IRAM_REG_CTRL_IRAM_CFG_WRITE_ACCESS, DISABLED));
/* Disable the ARC clock gate override. */
reg::ReadWrite(CLK_RST + CLK_RST_CONTROLLER_LVL2_CLK_GATE_OVRD, CLK_RST_REG_BITS_ENUM(LVL2_CLK_GATE_OVRD_ARC_CLK_OVR_ON, OFF));
/* Read IRAM REG CTRL to make sure our writes take. */
reg::Read(MC + MC_IRAM_REG_CTRL);
}
void DisableUntranslatedDeviceMemoryAccess() {
/* If we can (mariko only), disable GMMU accesses that bypass the SMMU. */
/* Additionally, force all untranslated acccesses to hit one of the carveouts. */
if (GetSocType() == fuse::SocType_Mariko) {
reg::Write(MC + MC_UNTRANSLATED_REGION_CHECK, MC_REG_BITS_ENUM(UNTRANSLATED_REGION_CHECK_UNTRANSLATED_REGION_CHECK_ACCESS, DISABLED),
MC_REG_BITS_ENUM(UNTRANSLATED_REGION_CHECK_REQUIRE_UNTRANSLATED_CLIENTS_HIT_CARVEOUT, ENABLED),
MC_REG_BITS_ENUM(UNTRANSLATED_REGION_CHECK_REQUIRE_UNTRANSLATED_GPU_HIT_CARVEOUT, ENABLED));
}
}
void FinalizeCarveoutSecureScratchRegisters() {
/* Define carveout scratch values. */
constexpr uintptr_t WarmbootCarveoutAddress = MemoryRegionDram.GetAddress();
constexpr size_t WarmbootCarveoutSize = 128_KB;
#define MC_ENABLE_CLIENT_ACCESS(INDEX, WHICH) MC_REG_BITS_ENUM(CLIENT_ACCESS##INDEX##_##WHICH, ENABLE)
constexpr u32 WarmbootCarveoutClientAccess0 = reg::Encode(MC_ENABLE_CLIENT_ACCESS(0, AVPCARM7R),
MC_ENABLE_CLIENT_ACCESS(0, PPCSAHBSLVR));
constexpr u32 WarmbootCarveoutClientAccess1 = reg::Encode(MC_ENABLE_CLIENT_ACCESS(1, AVPCARM7W));
#undef MC_ENABLE_CLIENT_ACCESS
constexpr u32 WarmbootCarveoutForceInternalAccess0 = reg::Encode(MC_REG_BITS_ENUM(CLIENT_ACCESS0_AVPCARM7R, ENABLE),
MC_REG_BITS_ENUM(CLIENT_ACCESS0_PPCSAHBSLVR, ENABLE));
constexpr u32 WarmbootCarveoutForceInternalAccess1 = reg::Encode(MC_REG_BITS_ENUM(CLIENT_ACCESS1_AVPCARM7W, ENABLE));
constexpr u32 WarmbootCarveoutConfig = 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, ANY_ADDRESS),
MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_LOCK_MODE, UNLOCKED),
MC_REG_BITS_ENUM (SECURITY_CARVEOUT_CFG0_PROTECT_MODE, LOCKBIT_SECURE));
/* Save the carveout values into secure scratch. */
/* Save MC_SECURITY_CARVEOUT4_BOM. */
reg::ReadWrite(PMC + APBDEV_PMC_SECURE_SCRATCH51, REG_BITS_VALUE( 0, 15, WarmbootCarveoutAddress >> 17));
/* Save MC_SECURITY_CARVEOUT4_BOM_HI. */
reg::ReadWrite(PMC + APBDEV_PMC_SECURE_SCRATCH16, REG_BITS_VALUE(30, 2, WarmbootCarveoutAddress >> 32));
/* Save MC_SECURITY_CARVEOUT4_SIZE_128KB. */
reg::ReadWrite(PMC + APBDEV_PMC_SECURE_SCRATCH55, REG_BITS_VALUE(12, 12, WarmbootCarveoutSize / 128_KB));
/* Save MC_SECURITY_CARVEOUT4_CLIENT_ACCESS. */
reg::Write(PMC + APBDEV_PMC_SECURE_SCRATCH74, WarmbootCarveoutClientAccess0);
reg::Write(PMC + APBDEV_PMC_SECURE_SCRATCH75, WarmbootCarveoutClientAccess1);
reg::Write(PMC + APBDEV_PMC_SECURE_SCRATCH76, 0);
reg::Write(PMC + APBDEV_PMC_SECURE_SCRATCH77, 0);
reg::Write(PMC + APBDEV_PMC_SECURE_SCRATCH78, 0);
/* Save MC_SECURITY_CARVEOUT4_FORCE_INTERNAL_ACCESS. */
reg::Write(PMC + APBDEV_PMC_SECURE_SCRATCH99, WarmbootCarveoutForceInternalAccess0);
reg::Write(PMC + APBDEV_PMC_SECURE_SCRATCH100, WarmbootCarveoutForceInternalAccess1);
reg::Write(PMC + APBDEV_PMC_SECURE_SCRATCH101, 0);
reg::Write(PMC + APBDEV_PMC_SECURE_SCRATCH102, 0);
reg::Write(PMC + APBDEV_PMC_SECURE_SCRATCH103, 0);
/* Save MC_SECURITY_CARVEOUT4_CFG0. */
reg::ReadWrite(PMC + APBDEV_PMC_SECURE_SCRATCH39, REG_BITS_VALUE(0, 27, WarmbootCarveoutConfig));
}
void EnableBpmpSmmu() {
/* Define the ASID contents. */
constexpr int BpmpAsid = 1;
constexpr uintptr_t BpmpAsidPde = MemoryRegionPhysicalDeviceSecurityEngine.GetAddress();
/* Configure the ASID. */
reg::Write(MC + MC_SMMU_PTB_ASID, MC_REG_BITS_VALUE(SMMU_PTB_ASID_CURRENT_ASID, BpmpAsid));
reg::Write(MC + MC_SMMU_PTB_DATA, MC_REG_BITS_VALUE(SMMU_PTB_DATA_ASID_PDE_BASE, BpmpAsidPde / 4_KB),
MC_REG_BITS_ENUM (SMMU_PTB_DATA_ASID_NONSECURE, DISABLE),
MC_REG_BITS_ENUM (SMMU_PTB_DATA_ASID_WRITABLE, DISABLE),
MC_REG_BITS_ENUM (SMMU_PTB_DATA_ASID_READABLE, DISABLE));
/* Configure the BPMP and PPCS1 to use the asid. */
reg::Write(MC + MC_SMMU_AVPC_ASID, MC_REG_BITS_ENUM(SMMU_AVPC_ASID_AVPC_SMMU_ENABLE, ENABLE), MC_REG_BITS_VALUE(SMMU_AVPC_ASID_AVPC_ASID, BpmpAsid));
reg::Write(MC + MC_SMMU_PPCS1_ASID, MC_REG_BITS_ENUM(SMMU_PPCS1_ASID_PPCS1_SMMU_ENABLE, ENABLE), MC_REG_BITS_VALUE(SMMU_PPCS1_ASID_PPCS1_ASID, BpmpAsid));
/* Flush the entire page table cache, and read TLB_CONFIG to ensure the flush takes. */
reg::Write(MC + MC_SMMU_PTC_FLUSH_0, 0);
reg::Read (MC + MC_SMMU_TLB_CONFIG);
/* Flush the entire translation lookaside buffer, and read TLB_CONFIG to ensure the flush takes. */
reg::Write(MC + MC_SMMU_TLB_FLUSH, 0);
reg::Read (MC + MC_SMMU_TLB_CONFIG);
}
void ValidateResetExpected() {
/* We're coming out of reset, so check that we expected to come out of reset. */
if (!IsResetExpected()) {
secmon::SetError(pkg1::ErrorInfo_UnexpectedReset);
AMS_ABORT("unexpected reset");
}
SetResetExpected(false);
}
void ActmonInterruptHandler() {
SetError(pkg1::ErrorInfo_ActivityMonitorInterrupt);
AMS_ABORT("actmon observed bpmp wakeup");
}
void ExitChargerHiZMode() {
/* Setup I2c-1. */
pinmux::SetupI2c1();
clkrst::EnableI2c1Clock();
/* Initialize I2c-1. */
i2c::Initialize(i2c::Port_1);
/* Exit Hi-Z mode. */
charger::ExitHiZMode();
/* Disable clock to I2c-1. */
clkrst::DisableI2c1Clock();
}
bool IsExitLp0() {
return reg::Read(MC + MC_SECURITY_CFG3) == 0;
}
void SetupLogForBoot() {
log::Initialize(secmon::GetLogPort(), secmon::GetLogBaudRate(), secmon::GetLogFlags());
log::SendText("OHAYO\n", 6);
log::Flush();
}
void LogExitLp0() {
/* NOTE: Nintendo only does this on dev, but we will always do it. */
if (true /* !pkg1::IsProduction() */) {
SetupLogForBoot();
}
}
void SetupForLp0Exit() {
/* Exit HiZ mode in charger, if we need to. */
const auto target_fw = GetTargetFirmware();
const bool force_exit_hiz_mode = (target_fw < TargetFirmware_4_0_0) || (target_fw < TargetFirmware_8_0_0 && fuse::GetHardwareType() == fuse::HardwareType_Icosa);
if (force_exit_hiz_mode || smc::IsChargerHiZModeEnabled()) {
ExitChargerHiZMode();
}
/* Refill the random cache, which is volatile and thus wiped on warmboot. */
smc::FillRandomCache();
/* Unlock the security engine. */
secmon::smc::UnlockSecurityEngine();
}
}
void Setup1() {
/* Load the global configuration context. */
InitializeConfigurationContext();
/* Initialize uart for logging. */
SetupLogForBoot();
/* Initialize the security engine. */
se::Initialize();
/* Initialize the gic. */
gic::InitializeCommon();
}
void Setup1ForWarmboot() {
/* Initialize the security engine. */
se::Initialize();
/* Initialize the gic. */
gic::InitializeCommon();
}
void SaveSecurityEngineAesKeySlotTestVector() {
GenerateSecurityEngineAesKeySlotTestVector(g_se_aes_key_slot_test_vector, sizeof(g_se_aes_key_slot_test_vector));
}
void SetupSocSecurity() {
/* Set the fuse visibility. */
clkrst::SetFuseVisibility(true);
/* Set fuses as only secure-writable. */
fuse::SetWriteSecureOnly();
/* Lockout the fuses. */
fuse::Lockout();
/* Set the security engine to secure mode. */
se::SetSecure(true);
/* Verify the security engine's sticky bits. */
VerifySecurityEngineStickyBits();
/* Verify the security engine's Aes slots contain correct contents. */
VerifySecurityEngineAesKeySlotTestVector();
/* Clear aes keyslots. */
ClearAesKeySlots();
/* Clear rsa keyslots. */
ClearRsaKeySlots();
/* Overwrite keys that we want to be random with random contents. */
se::InitializeRandom();
se::ConfigureAutomaticContextSave();
se::SetRandomKey(pkg1::AesKeySlot_Temporary);
se::GenerateSrk();
se::SetRandomKey(pkg1::AesKeySlot_TzramSaveKek);
/* Initialize pmc secure scratch. */
if (GetSocType() == fuse::SocType_Erista) {
pmc::InitializeRandomScratch();
}
pmc::LockSecureRegister(pmc::SecureRegister_Srk);
/* Setup secure registers. */
SetupSecureRegisters();
/* Setup the smmu. */
SetupSmmu();
/* Clear the cpu reset vector. */
reg::Write(EVP + EVP_CPU_RESET_VECTOR, 0);
/* Configure the SB registers to our start address. */
constexpr u32 ResetVectorLow = static_cast<u32>((PhysicalTzramProgramResetVector >> 0));
constexpr u32 ResetVectorHigh = static_cast<u32>((PhysicalTzramProgramResetVector >> BITSIZEOF(u32)));
/* Write our reset vector to the secure boot registers. */
reg::Write(secmon::MemoryRegionVirtualDeviceSystem.GetAddress() + SB_AA64_RESET_LOW, ResetVectorLow | 1);
reg::Write(secmon::MemoryRegionVirtualDeviceSystem.GetAddress() + SB_AA64_RESET_HIGH, ResetVectorHigh);
/* Disable non-secure writes to the reset vector. */
reg::Write(secmon::MemoryRegionVirtualDeviceSystem.GetAddress() + SB_CSR, SB_REG_BITS_ENUM(CSR_NS_RST_VEC_WR_DIS, DISABLE));
/* Read back SB_CSR to make sure our non-secure write disable takes. */
reg::Read(secmon::MemoryRegionVirtualDeviceSystem.GetAddress() + SB_CSR);
/* Write our reset vector to scratch registers used by warmboot, and lock those scratch registers. */
reg::Write(PMC + APBDEV_PMC_SECURE_SCRATCH34, ResetVectorLow);
reg::Write(PMC + APBDEV_PMC_SECURE_SCRATCH35, ResetVectorHigh);
pmc::LockSecureRegister(pmc::SecureRegister_ResetVector);
/* Setup the security engine interrupt. */
constexpr int SecurityEngineInterruptId = 90;
constexpr u8 SecurityEngineInterruptCoreMask = (1 << 3);
gic::SetPriority (SecurityEngineInterruptId, gic::HighestPriority);
gic::SetInterruptGroup(SecurityEngineInterruptId, 0);
gic::SetEnable (SecurityEngineInterruptId, true);
gic::SetSpiTargetCpu (SecurityEngineInterruptId, SecurityEngineInterruptCoreMask);
gic::SetSpiMode (SecurityEngineInterruptId, gic::InterruptMode_Level);
/* Setup the activity monitor interrupt. */
constexpr int ActivityMonitorInterruptId = 77;
constexpr u8 ActivityMonitorInterruptCoreMask = (1 << 3);
gic::SetPriority (ActivityMonitorInterruptId, gic::HighestPriority);
gic::SetInterruptGroup(ActivityMonitorInterruptId, 0);
gic::SetEnable (ActivityMonitorInterruptId, true);
gic::SetSpiTargetCpu (ActivityMonitorInterruptId, ActivityMonitorInterruptCoreMask);
gic::SetSpiMode (ActivityMonitorInterruptId, gic::InterruptMode_Level);
/* Setup the mariko fatal error interrupt. */
constexpr u8 MarikoFatalInterruptCoreMask = 0b1111;
gic::SetPriority (MarikoFatalErrorInterruptId, gic::HighestPriority);
gic::SetInterruptGroup(MarikoFatalErrorInterruptId, 0);
gic::SetEnable (MarikoFatalErrorInterruptId, true);
gic::SetSpiTargetCpu (MarikoFatalErrorInterruptId, 0);
gic::SetSpiMode (MarikoFatalErrorInterruptId, gic::InterruptMode_Level);
/* If we're coldboot, perform one-time setup. */
if (g_is_cold_boot) {
/* Register all interrupt handlers. */
SetInterruptHandler(SecurityEngineInterruptId, SecurityEngineInterruptCoreMask, se::HandleInterrupt);
SetInterruptHandler(ActivityMonitorInterruptId, ActivityMonitorInterruptCoreMask, actmon::HandleInterrupt);
SetInterruptHandler(MarikoFatalErrorInterruptId, MarikoFatalInterruptCoreMask, secmon::HandleMarikoFatalErrorInterrupt);
/* We're expecting the other cores to come out of reset. */
for (int i = 1; i < NumCores; ++i) {
SetResetExpected(i, true);
}
/* We only coldboot once. */
g_is_cold_boot = false;
}
}
void SetupSocSecurityWarmboot() {
/* Check that we're allowed to continue. */
ValidateResetExpected();
/* Unmap the tzram identity mapping. */
UnmapTzram();
/* If we're exiting LP0, there's a little more work for us to do. */
if (IsExitLp0()) {
/* Log that we're exiting LP0. */
LogExitLp0();
/* Perform initial setup. */
Setup1ForWarmboot();
/* Generate a random srk. */
se::GenerateSrk();
/* Setup the Soc security. */
SetupSocSecurity();
/* Set the PMC and MC as secure-only. */
SetupPmcAndMcSecure();
/* Perform Lp0-exit specific init. */
SetupForLp0Exit();
/* Setup the Soc protections. */
SetupSocProtections();
}
/* Perform remaining CPU initialization. */
SetupCpuCoreContext();
SetupCpuSErrorDebug();
}
void SetupSocProtections() {
/* Setup the GPU carveout. */
SetupGpuCarveout();
/* Configure the two kernel carveouts. */
SetupKernelCarveouts();
/* Disable the ARC. */
DisableArc();
/* Disable untranslated memory accesses by devices. */
DisableUntranslatedDeviceMemoryAccess();
/* Further protections aren't applied on <= 1.0.0. */
if (GetTargetFirmware() <= TargetFirmware_1_0_0) {
return;
}
/* Finalize and lock the carveout scratch registers. */
FinalizeCarveoutSecureScratchRegisters();
pmc::LockSecureRegister(pmc::SecureRegister_Carveout);
/* Clear all the BPMP exception vectors to a fixed value. */
constexpr u32 BpmpExceptionVector = 0x7D000000;
reg::Write(EVP + EVP_COP_RESET_VECTOR, BpmpExceptionVector);
reg::Write(EVP + EVP_COP_UNDEF_VECTOR, BpmpExceptionVector);
reg::Write(EVP + EVP_COP_SWI_VECTOR, BpmpExceptionVector);
reg::Write(EVP + EVP_COP_PREFETCH_ABORT_VECTOR, BpmpExceptionVector);
reg::Write(EVP + EVP_COP_DATA_ABORT_VECTOR, BpmpExceptionVector);
reg::Write(EVP + EVP_COP_RSVD_VECTOR, BpmpExceptionVector);
reg::Write(EVP + EVP_COP_IRQ_VECTOR, BpmpExceptionVector);
reg::Write(EVP + EVP_COP_FIQ_VECTOR, BpmpExceptionVector);
/* Disable arbitration for the bpmp. */
reg::ReadWrite(SYSTEM + AHB_ARBITRATION_DISABLE, AHB_REG_BITS_ENUM(ARBITRATION_DISABLE_COP, DISABLE));
/* Turn on the SMMU for the BPMP. */
EnableBpmpSmmu();
/* Wait until the flow controller reports that the BPMP is halted. */
while (!reg::HasValue(FLOW_CTLR + FLOW_CTLR_HALT_COP_EVENTS, FLOW_REG_BITS_ENUM(HALT_COP_EVENTS_MODE, FLOW_MODE_STOP))) {
util::WaitMicroSeconds(1);
}
/* Enable clock to the activity monitor. */
clkrst::EnableActmonClock();
/* If JTAG is disabled, disable JTAG. */
if (!secmon::IsJtagEnabled()) {
reg::Write(FLOW_CTLR + FLOW_CTLR_HALT_COP_EVENTS, FLOW_REG_BITS_ENUM(HALT_COP_EVENTS_MODE, FLOW_MODE_STOP),
FLOW_REG_BITS_ENUM(HALT_COP_EVENTS_JTAG, DISABLED));
/* Turn on the activity monitor to prevent booting up the bpmp. */
actmon::StartMonitoringBpmp(ActmonInterruptHandler);
}
}
void SetupPmcAndMcSecure() {
const auto target_fw = GetTargetFirmware();
if (target_fw >= TargetFirmware_2_0_0) {
/* Set the PMC secure. */
reg::ReadWrite(APB_MISC + APB_MISC_SECURE_REGS_APB_SLAVE_SECURITY_ENABLE_REG0_0, SLAVE_SECURITY_REG_BITS_ENUM(0, PMC, ENABLE));
}
if (target_fw >= TargetFirmware_4_0_0) {
/* Set the MC secure. */
reg::ReadWrite(APB_MISC + APB_MISC_SECURE_REGS_APB_SLAVE_SECURITY_ENABLE_REG1_0, SLAVE_SECURITY_REG_BITS_ENUM(1, MC0, ENABLE),
SLAVE_SECURITY_REG_BITS_ENUM(1, MC1, ENABLE),
SLAVE_SECURITY_REG_BITS_ENUM(1, MCB, ENABLE));
}
}
void SetupCpuCoreContext() {
/* Get the tsc frequency. */
const u32 tsc_frequency = reg::Read(MemoryRegionVirtualDeviceSysCtr0.GetAddress() + SYSCTR0_CNTFID0);
/* Setup the secure EL2/EL1 system registers. */
SetupSecureEl2AndEl1SystemRegisters();
/* Setup the non-secure system registers. */
SetupNonSecureSystemRegisters(tsc_frequency);
/* Reset the cpu flow controller registers. */
flow::ResetCpuRegisters(hw::GetCurrentCoreId());
/* Initialize the core unique gic registers. */
gic::InitializeCoreUnique();
/* Configure cpu fiq. */
constexpr int FiqInterruptId = 28;
gic::SetPriority (FiqInterruptId, gic::HighestPriority);
gic::SetInterruptGroup(FiqInterruptId, 0);
gic::SetEnable (FiqInterruptId, true);
/* Restore the cpu's debug registers. */
RestoreDebugRegisters();
}
void SetupCpuSErrorDebug() {
/* Get whether we should enable SError debug. */
const auto &bc_data = secmon::GetBootConfig().data;
const bool enabled = bc_data.IsDevelopmentFunctionEnabled() && bc_data.IsSErrorDebugEnabled();
/* Get and set scr_el3. */
{
util::BitPack32 scr;
HW_CPU_GET_SCR_EL3(scr);
scr.Set<hw::ScrEl3::Ea>(enabled ? 0 : 1);
HW_CPU_SET_SCR_EL3(scr);
}
/* Prevent reordering instructions around this call. */
hw::InstructionSynchronizationBarrier();
}
void SetKernelCarveoutRegion(int index, uintptr_t address, size_t size) {
/* Configure the carveout. */
auto &carveout = g_kernel_carveouts[index];
carveout.address = address;
carveout.size = size;
SetupKernelCarveouts();
}
}
| 91,424
|
C++
|
.cpp
| 1,075
| 59.510698
| 219
| 0.490426
|
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,327
|
secmon_error.cpp
|
Atmosphere-NX_Atmosphere/exosphere/program/source/secmon_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"
namespace ams {
namespace {
constexpr bool SaveSystemStateForDebug = false;
}
}
namespace ams::diag {
namespace {
ALWAYS_INLINE void SaveSystemStateForDebugAbort() {
*(volatile u32 *)(secmon::MemoryRegionVirtualDebug.GetAddress() + 0x00) = 0xDDDDDDDD;
u64 temp_reg;
__asm__ __volatile__("mov %0, lr" : "=r"(temp_reg) :: "memory");
*(volatile u32 *)(secmon::MemoryRegionVirtualDebug.GetAddress() + 0x10) = static_cast<u32>(temp_reg >> 0);
*(volatile u32 *)(secmon::MemoryRegionVirtualDebug.GetAddress() + 0x14) = static_cast<u32>(temp_reg >> 32);
__asm__ __volatile__("mov %0, sp" : "=r"(temp_reg) :: "memory");
for (int i = 0; i < 0x100; i += 4) {
*(volatile u32 *)(secmon::MemoryRegionVirtualDebug.GetAddress() + 0x20 + i) = *(volatile u32 *)(temp_reg + i);
}
*(volatile u32 *)(secmon::MemoryRegionVirtualDevicePmc.GetAddress() + 0x50) = 0x02;
*(volatile u32 *)(secmon::MemoryRegionVirtualDevicePmc.GetAddress() + 0x00) = 0x10;
util::WaitMicroSeconds(1000);
}
}
NORETURN void AbortImpl() {
/* Perform any necessary (typically none) debugging. */
if constexpr (SaveSystemStateForDebug) {
SaveSystemStateForDebugAbort();
}
secmon::SetError(pkg1::ErrorInfo_UnknownAbort);
secmon::ErrorReboot();
}
#include <exosphere/diag/diag_detailed_assertion_impl.inc>
}
namespace ams::secmon {
namespace {
constexpr inline uintptr_t PMC = MemoryRegionVirtualDevicePmc.GetAddress();
ALWAYS_INLINE void SaveSystemStateForDebugErrorReboot() {
u64 temp_reg;
*(volatile u32 *)(secmon::MemoryRegionVirtualDebug.GetAddress() + 0x00) = 0x5A5A5A5A;
__asm__ __volatile__("mrs %0, esr_el3" : "=r"(temp_reg) :: "memory");
*(volatile u32 *)(secmon::MemoryRegionVirtualDebug.GetAddress() + 0x08) = static_cast<u32>(temp_reg >> 0);
*(volatile u32 *)(secmon::MemoryRegionVirtualDebug.GetAddress() + 0x0C) = static_cast<u32>(temp_reg >> 32);
__asm__ __volatile__("mrs %0, elr_el3" : "=r"(temp_reg) :: "memory");
*(volatile u32 *)(secmon::MemoryRegionVirtualDebug.GetAddress() + 0x10) = static_cast<u32>(temp_reg >> 0);
*(volatile u32 *)(secmon::MemoryRegionVirtualDebug.GetAddress() + 0x14) = static_cast<u32>(temp_reg >> 32);
__asm__ __volatile__("mrs %0, far_el3" : "=r"(temp_reg) :: "memory");
*(volatile u32 *)(secmon::MemoryRegionVirtualDebug.GetAddress() + 0x18) = static_cast<u32>(temp_reg >> 0);
*(volatile u32 *)(secmon::MemoryRegionVirtualDebug.GetAddress() + 0x1C) = static_cast<u32>(temp_reg >> 32);
__asm__ __volatile__("mov %0, lr" : "=r"(temp_reg) :: "memory");
*(volatile u32 *)(secmon::MemoryRegionVirtualDebug.GetAddress() + 0x20) = static_cast<u32>(temp_reg >> 0);
*(volatile u32 *)(secmon::MemoryRegionVirtualDebug.GetAddress() + 0x24) = static_cast<u32>(temp_reg >> 32);
__asm__ __volatile__("mov %0, sp" : "=r"(temp_reg) :: "memory");
*(volatile u32 *)(secmon::MemoryRegionVirtualDebug.GetAddress() + 0x30) = static_cast<u32>(temp_reg >> 0);
*(volatile u32 *)(secmon::MemoryRegionVirtualDebug.GetAddress() + 0x34) = static_cast<u32>(temp_reg >> 32);
for (int i = 0; i < 0x100; i += 4) {
*(volatile u32 *)(secmon::MemoryRegionVirtualDebug.GetAddress() + 0x40 + i) = *(volatile u32 *)(temp_reg + i);
}
*(volatile u32 *)(secmon::MemoryRegionVirtualDevicePmc.GetAddress() + 0x50) = 0x02;
*(volatile u32 *)(secmon::MemoryRegionVirtualDevicePmc.GetAddress() + 0x00) = 0x10;
util::WaitMicroSeconds(1000);
}
}
void SetError(pkg1::ErrorInfo info) {
const uintptr_t address = secmon::MemoryRegionVirtualDevicePmc.GetAddress() + PKG1_SECURE_MONITOR_PMC_ERROR_SCRATCH;
if (reg::Read(address) == pkg1::ErrorInfo_None) {
reg::Write(address, info);
}
}
NORETURN void ErrorReboot() {
/* Perform any necessary (typically none) debugging. */
if constexpr (SaveSystemStateForDebug) {
SaveSystemStateForDebugErrorReboot();
}
/* Lockout the security engine. */
se::Lockout();
/* Lockout fuses. */
fuse::Lockout();
/* Disable crypto operations after reboot. */
reg::Write(PMC + APBDEV_PMC_CRYPTO_OP, 0);
while (true) {
wdt::Reboot();
}
}
}
| 5,366
|
C++
|
.cpp
| 100
| 44.89
| 126
| 0.618237
|
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,328
|
secmon_interrupt_handler.cpp
|
Atmosphere-NX_Atmosphere/exosphere/program/source/secmon_interrupt_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_interrupt_handler.hpp"
#include "secmon_error.hpp"
namespace ams::secmon {
namespace {
constexpr inline int InterruptHandlersMax = 4;
constinit InterruptHandler g_handlers[InterruptHandlersMax] = {};
constinit int g_interrupt_ids[InterruptHandlersMax] = {};
constinit u8 g_interrupt_core_masks[InterruptHandlersMax] = {};
}
void SetInterruptHandler(int interrupt_id, u8 core_mask, InterruptHandler handler) {
for (int i = 0; i < InterruptHandlersMax; ++i) {
if (g_interrupt_ids[i] == 0) {
g_interrupt_ids[i] = interrupt_id;
g_handlers[i] = handler;
g_interrupt_core_masks[i] = core_mask;
return;
}
}
AMS_ABORT("Failed to register interrupt handler");
}
void HandleInterrupt() {
/* Get the interrupt id. */
const int interrupt_id = gic::GetInterruptRequestId();
if (interrupt_id >= gic::InterruptCount) {
/* Invalid interrupt number, just return. */
return;
}
/* Check each handler. */
for (int i = 0; i < InterruptHandlersMax; ++i) {
if (g_interrupt_ids[i] == interrupt_id) {
/* Validate that we can invoke the handler. */
AMS_ABORT_UNLESS((g_interrupt_core_masks[i] & (1u << hw::GetCurrentCoreId())) != 0);
/* Invoke the handler. */
g_handlers[i]();
gic::SetEndOfInterrupt(interrupt_id);
return;
}
}
AMS_ABORT("Failed to find interrupt handler.");
}
}
| 2,347
|
C++
|
.cpp
| 57
| 33.122807
| 100
| 0.612818
|
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,329
|
secmon_setup_warm.cpp
|
Atmosphere-NX_Atmosphere/exosphere/program/source/secmon_setup_warm.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"
namespace ams::secmon {
namespace setup {
#include "secmon_cache_impl.inc"
}
namespace {
constexpr inline uintptr_t MC = MemoryRegionPhysicalDeviceMemoryController.GetAddress();
using namespace ams::mmu;
constexpr inline PageTableMappingAttribute MappingAttributesEl3SecureRwCode = AddMappingAttributeIndex(PageTableMappingAttributes_El3SecureRwCode, MemoryAttributeIndexNormal);
void SetupCpuCommonControllers() {
/* Set cpuactlr_el1. */
{
util::BitPack64 cpuactlr = {};
cpuactlr.Set<hw::CpuactlrEl1CortexA57::NonCacheableStreamingEnhancement>(1);
cpuactlr.Set<hw::CpuactlrEl1CortexA57::DisableLoadPassDmb>(1);
HW_CPU_SET_CPUACTLR_EL1(cpuactlr);
}
/* Set cpuectlr_el1. */
{
util::BitPack64 cpuectlr = {};
cpuectlr.Set<hw::CpuectlrEl1CortexA57::Smpen>(1);
cpuectlr.Set<hw::CpuectlrEl1CortexA57::L2LoadStoreDataPrefetchDistance>(3);
cpuectlr.Set<hw::CpuectlrEl1CortexA57::L2InstructionFetchPrefetchDistance>(3);
HW_CPU_SET_CPUECTLR_EL1(cpuectlr);
}
/* Prevent instruction reordering. */
hw::InstructionSynchronizationBarrier();
}
void SetupCpuEl3Controllers() {
/* Set scr_el3. */
{
util::BitPack32 scr = {};
scr.Set<hw::ScrEl3::Ns >(1); /* Set EL0/EL1 as Non-Secure. */
scr.Set<hw::ScrEl3::Irq >(0); /* IRQs are taken in IRQ mode. */
scr.Set<hw::ScrEl3::Fiq >(1); /* FIQs are taken in Monitor mode. */
scr.Set<hw::ScrEl3::Ea >(1); /* External aborts are taken in Monitor mode. */
scr.Set<hw::ScrEl3::Fw >(1); /* CPSR.F is non-secure writable. */
scr.Set<hw::ScrEl3::Aw >(1); /* CPSR.A is non-secure writable. */
scr.Set<hw::ScrEl3::Net >(0); /* This bit is not implemented. */
scr.Set<hw::ScrEl3::Smd >(0); /* Secure Monitor Call is allowed. */
scr.Set<hw::ScrEl3::Hce >(0); /* Hypervisor Calls are disabled. */ /* TODO: Enable for thermosphere? */
scr.Set<hw::ScrEl3::Sif >(1); /* Secure mode cannot fetch instructions from non-secure memory. */
scr.Set<hw::ScrEl3::RwCortexA53>(1); /* Reserved bit. N probably sets it because on Cortex A53, this sets kernel as aarch64. */
scr.Set<hw::ScrEl3::StCortexA53>(0); /* Reserved bit. On Cortex A53, this sets secure registers to EL3 only. */
scr.Set<hw::ScrEl3::Twi >(0); /* WFI is not trapped. */
scr.Set<hw::ScrEl3::Twe >(0); /* WFE is not trapped. */
HW_CPU_SET_SCR_EL3(scr);
}
/* Set ttbr0_el3. */
{
constexpr u64 ttbr0 = MemoryRegionPhysicalTzramL1PageTable.GetAddress();
HW_CPU_SET_TTBR0_EL3(ttbr0);
}
/* Set tcr_el3. */
{
util::BitPack32 tcr = { hw::TcrEl3::Res1 };
tcr.Set<hw::TcrEl3::T0sz >(31); /* Configure TTBR0 addressed size to be 64 GiB */
tcr.Set<hw::TcrEl3::Irgn0>(1); /* Configure PTE walks as inner write-back write-allocate cacheable */
tcr.Set<hw::TcrEl3::Orgn0>(1); /* Configure PTE walks as outer write-back write-allocate cacheable */
tcr.Set<hw::TcrEl3::Sh0 >(3); /* Configure PTE walks as inner shareable */
tcr.Set<hw::TcrEl3::Tg0 >(0); /* Set TTBR0_EL3 granule as 4 KiB */
tcr.Set<hw::TcrEl3::Ps >(1); /* Set the physical addrss size as 36-bit (64 GiB) */
tcr.Set<hw::TcrEl3::Tbi >(0); /* Top byte is not ignored in addrss calculations */
HW_CPU_SET_TCR_EL3(tcr);
}
/* Clear cptr_el3. */
{
util::BitPack32 cptr = {};
cptr.Set<hw::CptrEl3::Tfp >(0); /* FP/SIMD instructions don't trap. */
cptr.Set<hw::CptrEl3::Tta >(0); /* Reserved bit (no trace functionality present). */
cptr.Set<hw::CptrEl3::Tcpac>(0); /* Access to cpacr_El1 does not trap. */
HW_CPU_SET_CPTR_EL3(cptr);
}
/* Set mair_el3. */
{
u64 mair = (MemoryRegionAttributes_Normal << (MemoryRegionAttributeWidth * MemoryAttributeIndexNormal)) |
(MemoryRegionAttributes_Device << (MemoryRegionAttributeWidth * MemoryAttributeIndexDevice));
HW_CPU_SET_MAIR_EL3(mair);
}
/* Set vectors. */
{
constexpr u64 vectors = MemoryRegionVirtualTzramProgramExceptionVectors.GetAddress();
HW_CPU_SET_VBAR_EL3(vectors);
}
/* Prevent instruction re-ordering around this point. */
hw::InstructionSynchronizationBarrier();
}
void EnableMmu() {
/* Create sctlr value. */
util::BitPack64 sctlr = { hw::SctlrEl3::Res1 };
sctlr.Set<hw::SctlrEl3::M>(1); /* Globally enable the MMU. */
sctlr.Set<hw::SctlrEl3::A>(0); /* Disable alignment fault checking. */
sctlr.Set<hw::SctlrEl3::C>(1); /* Globally enable the data and unified caches. */
sctlr.Set<hw::SctlrEl3::Sa>(0); /* Disable stack alignment checking. */
sctlr.Set<hw::SctlrEl3::I>(1); /* Globally enable the instruction cache. */
sctlr.Set<hw::SctlrEl3::Wxn>(0); /* Do not force writable pages to be ExecuteNever. */
sctlr.Set<hw::SctlrEl3::Ee>(0); /* Exceptions should be little endian. */
/* Ensure all writes are done before turning on the mmu. */
hw::DataSynchronizationBarrierInnerShareable();
/* Invalidate the entire tlb. */
hw::InvalidateEntireTlb();
/* Ensure instruction consistency. */
hw::DataSynchronizationBarrierInnerShareable();
hw::InstructionSynchronizationBarrier();
/* Set sctlr_el3. */
HW_CPU_SET_SCTLR_EL3(sctlr);
hw::InstructionSynchronizationBarrier();
}
bool IsExitLp0() {
return reg::Read(MC + MC_SECURITY_CFG3) == 0;
}
constexpr void AddPhysicalTzramIdentityMappingImpl(u64 *l1, u64 *l2, u64 *l3) {
/* Define extents. */
const uintptr_t start_address = MemoryRegionPhysicalTzram.GetAddress();
const size_t size = MemoryRegionPhysicalTzram.GetSize();
const uintptr_t end_address = start_address + size;
/* Flush cache for the L3 page table entries. */
{
const uintptr_t start = GetL3EntryIndex(start_address);
const uintptr_t end = GetL3EntryIndex(end_address);
for (uintptr_t i = start; i < end; i += hw::DataCacheLineSize / sizeof(*l3)) {
if (!std::is_constant_evaluated()) { hw::FlushDataCacheLine(l3 + i); }
}
}
/* Flush cache for the L2 page table entry. */
if (!std::is_constant_evaluated()) { hw::FlushDataCacheLine(l2 + GetL2EntryIndex(start_address)); }
/* Flush cache for the L1 page table entry. */
if (!std::is_constant_evaluated()) { hw::FlushDataCacheLine(l1 + GetL1EntryIndex(start_address)); }
/* Add the L3 mappings. */
SetL3BlockEntry(l3, start_address, start_address, size, MappingAttributesEl3SecureRwCode);
/* Add the L2 entry for the physical tzram region. */
SetL2TableEntry(l2, MemoryRegionPhysicalTzramL2.GetAddress(), MemoryRegionPhysicalTzramL2L3PageTable.GetAddress(), PageTableTableAttributes_El3SecureCode);
/* Add the L1 entry for the physical region. */
SetL1TableEntry(l1, MemoryRegionPhysical.GetAddress(), MemoryRegionPhysicalTzramL2L3PageTable.GetAddress(), PageTableTableAttributes_El3SecureCode);
static_assert(GetL1EntryIndex(MemoryRegionPhysical.GetAddress()) == 1);
/* Invalidate the data cache for the L3 page table entries. */
{
const uintptr_t start = GetL3EntryIndex(start_address);
const uintptr_t end = GetL3EntryIndex(end_address);
for (uintptr_t i = start; i < end; i += hw::DataCacheLineSize / sizeof(*l3)) {
if (!std::is_constant_evaluated()) { hw::InvalidateDataCacheLine(l3 + i); }
}
}
/* Flush cache for the L2 page table entry. */
if (!std::is_constant_evaluated()) { hw::InvalidateDataCacheLine(l2 + GetL2EntryIndex(start_address)); }
/* Flush cache for the L1 page table entry. */
if (!std::is_constant_evaluated()) { hw::InvalidateDataCacheLine(l1 + GetL1EntryIndex(start_address)); }
}
void RestoreDebugCode() {
#if defined(AMS_BUILD_FOR_DEBUGGING) || defined(AMS_BUILD_FOR_AUDITING)
{
const u64 *src = MemoryRegionPhysicalDramDebugDataStore.GetPointer<u64>();
volatile u64 *dst = MemoryRegionPhysicalDebugCode.GetPointer<u64>();
for (size_t i = 0; i < MemoryRegionPhysicalDramDebugDataStore.GetSize() / sizeof(u64); ++i) {
dst[i] = src[i];
}
}
#endif
}
void AddPhysicalTzramIdentityMapping() {
/* Get page table extents. */
u64 * const l1 = MemoryRegionPhysicalTzramL1PageTable.GetPointer<u64>();
u64 * const l2_l3 = MemoryRegionPhysicalTzramL2L3PageTable.GetPointer<u64>();
/* Add the mapping. */
AddPhysicalTzramIdentityMappingImpl(l1, l2_l3, l2_l3);
/* Ensure that mappings are consistent. */
setup::EnsureMappingConsistency();
}
}
void SetupCpuMemoryControllersEnableMmu() {
SetupCpuCommonControllers();
SetupCpuEl3Controllers();
EnableMmu();
}
void SetupSocDmaControllers() {
/* Ensure that our caches are managed. */
setup::InvalidateEntireDataCache();
setup::EnsureInstructionConsistency();
/* Lock tsec. */
tsec::Lock();
/* Enable SWID[0] for all bits. */
reg::Write(AHB_ARBC(AHB_MASTER_SWID), ~0u);
/* Clear SWID1 for all bits. */
reg::Write(AHB_ARBC(AHB_MASTER_SWID_1), 0u);
/* Set MSELECT config to set WRAP_TO_INCR_SLAVE0(APC) | WRAP_TO_INCR_SLAVE1(PCIe) | WRAP_TO_INCR_SLAVE2(GPU) */
/* and clear ERR_RESP_EN_SLAVE1(PCIe) | ERR_RESP_EN_SLAVE2(GPU) */
{
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 USB, USB2, AHB-DMA from arbitration. */
{
reg::ReadWrite(AHB_ARBC(AHB_ARBITRATION_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));
}
/* Select high priority group with priority 7. */
{
u32 priority_ctrl = {};
priority_ctrl |= (7u << 29); /* Set group 7. */
priority_ctrl |= (1u << 0); /* Set high priority. */
reg::Write(AHB_ARBC(AHB_ARBITRATION_PRIORITY_CTRL), priority_ctrl);
}
/* Prevent splitting AHB writes to TZRAM. */
{
reg::Write(AHB_ARBC(AHB_GIZMO_TZRAM), (1u << 7));
}
/* NOTE: This is Mariko only in Nintendo's firmware. */
/* Still, it seems to have no adverse effects on Erista... */
/* TODO: Find a way to get access to SocType this early (fuse driver isn't alive yet), only write on mariko? */
{
reg::ReadWrite(AHB_ARBC(AHB_AHB_SPARE_REG), AHB_REG_BITS_VALUE(AHB_SPARE_REG_AHB_SPARE_REG, 0xE0000));
}
}
void SetupSocDmaControllersCpuMemoryControllersEnableMmuWarmboot() {
/* If this is being called from lp0 exit, we want to setup the soc dma controllers. */
if (IsExitLp0()) {
RestoreDebugCode();
SetupSocDmaControllers();
}
/* Add a physical TZRAM identity map. */
AddPhysicalTzramIdentityMapping();
/* Initialize cpu memory controllers and the MMU. */
SetupCpuMemoryControllersEnableMmu();
}
}
| 13,932
|
C++
|
.cpp
| 245
| 43.583673
| 183
| 0.577947
|
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,330
|
secmon_cpu_context.cpp
|
Atmosphere-NX_Atmosphere/exosphere/program/source/secmon_cpu_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 "secmon_cpu_context.hpp"
#include "secmon_error.hpp"
namespace ams::secmon {
namespace {
struct DebugRegisters {
u32 osdttrx_el1;
u32 osdtrtx_el1;
u32 mdscr_el1;
u32 oseccr_el1;
u32 mdccint_el1;
u32 dbgclaimclr_el1;
u32 dbgvcr32_el2;
u32 sder32_el3;
u32 mdcr_el2;
u32 mdcr_el3;
u32 spsr_el3;
};
struct CoreContext {
EntryContext entry_context;
bool is_on;
bool is_reset_expected;
bool is_debug_registers_saved;
DebugRegisters debug_registers;
};
void SaveDebugRegisters(DebugRegisters &dr) {
/* Set the OS lock; this will be unlocked by entry code. */
HW_CPU_SET_OSLAR_EL1(1);
/* Save general debug registers. */
HW_CPU_GET_OSDTRRX_EL1 (dr.osdttrx_el1);
HW_CPU_GET_OSDTRTX_EL1 (dr.osdtrtx_el1);
HW_CPU_GET_MDSCR_EL1 (dr.mdscr_el1);
HW_CPU_GET_OSECCR_EL1 (dr.oseccr_el1);
HW_CPU_GET_MDCCINT_EL1 (dr.mdccint_el1);
HW_CPU_GET_DBGCLAIMCLR_EL1(dr.dbgclaimclr_el1);
HW_CPU_GET_DBGVCR32_EL2 (dr.dbgvcr32_el2);
HW_CPU_GET_SDER32_EL3 (dr.sder32_el3);
HW_CPU_GET_MDCR_EL2 (dr.mdcr_el2);
HW_CPU_GET_MDCR_EL3 (dr.mdcr_el3);
HW_CPU_GET_SPSR_EL3 (dr.spsr_el3);
}
void RestoreDebugRegisters(const DebugRegisters &dr) {
/* Restore general debug registers. */
HW_CPU_SET_OSDTRRX_EL1 (dr.osdttrx_el1);
HW_CPU_SET_OSDTRTX_EL1 (dr.osdtrtx_el1);
HW_CPU_SET_MDSCR_EL1 (dr.mdscr_el1);
HW_CPU_SET_OSECCR_EL1 (dr.oseccr_el1);
HW_CPU_SET_MDCCINT_EL1 (dr.mdccint_el1);
HW_CPU_SET_DBGCLAIMCLR_EL1(dr.dbgclaimclr_el1);
HW_CPU_SET_DBGVCR32_EL2 (dr.dbgvcr32_el2);
HW_CPU_SET_SDER32_EL3 (dr.sder32_el3);
HW_CPU_SET_MDCR_EL2 (dr.mdcr_el2);
HW_CPU_SET_MDCR_EL3 (dr.mdcr_el3);
HW_CPU_SET_SPSR_EL3 (dr.spsr_el3);
}
constinit CoreContext g_core_contexts[NumCores] = {};
}
bool IsCoreOn(int core) {
return g_core_contexts[core].is_on;
}
void SetCoreOff() {
g_core_contexts[hw::GetCurrentCoreId()].is_on = false;
}
bool IsResetExpected() {
return g_core_contexts[hw::GetCurrentCoreId()].is_reset_expected;
}
void SetResetExpected(int core, bool expected) {
g_core_contexts[core].is_reset_expected = expected;
}
void SetResetExpected(bool expected) {
SetResetExpected(hw::GetCurrentCoreId(), expected);
}
void SetEntryContext(int core, uintptr_t address, uintptr_t arg) {
g_core_contexts[core].entry_context.pc = address;
g_core_contexts[core].entry_context.x0 = arg;
}
void GetEntryContext(EntryContext *out) {
auto &ctx = g_core_contexts[hw::GetCurrentCoreId()];
const auto pc = ctx.entry_context.pc;
const auto x0 = ctx.entry_context.x0;
if (pc == 0 || ctx.is_on) {
SetError(pkg1::ErrorInfo_InvalidCoreContext);
AMS_ABORT("Invalid core context");
}
ctx.entry_context = {};
ctx.is_on = true;
out->pc = pc;
out->x0 = x0;
}
void SaveDebugRegisters() {
auto &ctx = g_core_contexts[hw::GetCurrentCoreId()];
SaveDebugRegisters(ctx.debug_registers);
ctx.is_debug_registers_saved = true;
}
void RestoreDebugRegisters() {
auto &ctx = g_core_contexts[hw::GetCurrentCoreId()];
if (ctx.is_debug_registers_saved) {
RestoreDebugRegisters(ctx.debug_registers);
ctx.is_debug_registers_saved = false;
}
}
}
| 4,651
|
C++
|
.cpp
| 117
| 30.897436
| 76
| 0.593036
|
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,331
|
secmon_exception_handler.cpp
|
Atmosphere-NX_Atmosphere/exosphere/program/source/secmon_exception_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"
namespace ams::secmon {
namespace {
constexpr inline uintptr_t PMC = MemoryRegionVirtualDevicePmc.GetAddress();
constinit util::Atomic<bool> g_is_locked = false;
}
void ExceptionHandlerImpl(uintptr_t lr, uintptr_t sp) {
/* On release config, we won't actually use the passed parameters. */
AMS_UNUSED(lr, sp);
/* Ensure that previous logs have been flushed. */
AMS_LOG_FLUSH();
/* Get system registers. */
uintptr_t far_el1, far_el3, elr_el3;
util::BitPack32 esr_el3;
HW_CPU_GET_FAR_EL1(far_el1);
HW_CPU_GET_FAR_EL3(far_el3);
HW_CPU_GET_ELR_EL3(elr_el3);
HW_CPU_GET_ESR_EL3(esr_el3);
/* Print some whitespace before the exception handler. */
AMS_LOG("\n\n");
AMS_SECMON_LOG("ExceptionHandler\n");
AMS_SECMON_LOG("----------------\n");
AMS_SECMON_LOG("esr: 0x%08X\n", esr_el3.value);
AMS_SECMON_LOG(" Exception Class: 0x%02X\n", esr_el3.Get<hw::EsrEl3::Ec>());
AMS_SECMON_LOG(" Instruction Length: %d\n", esr_el3.Get<hw::EsrEl3::Il>() ? 32 : 16);
AMS_SECMON_LOG(" Instruction Specific Syndrome: 0x%07X\n", esr_el3.Get<hw::EsrEl3::Iss>());
AMS_SECMON_LOG("far_el1: 0x%016lX\n", far_el1);
AMS_SECMON_LOG("far_el3: 0x%016lX\n", far_el3);
AMS_SECMON_LOG("elr_el3: 0x%016lX\n", elr_el3);
AMS_SECMON_LOG("lr: 0x%016lX\n", lr);
AMS_SECMON_LOG("sp: 0x%016lX\n", sp);
AMS_DUMP(reinterpret_cast<void *>(sp), util::AlignUp(sp, mmu::PageSize) - sp);
AMS_LOG_FLUSH();
}
NORETURN void ExceptionHandler() {
/* Get link register and stack pointer. */
u64 lr, sp;
{
__asm__ __volatile__("mov %0, lr" : "=r"(lr) :: "memory");
__asm__ __volatile__("mov %0, sp" : "=r"(sp) :: "memory");
}
/* Acquire exclusive access to exception handling logic. */
if (!g_is_locked.Exchange(true)) {
/* Invoke the exception handler impl. */
ExceptionHandlerImpl(lr, sp);
/* Lockout the security engine. */
se::Lockout();
/* Lockout fuses. */
fuse::Lockout();
/* Disable crypto operations after reboot. */
reg::Write(PMC + APBDEV_PMC_CRYPTO_OP, 0);
/* Perform an error reboot. */
secmon::SetError(pkg1::ErrorInfo_UnknownAbort);
secmon::ErrorReboot();
} else {
/* Wait forever while the first core prints the exception and reboots. */
while (true) {
util::WaitMicroSeconds(1000);
}
}
}
}
| 3,425
|
C++
|
.cpp
| 78
| 35.807692
| 107
| 0.591524
|
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,332
|
secmon_user_power_management.cpp
|
Atmosphere-NX_Atmosphere/exosphere/program/source/secmon_user_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_cpu_context.hpp"
#include "secmon_page_mapper.hpp"
#include "secmon_mariko_fatal_error.hpp"
#include "secmon_user_power_management.hpp"
#include "rebootstub_bin.h"
namespace ams::secmon {
namespace {
constexpr inline const uintptr_t PMC = MemoryRegionVirtualDevicePmc.GetAddress();
constexpr inline const u32 RebootStubPhysicalAddress = MemoryRegionPhysicalIramRebootStub.GetAddress();
enum RebootStubAction {
RebootStubAction_ShutDown = 0,
RebootStubAction_JumpToPayload = 1,
};
NORETURN void PerformPmcReboot() {
/* Write MAIN_RST. */
reg::Write(PMC + APBDEV_PMC_CNTRL, 0x10);
while (true) {
/* ... */
}
}
void LoadRebootStub(u32 action) {
/* Configure the bootrom to boot to warmboot payload. */
reg::Write(PMC + APBDEV_PMC_SCRATCH0, 0x1);
/* Patch the bootrom to perform an SVC immediately after the second spare write. */
reg::Write(PMC + APBDEV_PMC_SCRATCH45, 0x2E38DFFF);
reg::Write(PMC + APBDEV_PMC_SCRATCH46, 0x6001DC28);
/* Patch the bootrom to jump to the reboot stub we'll prepare in iram on SVC. */
reg::Write(PMC + APBDEV_PMC_SCRATCH33, RebootStubPhysicalAddress);
reg::Write(PMC + APBDEV_PMC_SCRATCH40, 0x6000F208);
{
/* Map the iram page. */
AtmosphereIramPageMapper mapper(RebootStubPhysicalAddress);
AMS_ABORT_UNLESS(mapper.Map());
/* Copy the reboot stub. */
AMS_ABORT_UNLESS(mapper.CopyToMapping(RebootStubPhysicalAddress, rebootstub_bin, rebootstub_bin_size));
/* Set the reboot type. */
AMS_ABORT_UNLESS(mapper.CopyToMapping(RebootStubPhysicalAddress + 4, std::addressof(action), sizeof(action)));
}
}
}
void PerformUserRebootByPmic() {
/* Ensure that i2c-5 is usable for communicating with the pmic. */
clkrst::EnableI2c5Clock();
i2c::Initialize(i2c::Port_5);
/* Reboot. */
pmic::ShutdownSystem(true);
}
void PerformUserRebootToRcm() {
/* Configure the bootrom to boot to rcm. */
reg::Write(PMC + APBDEV_PMC_SCRATCH0, 0x2);
/* Reboot. */
PerformPmcReboot();
}
void PerformUserRebootToPayload() {
/* Load our reboot stub to iram. */
LoadRebootStub(RebootStubAction_JumpToPayload);
/* Reboot. */
PerformPmcReboot();
}
void PerformUserRebootToFatalError() {
if (fuse::GetSocType() == fuse::SocType_Erista) {
/* On Erista, we reboot to fatal error by jumping to fusee primary's handler. */
return PerformUserRebootToPayload();
} else /* if (fuse::GetSocType() == fuse::SocType_Mariko) */ {
/* Call the fatal error handler. */
HandleMarikoFatalErrorInterrupt();
/* We should never get to this point. */
AMS_ABORT("Returned from Mariko Fatal handler?\n");
}
}
void PerformUserShutDown() {
if (fuse::GetSocType() == fuse::SocType_Mariko) {
/* Ensure that i2c-5 is usable for communicating with the pmic. */
clkrst::EnableI2c5Clock();
i2c::Initialize(i2c::Port_5);
/* On Mariko shutdown via pmic. */
pmic::ShutdownSystem(false);
} else /* if (fuse::GetSocType() == fuse::SocType_Erista) */ {
/* Load our reboot stub to iram. */
LoadRebootStub(RebootStubAction_ShutDown);
/* Reboot. */
PerformPmcReboot();
}
}
}
| 4,399
|
C++
|
.cpp
| 101
| 34.584158
| 126
| 0.623976
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.