diff --git a/Source/rewrite-hoc-clk/common/include/battery.h b/Source/rewrite-hoc-clk/common/include/battery.h index dff0b08b..82754bc2 100644 --- a/Source/rewrite-hoc-clk/common/include/battery.h +++ b/Source/rewrite-hoc-clk/common/include/battery.h @@ -12,9 +12,9 @@ * * You should have received a copy of the GNU General Public License * along with this program. If not, see . - * + * */ - + #pragma once #include #include @@ -71,25 +71,6 @@ typedef struct { #define IS_BATTERY_CHARGING_ENABLED(info) (((info)->unk_x14 >> 8) & 1) -Result batteryInfoInitialize(void); - -void batteryInfoExit(void); - -Result batteryInfoGetChargeInfo(BatteryChargeInfo *out); - -Result batteryInfoGetChargePercentage(u32 *out); - -Result batteryInfoIsEnoughPowerSupplied(bool *out); - -Result batteryInfoEnableCharging(void); -Result batteryInfoDisableCharging(void); -Result batteryInfoEnableFastCharging(void); -Result batteryInfoDisableFastCharging(void); - -const char* batteryInfoGetChargerTypeString(BatteryChargerType type); -const char* batteryInfoGetPowerRoleString(BatteryPowerRole role); -const char* batteryInfoGetPDStateString(BatteryPDControllerState state); - static inline int batteryInfoGetTemperatureMiliCelsius(BatteryChargeInfo *info) { return info->BatteryTemperature; } @@ -106,147 +87,15 @@ static inline bool batteryInfoIsCharging(BatteryChargeInfo *info) { return IS_BATTERY_CHARGING_ENABLED(info); } -static const char* s_chargerTypeStrings[] = { - "None", - "Power Delivery", - "USB-C @ 1.5A", - "USB-C @ 3.0A", - "USB-DCP", - "USB-CDP", - "USB-SDP", - "Apple @ 0.5A", - "Apple @ 1.0A", - "Apple @ 2.0A", -}; - -static const char* s_powerRoleStrings[] = { - "Unknown", - "Sink", - "Source", -}; - -static const char* s_pdStateStrings[] = { - "Unknown", - "New PDO Received", - "No PD Source", - "RDO Accepted" -}; - -// Internal PSM service handle -static Service g_psmService = {0}; -static bool g_batteryInfoInitialized = false; - -// Internal PSM command implementations -static Result psmGetBatteryChargeInfoFields(BatteryChargeInfo *out) { - if (!g_batteryInfoInitialized) - return MAKERESULT(Module_Libnx, LibnxError_NotInitialized); - - return serviceDispatchOut(&g_psmService, 17, *out); -} - -static Result psmEnableBatteryCharging_internal(void) { - if (!g_batteryInfoInitialized) - return MAKERESULT(Module_Libnx, LibnxError_NotInitialized); - - return serviceDispatch(&g_psmService, 2); -} - -static Result psmDisableBatteryCharging_internal(void) { - if (!g_batteryInfoInitialized) - return MAKERESULT(Module_Libnx, LibnxError_NotInitialized); - - return serviceDispatch(&g_psmService, 3); -} - -static Result psmEnableFastBatteryCharging_internal(void) { - if (!g_batteryInfoInitialized) - return MAKERESULT(Module_Libnx, LibnxError_NotInitialized); - - return serviceDispatch(&g_psmService, 10); -} - -static Result psmDisableFastBatteryCharging_internal(void) { - if (!g_batteryInfoInitialized) - return MAKERESULT(Module_Libnx, LibnxError_NotInitialized); - - return serviceDispatch(&g_psmService, 11); -} - -Result batteryInfoInitialize(void) { - if (g_batteryInfoInitialized) - return 0; - - Result rc = psmInitialize(); - if (R_SUCCEEDED(rc)) { - memcpy(&g_psmService, psmGetServiceSession(), sizeof(Service)); - g_batteryInfoInitialized = true; - } - - return rc; -} - -void batteryInfoExit(void) { - if (g_batteryInfoInitialized) { - psmExit(); - memset(&g_psmService, 0, sizeof(Service)); - g_batteryInfoInitialized = false; - } -} - -Result batteryInfoGetChargeInfo(BatteryChargeInfo *out) { - if (!out) - return MAKERESULT(Module_Libnx, LibnxError_BadInput); - - return psmGetBatteryChargeInfoFields(out); -} - -Result batteryInfoGetChargePercentage(u32 *out) { - if (!g_batteryInfoInitialized) - return MAKERESULT(Module_Libnx, LibnxError_NotInitialized); - - return psmGetBatteryChargePercentage(out); -} - -Result batteryInfoIsEnoughPowerSupplied(bool *out) { - if (!g_batteryInfoInitialized) - return MAKERESULT(Module_Libnx, LibnxError_NotInitialized); - - return psmIsEnoughPowerSupplied(out); -} - -Result batteryInfoEnableCharging(void) { - return psmEnableBatteryCharging_internal(); -} - -Result batteryInfoDisableCharging(void) { - return psmDisableBatteryCharging_internal(); -} - -Result batteryInfoEnableFastCharging(void) { - return psmEnableFastBatteryCharging_internal(); -} - -Result batteryInfoDisableFastCharging(void) { - return psmDisableFastBatteryCharging_internal(); -} - -const char* batteryInfoGetChargerTypeString(BatteryChargerType type) { - if (type < 0 || type > ChargerType_Apple_2000mA) - return "Unknown"; - - return s_chargerTypeStrings[type]; -} - -const char* batteryInfoGetPowerRoleString(BatteryPowerRole role) { - if (role < PowerRole_Sink || role > PowerRole_Source) - return s_powerRoleStrings[0]; - - return s_powerRoleStrings[role]; -} - -const char* batteryInfoGetPDStateString(BatteryPDControllerState state) { - if (state < PDState_NewPDO || state > PDState_AcceptedRDO) - return s_pdStateStrings[0]; - - return s_pdStateStrings[state]; -} \ No newline at end of file +Result batteryInfoInitialize(void); +void batteryInfoExit(void); +Result batteryInfoGetChargeInfo(BatteryChargeInfo *out); +Result batteryInfoGetChargePercentage(u32 *out); +Result batteryInfoIsEnoughPowerSupplied(bool *out); +Result batteryInfoEnableCharging(void); +Result batteryInfoDisableCharging(void); +Result batteryInfoEnableFastCharging(void); +Result batteryInfoDisableFastCharging(void); +const char* batteryInfoGetChargerTypeString(BatteryChargerType type); +const char* batteryInfoGetPowerRoleString(BatteryPowerRole role); +const char* batteryInfoGetPDStateString(BatteryPDControllerState state); diff --git a/Source/rewrite-hoc-clk/common/include/fuse.h b/Source/rewrite-hoc-clk/common/include/fuse.h new file mode 100644 index 00000000..107cebd2 --- /dev/null +++ b/Source/rewrite-hoc-clk/common/include/fuse.h @@ -0,0 +1,314 @@ +/* + * Copyright (c) 2018 naehrwert + * Copyright (c) 2018 shuffle2 + * Copyright (c) 2018 balika011 + * Copyright (c) 2019-2025 CTCaer + * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors + * + * This program is free software; you can redistribute it and/or modify it + * under the terms and conditions of the GNU General Public License, + * version 2, as published by the Free Software Foundation. + * + * This program is distributed in the hope it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef _FUSE_H_ +#define _FUSE_H_ + +#ifndef BIT +#define BIT(n) (1U<<(n)) +#endif + +/*! Fuse registers. */ +#define FUSE_CTRL 0x0 +#define FUSE_ADDR 0x4 +#define FUSE_RDATA 0x8 +#define FUSE_WDATA 0xC +#define FUSE_TIME_RD1 0x10 +#define FUSE_TIME_RD2 0x14 +#define FUSE_TIME_PGM1 0x18 +#define FUSE_TIME_PGM2 0x1C +#define FUSE_PRIV2INTFC 0x20 +#define FUSE_PRIV2INTFC_START_DATA BIT(0) +#define FUSE_PRIV2INTFC_SKIP_RECORDS BIT(1) +#define FUSE_FUSEBYPASS 0x24 +#define FUSE_PRIVATEKEYDISABLE 0x28 +#define FUSE_PRIVKEY_DISABLE BIT(0) +#define FUSE_PRIVKEY_TZ_STICKY_BIT BIT(4) +#define FUSE_DISABLEREGPROGRAM 0x2C +#define FUSE_WRITE_ACCESS_SW 0x30 +#define FUSE_PWR_GOOD_SW 0x34 +#define FUSE_PRIV2RESHIFT 0x3C +#define FUSE_FUSETIME_RD0 0x40 +#define FUSE_FUSETIME_RD1 0x44 +#define FUSE_FUSETIME_RD2 0x48 +#define FUSE_FUSETIME_RD3 0x4C +#define FUSE_PRIVATE_KEY0_NONZERO 0x80 +#define FUSE_PRIVATE_KEY1_NONZERO 0x84 +#define FUSE_PRIVATE_KEY2_NONZERO 0x88 +#define FUSE_PRIVATE_KEY3_NONZERO 0x8C +#define FUSE_PRIVATE_KEY4_NONZERO 0x90 + +/*! Fuse Cached registers */ +#define FUSE_RESERVED_ODM8_B01 0x98 // FUSE_READ_TZ Group 0. +#define FUSE_RESERVED_ODM9_B01 0x9C // FUSE_READ_TZ Group 0. +#define FUSE_RESERVED_ODM10_B01 0xA0 // FUSE_READ_TZ Group 0. +#define FUSE_RESERVED_ODM11_B01 0xA4 // FUSE_READ_TZ Group 0. +#define FUSE_RESERVED_ODM12_B01 0xA8 // FUSE_READ_TZ Group 1? Is value -1? +#define FUSE_RESERVED_ODM13_B01 0xAC // FUSE_READ_TZ Group 1? Is value -1? +#define FUSE_RESERVED_ODM14_B01 0xB0 // FUSE_READ_TZ Group 1? Is value -1? +#define FUSE_RESERVED_ODM15_B01 0xB4 // FUSE_READ_TZ Group 1? Is value -1? +#define FUSE_RESERVED_ODM16_B01 0xB8 // FUSE_READ_TZ Group 2? Is value -1? +#define FUSE_RESERVED_ODM17_B01 0xBC // FUSE_READ_TZ Group 2? Is value -1? +#define FUSE_RESERVED_ODM18_B01 0xC0 // FUSE_READ_TZ Group 2. +#define FUSE_RESERVED_ODM19_B01 0xC4 // FUSE_READ_TZ Group 2. +#define FUSE_RESERVED_ODM20_B01 0xC8 // FUSE_READ_TZ Group 3. +#define FUSE_RESERVED_ODM21_B01 0xCC // FUSE_READ_TZ Group 3. +#define FUSE_KEK00_B01 0xD0 +#define FUSE_KEK01_B01 0xD4 +#define FUSE_KEK02_B01 0xD8 +#define FUSE_KEK03_B01 0xDC +#define FUSE_BEK00_B01 0xE0 +#define FUSE_BEK01_B01 0xE4 +#define FUSE_BEK02_B01 0xE8 +#define FUSE_BEK03_B01 0xEC +#define FUSE_OPT_RAM_RTSEL_TSMCSP_PO4SVT_B01 0xF0 +#define FUSE_OPT_RAM_WTSEL_TSMCSP_PO4SVT_B01 0xF4 +#define FUSE_OPT_RAM_RTSEL_TSMCPDP_PO4SVT_B01 0xF8 +#define FUSE_OPT_RAM_MTSEL_TSMCPDP_PO4SVT_B01 0xFC + +#define FUSE_PRODUCTION_MODE 0x100 +#define FUSE_JTAG_SECUREID_VALID 0x104 +#define FUSE_ODM_LOCK 0x108 +#define FUSE_OPT_OPENGL_EN 0x10C +#define FUSE_SKU_INFO 0x110 +#define FUSE_CPU_SPEEDO_0_CALIB 0x114 +#define FUSE_CPU_IDDQ_CALIB 0x118 + +#define FUSE_RESERVED_ODM22_B01 0x11C // FUSE_READ_TZ Group 3. +#define FUSE_RESERVED_ODM23_B01 0x120 // FUSE_READ_TZ Group 3. +#define FUSE_RESERVED_ODM24_B01 0x124 // FUSE_READ_TZ Group 4. + +#define FUSE_OPT_FT_REV 0x128 +#define FUSE_CPU_SPEEDO_1_CALIB 0x12C +#define FUSE_CPU_SPEEDO_2_CALIB 0x130 +#define FUSE_SOC_SPEEDO_0_CALIB 0x134 +#define FUSE_SOC_SPEEDO_1_CALIB 0x138 +#define FUSE_SOC_SPEEDO_2_CALIB 0x13C +#define FUSE_SOC_IDDQ_CALIB 0x140 + +#define FUSE_RESERVED_ODM25_B01 0x144 // FUSE_READ_TZ Group 4. + +#define FUSE_FA 0x148 +#define FUSE_RESERVED_PRODUCTION 0x14C +#define FUSE_HDMI_LANE0_CALIB 0x150 +#define FUSE_HDMI_LANE1_CALIB 0x154 +#define FUSE_HDMI_LANE2_CALIB 0x158 +#define FUSE_HDMI_LANE3_CALIB 0x15C +#define FUSE_ENCRYPTION_RATE 0x160 +#define FUSE_PUBLIC_KEY0 0x164 +#define FUSE_PUBLIC_KEY1 0x168 +#define FUSE_PUBLIC_KEY2 0x16C +#define FUSE_PUBLIC_KEY3 0x170 +#define FUSE_PUBLIC_KEY4 0x174 +#define FUSE_PUBLIC_KEY5 0x178 +#define FUSE_PUBLIC_KEY6 0x17C +#define FUSE_PUBLIC_KEY7 0x180 +#define FUSE_TSENSOR1_CALIB 0x184 // CPU1. +#define FUSE_TSENSOR2_CALIB 0x188 // CPU2. + +#define FUSE_OPT_SECURE_SCC_DIS_B01 0x18C + +#define FUSE_OPT_CP_REV 0x190 // FUSE style revision - ATE. 0x101 0x100 +#define FUSE_OPT_PFG 0x194 +#define FUSE_TSENSOR0_CALIB 0x198 // CPU0. +#define FUSE_FIRST_BOOTROM_PATCH_SIZE 0x19C +#define FUSE_SECURITY_MODE 0x1A0 +#define FUSE_PRIVATE_KEY0 0x1A4 +#define FUSE_PRIVATE_KEY1 0x1A8 +#define FUSE_PRIVATE_KEY2 0x1AC +#define FUSE_PRIVATE_KEY3 0x1B0 +#define FUSE_PRIVATE_KEY4 0x1B4 +#define FUSE_ARM_JTAG_DIS 0x1B8 +#define FUSE_BOOT_DEVICE_INFO 0x1BC +#define FUSE_RESERVED_SW 0x1C0 +#define FUSE_OPT_VP9_DISABLE 0x1C4 + +#define FUSE_RESERVED_ODM0 0x1C8 +#define FUSE_RESERVED_ODM1 0x1CC +#define FUSE_RESERVED_ODM2 0x1D0 +#define FUSE_RESERVED_ODM3 0x1D4 +#define FUSE_RESERVED_ODM4 0x1D8 +#define FUSE_RESERVED_ODM5 0x1DC +#define FUSE_RESERVED_ODM6 0x1E0 +#define FUSE_RESERVED_ODM7 0x1E4 + +#define FUSE_OBS_DIS 0x1E8 + +#define FUSE_OPT_NVJTAG_PROTECTION_ENABLE_B01 0x1EC + +#define FUSE_USB_CALIB 0x1F0 +#define FUSE_SKU_DIRECT_CONFIG 0x1F4 +#define FUSE_KFUSE_PRIVKEY_CTRL 0x1F8 +#define FUSE_PACKAGE_INFO 0x1FC // 1: MID, 2: DSC. +#define FUSE_OPT_VENDOR_CODE 0x200 +#define FUSE_OPT_FAB_CODE 0x204 +#define FUSE_OPT_LOT_CODE_0 0x208 +#define FUSE_OPT_LOT_CODE_1 0x20C +#define FUSE_OPT_WAFER_ID 0x210 +#define FUSE_OPT_X_COORDINATE 0x214 +#define FUSE_OPT_Y_COORDINATE 0x218 +#define FUSE_OPT_SEC_DEBUG_EN 0x21C +#define FUSE_OPT_OPS_RESERVED 0x220 +#define FUSE_SATA_CALIB 0x224 + +#define FUSE_SPARE_REGISTER_ODM_B01 0x224 + +#define FUSE_GPU_IDDQ_CALIB 0x228 +#define FUSE_TSENSOR3_CALIB 0x22C // CPU3. +#define FUSE_CLOCK_BONDOUT0 0x230 +#define FUSE_CLOCK_BONDOUT1 0x234 + +#define FUSE_RESERVED_ODM26_B01 0x238 // FUSE_READ_TZ Group 4. +#define FUSE_RESERVED_ODM27_B01 0x23C // FUSE_READ_TZ Group 4. +#define FUSE_RESERVED_ODM28_B01 0x240 // MAX77812 phase configuration. FUSE_READ_TZ Group 5. + +#define FUSE_OPT_SAMPLE_TYPE 0x244 +#define FUSE_OPT_SUBREVISION 0x248 // "", "p", "q", "r". e.g: A01p. +#define FUSE_OPT_SW_RESERVED_0 0x24C +#define FUSE_OPT_SW_RESERVED_1 0x250 +#define FUSE_TSENSOR4_CALIB 0x254 // GPU. +#define FUSE_TSENSOR5_CALIB 0x258 // MEM0. +#define FUSE_TSENSOR6_CALIB 0x25C // MEM1. +#define FUSE_TSENSOR7_CALIB 0x260 // PLLX. +#define FUSE_OPT_PRIV_SEC_DIS 0x264 +#define FUSE_PKC_DISABLE 0x268 + +#define FUSE_BOOT_SECURITY_INFO_B01 0x268 +#define FUSE_OPT_RAM_RTSEL_TSMCSP_PO4HVT_B01 0x26C +#define FUSE_OPT_RAM_WTSEL_TSMCSP_PO4HVT_B01 0x270 +#define FUSE_OPT_RAM_RTSEL_TSMCPDP_PO4HVT_B01 0x274 +#define FUSE_OPT_RAM_MTSEL_TSMCPDP_PO4HVT_B01 0x278 + +#define FUSE_FUSE2TSEC_DEBUG_DISABLE 0x27C +#define FUSE_TSENSOR_COMMON 0x280 +#define FUSE_OPT_CP_BIN 0x284 +#define FUSE_OPT_GPU_DISABLE 0x288 +#define FUSE_OPT_FT_BIN 0x28C +#define FUSE_OPT_DONE_MAP 0x290 + +#define FUSE_RESERVED_ODM29_B01 0x294 // FUSE_READ_TZ Group 5? Is value -1? + +#define FUSE_APB2JTAG_DISABLE 0x298 +#define FUSE_ODM_INFO 0x29C // Debug features disable. +#define FUSE_ARM_CRYPT_DE_FEATURE 0x2A8 + +#define FUSE_OPT_RAM_WTSEL_TSMCPDP_PO4SVT_B01 0x2B0 +#define FUSE_OPT_RAM_RCT_TSMCDP_PO4SVT_B01 0x2B4 +#define FUSE_OPT_RAM_WCT_TSMCDP_PO4SVT_B01 0x2B8 +#define FUSE_OPT_RAM_KP_TSMCDP_PO4SVT_B01 0x2BC + +#define FUSE_WOA_SKU_FLAG 0x2C0 +#define FUSE_ECO_RESERVE_1 0x2C4 +#define FUSE_GCPLEX_CONFIG_FUSE 0x2C8 +#define FUSE_GPU_VPR_AUTO_FETCH_DIS BIT(0) +#define FUSE_GPU_VPR_ENABLED BIT(1) +#define FUSE_GPU_WPR_ENABLED BIT(2) +#define FUSE_PRODUCTION_MONTH 0x2CC +#define FUSE_RAM_REPAIR_INDICATOR 0x2D0 +#define FUSE_TSENSOR9_CALIB 0x2D4 // AOTAG. +#define FUSE_VMIN_CALIBRATION 0x2DC +#define FUSE_AGING_SENSOR_CALIBRATION 0x2E0 +#define FUSE_DEBUG_AUTHENTICATION 0x2E4 +#define FUSE_SECURE_PROVISION_INDEX 0x2E8 +#define FUSE_SECURE_PROVISION_INFO 0x2EC +#define FUSE_OPT_GPU_DISABLE_CP1 0x2F0 +#define FUSE_SPARE_ENDIS 0x2F4 +#define FUSE_ECO_RESERVE_0 0x2F8 // AID. +#define FUSE_RESERVED_CALIB0 0x304 // GPCPLL ADC Calibration. +#define FUSE_RESERVED_CALIB1 0x308 +#define FUSE_OPT_GPU_TPC0_DISABLE 0x30C +#define FUSE_OPT_GPU_TPC0_DISABLE_CP1 0x310 +#define FUSE_OPT_CPU_DISABLE 0x314 +#define FUSE_OPT_CPU_DISABLE_CP1 0x318 +#define FUSE_TSENSOR10_CALIB 0x31C +#define FUSE_TSENSOR10_CALIB_AUX 0x320 +#define FUSE_OPT_RAM_SVOP_DP 0x324 +#define FUSE_OPT_RAM_SVOP_PDP 0x328 +#define FUSE_OPT_RAM_SVOP_REG 0x32C +#define FUSE_OPT_RAM_SVOP_SP 0x330 +#define FUSE_OPT_RAM_SVOP_SMPDP 0x334 + +#define FUSE_OPT_RAM_WTSEL_TSMCPDP_PO4HVT_B01 0x324 +#define FUSE_OPT_RAM_RCT_TSMCDP_PO4HVT_B01 0x328 +#define FUSE_OPT_RAM_WCT_TSMCDP_PO4HVT_B01 0x32c +#define FUSE_OPT_RAM_KP_TSMCDP_PO4HVT_B01 0x330 +#define FUSE_OPT_RAM_SVOP_SP_B01 0x334 + +#define FUSE_OPT_GPU_TPC0_DISABLE_CP2 0x338 +#define FUSE_OPT_GPU_TPC1_DISABLE 0x33C +#define FUSE_OPT_GPU_TPC1_DISABLE_CP1 0x340 +#define FUSE_OPT_GPU_TPC1_DISABLE_CP2 0x344 +#define FUSE_OPT_CPU_DISABLE_CP2 0x348 +#define FUSE_OPT_GPU_DISABLE_CP2 0x34C +#define FUSE_USB_CALIB_EXT 0x350 +#define FUSE_RESERVED_FIELD 0x354 // RMA. +#define FUSE_SPARE_REALIGNMENT_REG 0x37C +#define FUSE_SPARE_BIT_0 0x380 +//... +#define FUSE_SPARE_BIT_31 0x3FC + +/*! Fuse commands. */ +#define FUSE_IDLE 0x0 +#define FUSE_READ 0x1 +#define FUSE_WRITE 0x2 +#define FUSE_SENSE 0x3 +#define FUSE_CMD_MASK 0x3 + +/*! Fuse status. */ +#define FUSE_STATUS_RESET 0 +#define FUSE_STATUS_POST_RESET 1 +#define FUSE_STATUS_LOAD_ROW0 2 +#define FUSE_STATUS_LOAD_ROW1 3 +#define FUSE_STATUS_IDLE 4 +#define FUSE_STATUS_READ_SETUP 5 +#define FUSE_STATUS_READ_STROBE 6 +#define FUSE_STATUS_SAMPLE_FUSES 7 +#define FUSE_STATUS_READ_HOLD 8 +#define FUSE_STATUS_FUSE_SRC_SETUP 9 +#define FUSE_STATUS_WRITE_SETUP 10 +#define FUSE_STATUS_WRITE_ADDR_SETUP 11 +#define FUSE_STATUS_WRITE_PROGRAM 12 +#define FUSE_STATUS_WRITE_ADDR_HOLD 13 +#define FUSE_STATUS_FUSE_SRC_HOLD 14 +#define FUSE_STATUS_LOAD_RIR 15 +#define FUSE_STATUS_READ_BEFORE_WRITE_SETUP 16 +#define FUSE_STATUS_READ_DEASSERT_PD 17 + +/*! Fuse cache registers. */ +#define FUSE_RESERVED_ODMX(x) (0x1C8 + 4 * (x)) + +#define FUSE_ARRAY_WORDS_NUM 192 +#define FUSE_ARRAY_WORDS_NUM_B01 256 + +enum +{ + FUSE_NX_HW_TYPE_ICOSA, + FUSE_NX_HW_TYPE_IOWA, + FUSE_NX_HW_TYPE_HOAG, + FUSE_NX_HW_TYPE_AULA +}; + +enum +{ + FUSE_NX_HW_STATE_PROD, + FUSE_NX_HW_STATE_DEV +}; + +#endif diff --git a/Source/rewrite-hoc-clk/common/include/sysclk/clock_manager.h b/Source/rewrite-hoc-clk/common/include/sysclk/clock_manager.h index 917b3701..a24a0e48 100644 --- a/Source/rewrite-hoc-clk/common/include/sysclk/clock_manager.h +++ b/Source/rewrite-hoc-clk/common/include/sysclk/clock_manager.h @@ -43,12 +43,19 @@ typedef struct uint32_t voltages[HocClkVoltage_EnumMax]; u16 speedos[HorizonOCSpeedo_EnumMax]; u16 iddq[HorizonOCSpeedo_EnumMax]; + u16 waferX; + u16 waferY; + + // Misc stuff GpuSchedulingMode gpuSchedulingMode; bool isSysDockInstalled; bool isSaltyNXInstalled; + bool isUsingRetroSuper; u8 maxDisplayFreq; u8 dramID; bool isDram8GB; + + // FPS / Resolution u8 fps; u16 resolutionHeight; } SysClkContext; diff --git a/Source/rewrite-hoc-clk/common/src/battery.cpp b/Source/rewrite-hoc-clk/common/src/battery.cpp new file mode 100644 index 00000000..9a405575 --- /dev/null +++ b/Source/rewrite-hoc-clk/common/src/battery.cpp @@ -0,0 +1,165 @@ +/* + * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors + * + * This program is free software; you can redistribute it and/or modify it + * under the terms and conditions of the GNU General Public License, + * version 2, as published by the Free Software Foundation. + * + * This program is distributed in the hope it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include +#include +#include "battery.h" + +// Internal PSM service handle +static Service g_psmService = {0}; +static bool g_batteryInfoInitialized = false; + +static const char* s_chargerTypeStrings[] = { + "None", + "Power Delivery", + "USB-C @ 1.5A", + "USB-C @ 3.0A", + "USB-DCP", + "USB-CDP", + "USB-SDP", + "Apple @ 0.5A", + "Apple @ 1.0A", + "Apple @ 2.0A", +}; + +static const char* s_powerRoleStrings[] = { + "Unknown", + "Sink", + "Source", +}; + +static const char* s_pdStateStrings[] = { + "Unknown", + "New PDO Received", + "No PD Source", + "RDO Accepted" +}; + +// Internal PSM command implementations +static Result psmGetBatteryChargeInfoFields(BatteryChargeInfo *out) { + if (!g_batteryInfoInitialized) + return MAKERESULT(Module_Libnx, LibnxError_NotInitialized); + + return serviceDispatchOut(&g_psmService, 17, *out); +} + +static Result psmEnableBatteryCharging_internal(void) { + if (!g_batteryInfoInitialized) + return MAKERESULT(Module_Libnx, LibnxError_NotInitialized); + + return serviceDispatch(&g_psmService, 2); +} + +static Result psmDisableBatteryCharging_internal(void) { + if (!g_batteryInfoInitialized) + return MAKERESULT(Module_Libnx, LibnxError_NotInitialized); + + return serviceDispatch(&g_psmService, 3); +} + +static Result psmEnableFastBatteryCharging_internal(void) { + if (!g_batteryInfoInitialized) + return MAKERESULT(Module_Libnx, LibnxError_NotInitialized); + + return serviceDispatch(&g_psmService, 10); +} + +static Result psmDisableFastBatteryCharging_internal(void) { + if (!g_batteryInfoInitialized) + return MAKERESULT(Module_Libnx, LibnxError_NotInitialized); + + return serviceDispatch(&g_psmService, 11); +} + +Result batteryInfoInitialize(void) { + if (g_batteryInfoInitialized) + return 0; + + Result rc = psmInitialize(); + if (R_SUCCEEDED(rc)) { + memcpy(&g_psmService, psmGetServiceSession(), sizeof(Service)); + g_batteryInfoInitialized = true; + } + + return rc; +} + +void batteryInfoExit(void) { + if (g_batteryInfoInitialized) { + psmExit(); + memset(&g_psmService, 0, sizeof(Service)); + g_batteryInfoInitialized = false; + } +} + +Result batteryInfoGetChargeInfo(BatteryChargeInfo *out) { + if (!out) + return MAKERESULT(Module_Libnx, LibnxError_BadInput); + + return psmGetBatteryChargeInfoFields(out); +} + +Result batteryInfoGetChargePercentage(u32 *out) { + if (!g_batteryInfoInitialized) + return MAKERESULT(Module_Libnx, LibnxError_NotInitialized); + + return psmGetBatteryChargePercentage(out); +} + +Result batteryInfoIsEnoughPowerSupplied(bool *out) { + if (!g_batteryInfoInitialized) + return MAKERESULT(Module_Libnx, LibnxError_NotInitialized); + + return psmIsEnoughPowerSupplied(out); +} + +Result batteryInfoEnableCharging(void) { + return psmEnableBatteryCharging_internal(); +} + +Result batteryInfoDisableCharging(void) { + return psmDisableBatteryCharging_internal(); +} + +Result batteryInfoEnableFastCharging(void) { + return psmEnableFastBatteryCharging_internal(); +} + +Result batteryInfoDisableFastCharging(void) { + return psmDisableFastBatteryCharging_internal(); +} + +const char* batteryInfoGetChargerTypeString(BatteryChargerType type) { + if (type < 0 || type > ChargerType_Apple_2000mA) + return "Unknown"; + + return s_chargerTypeStrings[type]; +} + +const char* batteryInfoGetPowerRoleString(BatteryPowerRole role) { + if (role < PowerRole_Sink || role > PowerRole_Source) + return s_powerRoleStrings[0]; + + return s_powerRoleStrings[role]; +} + +const char* batteryInfoGetPDStateString(BatteryPDControllerState state) { + if (state < PDState_NewPDO || state > PDState_AcceptedRDO) + return s_pdStateStrings[0]; + + return s_pdStateStrings[state]; +} \ No newline at end of file diff --git a/Source/rewrite-hoc-clk/common/src/display_refresh_rate.cpp b/Source/rewrite-hoc-clk/common/src/display_refresh_rate.cpp index 7a169883..65936751 100644 --- a/Source/rewrite-hoc-clk/common/src/display_refresh_rate.cpp +++ b/Source/rewrite-hoc-clk/common/src/display_refresh_rate.cpp @@ -88,12 +88,29 @@ static const DockedTimings g_dockedTimings1080p[] = { // technically you can go to 476hz, but in practice, why would you? }; +// These timings *should* work but are untested static const HandheldTimings g_handheldTimingsRETRO[] = { - {72, 136, 72, 1, 660, 9, 78000}, - {72, 136, 72, 1, 443, 9, 77985}, - {72, 136, 72, 1, 270, 9, 78000}, - {72, 136, 72, 1, 128, 9, 77990}, - {72, 136, 72, 1, 10, 9, 78000} + {72, 136, 72, 1, 660, 9, 78000}, // 40Hz + {72, 136, 72, 1, 612, 9, 77982}, // 41Hz + {72, 136, 72, 1, 567, 9, 77994}, // 42Hz + {72, 136, 72, 1, 524, 9, 78002}, // 43Hz + {72, 136, 72, 1, 483, 9, 78012}, // 44Hz + {72, 136, 72, 1, 443, 9, 77985}, // 45Hz + {72, 136, 72, 1, 406, 9, 78016}, // 46Hz + {72, 136, 72, 1, 370, 9, 78020}, // 47Hz + {72, 136, 72, 1, 335, 9, 78000}, // 48Hz + {72, 136, 72, 1, 302, 9, 78008}, // 49Hz + {72, 136, 72, 1, 270, 9, 78000}, // 50Hz + {72, 136, 72, 1, 239, 9, 77979}, // 51Hz + {72, 136, 72, 1, 210, 9, 78000}, // 52Hz + {72, 136, 72, 1, 182, 9, 78016}, // 53Hz + {72, 136, 72, 1, 154, 9, 77976}, // 54Hz + {72, 136, 72, 1, 128, 9, 77990}, // 55Hz + {72, 136, 72, 1, 103, 9, 78008}, // 56Hz + {72, 136, 72, 1, 78, 9, 77976}, // 57Hz + {72, 136, 72, 1, 55, 9, 78010}, // 58Hz + {72, 136, 72, 1, 32, 9, 77998}, // 59Hz + {72, 136, 72, 1, 10, 9, 78000}, // 60Hz }; static const MinMaxRefreshRate g_handheldModeRefreshRate = {40, 80}; @@ -543,10 +560,6 @@ bool DisplayRefresh_SetRate(uint32_t new_refreshRate) { uint32_t fd = 0; - if (g_config.isLite && g_config.isPossiblySpoofedRetro) { - g_config.isRetroSUPER = false; // Would check flag file here in original, but i dont care lol - } - if (g_config.isRetroSUPER && !g_config.isDocked) { return _setNvDispHandheldRefreshRate(new_refreshRate); } diff --git a/Source/rewrite-hoc-clk/sysmodule/Makefile b/Source/rewrite-hoc-clk/sysmodule/Makefile index ae8bfa66..80f7495b 100644 --- a/Source/rewrite-hoc-clk/sysmodule/Makefile +++ b/Source/rewrite-hoc-clk/sysmodule/Makefile @@ -21,7 +21,7 @@ TARGET := horizon-oc BUILD := build OUTDIR := out RESOURCES := res -SOURCES := src src/nx/ipc ../common/src +SOURCES := src src/nx/ipc ../common/src src/board DATA := data INCLUDES := ../common/include EXEFS_SRC := exefs_src diff --git a/Source/rewrite-hoc-clk/sysmodule/src/board/board.cpp b/Source/rewrite-hoc-clk/sysmodule/src/board/board.cpp index 906a6bb8..3dbd1a97 100644 --- a/Source/rewrite-hoc-clk/sysmodule/src/board/board.cpp +++ b/Source/rewrite-hoc-clk/sysmodule/src/board/board.cpp @@ -29,6 +29,10 @@ #include #include #include +#include +#include +#include +#include #include "board.hpp" #include "board_fuse.hpp" @@ -41,14 +45,15 @@ namespace board { SysClkSocType gSocType; u8 gDramID; HorizonOCConsoleType gConsoleType = HorizonOCConsoleType_Iowa; - FuseSpeedoData gSpeedos; + FuseData fuseData; u8 speedoBracket; - Result nvCheck = 1; - u23 fd = 0, fd2 = 0; + PwmChannelSession iCon; + + u32 fd = 0, fd2 = 0; void FetchHardwareInfos() { - FuseReadSpeedos(gSpeedos); - FuseSetGpuBracket(gSpeedos.gpuSpeedo, speedoBracket); + ReadFuses(fuseData); + SetGpuBracket(fuseData.gpuSpeedo, speedoBracket); u64 sku = 0, dramID = 0; Result rc = splInitialize(); @@ -74,8 +79,7 @@ namespace board { CacheGpuVoltTable(); } - gConsoleType = static_cast sku; - g_dramID = dramID; + gConsoleType = static_cast(sku); } /* TODO: Check for config */ @@ -90,6 +94,12 @@ namespace board { ASSERT_RESULT_OK(rc, "pcvInitialize"); } + rc = apmExtInitialize(); + ASSERT_RESULT_OK(rc, "apmExtInitialize"); + + rc = psmInitialize(); + ASSERT_RESULT_OK(rc, "psmInitialize"); + if(HOSSVC_HAS_TC) { rc = tcInitialize(); ASSERT_RESULT_OK(rc, "tcInitialize"); @@ -101,10 +111,16 @@ namespace board { rc = tmp451Initialize(); ASSERT_RESULT_OK(rc, "tmp451Initialize"); - nvInitialize_rc = nvInitialize(); - if (R_SUCCEEDED(nvInitialize_rc)) { + Result nvCheck = 1; + if (R_SUCCEEDED(nvInitialize())) { nvCheck = nvOpen(&fd, "/dev/nvhost-ctrl-gpu"); - nvCheck_sched = nvOpen(&fd2, "/dev/nvsched-ctrl"); + Result nvCheck_sched = nvOpen(&fd2, "/dev/nvsched-ctrl"); + /* This can be improved. */ + NvSchedSucceed(nvCheck_sched); + + if (R_SUCCEEDED(nvCheck_sched)) { + SchedSetFD2(fd2); + } } rc = rgltrInitialize(); @@ -113,19 +129,17 @@ namespace board { rc = pmdmntInitialize(); ASSERT_RESULT_OK(rc, "pmdmntInitialize"); - StartGpuLoad(nvCheck, fd); - - StartMiscThread(pwmCheck) + StartLoad(nvCheck, fd); batteryInfoInitialize(); FetchHardwareInfos(); Result pwmCheck = 1; if (hosversionAtLeast(6,0,0) && R_SUCCEEDED(pwmInitialize())) { - pwmCheck = pwmOpenSession2(&g_ICon, 0x3D000001); + pwmCheck = pwmOpenSession2(&iCon, 0x3D000001); } - StartMiscThread(pwmCheck); + StartMiscThread(pwmCheck, &iCon); if (gConsoleType != HorizonOCConsoleType_Hoag) { u64 clkVirtAddr, dsiVirtAddr, outsize; @@ -164,7 +178,7 @@ namespace board { ExitMiscThread(); - pwmChannelSessionClose(&g_ICon); + pwmChannelSessionClose(&iCon); pwmExit(); rgltrExit(); batteryInfoExit(); @@ -185,7 +199,7 @@ namespace board { } u8 GetDramID() { - return dramID; + return gDramID; } bool IsDram8GB() { @@ -209,4 +223,16 @@ namespace board { } } + FuseData *GetFuseData() { + return &fuseData; + } + + u8 GetGpuSpeedoBracket() { + return speedoBracket; + } + + bool IsUsingRetroSuperDisplay() { + return false; /* stub for now. */ + } + } diff --git a/Source/rewrite-hoc-clk/sysmodule/src/board/board.hpp b/Source/rewrite-hoc-clk/sysmodule/src/board/board.hpp index 05830e57..cc83a93c 100644 --- a/Source/rewrite-hoc-clk/sysmodule/src/board/board.hpp +++ b/Source/rewrite-hoc-clk/sysmodule/src/board/board.hpp @@ -27,6 +27,14 @@ #pragma once #include +#include +#include "board_fuse.hpp" +#include "board_load.hpp" +#include "board_name.hpp" +#include "board_freq.hpp" +#include "board_sensor.hpp" +#include "board_volt.hpp" +#include "board_profile.hpp" #define HOSSVC_HAS_CLKRST (hosversionAtLeast(8,0,0)) #define HOSSVC_HAS_TC (hosversionAtLeast(5,0,0)) @@ -38,7 +46,10 @@ namespace board { SysClkSocType GetSocType(); HorizonOCConsoleType GetConsoleType(); u8 GetDramID(); + u8 GetGpuSpeedoBracket(); bool IsDram8GB(); void SetDisplayRefreshDockedState(bool docked); + FuseData *GetFuseData(); + bool IsUsingRetroSuperDisplay(); } diff --git a/Source/rewrite-hoc-clk/sysmodule/src/board/board_freq.cpp b/Source/rewrite-hoc-clk/sysmodule/src/board/board_freq.cpp index c0d26c17..d56c81fd 100644 --- a/Source/rewrite-hoc-clk/sysmodule/src/board/board_freq.cpp +++ b/Source/rewrite-hoc-clk/sysmodule/src/board/board_freq.cpp @@ -27,20 +27,13 @@ #include #include #include +#include #include "board.hpp" #include "board_name.hpp" -#include "../error.h" +#include "../errors.h" namespace board { - PcvModuleId GetPcvModuleId(SysClkModule sysclkModule) { - PcvModuleId pcvModuleId; - Result rc = pcvGetModuleId(&pcvModuleId, GetPcvModule(sysclkModule)); - ASSERT_RESULT_OK(rc, "pcvGetModuleId"); - - return pcvModuleId; - } - PcvModule GetPcvModule(SysClkModule sysclkModule) { switch (sysclkModule) { case SysClkModule_CPU: @@ -53,14 +46,22 @@ namespace board { ASSERT_ENUM_VALID(SysClkModule, sysclkModule); } - return (PcvModule)0; + return static_cast(0); + } + + PcvModuleId GetPcvModuleId(SysClkModule sysclkModule) { + PcvModuleId pcvModuleId; + Result rc = pcvGetModuleId(&pcvModuleId, GetPcvModule(sysclkModule)); + ASSERT_RESULT_OK(rc, "pcvGetModuleId"); + + return pcvModuleId; } void ClkrstSetHz(ClkrstSession &session, u32 hz) { ASSERT_RESULT_OK(clkrstSetClockRate(&session, hz), "clkrstSetClockRate"); } - void PcvSetHz(PcvModuleId moduleID, u32 hz) { + void PcvSetHz(PcvModule moduleID, u32 hz) { ASSERT_RESULT_OK(pcvSetClockRate(moduleID, hz), "pcvSetClockRate"); } @@ -86,7 +87,7 @@ namespace board { /* Voltage bug workaround. */ if (module == SysClkModule_CPU) { - svcSleepThread(200'000); + svcSleepThread(250'000); ClkrstSetHz(session, hz); } @@ -95,7 +96,7 @@ namespace board { PcvSetHz(GetPcvModule(module), hz); if (module == SysClkModule_CPU) { - svcSleepThread(200'000); + svcSleepThread(250'000); PcvSetHz(GetPcvModule(module), hz); } } @@ -114,7 +115,7 @@ namespace board { u32 hz = 0; if (module == HorizonOCModule_Display) { - return GetDisplayRate(); + return GetDisplayRate(hz); } if (HOSSVC_HAS_CLKRST) { @@ -145,7 +146,7 @@ namespace board { case SysClkModule_MEM: return t210ClkMemFreq(); case HorizonOCModule_Display: - return GetDisplayRate(); + return GetDisplayRate(hz); return hz; default: ASSERT_ENUM_VALID(SysClkModule, module); @@ -192,6 +193,7 @@ namespace board { } void ResetToStock() { + Result rc; if (hosversionAtLeast(9,0,0)) { std::uint32_t confId = 0; rc = apmExtGetCurrentPerformanceConfiguration(&confId); @@ -223,7 +225,7 @@ namespace board { } void ResetToStockDisplay() { - if (GetConsoleType != HorizonOCConsoleType_Hoag) { + if (GetConsoleType() != HorizonOCConsoleType_Hoag) { DisplayRefresh_SetRate(60); } } diff --git a/Source/rewrite-hoc-clk/sysmodule/src/board/board_freq.hpp b/Source/rewrite-hoc-clk/sysmodule/src/board/board_freq.hpp index 30f42a66..5ed8b624 100644 --- a/Source/rewrite-hoc-clk/sysmodule/src/board/board_freq.hpp +++ b/Source/rewrite-hoc-clk/sysmodule/src/board/board_freq.hpp @@ -28,6 +28,7 @@ #include #include #include +#include "../errors.h" namespace board { @@ -35,7 +36,7 @@ namespace board { u32 GetHz(SysClkModule module); u32 GetRealHz(SysClkModule module); - u32 GetFreqList(SysClkModule module, u32 *outList, u32 maxCount, u32 *outCount); + void GetFreqList(SysClkModule module, u32 *outList, u32 maxCount, u32 *outCount); u32 GetHighestDockedDisplayRate(); void ResetToStock(); diff --git a/Source/rewrite-hoc-clk/sysmodule/src/board/board_fuse.cpp b/Source/rewrite-hoc-clk/sysmodule/src/board/board_fuse.cpp index 516cbe79..43ec641a 100644 --- a/Source/rewrite-hoc-clk/sysmodule/src/board/board_fuse.cpp +++ b/Source/rewrite-hoc-clk/sysmodule/src/board/board_fuse.cpp @@ -25,24 +25,12 @@ */ #include +#include #include "board_fuse.hpp" +#include namespace board { - namespace { - constexpr u32 FuseCpuSpeedoCalib = 0x114; - // constexpr u32 FuseCpuSpeedo1Calib = 0x12C; - constexpr u32 FuseGpuSpeedoCalib = 0x130; - - constexpr u32 FuseSocSpeedoCalib = 0x134; - // constexpr u32 FuseSocSpeedo1Calib = 0x138; - // constexpr u32 FuseSocSpeedo2Calib = 0x13C; - - constexpr u32 FuseCpuIddqCalib = 0x118; - constexpr u32 FuseSocIddqCalib = 0x140; - constexpr u32 FuseGpuIddqCalib = 0x228; - } - void SetGpuBracket(u8 speedo, u8 &gpuBracket) { if (speedo <= 1624) { gpuBracket = 0; @@ -63,7 +51,7 @@ namespace board { gpuBracket = 3; } - FuseReadSpeedo(FuseSpeedoData &speedo) { + void ReadFuses(FuseData &speedo) { u64 pid = 0; constexpr u64 UsbID = 0x0100000000000006; if (R_FAILED(pmdmntGetProcessId(&pid, UsbID))) { @@ -99,12 +87,15 @@ namespace board { break; } - speedo.cpuSpeedo = *reinterpret_cast(dump + FuseCpuSpeedoCalib); - speedo.gpuSpeedo = *reinterpret_cast(dump + FuseGpuSpeedoCalib); - speedo.socSpeedo = *reinterpret_cast(dump + FuseSocSpeedoCalib); - speedo.cpuIDDQ = *reinterpret_cast(dump + FuseCpuIddqCalib); - speedo.gpuIDDQ = *reinterpret_cast(dump + FuseSocIddqCalib); - speedo.socIDDQ = *reinterpret_cast(dump + FUSE_GPU_IDDQ_CALIB); + speedo.cpuSpeedo = *reinterpret_cast(dump + FUSE_CPU_SPEEDO_0_CALIB); + speedo.gpuSpeedo = *reinterpret_cast(dump + FUSE_CPU_SPEEDO_2_CALIB); + speedo.socSpeedo = *reinterpret_cast(dump + FUSE_SOC_SPEEDO_0_CALIB); + + speedo.cpuIDDQ = *reinterpret_cast(dump + FUSE_CPU_IDDQ_CALIB) * 4; + speedo.gpuIDDQ = *reinterpret_cast(dump + FUSE_GPU_IDDQ_CALIB) * 5; + speedo.socIDDQ = *reinterpret_cast(dump + FUSE_SOC_IDDQ_CALIB) * 4; + speedo.waferX = *reinterpret_cast(dump + FUSE_OPT_X_COORDINATE); + speedo.waferY = *reinterpret_cast(dump + FUSE_OPT_Y_COORDINATE); svcCloseHandle(debug); return; diff --git a/Source/rewrite-hoc-clk/sysmodule/src/board/board_fuse.hpp b/Source/rewrite-hoc-clk/sysmodule/src/board/board_fuse.hpp index c67e0a2b..27b74399 100644 --- a/Source/rewrite-hoc-clk/sysmodule/src/board/board_fuse.hpp +++ b/Source/rewrite-hoc-clk/sysmodule/src/board/board_fuse.hpp @@ -24,11 +24,13 @@ * -------------------------------------------------------------------------- */ +#pragma once + #include namespace board { - struct FuseSpeedoData { + struct FuseData { u16 cpuSpeedo; u16 gpuSpeedo; u16 socSpeedo; @@ -36,9 +38,12 @@ namespace board { u16 cpuIDDQ; u16 gpuIDDQ; u16 socIDDQ; + + u16 waferX; + u16 waferY; }; - FuseReadSpeedo(FuseSpeedoData speedo); - FuseSetGpuBracket(u8 gpuSpeedo, u8 &gpuBracket); + void ReadFuses(FuseData &speedo); + void SetGpuBracket(u8 gpuSpeedo, u8 &gpuBracket); } diff --git a/Source/rewrite-hoc-clk/sysmodule/src/board/board_load.cpp b/Source/rewrite-hoc-clk/sysmodule/src/board/board_load.cpp index 1c495c04..6fbc559e 100644 --- a/Source/rewrite-hoc-clk/sysmodule/src/board/board_load.cpp +++ b/Source/rewrite-hoc-clk/sysmodule/src/board/board_load.cpp @@ -30,8 +30,10 @@ #include #include #include -#include "board_misc.hpp" #include +#include +#include "board_misc.hpp" +#include "board.hpp" namespace board { @@ -42,7 +44,8 @@ namespace board { Thread cpuCore2Thread; u32 gpuLoad; - u32 _fd; + u32 _fd, _fd2; + Result nvCheckSched; u64 idletick0 = 0; u64 idletick1 = 0; @@ -61,8 +64,8 @@ namespace board { if (R_SUCCEEDED(nvCheck)) do { u32 temp; if (R_SUCCEEDED(nvIoctl(_fd, NVGPU_GPU_IOCTL_PMU_GET_GPU_LOAD, &temp))) { - gpu_load_array[i++ % gpu_samples_average] = temp; - gpuLoad = std::accumulate(&gpu_load_array[0], &gpu_load_array[gpu_samples_average], 0) / gpu_samples_average; + gpu_load_array[i++ % GpuSamples] = temp; + gpuLoad = std::accumulate(&gpu_load_array[0], &gpu_load_array[GpuSamples], 0) / GpuSamples; } svcSleepThread(16'666'000); // wait a bit (this is the perfect amount of time to keep the reading accurate) } while(true); @@ -80,10 +83,10 @@ namespace board { } } - void StartLoad() { + void StartLoad(Result nvCheck, u32 fd) { _fd = fd; threadCreate(&gpuThread, GpuLoadThread, &nvCheck, NULL, 0x1000, 0x3F, -2); - threadStart(&gpuThread) + threadStart(&gpuThread); leventClear(&threadexit); threadCreate(&cpuCore0Thread, CheckCore, &idletick0, NULL, 0x1000, 0x10, 0); @@ -136,7 +139,7 @@ namespace board { constexpr u32 NVschedCtrlDisable = 0x00000602; } - void SetGpuSchedulingMode(GpuSchedulingMode mode, GpuSchedulingOverrideMethod method, Result nvCheckSched, u32 fd2) { + void SetGpuSchedulingMode(GpuSchedulingMode mode, GpuSchedulingOverrideMethod method) { if (R_FAILED(nvCheckSched) && method == GpuSchedulingOverrideMethod_NvService) { return; } @@ -147,14 +150,14 @@ namespace board { case GpuSchedulingMode_DoNotOverride: break; case GpuSchedulingMode_Disabled: if (method == GpuSchedulingOverrideMethod_NvService) { - nvIoctl(fd2, NVschedCtrlDisable, &temp); + nvIoctl(_fd2, NVschedCtrlDisable, &temp); } else { enabled = false; } break; case GpuSchedulingMode_Enabled: if (method == GpuSchedulingOverrideMethod_NvService) { - nvIoctl(fd2, NVschedCtrlEnable, &temp); + nvIoctl(_fd2, NVschedCtrlEnable, &temp); } else { enabled = true; } @@ -174,4 +177,12 @@ namespace board { } } + void SchedSetFD2(u32 fd2) { + _fd2 = fd2; + } + + void NvSchedSucceed(Result nvSched) { + nvCheckSched = nvSched; + } + } diff --git a/Source/rewrite-hoc-clk/sysmodule/src/board/board_load.hpp b/Source/rewrite-hoc-clk/sysmodule/src/board/board_load.hpp index 6f830738..02fdbf43 100644 --- a/Source/rewrite-hoc-clk/sysmodule/src/board/board_load.hpp +++ b/Source/rewrite-hoc-clk/sysmodule/src/board/board_load.hpp @@ -26,12 +26,15 @@ #pragma once #include +#include namespace board { void StartLoad(Result nvCheck, u32 fd); void ExitLoad(); - u32 GetPartLoad(); - void SetGpuSchedulingMode(GpuSchedulingMode mode, GpuSchedulingOverrideMethod method, Result nvCheckSched, u32 fd2); + u32 GetPartLoad(SysClkPartLoad loadSource); + void SetGpuSchedulingMode(GpuSchedulingMode mode, GpuSchedulingOverrideMethod method); + void SchedSetFD2(u32 fd2); + void NvSchedSucceed(Result nvSched); } diff --git a/Source/rewrite-hoc-clk/sysmodule/src/board/board_misc.cpp b/Source/rewrite-hoc-clk/sysmodule/src/board/board_misc.cpp index f43b85a5..51ce8c46 100644 --- a/Source/rewrite-hoc-clk/sysmodule/src/board/board_misc.cpp +++ b/Source/rewrite-hoc-clk/sysmodule/src/board/board_misc.cpp @@ -25,11 +25,15 @@ */ #include +#include +#include +#include namespace board { Thread miscThread; u8 fanLevel = 0; + PwmChannelSession *_iCon; void MiscThreadFunc(void *pwmCheckPtr) { Result pwmCheck = *static_cast(pwmCheckPtr); @@ -38,7 +42,7 @@ namespace board { while (true) { if (R_SUCCEEDED(pwmCheck)) { - if (R_SUCCEEDED(pwmChannelSessionGetDutyCycle(&g_ICon, &temp))) { + if (R_SUCCEEDED(pwmChannelSessionGetDutyCycle(_iCon, &temp))) { temp *= 10; temp = trunc(temp); temp /= 10; @@ -46,7 +50,7 @@ namespace board { } } - fanLevel = static_cast(Rotation_Duty); + fanLevel = static_cast(rotationDuty); svcSleepThread(300'000'000); } } @@ -55,7 +59,8 @@ namespace board { return fanLevel; } - void StartMiscThread(Result pwmCheck) { + void StartMiscThread(Result pwmCheck, PwmChannelSession *iCon) { + _iCon = iCon; threadCreate(&miscThread, MiscThreadFunc, &pwmCheck, NULL, 0x1000, 0x10, 3); threadStart(&miscThread); } diff --git a/Source/rewrite-hoc-clk/sysmodule/src/board/board_misc.hpp b/Source/rewrite-hoc-clk/sysmodule/src/board/board_misc.hpp index 15421d45..794902eb 100644 --- a/Source/rewrite-hoc-clk/sysmodule/src/board/board_misc.hpp +++ b/Source/rewrite-hoc-clk/sysmodule/src/board/board_misc.hpp @@ -28,10 +28,11 @@ #include #include +#include namespace board { - void StartMiscThread(Result pwmCheck); + void StartMiscThread(Result pwmCheck, PwmChannelSession *iCon); void ExitMiscThread(); u8 GetFanLevel(); diff --git a/Source/rewrite-hoc-clk/sysmodule/src/board/board_name.cpp b/Source/rewrite-hoc-clk/sysmodule/src/board/board_name.cpp index ca1e51d5..f7a17f03 100644 --- a/Source/rewrite-hoc-clk/sysmodule/src/board/board_name.cpp +++ b/Source/rewrite-hoc-clk/sysmodule/src/board/board_name.cpp @@ -26,6 +26,7 @@ #include #include +#include "board.hpp" namespace board { @@ -44,4 +45,9 @@ namespace board { return sysclkFormatThermalSensor(sensor, pretty); } + const char *GetPowerSensorName(SysClkPowerSensor sensor, bool pretty) { + ASSERT_ENUM_VALID(SysClkPowerSensor, sensor); + return sysclkFormatPowerSensor(sensor, pretty); + } + } diff --git a/Source/rewrite-hoc-clk/sysmodule/src/board/board_name.hpp b/Source/rewrite-hoc-clk/sysmodule/src/board/board_name.hpp index c2c4f29d..3699241e 100644 --- a/Source/rewrite-hoc-clk/sysmodule/src/board/board_name.hpp +++ b/Source/rewrite-hoc-clk/sysmodule/src/board/board_name.hpp @@ -33,5 +33,6 @@ namespace board { const char *GetModuleName(SysClkModule module, bool pretty); const char *GetProfileName(SysClkProfile profile, bool pretty); const char *GetThermalSensorName(SysClkThermalSensor sensor, bool pretty); + const char *GetPowerSensorName(SysClkPowerSensor sensor, bool pretty); } diff --git a/Source/rewrite-hoc-clk/sysmodule/src/board/board_profile.cpp b/Source/rewrite-hoc-clk/sysmodule/src/board/board_profile.cpp index 8c86828f..7d383fba 100644 --- a/Source/rewrite-hoc-clk/sysmodule/src/board/board_profile.cpp +++ b/Source/rewrite-hoc-clk/sysmodule/src/board/board_profile.cpp @@ -27,6 +27,7 @@ #include #include #include +#include "board.hpp" namespace board { diff --git a/Source/rewrite-hoc-clk/sysmodule/src/board/board_sensor.cpp b/Source/rewrite-hoc-clk/sysmodule/src/board/board_sensor.cpp index 955a1b38..df5ad87b 100644 --- a/Source/rewrite-hoc-clk/sysmodule/src/board/board_sensor.cpp +++ b/Source/rewrite-hoc-clk/sysmodule/src/board/board_sensor.cpp @@ -24,17 +24,19 @@ * -------------------------------------------------------------------------- */ -#pragma once #include #include #include -#include +#include +#include +#include #include "board.hpp" namespace board { u32 GetTemperatureMilli(SysClkThermalSensor sensor) { - u32 millis = 0; + s32 millis = 0; + BatteryChargeInfo info; if (sensor == SysClkThermalSensor_SOC) { millis = tmp451TempSoc(); diff --git a/Source/rewrite-hoc-clk/sysmodule/src/board/board_volt.cpp b/Source/rewrite-hoc-clk/sysmodule/src/board/board_volt.cpp index d1c8b886..e9be3112 100644 --- a/Source/rewrite-hoc-clk/sysmodule/src/board/board_volt.cpp +++ b/Source/rewrite-hoc-clk/sysmodule/src/board/board_volt.cpp @@ -29,6 +29,8 @@ #include #include #include +#include +#include #include "board.hpp" #include "board_freq.hpp" #include "board_volt.hpp" @@ -45,14 +47,14 @@ namespace board { struct EristaCpuUvEntry { u32 tune0; u32 tune1; - } EristaCpuUvEntry; + }; struct MarikoCpuUvEntry { u32 tune0_low; u32 tune0_high; u32 tune1_low; u32 tune1_high; - } MarikoCpuUvEntry; + }; EristaCpuUvEntry eristaCpuUvTable[5] = { {0xffff, 0x27007ff}, @@ -95,23 +97,23 @@ namespace board { void CacheDfllData() { u64 temp; - rc = svcQueryMemoryMapping(&cldvfs, &temp, CLDVFS_REGION_BASE, CLDVFS_REGION_SIZE); + Result rc = svcQueryMemoryMapping(&cldvfs, &temp, CLDVFS_REGION_BASE, CLDVFS_REGION_SIZE); ASSERT_RESULT_OK(rc, "svcQueryMemoryMapping (cldvfs)"); if (GetSocType() == SysClkSocType_Erista) { - cachedTune.tune0Low = *static_cast(cldvfs + CL_DVFS_TUNE0_0); - cachedTune.tune1Low = *static_cast(cldvfs + CL_DVFS_TUNE1_0); + cachedTune.tune0Low = *reinterpret_cast(cldvfs + CL_DVFS_TUNE0_0); + cachedTune.tune1Low = *reinterpret_cast(cldvfs + CL_DVFS_TUNE1_0); } else { SetHz(SysClkModule_CPU, 1785000000); - cachedTune.tune0High = *static_cast(cldvfs + CL_DVFS_TUNE0_0); + cachedTune.tune0High = *reinterpret_cast(cldvfs + CL_DVFS_TUNE0_0); ResetToStockCpu(); } } /* TODO: clean up this code. */ void SetDfllTunings(u32 levelLow, u32 levelHigh, u32 tbreakPoint) { - u32* tune0_ptr = static_cast(cldvfs + CL_DVFS_TUNE0_0); - u32* tune1_ptr = static_cast(cldvfs + CL_DVFS_TUNE1_0); + u32* tune0_ptr = reinterpret_cast(cldvfs + CL_DVFS_TUNE0_0); + u32* tune1_ptr = reinterpret_cast(cldvfs + CL_DVFS_TUNE1_0); if (GetSocType() == SysClkSocType_Mariko) { if (GetHz(SysClkModule_CPU) < tbreakPoint && (levelLow || levelHigh)) { if (levelLow) { @@ -253,10 +255,10 @@ namespace board { rc = rgltrOpenSession(&session, PcvPowerDomainId_Max77621_Gpu); } else { rc = rgltrOpenSession(&session, PcvPowerDomainId_Max77812_Gpu); - ASSERT_RESULT_OK(rc, "rgltrOpenSession") - rgltrGetVoltage(&session, &out); - rgltrCloseSession(&session); } + ASSERT_RESULT_OK(rc, "rgltrOpenSession") + rgltrGetVoltage(&session, &out); + rgltrCloseSession(&session); break; case HocClkVoltage_EMCVDDQ_MarikoOnly: if (GetSocType() == SysClkSocType_Mariko) { @@ -327,9 +329,9 @@ namespace board { void CacheGpuVoltTable() { UnkRegulator reg = { - .voltageMinUV = 600000, - .voltageStep = 12500, - .voltageMax = 1400000, + .voltageMin = 600000, + .voltageStep = 12500, + .voltageMax = 1400000, }; Handle handle = GetPcvHandle(); @@ -417,7 +419,7 @@ namespace board { return; } - Result rc = svcWriteDebugProcessMemory(handle, table, voltData.dvfsAddress, sizeof(table)); + Result rc = svcWriteDebugProcessMemory(handle, table, voltData.voltTableAddress, sizeof(table)); if (R_SUCCEEDED(rc)) { voltData.ramVmin = vmin; @@ -441,7 +443,7 @@ namespace board { return 0; } - for (u32 i = 0; i < std::size(gpuDvfsArray); ++i) { + for (u32 i = 0; i < std::size(gpuVoltArray); ++i) { if (freqMhz <= ramTable[bracket][i]) { return gpuVoltArray[i]; } diff --git a/Source/rewrite-hoc-clk/sysmodule/src/board/board_volt.hpp b/Source/rewrite-hoc-clk/sysmodule/src/board/board_volt.hpp index 9bed0117..a7e2fbde 100644 --- a/Source/rewrite-hoc-clk/sysmodule/src/board/board_volt.hpp +++ b/Source/rewrite-hoc-clk/sysmodule/src/board/board_volt.hpp @@ -38,7 +38,7 @@ namespace board { /* TODO: Find out what component this actually targets. */ struct UnkRegulator { - u32 voltageMinUV; + u32 voltageMin; u32 voltageStep; u32 voltageMax; }; @@ -53,8 +53,9 @@ namespace board { // u64 dvco_calibration_max; }; + void SetDfllTunings(u32 levelLow, u32 levelHigh, u32 tbreakPoint); void CacheDfllData(); - u32 CalculateTbreak(); + u32 CalculateTbreak(u32 table); u32 GetVoltage(HocClkVoltage voltage); void CacheGpuVoltTable(); void PcvHijackGpuVolts(u32 vmin); diff --git a/Source/rewrite-hoc-clk/sysmodule/src/clock_manager.cpp b/Source/rewrite-hoc-clk/sysmodule/src/clock_manager.cpp index a05aa637..4a9b4e50 100644 --- a/Source/rewrite-hoc-clk/sysmodule/src/clock_manager.cpp +++ b/Source/rewrite-hoc-clk/sysmodule/src/clock_manager.cpp @@ -28,8 +28,8 @@ #include "clock_manager.h" #include #include "file_utils.h" -#include "board.h" -#include "process_management.h" +#include "board/board.hpp" +#include "process_management.hpp" #include "errors.h" #include "ipc_service.h" #include "kip.h" @@ -61,6 +61,7 @@ u32 initialConfigValues[SysClkConfigValue_EnumMax]; // initial config. used for bool kipAvailable = false; bool isCpuGovernorInBoostMode = false; bool isVRREnabled = false; + ClockManager *ClockManager::GetInstance() { return instance; @@ -136,14 +137,20 @@ ClockManager::ClockManager() -2 ); - for(int i = 0; i < HorizonOCSpeedo_EnumMax; i++) { - this->context->speedos[i] = Board::getSpeedo((HorizonOCSpeedo)i); - this->context->iddq[i] = Board::getIDDQ((HorizonOCSpeedo)i); - } + board::FuseData *fuse = board::GetFuseData(); - this->context->dramID = Board::GetDramID(); - this->context->isDram8GB = Board::IsDram8GB(); - Board::SetGpuSchedulingMode((GpuSchedulingMode)this->config->GetConfigValue(HorizonOCConfigValue_GPUScheduling), (GpuSchedulingOverrideMethod)this->config->GetConfigValue(HorizonOCConfigValue_GPUSchedulingMethod)); + this->context->speedos[0] = fuse->cpuSpeedo; + this->context->speedos[1] = fuse->gpuSpeedo; + this->context->speedos[2] = fuse->socSpeedo; + this->context->iddq[0] = fuse->cpuIDDQ; + this->context->iddq[1] = fuse->gpuIDDQ; + this->context->iddq[2] = fuse->socIDDQ; + this->context->waferX = fuse->waferX; + this->context->waferY = fuse->waferY; + + this->context->dramID = board::GetDramID(); + this->context->isDram8GB = board::IsDram8GB(); + board::SetGpuSchedulingMode((GpuSchedulingMode)this->config->GetConfigValue(HorizonOCConfigValue_GPUScheduling), (GpuSchedulingOverrideMethod)this->config->GetConfigValue(HorizonOCConfigValue_GPUSchedulingMethod)); this->context->gpuSchedulingMode = (GpuSchedulingMode)this->config->GetConfigValue(HorizonOCConfigValue_GPUScheduling); this->context->isSysDockInstalled = this->sysDockIntegration->getCurrentSysDockState(); @@ -152,6 +159,7 @@ ClockManager::ClockManager() this->saltyNXIntegration->LoadSaltyNX(); } + this->context->isUsingRetroSuper = board::IsUsingRetroSuperDisplay(); threadStart(&cpuGovernorTHREAD); threadStart(&gpuGovernorTHREAD); @@ -224,7 +232,7 @@ std::uint32_t ClockManager::GetMaxAllowedHz(SysClkModule module, SysClkProfile p { if (profile < SysClkProfile_HandheldCharging) { - switch(Board::GetSocType()) { + switch (board::GetSocType()) { case SysClkSocType_Erista: return 460800000; case SysClkSocType_Mariko: @@ -244,7 +252,7 @@ std::uint32_t ClockManager::GetMaxAllowedHz(SysClkModule module, SysClkProfile p } else if (profile <= SysClkProfile_HandheldChargingUSB) { - switch(Board::GetSocType()) { + switch(board::GetSocType()) { case SysClkSocType_Erista: return 768000000; case SysClkSocType_Mariko: @@ -263,7 +271,7 @@ std::uint32_t ClockManager::GetMaxAllowedHz(SysClkModule module, SysClkProfile p } } } else if(module == SysClkModule_CPU) { - if(profile < SysClkProfile_HandheldCharging && Board::GetSocType() == SysClkSocType_Erista) { + if(profile < SysClkProfile_HandheldCharging && board::GetSocType() == SysClkSocType_Erista) { return 1581000000; } else { return ~0; @@ -317,8 +325,8 @@ void ClockManager::RefreshFreqTableRow(SysClkModule module) std::uint32_t freqs[SYSCLK_FREQ_LIST_MAX]; std::uint32_t count; - FileUtils::LogLine("[mgr] %s freq list refresh", Board::GetModuleName(module, true)); - Board::GetFreqList(module, &freqs[0], SYSCLK_FREQ_LIST_MAX, &count); + FileUtils::LogLine("[mgr] %s freq list refresh", board::GetModuleName(module, true)); + board::GetFreqList(module, &freqs[0], SYSCLK_FREQ_LIST_MAX, &count); std::uint32_t *hz = &this->freqTable[module].list[0]; this->freqTable[module].count = 0; @@ -369,7 +377,8 @@ void ClockManager::CpuGovernorThread(void* arg) { u32 downHoldRemaining = 0; u32 lastHz = 0; - + u32 minHz = 612; + u32 tick = 0; for (;;) { if (!mgr->running || !isCpuGovernorEnabled) { downHoldRemaining = 0; @@ -397,7 +406,7 @@ void ClockManager::CpuGovernorThread(void* arg) { std::scoped_lock lock{mgr->contextMutex}; - u32 cpuLoad = Board::GetPartLoad(HocClkPartLoad_CPUMax); + u32 cpuLoad = board::GetPartLoad(HocClkPartLoad_CPUMax); u32 tableMaxHz = table.list[table.count - 1]; u32 desiredHz = ClockManager::SchedutilTargetHz(cpuLoad, tableMaxHz); @@ -423,8 +432,16 @@ void ClockManager::CpuGovernorThread(void* arg) { if (downHoldRemaining > 0) downHoldRemaining--; + if(++tick > 50) { + minHz = mgr->config->GetConfigValue(HorizonOCConfigValue_CpuGovernorMinimumFreq); + tick = 0; + } + + if(newHz < minHz) + newHz = minHz; + if ((!goingDown || (downHoldRemaining == 0)) && mgr->IsAssignableHz(SysClkModule_CPU, newHz)) { - Board::SetHz(SysClkModule_CPU, newHz); + board::SetHz(SysClkModule_CPU, newHz); mgr->context->freqs[SysClkModule_CPU] = newHz; lastHz = newHz; } @@ -453,7 +470,7 @@ void ClockManager::GovernorThread(void* arg) { std::scoped_lock lock{mgr->contextMutex}; - u32 gpuLoad = Board::GetPartLoad(HocClkPartLoad_GPU); + u32 gpuLoad = board::GetPartLoad(HocClkPartLoad_GPU); u32 tableMaxHz = table.list[table.count - 1]; u32 desiredHz = ClockManager::SchedutilTargetHz(gpuLoad, tableMaxHz); u32 targetHz = ClockManager::ResolveTargetHz(mgr, SysClkModule_GPU); @@ -477,7 +494,7 @@ void ClockManager::GovernorThread(void* arg) { downHoldRemaining--; if ((!goingDown || (downHoldRemaining == 0)) && mgr->IsAssignableHz(SysClkModule_GPU, newHz)) { - Board::SetHz(SysClkModule_GPU, newHz); + board::SetHz(SysClkModule_GPU, newHz); mgr->context->freqs[SysClkModule_GPU] = newHz; lastHz = newHz; } @@ -495,11 +512,6 @@ void ClockManager::VRRThread(void* arg) { continue; } - if(Board::IsHoag()) { // don't do anything on lite - svcSleepThread(~0ULL); - continue; - } - std::scoped_lock lock{mgr->contextMutex}; u8 fps; @@ -517,7 +529,7 @@ void ClockManager::VRRThread(void* arg) { continue; } // if(appletGetFocusState() != AppletFocusState_InFocus) { - // Board::ResetToStockDisplay(); + // board::ResetToStockDisplay(); // continue; // } @@ -533,46 +545,49 @@ void ClockManager::VRRThread(void* arg) { if(targetHz) { maxDisplay = targetHz; } else { - maxDisplay = 60; + maxDisplay = 60; // don't assume display stuff! } - u8 minDisplay = Board::GetConsoleType() == HorizonOCConsoleType_Aula ? 45 : 40; + u8 minDisplay = board::GetConsoleType() == HorizonOCConsoleType_Aula ? 45 : 40; if(maxDisplay == minDisplay) continue; - if(fps >= minDisplay && fps <= maxDisplay) - Board::SetHz(HorizonOCModule_Display, fps); - else { + if(fps >= minDisplay && fps <= maxDisplay) { + board::SetHz(HorizonOCModule_Display, fps); + mgr->context->freqs[HorizonOCModule_Display] = fps; + mgr->context->realFreqs[HorizonOCModule_Display] = fps; + } else { for(u32 i = 0; i < 10; i++) { u32 compareHz = fps * i; if(compareHz >= minDisplay && compareHz <= maxDisplay) { - Board::SetHz(HorizonOCModule_Display, compareHz); + board::SetHz(HorizonOCModule_Display, compareHz); + mgr->context->freqs[HorizonOCModule_Display] = compareHz; + mgr->context->realFreqs[HorizonOCModule_Display] = compareHz; break; } } } + + if(++tick > 50) { - Board::ResetToStockDisplay(); + board::SetHz(HorizonOCModule_Display, maxDisplay); tick = 0; - svcSleepThread(25'000'000); + svcSleepThread(50'000'000); } svcSleepThread(POLL_NS); } } - - void ClockManager::HandleSafetyFeatures() { - AppletOperationMode opMode = appletGetOperationMode(); - if(this->config->GetConfigValue(HocClkConfigValue_HandheldTDP) && opMode == AppletOperationMode_Handheld) { - if(Board::GetConsoleType() == HorizonOCConsoleType_Hoag) { - if(Board::GetPowerMw(SysClkPowerSensor_Avg) < -(int)this->config->GetConfigValue(HocClkConfigValue_LiteTDPLimit)) { + if(this->config->GetConfigValue(HocClkConfigValue_HandheldTDP) && (this->context->profile != SysClkProfile_Docked)) { // Enable while charging as non-PD charger can cause lack of power + if (board::GetConsoleType() == HorizonOCConsoleType_Hoag) { + if (board::GetPowerMw(SysClkPowerSensor_Avg) < - this->config->GetConfigValue(HocClkConfigValue_LiteTDPLimit)) { ResetToStockClocks(); return; } } else { - if(Board::GetPowerMw(SysClkPowerSensor_Avg) < -(int)this->config->GetConfigValue(HocClkConfigValue_HandheldTDPLimit)) { + if(board::GetPowerMw(SysClkPowerSensor_Avg) < - this->config->GetConfigValue(HocClkConfigValue_HandheldTDPLimit)) { ResetToStockClocks(); return; } @@ -620,15 +635,15 @@ void ClockManager::HandleGovernor(uint32_t targetHz) { if(newCpuGovernorState == false && lastCpuGovernorState == true) { svcSleepThread(100'000'000); // thread syncing. probably a cleaner way to do this but hey, it works! - Board::ResetToStockCpu(); + board::ResetToStockCpu(); } if(newGpuGovernorState == false && lastGpuGovernorState == true) { svcSleepThread(100'000'000); - Board::ResetToStockGpu(); + board::ResetToStockGpu(); } if (newVrrGovernorState == false && lastVrrGovernorState == true) { svcSleepThread(100'000'000); - Board::ResetToStockDisplay(); + board::ResetToStockDisplay(); } if(newCpuGovernorState != lastCpuGovernorState || newGpuGovernorState != lastGpuGovernorState || newVrrGovernorState != lastVrrGovernorState) { FileUtils::LogLine("[mgr] Governor state changed: CPU %s, GPU %s, VRR %s", newCpuGovernorState ? "enabled" : "disabled", newGpuGovernorState ? "enabled" : "disabled", newVrrGovernorState ? "enabled" : "disabled"); @@ -640,9 +655,9 @@ void ClockManager::HandleGovernor(uint32_t targetHz) { void ClockManager::DVFSBeforeSet(u32 targetHz) { s32 dvfsOffset = this->config->GetConfigValue(HorizonOCConfigValue_DVFSOffset); - u32 vmin = Board::GetMinimumGpuVoltage(targetHz / 1000000) + dvfsOffset; + u32 vmin = board::GetMinimumGpuVmin(targetHz / 1000000, board::GetGpuSpeedoBracket()) + dvfsOffset; - Board::PcvHijackDvfs(vmin); + board::PcvHijackGpuVolts(vmin); /* Update the voltage. */ if (I2c_BuckConverter_GetMvOut(&I2c_Mariko_GPU) < vmin) { @@ -655,7 +670,7 @@ void ClockManager::DVFSBeforeSet(u32 targetHz) { void ClockManager::DVFSAfterSet(u32 targetHz) { s32 dvfsOffset = this->config->GetConfigValue(HorizonOCConfigValue_DVFSOffset); dvfsOffset = std::max(dvfsOffset, -80); - u32 vmin = Board::GetMinimumGpuVoltage(targetHz / 1000000); + u32 vmin = board::GetMinimumGpuVmin(targetHz / 1000000, board::GetGpuSpeedoBracket()); if (vmin) { vmin += dvfsOffset; @@ -663,27 +678,27 @@ void ClockManager::DVFSAfterSet(u32 targetHz) { u32 maxHz = this->GetMaxAllowedHz(SysClkModule_GPU, this->context->profile); u32 nearestHz = this->GetNearestHz(SysClkModule_GPU, targetHz, maxHz); - Board::PcvHijackDvfs(vmin); + board::PcvHijackGpuVolts(vmin); if (targetHz) { - Board::SetHz(SysClkModule_GPU, ~0); - Board::SetHz(SysClkModule_GPU, nearestHz); + board::SetHz(SysClkModule_GPU, ~0); + board::SetHz(SysClkModule_GPU, nearestHz); } else { - Board::SetHz(SysClkModule_GPU, ~0); - Board::ResetToStockGpu(); + board::SetHz(SysClkModule_GPU, ~0); + board::ResetToStockGpu(); } } void ClockManager::HandleCpuUv() { - if(Board::GetSocType() == SysClkSocType_Erista) - Board::SetCpuUvLevel(this->config->GetConfigValue(KipConfigValue_eristaCpuUV), 0, 1581000000); + if(board::GetSocType() == SysClkSocType_Erista) + board::SetDfllTunings(this->config->GetConfigValue(KipConfigValue_eristaCpuUV), 0, 1581000000); else - Board::SetCpuUvLevel(this->config->GetConfigValue(KipConfigValue_marikoCpuUVLow), this->config->GetConfigValue(KipConfigValue_marikoCpuUVHigh), Board::CalculateTbreak(this->config->GetConfigValue(KipConfigValue_tableConf))); + board::SetDfllTunings(this->config->GetConfigValue(KipConfigValue_marikoCpuUVLow), this->config->GetConfigValue(KipConfigValue_marikoCpuUVHigh), board::CalculateTbreak(this->config->GetConfigValue(KipConfigValue_tableConf))); } void ClockManager::DVFSReset() { - if (Board::GetSocType() == SysClkSocType_Mariko && this->config->GetConfigValue(HorizonOCConfigValue_DVFSMode) == DVFSMode_Hijack) { - Board::PcvHijackDvfs(0); + if (board::GetSocType() == SysClkSocType_Mariko && this->config->GetConfigValue(HorizonOCConfigValue_DVFSMode) == DVFSMode_Hijack) { + board::PcvHijackGpuVolts(0); u32 targetHz = this->context->overrideFreqs[SysClkModule_GPU]; if (!targetHz) { @@ -695,11 +710,11 @@ void ClockManager::DVFSReset() { u32 maxHz = this->GetMaxAllowedHz(SysClkModule_GPU, this->context->profile); u32 nearestHz = this->GetNearestHz(SysClkModule_GPU, targetHz, maxHz); - Board::SetHz(SysClkModule_GPU, ~0); + board::SetHz(SysClkModule_GPU, ~0); if(targetHz) { - Board::SetHz(SysClkModule_GPU, nearestHz); + board::SetHz(SysClkModule_GPU, nearestHz); } else { - Board::ResetToStockGpu(); + board::ResetToStockGpu(); } } } @@ -709,25 +724,25 @@ void ClockManager::HandleFreqReset(SysClkModule module, bool isBoost) { { case SysClkModule_CPU: if(!(isBoost || (this->config->GetConfigValue(HocClkConfigValue_OverwriteBoostMode) && isBoost))) - Board::ResetToStockCpu(); + board::ResetToStockCpu(); if(this->config->GetConfigValue(HorizonOCConfigValue_LiveCpuUv)) { - if(Board::GetSocType() == SysClkSocType_Erista) - Board::SetCpuUvLevel(this->config->GetConfigValue(KipConfigValue_eristaCpuUV), 0, 1581000000); + if(board::GetSocType() == SysClkSocType_Erista) + board::SetDfllTunings(this->config->GetConfigValue(KipConfigValue_eristaCpuUV), 0, 1581000000); else - Board::SetCpuUvLevel(this->config->GetConfigValue(KipConfigValue_marikoCpuUVLow), this->config->GetConfigValue(KipConfigValue_marikoCpuUVHigh), Board::CalculateTbreak(this->config->GetConfigValue(KipConfigValue_tableConf))); + board::SetDfllTunings(this->config->GetConfigValue(KipConfigValue_marikoCpuUVLow), this->config->GetConfigValue(KipConfigValue_marikoCpuUVHigh), board::CalculateTbreak(this->config->GetConfigValue(KipConfigValue_tableConf))); } break; case SysClkModule_GPU: - Board::ResetToStockGpu(); + board::ResetToStockGpu(); break; case SysClkModule_MEM: - Board::ResetToStockMem(); + board::ResetToStockMem(); DVFSReset(); break; case HorizonOCModule_Display: - if(this->config->GetConfigValue(HorizonOCConfigValue_OverwriteRefreshRate) && !Board::IsHoag()) { - Board::ResetToStockDisplay(); + if(this->config->GetConfigValue(HorizonOCConfigValue_OverwriteRefreshRate)) { + board::ResetToStockDisplay(); } break; default: @@ -742,9 +757,9 @@ void ClockManager::SetClocks(bool isBoost) { std::uint32_t nearestHz = 0; if(isBoost && !this->config->GetConfigValue(HocClkConfigValue_OverwriteBoostMode)) { - u32 boostFreq = Board::GetHz(SysClkModule_CPU); + u32 boostFreq = board::GetHz(SysClkModule_CPU); if (boostFreq / 1000000 > 1785) { - Board::SetHz(SysClkModule_CPU, boostFreq); + board::SetHz(SysClkModule_CPU, boostFreq); } return; // Return if we are't overwriting boost mode } @@ -752,7 +767,7 @@ void ClockManager::SetClocks(bool isBoost) { bool returnRaw = false; // Return a value scaled to MHz instead of raw value for (unsigned int module = 0; module < SysClkModule_EnumMax; module++) { - u32 oldHz = Board::GetHz((SysClkModule)module); // Get Old hz (used primarily for DVFS Logic) + u32 oldHz = board::GetHz((SysClkModule)module); // Get Old hz (used primarily for DVFS Logic) if(module > SysClkModule_MEM) returnRaw = true; @@ -772,17 +787,19 @@ void ClockManager::SetClocks(bool isBoost) { bool noCPU = isCpuGovernorEnabled; bool noGPU = isGpuGovernorEnabled; - if(!Board::IsHoag()) { - bool noDisp = isVRREnabled; - if(noDisp && module == HorizonOCModule_Display) - continue; + bool noDisp = isVRREnabled; + if(noDisp && module == HorizonOCModule_Display) + continue; - if(module == HorizonOCModule_Display && this->config->GetConfigValue(HorizonOCConfigValue_OverwriteRefreshRate)) { - if(targetHz) - Board::SetHz(HorizonOCModule_Display, targetHz); - else - Board::ResetToStockDisplay(); + if(module == HorizonOCModule_Display && this->config->GetConfigValue(HorizonOCConfigValue_OverwriteRefreshRate) && !noDisp) { + if(targetHz) { + board::SetHz(HorizonOCModule_Display, targetHz); + this->context->freqs[HorizonOCModule_Display] = targetHz; + this->context->realFreqs[HorizonOCModule_Display] = targetHz; + } else { + HandleFreqReset(HorizonOCModule_Display, isBoost); } + } // Skip GPU and CPU if governors handle them @@ -804,23 +821,23 @@ void ClockManager::SetClocks(bool isBoost) { if (nearestHz != this->context->freqs[module]) { FileUtils::LogLine( "[mgr] %s clock set : %u.%u MHz (target = %u.%u MHz)", - Board::GetModuleName((SysClkModule)module, true), + board::GetModuleName((SysClkModule)module, true), nearestHz / 1000000, nearestHz / 100000 - nearestHz / 1000000 * 10, targetHz / 1000000, targetHz / 100000 - targetHz / 1000000 * 10 ); - if(module == SysClkModule_MEM && Board::GetSocType() == SysClkSocType_Mariko && targetHz > oldHz && this->config->GetConfigValue(HorizonOCConfigValue_DVFSMode) == DVFSMode_Hijack) { + if(module == SysClkModule_MEM && board::GetSocType() == SysClkSocType_Mariko && targetHz > oldHz && this->config->GetConfigValue(HorizonOCConfigValue_DVFSMode) == DVFSMode_Hijack) { DVFSBeforeSet(targetHz); } - Board::SetHz((SysClkModule)module, nearestHz); + board::SetHz((SysClkModule)module, nearestHz); this->context->freqs[module] = nearestHz; if(module == SysClkModule_CPU && (this->config->GetConfigValue(HorizonOCConfigValue_LiveCpuUv))) { HandleCpuUv(); } - if(module == SysClkModule_MEM && Board::GetSocType() == SysClkSocType_Mariko && targetHz < oldHz && this->config->GetConfigValue(HorizonOCConfigValue_DVFSMode) == DVFSMode_Hijack) { + if(module == SysClkModule_MEM && board::GetSocType() == SysClkSocType_Mariko && targetHz < oldHz && this->config->GetConfigValue(HorizonOCConfigValue_DVFSMode) == DVFSMode_Hijack) { DVFSAfterSet(targetHz); } } @@ -850,21 +867,21 @@ void ClockManager::Tick() } void ClockManager::ResetToStockClocks() { - Board::ResetToStockCpu(); + board::ResetToStockCpu(); if(this->config->GetConfigValue(HorizonOCConfigValue_LiveCpuUv)) { - if(Board::GetSocType() == SysClkSocType_Erista) - Board::SetCpuUvLevel(this->config->GetConfigValue(KipConfigValue_eristaCpuUV), 0, 1581000000); + if(board::GetSocType() == SysClkSocType_Erista) + board::SetDfllTunings(this->config->GetConfigValue(KipConfigValue_eristaCpuUV), 0, 1581000000); else - Board::SetCpuUvLevel(this->config->GetConfigValue(KipConfigValue_marikoCpuUVLow), this->config->GetConfigValue(KipConfigValue_marikoCpuUVHigh), Board::CalculateTbreak(this->config->GetConfigValue(KipConfigValue_tableConf))); + board::SetDfllTunings(this->config->GetConfigValue(KipConfigValue_marikoCpuUVLow), this->config->GetConfigValue(KipConfigValue_marikoCpuUVHigh), board::CalculateTbreak(this->config->GetConfigValue(KipConfigValue_tableConf))); } - Board::ResetToStockGpu(); + board::ResetToStockGpu(); } void ClockManager::WaitForNextTick() { - if(!(Board::GetHz(SysClkModule_MEM) < 665000000)) + if(!(board::GetHz(SysClkModule_MEM) < 665000000)) svcSleepThread(this->GetConfig()->GetConfigValue(SysClkConfigValue_PollingIntervalMs) * 1000000ULL); else svcSleepThread(5000 * 1000000ULL); // 5 seconds in sleep mode @@ -878,7 +895,7 @@ bool ClockManager::RefreshContext() Result rc = apmExtGetCurrentPerformanceConfiguration(&mode); ASSERT_RESULT_OK(rc, "apmExtGetCurrentPerformanceConfiguration"); - std::uint64_t applicationId = ProcessManagement::GetCurrentApplicationId(); + std::uint64_t applicationId = processManagement::GetCurrentApplicationId(); if (applicationId != this->context->applicationId) { FileUtils::LogLine("[mgr] TitleID change: %016lX", applicationId); @@ -886,10 +903,10 @@ bool ClockManager::RefreshContext() hasChanged = true; } - SysClkProfile profile = Board::GetProfile(); + SysClkProfile profile = board::GetProfile(); if (profile != this->context->profile) { - FileUtils::LogLine("[mgr] Profile change: %s", Board::GetProfileName(profile, true)); + FileUtils::LogLine("[mgr] Profile change: %s", board::GetProfileName(profile, true)); this->context->profile = profile; hasChanged = true; } @@ -897,11 +914,11 @@ bool ClockManager::RefreshContext() // restore clocks to stock values on app or profile change if (hasChanged) { - Board::ResetToStock(); - if (Board::GetSocType() == SysClkSocType_Mariko && this->config->GetConfigValue(HorizonOCConfigValue_DVFSMode) == DVFSMode_Hijack) { - Board::PcvHijackDvfs(0); - Board::SetHz(SysClkModule_GPU, ~0); - Board::ResetToStockGpu(); + board::ResetToStock(); + if (board::GetSocType() == SysClkSocType_Mariko && this->config->GetConfigValue(HorizonOCConfigValue_DVFSMode) == DVFSMode_Hijack) { + board::PcvHijackGpuVolts(0); + board::SetHz(SysClkModule_GPU, ~0); + board::ResetToStockGpu(); } this->WaitForNextTick(); } @@ -909,10 +926,10 @@ bool ClockManager::RefreshContext() std::uint32_t hz = 0; for (unsigned int module = 0; module < SysClkModule_EnumMax; module++) { - hz = Board::GetHz((SysClkModule)module); + hz = board::GetHz((SysClkModule)module); if (hz != 0 && hz != this->context->freqs[module]) { - FileUtils::LogLine("[mgr] %s clock change: %u.%u MHz", Board::GetModuleName((SysClkModule)module, true), hz / 1000000, hz / 100000 - hz / 1000000 * 10); + FileUtils::LogLine("[mgr] %s clock change: %u.%u MHz", board::GetModuleName((SysClkModule)module, true), hz / 1000000, hz / 100000 - hz / 1000000 * 10); this->context->freqs[module] = hz; hasChanged = true; } @@ -922,7 +939,7 @@ bool ClockManager::RefreshContext() { if (hz) { - FileUtils::LogLine("[mgr] %s override change: %u.%u MHz", Board::GetModuleName((SysClkModule)module, true), hz / 1000000, hz / 100000 - hz / 1000000 * 10); + FileUtils::LogLine("[mgr] %s override change: %u.%u MHz", board::GetModuleName((SysClkModule)module, true), hz / 1000000, hz / 100000 - hz / 1000000 * 10); } this->context->overrideFreqs[module] = hz; hasChanged = true; @@ -936,10 +953,10 @@ bool ClockManager::RefreshContext() bool shouldLogTemp = this->ConfigIntervalTimeout(SysClkConfigValue_TempLogIntervalMs, ns, &this->lastTempLogNs); for (unsigned int sensor = 0; sensor < SysClkThermalSensor_EnumMax; sensor++) { - millis = Board::GetTemperatureMilli((SysClkThermalSensor)sensor); + millis = board::GetTemperatureMilli((SysClkThermalSensor)sensor); if (shouldLogTemp) { - FileUtils::LogLine("[mgr] %s temp: %u.%u °C", Board::GetThermalSensorName((SysClkThermalSensor)sensor, true), millis / 1000, (millis - millis / 1000 * 1000) / 100); + FileUtils::LogLine("[mgr] %s temp: %u.%u °C", board::GetThermalSensorName((SysClkThermalSensor)sensor, true), millis / 1000, (millis - millis / 1000 * 1000) / 100); } this->context->temps[sensor] = millis; } @@ -949,10 +966,10 @@ bool ClockManager::RefreshContext() bool shouldLogPower = this->ConfigIntervalTimeout(SysClkConfigValue_PowerLogIntervalMs, ns, &this->lastPowerLogNs); for (unsigned int sensor = 0; sensor < SysClkPowerSensor_EnumMax; sensor++) { - mw = Board::GetPowerMw((SysClkPowerSensor)sensor); + mw = board::GetPowerMw((SysClkPowerSensor)sensor); if (shouldLogPower) { - FileUtils::LogLine("[mgr] Power %s: %d mW", Board::GetPowerSensorName((SysClkPowerSensor)sensor, false), mw); + FileUtils::LogLine("[mgr] Power %s: %d mW", board::GetPowerSensorName((SysClkPowerSensor)sensor, false), mw); } this->context->power[sensor] = mw; } @@ -962,10 +979,10 @@ bool ClockManager::RefreshContext() bool shouldLogFreq = this->ConfigIntervalTimeout(SysClkConfigValue_FreqLogIntervalMs, ns, &this->lastFreqLogNs); for (unsigned int module = 0; module < SysClkModule_EnumMax; module++) { - realHz = Board::GetRealHz((SysClkModule)module); + realHz = board::GetRealHz((SysClkModule)module); if (shouldLogFreq) { - FileUtils::LogLine("[mgr] %s real freq: %u.%u MHz", Board::GetModuleName((SysClkModule)module, true), realHz / 1000000, realHz / 100000 - realHz / 1000000 * 10); + FileUtils::LogLine("[mgr] %s real freq: %u.%u MHz", board::GetModuleName((SysClkModule)module, true), realHz / 1000000, realHz / 100000 - realHz / 1000000 * 10); } this->context->realFreqs[module] = realHz; } @@ -973,12 +990,12 @@ bool ClockManager::RefreshContext() // ram load do not and should not force a refresh, hasChanged untouched for (unsigned int loadSource = 0; loadSource < SysClkPartLoad_EnumMax; loadSource++) { - this->context->partLoad[loadSource] = Board::GetPartLoad((SysClkPartLoad)loadSource); + this->context->partLoad[loadSource] = board::GetPartLoad((SysClkPartLoad)loadSource); } for (unsigned int voltageSource = 0; voltageSource < HocClkVoltage_EnumMax; voltageSource++) { - this->context->voltages[voltageSource] = Board::GetVoltage((HocClkVoltage)voltageSource); + this->context->voltages[voltageSource] = board::GetVoltage((HocClkVoltage)voltageSource); } if (this->ConfigIntervalTimeout(SysClkConfigValue_CsvWriteIntervalMs, ns, &this->lastCsvWriteNs)) @@ -986,21 +1003,22 @@ bool ClockManager::RefreshContext() FileUtils::WriteContextToCsv(this->context); } - // this->context->maxDisplayFreq = Board::GetHighestDockedDisplayRate(); - if(!Board::IsHoag()) { - u32 targetHz = this->context->overrideFreqs[HorizonOCModule_Display]; - if (!targetHz) - { - targetHz = this->config->GetAutoClockHz(this->context->applicationId, HorizonOCModule_Display, this->context->profile, true); - if(!targetHz) - targetHz = this->config->GetAutoClockHz(GLOBAL_PROFILE_ID, HorizonOCModule_Display, this->context->profile, true); - } - - if(targetHz && this->context->realFreqs[HorizonOCModule_Display] > targetHz && this->context->profile != SysClkProfile_Docked) - this->context->realFreqs[HorizonOCModule_Display] = targetHz; // clean up display real freqs, should probably be moved to the real freqs loop? - - Board::SetDisplayRefreshDockedState(this->context->profile == SysClkProfile_Docked); + // this->context->maxDisplayFreq = board::GetHighestDockedDisplayRate(); + u32 targetHz = this->context->overrideFreqs[HorizonOCModule_Display]; + if (!targetHz) + { + targetHz = this->config->GetAutoClockHz(this->context->applicationId, HorizonOCModule_Display, this->context->profile, true); + if(!targetHz) + targetHz = this->config->GetAutoClockHz(GLOBAL_PROFILE_ID, HorizonOCModule_Display, this->context->profile, true); } + + if(targetHz && this->context->realFreqs[HorizonOCModule_Display] > targetHz && this->context->profile != SysClkProfile_Docked) { + this->context->realFreqs[HorizonOCModule_Display] = targetHz; // clean up display real freqs, should probably be moved to the real freqs loop? + hasChanged = true; + } + + if(board::GetConsoleType() != HorizonOCConsoleType_Hoag) + board::SetDisplayRefreshDockedState(this->context->profile == SysClkProfile_Docked); if(this->context->isSaltyNXInstalled) this->context->fps = saltyNXIntegration->GetFPS(); else @@ -1016,7 +1034,7 @@ bool ClockManager::RefreshContext() void ClockManager::SetKipData() { // TODO: figure out if this REALLY causes issues (i doubt it) - // if(Board::GetSocType() == SysClkSocType_Mariko) { + // if(board::GetSocType() == SysClkSocType_Mariko) { // if(R_FAILED(I2c_BuckConverter_SetMvOut(&I2c_Mariko_DRAM_VDDQ, this->config->GetConfigValue(KipConfigValue_marikoEmcVddqVolt) / 1000))) { // FileUtils::LogLine("[clock_manager] Failed set i2c vddq"); // writeNotification("Horizon OC\nFailed to write I2C\nwhile setting vddq"); @@ -1259,7 +1277,7 @@ void ClockManager::GetKipData() { configValues.values[KipConfigValue_marikoGpuVmin] = cust_get_mariko_gpu_vmin(&table); configValues.values[KipConfigValue_marikoGpuVmax] = cust_get_mariko_gpu_vmax(&table); configValues.values[KipConfigValue_commonGpuVoltOffset] = cust_get_common_gpu_offset(&table); - configValues.values[KipConfigValue_gpuSpeedo] = Board::getSpeedo(HorizonOCSpeedo_GPU); // cust_get_gpu_speedo(&table); + configValues.values[KipConfigValue_gpuSpeedo] = board::GetFuseData()->gpuSpeedo; // cust_get_gpu_speedo(&table); for (int i = 0; i < 24; i++) { configValues.values[KipConfigValue_g_volt_76800 + i] = cust_get_mariko_gpu_volt(&table, i); diff --git a/Source/rewrite-hoc-clk/sysmodule/src/clock_manager.h b/Source/rewrite-hoc-clk/sysmodule/src/clock_manager.h index b09d10e1..9e195931 100644 --- a/Source/rewrite-hoc-clk/sysmodule/src/clock_manager.h +++ b/Source/rewrite-hoc-clk/sysmodule/src/clock_manager.h @@ -12,9 +12,9 @@ * * You should have received a copy of the GNU General Public License * along with this program. If not, see . - * + * */ - + /* -------------------------------------------------------------------------- * "THE BEER-WARE LICENSE" (Revision 42): * , , @@ -28,7 +28,6 @@ #include #include #include "config.h" -#include "board.h" #include #include "integrations.h" @@ -140,7 +139,7 @@ class ClockManager * @param isBoost Is in boost mode */ void SetClocks(bool isBoost); - + /** * Main function, runs every 5s in sleep mode, and a user specified amount when awake * diff --git a/Source/rewrite-hoc-clk/sysmodule/src/config.cpp b/Source/rewrite-hoc-clk/sysmodule/src/config.cpp index 06722105..31090152 100644 --- a/Source/rewrite-hoc-clk/sysmodule/src/config.cpp +++ b/Source/rewrite-hoc-clk/sysmodule/src/config.cpp @@ -12,9 +12,9 @@ * * You should have received a copy of the GNU General Public License * along with this program. If not, see . - * + * */ - + /* -------------------------------------------------------------------------- * "THE BEER-WARE LICENSE" (Revision 42): * , , @@ -215,9 +215,9 @@ bool Config::SetProfiles(std::uint64_t tid, SysClkTitleProfileList* profiles, bo { numProfiles++; - std::string key = std::string(Board::GetProfileName((SysClkProfile)profile, false)) + - "_" + - Board::GetModuleName((SysClkModule)module, false); + std::string key = std::string(board::GetProfileName((SysClkProfile)profile, false)) + + "_" + + board::GetModuleName((SysClkModule)module, false); std::string value = std::to_string(*mhz); keys.push_back(key); @@ -317,7 +317,7 @@ int Config::BrowseIniFunc(const char* section, const char* key, const char* valu for(unsigned int profile = 0; profile < SysClkProfile_EnumMax; profile++) { - const char* profileCode = Board::GetProfileName((SysClkProfile)profile, false); + const char* profileCode = board::GetProfileName((SysClkProfile)profile, false); size_t profileCodeLen = strlen(profileCode); if(!strncmp(key, profileCode, profileCodeLen) && key[profileCodeLen] == '_') @@ -326,7 +326,7 @@ int Config::BrowseIniFunc(const char* section, const char* key, const char* valu for(unsigned int module = 0; module < SysClkModule_EnumMax; module++) { - const char* moduleCode = Board::GetModuleName((SysClkModule)module, false); + const char* moduleCode = board::GetModuleName((SysClkModule)module, false); size_t moduleCodeLen = strlen(moduleCode); if(!strncmp(subkey, moduleCode, moduleCodeLen) && subkey[moduleCodeLen] == '\0') { @@ -426,13 +426,13 @@ bool Config::SetConfigValues(SysClkConfigValueList* configValues, bool immediate std::vector iniKeys; std::vector iniValues; - + iniKeys.reserve(SysClkConfigValue_EnumMax + 1); iniValues.reserve(SysClkConfigValue_EnumMax); for(unsigned int kval = 0; kval < SysClkConfigValue_EnumMax; kval++) { - if(!sysclkValidConfigValue((SysClkConfigValue)kval, configValues->values[kval]) || + if(!sysclkValidConfigValue((SysClkConfigValue)kval, configValues->values[kval]) || configValues->values[kval] == sysclkDefaultConfigValue((SysClkConfigValue)kval)) { continue; @@ -490,12 +490,12 @@ bool Config::ResetConfigValue(SysClkConfigValue kval) std::vector iniKeys; std::vector iniValues; - + iniKeys.reserve(2); iniValues.reserve(1); const char* keyStr = sysclkFormatConfigValue(kval, false); - + iniKeys.push_back(keyStr); iniValues.push_back(""); @@ -515,6 +515,6 @@ bool Config::ResetConfigValue(SysClkConfigValue kval) this->configValues[kval] = defaultValue; FileUtils::LogLine("[cfg] Reset config value %u to default: %llu", kval, defaultValue); - + return true; } \ No newline at end of file diff --git a/Source/rewrite-hoc-clk/sysmodule/src/config.h b/Source/rewrite-hoc-clk/sysmodule/src/config.h index 23a72acf..28ded8f5 100644 --- a/Source/rewrite-hoc-clk/sysmodule/src/config.h +++ b/Source/rewrite-hoc-clk/sysmodule/src/config.h @@ -12,9 +12,9 @@ * * You should have received a copy of the GNU General Public License * along with this program. If not, see . - * + * */ - + /* -------------------------------------------------------------------------- * "THE BEER-WARE LICENSE" (Revision 42): * , , @@ -35,7 +35,7 @@ #include #include #include -#include "board.h" +#include "board/board.hpp" #define CONFIG_VAL_SECTION "values" diff --git a/Source/rewrite-hoc-clk/sysmodule/src/integrations.cpp b/Source/rewrite-hoc-clk/sysmodule/src/integrations.cpp index 64077895..d088c5e8 100644 --- a/Source/rewrite-hoc-clk/sysmodule/src/integrations.cpp +++ b/Source/rewrite-hoc-clk/sysmodule/src/integrations.cpp @@ -12,14 +12,14 @@ * * You should have received a copy of the GNU General Public License * along with this program. If not, see . - * + * */ - + #include "integrations.h" #include #include -#include "process_management.h" +#include "process_management.hpp" SysDockIntegration::SysDockIntegration() { } @@ -42,10 +42,10 @@ bool SaltyNXIntegration::getCurrentSaltyNXState() { struct stat st = {0}; return stat("sdmc:/atmosphere/contents/0000000000534C56/flags/boot2.flag", &st) == 0; } - + bool SaltyNXIntegration::CheckPort() { Handle saltysd; - + for (int i = 0; i < 67; i++) { if (R_SUCCEEDED(svcConnectToNamedPort(&saltysd, "InjectServ"))) { svcCloseHandle(saltysd); @@ -54,7 +54,7 @@ bool SaltyNXIntegration::CheckPort() { if (i == 66) return false; svcSleepThread(1'000'000); } - + for (int i = 0; i < 67; i++) { if (R_SUCCEEDED(svcConnectToNamedPort(&saltysd, "InjectServ"))) { svcCloseHandle(saltysd); @@ -62,10 +62,10 @@ bool SaltyNXIntegration::CheckPort() { } svcSleepThread(1'000'000); } - + return false; } - + void SaltyNXIntegration::LoadSharedMemory() { if (SaltySD_Connect()) return; @@ -75,7 +75,7 @@ void SaltyNXIntegration::LoadSharedMemory() { if (!shmemMap(&_sharedmemory)) SharedMemoryUsed = true; } - + void SaltyNXIntegration::searchSharedMemoryBlock(uintptr_t base) { ptrdiff_t search_offset = 0; while (search_offset < 0x1000) { @@ -86,38 +86,38 @@ void SaltyNXIntegration::searchSharedMemoryBlock(uintptr_t base) { } NxFps = 0; } - + u64 prevTid = 0; u8 SaltyNXIntegration::GetFPS() { if (!SharedMemoryUsed) return 254; - - u64 tid = ProcessManagement::GetCurrentApplicationId(); + + u64 tid = processManagement::GetCurrentApplicationId(); if (tid == 0) return 254; - + if (prevTid != tid) { NxFps = 0; prevTid = tid; } - + if (!NxFps) { uintptr_t base = (uintptr_t)shmemGetAddr(&_sharedmemory); searchSharedMemoryBlock(base); } - + return NxFps ? NxFps->FPS : 254; } u16 SaltyNXIntegration::GetResolutionHeight() { if (!SharedMemoryUsed) return 0; - - u64 tid = ProcessManagement::GetCurrentApplicationId(); + + u64 tid = processManagement::GetCurrentApplicationId(); if (tid == 0) return 0; - + if (prevTid != tid) { NxFps = 0; prevTid = tid; @@ -130,7 +130,7 @@ u16 SaltyNXIntegration::GetResolutionHeight() { if(NxFps) { NxFps->renderCalls[0].calls = 0xFFFF; svcSleepThread(10*1000); - + return NxFps->renderCalls[0].height == 0 ? NxFps->viewportCalls[0].height : NxFps->renderCalls[0].height; } return 0; diff --git a/Source/rewrite-hoc-clk/sysmodule/src/main.cpp b/Source/rewrite-hoc-clk/sysmodule/src/main.cpp index 6249172c..3e1e039b 100644 --- a/Source/rewrite-hoc-clk/sysmodule/src/main.cpp +++ b/Source/rewrite-hoc-clk/sysmodule/src/main.cpp @@ -32,8 +32,8 @@ #include "errors.h" #include "file_utils.h" -#include "board.h" -#include "process_management.h" +#include "board/board.hpp" +#include "process_management.hpp" #include "clock_manager.h" #include "ipc_service.h" #define INNER_HEAP_SIZE 0x40000 @@ -65,7 +65,7 @@ extern "C" fake_heap_start = (char*)addr; fake_heap_end = (char*)addr + size; - + virtmemSetup(); } @@ -120,10 +120,10 @@ int main(int argc, char** argv) try { - Board::Initialize(); - ProcessManagement::Initialize(); + board::Initialize(); + processManagement::Initialize(); - ProcessManagement::WaitForQLaunch(); + processManagement::WaitForQLaunch(); ClockManager* clockMgr = new ClockManager(); IpcService* ipcSrv = new IpcService(clockMgr); @@ -147,8 +147,8 @@ int main(int argc, char** argv) ipcSrv->SetRunning(false); delete ipcSrv; delete clockMgr; - ProcessManagement::Exit(); - Board::Exit(); + processManagement::Exit(); + board::Exit(); } catch (const std::exception &ex) { diff --git a/Source/rewrite-hoc-clk/sysmodule/src/old_board.cpp b/Source/rewrite-hoc-clk/sysmodule/src/old_board.cpp deleted file mode 100644 index 7c59fdb3..00000000 --- a/Source/rewrite-hoc-clk/sysmodule/src/old_board.cpp +++ /dev/null @@ -1,1328 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - -// Note: Hoag crashes on display refresh rate init while in sleep mode - -#include -#include "board.h" -#include "errors.h" -#include "rgltr.h" -#include "file_utils.h" -#include // for std::clamp -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define MAX(A, B) std::max(A, B) -#define MIN(A, B) std::min(A, B) -#define CEIL(A) std::ceil(A) -#define FLOOR(A) std::floor(A) -#define ROUND(A) std::lround(A) - - -#define FUSE_CPU_SPEEDO_0_CALIB 0x114 -//#define FUSE_CPU_SPEEDO_1_CALIB 0x12C -#define FUSE_CPU_SPEEDO_2_CALIB 0x130 - -#define FUSE_SOC_SPEEDO_0_CALIB 0x134 -//#define FUSE_SOC_SPEEDO_1_CALIB 0x138 -//#define FUSE_SOC_SPEEDO_2_CALIB 0x13C - -#define FUSE_CPU_IDDQ_CALIB 0x118 -#define FUSE_SOC_IDDQ_CALIB 0x140 -#define FUSE_GPU_IDDQ_CALIB 0x228 - -#define HOSSVC_HAS_CLKRST (hosversionAtLeast(8,0,0)) -#define HOSSVC_HAS_TC (hosversionAtLeast(5,0,0)) -#define NVGPU_GPU_IOCTL_PMU_GET_GPU_LOAD 0x80044715 -#define NVSCHED_CTRL_ENABLE 0x00000601 -#define NVSCHED_CTRL_DISABLE 0x00000602 - -constexpr u64 CpuTimeOutNs = 500'000'000; -constexpr double Systemtickfrequency = 19200000.0 * (static_cast(CpuTimeOutNs) / 1'000'000'000.0); -Result nvInitialize_rc; -Result nvCheck = 1; -Result nvCheck_sched = 1; - -LEvent threadexit; -Thread gpuLThread; -Thread cpuCore0Thread; -Thread cpuCore1Thread; -Thread cpuCore2Thread; -Thread cpuCore3Thread; -Thread miscThread; -double temp = 0; - -PwmChannelSession g_ICon; -Result pwmCheck = 1; -Result pwmDutyCycleCheck = 1; -double Rotation_Duty = 0; -u8 fanLevel; - -uint32_t GPU_Load_u = 0, fd = 0, fd2 = 0; -BatteryChargeInfo info; - -static SysClkSocType g_socType = SysClkSocType_Erista; -static HorizonOCConsoleType g_consoleType = HorizonOCConsoleType_Iowa; - -u64 idletick0 = 0; -u64 idletick1 = 0; -u64 idletick2 = 0; -// u64 idletick3 = 0; - -u32 cpu0, cpu1, cpu2, cpu3, cpuAvg; -u16 cpuSpeedo0, cpuSpeedo2, socSpeedo0; // CPU, GPU, SOC -u32 speedoBracket; -u16 cpuIDDQ, gpuIDDQ, socIDDQ; -u8 g_dramID = 0; -u64 cldvfs, cldvfs_temp; -u32 cachedEristaUvLowTune0 = 0, cachedEristaUvLowTune1 = 0, cachedMarikoUvHighTune0 = 0; - -static const u32 ramBrackets[][22] = { - { 2133, 2200, 2266, 2300, 2366, 2400, 2433, 2466, 2533, 2566, 2600, 2633, 2700, 2733, 2766, 2833, 2866, 2900, 2933, 3033, 3066, 3100, }, - { 2300, 2366, 2433, 2466, 2533, 2566, 2633, 2700, 2733, 2800, 2833, 2900, 2933, 2966, 3033, 3066, 3100, 3133, 3166, 3200, 3233, 3266, }, - { 2433, 2466, 2533, 2600, 2666, 2733, 2766, 2800, 2833, 2866, 2933, 2966, 3033, 3066, 3100, 3133, 3166, 3200, 3233, 3300, 3333, 3366, }, - { 2500, 2533, 2600, 2633, 2666, 2733, 2800, 2866, 2900, 2966, 3033, 3100, 3166, 3200, 3233, 3266, 3300, 3333, 3366, 3400, 3400, 3400, }, -}; - -static const u32 gpuDvfsArray[] = { 590, 600, 610, 620, 630, 640, 650, 660, 670, 680, 690, 700, 710, 720, 730, 740, 750, 760, 770, 780, 790, 800}; - -u32 dvfsTable[6][32] = {}; -u64 dvfsAddress; -u32 ramVmin; - -const char* Board::GetModuleName(SysClkModule module, bool pretty) -{ - ASSERT_ENUM_VALID(SysClkModule, module); - return sysclkFormatModule(module, pretty); -} - -const char* Board::GetProfileName(SysClkProfile profile, bool pretty) -{ - ASSERT_ENUM_VALID(SysClkProfile, profile); - return sysclkFormatProfile(profile, pretty); -} - -const char* Board::GetThermalSensorName(SysClkThermalSensor sensor, bool pretty) -{ - ASSERT_ENUM_VALID(SysClkThermalSensor, sensor); - return sysclkFormatThermalSensor(sensor, pretty); -} - -const char* Board::GetPowerSensorName(SysClkPowerSensor sensor, bool pretty) -{ - ASSERT_ENUM_VALID(SysClkPowerSensor, sensor); - return sysclkFormatPowerSensor(sensor, pretty); -} - -PcvModule Board::GetPcvModule(SysClkModule sysclkModule) -{ - switch(sysclkModule) - { - case SysClkModule_CPU: - return PcvModule_CpuBus; - case SysClkModule_GPU: - return PcvModule_GPU; - case SysClkModule_MEM: - return PcvModule_EMC; - default: - ASSERT_ENUM_VALID(SysClkModule, sysclkModule); - } - - return (PcvModule)0; -} - -PcvModuleId Board::GetPcvModuleId(SysClkModule sysclkModule) -{ - PcvModuleId pcvModuleId; - Result rc = pcvGetModuleId(&pcvModuleId, GetPcvModule(sysclkModule)); - ASSERT_RESULT_OK(rc, "pcvGetModuleId"); - - return pcvModuleId; -} - -void CheckCore(void *idletickPtr) { - u64* idletick = static_cast(idletickPtr); - while(true) { - u64 idletickA; - u64 idletickB; - svcGetInfo(&idletickB, InfoType_IdleTickCount, INVALID_HANDLE, -1); - svcWaitForAddress(&threadexit, ArbitrationType_WaitIfEqual, 0, CpuTimeOutNs); - svcGetInfo(&idletickA, InfoType_IdleTickCount, INVALID_HANDLE, -1); - *idletick = idletickA - idletickB; - } -} - -void gpuLoadThread(void*) { - #define gpu_samples_average 8 - uint32_t gpu_load_array[gpu_samples_average] = {0}; - size_t i = 0; - if (R_SUCCEEDED(nvCheck)) do { - u32 temp; - if (R_SUCCEEDED(nvIoctl(fd, NVGPU_GPU_IOCTL_PMU_GET_GPU_LOAD, &temp))) { - gpu_load_array[i++ % gpu_samples_average] = temp; - GPU_Load_u = std::accumulate(&gpu_load_array[0], &gpu_load_array[gpu_samples_average], 0) / gpu_samples_average; - } - svcSleepThread(16'666'000); // wait a bit (this is the perfect amount of time to keep the reading accurate) - } while(true); -} - -void miscThreadFunc(void*) { - for(;;) { - if (R_SUCCEEDED(pwmCheck)) { - if (R_SUCCEEDED(pwmChannelSessionGetDutyCycle(&g_ICon, &temp))) { - temp *= 10; - temp = trunc(temp); - temp /= 10; - Rotation_Duty = 100.0 - temp; - } - } - fanLevel = (u8)Rotation_Duty; - svcSleepThread(300'000'000); - } -} - -void Board::Initialize() -{ - Result rc = 0; - if(HOSSVC_HAS_CLKRST) - { - rc = clkrstInitialize(); - ASSERT_RESULT_OK(rc, "clkrstInitialize"); - } - else - { - rc = pcvInitialize(); - ASSERT_RESULT_OK(rc, "pcvInitialize"); - } - - rc = apmExtInitialize(); - ASSERT_RESULT_OK(rc, "apmExtInitialize"); - - rc = psmInitialize(); - ASSERT_RESULT_OK(rc, "psmInitialize"); - - if(HOSSVC_HAS_TC) - { - rc = tcInitialize(); - ASSERT_RESULT_OK(rc, "tcInitialize"); - } - - rc = max17050Initialize(); - ASSERT_RESULT_OK(rc, "max17050Initialize"); - - rc = tmp451Initialize(); - ASSERT_RESULT_OK(rc, "tmp451Initialize"); - nvInitialize_rc = nvInitialize(); - if (R_SUCCEEDED(nvInitialize_rc)) { - nvCheck = nvOpen(&fd, "/dev/nvhost-ctrl-gpu"); - nvCheck_sched = nvOpen(&fd2, "/dev/nvsched-ctrl"); - } - - rc = rgltrInitialize(); - ASSERT_RESULT_OK(rc, "rgltrInitialize"); - - // if (R_SUCCEEDED(fanInitialize())) { - // if (hosversionAtLeast(7,0,0)) fanCheck = fanOpenController(&fanController, 0x3D000001); - // else fanCheck = fanOpenController(&fanController, 1); - // } - - rc = pmdmntInitialize(); - ASSERT_RESULT_OK(rc, "pmdmntInitialize"); - - threadCreate(&gpuLThread, gpuLoadThread, NULL, NULL, 0x1000, 0x3F, -2); - threadStart(&gpuLThread); - leventClear(&threadexit); - threadCreate(&cpuCore0Thread, CheckCore, &idletick0, NULL, 0x1000, 0x10, 0); - threadCreate(&cpuCore1Thread, CheckCore, &idletick1, NULL, 0x1000, 0x10, 1); - threadCreate(&cpuCore2Thread, CheckCore, &idletick2, NULL, 0x1000, 0x10, 2); - // threadCreate(&cpuCore3Thread, CheckCore, &idletick3, NULL, 0x1000, 0x10, 3); - threadCreate(&miscThread, miscThreadFunc, NULL, NULL, 0x1000, 0x10, 3); - - threadStart(&cpuCore0Thread); - threadStart(&cpuCore1Thread); - threadStart(&cpuCore2Thread); - // threadStart(&cpuCore3Thread); - threadStart(&miscThread); - batteryInfoInitialize(); - FetchHardwareInfos(); - - if (hosversionAtLeast(6,0,0) && R_SUCCEEDED(pwmInitialize())) { - pwmCheck = pwmOpenSession2(&g_ICon, 0x3D000001); - } - - if(!IsHoag()) { - u64 clkVirtAddr, dsiVirtAddr, outsize; - rc = svcQueryMemoryMapping(&clkVirtAddr, &outsize, 0x60006000, 0x1000); - ASSERT_RESULT_OK(rc, "svcQueryMemoryMapping (clk)"); - rc = svcQueryMemoryMapping(&dsiVirtAddr, &outsize, 0x54300000, 0x40000); - ASSERT_RESULT_OK(rc, "svcQueryMemoryMapping (dsi)"); - - DisplayRefreshConfig cfg = {.clkVirtAddr = clkVirtAddr, .dsiVirtAddr = dsiVirtAddr}; - - DisplayRefresh_Initialize(&cfg); - } - - rc = svcQueryMemoryMapping(&cldvfs, &cldvfs_temp, CLDVFS_REGION_BASE, CLDVFS_REGION_SIZE); - ASSERT_RESULT_OK(rc, "svcQueryMemoryMapping (cldvfs)"); - - if(Board::GetSocType() == SysClkSocType_Erista) { - cachedEristaUvLowTune0 = *(u32*)(cldvfs + CL_DVFS_TUNE0_0); - cachedEristaUvLowTune1 = *(u32*)(cldvfs + CL_DVFS_TUNE1_0); - } else { - Board::SetHz(SysClkModule_CPU, 1785000000); - cachedMarikoUvHighTune0 = *(u32*)(cldvfs + CL_DVFS_TUNE0_0); - Board::ResetToStockCpu(); - } - - -} - -void Board::fuseReadSpeedos() { - - u64 pid = 0; - if (R_FAILED(pmdmntGetProcessId(&pid, 0x0100000000000006))) { - return; - } - - Handle debug; - if (R_FAILED(svcDebugActiveProcess(&debug, pid))) { - return; - } - - MemoryInfo mem_info = {0}; - u32 pageinfo = 0; - u64 addr = 0; - - char stack[0x10] = {0}; - const char compare[0x10] = {0}; - char dump[0x400] = {0}; - - while (true) { - if (R_FAILED(svcQueryDebugProcessMemory(&mem_info, &pageinfo, debug, addr)) || mem_info.addr < addr) { - break; - } - - if (mem_info.type == MemType_Io && mem_info.size == 0x1000) { - if (R_FAILED(svcReadDebugProcessMemory(stack, debug, mem_info.addr, sizeof(stack)))) { - break; - } - - if (memcmp(stack, compare, sizeof(stack)) == 0) { - if (R_FAILED(svcReadDebugProcessMemory(dump, debug, mem_info.addr + 0x800, sizeof(dump)))) { - break; - } - - cpuSpeedo0 = *reinterpret_cast(dump + FUSE_CPU_SPEEDO_0_CALIB); - cpuSpeedo2 = *reinterpret_cast(dump + FUSE_CPU_SPEEDO_2_CALIB); - socSpeedo0 = *reinterpret_cast(dump + FUSE_SOC_SPEEDO_0_CALIB); - cpuIDDQ = *reinterpret_cast(dump + FUSE_CPU_IDDQ_CALIB); - gpuIDDQ = *reinterpret_cast(dump + FUSE_SOC_IDDQ_CALIB); - socIDDQ = *reinterpret_cast(dump + FUSE_GPU_IDDQ_CALIB); - - svcCloseHandle(debug); - return; - } - } - - addr = mem_info.addr + mem_info.size; - } - - svcCloseHandle(debug); -} - -u16 Board::getSpeedo(HorizonOCSpeedo speedoType) { - switch(speedoType) { - case HorizonOCSpeedo_CPU: - return cpuSpeedo0; - case HorizonOCSpeedo_GPU: - return cpuSpeedo2; - case HorizonOCSpeedo_SOC: - return socSpeedo0; - default: - ASSERT_ENUM_VALID(HorizonOCSpeedo, speedoType); - return 0; - } -} - -u16 Board::getIDDQ(HorizonOCSpeedo speedoType) { - switch(speedoType) { - case HorizonOCSpeedo_CPU: - return cpuIDDQ; - case HorizonOCSpeedo_GPU: - return gpuIDDQ; - case HorizonOCSpeedo_SOC: - return socIDDQ; - default: - ASSERT_ENUM_VALID(HorizonOCSpeedo, speedoType); - return 0; - } -} - - -void Board::Exit() -{ - if(HOSSVC_HAS_CLKRST) - { - clkrstExit(); - } - else - { - pcvExit(); - } - - apmExtExit(); - psmExit(); - - if(HOSSVC_HAS_TC) - { - tcExit(); - } - - max17050Exit(); - tmp451Exit(); - - threadClose(&gpuLThread); - threadClose(&cpuCore0Thread); - threadClose(&cpuCore1Thread); - threadClose(&cpuCore2Thread); - // threadClose(&cpuCore3Thread); - threadClose(&miscThread); - - pwmChannelSessionClose(&g_ICon); - pwmExit(); - rgltrExit(); - batteryInfoExit(); - pmdmntExit(); - nvExit(); - if(!IsHoag()) - DisplayRefresh_Shutdown(); -} - -SysClkProfile Board::GetProfile() -{ - std::uint32_t mode = 0; - Result rc = apmExtGetPerformanceMode(&mode); - ASSERT_RESULT_OK(rc, "apmExtGetPerformanceMode"); - - if(mode) - { - return SysClkProfile_Docked; - } - - PsmChargerType chargerType; - - rc = psmGetChargerType(&chargerType); - ASSERT_RESULT_OK(rc, "psmGetChargerType"); - - if(chargerType == PsmChargerType_EnoughPower) - { - return SysClkProfile_HandheldChargingOfficial; - } - else if(chargerType == PsmChargerType_LowPower) - { - return SysClkProfile_HandheldChargingUSB; - } - - return SysClkProfile_Handheld; -} - -void Board::SetHz(SysClkModule module, std::uint32_t hz) -{ - Result rc = 0; - if(module == HorizonOCModule_Display) { - if(!IsHoag()) - DisplayRefresh_SetRate(hz); - return; - } - if(module > SysClkModule_MEM) - return; - if(HOSSVC_HAS_CLKRST) - { - ClkrstSession session = {0}; - - rc = clkrstOpenSession(&session, Board::GetPcvModuleId(module), 3); - ASSERT_RESULT_OK(rc, "clkrstOpenSession"); - rc = clkrstSetClockRate(&session, hz); - ASSERT_RESULT_OK(rc, "clkrstSetClockRate"); - if (module == SysClkModule_CPU) { - svcSleepThread(200'000); - rc = clkrstSetClockRate(&session, hz); - ASSERT_RESULT_OK(rc, "clkrstSetClockRate"); - } - clkrstCloseSession(&session); - } - else - { - rc = pcvSetClockRate(Board::GetPcvModule(module), hz); - ASSERT_RESULT_OK(rc, "pcvSetClockRate"); - if (module == SysClkModule_CPU) { - svcSleepThread(200'000); - rc = pcvSetClockRate(Board::GetPcvModule(module), hz); - ASSERT_RESULT_OK(rc, "pcvSetClockRate"); - } - } -} - -std::uint32_t Board::GetHz(SysClkModule module) -{ - Result rc = 0; - std::uint32_t hz = 0; - - if(module == HorizonOCModule_Display) { - if(!IsHoag()) - DisplayRefresh_GetRate(&hz, false); - else - hz = 60; - return hz; - } - - if(HOSSVC_HAS_CLKRST) - { - ClkrstSession session = {0}; - - rc = clkrstOpenSession(&session, Board::GetPcvModuleId(module), 3); - ASSERT_RESULT_OK(rc, "clkrstOpenSession"); - - rc = clkrstGetClockRate(&session, &hz); - ASSERT_RESULT_OK(rc, "clkrstSetClockRate"); - - clkrstCloseSession(&session); - } - else - { - rc = pcvGetClockRate(Board::GetPcvModule(module), &hz); - ASSERT_RESULT_OK(rc, "pcvGetClockRate"); - } - - return hz; -} - -std::uint32_t Board::GetRealHz(SysClkModule module) -{ - u32 hz = 0; - switch(module) - { - case SysClkModule_CPU: - return t210ClkCpuFreq(); - case SysClkModule_GPU: - return t210ClkGpuFreq(); - case SysClkModule_MEM: - return t210ClkMemFreq(); - case HorizonOCModule_Display: - if(!IsHoag()) - DisplayRefresh_GetRate(&hz, false); - else - hz = 60; - return hz; - default: - ASSERT_ENUM_VALID(SysClkModule, module); - } - - return 0; -} - -void Board::GetFreqList(SysClkModule module, std::uint32_t* outList, std::uint32_t maxCount, std::uint32_t* outCount) -{ - Result rc = 0; - PcvClockRatesListType type; - s32 tmpInMaxCount = maxCount; - s32 tmpOutCount = 0; - - - - if(HOSSVC_HAS_CLKRST) - { - ClkrstSession session = {0}; - - rc = clkrstOpenSession(&session, Board::GetPcvModuleId(module), 3); - ASSERT_RESULT_OK(rc, "clkrstOpenSession"); - - rc = clkrstGetPossibleClockRates(&session, outList, tmpInMaxCount, &type, &tmpOutCount); - ASSERT_RESULT_OK(rc, "clkrstGetPossibleClockRates"); - - clkrstCloseSession(&session); - } - else - { - rc = pcvGetPossibleClockRates(Board::GetPcvModule(module), outList, tmpInMaxCount, &type, &tmpOutCount); - ASSERT_RESULT_OK(rc, "pcvGetPossibleClockRates"); - } - - if(type != PcvClockRatesListType_Discrete) - { - ERROR_THROW("Unexpected PcvClockRatesListType: %u (module = %s)", type, Board::GetModuleName(module, false)); - } - - *outCount = tmpOutCount; -} - -void Board::ResetToStock() -{ - Result rc = 0; - if(hosversionAtLeast(9,0,0)) - { - std::uint32_t confId = 0; - rc = apmExtGetCurrentPerformanceConfiguration(&confId); - ASSERT_RESULT_OK(rc, "apmExtGetCurrentPerformanceConfiguration"); - - SysClkApmConfiguration* apmConfiguration = NULL; - for(size_t i = 0; sysclk_g_apm_configurations[i].id; i++) - { - if(sysclk_g_apm_configurations[i].id == confId) - { - apmConfiguration = &sysclk_g_apm_configurations[i]; - break; - } - } - - if(!apmConfiguration) - { - ERROR_THROW("Unknown apm configuration: %x", confId); - } - - Board::SetHz(SysClkModule_CPU, apmConfiguration->cpu_hz); - Board::SetHz(SysClkModule_GPU, apmConfiguration->gpu_hz); - Board::SetHz(SysClkModule_MEM, apmConfiguration->mem_hz); - } - else - { - std::uint32_t mode = 0; - rc = apmExtGetPerformanceMode(&mode); - ASSERT_RESULT_OK(rc, "apmExtGetPerformanceMode"); - - rc = apmExtSysRequestPerformanceMode(mode); - ASSERT_RESULT_OK(rc, "apmExtSysRequestPerformanceMode"); - } -} - -void Board::ResetToStockCpu() -{ - Result rc = 0; - if(hosversionAtLeast(9,0,0)) - { - std::uint32_t confId = 0; - rc = apmExtGetCurrentPerformanceConfiguration(&confId); - ASSERT_RESULT_OK(rc, "apmExtGetCurrentPerformanceConfiguration"); - - SysClkApmConfiguration* apmConfiguration = NULL; - for(size_t i = 0; sysclk_g_apm_configurations[i].id; i++) - { - if(sysclk_g_apm_configurations[i].id == confId) - { - apmConfiguration = &sysclk_g_apm_configurations[i]; - break; - } - } - - if(!apmConfiguration) - { - ERROR_THROW("Unknown apm configuration: %x", confId); - } - - Board::SetHz(SysClkModule_CPU, apmConfiguration->cpu_hz); - } - else - { - std::uint32_t mode = 0; - rc = apmExtGetPerformanceMode(&mode); - ASSERT_RESULT_OK(rc, "apmExtGetPerformanceMode"); - - rc = apmExtSysRequestPerformanceMode(mode); - ASSERT_RESULT_OK(rc, "apmExtSysRequestPerformanceMode"); - } -} - -void Board::ResetToStockMem() -{ - Result rc = 0; - if(hosversionAtLeast(9,0,0)) - { - std::uint32_t confId = 0; - rc = apmExtGetCurrentPerformanceConfiguration(&confId); - ASSERT_RESULT_OK(rc, "apmExtGetCurrentPerformanceConfiguration"); - - SysClkApmConfiguration* apmConfiguration = NULL; - for(size_t i = 0; sysclk_g_apm_configurations[i].id; i++) - { - if(sysclk_g_apm_configurations[i].id == confId) - { - apmConfiguration = &sysclk_g_apm_configurations[i]; - break; - } - } - - if(!apmConfiguration) - { - ERROR_THROW("Unknown apm configuration: %x", confId); - } - - Board::SetHz(SysClkModule_MEM, apmConfiguration->mem_hz); - } - else - { - std::uint32_t mode = 0; - rc = apmExtGetPerformanceMode(&mode); - ASSERT_RESULT_OK(rc, "apmExtGetPerformanceMode"); - - rc = apmExtSysRequestPerformanceMode(mode); - ASSERT_RESULT_OK(rc, "apmExtSysRequestPerformanceMode"); - } -} - -void Board::ResetToStockGpu() -{ - Result rc = 0; - if(hosversionAtLeast(9,0,0)) - { - std::uint32_t confId = 0; - rc = apmExtGetCurrentPerformanceConfiguration(&confId); - ASSERT_RESULT_OK(rc, "apmExtGetCurrentPerformanceConfiguration"); - - SysClkApmConfiguration* apmConfiguration = NULL; - for(size_t i = 0; sysclk_g_apm_configurations[i].id; i++) - { - if(sysclk_g_apm_configurations[i].id == confId) - { - apmConfiguration = &sysclk_g_apm_configurations[i]; - break; - } - } - - if(!apmConfiguration) - { - ERROR_THROW("Unknown apm configuration: %x", confId); - } - - Board::SetHz(SysClkModule_GPU, apmConfiguration->gpu_hz); - } - else - { - std::uint32_t mode = 0; - rc = apmExtGetPerformanceMode(&mode); - ASSERT_RESULT_OK(rc, "apmExtGetPerformanceMode"); - - rc = apmExtSysRequestPerformanceMode(mode); - ASSERT_RESULT_OK(rc, "apmExtSysRequestPerformanceMode"); - } -} - -void Board::ResetToStockDisplay() { - if(!IsHoag()) - DisplayRefresh_SetRate(60); -} - -u8 Board::GetHighestDockedDisplayRate() { - if(Board::GetConsoleType() != HorizonOCConsoleType_Hoag) { - return DisplayRefresh_GetDockedHighestAllowed(); - } else - return 60; -} - -std::uint32_t Board::GetTemperatureMilli(SysClkThermalSensor sensor) -{ - std::int32_t millis = 0; - - if(sensor == SysClkThermalSensor_SOC) - { - millis = tmp451TempSoc(); - } - else if(sensor == SysClkThermalSensor_PCB) - { - millis = tmp451TempPcb(); - } - else if(sensor == SysClkThermalSensor_Skin) - { - if(HOSSVC_HAS_TC) - { - Result rc; - rc = tcGetSkinTemperatureMilliC(&millis); - ASSERT_RESULT_OK(rc, "tcGetSkinTemperatureMilliC"); - } - } - else if (sensor == HorizonOCThermalSensor_Battery) { - batteryInfoGetChargeInfo(&info); - millis = batteryInfoGetTemperatureMiliCelsius(&info); - } - else if (sensor == HorizonOCThermalSensor_PMIC) { - millis = 50000; - } - else - { - ASSERT_ENUM_VALID(SysClkThermalSensor, sensor); - } - - return std::max(0, millis); -} - -std::int32_t Board::GetPowerMw(SysClkPowerSensor sensor) -{ - switch(sensor) - { - case SysClkPowerSensor_Now: - return max17050PowerNow(); - case SysClkPowerSensor_Avg: - return max17050PowerAvg(); - default: - ASSERT_ENUM_VALID(SysClkPowerSensor, sensor); - } - - return 0; -} - -u32 GetMaxCpuLoad() { - float cpuUsage0 = std::clamp(((Systemtickfrequency - idletick0) / static_cast(Systemtickfrequency)) * 1000.0, 0.0, 1000.0); - float cpuUsage1 = std::clamp(((Systemtickfrequency - idletick1) / static_cast(Systemtickfrequency)) * 1000.0, 0.0, 1000.0); - float cpuUsage2 = std::clamp(((Systemtickfrequency - idletick2) / static_cast(Systemtickfrequency)) * 1000.0, 0.0, 1000.0); - // float cpuUsage3 = std::clamp(((Systemtickfrequency - idletick3) / static_cast(Systemtickfrequency)) * 1000.0, 0.0, 1000.0); - - return std::round(std::max({cpuUsage0, cpuUsage1, cpuUsage2})); -} - -std::uint32_t Board::GetPartLoad(SysClkPartLoad loadSource) -{ - switch(loadSource) - { - case SysClkPartLoad_EMC: - return t210EmcLoadAll(); - case SysClkPartLoad_EMCCpu: - return t210EmcLoadCpu(); - case HocClkPartLoad_GPU: - return GPU_Load_u; - case HocClkPartLoad_CPUMax: - return GetMaxCpuLoad(); - case HocClkPartLoad_BAT: - batteryInfoGetChargeInfo(&info); - return info.RawBatteryCharge; - case HocClkPartLoad_FAN: - return fanLevel; - default: - ASSERT_ENUM_VALID(SysClkPartLoad, loadSource); - } - - return 0; -} - - -SysClkSocType Board::GetSocType() { - return g_socType; -} - -HorizonOCConsoleType Board::GetConsoleType() { - return g_consoleType; -} - -u8 Board::GetDramID() { - return g_dramID; -} - -void Board::FetchHardwareInfos() -{ - fuseReadSpeedos(); - SetSpeedoBracket(); - u64 sku = 0, dramID = 0; - Result rc = splInitialize(); - ASSERT_RESULT_OK(rc, "splInitialize"); - - rc = splGetConfig(SplConfigItem_HardwareType, &sku); - ASSERT_RESULT_OK(rc, "splGetConfig"); - - rc = splGetConfig(SplConfigItem_DramId, &dramID); - ASSERT_RESULT_OK(rc, "splGetConfig"); - - splExit(); - - switch(sku) - { - case 2: - case 3: - case 4: - case 5: - g_socType = SysClkSocType_Mariko; - break; - default: - g_socType = SysClkSocType_Erista; - } - - if (g_socType == SysClkSocType_Mariko) { - CacheDvfsTable(); - } - - g_consoleType = (HorizonOCConsoleType)sku; - g_dramID = (u8)dramID; -} - -/* -* Switch Power domains (max77620): -* Name | Usage | uV step | uV min | uV default | uV max | Init -*-------+---------------+---------+--------+------------+---------+------------------ -* sd0 | SoC | 12500 | 600000 | 625000 | 1400000 | 1.125V (pkg1.1) -* sd1 | SDRAM | 12500 | 600000 | 1125000 | 1125000 | 1.1V (pkg1.1) -* sd2 | ldo{0-1, 7-8} | 12500 | 600000 | 1325000 | 1350000 | 1.325V (pcv) -* sd3 | 1.8V general | 12500 | 600000 | 1800000 | 1800000 | -* ldo0 | Display Panel | 25000 | 800000 | 1200000 | 1200000 | 1.2V (pkg1.1) -* ldo1 | XUSB, PCIE | 25000 | 800000 | 1050000 | 1050000 | 1.05V (pcv) -* ldo2 | SDMMC1 | 50000 | 800000 | 1800000 | 3300000 | -* ldo3 | GC ASIC | 50000 | 800000 | 3100000 | 3100000 | 3.1V (pcv) -* ldo4 | RTC | 12500 | 800000 | 850000 | 850000 | 0.85V (AO, pcv) -* ldo5 | GC Card | 50000 | 800000 | 1800000 | 1800000 | 1.8V (pcv) -* ldo6 | Touch, ALS | 50000 | 800000 | 2900000 | 2900000 | 2.9V (pcv) -* ldo7 | XUSB | 50000 | 800000 | 1050000 | 1050000 | 1.05V (pcv) -* ldo8 | XUSB, DP, MCU | 50000 | 800000 | 1050000 | 2800000 | 1.05V/2.8V (pcv) - -typedef enum { - PcvPowerDomainId_Max77620_Sd0 = 0x3A000080, - PcvPowerDomainId_Max77620_Sd1 = 0x3A000081, // vdd2 - PcvPowerDomainId_Max77620_Sd2 = 0x3A000082, - PcvPowerDomainId_Max77620_Sd3 = 0x3A000083, - PcvPowerDomainId_Max77620_Ldo0 = 0x3A0000A0, - PcvPowerDomainId_Max77620_Ldo1 = 0x3A0000A1, - PcvPowerDomainId_Max77620_Ldo2 = 0x3A0000A2, - PcvPowerDomainId_Max77620_Ldo3 = 0x3A0000A3, - PcvPowerDomainId_Max77620_Ldo4 = 0x3A0000A4, - PcvPowerDomainId_Max77620_Ldo5 = 0x3A0000A5, - PcvPowerDomainId_Max77620_Ldo6 = 0x3A0000A6, - PcvPowerDomainId_Max77620_Ldo7 = 0x3A0000A7, - PcvPowerDomainId_Max77620_Ldo8 = 0x3A0000A8, - PcvPowerDomainId_Max77621_Cpu = 0x3A000003, - PcvPowerDomainId_Max77621_Gpu = 0x3A000004, - PcvPowerDomainId_Max77812_Cpu = 0x3A000003, - PcvPowerDomainId_Max77812_Gpu = 0x3A000004, - PcvPowerDomainId_Max77812_Dram = 0x3A000005, // vddq -} PowerDomainId; - -*/ - -std::uint32_t Board::GetVoltage(HocClkVoltage voltage) -{ - RgltrSession session; - Result rc = 0; - u32 out = 0; - switch(voltage) - { - case HocClkVoltage_SOC: - rc = rgltrOpenSession(&session, PcvPowerDomainId_Max77620_Sd0); - ASSERT_RESULT_OK(rc, "rgltrOpenSession") - rgltrGetVoltage(&session, &out); - rgltrCloseSession(&session); - break; - case HocClkVoltage_EMCVDD2: - rc = rgltrOpenSession(&session, PcvPowerDomainId_Max77620_Sd1); - ASSERT_RESULT_OK(rc, "rgltrOpenSession") - rgltrGetVoltage(&session, &out); - rgltrCloseSession(&session); - break; - case HocClkVoltage_CPU: - if(Board::GetSocType() == SysClkSocType_Mariko) - rc = rgltrOpenSession(&session, PcvPowerDomainId_Max77621_Cpu); - else - rc = rgltrOpenSession(&session, PcvPowerDomainId_Max77812_Cpu); - ASSERT_RESULT_OK(rc, "rgltrOpenSession") - rgltrGetVoltage(&session, &out); - rgltrCloseSession(&session); - break; - case HocClkVoltage_GPU: - if(Board::GetSocType() == SysClkSocType_Mariko) - rc = rgltrOpenSession(&session, PcvPowerDomainId_Max77621_Gpu); - else - rc = rgltrOpenSession(&session, PcvPowerDomainId_Max77812_Gpu); - ASSERT_RESULT_OK(rc, "rgltrOpenSession") - rgltrGetVoltage(&session, &out); - rgltrCloseSession(&session); - break; - case HocClkVoltage_EMCVDDQ_MarikoOnly: - if(Board::GetSocType() == SysClkSocType_Mariko) { - rc = rgltrOpenSession(&session, PcvPowerDomainId_Max77812_Dram); - ASSERT_RESULT_OK(rc, "rgltrOpenSession") - rgltrGetVoltage(&session, &out); - rgltrCloseSession(&session); - } else { - out = Board::GetVoltage(HocClkVoltage_EMCVDD2); - } - break; - case HocClkVoltage_Display: - rc = rgltrOpenSession(&session, PcvPowerDomainId_Max77620_Ldo0); - ASSERT_RESULT_OK(rc, "rgltrOpenSession") - rgltrGetVoltage(&session, &out); - rgltrCloseSession(&session); - break; - case HocClkVoltage_Battery: - batteryInfoGetChargeInfo(&info); - out = info.VoltageAvg; - break; - default: - ASSERT_ENUM_VALID(HocClkVoltage, voltage); - } - - return out > 0 ? out : 0; -} - -void Board::SetSpeedoBracket() { - if (cpuSpeedo2 >= 1754) { - speedoBracket = 3; - } else if (cpuSpeedo2 >= 1690) { - speedoBracket = 2; - } else if (cpuSpeedo2 > 1625) { - speedoBracket = 1; - } else { - speedoBracket = 0; - } -} - -u32 Board::GetMinimumGpuVoltage(u32 freqMhz) { - if (freqMhz <= 1600) - return 0; - - for (u32 voltageIndex = 0; voltageIndex < 22; ++voltageIndex) { - if (freqMhz <= ramBrackets[speedoBracket][voltageIndex]) { - return gpuDvfsArray[voltageIndex]; - } - } - - return 800; -} - -Handle Board::GetPcvHandle() { - constexpr u64 PcvID = 0x10000000000001a; - u64 processIDList[80]{}; - s32 processCount = 0; - Handle handle = INVALID_HANDLE; - - DebugEventInfo debugEvent{}; - - /* Get all running processes. */ - Result resultGetProcessList = svcGetProcessList(&processCount, processIDList, std::size(processIDList)); - if (R_FAILED(resultGetProcessList)) { - return INVALID_HANDLE; - } - - /* Try to find pcv. */ - for (int i = 0; i < processCount; ++i) { - if (handle != INVALID_HANDLE) { - svcCloseHandle(handle); - handle = INVALID_HANDLE; - } - - /* Try to debug process, if it fails, try next process. */ - Result resultSvcDebugProcess = svcDebugActiveProcess(&handle, processIDList[i]); - if (R_FAILED(resultSvcDebugProcess)) { - continue; - } - - /* Try to get a debug event. */ - Result resultDebugEvent = svcGetDebugEvent(&debugEvent, handle); - if (R_SUCCEEDED(resultDebugEvent)) { - if (debugEvent.info.create_process.program_id == PcvID) { - return handle; - } - } - } - - /* Failed to get handle. */ - return INVALID_HANDLE; -} - -void Board::CacheDvfsTable() { - const u32 voltagePattern[] = { 600000, 12500, 1400000, }; - - Handle handle = GetPcvHandle(); - if (handle == INVALID_HANDLE) { - FileUtils::LogLine("[Board] Invalid handle!"); - return; - } - - MemoryInfo memoryInfo = {}; - u64 address = 0; - u32 pageInfo = 0; - constexpr u32 PageSize = 0x1000; - u8 buffer[PageSize]; - - /* Loop until failure. */ - while (true) { - /* Find pcv heap. */ - while (true) { - Result resultProcessMemory = svcQueryDebugProcessMemory(&memoryInfo, &pageInfo, handle, address); - address = memoryInfo.addr + memoryInfo.size; - - if (R_FAILED(resultProcessMemory) || !address) { - svcCloseHandle(handle); - FileUtils::LogLine("[Board] Failed to get process data. %u", R_DESCRIPTION(resultProcessMemory)); - handle = INVALID_HANDLE; - return; - } - - if (memoryInfo.size && (memoryInfo.perm & 3) == 3 && static_cast(memoryInfo.type) == 0x04) { - /* Found valid memory. */ - break; - } - } - - for (u64 base = 0; base < memoryInfo.size; base += PageSize) { - u32 memorySize = std::min(memoryInfo.size, static_cast(PageSize)); - if (R_FAILED(svcReadDebugProcessMemory(buffer, handle, base + memoryInfo.addr, memorySize))) { - break; - } - - u8 *resultPattern = static_cast(memmem_impl(buffer, sizeof(buffer), voltagePattern, sizeof(voltagePattern))); - u32 index = resultPattern - buffer; - - if (!resultPattern) { - continue; - } - - /* Assuming mariko. */ - const u32 vmax = 800; - constexpr u32 DvfsTableOffset = 312; - if (!std::memcmp(&buffer[index + DvfsTableOffset], &vmax, sizeof(vmax))) { - std::memcpy(dvfsTable, &buffer[index + DvfsTableOffset], sizeof(dvfsTable)); - dvfsAddress = base + memoryInfo.addr + DvfsTableOffset + index; - } - - svcCloseHandle(handle); - handle = INVALID_HANDLE; - return; - } - } - - svcCloseHandle(handle); - handle = INVALID_HANDLE; - return; -} - -void Board::PcvHijackDvfs(u32 vmin) { - u32 table[192]; - static_assert(sizeof(table) == sizeof(dvfsTable)); - std::memcpy(table, dvfsTable, sizeof(dvfsTable)); - - if (ramVmin == vmin) { - return; - } - - for (u32 i = 0; i < std::size(table); ++i) { - if (table[i] && table[i] <= vmin) { - table[i] = vmin; - } - } - - Handle handle = GetPcvHandle(); - if (handle == INVALID_HANDLE) { - FileUtils::LogLine("Invalid handle!"); - return; - } - - Result rc = svcWriteDebugProcessMemory(handle, table, dvfsAddress, sizeof(table)); - - if (R_SUCCEEDED(rc)) { - ramVmin = vmin; - } - - svcCloseHandle(handle); - FileUtils::LogLine("[dvfs] voltage set to %u mV", vmin); -} - -bool Board::IsDram8GB() { - SecmonArgs args = {}; - args.X[0] = 0xF0000002; - args.X[1] = MC_REGISTER_BASE + MC_EMEM_CFG_0; - svcCallSecureMonitor(&args); - - if(args.X[1] == (MC_REGISTER_BASE + MC_EMEM_CFG_0)) { // if param 1 is identical read failed - writeNotification("Horizon OC\nSecmon read failed!\n This may be a hardware issue!"); - return false; - } else - return args.X[1] == 0x00002000 ? true : false; -} - -void Board::SetGpuSchedulingMode(GpuSchedulingMode mode, GpuSchedulingOverrideMethod method) { - if (nvCheck_sched == 1 && method == GpuSchedulingOverrideMethod_NvService) { - return; - } - u32 temp; - bool enabled = false; - switch(mode) { - case GpuSchedulingMode_DoNotOverride: break; - case GpuSchedulingMode_Disabled: - if(method == GpuSchedulingOverrideMethod_NvService) - nvIoctl(fd2, NVSCHED_CTRL_DISABLE, &temp); - else - enabled = false; - break; - case GpuSchedulingMode_Enabled: - if(method == GpuSchedulingOverrideMethod_NvService) - nvIoctl(fd2, NVSCHED_CTRL_ENABLE, &temp); - else - enabled = true; - break; - default: - ASSERT_ENUM_VALID(GpuSchedulingMode, mode); - } - if(method == GpuSchedulingOverrideMethod_Ini) { - const char* ini_path = "sdmc:/atmosphere/config/system_settings.ini"; - const char* section = "am.gpu"; - const char* key = "gpu_scheduling_enabled"; - - const char* value = enabled ? "u8!0x1" : "u8!0x0"; - - ini_puts(section, key, value, ini_path); - } -} -void Board::SetDisplayRefreshDockedState(bool docked) { - if(Board::GetConsoleType() != HorizonOCConsoleType_Hoag) { - DisplayRefresh_SetDockedState(docked); - } -} - - -typedef struct EristaCpuUvEntry { - u32 tune0; - u32 tune1; -} EristaCpuUvEntry; -typedef struct MarikoCpuUvEntry { - u32 tune0_low; - u32 tune0_high; - u32 tune1_low; - u32 tune1_high; -} MarikoCpuUvEntry; - -EristaCpuUvEntry eristaCpuUvTable[5] = { - {0xffff, 0x27007ff}, - {0xefff, 0x27407ff}, - {0xdfff, 0x27807ff}, - {0xdfdf, 0x27a07ff}, - {0xcfdf, 0x37007ff}, -}; - -MarikoCpuUvEntry marikoCpuUvLow[12] = { - {0xffa0, 0xffff, 0x21107ff, 0}, - {0x0, 0xffdf, 0x21107ff, 0x27207ff}, - {0xffdf, 0xffdf, 0x21107ff, 0x27307ff}, - {0xffff, 0xffdf, 0x21107ff, 0x27407ff}, - {0x0, 0xffdf, 0x21607ff, 0x27707ff}, - {0x0, 0xffdf, 0x21607ff, 0x27807ff}, - {0x0, 0xdfff, 0x21607ff, 0x27b07ff}, - {0xdfff, 0xdfff, 0x21707ff, 0x27b07ff}, - {0xdfff, 0xdfff, 0x21707ff, 0x27c07ff}, - {0xdfff, 0xdfff, 0x21707ff, 0x27d07ff}, - {0xdfff, 0xdfff, 0x21707ff, 0x27e07ff}, - {0xdfff, 0xdfff, 0x21707ff, 0x27f07ff}, -}; - -MarikoCpuUvEntry marikoCpuUvHigh[12] = { - {0x0, 0xffff, 0, 0}, - {0x0, 0xffdf, 0, 0x27207ff}, - {0x0, 0xffdf, 0, 0x27307ff}, - {0x0, 0xffdf, 0, 0x27407ff}, - {0x0, 0xffdf, 0, 0x27707ff}, - {0x0, 0xffdf, 0, 0x27807ff}, - {0x0, 0xdfff, 0, 0x27b07ff}, - {0x0, 0xdfff, 0, 0x27c07ff}, - {0x0, 0xdfff, 0, 0x27d07ff}, - {0x0, 0xdfff, 0, 0x27e07ff}, - {0x0, 0xdfff, 0, 0x27f07ff}, - {0x0, 0xdfff, 0, 0x27f07ff}, -}; -void Board::SetCpuUvLevel(u32 levelLow, u32 levelHigh, u32 tbreakPoint) { - u32* tune0_ptr = (u32*)(cldvfs + CL_DVFS_TUNE0_0); - u32* tune1_ptr = (u32*)(cldvfs + CL_DVFS_TUNE1_0); - if(Board::GetSocType() == SysClkSocType_Mariko) { - if(Board::GetHz(SysClkModule_CPU) < tbreakPoint && (levelLow || levelHigh)) { - if(levelLow) { - *tune0_ptr = marikoCpuUvLow[levelLow-1].tune0_low; - *tune1_ptr = marikoCpuUvLow[levelLow-1].tune1_low; - } - return; - } else { - if(levelLow) { - *tune0_ptr = marikoCpuUvLow[levelLow-1].tune0_low; - *tune1_ptr = marikoCpuUvLow[levelLow-1].tune1_low; - } - if(levelHigh) { - *tune0_ptr = marikoCpuUvHigh[levelHigh-1].tune0_high; - *tune1_ptr = marikoCpuUvHigh[levelHigh-1].tune1_high; - } - return; - } - if(Board::GetHz(SysClkModule_CPU) < tbreakPoint || (!levelLow)) { // account for tbreak - *tune0_ptr = 0xCFFF; - *tune1_ptr = 0xFF072201; - return; - } else if (Board::GetHz(SysClkModule_CPU) >= tbreakPoint || (!levelHigh)) { - *tune0_ptr = cachedMarikoUvHighTune0; // per console? - *tune1_ptr = 0xFFF7FF3F; - return; - } - } else { - if(Board::GetHz(SysClkModule_CPU) < tbreakPoint || (!levelLow)) { // account for tbreak - *tune0_ptr = cachedEristaUvLowTune0; // I think each erista has a different tune0/tune1? - *tune1_ptr = cachedEristaUvLowTune1; - return; - } else { - if(levelLow) { - *tune0_ptr = eristaCpuUvTable[levelLow-1].tune0; - *tune1_ptr = eristaCpuUvTable[levelLow-1].tune1; - } else { - *tune0_ptr = 0x0; - *tune1_ptr = 0x0; - } - } - } -} -/* -enum TableConfig: u32 { - DEFAULT_TABLE = 1, - TBREAK_1581 = 2, - TBREAK_1683 = 3, - EXTREME_TABLE = 4, -}; -*/ -u32 Board::CalculateTbreak(u32 table) { - if(Board::GetSocType() == SysClkSocType_Erista) - return 1581000000; - else { - switch(table) { - case 1 ... 2: - case 4: - return 1581000000; - case 3: - return 1683000000; - default: - return 1581000000; - } - } - -} - -bool Board::IsHoag() { - return Board::GetConsoleType() == HorizonOCConsoleType_Hoag; -} \ No newline at end of file diff --git a/Source/rewrite-hoc-clk/sysmodule/src/old_board.h b/Source/rewrite-hoc-clk/sysmodule/src/old_board.h deleted file mode 100644 index 2a32c87b..00000000 --- a/Source/rewrite-hoc-clk/sysmodule/src/old_board.h +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#pragma once -#include -#include -#include - -class Board -{ - public: - static void PcvHijackDvfs(u32 vmin); - static u32 GetMinimumGpuVoltage(u32 freqMhz); - static void fuseReadSpeedos(); - static u16 getSpeedo(HorizonOCSpeedo speedoType); - static u16 getIDDQ(HorizonOCSpeedo speedoType); - static const char* GetProfileName(SysClkProfile profile, bool pretty); - static const char* GetModuleName(SysClkModule module, bool pretty); - static const char* GetThermalSensorName(SysClkThermalSensor sensor, bool pretty); - static const char* GetPowerSensorName(SysClkPowerSensor sensor, bool pretty); - static void Initialize(); - static void Exit(); - static void ResetToStock(); - static void ResetToStockCpu(); - static void ResetToStockMem(); - static void ResetToStockGpu(); - static void ResetToStockDisplay(); - static u8 GetHighestDockedDisplayRate(); - static SysClkProfile GetProfile(); - static void SetHz(SysClkModule module, std::uint32_t hz); - static std::uint32_t GetHz(SysClkModule module); - static std::uint32_t GetRealHz(SysClkModule module); - static void GetFreqList(SysClkModule module, std::uint32_t* outList, std::uint32_t maxCount, std::uint32_t* outCount); - static std::uint32_t GetTemperatureMilli(SysClkThermalSensor sensor); - static std::int32_t GetPowerMw(SysClkPowerSensor sensor); - static std::uint32_t GetPartLoad(SysClkPartLoad load); - static SysClkSocType GetSocType(); - static HorizonOCConsoleType GetConsoleType(); - static std::uint32_t GetVoltage(HocClkVoltage voltage); - static u8 GetFanRotationLevel(); - static u8 GetDramID(); - static bool IsDram8GB(); - static void SetGpuSchedulingMode(GpuSchedulingMode mode, GpuSchedulingOverrideMethod method); - static void SetDisplayRefreshDockedState(bool docked); - static void SetCpuUvLevel(u32 levelLow, u32 levelHigh, u32 tbreakPoint); - static u32 CalculateTbreak(u32 table); - static bool IsHoag(); - protected: - static void FetchHardwareInfos(); - static PcvModule GetPcvModule(SysClkModule sysclkModule); - static PcvModuleId GetPcvModuleId(SysClkModule sysclkModule); - private: - static void SetSpeedoBracket(); - static void CacheDvfsTable(); - static Handle GetPcvHandle(); -}; diff --git a/Source/rewrite-hoc-clk/sysmodule/src/process_management.cpp b/Source/rewrite-hoc-clk/sysmodule/src/process_management.cpp index 6c0f6953..c5bdcdf4 100644 --- a/Source/rewrite-hoc-clk/sysmodule/src/process_management.cpp +++ b/Source/rewrite-hoc-clk/sysmodule/src/process_management.cpp @@ -12,9 +12,9 @@ * * You should have received a copy of the GNU General Public License * along with this program. If not, see . - * + * */ - + /* -------------------------------------------------------------------------- * "THE BEER-WARE LICENSE" (Revision 42): * , , @@ -25,61 +25,63 @@ */ -#include "process_management.h" +#include "process_management.hpp" #include "file_utils.h" #include "errors.h" -#define IS_QLAUNCH 0x20f -void ProcessManagement::Initialize() -{ - Result rc = 0; +namespace processManagement { - rc = pmdmntInitialize(); - ASSERT_RESULT_OK(rc, "pmdmntInitialize"); - - rc = pminfoInitialize(); - ASSERT_RESULT_OK(rc, "pminfoInitialize"); -} - -void ProcessManagement::WaitForQLaunch() -{ - Result rc = 0; - std::uint64_t pid = 0; - do - { - rc = pmdmntGetProcessId(&pid, PROCESS_MANAGEMENT_QLAUNCH_TID); - svcSleepThread(50 * 1000000ULL); // 50ms - } while (R_FAILED(rc)); -} - -std::uint64_t ProcessManagement::GetCurrentApplicationId() -{ - Result rc = 0; - std::uint64_t pid = 0; - std::uint64_t tid = 0; - rc = pmdmntGetApplicationProcessId(&pid); - - if (rc == IS_QLAUNCH) - { - return PROCESS_MANAGEMENT_QLAUNCH_TID; + namespace { + constexpr u64 Qlaunch = 0x0100000000001000ULL; + constexpr u32 IsQlaunch = 0x20f; } - ASSERT_RESULT_OK(rc, "pmdmntGetApplicationProcessId"); + void Initialize() { + Result rc = 0; - rc = pminfoGetProgramId(&tid, pid); + rc = pmdmntInitialize(); + ASSERT_RESULT_OK(rc, "pmdmntInitialize"); - if (rc == IS_QLAUNCH) - { - return PROCESS_MANAGEMENT_QLAUNCH_TID; + rc = pminfoInitialize(); + ASSERT_RESULT_OK(rc, "pminfoInitialize"); } - ASSERT_RESULT_OK(rc, "pminfoGetProgramId"); + void WaitForQLaunch() { - return tid; -} + Result rc = 0; + u64 pid = 0; + do { + rc = pmdmntGetProcessId(&pid, Qlaunch); + svcSleepThread(50 * 1000000ULL); // 50ms + } while (R_FAILED(rc)); + } -void ProcessManagement::Exit() -{ - pmdmntExit(); - pminfoExit(); -} + u64 GetCurrentApplicationId() { + Result rc = 0; + u64 pid = 0; + u64 tid = 0; + rc = pmdmntGetApplicationProcessId(&pid); + + if (rc == IsQlaunch) { + return Qlaunch; + } + + ASSERT_RESULT_OK(rc, "pmdmntGetApplicationProcessId"); + + rc = pminfoGetProgramId(&tid, pid); + + if (rc == IsQlaunch) { + return Qlaunch; + } + + ASSERT_RESULT_OK(rc, "pminfoGetProgramId"); + + return tid; + } + + void Exit() { + pmdmntExit(); + pminfoExit(); + } + +} \ No newline at end of file diff --git a/Source/rewrite-hoc-clk/sysmodule/src/process_management.hpp b/Source/rewrite-hoc-clk/sysmodule/src/process_management.hpp new file mode 100644 index 00000000..579ad29a --- /dev/null +++ b/Source/rewrite-hoc-clk/sysmodule/src/process_management.hpp @@ -0,0 +1,38 @@ +/* + * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors + * + * This program is free software; you can redistribute it and/or modify it + * under the terms and conditions of the GNU General Public License, + * version 2, as published by the Free Software Foundation. + * + * This program is distributed in the hope it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +/* -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + + +#pragma once +#include + +namespace processManagement { + + void Initialize(); + void WaitForQLaunch(); + u64 GetCurrentApplicationId(); + void Exit(); + +} diff --git a/Source/sys-clk/overlay/lang/ko.json b/Source/sys-clk/overlay/lang/ko.json index 730ea4c4..09e73e66 100644 --- a/Source/sys-clk/overlay/lang/ko.json +++ b/Source/sys-clk/overlay/lang/ko.json @@ -10,7 +10,7 @@ "Developers": "개발자", "Contributors": "기여자", "Testers": "테스터", - "Special Thanks": "특별한 감사", + "Special Thanks": "특별한 분", "Unknown": "알 수 없음", "Installed": "설치됨", "Not Installed": "설치되지 않음", @@ -35,7 +35,7 @@ "Sleep Mode": "절전 모드", "Stock": "주식", "Dev OC": "개발 OC", - "Boost Mode": "부스트 모드", + "Overwrite Boost Mode": "부스트 모드 덮어쓰기", "Safe Max": "안전함 최대값", "Unsafe Max": "불안정 최대값", "Absolute Max": "절대 최대값", @@ -48,7 +48,7 @@ "About": "소개", "Compiling with minimal features": "최소한의 기능으로 컴파일하기", "General Settings": "일반 설정", - "Governor Settings": "주지사 설정", + "Governor Settings": "거버너 설정", "Safety Settings": "안전 설정", "Save KIP Settings": "KIP 설정 저장", "RAM Settings": "RAM 설정", @@ -63,9 +63,9 @@ "RAM Voltage Display Mode": "RAM 전압 표시 모드", "Polling Interval": "폴링 간격", "CPU Governor Minimum Frequency": "CPU 거버너 최소 주파수", - "refresh rates may cause stress": "새로 고침 빈도는 스트레스를 유발할 수 있습니다", - "or damage to your display! ": "또는 디스플레이가 손상되었습니다!", - "Proceed at your own risk!": "자신의 책임하에 진행하십시오!", + "refresh rates may cause stress": "디스플레이 주사율 빈도 변경은", + "or damage to your display! ": "기기에 손상이 발생될 수 있습니다!", + "Proceed at your own risk!": "책임하에 주의해서 사용하십시오!", "Max Handheld Display": "최대 휴대용 디스플레이", "Display Clock": "디스플레이 클럭", "Official Rating": "공식 등급", @@ -92,7 +92,7 @@ "3500MHz (Needs ridiculous Speedo/PLL)": "3500MHz(터무니없는 Speedo/PLL 필요)", "Ram Max Clock": "RAM 최대 클럭", "RAM Latency Editor": "RAM 지연 시간 편집기", - "RAM Timing Reductions": "RAM 타이밍 감소", + "RAM Timing Reductions": "RAM 타이밍 편집기", "Memory Timings": "메모리 타이밍", "Advanced": "고급", "t6 tRTW Fine Tune": "t6 tRTW 미세 조정", @@ -103,12 +103,12 @@ "Read Latency": "읽기 지연 시간", "Write Latency": "쓰기 지연 시간", "CPU Boost Clock": "CPU 부스트 클럭", - "CPU UV": "CPU UV", + "CPU UV": "CPU 언더볼트", "CPU Unlock": "CPU 잠금 해제", "CPU VMIN": "CPU VMIN", "CPU Max Voltage": "CPU 최대 전압", "CPU Max Clock": "CPU 최대 클럭", - "Extreme UV Table": "극자외선 테이블", + "Extreme UV Table": "익스트림 테이블", "CPU UV Table": "CPU 언더볼트 테이블", "CPU Low UV": "CPU 저주파 언더볼트", "CPU High UV": "CPU 고주파 언더볼트", @@ -117,7 +117,7 @@ "No Undervolt": "언더볼트 없음", "SLT Table": "SLT 테이블", "HiOPT Table": "HiOPT 테이블", - "GPU Undervolt Table": "GPU 언더볼트 표", + "GPU Undervolt Table": "GPU 언더볼트 테이블", "GPU Minimum Voltage": "GPU 최소 전압", "Calculate GPU Vmin": "GPU Vmin 계산", "GPU VMIN": "GPU VMIN", @@ -131,11 +131,11 @@ "Official Service": "공식 서비스", "GPU DVFS Mode": "GPU DVFS 모드", "GPU DVFS Offset": "GPU DVFS 오프셋", - "GPU Voltage Table": "GPU 전압 표", + "GPU Voltage Table": "GPU 전압 테이블", "GPU Custom Table (mV)": "GPU 사용자 정의 테이블(mV)", "1075MHz without UV, 1152MHz on SLT": "UV 없이 1075MHz, SLT에서 1152MHz", "or 1228MHz on HiOPT can cause ": "또는 HiOPT에서 1228MHz를 사용하면", - "permanent damage to your Switch!": "스위치가 영구적으로 손상되었습니다!", + "permanent damage to your Switch!": "스위치가 영구적으로 손상될 수 있습니다!", "921MHz without UV and 960MHz on": "UV가 없는 경우 921MHz, 켜진 경우에는 960MHz", "SLT or HiOPT can cause ": "SLT 또는 HiOPT는 다음을 유발할 수 있습니다." }