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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6,423
|
crypto_csrng.os.generic.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/crypto/crypto_csrng.os.generic.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "../spl/impl/spl_ctr_drbg.hpp"
#include <sys/random.h>
namespace ams::crypto {
namespace {
using Drbg = ::ams::spl::impl::CtrDrbg<crypto::AesEncryptor128, crypto::AesEncryptor128::KeySize, false>;
constinit util::TypedStorage<Drbg> g_drbg = {};
bool InitializeCsrng() {
u8 seed[Drbg::SeedSize];
AMS_ABORT_UNLESS(::getentropy(seed, sizeof(seed)) == 0);
util::ConstructAt(g_drbg);
util::GetReference(g_drbg).Initialize(seed, sizeof(seed), nullptr, 0, nullptr, 0);
return true;
}
}
void GenerateCryptographicallyRandomBytes(void *dst, size_t dst_size) {
AMS_FUNCTION_LOCAL_STATIC(bool, s_initialized, InitializeCsrng());
AMS_ABORT_UNLESS(s_initialized);
AMS_ASSERT(dst_size <= Drbg::RequestSizeMax);
if (!util::GetReference(g_drbg).Generate(dst, dst_size, nullptr, 0)) {
/* Reseed, if needed. */
{
u8 seed[Drbg::SeedSize];
AMS_ABORT_UNLESS(::getentropy(seed, sizeof(seed)) == 0);
util::GetReference(g_drbg).Reseed(seed, sizeof(seed), nullptr, 0);
}
util::GetReference(g_drbg).Generate(dst, dst_size, nullptr, 0);
}
}
}
| 1,946
|
C++
|
.cpp
| 45
| 36.2
| 113
| 0.652358
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,424
|
powctl_driver_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/powctl/powctl_driver_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 <stratosphere.hpp>
#include "impl/powctl_select_board_driver.hpp"
#include "impl/powctl_device_management.hpp"
namespace ams::powctl {
void Initialize(bool enable_interrupt_handlers) {
/* Initialize the board driver. */
impl::board::Initialize(enable_interrupt_handlers);
/* Initialize drivers. */
impl::InitializeDrivers();
}
void Finalize() {
/* Finalize drivers. */
impl::FinalizeDrivers();
/* Finalize the board driver. */
impl::board::Finalize();
}
}
| 1,187
|
C++
|
.cpp
| 32
| 32.9375
| 76
| 0.707317
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,425
|
powctl_charger_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/powctl/powctl_charger_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 <stratosphere.hpp>
#include "impl/powctl_i_power_control_driver.hpp"
#include "impl/powctl_device_management.hpp"
namespace ams::powctl {
namespace {
impl::SessionImpl &GetOpenSessionImpl(Session &session) {
AMS_ASSERT(session.has_session);
auto &impl = GetReference(session.impl_storage);
AMS_ASSERT(impl.IsOpen());
return impl;
}
}
Result GetChargerChargeCurrentState(ChargeCurrentState *out, Session &session) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Read), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().GetChargerChargeCurrentState(out, std::addressof(device)));
}
Result SetChargerChargeCurrentState(Session &session, ChargeCurrentState state) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Write), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().SetChargerChargeCurrentState(std::addressof(device), state));
}
Result GetChargerFastChargeCurrentLimit(int *out_ma, Session &session) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Read), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().GetChargerFastChargeCurrentLimit(out_ma, std::addressof(device)));
}
Result SetChargerFastChargeCurrentLimit(Session &session, int ma) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Write), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().SetChargerFastChargeCurrentLimit(std::addressof(device), ma));
}
Result GetChargerChargeVoltageLimit(int *out_mv, Session &session) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Read), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().GetChargerChargeVoltageLimit(out_mv, std::addressof(device)));
}
Result SetChargerChargeVoltageLimit(Session &session, int mv) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Write), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().SetChargerChargeVoltageLimit(std::addressof(device), mv));
}
Result SetChargerChargerConfiguration(Session &session, ChargerConfiguration cfg) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Write), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().SetChargerChargerConfiguration(std::addressof(device), cfg));
}
Result IsChargerHiZEnabled(bool *out, Session &session) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Read), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().IsChargerHiZEnabled(out, std::addressof(device)));
}
Result SetChargerHiZEnabled(Session &session, bool en) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Write), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().SetChargerHiZEnabled(std::addressof(device), en));
}
Result GetChargerInputCurrentLimit(int *out_ma, Session &session) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Read), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().GetChargerInputCurrentLimit(out_ma, std::addressof(device)));
}
Result SetChargerInputCurrentLimit(Session &session, int ma) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Write), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().SetChargerInputCurrentLimit(std::addressof(device), ma));
}
Result SetChargerInputVoltageLimit(Session &session, int mv) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Write), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().SetChargerInputVoltageLimit(std::addressof(device), mv));
}
Result SetChargerBoostModeCurrentLimit(Session &session, int ma) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Write), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().SetChargerBoostModeCurrentLimit(std::addressof(device), ma));
}
Result GetChargerChargerStatus(ChargerStatus *out, Session &session) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Read), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().GetChargerChargerStatus(out, std::addressof(device)));
}
Result IsChargerWatchdogTimerEnabled(bool *out, Session &session) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Read), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().IsChargerWatchdogTimerEnabled(out, std::addressof(device)));
}
Result SetChargerWatchdogTimerEnabled(Session &session, bool en) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Write), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().SetChargerWatchdogTimerEnabled(std::addressof(device), en));
}
Result SetChargerWatchdogTimerTimeout(Session &session, TimeSpan timeout) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Write), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().SetChargerWatchdogTimerTimeout(std::addressof(device), timeout));
}
Result ResetChargerWatchdogTimer(Session &session);
Result GetChargerBatteryCompensation(int *out_mo, Session &session) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Read), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().GetChargerBatteryCompensation(out_mo, std::addressof(device)));
}
Result SetChargerBatteryCompensation(Session &session, int mo) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Write), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().SetChargerBatteryCompensation(std::addressof(device), mo));
}
Result GetChargerVoltageClamp(int *out_mv, Session &session) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Read), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().GetChargerVoltageClamp(out_mv, std::addressof(device)));
}
Result SetChargerVoltageClamp(Session &session, int mv) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Write), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().SetChargerVoltageClamp(std::addressof(device), mv));
}
}
| 13,034
|
C++
|
.cpp
| 239
| 46.460251
| 142
| 0.669054
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,426
|
powctl_session_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/powctl/powctl_session_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 <stratosphere.hpp>
#include "impl/powctl_device_management.hpp"
namespace ams::powctl {
namespace {
ddsf::AccessMode SanitizeAccessMode(ddsf::AccessMode access_mode) {
switch (access_mode) {
case ddsf::AccessMode_Read:
case ddsf::AccessMode_Write:
case ddsf::AccessMode_ReadWrite:
case ddsf::AccessMode_WriteShared:
case ddsf::AccessMode_ReadWriteShared:
return access_mode;
default:
return ddsf::AccessMode_None;
}
}
impl::SessionImpl &GetSessionImpl(Session &session) {
return GetReference(session.impl_storage);
}
void DestroySession(Session &session) {
std::destroy_at(std::addressof(GetSessionImpl(session)));
session.has_session = false;
}
void DestroySessionIfNecessary(Session &session) {
if (session.has_session) {
DestroySession(session);
}
}
void CloseSessionIfOpen(Session &session) {
if (session.has_session && GetSessionImpl(session).IsOpen()) {
DestroySession(session);
}
}
}
Result OpenSession(Session *out, DeviceCode device_code, ddsf::AccessMode access_mode) {
/* Validate input. */
AMS_ASSERT(out != nullptr);
access_mode = SanitizeAccessMode(access_mode);
/* Find the target device. */
impl::IDevice *device = nullptr;
R_TRY(impl::FindDevice(std::addressof(device), device_code));
/* Clean up the session if we have one. */
DestroySessionIfNecessary(*out);
/* Construct the session. */
auto *session = std::construct_at(std::addressof(GetSessionImpl(*out)));
auto guard = SCOPE_GUARD { DestroySessionIfNecessary(*out); };
/* Try to open the session. */
R_TRY(ddsf::OpenSession(device, session, access_mode));
/* We opened the session! */
guard.Cancel();
R_SUCCEED();
}
void CloseSession(Session &session) {
/* This seems extremely unnecessary/duplicate, but it's what Nintendo does. */
CloseSessionIfOpen(session);
DestroySession(session);
}
}
| 2,956
|
C++
|
.cpp
| 73
| 31.808219
| 92
| 0.63145
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,427
|
powctl_battery_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/powctl/powctl_battery_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 <stratosphere.hpp>
#include "impl/powctl_i_power_control_driver.hpp"
#include "impl/powctl_device_management.hpp"
namespace ams::powctl {
namespace {
impl::SessionImpl &GetOpenSessionImpl(Session &session) {
AMS_ASSERT(session.has_session);
auto &impl = GetReference(session.impl_storage);
AMS_ASSERT(impl.IsOpen());
return impl;
}
}
Result GetBatteryChargePercentage(float *out_percent, Session &session) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Read), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().GetBatteryChargePercentage(out_percent, std::addressof(device)));
}
Result GetBatteryVoltageFuelGaugePercentage(float *out_percent, Session &session) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Read), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().GetBatteryVoltageFuelGaugePercentage(out_percent, std::addressof(device)));
}
Result GetBatteryFullCapacity(int *out_mah, Session &session) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Read), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().GetBatteryFullCapacity(out_mah, std::addressof(device)));
}
Result GetBatteryRemainingCapacity(int *out_mah, Session &session) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Read), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().GetBatteryRemainingCapacity(out_mah, std::addressof(device)));
}
Result SetBatteryChargePercentageMinimumAlertThreshold(Session &session, float percentage) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Write), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().SetBatteryChargePercentageMinimumAlertThreshold(std::addressof(device), percentage));
}
Result SetBatteryChargePercentageMaximumAlertThreshold(Session &session, float percentage) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Write), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().SetBatteryChargePercentageMaximumAlertThreshold(std::addressof(device), percentage));
}
Result SetBatteryVoltageFuelGaugePercentageMinimumAlertThreshold(Session &session, float percentage) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Write), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().SetBatteryVoltageFuelGaugePercentageMinimumAlertThreshold(std::addressof(device), percentage));
}
Result SetBatteryVoltageFuelGaugePercentageMaximumAlertThreshold(Session &session, float percentage) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Write), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().SetBatteryVoltageFuelGaugePercentageMaximumAlertThreshold(std::addressof(device), percentage));
}
Result SetBatteryFullChargeThreshold(Session &session, float percentage) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Write), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().SetBatteryFullChargeThreshold(std::addressof(device), percentage));
}
Result GetBatteryAverageCurrent(int *out_ma, Session &session) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Read), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().GetBatteryAverageCurrent(out_ma, std::addressof(device)));
}
Result GetBatteryCurrent(int *out_ma, Session &session) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Read), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().GetBatteryCurrent(out_ma, std::addressof(device)));
}
Result GetBatteryInternalState(void *dst, size_t *out_size, Session &session, size_t dst_size) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Read), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().GetBatteryInternalState(dst, out_size, std::addressof(device), dst_size));
}
Result SetBatteryInternalState(Session &session, const void *src, size_t src_size) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Write), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().SetBatteryInternalState(std::addressof(device), src, src_size));
}
Result GetBatteryNeedToRestoreParameters(bool *out, Session &session) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Read), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().GetBatteryNeedToRestoreParameters(out, std::addressof(device)));
}
Result SetBatteryNeedToRestoreParameters(Session &session, bool en) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Write), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().SetBatteryNeedToRestoreParameters(std::addressof(device), en));
}
Result IsBatteryI2cShutdownEnabled(bool *out, Session &session) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Read), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().IsBatteryI2cShutdownEnabled(out, std::addressof(device)));
}
Result SetBatteryI2cShutdownEnabled(Session &session, bool en) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Write), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().SetBatteryI2cShutdownEnabled(std::addressof(device), en));
}
Result IsBatteryPresent(bool *out, Session &session) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Read), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().IsBatteryPresent(out, std::addressof(device)));
}
Result GetBatteryCycles(int *out, Session &session) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Read), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().GetBatteryCycles(out, std::addressof(device)));
}
Result SetBatteryCycles(Session &session, int cycles) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Write), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().SetBatteryCycles(std::addressof(device), cycles));
}
Result GetBatteryAge(float *out_percent, Session &session) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Read), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().GetBatteryAge(out_percent, std::addressof(device)));
}
Result GetBatteryTemperature(float *out_c, Session &session) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Read), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().GetBatteryTemperature(out_c, std::addressof(device)));
}
Result GetBatteryMaximumTemperature(float *out_c, Session &session) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Read), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().GetBatteryMaximumTemperature(out_c, std::addressof(device)));
}
Result SetBatteryTemperatureMinimumAlertThreshold(Session &session, float c) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Write), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().SetBatteryTemperatureMinimumAlertThreshold(std::addressof(device), c));
}
Result SetBatteryTemperatureMaximumAlertThreshold(Session &session, float c) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Write), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().SetBatteryTemperatureMaximumAlertThreshold(std::addressof(device), c));
}
Result GetBatteryVCell(int *out_mv, Session &session) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Read), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().GetBatteryVCell(out_mv, std::addressof(device)));
}
Result GetBatteryAverageVCell(int *out_mv, Session &session) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Read), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().GetBatteryAverageVCell(out_mv, std::addressof(device)));
}
Result GetBatteryAverageVCellTime(TimeSpan *out, Session &session) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Read), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().GetBatteryAverageVCellTime(out, std::addressof(device)));
}
Result GetBatteryOpenCircuitVoltage(int *out_mv, Session &session) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Read), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().GetBatteryOpenCircuitVoltage(out_mv, std::addressof(device)));
}
Result SetBatteryVoltageMinimumAlertThreshold(Session &session, int mv) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Write), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().SetBatteryVoltageMinimumAlertThreshold(std::addressof(device), mv));
}
Result SetBatteryVoltageMaximumAlertThreshold(Session &session, int mv) {
/* Get the session impl. */
auto &impl = GetOpenSessionImpl(session);
/* Check the access mode. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Write), ddsf::ResultPermissionDenied());
/* Get the device. */
auto &device = impl.GetDevice().SafeCastTo<impl::IDevice>();
/* Call into the driver. */
R_RETURN(device.GetDriver().SafeCastTo<impl::IPowerControlDriver>().SetBatteryVoltageMaximumAlertThreshold(std::addressof(device), mv));
}
}
| 18,956
|
C++
|
.cpp
| 338
| 47.846154
| 171
| 0.670362
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,428
|
powctl_device_management.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/powctl/impl/powctl_device_management.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "powctl_device_management.hpp"
namespace ams::powctl::impl {
namespace {
constinit os::ThreadType g_interrupt_thread = {};
constexpr inline size_t InterruptThreadStackSize = os::MemoryPageSize;
alignas(os::MemoryPageSize) u8 g_interrupt_thread_stack[InterruptThreadStackSize];
IPowerControlDriver::List &GetDriverList() {
AMS_FUNCTION_LOCAL_STATIC_CONSTINIT(IPowerControlDriver::List, s_driver_list);
return s_driver_list;
}
ddsf::EventHandlerManager &GetInterruptHandlerManager() {
AMS_FUNCTION_LOCAL_STATIC(ddsf::EventHandlerManager, s_interrupt_handler_manager);
return s_interrupt_handler_manager;
}
ddsf::DeviceCodeEntryManager &GetDeviceCodeEntryManager() {
class DeviceCodeEntryManagerWithUnitHeap {
private:
u8 m_heap_memory[2_KB];
sf::UnitHeapMemoryResource m_memory_resource;
util::TypedStorage<ddsf::DeviceCodeEntryManager> m_manager;
public:
DeviceCodeEntryManagerWithUnitHeap() {
/* Initialize the memory resource. */
m_memory_resource.Attach(lmem::CreateUnitHeap(m_heap_memory, sizeof(m_heap_memory), sizeof(ddsf::DeviceCodeEntryHolder), lmem::CreateOption_ThreadSafe));
/* Construct the entry manager. */
util::ConstructAt(m_manager, std::addressof(m_memory_resource));
}
ALWAYS_INLINE operator ddsf::DeviceCodeEntryManager &() {
return util::GetReference(m_manager);
}
};
AMS_FUNCTION_LOCAL_STATIC(DeviceCodeEntryManagerWithUnitHeap, s_device_code_entry_manager_holder);
return s_device_code_entry_manager_holder;
}
void InterruptThreadFunction(void *arg) {
AMS_UNUSED(arg);
GetInterruptHandlerManager().LoopAuto();
}
}
void InitializeDrivers() {
/* Ensure the event handler manager is initialized. */
GetInterruptHandlerManager().Initialize();
/* Initialize all registered drivers. */
for (auto &driver : GetDriverList()) {
driver.SafeCastTo<IPowerControlDriver>().InitializeDriver();
}
/* Create the interrupt thread. */
R_ABORT_UNLESS(os::CreateThread(std::addressof(g_interrupt_thread), InterruptThreadFunction, nullptr, g_interrupt_thread_stack, InterruptThreadStackSize, AMS_GET_SYSTEM_THREAD_PRIORITY(powctl, InterruptHandler)));
os::SetThreadNamePointer(std::addressof(g_interrupt_thread), AMS_GET_SYSTEM_THREAD_NAME(powctl, InterruptHandler));
os::StartThread(std::addressof(g_interrupt_thread));
/* Wait for the interrupt thread to enter the loop. */
GetInterruptHandlerManager().WaitLoopEnter();
}
void FinalizeDrivers() {
/* Request the interrupt thread stop. */
GetInterruptHandlerManager().RequestStop();
os::WaitThread(std::addressof(g_interrupt_thread));
os::DestroyThread(std::addressof(g_interrupt_thread));
/* Reset all device code entries. */
GetDeviceCodeEntryManager().Reset();
/* Finalize all registered drivers. */
for (auto &driver : GetDriverList()) {
driver.SafeCastTo<IPowerControlDriver>().FinalizeDriver();
}
/* Finalize the interrupt handler manager. */
GetInterruptHandlerManager().Finalize();
}
void RegisterDriver(IPowerControlDriver *driver) {
AMS_ASSERT(driver != nullptr);
GetDriverList().push_back(*driver);
}
void UnregisterDriver(IPowerControlDriver *driver) {
AMS_ASSERT(driver != nullptr);
if (driver->IsLinkedToList()) {
auto &list = GetDriverList();
list.erase(list.iterator_to(*driver));
}
}
Result RegisterDeviceCode(DeviceCode device_code, IDevice *device) {
AMS_ASSERT(device != nullptr);
R_TRY(GetDeviceCodeEntryManager().Add(device_code, device));
R_SUCCEED();
}
bool UnregisterDeviceCode(DeviceCode device_code) {
return GetDeviceCodeEntryManager().Remove(device_code);
}
void RegisterInterruptHandler(ddsf::IEventHandler *handler) {
AMS_ASSERT(handler != nullptr);
GetInterruptHandlerManager().RegisterHandler(handler);
}
void UnregisterInterruptHandler(ddsf::IEventHandler *handler) {
AMS_ASSERT(handler != nullptr);
GetInterruptHandlerManager().UnregisterHandler(handler);
}
Result FindDevice(powctl::impl::IDevice **out, DeviceCode device_code) {
/* Validate output. */
AMS_ASSERT(out != nullptr);
/* Find the device. */
ddsf::IDevice *device;
R_TRY(GetDeviceCodeEntryManager().FindDevice(std::addressof(device), device_code));
/* Set output. */
*out = device->SafeCastToPointer<powctl::impl::IDevice>();
R_SUCCEED();
}
}
| 5,768
|
C++
|
.cpp
| 121
| 38.272727
| 221
| 0.658002
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,429
|
powctl_interrupt_event_handler.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/powctl/impl/board/nintendo/nx/powctl_interrupt_event_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 <stratosphere.hpp>
#include "powctl_interrupt_event_handler.hpp"
namespace ams::powctl::impl::board::nintendo::nx {
void ChargerInterruptEventHandler::SignalEvent(IDevice *device) {
/* TODO */
AMS_UNUSED(device);
AMS_ABORT();
}
void BatteryInterruptEventHandler::SignalEvent(IDevice *device) {
/* TODO */
AMS_UNUSED(device);
AMS_ABORT();
}
}
| 1,053
|
C++
|
.cpp
| 29
| 32.517241
| 76
| 0.715965
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,430
|
powctl_bq24193_driver.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/powctl/impl/board/nintendo/nx/powctl_bq24193_driver.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 "powctl_bq24193_driver.hpp"
namespace ams::powctl::impl::board::nintendo::nx {
namespace bq24193 {
constexpr inline u8 InputSourceControl = 0x00;
constexpr inline u8 PowerOnConfiguration = 0x01;
constexpr inline u8 ChargeCurrentControl = 0x02;
constexpr inline u8 PreChargeTerminationCurrentControl = 0x03;
constexpr inline u8 ChargeVoltageControl = 0x04;
constexpr inline u8 ChargeTerminationTimerControl = 0x05;
constexpr inline u8 IrCompensationThermalRegulationControl = 0x06;
constexpr inline u8 MiscOperationControl = 0x07;
constexpr inline u8 SystemStatus = 0x08;
constexpr inline u8 Fault = 0x09;
constexpr inline u8 VendorPartRevisionStatus = 0x0A;
constexpr u8 EncodePreChargeCurrentLimit(int ma) {
constexpr int Minimum = 128;
constexpr int Maximum = 2048;
ma = std::max(std::min(ma, Maximum), Minimum);
return static_cast<u8>((static_cast<u32>(ma - Minimum) >> 7) << 4);
}
constexpr u8 EncodeTerminationCurrentLimit(int ma) {
constexpr int Minimum = 128;
constexpr int Maximum = 2048;
ma = std::max(std::min(ma, Maximum), Minimum);
return static_cast<u8>((static_cast<u32>(ma - Minimum) >> 7) << 0);
}
constexpr u8 EncodeMinimumSystemVoltageLimit(int mv) {
constexpr int Minimum = 3000;
constexpr int Maximum = 3700;
mv = std::max(std::min(mv, Maximum), Minimum);
return static_cast<u8>(((mv - Minimum) / 100) << 1);
}
constexpr u8 EncodeFastChargeCurrentLimit(int ma) {
constexpr int Minimum = 512;
constexpr int Maximum = 4544;
ma = std::max(std::min(ma, Maximum), Minimum);
return static_cast<u8>((static_cast<u32>(ma - Minimum) >> 6) << 2);
}
constexpr int DecodeFastChargeCurrentLimit(u8 reg) {
constexpr int Minimum = 512;
return Minimum + (static_cast<u32>(reg & 0xFC) << 4);
}
static_assert(DecodeFastChargeCurrentLimit(EncodeFastChargeCurrentLimit(512)) == 512);
static_assert(DecodeFastChargeCurrentLimit(EncodeFastChargeCurrentLimit(4544)) == 4544);
static_assert(DecodeFastChargeCurrentLimit(EncodeFastChargeCurrentLimit(576)) == 576);
constexpr u8 EncodeChargeVoltageLimit(int mv) {
constexpr int Minimum = 3504;
constexpr int Maximum = 4400;
mv = std::max(std::min(mv, Maximum), Minimum);
return static_cast<u8>((static_cast<u32>(mv - Minimum) >> 4) << 2);
}
constexpr int DecodeChargeVoltageLimit(u8 reg) {
constexpr int Minimum = 3504;
constexpr int Maximum = 4400;
return std::min<int>(Maximum, Minimum + (static_cast<u32>(reg & 0xFC) << 2));
}
static_assert(DecodeChargeVoltageLimit(EncodeChargeVoltageLimit(3504)) == 3504);
static_assert(DecodeChargeVoltageLimit(EncodeChargeVoltageLimit(4400)) == 4400);
static_assert(DecodeChargeVoltageLimit(EncodeChargeVoltageLimit(3520)) == 3520);
constexpr u8 EncodeChargerConfiguration(bq24193::ChargerConfiguration cfg) {
switch (cfg) {
case ChargerConfiguration_ChargeDisable: return 0x00;
case ChargerConfiguration_ChargeBattery: return 0x10;
case ChargerConfiguration_Otg: return 0x20;
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
constexpr u8 EncodeWatchdogTimerSetting(int seconds) {
if (seconds == 0) {
return 0x00;
} else if (seconds < 80) {
return 0x10;
} else if (seconds < 160) {
return 0x20;
} else {
return 0x30;
}
}
constexpr u8 EncodeBatteryCompensation(int mo) {
constexpr int Minimum = 0;
constexpr int Maximum = 70;
mo = std::max(std::min(mo, Maximum), Minimum);
return static_cast<u8>((static_cast<u32>(mo - Minimum) / 10) << 5);
}
constexpr int DecodeBatteryCompensation(u8 reg) {
constexpr int Minimum = 0;
return Minimum + (static_cast<u32>(reg & 0xE0) >> 5) * 10;
}
static_assert(DecodeBatteryCompensation(EncodeBatteryCompensation(0)) == 0);
static_assert(DecodeBatteryCompensation(EncodeBatteryCompensation(70)) == 70);
static_assert(DecodeBatteryCompensation(EncodeBatteryCompensation(30)) == 30);
constexpr u8 EncodeVoltageClamp(int mv) {
constexpr int Minimum = 0;
constexpr int Maximum = 112;
mv = std::max(std::min(mv, Maximum), Minimum);
return static_cast<u8>((static_cast<u32>(mv - Minimum) >> 4) << 2);
}
constexpr int DecodeVoltageClamp(u8 reg) {
constexpr int Minimum = 0;
return Minimum + (static_cast<u32>(reg & 0x1C) << 2);
}
static_assert(DecodeVoltageClamp(EncodeVoltageClamp(0)) == 0);
static_assert(DecodeVoltageClamp(EncodeVoltageClamp(112)) == 112);
static_assert(DecodeVoltageClamp(EncodeVoltageClamp(64)) == 64);
constexpr u8 EncodeInputCurrentLimit(int ma) {
if (ma < 150) {
return 0;
} else if (ma < 500) {
return 1;
} else if (ma < 900) {
return 2;
} else if (ma < 1200) {
return 3;
} else if (ma < 1500) {
return 4;
} else if (ma < 2000) {
return 5;
} else if (ma < 3000) {
return 6;
} else{
return 7;
}
}
constexpr int DecodeInputCurrentLimit(u8 reg) {
switch (reg & 0x07) {
case 0: return 100;
case 1: return 150;
case 2: return 500;
case 3: return 900;
case 4: return 1200;
case 5: return 1500;
case 6: return 2000;
case 7: return 3000;
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
static_assert(DecodeInputCurrentLimit(EncodeInputCurrentLimit(100)) == 100);
static_assert(DecodeInputCurrentLimit(EncodeInputCurrentLimit(150)) == 150);
static_assert(DecodeInputCurrentLimit(EncodeInputCurrentLimit(500)) == 500);
static_assert(DecodeInputCurrentLimit(EncodeInputCurrentLimit(900)) == 900);
static_assert(DecodeInputCurrentLimit(EncodeInputCurrentLimit(1200)) == 1200);
static_assert(DecodeInputCurrentLimit(EncodeInputCurrentLimit(1500)) == 1500);
static_assert(DecodeInputCurrentLimit(EncodeInputCurrentLimit(2000)) == 2000);
static_assert(DecodeInputCurrentLimit(EncodeInputCurrentLimit(3000)) == 3000);
static_assert(DecodeInputCurrentLimit(EncodeInputCurrentLimit(0)) == 100);
static_assert(DecodeInputCurrentLimit(EncodeInputCurrentLimit(9999)) == 3000);
static_assert(DecodeInputCurrentLimit(EncodeInputCurrentLimit(149)) == 100);
static_assert(DecodeInputCurrentLimit(EncodeInputCurrentLimit(151)) == 150);
constexpr u8 EncodeInputVoltageLimit(int mv) {
constexpr int Minimum = 3880;
constexpr int Maximum = 5080;
mv = std::max(std::min(mv, Maximum), Minimum);
return static_cast<u8>(((static_cast<u32>(mv - Minimum) / 80) & 0xF) << 3);
}
constexpr u8 EncodeBoostModeCurrentLimit(int ma) {
return ma >= 1300 ? 1 : 0;
}
constexpr bq24193::ChargerStatus DecodeChargerStatus(u8 reg) {
switch (reg & 0x30) {
case 0x00: return bq24193::ChargerStatus_NotCharging;
case 0x10: return bq24193::ChargerStatus_PreCharge;
case 0x20: return bq24193::ChargerStatus_FastCharging;
case 0x30: return bq24193::ChargerStatus_ChargeTerminationDone;
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
}
namespace {
ALWAYS_INLINE Result ReadWriteRegister(const i2c::I2cSession &session, u8 address, u8 mask, u8 value) {
/* Read the current value. */
u8 cur_val;
R_TRY(i2c::ReadSingleRegister(session, address, std::addressof(cur_val)));
/* Update the value. */
const u8 new_val = (cur_val & ~mask) | (value & mask);
R_TRY(i2c::WriteSingleRegister(session, address, new_val));
R_SUCCEED();
}
}
Result Bq24193Driver::InitializeSession() {
/* Set fast charge current limit. */
R_TRY(this->SetFastChargeCurrentLimit(512));
/* Disable force 20 percent charge. */
R_TRY(this->SetForce20PercentChargeCurrent(false));
/* Set pre-charge current limit. */
R_TRY(this->SetPreChargeCurrentLimit(128));
/* Set termination current limit. */
R_TRY(this->SetTerminationCurrentLimit(128));
/* Set minimum system voltage limit. */
R_TRY(this->SetMinimumSystemVoltageLimit(3000));
/* Set watchdog timer setting. */
R_TRY(this->SetWatchdogTimerSetting(0));
/* Disable charging safety timer. */
R_TRY(this->SetChargingSafetyTimerEnabled(false));
/* Reset the watchdog timer. */
R_TRY(this->ResetWatchdogTimer());
R_SUCCEED();
}
Result Bq24193Driver::SetPreChargeCurrentLimit(int ma) {
R_RETURN(ReadWriteRegister(m_i2c_session, bq24193::PreChargeTerminationCurrentControl, 0xF0, bq24193::EncodePreChargeCurrentLimit(ma)));
}
Result Bq24193Driver::SetTerminationCurrentLimit(int ma) {
R_RETURN(ReadWriteRegister(m_i2c_session, bq24193::PreChargeTerminationCurrentControl, 0x0F, bq24193::EncodeTerminationCurrentLimit(ma)));
}
Result Bq24193Driver::SetMinimumSystemVoltageLimit(int mv) {
R_RETURN(ReadWriteRegister(m_i2c_session, bq24193::PowerOnConfiguration, 0x0E, bq24193::EncodeMinimumSystemVoltageLimit(mv)));
}
Result Bq24193Driver::SetChargingSafetyTimerEnabled(bool en) {
R_RETURN(ReadWriteRegister(m_i2c_session, bq24193::ChargeTerminationTimerControl, 0x08, en ? 0x08 : 0x00));
}
Result Bq24193Driver::GetForce20PercentChargeCurrent(bool *out) {
/* Get the register. */
u8 val;
R_TRY(i2c::ReadSingleRegister(m_i2c_session, bq24193::ChargeCurrentControl, std::addressof(val)));
/* Extract the value. */
*out = (val & 0x01) != 0;
R_SUCCEED();
}
Result Bq24193Driver::SetForce20PercentChargeCurrent(bool en) {
R_RETURN(ReadWriteRegister(m_i2c_session, bq24193::ChargeCurrentControl, 0x01, en ? 0x01 : 0x00));
}
Result Bq24193Driver::GetFastChargeCurrentLimit(int *out_ma) {
/* Get the register. */
u8 val;
R_TRY(i2c::ReadSingleRegister(m_i2c_session, bq24193::ChargeCurrentControl, std::addressof(val)));
/* Extract the value. */
*out_ma = bq24193::DecodeFastChargeCurrentLimit(val);
R_SUCCEED();
}
Result Bq24193Driver::SetFastChargeCurrentLimit(int ma) {
R_RETURN(ReadWriteRegister(m_i2c_session, bq24193::ChargeCurrentControl, 0xFC, bq24193::EncodeFastChargeCurrentLimit(ma)));
}
Result Bq24193Driver::GetChargeVoltageLimit(int *out_mv) {
/* Get the register. */
u8 val;
R_TRY(i2c::ReadSingleRegister(m_i2c_session, bq24193::ChargeVoltageControl, std::addressof(val)));
/* Extract the value. */
*out_mv = bq24193::DecodeChargeVoltageLimit(val);
R_SUCCEED();
}
Result Bq24193Driver::SetChargeVoltageLimit(int mv) {
R_RETURN(ReadWriteRegister(m_i2c_session, bq24193::ChargeVoltageControl, 0xFC, bq24193::EncodeChargeVoltageLimit(mv)));
}
Result Bq24193Driver::SetChargerConfiguration(bq24193::ChargerConfiguration cfg) {
R_RETURN(ReadWriteRegister(m_i2c_session, bq24193::PowerOnConfiguration, 0x30, bq24193::EncodeChargerConfiguration(cfg)));
}
Result Bq24193Driver::IsHiZEnabled(bool *out) {
/* Get the register. */
u8 val;
R_TRY(i2c::ReadSingleRegister(m_i2c_session, bq24193::InputSourceControl, std::addressof(val)));
/* Extract the value. */
*out = (val & 0x80) != 0;
R_SUCCEED();
}
Result Bq24193Driver::SetHiZEnabled(bool en) {
R_RETURN(ReadWriteRegister(m_i2c_session, bq24193::InputSourceControl, 0x80, en ? 0x80 : 0x00));
}
Result Bq24193Driver::GetInputCurrentLimit(int *out_ma) {
/* Get the register. */
u8 val;
R_TRY(i2c::ReadSingleRegister(m_i2c_session, bq24193::InputSourceControl, std::addressof(val)));
/* Extract the value. */
*out_ma = bq24193::DecodeInputCurrentLimit(val);
R_SUCCEED();
}
Result Bq24193Driver::SetInputCurrentLimit(int ma) {
R_RETURN(ReadWriteRegister(m_i2c_session, bq24193::InputSourceControl, 0x07, bq24193::EncodeInputCurrentLimit(ma)));
}
Result Bq24193Driver::SetInputVoltageLimit(int mv) {
R_RETURN(ReadWriteRegister(m_i2c_session, bq24193::InputSourceControl, 0x78, bq24193::EncodeInputVoltageLimit(mv)));
}
Result Bq24193Driver::SetBoostModeCurrentLimit(int ma) {
R_RETURN(ReadWriteRegister(m_i2c_session, bq24193::PowerOnConfiguration, 0x01, bq24193::EncodeBoostModeCurrentLimit(ma)));
}
Result Bq24193Driver::GetChargerStatus(bq24193::ChargerStatus *out) {
/* Get the register. */
u8 val;
R_TRY(i2c::ReadSingleRegister(m_i2c_session, bq24193::SystemStatus, std::addressof(val)));
/* Extract the value. */
*out = bq24193::DecodeChargerStatus(val);
R_SUCCEED();
}
Result Bq24193Driver::ResetWatchdogTimer() {
R_RETURN(ReadWriteRegister(m_i2c_session, bq24193::PowerOnConfiguration, 0x40, 0x40));
}
Result Bq24193Driver::SetWatchdogTimerSetting(int seconds) {
R_RETURN(ReadWriteRegister(m_i2c_session, bq24193::ChargeTerminationTimerControl, 0x30, bq24193::EncodeWatchdogTimerSetting(seconds)));
}
Result Bq24193Driver::GetBatteryCompensation(int *out_mo) {
/* Get the register. */
u8 val;
R_TRY(i2c::ReadSingleRegister(m_i2c_session, bq24193::IrCompensationThermalRegulationControl, std::addressof(val)));
/* Extract the value. */
*out_mo = bq24193::DecodeBatteryCompensation(val);
R_SUCCEED();
}
Result Bq24193Driver::SetBatteryCompensation(int mo) {
R_RETURN(ReadWriteRegister(m_i2c_session, bq24193::IrCompensationThermalRegulationControl, 0xE0, bq24193::EncodeBatteryCompensation(mo)));
}
Result Bq24193Driver::GetVoltageClamp(int *out_mv) {
/* Get the register. */
u8 val;
R_TRY(i2c::ReadSingleRegister(m_i2c_session, bq24193::IrCompensationThermalRegulationControl, std::addressof(val)));
/* Extract the value. */
*out_mv = bq24193::DecodeVoltageClamp(val);
R_SUCCEED();
}
Result Bq24193Driver::SetVoltageClamp(int mv) {
R_RETURN(ReadWriteRegister(m_i2c_session, bq24193::IrCompensationThermalRegulationControl, 0x1C, bq24193::EncodeVoltageClamp(mv)));
}
}
| 16,283
|
C++
|
.cpp
| 326
| 40.184049
| 146
| 0.639319
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,431
|
powctl_board_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/powctl/impl/board/nintendo/nx/powctl_board_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 "../../../powctl_device_management.hpp"
#include "powctl_board_impl.hpp"
#include "powctl_battery_driver.hpp"
#include "powctl_charger_driver.hpp"
namespace ams::powctl::impl::board::nintendo::nx {
namespace {
constinit util::optional<ChargerDriver> g_charger_driver;
constinit util::optional<BatteryDriver> g_battery_driver;
void InitializeChargerDriver(bool use_event_handlers) {
/* Create the charger driver. */
g_charger_driver.emplace(use_event_handlers);
/* Register the driver. */
powctl::impl::RegisterDriver(std::addressof(*g_charger_driver));
}
void InitializeBatteryDriver(bool use_event_handlers) {
/* Create the battery driver. */
g_battery_driver.emplace(use_event_handlers);
/* Register the driver. */
powctl::impl::RegisterDriver(std::addressof(*g_battery_driver));
}
void FinalizeChargerDriver() {
/* Unregister the driver. */
powctl::impl::UnregisterDriver(std::addressof(*g_charger_driver));
/* Destroy the battery driver. */
g_charger_driver = util::nullopt;
}
void FinalizeBatteryDriver() {
/* Unregister the driver. */
powctl::impl::UnregisterDriver(std::addressof(*g_battery_driver));
/* Destroy the battery driver. */
g_battery_driver = util::nullopt;
}
}
void Initialize(bool use_event_handlers) {
InitializeChargerDriver(use_event_handlers);
InitializeBatteryDriver(use_event_handlers);
}
void Finalize() {
FinalizeBatteryDriver();
FinalizeChargerDriver();
}
}
| 2,401
|
C++
|
.cpp
| 58
| 34.258621
| 78
| 0.664663
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,432
|
powctl_charger_driver.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/powctl/impl/board/nintendo/nx/powctl_charger_driver.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 "../../../powctl_device_management.hpp"
#include "powctl_retry_helper.hpp"
#include "powctl_charger_driver.hpp"
#include "powctl_bq24193_driver.hpp"
namespace ams::powctl::impl::board::nintendo::nx {
namespace {
constinit util::optional<ChargerDevice> g_charger_device;
constinit Bq24193Driver g_bq24193_driver;
ALWAYS_INLINE Bq24193Driver &GetBq24193Driver() {
return g_bq24193_driver;
}
}
ChargerDevice::ChargerDevice(bool ev) : m_gpio_pad_session(), m_watchdog_timer_enabled(false), m_watchdog_timer_timeout(0), m_use_event_handler(ev), m_event_handler() {
if (m_use_event_handler) {
/* Create the system event. */
os::CreateSystemEvent(std::addressof(m_system_event), os::EventClearMode_ManualClear, true);
/* Create the handler. */
m_event_handler.emplace(this);
/* Register the event handler. */
powctl::impl::RegisterInterruptHandler(std::addressof(*m_event_handler));
}
}
/* Generic API. */
void ChargerDriver::InitializeDriver() {
/* Initialize Bq24193Driver */
GetBq24193Driver().Initialize();
/* Initialize gpio library. */
gpio::Initialize();
/* Create charger device. */
g_charger_device.emplace(this->IsEventHandlerEnabled());
/* Open the device's gpio session. */
R_ABORT_UNLESS(gpio::OpenSession(g_charger_device->GetPadSession(), gpio::DeviceCode_BattChgEnableN));
/* Configure the gpio session as output. */
gpio::SetDirection(g_charger_device->GetPadSession(), gpio::Direction_Output);
/* Register our device. */
this->RegisterDevice(std::addressof(*g_charger_device));
/* Register the charger device's code. */
R_ABORT_UNLESS(powctl::impl::RegisterDeviceCode(powctl::DeviceCode_Bq24193, std::addressof(*g_charger_device)));
}
void ChargerDriver::FinalizeDriver() {
/* Unregister the charger device code. */
powctl::impl::UnregisterDeviceCode(powctl::DeviceCode_Bq24193);
/* Unregister our device. */
this->UnregisterDevice(std::addressof(*g_charger_device));
/* Close the device's gpio session. */
gpio::CloseSession(g_charger_device->GetPadSession());
/* Destroy the charger device. */
g_charger_device = util::nullopt;
/* Finalize gpio library. */
gpio::Finalize();
/* Finalize Bq24193Driver. */
GetBq24193Driver().Finalize();
}
Result ChargerDriver::GetDeviceSystemEvent(os::SystemEventType **out, IDevice *device) {
/* Validate arguments. */
R_UNLESS(out != nullptr, powctl::ResultInvalidArgument());
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
/* Check that we support event handlers. */
R_UNLESS(this->IsEventHandlerEnabled(), powctl::ResultNotAvailable());
*out = device->SafeCastTo<ChargerDevice>().GetSystemEvent();
R_SUCCEED();
}
Result ChargerDriver::SetDeviceInterruptEnabled(IDevice *device, bool enable) {
/* Validate arguments. */
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
/* Set the interrupt enable. */
device->SafeCastTo<ChargerDevice>().SetInterruptEnabled(enable);
R_SUCCEED();
}
Result ChargerDriver::GetDeviceErrorStatus(u32 *out, IDevice *device) {
/* TODO */
AMS_UNUSED(out, device);
AMS_ABORT();
}
Result ChargerDriver::SetDeviceErrorStatus(IDevice *device, u32 status) {
/* TODO */
AMS_UNUSED(device, status);
AMS_ABORT();
}
/* Charger API. */
Result ChargerDriver::GetChargerChargeCurrentState(ChargeCurrentState *out, IDevice *device) {
/* Validate arguments. */
R_UNLESS(out != nullptr, powctl::ResultInvalidArgument());
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
/* NOTE: Nintendo doesn't hold the mutex while doing the gpio:: call here, for some reason. */
/* Check if we're not charging. */
if (gpio::GetValue(device->SafeCastTo<ChargerDevice>().GetPadSession()) == gpio::GpioValue_High) {
*out = ChargeCurrentState_NotCharging;
} else {
/* Get force 20 percent charge state. */
bool force_20_percent = false;
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetBq24193Driver().GetForce20PercentChargeCurrent(std::addressof(force_20_percent)));
/* Set output appropriately. */
if (force_20_percent) {
*out = ChargeCurrentState_ChargingForce20Percent;
} else {
*out = ChargeCurrentState_Charging;
}
}
R_SUCCEED();
}
Result ChargerDriver::SetChargerChargeCurrentState(IDevice *device, ChargeCurrentState state) {
/* Validate arguments. */
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
std::scoped_lock lk(this->GetMutex());
switch (state) {
case ChargeCurrentState_NotCharging:
gpio::SetValue(device->SafeCastTo<ChargerDevice>().GetPadSession(), gpio::GpioValue_High);
break;
case ChargeCurrentState_ChargingForce20Percent:
case ChargeCurrentState_Charging:
gpio::SetValue(device->SafeCastTo<ChargerDevice>().GetPadSession(), gpio::GpioValue_Low);
AMS_POWCTL_DRIVER_R_TRY_WITH_RETRY(GetBq24193Driver().SetForce20PercentChargeCurrent(state == ChargeCurrentState_ChargingForce20Percent));
break;
case ChargeCurrentState_Unknown:
R_THROW(powctl::ResultInvalidArgument());
}
R_SUCCEED();
}
Result ChargerDriver::GetChargerFastChargeCurrentLimit(int *out_ma, IDevice *device) {
/* Validate arguments. */
R_UNLESS(out_ma != nullptr, powctl::ResultInvalidArgument());
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetBq24193Driver().GetFastChargeCurrentLimit(out_ma));
R_SUCCEED();
}
Result ChargerDriver::SetChargerFastChargeCurrentLimit(IDevice *device, int ma) {
/* Validate arguments. */
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetBq24193Driver().SetFastChargeCurrentLimit(ma));
R_SUCCEED();
}
Result ChargerDriver::GetChargerChargeVoltageLimit(int *out_mv, IDevice *device) {
/* Validate arguments. */
R_UNLESS(out_mv != nullptr, powctl::ResultInvalidArgument());
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetBq24193Driver().GetChargeVoltageLimit(out_mv));
R_SUCCEED();
}
Result ChargerDriver::SetChargerChargeVoltageLimit(IDevice *device, int mv) {
/* Validate arguments. */
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetBq24193Driver().SetChargeVoltageLimit(mv));
R_SUCCEED();
}
Result ChargerDriver::SetChargerChargerConfiguration(IDevice *device, ChargerConfiguration cfg) {
/* Validate arguments. */
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
bq24193::ChargerConfiguration bq_cfg;
switch (cfg) {
case ChargerConfiguration_ChargeDisable: bq_cfg = bq24193::ChargerConfiguration_ChargeDisable; break;
case ChargerConfiguration_ChargeBattery: bq_cfg = bq24193::ChargerConfiguration_ChargeBattery; break;
case ChargerConfiguration_Otg: bq_cfg = bq24193::ChargerConfiguration_Otg; break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetBq24193Driver().SetChargerConfiguration(bq_cfg));
R_SUCCEED();
}
Result ChargerDriver::IsChargerHiZEnabled(bool *out, IDevice *device) {
/* Validate arguments. */
R_UNLESS(out != nullptr, powctl::ResultInvalidArgument());
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetBq24193Driver().IsHiZEnabled(out));
R_SUCCEED();
}
Result ChargerDriver::SetChargerHiZEnabled(IDevice *device, bool en) {
/* Validate arguments. */
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetBq24193Driver().SetHiZEnabled(en));
R_SUCCEED();
}
Result ChargerDriver::GetChargerInputCurrentLimit(int *out_ma, IDevice *device) {
/* Validate arguments. */
R_UNLESS(out_ma != nullptr, powctl::ResultInvalidArgument());
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetBq24193Driver().GetInputCurrentLimit(out_ma));
R_SUCCEED();
}
Result ChargerDriver::SetChargerInputCurrentLimit(IDevice *device, int ma) {
/* Validate arguments. */
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetBq24193Driver().SetInputCurrentLimit(ma));
R_SUCCEED();
}
Result ChargerDriver::SetChargerInputVoltageLimit(IDevice *device, int mv) {
/* Validate arguments. */
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetBq24193Driver().SetInputVoltageLimit(mv));
R_SUCCEED();
}
Result ChargerDriver::SetChargerBoostModeCurrentLimit(IDevice *device, int ma) {
/* Validate arguments. */
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetBq24193Driver().SetBoostModeCurrentLimit(ma));
R_SUCCEED();
}
Result ChargerDriver::GetChargerChargerStatus(ChargerStatus *out, IDevice *device) {
/* Validate arguments. */
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
bq24193::ChargerStatus bq_status = static_cast<bq24193::ChargerStatus>(~0);
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetBq24193Driver().GetChargerStatus(std::addressof(bq_status)));
switch (bq_status) {
case bq24193::ChargerStatus_NotCharging:
*out = ChargerStatus_NotCharging;
break;
case bq24193::ChargerStatus_PreCharge:
case bq24193::ChargerStatus_FastCharging:
*out = ChargerStatus_Charging;
break;
case bq24193::ChargerStatus_ChargeTerminationDone:
*out = ChargerStatus_ChargeTerminationDone;
break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
R_SUCCEED();
}
Result ChargerDriver::IsChargerWatchdogTimerEnabled(bool *out, IDevice *device) {
/* Validate arguments. */
R_UNLESS(out != nullptr, powctl::ResultInvalidArgument());
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
*out = device->SafeCastTo<ChargerDevice>().IsWatchdogTimerEnabled();
R_SUCCEED();
}
Result ChargerDriver::SetChargerWatchdogTimerEnabled(IDevice *device, bool en) {
/* Validate arguments. */
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
auto &charger_device = device->SafeCastTo<ChargerDevice>();
if (en) {
std::scoped_lock lk(this->GetMutex());
AMS_POWCTL_DRIVER_R_TRY_WITH_RETRY(GetBq24193Driver().ResetWatchdogTimer());
AMS_POWCTL_DRIVER_R_TRY_WITH_RETRY(GetBq24193Driver().SetWatchdogTimerSetting(charger_device.GetWatchdogTimerTimeout().GetSeconds()));
} else {
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetBq24193Driver().SetWatchdogTimerSetting(0));
}
charger_device.SetWatchdogTimerEnabled(en);
R_SUCCEED();
}
Result ChargerDriver::SetChargerWatchdogTimerTimeout(IDevice *device, TimeSpan timeout) {
/* Validate arguments. */
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
device->SafeCastTo<ChargerDevice>().SetWatchdogTimerTimeout(timeout);
R_SUCCEED();
}
Result ChargerDriver::ResetChargerWatchdogTimer(IDevice *device) {
/* Validate arguments. */
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetBq24193Driver().ResetWatchdogTimer());
R_SUCCEED();
}
Result ChargerDriver::GetChargerBatteryCompensation(int *out_mo, IDevice *device) {
/* Validate arguments. */
R_UNLESS(out_mo != nullptr, powctl::ResultInvalidArgument());
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetBq24193Driver().GetBatteryCompensation(out_mo));
R_SUCCEED();
}
Result ChargerDriver::SetChargerBatteryCompensation(IDevice *device, int mo) {
/* Validate arguments. */
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetBq24193Driver().SetBatteryCompensation(mo));
R_SUCCEED();
}
Result ChargerDriver::GetChargerVoltageClamp(int *out_mv, IDevice *device) {
/* Validate arguments. */
R_UNLESS(out_mv != nullptr, powctl::ResultInvalidArgument());
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetBq24193Driver().GetVoltageClamp(out_mv));
R_SUCCEED();
}
Result ChargerDriver::SetChargerVoltageClamp(IDevice *device, int mv) {
/* Validate arguments. */
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetBq24193Driver().SetVoltageClamp(mv));
R_SUCCEED();
}
}
| 14,783
|
C++
|
.cpp
| 292
| 41.921233
| 172
| 0.667037
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,433
|
powctl_max17050_driver.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/powctl/impl/board/nintendo/nx/powctl_max17050_driver.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 "powctl_max17050_driver.hpp"
namespace ams::powctl::impl::board::nintendo::nx {
namespace max17050 {
constexpr inline u8 Status = 0x00;
constexpr inline u8 VAlrtThreshold = 0x01;
constexpr inline u8 TAlrtThreshold = 0x02;
constexpr inline u8 SocAlrtThreshold = 0x03;
constexpr inline u8 AtRate = 0x04;
constexpr inline u8 RemCapRep = 0x05;
constexpr inline u8 SocRep = 0x06;
constexpr inline u8 Age = 0x07;
constexpr inline u8 Temperature = 0x08;
constexpr inline u8 VCell = 0x09;
constexpr inline u8 Current = 0x0A;
constexpr inline u8 AverageCurrent = 0x0B;
constexpr inline u8 SocMix = 0x0D;
constexpr inline u8 SocAv = 0x0E;
constexpr inline u8 RemCapMix = 0x0F;
constexpr inline u8 FullCap = 0x10;
constexpr inline u8 Tte = 0x11;
constexpr inline u8 QResidual00 = 0x12;
constexpr inline u8 FullSocThr = 0x13;
constexpr inline u8 AverageTemp = 0x16;
constexpr inline u8 Cycles = 0x17;
constexpr inline u8 DesignCap = 0x18;
constexpr inline u8 AverageVCell = 0x19;
constexpr inline u8 MaxMinTemp = 0x1A;
constexpr inline u8 MaxMinVoltage = 0x1B;
constexpr inline u8 MaxMinCurrent = 0x1C;
constexpr inline u8 Config = 0x1D;
constexpr inline u8 IChgTerm = 0x1E;
constexpr inline u8 RemCapAv = 0x1F;
constexpr inline u8 Version = 0x21;
constexpr inline u8 QResidual10 = 0x22;
constexpr inline u8 FullCapNom = 0x23;
constexpr inline u8 TempNom = 0x24;
constexpr inline u8 TempLim = 0x25;
constexpr inline u8 Ain = 0x27;
constexpr inline u8 LearnCfg = 0x28;
constexpr inline u8 FilterCfg = 0x29;
constexpr inline u8 RelaxCfg = 0x2A;
constexpr inline u8 MiscCfg = 0x2B;
constexpr inline u8 TGain = 0x2C;
constexpr inline u8 TOff = 0x2D;
constexpr inline u8 CGain = 0x2E;
constexpr inline u8 COff = 0x2F;
constexpr inline u8 QResidual20 = 0x32;
constexpr inline u8 FullCap0 = 0x35;
constexpr inline u8 IAvgEmpty = 0x36;
constexpr inline u8 FCtc = 0x37;
constexpr inline u8 RComp0 = 0x38;
constexpr inline u8 TempCo = 0x39;
constexpr inline u8 VEmpty = 0x3A;
constexpr inline u8 FStat = 0x3D;
constexpr inline u8 Timer = 0x3E;
constexpr inline u8 ShdnTimer = 0x3F;
constexpr inline u8 QResidual30 = 0x42;
constexpr inline u8 DQAcc = 0x45;
constexpr inline u8 DPAcc = 0x46;
constexpr inline u8 SocVf0 = 0x48;
constexpr inline u8 Qh0 = 0x4C;
constexpr inline u8 Qh = 0x4D;
constexpr inline u8 SocVfAccess = 0x60;
constexpr inline u8 ModelAccess0 = 0x62;
constexpr inline u8 ModelAccess1 = 0x63;
constexpr inline u8 ModelChrTblStart = 0x80;
constexpr inline u8 ModelChrTblEnd = 0xB0;
constexpr inline u8 VFocV = 0xFB;
constexpr inline u8 SocVf = 0xFF;
constexpr inline size_t ModelChrTblSize = ModelChrTblEnd - ModelChrTblStart;
namespace {
struct CustomParameters {
u16 relaxcfg;
u16 rcomp0;
u16 tempco;
u16 ichgterm;
u16 tgain;
u16 toff;
u16 vempty;
u16 qresidual00;
u16 qresidual10;
u16 qresidual20;
u16 qresidual30;
u16 fullcap;
u16 vffullcap;
u16 modeltbl[ModelChrTblSize];
u16 fullsocthr;
u16 iavgempty;
};
#include "powctl_max17050_custom_parameters.inc"
const CustomParameters &GetCustomParameters(const char *battery_vendor, u8 battery_version) {
if (battery_version == 2) {
if (battery_vendor[7] == 'M') {
return CustomParameters2M;
} else if (battery_vendor[7] == 'R') {
return CustomParameters2R;
} else /* if (battery_vendor[7] == 'A') */ {
return CustomParameters2A;
}
} else if (battery_version == 1) {
return CustomParameters1;
} else /* if (battery_version == 0) */ {
if (battery_vendor[7] == 'M') {
return CustomParameters0M;
} else if (battery_vendor[7] == 'R') {
return CustomParameters0R;
} else /* if (battery_vendor[7] == 'A') */ {
return CustomParameters0A;
}
}
}
}
}
namespace {
ALWAYS_INLINE Result ReadWriteRegister(const i2c::I2cSession &session, u8 address, u16 mask, u16 value) {
/* Read the current value. */
u16 cur_val;
R_TRY(i2c::ReadSingleRegister(session, address, std::addressof(cur_val)));
/* Update the value. */
const u16 new_val = (cur_val & ~mask) | (value & mask);
R_TRY(i2c::WriteSingleRegister(session, address, new_val));
R_SUCCEED();
}
ALWAYS_INLINE Result ReadRegister(const i2c::I2cSession &session, u8 address, u16 *out) {
R_RETURN(i2c::ReadSingleRegister(session, address, out));
}
ALWAYS_INLINE Result WriteRegister(const i2c::I2cSession &session, u8 address, u16 val) {
R_RETURN(i2c::WriteSingleRegister(session, address, val));
}
ALWAYS_INLINE bool WriteValidateRegister(const i2c::I2cSession &session, u8 address, u16 val) {
/* Write the value. */
R_ABORT_UNLESS(WriteRegister(session, address, val));
/* Give it time to take. */
os::SleepThread(TimeSpan::FromMilliSeconds(3));
/* Read it back. */
u16 new_val;
R_ABORT_UNLESS(ReadRegister(session, address, std::addressof(new_val)));
return new_val == val;
}
ALWAYS_INLINE Result ReadWriteValidateRegister(const i2c::I2cSession &session, u8 address, u16 mask, u16 value) {
/* Read the current value. */
u16 cur_val;
R_TRY(i2c::ReadSingleRegister(session, address, std::addressof(cur_val)));
/* Update the value. */
const u16 new_val = (cur_val & ~mask) | (value & mask);
while (!WriteValidateRegister(session, address, new_val)) { /* ... */ }
R_SUCCEED();
}
double CoerceToDouble(u64 value) {
static_assert(sizeof(value) == sizeof(double));
double d;
__builtin_memcpy(std::addressof(d), std::addressof(value), sizeof(d));
return d;
}
double ExponentiateTwoToPower(s16 exponent, double scale) {
if (exponent >= 1024) {
exponent = exponent - 1023;
scale = scale * 8.98846567e307;
if (exponent >= 1024) {
exponent = std::min<s16>(exponent, 2046) - 1023;
scale = scale * 8.98846567e307;
}
} else if (exponent <= -1023) {
exponent = exponent + 969;
scale = scale * 2.00416836e-292;
if (exponent <= -1023) {
exponent = std::max<s16>(exponent, -1991) + 969;
scale = scale * 2.00416836e-292;
}
}
return scale * CoerceToDouble(static_cast<u64>(exponent + 1023) << 52);
}
}
Result Max17050Driver::InitializeSession(const char *battery_vendor, u8 battery_version) {
/* Get the custom parameters. */
const auto ¶ms = max17050::GetCustomParameters(battery_vendor, battery_version);
/* We only want to write the parameters on power on reset. */
R_SUCCEED_IF(!this->IsPowerOnReset());
/* Set that we need to restore parameters. */
R_TRY(this->SetNeedToRestoreParameters(true));
/* Wait for our configuration to take. */
os::SleepThread(TimeSpan::FromMilliSeconds(500));
/* Write initial config. */
R_TRY(WriteRegister(m_i2c_session, max17050::Config, 0x7210));
/* Write initial filter config. */
R_TRY(WriteRegister(m_i2c_session, max17050::FilterCfg, 0x8784));
/* Write relax config. */
R_TRY(WriteRegister(m_i2c_session, max17050::RelaxCfg, params.relaxcfg));
/* Write initial learn config. */
R_TRY(WriteRegister(m_i2c_session, max17050::LearnCfg, 0x2603));
/* Write fullsocthr. */
R_TRY(WriteRegister(m_i2c_session, max17050::FullSocThr, params.fullsocthr));
/* Write iavgempty. */
R_TRY(WriteRegister(m_i2c_session, max17050::IAvgEmpty, params.iavgempty));
/* Unlock model table, write model table. */
do {
R_TRY(this->UnlockModelTable());
R_TRY(this->SetModelTable(params.modeltbl));
} while (!this->IsModelTableSet(params.modeltbl));
/* Lock the model table, trying up to ten times. */
{
size_t i = 0;
while (true) {
++i;
R_TRY(this->LockModelTable());
if (this->IsModelTableLocked()) {
break;
}
R_SUCCEED_IF(i >= 10);
}
}
/* Write and validate rcomp0 */
while (!WriteValidateRegister(m_i2c_session, max17050::RComp0, params.rcomp0)) { /* ... */ }
/* Write and validate tempco */
while (!WriteValidateRegister(m_i2c_session, max17050::TempCo, params.tempco)) { /* ... */ }
/* Write ichgterm. */
R_TRY(WriteRegister(m_i2c_session, max17050::IChgTerm, params.ichgterm));
/* Write tgain. */
R_TRY(WriteRegister(m_i2c_session, max17050::TGain, params.tgain));
/* Write toff. */
R_TRY(WriteRegister(m_i2c_session, max17050::TOff, params.toff));
/* Write and validate vempty. */
while (!WriteValidateRegister(m_i2c_session, max17050::VEmpty, params.vempty)) { /* ... */ }
/* Write and validate qresidual. */
while (!WriteValidateRegister(m_i2c_session, max17050::QResidual00, params.qresidual00)) { /* ... */ }
while (!WriteValidateRegister(m_i2c_session, max17050::QResidual10, params.qresidual10)) { /* ... */ }
while (!WriteValidateRegister(m_i2c_session, max17050::QResidual20, params.qresidual20)) { /* ... */ }
while (!WriteValidateRegister(m_i2c_session, max17050::QResidual30, params.qresidual30)) { /* ... */ }
/* Write capacity parameters. */
while (!WriteValidateRegister(m_i2c_session, max17050::FullCap, params.fullcap)) { /* ... */ }
R_TRY(WriteRegister(m_i2c_session, max17050::DesignCap, params.vffullcap));
while (!WriteValidateRegister(m_i2c_session, max17050::FullCapNom, params.vffullcap)) { /* ... */ }
/* Give some time for configuration to take. */
os::SleepThread(TimeSpan::FromMilliSeconds(350));
/* Write vfsoc to vfsoc0, qh, to qh0. */
u16 vfsoc, qh;
{
R_TRY(ReadRegister(m_i2c_session, max17050::SocVf, std::addressof(vfsoc)));
R_TRY(this->UnlockVoltageFuelGauge());
while (!WriteValidateRegister(m_i2c_session, max17050::SocVf0, vfsoc)) { /* ... */ }
R_TRY(ReadRegister(m_i2c_session, max17050::Qh, std::addressof(qh)));
R_TRY(WriteRegister(m_i2c_session, max17050::Qh0, qh));
R_TRY(this->LockVoltageFuelGauge());
}
/* Reset cycles. */
while (!WriteValidateRegister(m_i2c_session, max17050::Cycles, 0x0060)) { /* ... */ }
/* Load new capacity parameters. */
const u16 remcap = static_cast<u16>((vfsoc * params.vffullcap) / 0x6400);
const u16 repcap = static_cast<u16>(remcap * (params.fullcap / params.vffullcap));
const u16 dpacc = 0x0C80;
const u16 dqacc = params.vffullcap / 0x10;
while (!WriteValidateRegister(m_i2c_session, max17050::RemCapMix, remcap)) { /* ... */ }
while (!WriteValidateRegister(m_i2c_session, max17050::RemCapRep, repcap)) { /* ... */ }
while (!WriteValidateRegister(m_i2c_session, max17050::DPAcc, dpacc)) { /* ... */ }
while (!WriteValidateRegister(m_i2c_session, max17050::DQAcc, dqacc)) { /* ... */ }
/* Write capacity parameters. */
while (!WriteValidateRegister(m_i2c_session, max17050::FullCap, params.fullcap)) { /* ... */ }
R_TRY(WriteRegister(m_i2c_session, max17050::DesignCap, params.vffullcap));
while (!WriteValidateRegister(m_i2c_session, max17050::FullCapNom, params.vffullcap)) { /* ... */ }
/* Write soc rep. */
R_TRY(WriteRegister(m_i2c_session, max17050::SocRep, vfsoc));
/* Clear power on reset. */
R_TRY(ReadWriteValidateRegister(m_i2c_session, max17050::Status, 0x0002, 0x0000));
/* Set cgain. */
R_TRY(WriteRegister(m_i2c_session, max17050::CGain, 0x7FFF));
R_SUCCEED();
}
Result Max17050Driver::SetMaximumShutdownTimerThreshold() {
R_RETURN(WriteRegister(m_i2c_session, max17050::ShdnTimer, 0xE000));
}
Result Max17050Driver::SetAlertByChargePercentage() {
R_RETURN(ReadWriteRegister(m_i2c_session, max17050::MiscCfg, 0x0003, 0x0000));
}
Result Max17050Driver::SetAlertByVoltageFuelGaugePercentage() {
R_RETURN(ReadWriteRegister(m_i2c_session, max17050::MiscCfg, 0x0003, 0x0003));
}
bool Max17050Driver::IsPowerOnReset() {
/* Get the register. */
u16 val;
R_ABORT_UNLESS(ReadRegister(m_i2c_session, max17050::Status, std::addressof(val)));
/* Extract the value. */
return (val & 0x0002) != 0;
}
Result Max17050Driver::LockVoltageFuelGauge() {
R_RETURN(WriteRegister(m_i2c_session, max17050::SocVfAccess, 0x0000));
}
Result Max17050Driver::UnlockVoltageFuelGauge() {
R_RETURN(WriteRegister(m_i2c_session, max17050::SocVfAccess, 0x0080));
}
Result Max17050Driver::LockModelTable() {
R_TRY(WriteRegister(m_i2c_session, max17050::ModelAccess0, 0x0000));
R_TRY(WriteRegister(m_i2c_session, max17050::ModelAccess1, 0x0000));
R_SUCCEED();
}
Result Max17050Driver::UnlockModelTable() {
R_TRY(WriteRegister(m_i2c_session, max17050::ModelAccess0, 0x0059));
R_TRY(WriteRegister(m_i2c_session, max17050::ModelAccess1, 0x00C4));
R_SUCCEED();
}
bool Max17050Driver::IsModelTableLocked() {
for (size_t i = 0; i < max17050::ModelChrTblSize; ++i) {
u16 val;
R_ABORT_UNLESS(ReadRegister(m_i2c_session, max17050::ModelChrTblStart + i, std::addressof(val)));
if (val != 0) {
return false;
}
}
return true;
}
Result Max17050Driver::SetModelTable(const u16 *model_table) {
for (size_t i = 0; i < max17050::ModelChrTblSize; ++i) {
R_TRY(WriteRegister(m_i2c_session, max17050::ModelChrTblStart + i, model_table[i]));
}
R_SUCCEED();
}
bool Max17050Driver::IsModelTableSet(const u16 *model_table) {
for (size_t i = 0; i < max17050::ModelChrTblSize; ++i) {
u16 val;
R_ABORT_UNLESS(ReadRegister(m_i2c_session, max17050::ModelChrTblStart + i, std::addressof(val)));
if (val != model_table[i]) {
return false;
}
}
return true;
}
Result Max17050Driver::ReadInternalState() {
R_TRY(ReadRegister(m_i2c_session, max17050::RComp0, std::addressof(m_internal_state.rcomp0)));
R_TRY(ReadRegister(m_i2c_session, max17050::TempCo, std::addressof(m_internal_state.tempco)));
R_TRY(ReadRegister(m_i2c_session, max17050::FullCap, std::addressof(m_internal_state.fullcap)));
R_TRY(ReadRegister(m_i2c_session, max17050::Cycles, std::addressof(m_internal_state.cycles)));
R_TRY(ReadRegister(m_i2c_session, max17050::FullCapNom, std::addressof(m_internal_state.fullcapnom)));
R_TRY(ReadRegister(m_i2c_session, max17050::IAvgEmpty, std::addressof(m_internal_state.iavgempty)));
R_TRY(ReadRegister(m_i2c_session, max17050::QResidual00, std::addressof(m_internal_state.qresidual00)));
R_TRY(ReadRegister(m_i2c_session, max17050::QResidual10, std::addressof(m_internal_state.qresidual10)));
R_TRY(ReadRegister(m_i2c_session, max17050::QResidual20, std::addressof(m_internal_state.qresidual20)));
R_TRY(ReadRegister(m_i2c_session, max17050::QResidual30, std::addressof(m_internal_state.qresidual30)));
R_SUCCEED();
}
Result Max17050Driver::WriteInternalState() {
while (!WriteValidateRegister(m_i2c_session, max17050::RComp0, m_internal_state.rcomp0)) { /* ... */ }
while (!WriteValidateRegister(m_i2c_session, max17050::TempCo, m_internal_state.tempco)) { /* ... */ }
while (!WriteValidateRegister(m_i2c_session, max17050::FullCapNom, m_internal_state.fullcapnom)) { /* ... */ }
while (!WriteValidateRegister(m_i2c_session, max17050::IAvgEmpty, m_internal_state.iavgempty)) { /* ... */ }
while (!WriteValidateRegister(m_i2c_session, max17050::QResidual00, m_internal_state.qresidual00)) { /* ... */ }
while (!WriteValidateRegister(m_i2c_session, max17050::QResidual10, m_internal_state.qresidual10)) { /* ... */ }
while (!WriteValidateRegister(m_i2c_session, max17050::QResidual20, m_internal_state.qresidual20)) { /* ... */ }
while (!WriteValidateRegister(m_i2c_session, max17050::QResidual30, m_internal_state.qresidual30)) { /* ... */ }
os::SleepThread(TimeSpan::FromMilliSeconds(350));
u16 fullcap0, socmix;
R_TRY(ReadRegister(m_i2c_session, max17050::FullCap0, std::addressof(fullcap0)));
R_TRY(ReadRegister(m_i2c_session, max17050::SocMix, std::addressof(socmix)));
while (!WriteValidateRegister(m_i2c_session, max17050::RemCapMix, static_cast<u16>((fullcap0 * socmix) / 0x6400))) { /* ... */ }
while (!WriteValidateRegister(m_i2c_session, max17050::FullCap, m_internal_state.fullcap)) { /* ... */ }
while (!WriteValidateRegister(m_i2c_session, max17050::DPAcc, 0x0C80)) { /* ... */ }
while (!WriteValidateRegister(m_i2c_session, max17050::DQAcc, m_internal_state.fullcapnom / 0x10)) { /* ... */ }
os::SleepThread(TimeSpan::FromMilliSeconds(350));
while (!WriteValidateRegister(m_i2c_session, max17050::Cycles, m_internal_state.cycles)) { /* ... */ }
if (m_internal_state.cycles >= 0x100) {
while (!WriteValidateRegister(m_i2c_session, max17050::LearnCfg, 0x2673)) { /* ... */ }
}
R_SUCCEED();
}
Result Max17050Driver::GetChargePercentage(double *out) {
/* Validate parameters. */
AMS_ABORT_UNLESS(out != nullptr);
/* Read the value. */
u16 val;
R_TRY(ReadRegister(m_i2c_session, max17050::SocRep, std::addressof(val)));
/* Set output. */
*out = static_cast<double>(val) * 0.00390625;
R_SUCCEED();
}
Result Max17050Driver::GetVoltageFuelGaugePercentage(double *out) {
/* Validate parameters. */
AMS_ABORT_UNLESS(out != nullptr);
/* Read the value. */
u16 val;
R_TRY(ReadRegister(m_i2c_session, max17050::SocVf, std::addressof(val)));
/* Set output. */
*out = static_cast<double>(val) * 0.00390625;
R_SUCCEED();
}
Result Max17050Driver::GetFullCapacity(double *out, double sense_resistor) {
/* Validate parameters. */
AMS_ABORT_UNLESS(out != nullptr);
AMS_ABORT_UNLESS(sense_resistor > 0.0);
/* Read the values. */
u16 cgain, fullcap;
R_TRY(ReadRegister(m_i2c_session, max17050::CGain, std::addressof(cgain)));
R_TRY(ReadRegister(m_i2c_session, max17050::FullCap, std::addressof(fullcap)));
/* Set output. */
*out = ((static_cast<double>(fullcap) * 0.005) / sense_resistor) / (static_cast<double>(cgain) * 0.0000610351562);
R_SUCCEED();
}
Result Max17050Driver::GetRemainingCapacity(double *out, double sense_resistor) {
/* Validate parameters. */
AMS_ABORT_UNLESS(out != nullptr);
AMS_ABORT_UNLESS(sense_resistor > 0.0);
/* Read the values. */
u16 cgain, remcap;
R_TRY(ReadRegister(m_i2c_session, max17050::CGain, std::addressof(cgain)));
R_TRY(ReadRegister(m_i2c_session, max17050::RemCapRep, std::addressof(remcap)));
/* Set output. */
*out = ((static_cast<double>(remcap) * 0.005) / sense_resistor) / (static_cast<double>(cgain) * 0.0000610351562);
R_SUCCEED();
}
Result Max17050Driver::SetChargePercentageMinimumAlertThreshold(int percentage) {
R_TRY(this->SetAlertByChargePercentage());
R_RETURN(ReadWriteRegister(m_i2c_session, max17050::SocAlrtThreshold, 0x00FF, static_cast<u8>(percentage)));
}
Result Max17050Driver::SetChargePercentageMaximumAlertThreshold(int percentage) {
R_TRY(this->SetAlertByChargePercentage());
R_RETURN(ReadWriteRegister(m_i2c_session, max17050::SocAlrtThreshold, 0xFF00, static_cast<u16>(static_cast<u8>(percentage)) << 8));
}
Result Max17050Driver::SetVoltageFuelGaugePercentageMinimumAlertThreshold(int percentage) {
R_TRY(this->SetAlertByVoltageFuelGaugePercentage());
R_RETURN(ReadWriteRegister(m_i2c_session, max17050::SocAlrtThreshold, 0x00FF, static_cast<u8>(percentage)));
}
Result Max17050Driver::SetVoltageFuelGaugePercentageMaximumAlertThreshold(int percentage) {
R_TRY(this->SetAlertByVoltageFuelGaugePercentage());
R_RETURN(ReadWriteRegister(m_i2c_session, max17050::SocAlrtThreshold, 0xFF00, static_cast<u16>(static_cast<u8>(percentage)) << 8));
}
Result Max17050Driver::SetFullChargeThreshold(double percentage) {
/* Convert percentage from double to signed fixed-point with 8 fractional bits. */
const u16 val = static_cast<u16>(static_cast<s16>(percentage * (1 << 8)));
/* Set the threshold. */
R_RETURN(WriteRegister(m_i2c_session, max17050::FullSocThr, val));
}
Result Max17050Driver::GetAverageCurrent(double *out, double sense_resistor) {
/* Validate parameters. */
AMS_ABORT_UNLESS(out != nullptr);
AMS_ABORT_UNLESS(sense_resistor > 0.0);
/* Read the values. */
u16 cgain, coff, avg_current;
R_TRY(ReadRegister(m_i2c_session, max17050::CGain, std::addressof(cgain)));
R_TRY(ReadRegister(m_i2c_session, max17050::COff, std::addressof(coff)));
R_TRY(ReadRegister(m_i2c_session, max17050::AverageCurrent, std::addressof(avg_current)));
/* Set output. */
*out = (((static_cast<double>(avg_current) - (static_cast<double>(coff) + static_cast<double>(coff))) / (static_cast<double>(cgain) * 0.0000610351562)) * 1.5625) / (sense_resistor * 1000.0);
R_SUCCEED();
}
Result Max17050Driver::GetCurrent(double *out, double sense_resistor) {
/* Validate parameters. */
AMS_ABORT_UNLESS(out != nullptr);
AMS_ABORT_UNLESS(sense_resistor > 0.0);
/* Read the values. */
u16 cgain, coff, current;
R_TRY(ReadRegister(m_i2c_session, max17050::CGain, std::addressof(cgain)));
R_TRY(ReadRegister(m_i2c_session, max17050::COff, std::addressof(coff)));
R_TRY(ReadRegister(m_i2c_session, max17050::Current, std::addressof(current)));
/* Set output. */
*out = (((static_cast<double>(current) - (static_cast<double>(coff) + static_cast<double>(coff))) / (static_cast<double>(cgain) * 0.0000610351562)) * 1.5625) / (sense_resistor * 1000.0);
R_SUCCEED();
}
Result Max17050Driver::GetNeedToRestoreParameters(bool *out) {
/* Get the register. */
u16 val;
R_TRY(ReadRegister(m_i2c_session, max17050::MiscCfg, std::addressof(val)));
/* Extract the value. */
*out = (val & 0x8000) != 0;
R_SUCCEED();
}
Result Max17050Driver::SetNeedToRestoreParameters(bool en) {
R_RETURN(ReadWriteRegister(m_i2c_session, max17050::MiscCfg, 0x8000, en ? 0x8000 : 0));
}
Result Max17050Driver::IsI2cShutdownEnabled(bool *out) {
/* Get the register. */
u16 val;
R_TRY(ReadRegister(m_i2c_session, max17050::Config, std::addressof(val)));
/* Extract the value. */
*out = (val & 0x0040) != 0;
R_SUCCEED();
}
Result Max17050Driver::SetI2cShutdownEnabled(bool en) {
R_RETURN(ReadWriteRegister(m_i2c_session, max17050::Config, 0x0040, en ? 0x0040 : 0));
}
Result Max17050Driver::GetStatus(u16 *out) {
/* Validate parameters. */
AMS_ABORT_UNLESS(out != nullptr);
R_RETURN(ReadRegister(m_i2c_session, max17050::Status, out));
}
Result Max17050Driver::GetCycles(u16 *out) {
/* Get the register. */
u16 val;
R_TRY(ReadRegister(m_i2c_session, max17050::Cycles, std::addressof(val)));
/* Extract the value. */
*out = std::max<u16>(val, 0x60) - 0x60;
R_SUCCEED();
}
Result Max17050Driver::ResetCycles() {
R_RETURN(WriteRegister(m_i2c_session, max17050::Cycles, 0x0060));
}
Result Max17050Driver::GetAge(double *out) {
/* Validate parameters. */
AMS_ABORT_UNLESS(out != nullptr);
/* Read the value. */
u16 val;
R_TRY(ReadRegister(m_i2c_session, max17050::Age, std::addressof(val)));
/* Set output. */
*out = static_cast<double>(val) * 0.00390625;
R_SUCCEED();
}
Result Max17050Driver::GetTemperature(double *out) {
/* Validate parameters. */
AMS_ABORT_UNLESS(out != nullptr);
/* Read the value. */
u16 val;
R_TRY(ReadRegister(m_i2c_session, max17050::Temperature, std::addressof(val)));
/* Set output. */
*out = static_cast<double>(val) * 0.00390625;
R_SUCCEED();
}
Result Max17050Driver::GetMaximumTemperature(u8 *out) {
/* Validate parameters. */
AMS_ABORT_UNLESS(out != nullptr);
/* Read the value. */
u16 val;
R_TRY(ReadRegister(m_i2c_session, max17050::MaxMinTemp, std::addressof(val)));
/* Set output. */
*out = static_cast<u8>(val >> 8);
R_SUCCEED();
}
Result Max17050Driver::SetTemperatureMinimumAlertThreshold(int c) {
R_RETURN(ReadWriteRegister(m_i2c_session, max17050::TAlrtThreshold, 0x00FF, static_cast<u8>(c)));
}
Result Max17050Driver::SetTemperatureMaximumAlertThreshold(int c) {
R_RETURN(ReadWriteRegister(m_i2c_session, max17050::TAlrtThreshold, 0xFF00, static_cast<u16>(static_cast<u8>(c)) << 8));
}
Result Max17050Driver::GetVCell(int *out) {
/* Validate parameters. */
AMS_ABORT_UNLESS(out != nullptr);
/* Read the value. */
u16 val;
R_TRY(ReadRegister(m_i2c_session, max17050::VCell, std::addressof(val)));
/* Set output. */
*out = (625 * (val >> 3)) / 1000;
R_SUCCEED();
}
Result Max17050Driver::GetAverageVCell(int *out) {
/* Validate parameters. */
AMS_ABORT_UNLESS(out != nullptr);
/* Read the value. */
u16 val;
R_TRY(ReadRegister(m_i2c_session, max17050::AverageVCell, std::addressof(val)));
/* Set output. */
*out = (625 * (val >> 3)) / 1000;
R_SUCCEED();
}
Result Max17050Driver::GetAverageVCellTime(double *out) {
/* Validate parameters. */
AMS_ABORT_UNLESS(out != nullptr);
/* Read the value. */
u16 val;
R_TRY(ReadRegister(m_i2c_session, max17050::FilterCfg, std::addressof(val)));
/* Set output. */
*out = 175.8 * ExponentiateTwoToPower(6 + ((val >> 4) & 7), 1.0);
R_SUCCEED();
}
Result Max17050Driver::GetOpenCircuitVoltage(int *out) {
/* Validate parameters. */
AMS_ABORT_UNLESS(out != nullptr);
/* Read the value. */
u16 val;
R_TRY(ReadRegister(m_i2c_session, max17050::VFocV, std::addressof(val)));
/* Set output. */
*out = (1250 * (val >> 4)) / 1000;
R_SUCCEED();
}
Result Max17050Driver::SetVoltageMinimumAlertThreshold(int mv) {
R_RETURN(ReadWriteRegister(m_i2c_session, max17050::VAlrtThreshold, 0x00FF, static_cast<u8>(util::DivideUp(mv, 20))));
}
Result Max17050Driver::SetVoltageMaximumAlertThreshold(int mv) {
R_RETURN(ReadWriteRegister(m_i2c_session, max17050::VAlrtThreshold, 0xFF00, static_cast<u16>(static_cast<u8>(mv / 20)) << 8));
}
}
| 30,280
|
C++
|
.cpp
| 591
| 41.482234
| 198
| 0.607649
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,434
|
powctl_battery_driver.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/powctl/impl/board/nintendo/nx/powctl_battery_driver.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 "../../../powctl_device_management.hpp"
#include "powctl_retry_helper.hpp"
#include "powctl_battery_driver.hpp"
#include "powctl_max17050_driver.hpp"
namespace ams::powctl::impl::board::nintendo::nx {
namespace {
constinit util::optional<BatteryDevice> g_battery_device;
constinit Max17050Driver g_max17050_driver;
ALWAYS_INLINE Max17050Driver &GetMax17050Driver() {
return g_max17050_driver;
}
constexpr inline const double SenseResistorValue = 0.005;
}
BatteryDevice::BatteryDevice(bool ev) : m_use_event_handler(ev), m_event_handler() {
if (m_use_event_handler) {
/* Create the system event. */
os::CreateSystemEvent(std::addressof(m_system_event), os::EventClearMode_ManualClear, true);
/* Create the handler. */
m_event_handler.emplace(this);
/* Register the event handler. */
powctl::impl::RegisterInterruptHandler(std::addressof(*m_event_handler));
}
}
/* Generic API. */
void BatteryDriver::InitializeDriver() {
/* Initialize gpio library. */
gpio::Initialize();
/* Create battery device. */
g_battery_device.emplace(this->IsEventHandlerEnabled());
/* Initialize the Max17050Driver. */
{
size_t battery_vendor_size;
char battery_vendor[0x18] = {};
if (R_FAILED(cal::GetBatteryVendor(std::addressof(battery_vendor_size), battery_vendor, sizeof(battery_vendor)))) {
battery_vendor[7] = 'A';
battery_vendor_size = 0;
}
u8 battery_version = 0;
if (R_FAILED(cal::GetBatteryVersion(std::addressof(battery_version)))) {
battery_version = 0;
}
GetMax17050Driver().Initialize(battery_vendor, battery_version);
}
/* Register our device. */
this->RegisterDevice(std::addressof(*g_battery_device));
/* Register the charger device's code. */
R_ABORT_UNLESS(powctl::impl::RegisterDeviceCode(powctl::DeviceCode_Max17050, std::addressof(*g_battery_device)));
}
void BatteryDriver::FinalizeDriver() {
/* Unregister the charger device code. */
powctl::impl::UnregisterDeviceCode(powctl::DeviceCode_Max17050);
/* Unregister our device. */
this->UnregisterDevice(std::addressof(*g_battery_device));
/* Finalize Max17050Driver. */
GetMax17050Driver().Finalize();
/* Destroy the charger device. */
g_battery_device = util::nullopt;
/* Finalize gpio library. */
gpio::Finalize();
}
Result BatteryDriver::GetDeviceSystemEvent(os::SystemEventType **out, IDevice *device) {
/* Validate arguments. */
R_UNLESS(out != nullptr, powctl::ResultInvalidArgument());
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
/* Check that we support event handlers. */
R_UNLESS(this->IsEventHandlerEnabled(), powctl::ResultNotAvailable());
*out = device->SafeCastTo<BatteryDevice>().GetSystemEvent();
R_SUCCEED();
}
Result BatteryDriver::SetDeviceInterruptEnabled(IDevice *device, bool enable) {
/* Validate arguments. */
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
/* Set the interrupt enable. */
device->SafeCastTo<BatteryDevice>().SetInterruptEnabled(enable);
R_SUCCEED();
}
Result BatteryDriver::GetDeviceErrorStatus(u32 *out, IDevice *device) {
/* TODO */
AMS_UNUSED(out, device);
AMS_ABORT();
}
Result BatteryDriver::SetDeviceErrorStatus(IDevice *device, u32 status) {
/* TODO */
AMS_UNUSED(device, status);
AMS_ABORT();
}
Result BatteryDriver::GetBatteryChargePercentage(float *out_percent, IDevice *device) {
/* Validate arguments. */
R_UNLESS(out_percent != nullptr, powctl::ResultInvalidArgument());
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
/* Get the value. */
double percent{};
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetMax17050Driver().GetChargePercentage(std::addressof(percent)));
/* Set output. */
*out_percent = percent;
R_SUCCEED();
}
Result BatteryDriver::GetBatteryVoltageFuelGaugePercentage(float *out_percent, IDevice *device) {
/* Validate arguments. */
R_UNLESS(out_percent != nullptr, powctl::ResultInvalidArgument());
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
/* Get the value. */
double percent{};
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetMax17050Driver().GetVoltageFuelGaugePercentage(std::addressof(percent)));
/* Set output. */
*out_percent = percent;
R_SUCCEED();
}
Result BatteryDriver::GetBatteryFullCapacity(int *out_mah, IDevice *device) {
/* Validate arguments. */
R_UNLESS(out_mah != nullptr, powctl::ResultInvalidArgument());
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
/* Get the value. */
double mah{};
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetMax17050Driver().GetFullCapacity(std::addressof(mah), SenseResistorValue));
/* Set output. */
*out_mah = mah;
R_SUCCEED();
}
Result BatteryDriver::GetBatteryRemainingCapacity(int *out_mah, IDevice *device) {
/* Validate arguments. */
R_UNLESS(out_mah != nullptr, powctl::ResultInvalidArgument());
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
/* Get the value. */
double mah{};
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetMax17050Driver().GetRemainingCapacity(std::addressof(mah), SenseResistorValue));
/* Set output. */
*out_mah = mah;
R_SUCCEED();
}
Result BatteryDriver::SetBatteryChargePercentageMinimumAlertThreshold(IDevice *device, float percentage) {
/* Validate arguments. */
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetMax17050Driver().SetChargePercentageMinimumAlertThreshold(percentage));
R_SUCCEED();
}
Result BatteryDriver::SetBatteryChargePercentageMaximumAlertThreshold(IDevice *device, float percentage) {
/* Validate arguments. */
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetMax17050Driver().SetChargePercentageMaximumAlertThreshold(percentage));
R_SUCCEED();
}
Result BatteryDriver::SetBatteryVoltageFuelGaugePercentageMinimumAlertThreshold(IDevice *device, float percentage) {
/* Validate arguments. */
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetMax17050Driver().SetVoltageFuelGaugePercentageMinimumAlertThreshold(percentage));
R_SUCCEED();
}
Result BatteryDriver::SetBatteryVoltageFuelGaugePercentageMaximumAlertThreshold(IDevice *device, float percentage) {
/* Validate arguments. */
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetMax17050Driver().SetVoltageFuelGaugePercentageMaximumAlertThreshold(percentage));
R_SUCCEED();
}
Result BatteryDriver::SetBatteryFullChargeThreshold(IDevice *device, float percentage) {
/* Validate arguments. */
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetMax17050Driver().SetFullChargeThreshold(percentage));
R_SUCCEED();
}
Result BatteryDriver::GetBatteryAverageCurrent(int *out_ma, IDevice *device) {
/* Validate arguments. */
R_UNLESS(out_ma != nullptr, powctl::ResultInvalidArgument());
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
/* Get the value. */
double ma{};
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetMax17050Driver().GetAverageCurrent(std::addressof(ma), SenseResistorValue));
/* Set output. */
*out_ma = ma;
R_SUCCEED();
}
Result BatteryDriver::GetBatteryCurrent(int *out_ma, IDevice *device) {
/* Validate arguments. */
R_UNLESS(out_ma != nullptr, powctl::ResultInvalidArgument());
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
/* Get the value. */
double ma{};
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetMax17050Driver().GetCurrent(std::addressof(ma), SenseResistorValue));
/* Set output. */
*out_ma = ma;
R_SUCCEED();
}
Result BatteryDriver::GetBatteryInternalState(void *dst, size_t *out_size, IDevice *device, size_t dst_size) {
/* Validate arguments. */
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
R_UNLESS(dst != nullptr, powctl::ResultInvalidArgument());
R_UNLESS(out_size != nullptr, powctl::ResultInvalidArgument());
R_UNLESS(dst_size == sizeof(max17050::InternalState), powctl::ResultInvalidArgument());
R_UNLESS(util::IsAligned(reinterpret_cast<uintptr_t>(dst), alignof(max17050::InternalState)), powctl::ResultInvalidArgument());
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetMax17050Driver().ReadInternalState());
GetMax17050Driver().GetInternalState(static_cast<max17050::InternalState *>(dst));
R_SUCCEED();
}
Result BatteryDriver::SetBatteryInternalState(IDevice *device, const void *src, size_t src_size) {
/* Validate arguments. */
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
R_UNLESS(src != nullptr, powctl::ResultInvalidArgument());
R_UNLESS(src_size == sizeof(max17050::InternalState), powctl::ResultInvalidArgument());
R_UNLESS(util::IsAligned(reinterpret_cast<uintptr_t>(src), alignof(max17050::InternalState)), powctl::ResultInvalidArgument());
GetMax17050Driver().SetInternalState(*static_cast<const max17050::InternalState *>(src));
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetMax17050Driver().WriteInternalState());
R_SUCCEED();
}
Result BatteryDriver::GetBatteryNeedToRestoreParameters(bool *out, IDevice *device) {
/* Validate arguments. */
R_UNLESS(out != nullptr, powctl::ResultInvalidArgument());
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
/* Get the value. */
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetMax17050Driver().GetNeedToRestoreParameters(out));
R_SUCCEED();
}
Result BatteryDriver::SetBatteryNeedToRestoreParameters(IDevice *device, bool en) {
/* Validate arguments. */
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
/* Set the value. */
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetMax17050Driver().SetNeedToRestoreParameters(en));
R_SUCCEED();
}
Result BatteryDriver::IsBatteryI2cShutdownEnabled(bool *out, IDevice *device) {
/* Validate arguments. */
R_UNLESS(out != nullptr, powctl::ResultInvalidArgument());
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
/* Get the value. */
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetMax17050Driver().IsI2cShutdownEnabled(out));
R_SUCCEED();
}
Result BatteryDriver::SetBatteryI2cShutdownEnabled(IDevice *device, bool en) {
/* Validate arguments. */
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
/* Set the value. */
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetMax17050Driver().SetI2cShutdownEnabled(en));
R_SUCCEED();
}
Result BatteryDriver::IsBatteryPresent(bool *out, IDevice *device) {
/* Validate arguments. */
R_UNLESS(out != nullptr, powctl::ResultInvalidArgument());
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
/* Get the battery status. */
u16 status;
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetMax17050Driver().GetStatus(std::addressof(status)));
/* Set output. */
*out = (status & 0x0008) == 0;
R_SUCCEED();
}
Result BatteryDriver::GetBatteryCycles(int *out, IDevice *device) {
/* Validate arguments. */
R_UNLESS(out != nullptr, powctl::ResultInvalidArgument());
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
/* Get the battery cycles. */
u16 cycles{};
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetMax17050Driver().GetCycles(std::addressof(cycles)));
/* Set output. */
*out = cycles;
R_SUCCEED();
}
Result BatteryDriver::SetBatteryCycles(IDevice *device, int cycles) {
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
R_UNLESS(cycles == 0, powctl::ResultInvalidArgument());
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetMax17050Driver().ResetCycles());
R_SUCCEED();
}
Result BatteryDriver::GetBatteryAge(float *out_percent, IDevice *device) {
/* Validate arguments. */
R_UNLESS(out_percent != nullptr, powctl::ResultInvalidArgument());
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
/* Get the value. */
double percent{};
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetMax17050Driver().GetAge(std::addressof(percent)));
/* Set output. */
*out_percent = percent;
R_SUCCEED();
}
Result BatteryDriver::GetBatteryTemperature(float *out_c, IDevice *device) {
/* Validate arguments. */
R_UNLESS(out_c != nullptr, powctl::ResultInvalidArgument());
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
/* Get the value. */
double temp{};
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetMax17050Driver().GetTemperature(std::addressof(temp)));
/* Set output. */
*out_c = temp;
R_SUCCEED();
}
Result BatteryDriver::GetBatteryMaximumTemperature(float *out_c, IDevice *device) {
/* Validate arguments. */
R_UNLESS(out_c != nullptr, powctl::ResultInvalidArgument());
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
/* Get the value. */
u8 max_temp{};
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetMax17050Driver().GetMaximumTemperature(std::addressof(max_temp)));
/* Set output. */
*out_c = static_cast<float>(max_temp);
R_SUCCEED();
}
Result BatteryDriver::SetBatteryTemperatureMinimumAlertThreshold(IDevice *device, float c) {
/* Validate arguments. */
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetMax17050Driver().SetTemperatureMinimumAlertThreshold(c));
R_SUCCEED();
}
Result BatteryDriver::SetBatteryTemperatureMaximumAlertThreshold(IDevice *device, float c) {
/* Validate arguments. */
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetMax17050Driver().SetTemperatureMaximumAlertThreshold(c));
R_SUCCEED();
}
Result BatteryDriver::GetBatteryVCell(int *out_mv, IDevice *device) {
/* Validate arguments. */
R_UNLESS(out_mv != nullptr, powctl::ResultInvalidArgument());
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
/* Get the value. */
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetMax17050Driver().GetVCell(out_mv));
R_SUCCEED();
}
Result BatteryDriver::GetBatteryAverageVCell(int *out_mv, IDevice *device) {
/* Validate arguments. */
R_UNLESS(out_mv != nullptr, powctl::ResultInvalidArgument());
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
/* Get the value. */
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetMax17050Driver().GetAverageVCell(out_mv));
R_SUCCEED();
}
Result BatteryDriver::GetBatteryAverageVCellTime(TimeSpan *out, IDevice *device) {
/* Validate arguments. */
R_UNLESS(out != nullptr, powctl::ResultInvalidArgument());
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
/* Get the value. */
double ms{};
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetMax17050Driver().GetAverageVCellTime(std::addressof(ms)));
/* Set output. */
*out = TimeSpan::FromMicroSeconds(static_cast<s64>(ms * 1000.0));
R_SUCCEED();
}
Result BatteryDriver::SetBatteryVoltageMinimumAlertThreshold(IDevice *device, int mv) {
/* Validate arguments. */
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetMax17050Driver().SetVoltageMinimumAlertThreshold(mv));
R_SUCCEED();
}
Result BatteryDriver::GetBatteryOpenCircuitVoltage(int *out_mv, IDevice *device) {
/* Validate arguments. */
R_UNLESS(out_mv != nullptr, powctl::ResultInvalidArgument());
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
/* Get the value. */
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetMax17050Driver().GetOpenCircuitVoltage(out_mv));
R_SUCCEED();
}
Result BatteryDriver::SetBatteryVoltageMaximumAlertThreshold(IDevice *device, int mv) {
/* Validate arguments. */
R_UNLESS(device != nullptr, powctl::ResultInvalidArgument());
AMS_POWCTL_DRIVER_LOCKED_R_TRY_WITH_RETRY(GetMax17050Driver().SetVoltageMaximumAlertThreshold(mv));
R_SUCCEED();
}
}
| 19,001
|
C++
|
.cpp
| 370
| 43.081081
| 135
| 0.648709
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,435
|
powctl_charger_parameters.board.nintendo_nx.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/powctl/driver/impl/powctl_charger_parameters.board.nintendo_nx.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::powctl::driver::impl {
namespace {
constexpr inline const PowerState AcceptablePowerStates[] = {
PowerState::FullAwake,
PowerState::MinimumAwake,
PowerState::SleepCharge,
PowerState::SleepDischarge,
PowerState::ShutdownChargeMain,
};
constexpr inline const PowerState AcceptablePowerStatesForNotAwakeCharge[] = {
PowerState::SleepCharge,
PowerState::ShutdownChargeMain,
};
constexpr inline const int Max = std::numeric_limits<int>::max();
constexpr inline const int Min = std::numeric_limits<int>::min();
constexpr inline const float FloatMax = std::numeric_limits<float>::max();
constexpr inline const float FloatMin = -FloatMax;
constexpr inline const UnknownParameterX UnknownXTableForBatteryVersion2[] = {
{ 20000, 4320, 95.0, 100.4 },
{ 30000, 4304, 94.0, 99.7 },
{ 40000, 4288, 93.0, 98.4 },
{ 50000, 4272, 92.0, 97.0 },
{ 60000, 4256, 90.0, 95.7 },
{ 80000, 4240, 89.0, 94.2 },
{ 100000, 4224, 88.0, 93.0 },
{ Max, 4192, 85.0, 90.0 },
};
/* Include automatically extracted charger parameters. */
#include "powctl_charger_parameters.board.nintendo_nx.inc"
}
const ChargeParameters &GetChargeParameters() {
/* Get the battery version. */
u8 battery_version;
if (R_FAILED(cal::GetBatteryVersion(std::addressof(battery_version)))) {
battery_version = 0;
}
if (battery_version == 2) {
return ChargeParametersForBatteryVersion2;
} else if (battery_version == 1) {
return ChargeParametersForBatteryVersion1;
} else {
if (spl::GetHardwareType() == spl::HardwareType::Aula) {
return ChargeParametersForBatteryVersion0ForAula;
} else {
return ChargeParametersForBatteryVersion0;
}
}
}
}
| 2,749
|
C++
|
.cpp
| 65
| 33.830769
| 86
| 0.630004
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,436
|
mem_standard_allocator.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/mem/mem_standard_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 "impl/mem_impl_platform.hpp"
#include "impl/heap/mem_impl_heap_tls_heap_static.hpp"
#include "impl/heap/mem_impl_heap_tls_heap_cache.hpp"
#include "impl/heap/mem_impl_heap_tls_heap_central.hpp"
namespace ams::mem {
constexpr inline size_t DefaultAlignment = alignof(std::max_align_t);
constexpr inline size_t MinimumAllocatorSize = 16_KB;
namespace {
void ThreadDestroy(uintptr_t arg) {
if (arg) {
reinterpret_cast<impl::heap::TlsHeapCache *>(arg)->Finalize();
}
}
ALWAYS_INLINE impl::heap::CentralHeap *GetCentral(const impl::InternalCentralHeapStorage *storage) {
return reinterpret_cast<impl::heap::CentralHeap *>(const_cast<impl::InternalCentralHeapStorage *>(storage));
}
ALWAYS_INLINE impl::heap::CentralHeap *GetCentral(const impl::InternalCentralHeapStorage &storage) {
return GetCentral(std::addressof(storage));
}
ALWAYS_INLINE void GetCache(impl::heap::CentralHeap *central, os::TlsSlot slot) {
impl::heap::CachedHeap tmp_cache;
if (central->MakeCache(std::addressof(tmp_cache))) {
impl::heap::TlsHeapCache *cache = tmp_cache.Release();
os::SetTlsValue(slot, reinterpret_cast<uintptr_t>(cache));
}
}
struct InternalHash {
size_t allocated_count;
size_t allocated_size;
crypto::Sha1Generator sha1;
};
int InternalHashCallback(void *ptr, size_t size, void *user_data) {
InternalHash *hash = reinterpret_cast<InternalHash *>(user_data);
hash->sha1.Update(reinterpret_cast<void *>(std::addressof(ptr)), sizeof(ptr));
hash->sha1.Update(reinterpret_cast<void *>(std::addressof(size)), sizeof(size));
hash->allocated_count++;
hash->allocated_size += size;
return 1;
}
}
StandardAllocator::StandardAllocator() : m_initialized(false), m_enable_thread_cache(false), m_unused(0) {
static_assert(sizeof(impl::heap::CentralHeap) <= sizeof(m_central_heap_storage));
std::construct_at(GetCentral(m_central_heap_storage));
}
StandardAllocator::StandardAllocator(void *mem, size_t size) : StandardAllocator() {
this->Initialize(mem, size);
}
StandardAllocator::StandardAllocator(void *mem, size_t size, bool enable_cache) : StandardAllocator() {
this->Initialize(mem, size, enable_cache);
}
void StandardAllocator::Initialize(void *mem, size_t size) {
this->Initialize(mem, size, false);
}
void StandardAllocator::Initialize(void *mem, size_t size, bool enable_cache) {
AMS_ABORT_UNLESS(!m_initialized);
const uintptr_t aligned_start = util::AlignUp(reinterpret_cast<uintptr_t>(mem), impl::heap::TlsHeapStatic::PageSize);
const uintptr_t aligned_end = util::AlignDown(reinterpret_cast<uintptr_t>(mem) + size, impl::heap::TlsHeapStatic::PageSize);
const size_t aligned_size = aligned_end - aligned_start;
if (mem == nullptr) {
AMS_ABORT_UNLESS(os::IsVirtualAddressMemoryEnabled());
AMS_ABORT_UNLESS(GetCentral(m_central_heap_storage)->Initialize(nullptr, size, 0) == 0);
} else {
AMS_ABORT_UNLESS(aligned_start < aligned_end);
AMS_ABORT_UNLESS(aligned_size >= MinimumAllocatorSize);
AMS_ABORT_UNLESS(GetCentral(m_central_heap_storage)->Initialize(reinterpret_cast<void *>(aligned_start), aligned_size, 0) == 0);
}
m_enable_thread_cache = enable_cache;
if (m_enable_thread_cache) {
R_ABORT_UNLESS(os::AllocateTlsSlot(std::addressof(m_tls_slot), ThreadDestroy));
}
m_initialized = true;
}
void StandardAllocator::Finalize() {
AMS_ABORT_UNLESS(m_initialized);
if (m_enable_thread_cache) {
os::FreeTlsSlot(m_tls_slot);
}
GetCentral(m_central_heap_storage)->Finalize();
m_initialized = false;
}
void *StandardAllocator::Allocate(size_t size) {
AMS_ASSERT(m_initialized);
return this->Allocate(size, DefaultAlignment);
}
void *StandardAllocator::Allocate(size_t size, size_t alignment) {
AMS_ASSERT(m_initialized);
impl::heap::TlsHeapCache *heap_cache = nullptr;
if (m_enable_thread_cache) {
heap_cache = reinterpret_cast<impl::heap::TlsHeapCache *>(os::GetTlsValue(m_tls_slot));
if (!heap_cache) {
GetCache(GetCentral(m_central_heap_storage), m_tls_slot);
heap_cache = reinterpret_cast<impl::heap::TlsHeapCache *>(os::GetTlsValue(m_tls_slot));
}
}
void *ptr = nullptr;
if (heap_cache) {
ptr = heap_cache->Allocate(size, alignment);
if (ptr) {
return ptr;
}
impl::heap::CachedHeap cache;
cache.Reset(heap_cache);
cache.Query(impl::AllocQuery_FinalizeCache);
os::SetTlsValue(m_tls_slot, 0);
}
return GetCentral(m_central_heap_storage)->Allocate(size, alignment);
}
void StandardAllocator::Free(void *ptr) {
AMS_ASSERT(m_initialized);
if (ptr == nullptr) {
return;
}
if (m_enable_thread_cache) {
impl::heap::TlsHeapCache *heap_cache = reinterpret_cast<impl::heap::TlsHeapCache *>(os::GetTlsValue(m_tls_slot));
if (heap_cache) {
heap_cache->Free(ptr);
return;
}
}
const auto err = GetCentral(m_central_heap_storage)->Free(ptr);
AMS_ASSERT(err == 0);
AMS_UNUSED(err);
}
void *StandardAllocator::Reallocate(void *ptr, size_t new_size) {
AMS_ASSERT(m_initialized);
if (new_size > impl::MaxSize) {
return nullptr;
}
if (ptr == nullptr) {
return this->Allocate(new_size);
}
if (new_size == 0) {
this->Free(ptr);
return nullptr;
}
size_t aligned_new_size = util::AlignUp(new_size, DefaultAlignment);
impl::heap::TlsHeapCache *heap_cache = nullptr;
if (m_enable_thread_cache) {
heap_cache = reinterpret_cast<impl::heap::TlsHeapCache *>(os::GetTlsValue(m_tls_slot));
if (!heap_cache) {
GetCache(GetCentral(m_central_heap_storage), m_tls_slot);
heap_cache = reinterpret_cast<impl::heap::TlsHeapCache *>(os::GetTlsValue(m_tls_slot));
}
}
void *p = nullptr;
impl::errno_t err;
if (heap_cache) {
err = heap_cache->Reallocate(ptr, aligned_new_size, std::addressof(p));
} else {
err = GetCentral(m_central_heap_storage)->Reallocate(ptr, aligned_new_size, std::addressof(p));
}
if (err == 0) {
return p;
} else {
return nullptr;
}
}
size_t StandardAllocator::Shrink(void *ptr, size_t new_size) {
AMS_ASSERT(m_initialized);
if (m_enable_thread_cache) {
impl::heap::TlsHeapCache *heap_cache = reinterpret_cast<impl::heap::TlsHeapCache *>(os::GetTlsValue(m_tls_slot));
if (heap_cache) {
if (heap_cache->Shrink(ptr, new_size) == 0) {
return heap_cache->GetAllocationSize(ptr);
} else {
return 0;
}
}
}
if (GetCentral(m_central_heap_storage)->Shrink(ptr, new_size) == 0) {
return GetCentral(m_central_heap_storage)->GetAllocationSize(ptr);
} else {
return 0;
}
}
void StandardAllocator::ClearThreadCache() const {
if (m_enable_thread_cache) {
impl::heap::TlsHeapCache *heap_cache = reinterpret_cast<impl::heap::TlsHeapCache *>(os::GetTlsValue(m_tls_slot));
impl::heap::CachedHeap cache;
cache.Reset(heap_cache);
cache.Query(impl::AllocQuery_ClearCache);
cache.Release();
}
}
void StandardAllocator::CleanUpManagementArea() const {
AMS_ASSERT(m_initialized);
const auto err = GetCentral(m_central_heap_storage)->Query(impl::AllocQuery_UnifyFreeList);
AMS_ASSERT(err == 0);
AMS_UNUSED(err);
}
size_t StandardAllocator::GetSizeOf(const void *ptr) const {
AMS_ASSERT(m_initialized);
if (!util::IsAligned(reinterpret_cast<uintptr_t>(ptr), DefaultAlignment)) {
return 0;
}
impl::heap::TlsHeapCache *heap_cache = nullptr;
if (m_enable_thread_cache) {
heap_cache = reinterpret_cast<impl::heap::TlsHeapCache *>(os::GetTlsValue(m_tls_slot));
if (!heap_cache) {
GetCache(GetCentral(m_central_heap_storage), m_tls_slot);
heap_cache = reinterpret_cast<impl::heap::TlsHeapCache *>(os::GetTlsValue(m_tls_slot));
}
}
if (heap_cache) {
return heap_cache->GetAllocationSize(ptr);
} else {
return GetCentral(m_central_heap_storage)->GetAllocationSize(ptr);
}
}
size_t StandardAllocator::GetTotalFreeSize() const {
size_t size = 0;
auto err = GetCentral(m_central_heap_storage)->Query(impl::AllocQuery_FreeSizeMapped, std::addressof(size));
if (err != 0) {
err = GetCentral(m_central_heap_storage)->Query(impl::AllocQuery_FreeSize, std::addressof(size));
}
AMS_ASSERT(err == 0);
return size;
}
size_t StandardAllocator::GetAllocatableSize() const {
size_t size = 0;
auto err = GetCentral(m_central_heap_storage)->Query(impl::AllocQuery_MaxAllocatableSizeMapped, std::addressof(size));
if (err != 0) {
err = GetCentral(m_central_heap_storage)->Query(impl::AllocQuery_MaxAllocatableSize, std::addressof(size));
}
AMS_ASSERT(err == 0);
return size;
}
void StandardAllocator::WalkAllocatedBlocks(WalkCallback callback, void *user_data) const {
AMS_ASSERT(m_initialized);
this->ClearThreadCache();
GetCentral(m_central_heap_storage)->WalkAllocatedPointers(callback, user_data);
}
void StandardAllocator::Dump() const {
AMS_ASSERT(m_initialized);
size_t tmp;
auto err = GetCentral(m_central_heap_storage)->Query(impl::AllocQuery_MaxAllocatableSizeMapped, std::addressof(tmp));
if (err == 0) {
GetCentral(m_central_heap_storage)->Query(impl::AllocQuery_Dump, impl::DumpMode_Spans | impl::DumpMode_Pointers, 1);
} else {
GetCentral(m_central_heap_storage)->Query(impl::AllocQuery_Dump, impl::DumpMode_All, 1);
}
}
StandardAllocator::AllocatorHash StandardAllocator::Hash() const {
AMS_ASSERT(m_initialized);
AllocatorHash alloc_hash;
{
char temp_hash[crypto::Sha1Generator::HashSize];
InternalHash internal_hash;
internal_hash.allocated_count = 0;
internal_hash.allocated_size = 0;
internal_hash.sha1.Initialize();
this->WalkAllocatedBlocks(InternalHashCallback, reinterpret_cast<void *>(std::addressof(internal_hash)));
alloc_hash.allocated_count = internal_hash.allocated_count;
alloc_hash.allocated_size = internal_hash.allocated_size;
internal_hash.sha1.GetHash(temp_hash, sizeof(temp_hash));
std::memcpy(std::addressof(alloc_hash.hash), temp_hash, sizeof(alloc_hash.hash));
}
return alloc_hash;
}
}
| 12,415
|
C++
|
.cpp
| 276
| 35.271739
| 140
| 0.61687
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,437
|
mem_impl_platform.os.linux.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/mem/impl/mem_impl_platform.os.linux.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 <sys/mman.h>
#include "mem_impl_platform.hpp"
namespace ams::mem::impl {
errno_t virtual_alloc(void **ptr, size_t size) {
/* Ensure size is non-zero. */
if (size == 0) {
return EINVAL;
}
/* Allocate virtual memory. */
if (const auto address = ::mmap(nullptr, size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); address != MAP_FAILED) {
*ptr = reinterpret_cast<void *>(address);
return 0;
} else {
return errno;
}
}
errno_t virtual_free(void *ptr, size_t size) {
/* Ensure pointer/size aren't zero. */
if (ptr == nullptr || size == 0) {
return EINVAL;
}
/* Free the memory. */
if (::munmap(ptr, size) == 0) {
return 0;
} else {
return errno;
}
}
errno_t physical_alloc(void *ptr, size_t size, Prot prot) {
/* Ensure pointer isn't zero. */
if (ptr == nullptr) {
return EINVAL;
}
/* Convert the protection. */
int native_prot;
switch (util::ToUnderlying(prot)) {
case Prot_none:
native_prot = PROT_NONE;
break;
case Prot_read:
native_prot = PROT_READ;
break;
case Prot_write:
case Prot_write | Prot_read:
native_prot = PROT_READ | PROT_WRITE;
break;
case Prot_exec:
native_prot = PROT_EXEC;
break;
case Prot_exec | Prot_read:
native_prot = PROT_READ | PROT_EXEC;
break;
case Prot_exec | Prot_write:
case Prot_exec | Prot_write | Prot_read:
native_prot = PROT_READ | PROT_WRITE | PROT_EXEC;
break;
default:
return EINVAL;
}
if (::mprotect(ptr, size, native_prot)) {
return 0;
} else {
return errno;
}
}
errno_t physical_free(void *ptr, size_t size) {
/* Detect empty allocation. */
const uintptr_t aligned_start = util::AlignUp(reinterpret_cast<uintptr_t>(ptr), os::MemoryPageSize);
const uintptr_t aligned_end = util::AlignDown(reinterpret_cast<uintptr_t>(ptr) + size, os::MemoryPageSize);
const size_t aligned_size = aligned_end - aligned_start;
if (aligned_end <= aligned_start) {
return 0;
}
if (::mprotect(reinterpret_cast<void *>(aligned_start), aligned_size, PROT_NONE)) {
return 0;
} else {
return errno;
}
}
size_t strlcpy(char *dst, const char *src, size_t size) {
const size_t src_size = std::strlen(src);
if (src_size >= size) {
if (size) {
std::memcpy(dst, src, size - 1);
dst[size - 1] = 0;
}
} else {
std::memcpy(dst, src, src_size + 1);
}
return src_size;
}
errno_t gen_random(void *dst, size_t dst_size) {
/* TODO: CryptGenRandom? */
os::GenerateRandomBytes(dst, dst_size);
return 0;
}
errno_t epochtime(s64 *dst) {
/* TODO: Something more sane than this. */
auto ts = os::ConvertToTimeSpan(os::GetSystemTick());
*dst = (ts.GetNanoSeconds() / INT64_C(100)) + INT64_C(0x8A09F909AE60000);
return 0;
}
errno_t getcpu(s32 *out) {
if (const auto core = sched_getcpu(); core >= 0) {
*out = core;
return 0;
} else {
return errno;
}
}
}
| 4,372
|
C++
|
.cpp
| 127
| 25.133858
| 127
| 0.540189
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,438
|
mem_impl_platform.os.macos.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/mem/impl/mem_impl_platform.os.macos.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 <sys/mman.h>
#include "mem_impl_platform.hpp"
#if defined(ATMOSPHERE_ARCH_X64)
#include <cpuid.h>
#endif
namespace ams::mem::impl {
errno_t virtual_alloc(void **ptr, size_t size) {
/* Ensure size is non-zero. */
if (size == 0) {
return EINVAL;
}
/* Allocate virtual memory. */
if (const auto address = ::mmap(nullptr, size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); address != MAP_FAILED) {
*ptr = reinterpret_cast<void *>(address);
return 0;
} else {
return errno;
}
}
errno_t virtual_free(void *ptr, size_t size) {
/* Ensure pointer/size aren't zero. */
if (ptr == nullptr || size == 0) {
return EINVAL;
}
/* Free the memory. */
if (::munmap(ptr, size) == 0) {
return 0;
} else {
return errno;
}
}
errno_t physical_alloc(void *ptr, size_t size, Prot prot) {
/* Ensure pointer isn't zero. */
if (ptr == nullptr) {
return EINVAL;
}
/* Convert the protection. */
int native_prot;
switch (util::ToUnderlying(prot)) {
case Prot_none:
native_prot = PROT_NONE;
break;
case Prot_read:
native_prot = PROT_READ;
break;
case Prot_write:
case Prot_write | Prot_read:
native_prot = PROT_READ | PROT_WRITE;
break;
case Prot_exec:
native_prot = PROT_EXEC;
break;
case Prot_exec | Prot_read:
native_prot = PROT_READ | PROT_EXEC;
break;
case Prot_exec | Prot_write:
case Prot_exec | Prot_write | Prot_read:
native_prot = PROT_READ | PROT_WRITE | PROT_EXEC;
break;
default:
return EINVAL;
}
if (::mprotect(ptr, size, native_prot)) {
return 0;
} else {
return errno;
}
}
errno_t physical_free(void *ptr, size_t size) {
/* Detect empty allocation. */
const uintptr_t aligned_start = util::AlignUp(reinterpret_cast<uintptr_t>(ptr), os::MemoryPageSize);
const uintptr_t aligned_end = util::AlignDown(reinterpret_cast<uintptr_t>(ptr) + size, os::MemoryPageSize);
const size_t aligned_size = aligned_end - aligned_start;
if (aligned_end <= aligned_start) {
return 0;
}
if (::mprotect(reinterpret_cast<void *>(aligned_start), aligned_size, PROT_NONE)) {
return 0;
} else {
return errno;
}
}
size_t strlcpy(char *dst, const char *src, size_t size) {
const size_t src_size = std::strlen(src);
if (src_size >= size) {
if (size) {
std::memcpy(dst, src, size - 1);
dst[size - 1] = 0;
}
} else {
std::memcpy(dst, src, src_size + 1);
}
return src_size;
}
errno_t gen_random(void *dst, size_t dst_size) {
/* TODO: CryptGenRandom? */
os::GenerateRandomBytes(dst, dst_size);
return 0;
}
errno_t epochtime(s64 *dst) {
/* TODO: Something more sane than this. */
auto ts = os::ConvertToTimeSpan(os::GetSystemTick());
*dst = (ts.GetNanoSeconds() / INT64_C(100)) + INT64_C(0x8A09F909AE60000);
return 0;
}
errno_t getcpu(s32 *out) {
if (__builtin_available(macOS 11.0, *)) {
/* On macOS 11.0+, we can use the exposed API they added. */
size_t cpu_number = 0;
const auto res = pthread_cpu_number_np(std::addressof(cpu_number));
AMS_ASSERT(res == 0);
AMS_UNUSED(res);
*out = static_cast<s32>(cpu_number);
return 0;
} else {
#if defined(ATMOSPHERE_ARCH_X64)
{
uint32_t cpu_info[4];
__cpuid_count(1, 0, cpu_info[0], cpu_info[1], cpu_info[2], cpu_info[3]);
s32 core;
if ((cpu_info[3] & (1 << 9)) == 0) {
core = 0;
} else {
core = static_cast<s32>(cpu_info[1] >> 24);
}
*out = core;
return 0;
}
#elif defined(ATMOSPHERE_ARCH_ARM64)
{
/* Read from TSD, per https://github.com/apple-oss-distributions/xnu/blob/e6231be02a03711ca404e5121a151b24afbff733/libsyscall/os/tsd.h#L68 */
uint64_t p;
__asm__ __volatile__ ("mrs %0, TPIDR_EL0" : "=r" (p));
*out = static_cast<s32>(p & 0xF);
return 0;
}
#else
AMS_ABORT("Unknown architecture to get current cpu on fallback path on macOS");
#endif
}
}
}
| 5,685
|
C++
|
.cpp
| 158
| 25.734177
| 157
| 0.525418
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,439
|
mem_impl_platform.os.horizon.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/mem/impl/mem_impl_platform.os.horizon.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "mem_impl_platform.hpp"
namespace ams::mem::impl {
namespace {
ALWAYS_INLINE bool IsVirtualAddressMemoryEnabled() {
AMS_FUNCTION_LOCAL_STATIC(bool, s_virt_mem_enabled, os::IsVirtualAddressMemoryEnabled());
return s_virt_mem_enabled;
}
ALWAYS_INLINE errno_t ConvertResult(Result result) {
/* TODO: Actually implement this in a meaningful way. */
if (R_FAILED(result)) {
return EINVAL;
}
return 0;
}
ALWAYS_INLINE os::MemoryPermission ConvertToOsPermission(Prot prot) {
static_assert(static_cast<int>(Prot_read) == static_cast<int>(os::MemoryPermission_ReadOnly));
static_assert(static_cast<int>(Prot_write) == static_cast<int>(os::MemoryPermission_WriteOnly));
static_assert((util::ToUnderlying(Prot_read) | util::ToUnderlying(Prot_write)) == util::ToUnderlying(os::MemoryPermission_ReadWrite));
return static_cast<os::MemoryPermission>(prot & (Prot_read | Prot_write));
}
}
errno_t virtual_alloc(void **ptr, size_t size) {
/* Ensure size isn't too large. */
if (size > mem::impl::MaxSize) {
return EINVAL;
}
/* Allocate virtual memory. */
uintptr_t addr;
if (IsVirtualAddressMemoryEnabled()) {
/* TODO: Support virtual address memory. */
AMS_ABORT("Virtual address memory not supported yet");
} else {
if (auto err = ConvertResult(os::AllocateMemoryBlock(std::addressof(addr), util::AlignUp(size, os::MemoryBlockUnitSize))); err != 0) {
return err;
}
os::SetMemoryPermission(addr, size, os::MemoryPermission_None);
}
/* Set the output pointer. */
*ptr = reinterpret_cast<void *>(addr);
return 0;
}
errno_t virtual_free(void *ptr, size_t size) {
/* Ensure size isn't zero. */
if (size == 0) {
return EINVAL;
}
if (IsVirtualAddressMemoryEnabled()) {
/* TODO: Support virtual address memory. */
AMS_ABORT("Virtual address memory not supported yet");
} else {
os::FreeMemoryBlock(reinterpret_cast<uintptr_t>(ptr), util::AlignUp(size, os::MemoryBlockUnitSize));
}
return 0;
}
errno_t physical_alloc(void *ptr, size_t size, Prot prot) {
/* Detect empty allocation. */
const uintptr_t aligned_start = util::AlignDown(reinterpret_cast<uintptr_t>(ptr), os::MemoryPageSize);
const uintptr_t aligned_end = util::AlignUp(reinterpret_cast<uintptr_t>(ptr) + size, os::MemoryPageSize);
const size_t aligned_size = aligned_end - aligned_start;
if (aligned_end <= aligned_start) {
return 0;
}
if (IsVirtualAddressMemoryEnabled()) {
/* TODO: Support virtual address memory. */
AMS_ABORT("Virtual address memory not supported yet");
} else {
os::SetMemoryPermission(aligned_start, aligned_size, ConvertToOsPermission(prot));
}
return 0;
}
errno_t physical_free(void *ptr, size_t size) {
/* Detect empty allocation. */
const uintptr_t aligned_start = util::AlignDown(reinterpret_cast<uintptr_t>(ptr), os::MemoryPageSize);
const uintptr_t aligned_end = util::AlignUp(reinterpret_cast<uintptr_t>(ptr) + size, os::MemoryPageSize);
const size_t aligned_size = aligned_end - aligned_start;
if (aligned_end <= aligned_start) {
return 0;
}
if (IsVirtualAddressMemoryEnabled()) {
/* TODO: Support virtual address memory. */
AMS_ABORT("Virtual address memory not supported yet");
} else {
os::SetMemoryPermission(aligned_start, aligned_size, os::MemoryPermission_None);
}
return 0;
}
size_t strlcpy(char *dst, const char *src, size_t size) {
const size_t src_size = std::strlen(src);
if (src_size >= size) {
if (size) {
std::memcpy(dst, src, size - 1);
dst[size - 1] = 0;
}
} else {
std::memcpy(dst, src, src_size + 1);
}
return src_size;
}
errno_t gen_random(void *dst, size_t dst_size) {
os::GenerateRandomBytes(dst, dst_size);
return 0;
}
errno_t epochtime(s64 *dst) {
/* TODO: What is this calc? */
auto ts = os::ConvertToTimeSpan(os::GetSystemTick());
*dst = (ts.GetNanoSeconds() / INT64_C(100)) + INT64_C(0x8A09F909AE60000);
return 0;
}
errno_t getcpu(s32 *out) {
*out = os::GetCurrentCoreNumber();
return 0;
}
}
| 5,475
|
C++
|
.cpp
| 129
| 33.666667
| 146
| 0.608908
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,440
|
mem_impl_platform.os.windows.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/mem/impl/mem_impl_platform.os.windows.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 <stratosphere/windows.hpp>
#include <VersionHelpers.h>
#include "mem_impl_platform.hpp"
namespace ams::mem::impl {
namespace {
errno_t ConvertGetLastError(DWORD error, errno_t fallback = EIO) {
/* TODO: Implement this? */
AMS_UNUSED(error);
return fallback;
}
}
errno_t virtual_alloc(void **ptr, size_t size) {
/* Ensure size is non-zero. */
if (size == 0) {
return EINVAL;
}
/* Allocate virtual memory. */
if (void *mem = ::VirtualAlloc(nullptr, size, MEM_RESERVE, PAGE_READWRITE); mem != nullptr) {
*ptr = mem;
return 0;
} else {
return ConvertGetLastError(::GetLastError());
}
}
errno_t virtual_free(void *ptr, size_t size) {
/* Ensure pointer/size aren't zero. */
if (ptr == nullptr || size == 0) {
return EINVAL;
}
/* Free the memory. */
if (::VirtualFree(ptr, 0, MEM_RELEASE)) {
return 0;
} else {
return ConvertGetLastError(::GetLastError());
}
}
errno_t physical_alloc(void *ptr, size_t size, Prot prot) {
/* Ensure pointer isn't zero. */
if (ptr == nullptr) {
return EINVAL;
}
/* Convert the protection. */
DWORD fl_protect;
switch (util::ToUnderlying(prot)) {
case Prot_none:
fl_protect = PAGE_NOACCESS;
break;
case Prot_read:
fl_protect = PAGE_READONLY;
break;
case Prot_write:
case Prot_write | Prot_read:
fl_protect = PAGE_READWRITE;
break;
case Prot_exec:
fl_protect = PAGE_EXECUTE;
break;
case Prot_exec | Prot_read:
fl_protect = PAGE_EXECUTE_READ;
break;
case Prot_exec | Prot_write:
case Prot_exec | Prot_write | Prot_read:
fl_protect = PAGE_EXECUTE_READWRITE;
break;
default:
return EINVAL;
}
if (::VirtualAlloc(ptr, size, MEM_COMMIT, fl_protect)) {
return 0;
} else {
return ConvertGetLastError(::GetLastError());
}
}
errno_t physical_free(void *ptr, size_t size) {
/* Detect empty allocation. */
const uintptr_t aligned_start = util::AlignUp(reinterpret_cast<uintptr_t>(ptr), os::MemoryPageSize);
const uintptr_t aligned_end = util::AlignDown(reinterpret_cast<uintptr_t>(ptr) + size, os::MemoryPageSize);
const size_t aligned_size = aligned_end - aligned_start;
if (aligned_end <= aligned_start) {
return 0;
}
if (::VirtualFree(reinterpret_cast<LPVOID>(aligned_start), aligned_size, MEM_DECOMMIT)) {
return 0;
} else {
return ConvertGetLastError(::GetLastError());
}
}
size_t strlcpy(char *dst, const char *src, size_t size) {
const size_t src_size = std::strlen(src);
if (src_size >= size) {
if (size) {
std::memcpy(dst, src, size - 1);
dst[size - 1] = 0;
}
} else {
std::memcpy(dst, src, src_size + 1);
}
return src_size;
}
errno_t gen_random(void *dst, size_t dst_size) {
/* TODO: CryptGenRandom? */
os::GenerateRandomBytes(dst, dst_size);
return 0;
}
errno_t epochtime(s64 *dst) {
/* TODO: Something more sane than this. */
auto ts = os::ConvertToTimeSpan(os::GetSystemTick());
*dst = (ts.GetNanoSeconds() / INT64_C(100)) + INT64_C(0x8A09F909AE60000);
return 0;
}
errno_t getcpu(s32 *out) {
AMS_FUNCTION_LOCAL_STATIC(bool, s_has_processor_ex, ::IsWindows7OrGreater());
if (s_has_processor_ex) {
PROCESSOR_NUMBER pnum;
::GetCurrentProcessorNumberEx(std::addressof(pnum));
*out = (pnum.Group << 8) | pnum.Number;
} else {
*out = ::GetCurrentProcessorNumber();
}
return 0;
}
}
| 4,920
|
C++
|
.cpp
| 138
| 26.34058
| 117
| 0.558706
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,441
|
mem_impl_heap_central_heap.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/mem/impl/heap/mem_impl_heap_central_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 <stratosphere.hpp>
#include "mem_impl_heap_platform.hpp"
#include "mem_impl_heap_tls_heap_static.hpp"
#include "mem_impl_heap_tls_heap_central.hpp"
namespace ams::mem::impl::heap {
errno_t CentralHeap::Initialize(void *start, size_t size, u32 option) {
/* Validate size. */
if (size == 0 || !util::IsAligned(size, PageSize)) {
return EINVAL;
}
/* Don't allow initializing twice. */
if (m_start) {
return EEXIST;
}
if (start) {
/* We were provided with a region to use as backing memory. */
u8 *aligned_start = reinterpret_cast<u8 *>(util::AlignUp(reinterpret_cast<uintptr_t>(start), PageSize));
u8 *aligned_end = reinterpret_cast<u8 *>(util::AlignDown(reinterpret_cast<uintptr_t>(start) + size, PageSize));
if (aligned_start >= aligned_end) {
return EINVAL;
}
m_start = aligned_start;
m_end = aligned_end;
m_option = option;
m_tls_heap_central = std::construct_at(reinterpret_cast<TlsHeapCentral *>(m_start));
if (auto err = m_tls_heap_central->Initialize(m_start, m_end - m_start, false); err != 0) {
std::destroy_at(m_tls_heap_central);
m_tls_heap_central = nullptr;
AMS_ASSERT(err == 0);
return err;
}
m_use_virtual_memory = false;
} else {
/* We were not provided with a region to use as backing. */
void *mem = nullptr;
if (auto err = AllocateVirtualMemory(std::addressof(mem), size); err != 0) {
return err;
}
if (!util::IsAligned(reinterpret_cast<uintptr_t>(mem), PageSize)) {
FreeVirtualMemory(mem, size);
size += PageSize;
if (auto err = AllocateVirtualMemory(std::addressof(mem), size); err != 0) {
return err;
}
}
m_start = static_cast<u8 *>(mem);
m_end = m_start + size;
m_option = option;
void *central = reinterpret_cast<void *>(util::AlignUp(reinterpret_cast<uintptr_t>(mem), PageSize));
if (auto err = AllocatePhysicalMemory(central, sizeof(TlsHeapCentral)); err != 0) {
return err;
}
m_tls_heap_central = std::construct_at(static_cast<TlsHeapCentral *>(central));
if (auto err = m_tls_heap_central->Initialize(central, size, true); err != 0) {
std::destroy_at(m_tls_heap_central);
m_tls_heap_central = nullptr;
AMS_ASSERT(err == 0);
return err;
}
m_use_virtual_memory = true;
}
return 0;
}
void CentralHeap::Finalize() {
if (m_tls_heap_central) {
std::destroy_at(m_tls_heap_central);
}
if (m_use_virtual_memory) {
mem::impl::physical_free(util::AlignUp(static_cast<void *>(m_start), PageSize), m_end - m_start);
mem::impl::virtual_free(m_start, m_end - m_start);
}
m_tls_heap_central = nullptr;
m_use_virtual_memory = false;
m_option = 0;
m_start = nullptr;
m_end = nullptr;
}
void *CentralHeap::Allocate(size_t n, size_t align) {
if (!util::IsPowerOfTwo(align)) {
return nullptr;
}
if (n > MaxSize) {
return nullptr;
}
if (align > PageSize) {
return m_tls_heap_central->CacheLargeMemoryWithBigAlign(util::AlignUp(n, PageSize), align);
}
const size_t real_size = TlsHeapStatic::GetRealSizeFromSizeAndAlignment(util::AlignUp(n, align), align);
const auto cls = TlsHeapStatic::GetClassFromSize(real_size);
if (!cls) {
return m_tls_heap_central->CacheLargeMemory(real_size);
}
if (real_size == 0) {
return nullptr;
}
AMS_ASSERT(static_cast<u32>(cls) < TlsHeapStatic::NumClassInfo);
return m_tls_heap_central->CacheSmallMemory(cls, align);
}
size_t CentralHeap::GetAllocationSize(const void *ptr) {
const auto cls = m_tls_heap_central->GetClassFromPointer(ptr);
if (cls > 0) {
/* Check that the pointer has alignment from out allocator. */
if (!util::IsAligned(reinterpret_cast<uintptr_t>(ptr), MinimumAlignment)) {
return 0;
}
AMS_ASSERT(static_cast<u32>(cls) < TlsHeapStatic::NumClassInfo);
return TlsHeapStatic::GetChunkSize(cls);
} else if (ptr != nullptr) {
return m_tls_heap_central->GetAllocationSize(ptr);
} else {
return 0;
}
}
errno_t CentralHeap::Free(void *ptr) {
/* Allow Free(nullptr) */
if (ptr == nullptr) {
return 0;
}
/* Check that the pointer has alignment from out allocator. */
if(!util::IsAligned(reinterpret_cast<uintptr_t>(ptr), MinimumAlignment)) {
AMS_ASSERT(util::IsAligned(reinterpret_cast<uintptr_t>(ptr), MinimumAlignment));
return EFAULT;
}
const auto cls = m_tls_heap_central->GetClassFromPointer(ptr);
if (cls >= 0) {
AMS_ASSERT(static_cast<u32>(cls) < TlsHeapStatic::NumClassInfo);
if (cls) {
return m_tls_heap_central->UncacheSmallMemory(ptr);
} else {
return m_tls_heap_central->UncacheLargeMemory(ptr);
}
} else {
AMS_ASSERT(cls >= 0);
return EFAULT;
}
}
errno_t CentralHeap::FreeWithSize(void *ptr, size_t size) {
if (TlsHeapStatic::GetClassFromSize(size)) {
return m_tls_heap_central->UncacheSmallMemory(ptr);
} else {
return m_tls_heap_central->UncacheLargeMemory(ptr);
}
}
errno_t CentralHeap::Reallocate(void *ptr, size_t size, void **p) {
AMS_ASSERT(ptr != nullptr && size != 0);
if (!size) {
return EINVAL;
}
if (size > MaxSize) {
return ENOMEM;
}
const auto cls_from_size = TlsHeapStatic::GetClassFromSize(size);
const auto cls_from_ptr = m_tls_heap_central->GetClassFromPointer(ptr);
if (cls_from_ptr) {
if (cls_from_ptr <= 0) {
return EFAULT;
} else if (cls_from_size && static_cast<s32>(cls_from_size) <= cls_from_ptr) {
*p = ptr;
return 0;
} else {
const size_t new_chunk_size = TlsHeapStatic::GetChunkSize(cls_from_ptr);
*p = this->Allocate(new_chunk_size);
if (*p) {
std::memcpy(*p, ptr, size);
return m_tls_heap_central->UncacheSmallMemory(ptr);
} else {
return ENOMEM;
}
}
} else if (cls_from_size) {
*p = this->Allocate(size);
if (*p) {
std::memcpy(*p, ptr, size);
return m_tls_heap_central->UncacheLargeMemory(ptr);
} else {
return ENOMEM;
}
} else {
return m_tls_heap_central->ReallocateLargeMemory(ptr, size, p);
}
}
errno_t CentralHeap::Shrink(void *ptr, size_t size) {
AMS_ASSERT(ptr != nullptr && size != 0);
if (!size) {
return EINVAL;
}
if (size > MaxSize) {
return ENOMEM;
}
const auto cls_from_size = TlsHeapStatic::GetClassFromSize(size);
const auto cls_from_ptr = m_tls_heap_central->GetClassFromPointer(ptr);
if (cls_from_ptr) {
if (cls_from_ptr <= 0) {
return EFAULT;
} else if (cls_from_size && static_cast<s32>(cls_from_size) <= cls_from_ptr) {
return 0;
} else {
return EINVAL;
}
} else if (cls_from_size) {
return m_tls_heap_central->ShrinkLargeMemory(ptr, PageSize);
} else {
return m_tls_heap_central->ShrinkLargeMemory(ptr, size);
}
}
bool CentralHeap::MakeCache(CachedHeap *cached_heap) {
if (cached_heap == nullptr) {
return false;
}
AMS_ASSERT(m_tls_heap_central != nullptr);
const auto cls = TlsHeapStatic::GetClassFromSize(sizeof(*cached_heap));
void *tls_heap_cache = m_tls_heap_central->CacheSmallMemoryForSystem(cls);
if (tls_heap_cache == nullptr) {
return false;
}
std::construct_at(static_cast<TlsHeapCache *>(tls_heap_cache), m_tls_heap_central, m_option);
if (m_tls_heap_central->AddThreadCache(reinterpret_cast<TlsHeapCache *>(tls_heap_cache)) != 0) {
m_tls_heap_central->UncacheSmallMemory(tls_heap_cache);
return false;
}
cached_heap->Reset(reinterpret_cast<TlsHeapCache *>(tls_heap_cache));
return true;
}
errno_t CentralHeap::WalkAllocatedPointers(HeapWalkCallback callback, void *user_data) {
if (!callback || !m_tls_heap_central) {
return EINVAL;
}
return m_tls_heap_central->WalkAllocatedPointers(callback, user_data);
}
errno_t CentralHeap::Query(int query, ...) {
std::va_list vl;
va_start(vl, query);
auto err = this->QueryV(query, vl);
va_end(vl);
return err;
}
errno_t CentralHeap::QueryV(int _query, std::va_list vl) {
const AllocQuery query = static_cast<AllocQuery>(_query);
switch (query) {
case AllocQuery_Dump:
case AllocQuery_DumpJson:
{
auto dump_mode = static_cast<DumpMode>(va_arg(vl, int));
auto fd = va_arg(vl, int);
if (m_tls_heap_central) {
m_tls_heap_central->Dump(dump_mode, fd, query == AllocQuery_DumpJson);
}
return 0;
}
case AllocQuery_PageSize:
{
size_t *out = va_arg(vl, size_t *);
if (out) {
*out = PageSize;
}
return 0;
}
case AllocQuery_AllocatedSize:
case AllocQuery_FreeSize:
case AllocQuery_SystemSize:
case AllocQuery_MaxAllocatableSize:
{
size_t *out = va_arg(vl, size_t *);
if (!out) {
return 0;
}
if (!m_tls_heap_central) {
*out = 0;
return 0;
}
TlsHeapMemStats stats;
m_tls_heap_central->GetMemStats(std::addressof(stats));
switch (query) {
case AllocQuery_AllocatedSize:
default:
*out = stats.allocated_size;
break;
case AllocQuery_FreeSize:
*out = stats.free_size;
break;
case AllocQuery_SystemSize:
*out = stats.system_size;
break;
case AllocQuery_MaxAllocatableSize:
*out = stats.max_allocatable_size;
break;
}
return 0;
}
case AllocQuery_IsClean:
{
int *out = va_arg(vl, int *);
if (out) {
*out = !m_tls_heap_central || m_tls_heap_central->IsClean();
}
return 0;
}
case AllocQuery_HeapHash:
{
HeapHash *out = va_arg(vl, HeapHash *);
if (out) {
if (m_tls_heap_central) {
m_tls_heap_central->CalculateHeapHash(out);
} else {
*out = {};
}
}
return 0;
}
case AllocQuery_UnifyFreeList:
/* NOTE: Nintendo does not check that the ptr is not null for this query, even though they do for other queries. */
m_tls_heap_central->IsClean();
return 0;
case AllocQuery_SetColor:
{
/* NOTE: Nintendo does not check that the ptr is not null for this query, even though they do for other queries. */
void *ptr = va_arg(vl, void *);
int color = va_arg(vl, int);
return m_tls_heap_central->SetColor(ptr, color);
}
case AllocQuery_GetColor:
{
/* NOTE: Nintendo does not check that the ptr is not null for this query, even though they do for other queries. */
void *ptr = va_arg(vl, void *);
int *out = va_arg(vl, int *);
return m_tls_heap_central->GetColor(ptr, out);
}
case AllocQuery_SetName:
{
/* NOTE: Nintendo does not check that the ptr is not null for this query, even though they do for other queries. */
void *ptr = va_arg(vl, void *);
const char *name = va_arg(vl, const char *);
return m_tls_heap_central->SetName(ptr, name);
}
case AllocQuery_GetName:
{
/* NOTE: Nintendo does not check that the ptr is not null for this query, even though they do for other queries. */
void *ptr = va_arg(vl, void *);
char *dst = va_arg(vl, char *);
size_t dst_size = va_arg(vl, size_t);
return m_tls_heap_central->GetName(ptr, dst, dst_size);
}
case AllocQuery_FreeSizeMapped:
case AllocQuery_MaxAllocatableSizeMapped:
{
/* NOTE: Nintendo does not check that the ptr is not null for this query, even though they do for other queries. */
size_t *out = va_arg(vl, size_t *);
size_t free_size;
size_t max_allocatable_size;
auto err = m_tls_heap_central->GetMappedMemStats(std::addressof(free_size), std::addressof(max_allocatable_size));
if (err == 0) {
if (query == AllocQuery_FreeSizeMapped) {
*out = free_size;
} else {
*out = max_allocatable_size;
}
}
return err;
}
default:
return EINVAL;
}
}
}
| 15,535
|
C++
|
.cpp
| 379
| 28.316623
| 131
| 0.520489
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,442
|
mem_impl_heap_cached_heap.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/mem/impl/heap/mem_impl_heap_cached_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 <stratosphere.hpp>
#include "mem_impl_heap_platform.hpp"
#include "mem_impl_heap_tls_heap_static.hpp"
#include "mem_impl_heap_tls_heap_central.hpp"
namespace ams::mem::impl::heap {
void *CachedHeap::Allocate(size_t n) {
return m_tls_heap_cache->Allocate(n);
}
void *CachedHeap::Allocate(size_t n, size_t align) {
return m_tls_heap_cache->Allocate(n, align);
}
size_t CachedHeap::GetAllocationSize(const void *ptr) {
return m_tls_heap_cache->GetAllocationSize(ptr);
}
errno_t CachedHeap::Free(void *p) {
return m_tls_heap_cache->Free(p);
}
errno_t CachedHeap::FreeWithSize(void *p, size_t size) {
return m_tls_heap_cache->FreeWithSize(p, size);
}
errno_t CachedHeap::Reallocate(void *ptr, size_t size, void **p) {
return m_tls_heap_cache->Reallocate(ptr, size, p);
}
errno_t CachedHeap::Shrink(void *ptr, size_t size) {
return m_tls_heap_cache->Shrink(ptr, size);
}
void CachedHeap::ReleaseAllCache() {
if (m_tls_heap_cache) {
m_tls_heap_cache->ReleaseAllCache();
}
}
void CachedHeap::Finalize() {
if (m_tls_heap_cache) {
m_tls_heap_cache->Finalize();
m_tls_heap_cache = nullptr;
}
}
bool CachedHeap::CheckCache() {
bool cache = false;
const auto err = this->Query(AllocQuery_CheckCache, std::addressof(cache));
AMS_ASSERT(err == 0);
AMS_UNUSED(err);
return cache;
}
errno_t CachedHeap::QueryV(int _query, std::va_list vl) {
const AllocQuery query = static_cast<AllocQuery>(_query);
switch (query) {
case AllocQuery_CheckCache:
{
bool *out = va_arg(vl, bool *);
if (out) {
*out = (m_tls_heap_cache == nullptr) || m_tls_heap_cache->CheckCache();
}
return 0;
}
case AllocQuery_ClearCache:
{
this->ReleaseAllCache();
return 0;
}
case AllocQuery_FinalizeCache:
{
this->Finalize();
return 0;
}
default:
return EINVAL;
}
}
errno_t CachedHeap::Query(int query, ...) {
std::va_list vl;
va_start(vl, query);
auto err = this->QueryV(query, vl);
va_end(vl);
return err;
}
void CachedHeap::Reset(TlsHeapCache *thc) {
this->Finalize();
m_tls_heap_cache = thc;
}
TlsHeapCache *CachedHeap::Release() {
TlsHeapCache *ret = m_tls_heap_cache;
m_tls_heap_cache = nullptr;
return ret;
}
}
| 3,395
|
C++
|
.cpp
| 101
| 25.722772
| 91
| 0.59188
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,443
|
mem_impl_heap_tls_heap_central.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/mem/impl/heap/mem_impl_heap_tls_heap_central.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 "mem_impl_heap_platform.hpp"
#include "mem_impl_heap_tls_heap_static.hpp"
#include "mem_impl_heap_tls_heap_central.hpp"
namespace ams::mem::impl::heap {
namespace {
void InitializeSpanPage(SpanPage *sp) {
static_assert(SpanPage::MaxSpanCount <= BITSIZEOF(u64));
constexpr size_t NumUnusedBits = BITSIZEOF(u64) - SpanPage::MaxSpanCount;
sp->info.free_count = SpanPage::MaxSpanCount;
sp->info.is_sticky = 0;
sp->info.alloc_bitmap = (static_cast<u64>(1) << NumUnusedBits) - 1;
ListClearLink(sp);
sp->info.span_of_spanpage.start.u = 0;
sp->info.span_of_spanpage.num_pages = 0;
sp->info.span_of_spanpage.aux.small.objects = nullptr;
sp->info.span_of_spanpage.object_count = 0;
sp->info.span_of_spanpage.page_class = 0;
sp->info.span_of_spanpage.status = Span::Status_NotUsed;
sp->info.span_of_spanpage.id = 0;
ListClearLink(std::addressof(sp->info.span_of_spanpage));
}
void RegisterSpan(SpanTable *span_table, Span *span) {
const size_t idx = TlsHeapStatic::GetPageIndex(span->start.u - reinterpret_cast<uintptr_t>(span_table));
span->page_class = 0;
span_table->page_to_span[idx] = span;
span_table->page_to_span[idx + span->num_pages - 1] = span;
}
void UnregisterSpan(SpanTable *span_table, Span *span) {
AMS_ASSERT(span->page_class == 0);
const size_t idx = TlsHeapStatic::GetPageIndex(span->start.u - reinterpret_cast<uintptr_t>(span_table));
span_table->page_to_span[idx] = nullptr;
span_table->page_to_span[idx + span->num_pages - 1] = nullptr;
}
void ChangeRangeOfSpan(SpanTable *span_table, Span *span, uintptr_t start, size_t new_pages) {
const size_t idx = TlsHeapStatic::GetPageIndex(span->start.u - reinterpret_cast<uintptr_t>(span_table));
if (span->start.u == start) {
if (span->num_pages != 1) {
span_table->page_to_span[idx + span->num_pages - 1] = nullptr;
}
span_table->page_to_span[idx + new_pages - 1] = span;
span->num_pages = new_pages;
} else {
span_table->page_to_span[idx] = nullptr;
span_table->page_to_span[idx + span->num_pages - 1] = nullptr;
const size_t new_idx = TlsHeapStatic::GetPageIndex(start - reinterpret_cast<uintptr_t>(span_table));
span_table->page_to_span[new_idx] = span;
span_table->page_to_span[new_idx + new_pages - 1] = span;
span->start.u = start;
span->num_pages = new_pages;
}
}
void MigrateSpan(SpanTable *span_table, Span *from, Span *to) {
AMS_ASSERT(from != to);
std::memcpy(to, from, sizeof(*from));
from->status = Span::Status_NotUsed;
if (from->list_next) {
to->list_next = from->list_next;
from->list_next->list_prev = to;
from->list_next = nullptr;
} else {
to->list_next = nullptr;
}
if (from->list_prev) {
to->list_prev = from->list_prev;
from->list_prev->list_next = to;
from->list_prev = nullptr;
} else {
to->list_prev = nullptr;
}
const size_t idx = TlsHeapStatic::GetPageIndex(to->start.u - reinterpret_cast<uintptr_t>(span_table));
if (from->page_class) {
for (size_t i = 0; i < to->num_pages; i++) {
span_table->page_to_span[idx + i] = to;
}
} else {
span_table->page_to_span[idx] = to;
span_table->page_to_span[idx + to->num_pages - 1] = to;
}
}
bool IsNthSmallMemoryMarked(const Span *span, size_t n) {
return (span->aux.small.is_allocated[n / BITSIZEOF(u64)] & (1ull << (n % BITSIZEOF(u64)))) != 0;
}
void MarkNthSmallMemory(Span *span, size_t n) {
span->aux.small.is_allocated[n / BITSIZEOF(u64)] |= (1ull << (n % BITSIZEOF(u64)));
}
void UnmarkNthSmallMemory(Span *span, size_t n) {
span->aux.small.is_allocated[n / BITSIZEOF(u64)] &= ~(1ull << (n % BITSIZEOF(u64)));
}
void *AllocateSmallMemory(Span *span) {
Span::SmallMemory *sm = span->aux.small.objects;
const size_t chunk_size = TlsHeapStatic::GetChunkSize(span->page_class);
const uintptr_t span_end = span->start.u + (span->num_pages * TlsHeapStatic::PageSize);
if (span->start.u <= reinterpret_cast<uintptr_t>(sm) && reinterpret_cast<uintptr_t>(sm) < span_end) {
const size_t idx = (reinterpret_cast<uintptr_t>(sm) - span->start.u) / chunk_size;
if (reinterpret_cast<uintptr_t>(sm) == (span->start.u + idx * chunk_size) && !IsNthSmallMemoryMarked(span, idx)) {
MarkNthSmallMemory(span, idx);
span->aux.small.objects = sm->next;
sm->next = nullptr;
span->object_count++;
return sm;
}
} else if (sm == nullptr) {
return nullptr;
}
/* Data corruption error. */
AMS_ASSERT(false);
span->aux.small.objects = nullptr;
return nullptr;
}
struct MangledSmallMemory {
Span::SmallMemory *from;
Span::SmallMemory *to;
};
size_t AllocateSmallMemory(Span *span, TlsHeapCache *cache, size_t n, MangledSmallMemory *memlist) {
auto ManglePointer = [cache](void *ptr) ALWAYS_INLINE_LAMBDA {
return static_cast<Span::SmallMemory *>(cache->ManglePointer(ptr));
};
Span::SmallMemory *sm = span->aux.small.objects;
if (sm) {
size_t count = 0;
memlist->from = ManglePointer(sm);
const size_t chunk_size = TlsHeapStatic::GetChunkSize(span->page_class);
const uintptr_t span_end = span->start.u + (span->num_pages * TlsHeapStatic::PageSize);
while (span->start.u <= reinterpret_cast<uintptr_t>(sm) && reinterpret_cast<uintptr_t>(sm) < span_end) {
const size_t idx = (reinterpret_cast<uintptr_t>(sm) - span->start.u) / chunk_size;
if (span->start.u + idx * chunk_size != reinterpret_cast<uintptr_t>(sm)) {
break;
}
if (IsNthSmallMemoryMarked(span, idx)) {
break;
}
MarkNthSmallMemory(span, idx);
count++;
Span::SmallMemory *next = sm->next;
sm->next = ManglePointer(next);
if (count >= n || next == nullptr) {
memlist->to = sm;
memlist->to->next = nullptr;
span->aux.small.objects = next;
span->object_count += count;
return count;
}
sm = next;
}
/* Data corruption error. */
Span::SmallMemory *prev = span->aux.small.objects;
Span::SmallMemory *cur = span->aux.small.objects;
while (cur != sm) {
prev = cur;
cur = ManglePointer(cur->next);
}
memlist->to = ManglePointer(prev);
memlist->to->next = nullptr;
span->aux.small.objects = nullptr;
span->object_count += count;
return count;
} else {
memlist->from = nullptr;
memlist->to = nullptr;
return 0;
}
}
void ReleaseSmallMemory(Span *span, void *ptr) {
AMS_ASSERT(span->object_count > 0);
const size_t span_ofs = reinterpret_cast<uintptr_t>(ptr) - span->start.u;
const size_t chunk_size = TlsHeapStatic::GetChunkSize(span->page_class);
const size_t span_idx = span_ofs / chunk_size;
if (span_ofs != (span_idx * chunk_size)) {
/* Invalid pointer. Do the best we can. */
ptr = reinterpret_cast<void *>(span->start.u + span_idx * chunk_size);
}
if (IsNthSmallMemoryMarked(span, span_idx)) {
UnmarkNthSmallMemory(span, span_idx);
Span::SmallMemory *sm = reinterpret_cast<Span::SmallMemory *>(ptr);
sm->next = span->aux.small.objects;
span->aux.small.objects = sm;
span->object_count--;
} else {
/* Double free error. */
/* TODO: Anything? */
}
}
void SpanToSmallMemorySpan(SpanTable *span_table, Span *span, size_t cls) {
AMS_ASSERT(cls != 0 && span->page_class == 0);
const size_t span_idx = TlsHeapStatic::GetPageIndex(span->start.u - reinterpret_cast<uintptr_t>(span_table));
Span **table_entry = std::addressof(span_table->page_to_span[span_idx]);
span->page_class = cls;
for (size_t i = 0; i < span->num_pages; i++) {
table_entry[i] = span;
}
std::atomic_thread_fence(std::memory_order_release);
std::memset(std::addressof(span_table->pageclass_cache[span_idx]), cls, span->num_pages);
}
void SmallMemorySpanToSpan(SpanTable *span_table, Span *span) {
AMS_ASSERT(span->page_class != 0);
const size_t span_idx = TlsHeapStatic::GetPageIndex(span->start.u - reinterpret_cast<uintptr_t>(span_table));
Span **table_entry = std::addressof(span_table->page_to_span[span_idx]);
for (size_t i = 0; i < span->num_pages; i++) {
table_entry[i] = nullptr;
}
span->page_class = 0;
table_entry[0] = span;
table_entry[span->num_pages - 1] = span;
std::atomic_thread_fence(std::memory_order_release);
std::memset(std::addressof(span_table->pageclass_cache[span_idx]), 0, span->num_pages);
}
void InitSmallMemorySpan(Span *span, size_t cls, bool for_system, int id) {
AMS_ASSERT(cls != 0);
span->page_class = cls;
AMS_ASSERT(span->status == Span::Status_InUse);
if (for_system) {
span->status = Span::Status_InUseSystem;
}
span->aux.small.objects = span->start.sm;
span->object_count = 0;
span->id = id;
const size_t chunk_size = TlsHeapStatic::GetChunkSize(cls);
const size_t num_chunks = (span->num_pages * TlsHeapStatic::PageSize) / chunk_size;
AMS_ASSERT(num_chunks <= sizeof(span->aux.small.is_allocated) * BITSIZEOF(u8));
Span::SmallMemory *last = reinterpret_cast<Span::SmallMemory *>(span->start.u + num_chunks * chunk_size);
Span::SmallMemory *prev = reinterpret_cast<Span::SmallMemory *>(span->start.u);
for (Span::SmallMemory *cur = reinterpret_cast<Span::SmallMemory *>(span->start.u + chunk_size); cur != last; cur = reinterpret_cast<Span::SmallMemory *>(reinterpret_cast<uintptr_t>(cur) + chunk_size)) {
prev->next = cur;
prev = cur;
}
prev->next = nullptr;
std::memset(span->aux.small.is_allocated, 0, sizeof(span->aux.small.is_allocated));
}
}
errno_t TlsHeapCentral::Initialize(void *start, size_t size, bool use_virtual_memory) {
AMS_ASSERT(size > 0);
AMS_ASSERT(TlsHeapStatic::IsPageAligned(start));
AMS_ASSERT(TlsHeapStatic::IsPageAligned(size));
/* Clear lists. */
ListClearLink(std::addressof(m_spanpage_list));
ListClearLink(std::addressof(m_full_spanpage_list));
for (size_t i = 0; i < util::size(m_freelists); i++) {
ListClearLink(std::addressof(m_freelists[i]));
}
for (size_t i = 0; i < util::size(m_freelists_bitmap); i++) {
m_freelists_bitmap[i] = 0;
}
for (size_t i = 0; i < util::size(m_smallmem_lists); i++) {
ListClearLink(std::addressof(m_smallmem_lists[i]));
}
/* Setup span table. */
const size_t total_pages = TlsHeapStatic::GetPageIndex(size);
const size_t n = total_pages * sizeof(Span *);
m_span_table.total_pages = total_pages;
m_span_table.page_to_span = reinterpret_cast<Span **>(static_cast<u8 *>(start) + sizeof(*this));
m_span_table.pageclass_cache = static_cast<u8 *>(start) + sizeof(*this) + n;
u8 *meta_end = m_span_table.pageclass_cache + total_pages;
size_t num_physical_page_flags;
if (use_virtual_memory) {
m_physical_page_flags = meta_end;
const uintptr_t phys_start = TlsHeapStatic::AlignDownPhysicalPage(reinterpret_cast<uintptr_t>(start));
const uintptr_t phys_end = TlsHeapStatic::AlignUpPhysicalPage(reinterpret_cast<uintptr_t>(start) + size);
num_physical_page_flags = TlsHeapStatic::GetPhysicalPageIndex(phys_end - phys_start);
meta_end = TlsHeapStatic::AlignUpPage(meta_end + num_physical_page_flags);
} else {
m_physical_page_flags = nullptr;
num_physical_page_flags = 0;
meta_end = TlsHeapStatic::AlignUpPage(meta_end);
}
AMS_ASSERT(TlsHeapStatic::IsPageAligned(meta_end));
if (use_virtual_memory) {
const uintptr_t phys_end = TlsHeapStatic::AlignUpPhysicalPage(reinterpret_cast<uintptr_t>(meta_end) + TlsHeapStatic::PageSize);
size_t phys_size = phys_end - reinterpret_cast<uintptr_t>(start);
phys_size = std::min(phys_size, size);
if (auto err = AllocatePhysicalMemory(start, phys_size); err != 0) {
m_span_table.total_pages = 0;
return err;
}
std::memset(m_physical_page_flags, 0, num_physical_page_flags);
std::memset(m_physical_page_flags, 1, TlsHeapStatic::GetPhysicalPageIndex(phys_end) - TlsHeapStatic::GetPhysicalPageIndex(reinterpret_cast<uintptr_t>(start)));
}
std::memset(m_span_table.page_to_span, 0, n);
std::memset(m_span_table.pageclass_cache, 0, total_pages);
SpanPage *span_page = reinterpret_cast<SpanPage *>(meta_end);
InitializeSpanPage(span_page);
ListInsertAfter(std::addressof(m_spanpage_list), span_page);
meta_end += TlsHeapStatic::PageSize;
AMS_ASSERT(TlsHeapStatic::IsPageAligned(meta_end));
/* Setup the spans. */
Span *span = this->AllocateSpanFromSpanPage(span_page);
AMS_ASSERT(span != nullptr);
Span *span_admin = this->AllocateSpanFromSpanPage(span_page);
AMS_ASSERT(span_admin != nullptr);
span_page->info.is_sticky = 1;
span->start.u = reinterpret_cast<uintptr_t>(meta_end);
span->num_pages = TlsHeapStatic::GetPageIndex(reinterpret_cast<uintptr_t>(start) + size - reinterpret_cast<uintptr_t>(meta_end));
span->aux.small.objects = nullptr;
span->object_count = 0;
span->status = Span::Status_InFreeList;
span->id = 0;
span_page->info.span_of_spanpage.start.u = reinterpret_cast<uintptr_t>(span_page);
span_page->info.span_of_spanpage.num_pages = 1;
span_page->info.span_of_spanpage.aux.small.objects = nullptr;
span_page->info.span_of_spanpage.object_count = 0;
span_page->info.span_of_spanpage.status = Span::Status_InUseSystem;
span_page->info.span_of_spanpage.id = 0;
span_admin->start.u = reinterpret_cast<uintptr_t>(start);
span_admin->num_pages = TlsHeapStatic::GetPageIndex(reinterpret_cast<uintptr_t>(span_page) - reinterpret_cast<uintptr_t>(start));
span_admin->aux.small.objects = nullptr;
span_admin->object_count = 0;
span_admin->status = Span::Status_InUseSystem;
span_admin->id = 0;
RegisterSpan(std::addressof(m_span_table), span_admin);
RegisterSpan(std::addressof(m_span_table), std::addressof(span_page->info.span_of_spanpage));
RegisterSpan(std::addressof(m_span_table), span);
this->AddToFreeBlockList(span);
m_num_threads = 1;
m_static_thread_quota = std::min<size_t>((m_span_table.total_pages * TlsHeapStatic::PageSize) / sizeof(void *), 2_MB);
m_dynamic_thread_quota = m_static_thread_quota;
m_use_virtual_memory = use_virtual_memory;
return 0;
}
bool TlsHeapCentral::IsClean() {
std::scoped_lock lk(m_lock);
this->MakeFreeSpan(std::numeric_limits<size_t>::max());
Span *span = this->GetFirstSpan();
Span *next = GetNextSpan(std::addressof(m_span_table), span);
if (next && next->status == Span::Status_InFreeList && GetNextSpan(std::addressof(m_span_table), next) == nullptr) {
return true;
} else {
return false;
}
}
errno_t TlsHeapCentral::ReallocateLargeMemory(void *ptr, size_t size, void **p) {
if (!TlsHeapStatic::IsPageAligned(ptr)) {
return EFAULT;
}
AMS_ASSERT(size <= MaxSize);
/* NOTE: This function uses locks unsafely (unscoped) */
m_lock.Lock();
Span *ptr_span = GetSpanFromPointer(std::addressof(m_span_table), ptr);
if (!ptr_span) {
AMS_ASSERT(ptr_span != nullptr);
m_lock.Unlock();
return EFAULT;
}
const size_t num_pages = TlsHeapStatic::GetPageIndex(size + TlsHeapStatic::PageSize - 1);
if (ptr_span->num_pages != num_pages) {
if (ptr_span->num_pages >= num_pages) {
Span *span = this->AllocateSpanStruct();
if (span != nullptr) {
span->start.u = ptr_span->start.u + (num_pages * TlsHeapStatic::PageSize);
span->num_pages = ptr_span->num_pages - num_pages;
span->id = 0;
span->status = Span::Status_InUse;
ChangeRangeOfSpan(std::addressof(m_span_table), ptr_span, ptr_span->start.u, num_pages);
RegisterSpan(std::addressof(m_span_table), span);
this->FreePagesImpl(span);
}
} else {
Span *next_span = GetNextSpan(std::addressof(m_span_table), ptr_span);
if (!next_span || next_span->status != Span::Status_InFreeList || next_span->num_pages < num_pages - ptr_span->num_pages) {
m_lock.Unlock();
m_lock.Lock();
Span *span = this->AllocatePagesImpl(num_pages);
if (span) {
*p = span->start.p;
std::memcpy(std::addressof(span->aux.large), std::addressof(ptr_span->aux.large), sizeof(ptr_span->aux.large));
} else {
*p = nullptr;
}
m_lock.Unlock();
if (*p == nullptr) {
return ENOMEM;
}
std::memcpy(*p, ptr, num_pages * TlsHeapStatic::PageSize);
m_lock.Lock();
this->FreePagesImpl(ptr_span);
m_lock.Unlock();
return 0;
}
if (m_use_virtual_memory && this->AllocatePhysical(next_span->start.p, (num_pages - ptr_span->num_pages) * TlsHeapStatic::PageSize)) {
m_lock.Unlock();
return ENOMEM;
}
this->RemoveFromFreeBlockList(next_span);
if (next_span->num_pages == num_pages - ptr_span->num_pages) {
UnregisterSpan(std::addressof(m_span_table), next_span);
ChangeRangeOfSpan(std::addressof(m_span_table), ptr_span, ptr_span->start.u, num_pages);
SpanPage *sp = GetSpanPage(next_span);
this->FreeSpanToSpanPage(next_span, sp);
this->DestroySpanPageIfEmpty(sp, false);
} else {
const uintptr_t new_end = ptr_span->start.u + num_pages * TlsHeapStatic::PageSize;
const size_t new_num_pages = next_span->num_pages - (num_pages - ptr_span->num_pages);
ChangeRangeOfSpan(std::addressof(m_span_table), next_span, new_end, new_num_pages);
ChangeRangeOfSpan(std::addressof(m_span_table), ptr_span, ptr_span->start.u, num_pages);
this->MergeIntoFreeList(next_span);
}
}
}
*p = ptr;
m_lock.Unlock();
return 0;
}
errno_t TlsHeapCentral::ShrinkLargeMemory(void *ptr, size_t size) {
if (!TlsHeapStatic::IsPageAligned(ptr)) {
return EFAULT;
}
AMS_ASSERT(size <= MaxSize);
std::scoped_lock lk(m_lock);
Span *ptr_span = GetSpanFromPointer(std::addressof(m_span_table), ptr);
if (!ptr_span) {
AMS_ASSERT(ptr_span != nullptr);
return EFAULT;
}
const size_t num_pages = TlsHeapStatic::GetPageIndex(size + TlsHeapStatic::PageSize - 1);
if (ptr_span->num_pages != num_pages) {
if (ptr_span->num_pages < num_pages) {
return EINVAL;
}
Span *span = this->AllocateSpanStruct();
if (span != nullptr) {
span->start.u = ptr_span->start.u + (num_pages * TlsHeapStatic::PageSize);
span->num_pages = ptr_span->num_pages - num_pages;
span->id = 0;
span->status = Span::Status_InUse;
ChangeRangeOfSpan(std::addressof(m_span_table), ptr_span, ptr_span->start.u, num_pages);
RegisterSpan(std::addressof(m_span_table), span);
this->FreePagesImpl(span);
}
}
return 0;
}
void TlsHeapCentral::CalculateHeapHash(HeapHash *out) {
size_t alloc_count = 0;
size_t alloc_size = 0;
size_t hash = 0;
{
std::scoped_lock lk(m_lock);
for (Span *span = GetSpanFromPointer(std::addressof(m_span_table), this); span != nullptr; span = GetNextSpan(std::addressof(m_span_table), span)) {
if (span->status != Span::Status_InUse) {
continue;
}
const size_t size = span->num_pages * TlsHeapStatic::PageSize;
if (span->page_class == 0) {
alloc_count++;
alloc_size += size;
hash += std::hash<size_t>{}(size) + std::hash<size_t>{}(span->start.u);
} else {
const size_t chunk_size = TlsHeapStatic::GetChunkSize(span->page_class);
const size_t n = size / chunk_size;
AMS_ASSERT(n <= TlsHeapStatic::PageSize);
static_assert(util::IsAligned(TlsHeapStatic::PageSize, BITSIZEOF(FreeListAvailableWord)));
FreeListAvailableWord flags[TlsHeapStatic::PageSize / BITSIZEOF(FreeListAvailableWord)];
std::memset(flags, 0, sizeof(flags));
for (Span::SmallMemory *sm = span->aux.small.objects; sm != nullptr; sm = sm->next) {
const size_t idx = (reinterpret_cast<uintptr_t>(sm) - span->start.u) / chunk_size;
flags[FreeListAvailableIndex(idx)] |= FreeListAvailableMask(idx);
}
for (size_t i = 0; i < n; i++) {
if (!(flags[FreeListAvailableIndex(i)] & FreeListAvailableMask(i))) {
alloc_count++;
alloc_size += chunk_size;
hash += std::hash<size_t>{}(chunk_size) + std::hash<size_t>{}(span->start.u + chunk_size * n);
}
}
}
}
}
out->alloc_count = alloc_count;
out->alloc_size = alloc_size;
out->hash = hash;
}
SpanPage *TlsHeapCentral::AllocateSpanPage() {
Span *span = this->SearchFreeSpan(1);
if (span == nullptr) {
return nullptr;
}
AMS_ASSERT(span->page_class == 0);
if (m_use_virtual_memory && this->AllocatePhysical(span->start.p, TlsHeapStatic::PageSize) != 0) {
return nullptr;
}
SpanPage *sp = static_cast<SpanPage *>(span->start.p);
InitializeSpanPage(sp);
Span *new_span = GetSpanPageSpan(sp);
if (span->num_pages == 1) {
this->RemoveFromFreeBlockList(span);
MigrateSpan(std::addressof(m_span_table), span, new_span);
AMS_ASSERT(new_span->num_pages == 1);
new_span->status = Span::Status_InUseSystem;
SpanPage *sp_of_span = GetSpanPage(span);
this->FreeSpanToSpanPage(span, sp_of_span);
this->DestroySpanPageIfEmpty(sp_of_span, false);
} else {
new_span->start.u = span->start.u;
new_span->num_pages = 1;
new_span->status = Span::Status_InUseSystem;
new_span->id = 0;
if (span->num_pages - 1 < FreeListCount) {
this->RemoveFromFreeBlockList(span);
}
ChangeRangeOfSpan(std::addressof(m_span_table), span, span->start.u + TlsHeapStatic::PageSize, span->num_pages - 1);
RegisterSpan(std::addressof(m_span_table), new_span);
if (span->num_pages < FreeListCount) {
this->AddToFreeBlockList(span);
}
}
ListInsertAfter(std::addressof(m_spanpage_list), sp);
return sp;
}
Span *TlsHeapCentral::AllocateSpanFromSpanPage(SpanPage *sp) {
const size_t span_idx = __builtin_clzll(~sp->info.alloc_bitmap);
AMS_ASSERT(span_idx < SpanPage::MaxSpanCount);
constexpr u64 TopBit = static_cast<u64>(1) << (BITSIZEOF(u64) - 1);
sp->info.alloc_bitmap |= (TopBit >> span_idx);
sp->info.free_count--;
Span *span = std::addressof(sp->spans[span_idx]);
ListClearLink(span);
span->status = Span::Status_NotUsed;
span->page_class = 0;
span->object_count = 0;
if (sp->info.free_count == 0) {
ListRemoveSelf(sp);
ListInsertAfter(std::addressof(m_full_spanpage_list), sp);
}
return span;
}
Span *TlsHeapCentral::SplitSpan(Span *span, size_t num_pages, Span *new_span) {
AMS_ASSERT(span->status == Span::Status_InFreeList);
AMS_ASSERT(span->num_pages > num_pages);
const size_t remaining_pages = span->num_pages - num_pages;
uintptr_t new_start, old_start;
if (num_pages < FreeListCount) {
new_start = span->start.u;
old_start = span->start.u + (num_pages * TlsHeapStatic::PageSize);
} else {
new_start = span->start.u + (remaining_pages * TlsHeapStatic::PageSize);
old_start = span->start.u;
}
if (remaining_pages >= FreeListCount) {
ChangeRangeOfSpan(std::addressof(m_span_table), span, old_start, remaining_pages);
} else {
this->RemoveFromFreeBlockList(span);
ChangeRangeOfSpan(std::addressof(m_span_table), span, old_start, remaining_pages);
this->AddToFreeBlockList(span);
}
new_span->start.u = new_start;
new_span->num_pages = num_pages;
new_span->page_class = 0;
new_span->status = Span::Status_InUse;
new_span->id = 0;
new_span->aux.large_clear.zero = 0;
span->aux.large_clear.zero = 0;
if (m_use_virtual_memory && this->AllocatePhysical(new_span->start.p, new_span->num_pages * TlsHeapStatic::PageSize) != 0) {
new_span->status = Span::Status_InFreeList;
this->MergeIntoFreeList(new_span);
return nullptr;
}
RegisterSpan(std::addressof(m_span_table), new_span);
return new_span;
}
void TlsHeapCentral::MergeFreeSpans(Span *span, Span *span_to_merge, uintptr_t start) {
const size_t total_pages = span->num_pages + span_to_merge->num_pages;
UnregisterSpan(std::addressof(m_span_table), span_to_merge);
SpanPage *span_page = GetSpanPage(span_to_merge);
this->FreeSpanToSpanPage(span_to_merge, span_page);
ChangeRangeOfSpan(std::addressof(m_span_table), span, start, total_pages);
}
bool TlsHeapCentral::DestroySpanPageIfEmpty(SpanPage *sp, bool full) {
if (sp->info.is_sticky) {
if (!(full || sp->info.free_count > 0x10)) {
return false;
}
if (!sp->info.free_count) {
return false;
}
size_t first = this->FreeListFirstNonEmpty(0);
while (first < FreeListCount) {
for (Span *target = ListGetNext(std::addressof(m_freelists[first])); target; target = ListGetNext(target)) {
AMS_ASSERT(target->status == Span::Status_InFreeList);
SpanPage *target_sp = GetSpanPage(target);
if (target_sp != sp) {
Span *new_span = this->AllocateSpanFromSpanPage(sp);
AMS_ASSERT(new_span != nullptr);
MigrateSpan(std::addressof(m_span_table), target, new_span);
this->FreeSpanToSpanPage(target, target_sp);
this->DestroySpanPageIfEmpty(target_sp, full);
}
}
first = this->FreeListFirstNonEmpty(first + 1);
}
return false;
} else if (sp->info.free_count == SpanPage::MaxSpanCount) {
if (!ListGetNext(sp) && !ListGetPrev(sp)) {
return false;
}
SpanPage *other_sp = GetSpanPage(this->GetFirstSpan());
SpanPage *target;
if (other_sp->info.free_count > 0x10) {
target = other_sp;
} else {
for (target = ListGetNext(std::addressof(m_spanpage_list)); target && (target == sp || !target->info.free_count); target = ListGetNext(target)) {
/* ... */
}
if (!target) {
if (!other_sp->info.free_count) {
return false;
}
target = other_sp;
}
}
Span *new_span = this->AllocateSpanFromSpanPage(target);
AMS_ASSERT(new_span != nullptr);
MigrateSpan(std::addressof(m_span_table), GetSpanPageSpan(sp), new_span);
ListRemoveSelf(sp);
this->FreePagesImpl(new_span);
return true;
} else {
return false;
}
}
Span *TlsHeapCentral::GetFirstSpan() const {
Span *span = GetSpanFromPointer(std::addressof(m_span_table), reinterpret_cast<const void *>(this));
AMS_ASSERT(span != nullptr);
return GetNextSpan(std::addressof(m_span_table), span);
}
Span *TlsHeapCentral::MakeFreeSpan(size_t num_pages) {
while (true) {
SpanPage *sp;
for (sp = ListGetNext(std::addressof(m_spanpage_list)); sp && !this->DestroySpanPageIfEmpty(sp, true); sp = ListGetNext(sp)) {
/* ... */
}
if (!sp) {
break;
}
if (Span *span = this->SearchFreeSpan(num_pages); span != nullptr) {
return span;
}
}
return nullptr;
}
Span *TlsHeapCentral::SearchFreeSpan(size_t num_pages) const {
size_t start = FreeListCount - 1;
if (num_pages < FreeListCount) {
start = this->FreeListFirstNonEmpty(num_pages - 1);
if (start == FreeListCount) {
return nullptr;
}
}
Span *cur = ListGetNext(std::addressof(m_freelists[start]));
Span *best = cur;
if (start == FreeListCount - 1) {
if (num_pages >= FreeListCount) {
best = nullptr;
while (cur) {
if (num_pages <= cur->num_pages) {
if (best) {
if (cur->num_pages >= best->num_pages) {
if (cur->num_pages == best->num_pages && cur->start.u < best->start.u) {
best = cur;
}
} else {
best = cur;
}
} else {
best = cur;
}
}
cur = ListGetNext(cur);
}
} else {
while (cur) {
if (cur->num_pages >= best->num_pages) {
if (cur->num_pages == best->num_pages && cur->start.u < best->start.u) {
best = cur;
}
} else {
best = cur;
}
cur = ListGetNext(cur);
}
}
}
if (best != nullptr) {
AMS_ASSERT(best->status == Span::Status_InFreeList);
}
return best;
}
void TlsHeapCentral::FreeSpanToSpanPage(Span *span, SpanPage *sp) {
span->status = Span::Status_NotUsed;
const size_t span_idx = span - sp->spans;
constexpr u64 TopBit = static_cast<u64>(1) << (BITSIZEOF(u64) - 1);
sp->info.alloc_bitmap &= ~(TopBit >> span_idx);
if ((++(sp->info.free_count)) == 1) {
ListRemoveSelf(sp);
ListInsertAfter(std::addressof(m_spanpage_list), sp);
}
}
void TlsHeapCentral::FreeSpanToSpanPage(Span *span) {
return this->FreeSpanToSpanPage(span, GetSpanPage(span));
}
void TlsHeapCentral::MergeIntoFreeList(Span *&span) {
AMS_ASSERT(!span->list_prev && !span->list_next);
AMS_ASSERT(span->status != Span::Status_InUse);
Span *prev_span = GetPrevSpan(std::addressof(m_span_table), span);
Span *next_span = GetNextSpan(std::addressof(m_span_table), span);
const bool prev_free = prev_span && prev_span->status == Span::Status_InFreeList;
const bool prev_small = prev_span && prev_span->num_pages < FreeListCount;
const bool next_free = next_span && next_span->status == Span::Status_InFreeList;
const bool next_small = next_span && next_span->num_pages < FreeListCount;
if (prev_free) {
if (next_free) {
if (prev_small) {
if (next_small) {
this->RemoveFromFreeBlockList(prev_span);
this->RemoveFromFreeBlockList(next_span);
this->MergeFreeSpans(prev_span, span, prev_span->start.u);
this->MergeFreeSpans(prev_span, next_span, prev_span->start.u);
this->AddToFreeBlockList(prev_span);
span = prev_span;
} else {
this->RemoveFromFreeBlockList(prev_span);
this->MergeFreeSpans(prev_span, span, prev_span->start.u);
this->MergeFreeSpans(next_span, prev_span, prev_span->start.u);
span = next_span;
}
} else {
this->RemoveFromFreeBlockList(next_span);
this->MergeFreeSpans(prev_span, span, prev_span->start.u);
this->MergeFreeSpans(prev_span, next_span, prev_span->start.u);
span = prev_span;
}
} else {
if (prev_small) {
this->RemoveFromFreeBlockList(prev_span);
this->MergeFreeSpans(prev_span, span, prev_span->start.u);
this->AddToFreeBlockList(prev_span);
} else {
this->MergeFreeSpans(prev_span, span, prev_span->start.u);
}
span = prev_span;
}
} else if (next_free) {
if (next_small) {
this->RemoveFromFreeBlockList(next_span);
this->MergeFreeSpans(span, next_span, span->start.u);
this->AddToFreeBlockList(span);
} else {
this->MergeFreeSpans(next_span, span, span->start.u);
span = next_span;
}
} else {
this->AddToFreeBlockList(span);
}
AMS_ASSERT(GetSpanPageSpan(GetSpanPage(span)) != span);
AMS_ASSERT(span->status == Span::Status_InFreeList);
}
errno_t TlsHeapCentral::AllocatePhysical(void *start, size_t size) {
/* TODO: Implement physical tls heap central logic. */
AMS_UNUSED(start, size);
return 0;
}
errno_t TlsHeapCentral::FreePhysical(void *start, size_t size) {
const uintptr_t start_alignup = TlsHeapStatic::AlignUpPhysicalPage(reinterpret_cast<uintptr_t>(start));
const uintptr_t end_aligndown = TlsHeapStatic::AlignDownPhysicalPage(reinterpret_cast<uintptr_t>(start) + size);
if (end_aligndown <= start_alignup) {
return 0;
}
const uintptr_t phys_heap_start = TlsHeapStatic::AlignDownPhysicalPage(reinterpret_cast<uintptr_t>(this));
const uintptr_t i = TlsHeapStatic::GetPhysicalPageIndex(start_alignup - phys_heap_start);
const uintptr_t idx_end = TlsHeapStatic::GetPhysicalPageIndex(end_aligndown - phys_heap_start);
AMS_ASSERT(i < idx_end);
if (i + 1 == idx_end) {
if (m_physical_page_flags[i]) {
m_physical_page_flags[i] = 2;
}
} else {
const void *set_flag = util::Memchr(std::addressof(m_physical_page_flags[i]), 1, idx_end - i);
if (set_flag) {
const uintptr_t set_idx = reinterpret_cast<const u8 *>(set_flag) - m_physical_page_flags;
const void *lst_flag = util::Memrchr(std::addressof(m_physical_page_flags[set_idx]), 1, idx_end - set_idx);
const uintptr_t lst_idx = (lst_flag) ? (reinterpret_cast<const u8 *>(lst_flag) - m_physical_page_flags + 1) : idx_end;
std::memset(std::addressof(m_physical_page_flags[set_idx]), 2, lst_idx - set_idx);
}
}
return 0;
}
Span *TlsHeapCentral::AllocatePagesImpl(size_t num_pages) {
if (num_pages >= m_span_table.total_pages / 4) {
this->MakeFreeSpan(std::numeric_limits<size_t>::max());
}
Span *span = this->SearchFreeSpan(num_pages);
if (span == nullptr) {
span = this->MakeFreeSpan(num_pages);
if (span == nullptr) {
return nullptr;
}
}
AMS_ASSERT(span->status == Span::Status_InFreeList);
if (num_pages == span->num_pages) {
if (m_use_virtual_memory && this->AllocatePhysical(span->start.p, span->num_pages * TlsHeapStatic::PageSize) != 0) {
return nullptr;
} else {
this->RemoveFromFreeBlockList(span);
span->status = Span::Status_InUse;
span->id = 0;
span->aux.large_clear.zero = 0;
return span;
}
} else {
/* Save the extents of the free span we found. */
auto * const prev_ptr = span->start.p;
const size_t prev_pages = span->num_pages;
/* Allocate a new span struct. */
Span *new_span = this->AllocateSpanStruct();
if (new_span == nullptr) {
return nullptr;
}
auto new_span_guard = SCOPE_GUARD { this->FreeSpanToSpanPage(new_span); };
/* Allocating the new span potentially invalidates the span we were looking at, so find the span for it in the table. */
span = GetSpanFromPointer(std::addressof(m_span_table), prev_ptr);
const size_t cur_pages = span->num_pages;
/* If the span was partially allocated, we need to find a new one that's big enough. */
if (cur_pages != prev_pages) {
span = this->SearchFreeSpan(num_pages);
if (span == nullptr) {
return nullptr;
}
}
/* If the span is big enough to split (span->num_pages > num_pages), we want to split it. */
/* span->num_pages > num_pages is true if the span wasn't partially allocated (cur_pages == prev_pages) */
/* OR if the new free span we found has num_pages > num_pages. Note that we know span->num_pages >= num_pages */
/* so this > condition can be expressed as span->num_pages != num_pages. */
if (cur_pages == prev_pages || num_pages != span->num_pages) {
/* We're going to use the new span for our split. */
new_span_guard.Cancel();
return this->SplitSpan(span, num_pages, new_span);
} else if (m_use_virtual_memory && this->AllocatePhysical(span->start.p, span->num_pages * TlsHeapStatic::PageSize) != 0) {
return nullptr;
} else {
this->RemoveFromFreeBlockList(span);
span->status = Span::Status_InUse;
span->id = 0;
span->aux.large_clear.zero = 0;
return span;
}
}
}
Span *TlsHeapCentral::AllocatePagesWithBigAlignImpl(size_t num_pages, size_t align) {
if (num_pages >= m_span_table.total_pages / 4) {
this->MakeFreeSpan(std::numeric_limits<size_t>::max());
}
Span *before_span = this->AllocateSpanStruct();
if (!before_span) {
return nullptr;
}
Span *after_span = this->AllocateSpanStruct();
if (!after_span) {
this->FreeSpanToSpanPage(before_span);
return nullptr;
}
AMS_ASSERT(align <= TlsHeapStatic::PageSize);
AMS_ASSERT(util::IsPowerOfTwo(align));
Span *span = this->SearchFreeSpan(num_pages);
if (span == nullptr) {
span = this->MakeFreeSpan(num_pages);
if (span == nullptr) {
this->FreeSpanToSpanPage(before_span);
this->FreeSpanToSpanPage(after_span);
return nullptr;
}
}
AMS_ASSERT(span->status == Span::Status_InFreeList);
const uintptr_t aligned_start = util::AlignUp(span->start.u, align);
if (m_use_virtual_memory && this->AllocatePhysical(reinterpret_cast<void *>(aligned_start), num_pages * TlsHeapStatic::PageSize) != 0) {
this->FreeSpanToSpanPage(before_span);
this->FreeSpanToSpanPage(after_span);
return nullptr;
} else if (aligned_start == span->start.u) {
/* We don't need the before span, but we do need the after span. */
this->FreeSpanToSpanPage(before_span);
after_span->start.u = aligned_start + num_pages * TlsHeapStatic::PageSize;
after_span->num_pages = span->num_pages - num_pages;
after_span->page_class = 0;
after_span->status = Span::Status_InFreeList;
after_span->id = 0;
this->RemoveFromFreeBlockList(span);
span->status = Span::Status_InUse;
span->aux.large_clear.zero = 0;
ChangeRangeOfSpan(std::addressof(m_span_table), span, aligned_start, num_pages);
RegisterSpan(std::addressof(m_span_table), after_span);
this->MergeIntoFreeList(after_span);
return span;
} else {
/* We need the before span. */
before_span->start.u = span->start.u;
before_span->num_pages = TlsHeapStatic::GetPageIndex(aligned_start - span->start.u);
before_span->page_class = 0;
before_span->status = Span::Status_InFreeList;
before_span->id = 0;
const size_t after_pages = span->num_pages - before_span->num_pages - num_pages;
if (after_pages) {
/* We need the after span. */
after_span->start.u = aligned_start + num_pages * TlsHeapStatic::PageSize;
after_span->num_pages = after_pages;
after_span->page_class = 0;
after_span->status = Span::Status_InFreeList;
after_span->id = 0;
this->RemoveFromFreeBlockList(span);
span->status = Span::Status_InUse;
span->aux.large_clear.zero = 0;
ChangeRangeOfSpan(std::addressof(m_span_table), span, aligned_start, num_pages);
RegisterSpan(std::addressof(m_span_table), before_span);
RegisterSpan(std::addressof(m_span_table), after_span);
this->MergeIntoFreeList(before_span);
this->MergeIntoFreeList(after_span);
return span;
} else {
/* We don't need the after span. */
this->FreeSpanToSpanPage(after_span);
this->RemoveFromFreeBlockList(span);
span->status = Span::Status_InUse;
span->aux.large_clear.zero = 0;
ChangeRangeOfSpan(std::addressof(m_span_table), span, aligned_start, num_pages);
RegisterSpan(std::addressof(m_span_table), before_span);
this->MergeIntoFreeList(before_span);
return span;
}
}
}
void TlsHeapCentral::FreePagesImpl(Span *span) {
AMS_ASSERT(span && span->page_class == 0);
if (span->status == Span::Status_InFreeList) {
/* Double free error. */
} else {
span->status = Span::Status_InFreeList;
if (m_use_virtual_memory) {
const uintptr_t start = span->start.u;
const uintptr_t end = span->start.u + (span->num_pages * TlsHeapStatic::PageSize);
uintptr_t start_alignup = TlsHeapStatic::AlignUpPhysicalPage(start);
uintptr_t end_aligndown = TlsHeapStatic::AlignDownPhysicalPage(end);
this->MergeIntoFreeList(span);
const uintptr_t new_start = span->start.u;
const uintptr_t new_end = span->start.u + (span->num_pages * TlsHeapStatic::PageSize);
if (start != start_alignup && new_start + TlsHeapStatic::PhysicalPageSize <= start_alignup) {
start_alignup -= TlsHeapStatic::PhysicalPageSize;
}
if (end != end_aligndown && end_aligndown + TlsHeapStatic::PhysicalPageSize <= new_end) {
end_aligndown += TlsHeapStatic::PhysicalPageSize;
}
if (start_alignup < end_aligndown) {
const auto err = this->FreePhysical(reinterpret_cast<void *>(start_alignup), end_aligndown - start_alignup);
AMS_ASSERT(err == 0);
AMS_UNUSED(err);
}
} else {
this->MergeIntoFreeList(span);
}
}
}
void *TlsHeapCentral::CacheSmallMemoryImpl(size_t cls, size_t align, bool for_system) {
AMS_ASSERT(cls != 0 && cls < TlsHeapStatic::NumClassInfo);
Span *span = ListGetNext(std::addressof(m_smallmem_lists[cls]));
while (true) {
if (for_system) {
while (span && span->status != Span::Status_InUseSystem) {
span = ListGetNext(span);
}
} else {
while (span && (span->status == Span::Status_InUseSystem || span->id)) {
span = ListGetNext(span);
}
}
if (!span) {
break;
}
void *mem = AllocateSmallMemory(span);
if (mem) {
if (!span->aux.small.objects) {
ListRemoveSelf(span);
}
return mem;
}
AMS_ASSERT(!span->aux.small.objects);
Span *old = span;
span = ListGetNext(span);
ListRemoveSelf(old);
}
Span *new_span = this->AllocatePagesImpl(TlsHeapStatic::GetNumPages(cls));
if (new_span) {
SpanToSmallMemorySpan(std::addressof(m_span_table), new_span, cls);
ListInsertAfter(std::addressof(m_smallmem_lists[cls]), new_span);
InitSmallMemorySpan(new_span, cls, for_system, 0);
void *mem = AllocateSmallMemory(new_span);
if (!new_span->aux.small.objects) {
ListRemoveSelf(new_span);
}
return mem;
} else {
for (size_t cur_cls = cls; cur_cls < TlsHeapStatic::NumClassInfo; cur_cls++) {
if (align == 0 || util::IsAligned(TlsHeapStatic::GetChunkSize(cur_cls), align)) {
span = ListGetNext(std::addressof(m_smallmem_lists[cur_cls]));
if (for_system) {
while (span && span->status != Span::Status_InUseSystem) {
span = ListGetNext(span);
}
} else {
while (span && (span->status == Span::Status_InUseSystem)) {
span = ListGetNext(span);
}
}
if (!span) {
continue;
}
void *mem = AllocateSmallMemory(span);
if (!mem) {
continue;
}
if (!span->aux.small.objects) {
ListRemoveSelf(span);
}
return mem;
}
}
return nullptr;
}
}
errno_t TlsHeapCentral::UncacheSmallMemoryImpl(void *ptr) {
Span *span = GetSpanFromPointer(std::addressof(m_span_table), ptr);
if (span && span->page_class) {
if (!span->aux.small.objects) {
ListInsertAfter(std::addressof(m_smallmem_lists[span->page_class]), span);
}
ReleaseSmallMemory(span, ptr);
if (!span->object_count) {
span->aux.small.objects = nullptr;
ListRemoveSelf(span);
AMS_ASSERT(span->page_class != 0);
SmallMemorySpanToSpan(std::addressof(m_span_table), span);
this->FreePagesImpl(span);
}
return 0;
} else {
AMS_ASSERT(span);
AMS_ASSERT(span->page_class == 0);
return EFAULT;
}
}
size_t TlsHeapCentral::CacheSmallMemoryListImpl(TlsHeapCache *cache, size_t *cls, size_t count, void **p, s32 cpu_id, size_t align) {
AMS_ASSERT(*cls != 0 && *cls < TlsHeapStatic::NumClassInfo);
Span::SmallMemory head = {};
Span::SmallMemory *hptr = std::addressof(head);
Span *span = ListGetNext(std::addressof(m_smallmem_lists[*cls]));
size_t n = 0;
while (span) {
if (span->status != Span::Status_InUseSystem && span->id == cpu_id) {
MangledSmallMemory memlist;
if (size_t num = AllocateSmallMemory(span, cache, count - n, std::addressof(memlist)); num != 0) {
hptr->next = memlist.from;
hptr = memlist.to;
memlist.to->next = nullptr;
n += num;
if (n >= count) {
if (!span->aux.small.objects) {
ListRemoveSelf(span);
}
*p = head.next;
return n;
}
}
AMS_ASSERT(span->aux.small.objects);
Span *old = span;
span = ListGetNext(span);
ListRemoveSelf(old);
} else {
span = ListGetNext(span);
}
}
Span *new_span = this->AllocatePagesImpl(TlsHeapStatic::GetNumPages(*cls));
if (new_span) {
SpanToSmallMemorySpan(std::addressof(m_span_table), new_span, *cls);
ListInsertAfter(std::addressof(m_smallmem_lists[*cls]), new_span);
InitSmallMemorySpan(new_span, *cls, false, cpu_id);
MangledSmallMemory memlist;
size_t num = AllocateSmallMemory(new_span, cache, count - n, std::addressof(memlist));
AMS_ASSERT(num > 0);
hptr->next = memlist.from;
hptr = memlist.to;
memlist.to->next = nullptr;
n += num;
if (!new_span->aux.small.objects) {
ListRemoveSelf(new_span);
}
*p = head.next;
return n;
} else if (head.next) {
*p = head.next;
return n;
} else {
for (size_t cur_cls = *cls; cur_cls < TlsHeapStatic::NumClassInfo; cur_cls++) {
if (align == 0 || util::IsAligned(TlsHeapStatic::GetChunkSize(cur_cls), align)) {
span = ListGetNext(std::addressof(m_smallmem_lists[cur_cls]));
while (span && (span->status == Span::Status_InUseSystem)) {
span = ListGetNext(span);
}
if (!span) {
continue;
}
void *mem = AllocateSmallMemory(span);
if (!mem) {
continue;
}
if (!span->aux.small.objects) {
ListRemoveSelf(span);
}
reinterpret_cast<Span::SmallMemory *>(mem)->next = nullptr;
*p = cache->ManglePointer(mem);
*cls = cur_cls;
return 1;
}
}
*p = nullptr;
return 0;
}
}
errno_t TlsHeapCentral::WalkAllocatedPointersImpl(HeapWalkCallback callback, void *user_data) {
errno_t err = ENOENT;
for (Span *span = GetSpanFromPointer(std::addressof(m_span_table), this); span != nullptr; span = GetNextSpan(std::addressof(m_span_table), span)) {
if (span->status != Span::Status_InUse) {
continue;
}
const size_t size = span->num_pages * TlsHeapStatic::PageSize;
if (span->page_class != 0) {
static_assert(util::IsAligned(TlsHeapStatic::PageSize, BITSIZEOF(FreeListAvailableWord)));
FreeListAvailableWord flags[TlsHeapStatic::PageSize / BITSIZEOF(FreeListAvailableWord)];
std::memset(flags, 0, sizeof(flags));
const size_t chunk_size = TlsHeapStatic::GetChunkSize(span->page_class);
const size_t n = size / chunk_size;
AMS_ASSERT(n <= TlsHeapStatic::PageSize);
if (n <= TlsHeapStatic::PageSize) {
for (Span::SmallMemory *sm = span->aux.small.objects; sm != nullptr; sm = sm->next) {
const size_t idx = (reinterpret_cast<uintptr_t>(sm) - span->start.u) / chunk_size;
flags[FreeListAvailableIndex(idx)] |= FreeListAvailableMask(idx);
}
for (size_t i = 0; i < n; i++) {
if (!(flags[FreeListAvailableIndex(i)] & FreeListAvailableMask(i))) {
if (s32 res = this->CallWalkCallback(callback, reinterpret_cast<void *>(span->start.u + chunk_size * i), chunk_size, user_data); res != 0) {
if (res >= 0) {
err = res;
break;
} else {
err = 0;
}
}
}
}
} else {
return EIO;
}
} else {
if (s32 res = this->CallWalkCallback(callback, span->start.p, size, user_data); res != 0) {
if (res >= 0) {
err = res;
break;
} else {
err = 0;
}
}
}
}
return err;
}
errno_t TlsHeapCentral::GetMappedMemStatsImpl(size_t *out_free_size, size_t *out_max_allocatable_size) {
if (!m_use_virtual_memory) {
return EOPNOTSUPP;
}
/* TODO: Is this worth supporting? */
AMS_UNUSED(out_free_size, out_max_allocatable_size);
return EOPNOTSUPP;
}
errno_t TlsHeapCentral::GetMemStatsImpl(TlsHeapMemStats *out) {
size_t max_allocatable_size = 0;
size_t free_size = 0;
size_t system_size = 0;
size_t allocated_size = 0;
size_t num_free_regions = 0;
size_t num_free_spans = 0;
size_t wip_allocatable_size = 0;
Span *span = GetSpanFromPointer(std::addressof(m_span_table), this);
while (span) {
const size_t size = span->num_pages * TlsHeapStatic::PageSize;
if (span->status == Span::Status_InUse || span->status == Span::Status_InUseSystem) {
/* Found a usable span, so end our contiguous run. */
max_allocatable_size = std::max(max_allocatable_size, wip_allocatable_size);
wip_allocatable_size = 0;
if (span->status == Span::Status_InUseSystem) {
system_size += size;
} else if (span->page_class && span->aux.small.objects) {
const size_t chunk_size = TlsHeapStatic::GetChunkSize(span->page_class);
const size_t used_size = chunk_size * span->object_count;
allocated_size += used_size;
free_size += size - used_size;
} else {
allocated_size += size;
}
} else {
/* Free span. */
free_size += size;
num_free_spans++;
if (wip_allocatable_size == 0) {
num_free_regions++;
}
wip_allocatable_size += size;
}
span = GetNextSpan(std::addressof(m_span_table), span);
}
max_allocatable_size = std::max(max_allocatable_size, wip_allocatable_size);
bool sp_full = true;
for (SpanPage *sp = ListGetNext(std::addressof(m_spanpage_list)); sp != nullptr; sp = ListGetNext(sp)) {
if (sp->info.is_sticky == 0 && CanAllocateSpan(sp)) {
sp_full = false;
break;
}
}
if (num_free_spans == 1 && allocated_size == 0) {
sp_full = false;
}
if (sp_full && num_free_regions < 2 && max_allocatable_size >= TlsHeapStatic::PageSize) {
max_allocatable_size -= TlsHeapStatic::PageSize;
}
if (max_allocatable_size < 3 * TlsHeapStatic::PageSize) {
max_allocatable_size = 0;
}
out->max_allocatable_size = max_allocatable_size;
out->free_size = free_size;
out->allocated_size = allocated_size;
out->system_size = system_size;
return 0;
}
void TlsHeapCentral::DumpImpl(DumpMode dump_mode, int fd, bool json) {
AMS_UNUSED(dump_mode, fd, json);
AMS_ABORT("Not yet implemented");
}
}
| 61,775
|
C++
|
.cpp
| 1,256
| 34.985669
| 215
| 0.527849
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,444
|
mem_impl_heap_tls_heap_cache.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/mem/impl/heap/mem_impl_heap_tls_heap_cache.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "mem_impl_heap_platform.hpp"
#include "mem_impl_heap_tls_heap_static.hpp"
#include "mem_impl_heap_tls_heap_cache.hpp"
#include "mem_impl_heap_tls_heap_central.hpp"
namespace ams::mem::impl::heap {
TlsHeapCache::TlsHeapCache(TlsHeapCentral *central, u32 option) {
/* Choose function impls based on option. */
if ((option & HeapOption_DisableCache) != 0) {
m_allocate = AllocateImpl<false>;
m_allocate_aligned = AllocateAlignedImpl<false>;
m_free = FreeImpl<false>;
m_free_with_size = FreeWithSizeImpl<false>;
m_get_allocation_size = GetAllocationSizeImpl<false>;
m_reallocate = ReallocateImpl<false>;
m_shrink = ShrinkImpl<false>;
} else {
m_allocate = AllocateImpl<true>;
m_allocate_aligned = AllocateAlignedImpl<true>;
m_free = FreeImpl<true>;
m_free_with_size = FreeWithSizeImpl<true>;
m_get_allocation_size = GetAllocationSizeImpl<true>;
m_reallocate = ReallocateImpl<true>;
m_shrink = ShrinkImpl<true>;
}
/* Generate random bytes to mangle pointers. */
if (auto err = gen_random(std::addressof(m_mangle_val), sizeof(m_mangle_val)); err != 0) {
s64 epoch_time;
epochtime(std::addressof(epoch_time));
m_mangle_val = reinterpret_cast<uintptr_t>(std::addressof(epoch_time)) ^ static_cast<u64>(epoch_time);
}
/* Set member variables. */
m_central = central;
m_total_heap_size = central->GetTotalHeapSize();
m_heap_option = option;
m_total_cached_size = 0;
m_largest_class = 0;
/* Setup chunks. */
for (size_t i = 0; i < TlsHeapStatic::NumClassInfo; i++) {
m_small_mem_lists[i] = nullptr;
m_cached_size[i] = 0;
m_chunk_count[i] = 1;
}
/* Set fixed chunk counts for particularly small chunks. */
m_chunk_count[1] = MaxChunkCount;
m_chunk_count[2] = MaxChunkCount;
m_chunk_count[3] = MaxChunkCount;
m_chunk_count[4] = MaxChunkCount / 2;
m_chunk_count[5] = MaxChunkCount / 2;
m_chunk_count[6] = MaxChunkCount / 2;
m_chunk_count[7] = MaxChunkCount / 4;
m_chunk_count[8] = MaxChunkCount / 4;
m_chunk_count[9] = MaxChunkCount / 4;
}
void TlsHeapCache::Finalize() {
/* Free all small mem lists. */
this->ReleaseAllCache();
/* Remove this cache from the owner central heap. */
m_central->RemoveThreadCache(this);
m_central->UncacheSmallMemory(this);
}
bool TlsHeapCache::CheckCache() const {
for (size_t i = 0; i < util::size(m_small_mem_lists); i++) {
void *ptr = m_small_mem_lists[i];
if (ptr) {
s64 depth = -static_cast<s64>(m_cached_size[i] / TlsHeapStatic::GetChunkSize(i));
while (ptr) {
ptr = *reinterpret_cast<void **>(this->ManglePointer(ptr));
if ((++depth) == 0) {
AMS_ASSERT(ptr == nullptr);
break;
}
}
}
}
return true;
}
void TlsHeapCache::ReleaseAllCache() {
for (size_t i = 0; i < util::size(m_small_mem_lists); i++) {
if (m_small_mem_lists[i]) {
m_central->UncacheSmallMemoryList(this, m_small_mem_lists[i]);
m_small_mem_lists[i] = nullptr;
m_cached_size[i] = 0;
}
}
m_total_cached_size = 0;
m_largest_class = 0;
}
template<>
void *TlsHeapCache::AllocateImpl<false>(TlsHeapCache *tls_heap_cache, size_t size) {
/* Validate allocation size. */
if (size == 0 || size > MaxSize) {
return nullptr;
}
if (const size_t cls = TlsHeapStatic::GetClassFromSize(size); cls != 0) {
AMS_ASSERT(static_cast<u32>(cls) < TlsHeapStatic::NumClassInfo);
return tls_heap_cache->m_central->CacheSmallMemory(cls);
} else {
/* If allocating a huge size, release our cache. */
if (size >= tls_heap_cache->m_total_heap_size / 4) {
tls_heap_cache->ReleaseAllCache();
}
return tls_heap_cache->m_central->CacheLargeMemory(size);
}
}
template<>
void *TlsHeapCache::AllocateImpl<true>(TlsHeapCache *tls_heap_cache, size_t size) {
/* Validate allocation size. */
if (size == 0 || size > MaxSize) {
return nullptr;
}
if (size_t cls = TlsHeapStatic::GetClassFromSize(size); cls != 0) {
AMS_ASSERT(static_cast<u32>(cls) < TlsHeapStatic::NumClassInfo);
/* Allocate a chunk. */
void *ptr = tls_heap_cache->m_small_mem_lists[cls];
if (ptr == nullptr) {
const size_t prev_cls = cls;
size_t count = tls_heap_cache->m_chunk_count[cls];
size_t n = tls_heap_cache->m_central->CacheSmallMemoryList(tls_heap_cache, std::addressof(cls), count, std::addressof(ptr));
if (n == 0) {
return nullptr;
}
if (cls == prev_cls) {
if (count < MaxChunkCount) {
count++;
}
tls_heap_cache->m_chunk_count[cls] = std::max(count, n);
} else {
AMS_ASSERT(n == 1);
}
const size_t csize = TlsHeapStatic::GetChunkSize(cls) * (n - 1);
tls_heap_cache->m_cached_size[cls] += csize;
if (tls_heap_cache->m_cached_size[cls] > tls_heap_cache->m_cached_size[tls_heap_cache->m_largest_class]) {
tls_heap_cache->m_largest_class = cls;
}
tls_heap_cache->m_total_cached_size += csize;
}
/* Demangle our pointer, update free list. */
ptr = tls_heap_cache->ManglePointer(ptr);
tls_heap_cache->m_small_mem_lists[cls] = *reinterpret_cast<void **>(ptr);
return ptr;
} else {
/* If allocating a huge size, release our cache. */
if (size >= tls_heap_cache->m_total_heap_size / 4) {
tls_heap_cache->ReleaseAllCache();
}
return tls_heap_cache->m_central->CacheLargeMemory(size);
}
}
template<>
void *TlsHeapCache::AllocateAlignedImpl<false>(TlsHeapCache *tls_heap_cache, size_t size, size_t align) {
/* Ensure valid alignment. */
if (!util::IsPowerOfTwo(align)) {
return nullptr;
}
/* NOTE: Nintendo does not check size == 0 here, despite doing so in Alloc */
if (size > MaxSize) {
return nullptr;
}
/* Handle big alignment. */
if (align > TlsHeapStatic::PageSize) {
return tls_heap_cache->m_central->CacheLargeMemoryWithBigAlign(util::AlignUp(size, TlsHeapStatic::PageSize), align);
}
const size_t real_size = TlsHeapStatic::GetRealSizeFromSizeAndAlignment(util::AlignUp(size, align), align);
if (const size_t cls = TlsHeapStatic::GetClassFromSize(real_size); cls != 0) {
if (real_size == 0) {
return nullptr;
}
AMS_ASSERT(static_cast<u32>(cls) < TlsHeapStatic::NumClassInfo);
return tls_heap_cache->m_central->CacheSmallMemory(cls, align);
} else {
/* If allocating a huge size, release our cache. */
if (real_size >= tls_heap_cache->m_total_heap_size / 4) {
tls_heap_cache->ReleaseAllCache();
}
return tls_heap_cache->m_central->CacheLargeMemory(real_size);
}
}
template<>
void *TlsHeapCache::AllocateAlignedImpl<true>(TlsHeapCache *tls_heap_cache, size_t size, size_t align) {
/* Ensure valid alignment. */
if (!util::IsPowerOfTwo(align)) {
return nullptr;
}
/* NOTE: Nintendo does not check size == 0 here, despite doing so in Alloc */
if (size > MaxSize) {
return nullptr;
}
/* Handle big alignment. */
if (align > TlsHeapStatic::PageSize) {
return tls_heap_cache->m_central->CacheLargeMemoryWithBigAlign(util::AlignUp(size, TlsHeapStatic::PageSize), align);
}
const size_t real_size = TlsHeapStatic::GetRealSizeFromSizeAndAlignment(util::AlignUp(size, align), align);
if (size_t cls = TlsHeapStatic::GetClassFromSize(real_size); cls != 0) {
if (real_size == 0) {
return nullptr;
}
AMS_ASSERT(static_cast<u32>(cls) < TlsHeapStatic::NumClassInfo);
/* Allocate a chunk. */
void *ptr = tls_heap_cache->m_small_mem_lists[cls];
if (ptr == nullptr) {
const size_t prev_cls = cls;
size_t count = tls_heap_cache->m_chunk_count[cls];
size_t n = tls_heap_cache->m_central->CacheSmallMemoryList(tls_heap_cache, std::addressof(cls), count, std::addressof(ptr), align);
if (n == 0) {
return nullptr;
}
if (cls == prev_cls) {
if (count < MaxChunkCount) {
count++;
}
tls_heap_cache->m_chunk_count[cls] = std::max(count, n);
} else {
AMS_ASSERT(n == 1);
}
const s32 csize = TlsHeapStatic::GetChunkSize(cls) * (n - 1);
tls_heap_cache->m_total_cached_size += csize;
tls_heap_cache->m_cached_size[cls] += csize;
if (tls_heap_cache->m_cached_size[cls] > tls_heap_cache->m_cached_size[tls_heap_cache->m_largest_class]) {
tls_heap_cache->m_largest_class = cls;
}
}
/* Demangle our pointer, update free list. */
ptr = tls_heap_cache->ManglePointer(ptr);
tls_heap_cache->m_small_mem_lists[cls] = *reinterpret_cast<void **>(ptr);
return ptr;
} else {
/* If allocating a huge size, release our cache. */
if (size >= tls_heap_cache->m_total_heap_size / 4) {
tls_heap_cache->ReleaseAllCache();
}
return tls_heap_cache->m_central->CacheLargeMemory(size);
}
}
template<>
errno_t TlsHeapCache::FreeImpl<false>(TlsHeapCache *tls_heap_cache, void *ptr) {
const auto cls = tls_heap_cache->m_central->GetClassFromPointer(ptr);
if (cls == 0) {
return tls_heap_cache->m_central->UncacheLargeMemory(ptr);
}
AMS_ASSERT(static_cast<u32>(cls) < TlsHeapStatic::NumClassInfo);
if (cls >= 0) {
return tls_heap_cache->m_central->UncacheSmallMemory(ptr);
} else if (ptr == nullptr) {
return 0;
} else {
return EFAULT;
}
}
template<>
errno_t TlsHeapCache::FreeImpl<true>(TlsHeapCache *tls_heap_cache, void *ptr) {
const auto cls = tls_heap_cache->m_central->GetClassFromPointer(ptr);
if (cls == 0) {
return tls_heap_cache->m_central->UncacheLargeMemory(ptr);
}
AMS_ASSERT(static_cast<u32>(cls) < TlsHeapStatic::NumClassInfo);
if (cls >= 0) {
*reinterpret_cast<void **>(ptr) = tls_heap_cache->m_small_mem_lists[cls];
tls_heap_cache->m_small_mem_lists[cls] = tls_heap_cache->ManglePointer(ptr);
const s32 csize = TlsHeapStatic::GetChunkSize(cls);
tls_heap_cache->m_total_cached_size += csize;
tls_heap_cache->m_cached_size[cls] += csize;
if (tls_heap_cache->m_cached_size[cls] > tls_heap_cache->m_cached_size[tls_heap_cache->m_largest_class]) {
tls_heap_cache->m_largest_class = cls;
}
errno_t err = 0;
if (!tls_heap_cache->m_central->CheckCachedSize(tls_heap_cache->m_total_cached_size)) {
tls_heap_cache->m_central->UncacheSmallMemoryList(tls_heap_cache, tls_heap_cache->m_small_mem_lists[tls_heap_cache->m_largest_class]);
tls_heap_cache->m_small_mem_lists[tls_heap_cache->m_largest_class] = nullptr;
tls_heap_cache->m_total_cached_size -= tls_heap_cache->m_cached_size[tls_heap_cache->m_largest_class];
tls_heap_cache->m_cached_size[tls_heap_cache->m_largest_class] = 0;
s32 largest_class = 0;
s32 biggest_size = -1;
for (size_t i = 0; i < TlsHeapStatic::NumClassInfo; i++) {
if (biggest_size < tls_heap_cache->m_cached_size[i]) {
biggest_size = tls_heap_cache->m_cached_size[i];
largest_class = static_cast<s32>(i);
}
}
tls_heap_cache->m_largest_class = largest_class;
}
return err;
} else if (ptr == nullptr) {
return 0;
} else {
return EFAULT;
}
}
template<>
errno_t TlsHeapCache::FreeWithSizeImpl<false>(TlsHeapCache *tls_heap_cache, void *ptr, size_t size) {
if (ptr == nullptr) {
return 0;
}
const size_t cls = TlsHeapStatic::GetClassFromSize(size);
if (cls == 0) {
return tls_heap_cache->m_central->UncacheLargeMemory(ptr);
} else {
return tls_heap_cache->m_central->UncacheSmallMemory(ptr);
}
}
template<>
errno_t TlsHeapCache::FreeWithSizeImpl<true>(TlsHeapCache *tls_heap_cache, void *ptr, size_t size) {
if (ptr == nullptr) {
return 0;
}
const size_t cls = TlsHeapStatic::GetClassFromSize(size);
if (cls == 0) {
return tls_heap_cache->m_central->UncacheLargeMemory(ptr);
} else {
*reinterpret_cast<void **>(ptr) = tls_heap_cache->m_small_mem_lists[cls];
tls_heap_cache->m_small_mem_lists[cls] = tls_heap_cache->ManglePointer(ptr);
const s32 csize = TlsHeapStatic::GetChunkSize(cls);
tls_heap_cache->m_total_cached_size += csize;
tls_heap_cache->m_cached_size[cls] += csize;
if (tls_heap_cache->m_cached_size[cls] > tls_heap_cache->m_cached_size[tls_heap_cache->m_largest_class]) {
tls_heap_cache->m_largest_class = cls;
}
errno_t err = 0;
if (!tls_heap_cache->m_central->CheckCachedSize(tls_heap_cache->m_total_cached_size)) {
tls_heap_cache->m_central->UncacheSmallMemoryList(tls_heap_cache, tls_heap_cache->m_small_mem_lists[tls_heap_cache->m_largest_class]);
tls_heap_cache->m_small_mem_lists[tls_heap_cache->m_largest_class] = nullptr;
tls_heap_cache->m_total_cached_size -= tls_heap_cache->m_cached_size[tls_heap_cache->m_largest_class];
tls_heap_cache->m_cached_size[tls_heap_cache->m_largest_class] = 0;
s32 largest_class = 0;
s32 biggest_size = -1;
for (size_t i = 0; i < TlsHeapStatic::NumClassInfo; i++) {
if (biggest_size < tls_heap_cache->m_cached_size[i]) {
biggest_size = tls_heap_cache->m_cached_size[i];
largest_class = static_cast<s32>(i);
}
}
tls_heap_cache->m_largest_class = largest_class;
}
return err;
}
}
template<>
size_t TlsHeapCache::GetAllocationSizeImpl<false>(TlsHeapCache *tls_heap_cache, const void *ptr) {
return tls_heap_cache->GetAllocationSizeCommonImpl(ptr);
}
template<>
size_t TlsHeapCache::GetAllocationSizeImpl<true>(TlsHeapCache *tls_heap_cache, const void *ptr) {
return tls_heap_cache->GetAllocationSizeCommonImpl(ptr);
}
size_t TlsHeapCache::GetAllocationSizeCommonImpl(const void *ptr) const {
const s32 cls = m_central->GetClassFromPointer(ptr);
if (cls > 0) {
if (!util::IsAligned(ptr, alignof(u64))) {
/* All pointers we allocate have alignment at least 8. */
return 0;
}
/* Validate class. */
AMS_ASSERT(cls < static_cast<s32>(TlsHeapStatic::NumClassInfo));
if (cls < 0) {
return 0;
}
return TlsHeapStatic::GetChunkSize(cls);
} else if (ptr != nullptr) {
return m_central->GetAllocationSize(ptr);
} else {
return 0;
}
}
template<>
errno_t TlsHeapCache::ReallocateImpl<false>(TlsHeapCache *tls_heap_cache, void *ptr, size_t size, void **p) {
AMS_ASSERT(ptr != nullptr && size != 0);
if (size > MaxSize) {
return ENOMEM;
}
size_t alloc_size, copy_size;
const s32 cls_from_size = TlsHeapStatic::GetClassFromSize(size);
const s32 cls_from_ptr = tls_heap_cache->m_central->GetClassFromPointer(ptr);
if (cls_from_ptr < 0) {
/* error case. */
return EFAULT;
} else if (cls_from_size) {
if (cls_from_ptr > 0) {
if (cls_from_size <= cls_from_ptr) {
*p = ptr;
return 0;
} else {
alloc_size = size;
copy_size = TlsHeapStatic::GetChunkSize(cls_from_ptr);
}
} else /* if (cls_from_ptr == 0) */ {
alloc_size = size;
copy_size = size;
}
} else if (cls_from_ptr == 0) {
return tls_heap_cache->m_central->ReallocateLargeMemory(ptr, size, p);
} else /* if (cls_from_ptr > 0) */ {
alloc_size = size;
copy_size = TlsHeapStatic::GetChunkSize(cls_from_ptr);
}
*p = AllocateImpl<false>(tls_heap_cache, alloc_size);
if (*p == nullptr) {
return ENOMEM;
}
std::memcpy(*p, ptr, copy_size);
return FreeImpl<false>(tls_heap_cache, ptr);
}
template<>
errno_t TlsHeapCache::ReallocateImpl<true>(TlsHeapCache *tls_heap_cache, void *ptr, size_t size, void **p) {
AMS_ASSERT(ptr != nullptr && size != 0);
if (size > MaxSize) {
return ENOMEM;
}
size_t alloc_size, copy_size;
const s32 cls_from_size = TlsHeapStatic::GetClassFromSize(size);
const s32 cls_from_ptr = tls_heap_cache->m_central->GetClassFromPointer(ptr);
if (cls_from_ptr < 0) {
/* error case. */
return EFAULT;
} else if (cls_from_size) {
if (cls_from_ptr > 0) {
if (cls_from_size <= cls_from_ptr) {
*p = ptr;
return 0;
} else {
alloc_size = size;
copy_size = TlsHeapStatic::GetChunkSize(cls_from_ptr);
}
} else /* if (cls_from_ptr == 0) */ {
alloc_size = size;
copy_size = size;
}
} else if (cls_from_ptr == 0) {
return tls_heap_cache->m_central->ReallocateLargeMemory(ptr, size, p);
} else /* if (cls_from_ptr > 0) */ {
alloc_size = size;
copy_size = TlsHeapStatic::GetChunkSize(cls_from_ptr);
}
*p = AllocateImpl<true>(tls_heap_cache, alloc_size);
if (*p == nullptr) {
return ENOMEM;
}
std::memcpy(*p, ptr, copy_size);
return FreeImpl<true>(tls_heap_cache, ptr);
}
template<>
errno_t TlsHeapCache::ShrinkImpl<false>(TlsHeapCache *tls_heap_cache, void *ptr, size_t size) {
return tls_heap_cache->ShrinkCommonImpl(ptr, size);
}
template<>
errno_t TlsHeapCache::ShrinkImpl<true>(TlsHeapCache *tls_heap_cache, void *ptr, size_t size) {
return tls_heap_cache->ShrinkCommonImpl(ptr, size);
}
errno_t TlsHeapCache::ShrinkCommonImpl(void *ptr, size_t size) const {
AMS_ASSERT(ptr != nullptr && size != 0);
if (size > MaxSize) {
return ENOMEM;
}
const s32 cls_from_size = TlsHeapStatic::GetClassFromSize(size);
const s32 cls_from_ptr = m_central->GetClassFromPointer(ptr);
if (cls_from_ptr) {
if (cls_from_ptr <= 0) {
return EFAULT;
} else if (cls_from_size && cls_from_size <= cls_from_ptr) {
return 0;
} else {
return EINVAL;
}
} else if (cls_from_size) {
return m_central->ShrinkLargeMemory(ptr, TlsHeapStatic::PageSize);
} else {
return m_central->ShrinkLargeMemory(ptr, size);
}
}
}
| 21,862
|
C++
|
.cpp
| 484
| 33.444215
| 150
| 0.548744
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,445
|
pwm_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/pwm/pwm_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 <stratosphere.hpp>
namespace ams::pwm {
namespace {
constinit os::SdkMutex g_init_mutex;
constinit int g_initialize_count = 0;
ams::sf::SharedPointer<pwm::sf::IManager> g_pwm_manager;
pwm::sf::IChannelSession *GetInterface(const ChannelSession &session) {
AMS_ASSERT(session._session != nullptr);
return static_cast<pwm::sf::IChannelSession *>(session._session);
}
}
void InitializeWith(ams::sf::SharedPointer<pwm::sf::IManager> sp) {
std::scoped_lock lk(g_init_mutex);
AMS_ABORT_UNLESS(g_initialize_count == 0);
g_pwm_manager = sp;
g_initialize_count = 1;
}
void Finalize() {
std::scoped_lock lk(g_init_mutex);
AMS_ASSERT(g_initialize_count > 0);
if ((--g_initialize_count) == 0) {
g_pwm_manager.Reset();
}
}
Result OpenSession(ChannelSession *out, DeviceCode device_code) {
/* Get the session. */
ams::sf::SharedPointer<pwm::sf::IChannelSession> session;
{
if (hos::GetVersion() >= hos::Version_6_0_0) {
R_TRY(g_pwm_manager->OpenSession2(std::addressof(session), device_code));
} else {
R_TRY(g_pwm_manager->OpenSession(std::addressof(session), ConvertToChannelName(device_code)));
}
}
/* Set output. */
out->_session = session.Detach();
/* We succeeded. */
R_SUCCEED();
}
void CloseSession(ChannelSession &session) {
/* Close the session. */
ams::sf::ReleaseSharedObject(GetInterface(session));
session._session = nullptr;
}
void SetPeriod(ChannelSession &session, TimeSpan period) {
R_ABORT_UNLESS(GetInterface(session)->SetPeriod(period));
}
TimeSpan GetPeriod(ChannelSession &session) {
TimeSpanType out_val;
R_ABORT_UNLESS(GetInterface(session)->GetPeriod(std::addressof(out_val)));
return out_val;
}
void SetDuty(ChannelSession &session, int duty) {
R_ABORT_UNLESS(GetInterface(session)->SetDuty(duty));
}
int GetDuty(ChannelSession &session) {
int out_val;
R_ABORT_UNLESS(GetInterface(session)->GetDuty(std::addressof(out_val)));
return out_val;
}
void SetEnabled(ChannelSession &session, bool en) {
R_ABORT_UNLESS(GetInterface(session)->SetEnabled(en));
}
bool GetEnabled(ChannelSession &session) {
bool out_val;
R_ABORT_UNLESS(GetInterface(session)->GetEnabled(std::addressof(out_val)));
return out_val;
}
void SetScale(ChannelSession &session, double scale) {
R_ABORT_UNLESS(GetInterface(session)->SetScale(scale));
}
double GetScale(ChannelSession &session) {
double out_val;
R_ABORT_UNLESS(GetInterface(session)->GetScale(std::addressof(out_val)));
return out_val;
}
}
| 3,580
|
C++
|
.cpp
| 92
| 31.75
| 110
| 0.647704
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,446
|
pwm_driver_service_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/pwm/driver/pwm_driver_service_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 <stratosphere.hpp>
#include "impl/pwm_driver_core.hpp"
namespace ams::pwm::driver {
void RegisterDriver(IPwmDriver *driver) {
return impl::RegisterDriver(driver);
}
void UnregisterDriver(IPwmDriver *driver) {
return impl::UnregisterDriver(driver);
}
Result RegisterDeviceCode(DeviceCode device_code, IPwmDevice *device) {
R_RETURN(impl::RegisterDeviceCode(device_code, device));
}
bool UnregisterDeviceCode(DeviceCode device_code) {
return impl::UnregisterDeviceCode(device_code);
}
}
| 1,200
|
C++
|
.cpp
| 31
| 34.967742
| 76
| 0.740103
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,447
|
pwm_driver_channel_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/pwm/driver/pwm_driver_channel_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 <stratosphere.hpp>
#include "impl/pwm_driver_core.hpp"
#include "impl/pwm_channel_session_impl.hpp"
namespace ams::pwm::driver {
namespace {
Result OpenSessionImpl(ChannelSession *out, IPwmDevice *device) {
/* Construct the session. */
auto *session = std::construct_at(std::addressof(impl::GetChannelSessionImpl(*out)));
ON_RESULT_FAILURE { std::destroy_at(session); };
/* Open the session. */
R_RETURN(session->Open(device, ddsf::AccessMode_ReadWrite));
}
}
Result OpenSession(ChannelSession *out, DeviceCode device_code) {
AMS_ASSERT(out != nullptr);
/* Find the device. */
IPwmDevice *device = nullptr;
R_TRY(impl::FindDevice(std::addressof(device), device_code));
AMS_ASSERT(device != nullptr);
/* Open the session. */
R_TRY(OpenSessionImpl(out, device));
R_SUCCEED();
}
void CloseSession(ChannelSession &session) {
std::destroy_at(std::addressof(impl::GetOpenChannelSessionImpl(session)));
}
void SetPeriod(ChannelSession &session, TimeSpan period) {
R_ABORT_UNLESS(impl::GetOpenChannelSessionImpl(session).SetPeriod(period));
}
TimeSpan GetPeriod(ChannelSession &session) {
TimeSpan out_val;
R_ABORT_UNLESS(impl::GetOpenChannelSessionImpl(session).GetPeriod(std::addressof(out_val)));
return out_val;
}
void SetDuty(ChannelSession &session, int duty) {
R_ABORT_UNLESS(impl::GetOpenChannelSessionImpl(session).SetDuty(duty));
}
int GetDuty(ChannelSession &session) {
int out_val;
R_ABORT_UNLESS(impl::GetOpenChannelSessionImpl(session).GetDuty(std::addressof(out_val)));
return out_val;
}
void SetEnabled(ChannelSession &session, bool en) {
R_ABORT_UNLESS(impl::GetOpenChannelSessionImpl(session).SetEnabled(en));
}
bool GetEnabled(ChannelSession &session) {
bool out_val;
R_ABORT_UNLESS(impl::GetOpenChannelSessionImpl(session).GetEnabled(std::addressof(out_val)));
return out_val;
}
void SetScale(ChannelSession &session, double scale) {
R_ABORT_UNLESS(impl::GetOpenChannelSessionImpl(session).SetScale(scale));
}
double GetScale(ChannelSession &session) {
double out_val;
R_ABORT_UNLESS(impl::GetOpenChannelSessionImpl(session).GetScale(std::addressof(out_val)));
return out_val;
}
}
| 3,120
|
C++
|
.cpp
| 74
| 35.797297
| 101
| 0.688801
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,448
|
pwm_driver_client_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/pwm/driver/pwm_driver_client_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 <stratosphere.hpp>
#include "impl/pwm_driver_core.hpp"
namespace ams::pwm::driver {
void Initialize() {
return impl::InitializeDrivers();
}
void Finalize() {
return impl::FinalizeDrivers();
}
}
| 875
|
C++
|
.cpp
| 25
| 31.96
| 76
| 0.730178
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,449
|
pwm_driver_core.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/pwm/driver/impl/pwm_driver_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 <stratosphere.hpp>
#include "pwm_driver_core.hpp"
namespace ams::pwm::driver::impl {
namespace {
constinit os::SdkMutex g_init_mutex;
constinit int g_init_count = 0;
pwm::driver::IPwmDriver::List &GetPwmDriverList() {
AMS_FUNCTION_LOCAL_STATIC_CONSTINIT(pwm::driver::IPwmDriver::List, s_driver_list);
return s_driver_list;
}
ddsf::DeviceCodeEntryManager &GetDeviceCodeEntryManager() {
AMS_FUNCTION_LOCAL_STATIC(ddsf::DeviceCodeEntryManager, s_device_code_entry_manager, ddsf::GetDeviceCodeEntryHolderMemoryResource());
return s_device_code_entry_manager;
}
}
void InitializeDrivers() {
std::scoped_lock lk(g_init_mutex);
/* Initialize all registered drivers, if this is our first initialization. */
if ((g_init_count++) == 0) {
for (auto &driver : GetPwmDriverList()) {
driver.SafeCastTo<IPwmDriver>().InitializeDriver();
}
}
}
void FinalizeDrivers() {
std::scoped_lock lk(g_init_mutex);
/* If we have no remaining sessions, close. */
if ((--g_init_count) == 0) {
/* Reset all device code entries. */
GetDeviceCodeEntryManager().Reset();
/* Finalize all drivers. */
for (auto &driver : GetPwmDriverList()) {
driver.SafeCastTo<IPwmDriver>().FinalizeDriver();
}
}
}
void RegisterDriver(IPwmDriver *driver) {
AMS_ASSERT(driver != nullptr);
GetPwmDriverList().push_back(*driver);
}
void UnregisterDriver(IPwmDriver *driver) {
AMS_ASSERT(driver != nullptr);
if (driver->IsLinkedToList()) {
auto &list = GetPwmDriverList();
list.erase(list.iterator_to(*driver));
}
}
Result RegisterDeviceCode(DeviceCode device_code, IPwmDevice *device) {
AMS_ASSERT(device != nullptr);
R_TRY(GetDeviceCodeEntryManager().Add(device_code, device));
R_SUCCEED();
}
bool UnregisterDeviceCode(DeviceCode device_code) {
return GetDeviceCodeEntryManager().Remove(device_code);
}
Result FindDevice(IPwmDevice **out, DeviceCode device_code) {
/* Validate output. */
AMS_ASSERT(out != nullptr);
/* Find the device. */
ddsf::IDevice *device;
R_TRY(GetDeviceCodeEntryManager().FindDevice(std::addressof(device), device_code));
/* Set output. */
*out = device->SafeCastToPointer<IPwmDevice>();
R_SUCCEED();
}
Result FindDeviceByChannelIndex(IPwmDevice **out, int channel) {
/* Validate output. */
AMS_ASSERT(out != nullptr);
/* Find the device. */
bool found = false;
GetDeviceCodeEntryManager().ForEachEntry([&](ddsf::DeviceCodeEntry &entry) -> bool {
/* Convert the entry to an IPwmDevice. */
auto &device = entry.GetDevice().SafeCastTo<IPwmDevice>();
/* Check if the device is the one we're looking for. */
if (device.GetChannelIndex() == channel) {
found = true;
*out = std::addressof(device);
return false;
}
return true;
});
/* Check that we found the pad. */
R_UNLESS(found, ddsf::ResultDeviceCodeNotFound());
R_SUCCEED();
}
}
| 4,069
|
C++
|
.cpp
| 101
| 31.960396
| 145
| 0.62278
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,450
|
pwm_channel_session_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/pwm/driver/impl/pwm_channel_session_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 "pwm_driver_core.hpp"
#include "pwm_channel_session_impl.hpp"
namespace ams::pwm::driver::impl {
Result ChannelSessionImpl::Open(IPwmDevice *device, ddsf::AccessMode access_mode) {
AMS_ASSERT(device != nullptr);
/* Check if we're the device's first session. */
const bool first = !device->HasAnyOpenSession();
/* Open the session. */
R_TRY(ddsf::OpenSession(device, this, access_mode));
auto guard = SCOPE_GUARD { ddsf::CloseSession(this); };
/* If we're the first session, initialize the device. */
if (first) {
R_TRY(device->GetDriver().SafeCastTo<IPwmDriver>().InitializeDevice(device));
}
/* We're opened. */
guard.Cancel();
R_SUCCEED();
}
void ChannelSessionImpl::Close() {
/* If we're not open, do nothing. */
if (!this->IsOpen()) {
return;
}
/* Get the device. */
auto &device = this->GetDevice().SafeCastTo<IPwmDevice>();
/* Close the session. */
ddsf::CloseSession(this);
/* If there are no remaining sessions, finalize the device. */
if (!device.HasAnyOpenSession()) {
device.GetDriver().SafeCastTo<IPwmDriver>().FinalizeDevice(std::addressof(device));
}
}
Result ChannelSessionImpl::SetPeriod(TimeSpan period) {
/* Get the device. */
IPwmDevice &device = this->GetDevice().SafeCastTo<IPwmDevice>();
/* Invoke the driver handler. */
R_RETURN(device.GetDriver().SafeCastTo<IPwmDriver>().SetPeriod(std::addressof(device), period));
}
Result ChannelSessionImpl::GetPeriod(TimeSpan *out) {
/* Get the device. */
IPwmDevice &device = this->GetDevice().SafeCastTo<IPwmDevice>();
/* Invoke the driver handler. */
R_RETURN(device.GetDriver().SafeCastTo<IPwmDriver>().GetPeriod(out, std::addressof(device)));
}
Result ChannelSessionImpl::SetDuty(int duty) {
/* Get the device. */
IPwmDevice &device = this->GetDevice().SafeCastTo<IPwmDevice>();
/* Invoke the driver handler. */
R_RETURN(device.GetDriver().SafeCastTo<IPwmDriver>().SetDuty(std::addressof(device), duty));
}
Result ChannelSessionImpl::GetDuty(int *out) {
/* Get the device. */
IPwmDevice &device = this->GetDevice().SafeCastTo<IPwmDevice>();
/* Invoke the driver handler. */
R_RETURN(device.GetDriver().SafeCastTo<IPwmDriver>().GetDuty(out, std::addressof(device)));
}
Result ChannelSessionImpl::SetEnabled(bool en) {
/* Get the device. */
IPwmDevice &device = this->GetDevice().SafeCastTo<IPwmDevice>();
/* Invoke the driver handler. */
R_RETURN(device.GetDriver().SafeCastTo<IPwmDriver>().SetEnabled(std::addressof(device), en));
}
Result ChannelSessionImpl::GetEnabled(bool *out) {
/* Get the device. */
IPwmDevice &device = this->GetDevice().SafeCastTo<IPwmDevice>();
/* Invoke the driver handler. */
R_RETURN(device.GetDriver().SafeCastTo<IPwmDriver>().GetEnabled(out, std::addressof(device)));
}
Result ChannelSessionImpl::SetScale(double scale) {
/* Get the device. */
IPwmDevice &device = this->GetDevice().SafeCastTo<IPwmDevice>();
/* Invoke the driver handler. */
R_RETURN(device.GetDriver().SafeCastTo<IPwmDriver>().SetScale(std::addressof(device), scale));
}
Result ChannelSessionImpl::GetScale(double *out) {
/* Get the device. */
IPwmDevice &device = this->GetDevice().SafeCastTo<IPwmDevice>();
/* Invoke the driver handler. */
R_RETURN(device.GetDriver().SafeCastTo<IPwmDriver>().GetScale(out, std::addressof(device)));
}
}
| 4,452
|
C++
|
.cpp
| 97
| 38.824742
| 104
| 0.652957
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,451
|
pwm_driver_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/pwm/driver/board/nintendo/nx/pwm_driver_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 <stratosphere.hpp>
#include "impl/pwm_impl_pwm_driver_api.hpp"
namespace ams::pwm::driver::board::nintendo::nx {
void Initialize() {
R_ABORT_UNLESS(impl::InitializePwmDriver());
/* TODO: R_ABORT_UNLESS(impl::InitializePmcDriver()); */
}
}
| 910
|
C++
|
.cpp
| 23
| 36.782609
| 76
| 0.733032
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,452
|
pwm_impl_pwm_driver_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/pwm/driver/board/nintendo/nx/impl/pwm_impl_pwm_driver_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 <stratosphere.hpp>
#include "pwm_impl_pwm_driver_api.hpp"
#include "pwm_pwm_driver_impl.hpp"
namespace ams::pwm::driver::board::nintendo::nx::impl {
namespace {
constexpr inline const dd::PhysicalAddress PwmRegistersPhysicalAddress = 0x7000A000;
constexpr inline size_t PwmRegistersSize = 0x100;
constexpr const ChannelDefinition SupportedChannels[] = {
{ pwm::DeviceCode_LcdBacklight, 0 },
{ pwm::DeviceCode_CpuFan, 1 },
};
}
Result InitializePwmDriver() {
/* Get the memory resource with which to allocate our driver/devices. */
auto *memory_resource = ddsf::GetMemoryResource();
/* Allocate storage for our driver. */
auto *driver_storage = memory_resource->Allocate(sizeof(PwmDriverImpl), alignof(PwmDriverImpl));
AMS_ABORT_UNLESS(driver_storage != nullptr);
/* Create our driver. */
auto *driver = std::construct_at(static_cast<PwmDriverImpl *>(driver_storage), PwmRegistersPhysicalAddress, PwmRegistersSize, SupportedChannels, util::size(SupportedChannels));
/* Register our driver. */
pwm::driver::RegisterDriver(driver);
/* Create our devices. */
for (const auto &entry : SupportedChannels) {
auto *device_storage = memory_resource->Allocate(sizeof(PwmDriverImpl), alignof(PwmDriverImpl));
AMS_ABORT_UNLESS(device_storage != nullptr);
/* Create our driver. */
auto *device = std::construct_at(static_cast<PwmDeviceImpl *>(device_storage), entry.channel_id);
/* Register the device with our driver. */
driver->RegisterDevice(device);
/* Register the device code with our driver. */
R_ABORT_UNLESS(pwm::driver::RegisterDeviceCode(entry.device_code, device));
}
R_SUCCEED();
}
}
| 2,521
|
C++
|
.cpp
| 51
| 42.529412
| 184
| 0.683096
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,453
|
pwm_pwm_driver_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/pwm/driver/board/nintendo/nx/impl/pwm_pwm_driver_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 "pwm_pwm_driver_impl.hpp"
namespace ams::pwm::driver::board::nintendo::nx::impl {
namespace {
constexpr inline u32 PwmClockRateHz = 45'333'333;
constexpr inline TimeSpan DefaultChannelPeriod = TimeSpan::FromMilliSeconds(10);
constexpr inline int MaxDuty = 0x100;
template<typename T>
T DivideRoundUp(T a, T b) {
return (a + (b / 2)) / b;
}
}
PwmDriverImpl::PwmDriverImpl(dd::PhysicalAddress paddr, size_t sz, const ChannelDefinition *c, size_t nc) : m_registers_phys_addr(paddr), m_registers_size(sz), m_channels(c), m_num_channels(nc), m_registers(0) {
/* ... */
}
void PwmDriverImpl::PowerOn() {
/* Initialize pcv driver. */
pcv::Initialize();
/* Setup clock/power for pwm. */
R_ABORT_UNLESS(pcv::SetReset(pcv::Module_Pwm, true));
R_ABORT_UNLESS(pcv::SetClockEnabled(pcv::Module_Pwm, true));
R_ABORT_UNLESS(pcv::SetClockRate(pcv::Module_Pwm, PwmClockRateHz));
R_ABORT_UNLESS(pcv::SetReset(pcv::Module_Pwm, false));
}
void PwmDriverImpl::PowerOff() {
/* Disable clock and hold pwm in reset. */
/* NOTE: Nintendo does not check this succeeds. */
pcv::SetClockEnabled(pcv::Module_Pwm, false);
pcv::SetReset(pcv::Module_Pwm, true);
/* Finalize pcv driver. */
pcv::Finalize();
}
void PwmDriverImpl::InitializeDriver() {
/* Get the registers virtual address. */
m_registers = dd::QueryIoMapping(m_registers_phys_addr, m_registers_size);
AMS_ABORT_UNLESS(m_registers != 0);
/* Setup power to pwm. */
this->PowerOn();
}
void PwmDriverImpl::FinalizeDriver() {
/* Shut down power to pwm. */
this->PowerOff();
}
Result PwmDriverImpl::InitializeDevice(IPwmDevice *device) {
/* Validate the device. */
AMS_ASSERT(device != nullptr);
/* Configure initial settings. */
/* NOTE: None of these results are checked. */
this->SetEnabled(device, false);
this->SetScale(device, 0.0);
this->SetPeriod(device, DefaultChannelPeriod);
R_SUCCEED();
}
void PwmDriverImpl::FinalizeDevice(IPwmDevice *device) {
/* Validate the device. */
AMS_ASSERT(device != nullptr);
/* Nothing to do here. */
AMS_UNUSED(device);
}
Result PwmDriverImpl::SetPeriod(IPwmDevice *device, TimeSpan period) {
/* Validate the device. */
AMS_ASSERT(device != nullptr);
/* Verify the period is valid. */
const auto ns = period.GetNanoSeconds();
R_UNLESS(ns > 0, pwm::ResultInvalidArgument());
/* Convert the ns to a desired frequency (rounding up). */
const auto hz = DivideRoundUp(TimeSpan::FromSeconds(1).GetNanoSeconds(), ns);
R_UNLESS(hz > 0, pwm::ResultInvalidArgument());
/* Convert the frequency to a pfm value. */
const u32 pfm = std::min<u32>(std::max<u32>(DivideRoundUp<u64>(PwmClockRateHz, hz * 256), 1) - 1, 0x1FFF);
/* Acquire exclusive access to the device registers. */
std::scoped_lock lk(device->SafeCastTo<PwmDeviceImpl>());
/* Update the period. */
reg::ReadWrite(this->GetRegistersFor(device) + PWM_CONTROLLER_PWM_CSR, PWM_REG_BITS_VALUE(PWM_CSR_PFM, pfm));
R_SUCCEED();
}
Result PwmDriverImpl::GetPeriod(TimeSpan *out, IPwmDevice *device) {
/* Validate the device. */
AMS_ASSERT(out != nullptr);
AMS_ASSERT(device != nullptr);
/* Get the pfm value. */
const u32 pfm = reg::GetValue(this->GetRegistersFor(device) + PWM_CONTROLLER_PWM_CSR, PWM_REG_BITS_MASK(PWM_CSR_PFM));
/* Convert it to a frequency. */
/* pfm = ((ClockRate / (hz * 256)) - 1) -> hz = (ClockRate / ((pfm + 1) * 256)) */
const auto hz = DivideRoundUp<s64>(PwmClockRateHz, (pfm + 1) * 256);
/* Convert the frequency to a period. */
const auto ns = DivideRoundUp(TimeSpan::FromSeconds(1).GetNanoSeconds(), hz);
/* Set the output. */
*out = TimeSpan::FromNanoSeconds(ns);
R_SUCCEED();
}
Result PwmDriverImpl::SetDuty(IPwmDevice *device, int duty) {
/* Validate the device. */
AMS_ASSERT(device != nullptr);
/* Validate the duty. */
R_UNLESS(0 <= duty && duty <= MaxDuty, pwm::ResultInvalidArgument());
/* Acquire exclusive access to the device registers. */
std::scoped_lock lk(device->SafeCastTo<PwmDeviceImpl>());
/* Update the duty. */
reg::ReadWrite(this->GetRegistersFor(device) + PWM_CONTROLLER_PWM_CSR, PWM_REG_BITS_VALUE(PWM_CSR_PWM, static_cast<u32>(duty)));
R_SUCCEED();
}
Result PwmDriverImpl::GetDuty(int *out, IPwmDevice *device) {
/* Validate the device. */
AMS_ASSERT(out != nullptr);
AMS_ASSERT(device != nullptr);
/* Get the duty. */
*out = static_cast<int>(reg::GetValue(this->GetRegistersFor(device) + PWM_CONTROLLER_PWM_CSR, PWM_REG_BITS_MASK(PWM_CSR_PWM)));
R_SUCCEED();
}
Result PwmDriverImpl::SetScale(IPwmDevice *device, double scale) {
/* Validate the device. */
AMS_ASSERT(device != nullptr);
/* Convert the scale to a duty. */
const int duty = static_cast<int>(((scale * 256.0) / 100.0) + 0.5);
/* Validate the duty. */
R_UNLESS(0 <= duty && duty <= MaxDuty, pwm::ResultInvalidArgument());
/* Acquire exclusive access to the device registers. */
std::scoped_lock lk(device->SafeCastTo<PwmDeviceImpl>());
/* Update the duty. */
reg::ReadWrite(this->GetRegistersFor(device) + PWM_CONTROLLER_PWM_CSR, PWM_REG_BITS_VALUE(PWM_CSR_PWM, static_cast<u32>(duty)));
R_SUCCEED();
}
Result PwmDriverImpl::GetScale(double *out, IPwmDevice *device) {
/* Validate the device. */
AMS_ASSERT(out != nullptr);
AMS_ASSERT(device != nullptr);
/* Get the duty. */
const int duty = static_cast<int>(reg::GetValue(this->GetRegistersFor(device) + PWM_CONTROLLER_PWM_CSR, PWM_REG_BITS_MASK(PWM_CSR_PWM)));
/* Convert to scale. */
*out = (static_cast<double>(duty) * 100.0) / 256.0;
R_SUCCEED();
}
Result PwmDriverImpl::SetEnabled(IPwmDevice *device, bool en) {
/* Validate the device. */
AMS_ASSERT(device != nullptr);
/* Acquire exclusive access to the device registers. */
std::scoped_lock lk(device->SafeCastTo<PwmDeviceImpl>());
/* Update the enable. */
reg::ReadWrite(this->GetRegistersFor(device) + PWM_CONTROLLER_PWM_CSR, PWM_REG_BITS_ENUM_SEL(PWM_CSR_ENB, en, ENABLE, DISABLE));
R_SUCCEED();
}
Result PwmDriverImpl::GetEnabled(bool *out, IPwmDevice *device) {
/* Validate the device. */
AMS_ASSERT(out != nullptr);
AMS_ASSERT(device != nullptr);
/* Get the enable. */
*out = reg::HasValue(this->GetRegistersFor(device) + PWM_CONTROLLER_PWM_CSR, PWM_REG_BITS_ENUM(PWM_CSR_ENB, ENABLE));
R_SUCCEED();
}
Result PwmDriverImpl::Suspend() {
/* Suspend each device. */
this->ForEachDevice([&](ddsf::IDevice &device) -> bool {
/* Convert the device to a pwm device. */
auto &pwm_device = device.SafeCastTo<PwmDeviceImpl>();
/* Cache the suspend value. */
pwm_device.SetSuspendValue(reg::Read(this->GetRegistersFor(pwm_device) + PWM_CONTROLLER_PWM_CSR));
/* Acquire exclusive access to the device. */
std::scoped_lock lk(pwm_device);
/* Disable the device. */
reg::ReadWrite(this->GetRegistersFor(pwm_device) + PWM_CONTROLLER_PWM_CSR, PWM_REG_BITS_ENUM(PWM_CSR_ENB, DISABLE));
/* Continue to the next device. */
return true;
});
/* Disable clock to pwm. */
R_RETURN(pcv::SetClockEnabled(pcv::Module_Pwm, false));
}
void PwmDriverImpl::Resume() {
/* Power on. */
this->PowerOn();
/* Resume each device. */
this->ForEachDevice([&](ddsf::IDevice &device) -> bool {
/* Convert the device to a pwm device. */
auto &pwm_device = device.SafeCastTo<PwmDeviceImpl>();
/* Acquire exclusive access to the device. */
std::scoped_lock lk(pwm_device);
/* Write the device's suspend value. */
reg::Write(this->GetRegistersFor(pwm_device) + PWM_CONTROLLER_PWM_CSR, pwm_device.GetSuspendValue());
/* Continue to the next device. */
return true;
});
}
}
| 9,383
|
C++
|
.cpp
| 198
| 39.10101
| 215
| 0.619079
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,454
|
pwm_server_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/pwm/server/pwm_server_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 <stratosphere.hpp>
#include "pwm_server_manager_impl.hpp"
namespace ams::pwm::server {
namespace {
ams::sf::UnmanagedServiceObject<pwm::sf::IManager, pwm::server::ManagerImpl> g_manager_impl;
}
ams::sf::SharedPointer<pwm::sf::IManager> GetServiceObject() {
return g_manager_impl.GetShared();
}
}
| 978
|
C++
|
.cpp
| 25
| 36.04
| 100
| 0.736008
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,455
|
pwm_server_manager_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/pwm/server/pwm_server_manager_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 "pwm_server_manager_impl.hpp"
namespace ams::pwm::server {
ManagerImpl::ManagerImpl() {
m_heap_handle = lmem::CreateExpHeap(m_heap_buffer, sizeof(m_heap_buffer), lmem::CreateOption_None);
m_allocator.Attach(m_heap_handle);
}
ManagerImpl::~ManagerImpl() {
lmem::DestroyExpHeap(m_heap_handle);
}
Result ManagerImpl::OpenSessionForDev(ams::sf::Out<ams::sf::SharedPointer<pwm::sf::IChannelSession>> out, int channel) {
/* TODO */
AMS_UNUSED(out, channel);
AMS_ABORT();
}
Result ManagerImpl::OpenSession(ams::sf::Out<ams::sf::SharedPointer<pwm::sf::IChannelSession>> out, pwm::ChannelName channel_name) {
R_RETURN(this->OpenSession2(out, ConvertToDeviceCode(channel_name)));
}
Result ManagerImpl::OpenSession2(ams::sf::Out<ams::sf::SharedPointer<pwm::sf::IChannelSession>> out, DeviceCode device_code) {
/* Allocate a session. */
auto session = Factory::CreateSharedEmplaced<pwm::sf::IChannelSession, ChannelSessionImpl>(std::addressof(m_allocator), this);
/* Open the session. */
R_TRY(session.GetImpl().OpenSession(device_code));
/* We succeeded. */
*out = std::move(session);
R_SUCCEED();
}
}
| 1,924
|
C++
|
.cpp
| 43
| 39.674419
| 136
| 0.697115
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,456
|
sm_mitm_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/sm/sm_mitm_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 <stratosphere.hpp>
#include "sm_utils.hpp"
namespace ams::sm::mitm {
#if defined(ATMOSPHERE_OS_HORIZON)
#if AMS_SF_MITM_SUPPORTED
/* Mitm API. */
Result InstallMitm(os::NativeHandle *out_port, os::NativeHandle *out_query, ServiceName name) {
R_RETURN(impl::DoWithPerThreadSession([&](TipcService *fwd) {
R_RETURN(smAtmosphereMitmInstall(fwd, out_port, out_query, impl::ConvertName(name)));
}));
}
Result UninstallMitm(ServiceName name) {
R_RETURN(smAtmosphereMitmUninstall(impl::ConvertName(name)));
}
Result DeclareFutureMitm(ServiceName name) {
R_RETURN(smAtmosphereMitmDeclareFuture(impl::ConvertName(name)));
}
Result ClearFutureMitm(ServiceName name) {
R_RETURN(smAtmosphereMitmClearFuture(impl::ConvertName(name)));
}
Result AcknowledgeSession(Service *out_service, MitmProcessInfo *out_info, ServiceName name) {
return impl::DoWithMitmAcknowledgementSession([&]() {
R_RETURN(smAtmosphereMitmAcknowledgeSession(out_service, reinterpret_cast<void *>(out_info), impl::ConvertName(name)));
});
}
Result HasMitm(bool *out, ServiceName name) {
R_RETURN(smAtmosphereHasMitm(out, impl::ConvertName(name)));
}
Result WaitMitm(ServiceName name) {
R_RETURN(smAtmosphereWaitMitm(impl::ConvertName(name)));
}
#endif
#endif
}
| 2,044
|
C++
|
.cpp
| 49
| 36.734694
| 131
| 0.715509
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,457
|
sm_manager_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/sm/sm_manager_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 <stratosphere.hpp>
#include "sm_utils.hpp"
#if defined(ATMOSPHERE_OS_HORIZON)
#include "smm_ams.os.horizon.h"
#endif
namespace ams::sm::manager {
#if defined(ATMOSPHERE_OS_HORIZON)
/* Manager API. */
Result RegisterProcess(os::ProcessId process_id, ncm::ProgramId program_id, cfg::OverrideStatus status, const void *acid, size_t acid_size, const void *aci, size_t aci_size) {
static_assert(sizeof(status) == sizeof(CfgOverrideStatus), "CfgOverrideStatus definition");
R_RETURN(smManagerAtmosphereRegisterProcess(static_cast<u64>(process_id), static_cast<u64>(program_id), reinterpret_cast<const CfgOverrideStatus *>(std::addressof(status)), acid, acid_size, aci, aci_size));
}
Result UnregisterProcess(os::ProcessId process_id) {
R_RETURN(smManagerUnregisterProcess(static_cast<u64>(process_id)));
}
/* Atmosphere extensions. */
Result EndInitialDefers() {
R_RETURN(smManagerAtmosphereEndInitialDefers());
}
Result HasMitm(bool *out, ServiceName name) {
R_RETURN(smManagerAtmosphereHasMitm(out, impl::ConvertName(name)));
}
#endif
}
| 1,772
|
C++
|
.cpp
| 39
| 41.641026
| 214
| 0.736385
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,458
|
sm_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/sm/sm_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 <stratosphere.hpp>
#include "sm_utils.hpp"
namespace ams::sm {
#if defined(ATMOSPHERE_OS_HORIZON)
namespace {
constinit int g_ref_count = 0;
constinit os::SdkMutex g_mutex;
}
/* Initialization. */
Result Initialize() {
std::scoped_lock lk(g_mutex);
if (g_ref_count > 0) {
++g_ref_count;
} else {
R_TRY(::smInitialize());
g_ref_count = 1;
}
R_SUCCEED();
}
Result Finalize() {
/* NOTE: Nintendo does nothing here. */
R_SUCCEED();
}
/* Ordinary SM API. */
Result GetServiceHandle(os::NativeHandle *out, ServiceName name) {
R_RETURN(smGetServiceOriginal(out, impl::ConvertName(name)));
}
Result RegisterService(os::NativeHandle *out, ServiceName name, size_t max_sessions, bool is_light) {
R_RETURN(smRegisterService(out, impl::ConvertName(name), is_light, static_cast<int>(max_sessions)));
}
Result UnregisterService(ServiceName name) {
R_RETURN(smUnregisterService(impl::ConvertName(name)));
}
/* Atmosphere extensions. */
Result HasService(bool *out, ServiceName name) {
R_RETURN(smAtmosphereHasService(out, impl::ConvertName(name)));
}
Result WaitService(ServiceName name) {
R_RETURN(smAtmosphereWaitService(impl::ConvertName(name)));
}
#else
Result Initialize() {
R_SUCCEED();
}
Result Finalize() {
R_SUCCEED();
}
/* Ordinary SM API. */
Result GetServiceHandle(os::NativeHandle *out, ServiceName name) {
AMS_UNUSED(out, name);
AMS_ABORT("TODO?");
}
Result RegisterService(os::NativeHandle *out, ServiceName name, size_t max_sessions, bool is_light) {
AMS_UNUSED(out, name, max_sessions, is_light);
AMS_ABORT("TODO?");
}
Result UnregisterService(ServiceName name) {
AMS_UNUSED(name);
AMS_ABORT("TODO?");
}
/* Atmosphere extensions. */
Result HasService(bool *out, ServiceName name) {
AMS_UNUSED(out, name);
AMS_ABORT("TODO?");
}
Result WaitService(ServiceName name) {
AMS_UNUSED(name);
AMS_ABORT("TODO?");
}
#endif
}
| 2,877
|
C++
|
.cpp
| 86
| 27.453488
| 108
| 0.647059
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,459
|
sm_utils.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/sm/sm_utils.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 "sm_utils.hpp"
namespace ams::sm::impl {
namespace {
/* Globals. */
constinit os::SdkRecursiveMutex g_mitm_ack_session_mutex;
constinit os::SdkRecursiveMutex g_per_thread_session_mutex;
}
/* Utilities. */
os::SdkRecursiveMutex &GetMitmAcknowledgementSessionMutex() {
return g_mitm_ack_session_mutex;
}
os::SdkRecursiveMutex &GetPerThreadSessionMutex() {
return g_per_thread_session_mutex;
}
}
| 1,140
|
C++
|
.cpp
| 31
| 32.903226
| 76
| 0.725045
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,460
|
cfg_sd_card.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/cfg/cfg_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 <stratosphere.hpp>
#if defined(ATMOSPHERE_BOARD_NINTENDO_NX)
#include "cfg_sd_card.board.nintendo_nx.inc"
#else
#include "cfg_sd_card.generic.inc"
#endif
| 806
|
C++
|
.cpp
| 21
| 36.333333
| 76
| 0.756688
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,461
|
cfg_flags.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/cfg/cfg_flags.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>
#if defined(ATMOSPHERE_BOARD_NINTENDO_NX)
#include "cfg_flags.board.nintendo_nx.inc"
#else
#include "cfg_flags.generic.inc"
#endif
| 802
|
C++
|
.cpp
| 21
| 36.142857
| 76
| 0.758003
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,462
|
cfg_override.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/cfg/cfg_override.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>
#if defined(ATMOSPHERE_BOARD_NINTENDO_NX)
#include "cfg_override.board.nintendo_nx.inc"
#else
#include "cfg_override.generic.inc"
#endif
| 808
|
C++
|
.cpp
| 21
| 36.428571
| 76
| 0.759848
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,463
|
updater_paths.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/updater/updater_paths.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 "updater_paths.hpp"
namespace ams::updater {
namespace {
/* Actual paths. */
constexpr const char *BootImagePackageMountName = "bip";
constexpr const char *BctPathNx = "bip:/nx/bct";
constexpr const char *Package1PathNx = "bip:/nx/package1";
constexpr const char *Package2PathNx = "bip:/nx/package2";
constexpr const char *BctPathA = "bip:/a/bct";
constexpr const char *Package1PathA = "bip:/a/package1";
constexpr const char *Package2PathA = "bip:/a/package2";
const char *ChooseCandidatePath(const char * const *candidates, size_t num_candidates) {
AMS_ABORT_UNLESS(num_candidates > 0);
for (size_t i = 0; i < num_candidates; i++) {
fs::DirectoryEntryType type;
if (R_FAILED(fs::GetEntryType(std::addressof(type), candidates[i]))) {
continue;
}
if (type != fs::DirectoryEntryType_File) {
continue;
}
return candidates[i];
}
/* Nintendo just uses the last candidate if they all fail...should we abort? */
return candidates[num_candidates - 1];
}
}
const char *GetMountName() {
return BootImagePackageMountName;
}
const char *GetBctPath(BootImageUpdateType boot_image_update_type) {
switch (boot_image_update_type) {
case BootImageUpdateType::Erista:
{
constexpr const char *candidates[] = {BctPathNx};
return ChooseCandidatePath(candidates, util::size(candidates));
}
case BootImageUpdateType::Mariko:
{
constexpr const char *candidates[] = {BctPathA, BctPathNx};
return ChooseCandidatePath(candidates, util::size(candidates));
}
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
const char *GetPackage1Path(BootImageUpdateType boot_image_update_type) {
switch (boot_image_update_type) {
case BootImageUpdateType::Erista:
{
constexpr const char *candidates[] = {Package1PathNx};
return ChooseCandidatePath(candidates, util::size(candidates));
}
case BootImageUpdateType::Mariko:
{
constexpr const char *candidates[] = {Package1PathA, Package1PathNx};
return ChooseCandidatePath(candidates, util::size(candidates));
}
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
const char *GetPackage2Path(BootImageUpdateType boot_image_update_type) {
switch (boot_image_update_type) {
case BootImageUpdateType::Erista:
{
constexpr const char *candidates[] = {Package2PathNx};
return ChooseCandidatePath(candidates, util::size(candidates));
}
case BootImageUpdateType::Mariko:
{
constexpr const char *candidates[] = {Package2PathA, Package2PathNx};
return ChooseCandidatePath(candidates, util::size(candidates));
}
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
}
| 4,017
|
C++
|
.cpp
| 92
| 32.402174
| 96
| 0.599181
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,464
|
updater_bis_management.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/updater/updater_bis_management.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "updater_bis_management.hpp"
namespace ams::updater {
namespace {
/* Recognize special public key (https://gist.github.com/SciresM/16b63ac1d80494522bdba2c57995257c). */
/* P = 19 */
/* Q = 1696986749729493925354392349339746171297507422986462747526968361144447230710192316397327889522451749459854070558277878297255552508603806832852079596337539247651161831569525505882103311631577368514276343192042634740927726070847704397913856975832811679847928433261678072951551065705680482548543833651752439700272736498378724153330763357721354498194000536297732323628263256733931353143625854828275237159155585342783077681713929284136658773985266864804093157854331138230313706015557050002740810464618031715670281442110238274404626065924786185264268216336867948322976979393032640085259926883014490947373494538254895109731 */
/* N = 0xFF696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696959 */
/* E = 0x10001 */
/* D = 6512128715229088976470211610075969347035078304643231077895577077900787352712063823560162578441773733649014439616165727455431015055675770987914713980812453585413988983206576233689754710500864883529402371292948326392791238474661859182717295176679567362482790015587820446999760239570255254879359445627372805817473978644067558931078225451477635089763009580492462097185005355990612929951162366081631888011031830742459571000203341001926135389508196521518687349554188686396554248868403128728646457247197407637887195043486221295751496667162366700477934591694110831002874992896076061627516220934290742867397720103040314639313 */
constexpr const u8 CustomPublicKey[0x100] = {
0x59, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0xFF,
};
}
Result BisAccessor::Initialize() {
R_RETURN(fs::OpenBisPartition(std::addressof(m_storage), m_partition_id));
}
void BisAccessor::Finalize() {
/* ... */
}
Result BisAccessor::Read(void *dst, size_t size, u64 offset) {
AMS_ABORT_UNLESS((offset % SectorAlignment) == 0);
R_RETURN(m_storage->Read(static_cast<u32>(offset), dst, size));
}
Result BisAccessor::Write(u64 offset, const void *src, size_t size) {
AMS_ABORT_UNLESS((offset % SectorAlignment) == 0);
R_RETURN(m_storage->Write(static_cast<u32>(offset), src, size));
}
Result BisAccessor::Write(u64 offset, size_t size, const char *bip_path, void *work_buffer, size_t work_buffer_size) {
AMS_ABORT_UNLESS((offset % SectorAlignment) == 0);
AMS_ABORT_UNLESS((work_buffer_size % SectorAlignment) == 0);
fs::FileHandle file;
R_TRY_CATCH(fs::OpenFile(std::addressof(file), bip_path, fs::OpenMode_Read)) {
R_CONVERT(fs::ResultPathNotFound, updater::ResultInvalidBootImagePackage())
} R_END_TRY_CATCH;
ON_SCOPE_EXIT { fs::CloseFile(file); };
size_t written = 0;
while (true) {
std::memset(work_buffer, 0, work_buffer_size);
size_t read_size;
R_TRY(fs::ReadFile(std::addressof(read_size), file, written, work_buffer, work_buffer_size, fs::ReadOption()));
AMS_ABORT_UNLESS(written + read_size <= size);
size_t aligned_size = ((read_size + SectorAlignment - 1) / SectorAlignment) * SectorAlignment;
R_TRY(this->Write(offset + written, work_buffer, aligned_size));
written += read_size;
if (read_size != work_buffer_size) {
break;
}
}
R_SUCCEED();
}
Result BisAccessor::Clear(u64 offset, u64 size, void *work_buffer, size_t work_buffer_size) {
AMS_ABORT_UNLESS((offset % SectorAlignment) == 0);
AMS_ABORT_UNLESS((work_buffer_size % SectorAlignment) == 0);
std::memset(work_buffer, 0, work_buffer_size);
size_t written = 0;
while (written < size) {
size_t cur_write_size = std::min<size_t>(work_buffer_size, size - written);
R_TRY(this->Write(offset + written, work_buffer, cur_write_size));
written += cur_write_size;
}
R_SUCCEED();
}
Result BisAccessor::GetHash(void *dst, u64 offset, u64 size, u64 hash_size, void *work_buffer, size_t work_buffer_size) {
AMS_ABORT_UNLESS((offset % SectorAlignment) == 0);
AMS_ABORT_UNLESS((work_buffer_size % SectorAlignment) == 0);
crypto::Sha256Generator generator;
generator.Initialize();
size_t total_read = 0;
while (total_read < hash_size) {
size_t cur_read_size = std::min<size_t>(work_buffer_size, size - total_read);
size_t cur_update_size = std::min<size_t>(cur_read_size, hash_size - total_read);
R_TRY(this->Read(work_buffer, cur_read_size, offset + total_read));
generator.Update(work_buffer, cur_update_size);
total_read += cur_read_size;
}
generator.GetHash(dst, hash_size);
R_SUCCEED();
}
size_t Boot0Accessor::GetBootloaderVersion(void *bct) {
u32 version = *reinterpret_cast<u32 *>(reinterpret_cast<uintptr_t>(bct) + BctVersionOffset);
AMS_ABORT_UNLESS(version <= BctVersionMax);
return static_cast<size_t>(version);
}
size_t Boot0Accessor::GetEksIndex(size_t bootloader_version) {
AMS_ABORT_UNLESS(bootloader_version <= BctVersionMax);
return (bootloader_version > 0) ? bootloader_version - 1 : 0;
}
void Boot0Accessor::CopyEks(void *dst_bct, const void *src_eks, size_t eks_index) {
std::memcpy(reinterpret_cast<u8 *>(dst_bct) + BctEksOffset, reinterpret_cast<const u8 *>(src_eks) + eks_index * EksEntrySize, EksBlobSize);
}
Result Boot0Accessor::UpdateEks(void *dst_bct, void *eks_work_buffer) {
size_t read_size;
R_TRY(this->Read(&read_size, eks_work_buffer, EksSize, Boot0Partition::Eks));
R_RETURN(this->UpdateEksManually(dst_bct, eks_work_buffer));
}
Result Boot0Accessor::UpdateEksManually(void *dst_bct, const void *src_eks) {
this->CopyEks(dst_bct, src_eks, GetEksIndex(GetBootloaderVersion(dst_bct)));
R_SUCCEED();
}
Result Boot0Accessor::PreserveAutoRcm(void *dst_bct, void *work_buffer, Boot0Partition which) {
std::memset(work_buffer, 0, BctSize);
size_t read_size;
R_TRY(this->Read(&read_size, work_buffer, BctSize, which));
/* NOTE: AutoRcm is only viable on Erista, so hardcode erista offsets. */
void *dst_pubk = reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(dst_bct) + BctPubkOffsetErista);
void *src_pubk = reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(work_buffer) + BctPubkOffsetErista);
std::memcpy(dst_pubk, src_pubk, BctPubkSize);
R_SUCCEED();
}
Result Boot0Accessor::DetectCustomPublicKey(bool *out, void *work_buffer, BootImageUpdateType boot_image_update_type) {
std::memset(work_buffer, 0, BctSize);
const size_t pubk_offset = GetBctPubkOffset(boot_image_update_type);
size_t read_size;
R_TRY(this->Read(&read_size, work_buffer, BctSize, Boot0Partition::BctNormalMain));
if (std::memcmp(reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(work_buffer) + pubk_offset), CustomPublicKey, sizeof(CustomPublicKey)) != 0) {
*out = false;
R_SUCCEED();
}
R_TRY(this->Read(&read_size, work_buffer, BctSize, Boot0Partition::BctSafeMain));
if (std::memcmp(reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(work_buffer) + pubk_offset), CustomPublicKey, sizeof(CustomPublicKey)) != 0) {
*out = false;
R_SUCCEED();
}
*out = true;
R_SUCCEED();
}
}
| 10,511
|
C++
|
.cpp
| 158
| 57.892405
| 634
| 0.693106
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,465
|
updater_files.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/updater/updater_files.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 "updater_files.hpp"
namespace ams::updater {
Result ReadFile(size_t *out_size, void *dst, size_t dst_size, const char *path) {
/* Open the file. */
fs::FileHandle file;
R_TRY_CATCH(fs::OpenFile(std::addressof(file), path, fs::OpenMode_Read)) {
R_CONVERT(fs::ResultPathNotFound, updater::ResultInvalidBootImagePackage())
} R_END_TRY_CATCH;
ON_SCOPE_EXIT { fs::CloseFile(file); };
std::memset(dst, 0, dst_size);
R_RETURN(fs::ReadFile(out_size, file, 0, dst, dst_size, fs::ReadOption()));
}
Result GetFileHash(size_t *out_size, void *dst_hash, const char *path, void *work_buffer, size_t work_buffer_size) {
/* Open the file. */
fs::FileHandle file;
R_TRY_CATCH(fs::OpenFile(std::addressof(file), path, fs::OpenMode_Read)) {
R_CONVERT(fs::ResultPathNotFound, updater::ResultInvalidBootImagePackage())
} R_END_TRY_CATCH;
ON_SCOPE_EXIT { fs::CloseFile(file); };
/* Read in chunks, hashing as we go. */
crypto::Sha256Generator generator;
generator.Initialize();
size_t total_size = 0;
while (true) {
size_t size;
R_TRY(fs::ReadFile(std::addressof(size), file, total_size, work_buffer, work_buffer_size, fs::ReadOption()));
generator.Update(work_buffer, size);
total_size += size;
if (size != work_buffer_size) {
break;
}
}
generator.GetHash(dst_hash, crypto::Sha256Generator::HashSize);
*out_size = total_size;
R_SUCCEED();
}
}
| 2,300
|
C++
|
.cpp
| 53
| 36.358491
| 121
| 0.643719
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,466
|
updater_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/updater/updater_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 <stratosphere.hpp>
#include <stratosphere/updater.hpp>
#include "updater_bis_save.hpp"
#include "updater_files.hpp"
#include "updater_paths.hpp"
namespace ams::updater {
namespace {
/* Validation Prototypes. */
Result ValidateWorkBuffer(const void *work_buffer, size_t work_buffer_size);
/* Configuration Prototypes. */
bool HasEks(BootImageUpdateType boot_image_update_type);
bool HasAutoRcmPreserve(BootImageUpdateType boot_image_update_type);
ncm::ContentMetaType GetContentMetaType(BootModeType mode);
/* Verification Prototypes. */
Result GetVerificationState(VerificationState *out, void *work_buffer, size_t work_buffer_size);
Result VerifyBootImages(ncm::SystemDataId data_id, BootModeType mode, void *work_buffer, size_t work_buffer_size, BootImageUpdateType boot_image_update_type);
Result VerifyBootImagesNormal(ncm::SystemDataId data_id, void *work_buffer, size_t work_buffer_size, BootImageUpdateType boot_image_update_type);
Result VerifyBootImagesSafe(ncm::SystemDataId data_id, void *work_buffer, size_t work_buffer_size, BootImageUpdateType boot_image_update_type);
/* Update Prototypes. */
Result SetVerificationNeeded(BootModeType mode, void *work_buffer, size_t work_buffer_size, bool needed);
Result UpdateBootImagesNormal(ncm::SystemDataId data_id, void *work_buffer, size_t work_buffer_size, BootImageUpdateType boot_image_update_type);
Result UpdateBootImagesSafe(ncm::SystemDataId data_id, void *work_buffer, size_t work_buffer_size, BootImageUpdateType boot_image_update_type);
/* Package helpers. */
Result ValidateBctFileHash(Boot0Accessor &accessor, Boot0Partition which, const void *stored_hash, void *work_buffer, size_t work_buffer_size, BootImageUpdateType boot_image_update_type);
Result GetPackage2Hash(void *dst_hash, size_t package2_size, void *work_buffer, size_t work_buffer_size, Package2Type which);
Result WritePackage2(void *work_buffer, size_t work_buffer_size, Package2Type which, BootImageUpdateType boot_image_update_type);
Result CompareHash(const void *lhs, const void *rhs, size_t size);
/* Implementations. */
Result ValidateWorkBuffer(const void *work_buffer, size_t work_buffer_size) {
R_UNLESS(work_buffer_size >= BctSize + EksSize, updater::ResultTooSmallWorkBuffer());
R_UNLESS(util::IsAligned(work_buffer, os::MemoryPageSize), updater::ResultNotAlignedWorkBuffer());
R_UNLESS(util::IsAligned(work_buffer_size, 0x200), updater::ResultNotAlignedWorkBuffer());
R_SUCCEED();
}
bool HasEks(BootImageUpdateType boot_image_update_type) {
switch (boot_image_update_type) {
case BootImageUpdateType::Erista:
return true;
case BootImageUpdateType::Mariko:
return false;
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
bool HasAutoRcmPreserve(BootImageUpdateType boot_image_update_type) {
switch (boot_image_update_type) {
case BootImageUpdateType::Erista:
return true;
case BootImageUpdateType::Mariko:
return false;
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
ncm::ContentMetaType GetContentMetaType(BootModeType mode) {
switch (mode) {
case BootModeType::Normal:
return ncm::ContentMetaType::BootImagePackage;
case BootModeType::Safe:
return ncm::ContentMetaType::BootImagePackageSafe;
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
Result GetVerificationState(VerificationState *out, void *work_buffer, size_t work_buffer_size) {
/* Always set output to true before doing anything else. */
out->needs_verify_normal = true;
out->needs_verify_safe = true;
/* Ensure work buffer is big enough for us to do what we want to do. */
R_TRY(ValidateWorkBuffer(work_buffer, work_buffer_size));
/* Initialize boot0 save accessor. */
BisSave save;
R_TRY(save.Initialize(work_buffer, work_buffer_size));
ON_SCOPE_EXIT { save.Finalize(); };
/* Load save from NAND. */
R_TRY(save.Load());
/* Read data from save. */
out->needs_verify_normal = save.GetNeedsVerification(BootModeType::Normal);
out->needs_verify_safe = save.GetNeedsVerification(BootModeType::Safe);
R_SUCCEED();
}
Result VerifyBootImagesAndRepairIfNeeded(bool *out_repaired, BootModeType mode, void *work_buffer, size_t work_buffer_size, BootImageUpdateType boot_image_update_type) {
/* Get system data id for boot images (819/81A/81B/81C). */
ncm::SystemDataId bip_data_id = {};
R_TRY(GetBootImagePackageId(std::addressof(bip_data_id), mode, work_buffer, work_buffer_size));
/* Verify the boot images in NAND. */
R_TRY_CATCH(VerifyBootImages(bip_data_id, mode, work_buffer, work_buffer_size, boot_image_update_type)) {
R_CATCH(ResultNeedsRepairBootImages) {
/* Perform repair. */
*out_repaired = true;
R_TRY(UpdateBootImagesFromPackage(bip_data_id, mode, work_buffer, work_buffer_size, boot_image_update_type));
}
} R_END_TRY_CATCH;
/* We've either just verified or just repaired. Either way, we don't need to verify any more. */
R_RETURN(SetVerificationNeeded(mode, work_buffer, work_buffer_size, false));
}
Result VerifyBootImages(ncm::SystemDataId data_id, BootModeType mode, void *work_buffer, size_t work_buffer_size, BootImageUpdateType boot_image_update_type) {
switch (mode) {
case BootModeType::Normal:
R_RETURN(VerifyBootImagesNormal(data_id, work_buffer, work_buffer_size, boot_image_update_type));
case BootModeType::Safe:
R_RETURN(VerifyBootImagesSafe(data_id, work_buffer, work_buffer_size, boot_image_update_type));
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
Result VerifyBootImagesNormal(ncm::SystemDataId data_id, void *work_buffer, size_t work_buffer_size, BootImageUpdateType boot_image_update_type) {
/* Ensure work buffer is big enough for us to do what we want to do. */
R_TRY(ValidateWorkBuffer(work_buffer, work_buffer_size));
/* Mount the boot image package. */
const char *mount_name = GetMountName();
R_TRY_CATCH(fs::MountSystemData(mount_name, data_id)) {
R_CONVERT(fs::ResultTargetNotFound, updater::ResultBootImagePackageNotFound())
} R_END_TRY_CATCH;
ON_SCOPE_EXIT { fs::Unmount(mount_name); };
/* Read and validate hashes of boot images. */
{
size_t size;
u8 nand_hash[crypto::Sha256Generator::HashSize];
u8 file_hash[crypto::Sha256Generator::HashSize];
Boot0Accessor boot0_accessor;
R_TRY(boot0_accessor.Initialize());
ON_SCOPE_EXIT { boot0_accessor.Finalize(); };
/* Detect the use of custom public key. */
/* If custom public key is present, we want to validate BCT Sub but not Main */
bool custom_public_key = false;
R_TRY(boot0_accessor.DetectCustomPublicKey(std::addressof(custom_public_key), work_buffer, boot_image_update_type));
/* Compare BCT hashes. */
if (!custom_public_key) {
R_TRY(boot0_accessor.GetHash(nand_hash, BctSize, work_buffer, work_buffer_size, Boot0Partition::BctNormalMain));
R_TRY(ValidateBctFileHash(boot0_accessor, Boot0Partition::BctNormalMain, nand_hash, work_buffer, work_buffer_size, boot_image_update_type));
}
/* Compare BCT Sub hashes. */
R_TRY(boot0_accessor.GetHash(nand_hash, BctSize, work_buffer, work_buffer_size, Boot0Partition::BctNormalSub));
R_TRY(ValidateBctFileHash(boot0_accessor, Boot0Partition::BctNormalSub, nand_hash, work_buffer, work_buffer_size, boot_image_update_type));
/* Compare Package1 Normal/Sub hashes. */
R_TRY(GetFileHash(std::addressof(size), file_hash, GetPackage1Path(boot_image_update_type), work_buffer, work_buffer_size));
R_TRY(boot0_accessor.GetHash(nand_hash, size, work_buffer, work_buffer_size, Boot0Partition::Package1NormalMain));
R_TRY(CompareHash(file_hash, nand_hash, sizeof(file_hash)));
R_TRY(boot0_accessor.GetHash(nand_hash, size, work_buffer, work_buffer_size, Boot0Partition::Package1NormalSub));
R_TRY(CompareHash(file_hash, nand_hash, sizeof(file_hash)));
/* Compare Package2 Normal/Sub hashes. */
R_TRY(GetFileHash(std::addressof(size), file_hash, GetPackage2Path(boot_image_update_type), work_buffer, work_buffer_size));
R_TRY(GetPackage2Hash(nand_hash, size, work_buffer, work_buffer_size, Package2Type::NormalMain));
R_TRY(CompareHash(file_hash, nand_hash, sizeof(file_hash)));
R_TRY(GetPackage2Hash(nand_hash, size, work_buffer, work_buffer_size, Package2Type::NormalSub));
R_TRY(CompareHash(file_hash, nand_hash, sizeof(file_hash)));
}
R_SUCCEED();
}
Result VerifyBootImagesSafe(ncm::SystemDataId data_id, void *work_buffer, size_t work_buffer_size, BootImageUpdateType boot_image_update_type) {
/* Ensure work buffer is big enough for us to do what we want to do. */
R_TRY(ValidateWorkBuffer(work_buffer, work_buffer_size));
/* Mount the boot image package. */
const char *mount_name = GetMountName();
R_TRY_CATCH(fs::MountSystemData(mount_name, data_id)) {
R_CONVERT(fs::ResultTargetNotFound, updater::ResultBootImagePackageNotFound())
} R_END_TRY_CATCH;
ON_SCOPE_EXIT { fs::Unmount(mount_name); };
/* Read and validate hashes of boot images. */
{
size_t size;
u8 nand_hash[crypto::Sha256Generator::HashSize];
u8 file_hash[crypto::Sha256Generator::HashSize];
Boot0Accessor boot0_accessor;
R_TRY(boot0_accessor.Initialize());
ON_SCOPE_EXIT { boot0_accessor.Finalize(); };
Boot1Accessor boot1_accessor;
R_TRY(boot1_accessor.Initialize());
ON_SCOPE_EXIT { boot1_accessor.Finalize(); };
/* Detect the use of custom public key. */
/* If custom public key is present, we want to validate BCT Sub but not Main */
bool custom_public_key = false;
R_TRY(boot0_accessor.DetectCustomPublicKey(std::addressof(custom_public_key), work_buffer, boot_image_update_type));
/* Compare BCT hashes. */
if (!custom_public_key) {
R_TRY(boot0_accessor.GetHash(nand_hash, BctSize, work_buffer, work_buffer_size, Boot0Partition::BctSafeMain));
R_TRY(ValidateBctFileHash(boot0_accessor, Boot0Partition::BctSafeMain, nand_hash, work_buffer, work_buffer_size, boot_image_update_type));
}
/* Compare BCT Sub hashes. */
R_TRY(boot0_accessor.GetHash(nand_hash, BctSize, work_buffer, work_buffer_size, Boot0Partition::BctSafeSub));
R_TRY(ValidateBctFileHash(boot0_accessor, Boot0Partition::BctSafeSub, nand_hash, work_buffer, work_buffer_size, boot_image_update_type));
/* Compare Package1 Normal/Sub hashes. */
R_TRY(GetFileHash(std::addressof(size), file_hash, GetPackage1Path(boot_image_update_type), work_buffer, work_buffer_size));
R_TRY(boot1_accessor.GetHash(nand_hash, size, work_buffer, work_buffer_size, Boot1Partition::Package1SafeMain));
R_TRY(CompareHash(file_hash, nand_hash, sizeof(file_hash)));
R_TRY(boot1_accessor.GetHash(nand_hash, size, work_buffer, work_buffer_size, Boot1Partition::Package1SafeSub));
R_TRY(CompareHash(file_hash, nand_hash, sizeof(file_hash)));
/* Compare Package2 Normal/Sub hashes. */
R_TRY(GetFileHash(std::addressof(size), file_hash, GetPackage2Path(boot_image_update_type), work_buffer, work_buffer_size));
R_TRY(GetPackage2Hash(nand_hash, size, work_buffer, work_buffer_size, Package2Type::SafeMain));
R_TRY(CompareHash(file_hash, nand_hash, sizeof(file_hash)));
R_TRY(GetPackage2Hash(nand_hash, size, work_buffer, work_buffer_size, Package2Type::SafeSub));
R_TRY(CompareHash(file_hash, nand_hash, sizeof(file_hash)));
}
R_SUCCEED();
}
Result UpdateBootImagesNormal(ncm::SystemDataId data_id, void *work_buffer, size_t work_buffer_size, BootImageUpdateType boot_image_update_type) {
/* Ensure work buffer is big enough for us to do what we want to do. */
R_TRY(ValidateWorkBuffer(work_buffer, work_buffer_size));
/* Mount the boot image package. */
const char *mount_name = GetMountName();
R_TRY_CATCH(fs::MountSystemData(mount_name, data_id)) {
R_CONVERT(fs::ResultTargetNotFound, updater::ResultBootImagePackageNotFound())
} R_END_TRY_CATCH;
ON_SCOPE_EXIT { fs::Unmount(mount_name); };
{
Boot0Accessor boot0_accessor;
R_TRY(boot0_accessor.Initialize());
ON_SCOPE_EXIT { boot0_accessor.Finalize(); };
/* Detect the use of custom public key. */
/* If custom public key is present, we want to update BCT Sub but not Main */
bool custom_public_key = false;
R_TRY(boot0_accessor.DetectCustomPublicKey(std::addressof(custom_public_key), work_buffer, boot_image_update_type));
/* Write Package1 sub. */
R_TRY(boot0_accessor.Clear(work_buffer, work_buffer_size, Boot0Partition::Package1NormalSub));
R_TRY(boot0_accessor.Write(GetPackage1Path(boot_image_update_type), work_buffer, work_buffer_size, Boot0Partition::Package1NormalSub));
/* Write Package2 sub. */
R_TRY(WritePackage2(work_buffer, work_buffer_size, Package2Type::NormalSub, boot_image_update_type));
/* Write BCT sub + BCT main, in that order. */
{
void *bct = reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(work_buffer) + 0);
void *work = reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(work_buffer) + BctSize);
size_t size;
R_TRY(ReadFile(std::addressof(size), bct, BctSize, GetBctPath(boot_image_update_type)));
if (HasEks(boot_image_update_type)) {
R_TRY(boot0_accessor.UpdateEks(bct, work));
}
/* Only preserve autorcm if on a unit with unpatched rcm bug. */
#if defined(ATMOSPHERE_BOARD_NINTENDO_NX)
if (HasAutoRcmPreserve(boot_image_update_type) && !exosphere::IsRcmBugPatched()) {
R_TRY(boot0_accessor.PreserveAutoRcm(bct, work, Boot0Partition::BctNormalSub));
R_TRY(boot0_accessor.Write(bct, BctSize, Boot0Partition::BctNormalSub));
if (!custom_public_key) {
R_TRY(boot0_accessor.PreserveAutoRcm(bct, work, Boot0Partition::BctNormalMain));
R_TRY(boot0_accessor.Write(bct, BctSize, Boot0Partition::BctNormalMain));
}
} else {
#else
{
#endif
R_TRY(boot0_accessor.Write(bct, BctSize, Boot0Partition::BctNormalSub));
if (!custom_public_key) {
R_TRY(boot0_accessor.Write(bct, BctSize, Boot0Partition::BctNormalMain));
}
}
}
/* Write Package2 main. */
R_TRY(WritePackage2(work_buffer, work_buffer_size, Package2Type::NormalMain, boot_image_update_type));
/* Write Package1 main. */
R_TRY(boot0_accessor.Clear(work_buffer, work_buffer_size, Boot0Partition::Package1NormalMain));
R_TRY(boot0_accessor.Write(GetPackage1Path(boot_image_update_type), work_buffer, work_buffer_size, Boot0Partition::Package1NormalMain));
}
R_SUCCEED();
}
Result UpdateBootImagesSafe(ncm::SystemDataId data_id, void *work_buffer, size_t work_buffer_size, BootImageUpdateType boot_image_update_type) {
/* Ensure work buffer is big enough for us to do what we want to do. */
R_TRY(ValidateWorkBuffer(work_buffer, work_buffer_size));
/* Mount the boot image package. */
const char *mount_name = GetMountName();
R_TRY_CATCH(fs::MountSystemData(mount_name, data_id)) {
R_CONVERT(fs::ResultTargetNotFound, updater::ResultBootImagePackageNotFound())
} R_END_TRY_CATCH;
ON_SCOPE_EXIT { fs::Unmount(mount_name); };
{
Boot0Accessor boot0_accessor;
R_TRY(boot0_accessor.Initialize());
ON_SCOPE_EXIT { boot0_accessor.Finalize(); };
Boot1Accessor boot1_accessor;
R_TRY(boot1_accessor.Initialize());
ON_SCOPE_EXIT { boot1_accessor.Finalize(); };
/* Detect the use of custom public key. */
/* If custom public key is present, we want to update BCT Sub but not Main */
bool custom_public_key = false;
R_TRY(boot0_accessor.DetectCustomPublicKey(std::addressof(custom_public_key), work_buffer, boot_image_update_type));
/* Write Package1 sub. */
R_TRY(boot1_accessor.Clear(work_buffer, work_buffer_size, Boot1Partition::Package1SafeSub));
R_TRY(boot1_accessor.Write(GetPackage1Path(boot_image_update_type), work_buffer, work_buffer_size, Boot1Partition::Package1SafeSub));
/* Write Package2 sub. */
R_TRY(WritePackage2(work_buffer, work_buffer_size, Package2Type::SafeSub, boot_image_update_type));
/* Write BCT sub + BCT main, in that order. */
{
void *bct = reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(work_buffer) + 0);
void *work = reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(work_buffer) + BctSize);
size_t size;
R_TRY(ReadFile(std::addressof(size), bct, BctSize, GetBctPath(boot_image_update_type)));
if (HasEks(boot_image_update_type)) {
R_TRY(boot0_accessor.UpdateEks(bct, work));
}
/* Only preserve autorcm if on a unit with unpatched rcm bug. */
#if defined(ATMOSPHERE_BOARD_NINTENDO_NX)
if (HasAutoRcmPreserve(boot_image_update_type) && !exosphere::IsRcmBugPatched()) {
R_TRY(boot0_accessor.PreserveAutoRcm(bct, work, Boot0Partition::BctSafeSub));
R_TRY(boot0_accessor.Write(bct, BctSize, Boot0Partition::BctSafeSub));
if (!custom_public_key) {
R_TRY(boot0_accessor.PreserveAutoRcm(bct, work, Boot0Partition::BctSafeMain));
R_TRY(boot0_accessor.Write(bct, BctSize, Boot0Partition::BctSafeMain));
}
} else {
#else
{
#endif
R_TRY(boot0_accessor.Write(bct, BctSize, Boot0Partition::BctSafeSub));
if (!custom_public_key) {
R_TRY(boot0_accessor.Write(bct, BctSize, Boot0Partition::BctSafeMain));
}
}
}
/* Write Package2 main. */
R_TRY(WritePackage2(work_buffer, work_buffer_size, Package2Type::SafeMain, boot_image_update_type));
/* Write Package1 main. */
R_TRY(boot1_accessor.Clear(work_buffer, work_buffer_size, Boot1Partition::Package1SafeMain));
R_TRY(boot1_accessor.Write(GetPackage1Path(boot_image_update_type), work_buffer, work_buffer_size, Boot1Partition::Package1SafeMain));
}
R_SUCCEED();
}
Result SetVerificationNeeded(BootModeType mode, void *work_buffer, size_t work_buffer_size, bool needed) {
/* Ensure work buffer is big enough for us to do what we want to do. */
R_TRY(ValidateWorkBuffer(work_buffer, work_buffer_size));
/* Initialize boot0 save accessor. */
BisSave save;
R_TRY(save.Initialize(work_buffer, work_buffer_size));
ON_SCOPE_EXIT { save.Finalize(); };
/* Load save from NAND. */
R_TRY(save.Load());
/* Set whether we need to verify, then save to nand. */
save.SetNeedsVerification(mode, needed);
R_TRY(save.Save());
R_SUCCEED();
}
Result ValidateBctFileHash(Boot0Accessor &accessor, Boot0Partition which, const void *stored_hash, void *work_buffer, size_t work_buffer_size, BootImageUpdateType boot_image_update_type) {
/* Ensure work buffer is big enough for us to do what we want to do. */
R_TRY(ValidateWorkBuffer(work_buffer, work_buffer_size));
void *bct = reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(work_buffer) + 0);
void *work = reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(work_buffer) + BctSize);
size_t size;
R_TRY(ReadFile(std::addressof(size), bct, BctSize, GetBctPath(boot_image_update_type)));
if (HasEks(boot_image_update_type)) {
R_TRY(accessor.UpdateEks(bct, work));
}
if (HasAutoRcmPreserve(boot_image_update_type)) {
R_TRY(accessor.PreserveAutoRcm(bct, work, which));
}
u8 file_hash[crypto::Sha256Generator::HashSize];
crypto::GenerateSha256(file_hash, sizeof(file_hash), bct, BctSize);
R_RETURN(CompareHash(file_hash, stored_hash, sizeof(file_hash)));
}
Result GetPackage2Hash(void *dst_hash, size_t package2_size, void *work_buffer, size_t work_buffer_size, Package2Type which) {
Package2Accessor accessor(which);
R_TRY(accessor.Initialize());
ON_SCOPE_EXIT { accessor.Finalize(); };
R_RETURN(accessor.GetHash(dst_hash, package2_size, work_buffer, work_buffer_size, Package2Partition::Package2));
}
Result WritePackage2(void *work_buffer, size_t work_buffer_size, Package2Type which, BootImageUpdateType boot_image_update_type) {
Package2Accessor accessor(which);
R_TRY(accessor.Initialize());
ON_SCOPE_EXIT { accessor.Finalize(); };
R_RETURN(accessor.Write(GetPackage2Path(boot_image_update_type), work_buffer, work_buffer_size, Package2Partition::Package2));
}
Result CompareHash(const void *lhs, const void *rhs, size_t size) {
R_UNLESS(crypto::IsSameBytes(lhs, rhs, size), updater::ResultNeedsRepairBootImages());
R_SUCCEED();
}
}
BootImageUpdateType GetBootImageUpdateType(spl::HardwareType hw_type) {
switch (hw_type) {
case spl::HardwareType::Icosa:
case spl::HardwareType::Copper:
return BootImageUpdateType::Erista;
case spl::HardwareType::Hoag:
case spl::HardwareType::Iowa:
case spl::HardwareType::Calcio:
case spl::HardwareType::Aula:
return BootImageUpdateType::Mariko;
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
BootImageUpdateType GetBootImageUpdateType(int boot_image_update_type) {
switch (boot_image_update_type) {
case 0:
return BootImageUpdateType::Erista;
case 1:
return BootImageUpdateType::Mariko;
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
Result GetBootImagePackageId(ncm::SystemDataId *out_data_id, BootModeType mode, void *work_buffer, size_t work_buffer_size) {
/* Ensure we can read content metas. */
constexpr size_t MaxContentMetas = 0x40;
AMS_ABORT_UNLESS(work_buffer_size >= sizeof(ncm::ContentMetaKey) * MaxContentMetas);
/* Open NAND System meta database, list contents. */
ncm::ContentMetaDatabase db;
R_TRY(ncm::OpenContentMetaDatabase(std::addressof(db), ncm::StorageId::BuiltInSystem));
ncm::ContentMetaKey *keys = reinterpret_cast<ncm::ContentMetaKey *>(work_buffer);
const auto content_meta_type = GetContentMetaType(mode);
auto count = db.ListContentMeta(keys, MaxContentMetas, content_meta_type);
R_UNLESS(count.total > 0, updater::ResultBootImagePackageNotFound());
/* Output is sorted, return the lowest valid exfat entry. */
if (count.total > 1) {
for (auto i = 0; i < count.total; i++) {
u8 attr;
R_TRY(db.GetAttributes(std::addressof(attr), keys[i]));
if (attr & ncm::ContentMetaAttribute_IncludesExFatDriver) {
out_data_id->value = keys[i].id;
R_SUCCEED();
}
}
}
/* If there's only one entry or no exfat entries, return that entry. */
out_data_id->value = keys[0].id;
R_SUCCEED();
}
Result MarkVerifyingRequired(BootModeType mode, void *work_buffer, size_t work_buffer_size) {
R_RETURN(SetVerificationNeeded(mode, work_buffer, work_buffer_size, true));
}
Result MarkVerified(BootModeType mode, void *work_buffer, size_t work_buffer_size) {
R_RETURN(SetVerificationNeeded(mode, work_buffer, work_buffer_size, false));
}
Result UpdateBootImagesFromPackage(ncm::SystemDataId data_id, BootModeType mode, void *work_buffer, size_t work_buffer_size, BootImageUpdateType boot_image_update_type) {
switch (mode) {
case BootModeType::Normal:
R_RETURN(UpdateBootImagesNormal(data_id, work_buffer, work_buffer_size, boot_image_update_type));
case BootModeType::Safe:
R_RETURN(UpdateBootImagesSafe(data_id, work_buffer, work_buffer_size, boot_image_update_type));
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
Result VerifyBootImagesAndRepairIfNeeded(bool *out_repaired_normal, bool *out_repaired_safe, void *work_buffer, size_t work_buffer_size, BootImageUpdateType boot_image_update_type) {
/* Always set output to false before doing anything else. */
*out_repaired_normal = false;
*out_repaired_safe = false;
/* Ensure work buffer is big enough for us to do what we want to do. */
R_TRY(ValidateWorkBuffer(work_buffer, work_buffer_size));
/* Get verification state from NAND. */
VerificationState verification_state;
R_TRY(GetVerificationState(std::addressof(verification_state), work_buffer, work_buffer_size));
/* If we don't need to verify anything, we're done. */
if (!verification_state.needs_verify_normal && !verification_state.needs_verify_safe) {
R_SUCCEED();
}
/* Get a session to ncm. */
ncm::Initialize();
ON_SCOPE_EXIT { ncm::Finalize(); };
/* Verify normal, verify safe as needed. */
if (verification_state.needs_verify_normal) {
R_TRY_CATCH(VerifyBootImagesAndRepairIfNeeded(out_repaired_normal, BootModeType::Normal, work_buffer, work_buffer_size, boot_image_update_type)) {
R_CATCH(ResultBootImagePackageNotFound) { /* Nintendo considers failure to locate bip a success. TODO: don't do that? */ }
} R_END_TRY_CATCH;
}
if (verification_state.needs_verify_safe) {
R_TRY_CATCH(VerifyBootImagesAndRepairIfNeeded(out_repaired_safe, BootModeType::Safe, work_buffer, work_buffer_size, boot_image_update_type)) {
R_CATCH(ResultBootImagePackageNotFound) { /* Nintendo considers failure to locate bip a success. TODO: don't do that? */ }
} R_END_TRY_CATCH;
}
R_SUCCEED();
}
}
| 29,922
|
C++
|
.cpp
| 468
| 49.805556
| 196
| 0.618853
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,467
|
updater_bis_save.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/updater/updater_bis_save.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 "updater_bis_save.hpp"
namespace ams::updater {
size_t BisSave::GetVerificationFlagOffset(BootModeType mode) {
switch (mode) {
case BootModeType::Normal:
return 0;
case BootModeType::Safe:
return 1;
default:
return 2;
}
}
Result BisSave::Initialize(void *work_buffer, size_t work_buffer_size) {
AMS_ABORT_UNLESS(work_buffer_size >= SaveSize);
AMS_ABORT_UNLESS(util::IsAligned(reinterpret_cast<uintptr_t>(work_buffer), os::MemoryPageSize));
AMS_ABORT_UNLESS(util::IsAligned(work_buffer_size, 0x200));
R_TRY(m_accessor.Initialize());
m_save_buffer = work_buffer;
R_SUCCEED();
}
void BisSave::Finalize() {
m_accessor.Finalize();
}
Result BisSave::Load() {
size_t read_size;
R_RETURN(m_accessor.Read(std::addressof(read_size), m_save_buffer, SaveSize, Boot0Partition::BctSave));
}
Result BisSave::Save() {
R_RETURN(m_accessor.Write(m_save_buffer, SaveSize, Boot0Partition::BctSave));
}
bool BisSave::GetNeedsVerification(BootModeType mode) {
return reinterpret_cast<const u8 *>(m_save_buffer)[GetVerificationFlagOffset(mode)] != 0;
}
void BisSave::SetNeedsVerification(BootModeType mode, bool needs_verification) {
reinterpret_cast<u8 *>(m_save_buffer)[GetVerificationFlagOffset(mode)] = needs_verification ? 1 : 0;
}
}
| 2,150
|
C++
|
.cpp
| 53
| 34.358491
| 111
| 0.678965
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,468
|
wec_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/wec/wec_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 <stratosphere.hpp>
namespace ams::wec {
/* TODO: How much of this should be namespaced under BOARD_NINTENDO_NX? */
#if defined(ATMOSPHERE_BOARD_NINTENDO_NX)
namespace {
constexpr inline dd::PhysicalAddress ApbdevPmc = 0x7000E400;
constinit bool g_initialized = false;
void UpdateControlBit(dd::PhysicalAddress phys_addr, u32 mask, bool flag) {
dd::ReadModifyWriteIoRegister(phys_addr, flag ? ~0u : 0u, mask);
dd::ReadIoRegister(phys_addr);
}
void Initialize(bool blink) {
/* Initialize WAKE_DEBOUNCE_EN. */
dd::WriteIoRegister(ApbdevPmc + APBDEV_PMC_WAKE_DEBOUNCE_EN, 0);
dd::ReadIoRegister(ApbdevPmc + APBDEV_PMC_WAKE_DEBOUNCE_EN);
/* Initialize BLINK_TIMER. */
dd::WriteIoRegister(ApbdevPmc + APBDEV_PMC_BLINK_TIMER, 0x08008800);
dd::ReadIoRegister(ApbdevPmc + APBDEV_PMC_BLINK_TIMER);
/* Set control configs. */
UpdateControlBit(ApbdevPmc + APBDEV_PMC_CNTRL, 0x0800, true);
UpdateControlBit(ApbdevPmc + APBDEV_PMC_CNTRL, 0x0400, false);
UpdateControlBit(ApbdevPmc + APBDEV_PMC_CNTRL, 0x0200, true);
UpdateControlBit(ApbdevPmc + APBDEV_PMC_CNTRL, 0x0100, false);
UpdateControlBit(ApbdevPmc + APBDEV_PMC_CNTRL, 0x0040, false);
UpdateControlBit(ApbdevPmc + APBDEV_PMC_CNTRL, 0x0020, false);
UpdateControlBit(ApbdevPmc + APBDEV_PMC_CNTRL2, 0x4000, true);
UpdateControlBit(ApbdevPmc + APBDEV_PMC_CNTRL2, 0x0200, false);
UpdateControlBit(ApbdevPmc + APBDEV_PMC_CNTRL2, 0x0001, true);
/* Update blink bit in APBDEV_PMC_CNTRL. */
UpdateControlBit(ApbdevPmc + APBDEV_PMC_CNTRL, 0x0080, blink);
/* Update blink bit in APBDEV_PMC_DPD_PADS_ORIDE. */
UpdateControlBit(ApbdevPmc + APBDEV_PMC_DPD_PADS_ORIDE, 0x100000, blink);
}
}
void Initialize() {
/* Set initial wake configuration. */
if (!g_initialized) {
Initialize(false);
g_initialized = true;
}
}
void ClearWakeEvents() {
/* TODO */
AMS_ABORT();
}
void WecRestoreForExitSuspend() {
/* TODO */
AMS_ABORT();
}
void SetWakeEventLevel(wec::WakeEvent event, wec::WakeEventLevel level) {
if (g_initialized && event < wec::WakeEvent_Count) {
/* Determine the event index. */
const bool which = static_cast<u32>(event) < BITSIZEOF(u32);
const u32 index = static_cast<u32>(event) & (BITSIZEOF(u32) - 1);
/* Get the level and auto_mask offsets. */
u32 level_ofs = which ? APBDEV_PMC_WAKE_LVL : APBDEV_PMC_WAKE2_LVL;
u32 auto_mask_ofs = which ? APBDEV_PMC_AUTO_WAKE_LVL_MASK : APBDEV_PMC_AUTO_WAKE2_LVL_MASK;
/* If the level isn't auto, swap the offsets. */
if (level != wec::WakeEventLevel_Auto) {
std::swap(level_ofs, auto_mask_ofs);
}
/* Clear the bit in the level register. */
UpdateControlBit(ApbdevPmc + level_ofs, (1u << index), false);
/* Set or clear the bit in the auto mask register. */
UpdateControlBit(ApbdevPmc + auto_mask_ofs, (1u << index), level != wec::WakeEventLevel_Low);
}
}
void SetWakeEventEnabled(wec::WakeEvent event, bool en) {
if (g_initialized && event < wec::WakeEvent_Count) {
/* Set or clear the relevant enabled bit. */
const u32 offset = static_cast<u32>(event) < BITSIZEOF(u32) ? APBDEV_PMC_WAKE_MASK : APBDEV_PMC_WAKE2_MASK;
const u32 index = static_cast<u32>(event) & (BITSIZEOF(u32) - 1);
UpdateControlBit(ApbdevPmc + offset, (1u << index), en);
}
}
#endif
}
| 4,518
|
C++
|
.cpp
| 92
| 40.076087
| 119
| 0.63042
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,469
|
sprofile_srv_profile_manager.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/sprofile/srv/sprofile_srv_profile_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 "sprofile_srv_profile_manager.hpp"
#include "sprofile_srv_fs_utils.hpp"
namespace ams::sprofile::srv {
namespace {
constexpr const char PrimaryDirectoryName[] = "primary";
constexpr const char TemporaryDirectoryName[] = "temp";
Result CreateSaveData(const ProfileManager::SaveDataInfo &save_data_info) {
R_TRY_CATCH(fs::CreateSystemSaveData(save_data_info.id, save_data_info.size, save_data_info.journal_size, save_data_info.flags)) {
R_CATCH(fs::ResultPathAlreadyExists) { /* Nintendo accepts already-existing savedata here. */ }
} R_END_TRY_CATCH;
R_SUCCEED();
}
void SafePrint(char *dst, size_t dst_size, const char *fmt, ...) __attribute__((format(printf, 3, 4)));
void SafePrint(char *dst, size_t dst_size, const char *fmt, ...) {
std::va_list vl;
va_start(vl, fmt);
const size_t len = util::TVSNPrintf(dst, dst_size, fmt, vl);
va_end(vl);
AMS_ABORT_UNLESS(len < dst_size);
}
void CreateMetadataPathImpl(char *dst, size_t dst_size, const char *mount, const char *dir) {
SafePrint(dst, dst_size, "%s:/%s/metadata", mount, dir);
}
void CreatePrimaryMetadataPath(char *dst, size_t dst_size, const char *mount) {
CreateMetadataPathImpl(dst, dst_size, mount, PrimaryDirectoryName);
}
void CreateTemporaryMetadataPath(char *dst, size_t dst_size, const char *mount) {
CreateMetadataPathImpl(dst, dst_size, mount, TemporaryDirectoryName);
}
void CreateProfilePathImpl(char *dst, size_t dst_size, const char *mount, const char *dir, const Identifier &id) {
SafePrint(dst, dst_size, "%s:/%s/profiles/%02x%02x%02x%02x%02x%02x%02x", mount, dir, id.data[0], id.data[1], id.data[2], id.data[3], id.data[4], id.data[5], id.data[6]);
}
void CreatePrimaryProfilePath(char *dst, size_t dst_size, const char *mount, const Identifier &id) {
CreateProfilePathImpl(dst, dst_size, mount, PrimaryDirectoryName, id);
}
void CreateTemporaryProfilePath(char *dst, size_t dst_size, const char *mount, const Identifier &id) {
CreateProfilePathImpl(dst, dst_size, mount, TemporaryDirectoryName, id);
}
void CreateDirectoryPathImpl(char *dst, size_t dst_size, const char *mount, const char *dir) {
SafePrint(dst, dst_size, "%s:/%s", mount, dir);
}
void CreatePrimaryDirectoryPath(char *dst, size_t dst_size, const char *mount) {
CreateDirectoryPathImpl(dst, dst_size, mount, PrimaryDirectoryName);
}
void CreateTemporaryDirectoryPath(char *dst, size_t dst_size, const char *mount) {
CreateDirectoryPathImpl(dst, dst_size, mount, TemporaryDirectoryName);
}
void CreateProfileDirectoryPathImpl(char *dst, size_t dst_size, const char *mount, const char *dir) {
SafePrint(dst, dst_size, "%s:/%s/profiles", mount, dir);
}
void CreatePrimaryProfileDirectoryPath(char *dst, size_t dst_size, const char *mount) {
CreateProfileDirectoryPathImpl(dst, dst_size, mount, PrimaryDirectoryName);
}
void CreateTemporaryProfileDirectoryPath(char *dst, size_t dst_size, const char *mount) {
CreateProfileDirectoryPathImpl(dst, dst_size, mount, TemporaryDirectoryName);
}
}
ProfileManager::ProfileManager(const SaveDataInfo &save_data_info)
: m_save_data_info(save_data_info), m_save_file_mounted(false), m_profile_importer(util::nullopt),
m_profile_metadata(util::nullopt), m_service_profile(util::nullopt), m_update_observer_manager()
{
/* ... */
}
void ProfileManager::InitializeSaveData() {
/* Acquire locks. */
std::scoped_lock lk1(m_general_mutex);
std::scoped_lock lk2(m_fs_mutex);
/* Ensure the savedata exists. */
if (R_SUCCEEDED(CreateSaveData(m_save_data_info))) {
m_save_file_mounted = R_SUCCEEDED(fs::MountSystemSaveData(m_save_data_info.mount_name, m_save_data_info.id));
}
}
Result ProfileManager::ResetSaveData() {
/* Acquire locks. */
std::scoped_lock lk1(m_service_profile_mutex);
std::scoped_lock lk2(m_profile_metadata_mutex);
std::scoped_lock lk3(m_general_mutex);
std::scoped_lock lk4(m_fs_mutex);
/* Unmount save file. */
fs::Unmount(m_save_data_info.mount_name);
m_save_file_mounted = false;
/* Delete save file. */
R_TRY(fs::DeleteSystemSaveData(fs::SaveDataSpaceId::System, m_save_data_info.id, fs::InvalidUserId));
/* Unload profile. */
m_profile_metadata = util::nullopt;
m_service_profile = util::nullopt;
/* Create the save data. */
R_TRY(CreateSaveData(m_save_data_info));
/* Try to mount the save file. */
const auto result = fs::MountSystemSaveData(m_save_data_info.mount_name, m_save_data_info.id);
m_save_file_mounted = R_SUCCEEDED(result);
R_RETURN(result);
}
Result ProfileManager::OpenProfileImporter() {
/* Acquire locks. */
std::scoped_lock lk1(m_profile_metadata_mutex);
std::scoped_lock lk2(m_profile_importer_mutex);
std::scoped_lock lk3(m_general_mutex);
/* Check that we don't already have an importer. */
R_UNLESS(!m_profile_importer.has_value(), sprofile::ResultInvalidState());
/* Try to load profile metadata. NOTE: result is not checked, it is okay if this fails. */
this->LoadPrimaryMetadataImpl();
/* Create importer. */
m_profile_importer.emplace(m_profile_metadata);
R_SUCCEED();
}
void ProfileManager::CloseProfileImporterImpl() {
/* Check pre-conditions. */
AMS_ASSERT(m_profile_importer_mutex.IsLockedByCurrentThread());
AMS_ASSERT(m_general_mutex.IsLockedByCurrentThread());
AMS_ASSERT(m_fs_mutex.IsLockedByCurrentThread());
if (m_profile_importer.has_value()) {
/* Unmount save file. */
fs::Unmount(m_save_data_info.mount_name);
m_save_file_mounted = false;
/* Re-mount save file. */
R_ABORT_UNLESS(fs::MountSystemSaveData(m_save_data_info.mount_name, m_save_data_info.id));
m_save_file_mounted = true;
/* Reset our importer. */
m_profile_importer = util::nullopt;
}
}
void ProfileManager::CloseProfileImporter() {
/* Acquire locks. */
std::scoped_lock lk1(m_profile_importer_mutex);
std::scoped_lock lk2(m_general_mutex);
std::scoped_lock lk3(m_fs_mutex);
/* Close our importer. */
this->CloseProfileImporterImpl();
}
Result ProfileManager::ImportProfile(const sprofile::srv::ProfileDataForImportData &import) {
/* Acquire locks. */
std::scoped_lock lk1(m_profile_importer_mutex);
std::scoped_lock lk2(m_fs_mutex);
/* Check that we have an importer. */
R_UNLESS(m_profile_importer.has_value(), sprofile::ResultInvalidState());
/* Check that the metadata we're importing is a valid version. */
R_UNLESS(IsValidProfileFormatVersion(import.header.version), sprofile::ResultInvalidDataVersion());
/* Check that the metadata we're importing has a valid hash. */
{
crypto::Md5Generator md5;
md5.Initialize();
md5.Update(std::addressof(import.header), sizeof(import.header));
md5.Update(std::addressof(import.data), sizeof(import.data) - sizeof(import.data.entries[0]) * (util::size(import.data.entries) - std::min<size_t>(import.data.num_entries, util::size(import.data.entries))));
u8 hash[crypto::Md5Generator::HashSize];
md5.GetHash(hash, sizeof(hash));
R_UNLESS(crypto::IsSameBytes(hash, import.hash, sizeof(hash)), sprofile::ResultInvalidDataHash());
}
/* Succeed if we already have the profile. */
R_SUCCEED_IF(m_profile_importer->HasProfile(import.header.identifier_0, import.header.identifier_1));
/* Check that we're importing the profile. */
R_UNLESS(m_profile_importer->CanImportProfile(import.header.identifier_0), sprofile::ResultInvalidState());
/* Create temporary directories. */
R_TRY(this->EnsureTemporaryDirectories());
/* Create profile. */
char path[0x30];
CreateTemporaryProfilePath(path, sizeof(path), m_save_data_info.mount_name, import.header.identifier_0);
R_TRY(WriteFile(path, std::addressof(import.data), sizeof(import.data)));
/* Set profile imported. */
m_profile_importer->OnImportProfile(import.header.identifier_0);
R_SUCCEED();
}
Result ProfileManager::Commit() {
/* Acquire locks. */
std::scoped_lock lk1(m_service_profile_mutex);
std::scoped_lock lk2(m_profile_metadata_mutex);
std::scoped_lock lk3(m_profile_importer_mutex);
std::scoped_lock lk4(m_general_mutex);
std::scoped_lock lk5(m_fs_mutex);
/* Check that we have an importer. */
R_UNLESS(m_profile_importer.has_value(), sprofile::ResultInvalidState());
/* Commit, and if we fail remount our save. */
{
/* If we fail, close our importer. */
ON_RESULT_FAILURE { this->CloseProfileImporterImpl(); };
/* Check that we can commit the importer. */
R_UNLESS(m_profile_importer->CanCommit(), sprofile::ResultInvalidState());
/* Commit newly imported profiles. */
R_TRY(this->CommitImportedProfiles());
/* Cleanup orphaned profiles. */
R_TRY(this->CleanupOrphanedProfiles());
/* Commit the save file. */
R_TRY(fs::CommitSaveData(m_save_data_info.mount_name));
}
/* NOTE: Here nintendo generates an "sprofile_update_profile" sreport with the new and old revision keys. */
/* Handle tasks for when we've committed (including notifying update observers). */
this->OnCommitted();
R_SUCCEED();
}
Result ProfileManager::ImportMetadata(const sprofile::srv::ProfileMetadataForImportMetadata &import) {
/* Acquire locks. */
std::scoped_lock lk1(m_profile_importer_mutex);
std::scoped_lock lk2(m_fs_mutex);
/* Check that we can import metadata. */
R_UNLESS(m_profile_importer.has_value(), sprofile::ResultInvalidState());
R_UNLESS(m_profile_importer->CanImportMetadata(), sprofile::ResultInvalidState());
/* Check that the metadata we're importing is a valid version. */
R_UNLESS(IsValidProfileFormatVersion(import.header.version), sprofile::ResultInvalidMetadataVersion());
/* Check that the metadata we're importing has a valid hash. */
{
crypto::Md5Generator md5;
md5.Initialize();
md5.Update(std::addressof(import.header), sizeof(import.header));
md5.Update(std::addressof(import.metadata), sizeof(import.metadata));
md5.Update(std::addressof(import.profile_urls), sizeof(import.profile_urls[0]) * std::min<size_t>(import.metadata.num_entries, util::size(import.metadata.entries)));
u8 hash[crypto::Md5Generator::HashSize];
md5.GetHash(hash, sizeof(hash));
R_UNLESS(crypto::IsSameBytes(hash, import.hash, sizeof(hash)), sprofile::ResultInvalidMetadataHash());
}
/* Create temporary directories. */
R_TRY(this->EnsureTemporaryDirectories());
/* Create metadata. */
char path[0x30];
CreateTemporaryMetadataPath(path, sizeof(path), m_save_data_info.mount_name);
R_TRY(WriteFile(path, std::addressof(import.metadata), sizeof(import.metadata)));
/* Import the metadata. */
m_profile_importer->ImportMetadata(import.metadata);
R_SUCCEED();
}
Result ProfileManager::LoadPrimaryMetadataImpl() {
/* Check pre-conditions. */
AMS_ASSERT(m_profile_metadata_mutex.IsLockedByCurrentThread());
AMS_ASSERT(m_general_mutex.IsLockedByCurrentThread());
/* If we don't have metadata, load it. */
if (!m_profile_metadata.has_value()) {
/* Emplace our metadata. */
m_profile_metadata.emplace();
ON_RESULT_FAILURE { m_profile_metadata = util::nullopt; };
/* Read profile metadata. */
char path[0x30];
CreatePrimaryMetadataPath(path, sizeof(path), m_save_data_info.mount_name);
R_TRY(ReadFile(path, std::addressof(*m_profile_metadata), sizeof(*m_profile_metadata), 0));
}
/* We now have loaded metadata. */
R_SUCCEED();
}
Result ProfileManager::LoadPrimaryMetadata(ProfileMetadata *out) {
/* Acquire locks. */
std::scoped_lock lk1(m_profile_metadata_mutex);
std::scoped_lock lk2(m_general_mutex);
/* Load our metadata. */
R_TRY(this->LoadPrimaryMetadataImpl());
/* Set the output. */
*out = *m_profile_metadata;
R_SUCCEED();
}
Result ProfileManager::LoadProfile(Identifier profile) {
/* Check if we already have the profile. */
if (m_service_profile.has_value()) {
R_SUCCEED_IF(m_service_profile->name == profile);
}
/* If we fail past this point, we want to have no profile. */
auto prof_guard = SCOPE_GUARD { m_service_profile = util::nullopt; };
/* Create profile path. */
char path[0x30];
CreatePrimaryProfilePath(path, sizeof(path), m_save_data_info.mount_name, profile);
/* Load the profile. */
m_service_profile = {};
R_TRY(ReadFile(path, std::addressof(m_service_profile->data), sizeof(m_service_profile->data), 0));
/* We succeeded. */
prof_guard.Cancel();
R_SUCCEED();
}
Result ProfileManager::GetDataEntry(ProfileDataEntry *out, Identifier profile, Identifier key) {
/* Acquire locks. */
std::scoped_lock lk1(m_service_profile_mutex);
std::scoped_lock lk2(m_general_mutex);
/* Load the desired profile. */
if (R_SUCCEEDED(this->LoadProfile(profile))) {
/* Find the specified key. */
for (auto i = 0u; i < std::min<size_t>(m_service_profile->data.num_entries, util::size(m_service_profile->data.entries)); ++i) {
if (m_service_profile->data.entries[i].key == key) {
*out = m_service_profile->data.entries[i];
R_SUCCEED();
}
}
}
R_THROW(sprofile::ResultKeyNotFound());
}
Result ProfileManager::GetSigned64(s64 *out, Identifier profile, Identifier key) {
/* Get the data entry. */
ProfileDataEntry entry;
R_TRY(this->GetDataEntry(std::addressof(entry), profile, key));
/* Check the type. */
R_UNLESS(entry.type == ValueType_S64, sprofile::ResultInvalidDataType());
/* Set the output value. */
*out = entry.value_s64;
R_SUCCEED();
}
Result ProfileManager::GetUnsigned64(u64 *out, Identifier profile, Identifier key) {
/* Get the data entry. */
ProfileDataEntry entry;
R_TRY(this->GetDataEntry(std::addressof(entry), profile, key));
/* Check the type. */
R_UNLESS(entry.type == ValueType_U64, sprofile::ResultInvalidDataType());
/* Set the output value. */
*out = entry.value_u64;
R_SUCCEED();
}
Result ProfileManager::GetSigned32(s32 *out, Identifier profile, Identifier key) {
/* Get the data entry. */
ProfileDataEntry entry;
R_TRY(this->GetDataEntry(std::addressof(entry), profile, key));
/* Check the type. */
R_UNLESS(entry.type == ValueType_S32, sprofile::ResultInvalidDataType());
/* Set the output value. */
*out = entry.value_s32;
R_SUCCEED();
}
Result ProfileManager::GetUnsigned32(u32 *out, Identifier profile, Identifier key) {
/* Get the data entry. */
ProfileDataEntry entry;
R_TRY(this->GetDataEntry(std::addressof(entry), profile, key));
/* Check the type. */
R_UNLESS(entry.type == ValueType_U32, sprofile::ResultInvalidDataType());
/* Set the output value. */
*out = entry.value_u32;
R_SUCCEED();
}
Result ProfileManager::GetByte(u8 *out, Identifier profile, Identifier key) {
/* Get the data entry. */
ProfileDataEntry entry;
R_TRY(this->GetDataEntry(std::addressof(entry), profile, key));
/* Check the type. */
R_UNLESS(entry.type == ValueType_Byte, sprofile::ResultInvalidDataType());
/* Set the output value. */
*out = entry.value_u8;
R_SUCCEED();
}
Result ProfileManager::GetRaw(u8 *out_type, u64 *out_value, Identifier profile, Identifier key) {
/* Get the data entry. */
ProfileDataEntry entry;
R_TRY(this->GetDataEntry(std::addressof(entry), profile, key));
/* Set the output type and value. */
*out_type = entry.type;
*out_value = entry.value_u64;
R_SUCCEED();
}
Result ProfileManager::CommitImportedProfiles() {
/* Ensure primary directories. */
R_TRY(this->EnsurePrimaryDirectories());
/* Declare re-usable paths. */
char tmp_path[0x30];
char pri_path[0x30];
/* Move the metadata. */
{
CreateTemporaryMetadataPath(tmp_path, sizeof(tmp_path), m_save_data_info.mount_name);
CreatePrimaryMetadataPath(pri_path, sizeof(pri_path), m_save_data_info.mount_name);
R_TRY(MoveFile(tmp_path, pri_path));
}
/* Move all newly imported profiles. */
for (auto i = 0; i < m_profile_importer->GetImportingCount(); ++i) {
const auto &profile = m_profile_importer->GetImportingProfile(i);
if (profile.is_new_import) {
CreateTemporaryProfilePath(tmp_path, sizeof(tmp_path), m_save_data_info.mount_name, profile.identifier_0);
CreatePrimaryProfilePath(pri_path, sizeof(pri_path), m_save_data_info.mount_name, profile.identifier_0);
R_TRY(MoveFile(tmp_path, pri_path));
}
}
R_SUCCEED();
}
Result ProfileManager::CleanupOrphanedProfiles() {
/* Check pre-conditions. */
AMS_ASSERT(m_profile_importer.has_value());
/* Declare re-usable path. */
char pri_path[0x30];
/* Cleanup the profiles. */
R_RETURN(m_profile_importer->CleanupOrphanedProfiles([&](Identifier profile) ALWAYS_INLINE_LAMBDA -> Result {
CreatePrimaryProfilePath(pri_path, sizeof(pri_path), m_save_data_info.mount_name, profile);
R_RETURN(DeleteFile(pri_path));
}));
}
void ProfileManager::OnCommitted() {
/* TODO: Here, Nintendo sets the erpt ServiceProfileRevisionKey to the current revision key. */
/* If we need to, invalidate the loaded service profile. */
if (m_service_profile.has_value()) {
for (auto i = 0; i < m_profile_importer->GetImportingCount(); ++i) {
if (m_service_profile->name == m_profile_importer->GetImportingProfile(i).identifier_0) {
m_service_profile = util::nullopt;
break;
}
}
}
/* Reset profile metadata. */
m_profile_metadata = util::nullopt;
/* Invoke any listeners. */
for (auto i = 0; i < m_profile_importer->GetImportingCount(); ++i) {
const auto &profile = m_profile_importer->GetImportingProfile(i);
if (profile.is_new_import) {
m_update_observer_manager.OnUpdate(profile.identifier_0);
}
}
/* Reset profile importer. */
m_profile_importer = util::nullopt;
}
Result ProfileManager::EnsurePrimaryDirectories() {
/* Ensure the primary directories. */
char path[0x30];
CreatePrimaryDirectoryPath(path, sizeof(path), m_save_data_info.mount_name);
R_TRY(EnsureDirectory(path));
CreatePrimaryProfileDirectoryPath(path, sizeof(path), m_save_data_info.mount_name);
R_TRY(EnsureDirectory(path));
R_SUCCEED();
}
Result ProfileManager::EnsureTemporaryDirectories() {
/* Ensure the temporary directories. */
char path[0x30];
CreateTemporaryDirectoryPath(path, sizeof(path), m_save_data_info.mount_name);
R_TRY(EnsureDirectory(path));
CreateTemporaryProfileDirectoryPath(path, sizeof(path), m_save_data_info.mount_name);
R_TRY(EnsureDirectory(path));
R_SUCCEED();
}
}
| 21,657
|
C++
|
.cpp
| 430
| 40.872093
| 219
| 0.631262
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,470
|
sprofile_srv_profile_update_observer_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/sprofile/srv/sprofile_srv_profile_update_observer_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 "sprofile_srv_profile_manager.hpp"
#include "sprofile_srv_profile_update_observer_impl.hpp"
namespace ams::sprofile::srv {
namespace {
class AutoUnregisterObserver : public ProfileUpdateObserverImpl {
private:
ProfileUpdateObserverManager *m_manager;
public:
AutoUnregisterObserver(ProfileUpdateObserverManager *manager) : m_manager(manager) { /* ... */ }
virtual ~AutoUnregisterObserver() { m_manager->CloseObserver(this); }
};
static_assert(sprofile::srv::IsIProfileUpdateObserver<AutoUnregisterObserver>);
}
Result ProfileUpdateObserverManager::OpenObserver(sf::Out<sf::SharedPointer<::ams::sprofile::srv::IProfileUpdateObserver>> &out, MemoryResource *memory_resource) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that we can allocate. */
R_UNLESS(m_observer_count < MaxObservers, sprofile::ResultMaxObservers());
/* Allocate an object. */
auto obj = sf::ObjectFactory<sf::MemoryResourceAllocationPolicy>::CreateSharedEmplaced<IProfileUpdateObserver, AutoUnregisterObserver>(memory_resource, this);
R_UNLESS(obj != nullptr, sprofile::ResultAllocationFailed());
/* Register the observer. */
m_observers[m_observer_count++] = std::addressof(obj.GetImpl());
/* Return the object. */
*out = std::move(obj);
R_SUCCEED();
}
void ProfileUpdateObserverManager::CloseObserver(ProfileUpdateObserverImpl *observer) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Find the observer. */
int index = -1;
for (auto i = 0; i < m_observer_count; ++i) {
if (m_observers[i] == observer) {
index = i;
break;
}
}
AMS_ABORT_UNLESS(index != -1);
/* Remove from our list. */
m_observers[index] = m_observers[--m_observer_count];
/* Sanity check. */
AMS_ABORT_UNLESS(m_observer_count >= 0);
}
}
| 2,747
|
C++
|
.cpp
| 61
| 37.672131
| 167
| 0.659805
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,471
|
sprofile_srv_service_for_bg_agent.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/sprofile/srv/sprofile_srv_service_for_bg_agent.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 "sprofile_srv_profile_manager.hpp"
#include "sprofile_srv_service_for_bg_agent.hpp"
#include "sprofile_srv_profile_importer_impl.hpp"
#include "sprofile_srv_fs_utils.hpp"
namespace ams::sprofile::srv {
Result ServiceForBgAgent::OpenProfileImporter(sf::Out<sf::SharedPointer<::ams::sprofile::srv::IProfileImporter>> out) {
/* Allocate an object. */
auto obj = sf::ObjectFactory<sf::MemoryResourceAllocationPolicy>::CreateSharedEmplaced<IProfileImporter, ProfileImporterImpl>(m_memory_resource, m_profile_manager);
R_UNLESS(obj != nullptr, sprofile::ResultAllocationFailed());
/* Confirm that we can begin an import. */
R_TRY(m_profile_manager->OpenProfileImporter());
/* Return the object. */
*out = std::move(obj);
R_SUCCEED();
}
Result ServiceForBgAgent::GetImportableProfileUrls(sf::Out<u32> out_count, const sf::OutArray<sprofile::srv::ProfileUrl> &out, const sprofile::srv::ProfileMetadataForImportMetadata &arg) {
/* Check size. */
R_UNLESS(out.GetSize() >= arg.metadata.num_entries, sprofile::ResultInvalidArgument());
/* Load primary metadata. */
sprofile::srv::ProfileMetadata primary_metadata;
R_TRY_CATCH(m_profile_manager->LoadPrimaryMetadata(std::addressof(primary_metadata))) {
R_CATCH(fs::ResultPathNotFound) {
/* It's okay if we have no primary metadata -- this means that all profiles are importable. */
primary_metadata.num_entries = 0;
}
} R_END_TRY_CATCH;
/* We want to return the set of profiles that can be imported, which is just the profiles we don't already have. */
u32 count = 0;
for (u32 i = 0; i < arg.metadata.num_entries; ++i) {
const auto &arg_entry = arg.metadata.entries[i];
/* Check if we have the entry. */
bool have_entry = false;
for (u32 j = 0; j < primary_metadata.num_entries; ++j) {
const auto &pri_entry = primary_metadata.entries[j];
if (pri_entry.identifier_0 == arg_entry.identifier_0 && pri_entry.identifier_1 == arg_entry.identifier_1) {
have_entry = true;
break;
}
}
/* If we don't already have the entry, it's importable -- copy it out. */
if (!have_entry) {
out[count++] = arg.profile_urls[i];
}
}
/* Set output count. */
*out_count = count;
R_SUCCEED();
}
Result ServiceForBgAgent::IsUpdateNeeded(sf::Out<bool> out, Identifier revision_key) {
/* Load primary metadata. */
bool loaded_metadata = true;
sprofile::srv::ProfileMetadata primary_metadata;
R_TRY_CATCH(m_profile_manager->LoadPrimaryMetadata(std::addressof(primary_metadata))) {
R_CATCH(fs::ResultPathNotFound) {
/* If we have no metadata, we don't have a revision key. */
loaded_metadata = false;
}
} R_END_TRY_CATCH;
/* Determine if update is needed. */
*out = !(loaded_metadata && revision_key == primary_metadata.revision_key);
R_SUCCEED();
}
Result ServiceForBgAgent::Reset() {
R_RETURN(m_profile_manager->ResetSaveData());
}
}
| 4,015
|
C++
|
.cpp
| 82
| 40.47561
| 192
| 0.639775
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,472
|
sprofile_srv_service_for_system_process.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/sprofile/srv/sprofile_srv_service_for_system_process.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "sprofile_srv_profile_manager.hpp"
#include "sprofile_srv_service_for_system_process.hpp"
#include "sprofile_srv_profile_reader_impl.hpp"
#include "sprofile_srv_profile_controller_for_debug_impl.hpp"
namespace ams::sprofile::srv {
Result ServiceForSystemProcess::OpenProfileReader(sf::Out<sf::SharedPointer<::ams::sprofile::srv::IProfileReader>> out) {
/* Allocate an object. */
auto obj = sf::ObjectFactory<sf::MemoryResourceAllocationPolicy>::CreateSharedEmplaced<IProfileReader, ProfileReaderImpl>(m_memory_resource, m_profile_manager);
R_UNLESS(obj != nullptr, sprofile::ResultAllocationFailed());
/* Return the object. */
*out = std::move(obj);
R_SUCCEED();
}
Result ServiceForSystemProcess::OpenProfileUpdateObserver(sf::Out<sf::SharedPointer<::ams::sprofile::srv::IProfileUpdateObserver>> out) {
R_RETURN(m_profile_manager->GetUpdateObserverManager().OpenObserver(out, m_memory_resource));
}
Result ServiceForSystemProcess::OpenProfileControllerForDebug(sf::Out<sf::SharedPointer<::ams::sprofile::srv::IProfileControllerForDebug>> out) {
/* Require debug mode in order to open a debug controller. */
R_UNLESS(settings::fwdbg::IsDebugModeEnabled(), sprofile::ResultNotPermitted());
/* Allocate an object. */
auto obj = sf::ObjectFactory<sf::MemoryResourceAllocationPolicy>::CreateSharedEmplaced<IProfileControllerForDebug, ProfileControllerForDebugImpl>(m_memory_resource, m_profile_manager);
R_UNLESS(obj != nullptr, sprofile::ResultAllocationFailed());
/* Return the object. */
*out = std::move(obj);
R_SUCCEED();
}
}
| 2,350
|
C++
|
.cpp
| 43
| 49.790698
| 192
| 0.734667
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,473
|
sprofile_srv_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/sprofile/srv/sprofile_srv_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 <stratosphere.hpp>
#include "sprofile_srv_profile_manager.hpp"
#include "sprofile_srv_service_for_bg_agent.hpp"
#include "sprofile_srv_service_for_system_process.hpp"
#include "sprofile_srv_service_getter.hpp"
namespace ams::sprofile::srv {
namespace {
constexpr const ProfileManager::SaveDataInfo SaveDataInfo = {
.id = 0x8000000000000220,
.mount_name = "sprof",
.size = 0x1C0000,
.journal_size = 0x80000,
.flags = fs::SaveDataFlags_KeepAfterResettingSystemSaveData,
};
constexpr const sm::ServiceName ServiceNameForBgAgent = sm::ServiceName::Encode("sprof:bg");
constexpr const sm::ServiceName ServiceNameForSystemProcess = sm::ServiceName::Encode("sprof:sp");
constexpr inline size_t BgAgentSessionCountMax = 2;
constexpr inline size_t SystemProcessSessionCountMax = 10;
constexpr inline size_t SessionCountMax = BgAgentSessionCountMax + SystemProcessSessionCountMax;
constexpr inline size_t PortCountMax = 2;
struct ServerManagerOptions {
static constexpr size_t PointerBufferSize = 0x0;
static constexpr size_t MaxDomains = SessionCountMax; /* NOTE: Official is 9 */
static constexpr size_t MaxDomainObjects = 16; /* NOTE: Official is 14 */
static constexpr bool CanDeferInvokeRequest = false;
static constexpr bool CanManageMitmServers = false;
};
using ServerManager = sf::hipc::ServerManager<PortCountMax, ServerManagerOptions, SessionCountMax>;
constinit util::TypedStorage<ProfileManager> g_profile_manager = {};
constinit util::TypedStorage<sf::UnmanagedServiceObject<ISprofileServiceForBgAgent, ServiceForBgAgent>> g_bg_service_object = {};
constinit util::TypedStorage<sf::UnmanagedServiceObject<ISprofileServiceForSystemProcess, ServiceForSystemProcess>> g_sp_service_object = {};
constinit util::TypedStorage<sf::UnmanagedServiceObject<IServiceGetter, ServiceGetter>> g_bg_service_getter = {};
constinit util::TypedStorage<sf::UnmanagedServiceObject<IServiceGetter, ServiceGetter>> g_sp_service_getter = {};
constinit util::TypedStorage<ServerManager> g_server_manager = {};
alignas(os::ThreadStackAlignment) constinit u8 g_ipc_thread_stack[0x3000];
constinit u8 g_heap[16_KB];
constinit os::ThreadType g_ipc_thread = {};
constinit lmem::HeapHandle g_heap_handle = nullptr;
constinit sf::ExpHeapMemoryResource g_sf_memory_resource;
void IpcServerThreadFunction(void *) {
/* Get the server manager. */
auto &server_manager = util::GetReference(g_server_manager);
/* Resume processing. */
server_manager.ResumeProcessing();
/* Loop processing. */
server_manager.LoopProcess();
}
}
void Initialize() {
/* Initialize heap. */
g_heap_handle = lmem::CreateExpHeap(g_heap, sizeof(g_heap), lmem::CreateOption_ThreadSafe);
/* Attach the memory resource to heap. */
g_sf_memory_resource.Attach(g_heap_handle);
/* Create the profile manager. */
util::ConstructAt(g_profile_manager, SaveDataInfo);
/* Process profile manager savedata. */
util::GetReference(g_profile_manager).InitializeSaveData();
/* Create the service objects. */
util::ConstructAt(g_bg_service_object, std::addressof(g_sf_memory_resource), util::GetPointer(g_profile_manager));
util::ConstructAt(g_sp_service_object, std::addressof(g_sf_memory_resource), util::GetPointer(g_profile_manager));
/* Create the service getters. */
util::ConstructAt(g_bg_service_getter, util::GetReference(g_bg_service_object).GetShared(), util::GetReference(g_sp_service_object).GetShared());
util::ConstructAt(g_sp_service_getter, nullptr, util::GetReference(g_sp_service_object).GetShared());
/* Create the server manager. */
util::ConstructAt(g_server_manager);
/* Create services. */
if (hos::GetVersion() >= hos::Version_14_0_0) {
R_ABORT_UNLESS(util::GetReference(g_server_manager).RegisterObjectForServer(util::GetReference(g_bg_service_getter).GetShared(), ServiceNameForBgAgent, BgAgentSessionCountMax));
R_ABORT_UNLESS(util::GetReference(g_server_manager).RegisterObjectForServer(util::GetReference(g_sp_service_getter).GetShared(), ServiceNameForSystemProcess, SystemProcessSessionCountMax));
} else {
R_ABORT_UNLESS(util::GetReference(g_server_manager).RegisterObjectForServer(util::GetReference(g_bg_service_object).GetShared(), ServiceNameForBgAgent, BgAgentSessionCountMax));
R_ABORT_UNLESS(util::GetReference(g_server_manager).RegisterObjectForServer(util::GetReference(g_sp_service_object).GetShared(), ServiceNameForSystemProcess, SystemProcessSessionCountMax));
}
}
void StartIpcServer() {
/* Create the ipc server thread. */
R_ABORT_UNLESS(os::CreateThread(std::addressof(g_ipc_thread), IpcServerThreadFunction, nullptr, g_ipc_thread_stack, sizeof(g_ipc_thread_stack), AMS_GET_SYSTEM_THREAD_PRIORITY(sprofile, IpcServer)));
os::SetThreadNamePointer(std::addressof(g_ipc_thread), AMS_GET_SYSTEM_THREAD_NAME(sprofile, IpcServer));
/* Start the ipc server thread. */
os::StartThread(std::addressof(g_ipc_thread));
}
}
| 6,186
|
C++
|
.cpp
| 97
| 55.546392
| 206
| 0.699571
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,474
|
sprofile_srv_fs_utils.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/sprofile/srv/sprofile_srv_fs_utils.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 "sprofile_srv_profile_manager.hpp"
namespace ams::sprofile::srv {
Result ReadFile(const char *path, void *dst, size_t size, s64 offset) {
/* Open the file. */
fs::FileHandle file;
R_TRY_CATCH(fs::OpenFile(std::addressof(file), path, fs::OpenMode_Read)) {
R_CATCH_RETHROW(fs::ResultPathNotFound) /* It's okay if the file doesn't exist. */
} R_END_TRY_CATCH_WITH_ABORT_UNLESS;
ON_SCOPE_EXIT { fs::CloseFile(file); };
/* Read the file. */
size_t read_size;
R_TRY(fs::ReadFile(std::addressof(read_size), file, offset, dst, size));
/* Check the size was correct. */
AMS_ABORT_UNLESS(size == read_size);
R_SUCCEED();
}
Result WriteFile(const char *path, const void *src, size_t size) {
/* Create the file. */
R_TRY_CATCH(fs::CreateFile(path, size)) {
R_CATCH(fs::ResultPathAlreadyExists) { /* It's okay if the file already exists. */ }
} R_END_TRY_CATCH_WITH_ABORT_UNLESS;
/* Open the file. */
fs::FileHandle file;
R_ABORT_UNLESS(fs::OpenFile(std::addressof(file), path, fs::OpenMode_Write));
ON_SCOPE_EXIT { fs::CloseFile(file); };
/* Set the file size. */
R_ABORT_UNLESS(fs::SetFileSize(file, size));
/* Write the file. */
R_RETURN(fs::WriteFile(file, 0, src, size, fs::WriteOption::Flush));
}
Result MoveFile(const char *src_path, const char *dst_path) {
/* Require that the source path is a file. */
{
fs::DirectoryEntryType type;
R_ABORT_UNLESS(fs::GetEntryType(std::addressof(type), src_path));
AMS_ABORT_UNLESS(type == fs::DirectoryEntryType_File);
}
/* Delete the destination file. */
R_TRY_CATCH(fs::DeleteFile(dst_path)) {
R_CATCH(fs::ResultPathNotFound) { /* It's okay if the dst path doesn't exist. */ }
} R_END_TRY_CATCH;
/* Move the source file to the destination file. */
R_TRY(fs::RenameFile(src_path, dst_path));
R_SUCCEED();
}
Result DeleteFile(const char *path) {
R_TRY_CATCH(fs::DeleteFile(path)) {
R_CATCH(fs::ResultPathNotFound) { /* It's okay if the file doesn't exist. */ }
} R_END_TRY_CATCH;
R_SUCCEED();
}
Result EnsureDirectory(const char *path) {
R_TRY_CATCH(fs::CreateDirectory(path)) {
R_CATCH(fs::ResultPathAlreadyExists) { /* It's okay if the directory already exists. */ }
} R_END_TRY_CATCH;
R_SUCCEED();
}
}
| 3,258
|
C++
|
.cpp
| 74
| 36.756757
| 101
| 0.626342
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,475
|
sprofile_srv_service_getter.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/sprofile/srv/sprofile_srv_service_getter.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 "sprofile_srv_service_getter.hpp"
namespace ams::sprofile::srv {
Result ServiceGetter::GetServiceForSystemProcess(sf::Out<sf::SharedPointer<sprofile::srv::ISprofileServiceForSystemProcess>> out) {
/* Check that we have a service-for-system-process. */
R_UNLESS(m_service_for_system_process != nullptr, sprofile::ResultNotPermitted());
/* Set the output. */
*out = m_service_for_system_process;
R_SUCCEED();
}
Result ServiceGetter::GetServiceForBgAgent(sf::Out<sf::SharedPointer<sprofile::srv::ISprofileServiceForBgAgent>> out) {
/* Check that we have a service-for-bg-agent. */
R_UNLESS(m_service_for_bg_agent != nullptr, sprofile::ResultNotPermitted());
/* Set the output. */
*out = m_service_for_bg_agent;
R_SUCCEED();
}
}
| 1,499
|
C++
|
.cpp
| 33
| 40.909091
| 135
| 0.712329
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,476
|
sprofile_srv_profile_reader_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/sprofile/srv/sprofile_srv_profile_reader_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 "sprofile_srv_profile_manager.hpp"
#include "sprofile_srv_profile_reader_impl.hpp"
namespace ams::sprofile::srv {
Result ProfileReaderImpl::GetSigned64(sf::Out<s64> out, sprofile::Identifier profile, sprofile::Identifier key) {
R_RETURN(m_manager->GetSigned64(out.GetPointer(), profile, key));
}
Result ProfileReaderImpl::GetUnsigned64(sf::Out<u64> out, sprofile::Identifier profile, sprofile::Identifier key) {
R_RETURN(m_manager->GetUnsigned64(out.GetPointer(), profile, key));
}
Result ProfileReaderImpl::GetSigned32(sf::Out<s32> out, sprofile::Identifier profile, sprofile::Identifier key) {
R_RETURN(m_manager->GetSigned32(out.GetPointer(), profile, key));
}
Result ProfileReaderImpl::GetUnsigned32(sf::Out<u32> out, sprofile::Identifier profile, sprofile::Identifier key) {
R_RETURN(m_manager->GetUnsigned32(out.GetPointer(), profile, key));
}
Result ProfileReaderImpl::GetByte(sf::Out<u8> out, sprofile::Identifier profile, sprofile::Identifier key) {
R_RETURN(m_manager->GetByte(out.GetPointer(), profile, key));
}
}
| 1,784
|
C++
|
.cpp
| 35
| 47.085714
| 119
| 0.738232
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,477
|
sprofile_srv_profile_importer_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/sprofile/srv/sprofile_srv_profile_importer_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 "sprofile_srv_profile_manager.hpp"
#include "sprofile_srv_profile_importer_impl.hpp"
namespace ams::sprofile::srv {
Result ProfileImporterImpl::ImportProfile(const sprofile::srv::ProfileDataForImportData &import) {
R_RETURN(m_manager->ImportProfile(import));
}
Result ProfileImporterImpl::Commit() {
R_RETURN(m_manager->Commit());
}
Result ProfileImporterImpl::ImportMetadata(const sprofile::srv::ProfileMetadataForImportMetadata &import) {
R_RETURN(m_manager->ImportMetadata(import));
}
}
| 1,215
|
C++
|
.cpp
| 29
| 38.586207
| 111
| 0.751058
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,478
|
sprofile_srv_profile_controller_for_debug_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/sprofile/srv/sprofile_srv_profile_controller_for_debug_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 "sprofile_srv_profile_manager.hpp"
#include "sprofile_srv_profile_controller_for_debug_impl.hpp"
namespace ams::sprofile::srv {
Result ProfileControllerForDebugImpl::Reset() {
R_RETURN(m_manager->ResetSaveData());
}
Result ProfileControllerForDebugImpl::GetRaw(sf::Out<u8> out_type, sf::Out<u64> out_value, sprofile::Identifier profile, sprofile::Identifier key) {
R_RETURN(m_manager->GetRaw(out_type.GetPointer(), out_value.GetPointer(), profile, key));
}
}
| 1,167
|
C++
|
.cpp
| 26
| 41.961538
| 152
| 0.747581
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,479
|
scs_tenv.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/scs/scs_tenv.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::scs {
namespace {
alignas(os::MemoryPageSize) constinit u8 g_tenv_heap_storage[48_KB];
constinit lmem::HeapHandle g_tenv_heap_handle = nullptr;
constinit os::SdkMutex g_mutex;
void InitializeExpHeap() {
std::scoped_lock lk(g_mutex);
g_tenv_heap_handle = lmem::CreateExpHeap(g_tenv_heap_storage, sizeof(g_tenv_heap_storage), lmem::CreateOption_None);
}
void *Allocate(size_t size) {
std::scoped_lock lk(g_mutex);
void *mem = lmem::AllocateFromExpHeap(g_tenv_heap_handle, size);
return mem;
}
void Deallocate(void *p, size_t size) {
AMS_UNUSED(size);
std::scoped_lock lk(g_mutex);
lmem::FreeToExpHeap(g_tenv_heap_handle, p);
}
}
void InitializeTenvServiceManager() {
/* Initialize the tenv heap. */
InitializeExpHeap();
/* Initialize the tenv library. */
htc::tenv::Initialize(Allocate, Deallocate);
}
}
| 1,707
|
C++
|
.cpp
| 43
| 33.093023
| 128
| 0.662432
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,480
|
scs_shell.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/scs/scs_shell.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::scs {
namespace {
struct SocketInfo {
u64 id;
s32 socket;
};
struct ProgramInfo {
os::ProcessId process_id;
u64 id;
s32 socket;
s32 info_id;
bool started;
bool jit_debug;
bool launched_by_cs;
};
constexpr inline auto MaxSocketInfo = 2;
constexpr inline auto MaxProgramInfo = 64;
class SocketInfoManager {
private:
SocketInfo m_infos[MaxSocketInfo]{};
int m_count{};
public:
constexpr SocketInfoManager() = default;
void Initialize() {
/* Clear our count. */
m_count = 0;
}
Result Register(s32 socket, u64 id) {
/* Check that the socket isn't already registered. */
for (auto i = 0; i < m_count; ++i) {
R_UNLESS(m_infos[i].socket != socket, scs::ResultNoSocket());
}
/* Check that we can allocate a new socket info. */
if (m_count >= MaxSocketInfo) {
/* NOTE: Nintendo aborts with this result here. */
R_ABORT_UNLESS(scs::ResultOutOfResource());
}
/* Create the new socket info. */
m_infos[m_count++] = {
.id = id,
.socket = socket,
};
R_SUCCEED();
}
void Unregister(s32 socket) {
/* Unregister the socket, if it's registered. */
for (auto i = 0; i < m_count; ++i) {
if (m_infos[i].socket == socket) {
/* Ensure that the valid socket infos remain in bounds. */
std::memcpy(m_infos + i, m_infos + i + 1, (m_count - (i + 1)) * sizeof(*m_infos));
/* Note that we now have one fewer socket info. */
--m_count;
break;
}
}
}
void InvokeHandler(ProcessEventHandler handler, os::ProcessId process_id) {
/* Invoke the handler on all our sockets. */
for (auto i = 0; i < m_count; ++i) {
handler(m_infos[i].id, m_infos[i].socket, process_id);
}
}
};
class ProgramInfoManager {
private:
s32 m_next_info_id{};
ProgramInfo m_infos[MaxProgramInfo]{};
int m_count{};
public:
constexpr ProgramInfoManager() = default;
void Initialize() {
/* Reset our next id. */
m_next_info_id = 1;
/* Clear our count. */
m_count = 0;
}
const ProgramInfo *Find(os::ProcessId process_id) const {
/* Find a matching program. */
for (auto i = 0; i < m_count; ++i) {
if (m_infos[i].process_id == process_id) {
return std::addressof(m_infos[i]);
}
}
return nullptr;
}
bool Register(os::ProcessId process_id) {
/* Allocate an info id. */
const auto info_id = m_next_info_id++;
/* Check that we have space for the program. */
if (m_count >= MaxProgramInfo) {
return false;
}
/* Create the new program info. */
m_infos[m_count++] = {
.process_id = process_id,
.id = 0,
.socket = 0,
.info_id = info_id,
.started = false,
.jit_debug = false,
.launched_by_cs = false,
};
return true;
}
void Unregister(os::ProcessId process_id) {
/* Unregister the program, if it's registered. */
for (auto i = 0; i < m_count; ++i) {
if (m_infos[i].process_id == process_id) {
/* Ensure that the valid program infos remain in bounds. */
std::memcpy(m_infos + i, m_infos + i + 1, (m_count - (i + 1)) * sizeof(*m_infos));
/* Note that we now have one fewer program info. */
--m_count;
break;
}
}
}
void SetStarted(os::ProcessId process_id) {
/* Start the program. */
for (auto i = 0; i < m_count; ++i) {
if (m_infos[i].process_id == process_id) {
m_infos[i].started = true;
break;
}
}
}
void SetJitDebug(os::ProcessId process_id) {
/* Set the program as jit debug. */
for (auto i = 0; i < m_count; ++i) {
if (m_infos[i].process_id == process_id) {
m_infos[i].jit_debug = true;
break;
}
}
}
};
alignas(os::ThreadStackAlignment) constinit u8 g_thread_stack[os::MemoryPageSize];
constinit os::ThreadType g_thread = {};
constinit ProcessEventHandler g_common_start_handler;
constinit ProcessEventHandler g_common_exit_handler;
constinit ProcessEventHandler g_common_jit_debug_handler;
constinit SocketInfoManager g_socket_info_manager;
constinit ProgramInfoManager g_program_info_manager;
constinit os::SdkMutex g_manager_mutex;
void ProcessExitEvent(const pm::ProcessEventInfo &event_info) {
/* Unregister the target environment definition. */
htc::tenv::UnregisterDefinitionFilePath(event_info.process_id);
/* Unregister program info. */
ProgramInfo program_info;
bool found = false;
{
std::scoped_lock lk(g_manager_mutex);
if (const ProgramInfo *pi = g_program_info_manager.Find(event_info.process_id); pi != nullptr) {
program_info = *pi;
found = true;
g_program_info_manager.Unregister(event_info.process_id);
}
}
/* If we found the program, handle callbacks. */
if (found) {
/* Invoke the common exit handler. */
if (program_info.launched_by_cs) {
g_common_exit_handler(program_info.id, program_info.socket, program_info.process_id);
}
/* Notify the process event. */
if (program_info.started) {
std::scoped_lock lk(g_manager_mutex);
g_socket_info_manager.InvokeHandler(g_common_exit_handler, program_info.process_id);
}
}
}
void ProcessStartedEvent(const pm::ProcessEventInfo &event_info) {
/* Start the program (registering it, if needed). */
{
std::scoped_lock lk(g_manager_mutex);
if (g_program_info_manager.Find(event_info.process_id) == nullptr) {
AMS_ABORT_UNLESS(g_program_info_manager.Register(event_info.process_id));
}
g_program_info_manager.SetStarted(event_info.process_id);
}
/* Handle callbacks. */
{
std::scoped_lock lk(g_manager_mutex);
g_socket_info_manager.InvokeHandler(g_common_start_handler, event_info.process_id);
}
}
void ProcessExceptionEvent(const pm::ProcessEventInfo &event_info) {
/* Find the program info. */
ProgramInfo program_info;
bool found = false;
{
std::scoped_lock lk(g_manager_mutex);
if (const ProgramInfo *pi = g_program_info_manager.Find(event_info.process_id); pi != nullptr) {
program_info = *pi;
found = true;
}
/* Set the program as jit debug. */
g_program_info_manager.SetJitDebug(event_info.process_id);
}
/* If we found the program, handle callbacks. */
if (found) {
/* Invoke the common exception handler. */
if (program_info.launched_by_cs) {
g_common_jit_debug_handler(program_info.id, program_info.socket, program_info.process_id);
}
/* Notify the process event. */
if (program_info.started) {
std::scoped_lock lk(g_manager_mutex);
g_socket_info_manager.InvokeHandler(g_common_jit_debug_handler, program_info.process_id);
}
}
}
void EventHandlerThread(void *) {
/* Get event observer. */
pgl::EventObserver observer;
R_ABORT_UNLESS(pgl::GetEventObserver(std::addressof(observer)));
/* Get the observer's event. */
os::SystemEventType shell_event;
R_ABORT_UNLESS(observer.GetSystemEvent(std::addressof(shell_event)));
/* Loop handling events. */
while (true) {
/* Wait for an event to come in. */
os::WaitSystemEvent(std::addressof(shell_event));
/* Loop processing event infos. */
while (true) {
/* Get the next event info. */
pm::ProcessEventInfo event_info;
if (R_FAILED(observer.GetProcessEventInfo(std::addressof(event_info)))) {
break;
}
/* Process the event. */
switch (event_info.GetProcessEvent()) {
case pm::ProcessEvent::Exited:
ProcessExitEvent(event_info);
break;
case pm::ProcessEvent::Started:
ProcessStartedEvent(event_info);
break;
case pm::ProcessEvent::Exception:
ProcessExceptionEvent(event_info);
break;
default:
break;
}
}
}
}
void StartEventHandlerThread() {
/* Create the handler thread. */
R_ABORT_UNLESS(os::CreateThread(std::addressof(g_thread), EventHandlerThread, nullptr, g_thread_stack, sizeof(g_thread_stack), AMS_GET_SYSTEM_THREAD_PRIORITY(scs, ShellEventHandler)));
/* Set the handler thread's name. */
os::SetThreadNamePointer(std::addressof(g_thread), AMS_GET_SYSTEM_THREAD_NAME(scs, ShellEventHandler));
/* Start the handler thread. */
os::StartThread(std::addressof(g_thread));
}
Result PrepareToLaunchProgram(ncm::ProgramId program_id, const void *args, size_t args_size) {
/* Set the arguments. */
R_TRY_CATCH(ldr::SetProgramArgument(program_id, args, args_size)) {
R_CATCH(ldr::ResultArgumentCountOverflow) {
/* There are too many arguments already registered. Flush the arguments queue. */
R_TRY(ldr::FlushArguments());
/* Try again. */
R_TRY(ldr::SetProgramArgument(program_id, args, args_size));
}
} R_END_TRY_CATCH;
R_SUCCEED();
}
void FlushProgramArgument(ncm::ProgramId program_id) {
/* Ensure there are no arguments for the program. */
ldr::SetProgramArgument(program_id, "", 1);
}
}
void InitializeShell() {
/* Initialize our managers. */
g_socket_info_manager.Initialize();
g_program_info_manager.Initialize();
/* Start our event handler. */
StartEventHandlerThread();
}
void RegisterCommonProcessEventHandler(ProcessEventHandler on_start, ProcessEventHandler on_exit, ProcessEventHandler on_jit_debug) {
g_common_start_handler = on_start;
g_common_exit_handler = on_exit;
g_common_jit_debug_handler = on_jit_debug;
}
Result RegisterSocket(s32 socket, u64 id) {
/* Acquire exclusive access to the socket info manager. */
std::scoped_lock lk(g_manager_mutex);
/* Register the socket. */
R_RETURN(g_socket_info_manager.Register(socket, id));
}
void UnregisterSocket(s32 socket) {
/* Acquire exclusive access to the socket info manager. */
std::scoped_lock lk(g_manager_mutex);
/* Unregister the socket. */
return g_socket_info_manager.Unregister(socket);
}
Result LaunchProgram(os::ProcessId *out, const ncm::ProgramLocation &loc, const void *args, size_t args_size, u32 process_flags) {
/* Set up the arguments. */
PrepareToLaunchProgram(loc.program_id, args, args_size);
/* Ensure arguments are managed correctly. */
ON_SCOPE_EXIT { FlushProgramArgument(loc.program_id); };
/* Launch the program. */
R_TRY(pgl::LaunchProgram(out, loc, process_flags | pm::LaunchFlags_SignalOnExit, 0));
R_SUCCEED();
}
Result SubscribeProcessEvent(s32 socket, bool is_register, u64 id);
}
| 14,924
|
C++
|
.cpp
| 322
| 30.161491
| 196
| 0.494699
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,481
|
scs_server_manager.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/scs/scs_server_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>
namespace ams::scs {
namespace {
ServerManager g_server_manager;
}
ServerManager *GetServerManager() {
return std::addressof(g_server_manager);
}
void StartServer() {
/* Start the server. */
g_server_manager.ResumeProcessing();
/* Loop processing the server. */
g_server_manager.LoopProcess();
}
}
| 1,041
|
C++
|
.cpp
| 30
| 30.566667
| 76
| 0.707876
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,482
|
scs_shell_server.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/scs/scs_shell_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>
namespace ams::scs {
namespace {
s32 CreateSocket() {
while (true) {
/* Try to create a socket. */
if (const auto desc = htcs::Socket(); desc >= 0) {
return desc;
}
/* Wait 100ms before trying again. */
os::SleepThread(TimeSpan::FromMilliSeconds(100));
}
}
s32 AcceptSocket(s32 listen_socket) {
htcs::SockAddrHtcs temp;
return htcs::Accept(listen_socket, std::addressof(temp));
}
s32 Bind(s32 socket, const htcs::HtcsPortName &port_name) {
/* Set up the bind address. */
htcs::SockAddrHtcs addr;
addr.family = htcs::HTCS_AF_HTCS;
addr.peer_name = htcs::GetPeerNameAny();
std::strcpy(addr.port_name.name, port_name.name);
/* Bind. */
return htcs::Bind(socket, std::addressof(addr));
}
htcs::ssize_t Receive(s32 socket, void *buffer, size_t size) {
u8 *dst = static_cast<u8 *>(buffer);
size_t received = 0;
while (received < size) {
const auto ret = htcs::Recv(socket, dst + received, size - received, 0);
if (ret <= 0) {
return ret;
}
received += ret;
}
return static_cast<htcs::ssize_t>(received);
}
bool ReceiveCommand(CommandHeader *header, void *buffer, size_t buffer_size, s32 socket) {
/* Receive the header. */
if (Receive(socket, header, sizeof(*header)) != sizeof(*header)) {
return false;
}
/* Check that the body will fit in the buffer. */
if (header->body_size >= buffer_size) {
return false;
}
/* Receive the body. */
if(Receive(socket, buffer, header->body_size) != static_cast<htcs::ssize_t>(header->body_size)) {
return false;
}
return true;
}
}
void ShellServer::Initialize(const char *port_name, void *stack, size_t stack_size, CommandProcessor *command_processor) {
/* Set our variables. */
m_command_processor = command_processor;
std::strcpy(m_port_name.name, port_name);
/* Create our thread. */
R_ABORT_UNLESS(os::CreateThread(std::addressof(m_thread), ThreadEntry, this, stack, stack_size, AMS_GET_SYSTEM_THREAD_PRIORITY(scs, ShellServer)));
/* Set our thread's name. */
os::SetThreadNamePointer(std::addressof(m_thread), AMS_GET_SYSTEM_THREAD_NAME(scs, ShellServer));
}
void ShellServer::Start() {
os::StartThread(std::addressof(m_thread));
}
void ShellServer::DoShellServer() {
/* Loop servicing the shell server. */
while (true) {
/* Create a socket to listen on. */
const auto listen_socket = CreateSocket();
ON_SCOPE_EXIT { htcs::Close(listen_socket); };
/* Bind to the listen socket. */
if (Bind(listen_socket, m_port_name) != 0) {
continue;
}
/* Loop processing on our bound socket. */
while (true) {
/* Listen on the socket. */
if (const s32 listen_result = htcs::Listen(listen_socket, 0); listen_result != 0) {
/* TODO: logging. */
break;
}
/* Accept a socket. */
const s32 socket = AcceptSocket(listen_socket);
if (socket <= 0) {
/* TODO: logging. */
continue;
}
/* Ensure that the socket is cleaned up when we're done with it. */
ON_SCOPE_EXIT {
UnregisterSocket(socket);
htcs::Close(socket);
};
/* Loop servicing the socket. */
while (true) {
/* Receive a command header. */
CommandHeader header;
if (!ReceiveCommand(std::addressof(header), m_buffer, sizeof(m_buffer), socket)) {
break;
}
/* Process the command. */
if (!m_command_processor->ProcessCommand(header, m_buffer, socket)) {
break;
}
}
}
}
}
}
| 5,218
|
C++
|
.cpp
| 125
| 29.336
| 155
| 0.527739
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,483
|
scs_command_processor.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/scs/scs_command_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>
namespace ams::scs {
namespace {
struct ResponseError {
ResponseHeader header;
u32 result;
};
struct ResponseProgramExited {
ResponseHeader header;
u64 process_id;
};
struct ResponseProgramLaunched {
ResponseHeader header;
u64 process_id;
};
constinit os::SdkMutex g_htcs_send_mutex;
}
std::scoped_lock<os::SdkMutex> CommandProcessor::MakeSendGuardBlock() {
return std::scoped_lock<os::SdkMutex>{g_htcs_send_mutex};
}
void CommandProcessor::Send(s32 socket, const void *data, size_t size) {
htcs::Send(socket, data, size, 0);
}
void CommandProcessor::SendSuccess(s32 socket, const CommandHeader &header) {
/* Build the response. */
const ResponseHeader response = {
.id = header.id,
.response = Response_Success,
.body_size = 0,
};
/* Send the response. */
auto lk = MakeSendGuardBlock();
Send(socket, std::addressof(response), sizeof(response));
}
void CommandProcessor::SendErrorResult(s32 socket, const CommandHeader &header, Result result) {
return SendErrorResult(socket, header.id, result);
}
void CommandProcessor::SendErrorResult(s32 socket, u64 id, Result result) {
/* Build the response. */
const ResponseError response = {
.header = {
.id = id,
.response = Response_Error,
.body_size = sizeof(response) - sizeof(response.header),
},
.result = result.GetValue(),
};
/* Send the response. */
auto lk = MakeSendGuardBlock();
Send(socket, std::addressof(response), sizeof(response));
}
void CommandProcessor::SendExited(s32 socket, u64 id, u64 process_id) {
/* Build the response. */
const ResponseProgramExited response = {
.header = {
.id = id,
.response = Response_ProgramExited,
.body_size = sizeof(response) - sizeof(response.header),
},
.process_id = process_id,
};
/* Send the response. */
auto lk = MakeSendGuardBlock();
Send(socket, std::addressof(response), sizeof(response));
}
void CommandProcessor::SendJitDebug(s32 socket, u64 id) {
/* Build the response. */
const ResponseHeader response = {
.id = id,
.response = Response_JitDebug,
.body_size = 0,
};
/* Send the response. */
auto lk = MakeSendGuardBlock();
Send(socket, std::addressof(response), sizeof(response));
}
void CommandProcessor::SendLaunched(s32 socket, u64 id, u64 process_id) {
/* Build the response. */
const ResponseProgramLaunched response = {
.header = {
.id = id,
.response = Response_ProgramLaunched,
.body_size = sizeof(response) - sizeof(response.header),
},
.process_id = process_id,
};
/* Send the response. */
auto lk = MakeSendGuardBlock();
Send(socket, std::addressof(response), sizeof(response));
}
void CommandProcessor::OnProcessStart(u64 id, s32 socket, os::ProcessId process_id) {
SendLaunched(socket, id, process_id.value);
}
void CommandProcessor::OnProcessExit(u64 id, s32 socket, os::ProcessId process_id) {
SendExited(socket, id, process_id.value);
}
void CommandProcessor::OnProcessJitDebug(u64 id, s32 socket, os::ProcessId process_id) {
AMS_UNUSED(process_id);
SendJitDebug(socket, id);
}
void CommandProcessor::Initialize() {
/* Register our process event handlers. */
scs::RegisterCommonProcessEventHandler(OnProcessStart, OnProcessExit, OnProcessJitDebug);
}
bool CommandProcessor::ProcessCommand(const CommandHeader &header, const u8 *body, s32 socket) {
AMS_UNUSED(body);
switch (header.command) {
/* TODO: Support commands. */
default:
SendErrorResult(socket, header, scs::ResultUnknownCommand());
break;
}
return true;
}
}
| 5,039
|
C++
|
.cpp
| 130
| 30.015385
| 100
| 0.608402
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,484
|
pinmux_driver_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/pinmux/driver/pinmux_driver_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 <stratosphere.hpp>
#include "pinmux_select_board_impl.hpp"
namespace ams::pinmux::driver {
namespace {
constinit os::SdkMutex g_init_mutex;
constinit int g_init_count = 0;
}
void Initialize() {
std::scoped_lock lk(g_init_mutex);
if ((g_init_count++) == 0) {
if (!board::IsInitialized()) {
board::Initialize();
}
}
}
void Finalize() {
std::scoped_lock lk(g_init_mutex);
if ((--g_init_count) == 0) {
AMS_ASSERT(board::IsInitialized());
board::Finalize();
}
}
void SetInitialConfig() {
board::SetInitialConfig();
}
void SetInitialDrivePadConfig() {
board::SetInitialDrivePadConfig();
}
}
| 1,424
|
C++
|
.cpp
| 44
| 26.613636
| 76
| 0.644266
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,485
|
pinmux_board_driver_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/pinmux/driver/board/nintendo/nx/pinmux_board_driver_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 <stratosphere.hpp>
#include "pinmux_pad_index.hpp"
#include "pinmux_board_driver_api.hpp"
#include "pinmux_platform_pads.hpp"
namespace ams::pinmux::driver::board::nintendo::nx {
namespace {
constinit bool g_initialized = false;
#include "pinmux_initial_pad_config_icosa.inc"
#include "pinmux_initial_pad_config_hoag.inc"
#include "pinmux_initial_pad_config_iowa.inc"
#include "pinmux_initial_pad_config_calcio.inc"
#include "pinmux_initial_pad_config_aula.inc"
#include "pinmux_initial_drive_pad_config.inc"
#include "pinmux_initial_drive_pad_config_hoag.inc"
}
bool IsInitialized() {
return g_initialized;
}
void Initialize() {
InitializePlatformPads();
g_initialized = true;
}
void Finalize() {
/* ... */
}
void SetInitialConfig() {
const PinmuxPadConfig *configs = nullptr;
size_t num_configs = 0;
bool is_mariko = false;
switch (spl::GetHardwareType()) {
case spl::HardwareType::Icosa:
configs = PinmuxPadConfigsIcosa;
num_configs = NumPinmuxPadConfigsIcosa;
is_mariko = false;
break;
case spl::HardwareType::Hoag:
configs = PinmuxPadConfigsHoag;
num_configs = NumPinmuxPadConfigsHoag;
is_mariko = true;
break;
case spl::HardwareType::Iowa:
configs = PinmuxPadConfigsIowa;
num_configs = NumPinmuxPadConfigsIowa;
is_mariko = true;
break;
case spl::HardwareType::Calcio:
configs = PinmuxPadConfigsCalcio;
num_configs = NumPinmuxPadConfigsCalcio;
is_mariko = true;
break;
case spl::HardwareType::Aula:
configs = PinmuxPadConfigsAula;
num_configs = NumPinmuxPadConfigsAula;
is_mariko = true;
break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
AMS_ABORT_UNLESS(configs != nullptr);
for (size_t i = 0; i < num_configs; ++i) {
UpdateSinglePinmuxPad(configs[i]);
}
if (is_mariko) {
UpdateSinglePinmuxPad({ PinmuxPadIndex_Sdmmc2Clk, 0x2000, 0x2000 });
UpdateSinglePinmuxPad({ PinmuxPadIndex_Sdmmc2Cmd, 0x2000, 0x2000 });
UpdateSinglePinmuxPad({ PinmuxPadIndex_Sdmmc2Dat0, 0x2000, 0x2000 });
UpdateSinglePinmuxPad({ PinmuxPadIndex_Sdmmc2Dat1, 0x2000, 0x2000 });
UpdateSinglePinmuxPad({ PinmuxPadIndex_Sdmmc2Dat2, 0x2000, 0x2000 });
UpdateSinglePinmuxPad({ PinmuxPadIndex_Sdmmc2Dat3, 0x2000, 0x2000 });
UpdateSinglePinmuxPad({ PinmuxPadIndex_Sdmmc2Dat4, 0x2000, 0x2000 });
UpdateSinglePinmuxPad({ PinmuxPadIndex_Sdmmc2Dat5, 0x2000, 0x2000 });
UpdateSinglePinmuxPad({ PinmuxPadIndex_Sdmmc2Dat6, 0x2000, 0x2000 });
UpdateSinglePinmuxPad({ PinmuxPadIndex_Sdmmc2Dat7, 0x2000, 0x2000 });
}
}
void SetInitialDrivePadConfig() {
const PinmuxDrivePadConfig *configs = nullptr;
size_t num_configs = 0;
switch (spl::GetHardwareType()) {
case spl::HardwareType::Icosa:
configs = PinmuxDrivePadConfigs;
num_configs = NumPinmuxDrivePadConfigs;
break;
case spl::HardwareType::Hoag:
configs = PinmuxDrivePadConfigsHoag;
num_configs = NumPinmuxDrivePadConfigsHoag;
break;
case spl::HardwareType::Iowa:
configs = PinmuxDrivePadConfigs;
num_configs = NumPinmuxDrivePadConfigs;
break;
case spl::HardwareType::Calcio:
configs = PinmuxDrivePadConfigs;
num_configs = NumPinmuxDrivePadConfigs;
break;
case spl::HardwareType::Aula:
configs = PinmuxDrivePadConfigs;
num_configs = NumPinmuxDrivePadConfigs;
break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
AMS_ABORT_UNLESS(configs != nullptr);
for (size_t i = 0; i < num_configs; ++i) {
UpdateSinglePinmuxDrivePad(configs[i]);
}
}
}
| 5,063
|
C++
|
.cpp
| 121
| 31.264463
| 81
| 0.60731
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,486
|
pinmux_platform_pads.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/pinmux/driver/board/nintendo/nx/pinmux_platform_pads.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 "pinmux_pad_index.hpp"
#include "pinmux_board_driver_api.hpp"
#include "pinmux_platform_pads.hpp"
namespace ams::pinmux::driver::board::nintendo::nx {
namespace {
uintptr_t g_apb_misc_virtual_address = dd::QueryIoMapping(0x70000000, 0x4000);
enum PinmuxPadMask : u32 {
PinmuxPadMask_Pm = 0x3,
PinmuxPadMask_Pupd = 0xC,
PinmuxPadMask_Tristate = 0x10,
PinmuxPadMask_Park = 0x20,
PinmuxPadMask_EInput = 0x40,
PinmuxPadMask_Lock = 0x80,
PinmuxPadMask_ELpdr = 0x100,
PinmuxPadMask_EHsm = 0x200,
PinmuxPadMask_EIoHv = 0x400,
PinmuxPadMask_EOd = 0x800,
PinmuxPadMask_ESchmt = 0x1000,
PinmuxPadMask_DrvType = 0x6000,
PinmuxPadMask_Preemp = 0x8000,
PinmuxPadMask_IoReset = 0x10000,
};
enum PinmuxPadBitOffset : u32 {
PinmuxPadBitOffset_Pm = 0x0,
PinmuxPadBitOffset_Pupd = 0x2,
PinmuxPadBitOffset_Tristate = 0x4,
PinmuxPadBitOffset_Park = 0x5,
PinmuxPadBitOffset_EInput = 0x6,
PinmuxPadBitOffset_Lock = 0x7,
PinmuxPadBitOffset_ELpdr = 0x8,
PinmuxPadBitOffset_EHsm = 0x9,
PinmuxPadBitOffset_EIoHv = 0xA,
PinmuxPadBitOffset_EOd = 0xB,
PinmuxPadBitOffset_ESchmt = 0xC,
PinmuxPadBitOffset_DrvType = 0xD,
PinmuxPadBitOffset_Preemp = 0xF,
PinmuxPadBitOffset_IoReset = 0x10,
};
enum PinmuxOptBitMask : u32 {
PinmuxOptBitMask_Pm = 0x7,
PinmuxOptBitMask_Pupd = 0x18,
PinmuxOptBitMask_Dir = 0x60,
PinmuxOptBitMask_Lock = 0x80,
PinmuxOptBitMask_IoReset = 0x100,
PinmuxOptBitMask_IoHv = 0x200,
PinmuxOptBitMask_Park = 0x400,
PinmuxOptBitMask_Lpdr = 0x800,
PinmuxOptBitMask_Hsm = 0x1000,
PinmuxOptBitMask_Schmt = 0x2000,
PinmuxOptBitMask_DrvType = 0xC000,
PinmuxOptBitMask_Preemp = 0x10000,
};
enum PinmuxOptBitOffset {
PinmuxOptBitOffset_Pm = 0x0,
PinmuxOptBitOffset_Pupd = 0x3,
PinmuxOptBitOffset_Dir = 0x5,
PinmuxOptBitOffset_Lock = 0x7,
PinmuxOptBitOffset_IoReset = 0x8,
PinmuxOptBitOffset_IoHv = 0x9,
PinmuxOptBitOffset_Park = 0xA,
PinmuxOptBitOffset_Lpdr = 0xB,
PinmuxOptBitOffset_Hsm = 0xC,
PinmuxOptBitOffset_Schmt = 0xD,
PinmuxOptBitOffset_DrvType = 0xE,
PinmuxOptBitOffset_Preemp = 0x10,
};
enum PinmuxDrivePadMask : u32{
PinmuxDrivePadMask_DrvDn = 0x0001F000,
PinmuxDrivePadMask_DrvUp = 0x01F00000,
PinmuxDrivePadMask_CzDrvDn = 0x0007F000,
PinmuxDrivePadMask_CzDrvUp = 0x07F00000,
PinmuxDrivePadMask_SlwR = 0x30000000,
PinmuxDrivePadMask_SlwF = 0xC0000000,
};
enum PinmuxDrivePadBitOffset : u32 {
PinmuxDrivePadBitOffset_DrvDn = 12,
PinmuxDrivePadBitOffset_DrvUp = 20,
PinmuxDrivePadBitOffset_CzDrvDn = 12,
PinmuxDrivePadBitOffset_CzDrvUp = 20,
PinmuxDrivePadBitOffset_SlwR = 28,
PinmuxDrivePadBitOffset_SlwF = 30,
};
enum PinmuxDriveOptBitMask : u32 {
PinmuxDriveOptBitMask_DrvDn = 0x0001F000,
PinmuxDriveOptBitMask_DrvUp = 0x01F00000,
PinmuxDriveOptBitMask_CzDrvDn = 0x0007F000,
PinmuxDriveOptBitMask_CzDrvUp = 0x07F00000,
PinmuxDriveOptBitMask_SlwR = 0x30000000,
PinmuxDriveOptBitMask_SlwF = 0xC0000000,
};
enum PinmuxDriveOptBitOffset : u32 {
PinmuxDriveOptBitOffset_DrvDn = 12,
PinmuxDriveOptBitOffset_DrvUp = 20,
PinmuxDriveOptBitOffset_CzDrvDn = 12,
PinmuxDriveOptBitOffset_CzDrvUp = 20,
PinmuxDriveOptBitOffset_SlwR = 28,
PinmuxDriveOptBitOffset_SlwF = 30,
};
enum PinmuxOpt : u32 {
/* Pm */
PinmuxOpt_Gpio = 0x4,
PinmuxOpt_Unused = 0x5,
/* Pupd */
PinmuxOpt_NoPupd = 0x0,
PinmuxOpt_PullDown = 0x8,
PinmuxOpt_PullUp = 0x10,
/* Dir */
PinmuxOpt_Output = 0x0,
PinmuxOpt_Input = 0x20,
PinmuxOpt_Bidirection = 0x40,
PinmuxOpt_OpenDrain = 0x60,
/* Lock */
PinmuxOpt_Unlock = 0x0,
PinmuxOpt_Lock = 0x80,
/* IoReset */
PinmuxOpt_DisableIoReset = 0x0,
PinmuxOpt_EnableIoReset = 0x100,
/* IoHv */
PinmuxOpt_NormalVoltage = 0x0,
PinmuxOpt_HighVoltage = 0x200,
/* Park */
PinmuxOpt_ResetOnLowPower = 0x0,
PinmuxOpt_ParkOnLowPower = 0x400,
/* Lpdr */
PinmuxOpt_DisableBaseDriver = 0x0,
PinmuxOpt_EnableBaseDriver = 0x800,
/* Hsm */
PinmuxOpt_DisableHighSpeedMode = 0x0,
PinmuxOpt_EnableHighSpeedMode = 0x1000,
/* Schmt */
PinmuxOpt_CmosMode = 0x0,
PinmuxOpt_SchmittTrigger = 0x2000,
/* DrvType */
PinmuxOpt_DrvType1X = 0x0,
PinmuxOpt_DrvType2X = 0x4000,
PinmuxOpt_DrvType3X = 0x8000,
PinmuxOpt_DrvType4X = 0xC000,
/* Preemp */
PinmuxOpt_DisablePreemp = 0x0,
PinmuxOpt_EnablePreemp = 0x10000,
};
enum PinmuxPadPm : u32 {
PinmuxPadPm_Default = 0xFFFFFFFF,
PinmuxPadPm_Pm0 = 0x0,
PinmuxPadPm_Pm1 = 0x1,
PinmuxPadPm_Pm2 = 0x2,
PinmuxPadPm_Pm3 = 0x3,
PinmuxPadPm_Safe = 0x4,
};
struct PinmuxPadCharacter {
u32 reg_offset;
u32 reg_mask;
u8 safe_func;
const char *pad_name;
};
struct PinmuxDrivePadCharacter {
u32 reg_offset;
u32 reg_mask;
const char *pad_name;
};
#include "pinmux_pad_characters.inc"
#include "pinmux_drive_pad_characters.inc"
class PinmuxPad {
private:
u32 m_reg_address;
u32 m_reg_mask;
u32 m_reg_value;
u8 m_safe_func;
const char *m_pad_name;
private:
bool IsValidRegisterAddress() const {
return m_reg_address - 0x70003000 <= 0x2C4;
}
uintptr_t GetRegisterAddress() const {
return g_apb_misc_virtual_address + (m_reg_address - 0x70000000);
}
bool UpdateBits(u32 value, u32 offset, u32 mask) {
if ((m_reg_mask & mask) != 0) {
if ((value & (mask >> offset)) != ((m_reg_value & mask) >> offset)) {
m_reg_value = (m_reg_value & ~mask) | ((value << offset) & mask);
}
return true;
} else {
return false;
}
}
u32 ReadReg() const {
if (this->IsValidRegisterAddress()) {
return reg::Read(this->GetRegisterAddress());
} else {
return 0;
}
}
void WriteReg() const {
if (this->IsValidRegisterAddress()) {
reg::Write(this->GetRegisterAddress(), m_reg_value);
}
}
bool IsLocked() const {
return (m_reg_value & PinmuxPadMask_Lock) != 0;
}
void UpdatePm(u8 v) {
if (v != 0xFF) {
if (v == PinmuxPadPm_Safe) {
v = m_safe_func;
}
this->UpdateBits(v, PinmuxPadBitOffset_Pm, PinmuxPadMask_Pm);
}
}
void UpdatePupd(u8 v) {
if (v != 0xFF) {
this->UpdateBits(v, PinmuxPadBitOffset_Pupd, PinmuxPadMask_Pupd);
}
}
void UpdateTristate(u8 v) {
if (v != 0xFF) {
this->UpdateBits(v, PinmuxPadBitOffset_Tristate, PinmuxPadMask_Tristate);
}
}
void UpdateEInput(u8 v) {
if (v != 0xFF) {
this->UpdateBits(v, PinmuxPadBitOffset_EInput, PinmuxPadMask_EInput);
}
}
void UpdateEOd(u8 v) {
if (v != 0xFF) {
this->UpdateBits(v, PinmuxPadBitOffset_EOd, PinmuxPadMask_EOd);
}
}
void UpdateLock(u8 v) {
if (v != 0xFF) {
this->UpdateBits(v, PinmuxPadBitOffset_Lock, PinmuxPadMask_Lock);
}
}
void UpdateIoReset(u8 v) {
if (v != 0xFF) {
this->UpdateBits(v, PinmuxPadBitOffset_IoReset, PinmuxPadMask_IoReset);
}
}
void UpdatePark(u8 v) {
if (v != 0xFF) {
this->UpdateBits(v, PinmuxPadBitOffset_Park, PinmuxPadMask_Park);
}
}
void UpdateELpdr(u8 v) {
if (v != 0xFF) {
this->UpdateBits(v, PinmuxPadBitOffset_ELpdr, PinmuxPadMask_ELpdr);
}
}
void UpdateEHsm(u8 v) {
if (v != 0xFF) {
this->UpdateBits(v, PinmuxPadBitOffset_EHsm, PinmuxPadMask_EHsm);
}
}
void UpdateEIoHv(u8 v) {
if (v != 0xFF) {
this->UpdateBits(v, PinmuxPadBitOffset_EIoHv, PinmuxPadMask_EIoHv);
}
}
void UpdateESchmt(u8 v) {
if (v != 0xFF) {
this->UpdateBits(v, PinmuxPadBitOffset_ESchmt, PinmuxPadMask_ESchmt);
}
}
void UpdatePreemp(u8 v) {
if (v != 0xFF) {
this->UpdateBits(v, PinmuxPadBitOffset_Preemp, PinmuxPadMask_Preemp);
}
}
void UpdateDrvType(u8 v) {
if (v != 0xFF) {
this->UpdateBits(v, PinmuxPadBitOffset_DrvType, PinmuxPadMask_DrvType);
}
}
public:
constexpr PinmuxPad() : m_reg_address(), m_reg_mask(), m_reg_value(), m_safe_func(), m_pad_name() { /* ... */ }
void UpdatePinmuxPad(u32 config, u32 config_mask) {
/* Update register value. */
m_reg_value = this->ReadReg();
/* Check if we're locked. */
if (this->IsLocked()) {
return;
}
/* Update PM. */
if ((config_mask & PinmuxOptBitMask_Pm) != 0) {
const auto opt = (config & PinmuxOptBitMask_Pm);
u8 pm = PinmuxPadPm_Safe;
if (opt != PinmuxOpt_Gpio) {
if (opt == PinmuxOpt_Unused) {
this->UpdatePupd(true);
this->UpdateTristate(true);
this->UpdateEInput(0);
} else if (opt <= PinmuxOpt_Unused) {
pm = opt >> PinmuxOptBitOffset_Pm;
}
}
this->UpdatePm(pm);
}
/* Update pupd. */
if ((config_mask & PinmuxOptBitMask_Pupd) != 0) {
const auto opt = (config & PinmuxOptBitMask_Pupd);
if (opt == PinmuxOpt_NoPupd || opt == PinmuxOpt_PullDown || opt == PinmuxOpt_PullUp) {
this->UpdatePupd(opt >> PinmuxOptBitOffset_Pupd);
}
}
/* Update direction. */
if ((config_mask & PinmuxOptBitMask_Dir) != 0) {
const auto opt = (config & PinmuxOptBitMask_Dir);
if (opt == PinmuxOpt_Output) {
this->UpdateTristate(false);
this->UpdateEInput(false);
if ((m_reg_mask & PinmuxPadMask_EOd) != 0) {
this->UpdateEOd(false);
}
} else if (opt == PinmuxOpt_Input) {
this->UpdateTristate(true);
this->UpdateEInput(true);
if ((m_reg_mask & PinmuxPadMask_EOd) != 0) {
this->UpdateEOd(false);
}
} else if (opt == PinmuxOpt_Bidirection) {
this->UpdateTristate(false);
this->UpdateEInput(true);
if ((m_reg_mask & PinmuxPadMask_EOd) != 0) {
this->UpdateEOd(false);
}
} else if (opt == PinmuxOpt_OpenDrain) {
this->UpdateTristate(false);
this->UpdateEInput(true);
this->UpdateEOd(true);
}
}
/* Update Lock. */
if ((config_mask & PinmuxOptBitMask_Lock) != 0) {
const auto opt = (config & PinmuxOptBitMask_Lock);
this->UpdateLock(opt != 0);
}
/* Update IoReset. */
if ((config_mask & PinmuxOptBitMask_IoReset) != 0) {
const auto opt = (config & PinmuxOptBitMask_IoReset);
this->UpdateIoReset(opt != 0);
}
/* Update Park. */
if ((config_mask & PinmuxOptBitMask_Park) != 0) {
const auto opt = (config & PinmuxOptBitMask_Park);
this->UpdatePark(opt != 0);
}
/* Update Lpdr. */
if ((config_mask & PinmuxOptBitMask_Lpdr) != 0) {
const auto opt = (config & PinmuxOptBitMask_Lpdr);
this->UpdateELpdr(opt != 0);
}
/* Update Hsm. */
if ((config_mask & PinmuxOptBitMask_Hsm) != 0) {
const auto opt = (config & PinmuxOptBitMask_Hsm);
this->UpdateEHsm(opt != 0);
}
/* Update IoHv. */
if ((config_mask & PinmuxOptBitMask_IoHv) != 0) {
const auto opt = (config & PinmuxOptBitMask_IoHv);
this->UpdateEIoHv(opt != 0);
}
/* Update Schmt. */
if ((config_mask & PinmuxOptBitMask_Schmt) != 0) {
const auto opt = (config & PinmuxOptBitMask_Schmt);
this->UpdateESchmt(opt != 0);
}
/* Update Preemp. */
if ((config_mask & PinmuxOptBitMask_Preemp) != 0) {
const auto opt = (config & PinmuxOptBitMask_Preemp);
this->UpdatePreemp(opt != 0);
}
/* Update drive type. */
if ((config_mask & PinmuxOptBitMask_DrvType) != 0) {
const auto opt = (config & PinmuxOptBitMask_DrvType);
this->UpdateDrvType(opt >> PinmuxOptBitOffset_DrvType);
}
/* Write the updated register value. */
this->WriteReg();
}
void SetCharacter(const PinmuxPadCharacter &character) {
m_reg_address = character.reg_offset + 0x70000000;
m_reg_mask = character.reg_mask;
m_safe_func = character.safe_func;
m_reg_value = this->ReadReg();
m_pad_name = character.pad_name;
if ((m_reg_mask & m_reg_value & PinmuxPadMask_Park) != 0) {
m_reg_value &= ~(PinmuxPadMask_Park);
}
this->WriteReg();
}
};
class PinmuxDrivePad {
private:
u32 m_reg_address;
u32 m_reg_mask;
u32 m_reg_value;
const char *m_pad_name;
private:
bool IsValidRegisterAddress() const {
return m_reg_address - 0x700008E4 <= 0x288;
}
uintptr_t GetRegisterAddress() const {
return g_apb_misc_virtual_address + (m_reg_address - 0x70000000);
}
bool UpdateBits(u32 value, u32 offset, u32 mask) {
if ((m_reg_mask & mask) != 0) {
if ((value & (mask >> offset)) != ((m_reg_value & mask) >> offset)) {
m_reg_value = (m_reg_value & ~mask) | ((value << offset) & mask);
}
return true;
} else {
return false;
}
}
u32 ReadReg() const {
if (this->IsValidRegisterAddress()) {
return reg::Read(this->GetRegisterAddress());
} else {
return 0;
}
}
void WriteReg() const {
if (this->IsValidRegisterAddress()) {
reg::Write(this->GetRegisterAddress(), m_reg_value);
}
}
bool IsCzDrvDn() const {
return (m_reg_mask & PinmuxDrivePadMask_CzDrvDn) == PinmuxDrivePadMask_CzDrvDn;
}
bool IsCzDrvUp() const {
return (m_reg_mask & PinmuxDrivePadMask_CzDrvUp) == PinmuxDrivePadMask_CzDrvUp;
}
void UpdateDrvDn(u8 v) {
if (v != 0xFF) {
this->UpdateBits(v, PinmuxDrivePadBitOffset_DrvDn, PinmuxDrivePadMask_DrvDn);
}
}
void UpdateDrvUp(u8 v) {
if (v != 0xFF) {
this->UpdateBits(v, PinmuxDrivePadBitOffset_DrvUp, PinmuxDrivePadMask_DrvUp);
}
}
void UpdateCzDrvDn(u8 v) {
if (v != 0xFF) {
this->UpdateBits(v, PinmuxDrivePadBitOffset_CzDrvDn, PinmuxDrivePadMask_CzDrvDn);
}
}
void UpdateCzDrvUp(u8 v) {
if (v != 0xFF) {
this->UpdateBits(v, PinmuxDrivePadBitOffset_CzDrvUp, PinmuxDrivePadMask_CzDrvUp);
}
}
void UpdateSlwR(u8 v) {
if (v != 0xFF) {
this->UpdateBits(v, PinmuxDrivePadBitOffset_SlwR, PinmuxDrivePadMask_SlwR);
}
}
void UpdateSlwF(u8 v) {
if (v != 0xFF) {
this->UpdateBits(v, PinmuxDrivePadBitOffset_SlwF, PinmuxDrivePadMask_SlwF);
}
}
public:
constexpr PinmuxDrivePad() : m_reg_address(), m_reg_mask(), m_reg_value(), m_pad_name() { /* ... */ }
void UpdatePinmuxDrivePad(u32 config, u32 config_mask) {
/* Update register value. */
m_reg_value = this->ReadReg();
/* Update drvdn. */
if ((config_mask & PinmuxDriveOptBitMask_DrvDn) != 0) {
if (this->IsCzDrvDn()) {
const auto opt = (config & PinmuxDriveOptBitMask_CzDrvDn);
this->UpdateCzDrvDn(opt >> PinmuxDriveOptBitOffset_CzDrvDn);
} else {
const auto opt = (config & PinmuxDriveOptBitMask_DrvDn);
this->UpdateDrvDn(opt >> PinmuxDriveOptBitOffset_DrvDn);
}
}
/* Update drvup. */
if ((config_mask & PinmuxDriveOptBitMask_DrvUp) != 0) {
if (this->IsCzDrvUp()) {
const auto opt = (config & PinmuxDriveOptBitMask_CzDrvUp);
this->UpdateCzDrvUp(opt >> PinmuxDriveOptBitOffset_CzDrvUp);
} else {
const auto opt = (config & PinmuxDriveOptBitMask_DrvUp);
this->UpdateDrvUp(opt >> PinmuxDriveOptBitOffset_DrvUp);
}
}
/* Update slwr */
if ((config_mask & PinmuxDriveOptBitMask_SlwR) != 0) {
const auto opt = (config & PinmuxDriveOptBitMask_SlwR);
this->UpdateSlwR(opt >> PinmuxDriveOptBitOffset_SlwR);
}
/* Update slwf */
if ((config_mask & PinmuxDriveOptBitMask_SlwR) != 0) {
const auto opt = (config & PinmuxDriveOptBitMask_SlwF);
this->UpdateSlwF(opt >> PinmuxDriveOptBitOffset_SlwF);
}
/* Write the updated register value. */
this->WriteReg();
}
void SetCharacter(const PinmuxDrivePadCharacter &character) {
m_reg_address = character.reg_offset + 0x70000000;
m_reg_mask = character.reg_mask;
m_reg_value = this->ReadReg();
m_pad_name = character.pad_name;
}
};
constinit std::array<PinmuxPad, NumPinmuxPadCharacters> g_pinmux_pads{};
constinit std::array<PinmuxDrivePad, NumPinmuxDrivePadCharacters> g_pinmux_drive_pads{};
}
void InitializePlatformPads() {
/* Initialize all pads. */
for (size_t i = 0; i < NumPinmuxPadCharacters; ++i) {
g_pinmux_pads[i].SetCharacter(PinmuxPadCharacters[i]);
}
/* Update all drive pads. */
for (size_t i = 0; i < NumPinmuxDrivePadCharacters; ++i) {
g_pinmux_drive_pads[i].SetCharacter(PinmuxDrivePadCharacters[i]);
}
}
void UpdateSinglePinmuxPad(const PinmuxPadConfig &config) {
if (IsInitialized()) {
g_pinmux_pads[config.index].UpdatePinmuxPad(config.option, config.option_mask);
}
}
void UpdateSinglePinmuxDrivePad(const PinmuxDrivePadConfig &config) {
if (IsInitialized()) {
g_pinmux_drive_pads[config.index].UpdatePinmuxDrivePad(config.option, config.option_mask);
}
}
}
| 24,970
|
C++
|
.cpp
| 548
| 27.80292
| 127
| 0.46231
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,487
|
ams_environment_weak.os.linux.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ams/ams_environment_weak.os.linux.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 os {
void Initialize();
}
void *Malloc(size_t size) {
return std::malloc(size);
}
void Free(void *ptr) {
return std::free(ptr);
}
void *MallocForRapidJson(size_t size) {
return std::malloc(size);
}
void *ReallocForRapidJson(void *ptr, size_t size) {
return std::realloc(ptr, size);
}
void FreeForRapidJson(void *ptr) {
return std::free(ptr);
}
NORETURN void AbortImpl() {
std::abort();
}
}
extern "C" {
/* Redefine C++ exception handlers. Requires wrap linker flag. */
#define WRAP_ABORT_FUNC(func) void NORETURN __wrap_##func(void) { std::abort(); __builtin_unreachable(); }
WRAP_ABORT_FUNC(__cxa_pure_virtual)
#undef WRAP_ABORT_FUNC
}
| 1,468
|
C++
|
.cpp
| 45
| 28.155556
| 110
| 0.677076
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,488
|
ams_environment_weak.os.windows.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ams/ams_environment_weak.os.windows.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
extern "C" char **__real___p__acmdln(void);
extern "C" _invalid_parameter_handler __real__set_invalid_parameter_handler(_invalid_parameter_handler);
namespace ams {
namespace os {
void Initialize();
}
void *Malloc(size_t size) {
return std::malloc(size);
}
void Free(void *ptr) {
return std::free(ptr);
}
void *MallocForRapidJson(size_t size) {
return std::malloc(size);
}
void *ReallocForRapidJson(void *ptr, size_t size) {
return std::realloc(ptr, size);
}
void FreeForRapidJson(void *ptr) {
return std::free(ptr);
}
NORETURN void AbortImpl() {
std::abort();
}
}
extern "C" {
/* Redefine C++ exception handlers. Requires wrap linker flag. */
#define WRAP_ABORT_FUNC(func) void NORETURN __wrap_##func(void) { std::abort(); __builtin_unreachable(); }
WRAP_ABORT_FUNC(__cxa_pure_virtual)
#undef WRAP_ABORT_FUNC
/* On windows, mingw may attempt to call malloc before we've initialized globals to set up the command line. */
/* We perform some critical init here, to make that work. */
char **__wrap___p__acmdln(void) {
::ams::os::Initialize();
return __real___p__acmdln();
}
/* On some mingw gcc versions, acmdln isn't used, so we need to hook a different part of crt init. */
_invalid_parameter_handler __wrap__set_invalid_parameter_handler(_invalid_parameter_handler handler) {
::ams::os::Initialize();
return __real__set_invalid_parameter_handler(handler);
}
}
| 2,231
|
C++
|
.cpp
| 58
| 33.672414
| 115
| 0.675638
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,489
|
ams_emummc_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ams/ams_emummc_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 <stratosphere.hpp>
namespace ams::emummc {
namespace {
/* Convenience Definitions. */
constexpr u32 StorageMagic = util::FourCC<'E','F','S','0'>::Code;
constexpr size_t MaxDirLen = 0x7F;
/* Types. */
struct BaseConfig {
u32 magic;
u32 type;
u32 id;
u32 fs_version;
};
struct PartitionConfig {
u64 start_sector;
};
struct FileConfig {
char path[MaxDirLen + 1];
};
struct ExosphereConfig {
BaseConfig base_cfg;
union {
PartitionConfig partition_cfg;
FileConfig file_cfg;
};
char emu_dir_path[MaxDirLen + 1];
};
enum Storage : u32 {
Storage_Emmc,
Storage_Sd,
Storage_SdFile,
Storage_Count,
};
/* Globals. */
constinit os::SdkMutex g_lock;
constinit ExosphereConfig g_exo_config = {};
constinit bool g_is_emummc;
constinit bool g_has_cached;
/* Helpers. */
void CacheValues() {
std::scoped_lock lk(g_lock);
if (g_has_cached) {
return;
}
/* Retrieve and cache values. */
{
alignas(os::MemoryPageSize) std::byte path_storage[2 * (MaxDirLen + 1)];
struct {
char file_path[MaxDirLen + 1];
char nintendo_path[MaxDirLen + 1];
} *paths = reinterpret_cast<decltype(paths)>(std::addressof(path_storage));
/* Retrieve paths from secure monitor. */
AMS_ABORT_UNLESS(spl::smc::AtmosphereGetEmummcConfig(std::addressof(g_exo_config), paths, 0) == spl::smc::Result::Success);
const Storage storage = static_cast<Storage>(g_exo_config.base_cfg.type);
g_is_emummc = g_exo_config.base_cfg.magic == StorageMagic && storage != Storage_Emmc;
/* Format paths. */
{
char tmp_path[MaxDirLen + 1];
/* Format paths. */
if (storage == Storage_SdFile) {
util::TSNPrintf(tmp_path, sizeof(tmp_path), "/%s", paths->file_path);
R_ABORT_UNLESS(fs::PathFormatter::Normalize(g_exo_config.file_cfg.path, sizeof(g_exo_config.file_cfg.path), tmp_path, std::strlen(tmp_path) + 1, fs::PathFlags{}));
}
util::TSNPrintf(tmp_path, sizeof(tmp_path), "/%s", paths->nintendo_path);
R_ABORT_UNLESS(fs::PathFormatter::Normalize(g_exo_config.emu_dir_path, sizeof(g_exo_config.emu_dir_path), tmp_path, std::strlen(tmp_path) + 1, fs::PathFlags{}));
/* If we're emummc, implement default nintendo redirection path. */
if (g_is_emummc && std::strcmp(g_exo_config.emu_dir_path, "/") == 0) {
util::TSNPrintf(tmp_path, sizeof(tmp_path), "/emummc/Nintendo_%04x", g_exo_config.base_cfg.id);
R_ABORT_UNLESS(fs::PathFormatter::Normalize(g_exo_config.emu_dir_path, sizeof(g_exo_config.emu_dir_path), tmp_path, std::strlen(tmp_path) + 1, fs::PathFlags{}));
}
}
}
g_has_cached = true;
}
}
/* Get whether emummc is active. */
bool IsActive() {
CacheValues();
return g_is_emummc;
}
/* Get the active emummc id. */
u32 GetActiveId() {
CacheValues();
return g_exo_config.base_cfg.id;
}
/* Get Nintendo redirection path. */
const char *GetNintendoDirPath() {
CacheValues();
if (!g_is_emummc) {
return nullptr;
}
return g_exo_config.emu_dir_path;
}
/* Get Emummc folderpath, NULL if not file-based. */
const char *GetFilePath() {
CacheValues();
if (!g_is_emummc || g_exo_config.base_cfg.type != Storage_SdFile) {
return nullptr;
}
return g_exo_config.file_cfg.path;
}
}
| 4,798
|
C++
|
.cpp
| 117
| 30.008547
| 187
| 0.555556
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,490
|
ams_exosphere_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ams/ams_exosphere_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 <stratosphere.hpp>
namespace ams::exosphere {
ApiInfo GetApiInfo() {
u64 exosphere_cfg;
if (R_FAILED(spl::impl::GetConfig(std::addressof(exosphere_cfg), spl::ConfigItem::ExosphereApiVersion))) {
R_ABORT_UNLESS(exosphere::ResultNotPresent());
}
return ApiInfo{ util::BitPack64{exosphere_cfg} };
}
#if defined(ATMOSPHERE_BOARD_NINTENDO_NX)
void ForceRebootToRcm() {
R_ABORT_UNLESS(spl::impl::SetConfig(spl::ConfigItem::ExosphereNeedsReboot, 1));
}
void ForceRebootToIramPayload() {
R_ABORT_UNLESS(spl::impl::SetConfig(spl::ConfigItem::ExosphereNeedsReboot, 2));
}
void ForceRebootToFatalError() {
R_ABORT_UNLESS(spl::impl::SetConfig(spl::ConfigItem::ExosphereNeedsReboot, 3));
}
void ForceRebootByPmic() {
R_ABORT_UNLESS(spl::impl::SetConfig(spl::ConfigItem::ExosphereNeedsReboot, 4));
}
void ForceShutdown() {
R_ABORT_UNLESS(spl::impl::SetConfig(spl::ConfigItem::ExosphereNeedsShutdown, 1));
}
void CopyToIram(uintptr_t iram_dst, const void *dram_src, size_t size) {
spl::smc::AtmosphereCopyToIram(iram_dst, dram_src, size);
}
void CopyFromIram(void *dram_dst, uintptr_t iram_src, size_t size) {
spl::smc::AtmosphereCopyFromIram(dram_dst, iram_src, size);
}
namespace {
inline u64 GetU64ConfigItem(spl::ConfigItem cfg) {
u64 tmp;
R_ABORT_UNLESS(spl::smc::ConvertResult(spl::smc::GetConfig(std::addressof(tmp), 1, cfg)));
return tmp;
}
inline bool GetBooleanConfigItem(spl::ConfigItem cfg) {
return GetU64ConfigItem(cfg) != 0;
}
}
bool IsRcmBugPatched() {
return spl::impl::GetConfigBool(spl::ConfigItem::ExosphereHasRcmBugPatch);
}
bool ShouldBlankProdInfo() {
return spl::impl::GetConfigBool(spl::ConfigItem::ExosphereBlankProdInfo);
}
bool ShouldAllowWritesToProdInfo() {
return spl::impl::GetConfigBool(spl::ConfigItem::ExosphereAllowCalWrites);
}
u64 GetDeviceId() {
u64 device_id;
R_ABORT_UNLESS(spl::impl::GetConfig(std::addressof(device_id), spl::ConfigItem::DeviceId));
return device_id;
}
#endif
}
| 2,909
|
C++
|
.cpp
| 72
| 34.222222
| 114
| 0.683818
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,491
|
ams_environment.os.horizon.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ams/ams_environment.os.horizon.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "ams_bpc.os.horizon.h"
namespace ams {
namespace {
#if defined(ATMOSPHERE_ARCH_ARM64)
inline u64 GetPc() {
u64 pc;
__asm__ __volatile__ ("adr %[pc], ." : [pc]"=&r"(pc) :: );
return pc;
}
struct StackFrame {
u64 fp;
u64 lr;
};
#else
#error "Unknown architecture for os Horizon"
#endif
}
void InitializeForBoot() {
R_ABORT_UNLESS(amsBpcInitialize());
}
void SetInitialRebootPayload(const void *src, size_t src_size) {
R_ABORT_UNLESS(amsBpcSetRebootPayload(src, src_size));
}
void WEAK_SYMBOL ExceptionHandler(FatalErrorContext *ctx) {
R_ABORT_UNLESS(amsBpcInitialize());
R_ABORT_UNLESS(amsBpcRebootToFatalError(ctx));
while (1) { /* ... */ }
}
void CrashHandler(ThreadExceptionDump *ctx) {
FatalErrorContext ams_ctx;
/* Convert thread dump to atmosphere dump. */
{
ams_ctx.magic = FatalErrorContext::Magic;
ams_ctx.error_desc = ctx->error_desc;
ams_ctx.program_id = os::GetCurrentProgramId().value;
for (size_t i = 0; i < FatalErrorContext::NumGprs; i++) {
ams_ctx.gprs[i] = ctx->cpu_gprs[i].x;
}
if (ams_ctx.error_desc == FatalErrorContext::DataAbortErrorDesc &&
ams_ctx.gprs[27] == FatalErrorContext::StdAbortMagicAddress &&
ams_ctx.gprs[28] == FatalErrorContext::StdAbortMagicValue)
{
/* Detect std::abort(). */
ams_ctx.error_desc = FatalErrorContext::StdAbortErrorDesc;
}
ams_ctx.fp = ctx->fp.x;
ams_ctx.lr = ctx->lr.x;
ams_ctx.sp = ctx->sp.x;
ams_ctx.pc = ctx->pc.x;
ams_ctx.pstate = ctx->pstate;
ams_ctx.afsr0 = static_cast<u32>(::ams::exosphere::GetVersion(ATMOSPHERE_RELEASE_VERSION));
ams_ctx.afsr1 = static_cast<u32>(hos::GetVersion());
ams_ctx.far = ctx->far.x;
ams_ctx.report_identifier = armGetSystemTick();
/* Detect stack overflow. */
if (ams_ctx.error_desc == FatalErrorContext::DataAbortErrorDesc) {
svc::lp64::MemoryInfo mem_info;
svc::PageInfo page_info;
if (/* Check if stack pointer is in guard page. */
R_SUCCEEDED(svc::QueryMemory(std::addressof(mem_info), std::addressof(page_info), ams_ctx.sp)) &&
mem_info.state == svc::MemoryState_Free &&
/* Check if stack pointer fell off stack. */
R_SUCCEEDED(svc::QueryMemory(std::addressof(mem_info), std::addressof(page_info), ams_ctx.sp + 0x1000)) &&
mem_info.state == svc::MemoryState_Stack) {
ams_ctx.error_desc = FatalErrorContext::StackOverflowErrorDesc;
}
}
/* Grab module base. */
{
svc::lp64::MemoryInfo mem_info;
svc::PageInfo page_info;
if (R_SUCCEEDED(svc::QueryMemory(std::addressof(mem_info), std::addressof(page_info), GetPc()))) {
ams_ctx.module_base = mem_info.base_address;
} else {
ams_ctx.module_base = 0;
}
}
ams_ctx.stack_trace_size = 0;
u64 cur_fp = ams_ctx.fp;
for (size_t i = 0; i < FatalErrorContext::MaxStackTrace; i++) {
/* Validate current frame. */
if (cur_fp == 0 || (cur_fp & 0xF)) {
break;
}
/* Read a new frame. */
StackFrame cur_frame;
svc::lp64::MemoryInfo mem_info;
svc::PageInfo page_info;
if (R_SUCCEEDED(svc::QueryMemory(std::addressof(mem_info), std::addressof(page_info), cur_fp)) && (mem_info.permission & svc::MemoryPermission_Read) == svc::MemoryPermission_Read) {
std::memcpy(std::addressof(cur_frame), reinterpret_cast<void *>(cur_fp), sizeof(cur_frame));
} else {
break;
}
/* Advance to the next frame. */
ams_ctx.stack_trace[ams_ctx.stack_trace_size++] = cur_frame.lr;
cur_fp = cur_frame.fp;
}
/* Clear unused parts of stack trace. */
for (size_t i = ams_ctx.stack_trace_size; i < FatalErrorContext::MaxStackTrace; i++) {
ams_ctx.stack_trace[i] = 0;
}
/* Grab up to 0x100 of stack. */
{
svc::lp64::MemoryInfo mem_info;
svc::PageInfo page_info;
if (R_SUCCEEDED(svc::QueryMemory(std::addressof(mem_info), std::addressof(page_info), ams_ctx.sp)) && (mem_info.permission & svc::MemoryPermission_Read) == svc::MemoryPermission_Read) {
size_t copy_size = std::min(FatalErrorContext::MaxStackDumpSize, static_cast<size_t>(mem_info.base_address + mem_info.size - ams_ctx.sp));
ams_ctx.stack_dump_size = copy_size;
std::memcpy(ams_ctx.stack_dump, reinterpret_cast<void *>(ams_ctx.sp), copy_size);
} else {
ams_ctx.stack_dump_size = 0;
}
}
/* Grab 0x100 of tls. */
std::memcpy(ams_ctx.tls, svc::GetThreadLocalRegion(), sizeof(ams_ctx.tls));
}
/* Just call the user exception handler. */
::ams::ExceptionHandler(std::addressof(ams_ctx));
}
NORETURN void AbortImpl();
}
extern "C" {
/* Redefine C++ exception handlers. Requires wrap linker flag. */
#define WRAP_ABORT_FUNC(func) void NORETURN __wrap_##func(void) { ::ams::AbortImpl(); __builtin_unreachable(); }
WRAP_ABORT_FUNC(__cxa_throw)
WRAP_ABORT_FUNC(__cxa_rethrow)
WRAP_ABORT_FUNC(__cxa_allocate_exception)
WRAP_ABORT_FUNC(__cxa_free_exception)
WRAP_ABORT_FUNC(__cxa_begin_catch)
WRAP_ABORT_FUNC(__cxa_end_catch)
WRAP_ABORT_FUNC(__cxa_call_unexpected)
WRAP_ABORT_FUNC(__cxa_call_terminate)
WRAP_ABORT_FUNC(__gxx_personality_v0)
WRAP_ABORT_FUNC(_ZSt19__throw_logic_errorPKc)
WRAP_ABORT_FUNC(_ZSt20__throw_length_errorPKc)
WRAP_ABORT_FUNC(_ZNSt11logic_errorC2EPKc)
/* TODO: We may wish to consider intentionally not defining an _Unwind_Resume wrapper. */
/* This would mean that a failure to wrap all exception functions is a linker error. */
WRAP_ABORT_FUNC(_Unwind_Resume)
#undef WRAP_ABORT_FUNC
}
| 7,331
|
C++
|
.cpp
| 157
| 35.388535
| 201
| 0.573566
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,492
|
ams_environment_weak.os.horizon.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ams/ams_environment_weak.os.horizon.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
extern "C" void NORETURN __real_exit(int rc);
namespace ams {
WEAK_SYMBOL void *Malloc(size_t size) {
return std::malloc(size);
}
WEAK_SYMBOL void Free(void *ptr) {
return std::free(ptr);
}
WEAK_SYMBOL void *MallocForRapidJson(size_t size) {
return std::malloc(size);
}
WEAK_SYMBOL void *ReallocForRapidJson(void *ptr, size_t size) {
return std::realloc(ptr, size);
}
WEAK_SYMBOL void FreeForRapidJson(void *ptr) {
return std::free(ptr);
}
WEAK_SYMBOL void NORETURN Exit(int rc) {
__real_exit(rc);
__builtin_unreachable();
}
NOINLINE NORETURN void AbortImpl() {
#if defined(ATMOSPHERE_BOARD_NINTENDO_NX)
/* Just perform a data abort. */
register u64 addr __asm__("x27") = FatalErrorContext::StdAbortMagicAddress;
register u64 val __asm__("x28") = FatalErrorContext::StdAbortMagicValue;
while (true) {
__asm__ __volatile__ (
"str %[val], [%[addr]]"
:
: [val]"r"(val), [addr]"r"(addr)
);
}
#else
/* What should be done here? */
AMS_INFINITE_LOOP();
#endif
__builtin_unreachable();
}
}
extern "C" {
/* Redefine abort to trigger these handlers. */
void abort();
/* Redefine C++ exception handlers. Requires wrap linker flag. */
#define WRAP_ABORT_FUNC(func) void NORETURN __wrap_##func(void) { ::ams::AbortImpl(); __builtin_unreachable(); }
WRAP_ABORT_FUNC(__cxa_pure_virtual)
#undef WRAP_ABORT_FUNC
void NORETURN __wrap_exit(int rc) { ::ams::Exit(rc); __builtin_unreachable(); }
}
/* Custom abort handler, so that std::abort will trigger these. */
void abort() {
ams::AbortImpl();
__builtin_unreachable();
}
| 2,493
|
C++
|
.cpp
| 70
| 29.785714
| 116
| 0.636892
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,493
|
dd_device_address_space.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/dd/dd_device_address_space.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "impl/dd_device_address_space_impl.hpp"
namespace ams::dd {
Result CreateDeviceAddressSpace(DeviceAddressSpaceType *das, u64 address, u64 size) {
/* Check pre-conditions. */
AMS_ASSERT(util::IsAligned(address, os::MemoryPageSize));
AMS_ASSERT(util::IsAligned(size, os::MemoryPageSize));
AMS_ASSERT(size > 0);
/* Ensure we leave in a consistent state. */
auto state_guard = SCOPE_GUARD { das->state = DeviceAddressSpaceType::State_NotInitialized; };
/* Create the address space. */
DeviceAddressSpaceHandle handle;
R_TRY(impl::DeviceAddressSpaceImpl::Create(std::addressof(handle), address, size));
/* Set the values in the das. */
das->device_handle = handle;
das->is_handle_managed = true;
das->state = DeviceAddressSpaceType::State_Initialized;
/* We succeeded. */
state_guard.Cancel();
R_SUCCEED();
}
Result CreateDeviceAddressSpace(DeviceAddressSpaceType *das, u64 size) {
R_RETURN(CreateDeviceAddressSpace(das, 0, size));
}
void DestroyDeviceAddressSpace(DeviceAddressSpaceType *das) {
/* Check pre-conditions. */
AMS_ASSERT(das->state == DeviceAddressSpaceType::State_Initialized);
/* Destroy the handle. */
if (das->is_handle_managed) {
impl::DeviceAddressSpaceImpl::Close(das->device_handle);
}
das->device_handle = 0;
das->is_handle_managed = false;
das->state = DeviceAddressSpaceType::State_NotInitialized;
}
void AttachDeviceAddressSpaceHandle(DeviceAddressSpaceType *das, DeviceAddressSpaceHandle handle, bool managed) {
/* Check pre-conditions. */
AMS_ASSERT(handle != os::InvalidNativeHandle);
das->device_handle = handle;
das->is_handle_managed = managed;
das->state = DeviceAddressSpaceType::State_Initialized;
}
DeviceAddressSpaceHandle GetDeviceAddressSpaceHandle(DeviceAddressSpaceType *das) {
/* Check pre-conditions. */
AMS_ASSERT(das->state == DeviceAddressSpaceType::State_Initialized);
return das->device_handle;
}
Result MapDeviceAddressSpaceAligned(DeviceAddressSpaceType *das, ProcessHandle process_handle, u64 process_address, size_t size, DeviceVirtualAddress device_address, MemoryPermission device_perm) {
/* Check pre-conditions. */
AMS_ASSERT(das->state == DeviceAddressSpaceType::State_Initialized);
AMS_ASSERT(util::IsAligned(process_address, os::MemoryPageSize));
AMS_ASSERT(util::IsAligned(device_address, os::MemoryPageSize));
AMS_ASSERT(util::IsAligned(size, os::MemoryPageSize));
AMS_ASSERT(process_address + size > process_address);
AMS_ASSERT(device_address + size > device_address);
AMS_ASSERT(size > 0);
AMS_ASSERT((process_address & (4_MB - 1)) == (device_address & (4_MB - 1)));
R_RETURN(impl::DeviceAddressSpaceImpl::MapAligned(das->device_handle, process_handle, process_address, size, device_address, device_perm));
}
Result MapDeviceAddressSpaceNotAligned(DeviceAddressSpaceType *das, ProcessHandle process_handle, u64 process_address, size_t size, DeviceVirtualAddress device_address, MemoryPermission device_perm) {
/* Check pre-conditions. */
AMS_ASSERT(das->state == DeviceAddressSpaceType::State_Initialized);
AMS_ASSERT(util::IsAligned(process_address, os::MemoryPageSize));
AMS_ASSERT(util::IsAligned(device_address, os::MemoryPageSize));
AMS_ASSERT(util::IsAligned(size, os::MemoryPageSize));
AMS_ASSERT(process_address + size > process_address);
AMS_ASSERT(device_address + size > device_address);
AMS_ASSERT(size > 0);
R_RETURN(impl::DeviceAddressSpaceImpl::MapNotAligned(das->device_handle, process_handle, process_address, size, device_address, device_perm));
}
void UnmapDeviceAddressSpace(DeviceAddressSpaceType *das, ProcessHandle process_handle, u64 process_address, size_t size, DeviceVirtualAddress device_address) {
/* Check pre-conditions. */
AMS_ASSERT(das->state == DeviceAddressSpaceType::State_Initialized);
AMS_ASSERT(util::IsAligned(process_address, os::MemoryPageSize));
AMS_ASSERT(util::IsAligned(device_address, os::MemoryPageSize));
AMS_ASSERT(util::IsAligned(size, os::MemoryPageSize));
AMS_ASSERT(process_address + size > process_address);
AMS_ASSERT(device_address + size > device_address);
AMS_ASSERT(size > 0);
return impl::DeviceAddressSpaceImpl::Unmap(das->device_handle, process_handle, process_address, size, device_address);
}
Result AttachDeviceAddressSpace(DeviceAddressSpaceType *das, DeviceName device_name) {
/* Check pre-conditions. */
AMS_ASSERT(das->state == DeviceAddressSpaceType::State_Initialized);
R_RETURN(impl::DeviceAddressSpaceImpl::Attach(das, device_name));
}
void DetachDeviceAddressSpace(DeviceAddressSpaceType *das, DeviceName device_name) {
/* Check pre-conditions. */
AMS_ASSERT(das->state == DeviceAddressSpaceType::State_Initialized);
return impl::DeviceAddressSpaceImpl::Detach(das, device_name);
}
}
| 5,992
|
C++
|
.cpp
| 107
| 48.766355
| 204
| 0.698294
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,494
|
dd_device_address_space_impl.os.horizon.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/dd/impl/dd_device_address_space_impl.os.horizon.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "dd_device_address_space_impl.os.horizon.hpp"
namespace ams::dd::impl {
static_assert(static_cast<int>(dd::MemoryPermission_None) == static_cast<int>(svc::MemoryPermission_None));
static_assert(static_cast<int>(dd::MemoryPermission_ReadOnly) == static_cast<int>(svc::MemoryPermission_Read));
static_assert(static_cast<int>(dd::MemoryPermission_WriteOnly) == static_cast<int>(svc::MemoryPermission_Write));
static_assert(static_cast<int>(dd::MemoryPermission_ReadWrite) == static_cast<int>(svc::MemoryPermission_ReadWrite));
Result DeviceAddressSpaceImplByHorizon::Create(DeviceAddressSpaceHandle *out, u64 address, u64 size) {
/* Create the space. */
svc::Handle handle;
R_TRY_CATCH(svc::CreateDeviceAddressSpace(std::addressof(handle), address, size)) {
R_CONVERT(svc::ResultOutOfMemory, dd::ResultOutOfMemory())
R_CONVERT(svc::ResultOutOfResource, dd::ResultOutOfResource())
} R_END_TRY_CATCH_WITH_ABORT_UNLESS;
*out = static_cast<DeviceAddressSpaceHandle>(handle);
R_SUCCEED();
}
void DeviceAddressSpaceImplByHorizon::Close(DeviceAddressSpaceHandle handle) {
const auto svc_handle = svc::Handle(handle);
if (svc_handle == svc::PseudoHandle::CurrentThread || svc_handle == svc::PseudoHandle::CurrentProcess) {
return;
}
R_ABORT_UNLESS(svc::CloseHandle(svc_handle));
}
Result DeviceAddressSpaceImplByHorizon::MapAligned(DeviceAddressSpaceHandle handle, ProcessHandle process_handle, u64 process_address, size_t process_size, DeviceVirtualAddress device_address, dd::MemoryPermission device_perm) {
/* Check alignment. */
AMS_ABORT_UNLESS((process_address & (4_MB - 1)) == (device_address & (4_MB - 1)));
R_TRY_CATCH(svc::MapDeviceAddressSpaceAligned(svc::Handle(handle), svc::Handle(process_handle), process_address, process_size, device_address, svc::MapDeviceAddressSpaceOption::Encode(static_cast<svc::MemoryPermission>(device_perm), svc::MapDeviceAddressSpaceFlag_None))) {
R_CONVERT(svc::ResultInvalidHandle, dd::ResultInvalidHandle())
R_CONVERT(svc::ResultOutOfMemory, dd::ResultOutOfMemory())
R_CONVERT(svc::ResultOutOfResource, dd::ResultOutOfResource())
R_CONVERT(svc::ResultInvalidCurrentMemory, dd::ResultInvalidMemoryState())
} R_END_TRY_CATCH_WITH_ABORT_UNLESS;
R_SUCCEED();
}
Result DeviceAddressSpaceImplByHorizon::MapNotAligned(DeviceAddressSpaceHandle handle, ProcessHandle process_handle, u64 process_address, size_t process_size, DeviceVirtualAddress device_address, dd::MemoryPermission device_perm) {
R_TRY_CATCH(svc::MapDeviceAddressSpaceByForce(svc::Handle(handle), svc::Handle(process_handle), process_address, process_size, device_address, svc::MapDeviceAddressSpaceOption::Encode(static_cast<svc::MemoryPermission>(device_perm), svc::MapDeviceAddressSpaceFlag_None))) {
R_CONVERT(svc::ResultInvalidHandle, dd::ResultInvalidHandle())
R_CONVERT(svc::ResultOutOfMemory, dd::ResultOutOfMemory())
R_CONVERT(svc::ResultOutOfResource, dd::ResultOutOfResource())
R_CONVERT(svc::ResultInvalidCurrentMemory, dd::ResultInvalidMemoryState())
} R_END_TRY_CATCH_WITH_ABORT_UNLESS;
R_SUCCEED();
}
void DeviceAddressSpaceImplByHorizon::Unmap(DeviceAddressSpaceHandle handle, ProcessHandle process_handle, u64 process_address, size_t process_size, DeviceVirtualAddress device_address) {
R_ABORT_UNLESS(svc::UnmapDeviceAddressSpace(svc::Handle(handle), svc::Handle(process_handle), process_address, process_size, device_address));
}
Result DeviceAddressSpaceImplByHorizon::Attach(DeviceAddressSpaceType *das, DeviceName device_name) {
R_TRY_CATCH(svc::AttachDeviceAddressSpace(static_cast<svc::DeviceName>(device_name), svc::Handle(das->device_handle))) {
R_CONVERT(svc::ResultOutOfMemory, dd::ResultOutOfMemory())
} R_END_TRY_CATCH_WITH_ABORT_UNLESS;
R_SUCCEED();
}
void DeviceAddressSpaceImplByHorizon::Detach(DeviceAddressSpaceType *das, DeviceName device_name) {
R_ABORT_UNLESS(svc::DetachDeviceAddressSpace(static_cast<svc::DeviceName>(device_name), svc::Handle(das->device_handle)));
}
}
| 5,047
|
C++
|
.cpp
| 72
| 63.138889
| 281
| 0.725806
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,495
|
capsrv_screen_shot_control_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/capsrv/capsrv_screen_shot_control_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 <stratosphere.hpp>
namespace ams::capsrv {
Result InitializeScreenShotControl() {
#if defined(ATMOSPHERE_OS_HORIZON)
R_RETURN(::capsscInitialize());
#else
AMS_ABORT("TODO");
#endif
}
void FinalizeScreenShotControl() {
#if defined(ATMOSPHERE_OS_HORIZON)
return ::capsscExit();
#else
AMS_ABORT("TODO");
#endif
}
Result CaptureJpegScreenshot(u64 *out_size, void *dst, size_t dst_size, vi::LayerStack layer_stack, TimeSpan timeout) {
#if defined(ATMOSPHERE_OS_HORIZON)
R_RETURN(::capsscCaptureJpegScreenShot(out_size, dst, dst_size, static_cast<::ViLayerStack>(layer_stack), timeout.GetNanoSeconds()));
#else
AMS_UNUSED(out_size, dst, dst_size, layer_stack, timeout);
AMS_ABORT("TODO");
#endif
}
Result OpenRawScreenShotReadStreamForDevelop(size_t *out_data_size, s32 *out_width, s32 *out_height, vi::LayerStack layer_stack, TimeSpan timeout) {
#if defined(ATMOSPHERE_OS_HORIZON)
u64 data_size, width, height;
R_TRY(::capsscOpenRawScreenShotReadStream(std::addressof(data_size), std::addressof(width), std::addressof(height), static_cast<::ViLayerStack>(layer_stack), timeout.GetNanoSeconds()));
*out_data_size = static_cast<size_t>(data_size);
*out_width = static_cast<s32>(width);
*out_height = static_cast<s32>(height);
R_SUCCEED();
#else
AMS_UNUSED(out_data_size, out_width, out_height, layer_stack, timeout);
AMS_ABORT("TODO");
#endif
}
Result ReadRawScreenShotReadStreamForDevelop(size_t *out_read_size, void *dst, size_t dst_size, std::ptrdiff_t offset) {
#if defined(ATMOSPHERE_OS_HORIZON)
u64 read_size;
R_TRY(::capsscReadRawScreenShotReadStream(std::addressof(read_size), dst, dst_size, static_cast<u64>(offset)));
*out_read_size = static_cast<size_t>(read_size);
R_SUCCEED();
#else
AMS_UNUSED(out_read_size, dst, dst_size, offset);
AMS_ABORT("TODO");
#endif
}
void CloseRawScreenShotReadStreamForDevelop() {
#if defined(ATMOSPHERE_OS_HORIZON)
::capsscCloseRawScreenShotReadStream();
#else
AMS_UNUSED();
AMS_ABORT("TODO");
#endif
}
}
| 2,986
|
C++
|
.cpp
| 72
| 34.791667
| 193
| 0.666552
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,496
|
capsrv_server_decoder_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/capsrv/server/capsrv_server_decoder_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 <stratosphere.hpp>
#include "decodersrv/decodersrv_decoder_server_object.hpp"
namespace ams::capsrv::server {
namespace {
bool g_initialized = false;
}
Result InitializeForDecoderServer() {
/* Ensure we initialize only once. */
AMS_ABORT_UNLESS(!g_initialized);
/* Clear work memory. */
std::memset(std::addressof(g_work_memory), 0, sizeof(g_work_memory));
/* Initialize the decoder server. */
R_ABORT_UNLESS(g_decoder_control_server_manager.Initialize());
/* Start the server. */
g_decoder_control_server_manager.StartServer();
/* We're initialized. */
g_initialized = true;
R_SUCCEED();
}
void FinalizeForDecoderServer() {
/* Ensure we don't finalize when uninitialized. */
AMS_ABORT_UNLESS(g_initialized);
/* Finalize the server. */
g_decoder_control_server_manager.Finalize();
/* Mark uninitialized. */
g_initialized = false;
}
void DecoderControlServerThreadFunction(void *) {
/* We need to be initialized. */
AMS_ABORT_UNLESS(g_initialized);
/* Run the server. */
g_decoder_control_server_manager.RunServer();
}
}
| 1,887
|
C++
|
.cpp
| 49
| 32.673469
| 77
| 0.673066
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,497
|
decodersrv_software_jpeg_decoder.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/capsrv/server/jpeg/decodersrv_software_jpeg_decoder.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 "decodersrv_software_jpeg_decoder.hpp"
#include "capsrv_server_jpeg_library_types.hpp"
#include "capsrv_server_jpeg_error_handler.hpp"
namespace ams::capsrv::server::jpeg {
#define CAPSRV_ABORT_UNLESS(expr) do { \
const bool __capsrv_assert_res = (expr); \
AMS_ASSERT(__capsrv_assert_res); \
AMS_ABORT_UNLESS(__capsrv_assert_res); \
} while (0)
#define CAPSRV_ASSERT(expr) do { \
const bool __capsrv_assert_res = (expr); \
AMS_ASSERT(__capsrv_assert_res); \
R_UNLESS(__capsrv_assert_res, capsrv::ResultAlbumError()); \
} while (0)
namespace {
constexpr s32 ImageSizeHorizonalUnit = 0x10;
constexpr s32 ImageSizeVerticalUnit = 0x4;
constexpr s32 RgbColorComponentCount = 3;
constexpr s32 RgbaColorComponentCount = 4;
Result GetRgbBufferSize(size_t *out_size, size_t *out_stride, s32 width, size_t work_size) {
/* Calculate the space we need and verify we have enough. */
const size_t rgb_width = util::AlignUp(static_cast<size_t>(width), ImageSizeHorizonalUnit);
const size_t rgb_stride = rgb_width * RgbColorComponentCount;
const size_t rgb_size = rgb_stride * ImageSizeVerticalUnit;
R_UNLESS(work_size >= rgb_size, capsrv::ResultInternalJpegWorkMemoryShortage());
/* Return the output to the caller. */
*out_size = rgb_size;
*out_stride = rgb_stride;
R_SUCCEED();
}
}
Result SoftwareJpegDecoder::DecodeRgba8(SoftwareJpegDecoderOutput &output, const SoftwareJpegDecoderInput &input, void *work, size_t work_size) {
CAPSRV_ABORT_UNLESS(util::IsAligned(input.width, ImageSizeHorizonalUnit));
CAPSRV_ABORT_UNLESS(util::IsAligned(input.height, ImageSizeVerticalUnit));
CAPSRV_ABORT_UNLESS(output.dst != nullptr);
CAPSRV_ABORT_UNLESS(output.dst_size >= static_cast<size_t>(RgbaColorComponentCount * input.width * input.height));
CAPSRV_ABORT_UNLESS(output.out_width != nullptr);
CAPSRV_ABORT_UNLESS(output.out_height != nullptr);
/* Determine work buffer extents. */
char *work_start = static_cast<char *>(work);
char *work_end = work_start + work_size;
/* Determine the buffer extents for our linebuffers. */
u8 *rgb_buffer = static_cast<u8 *>(static_cast<void *>(work_start));
size_t rgb_buffer_size;
size_t rgb_buffer_stride;
R_TRY(GetRgbBufferSize(std::addressof(rgb_buffer_size), std::addressof(rgb_buffer_stride), input.width, work_size));
/* The start of the workbuffer is reserved for linebuffer space. */
work_start += rgb_buffer_size;
/* Create our decompression structure. */
JpegLibraryType::jpeg_decompress_struct cinfo = {};
/* Here nintendo creates a work buffer structure containing work_start + work_size. */
/* This seems to be a custom patch for/to libjpeg-turbo. */
/* It would be desirable for us to mimic this, because it gives Nintendo strong */
/* fixed memory usage guarantees. */
/* TODO: Determine if it is feasible for us to recreate this ourselves, */
/* Either by adding support to the devkitPro libjpeg-turbo portlib or otherwise. */
AMS_UNUSED(work_end);
/* Create our error manager. */
JpegErrorHandler jerr = {
.result = ResultSuccess(),
};
jerr.error_exit = JpegErrorHandler::HandleError,
/* Link our error manager to our decompression structure. */
cinfo.err = jpeg_std_error(std::addressof(jerr));
/* Use setjmp, so that on error our handler will longjmp to return an error result. */
if (setjmp(jerr.jmp_buf) == 0) {
/* Create our decompressor. */
jpeg_create_decompress(std::addressof(cinfo));
ON_SCOPE_EXIT { jpeg_destroy_decompress(std::addressof(cinfo)); };
/* Setup our memory reader, ensure the header is correct. */
jpeg_mem_src(std::addressof(cinfo), const_cast<unsigned char *>(static_cast<const unsigned char *>(input.jpeg)), input.jpeg_size);
R_UNLESS(jpeg_read_header(std::addressof(cinfo), true) == JPEG_HEADER_OK, capsrv::ResultAlbumInvalidFileData());
/* Ensure width and height are correct. */
R_UNLESS(cinfo.image_width == input.width, capsrv::ResultAlbumInvalidFileData());
R_UNLESS(cinfo.image_height == input.height, capsrv::ResultAlbumInvalidFileData());
/* Set output parameters. */
cinfo.out_color_space = JpegLibraryType::J_COLOR_SPACE::JCS_RGB;
cinfo.dct_method = JpegLibraryType::J_DCT_METHOD::JDCT_ISLOW;
cinfo.do_fancy_upsampling = input.fancy_upsampling;
cinfo.do_block_smoothing = input.block_smoothing;
/* Start decompression. */
R_UNLESS(jpeg_start_decompress(std::addressof(cinfo)) == TRUE, capsrv::ResultAlbumInvalidFileData());
/* Check the parameters. */
CAPSRV_ASSERT(cinfo.output_width == input.width);
CAPSRV_ASSERT(cinfo.output_height == input.height);
CAPSRV_ASSERT(cinfo.out_color_components == RgbColorComponentCount);
CAPSRV_ASSERT(cinfo.output_components == RgbColorComponentCount);
/* Parse the scanlines. */
{
/* Convert our destination to a writable u8 buffer. */
u8 *dst = static_cast<u8 *>(output.dst);
/* Create our linebuffer structure. */
JpegLibraryType::JSAMPROW linebuffers[ImageSizeVerticalUnit] = {};
for (int i = 0; i < ImageSizeVerticalUnit; i++) {
linebuffers[i] = rgb_buffer + rgb_buffer_stride * i;
}
/* While we still have scanlines, parse! */
while (cinfo.output_scanline < input.height) {
/* Decode scanlines. */
int num_scanlines = jpeg_read_scanlines(std::addressof(cinfo), linebuffers, ImageSizeVerticalUnit);
CAPSRV_ASSERT(num_scanlines <= ImageSizeVerticalUnit);
/* Write out line by line. */
for (s32 i = 0; i < num_scanlines; i++) {
const u8 *src = linebuffers[i];
for (s32 j = 0; j < static_cast<s32>(input.width); j++) {
/* Write the output. */
/* First R, */
*(dst++) = *(src++);
/* Then G, */
*(dst++) = *(src++);
/* Then B, */
*(dst++) = *(src++);
/* Then A. */
*(dst++) = 0xFF;
}
}
}
}
/* Finish the decompression. */
R_UNLESS(jpeg_finish_decompress(std::addressof(cinfo)) == TRUE, capsrv::ResultAlbumInvalidFileData());
} else {
/* Some unknown error was caught by our handler. */
R_THROW(capsrv::ResultAlbumInvalidFileData());
}
/* Write the size we decoded to output. */
*output.out_width = static_cast<s32>(cinfo.output_width);
*output.out_width = static_cast<s32>(cinfo.output_height);
R_SUCCEED();
}
}
| 8,368
|
C++
|
.cpp
| 146
| 45.650685
| 149
| 0.589637
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,498
|
decodersrv_software_jpeg_shrinker.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/capsrv/server/jpeg/decodersrv_software_jpeg_shrinker.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 "decodersrv_software_jpeg_shrinker.hpp"
#include "capsrv_server_jpeg_library_types.hpp"
#include "capsrv_server_jpeg_error_handler.hpp"
namespace ams::capsrv::server::jpeg {
#define CAPSRV_ABORT_UNLESS(expr) do { \
const bool __capsrv_assert_res = (expr); \
AMS_ASSERT(__capsrv_assert_res); \
AMS_ABORT_UNLESS(__capsrv_assert_res); \
} while (0)
#define CAPSRV_ASSERT(expr) do { \
const bool __capsrv_assert_res = (expr); \
AMS_ASSERT(__capsrv_assert_res); \
R_UNLESS(__capsrv_assert_res, capsrv::ResultAlbumError()); \
} while (0)
namespace {
constexpr s32 ImageSizeHorizonalUnit = 0x10;
constexpr s32 ImageSizeVerticalUnitDecode = 0x4;
constexpr s32 ImageSizeVerticalUnitEncode = 0x8;
constexpr s32 RgbColorComponentCount = 3;
constexpr s32 RgbaColorComponentCount = 4;
Result GetRgbBufferSize(size_t *out_size, size_t *out_stride, s32 width, size_t work_size) {
/* Calculate the space we need and verify we have enough. */
const size_t rgb_width = util::AlignUp(static_cast<size_t>(width), ImageSizeHorizonalUnit);
const size_t rgb_stride = rgb_width * RgbColorComponentCount;
const size_t rgb_size = rgb_stride * ImageSizeVerticalUnitEncode;
R_UNLESS(work_size >= rgb_size, capsrv::ResultInternalJpegWorkMemoryShortage());
/* Return the output to the caller. */
*out_size = rgb_size;
*out_stride = rgb_stride;
R_SUCCEED();
}
void SetupEncodingParameter(JpegLibraryType::jpeg_compress_struct *cinfo, const SoftwareJpegShrinkerInput &input, int quality) {
/* Set parameters. */
cinfo->image_width = static_cast<JpegLibraryType::JDIMENSION>(input.width / 2);
cinfo->image_height = static_cast<JpegLibraryType::JDIMENSION>(input.height / 2);
cinfo->input_components = RgbColorComponentCount;
cinfo->in_color_space = JpegLibraryType::J_COLOR_SPACE::JCS_RGB;
/* Set defaults/color space. */
jpeg_set_defaults(cinfo);
jpeg_set_colorspace(cinfo, JpegLibraryType::J_COLOR_SPACE::JCS_YCbCr);
/* Configure sampling. */
/* libjpeg-turbo doesn't actually have this field, as of now. */
/* cinfo->do_fancy_downsampling = false; */
cinfo->comp_info[0].h_samp_factor = 2;
cinfo->comp_info[0].v_samp_factor = 1;
cinfo->comp_info[1].h_samp_factor = 1;
cinfo->comp_info[1].v_samp_factor = 1;
cinfo->comp_info[2].h_samp_factor = 1;
cinfo->comp_info[2].v_samp_factor = 1;
/* Set the quality. */
jpeg_set_quality(cinfo, quality, true);
/* Configure remaining parameters. */
cinfo->dct_method = JpegLibraryType::J_DCT_METHOD::JDCT_ISLOW;
cinfo->optimize_coding = false;
cinfo->write_JFIF_header = true;
}
}
Result SoftwareJpegShrinker::ShrinkRgba8(SoftwareJpegShrinkerOutput &output, const SoftwareJpegShrinkerInput &input, int quality, void *work, size_t work_size) {
CAPSRV_ABORT_UNLESS(util::IsAligned(input.width, ImageSizeHorizonalUnit));
CAPSRV_ABORT_UNLESS(util::IsAligned(input.height, ImageSizeVerticalUnitDecode));
const u32 shrunk_width = input.width / 2;
const u32 shrunk_height = input.height / 2;
CAPSRV_ABORT_UNLESS(util::IsAligned(shrunk_width, ImageSizeHorizonalUnit));
CAPSRV_ABORT_UNLESS(output.dst != nullptr);
CAPSRV_ABORT_UNLESS(output.out_width != nullptr);
CAPSRV_ABORT_UNLESS(output.out_height != nullptr);
/* Determine work buffer extents. */
char *work_start = static_cast<char *>(work);
char *work_end = work_start + work_size;
/* Determine the buffer extents for our linebuffers. */
u8 *rgb_buffer = static_cast<u8 *>(static_cast<void *>(work_start));
size_t rgb_buffer_size;
size_t rgb_buffer_stride;
R_TRY(GetRgbBufferSize(std::addressof(rgb_buffer_size), std::addressof(rgb_buffer_stride), input.width, work_size));
/* The start of the workbuffer is reserved for linebuffer space. */
work_start += rgb_buffer_size;
/* Create our compression structures. */
JpegLibraryType::jpeg_decompress_struct dcinfo = {};
JpegLibraryType::jpeg_compress_struct ecinfo = {};
/* Here nintendo creates a work buffer structure containing work_start + work_size. */
/* This seems to be a custom patch for/to libjpeg-turbo. */
/* It would be desirable for us to mimic this, because it gives Nintendo strong */
/* fixed memory usage guarantees. */
/* TODO: Determine if it is feasible for us to recreate this ourselves, */
/* Either by adding support to the devkitPro libjpeg-turbo portlib or otherwise. */
AMS_UNUSED(work_end);
/* Create our error managers. */
JpegErrorHandler jerr_dc = { .result = ResultSuccess(), };
JpegErrorHandler jerr_ec = { .result = ResultSuccess(), };
jerr_dc.error_exit = JpegErrorHandler::HandleError,
jerr_ec.error_exit = JpegErrorHandler::HandleError,
/* Link our error managers to our compression structures. */
dcinfo.err = jpeg_std_error(std::addressof(jerr_dc));
ecinfo.err = jpeg_std_error(std::addressof(jerr_ec));
/* Use setjmp, so that on error our handler will longjmp to return an error result. */
if (setjmp(jerr_ec.jmp_buf) == 0) {
if (setjmp(jerr_dc.jmp_buf) == 0) {
/* Create our decompressor. */
jpeg_create_decompress(std::addressof(dcinfo));
ON_SCOPE_EXIT { jpeg_destroy_decompress(std::addressof(dcinfo)); };
/* Setup our memory reader, ensure the header is correct. */
jpeg_mem_src(std::addressof(dcinfo), const_cast<unsigned char *>(static_cast<const unsigned char *>(input.jpeg)), input.jpeg_size);
R_UNLESS(jpeg_read_header(std::addressof(dcinfo), true) == JPEG_HEADER_OK, capsrv::ResultAlbumInvalidFileData());
/* Ensure width and height are correct. */
R_UNLESS(dcinfo.image_width == input.width, capsrv::ResultAlbumInvalidFileData());
R_UNLESS(dcinfo.image_height == input.height, capsrv::ResultAlbumInvalidFileData());
/* Set output parameters. */
dcinfo.out_color_space = JpegLibraryType::J_COLOR_SPACE::JCS_RGB;
dcinfo.dct_method = JpegLibraryType::J_DCT_METHOD::JDCT_ISLOW;
dcinfo.do_fancy_upsampling = input.fancy_upsampling;
dcinfo.do_block_smoothing = input.block_smoothing;
dcinfo.scale_num = 1;
dcinfo.scale_denom = 2;
/* Start decompression. */
R_UNLESS(jpeg_start_decompress(std::addressof(dcinfo)) == TRUE, capsrv::ResultAlbumInvalidFileData());
/* Check the parameters. */
CAPSRV_ASSERT(dcinfo.output_width == shrunk_width);
CAPSRV_ASSERT(dcinfo.output_height == shrunk_height);
CAPSRV_ASSERT(dcinfo.out_color_components == RgbColorComponentCount);
CAPSRV_ASSERT(dcinfo.output_components == RgbColorComponentCount);
/* Create our compressor. */
jpeg_create_compress(std::addressof(ecinfo));
ON_SCOPE_EXIT { jpeg_destroy_compress(std::addressof(ecinfo)); };
/* Setup our memory writer. */
unsigned long out_size = static_cast<unsigned long>(output.dst_size);
jpeg_mem_dest(std::addressof(ecinfo), reinterpret_cast<unsigned char **>(std::addressof(output.dst)), std::addressof(out_size));
/* Setup the encoding parameters. */
SetupEncodingParameter(std::addressof(ecinfo), input, quality);
/* Start compression. */
jpeg_start_compress(std::addressof(ecinfo), true);
/* Parse the scanlines. */
{
/* Create our linebuffer structure. */
JpegLibraryType::JSAMPROW linebuffers[ImageSizeVerticalUnitEncode] = {};
for (int i = 0; i < ImageSizeVerticalUnitEncode; i++) {
linebuffers[i] = rgb_buffer + rgb_buffer_stride * i;
}
/* While we still have scanlines, parse! */
while (dcinfo.output_scanline < shrunk_height) {
/* Determine remaining scanlines. */
const auto remaining_scanlines = shrunk_height - dcinfo.output_scanline;
const auto cur_max_scanlines = std::min<s32>(remaining_scanlines, ImageSizeVerticalUnitEncode);
/* If we have scanlines to decode, try to do so. */
auto writable_scanlines = 0;
while (writable_scanlines < cur_max_scanlines) {
const auto decoded = jpeg_read_scanlines(std::addressof(dcinfo), linebuffers + writable_scanlines, ImageSizeVerticalUnitDecode);
CAPSRV_ASSERT(decoded <= ImageSizeVerticalUnitDecode / 2);
writable_scanlines += decoded;
}
/* If we have scanlines to write, try to do so. */
jpeg_write_scanlines(std::addressof(ecinfo), linebuffers, writable_scanlines);
}
}
/* Finish the decompression. */
R_UNLESS(jpeg_finish_decompress(std::addressof(dcinfo)) == TRUE, capsrv::ResultAlbumInvalidFileData());
/* Finish the compression. */
jpeg_finish_compress(std::addressof(ecinfo));
/* Set the output size. */
*output.out_size = out_size;
} else {
/* Some unknown error was caught by our handler. */
R_THROW(capsrv::ResultAlbumInvalidFileData());
}
} else {
/* Return the encoding result. */
R_THROW(jerr_ec.result);
}
/* Write the size we decoded to output. */
*output.out_width = static_cast<s32>(dcinfo.output_width);
*output.out_width = static_cast<s32>(dcinfo.output_height);
R_SUCCEED();
}
}
| 11,506
|
C++
|
.cpp
| 189
| 48.359788
| 165
| 0.59929
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,499
|
decodersrv_decoder_server_object.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/capsrv/server/decodersrv/decodersrv_decoder_server_object.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 "decodersrv_decoder_server_object.hpp"
namespace ams::capsrv::server {
/* Instantiate the decoder server globals in a single TU. */
DecoderWorkMemory g_work_memory;
DecoderControlServerManager g_decoder_control_server_manager;
}
| 916
|
C++
|
.cpp
| 22
| 39.318182
| 76
| 0.765432
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,500
|
decodersrv_decoder_control_service.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/capsrv/server/decodersrv/decodersrv_decoder_control_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 "decodersrv_decoder_server_object.hpp"
#include "../jpeg/decodersrv_software_jpeg_decoder.hpp"
#include "../jpeg/decodersrv_software_jpeg_shrinker.hpp"
namespace ams::capsrv::server {
namespace {
constexpr const int JpegShrinkQualities[] = {
98, 95, 90, 80, 70, 60, 50, 40, 30, 20, 10, 0
};
Result DecodeJpegImpl(void *dst, size_t dst_size, const void *src_jpeg, size_t src_jpeg_size, u32 width, u32 height, const ScreenShotDecodeOption &option, void *work, size_t work_size) {
/* Clear the work memory. */
std::memset(work, 0, work_size);
ON_SCOPE_EXIT { std::memset(work, 0, work_size); };
/* Clear the output memory. */
std::memset(dst, 0, dst_size);
auto clear_guard = SCOPE_GUARD { std::memset(dst, 0, dst_size); };
/* Validate parameters. */
R_UNLESS(util::IsAligned(width, 0x10), capsrv::ResultAlbumOutOfRange());
R_UNLESS(util::IsAligned(height, 0x4), capsrv::ResultAlbumOutOfRange());
R_UNLESS(dst != nullptr, capsrv::ResultAlbumReadBufferShortage());
R_UNLESS(dst_size >= 4 * width * height, capsrv::ResultAlbumReadBufferShortage());
R_UNLESS(src_jpeg != nullptr, capsrv::ResultAlbumInvalidFileData());
R_UNLESS(src_jpeg_size != 0, capsrv::ResultAlbumInvalidFileData());
/* Create the input. */
const jpeg::SoftwareJpegDecoderInput decode_input = {
.jpeg = src_jpeg,
.jpeg_size = src_jpeg_size,
.width = width,
.height = height,
.fancy_upsampling = option.HasJpegDecoderFlag(ScreenShotDecoderFlag_EnableFancyUpsampling),
.block_smoothing = option.HasJpegDecoderFlag(ScreenShotDecoderFlag_EnableBlockSmoothing),
};
/* Create the output. */
s32 out_width = 0, out_height = 0;
jpeg::SoftwareJpegDecoderOutput decode_output = {
.out_width = std::addressof(out_width),
.out_height = std::addressof(out_height),
.dst = dst,
.dst_size = dst_size,
};
/* Decode the jpeg. */
R_TRY(jpeg::SoftwareJpegDecoder::DecodeRgba8(decode_output, decode_input, work, work_size));
/* We succeeded, so we shouldn't clear the output memory. */
clear_guard.Cancel();
R_SUCCEED();
}
Result ShrinkJpegImpl(u64 *out_size, void *dst, size_t dst_size, const void *src_jpeg, size_t src_jpeg_size, u32 width, u32 height, const ScreenShotDecodeOption &option, void *work, size_t work_size) {
/* Validate parameters. */
R_UNLESS(util::IsAligned(width, 0x10), capsrv::ResultAlbumOutOfRange());
R_UNLESS(util::IsAligned(height, 0x4), capsrv::ResultAlbumOutOfRange());
R_UNLESS(dst != nullptr, capsrv::ResultInternalJpegOutBufferShortage());
R_UNLESS(dst_size != 0, capsrv::ResultAlbumReadBufferShortage());
R_UNLESS(src_jpeg != nullptr, capsrv::ResultAlbumInvalidFileData());
R_UNLESS(src_jpeg_size != 0, capsrv::ResultAlbumInvalidFileData());
/* Create the input. */
const jpeg::SoftwareJpegShrinkerInput shrink_input = {
.jpeg = src_jpeg,
.jpeg_size = src_jpeg_size,
.width = width,
.height = height,
.fancy_upsampling = option.HasJpegDecoderFlag(ScreenShotDecoderFlag_EnableFancyUpsampling),
.block_smoothing = option.HasJpegDecoderFlag(ScreenShotDecoderFlag_EnableBlockSmoothing),
};
/* Create the output. */
u64 shrunk_size = 0;
s32 shrunk_width = 0, shrunk_height = 0;
jpeg::SoftwareJpegShrinkerOutput shrink_output = {
.out_size = std::addressof(shrunk_size),
.out_width = std::addressof(shrunk_width),
.out_height = std::addressof(shrunk_height),
.dst = dst,
.dst_size = dst_size,
};
/* Try to shrink the jpeg at various quality levels. */
for (auto quality : JpegShrinkQualities) {
/* Shrink at the current quality. */
R_TRY_CATCH(jpeg::SoftwareJpegShrinker::ShrinkRgba8(shrink_output, shrink_input, quality, work, work_size)) {
/* If the output buffer isn't large enough to fit the output, we should try at a lower quality. */
R_CATCH(capsrv::ResultInternalJpegOutBufferShortage) {
continue;
}
/* Nintendo doesn't catch this result, but our lack of work buffer use makes me think this may be necessary. */
R_CATCH(capsrv::ResultInternalJpegWorkMemoryShortage) {
continue;
}
} R_END_TRY_CATCH;
/* Write the output size. */
*out_size = shrunk_size;
R_SUCCEED();
}
/* Nintendo aborts if no quality succeeds. */
AMS_ABORT("ShrinkJpeg should succeed before this point\n");
}
}
Result DecoderControlService::DecodeJpeg(const ams::sf::OutNonSecureBuffer &out, const ams::sf::InBuffer &in, u32 width, u32 height, const ScreenShotDecodeOption &option) {
/* Get the work buffer. */
void *work = g_work_memory.jpeg_decoder_memory;
size_t work_size = sizeof(g_work_memory.jpeg_decoder_memory);
/* Call the decoder implementation. */
R_RETURN(DecodeJpegImpl(out.GetPointer(), out.GetSize(), in.GetPointer(), in.GetSize(), width, height, option, work, work_size));
}
Result DecoderControlService::ShrinkJpeg(ams::sf::Out<u64> out_size, const ams::sf::OutNonSecureBuffer &out, const ams::sf::InBuffer &in, u32 width, u32 height, const capsrv::ScreenShotDecodeOption &option) {
/* Get the work buffer. */
void *work = g_work_memory.jpeg_decoder_memory;
size_t work_size = sizeof(g_work_memory.jpeg_decoder_memory);
/* Call the shrink implementation. */
R_RETURN(ShrinkJpegImpl(out_size.GetPointer(), out.GetPointer(), out.GetSize(), in.GetPointer(), in.GetSize(), width, height, option, work, work_size));
}
}
| 7,244
|
C++
|
.cpp
| 124
| 46.58871
| 212
| 0.599718
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,501
|
decodersrv_decoder_control_server_manager.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/capsrv/server/decodersrv/decodersrv_decoder_control_server_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 "decodersrv_decoder_server_object.hpp"
namespace ams::capsrv::server {
Result DecoderControlServerManager::Initialize() {
/* Create the objects. */
m_service_holder.emplace();
m_server_manager_holder.emplace();
/* Register the service. */
R_ABORT_UNLESS((m_server_manager_holder->RegisterObjectForServer(m_service_holder->GetShared(), ServiceName, MaxSessions)));
/* Initialize the idle event, we're idle initially. */
os::InitializeEvent(std::addressof(m_idle_event), true, os::EventClearMode_ManualClear);
R_SUCCEED();
}
void DecoderControlServerManager::Finalize() {
/* Check that the server is idle. */
AMS_ASSERT(os::TryWaitEvent(std::addressof(m_idle_event)));
/* Destroy the server. */
os::FinalizeEvent(std::addressof(m_idle_event));
m_server_manager_holder = util::nullopt;
m_service_holder = util::nullopt;
}
void DecoderControlServerManager::StartServer() {
m_server_manager_holder->ResumeProcessing();
}
void DecoderControlServerManager::StopServer() {
/* Request the server stop, and wait until it does. */
m_server_manager_holder->RequestStopProcessing();
os::WaitEvent(std::addressof(m_idle_event));
}
void DecoderControlServerManager::RunServer() {
/* Ensure that we are allowed to run. */
AMS_ABORT_UNLESS(os::TryWaitEvent(std::addressof(m_idle_event)));
/* Clear the event. */
os::ClearEvent(std::addressof(m_idle_event));
/* Process forever. */
m_server_manager_holder->LoopProcess();
/* Signal that we're idle again. */
os::SignalEvent(std::addressof(m_idle_event));
}
}
| 2,432
|
C++
|
.cpp
| 55
| 38.2
| 132
| 0.68176
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,502
|
lm_remote_log_service.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/lm/lm_remote_log_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 "lm_remote_log_service.hpp"
#include "lm_service_name.hpp"
namespace ams::lm {
#if defined(ATMOSPHERE_OS_HORIZON)
namespace {
struct LmRemoteLogServiceTag;
using RemoteAllocator = ams::sf::ExpHeapStaticAllocator<0x80, LmRemoteLogServiceTag>;
using RemoteObjectFactory = ams::sf::ObjectFactory<typename RemoteAllocator::Policy>;
class StaticAllocatorInitializer {
public:
StaticAllocatorInitializer() {
RemoteAllocator::Initialize(lmem::CreateOption_None);
}
} g_static_allocator_initializer;
}
Result RemoteLogService::OpenLogger(sf::Out<sf::SharedPointer<::ams::lm::ILogger>> out, const sf::ClientProcessId &client_process_id) {
AMS_UNUSED(client_process_id);
/* Send libnx command. */
::Service logger_srv;
{
u64 pid_placeholder = 0;
#define NX_SERVICE_ASSUME_NON_DOMAIN
R_TRY(serviceDispatchIn(std::addressof(m_srv), 0, pid_placeholder,
.in_send_pid = true,
.out_num_objects = 1,
.out_objects = std::addressof(logger_srv),
));
#undef NX_SERVICE_ASSUME_NON_DOMAIN
}
/* Open logger. */
out.SetValue(RemoteObjectFactory::CreateSharedEmplaced<::ams::lm::ILogger, RemoteLogger>(logger_srv));
R_SUCCEED();
}
sf::SharedPointer<ILogService> CreateLogService() {
os::NativeHandle h;
R_ABORT_UNLESS(sm::GetServiceHandle(std::addressof(h), LogServiceName));
return RemoteObjectFactory::CreateSharedEmplaced<::ams::lm::ILogService, RemoteLogService>(h);
}
#else
sf::SharedPointer<ILogService> CreateLogService() {
AMS_ABORT("TODO");
}
#endif
}
| 2,475
|
C++
|
.cpp
| 60
| 33.95
| 139
| 0.666251
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,503
|
lm_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/lm/lm_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 <stratosphere.hpp>
#include "lm_remote_log_service.hpp"
#include "impl/lm_log_packet_header.hpp"
#include "impl/lm_log_packet_transmitter.hpp"
namespace ams::diag::impl {
void ReplaceDefaultLogObserver(LogObserver observer);
void ResetDefaultLogObserver();
void GetProcessNamePointer(const char **out, size_t *out_len);
}
namespace ams::lm {
namespace {
constinit sf::SharedPointer<ILogger> g_logger = nullptr;
constexpr inline size_t TransmissionBufferSize = 1_KB;
constexpr inline size_t TransmissionBufferAlign = alignof(impl::LogPacketHeader);
constinit os::SdkMutex g_transmission_buffer_mutex;
alignas(TransmissionBufferAlign) constinit char g_transmission_buffer[TransmissionBufferSize];
using PushTextFunction = void (impl::LogPacketTransmitter::*)(const char *, size_t);
bool LogPacketTransmitterFlushFunction(const u8 *data, size_t size) {
const Result result = g_logger->Log(sf::InAutoSelectBuffer(data, size));
R_ABORT_UNLESS(result);
return R_SUCCEEDED(result);
}
void InvokePushTextWithUtf8Sanitizing(impl::LogPacketTransmitter &transmitter, PushTextFunction push_func, const char *str) {
/* Get the string length. */
const auto len = std::strlen(str);
if (len == 0 || util::VerifyUtf8String(str, len)) {
(transmitter.*push_func)(str, len);
} else {
(transmitter.*push_func)("(Invalid UTF8 string)", sizeof("(Invalid UTF8 string)") - 1);
}
}
void LogManagerLogObserver(const diag::LogMetaData &meta, const diag::LogBody &body, void *) {
/* Check pre-conditions. */
AMS_ASSERT(!meta.use_default_locale_charset);
/* Acquire access to the transmission buffer. */
std::scoped_lock lk(g_transmission_buffer_mutex);
/* Create transmitter. */
impl::LogPacketTransmitter transmitter(g_transmission_buffer, TransmissionBufferSize, LogPacketTransmitterFlushFunction, static_cast<u8>(meta.severity), static_cast<u8>(meta.verbosity), 0, body.is_head, body.is_tail);
/* Push head-only logs. */
if (body.is_head) {
transmitter.PushUserSystemClock(os::GetSystemTick().ToTimeSpan().GetSeconds());
transmitter.PushLineNumber(meta.source_info.line_number);
InvokePushTextWithUtf8Sanitizing(transmitter, &impl::LogPacketTransmitter::PushFileName, meta.source_info.file_name);
InvokePushTextWithUtf8Sanitizing(transmitter, &impl::LogPacketTransmitter::PushFunctionName, meta.source_info.function_name);
InvokePushTextWithUtf8Sanitizing(transmitter, &impl::LogPacketTransmitter::PushModuleName, meta.module_name);
InvokePushTextWithUtf8Sanitizing(transmitter, &impl::LogPacketTransmitter::PushThreadName, os::GetThreadNamePointer(os::GetCurrentThread()));
const char *process_name;
size_t process_name_len;
diag::impl::GetProcessNamePointer(std::addressof(process_name), std::addressof(process_name_len));
transmitter.PushProcessName(process_name, process_name_len);
}
/* Push the actual log. */
transmitter.PushTextLog(body.message, body.message_size);
}
}
void Initialize() {
AMS_ABORT_UNLESS(g_logger == nullptr);
/* Create the logger. */
{
auto service = CreateLogService();
R_ABORT_UNLESS(service->OpenLogger(std::addressof(g_logger), sf::ClientProcessId{}));
}
/* Replace the default log observer. */
diag::impl::ReplaceDefaultLogObserver(LogManagerLogObserver);
}
void Finalize() {
AMS_ABORT_UNLESS(g_logger != nullptr);
/* Reset the default log observer. */
diag::impl::ResetDefaultLogObserver();
/* Destroy the logger. */
g_logger = nullptr;
}
void SetDestination(u32 destination) {
g_logger->SetDestination(destination);
}
}
| 4,783
|
C++
|
.cpp
| 91
| 43.604396
| 229
| 0.674174
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,504
|
lm_log_packet_transmitter_base.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/lm/impl/lm_log_packet_transmitter_base.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "lm_log_packet_transmitter_base.hpp"
namespace ams::lm::impl {
LogPacketTransmitterBase::LogPacketTransmitterBase(void *buffer, size_t buffer_size, FlushFunction flush_func, u8 severity, u8 verbosity, u64 process_id, bool head, bool tail) {
/* Check pre-conditions. */
AMS_ASSERT(buffer != nullptr);
AMS_ASSERT(util::IsAligned(reinterpret_cast<uintptr_t>(buffer), alignof(LogPacketHeader)));
AMS_ASSERT(buffer_size >= LogPacketHeaderSize);
AMS_ASSERT(flush_func != nullptr);
/* Construct log packet header. */
m_header = std::construct_at(static_cast<LogPacketHeader *>(buffer));
/* Set fields. */
m_start = static_cast<u8 *>(buffer);
m_end = m_start + buffer_size;
m_payload = m_start + LogPacketHeaderSize;
m_current = m_payload;
m_is_tail = tail;
m_flush_function = flush_func;
/* Set header fields. */
m_header->SetProcessId(process_id);
m_header->SetThreadId(os::GetThreadId(os::GetCurrentThread()));
m_header->SetHead(head);
m_header->SetLittleEndian(util::IsLittleEndian());
m_header->SetSeverity(severity);
m_header->SetVerbosity(verbosity);
}
bool LogPacketTransmitterBase::Flush(bool is_tail) {
/* Check if we're already flushed. */
if (m_current == m_payload) {
return true;
}
/* Flush the data. */
m_header->SetTail(is_tail);
m_header->SetPayloadSize(static_cast<u32>(m_current - m_payload));
const auto result = m_flush_function(m_start, static_cast<size_t>(m_current - m_start));
m_header->SetHead(false);
/* Reset. */
m_current = m_payload;
return result;
}
size_t LogPacketTransmitterBase::GetRemainSize() {
return static_cast<size_t>(m_end - m_current);
}
size_t LogPacketTransmitterBase::GetPushableDataSize(size_t uleb_size) {
const size_t remain = this->GetRemainSize();
if (remain < uleb_size + 2) {
return 0;
}
const size_t cmp = remain - uleb_size;
u64 mask = 0x7F;
size_t n;
for (n = 1; mask + n < cmp; ++n) {
mask |= mask << 7;
}
return cmp - n;
}
size_t LogPacketTransmitterBase::GetRequiredSizeToPushUleb128(u64 v) {
/* Determine bytes needed for uleb128 value. */
size_t required = 0;
do {
++required;
v >>= 7;
} while (v > 0);
return required;
}
void LogPacketTransmitterBase::PushUleb128(u64 v) {
const u32 Mask = 0x7F;
const u32 InverseMask = ~Mask;
do {
/* Check we're within bounds. */
AMS_ASSERT(m_current < m_end);
/* Write byte. */
*(m_current++) = static_cast<u8>(v & Mask) | (((v & InverseMask) != 0) ? 0x80 : 0x00);
/* Adjust remaining bit range. */
v >>= 7;
} while (v > 0);
}
void LogPacketTransmitterBase::PushDataChunkImpl(LogDataChunkKey key, const void *data, size_t data_size, bool is_text) {
/* Check pre-conditions. */
AMS_ASSERT(data != nullptr);
/* Push as much data as we can, until the chunk is complete. */
const u8 *cur = static_cast<const u8 *>(data);
const u8 * const end = cur + data_size;
const size_t required_key = this->GetRequiredSizeToPushUleb128(key);
do {
/* Get the pushable size. */
size_t pushable_size = this->GetPushableDataSize(required_key);
size_t required_size = is_text ? 4 : 1;
if (pushable_size < required_size) {
this->Flush(false);
pushable_size = this->GetPushableDataSize(required_key);
}
AMS_ASSERT(pushable_size >= required_size);
/* Determine the current size. */
size_t current_size = std::min<size_t>(pushable_size, end - cur);
if (is_text) {
const auto valid_size = diag::impl::GetValidSizeAsUtf8String(reinterpret_cast<const char *>(cur), current_size);
if (valid_size >= 0) {
current_size = static_cast<size_t>(valid_size);
}
}
/* Push data. */
this->PushUleb128(key);
this->PushUleb128(current_size);
this->PushData(cur, current_size);
/* Advance. */
cur = cur + current_size;
} while (cur < end);
/* Check that we pushed all the data. */
AMS_ASSERT(cur == end);
}
void LogPacketTransmitterBase::PushData(const void *data, size_t size) {
/* Check pre-conditions. */
AMS_ASSERT(data != nullptr);
AMS_ASSERT(size <= this->GetRemainSize());
/* Push the data. */
if (size > 0) {
std::memcpy(m_current, data, size);
m_current += size;
}
}
}
| 5,688
|
C++
|
.cpp
| 137
| 32.554745
| 181
| 0.589823
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,505
|
lm_event_log_transmitter.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/lm/srv/lm_event_log_transmitter.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 "lm_event_log_transmitter.hpp"
#include "lm_log_buffer.hpp"
#include "../impl/lm_log_packet_header.hpp"
#include "../impl/lm_log_packet_transmitter.hpp"
namespace ams::lm::srv {
namespace {
constexpr inline size_t TransmitterBufferAlign = alignof(impl::LogPacketHeader);
constexpr inline size_t TransmitterBufferSizeForSessionInfo = impl::LogPacketHeaderSize + 3;
constexpr inline size_t TransmitterBufferSizeForDropCount = impl::LogPacketHeaderSize + 10;
bool DefaultFlushFunction(const u8 *data, size_t size) {
return LogBuffer::GetDefaultInstance().TryPush(data, size);
}
}
EventLogTransmitter &EventLogTransmitter::GetDefaultInstance() {
AMS_FUNCTION_LOCAL_STATIC_CONSTINIT(EventLogTransmitter, s_default_event_log_transmitter, DefaultFlushFunction);
return s_default_event_log_transmitter;
}
bool EventLogTransmitter::PushLogSessionBegin(u64 process_id) {
/* Create a transmitter. */
alignas(TransmitterBufferAlign) u8 buffer[TransmitterBufferSizeForSessionInfo];
impl::LogPacketTransmitter transmitter(buffer, sizeof(buffer), m_flush_function, static_cast<u8>(diag::LogSeverity_Info), 0, process_id, true, true);
/* Push session begin. */
transmitter.PushLogSessionBegin();
/* Flush the data. */
const bool success = transmitter.Flush(true);
/* Update drop count. */
if (!success) {
++m_log_packet_drop_count;
}
return success;
}
bool EventLogTransmitter::PushLogSessionEnd(u64 process_id) {
/* Create a transmitter. */
alignas(TransmitterBufferAlign) u8 buffer[TransmitterBufferSizeForSessionInfo];
impl::LogPacketTransmitter transmitter(buffer, sizeof(buffer), m_flush_function, static_cast<u8>(diag::LogSeverity_Info), 0, process_id, true, true);
/* Push session end. */
transmitter.PushLogSessionEnd();
/* Flush the data. */
const bool success = transmitter.Flush(true);
/* Update drop count. */
if (!success) {
++m_log_packet_drop_count;
}
return success;
}
bool EventLogTransmitter::PushLogPacketDropCountIfExists() {
/* Acquire exclusive access. */
std::scoped_lock lk(m_log_packet_drop_count_mutex);
/* If we have no dropped packets, nothing to push. */
if (m_log_packet_drop_count == 0) {
return true;
}
/* Create a transmitter. */
alignas(TransmitterBufferAlign) u8 buffer[TransmitterBufferSizeForDropCount];
impl::LogPacketTransmitter transmitter(buffer, sizeof(buffer), m_flush_function, static_cast<u8>(diag::LogSeverity_Info), 0, 0, true, true);
/* Push log packet drop count. */
transmitter.PushLogPacketDropCount(m_log_packet_drop_count);
/* Flush the data. */
const bool success = transmitter.Flush(true);
/* Update drop count. */
if (success) {
m_log_packet_drop_count = 0;
} else {
++m_log_packet_drop_count;
}
return success;
}
void EventLogTransmitter::IncreaseLogPacketDropCount() {
/* Acquire exclusive access. */
std::scoped_lock lk(m_log_packet_drop_count_mutex);
/* Increase the dropped packet count. */
++m_log_packet_drop_count;
}
}
| 4,101
|
C++
|
.cpp
| 90
| 38.333333
| 157
| 0.675703
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,506
|
lm_ipc_server.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/lm/srv/lm_ipc_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 "../lm_service_name.hpp"
#include "lm_log_service_impl.hpp"
#include "lm_log_getter.hpp"
namespace ams::lm::srv {
namespace {
constexpr inline size_t LogSessionCountMax = 42;
constexpr inline size_t LogGetterSessionCountMax = 1;
constexpr inline size_t SessionCountMax = LogSessionCountMax + LogGetterSessionCountMax;
constexpr inline size_t PortCountMax = 2;
struct ServerManagerOptions {
static constexpr size_t PointerBufferSize = 0x400;
static constexpr size_t MaxDomains = 31;
static constexpr size_t MaxDomainObjects = 61;
static constexpr bool CanDeferInvokeRequest = false;
static constexpr bool CanManageMitmServers = false;
};
using ServerManager = sf::hipc::ServerManager<PortCountMax, ServerManagerOptions, SessionCountMax>;
constinit util::TypedStorage<ServerManager> g_server_manager_storage = {};
constinit ServerManager *g_server_manager = nullptr;
constinit util::TypedStorage<psc::PmModule> g_pm_module_storage = {};
constinit psc::PmModule *g_pm_module = nullptr;
constinit os::MultiWaitHolderType g_pm_module_holder = {};
constexpr const psc::PmModuleId PmModuleDependencies[] = { psc::PmModuleId_TmaHostIo, psc::PmModuleId_Fs };
/* Service objects. */
constinit sf::UnmanagedServiceObject<lm::ILogService, lm::srv::LogServiceImpl> g_log_service_object;
constinit sf::UnmanagedServiceObject<lm::ILogGetter, lm::srv::LogGetter> g_log_getter_service_object;
constinit std::atomic<bool> g_is_sleeping = false;
}
bool IsSleeping() {
return g_is_sleeping;
}
void InitializeIpcServer() {
/* Check that we're not already initialized. */
AMS_ABORT_UNLESS(g_server_manager == nullptr);
AMS_ABORT_UNLESS(g_pm_module == nullptr);
/* Create and initialize the psc module. */
g_pm_module = util::ConstructAt(g_pm_module_storage);
R_ABORT_UNLESS(g_pm_module->Initialize(psc::PmModuleId_Lm, PmModuleDependencies, util::size(PmModuleDependencies), os::EventClearMode_ManualClear));
/* Create the psc module multi wait holder. */
os::InitializeMultiWaitHolder(std::addressof(g_pm_module_holder), g_pm_module->GetEventPointer()->GetBase());
os::SetMultiWaitHolderUserData(std::addressof(g_pm_module_holder), psc::PmModuleId_Lm);
/* Create the server manager. */
g_server_manager = util::ConstructAt(g_server_manager_storage);
/* Add the pm module holder. */
g_server_manager->AddUserMultiWaitHolder(std::addressof(g_pm_module_holder));
/* Create services. */
R_ABORT_UNLESS(g_server_manager->RegisterObjectForServer(g_log_service_object.GetShared(), LogServiceName, LogSessionCountMax));
R_ABORT_UNLESS(g_server_manager->RegisterObjectForServer(g_log_getter_service_object.GetShared(), LogGetterServiceName, LogGetterSessionCountMax));
/* Start the server manager. */
g_server_manager->ResumeProcessing();
}
void LoopIpcServer() {
/* Check that we're initialized. */
AMS_ABORT_UNLESS(g_server_manager != nullptr);
/* Loop forever, servicing the server. */
auto prev_state = psc::PmState_Unknown;
while (true) {
/* Get the next signaled holder. */
auto *signaled_holder = g_server_manager->WaitSignaled();
if (signaled_holder != std::addressof(g_pm_module_holder)) {
/* If ipc, process. */
R_ABORT_UNLESS(g_server_manager->Process(signaled_holder));
} else {
/* If pm module, clear the event. */
g_pm_module->GetEventPointer()->Clear();
g_server_manager->AddUserMultiWaitHolder(signaled_holder);
/* Get the power state. */
psc::PmState pm_state;
psc::PmFlagSet pm_flags;
R_ABORT_UNLESS(g_pm_module->GetRequest(std::addressof(pm_state), std::addressof(pm_flags)));
/* Handle the power state. */
if (prev_state == psc::PmState_EssentialServicesAwake && pm_state == psc::PmState_MinimumAwake) {
g_is_sleeping = false;
} else if (prev_state == psc::PmState_MinimumAwake && pm_state == psc::PmState_SleepReady) {
g_is_sleeping = true;
} else if (pm_state == psc::PmState_ShutdownReady) {
g_is_sleeping = true;
}
/* Set the previous state. */
prev_state = pm_state;
/* Acknowledge the state transition. */
R_ABORT_UNLESS(g_pm_module->Acknowledge(pm_state, ResultSuccess()));
}
}
}
void StopIpcServer() {
/* Check that we're initialized. */
AMS_ABORT_UNLESS(g_server_manager != nullptr);
/* Stop the server manager. */
g_server_manager->RequestStopProcessing();
}
void FinalizeIpcServer() {
/* Check that we're initialized. */
AMS_ABORT_UNLESS(g_server_manager != nullptr);
/* Destroy the server manager. */
std::destroy_at(g_server_manager);
g_server_manager = nullptr;
}
}
| 6,023
|
C++
|
.cpp
| 115
| 42.93913
| 156
| 0.644656
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,507
|
lm_custom_sink_buffer.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/lm/srv/lm_custom_sink_buffer.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "lm_custom_sink_buffer.hpp"
namespace ams::lm::srv {
bool CustomSinkBuffer::TryPush(const void *data, size_t size) {
/* Check pre-conditions. */
AMS_ASSERT(size <= m_buffer_size);
AMS_ASSERT(data || size == 0);
/* If we have nothing to push, succeed. */
if (size == 0) {
return true;
}
/* Check that we can push the data. */
if (size > m_buffer_size - m_used_buffer_size) {
return false;
}
/* Push the data. */
std::memcpy(m_buffer + m_used_buffer_size, data, size);
m_used_buffer_size += size;
return true;
}
bool CustomSinkBuffer::TryFlush() {
/* Check that we have data to flush. */
if (m_used_buffer_size == 0) {
return false;
}
/* Try to flush the data. */
if (!m_flush_function(m_buffer, m_used_buffer_size)) {
return false;
}
/* Clear our used size. */
m_used_buffer_size = 0;
return true;
}
}
| 1,724
|
C++
|
.cpp
| 49
| 28.77551
| 76
| 0.617788
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,508
|
lm_log_getter_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/lm/srv/lm_log_getter_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 "lm_log_getter_impl.hpp"
namespace ams::lm::srv {
CustomSinkBuffer &LogGetterImpl::GetBuffer() {
AMS_FUNCTION_LOCAL_STATIC_CONSTINIT(u8, s_buffer[32_KB]);
AMS_FUNCTION_LOCAL_STATIC_CONSTINIT(CustomSinkBuffer, s_custom_sink_buffer, s_buffer, sizeof(s_buffer), FlushFunction);
return s_custom_sink_buffer;
}
s64 LogGetterImpl::GetLog(void *buffer, size_t buffer_size, u32 *out_drop_count) {
/* Check pre-condition. */
AMS_ASSERT(buffer != nullptr);
/* Determine how much we can get. */
size_t min_size = s_buffer_size;
if (buffer_size < s_buffer_size) {
min_size = buffer_size;
IncreaseLogPacketDropCount();
}
/* Get the data. */
std::memcpy(buffer, s_message, min_size);
/* Set output drop count. */
*out_drop_count = s_log_packet_drop_count;
s_log_packet_drop_count = 0;
return min_size;
}
}
| 1,633
|
C++
|
.cpp
| 40
| 35.25
| 127
| 0.676136
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,509
|
lm_log_packet_parser.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/lm/srv/lm_log_packet_parser.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 "lm_log_packet_parser.hpp"
namespace ams::lm::srv {
namespace {
const u8 *ParseUleb128(u64 *out, const u8 *cur, const u8 *end) {
u64 value = 0;
size_t shift = 0;
while (cur < end && shift + 7 <= BITSIZEOF(u64)) {
value |= static_cast<u64>(*cur & 0x7F) << shift;
if ((*cur & 0x80) == 0) {
*out = value;
return cur;
}
++cur;
shift += 7;
}
return end;
}
}
bool LogPacketParser::ParsePacket(const void *buffer, size_t buffer_size, ParsePacketCallback callback, void *arg) {
const u8 *cur = static_cast<const u8 *>(buffer);
const u8 *end = cur + buffer_size;
while (cur < end) {
/* Check that we can parse a header. */
size_t remaining_size = end - cur;
if (remaining_size < sizeof(impl::LogPacketHeader)) {
AMS_ASSERT(remaining_size >= sizeof(impl::LogPacketHeader));
return false;
}
/* Get the header. */
impl::LogPacketHeader header;
std::memcpy(std::addressof(header), cur, sizeof(header));
/* Advance past the header. */
cur += sizeof(header);
/* Check that we can parse the payload. */
const auto payload_size = header.GetPayloadSize();
remaining_size = end - cur;
if (remaining_size < payload_size) {
AMS_ASSERT(remaining_size >= payload_size);
return false;
}
/* Invoke the callback. */
if (!callback(header, cur, payload_size, arg)) {
return false;
}
/* Advance. */
cur += payload_size;
}
/* Check that we parsed all the data. */
AMS_ASSERT(cur == end);
return true;
}
bool LogPacketParser::ParseDataChunk(const void *payload, size_t payload_size, ParseDataChunkCallback callback, void *arg) {
const u8 *cur = static_cast<const u8 *>(payload);
const u8 *end = cur + payload_size;
while (cur < end) {
/* Get the key. */
u64 key;
const auto key_last = ParseUleb128(std::addressof(key), cur, end);
if (key_last >= end) {
return false;
}
cur = key_last + 1;
/* Get the size. */
u64 size;
const auto size_last = ParseUleb128(std::addressof(size), cur, end);
if (size_last >= end) {
return false;
}
cur = size_last + 1;
/* If we're in bounds, invoke the callback. */
if (cur + size <= end && !callback(static_cast<impl::LogDataChunkKey>(key), cur, size, arg)) {
return false;
}
cur += size;
}
return true;
}
bool LogPacketParser::FindDataChunk(const void **out, size_t *out_size, impl::LogDataChunkKey key, const void *buffer, size_t buffer_size) {
/* Create context for iteration. */
struct FindDataChunkContext {
const void *chunk;
size_t chunk_size;
bool found;
impl::LogDataChunkKey key;
} context = { nullptr, 0, false, key };
/* Find the chunk. */
LogPacketParser::ParsePacket(buffer, buffer_size, [](const impl::LogPacketHeader &header, const void *payload, size_t payload_size, void *arg) -> bool {
/* If the header isn't a header packet, continue. */
if (!header.IsHead()) {
return true;
}
return LogPacketParser::ParseDataChunk(payload, payload_size, [](impl::LogDataChunkKey cur_key, const void *chunk, size_t chunk_size, void *arg) -> bool {
/* Get the context. */
auto *context = static_cast<FindDataChunkContext *>(arg);
/* Check if we found the desired key. */
if (context->key == cur_key) {
context->chunk = chunk;
context->chunk_size = chunk_size;
context->found = true;
return false;
}
/* Otherwise, continue. */
return true;
}, arg);
}, std::addressof(context));
/* Write the chunk we found. */
if (context.found) {
*out = context.chunk;
*out_size = context.chunk_size;
return true;
} else {
return false;
}
}
size_t LogPacketParser::ParseModuleName(char *dst, size_t dst_size, const void *buffer, size_t buffer_size) {
/* Check pre-conditions. */
AMS_ASSERT(dst != nullptr);
AMS_ASSERT(dst_size > 0);
AMS_ASSERT(buffer != nullptr);
AMS_ASSERT(buffer_size > 0);
/* Find the relevant data chunk. */
const void *chunk;
size_t chunk_size;
const bool found = LogPacketParser::FindDataChunk(std::addressof(chunk), std::addressof(chunk_size), impl::LogDataChunkKey_ModuleName, buffer, buffer_size);
if (!found || chunk_size == 0) {
dst[0] = '\x00';
return 0;
}
/* Copy as much of the module name as we can. */
const size_t copy_size = std::min(chunk_size, dst_size - 1);
std::memcpy(dst, chunk, copy_size);
dst[copy_size] = '\x00';
return chunk_size;
}
void LogPacketParser::ParseTextLogWithContext(const void *buffer, size_t buffer_size, ParseTextLogCallback callback, void *arg) {
/* Declare context for inter-call storage. */
struct PreviousPacketContext {
u64 process_id;
u64 thread_id;
size_t carry_size;
bool ends_with_text_log;
};
AMS_FUNCTION_LOCAL_STATIC_CONSTINIT(PreviousPacketContext, s_previous_packet_context);
/* Get the packet header. */
auto *header = static_cast<const impl::LogPacketHeader *>(buffer);
auto *payload = static_cast<const char *>(buffer) + impl::LogPacketHeaderSize;
auto payload_size = buffer_size - impl::LogPacketHeaderSize;
/* Determine if the packet is a continuation. */
const bool is_continuation = !header->IsHead() && header->GetProcessId() == s_previous_packet_context.process_id && header->GetThreadId() == s_previous_packet_context.thread_id;
/* Require that the packet be a header or a continuation. */
if (!header->IsHead() && !is_continuation) {
return;
}
/* If the packet is a continuation, handle the leftover data. */
if (is_continuation && s_previous_packet_context.carry_size > 0) {
/* Invoke the callback on what we can. */
const size_t sendable = std::min(s_previous_packet_context.carry_size, payload_size);
if (s_previous_packet_context.ends_with_text_log) {
callback(payload, sendable, arg);
}
/* Advance the leftover data. */
s_previous_packet_context.carry_size -= sendable;
payload += sendable;
payload_size -= sendable;
}
/* If we've sent the whole payload, we're done. */
if (payload_size == 0) {
return;
}
/* Parse the payload. */
size_t carry_size = 0;
bool ends_with_text_log = false;
{
const u8 *cur = reinterpret_cast<const u8 *>(payload);
const u8 *end = cur + payload_size;
while (cur < end) {
/* Get the key. */
u64 key;
const auto key_last = ParseUleb128(std::addressof(key), cur, end);
if (key_last >= end) {
break;
}
cur = key_last + 1;
/* Get the size. */
u64 size;
const auto size_last = ParseUleb128(std::addressof(size), cur, end);
if (size_last >= end) {
break;
}
cur = size_last + 1;
/* Process the data. */
const bool is_text_log = static_cast<impl::LogDataChunkKey>(key) == impl::LogDataChunkKey_TextLog;
const size_t remaining = end - cur;
if (size >= remaining) {
carry_size = size - remaining;
ends_with_text_log = is_text_log;
}
if (is_text_log) {
const size_t sendable_size = std::min<size_t>(size, remaining);
callback(reinterpret_cast<const char *>(cur), sendable_size, arg);
}
cur += size;
}
}
/* If the packet isn't a tail packet, update the context. */
if (!header->IsTail()) {
s_previous_packet_context.process_id = header->GetProcessId();
s_previous_packet_context.thread_id = header->GetThreadId();
s_previous_packet_context.carry_size = carry_size;
s_previous_packet_context.ends_with_text_log = ends_with_text_log;
}
}
}
| 10,018
|
C++
|
.cpp
| 229
| 31.912664
| 185
| 0.540854
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,510
|
lm_logger_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/lm/srv/lm_logger_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 "lm_logger_impl.hpp"
#include "lm_event_log_transmitter.hpp"
#include "lm_log_buffer.hpp"
#include "lm_log_packet_parser.hpp"
#include "lm_log_getter_impl.hpp"
#include "../impl/lm_log_packet_header.hpp"
namespace ams::lm::srv {
bool IsFlushAvailable();
bool g_is_logging_to_custom_sink = false;
namespace {
constinit u32 g_log_destination = lm::LogDestination_TargetManager;
bool SetProcessId(const sf::InAutoSelectBuffer &message, u64 process_id) {
/* Check the message. */
AMS_ASSERT(util::IsAligned(reinterpret_cast<uintptr_t>(message.GetPointer()), alignof(impl::LogPacketHeader)));
/* Get a modifiable copy of the header. */
auto *header = const_cast<impl::LogPacketHeader *>(reinterpret_cast<const impl::LogPacketHeader *>(message.GetPointer()));
/* Check that the message size is correct. */
if (impl::LogPacketHeaderSize + header->GetPayloadSize() != message.GetSize()) {
return false;
}
/* Set the header's process id. */
header->SetProcessId(process_id);
return true;
}
void PutLogToTargetManager(const sf::InAutoSelectBuffer &message) {
/* Try to push the message. */
bool success;
if (IsFlushAvailable()) {
success = LogBuffer::GetDefaultInstance().Push(message.GetPointer(), message.GetSize());
} else {
success = LogBuffer::GetDefaultInstance().TryPush(message.GetPointer(), message.GetSize());
}
/* If we fail, increment dropped packet count. */
if (!success) {
EventLogTransmitter::GetDefaultInstance().IncreaseLogPacketDropCount();
}
}
void PutLogToUart(const sf::InAutoSelectBuffer &message) {
#if defined(AMS_BUILD_FOR_DEBUGGING) || defined(AMS_BUILD_FOR_AUDITING)
{
/* Get header. */
auto *data = message.GetPointer();
auto data_size = message.GetSize();
const auto *header = reinterpret_cast<const impl::LogPacketHeader *>(data);
/* Get the module name. */
char module_name[0x10] = {};
LogPacketParser::ParseModuleName(module_name, sizeof(module_name), data, data_size);
/* Create log metadata. */
const diag::LogMetaData log_meta = {
.module_name = module_name,
.severity = static_cast<diag::LogSeverity>(header->GetSeverity()),
.verbosity = header->GetVerbosity(),
};
LogPacketParser::ParseTextLogWithContext(message.GetPointer(), message.GetSize(), [](const char *txt, size_t size, void *arg) {
/* Get metadata. */
const auto &meta = *static_cast<const diag::LogMetaData *>(arg);
/* Put the message to uart. */
diag::impl::PutImpl(meta, txt, size);
}, const_cast<diag::LogMetaData *>(std::addressof(log_meta)));
}
#else
{
AMS_UNUSED(message);
}
#endif
}
void PutLogToCustomSink(const sf::InAutoSelectBuffer &message) {
LogPacketParser::ParseTextLogWithContext(message.GetPointer(), message.GetSize(), [](const char *txt, size_t size, void *) {
/* Try to push the message. */
if (!LogGetterImpl::GetBuffer().TryPush(txt, size)) {
LogGetterImpl::IncreaseLogPacketDropCount();
}
}, nullptr);
}
}
LoggerImpl::LoggerImpl(LogServiceImpl *parent, os::ProcessId process_id) : m_parent(parent), m_process_id(process_id.value) {
/* Log start of session for process. */
EventLogTransmitter::GetDefaultInstance().PushLogSessionBegin(m_process_id);
}
LoggerImpl::~LoggerImpl() {
/* Log end of session for process. */
EventLogTransmitter::GetDefaultInstance().PushLogSessionEnd(m_process_id);
}
Result LoggerImpl::Log(const sf::InAutoSelectBuffer &message) {
/* Try to set the log process id. */
/* NOTE: Nintendo succeeds here, for whatever purpose, so we will as well. */
R_UNLESS(SetProcessId(message, m_process_id), ResultSuccess());
/* If we should, log to target manager. */
if (g_log_destination & lm::LogDestination_TargetManager) {
PutLogToTargetManager(message);
}
/* If we should, log to uart. */
if ((g_log_destination & lm::LogDestination_Uart) || (IsFlushAvailable() && (g_log_destination & lm::LogDestination_UartIfSleep))) {
PutLogToUart(message);
}
/* If we should, log to custom sink. */
if (g_is_logging_to_custom_sink) {
PutLogToCustomSink(message);
}
R_SUCCEED();
}
Result LoggerImpl::SetDestination(u32 destination) {
/* Set the log destination. */
g_log_destination = destination;
R_SUCCEED();
}
}
| 5,861
|
C++
|
.cpp
| 123
| 37.203252
| 143
| 0.605954
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,511
|
lm_flush_thread.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/lm/srv/lm_flush_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 "lm_log_server_proxy.hpp"
#include "lm_sd_card_logger.hpp"
#include "lm_log_buffer.hpp"
#include "lm_event_log_transmitter.hpp"
namespace ams::lm::srv {
bool IsSleeping();
namespace {
alignas(os::ThreadStackAlignment) u8 g_flush_thread_stack[8_KB];
constinit u8 g_fs_heap[32_KB];
constinit lmem::HeapHandle g_fs_heap_handle;
constinit os::ThreadType g_flush_thread = {};
os::Event g_stop_event(os::EventClearMode_ManualClear);
os::Event g_sd_logging_event(os::EventClearMode_ManualClear);
os::Event g_host_connection_event(os::EventClearMode_ManualClear);
constinit std::unique_ptr<fs::IEventNotifier> g_sd_card_detection_event_notifier;
os::SystemEvent g_sd_card_detection_event;
void *AllocateForFs(size_t size) {
return lmem::AllocateFromExpHeap(g_fs_heap_handle, size);
}
void DeallocateForFs(void *ptr, size_t size) {
AMS_UNUSED(size);
return lmem::FreeToExpHeap(g_fs_heap_handle, ptr);
}
void HostConnectionObserver(bool is_connected) {
/* Update the host connection event. */
if (is_connected) {
g_host_connection_event.Signal();
} else {
g_host_connection_event.Clear();
/* Potentially cancel the log buffer push. */
if (!g_sd_logging_event.TryWait()) {
LogBuffer::GetDefaultInstance().CancelPush();
}
}
}
void SdLoggingObserver(bool is_available) {
/* Update the SD card logging event. */
if (is_available) {
g_sd_logging_event.Signal();
} else {
g_sd_logging_event.Clear();
/* Potentially cancel the log buffer push. */
if (!g_host_connection_event.TryWait()) {
LogBuffer::GetDefaultInstance().CancelPush();
}
}
}
bool WaitForFlush() {
while (true) {
/* Wait for something to be signaled. */
os::WaitAny(g_stop_event.GetBase(), g_host_connection_event.GetBase(), g_sd_logging_event.GetBase(), g_sd_card_detection_event.GetBase());
/* If we're stopping, no flush. */
if (g_stop_event.TryWait()) {
return false;
}
/* If host is connected/we're logging to sd, flush. */
if (g_host_connection_event.TryWait() || g_sd_logging_event.TryWait()) {
return true;
}
/* If the sd card is newly inserted, flush. */
if (g_sd_card_detection_event.TryWait()) {
g_sd_card_detection_event.Clear();
if (fs::IsSdCardInserted()) {
return true;
}
}
}
}
void FlushThreadFunction(void *) {
/* Initialize fs. */
fs::InitializeWithMultiSessionForSystem();
fs::SetEnabledAutoAbort(false);
/* Create fs heap. */
g_fs_heap_handle = lmem::CreateExpHeap(g_fs_heap, sizeof(g_fs_heap), lmem::CreateOption_None);
AMS_ABORT_UNLESS(g_fs_heap_handle != nullptr);
/* Set fs allocator functions. */
fs::SetAllocator(AllocateForFs, DeallocateForFs);
/* Create SD card detection event notifier. */
R_ABORT_UNLESS(fs::OpenSdCardDetectionEventNotifier(std::addressof(g_sd_card_detection_event_notifier)));
R_ABORT_UNLESS(g_sd_card_detection_event_notifier->BindEvent(g_sd_card_detection_event.GetBase(), os::EventClearMode_ManualClear));
/* Set connection observers. */
SdCardLogger::GetInstance().SetLoggingObserver(SdLoggingObserver);
LogServerProxy::GetInstance().SetConnectionObserver(HostConnectionObserver);
/* Do flush loop. */
do {
if (LogBuffer::GetDefaultInstance().Flush()) {
EventLogTransmitter::GetDefaultInstance().PushLogPacketDropCountIfExists();
}
} while (WaitForFlush());
/* Clear connection observer. */
LogServerProxy::GetInstance().SetConnectionObserver(nullptr);
/* Finalize the SD card logger. */
SdCardLogger::GetInstance().Finalize();
SdCardLogger::GetInstance().SetLoggingObserver(nullptr);
/* Destroy the fs heap. */
lmem::DestroyExpHeap(g_fs_heap_handle);
}
}
bool IsFlushAvailable() {
/* If we're sleeping, we can't flush. */
if (IsSleeping()) {
return false;
}
/* Try to wait for an event. */
if (os::TryWaitAny(g_stop_event.GetBase(), g_host_connection_event.GetBase(), g_sd_logging_event.GetBase()) < 0) {
return false;
}
/* Return whether we're not stopping. */
return !os::TryWaitEvent(g_stop_event.GetBase());
}
void InitializeFlushThread() {
/* Create the flush thread. */
R_ABORT_UNLESS(os::CreateThread(std::addressof(g_flush_thread), FlushThreadFunction, nullptr, g_flush_thread_stack, sizeof(g_flush_thread_stack), AMS_GET_SYSTEM_THREAD_PRIORITY(lm, Flush)));
os::SetThreadNamePointer(std::addressof(g_flush_thread), AMS_GET_SYSTEM_THREAD_NAME(lm, Flush));
/* Clear the stop event. */
g_stop_event.Clear();
/* Start the flush thread. */
os::StartThread(std::addressof(g_flush_thread));
}
void FinalizeFlushThread() {
/* Signal the flush thread to stop. */
g_stop_event.Signal();
/* Wait for the flush thread to stop. */
os::WaitThread(std::addressof(g_flush_thread));
os::DestroyThread(std::addressof(g_flush_thread));
}
}
| 6,625
|
C++
|
.cpp
| 143
| 35.286713
| 198
| 0.595127
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,512
|
lm_log_server_proxy.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/lm/srv/lm_log_server_proxy.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 "lm_log_server_proxy.hpp"
namespace ams::lm::srv {
namespace {
constexpr inline const char PortName[] = "iywys@$LogManager";
constexpr inline const int HtcsSessionCountMax = 2;
constexpr inline const TimeSpan PollingInterval = TimeSpan::FromSeconds(1);
constinit u8 g_htcs_heap_buffer[2_KB];
constexpr inline const int InvalidHtcsSocket = -1;
constexpr ALWAYS_INLINE bool IsValidHtcsSocket(int socket) {
return socket >= 0;
}
static_assert(!IsValidHtcsSocket(InvalidHtcsSocket));
bool IsHtcEnabled() {
u8 enable_htc = 0;
settings::fwdbg::GetSettingsItemValue(&enable_htc, sizeof(enable_htc), "atmosphere", "enable_htc");
return enable_htc != 0;
}
}
LogServerProxy::LogServerProxy() : m_cv_connected(), m_stop_event(os::EventClearMode_ManualClear), m_connection_mutex(), m_observer_mutex(), m_server_socket(InvalidHtcsSocket), m_client_socket(InvalidHtcsSocket), m_connection_observer(nullptr) {
/* ... */
}
void LogServerProxy::Start() {
/* Create thread. */
R_ABORT_UNLESS(os::CreateThread(std::addressof(m_thread), [](void *_this) { static_cast<LogServerProxy *>(_this)->LoopAuto(); }, this, m_thread_stack, sizeof(m_thread_stack), AMS_GET_SYSTEM_THREAD_PRIORITY(lm, HtcsConnection)));
/* Set thread name pointer. */
os::SetThreadNamePointer(std::addressof(m_thread), AMS_GET_SYSTEM_THREAD_NAME(lm, HtcsConnection));
/* Clear stop event. */
m_stop_event.Clear();
/* Start thread. */
os::StartThread(std::addressof(m_thread));
}
void LogServerProxy::Stop() {
/* Signal to connection thread to stop. */
m_stop_event.Signal();
/* Close client socket. */
if (const int client_socket = m_client_socket; client_socket >= 0) {
htcs::Close(client_socket);
}
/* Close server socket. */
if (const int server_socket = m_server_socket; server_socket >= 0) {
htcs::Close(server_socket);
}
/* Wait for the connection thread to exit. */
os::WaitThread(std::addressof(m_thread));
os::DestroyThread(std::addressof(m_thread));
}
bool LogServerProxy::IsConnected() {
/* Return whether there's a valid client socket. */
return IsValidHtcsSocket(m_client_socket);
}
void LogServerProxy::SetConnectionObserver(ConnectionObserver observer) {
/* Acquire exclusive access to observer data. */
std::scoped_lock lk(m_observer_mutex);
/* Set the observer. */
m_connection_observer = observer;
}
bool LogServerProxy::Send(const u8 *data, size_t size) {
/* Send as much data as we can, until it's all send. */
size_t offset = 0;
while (this->IsConnected() && offset < size) {
/* Try to send the remaining data. */
if (const auto result = htcs::Send(m_client_socket, data + offset, size - offset, 0); result >= 0) {
/* Advance. */
offset += static_cast<size_t>(result);
} else {
/* We failed to send data, shutdown the socket. */
htcs::Shutdown(m_client_socket, htcs::HTCS_SHUT_RDWR);
/* Wait a second, before returning to the caller. */
os::SleepThread(TimeSpan::FromSeconds(1));
return false;
}
}
/* Return whether we sent all the data. */
AMS_ASSERT(offset <= size);
return offset == size;
}
void LogServerProxy::LoopAuto() {
/* If we're not using htcs, there's nothing to do. */
if (!IsHtcEnabled()) {
return;
}
/* Check that we have enough working memory. */
const auto working_memory_size = htcs::GetWorkingMemorySize(HtcsSessionCountMax);
AMS_ABORT_UNLESS(working_memory_size <= sizeof(g_htcs_heap_buffer));
/* Initialize htcs for the duration that we loop. */
htcs::InitializeForDisableDisconnectionEmulation(g_htcs_heap_buffer, working_memory_size);
ON_SCOPE_EXIT { htcs::Finalize(); };
/* Setup socket address. */
htcs::SockAddrHtcs server_address;
server_address.family = htcs::HTCS_AF_HTCS;
server_address.peer_name = htcs::GetPeerNameAny();
std::strcpy(server_address.port_name.name, PortName);
/* Manage htcs connections until a stop is requested. */
do {
/* Create a server socket. */
const auto server_socket = htcs::Socket();
if (!IsValidHtcsSocket(server_socket)) {
continue;
}
m_server_socket = server_socket;
/* Ensure we cleanup the server socket when done. */
ON_SCOPE_EXIT {
htcs::Close(server_socket);
m_server_socket = InvalidHtcsSocket;
};
/* Bind to the server socket. */
if (htcs::Bind(server_socket, std::addressof(server_address)) != 0) {
continue;
}
/* Listen on the server socket. */
if (htcs::Listen(server_socket, 0) != 0) {
continue;
}
/* Loop on clients, until we're asked to stop. */
while (!m_stop_event.TryWait()) {
/* Accept a client socket. */
const auto client_socket = htcs::Accept(server_socket, nullptr);
if (!IsValidHtcsSocket(client_socket)) {
break;
}
m_client_socket = client_socket;
/* Note that we're connected. */
this->InvokeConnectionObserver(true);
this->SignalConnection();
/* Ensure we cleanup the client socket when done. */
ON_SCOPE_EXIT {
htcs::Close(client_socket);
m_client_socket = InvalidHtcsSocket;
this->InvokeConnectionObserver(false);
};
/* Receive data (and do nothing with it), so long as we're connected. */
u8 v;
while (htcs::Recv(client_socket, std::addressof(v), sizeof(v), 0) == sizeof(v)) { /* ... */ }
}
} while (!m_stop_event.TimedWait(PollingInterval));
}
void LogServerProxy::SignalConnection() {
/* Acquire exclusive access to observer data. */
std::scoped_lock lk(m_connection_mutex);
/* Broadcast to our connected cv. */
m_cv_connected.Broadcast();
}
void LogServerProxy::InvokeConnectionObserver(bool connected) {
/* Acquire exclusive access to observer data. */
std::scoped_lock lk(m_observer_mutex);
/* If we have an observer, observe the connection state. */
if (m_connection_observer) {
m_connection_observer(connected);
}
}
void StartLogServerProxy() {
LogServerProxy::GetInstance().Start();
}
void StopLogServerProxy() {
LogServerProxy::GetInstance().Stop();
}
}
| 7,859
|
C++
|
.cpp
| 173
| 35.369942
| 249
| 0.597697
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,513
|
lm_log_service_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/lm/srv/lm_log_service_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 "lm_log_service_impl.hpp"
#include "lm_logger_impl.hpp"
namespace ams::lm::srv {
namespace {
struct LoggerImplAllocatorTag;
using LoggerAllocator = ams::sf::ExpHeapStaticAllocator<3_KB, LoggerImplAllocatorTag>;
using LoggerObjectFactory = ams::sf::ObjectFactory<typename LoggerAllocator::Policy>;
class StaticAllocatorInitializer {
public:
StaticAllocatorInitializer() {
LoggerAllocator::Initialize(lmem::CreateOption_None);
}
} g_static_allocator_initializer;
}
Result LogServiceImpl::OpenLogger(sf::Out<sf::SharedPointer<::ams::lm::ILogger>> out, const sf::ClientProcessId &client_process_id) {
/* Open logger. */
out.SetValue(LoggerObjectFactory::CreateSharedEmplaced<::ams::lm::ILogger, LoggerImpl>(this, client_process_id.GetValue()));
R_SUCCEED();
}
}
| 1,586
|
C++
|
.cpp
| 36
| 38.472222
| 137
| 0.706416
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,514
|
lm_log_getter.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/lm/srv/lm_log_getter.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 "lm_log_getter.hpp"
#include "lm_log_getter_impl.hpp"
namespace ams::lm::srv {
extern bool g_is_logging_to_custom_sink;
Result LogGetter::StartLogging() {
g_is_logging_to_custom_sink = true;
R_SUCCEED();
}
Result LogGetter::StopLogging() {
g_is_logging_to_custom_sink = false;
R_SUCCEED();
}
Result LogGetter::GetLog(const sf::OutAutoSelectBuffer &message, sf::Out<s64> out_size, sf::Out<u32> out_drop_count) {
/* Try to flush logs. */
if (LogGetterImpl::GetBuffer().TryFlush()) {
*out_size = LogGetterImpl::GetLog(message.GetPointer(), message.GetSize(), out_drop_count.GetPointer());
} else {
/* Otherwise, we got no data. */
*out_size = 0;
}
R_SUCCEED();
}
}
| 1,477
|
C++
|
.cpp
| 39
| 32.846154
| 122
| 0.672257
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,515
|
lm_sd_card_logger.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/lm/srv/lm_sd_card_logger.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 "lm_sd_card_logger.hpp"
#include "lm_time_util.hpp"
namespace ams::lm::srv {
namespace {
constexpr const char SdCardMountName[] = "sdcard";
constexpr const char LogFileExtension[] = "nxbinlog";
constexpr const char SettingName[] = "lm";
constexpr const char SettingKeyLoggingEnabled[] = "enable_sd_card_logging";
constexpr const char SettingKeyOutputDirectory[] = "sd_card_log_output_directory";
constexpr inline size_t LogFileHeaderSize = 8;
constexpr inline u32 LogFileHeaderMagic = util::ReverseFourCC<'p','h','p','h'>::Code;
constexpr inline u8 LogFileHeaderVersion = 1;
struct LogFileHeader {
u32 magic;
u8 version;
u8 reserved[3];
};
static_assert(sizeof(LogFileHeader) == LogFileHeaderSize);
constinit os::SdkMutex g_sd_card_logging_enabled_mutex;
constinit bool g_determined_sd_card_logging_enabled = false;
constinit bool g_sd_card_logging_enabled = false;
constinit os::SdkMutex g_sd_card_detection_event_mutex;
constinit bool g_sd_card_inserted_cache = false;
constinit bool g_sd_card_detection_event_initialized = false;
constinit std::unique_ptr<fs::IEventNotifier> g_sd_card_detection_event_notifier;
os::SystemEvent g_sd_card_detection_event;
bool GetSdCardLoggingEnabledImpl() {
bool enabled;
const auto size = settings::fwdbg::GetSettingsItemValue(std::addressof(enabled), sizeof(enabled), SettingName, SettingKeyLoggingEnabled);
if (size != sizeof(enabled)) {
AMS_ASSERT(size == sizeof(enabled));
return false;
}
return enabled;
}
bool GetSdCardLoggingEnabled() {
if (AMS_UNLIKELY(!g_determined_sd_card_logging_enabled)) {
std::scoped_lock lk(g_sd_card_logging_enabled_mutex);
if (AMS_LIKELY(!g_determined_sd_card_logging_enabled)) {
g_sd_card_logging_enabled = GetSdCardLoggingEnabledImpl();
g_determined_sd_card_logging_enabled = true;
}
}
return g_sd_card_logging_enabled;
}
void EnsureSdCardDetectionEventInitialized() {
if (AMS_UNLIKELY(!g_sd_card_detection_event_initialized)) {
std::scoped_lock lk(g_sd_card_detection_event_mutex);
if (AMS_LIKELY(!g_sd_card_detection_event_initialized)) {
/* Create SD card detection event notifier. */
R_ABORT_UNLESS(fs::OpenSdCardDetectionEventNotifier(std::addressof(g_sd_card_detection_event_notifier)));
R_ABORT_UNLESS(g_sd_card_detection_event_notifier->BindEvent(g_sd_card_detection_event.GetBase(), os::EventClearMode_ManualClear));
/* Get initial inserted value. */
g_sd_card_inserted_cache = fs::IsSdCardInserted();
g_sd_card_detection_event_initialized = true;
}
}
}
void GetSdCardStatus(bool *out_inserted, bool *out_status_changed) {
/* Ensure that we can detect the sd card. */
EnsureSdCardDetectionEventInitialized();
/* Check if there's a detection event. */
const bool status_changed = g_sd_card_detection_event.TryWait();
if (status_changed) {
g_sd_card_detection_event.Clear();
/* Update the inserted cache. */
g_sd_card_inserted_cache = fs::IsSdCardInserted();
}
*out_inserted = g_sd_card_inserted_cache;
*out_status_changed = status_changed;
}
bool GetSdCardLogOutputDirectory(char *dst, size_t size) {
/* Get the output directory size. */
const auto value_size = settings::fwdbg::GetSettingsItemValueSize(SettingName, SettingKeyOutputDirectory);
if (value_size > size) {
AMS_ASSERT(value_size <= size);
return false;
}
/* Get the output directory. */
const auto read_size = settings::fwdbg::GetSettingsItemValue(dst, size, SettingName, SettingKeyOutputDirectory);
AMS_ASSERT(read_size == value_size);
return read_size == value_size;
}
bool EnsureLogDirectory(const char *dir) {
/* Generate the log directory path. */
char path[0x80];
const size_t len = util::SNPrintf(path, sizeof(path), "%s:/%s", SdCardMountName, dir);
if (len >= sizeof(path)) {
AMS_ASSERT(len < sizeof(path));
return false;
}
/* Ensure the directory. */
/* NOTE: Nintendo does not perform recusrive directory ensure, only a single CreateDirectory level. */
return R_SUCCEEDED(fs::EnsureDirectory(path));
}
bool MakeLogFilePathWithoutExtension(char *dst, size_t size, const char *dir) {
/* Get the current time. */
const auto cur_time = time::ToCalendarTimeInUtc(lm::srv::GetCurrentTime());
/* Get the device serial number. */
settings::system::SerialNumber serial_number;
settings::system::GetSerialNumber(std::addressof(serial_number));
/* Print the path. */
const size_t len = util::SNPrintf(dst, size, "%s:/%s/%s_%04d%02d%02d%02d%02d%02d", SdCardMountName, dir, serial_number.str, cur_time.year, cur_time.month, cur_time.day, cur_time.hour, cur_time.minute, cur_time.second);
AMS_ASSERT(len < size);
return len < size;
}
bool GenerateLogFile(char *dst, size_t size, const char *dir) {
/* Generate the log file path. */
char path_without_ext[0x80];
if (!MakeLogFilePathWithoutExtension(path_without_ext, sizeof(path_without_ext), dir)) {
return false;
}
/* Try to find an available log file path. */
constexpr auto MaximumLogIndex = 99;
for (auto i = 1; i <= MaximumLogIndex; ++i) {
/* Print the current log file path. */
const size_t len = (i == 1) ? util::SNPrintf(dst, size, "%s.%s", path_without_ext, LogFileExtension) : util::SNPrintf(dst, size, "%s_%d.%s", path_without_ext, i, LogFileExtension);
if (len >= size) {
AMS_ASSERT(len < size);
return false;
}
/* Try to create the log file. */
const auto result = fs::CreateFile(dst, 0);
if (R_SUCCEEDED(result)) {
return true;
} else if (fs::ResultPathAlreadyExists::Includes(result)) {
/* The log file already exists, so try the next index. */
continue;
} else {
/* We failed to create a log file. */
return false;
}
}
/* We ran out of log file indices. */
return false;
}
Result WriteLogFileHeaderImpl(const char *path) {
/* Open the log file. */
fs::FileHandle file;
R_TRY(fs::OpenFile(std::addressof(file), path, fs::OpenMode_Write | fs::OpenMode_AllowAppend));
ON_SCOPE_EXIT { fs::CloseFile(file); };
/* Write the log file header. */
const LogFileHeader header = {
.magic = LogFileHeaderMagic,
.version = LogFileHeaderVersion
};
R_RETURN(fs::WriteFile(file, 0, std::addressof(header), sizeof(header), fs::WriteOption::Flush));
}
bool WriteLogFileHeader(const char *path) {
return R_SUCCEEDED(WriteLogFileHeaderImpl(path));
}
Result WriteLogFileBodyImpl(const char *path, s64 offset, const u8 *data, size_t size) {
/* Open the log file. */
fs::FileHandle file;
R_TRY(fs::OpenFile(std::addressof(file), path, fs::OpenMode_Write | fs::OpenMode_AllowAppend));
ON_SCOPE_EXIT { fs::CloseFile(file); };
/* Write the data. */
R_RETURN(fs::WriteFile(file, offset, data, size, fs::WriteOption::Flush));
}
bool WriteLogFileBody(const char *path, s64 offset, const u8 *data, size_t size) {
return R_SUCCEEDED(WriteLogFileBodyImpl(path, offset, data, size));
}
}
SdCardLogger::SdCardLogger() : m_logging_observer_mutex(), m_is_enabled(false), m_is_sd_card_mounted(false), m_is_sd_card_status_unknown(false), m_log_file_offset(0), m_logging_observer(nullptr) {
/* ... */
}
bool SdCardLogger::GetEnabled() const {
return m_is_enabled;
}
void SdCardLogger::SetEnabled(bool enabled) {
/* Only update if we need to. */
if (m_is_enabled == enabled) {
return;
}
/* Set enabled. */
m_is_enabled = enabled;
/* Invoke our observer. */
std::scoped_lock lk(m_logging_observer_mutex);
if (m_logging_observer) {
m_logging_observer(enabled);
}
}
void SdCardLogger::SetLoggingObserver(LoggingObserver observer) {
std::scoped_lock lk(m_logging_observer_mutex);
m_logging_observer = observer;
}
bool SdCardLogger::Initialize() {
/* If we're already enabled, nothing to do. */
if (this->GetEnabled()) {
return true;
}
/* Get the sd card status. */
bool inserted = false, status_changed = false;
GetSdCardStatus(std::addressof(inserted), std::addressof(status_changed));
/* Update whether status is known. */
if (status_changed) {
m_is_sd_card_status_unknown = false;
}
/* If the SD isn't inserted, we can't initialize. */
if (!inserted) {
return false;
}
/* If the status is unknown, we can't initialize. */
if (m_is_sd_card_status_unknown) {
return false;
}
/* Mount the SD card. */
if (R_FAILED(fs::MountSdCard(SdCardMountName))) {
return false;
}
/* Note that the SD card is mounted. */
m_is_sd_card_mounted = true;
/* Get the output directory. */
char output_dir[0x80];
if (!GetSdCardLogOutputDirectory(output_dir, sizeof(output_dir))) {
return false;
}
/* Ensure the output directory exists. */
if (!EnsureLogDirectory(output_dir)) {
return false;
}
/* Ensure that a log file exists for us to write to. */
if (!GenerateLogFile(m_log_file_path, sizeof(m_log_file_path), output_dir)) {
return false;
}
/* Write the log file header. */
if (!WriteLogFileHeader(m_log_file_path)) {
return false;
}
/* Set our initial offset. */
m_log_file_offset = LogFileHeaderSize;
return true;
}
void SdCardLogger::Finalize() {
this->SetEnabled(false);
if (m_is_sd_card_mounted) {
fs::Unmount(SdCardMountName);
m_is_sd_card_mounted = false;
}
}
bool SdCardLogger::Write(const u8 *data, size_t size) {
/* Only write if sd card logging is enabled. */
if (!GetSdCardLoggingEnabled()) {
return false;
}
/* Ensure we keep our pre and post-conditions in check. */
bool success = false;
ON_SCOPE_EXIT {
if (!success && m_is_sd_card_mounted) {
fs::Unmount(SdCardMountName);
m_is_sd_card_mounted = false;
m_is_sd_card_status_unknown = true;
}
this->SetEnabled(success);
};
/* Try to initialize. */
if (!this->Initialize()) {
return false;
}
/* Try to write the log file. */
if (!WriteLogFileBody(m_log_file_path, m_log_file_offset, data, size)) {
return false;
}
/* Advance. */
m_log_file_offset += size;
/* We succeeded. */
success = true;
return true;
}
}
| 13,047
|
C++
|
.cpp
| 286
| 34.335664
| 230
| 0.579196
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,516
|
lm_log_buffer.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/lm/srv/lm_log_buffer.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "lm_log_buffer.hpp"
#include "lm_log_server_proxy.hpp"
#include "lm_sd_card_logger.hpp"
#include "lm_time_util.hpp"
#include "lm_log_packet_parser.hpp"
namespace ams::lm::srv {
namespace {
void UpdateUserSystemClock(const u8 *data, size_t size) {
/* Get the current time. */
const time::PosixTime current_time = GetCurrentTime();
/* Get the base time. */
s64 base_time = current_time.value - os::GetSystemTick().ToTimeSpan().GetSeconds();
/* Modify the message timestamp. */
LogPacketParser::ParsePacket(data, size, [](const impl::LogPacketHeader &header, const void *payload, size_t payload_size, void *arg) -> bool {
/* Check that we're a header message. */
if (!header.IsHead()) {
return true;
}
/* Find the timestamp data chunk. */
return LogPacketParser::ParseDataChunk(payload, payload_size, [](impl::LogDataChunkKey key, const void *chunk, size_t chunk_size, void *arg) -> bool {
/* Convert the argument. */
const s64 *p_base_time = static_cast<const s64 *>(arg);
/* Modify user system clock. */
if (key == impl::LogDataChunkKey_UserSystemClock) {
/* Get the time from the chunk. */
s64 time;
AMS_ASSERT(chunk_size == sizeof(time));
std::memcpy(std::addressof(time), chunk, chunk_size);
/* Add the base time. */
time += *p_base_time;
/* Update the time in the chunk. */
std::memcpy(const_cast<void *>(chunk), std::addressof(time), sizeof(time));
}
return true;
}, arg);
}, std::addressof(base_time));
}
bool DefaultFlushFunction(const u8 *data, size_t size) {
/* Declare persistent clock-updated state storage. */
AMS_FUNCTION_LOCAL_STATIC_CONSTINIT(bool, s_is_user_system_clock_updated, false);
/* Update clock. */
if (!s_is_user_system_clock_updated) {
UpdateUserSystemClock(data, size);
s_is_user_system_clock_updated = true;
}
/* Send the message. */
const bool tma_success = LogServerProxy::GetInstance().Send(data, size);
const bool sd_success = SdCardLogger::GetInstance().Write(data, size);
const bool is_success = tma_success || sd_success;
/* If we succeeded, wipe the current time. */
s_is_user_system_clock_updated &= !is_success;
return is_success;
}
}
LogBuffer &LogBuffer::GetDefaultInstance() {
AMS_FUNCTION_LOCAL_STATIC_CONSTINIT(u8, s_default_buffers[128_KB * 2]);
AMS_FUNCTION_LOCAL_STATIC_CONSTINIT(LogBuffer, s_default_log_buffer, s_default_buffers, sizeof(s_default_buffers), DefaultFlushFunction);
return s_default_log_buffer;
}
void LogBuffer::CancelPush() {
/* Acquire exclusive access to the push buffer. */
std::scoped_lock lk(m_push_buffer_mutex);
/* Cancel any pending pushes. */
if (m_push_ready_wait_count > 0) {
m_push_canceled = true;
m_cv_push_ready.Broadcast();
}
}
bool LogBuffer::PushImpl(const void *data, size_t size, bool blocking) {
/* Check pre-conditions. */
AMS_ASSERT(size <= m_buffer_size);
AMS_ASSERT(data != nullptr || size == 0);
/* Check that we have data to push. */
if (size == 0) {
return true;
}
/* Wait to be able to push. */
u8 *dst;
{
/* Acquire exclusive access to the push buffer. */
std::scoped_lock lk(m_push_buffer_mutex);
/* Wait for enough space to be available. */
while (size > m_buffer_size - m_push_buffer->m_stored_size) {
/* Only block if we're allowed to. */
if (!blocking) {
return false;
}
/* Wait for push to be ready. */
{
++m_push_ready_wait_count;
m_cv_push_ready.Wait(m_push_buffer_mutex);
--m_push_ready_wait_count;
}
/* Check if push was canceled. */
if (m_push_canceled) {
if (m_push_ready_wait_count == 0) {
m_push_canceled = false;
}
return false;
}
}
/* Set the destination. */
dst = m_push_buffer->m_head + m_push_buffer->m_stored_size;
/* Advance the push buffer. */
m_push_buffer->m_stored_size += size;
++m_push_buffer->m_reference_count;
}
/* Copy the data to the push buffer. */
std::memcpy(dst, data, size);
/* Close our push buffer reference, and signal that we can flush. */
{
/* Acquire exclusive access to the push buffer. */
std::scoped_lock lk(m_push_buffer_mutex);
/* If there are no pending pushes, signal that we can flush. */
if ((--m_push_buffer->m_reference_count) == 0) {
m_cv_flush_ready.Signal();
}
}
return true;
}
bool LogBuffer::FlushImpl(bool blocking) {
/* Acquire exclusive access to the flush buffer. */
std::scoped_lock lk(m_flush_buffer_mutex);
/* If we don't have data to flush, wait for us to have data. */
if (m_flush_buffer->m_stored_size == 0) {
/* Acquire exclusive access to the push buffer. */
std::scoped_lock lk(m_push_buffer_mutex);
/* Wait for there to be pushed data. */
while (m_push_buffer->m_stored_size == 0 || m_push_buffer->m_reference_count != 0) {
/* Only block if we're allowed to. */
if (!blocking) {
return false;
}
/* Wait for us to be ready to flush. */
m_cv_flush_ready.Wait(m_push_buffer_mutex);
}
/* Swap the push buffer and the flush buffer pointers. */
std::swap(m_push_buffer, m_flush_buffer);
/* Signal that we can push. */
m_cv_push_ready.Broadcast();
}
/* Flush any data. */
if (!m_flush_function(m_flush_buffer->m_head, m_flush_buffer->m_stored_size)) {
return false;
}
/* Reset the flush buffer. */
m_flush_buffer->m_stored_size = 0;
return true;
}
}
| 7,527
|
C++
|
.cpp
| 166
| 33.156627
| 166
| 0.544958
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,517
|
lm_time_util.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/lm/srv/lm_time_util.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "lm_time_util.hpp"
namespace ams::lm::srv {
namespace {
constinit std::atomic_bool g_is_time_invalid = false;
constinit time::PosixTime InvalidPosixTime = { .value = 0 };
constexpr bool IsValidPosixTime(time::PosixTime time) {
return time.value > 0;
}
void EnsureTimeInitialized() {
static constinit os::SdkMutex g_time_initialized_mutex;
static constinit bool g_time_initialized = false;
if (AMS_UNLIKELY(!g_time_initialized)) {
std::scoped_lock lk(g_time_initialized_mutex);
if (AMS_LIKELY(!g_time_initialized)) {
R_ABORT_UNLESS(time::Initialize());
g_time_initialized = true;
}
}
}
}
time::PosixTime GetCurrentTime() {
/* Ensure that we can use time services. */
EnsureTimeInitialized();
/* Repeatedly try to get a valid time. */
for (auto wait_seconds = 1; wait_seconds <= 8; wait_seconds *= 2) {
/* Get the standard user system clock time. */
time::PosixTime current_time{};
if (R_FAILED(time::StandardUserSystemClock::GetCurrentTime(std::addressof(current_time)))) {
return InvalidPosixTime;
}
/* If the time is valid, return it. */
if (IsValidPosixTime(current_time)) {
return current_time;
}
/* Check if we've failed to get a time in the past. */
if (g_is_time_invalid) {
return InvalidPosixTime;
}
/* Wait a bit before trying again. */
os::SleepThread(TimeSpan::FromSeconds(wait_seconds));
}
/* We failed to get a valid time. */
g_is_time_invalid = true;
return InvalidPosixTime;
}
}
| 2,549
|
C++
|
.cpp
| 62
| 32.080645
| 104
| 0.610684
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,518
|
lmem_common.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/lmem/lmem_common.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "impl/lmem_impl_common_heap.hpp"
namespace ams::lmem {
u32 GetDebugFillValue(FillType fill_type) {
return impl::GetDebugFillValue(fill_type);
}
void SetDebugFillValue(FillType fill_type, u32 value) {
impl::SetDebugFillValue(fill_type, value);
}
size_t GetTotalSize(HeapHandle handle) {
impl::ScopedHeapLock lk(handle);
return impl::GetHeapTotalSize(handle);
}
void *GetStartAddress(HeapHandle handle) {
impl::ScopedHeapLock lk(handle);
return impl::GetHeapStartAddress(handle);
}
bool ContainsAddress(HeapHandle handle, const void *address) {
impl::ScopedHeapLock lk(handle);
return impl::ContainsAddress(handle, address);
}
}
| 1,410
|
C++
|
.cpp
| 37
| 33.72973
| 76
| 0.725476
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,519
|
lmem_unit_heap.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/lmem/lmem_unit_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 <stratosphere.hpp>
#include "impl/lmem_impl_unit_heap.hpp"
namespace ams::lmem {
HeapHandle CreateUnitHeap(void *address, size_t size, size_t unit_size, u32 option) {
HeapHandle handle = impl::CreateUnitHeap(address, size, unit_size, DefaultAlignment, static_cast<u16>(option), InfoPlacement_Head, nullptr);
if (option & CreateOption_ThreadSafe) {
os::InitializeSdkMutex(std::addressof(handle->mutex));
}
return handle;
}
HeapHandle CreateUnitHeap(void *address, size_t size, size_t unit_size, u32 option, s32 alignment, InfoPlacement info_placement) {
HeapHandle handle = impl::CreateUnitHeap(address, size, unit_size, alignment, static_cast<u16>(option), info_placement, nullptr);
if (option & CreateOption_ThreadSafe) {
os::InitializeSdkMutex(std::addressof(handle->mutex));
}
return handle;
}
HeapHandle CreateUnitHeap(void *address, size_t size, size_t unit_size, u32 option, s32 alignment, HeapCommonHead *heap_head) {
HeapHandle handle = impl::CreateUnitHeap(address, size, unit_size, alignment, static_cast<u16>(option), InfoPlacement_Head, heap_head);
if (option & CreateOption_ThreadSafe) {
os::InitializeSdkMutex(std::addressof(handle->mutex));
}
return handle;
}
void DestroyUnitHeap(HeapHandle handle) {
impl::DestroyUnitHeap(handle);
}
void InvalidateUnitHeap(HeapHandle handle) {
impl::ScopedHeapLock lk(handle);
impl::InvalidateUnitHeap(handle);
}
void ExtendUnitHeap(HeapHandle handle, size_t size) {
impl::ScopedHeapLock lk(handle);
impl::ExtendUnitHeap(handle, size);
}
void *AllocateFromUnitHeap(HeapHandle handle) {
impl::ScopedHeapLock lk(handle);
return impl::AllocateFromUnitHeap(handle);
}
void FreeToUnitHeap(HeapHandle handle, void *block) {
impl::ScopedHeapLock lk(handle);
impl::FreeToUnitHeap(handle, block);
}
size_t GetUnitHeapUnitSize(HeapHandle handle) {
/* Nintendo doesn't acquire a lock here. */
return impl::GetUnitHeapUnitSize(handle);
}
s32 GetUnitHeapAlignment(HeapHandle handle) {
/* Nintendo doesn't acquire a lock here. */
return impl::GetUnitHeapAlignment(handle);
}
size_t GetUnitHeapFreeCount(HeapHandle handle) {
impl::ScopedHeapLock lk(handle);
return impl::GetUnitHeapFreeCount(handle);
}
size_t GetUnitHeapUsedCount(HeapHandle handle) {
impl::ScopedHeapLock lk(handle);
return impl::GetUnitHeapUsedCount(handle);
}
size_t GetUnitHeapRequiredSize(size_t unit_size, size_t unit_count, s32 alignment, bool internal_metadata) {
return impl::GetUnitHeapRequiredSize(unit_size, unit_count, alignment, internal_metadata);
}
}
| 3,512
|
C++
|
.cpp
| 78
| 38.782051
| 148
| 0.7043
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,520
|
lmem_exp_heap.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/lmem/lmem_exp_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 <stratosphere.hpp>
#include "impl/lmem_impl_exp_heap.hpp"
namespace ams::lmem {
HeapHandle CreateExpHeap(void *address, size_t size, u32 option) {
HeapHandle handle = impl::CreateExpHeap(address, size, option);
if (option & CreateOption_ThreadSafe) {
os::InitializeSdkMutex(std::addressof(handle->mutex));
}
return handle;
}
void DestroyExpHeap(HeapHandle handle) {
impl::DestroyExpHeap(handle);
}
MemoryRange AdjustExpHeap(HeapHandle handle) {
impl::ScopedHeapLock lk(handle);
return impl::AdjustExpHeap(handle);
}
void *AllocateFromExpHeap(HeapHandle handle, size_t size) {
impl::ScopedHeapLock lk(handle);
return impl::AllocateFromExpHeap(handle, size, DefaultAlignment);
}
void *AllocateFromExpHeap(HeapHandle handle, size_t size, s32 alignment) {
impl::ScopedHeapLock lk(handle);
return impl::AllocateFromExpHeap(handle, size, alignment);
}
void FreeToExpHeap(HeapHandle handle, void *block) {
impl::ScopedHeapLock lk(handle);
impl::FreeToExpHeap(handle, block);
}
size_t ResizeExpHeapMemoryBlock(HeapHandle handle, void *block, size_t size) {
impl::ScopedHeapLock lk(handle);
return impl::ResizeExpHeapMemoryBlock(handle, block, size);
}
size_t GetExpHeapTotalFreeSize(HeapHandle handle) {
impl::ScopedHeapLock lk(handle);
return impl::GetExpHeapTotalFreeSize(handle);
}
size_t GetExpHeapAllocatableSize(HeapHandle handle, s32 alignment) {
impl::ScopedHeapLock lk(handle);
return impl::GetExpHeapAllocatableSize(handle, alignment);
}
AllocationMode GetExpHeapAllocationMode(HeapHandle handle) {
impl::ScopedHeapLock lk(handle);
return impl::GetExpHeapAllocationMode(handle);
}
AllocationMode SetExpHeapAllocationMode(HeapHandle handle, AllocationMode new_mode) {
impl::ScopedHeapLock lk(handle);
return impl::SetExpHeapAllocationMode(handle, new_mode);
}
bool GetExpHeapUseMarginsOfAlignment(HeapHandle handle) {
impl::ScopedHeapLock lk(handle);
return impl::GetExpHeapUseMarginsOfAlignment(handle);
}
bool SetExpHeapUseMarginsOfAlignment(HeapHandle handle, bool use_margins) {
impl::ScopedHeapLock lk(handle);
return impl::SetExpHeapUseMarginsOfAlignment(handle, use_margins);
}
u16 GetExpHeapGroupId(HeapHandle handle) {
impl::ScopedHeapLock lk(handle);
return impl::GetExpHeapGroupId(handle);
}
u16 SetExpHeapGroupId(HeapHandle handle, u16 group_id) {
impl::ScopedHeapLock lk(handle);
return impl::SetExpHeapGroupId(handle, group_id);
}
size_t GetExpHeapMemoryBlockSize(const void *memory_block) {
return impl::GetExpHeapMemoryBlockSize(memory_block);
}
u16 GetExpHeapMemoryBlockGroupId(const void *memory_block) {
return impl::GetExpHeapMemoryBlockGroupId(memory_block);
}
AllocationDirection GetExpHeapMemoryBlockAllocationDirection(const void *memory_block) {
return impl::GetExpHeapMemoryBlockAllocationDirection(memory_block);
}
void VisitExpHeapAllocatedBlocks(HeapHandle handle, HeapVisitor visitor, uintptr_t user_data) {
impl::ScopedHeapLock lk(handle);
impl::VisitExpHeapAllocatedBlocks(handle, visitor, user_data);
}
}
| 4,056
|
C++
|
.cpp
| 94
| 36.968085
| 99
| 0.725197
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,521
|
lmem_impl_unit_heap.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/lmem/impl/lmem_impl_unit_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 <stratosphere.hpp>
#include "lmem_impl_unit_heap.hpp"
namespace ams::lmem::impl {
namespace {
constexpr size_t MinimumAlignment = 4;
constexpr inline bool IsValidHeapHandle(HeapHandle handle) {
return handle->magic == UnitHeapMagic;
}
constexpr inline UnitHeapHead *GetUnitHeapHead(HeapHead *heap_head) {
return std::addressof(heap_head->impl_head.unit_heap_head);
}
[[maybe_unused]] constexpr inline const UnitHeapHead *GetUnitHeapHead(const HeapHead *heap_head) {
return std::addressof(heap_head->impl_head.unit_heap_head);
}
inline UnitHead *PopUnit(UnitHeapList *list) {
if (UnitHead *block = list->head; block != nullptr) {
list->head = block->next;
return block;
} else {
return nullptr;
}
}
inline void PushUnit(UnitHeapList *list, UnitHead *block) {
block->next = list->head;
list->head = block;
}
}
HeapHandle CreateUnitHeap(void *address, size_t size, size_t unit_size, s32 alignment, u16 option, InfoPlacement info_placement, HeapCommonHead *heap_head) {
AMS_ASSERT(address != nullptr);
/* Correct alignment, validate. */
if (alignment == 1 || alignment == 2) {
alignment = 4;
}
AMS_ASSERT(util::IsAligned(alignment, MinimumAlignment));
AMS_ASSERT(static_cast<s32>(MinimumAlignment) <= alignment);
AMS_ASSERT(unit_size >= sizeof(uintptr_t));
/* Setup heap metadata. */
UnitHeapHead *unit_heap = nullptr;
void *heap_start = nullptr;
void *heap_end = nullptr;
if (heap_head == nullptr) {
/* Internal heap metadata. */
if (info_placement == InfoPlacement_Head) {
heap_head = reinterpret_cast<HeapHead *>(util::AlignUp(address, MinimumAlignment));
unit_heap = GetUnitHeapHead(heap_head);
heap_end = util::AlignDown(reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(address) + size), MinimumAlignment);
heap_start = util::AlignUp(reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(heap_head) + sizeof(HeapHead)), alignment);
} else if (info_placement == InfoPlacement_Tail) {
heap_end = util::AlignDown(reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(address) + size - sizeof(HeapHead)), MinimumAlignment);
heap_head = reinterpret_cast<HeapHead *>(heap_end);
unit_heap = GetUnitHeapHead(heap_head);
heap_start = util::AlignUp(address, alignment);
} else {
AMS_ASSERT(false);
}
} else {
/* External heap metadata. */
unit_heap = GetUnitHeapHead(heap_head);
heap_end = util::AlignDown(reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(address) + size), MinimumAlignment);
heap_start = util::AlignUp(address, alignment);
}
/* Correct unit size. */
unit_size = util::AlignUp(unit_size, alignment);
/* Don't allow a heap with start after end. */
if (heap_start > heap_end) {
return nullptr;
}
/* Don't allow a heap with no units. */
size_t max_units = GetPointerDifference(heap_start, heap_end) / unit_size;
if (max_units == 0) {
return nullptr;
}
/* Set real heap end. */
heap_end = reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(heap_start) + max_units * unit_size);
/* Initialize the parent heap. */
InitializeHeapHead(heap_head, UnitHeapMagic, heap_start, heap_end, option);
/* Initialize the actual unit heap. */
{
unit_heap->free_list.head = reinterpret_cast<UnitHead *>(heap_start);
unit_heap->unit_size = unit_size;
unit_heap->alignment = alignment;
unit_heap->num_units = 0;
/* Create the new units. */
UnitHead *cur_tail = unit_heap->free_list.head;
for (size_t i = 0; i < max_units - 1; i++) {
cur_tail->next = reinterpret_cast<UnitHead *>(reinterpret_cast<uintptr_t>(cur_tail) + unit_size);
cur_tail = cur_tail->next;
}
cur_tail->next = nullptr;
}
/* Return the heap header as handle. */
return heap_head;
}
void DestroyUnitHeap(HeapHandle handle) {
AMS_ASSERT(IsValidHeapHandle(handle));
/* Validate that the heap has no living units. */
UnitHeapHead *unit_heap = GetUnitHeapHead(handle);
if (unit_heap->free_list.head != nullptr) {
AMS_ASSERT(unit_heap->num_units == 0);
unit_heap->free_list.head = nullptr;
}
FinalizeHeap(handle);
}
void InvalidateUnitHeap(HeapHandle handle) {
AMS_ASSERT(IsValidHeapHandle(handle));
GetUnitHeapHead(handle)->free_list.head = nullptr;
}
void ExtendUnitHeap(HeapHandle handle, size_t size) {
AMS_ASSERT(IsValidHeapHandle(handle));
/* Find the current tail unit, and insert <end of heap> as next. */
UnitHeapHead *unit_heap = GetUnitHeapHead(handle);
UnitHead *cur_tail;
if (unit_heap->free_list.head != nullptr) {
cur_tail = unit_heap->free_list.head;
while (cur_tail->next != nullptr) {
cur_tail = cur_tail->next;
}
cur_tail->next = reinterpret_cast<UnitHead *>(handle->heap_end);
cur_tail = cur_tail->next;
cur_tail->next = nullptr;
} else {
/* All units are allocated, so set the free list to be at the end of the heap area. */
unit_heap->free_list.head = reinterpret_cast<UnitHead *>(handle->heap_end);
cur_tail = unit_heap->free_list.head;
cur_tail->next = nullptr;
}
/* Calculate new unit extents. */
void *new_units_start = handle->heap_end;
void *new_units_end = reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(new_units_start) + size);
size_t num_new_units = GetPointerDifference(new_units_start, new_units_end) / unit_heap->unit_size;
AMS_ASSERT(num_new_units > 0);
/* Create the new units. */
for (size_t i = 0; i < num_new_units - 1; i++) {
cur_tail->next = reinterpret_cast<UnitHead *>(reinterpret_cast<uintptr_t>(cur_tail) + unit_heap->unit_size);
cur_tail = cur_tail->next;
}
cur_tail->next = nullptr;
/* Note that the heap is bigger. */
handle->heap_end = new_units_end;
}
void *AllocateFromUnitHeap(HeapHandle handle) {
AMS_ASSERT(IsValidHeapHandle(handle));
/* Allocate a unit. */
UnitHeapHead *unit_heap = GetUnitHeapHead(handle);
UnitHead *unit = PopUnit(std::addressof(unit_heap->free_list));
if (unit != nullptr) {
/* Fill memory with pattern for debug, if needed. */
FillAllocatedMemory(handle, unit, unit_heap->unit_size);
/* Note that we allocated a unit. */
unit_heap->num_units++;
}
return unit;
}
void FreeToUnitHeap(HeapHandle handle, void *block) {
AMS_ASSERT(IsValidHeapHandle(handle));
/* Allow Free(nullptr) to succeed. */
if (block == nullptr) {
return;
}
/* Fill memory with pattern for debug, if needed. */
UnitHeapHead *unit_heap = GetUnitHeapHead(handle);
FillFreedMemory(handle, block, unit_heap->unit_size);
/* Push the unit onto the free list. */
PushUnit(std::addressof(unit_heap->free_list), static_cast<UnitHead *>(block));
/* Note that we freed a unit. */
unit_heap->num_units--;
}
size_t GetUnitHeapUnitSize(HeapHandle handle) {
AMS_ASSERT(IsValidHeapHandle(handle));
return GetUnitHeapHead(handle)->unit_size;
}
s32 GetUnitHeapAlignment(HeapHandle handle) {
AMS_ASSERT(IsValidHeapHandle(handle));
return GetUnitHeapHead(handle)->alignment;
}
size_t GetUnitHeapFreeCount(HeapHandle handle) {
AMS_ASSERT(IsValidHeapHandle(handle));
size_t count = 0;
for (UnitHead *cur = GetUnitHeapHead(handle)->free_list.head; cur != nullptr; cur = cur->next) {
count++;
}
return count;
}
size_t GetUnitHeapUsedCount(HeapHandle handle) {
AMS_ASSERT(IsValidHeapHandle(handle));
return GetUnitHeapHead(handle)->num_units;
}
size_t GetUnitHeapRequiredSize(size_t unit_size, size_t unit_count, s32 alignment, bool internal_metadata) {
/* Nintendo does not round up alignment here, even though they do so in CreateUnitHeap. */
/* We will round up alignment to return more accurate results. */
if (alignment == 1 || alignment == 2) {
alignment = 4;
}
AMS_ASSERT(util::IsAligned(alignment, MinimumAlignment));
AMS_ASSERT(static_cast<s32>(MinimumAlignment) <= alignment);
AMS_ASSERT(unit_size >= sizeof(uintptr_t));
return (alignment - 1) + (unit_count * util::AlignUp(unit_size, alignment)) + (internal_metadata ? sizeof(HeapHead) : 0);
}
}
| 10,107
|
C++
|
.cpp
| 214
| 37.598131
| 161
| 0.605445
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,522
|
lmem_impl_common_heap.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/lmem/impl/lmem_impl_common_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 <stratosphere.hpp>
#include "lmem_impl_common_heap.hpp"
namespace ams::lmem::impl {
namespace {
u32 g_fill_values[FillType_Count] = {
0xC3C3C3C3, /* FillType_Unallocated */
0xF3F3F3F3, /* FillType_Allocated */
0xD3D3D3D3, /* FillType_Freed */
};
}
void InitializeHeapHead(HeapHead *out, u32 magic, void *start, void *end, u32 option) {
/* Call member constructors. */
std::construct_at(std::addressof(out->list_node));
std::construct_at(std::addressof(out->child_list));
/* Set fields. */
out->magic = magic;
out->heap_start = start;
out->heap_end = end;
out->option = static_cast<u8>(option);
/* Fill memory with pattern if needed. */
FillUnallocatedMemory(out, start, GetPointerDifference(start, end));
}
void FinalizeHeap(HeapHead *heap) {
/* Nothing actually needs to be done here. */
AMS_UNUSED(heap);
}
bool ContainsAddress(HeapHandle handle, const void *address) {
const uintptr_t uptr_handle = reinterpret_cast<uintptr_t>(handle);
const uintptr_t uptr_start = reinterpret_cast<uintptr_t>(handle->heap_start);
const uintptr_t uptr_end = reinterpret_cast<uintptr_t>(handle->heap_end);
const uintptr_t uptr_addr = reinterpret_cast<uintptr_t>(address);
if (uptr_start - sizeof(HeapHead) == uptr_handle) {
/* The heap head is at the start of the managed memory. */
return uptr_handle <= uptr_addr && uptr_addr < uptr_end;
} else if (uptr_handle == uptr_end) {
/* The heap head is at the end of the managed memory. */
return uptr_start <= uptr_addr && uptr_addr < uptr_end + sizeof(HeapHead);
} else {
/* Heap head is somewhere unrelated to managed memory. */
return uptr_start <= uptr_addr && uptr_addr < uptr_end;
}
}
size_t GetHeapTotalSize(HeapHandle handle) {
const uintptr_t uptr_start = reinterpret_cast<uintptr_t>(handle->heap_start);
const uintptr_t uptr_end = reinterpret_cast<uintptr_t>(handle->heap_end);
if (ContainsAddress(handle, reinterpret_cast<const void *>(handle))) {
/* The heap metadata is contained within the heap, either before or after. */
return static_cast<size_t>(uptr_end - uptr_start + sizeof(HeapHead));
} else {
/* The heap metadata is not contained within the heap. */
return static_cast<size_t>(uptr_end - uptr_start);
}
}
u32 GetDebugFillValue(FillType type) {
return g_fill_values[type];
}
u32 SetDebugFillValue(FillType type, u32 value) {
const u32 old_value = g_fill_values[type];
g_fill_values[type] = value;
return old_value;
}
}
| 3,504
|
C++
|
.cpp
| 77
| 38.155844
| 91
| 0.643318
|
Atmosphere-NX/Atmosphere
| 14,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.