rewrite much of timings stuff

This commit is contained in:
souldbminersmwc
2025-08-30 11:59:19 -04:00
parent b5b509c828
commit fd91bc07d8
120 changed files with 19886 additions and 578 deletions

View File

@@ -1,8 +1,6 @@
/*
* Copyright (C) Switch-OC-Suite
*
* Copyright (c) 2023 hanai3Bi
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
@@ -30,7 +28,7 @@ volatile CustomizeTable C = {
* NO_ADJ_ALL: No timing adjustment for both Erista and Mariko.
* CUSTOMIZED_ALL: Replace with values in customized table for both Erista and Mariko.
*/
.mtcConf = AUTO_ADJ_ALL,
.mtcConf = CUSTOM_ADJ_ALL,
/* Common:
* - Boost Clock in kHz:
@@ -38,7 +36,7 @@ volatile CustomizeTable C = {
* Boost clock will be applied when applications request higher CPU frequency for quicker loading.
* This will be set regardless of whether sys-clk is enabled.
*/
.commonCpuBoostClock = 1785000,
.commonCpuBoostClock = 2295000,
/* - EMC Vddq (Erista Only) and RAM Vdd2 Voltage in uV
* Range: 1100'000 to 1250'000 uV
* Erista Default(HOS): 1125'000 (bootloader: 1100'000)
@@ -46,7 +44,7 @@ volatile CustomizeTable C = {
* Value should be divided evenly by 12'500.
* Not enabled by default.
*/
.commonEmcMemVolt = 1175000, // RAM Rated Voltage
.commonEmcMemVolt = 1212500,
/* Erista CPU:
* - Max Voltage in mV
@@ -68,7 +66,7 @@ volatile CustomizeTable C = {
* - Max Voltage in mV:
* Default voltage: 1120
*/
.marikoCpuMaxVolt = 1120,
.marikoCpuMaxVolt = 1160,
/* Mariko EMC(RAM):
* - RAM Clock in kHz:
@@ -79,39 +77,40 @@ volatile CustomizeTable C = {
* - System instabilities
* - NAND corruption
*/
.marikoEmcMaxClock = 1996800,
.marikoEmcMaxClock = 2400000,
/* - EMC Vddq (Mariko Only) Voltage in uV
* Range: 550'000 to 650'000 uV
* Value should be divided evenly by 5'000
* Value should be dicvided evenly by 5'000
* Default: 600'000
* Not enabled by default.
* This will not work without sys-clk-OC.
*/
.marikoEmcVddqVolt = 0,
.marikoEmcVddqVolt = 640000,
.marikoCpuUV = 0,
.marikoCpuUV = 1,
.marikoGpuUV = 0,
.marikoGpuUV = 2,
.commonGpuVoltOffset = 0,
.marikoEmcDvbShift = 0,
.marikoEmcDvbShift = 5,
.ramTimingPresetOne = 0,
.tRAS = 0,
.tRCD = 0,
.tREFpb = 0,
.tRFCpb = 0,
.tRPpb = 0,
.tRRD = 0,
.R2W = 0,
.tWTR = 0,
.ramTimingPresetTwo = 0,
.marikoGpuVoltArray = {635, 635, 635, 635, 635, 635, 635, 635, 635, 635, 635, 635, 660, 685, 715, 745, 765, 785},
.ramTimingPresetThree = 0,
.marikoCpuHighVoltOffset = 70,
.ramTimingPresetFour = 0,
.marikoB3 = 179,
.ramTimingPresetFive = 0,
.ramTimingPresetSix = 0,
.ramTimingPresetSeven = 0,
.marikoGpuVoltArray = {610, 610, 610, 610, 610, 610, 610, 610, 610, 610, 620, 640, 675, 710, 735, 785, 815},
.marikoCpuHighUV = 0,
/* Advanced Settings:
* - Erista CPU DVFS Table:
@@ -137,8 +136,6 @@ volatile CustomizeTable C = {
{ 1887000, { 1235000 }, { 5100873, -279186, 4747 } },
{ 1963500, { 1235000 }, { 5100873, -279186, 4747 } },
{ 2091000, { 1235000 }, { 5100873, -279186, 4747 } },
{ 2193000, { 1235000 }, { 5100873, -279186, 4747 } },
{ 2295000, { 1235000 }, { 5100873, -279186, 4747 } },
},
/* - Mariko CPU DVFS Table:
@@ -164,13 +161,15 @@ volatile CustomizeTable C = {
{ 1887000, { 1609246, -37515, 27 }, { 1120000 } },
{ 1963500, { 1675751, -38635, 27 }, { 1120000 } },
// Appending table
{ 2091000, { 1716501, -39395, 27 }, { 1235000 } },
{ 2193000, { 1775132, -40505, 27 }, { 1235000 } },
{ 2295000, { 1866287, -42005, 27 }, { 1235000 } },
// Unsafe
{ 2397000, { 1961107, -43506, 27 }, { 1235000 } },
{ 2499000, { 1754400, -35643, 27 }, { 1235000 } },
{ 2601000, { 1805897, -36331, 27 }, { 1235000 } },
{ 2091000, { 1580725, -33235, 113 }, { 1120000 } },
{ 2193000, { 1580725, -33235, 113 }, { 1235000 } },
{ 2295000, { 1635431, -34095, 113 }, { 1235000 } },
{ 2397000, { 1702903, -34955, 113 }, { 1235000 } },
{ 2499000, { 1754400, -35643, 113 }, { 1235000 } },
{ 2601000, { 1805897, -36331, 113 }, { 1235000 } },
{ 2703000, { 1857394, -37019, 113 }, { 1235000 } },
{ 2805000, { 1908891, -37707, 113 }, { 1235000 } },
{ 2907000, { 1960388, -38395, 113 }, { 1250000 } },
},
.marikoCpuDvfsTableSLT = {
@@ -226,47 +225,6 @@ volatile CustomizeTable C = {
* 1305600 might not work for some SoCs.
*/
.marikoGpuDvfsTable = {
{ 76800, {}, { 610000, } },
{ 153600, {}, { 610000, } },
{ 230400, {}, { 610000, } },
{ 307200, {}, { 610000, } },
{ 384000, {}, { 610000, } },
{ 460800, {}, { 610000, } },
{ 537600, {}, { 801688, -10900, -163, 298, -10599, 162 } },
{ 614400, {}, { 824214, -5743, -452, 238, -6325, 81 } },
{ 691200, {}, { 848830, -3903, -552, 119, -4030, -2 } },
{ 768000, {}, { 891575, -4409, -584, 0, -2849, 39 } },
{ 844800, {}, { 940071, -5367, -602, -60, -63, -93 } },
{ 921600, {}, { 986765, -6637, -614, -179, 1905, -13 } },
{ 998400, {}, { 1098475, -13529, -497, -179, 3626, 9 } },
{ 1075200, {}, { 1163644, -12688, -648, 0, 1077, 40 } },
{ 1152000, {}, { 1204812, -9908, -830, 0, 1469, 110 } },
{ 1228800, {}, { 1277303, -11675, -859, 0, 3722, 313 } },
{ 1267200, {}, { 1335531, -12567, -867, 0, 3681, 559 } },
// Appending table
{ 1305600, {}, { 1374130, -13725, -859, 0, 4442, 576 } },
},
.marikoGpuDvfsTableSLT = {
{ 76800, {}, { 590000, } },
{ 153600, {}, { 590000, } },
{ 230400, {}, { 590000, } },
{ 307200, {}, { 590000, } },
{ 384000, {}, { 590000, } },
{ 460800, {}, { 795089, -11096, -163, 298, -10421, 162 } },
{ 537600, {}, { 795089, -11096, -163, 298, -10421, 162 } },
{ 614400, {}, { 820606, -6285, -452, 238, -6182, 81 } },
{ 691200, {}, { 846289, -4565, -552, 119, -3958, -2 } },
{ 768000, {}, { 888720, -5110, -584, 0, -2849, 39 } },
{ 844800, {}, { 936634, -6089, -602, -60, -99, -93 } },
{ 921600, {}, { 982562, -7373, -614, -179, 1797, -13 } },
{ 998400, {}, { 1090179, -14125, -497, -179, 3518, 9 } },
{ 1075200, {}, { 1155798, -13465, -648, 0, 1077, 40 } },
{ 1152000, {}, { 1198568, -10904, -830, 0, 1469, 110 } },
{ 1228800, {}, { 1269988, -12707, -859, 0, 3722, 313 } },
{ 1267200, {}, { 1308155, -13694, -867, 0, 3681, 559 } },
},
.marikoGpuDvfsTableHiOPT = {
{ 76800, {}, { 590000, } },
{ 153600, {}, { 590000, } },
{ 230400, {}, { 590000, } },
@@ -284,6 +242,49 @@ volatile CustomizeTable C = {
{ 1152000, {}, { 1180029, -14534, -830, 0, 1469, 110 } },
{ 1228800, {}, { 1248293, -16383, -859, 0, 3722, 313 } },
{ 1267200, {}, { 1286399, -17475, -867, 0, 3681, 559 } },
// Appending table
{ 1305600, {}, { 1304130, -13725, -859, 0, 4442, 576 } },
},
.marikoGpuDvfsTableSLT = {
{ 76800, {}, { 635000, } },
{ 153600, {}, { 635000, } },
{ 230400, {}, { 635000, } },
{ 307200, {}, { 635000, } },
{ 384000, {}, { 635000, } },
{ 460800, {}, { 635000, } },
{ 537600, {}, { 635000, } },
{ 614400, {}, { 635000, } },
{ 691200, {}, { 635000, } },
{ 768000, {}, { 635000, } },
{ 844800, {}, { 635000, } },
{ 921600, {}, { 635000, } },
{ 998400, {}, { 901575, -4409, -584, 0, -2849, 39 } },
{ 1075200, {}, { 940071, -5367, -602, -60, -63, -93 } },
{ 1152000, {}, { 996765, -6637, -614, -179, 1905, -13 } },
{ 1228800, {}, { 1098475, -13529, -497, -179, 3626, 9 } },
{ 1267200, {}, { 1131060, -13109, -573, -90, 2352, 25 } },
{ 1305600, {}, { 1163644, -12688, -648, 0, 1077, 40 } },
},
.marikoGpuDvfsTableHiOPT = {
{ 76800, {}, { 550000, } },
{ 153600, {}, { 550000, } },
{ 230400, {}, { 550000, } },
{ 307200, {}, { 550000, } },
{ 384000, {}, { 550000, } },
{ 460800, {}, { 550000, } },
{ 537600, {}, { 550000, } },
{ 614400, {}, { 550000, } },
{ 691200, {}, { 550000, } },
{ 768000, {}, { 801688, -10900, -163, 298, -10599, 162 } },
{ 844800, {}, { 824214, -5743, -452, 238, -6325, 81 } },
{ 921600, {}, { 848830, -3903, -552, 119, -4030, -2 } },
{ 998400, {}, { 901575, -4409, -584, 0, -2849, 39 } },
{ 1075200, {}, { 940071, -5367, -602, -60, -63, -93 } },
{ 1152000, {}, { 996765, -6637, -614, -179, 1905, -13 } },
{ 1228800, {}, { 1098475, -13529, -497, -179, 3626, 9 } },
{ 1267200, {}, { 1131060, -13109, -573, -90, 2352, 25 } },
{ 1305600, {}, { 1163644, -12688, -648, 0, 1077, 40 } },
},
//.eristaMtcTable = const_cast<EristaMtcTable *>(&EristaMtcTablePlaceholder),
@@ -291,4 +292,4 @@ volatile CustomizeTable C = {
};
}
}

View File

@@ -1,8 +1,6 @@
/*
* Copyright (C) Switch-OC-Suite
*
* Copyright (c) 2023 hanai3Bi
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
@@ -59,15 +57,20 @@ typedef struct CustomizeTable {
u32 commonGpuVoltOffset;
// advanced config
u32 marikoEmcDvbShift;
u32 ramTimingPresetOne;
u32 ramTimingPresetTwo;
u32 ramTimingPresetThree;
u32 ramTimingPresetFour;
u32 ramTimingPresetFive;
u32 ramTimingPresetSix;
u32 ramTimingPresetSeven;
const u32 tRAS;
const u32 tRCD;
const u32 tREFpb;
const u32 tRFCpb;
const u32 tRPpb;
const double tRRD;
const u32 R2W;
const u32 tWTR;
//
u32 marikoGpuVoltArray[17];
u32 marikoGpuVoltArray[18];
u8 marikoCpuHighVoltOffset;
u8 marikoB3;
u8 marikoCpuHighUV;
CustomizeCpuDvfsTable eristaCpuDvfsTable;
CustomizeCpuDvfsTable marikoCpuDvfsTable;
CustomizeCpuDvfsTable marikoCpuDvfsTableSLT;
@@ -86,4 +89,4 @@ extern volatile CustomizeTable C;
//extern volatile EristaMtcTable EristaMtcTablePlaceholder;
//extern volatile MarikoMtcTable MarikoMtcTablePlaceholder;
}
}

View File

@@ -26,7 +26,7 @@ struct MarikoTiming {
uint32_t emc_rfc_slr;
uint32_t emc_ras;
uint32_t emc_rp;
uint32_t emc_r2w;
uint32_t emcR2W;
uint32_t emc_w2r;
uint32_t emc_r2p;
uint32_t emc_w2p;
@@ -257,7 +257,7 @@ struct EristaTiming {
uint32_t emc_rfc_slr;
uint32_t emc_ras;
uint32_t emc_rp;
uint32_t emc_r2w;
uint32_t emcR2W;
uint32_t emc_w2r;
uint32_t emc_r2p;
uint32_t emc_w2p;
@@ -777,7 +777,7 @@ struct MarikoMtcTable {
uint32_t mc_emem_arb_timing_wap2pre;
uint32_t mc_emem_arb_timing_r2r;
uint32_t mc_emem_arb_timing_w2w;
uint32_t mc_emem_arb_timing_r2w;
uint32_t mc_emem_arb_timingR2W;
uint32_t mc_emem_arb_timing_ccdmw;
uint32_t mc_emem_arb_timing_w2r;
uint32_t mc_emem_arb_timing_rfcpb;
@@ -1170,7 +1170,7 @@ struct EristaMtcTable {
uint32_t mc_emem_arb_timing_wap2pre;
uint32_t mc_emem_arb_timing_r2r;
uint32_t mc_emem_arb_timing_w2w;
uint32_t mc_emem_arb_timing_r2w;
uint32_t mc_emem_arb_timingR2W;
uint32_t mc_emem_arb_timing_ccdmw;
uint32_t mc_emem_arb_timing_w2r;
uint32_t mc_emem_arb_timing_rfcpb;

View File

@@ -1,235 +1,172 @@
/*
* Copyright (c) 2023 hanai3Bi
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* from GCC preprocessor output
*/
#pragma once
#pragma once
#include "oc_common.hpp"
#include "oc_common.hpp"
namespace ams::ldr::oc {
#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)
const u8 ramtmarker[4] = {'R', 'A', 'M', 'T'};
//Preset One
const std::array<u32, 6> tRCD_values = {18, 17, 16, 15, 14, 13};
const std::array<u32, 6> tRP_values = {18, 17, 16, 15, 14, 13};
const std::array<u32, 6> tRAS_values = {42, 39, 36, 34, 32, 30};
// Preset Two
const std::array<double, 5> tRRD_values = {10, 7.5, 6, 4, 3};
const std::array<double, 5> tFAW_values = {40, 30, 24, 16, 12};
// Preset Three
const std::array<u32, 6> tWR_values = {18, 15, 15, 12, 12, 8};
const std::array<double, 6> tRTP_values = {7.5, 7.5, 6, 6, 4, 4};
// Preset Four
const std::array<u32, 6> tRFC_values = {140, 120, 100, 80, 70, 60};
// Preset Five
const std::array<u32, 6> tWTR_values = {10, 8, 6, 4, 2, 1};
// Preset Six
const std::array<u32, 5> tREFpb_values = {488, 976, 1952, 3256, 9999};
const u32 TIMING_PRESET_ONE = C.ramTimingPresetOne;
const u32 TIMING_PRESET_TWO = C.ramTimingPresetTwo;
const u32 TIMING_PRESET_THREE = C.ramTimingPresetThree;
const u32 TIMING_PRESET_FOUR = C.ramTimingPresetFour;
const u32 TIMING_PRESET_FIVE = C.ramTimingPresetFive;
const u32 TIMING_PRESET_SIX = C.ramTimingPresetSix;
const u32 TIMING_PRESET_SEVEN = C.ramTimingPresetSeven;
// Burst Length
const u32 BL = 16;
// tRFCpb (refresh cycle time per bank) in ns for 8Gb density
const u32 tRFCpb = !TIMING_PRESET_FOUR ? 140 : tRFC_values[TIMING_PRESET_FOUR-1];
// tRFCab (refresh cycle time all banks) in ns for 8Gb density
const u32 tRFCab = !TIMING_PRESET_FOUR ? 280 : 2*tRFCpb;
// tRAS (row active time) in ns
const u32 tRAS = !TIMING_PRESET_ONE ? 42 : tRAS_values[TIMING_PRESET_ONE-1];
// tRPpb (row precharge time per bank) in ns
const u32 tRPpb = !TIMING_PRESET_ONE ? 18 : tRP_values[TIMING_PRESET_ONE-1];
// tRPab (row precharge time all banks) in ns
const u32 tRPab = !TIMING_PRESET_ONE ? 21 : tRPpb + 3;
// tRC (ACTIVATE-ACTIVATE command period same bank) in ns
const u32 tRC = tRPpb + tRAS;
// DQS output access time from CK_t/CK_c
const double tDQSCK_min = 1.5;
// DQS output access time from CK_t/CK_c
const double tDQSCK_max = 3.5;
// Write preamble (tCK)
const double tWPRE = 1.8;
// Read postamble (tCK)
const double tRPST = 0.4;
// WRITE command to first DQS transition(max) (tCK)
const double tDQSS_max = 1.25;
// DQ-to-DQS offset(max) (ns)
const double tDQS2DQ_max = 0.8;
// DQS_t, DQS_c to DQ skew total, per group, per access (DBI Disabled)
const double tDQSQ = 0.18;
// Write-to-Read delay
const u32 tWTR = !TIMING_PRESET_FIVE ? 10 : tWTR_values[TIMING_PRESET_FIVE-1];
// Internal READ-to-PRE-CHARGE command delay in ns
const double tRTP = !TIMING_PRESET_THREE ? 7.5 : tRTP_values[TIMING_PRESET_THREE-1];
// write recovery time
const u32 tWR = !TIMING_PRESET_THREE ? 18 : tWR_values[TIMING_PRESET_THREE-1];
// Read to refresh delay
const u32 tR2REF = tRTP + tRPpb;
// tRCD (RAS-CAS delay) in ns
const u32 tRCD = !TIMING_PRESET_ONE ? 18 : tRCD_values[TIMING_PRESET_ONE-1];
// tRRD (Active bank-A to Active bank-B) in ns
const double tRRD = !TIMING_PRESET_TWO ? 10. : tRRD_values[TIMING_PRESET_TWO-1];
// tREFpb (average refresh interval per bank) in ns for 8Gb density
const u32 tREFpb = !TIMING_PRESET_SIX ? 488 : tREFpb_values[TIMING_PRESET_SIX-1];
// tREFab (average refresh interval all 8 banks) in ns for 8Gb density
// const u32 tREFab = tREFpb * 8;
// tPDEX2WR, tPDEX2RD (timing delay from exiting powerdown mode to a write/read command) in ns
// const u32 tPDEX2 = 10;
// Exit power-down to next valid command delay
const double tXP = 10;
// Delay from valid command to CKE input LOW in ns
const double tCMDCKE = 1.75;
// tACT2PDEN (timing delay from an activate, MRS or EMRS command to power-down entry) in ns
// Valid clock and CS requirement after CKE input LOW after MRW command
const u32 tMRWCKEL = 14;
// Valid CS requirement after CKE input LOW
const double tCKELCS = 5;
// Valid CS requirement before CKE input HIGH
const double tCSCKEH = 1.75;
// tXSR (SELF REFRESH exit to next valid command delay) in ns
const double tXSR = tRFCab + 7.5;
// tCKE (minimum pulse width(HIGH and LOW pulse width)) in ns
const double tCKE = 7.5;
// Minimum self refresh time (entry to exit)
const u32 tSR = 15;
// tFAW (Four-bank Activate Window) in ns
const u32 tFAW = !TIMING_PRESET_TWO ? 40 : tFAW_values[TIMING_PRESET_TWO-1];
// Valid Clock requirement before CKE Input HIGH in ns
const double tCKCKEH = 1.75;
// p78 The first valid data is available RL × t CK + t DQSCK + t DQSQ
//const u32 QUSE = RL + CEIL(tDQSCK_min/tCK_avg + tDQSQ);
namespace pcv::erista {
// tCK_avg (average clock period) in ns
const double tCK_avg = 1000'000. / C.eristaEmcMaxClock;
// Write Latency
const u32 WL = 14 - 2*TIMING_PRESET_SEVEN;
// Read Latency
const u32 RL = 32 - 4*TIMING_PRESET_SEVEN;
// minimum number of cycles from any read command to any write command, irrespective of bank
const u32 R2W = CEIL (RL + CEIL(tDQSCK_max/tCK_avg) + BL/2 - WL + tWPRE + FLOOR(tRPST)) + 6;
// Delay Time From WRITE-to-READ
const u32 W2R = WL + BL/2 + 1 + CEIL(tWTR/tCK_avg) - 6;
// write-to-precharge time for commands to the same bank in cycles
const u32 WTP = WL + BL/2 + 1 + CEIL(tWR/tCK_avg) - 8;
// #_of_rows per die for 8Gb density
const u32 numOfRows = 65536;
// {REFRESH, REFRESH_LO} = max[(tREF/#_of_rows) / (emc_clk_period) - 64, (tREF/#_of_rows) / (emc_clk_period) * 97%]
// emc_clk_period = dram_clk / 2;
// 1600 MHz: 5894, but N' set to 6176 (~4.8% margin)
const u32 REFRESH = MIN((u32)65472, u32(std::ceil((double(tREFpb) * C.eristaEmcMaxClock / numOfRows * 1.048 / 2 - 64))) / 4 * 4);
const u32 REFBW = MIN((u32)65536, REFRESH+64);
// Write With Auto Precharge to to Power-Down Entry
const u32 WTPDEN = WTP + 1 + CEIL(tDQSS_max/tCK_avg) + CEIL(tDQS2DQ_max/tCK_avg) + 6;
// Additional time after t XP hasexpired until the MRR commandmay be issued
const double tMRRI = tRCD + 3 * tCK_avg;
// tPDEX2MRR (timing delay from exiting powerdown mode to MRR command) in ns
const double tPDEX2MRR = tXP + tMRRI;
}
namespace pcv::mariko {
// tCK_avg (average clock period) in ns
const double tCK_avg = 1000'000. / C.marikoEmcMaxClock;
// Write Latency
const u32 WL = 14 - 2*TIMING_PRESET_SEVEN;
// Read Latency
const u32 RL = 32 - 4*TIMING_PRESET_SEVEN;
// minimum number of cycles from any read command to any write command, irrespective of bank
const u32 R2W = CEIL (RL + CEIL(tDQSCK_max/tCK_avg) + BL/2 - WL + tWPRE + FLOOR(tRPST));
// Delay Time From WRITE-to-READ
const u32 W2R = WL + BL/2 + 1 + CEIL(tWTR/tCK_avg);
// write-to-precharge time for commands to the same bank in cycles
const u32 WTP = WL + BL/2 + 1 + CEIL(tWR/tCK_avg);
// Read-To-MRW delay
const u32 RTM = RL + BL/2 + CEIL(tDQSCK_max/tCK_avg) + FLOOR(tRPST) + CEIL(7.5/tCK_avg);
// Write-To-MRW/MRR delay
const u32 WTM = WL + 1 + BL/2 + CEIL(7.5/tCK_avg);
// Read With AP-To-MRW/MRR delay
const u32 RATM = RTM + CEIL(tRTP/tCK_avg) - 8;
// Write With AP-To-MRW/MRR delay
const u32 WATM = WTM + CEIL(tWR/tCK_avg);
// #_of_rows per die for 8Gb density
const u32 numOfRows = 65536;
// {REFRESH, REFRESH_LO} = max[(tREF/#_of_rows) / (emc_clk_period) - 64, (tREF/#_of_rows) / (emc_clk_period) * 97%]
// emc_clk_period = dram_clk / 2;
// 1600 MHz: 5894, but N' set to 6176 (~4.8% margin)
const u32 REFRESH = MIN((u32)65472, u32(std::ceil((double(tREFpb) * C.marikoEmcMaxClock / numOfRows * 1.048 / 2 - 64))) / 4 * 4);
const u32 REFBW = MIN((u32)65536, REFRESH+64);
// Write With Auto Precharge to to Power-Down Entry
const u32 WTPDEN = WTP + 1 + CEIL(tDQSS_max/tCK_avg) + CEIL(tDQS2DQ_max/tCK_avg) + 6;
// Additional time after t XP hasexpired until the MRR commandmay be issued
const double tMRRI = tRCD + 3 * tCK_avg;
// tPDEX2MRR (timing delay from exiting powerdown mode to MRR command) in ns
const double tPDEX2MRR = tXP + tMRRI;
}
}
namespace ams::ldr::oc {
#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)
// Burst Length
const u32 BL = 16;
// tRFCab (refresh cycle time all banks) in ns for 8Gb density
const u32 tRFCab = 2*C.tRFCpb;
// C.tRAS (row active time) in ns
// C.tRPpb (row precharge time per bank) in ns
// tRPab (row precharge time all banks) in ns
const u32 tRPab = C.tRPpb + 3;
// tRC (ACTIVATE-ACTIVATE command period same bank) in ns
const u32 tRC = C.tRPpb + C.tRAS;
// DQS output access time from CK_t/CK_c
const double tDQSCK_min = 1.5;
// DQS output access time from CK_t/CK_c
const double tDQSCK_max = 3.5;
// Write preamble (tCK)
const double tWPRE = 1.8;
// Read postamble (tCK)
const double tRPST = 0.4;
// WRITE command to first DQS transition(max) (tCK)
const double tDQSS_max = 1.25;
// DQ-to-DQS offset(max) (ns)
const double tDQS2DQ_max = 0.8;
// DQS_t, DQS_c to DQ skew total, per group, per access (DBI Disabled)
const double tDQSQ = 0.18;
// Write-to-Read delay
// Internal READ-to-PRE-CHARGE command delay in ns
const double tRTP = 7.5;
// write recovery time
const u32 tWR = 18;
// Read to refresh delay
const u32 tR2REF = tRTP + C.tRPpb;
// C.tRCD (RAS-CAS delay) in ns
// C.tRRD (Active bank-A to Active bank-B) in ns
// C.tREFpb (average refresh interval per bank) in ns for 8Gb density
// tREFab (average refresh interval all 8 banks) in ns for 8Gb density
// const u32 tREFab = C.tREFpb * 8;
// tPDEX2WR, tPDEX2RD (timing delay from exiting powerdown mode to a write/read command) in ns
// const u32 tPDEX2 = 10;
// Exit power-down to next valid command delay
const double tXP = 10;
// Delay from valid command to CKE input LOW in ns
const double tCMDCKE = 1.75;
// tACT2PDEN (timing delay from an activate, MRS or EMRS command to power-down entry) in ns
// Valid clock and CS requirement after CKE input LOW after MRW command
const u32 tMRWCKEL = 14;
// Valid CS requirement after CKE input LOW
const double tCKELCS = 5;
// Valid CS requirement before CKE input HIGH
const double tCSCKEH = 1.75;
// tXSR (SELF REFRESH exit to next valid command delay) in ns
const double tXSR = tRFCab + 7.5;
// tCKE (minimum pulse width(HIGH and LOW pulse width)) in ns
const double tCKE = 7.5;
// Minimum self refresh time (entry to exit)
const u32 tSR = 15;
// tFAW (Four-bank Activate Window) in ns
const u32 tFAW = 40;
// Valid Clock requirement before CKE Input HIGH in ns
const double tCKCKEH = 1.75;
// p78 The first valid data is available RL × t CK + t DQSCK + t DQSQ
//const u32 QUSE = RL + CEIL(tDQSCK_min/tCK_avg + tDQSQ);
namespace pcv::erista {
// tCK_avg (average clock period) in ns
const double tCK_avg = 1000'000. / C.eristaEmcMaxClock;
// Write Latency
const u32 WL = 14;
// Read Latency
const u32 RL = 32;
// minimum number of cycles from any read command to any write command, irrespective of bank
// Delay Time From WRITE-to-READ
const u32 W2R = WL + BL/2 + 1 + CEIL(C.tWTR/tCK_avg) - 6;
// write-to-precharge time for commands to the same bank in cycles
const u32 WTP = WL + BL/2 + 1 + CEIL(tWR/tCK_avg) - 8;
// #_of_rows per die for 8Gb density
const u32 numOfRows = 65536;
// {REFRESH, REFRESH_LO} = max[(tREF/#_of_rows) / (emc_clk_period) - 64, (tREF/#_of_rows) / (emc_clk_period) * 97%]
// emc_clk_period = dram_clk / 2;
// 1600 MHz: 5894, but N' set to 6176 (~4.8% margin)
const u32 REFRESH = MIN((u32)65472, u32(std::ceil((double(C.tREFpb) * C.eristaEmcMaxClock / numOfRows * 1.048 / 2 - 64))) / 4 * 4);
const u32 REFBW = MIN((u32)65536, REFRESH+64);
// Write With Auto Precharge to to Power-Down Entry
const u32 WTPDEN = WTP + 1 + CEIL(tDQSS_max/tCK_avg) + CEIL(tDQS2DQ_max/tCK_avg) + 6;
// Additional time after t XP hasexpired until the MRR commandmay be issued
const double tMRRI = C.tRCD + 3 * tCK_avg;
// tPDEX2MRR (timing delay from exiting powerdown mode to MRR command) in ns
const double tPDEX2MRR = tXP + tMRRI;
}
namespace pcv::mariko {
// tCK_avg (average clock period) in ns
const double tCK_avg = 1000'000. / C.marikoEmcMaxClock;
// Write Latency
const u32 WL = 14;
// Read Latency
const u32 RL = 32;
// minimum number of cycles from any read command to any write command, irrespective of bank
// Delay Time From WRITE-to-READ
const u32 W2R = WL + BL/2 + 1 + CEIL(C.tWTR/tCK_avg);
// write-to-precharge time for commands to the same bank in cycles
const u32 WTP = WL + BL/2 + 1 + CEIL(tWR/tCK_avg);
// Read-To-MRW delay
const u32 RTM = RL + BL/2 + CEIL(tDQSCK_max/tCK_avg) + FLOOR(tRPST) + CEIL(7.5/tCK_avg);
// Write-To-MRW/MRR delay
const u32 WTM = WL + 1 + BL/2 + CEIL(7.5/tCK_avg);
// Read With AP-To-MRW/MRR delay
const u32 RATM = RTM + CEIL(tRTP/tCK_avg) - 8;
// Write With AP-To-MRW/MRR delay
const u32 WATM = WTM + CEIL(tWR/tCK_avg);
// #_of_rows per die for 8Gb density
const u32 numOfRows = 65536;
// {REFRESH, REFRESH_LO} = max[(tREF/#_of_rows) / (emc_clk_period) - 64, (tREF/#_of_rows) / (emc_clk_period) * 97%]
// emc_clk_period = dram_clk / 2;
// 1600 MHz: 5894, but N' set to 6176 (~4.8% margin)
const u32 REFRESH = MIN((u32)65472, u32(std::ceil((double(C.tREFpb) * C.marikoEmcMaxClock / numOfRows * 1.048 / 2 - 64))) / 4 * 4);
const u32 REFBW = MIN((u32)65536, REFRESH+64);
// Write With Auto Precharge to to Power-Down Entry
const u32 WTPDEN = WTP + 1 + CEIL(tDQSS_max/tCK_avg) + CEIL(tDQS2DQ_max/tCK_avg) + 6;
// Additional time after t XP hasexpired until the MRR commandmay be issued
const double tMRRI = C.tRCD + 3 * tCK_avg;
// tPDEX2MRR (timing delay from exiting powerdown mode to MRR command) in ns
const double tPDEX2MRR = tXP + tMRRI;
}
}

View File

@@ -77,13 +77,13 @@ Result Test_PcvDvfsTable() {
// Customized table default
assert(GetDvfsTableEntryCount((cvb_entry_t *)(&ams::ldr::oc::C.eristaCpuDvfsTable)) == 19);
assert(GetDvfsTableEntryCount((cvb_entry_t *)(&ams::ldr::oc::C.marikoCpuDvfsTable)) == 21);
assert(GetDvfsTableEntryCount((cvb_entry_t *)(&ams::ldr::oc::C.marikoCpuDvfsTableSLT)) == 22);
assert(GetDvfsTableEntryCount((cvb_entry_t *)(&ams::ldr::oc::C.marikoCpuDvfsTable)) == 22);
assert(GetDvfsTableEntryCount((cvb_entry_t *)(&ams::ldr::oc::C.marikoCpuDvfsTableSLT)) == 25);
assert(GetDvfsTableEntryCount((cvb_entry_t *)(&ams::ldr::oc::C.eristaGpuDvfsTable)) == 12);
assert(GetDvfsTableEntryCount((cvb_entry_t *)(&ams::ldr::oc::C.marikoGpuDvfsTable)) == 17);
assert(GetDvfsTableEntryCount((cvb_entry_t *)(&ams::ldr::oc::C.marikoGpuDvfsTableSLT)) == 17);
assert(GetDvfsTableEntryCount((cvb_entry_t *)(&ams::ldr::oc::C.marikoGpuDvfsTableHiOPT)) == 17);
assert(GetDvfsTableEntryCount((cvb_entry_t *)(&ams::ldr::oc::C.marikoGpuDvfsTable)) == 18);
assert(GetDvfsTableEntryCount((cvb_entry_t *)(&ams::ldr::oc::C.marikoGpuDvfsTableSLT)) == 18);
assert(GetDvfsTableEntryCount((cvb_entry_t *)(&ams::ldr::oc::C.marikoGpuDvfsTableHiOPT)) == 18);
constexpr size_t limit = ams::ldr::oc::pcv::DvfsTableEntryLimit;
cvb_entry_t customized_table[limit] = {};

View File

@@ -1,8 +1,6 @@
/*
* Copyright (C) Switch-OC-Suite
*
* Copyright (c) 2023 hanai3Bi
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
@@ -114,11 +112,11 @@ void SafetyCheck() {
sValidator validators[] = {
{ C.commonCpuBoostClock, 1020'000, 3000'000, true },
{ C.commonEmcMemVolt, 1100'000, 1250'000 },
{ C.commonEmcMemVolt, 1000'000, 1350'000 },
{ C.eristaCpuMaxVolt, 1100, 1300 },
{ C.eristaEmcMaxClock, 1600'000, 2131'200 },
{ C.marikoCpuMaxVolt, 1100, 1300 },
{ C.marikoEmcMaxClock, 1600'000, 2800'000 },
{ C.marikoCpuMaxVolt, 800, 1160 },
{ C.marikoEmcMaxClock, 1600'000, 3200'000 },
{ C.marikoEmcVddqVolt, 550'000, 650'000 },
{ eristaCpuDvfsMaxFreq, 1785'000, 3000'000 },
{ marikoCpuDvfsMaxFreq, 1785'000, 3000'000 },
@@ -143,4 +141,4 @@ void Patch(uintptr_t mapped_nso, size_t nso_size) {
#endif
}
}
}

View File

@@ -1,8 +1,6 @@
/*
* Copyright (C) Switch-OC-Suite
*
* Copyright (c) 2023 hanai3Bi
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.

View File

@@ -1,8 +1,6 @@
/*
* Copyright (C) Switch-OC-Suite
*
* Copyright (c) 2023 hanai3Bi
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
@@ -87,16 +85,16 @@ void MemMtcTableAutoAdjust(EristaMtcTable* table) {
WRITE_PARAM_ALL_REG(table, emc_rc, GET_CYCLE_CEIL(tRC));
WRITE_PARAM_ALL_REG(table, emc_rfc, GET_CYCLE_CEIL(tRFCab));
WRITE_PARAM_ALL_REG(table, emc_rfcpb, GET_CYCLE_CEIL(tRFCpb));
WRITE_PARAM_ALL_REG(table, emc_ras, GET_CYCLE_CEIL(tRAS));
WRITE_PARAM_ALL_REG(table, emc_rp, GET_CYCLE_CEIL(tRPpb));
WRITE_PARAM_ALL_REG(table, emc_r2w, R2W);
WRITE_PARAM_ALL_REG(table, emc_rfcpb, GET_CYCLE_CEIL(C.tRFCpb));
WRITE_PARAM_ALL_REG(table, emc_ras, GET_CYCLE_CEIL(C.tRAS));
WRITE_PARAM_ALL_REG(table, emc_rp, GET_CYCLE_CEIL(C.tRPpb));
WRITE_PARAM_ALL_REG(table, emcR2W, C.R2W);
WRITE_PARAM_ALL_REG(table, emc_w2r, W2R);
WRITE_PARAM_ALL_REG(table, emc_r2p, GET_CYCLE_CEIL(tRTP));
WRITE_PARAM_ALL_REG(table, emc_w2p, WTP);
WRITE_PARAM_ALL_REG(table, emc_rd_rcd, GET_CYCLE_CEIL(tRCD));
WRITE_PARAM_ALL_REG(table, emc_wr_rcd, GET_CYCLE_CEIL(tRCD));
WRITE_PARAM_ALL_REG(table, emc_rrd, GET_CYCLE_CEIL(tRRD));
WRITE_PARAM_ALL_REG(table, emc_rd_rcd, GET_CYCLE_CEIL(C.tRCD));
WRITE_PARAM_ALL_REG(table, emc_wr_rcd, GET_CYCLE_CEIL(C.tRCD));
WRITE_PARAM_ALL_REG(table, emc_rrd, GET_CYCLE_CEIL(C.tRRD));
WRITE_PARAM_ALL_REG(table, emc_refresh, REFRESH);
WRITE_PARAM_ALL_REG(table, emc_pre_refresh_req_cnt, REFRESH / 4);
WRITE_PARAM_ALL_REG(table, emc_pdex2wr, GET_CYCLE_CEIL(tXP));
@@ -123,19 +121,19 @@ void MemMtcTableAutoAdjust(EristaMtcTable* table) {
constexpr u32 MC_ARB_DIV = 4;
constexpr u32 MC_ARB_SFA = 2;
table->burst_mc_regs.mc_emem_arb_timing_rcd = CEIL(GET_CYCLE_CEIL(tRCD) / MC_ARB_DIV) - 2;
table->burst_mc_regs.mc_emem_arb_timing_rp = CEIL(GET_CYCLE_CEIL(tRPpb) / MC_ARB_DIV) - 1 + MC_ARB_SFA;
table->burst_mc_regs.mc_emem_arb_timing_rcd = CEIL(GET_CYCLE_CEIL(C.tRCD) / MC_ARB_DIV) - 2;
table->burst_mc_regs.mc_emem_arb_timing_rp = CEIL(GET_CYCLE_CEIL(C.tRPpb) / MC_ARB_DIV) - 1 + MC_ARB_SFA;
table->burst_mc_regs.mc_emem_arb_timing_rc = CEIL(GET_CYCLE_CEIL(tRC) / MC_ARB_DIV) - 1;
table->burst_mc_regs.mc_emem_arb_timing_ras = CEIL(GET_CYCLE_CEIL(tRAS) / MC_ARB_DIV) - 2;
table->burst_mc_regs.mc_emem_arb_timing_ras = CEIL(GET_CYCLE_CEIL(C.tRAS) / MC_ARB_DIV) - 2;
table->burst_mc_regs.mc_emem_arb_timing_faw = CEIL(GET_CYCLE_CEIL(tFAW) / MC_ARB_DIV) - 1;
table->burst_mc_regs.mc_emem_arb_timing_rrd = CEIL(GET_CYCLE_CEIL(tRRD) / MC_ARB_DIV) - 1;
table->burst_mc_regs.mc_emem_arb_timing_rrd = CEIL(GET_CYCLE_CEIL(C.tRRD) / MC_ARB_DIV) - 1;
table->burst_mc_regs.mc_emem_arb_timing_rap2pre = CEIL(GET_CYCLE_CEIL(tRTP) / MC_ARB_DIV);
table->burst_mc_regs.mc_emem_arb_timing_wap2pre = CEIL(WTP / MC_ARB_DIV);
//table->burst_mc_regs.mc_emem_arb_timing_r2r = CEIL(table->burst_regs.emc_rext / MC_ARB_DIV) - 1 + MC_ARB_SFA;
//table->burst_mc_regs.mc_emem_arb_timing_w2w = CEIL(table->burst_regs.emc_wext / MC_ARB_DIV) - 1 + MC_ARB_SFA;
table->burst_mc_regs.mc_emem_arb_timing_r2w = CEIL(R2W / MC_ARB_DIV) - 1 + MC_ARB_SFA;
table->burst_mc_regs.mc_emem_arb_timingR2W = CEIL(C.R2W / MC_ARB_DIV) - 1 + MC_ARB_SFA;
table->burst_mc_regs.mc_emem_arb_timing_w2r = CEIL(W2R / MC_ARB_DIV) - 1 + MC_ARB_SFA;
table->burst_mc_regs.mc_emem_arb_timing_rfcpb = CEIL(GET_CYCLE_CEIL(tRFCpb) / MC_ARB_DIV);
table->burst_mc_regs.mc_emem_arb_timing_rfcpb = CEIL(GET_CYCLE_CEIL(C.tRFCpb) / MC_ARB_DIV);
//table->burst_mc_regs.mc_emem_arb_timing_ccdmw = CEIL(tCCDMW / MC_ARB_DIV) -1 + MC_ARB_SFA;
}
@@ -146,72 +144,58 @@ void MemMtcTableCustomAdjust(EristaMtcTable* table) {
constexpr u32 MC_ARB_DIV = 4;
constexpr u32 MC_ARB_SFA = 2;
if (TIMING_PRESET_ONE) {
WRITE_PARAM_ALL_REG(table, emc_rc, GET_CYCLE_CEIL(tRC));
WRITE_PARAM_ALL_REG(table, emc_ras, GET_CYCLE_CEIL(tRAS));
WRITE_PARAM_ALL_REG(table, emc_rp, GET_CYCLE_CEIL(tRPpb));
WRITE_PARAM_ALL_REG(table, emc_trpab, GET_CYCLE_CEIL(tRPab));
WRITE_PARAM_ALL_REG(table, emc_rd_rcd, GET_CYCLE_CEIL(tRCD));
WRITE_PARAM_ALL_REG(table, emc_wr_rcd, GET_CYCLE_CEIL(tRCD));
WRITE_PARAM_ALL_REG(table, emc_pdex2mrr, GET_CYCLE_CEIL(tPDEX2MRR));
WRITE_PARAM_ALL_REG(table, emc_rc, GET_CYCLE_CEIL(tRC));
WRITE_PARAM_ALL_REG(table, emc_ras, GET_CYCLE_CEIL(C.tRAS));
WRITE_PARAM_ALL_REG(table, emc_rp, GET_CYCLE_CEIL(C.tRPpb));
WRITE_PARAM_ALL_REG(table, emc_trpab, GET_CYCLE_CEIL(tRPab));
WRITE_PARAM_ALL_REG(table, emc_rd_rcd, GET_CYCLE_CEIL(C.tRCD));
WRITE_PARAM_ALL_REG(table, emc_wr_rcd, GET_CYCLE_CEIL(C.tRCD));
WRITE_PARAM_ALL_REG(table, emc_pdex2mrr, GET_CYCLE_CEIL(tPDEX2MRR));
table->burst_mc_regs.mc_emem_arb_timing_rcd = CEIL(GET_CYCLE_CEIL(tRCD) / MC_ARB_DIV - 2);
table->burst_mc_regs.mc_emem_arb_timing_rc = CEIL(GET_CYCLE_CEIL(tRC) / MC_ARB_DIV - 1);
table->burst_mc_regs.mc_emem_arb_timing_rp = CEIL(GET_CYCLE_CEIL(tRPpb) / MC_ARB_DIV - 1 + MC_ARB_SFA);
table->burst_mc_regs.mc_emem_arb_timing_ras = CEIL(GET_CYCLE_CEIL(tRAS) / MC_ARB_DIV - 2);
}
table->burst_mc_regs.mc_emem_arb_timing_rcd = CEIL(GET_CYCLE_CEIL(C.tRCD) / MC_ARB_DIV - 2);
table->burst_mc_regs.mc_emem_arb_timing_rc = CEIL(GET_CYCLE_CEIL(tRC) / MC_ARB_DIV - 1);
table->burst_mc_regs.mc_emem_arb_timing_rp = CEIL(GET_CYCLE_CEIL(C.tRPpb) / MC_ARB_DIV - 1 + MC_ARB_SFA);
table->burst_mc_regs.mc_emem_arb_timing_ras = CEIL(GET_CYCLE_CEIL(C.tRAS) / MC_ARB_DIV - 2);
if (TIMING_PRESET_TWO) {
WRITE_PARAM_ALL_REG(table, emc_tfaw, GET_CYCLE_CEIL(tFAW));
WRITE_PARAM_ALL_REG(table, emc_rrd, GET_CYCLE_CEIL(tRRD));
WRITE_PARAM_ALL_REG(table, emc_tfaw, GET_CYCLE_CEIL(tFAW));
WRITE_PARAM_ALL_REG(table, emc_rrd, GET_CYCLE_CEIL(C.tRRD));
table->burst_mc_regs.mc_emem_arb_timing_faw = CEIL(GET_CYCLE_CEIL(tFAW) / MC_ARB_DIV) - 1;
table->burst_mc_regs.mc_emem_arb_timing_rrd = CEIL(GET_CYCLE_CEIL(tRRD) / MC_ARB_DIV) - 1;
}
table->burst_mc_regs.mc_emem_arb_timing_faw = CEIL(GET_CYCLE_CEIL(tFAW) / MC_ARB_DIV) - 1;
table->burst_mc_regs.mc_emem_arb_timing_rrd = CEIL(GET_CYCLE_CEIL(C.tRRD) / MC_ARB_DIV) - 1;
if (TIMING_PRESET_THREE) {
WRITE_PARAM_ALL_REG(table, emc_r2p, GET_CYCLE_CEIL(tRTP));
WRITE_PARAM_ALL_REG(table, emc_w2p, WTP);
WRITE_PARAM_ALL_REG(table, emc_rw2pden, WTPDEN);
WRITE_PARAM_ALL_REG(table, emc_r2p, GET_CYCLE_CEIL(tRTP));
WRITE_PARAM_ALL_REG(table, emc_w2p, WTP);
WRITE_PARAM_ALL_REG(table, emc_rw2pden, WTPDEN);
table->burst_mc_regs.mc_emem_arb_timing_rap2pre = CEIL(GET_CYCLE_CEIL(tRTP) / MC_ARB_DIV);
table->burst_mc_regs.mc_emem_arb_timing_wap2pre = CEIL(WTP / MC_ARB_DIV);
}
table->burst_mc_regs.mc_emem_arb_timing_rap2pre = CEIL(GET_CYCLE_CEIL(tRTP) / MC_ARB_DIV);
table->burst_mc_regs.mc_emem_arb_timing_wap2pre = CEIL(WTP / MC_ARB_DIV);
if (TIMING_PRESET_FOUR) {
WRITE_PARAM_ALL_REG(table, emc_rfc, GET_CYCLE_CEIL(tRFCab));
WRITE_PARAM_ALL_REG(table, emc_rfcpb, GET_CYCLE_CEIL(tRFCpb));
WRITE_PARAM_ALL_REG(table, emc_txsr, MIN(GET_CYCLE_CEIL(tXSR), (u32)0x3fe));
WRITE_PARAM_ALL_REG(table, emc_txsrdll, MIN(GET_CYCLE_CEIL(tXSR), (u32)0x3fe));
WRITE_PARAM_ALL_REG(table, emc_rfc, GET_CYCLE_CEIL(tRFCab));
WRITE_PARAM_ALL_REG(table, emc_rfcpb, GET_CYCLE_CEIL(C.tRFCpb));
WRITE_PARAM_ALL_REG(table, emc_txsr, MIN(GET_CYCLE_CEIL(tXSR), (u32)0x3fe));
WRITE_PARAM_ALL_REG(table, emc_txsrdll, MIN(GET_CYCLE_CEIL(tXSR), (u32)0x3fe));
table->burst_mc_regs.mc_emem_arb_timing_rfcpb = CEIL(GET_CYCLE_CEIL(tRFCpb) / MC_ARB_DIV);
}
table->burst_mc_regs.mc_emem_arb_timing_rfcpb = CEIL(GET_CYCLE_CEIL(C.tRFCpb) / MC_ARB_DIV);
if (TIMING_PRESET_FIVE) {
WRITE_PARAM_ALL_REG(table, emc_w2r, W2R);
WRITE_PARAM_ALL_REG(table, emc_w2r, W2R);
table->burst_mc_regs.mc_emem_arb_timing_w2r = CEIL(W2R / MC_ARB_DIV) - 1 + MC_ARB_SFA;
}
table->burst_mc_regs.mc_emem_arb_timing_w2r = CEIL(W2R / MC_ARB_DIV) - 1 + MC_ARB_SFA;
if (TIMING_PRESET_SIX) {
WRITE_PARAM_ALL_REG(table, emc_refresh, REFRESH);
WRITE_PARAM_ALL_REG(table, emc_pre_refresh_req_cnt, REFRESH / 4);
WRITE_PARAM_ALL_REG(table, emc_trefbw, REFBW);
}
WRITE_PARAM_ALL_REG(table, emc_refresh, REFRESH);
WRITE_PARAM_ALL_REG(table, emc_pre_refresh_req_cnt, REFRESH / 4);
WRITE_PARAM_ALL_REG(table, emc_trefbw, REFBW);
if (TIMING_PRESET_SEVEN) {
WRITE_PARAM_ALL_REG(table, emc_r2w, R2W);
WRITE_PARAM_ALL_REG(table, emc_w2r, W2R);
WRITE_PARAM_ALL_REG(table, emc_w2p, WTP);
WRITE_PARAM_ALL_REG(table, emc_rw2pden, WTPDEN);
table->burst_mc_regs.mc_emem_arb_timing_wap2pre = CEIL(WTP / MC_ARB_DIV);
table->burst_mc_regs.mc_emem_arb_timing_r2w = CEIL(R2W / MC_ARB_DIV) - 1 + MC_ARB_SFA;
table->burst_mc_regs.mc_emem_arb_timing_w2r = CEIL(W2R / MC_ARB_DIV) - 1 + MC_ARB_SFA;
}
WRITE_PARAM_ALL_REG(table, emcR2W, C.R2W);
WRITE_PARAM_ALL_REG(table, emc_w2r, W2R);
WRITE_PARAM_ALL_REG(table, emc_w2p, WTP);
WRITE_PARAM_ALL_REG(table, emc_rw2pden, WTPDEN);
table->burst_mc_regs.mc_emem_arb_timing_wap2pre = CEIL(WTP / MC_ARB_DIV);
table->burst_mc_regs.mc_emem_arb_timingR2W = CEIL(C.R2W / MC_ARB_DIV) - 1 + MC_ARB_SFA;
table->burst_mc_regs.mc_emem_arb_timing_w2r = CEIL(W2R / MC_ARB_DIV) - 1 + MC_ARB_SFA;
u32 DA_TURNS = 0;
DA_TURNS |= u8(table->burst_mc_regs.mc_emem_arb_timing_r2w / 2) << 16; //R2W TURN
DA_TURNS |= u8(table->burst_mc_regs.mc_emem_arb_timingR2W / 2) << 16; //C.R2W TURN
DA_TURNS |= u8(table->burst_mc_regs.mc_emem_arb_timing_w2r / 2) << 24; //W2R TURN
WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_da_turns, DA_TURNS);
u32 DA_COVERS = 0;

View File

@@ -1,8 +1,6 @@
/*
* Copyright (C) Switch-OC-Suite
*
* Copyright (c) 2023 hanai3Bi
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
@@ -74,12 +72,16 @@ Result CpuVoltDfll(u32* ptr) {
if (C.marikoCpuUV) {
if (C.marikoCpuUV == 1) {
PATCH_OFFSET(&(entry->tune0_low), 0x0000FF90); //process_id 0
} else if (C.marikoCpuUV == 2) {
PATCH_OFFSET(&(entry->tune0_high), 0x0000FFFF);
PATCH_OFFSET(&(entry->tune1_low), 0x021107FF);
PATCH_OFFSET(&(entry->tune1_high), 0x00000000);
}
else if (C.marikoCpuUV == 2) {
PATCH_OFFSET(&(entry->tune0_low), 0x0000FFA0); //process_id 1
PATCH_OFFSET(&(entry->tune0_high), 0x0000FFFF);
PATCH_OFFSET(&(entry->tune1_low), 0x021107FF);
PATCH_OFFSET(&(entry->tune1_high), 0x00000000);
}
PATCH_OFFSET(&(entry->tune0_high), 0x0000FFFF);
PATCH_OFFSET(&(entry->tune1_low), 0x021107FF);
PATCH_OFFSET(&(entry->tune1_high), 0x00000000);
}
R_SUCCEED();
@@ -184,10 +186,10 @@ void MemMtcTableAutoAdjust(MarikoMtcTable* table, const MarikoMtcTable* ref) {
WRITE_PARAM_ALL_REG(table, emc_rc, GET_CYCLE_CEIL(tRC));
WRITE_PARAM_ALL_REG(table, emc_rfc, GET_CYCLE_CEIL(tRFCab));
WRITE_PARAM_ALL_REG(table, emc_rfcpb, GET_CYCLE_CEIL(tRFCpb));
WRITE_PARAM_ALL_REG(table, emc_ras, GET_CYCLE_CEIL(tRAS));
WRITE_PARAM_ALL_REG(table, emc_rp, GET_CYCLE_CEIL(tRPpb));
WRITE_PARAM_ALL_REG(table, emc_r2w, R2W);
WRITE_PARAM_ALL_REG(table, emc_rfcpb, GET_CYCLE_CEIL(C.tRFCpb));
WRITE_PARAM_ALL_REG(table, emc_ras, GET_CYCLE_CEIL(C.tRAS));
WRITE_PARAM_ALL_REG(table, emc_rp, GET_CYCLE_CEIL(C.tRPpb));
WRITE_PARAM_ALL_REG(table, emcR2W, C.R2W);
WRITE_PARAM_ALL_REG(table, emc_w2r, W2R);
WRITE_PARAM_ALL_REG(table, emc_r2p, GET_CYCLE_CEIL(tRTP));
WRITE_PARAM_ALL_REG(table, emc_w2p, WTP);
@@ -196,9 +198,9 @@ void MemMtcTableAutoAdjust(MarikoMtcTable* table, const MarikoMtcTable* ref) {
WRITE_PARAM_ALL_REG(table, emc_tratm, RATM);
WRITE_PARAM_ALL_REG(table, emc_twatm, WATM);
//WRITE_PARAM_ALL_REG(table, emc_tr2ref, GET_CYCLE_CEIL(tR2REF));
WRITE_PARAM_ALL_REG(table, emc_rd_rcd, GET_CYCLE_CEIL(tRCD));
WRITE_PARAM_ALL_REG(table, emc_wr_rcd, GET_CYCLE_CEIL(tRCD));
WRITE_PARAM_ALL_REG(table, emc_rrd, GET_CYCLE_CEIL(tRRD));
WRITE_PARAM_ALL_REG(table, emc_rd_rcd, GET_CYCLE_CEIL(C.tRCD));
WRITE_PARAM_ALL_REG(table, emc_wr_rcd, GET_CYCLE_CEIL(C.tRCD));
WRITE_PARAM_ALL_REG(table, emc_rrd, GET_CYCLE_CEIL(C.tRRD));
WRITE_PARAM_ALL_REG(table, emc_rext, 26);
WRITE_PARAM_ALL_REG(table, emc_refresh, REFRESH);
WRITE_PARAM_ALL_REG(table, emc_pre_refresh_req_cnt, REFRESH / 4);
@@ -238,21 +240,21 @@ void MemMtcTableAutoAdjust(MarikoMtcTable* table, const MarikoMtcTable* ref) {
constexpr u32 MC_ARB_SFA = 2;
WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_cfg, C.marikoEmcMaxClock / (33.3 * 1000) / MC_ARB_DIV); //CYCLES_PER_UPDATE: The number of mcclk cycles per deadline timer update
WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_timing_rcd, CEIL(GET_CYCLE_CEIL(tRCD) / MC_ARB_DIV) - 2)
WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_timing_rp, CEIL(GET_CYCLE_CEIL(tRPpb) / MC_ARB_DIV) - 1 + MC_ARB_SFA)
WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_timing_rcd, CEIL(GET_CYCLE_CEIL(C.tRCD) / MC_ARB_DIV) - 2)
WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_timing_rp, CEIL(GET_CYCLE_CEIL(C.tRPpb) / MC_ARB_DIV) - 1 + MC_ARB_SFA)
WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_timing_rc, CEIL(GET_CYCLE_CEIL(tRC) / MC_ARB_DIV) - 1)
WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_timing_ras, CEIL(GET_CYCLE_CEIL(tRAS) / MC_ARB_DIV) - 2)
WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_timing_ras, CEIL(GET_CYCLE_CEIL(C.tRAS) / MC_ARB_DIV) - 2)
WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_timing_faw, CEIL(GET_CYCLE_CEIL(tFAW) / MC_ARB_DIV) - 1)
WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_timing_rrd, CEIL(GET_CYCLE_CEIL(tRRD) / MC_ARB_DIV) - 1)
WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_timing_rrd, CEIL(GET_CYCLE_CEIL(C.tRRD) / MC_ARB_DIV) - 1)
WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_timing_rap2pre, CEIL(GET_CYCLE_CEIL(tRTP) / MC_ARB_DIV))
WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_timing_wap2pre, CEIL((WTP) / MC_ARB_DIV))
WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_timing_r2r, CEIL(table->burst_regs.emc_rext / MC_ARB_DIV) - 1 + MC_ARB_SFA)
WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_timing_r2w, CEIL((R2W) / MC_ARB_DIV) - 1 + MC_ARB_SFA)
WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_timingR2W, CEIL((C.R2W) / MC_ARB_DIV) - 1 + MC_ARB_SFA)
WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_timing_w2r, CEIL((W2R) / MC_ARB_DIV) - 1 + MC_ARB_SFA)
WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_timing_rfcpb, CEIL(GET_CYCLE_CEIL(tRFCpb) / MC_ARB_DIV))
WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_timing_rfcpb, CEIL(GET_CYCLE_CEIL(C.tRFCpb) / MC_ARB_DIV))
u32 DA_TURNS = 0;
DA_TURNS |= u8(table->burst_mc_regs.mc_emem_arb_timing_r2w / 2) << 16; //R2W TURN
DA_TURNS |= u8(table->burst_mc_regs.mc_emem_arb_timingR2W / 2) << 16; //C.R2W TURN
DA_TURNS |= u8(table->burst_mc_regs.mc_emem_arb_timing_w2r / 2) << 24; //W2R TURN
WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_da_turns, DA_TURNS);
u32 DA_COVERS = 0;
@@ -318,7 +320,7 @@ void MemMtcTableAutoAdjust(MarikoMtcTable* table, const MarikoMtcTable* ref) {
table->pllmb_ss_ctrl1 = 0x0b55fe01;
table->pllmb_ss_ctrl2 = 0x10170b55;
table->dram_timings.t_rp = tRPpb;
table->dram_timings.t_rp = C.tRPpb;
table->dram_timings.t_rfc = tRFCab;
//table->dram_timings.rl = 32;
@@ -332,79 +334,64 @@ void MemMtcTableCustomAdjust(MarikoMtcTable* table) {
constexpr u32 MC_ARB_DIV = 4;
constexpr u32 MC_ARB_SFA = 2;
if (TIMING_PRESET_ONE) {
WRITE_PARAM_ALL_REG(table, emc_rc, GET_CYCLE_CEIL(tRC));
WRITE_PARAM_ALL_REG(table, emc_ras, GET_CYCLE_CEIL(tRAS));
WRITE_PARAM_ALL_REG(table, emc_rp, GET_CYCLE_CEIL(tRPpb));
WRITE_PARAM_ALL_REG(table, emc_trpab, GET_CYCLE_CEIL(tRPab));
WRITE_PARAM_ALL_REG(table, emc_rd_rcd, GET_CYCLE_CEIL(tRCD));
WRITE_PARAM_ALL_REG(table, emc_wr_rcd, GET_CYCLE_CEIL(tRCD));
WRITE_PARAM_ALL_REG(table, emc_pdex2mrr,GET_CYCLE_CEIL(tPDEX2MRR));
WRITE_PARAM_ALL_REG(table, emc_rc, GET_CYCLE_CEIL(tRC));
WRITE_PARAM_ALL_REG(table, emc_ras, GET_CYCLE_CEIL(C.tRAS));
WRITE_PARAM_ALL_REG(table, emc_rp, GET_CYCLE_CEIL(C.tRPpb));
WRITE_PARAM_ALL_REG(table, emc_trpab, GET_CYCLE_CEIL(tRPab));
WRITE_PARAM_ALL_REG(table, emc_rd_rcd, GET_CYCLE_CEIL(C.tRCD));
WRITE_PARAM_ALL_REG(table, emc_wr_rcd, GET_CYCLE_CEIL(C.tRCD));
WRITE_PARAM_ALL_REG(table, emc_pdex2mrr,GET_CYCLE_CEIL(tPDEX2MRR));
table->burst_mc_regs.mc_emem_arb_timing_rcd = CEIL(GET_CYCLE_CEIL(tRCD) / MC_ARB_DIV) - 2;
table->burst_mc_regs.mc_emem_arb_timing_rc = CEIL(GET_CYCLE_CEIL(tRC) / MC_ARB_DIV) - 1;
table->burst_mc_regs.mc_emem_arb_timing_rp = CEIL(GET_CYCLE_CEIL(tRPpb) / MC_ARB_DIV) - 1 + MC_ARB_SFA;
table->burst_mc_regs.mc_emem_arb_timing_ras = CEIL(GET_CYCLE_CEIL(tRAS) / MC_ARB_DIV) - 2;
table->burst_mc_regs.mc_emem_arb_timing_rcd = CEIL(GET_CYCLE_CEIL(C.tRCD) / MC_ARB_DIV) - 2;
table->burst_mc_regs.mc_emem_arb_timing_rc = CEIL(GET_CYCLE_CEIL(tRC) / MC_ARB_DIV) - 1;
table->burst_mc_regs.mc_emem_arb_timing_rp = CEIL(GET_CYCLE_CEIL(C.tRPpb) / MC_ARB_DIV) - 1 + MC_ARB_SFA;
table->burst_mc_regs.mc_emem_arb_timing_ras = CEIL(GET_CYCLE_CEIL(C.tRAS) / MC_ARB_DIV) - 2;
}
if (TIMING_PRESET_TWO) {
WRITE_PARAM_ALL_REG(table, emc_tfaw, GET_CYCLE_CEIL(tFAW));
WRITE_PARAM_ALL_REG(table, emc_rrd, GET_CYCLE_CEIL(tRRD));
WRITE_PARAM_ALL_REG(table, emc_tfaw, GET_CYCLE_CEIL(tFAW));
WRITE_PARAM_ALL_REG(table, emc_rrd, GET_CYCLE_CEIL(C.tRRD));
table->burst_mc_regs.mc_emem_arb_timing_faw = CEIL(GET_CYCLE_CEIL(tFAW) / MC_ARB_DIV) - 1;
table->burst_mc_regs.mc_emem_arb_timing_rrd = CEIL(GET_CYCLE_CEIL(tRRD) / MC_ARB_DIV) - 1;
}
table->burst_mc_regs.mc_emem_arb_timing_faw = CEIL(GET_CYCLE_CEIL(tFAW) / MC_ARB_DIV) - 1;
table->burst_mc_regs.mc_emem_arb_timing_rrd = CEIL(GET_CYCLE_CEIL(C.tRRD) / MC_ARB_DIV) - 1;
if (TIMING_PRESET_THREE) {
WRITE_PARAM_ALL_REG(table, emc_r2p, GET_CYCLE_CEIL(tRTP));
WRITE_PARAM_ALL_REG(table, emc_w2p, WTP);
WRITE_PARAM_ALL_REG(table, emc_tratm, RATM);
WRITE_PARAM_ALL_REG(table, emc_twatm, WATM);
WRITE_PARAM_ALL_REG(table, emc_rw2pden, WTPDEN);
WRITE_PARAM_ALL_REG(table, emc_r2p, GET_CYCLE_CEIL(tRTP));
WRITE_PARAM_ALL_REG(table, emc_w2p, WTP);
WRITE_PARAM_ALL_REG(table, emc_tratm, RATM);
WRITE_PARAM_ALL_REG(table, emc_twatm, WATM);
WRITE_PARAM_ALL_REG(table, emc_rw2pden, WTPDEN);
table->burst_mc_regs.mc_emem_arb_timing_rap2pre = CEIL(GET_CYCLE_CEIL(tRTP) / MC_ARB_DIV);
table->burst_mc_regs.mc_emem_arb_timing_wap2pre = CEIL(WTP / MC_ARB_DIV);
}
table->burst_mc_regs.mc_emem_arb_timing_rap2pre = CEIL(GET_CYCLE_CEIL(tRTP) / MC_ARB_DIV);
table->burst_mc_regs.mc_emem_arb_timing_wap2pre = CEIL(WTP / MC_ARB_DIV);
if (TIMING_PRESET_FOUR) {
WRITE_PARAM_ALL_REG(table, emc_rfc, GET_CYCLE_CEIL(tRFCab));
WRITE_PARAM_ALL_REG(table, emc_rfcpb, GET_CYCLE_CEIL(tRFCpb));
WRITE_PARAM_ALL_REG(table, emc_txsr, MIN(GET_CYCLE_CEIL(tXSR), (u32)0x3fe));
WRITE_PARAM_ALL_REG(table, emc_txsrdll, MIN(GET_CYCLE_CEIL(tXSR), (u32)0x3fe));
WRITE_PARAM_ALL_REG(table, emc_rfc, GET_CYCLE_CEIL(tRFCab));
WRITE_PARAM_ALL_REG(table, emc_rfcpb, GET_CYCLE_CEIL(C.tRFCpb));
WRITE_PARAM_ALL_REG(table, emc_txsr, MIN(GET_CYCLE_CEIL(tXSR), (u32)0x3fe));
WRITE_PARAM_ALL_REG(table, emc_txsrdll, MIN(GET_CYCLE_CEIL(tXSR), (u32)0x3fe));
table->burst_mc_regs.mc_emem_arb_timing_rfcpb = CEIL(GET_CYCLE_CEIL(tRFCpb) / MC_ARB_DIV);
}
table->burst_mc_regs.mc_emem_arb_timing_rfcpb = CEIL(GET_CYCLE_CEIL(C.tRFCpb) / MC_ARB_DIV);
if (TIMING_PRESET_FIVE) {
WRITE_PARAM_ALL_REG(table, emc_w2r, W2R);
WRITE_PARAM_ALL_REG(table, emc_w2r, W2R);
table->burst_mc_regs.mc_emem_arb_timing_w2r = CEIL(W2R / MC_ARB_DIV) - 1 + MC_ARB_SFA;
}
table->burst_mc_regs.mc_emem_arb_timing_w2r = CEIL(W2R / MC_ARB_DIV) - 1 + MC_ARB_SFA;
if (TIMING_PRESET_SIX) {
WRITE_PARAM_ALL_REG(table, emc_refresh, REFRESH);
WRITE_PARAM_ALL_REG(table, emc_pre_refresh_req_cnt, REFRESH / 4);
WRITE_PARAM_ALL_REG(table, emc_trefbw, REFBW);
}
WRITE_PARAM_ALL_REG(table, emc_refresh, REFRESH);
WRITE_PARAM_ALL_REG(table, emc_pre_refresh_req_cnt, REFRESH / 4);
WRITE_PARAM_ALL_REG(table, emc_trefbw, REFBW);
if (TIMING_PRESET_SEVEN) {
WRITE_PARAM_ALL_REG(table, emc_r2w, R2W);
WRITE_PARAM_ALL_REG(table, emc_w2r, W2R);
WRITE_PARAM_ALL_REG(table, emc_w2p, WTP);
WRITE_PARAM_ALL_REG(table, emc_trtm, RTM);
WRITE_PARAM_ALL_REG(table, emc_twtm, WTM);
WRITE_PARAM_ALL_REG(table, emc_tratm, RATM);
WRITE_PARAM_ALL_REG(table, emc_twatm, WATM);
WRITE_PARAM_ALL_REG(table, emc_rw2pden, WTPDEN);
WRITE_PARAM_ALL_REG(table, emcR2W, C.R2W);
WRITE_PARAM_ALL_REG(table, emc_w2r, W2R);
WRITE_PARAM_ALL_REG(table, emc_w2p, WTP);
WRITE_PARAM_ALL_REG(table, emc_trtm, RTM);
WRITE_PARAM_ALL_REG(table, emc_twtm, WTM);
WRITE_PARAM_ALL_REG(table, emc_tratm, RATM);
WRITE_PARAM_ALL_REG(table, emc_twatm, WATM);
WRITE_PARAM_ALL_REG(table, emc_rw2pden, WTPDEN);
table->burst_mc_regs.mc_emem_arb_timing_wap2pre = CEIL(WTP / MC_ARB_DIV);
table->burst_mc_regs.mc_emem_arb_timing_r2w = CEIL(R2W / MC_ARB_DIV) - 1 + MC_ARB_SFA;
table->burst_mc_regs.mc_emem_arb_timing_w2r = CEIL(W2R / MC_ARB_DIV) - 1 + MC_ARB_SFA;
}
table->burst_mc_regs.mc_emem_arb_timing_wap2pre = CEIL(WTP / MC_ARB_DIV);
table->burst_mc_regs.mc_emem_arb_timingR2W = CEIL(C.R2W / MC_ARB_DIV) - 1 + MC_ARB_SFA;
table->burst_mc_regs.mc_emem_arb_timing_w2r = CEIL(W2R / MC_ARB_DIV) - 1 + MC_ARB_SFA;
u32 DA_TURNS = 0;
DA_TURNS |= u8(table->burst_mc_regs.mc_emem_arb_timing_r2w / 2) << 16; //R2W TURN
DA_TURNS |= u8(table->burst_mc_regs.mc_emem_arb_timingR2W / 2) << 16; //C.R2W TURN
DA_TURNS |= u8(table->burst_mc_regs.mc_emem_arb_timing_w2r / 2) << 24; //W2R TURN
WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_da_turns, DA_TURNS);
u32 DA_COVERS = 0;
@@ -626,4 +613,4 @@ void Patch(uintptr_t mapped_nso, size_t nso_size) {
}
}
}
}

View File

@@ -0,0 +1,74 @@
#!python3
import sys
import os
def file_replace_str(file_path, search_replace_list):
assert file_path
assert search_replace_list
with open(file_path, "r") as f:
content = f.read()
for entry in search_replace_list:
(search, replace) = entry
if search in content:
content = content.replace(search, replace)
else:
assert replace in content, f"Pattern \"{search}\" not found"
with open(file_path, "w") as f:
f.write(content)
dir_path = os.path.dirname(__file__)
os.chdir(dir_path)
os.system("git reset --hard")
ldr_process_creation = os.path.join(dir_path, "ldr_process_creation.cpp")
file_replace_str(ldr_process_creation,
[("""#include "ldr_ro_manager.hpp"
namespace ams::ldr {""",
"""#include "ldr_ro_manager.hpp"
#include "oc/oc_loader.hpp"
namespace ams::ldr {"""),
(""" NsoHeader g_nso_headers[Nso_Count];
Result ValidateProgramVersion(ncm::ProgramId program_id, u32 version) {""",
""" NsoHeader g_nso_headers[Nso_Count];
/* Pcv/Ptm check cache. */
bool g_is_pcv;
bool g_is_ptm;
Result ValidateProgramVersion(ncm::ProgramId program_id, u32 version) {"""),
(""" R_UNLESS(meta->aci->program_id <= meta->acid->program_id_max, ldr::ResultInvalidProgramId());
/* Validate the kernel capabilities. */""",
""" R_UNLESS(meta->aci->program_id <= meta->acid->program_id_max, ldr::ResultInvalidProgramId());
/* Check if nca is pcv or ptm */
g_is_pcv = meta->aci->program_id == ncm::SystemProgramId::Pcv;
g_is_ptm = meta->aci->program_id == ncm::SystemProgramId::Ptm;
/* Validate the kernel capabilities. */"""),
(""" LocateAndApplyIpsPatchesToModule(nso_header->module_id, map_address, nso_size);
}""",
""" LocateAndApplyIpsPatchesToModule(nso_header->module_id, map_address, nso_size);
/* Apply pcv and ptm patches. */
if (g_is_pcv)
oc::pcv::Patch(map_address, nso_size);
if (g_is_ptm)
oc::ptm::Patch(map_address, nso_size);
}""")])
ldr_meta = os.path.join(dir_path, "ldr_meta.cpp")
file_replace_str(ldr_meta,
[(""" Result ValidateAcidSignature(Meta *meta) {
/* Loader did not check signatures prior to 10.0.0. */""",
""" Result ValidateAcidSignature(Meta *meta) {
R_SUCCEED();
/* Loader did not check signatures prior to 10.0.0. */""")])

287
Source/ReverseNX-RT.diff Normal file
View File

@@ -0,0 +1,287 @@
diff --git a/Overlay/Makefile b/Overlay/Makefile
index 9656834..3b2ebd5 100644
--- a/Overlay/Makefile
+++ b/Overlay/Makefile
@@ -38,7 +38,7 @@ include $(DEVKITPRO)/libnx/switch_rules
# NACP building is skipped as well.
#---------------------------------------------------------------------------------
APP_TITLE := ReverseNX-RT
-APP_VERSION := 1.1.1
+APP_VERSION := 1.1.1-OC
TARGET := ReverseNX-RT-ovl
BUILD := build
diff --git a/Overlay/source/main.cpp b/Overlay/source/main.cpp
index 810295c..2b3aa52 100644
--- a/Overlay/source/main.cpp
+++ b/Overlay/source/main.cpp
@@ -1,7 +1,202 @@
#define TESLA_INIT_IMPL // If you have more than one file using the tesla header, only define this in the main one
#include <tesla.hpp> // The Tesla Header
+#include <atomic>
#include "SaltyNX.h"
+class ModeSync {
+public:
+ enum ReverseNXMode {
+ ReverseNX_NotValid = 0,
+ ReverseNX_SystemDefault = 0,
+ ReverseNX_Handheld,
+ ReverseNX_Docked,
+ ReverseNX_Undefined,
+ };
+
+ void SetMode(bool isDefault, bool setDock, char* descBuf, size_t bufSize) {
+ auto changeHandler = [this](ReverseNXMode newMode) {
+ if (this->currentMode == ReverseNX_Undefined || this->currentMode != newMode) {
+ if (R_FAILED(this->ipc->SetMode(newMode))) {
+ this->ipc->ipcStatus = Ipc::IpcStatus_ConnectFailed;
+ return;
+ }
+ this->currentMode = newMode;
+ }
+ };
+
+ tsl::hlp::ScopeGuard updateBufGuard([&] { this->ipc->UpdateStatusDesc(descBuf, bufSize); });
+
+ if (isDefault) {
+ changeHandler(ReverseNX_SystemDefault);
+ return;
+ }
+
+ changeHandler(setDock ? ReverseNX_Docked : ReverseNX_Handheld);
+ }
+
+ ModeSync() {
+ this->ipc = new Ipc;
+ this->ipc->Init();
+ }
+
+ ~ModeSync() {
+ this->ipc->Exit();
+ delete this->ipc;
+ }
+
+protected:
+ struct Ipc {
+ #define API_VER 2
+ #define SERVICE_NAME "sysclkOC"
+
+ enum SysClkIpcCmd {
+ SysClkIpcCmd_GetApiVersion = 0,
+ SysClkIpcCmd_GetConfigValues = 9,
+ SysClkIpcCmd_SetReverseNXRTMode = 11,
+ };
+
+ enum SysClkConfigValue {
+ SysClkConfigValue_SyncReverseNXMode = 4,
+ SysClkConfigValue_EnumMax = 8,
+ };
+
+ struct SysClkConfigValueList {
+ uint64_t values[SysClkConfigValue_EnumMax];
+ };
+
+ enum IpcStatus {
+ IpcStatus_OK,
+
+ IpcStatus_Unknown,
+ IpcStatus_NotRunning,
+ IpcStatus_InitFailed,
+ IpcStatus_ConnectFailed,
+ IpcStatus_UnsupportedVer,
+
+ IpcStatus_Count,
+ };
+
+ static constexpr const char* IpcStatusStr[IpcStatus_Count] = {
+ "",
+
+ "Unknown",
+ "Err: Not running",
+ "Err: Failed to init",
+ "Err: Failed to connect",
+ "Err: Unsupported version",
+ };
+
+ Result Init() {
+ Result rc = 0;
+
+ rc = IpcInitialize();
+
+ rc = GetStatus();
+
+ return rc;
+ }
+
+ void Exit() {
+ if (--refCnt == 0)
+ serviceClose(&service);
+ }
+
+ bool IsServiceRunning() {
+ Handle handle;
+ SmServiceName name = smEncodeName(SERVICE_NAME);
+ if (R_FAILED(smRegisterService(&handle, name, false, 1))) {
+ return true;
+ }
+ svcCloseHandle(handle);
+ smUnregisterService(name);
+ return false;
+ }
+
+ Result IpcInitialize(void) {
+ Result rc = 0;
+ refCnt++;
+
+ if (serviceIsActive(&service))
+ return 0;
+
+ rc = smGetService(&service, SERVICE_NAME);
+
+ if (R_FAILED(rc)) {
+ this->ipcStatus = IpcStatus_InitFailed;
+ rc = this->ipcStatus;
+ this->Exit();
+ return rc;
+ }
+
+ return rc;
+ }
+
+ Result GetApiVersion(u32* outVer) {
+ return serviceDispatchOut(&service, SysClkIpcCmd_GetApiVersion, *outVer);
+ }
+
+ Result GetConfigValues(SysClkConfigValueList* outConfigValues) {
+ return serviceDispatchOut(&service, SysClkIpcCmd_GetConfigValues, *outConfigValues);
+ }
+
+ Result SetMode(ReverseNXMode mode) {
+ return serviceDispatchIn(&service, SysClkIpcCmd_SetReverseNXRTMode, mode);
+ }
+
+ Result GetStatus() {
+ if (!IsServiceRunning()) {
+ this->ipcStatus = IpcStatus_NotRunning;
+ return this->ipcStatus;
+ }
+
+ tsl::hlp::ScopeGuard exitSrvGuard([&] { this->Exit(); });
+
+ uint32_t api_ver;
+ if (R_FAILED(GetApiVersion(&api_ver))) {
+ this->ipcStatus = IpcStatus_ConnectFailed;
+ return this->ipcStatus;
+ }
+
+ if (api_ver != API_VER) {
+ this->ipcStatus = IpcStatus_UnsupportedVer;
+ return this->ipcStatus;
+ }
+
+ SysClkConfigValueList* list = new SysClkConfigValueList;
+ tsl::hlp::ScopeGuard listGuard([&] { delete list; });
+
+ if (R_FAILED(GetConfigValues(list))) {
+ this->ipcStatus = IpcStatus_ConnectFailed;
+ return this->ipcStatus;
+ }
+
+ exitSrvGuard.dismiss();
+
+ shouldSync = bool(list->values[SysClkConfigValue_SyncReverseNXMode]);
+ this->ipcStatus = IpcStatus_OK;
+ return this->ipcStatus;
+ }
+
+ void UpdateStatusDesc(char* buffer, size_t size) {
+ snprintf(buffer, size,
+ "Mode Sync: %s%s",
+ IpcStatusStr[ipcStatus],
+ (ipcStatus == IpcStatus_OK) ? (
+ shouldSync ? "ON" : "OFF"
+ ) : ""
+ );
+ }
+
+ Service service = {};
+ std::atomic<std::size_t> refCnt = 0;
+ IpcStatus ipcStatus = IpcStatus_Unknown;
+ bool shouldSync = false;
+ };
+
+ Ipc* ipc = nullptr;
+ ReverseNXMode currentMode = ReverseNX_Undefined;
+};
+
bool* def = 0;
bool* isDocked = 0;
bool* pluginActive = 0;
@@ -17,6 +212,7 @@ bool plugin = false;
char DockedChar[32];
char SystemChar[32];
char PluginChar[36];
+char SysclkChar[0x40];
uint64_t PID = 0;
Handle remoteSharedMemory = 1;
SharedMemory _sharedmemory = {};
@@ -73,7 +269,7 @@ bool CheckPort () {
class GuiTest : public tsl::Gui {
public:
- GuiTest(u8 arg1, u8 arg2, bool arg3) { }
+ GuiTest(ModeSync* p) : modeSync(p) { }
// Called when this Gui gets loaded to create the UI
// Allocate all elements on the heap. libtesla will make sure to clean them up when not needed anymore
@@ -112,6 +308,7 @@ public:
else {
renderer->drawString(SystemChar, false, x, y+40, 20, renderer->a(0xFFFF));
renderer->drawString(DockedChar, false, x, y+60, 20, renderer->a(0xFFFF));
+ renderer->drawString(SysclkChar, false, x, y+80, 20, renderer->a(0xFFFF));
}
}
}), 100);
@@ -190,6 +387,8 @@ public:
if (_def) sprintf(SystemChar, "Controlled by system: Yes");
else sprintf(SystemChar, "Controlled by system: No");
+
+ modeSync->SetMode(_def, _isDocked, SysclkChar, sizeof(SysclkChar));
}
else i++;
}
@@ -200,6 +399,8 @@ public:
virtual bool handleInput(u64 keysDown, u64 keysHeld, const HidTouchState &touchPos, HidAnalogStickState joyStickPosLeft, HidAnalogStickState joyStickPosRight) override {
return false; // Return true here to singal the inputs have been consumed
}
+
+ ModeSync* modeSync;
};
class OverlayTest : public tsl::Overlay {
@@ -248,9 +449,11 @@ public:
});
+ modeSync = new ModeSync;
} // Called at the start to initialize all services necessary for this Overlay
virtual void exitServices() override {
+ delete modeSync;
shmemClose(&_sharedmemory);
fsdevUnmountDevice("sdmc");
} // Callet at the end to clean up all services previously initialized
@@ -260,8 +463,10 @@ public:
virtual void onHide() override {} // Called before overlay wants to change from visible to invisible state
virtual std::unique_ptr<tsl::Gui> loadInitialGui() override {
- return initially<GuiTest>(1, 2, true); // Initial Gui to load. It's possible to pass arguments to it's constructor like this
+ return initially<GuiTest>(modeSync); // Initial Gui to load. It's possible to pass arguments to it's constructor like this
}
+
+ ModeSync* modeSync = nullptr;
};
int main(int argc, char **argv) {

View File

@@ -903,7 +903,7 @@ int main(int argc, char* argv[])
printf("TinyMemBenchNX v0.4.11\n\
(based on tinymembench-pthread, a multi-thread fork of simple benchmark for memory throughput and latency)\n\n");
printf("Copyright (c) 2011-2016 Siarhei Siamashka\n");
printf("Copyright (c) 2021-2022 KazushiMe\n");
printf("Copyright (c) 2023 hanai3Bi\n");
printf("\n");

View File

@@ -0,0 +1 @@
dist

View File

@@ -0,0 +1,7 @@
--------------------------------------------------------------------------
"THE BEER-WARE LICENSE" (Revision 42):
<p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
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
--------------------------------------------------------------------------

View File

@@ -0,0 +1,224 @@
# sys-clk-OC
Switch sysmodule allowing you to set cpu/gpu clocks according to the running application and docked state.
## Clock table (MHz)
official means HOS official, unless specified
### CPU clocks
* 2397 → OC max for Mariko (with CPU UV)
* 2295 → OC max for Mariko
* 2193
* 2091 → OC max for Erista
* 1963 → official and safe max for Mariko
* 1887
* 1785 → official boost mode, safe max for Erista
* 1683
* 1581
* 1428
* 1326
* 1224 → sdev OC
* 1122
* 1020 → official docked & handheld
* 918
* 816
* 714
* 612
### GPU clocks
* 1305 → N/A
* 1267 → official max for Mariko (Tegra X1+ official max)
* 1228 → recommended max for Hiopt
* 1152
* 1075 → recommended max for SLT
* 998 → safe max for Mariko, max for Erista (Tegra X1 official max)
* 921 → safe max for Erista
* 844
* 768 → official docked
* 691
* 614 → recommended Mariko max for handheld
* 537
* 460 → max handheld
* 384 → official handheld
* 307 → official handheld
* 230
* 153
* 76 → boost mode
### MEM clocks
From Hekate Minerva module [sys_sdrammtc.c](https://github.com/CTCaer/hekate/blob/master/modules/hekate_libsys_minerva/sys_sdrammtc.c#L65)
- 3200 → l4t and closed version max for Mariko
- 2931
- 2665
- 2502 → max for Mariko
- 2400
- 2361 → l4t and closed version max for Erista
- 2131 → JEDEC. max for Erista and official max for Mariko. lpddr4(x) official max
- 2099
- 2064
- 1996 → OCS mariko default
- 1932
- 1894
- 1862 → JEDEC. official max for Erista; OCS erista default
- 1795
- 1728
- 1600 → official docked & official boost mode
- 1331 → JEDEC. official handheld
- 1065
- 800
- 665
## Capping
To protect the battery from excessive strain, clocks requested from config may be capped before applying, depending on your current profile:
### Erista (Safe)
| | Handheld | Charging (USB) | Charging (Official) | Docked |
|:-------:|:--------:|:--------------:|:-------------------:|:------:|
| **MEM** | - | - | - | - |
| **CPU** | 1785 | 1785 | 1785 | 1785 |
| **GPU** | 460 | 768 | 921 | 921 |
### Erista (Unsafe allowed)
| | Handheld | Charging (USB) | Charging (Official) | Docked |
|:-------:|:--------:|:--------------:|:-------------------:|:------:|
| **MEM** | - | - | - | - |
| **CPU** | 1785 | 1785 | - | - |
| **GPU** | 460 | 768 | - | - |
### Mariko (Safe)
| | Handheld | Charging (USB) | Charging (Official) | Docked |
|:-------:|:--------:|:--------------:|:-------------------:|:------:|
| **MEM** | - | - | - | - |
| **CPU** | 1963 | 1963 | 1963 | 1963 |
| **GPU** | 768 | 921 | 998 | 998 |
### Mariko (Unsafe allowed)
| | Handheld | Charging (USB) | Charging (Official) | Docked |
|:-------:|:--------:|:--------------:|:-------------------:|:------:|
| **MEM** | - | - | - | - |
| **CPU** | 1963 | 1963 | - | - |
| **GPU** | 768 | 921 | - | - |
## Installation
The following instructions assumes you have a Nintendo Switch running Atmosphère, updated to at least the latest stable version.
Copy the `atmosphere`, and `switch` folders at the root of your sdcard, overwriting files if prompted. Also copy the `config` folder if you're not updating, to include default settings.
**Note:** sys-clk-overlay requires to have [Tesla](https://gbatemp.net/threads/tesla-the-nintendo-switch-overlay-menu.557362/) installed and running
## Relevant files
* Config file allows one to set custom clocks per docked state and title id, described below
`/config/sys-clk-oc/config.ini`
* Log file where the logs are written if enabled
`/config/sys-clk-oc/log.txt`
* Log flag file enables log writing if file exists
`/config/sys-clk-oc/log.flag`
* CSV file where the title id, profile, clocks and temperatures are written if enabled
`/config/sys-clk-oc/context.csv`
* sys-clk overlay (accessible from anywhere by invoking the [Tesla menu](https://gbatemp.net/threads/tesla-the-nintendo-switch-overlay-menu.557362/))
`/switch/.overlays/sys-clk-overlay.ovl`
* sys-clk core sysmodule
`/atmosphere/contents/00FF0000636C6BFF/exefs.nsp`
`/atmosphere/contents/00FF0000636C6BFF/flags/boot2.flag`
## Config
Presets can be customized by adding them to the ini config file located at `/config/sys-clk/config.ini`, using the following template for each app
```
[Application Title ID]
docked_cpu=
docked_gpu=
docked_mem=
handheld_charging_cpu=
handheld_charging_gpu=
handheld_charging_mem=
handheld_charging_usb_cpu=
handheld_charging_usb_gpu=
handheld_charging_usb_mem=
handheld_charging_official_cpu=
handheld_charging_official_gpu=
handheld_charging_official_mem=
handheld_cpu=
handheld_gpu=
handheld_mem=
governor_config=
```
* Replace `Application Title ID` with the title id of the game/application you're interested in customizing.
A list of games title id can be found in the [Switchbrew wiki](https://switchbrew.org/wiki/Title_list/Games).
* Frequencies are expressed in mhz, and will be scaled to the nearest possible values, described in the clock table below.
* If any key is omitted, value is empty or set to 0, it will be ignored, and stock clocks will apply.
* If charging, sys-clk will look for the frequencies in that order, picking the first found
1. Charger specific config (USB or Official) `handheld_charging_usb_X` or `handheld_charging_official_X`
2. Non specific charging config `handheld_charging_X`
3. Handheld config `handheld_X`
### Example 1: Zelda BOTW
* Overclock CPU when docked or charging
Leads to a smoother framerate overall (ex: in the korok forest)
```
[01007EF00011E000]
docked_cpu=1224
handheld_charging_cpu=1224
handheld_mem=1600
```
### Example 2: Picross
* Underclocks on handheld to save battery
```
[0100BA0003EEA000]
handheld_cpu=816
handheld_gpu=153
```
### Advanced
The `[values]` section allows you to alter timings in sys-clk, you should not need to edit any of these unless you know what you are doing. Possible values are:
| Key | Desc | Default |
|:------------------------:|-------------------------------------------------------------------------------|:---------:|
|**allow_unsafe_freq** | Allow unsafe frequencies (CPU > 1963.5 MHz, GPU > 921.6 MHz) | OFF |
|**uncapped_clocks** | Remove CPU/GPU clock cappings | OFF |
|**temp_log_interval_ms** | Defines how often sys-clk log temperatures, in milliseconds (`0` to disable) | 0 ms |
|**csv_write_interval_ms** | Defines how often sys-clk writes to the CSV, in milliseconds (`0` to disable) | 0 ms |
|**poll_interval_ms** | Defines how fast sys-clk checks and applies profiles, in milliseconds | 500 ms |
Only available for prior to Switch OC Suite 1.9.0
| Key | Desc | Default |
|:------------------------:|-------------------------------------------------------------------------------|:---------:|
|**auto_cpu_boost** | Auto-boost CPU when system Core #3 utilization ≥ 95% | OFF |
|**sync_reversenx_mode** | Sync nominal profile (mode) with ReverseNX (-Tool and -RT) | ON |
|**charging_current** | Charging current limit (100 mA - 2000 mA) | 2000 mA |
|**charging_limit_perc** | Charging limit (20% - 100%) | 100%(OFF) |
|**governor_experimental** | CPU & GPU frequency governor (Experimental) | OFF |
|**governor_handheld_only**| Use governor only on Handheld Profile | OFF |

View File

@@ -0,0 +1,38 @@
#!/bin/bash
set -e
ROOT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
DIST_DIR="$ROOT_DIR/dist"
CORES=$(nproc --all)
if [[ -n "$1" ]]; then
DIST_DIR="$1"
fi
echo "DIST_DIR: $DIST_DIR"
echo "CORES: $CORES"
echo "*** sysmodule ***"
TITLE_ID="00FF0000636C6BFF"
pushd "$ROOT_DIR/sysmodule"
make -j$CORES
popd > /dev/null
mkdir -p "$DIST_DIR/atmosphere/contents/$TITLE_ID/flags"
cp -vf "$ROOT_DIR/sysmodule/out/sys-clk-OC.nsp" "$DIST_DIR/atmosphere/contents/$TITLE_ID/exefs.nsp"
>"$DIST_DIR/atmosphere/contents/$TITLE_ID/flags/boot2.flag"
echo "*** overlay ***"
pushd "$ROOT_DIR/overlay"
make -j$CORES
popd > /dev/null
mkdir -p "$DIST_DIR/switch/.overlays"
cp -vf "$ROOT_DIR/overlay/out/sys-clk-overlay.ovl" "$DIST_DIR/switch/.overlays/sys-clk-overlay.ovl"
echo "*** assets ***"
mkdir -p "$DIST_DIR/config/sys-clk-oc"
cp -vf "$ROOT_DIR/config.ini.template" "$DIST_DIR/config/sys-clk-oc/config.ini.template"
>"$DIST_DIR/config/sys-clk-oc/log.flag"
cp -vf "$ROOT_DIR/README.md" "$DIST_DIR/README.md"

View File

@@ -0,0 +1,36 @@
#pragma once
#include <utility>
template<typename F>
class ScopeGuard {
public:
ScopeGuard(F&& f)
: f(f), engaged(true) {};
~ScopeGuard() {
if (engaged)
f();
};
ScopeGuard(ScopeGuard&& rhs)
: f(std::move(rhs.f)) {};
void dismiss() { engaged = false; }
private:
F f;
bool engaged;
};
struct MakeScopeExit {
template<typename F>
ScopeGuard<F> operator+=(F&& f) {
return ScopeGuard<F>(std::move(f));
};
};
#define STRING_CAT2(x, y) x##y
#define STRING_CAT(x, y) STRING_CAT2(x, y)
#define SCOPE_GUARD MakeScopeExit() += [&]() __attribute__((always_inline))
#define SCOPE_EXIT auto STRING_CAT(scope_exit_, __LINE__) = SCOPE_GUARD

View File

@@ -0,0 +1,28 @@
/*
* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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
#ifdef __cplusplus
#include "cpp_util.hpp"
extern "C" {
#endif
#include "sysclk/ipc.h"
#include "sysclk/clocks.h"
#include "sysclk/apm.h"
#include "sysclk/config.h"
#include "sysclk/errors.h"
#include "sysclk/i2c.h"
#include "sysclk/psm_ext.h"
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,22 @@
/*
* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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 "clocks.h"
typedef struct {
uint32_t id;
uint32_t cpu_hz;
uint32_t gpu_hz;
uint32_t mem_hz;
} SysClkApmConfiguration;
extern SysClkApmConfiguration sysclk_g_apm_configurations[];

View File

@@ -0,0 +1,50 @@
/*
* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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
#ifdef __cplusplus
extern "C" {
#endif
#include "types.h"
#include "../config.h"
#include "../clocks.h"
#include "../ipc.h"
bool sysclkIpcRunning();
Result sysclkIpcInitialize(void);
void sysclkIpcExit(void);
Result sysclkIpcGetAPIVersion(u32* out_ver);
Result sysclkIpcGetVersionString(char* out, size_t len);
Result sysclkIpcGetCurrentContext(SysClkContext* out_context);
Result sysclkIpcGetProfileCount(u64 tid, u8* out_count);
Result sysclkIpcSetEnabled(bool enabled);
Result sysclkIpcExitCmd();
Result sysclkIpcSetOverride(SysClkModule module, u32 hz);
Result sysclkIpcGetProfiles(u64 tid, SysClkTitleProfileList* out_profiles);
Result sysclkIpcSetProfiles(u64 tid, SysClkTitleProfileList* profiles);
Result sysclkIpcGetConfigValues(SysClkConfigValueList* out_configValues);
Result sysclkIpcSetConfigValues(SysClkConfigValueList* configValues);
Result sysclkIpcSetReverseNXRTMode(ReverseNXMode mode);
Result sysclkIpcGetFrequencyTable(SysClkModule module, SysClkProfile profile, SysClkFrequencyTable* out_table);
Result sysclkIpcGetIsMariko(bool* out_is_mariko);
Result sysclkIpcGetBatteryChargingDisabledOverride(bool* out_is_true);
Result sysclkIpcSetBatteryChargingDisabledOverride(bool toggle_true);
static inline Result sysclkIpcRemoveOverride(SysClkModule module)
{
return sysclkIpcSetOverride(module, 0);
}
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,29 @@
/*
* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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
#ifdef __SWITCH__
#include <switch/types.h>
#include <switch/result.h>
#else
#define R_FAILED(res) ((res) != 0)
#define R_SUCCEEDED(res) ((res) == 0)
typedef std::uint32_t Result;
typedef std::uint32_t u32;
typedef std::int32_t s32;
typedef std::uint64_t u64;
typedef std::uint8_t u8;
#endif

View File

@@ -0,0 +1,183 @@
/*
* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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 <stdint.h>
#include <stddef.h>
#include <stdbool.h>
typedef enum
{
SysClkProfile_Handheld = 0,
SysClkProfile_HandheldCharging,
SysClkProfile_HandheldChargingUSB,
SysClkProfile_HandheldChargingOfficial,
SysClkProfile_Docked,
SysClkProfile_EnumMax
} SysClkProfile;
typedef enum
{
SysClkModule_CPU = 0,
SysClkModule_GPU,
SysClkModule_MEM,
SysClkModule_EnumMax
} SysClkModule;
typedef enum
{
SysClkThermalSensor_SOC = 0,
SysClkThermalSensor_PCB,
SysClkThermalSensor_Skin,
SysClkThermalSensor_EnumMax
} SysClkThermalSensor;
typedef struct
{
uint8_t enabled;
uint64_t applicationId;
SysClkProfile profile;
uint32_t freqs[SysClkModule_EnumMax];
uint32_t overrideFreqs[SysClkModule_EnumMax];
uint32_t temps[SysClkThermalSensor_EnumMax];
uint32_t perfConfId;
} SysClkContext;
typedef enum
{
ReverseNX_NotFound = 0,
ReverseNX_SystemDefault = 0,
ReverseNX_Handheld,
ReverseNX_Docked,
} ReverseNXMode;
typedef struct
{
bool systemCoreBoostCPU;
bool batteryChargingDisabledOverride;
SysClkProfile realProfile;
} SysClkOcExtra;
#define FREQ_TABLE_MAX_ENTRY_COUNT 31
typedef struct
{
uint32_t freq[FREQ_TABLE_MAX_ENTRY_COUNT];
} SysClkFrequencyTable;
typedef enum {
SysClkOcGovernorConfig_AllDisabled = 0,
SysClkOcGovernorConfig_CPU_Shift = 0,
SysClkOcGovernorConfig_CPUOnly = 1 << SysClkOcGovernorConfig_CPU_Shift,
SysClkOcGovernorConfig_CPU = 1 << SysClkOcGovernorConfig_CPU_Shift,
SysClkOcGovernorConfig_GPU_Shift = 1,
SysClkOcGovernorConfig_GPUOnly = 1 << SysClkOcGovernorConfig_GPU_Shift,
SysClkOcGovernorConfig_GPU = 1 << SysClkOcGovernorConfig_GPU_Shift,
SysClkOcGovernorConfig_AllEnabled = 3,
SysClkOcGovernorConfig_Default = 3,
SysClkOcGovernorConfig_Mask = 3,
} SysClkOcGovernorConfig;
inline bool GetGovernorEnabled(SysClkOcGovernorConfig config, SysClkModule module) {
switch (module) {
case SysClkModule_CPU:
return (config >> SysClkOcGovernorConfig_CPU_Shift) & 1;
case SysClkModule_GPU:
return (config >> SysClkOcGovernorConfig_GPU_Shift) & 1;
case SysClkModule_MEM:
return false;
default:
return config != SysClkOcGovernorConfig_AllDisabled;
}
}
inline SysClkOcGovernorConfig ToggleGovernor(SysClkOcGovernorConfig prev, SysClkModule module, bool state) {
uint8_t shift;
switch (module) {
case SysClkModule_CPU:
shift = SysClkOcGovernorConfig_CPU_Shift;
break;
case SysClkModule_GPU:
shift = SysClkOcGovernorConfig_GPU_Shift;
break;
case SysClkModule_MEM:
return prev;
default:
return state ? SysClkOcGovernorConfig_AllEnabled : SysClkOcGovernorConfig_AllDisabled;
}
return (SysClkOcGovernorConfig)((prev & ~(1 << shift)) | state << shift);
}
typedef struct
{
union {
uint32_t mhz[(size_t)SysClkProfile_EnumMax * (size_t)SysClkModule_EnumMax];
uint32_t mhzMap[SysClkProfile_EnumMax][SysClkModule_EnumMax];
};
SysClkOcGovernorConfig governorConfig;
} SysClkTitleProfileList;
#define SYSCLK_GLOBAL_PROFILE_TID 0xA111111111111111
extern uint32_t g_freq_table_mem_hz[];
extern uint32_t g_freq_table_cpu_hz[];
extern uint32_t g_freq_table_gpu_hz[];
#define SYSCLK_ENUM_VALID(n, v) ((v) < n##_EnumMax)
static inline const char* sysclkFormatModule(SysClkModule module, bool pretty)
{
switch(module)
{
case SysClkModule_CPU:
return pretty ? "CPU" : "cpu";
case SysClkModule_GPU:
return pretty ? "GPU" : "gpu";
case SysClkModule_MEM:
return pretty ? "Memory" : "mem";
default:
return NULL;
}
}
static inline const char* sysclkFormatThermalSensor(SysClkThermalSensor thermSensor, bool pretty)
{
switch(thermSensor)
{
case SysClkThermalSensor_SOC:
return pretty ? "SOC" : "soc";
case SysClkThermalSensor_PCB:
return pretty ? "PCB" : "pcb";
case SysClkThermalSensor_Skin:
return pretty ? "Skin" : "skin";
default:
return NULL;
}
}
static inline const char* sysclkFormatProfile(SysClkProfile profile, bool pretty)
{
switch(profile)
{
case SysClkProfile_Docked:
return pretty ? "Docked" : "docked";
case SysClkProfile_Handheld:
return pretty ? "Handheld" : "handheld";
case SysClkProfile_HandheldCharging:
return pretty ? "Charging" : "handheld_charging";
case SysClkProfile_HandheldChargingUSB:
return pretty ? "USB Charger" : "handheld_charging_usb";
case SysClkProfile_HandheldChargingOfficial:
return pretty ? "Official Charger" : "handheld_charging_official";
default:
return NULL;
}
}

View File

@@ -0,0 +1,111 @@
/*
* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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 <stdint.h>
#include <stddef.h>
const uint32_t CHARGING_CURRENT_MA_LIMIT = 2000;
typedef enum {
SysClkConfigValue_PollingIntervalMs = 0,
SysClkConfigValue_TempLogIntervalMs,
SysClkConfigValue_CsvWriteIntervalMs,
SysClkConfigValue_AutoCPUBoost,
SysClkConfigValue_SyncReverseNXMode,
SysClkConfigValue_AllowUnsafeFrequencies,
SysClkConfigValue_ChargingCurrentLimit,
SysClkConfigValue_ChargingLimitPercentage,
SysClkConfigValue_GovernorExperimental,
SysClkConfigValue_GovernorHandheldOnly,
SysClkConfigValue_EnumMax,
} SysClkConfigValue;
typedef struct {
uint64_t values[SysClkConfigValue_EnumMax];
} SysClkConfigValueList;
static inline const char* sysclkFormatConfigValue(SysClkConfigValue val, bool pretty)
{
switch(val)
{
case SysClkConfigValue_PollingIntervalMs:
return pretty ? "Polling Interval (ms)" : "poll_interval_ms";
case SysClkConfigValue_TempLogIntervalMs:
return pretty ? "Temperature logging interval (ms)" : "temp_log_interval_ms";
case SysClkConfigValue_CsvWriteIntervalMs:
return pretty ? "CSV write interval (ms)" : "csv_write_interval_ms";
case SysClkConfigValue_AutoCPUBoost:
return pretty ? "Auto CPU Boost" : "auto_cpu_boost";
case SysClkConfigValue_SyncReverseNXMode:
return pretty ? "Sync ReverseNX Mode Sync" : "sync_reversenx_mode";
case SysClkConfigValue_AllowUnsafeFrequencies:
return pretty ? "Allow Unsafe Frequencies" : "allow_unsafe_freq";
case SysClkConfigValue_ChargingCurrentLimit:
return pretty ? "Charging Current Limit (mA)" : "charging_current";
case SysClkConfigValue_ChargingLimitPercentage:
return pretty ? "Charging Limit (%%)" : "charging_limit_perc";
case SysClkConfigValue_GovernorExperimental:
return pretty ? "Frequency Governor (Experimental)" : "governor_experimental";
case SysClkConfigValue_GovernorHandheldOnly:
return pretty ? "Frequency Governor Handheld Only" : "governor_handheld_only";
default:
return NULL;
}
}
static inline uint64_t sysclkDefaultConfigValue(SysClkConfigValue val)
{
switch(val)
{
case SysClkConfigValue_PollingIntervalMs:
return 500ULL;
case SysClkConfigValue_TempLogIntervalMs:
case SysClkConfigValue_CsvWriteIntervalMs:
case SysClkConfigValue_AllowUnsafeFrequencies:
case SysClkConfigValue_GovernorExperimental:
case SysClkConfigValue_GovernorHandheldOnly:
case SysClkConfigValue_AutoCPUBoost:
return 0ULL;
case SysClkConfigValue_SyncReverseNXMode:
return 1ULL;
case SysClkConfigValue_ChargingCurrentLimit:
return 2000ULL;
case SysClkConfigValue_ChargingLimitPercentage:
return 100ULL;
default:
return 0ULL;
}
}
static inline uint64_t sysclkValidConfigValue(SysClkConfigValue val, uint64_t input)
{
switch(val)
{
case SysClkConfigValue_PollingIntervalMs:
return input > 0;
case SysClkConfigValue_TempLogIntervalMs:
case SysClkConfigValue_CsvWriteIntervalMs:
return true;
case SysClkConfigValue_AutoCPUBoost:
case SysClkConfigValue_SyncReverseNXMode:
case SysClkConfigValue_AllowUnsafeFrequencies:
case SysClkConfigValue_GovernorExperimental:
case SysClkConfigValue_GovernorHandheldOnly:
return (input & 0x1) == input;
case SysClkConfigValue_ChargingCurrentLimit:
return (input >= 100 && input <= CHARGING_CURRENT_MA_LIMIT && input % 100 == 0);
case SysClkConfigValue_ChargingLimitPercentage:
return (input <= 100 && input >= 20);
default:
return false;
}
}

View File

@@ -0,0 +1,22 @@
/*
* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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
#define SYSCLK_ERROR_MODULE 388
#define SYSCLK_ERROR(desc) ((SYSCLK_ERROR_MODULE & 0x1FF) | (SysClkError_##desc & 0x1FFF)<<9)
typedef enum
{
SysClkError_Generic = 0,
SysClkError_ConfigNotLoaded = 1,
SysClkError_ConfigSaveFailed = 2,
SysClkError_InternalFrequencyTableError = 3,
} SysClkError;

View File

@@ -0,0 +1,57 @@
#pragma once
#include <switch.h>
// To use i2c service, sm and i2c should be intialized via smInitialize() and i2cInitialize().
Result I2cSet_U8(I2cDevice dev, u8 reg, u8 val);
Result I2cRead_OutU8(I2cDevice dev, u8 reg, u8 *out);
Result I2cRead_OutU16(I2cDevice dev, u8 reg, u16 *out);
// Max17050 fuel gauge
float I2c_Max17050_GetBatteryCurrent();
const u8 MAX17050_CURRENT_REG = 0x0A;
// Buck Converter
typedef enum I2c_BuckConverter_Reg {
I2c_Max77620_SD1VOLT_REG = 0x17, // Used for Erista DDR VDDQ+VDD2 / Mariko VDD2
I2c_Max77621_VOLT_REG = 0x00,
I2c_Max77812_CPUVOLT_REG = 0x26,
I2c_Max77812_GPUVOLT_REG = 0x23,
I2c_Max77812_MEMVOLT_REG = 0x25, // Master 3 (GPU 1 + 2, DRAM 3, CPU 4), used for Mariko VDDQ
} I2c_BuckConverter_Reg;
typedef struct I2c_BuckConverter_Domain {
I2cDevice device;
I2c_BuckConverter_Reg reg;
u8 volt_mask;
u32 uv_step;
u32 uv_min;
u32 uv_max;
u8 por_val;
} I2c_BuckConverter_Domain;
const I2c_BuckConverter_Domain I2c_Erista_CPU = { I2cDevice_Max77621Cpu, I2c_Max77621_VOLT_REG, 0x7F, 6250, 606250, 1400000, };
const I2c_BuckConverter_Domain I2c_Erista_GPU = { I2cDevice_Max77621Gpu, I2c_Max77621_VOLT_REG, 0x7F, 6250, 606250, 1400000, };
const I2c_BuckConverter_Domain I2c_Erista_DRAM = { I2cDevice_Max77620Pmic, I2c_Max77620_SD1VOLT_REG, 0x7F, 12500, 600000, 1250000, };
const I2c_BuckConverter_Domain I2c_Mariko_CPU = { I2cDevice_Max77812_2, I2c_Max77812_CPUVOLT_REG, 0xFF, 5000, 250000, 1525000, 0x78 };
const I2c_BuckConverter_Domain I2c_Mariko_GPU = { I2cDevice_Max77812_2, I2c_Max77812_GPUVOLT_REG, 0xFF, 5000, 250000, 1525000, 0x78 };
const I2c_BuckConverter_Domain I2c_Mariko_DRAM_VDDQ = { I2cDevice_Max77812_2, I2c_Max77812_MEMVOLT_REG, 0xFF, 5000, 250000, 650000, 0x78 };
const I2c_BuckConverter_Domain I2c_Mariko_DRAM_VDD2 = { I2cDevice_Max77620Pmic, I2c_Max77620_SD1VOLT_REG, 0x7F, 12500, 600000, 1250000, };
u32 I2c_BuckConverter_GetMvOut(const I2c_BuckConverter_Domain* domain);
Result I2c_BuckConverter_SetMvOut(const I2c_BuckConverter_Domain* domain, u32 mvolt);
// Bq24193 Battery management
u32 I2c_Bq24193_Convert_Raw_mA(u8 raw);
u8 I2c_Bq24193_Convert_mA_Raw(u32 ma);
Result I2c_Bq24193_GetFastChargeCurrentLimit(u32 *ma);
Result I2c_Bq24193_SetFastChargeCurrentLimit(u32 ma);
const u32 MA_RANGE_MIN = 512;
const u32 MA_RANGE_MAX = 4544;
const u8 BQ24193_CHARGE_CURRENT_CONTROL_REG = 0x2;

View File

@@ -0,0 +1,55 @@
/*
* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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 <stdint.h>
#include "clocks.h"
#define SYSCLK_IPC_API_VERSION 2
#define SYSCLK_IPC_SERVICE_NAME "sysclkOC"
enum SysClkIpcCmd
{
SysClkIpcCmd_GetApiVersion = 0,
SysClkIpcCmd_GetVersionString = 1,
SysClkIpcCmd_GetCurrentContext = 2,
SysClkIpcCmd_Exit = 3,
SysClkIpcCmd_GetProfileCount = 4,
SysClkIpcCmd_GetProfiles = 5,
SysClkIpcCmd_SetProfiles = 6,
SysClkIpcCmd_SetEnabled = 7,
SysClkIpcCmd_SetOverride = 8,
SysClkIpcCmd_GetConfigValues = 9,
SysClkIpcCmd_SetConfigValues = 10,
SysClkIpcCmd_SetReverseNXRTMode = 11,
SysClkIpcCmd_GetFrequencyTable = 12,
SysClkIpcCmd_GetIsMariko = 13,
SysClkIpcCmd_GetBatteryChargingDisabledOverride = 14,
SysClkIpcCmd_SetBatteryChargingDisabledOverride = 15,
};
typedef struct
{
uint64_t tid;
SysClkTitleProfileList profiles;
} SysClkIpc_SetProfiles_Args;
typedef struct
{
SysClkModule module;
uint32_t hz;
} SysClkIpc_SetOverride_Args;
typedef struct
{
SysClkModule module;
SysClkProfile profile;
} SysClkIpc_GetFrequencyTable_Args;

View File

@@ -0,0 +1,77 @@
#pragma once
#include <switch.h>
typedef enum {
PsmPDC_NewPDO = 1, //Received new Power Data Object
PsmPDC_NoPD = 2, //No Power Delivery source is detected
PsmPDC_AcceptedRDO = 3 //Received and accepted Request Data Object
} PsmChargeInfoPDC; //BM92T series
typedef enum {
PsmPowerRole_Sink = 1,
PsmPowerRole_Source = 2
} PsmPowerRole;
const char* PsmPowerRoleToStr(PsmPowerRole role);
typedef enum {
PsmInfoChargerType_None = 0,
PsmInfoChargerType_PD = 1,
PsmInfoChargerType_TypeC_1500mA = 2,
PsmInfoChargerType_TypeC_3000mA = 3,
PsmInfoChargerType_DCP = 4,
PsmInfoChargerType_CDP = 5,
PsmInfoChargerType_SDP = 6,
PsmInfoChargerType_Apple_500mA = 7,
PsmInfoChargerType_Apple_1000mA = 8,
PsmInfoChargerType_Apple_2000mA = 9
} PsmInfoChargerType;
const char* PsmInfoChargerTypeToStr(PsmInfoChargerType type);
typedef enum {
PsmFlags_NoHub = BIT(0), //If hub is disconnected
PsmFlags_Rail = BIT(8), //At least one Joy-con is charging from rail
PsmFlags_SPDSRC = BIT(12), //OTG
PsmFlags_ACC = BIT(16) //Accessory
} PsmChargeInfoFlags;
typedef struct {
int32_t InputCurrentLimit; //Input (Sink) current limit in mA
int32_t VBUSCurrentLimit; //Output (Source/VBUS/OTG) current limit in mA
int32_t ChargeCurrentLimit; //Battery charging current limit in mA (512mA when Docked, 768mA when BatteryTemperature < 17.0 C)
int32_t ChargeVoltageLimit; //Battery charging voltage limit in mV (3952mV when BatteryTemperature >= 51.0 C)
int32_t unk_x10; //Possibly an emum, getting the same value as PowerRole in all tested cases
int32_t unk_x14; //Possibly flags
PsmChargeInfoPDC PDCState; //Power Delivery Controller State
int32_t BatteryTemperature; //Battery temperature in milli C
int32_t RawBatteryCharge; //Raw battery charged capacity per cent-mille (i.e. 100% = 100000 pcm)
int32_t VoltageAvg; //Voltage avg in mV (more in Notes)
int32_t BatteryAge; //Battery age (capacity full / capacity design) per cent-mille (i.e. 100% = 100000 pcm)
PsmPowerRole PowerRole;
PsmInfoChargerType ChargerType;
int32_t ChargerVoltageLimit; //Charger and external device voltage limit in mV
int32_t ChargerCurrentLimit; //Charger and external device current limit in mA
PsmChargeInfoFlags Flags; //Unknown flags
} PsmChargeInfo;
typedef enum {
Psm_EnableBatteryCharging = 2,
Psm_DisableBatteryCharging = 3,
Psm_EnableFastBatteryCharging = 10,
Psm_DisableFastBatteryCharging = 11,
Psm_GetBatteryChargeInfoFields = 17,
} IPsmServerCmd;
bool PsmIsChargerConnected(const PsmChargeInfo* info);
bool PsmIsCharging(const PsmChargeInfo* info);
typedef enum {
PsmBatteryState_Discharging,
PsmBatteryState_ChargingPaused,
PsmBatteryState_FastCharging
} PsmBatteryState;
PsmBatteryState PsmGetBatteryState(const PsmChargeInfo* info);
const char* PsmGetBatteryStateIcon(const PsmChargeInfo* info);

View File

@@ -0,0 +1,32 @@
/*
* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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
* --------------------------------------------------------------------------
*/
#include <sysclk/apm.h>
SysClkApmConfiguration sysclk_g_apm_configurations[] = {
{0x00010000, 1020000000, 384000000, 1600000000},
{0x00010001, 1020000000, 768000000, 1600000000},
{0x00010002, 1224000000, 691200000, 1600000000},
{0x00020000, 1020000000, 230400000, 1600000000},
{0x00020001, 1020000000, 307200000, 1600000000},
{0x00020002, 1224000000, 230400000, 1600000000},
{0x00020003, 1020000000, 307000000, 1331200000},
{0x00020004, 1020000000, 384000000, 1331200000},
{0x00020005, 1020000000, 307200000, 1065600000},
{0x00020006, 1020000000, 384000000, 1065600000},
{0x92220007, 1020000000, 460800000, 1600000000},
{0x92220008, 1020000000, 460800000, 1331200000},
{0x92220009, 1785000000, 76800000, 1600000000},
{0x9222000A, 1785000000, 76800000, 1331200000},
{0x9222000B, 1020000000, 76800000, 1600000000},
{0x9222000C, 1020000000, 76800000, 1331200000},
{0, 0, 0, 0},
};

View File

@@ -0,0 +1,145 @@
/*
* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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
* --------------------------------------------------------------------------
*/
#define NX_SERVICE_ASSUME_NON_DOMAIN
#include <sysclk/client/ipc.h>
#include <switch.h>
#include <string.h>
#include <stdatomic.h>
static Service g_sysclkSrv;
static atomic_size_t g_refCnt;
bool sysclkIpcRunning()
{
Handle handle;
bool running = R_FAILED(smRegisterService(&handle, smEncodeName(SYSCLK_IPC_SERVICE_NAME), false, 1));
if (!running)
{
smUnregisterService(smEncodeName(SYSCLK_IPC_SERVICE_NAME));
}
return running;
}
Result sysclkIpcInitialize(void)
{
Result rc = 0;
g_refCnt++;
if (serviceIsActive(&g_sysclkSrv))
return 0;
rc = smGetService(&g_sysclkSrv, SYSCLK_IPC_SERVICE_NAME);
if (R_FAILED(rc)) sysclkIpcExit();
return rc;
}
void sysclkIpcExit(void)
{
if (--g_refCnt == 0)
{
serviceClose(&g_sysclkSrv);
}
}
Result sysclkIpcGetAPIVersion(u32* out_ver)
{
return serviceDispatchOut(&g_sysclkSrv, SysClkIpcCmd_GetApiVersion, *out_ver);
}
Result sysclkIpcGetVersionString(char* out, size_t len)
{
return serviceDispatch(&g_sysclkSrv, SysClkIpcCmd_GetVersionString,
.buffer_attrs = { SfBufferAttr_HipcMapAlias | SfBufferAttr_Out },
.buffers = {{out, len}},
);
}
Result sysclkIpcGetCurrentContext(SysClkContext* out_context)
{
return serviceDispatchOut(&g_sysclkSrv, SysClkIpcCmd_GetCurrentContext, *out_context);
}
Result sysclkIpcGetProfileCount(u64 tid, u8* out_count)
{
return serviceDispatchInOut(&g_sysclkSrv, SysClkIpcCmd_GetProfileCount, tid, *out_count);
}
Result sysclkIpcSetEnabled(bool enabled)
{
u8 enabledRaw = (u8)enabled;
return serviceDispatchIn(&g_sysclkSrv, SysClkIpcCmd_SetEnabled, enabledRaw);
}
Result sysclkIpcSetOverride(SysClkModule module, u32 hz)
{
SysClkIpc_SetOverride_Args args = {
.module = module,
.hz = hz
};
return serviceDispatchIn(&g_sysclkSrv, SysClkIpcCmd_SetOverride, args);
}
Result sysclkIpcGetProfiles(u64 tid, SysClkTitleProfileList* out_profiles)
{
return serviceDispatchInOut(&g_sysclkSrv, SysClkIpcCmd_GetProfiles, tid, *out_profiles);
}
Result sysclkIpcSetProfiles(u64 tid, SysClkTitleProfileList* profiles)
{
SysClkIpc_SetProfiles_Args args;
args.tid = tid;
memcpy(&args.profiles, profiles, sizeof(SysClkTitleProfileList));
return serviceDispatchIn(&g_sysclkSrv, SysClkIpcCmd_SetProfiles, args);
}
Result sysclkIpcGetConfigValues(SysClkConfigValueList* out_configValues)
{
return serviceDispatchOut(&g_sysclkSrv, SysClkIpcCmd_GetConfigValues, *out_configValues);
}
Result sysclkIpcSetConfigValues(SysClkConfigValueList* configValues)
{
return serviceDispatchIn(&g_sysclkSrv, SysClkIpcCmd_SetConfigValues, *configValues);
}
Result sysclkIpcSetReverseNXRTMode(ReverseNXMode mode)
{
return serviceDispatchIn(&g_sysclkSrv, SysClkIpcCmd_SetReverseNXRTMode, mode);
}
Result sysclkIpcGetFrequencyTable(SysClkModule module, SysClkProfile profile, SysClkFrequencyTable* out_table)
{
SysClkIpc_GetFrequencyTable_Args args = {
.module = module,
.profile = profile,
};
return serviceDispatchInOut(&g_sysclkSrv, SysClkIpcCmd_GetFrequencyTable, args, *out_table);
}
Result sysclkIpcGetIsMariko(bool* out_is_mariko)
{
return serviceDispatchOut(&g_sysclkSrv, SysClkIpcCmd_GetIsMariko, *out_is_mariko);
}
Result sysclkIpcGetBatteryChargingDisabledOverride(bool* out_is_true)
{
return serviceDispatchOut(&g_sysclkSrv, SysClkIpcCmd_GetBatteryChargingDisabledOverride, *out_is_true);
}
Result sysclkIpcSetBatteryChargingDisabledOverride(bool toggle_true)
{
return serviceDispatchIn(&g_sysclkSrv, SysClkIpcCmd_SetBatteryChargingDisabledOverride, toggle_true);
}

View File

@@ -0,0 +1,186 @@
#include <sysclk/i2c.h>
Result I2cSet_U8(I2cDevice dev, u8 reg, u8 val) {
// ams::fatal::srv::StopSoundTask::StopSound()
// I2C Bus Communication Reference: https://www.ti.com/lit/an/slva704/slva704.pdf
struct {
u8 reg;
u8 val;
} __attribute__((packed)) cmd;
I2cSession _session;
Result res = i2cOpenSession(&_session, dev);
if (res)
return res;
cmd.reg = reg;
cmd.val = val;
res = i2csessionSendAuto(&_session, &cmd, sizeof(cmd), I2cTransactionOption_All);
i2csessionClose(&_session);
return res;
}
Result I2cRead_OutU8(I2cDevice dev, u8 reg, u8 *out) {
struct { u8 reg; } __attribute__((packed)) cmd;
struct { u8 val; } __attribute__((packed)) rec;
I2cSession _session;
Result res = i2cOpenSession(&_session, dev);
if (res)
return res;
cmd.reg = reg;
res = i2csessionSendAuto(&_session, &cmd, sizeof(cmd), I2cTransactionOption_All);
if (res) {
i2csessionClose(&_session);
return res;
}
res = i2csessionReceiveAuto(&_session, &rec, sizeof(rec), I2cTransactionOption_All);
i2csessionClose(&_session);
if (res) {
return res;
}
*out = rec.val;
return 0;
}
Result I2cRead_OutU16(I2cDevice dev, u8 reg, u16 *out) {
struct { u8 reg; } __attribute__((packed)) cmd;
struct { u16 val; } __attribute__((packed)) rec;
I2cSession _session;
Result res = i2cOpenSession(&_session, dev);
if (res)
return res;
cmd.reg = reg;
res = i2csessionSendAuto(&_session, &cmd, sizeof(cmd), I2cTransactionOption_All);
if (res) {
i2csessionClose(&_session);
return res;
}
res = i2csessionReceiveAuto(&_session, &rec, sizeof(rec), I2cTransactionOption_All);
i2csessionClose(&_session);
if (res) {
return res;
}
*out = rec.val;
return 0;
}
float I2c_Max17050_GetBatteryCurrent() {
u16 val;
Result res = I2cRead_OutU16(I2cDevice_Max17050, MAX17050_CURRENT_REG, &val);
if (res)
return 0.f;
const float SenseResistor = 5.; // in uOhm
const float CGain = 1.99993;
return (s16)val * (1.5625 / (SenseResistor * CGain));
}
u32 I2c_BuckConverter_MultiplierToMvOut(const I2c_BuckConverter_Domain* domain, u8 multiplier) {
return (domain->uv_min + domain->uv_step * multiplier) / 1000;
}
u8 I2c_BuckConverter_MvOutToMultiplier(const I2c_BuckConverter_Domain* domain, u32 mvolt) {
u32 uvolt = mvolt * 1000;
if (uvolt < domain->uv_min)
uvolt = domain->uv_min;
if (uvolt > domain->uv_max)
uvolt = domain->uv_max;
return (uvolt - domain->uv_min) / domain->uv_step;
}
u32 I2c_BuckConverter_GetMvOut(const I2c_BuckConverter_Domain* domain) {
u8 val;
// Retry 5 times if received POR value
for (int i = 0; i < 5; i++) {
if (R_FAILED(I2cRead_OutU8(domain->device, domain->reg, &val)))
return 0u;
// Wait 1us
svcSleepThread(1E3);
if (!domain->por_val || val != domain->por_val)
break;
}
return I2c_BuckConverter_MultiplierToMvOut(domain, val & domain->volt_mask);
}
Result I2c_BuckConverter_SetMvOut(const I2c_BuckConverter_Domain* domain, u32 mvolt) {
u8 val;
Result res = I2cRead_OutU8(domain->device, domain->reg, &val);
if (R_FAILED(res))
return res;
u8 multiplier = I2c_BuckConverter_MvOutToMultiplier(domain, mvolt);
val &= ~domain->volt_mask;
val |= multiplier & domain->volt_mask;
res = I2cSet_U8(domain->device, domain->reg, val);
if (R_FAILED(res))
return res;
// 5ms Ramp delay
svcSleepThread(5E6);
u8 new_val;
res = I2cRead_OutU8(domain->device, domain->reg, &new_val);
if (R_FAILED(res))
return res;
if (new_val != val)
return -1;
return 0;
}
u8 I2c_Bq24193_Convert_mA_Raw(u32 ma) {
// Adjustment is required
u8 raw = 0;
if (ma > MA_RANGE_MAX) // capping
ma = MA_RANGE_MAX;
bool pct20 = ma <= (MA_RANGE_MIN - 64);
if (pct20) {
ma = ma * 5;
raw |= 0x1;
}
ma -= ma % 100; // round to 100
ma -= (MA_RANGE_MIN - 64); // ceiling
raw |= (ma >> 6) << 2;
return raw;
};
u32 I2c_Bq24193_Convert_Raw_mA(u8 raw) {
// No adjustment is allowed
u32 ma = (((raw >> 2)) << 6) + MA_RANGE_MIN;
bool pct20 = raw & 1;
if (pct20)
ma = ma * 20 / 100;
return ma;
};
Result I2c_Bq24193_GetFastChargeCurrentLimit(u32 *ma) {
u8 raw;
Result res = I2cRead_OutU8(I2cDevice_Bq24193, BQ24193_CHARGE_CURRENT_CONTROL_REG, &raw);
if (res)
return res;
*ma = I2c_Bq24193_Convert_Raw_mA(raw);
return 0;
}
Result I2c_Bq24193_SetFastChargeCurrentLimit(u32 ma) {
u8 raw = I2c_Bq24193_Convert_mA_Raw(ma);
return I2cSet_U8(I2cDevice_Bq24193, BQ24193_CHARGE_CURRENT_CONTROL_REG, raw);
}

View File

@@ -0,0 +1,50 @@
#include <sysclk/psm_ext.h>
const char* PsmPowerRoleToStr(PsmPowerRole role) {
switch (role) {
case PsmPowerRole_Sink: return "Sink";
case PsmPowerRole_Source: return "Source";
default: return "Unknown";
}
}
const char* PsmInfoChargerTypeToStr(PsmInfoChargerType type) {
switch (type) {
case PsmInfoChargerType_None: return "None";
case PsmInfoChargerType_PD: return "USB-C PD";
case PsmInfoChargerType_TypeC_1500mA:
case PsmInfoChargerType_TypeC_3000mA: return "USB-C";
case PsmInfoChargerType_DCP: return "USB DCP";
case PsmInfoChargerType_CDP: return "USB CDP";
case PsmInfoChargerType_SDP: return "USB SDP";
case PsmInfoChargerType_Apple_500mA:
case PsmInfoChargerType_Apple_1000mA:
case PsmInfoChargerType_Apple_2000mA: return "Apple";
default: return "Unknown";
}
}
bool PsmIsChargerConnected(const PsmChargeInfo* info) {
return info->ChargerType != PsmInfoChargerType_None;
}
bool PsmIsCharging(const PsmChargeInfo* info) {
return PsmIsChargerConnected(info) && ((info->unk_x14 >> 8) & 1);
}
PsmBatteryState PsmGetBatteryState(const PsmChargeInfo* info) {
if (!PsmIsChargerConnected(info))
return PsmBatteryState_Discharging;
if (!PsmIsCharging(info))
return PsmBatteryState_ChargingPaused;
return PsmBatteryState_FastCharging;
}
const char* PsmGetBatteryStateIcon(const PsmChargeInfo* info) {
switch (PsmGetBatteryState(info)) {
case PsmBatteryState_Discharging: return "\u25c0"; // ◀
case PsmBatteryState_ChargingPaused:return "| |";
case PsmBatteryState_FastCharging: return "\u25b6"; // ▶
default: return "?";
}
}

View File

@@ -0,0 +1,16 @@
[values]
; Defines how often sys-clk log temperatures, in milliseconds (set 0 to disable)
temp_log_interval_ms=0
; Defines how often sys-clk writes to the CSV, in milliseconds (set 0 to disable)
csv_write_interval_ms=0
; Example #1: BOTW
; Overclock CPU when docked
;[01007EF00011E000]
;docked_cpu=1224
; Example #2: Picross
; Underclock to save battery
;[0100BA0003EEA000]
;handheld_cpu=816
;handheld_gpu=153

View File

@@ -0,0 +1,2 @@
/out
/build

View File

@@ -0,0 +1,154 @@
#---------------------------------------------------------------------------------
.SUFFIXES:
#---------------------------------------------------------------------------------
ifeq ($(strip $(DEVKITPRO)),)
$(error "Please set DEVKITPRO in your environment. export DEVKITPRO=<path to>/devkitpro")
endif
TOPDIR ?= $(CURDIR)
include $(DEVKITPRO)/libnx/switch_rules
#---------------------------------------------------------------------------------
# TARGET is the name of the output
# BUILD is the directory where object files & intermediate files will be placed
# SOURCES is a list of directories containing source code
# DATA is a list of directories containing data files
# INCLUDES is a list of directories containing header files
# EXEFS_SRC is the optional input directory containing data copied into exefs, if anything this normally should only contain "main.npdm".
#---------------------------------------------------------------------------------
TARGET := sys-clk-overlay
BUILD := build
OUTDIR := out
RESOURCES := res
SOURCES := src src/ui/gui src/ui/elements ../common/src ../common/src/client
DATA := data
INCLUDES := ../common/include
EXEFS_SRC := exefs_src
APP_TITLE := Switch-OC-Suite
NO_ICON := 1
#---------------------------------------------------------------------------------
# version control constants
#---------------------------------------------------------------------------------
TARGET_VERSION := 1.8.3
APP_VERSION := $(TARGET_VERSION)
#---------------------------------------------------------------------------------
# options for code generation
#---------------------------------------------------------------------------------
DEFINES := -DDISABLE_IPC -DTARGET="\"$(TARGET)\"" -DTARGET_VERSION="\"$(TARGET_VERSION)\""
ARCH := -march=armv8-a+crc+crypto -mtune=cortex-a57 -mtp=soft -fPIE
CFLAGS := -g -Wall -O2 -ffunction-sections \
$(ARCH) $(DEFINES)
CFLAGS += $(INCLUDE) -D__SWITCH__
CXXFLAGS := $(CFLAGS) -fno-exceptions -std=gnu++20
ASFLAGS := -g $(ARCH)
LDFLAGS = -specs=$(DEVKITPRO)/libnx/switch.specs -g $(ARCH) -Wl,-Map,$(notdir $*.map)
LIBS := -lnx
#---------------------------------------------------------------------------------
# list of directories containing libraries, this must be the top level containing
# include and lib
#---------------------------------------------------------------------------------
LIBDIRS := $(PORTLIBS) $(LIBNX) $(TOPDIR)/lib/tesla
#---------------------------------------------------------------------------------
# no real need to edit anything past this point unless you need to add additional
# rules for different file extensions
#---------------------------------------------------------------------------------
ifneq ($(BUILD),$(notdir $(CURDIR)))
#---------------------------------------------------------------------------------
export OUTPUT := $(CURDIR)/$(OUTDIR)/$(TARGET)
export TOPDIR := $(CURDIR)
export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \
$(foreach dir,$(DATA),$(CURDIR)/$(dir))
export DEPSDIR := $(CURDIR)/$(BUILD)
CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c)))
CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp)))
SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s)))
BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*)))
#---------------------------------------------------------------------------------
# use CXX for linking C++ projects, CC for standard C
#---------------------------------------------------------------------------------
ifeq ($(strip $(CPPFILES)),)
#---------------------------------------------------------------------------------
export LD := $(CC)
#---------------------------------------------------------------------------------
else
#---------------------------------------------------------------------------------
export LD := $(CXX)
#---------------------------------------------------------------------------------
endif
#---------------------------------------------------------------------------------
export OFILES := $(addsuffix .o,$(BINFILES)) \
$(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o)
export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \
$(foreach dir,$(LIBDIRS),-I$(dir)/include) \
-I$(CURDIR)/$(BUILD)
export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)/lib)
export BUILD_EXEFS_SRC := $(TOPDIR)/$(EXEFS_SRC)
.PHONY: $(BUILD) clean all
#---------------------------------------------------------------------------------
all: $(BUILD)
$(BUILD):
@[ -d $@ ] || mkdir -p $@
@[ -d $(OUTDIR) ] || mkdir -p $(OUTDIR)
@$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile
#---------------------------------------------------------------------------------
clean:
@echo clean ...
@rm -fr $(BUILD) $(TARGET).ovl $(TARGET).nacp $(TARGET).nso $(TARGET).elf $(OUTDIR)
#---------------------------------------------------------------------------------
else
.PHONY: all
DEPENDS := $(OFILES:.o=.d)
#---------------------------------------------------------------------------------
# main targets
#---------------------------------------------------------------------------------
all: $(OUTPUT).ovl
$(OUTPUT).ovl: $(OUTPUT).elf $(OUTPUT).nacp
@elf2nro $< $@ --nacp=$(OUTPUT).nacp
@echo "built ... $(notdir $(OUTPUT).ovl)"
$(OUTPUT).elf: $(OFILES)
#---------------------------------------------------------------------------------
# you need a rule like this for each extension you use as binary data
#---------------------------------------------------------------------------------
%.bin.o : %.bin
#---------------------------------------------------------------------------------
@echo $(notdir $<)
@$(bin2o)
-include $(DEPENDS)
#---------------------------------------------------------------------------------------
endif
#---------------------------------------------------------------------------------------

View File

@@ -0,0 +1,5 @@
# These are supported funding model platforms
patreon: werwolv
custom: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=KP7XRJAND9KWU&source=url
github: WerWolv

View File

@@ -0,0 +1,12 @@
debug
release
lib
*.bz2
example/build/
*.elf
*.nacp
*.ovl

View File

@@ -0,0 +1,12 @@
; DO NOT EDIT (unless you know what you are doing)
;
; This subdirectory is a git "subrepo", and this file is maintained by the
; git-subrepo command. See https://github.com/git-commands/git-subrepo#readme
;
[subrepo]
remote = https://github.com/WerWolv/libtesla
branch = master
commit = 779b4ead7df6b277b947a535544aa519785c437e
parent = 3b9fed9f6b06581a0748fcfbcf992929919c01b5
method = merge
cmdver = 0.4.5

View File

@@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

View File

@@ -0,0 +1,32 @@
# libtesla
<p align="center">
<img src="https://i.imgur.com/fhwyjbd.png">
</p>
libtesla is the interface between the Tesla overlay loader and user-made Overlays. It handles all layer creation, UI creation, drawing and input management.
It's main goal is to make sure all overlays look and feel similar and don't differenciate themselves from the switch's native overlays.
## Screenshots
<div>
<img src="https://i.imgur.com/jJpxYjb.jpg" style="width: 50%; float: center">
<img src="https://i.imgur.com/nBUc7ps.jpg" style="width: 50%; float: right">
</div>
`Overlays do NOT show up on Screenshots. These pictures were taken using a capture card`
## Example
An example for how to use libtesla can be found here: https://github.com/WerWolv/libtesla/tree/master/example
To create your own Overlay, please consider creating a new repository using the official Tesla overlay template: https://github.com/WerWolv/Tesla-Template
**Please Note:** While it is possible to create overlays without libtesla, it's highly recommended to not do so. libtesla handles showing and hiding of overlays, button combo detection, layer creation and a lot more. Not using it will lead to an inconsistent user experience when using multiple different overlays ultimately making it worse for the end user. If something's missing, please consider opening a PR here.
## Credits
- **switchbrew** for nx-hbloader which is used as basis for overlay loading
- **kardch** for the amazing icon
- **All the devs on AtlasNX, RetroNX and Switchbrew** for their feedback
- **All overlay devs** for making something awesome out of this :)

View File

@@ -0,0 +1,209 @@
#---------------------------------------------------------------------------------
.SUFFIXES:
#---------------------------------------------------------------------------------
ifeq ($(strip $(DEVKITPRO)),)
$(error "Please set DEVKITPRO in your environment. export DEVKITPRO=<path to>/devkitpro")
endif
TOPDIR ?= $(CURDIR)
include $(DEVKITPRO)/libnx/switch_rules
#---------------------------------------------------------------------------------
# TARGET is the name of the output
# BUILD is the directory where object files & intermediate files will be placed
# SOURCES is a list of directories containing source code
# DATA is a list of directories containing data files
# INCLUDES is a list of directories containing header files
# ROMFS is the directory containing data to be added to RomFS, relative to the Makefile (Optional)
#
# NO_ICON: if set to anything, do not use icon.
# NO_NACP: if set to anything, no .nacp file is generated.
# APP_TITLE is the name of the app stored in the .nacp file (Optional)
# APP_AUTHOR is the author of the app stored in the .nacp file (Optional)
# APP_VERSION is the version of the app stored in the .nacp file (Optional)
# APP_TITLEID is the titleID of the app stored in the .nacp file (Optional)
# ICON is the filename of the icon (.jpg), relative to the project folder.
# If not set, it attempts to use one of the following (in this order):
# - <Project name>.jpg
# - icon.jpg
# - <libnx folder>/default_icon.jpg
#
# CONFIG_JSON is the filename of the NPDM config file (.json), relative to the project folder.
# If not set, it attempts to use one of the following (in this order):
# - <Project name>.json
# - config.json
# If a JSON file is provided or autodetected, an ExeFS PFS0 (.nsp) is built instead
# of a homebrew executable (.nro). This is intended to be used for sysmodules.
# NACP building is skipped as well.
#---------------------------------------------------------------------------------
APP_TITLE := Tesla Example
APP_VERSION := 1.3.0
TARGET := $(notdir $(CURDIR))
BUILD := build
SOURCES := source
DATA := data
INCLUDES := ../include
NO_ICON := 1
#---------------------------------------------------------------------------------
# options for code generation
#---------------------------------------------------------------------------------
ARCH := -march=armv8-a+crc+crypto -mtune=cortex-a57 -mtp=soft -fPIE
CFLAGS := -g -Wall -O2 -ffunction-sections \
$(ARCH) $(DEFINES)
CFLAGS += $(INCLUDE) -D__SWITCH__
CXXFLAGS := $(CFLAGS) -fno-exceptions -std=c++20
ASFLAGS := -g $(ARCH)
LDFLAGS = -specs=$(DEVKITPRO)/libnx/switch.specs -g $(ARCH) -Wl,-Map,$(notdir $*.map)
LIBS := -lnx
#---------------------------------------------------------------------------------
# list of directories containing libraries, this must be the top level containing
# include and lib
#---------------------------------------------------------------------------------
LIBDIRS := $(PORTLIBS) $(LIBNX)
#---------------------------------------------------------------------------------
# no real need to edit anything past this point unless you need to add additional
# rules for different file extensions
#---------------------------------------------------------------------------------
ifneq ($(BUILD),$(notdir $(CURDIR)))
#---------------------------------------------------------------------------------
export OUTPUT := $(CURDIR)/$(TARGET)
export TOPDIR := $(CURDIR)
export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \
$(foreach dir,$(DATA),$(CURDIR)/$(dir))
export DEPSDIR := $(CURDIR)/$(BUILD)
CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c)))
CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp)))
SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s)))
BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*)))
#---------------------------------------------------------------------------------
# use CXX for linking C++ projects, CC for standard C
#---------------------------------------------------------------------------------
ifeq ($(strip $(CPPFILES)),)
#---------------------------------------------------------------------------------
export LD := $(CC)
#---------------------------------------------------------------------------------
else
#---------------------------------------------------------------------------------
export LD := $(CXX)
#---------------------------------------------------------------------------------
endif
#---------------------------------------------------------------------------------
export OFILES_BIN := $(addsuffix .o,$(BINFILES))
export OFILES_SRC := $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o)
export OFILES := $(OFILES_BIN) $(OFILES_SRC)
export HFILES_BIN := $(addsuffix .h,$(subst .,_,$(BINFILES)))
export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \
$(foreach dir,$(LIBDIRS),-I$(dir)/include) \
-I$(CURDIR)/$(BUILD)
export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)/lib)
ifeq ($(strip $(CONFIG_JSON)),)
jsons := $(wildcard *.json)
ifneq (,$(findstring $(TARGET).json,$(jsons)))
export APP_JSON := $(TOPDIR)/$(TARGET).json
else
ifneq (,$(findstring config.json,$(jsons)))
export APP_JSON := $(TOPDIR)/config.json
endif
endif
else
export APP_JSON := $(TOPDIR)/$(CONFIG_JSON)
endif
ifeq ($(strip $(ICON)),)
icons := $(wildcard *.jpg)
ifneq (,$(findstring $(TARGET).jpg,$(icons)))
export APP_ICON := $(TOPDIR)/$(TARGET).jpg
else
ifneq (,$(findstring icon.jpg,$(icons)))
export APP_ICON := $(TOPDIR)/icon.jpg
endif
endif
else
export APP_ICON := $(TOPDIR)/$(ICON)
endif
ifeq ($(strip $(NO_ICON)),)
export NROFLAGS += --icon=$(APP_ICON)
endif
ifeq ($(strip $(NO_NACP)),)
export NROFLAGS += --nacp=$(CURDIR)/$(TARGET).nacp
endif
ifneq ($(APP_TITLEID),)
export NACPFLAGS += --titleid=$(APP_TITLEID)
endif
ifneq ($(ROMFS),)
export NROFLAGS += --romfsdir=$(CURDIR)/$(ROMFS)
endif
.PHONY: $(BUILD) clean all
#---------------------------------------------------------------------------------
all: $(BUILD)
$(BUILD):
@[ -d $@ ] || mkdir -p $@
@$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile
#---------------------------------------------------------------------------------
clean:
@rm -fr $(BUILD) $(TARGET).ovl $(TARGET).nro $(TARGET).nacp $(TARGET).elf
#---------------------------------------------------------------------------------
else
.PHONY: all
DEPENDS := $(OFILES:.o=.d)
#---------------------------------------------------------------------------------
# main targets
#---------------------------------------------------------------------------------
all : $(OUTPUT).ovl
$(OUTPUT).ovl : $(OUTPUT).elf $(OUTPUT).nacp
@elf2nro $< $@ $(NROFLAGS)
@echo "built ... $(notdir $(OUTPUT).ovl)"
$(OUTPUT).elf : $(OFILES)
$(OFILES_SRC) : $(HFILES_BIN)
#---------------------------------------------------------------------------------
# you need a rule like this for each extension you use as binary data
#---------------------------------------------------------------------------------
%.bin.o %_bin.h : %.bin
#---------------------------------------------------------------------------------
@echo $(notdir $<)
@$(bin2o)
-include $(DEPENDS)
#---------------------------------------------------------------------------------------
endif
#---------------------------------------------------------------------------------------

View File

@@ -0,0 +1,100 @@
#define TESLA_INIT_IMPL // If you have more than one file using the tesla header, only define this in the main one
#include <tesla.hpp> // The Tesla Header
class GuiSecondary : public tsl::Gui {
public:
GuiSecondary() {}
virtual tsl::elm::Element* createUI() override {
auto *rootFrame = new tsl::elm::OverlayFrame("Tesla Example", "v1.3.2 - Secondary Gui");
rootFrame->setContent(new tsl::elm::DebugRectangle(tsl::Color{ 0x8, 0x3, 0x8, 0xF }));
return rootFrame;
}
};
class GuiTest : public tsl::Gui {
public:
GuiTest(u8 arg1, u8 arg2, bool arg3) { }
// Called when this Gui gets loaded to create the UI
// Allocate all elements on the heap. libtesla will make sure to clean them up when not needed anymore
virtual tsl::elm::Element* createUI() override {
// A OverlayFrame is the base element every overlay consists of. This will draw the default Title and Subtitle.
// If you need more information in the header or want to change it's look, use a HeaderOverlayFrame.
auto frame = new tsl::elm::OverlayFrame("Tesla Example", "v1.3.2");
// A list that can contain sub elements and handles scrolling
auto list = new tsl::elm::List();
// List Items
list->addItem(new tsl::elm::CategoryHeader("List items"));
auto *clickableListItem = new tsl::elm::ListItem("Clickable List Item", "...");
clickableListItem->setClickListener([](u64 keys) {
if (keys & HidNpadButton_A) {
tsl::changeTo<GuiSecondary>();
return true;
}
return false;
});
list->addItem(clickableListItem);
list->addItem(new tsl::elm::ListItem("Default List Item"));
list->addItem(new tsl::elm::ListItem("Default List Item with an extra long name to trigger truncation and scrolling"));
list->addItem(new tsl::elm::ToggleListItem("Toggle List Item", true));
// Custom Drawer, a element that gives direct access to the renderer
list->addItem(new tsl::elm::CategoryHeader("Custom Drawer", true));
list->addItem(new tsl::elm::CustomDrawer([](tsl::gfx::Renderer *renderer, s32 x, s32 y, s32 w, s32 h) {
renderer->drawCircle(x + 40, y + 40, 20, true, renderer->a(0xF00F));
renderer->drawCircle(x + 50, y + 50, 20, true, renderer->a(0xF0F0));
renderer->drawRect(x + 130, y + 30, 60, 40, renderer->a(0xFF00));
renderer->drawString("Hello :)", false, x + 250, y + 70, 20, renderer->a(0xFF0F));
renderer->drawRect(x + 40, y + 90, 300, 10, renderer->a(0xF0FF));
}), 100);
// Track bars
list->addItem(new tsl::elm::CategoryHeader("Track bars"));
list->addItem(new tsl::elm::TrackBar("\u2600"));
list->addItem(new tsl::elm::StepTrackBar("\uE13C", 20));
list->addItem(new tsl::elm::NamedStepTrackBar("\uE132", { "Selection 1", "Selection 2", "Selection 3" }));
// Add the list to the frame for it to be drawn
frame->setContent(list);
// Return the frame to have it become the top level element of this Gui
return frame;
}
// Called once every frame to update values
virtual void update() override {
}
// Called once every frame to handle inputs not handled by other UI elements
virtual bool handleInput(u64 keysDown, u64 keysHeld, const HidTouchState &touchPos, HidAnalogStickState joyStickPosLeft, HidAnalogStickState joyStickPosRight) override {
return false; // Return true here to signal the inputs have been consumed
}
};
class OverlayTest : public tsl::Overlay {
public:
// libtesla already initialized fs, hid, pl, pmdmnt, hid:sys and set:sys
virtual void initServices() override {} // Called at the start to initialize all services necessary for this Overlay
virtual void exitServices() override {} // Called at the end to clean up all services previously initialized
virtual void onShow() override {} // Called before overlay wants to change from invisible to visible state
virtual void onHide() override {} // Called before overlay wants to change from visible to invisible state
virtual std::unique_ptr<tsl::Gui> loadInitialGui() override {
return initially<GuiTest>(1, 2, true); // Initial Gui to load. It's possible to pass arguments to it's constructor like this
}
};
int main(int argc, char **argv) {
return tsl::loop<OverlayTest>(argc, argv);
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,16 @@
#!/bin/bash
set -e
CURRENT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
DEST="$CURRENT_DIR/../data/logo_rgba.bin"
FONT="$CURRENT_DIR/../../manager/resources/fira/FiraSans-Medium-rnx.ttf"
FONT_SIZE="30.5"
TEXT="sys-clk"
function render() {
convert -background transparent -colorspace RGB -depth 8 -fill white -font "$1" -pointsize "$2" "label:$3" "$4"
}
render "$FONT" "$FONT_SIZE" "$TEXT" info:
render "$FONT" "$FONT_SIZE" "$TEXT" "RGBA:$DEST"

View File

@@ -0,0 +1,14 @@
/*
* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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 <sysclk.h>
#include <sysclk/client/ipc.h>

View File

@@ -0,0 +1,78 @@
/*
* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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
* --------------------------------------------------------------------------
*/
#define TESLA_INIT_IMPL
#include <tesla.hpp>
#include "ui/gui/fatal_gui.h"
#include "ui/gui/main_gui.h"
class AppOverlay : public tsl::Overlay
{
public:
AppOverlay() {}
~AppOverlay() {}
virtual void exitServices() override {
sysclkIpcExit();
}
virtual std::unique_ptr<tsl::Gui> loadInitialGui() override
{
uint32_t apiVersion;
smInitialize();
tsl::hlp::ScopeGuard smGuard([] { smExit(); });
if(!sysclkIpcRunning())
{
return initially<FatalGui>(
"sys-clk is not running.\n\n"
"\n"
"Please make sure it is correctly\n\n"
"installed and enabled.\n\n"
"\n"
"Loader.kip is required to\n\n"
"use this version of sys-clk.",
""
);
}
if(R_FAILED(sysclkIpcInitialize()) || R_FAILED(sysclkIpcGetAPIVersion(&apiVersion)))
{
return initially<FatalGui>(
"Could not connect to sys-clk.\n\n"
"\n"
"Please make sure it is correctly\n\n"
"installed and enabled.",
""
);
}
if(SYSCLK_IPC_API_VERSION != apiVersion)
{
return initially<FatalGui>(
"Overlay not compatible with\n\n"
"the running sys-clk version.\n\n"
"\n"
"Please make sure everything is\n\n"
"installed and up to date.",
""
);
}
return initially<MainGui>();
}
};
int main(int argc, char **argv)
{
return tsl::loop<AppOverlay>(argc, argv);
}

View File

@@ -0,0 +1,31 @@
/*
* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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 <tesla.hpp>
#include "../gui/base_gui.h"
class BaseFrame : public tsl::elm::HeaderOverlayFrame
{
public:
BaseFrame(BaseGui* gui) : tsl::elm::HeaderOverlayFrame(130) { // headerHeight
this->gui = gui;
}
void draw(tsl::gfx::Renderer* renderer) override
{
tsl::elm::HeaderOverlayFrame::draw(renderer);
this->gui->preDraw(renderer);
}
protected:
BaseGui* gui;
};

View File

@@ -0,0 +1,26 @@
/*
* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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 <cstdio>
#define FREQ_DEFAULT_TEXT "Do not override"
static inline std::string formatListFreqMhz(std::uint32_t mhz)
{
if(mhz == 0)
return FREQ_DEFAULT_TEXT;
char buf[10];
return std::string(buf, snprintf(buf, sizeof(buf), "%u MHz", mhz));
}
static inline std::string formatListFreqHz(std::uint32_t hz) { return formatListFreqMhz(hz / 1000000); }

View File

@@ -0,0 +1,137 @@
/*
* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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
* --------------------------------------------------------------------------
*/
#include "app_profile_gui.h"
#include "../format.h"
#include "fatal_gui.h"
AppProfileGui::AppProfileGui(std::uint64_t applicationId, SysClkTitleProfileList* profileList)
{
this->applicationId = applicationId;
this->profileList = profileList;
}
AppProfileGui::~AppProfileGui()
{
delete this->profileList;
}
void AppProfileGui::openFreqChoiceGui(tsl::elm::ListItem* listItem, SysClkProfile profile, SysClkModule module)
{
tsl::changeTo<FreqChoiceGui>(this->profileList->mhzMap[profile][module], module, profile, [this, listItem, profile, module](std::uint32_t mhz) {
this->profileList->mhzMap[profile][module] = mhz;
listItem->setValue(formatListFreqMhz(this->profileList->mhzMap[profile][module]));
Result rc = sysclkIpcSetProfiles(this->applicationId, this->profileList);
if(R_FAILED(rc))
{
FatalGui::openWithResultCode("sysclkIpcSetProfiles", rc);
return false;
}
return true;
});
}
void AppProfileGui::addModuleListItem(SysClkProfile profile, SysClkModule module)
{
tsl::elm::ListItem* listItem = new tsl::elm::ListItem(sysclkFormatModule(module, true));
listItem->setValue(formatListFreqMhz(this->profileList->mhzMap[profile][module]));
listItem->setClickListener([this, listItem, profile, module](u64 keys) {
if((keys & HidNpadButton_A) == HidNpadButton_A)
{
this->openFreqChoiceGui(listItem, profile, module);
return true;
}
return false;
});
this->listElement->addItem(listItem);
}
void AppProfileGui::addProfileUI(SysClkProfile profile)
{
this->listElement->addItem(new tsl::elm::CategoryHeader(sysclkFormatProfile(profile, true)));
this->addModuleListItem(profile, SysClkModule_CPU);
this->addModuleListItem(profile, SysClkModule_GPU);
this->addModuleListItem(profile, SysClkModule_MEM);
}
void AppProfileGui::listUI()
{
if (this->applicationId != SYSCLK_GLOBAL_PROFILE_TID) {
SysClkConfigValueList* configList = new SysClkConfigValueList;
sysclkIpcGetConfigValues(configList);
bool globalGovernorEnabled = configList->values[SysClkConfigValue_GovernorExperimental];
if (globalGovernorEnabled) {
tsl::elm::ToggleListItem* cpuGovernorToggle = new tsl::elm::ToggleListItem("CPU Freq Governor",
GetGovernorEnabled(this->profileList->governorConfig, SysClkModule_CPU));
cpuGovernorToggle->setStateChangedListener([this](bool state) {
this->profileList->governorConfig = ToggleGovernor(this->profileList->governorConfig, SysClkModule_CPU, state);
Result rc = sysclkIpcSetProfiles(this->applicationId, this->profileList);
if (R_FAILED(rc))
FatalGui::openWithResultCode("sysclkIpcSetProfiles", rc);
});
this->listElement->addItem(cpuGovernorToggle);
tsl::elm::ToggleListItem* gpuGovernorToggle = new tsl::elm::ToggleListItem("GPU Freq Governor",
GetGovernorEnabled(this->profileList->governorConfig, SysClkModule_GPU));
gpuGovernorToggle->setStateChangedListener([this](bool state) {
this->profileList->governorConfig = ToggleGovernor(this->profileList->governorConfig, SysClkModule_GPU, state);
Result rc = sysclkIpcSetProfiles(this->applicationId, this->profileList);
if (R_FAILED(rc))
FatalGui::openWithResultCode("sysclkIpcSetProfiles", rc);
});
this->listElement->addItem(gpuGovernorToggle);
}
delete configList;
}
this->addProfileUI(SysClkProfile_Docked);
this->addProfileUI(SysClkProfile_Handheld);
this->addProfileUI(SysClkProfile_HandheldCharging);
this->addProfileUI(SysClkProfile_HandheldChargingOfficial);
this->addProfileUI(SysClkProfile_HandheldChargingUSB);
}
void AppProfileGui::changeTo(std::uint64_t applicationId)
{
SysClkTitleProfileList* profileList = new SysClkTitleProfileList;
Result rc = sysclkIpcGetProfiles(applicationId, profileList);
if(R_FAILED(rc))
{
delete profileList;
FatalGui::openWithResultCode("sysclkIpcGetProfiles", rc);
return;
}
tsl::changeTo<AppProfileGui>(applicationId, profileList);
}
void AppProfileGui::update()
{
BaseMenuGui::update();
if(this->context && this->applicationId != SYSCLK_GLOBAL_PROFILE_TID && this->applicationId != this->context->applicationId)
{
tsl::changeTo<FatalGui>(
"Application changed\n\n"
"\n"
"The running application changed\n\n"
"while editing was going on.",
""
);
}
}

View File

@@ -0,0 +1,33 @@
/*
* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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 "../../ipc.h"
#include "base_menu_gui.h"
#include "freq_choice_gui.h"
class AppProfileGui : public BaseMenuGui
{
protected:
std::uint64_t applicationId;
SysClkTitleProfileList* profileList;
void openFreqChoiceGui(tsl::elm::ListItem* listItem, SysClkProfile profile, SysClkModule module);
void addModuleListItem(SysClkProfile profile, SysClkModule module);
void addProfileUI(SysClkProfile profile);
public:
AppProfileGui(std::uint64_t applicationId, SysClkTitleProfileList* profileList);
~AppProfileGui();
void listUI() override;
static void changeTo(std::uint64_t applicationId);
void update() override;
};

View File

@@ -0,0 +1,40 @@
/*
* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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
* --------------------------------------------------------------------------
*/
#include "base_gui.h"
#include "../elements/base_frame.h"
// #include "logo_rgba_bin.h"
#define LOGO_LABEL_X 40
#define LOGO_LABEL_Y 35
#define LOGO_LABEL_FONT_SIZE 20
#define VERSION_X 266
#define VERSION_Y LOGO_LABEL_Y
#define VERSION_FONT_SIZE SMALL_TEXT_SIZE
void BaseGui::preDraw(tsl::gfx::Renderer* renderer)
{
renderer->drawString("Sys-clk-OC overlay", false, LOGO_LABEL_X, LOGO_LABEL_Y, LOGO_LABEL_FONT_SIZE, TEXT_COLOR);
renderer->drawString(TARGET_VERSION, false, VERSION_X, VERSION_Y, VERSION_FONT_SIZE, DESC_COLOR);
}
tsl::elm::Element* BaseGui::createUI()
{
BaseFrame* rootFrame = new BaseFrame(this);
rootFrame->setContent(this->baseUI());
return rootFrame;
}
void BaseGui::update()
{
this->refresh();
}

View File

@@ -0,0 +1,27 @@
/*
* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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 <tesla.hpp>
#include "../style.h"
class BaseGui : public tsl::Gui
{
public:
BaseGui() {}
~BaseGui() {}
virtual void preDraw(tsl::gfx::Renderer* renderer);
void update() override;
tsl::elm::Element* createUI() override;
virtual tsl::elm::Element* baseUI() = 0;
virtual void refresh() {}
};

View File

@@ -0,0 +1,114 @@
/*
* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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
* --------------------------------------------------------------------------
*/
#include "base_menu_gui.h"
#include "fatal_gui.h"
BaseMenuGui::BaseMenuGui()
{
this->context = nullptr;
this->lastContextUpdate = 0;
this->listElement = nullptr;
}
BaseMenuGui::~BaseMenuGui()
{
if(this->context)
{
delete this->context;
}
}
void BaseMenuGui::preDraw(tsl::gfx::Renderer* renderer)
{
BaseGui::preDraw(renderer);
if(this->context)
{
char buf[32];
renderer->drawString("App ID: ", false, 40, 60, SMALL_TEXT_SIZE, DESC_COLOR);
snprintf(buf, sizeof(buf), "%016lX", context->applicationId);
renderer->drawString(buf, false, 100, 60, SMALL_TEXT_SIZE, VALUE_COLOR);
renderer->drawString("Profile: ", false, 266, 60, SMALL_TEXT_SIZE, DESC_COLOR);
renderer->drawString(sysclkFormatProfile(context->profile, true), false, 322, 60, SMALL_TEXT_SIZE, VALUE_COLOR);
static struct
{
SysClkModule m;
std::uint32_t x;
} freqOffsets[SysClkModule_EnumMax] = {
{ SysClkModule_CPU, 80 },
{ SysClkModule_GPU, 200 },
{ SysClkModule_MEM, 320 },
};
for(unsigned int i = 0; i < SysClkModule_EnumMax; i++)
{
std::uint32_t hz = this->context->freqs[freqOffsets[i].m];
snprintf(buf, sizeof(buf), "%u MHz", hz / 1000000);
renderer->drawString(buf, false, freqOffsets[i].x, 85, SMALL_TEXT_SIZE, VALUE_COLOR);
}
renderer->drawString("CPU:", false, 40, 85, SMALL_TEXT_SIZE, DESC_COLOR);
renderer->drawString("GPU:", false, 160, 85, SMALL_TEXT_SIZE, DESC_COLOR);
renderer->drawString("MEM:", false, 270, 85, SMALL_TEXT_SIZE, DESC_COLOR);
static struct
{
SysClkThermalSensor s;
std::uint32_t x;
} tempOffsets[SysClkModule_EnumMax] = {
{ SysClkThermalSensor_SOC, 80 },
{ SysClkThermalSensor_PCB, 200 },
{ SysClkThermalSensor_Skin, 320 },
};
renderer->drawString("SOC:", false, 40, 110, SMALL_TEXT_SIZE, DESC_COLOR);
renderer->drawString("PCB:", false, 160, 110, SMALL_TEXT_SIZE, DESC_COLOR);
renderer->drawString("Skin:", false, 270, 110, SMALL_TEXT_SIZE, DESC_COLOR);
for(unsigned int i = 0; i < SysClkModule_EnumMax; i++)
{
std::uint32_t millis = this->context->temps[tempOffsets[i].s];
snprintf(buf, sizeof(buf), "%u.%u °C", millis / 1000, (millis - millis / 1000 * 1000) / 100);
renderer->drawString(buf, false, tempOffsets[i].x, 110, SMALL_TEXT_SIZE, VALUE_COLOR);
}
}
}
void BaseMenuGui::refresh()
{
std::uint64_t ticks = armGetSystemTick();
if(armTicksToNs(ticks - this->lastContextUpdate) > 500000000UL)
{
this->lastContextUpdate = ticks;
if(!this->context)
{
this->context = new SysClkContext;
}
Result rc = sysclkIpcGetCurrentContext(this->context);
if(R_FAILED(rc))
{
FatalGui::openWithResultCode("sysclkIpcGetCurrentContext", rc);
return;
}
}
}
tsl::elm::Element* BaseMenuGui::baseUI()
{
tsl::elm::List* list = new tsl::elm::List();
this->listElement = list;
this->listUI();
return list;
}

View File

@@ -0,0 +1,30 @@
/*
* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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 "../../ipc.h"
#include "base_gui.h"
class BaseMenuGui : public BaseGui
{
protected:
SysClkContext* context;
std::uint64_t lastContextUpdate;
tsl::elm::List* listElement;
public:
BaseMenuGui();
~BaseMenuGui();
void preDraw(tsl::gfx::Renderer* renderer) override;
tsl::elm::Element* baseUI() override;
void refresh() override;
virtual void listUI() = 0;
};

View File

@@ -0,0 +1,67 @@
/*
* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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
* --------------------------------------------------------------------------
*/
#include "fatal_gui.h"
FatalGui::FatalGui(const std::string message, const std::string info)
{
this->message = message;
this->info = info;
}
void FatalGui::openWithResultCode(std::string tag, Result rc)
{
char rcStr[32];
std::string info = tag;
info.append(rcStr, snprintf(rcStr, sizeof(rcStr), "\n\n[0x%x] %04d-%04d", rc, R_MODULE(rc), R_DESCRIPTION(rc)));
tsl::changeTo<FatalGui>(
"Could not connect to sys-clk.\n\n"
"\n"
"Please make sure everything is\n\n"
"correctly installed and enabled.",
info
);
}
tsl::elm::Element* FatalGui::baseUI()
{
tsl::elm::CustomDrawer* drawer = new tsl::elm::CustomDrawer([this](tsl::gfx::Renderer* renderer, u16 x, u16 y, u16 w, u16 h) {
renderer->drawString("\uE150", false, 40, 210, 40, TEXT_COLOR);
renderer->drawString("Fatal error", false, 100, 210, 30, TEXT_COLOR);
std::uint32_t txtY = 255;
if(!this->message.empty())
{
txtY += renderer->drawString(this->message.c_str(), false, 40, txtY, 23, TEXT_COLOR).second;
txtY += 55;
}
if(!this->info.empty())
{
renderer->drawString(this->info.c_str(), false, 40, txtY, 18, DESC_COLOR);
}
});
return drawer;
}
bool FatalGui::handleInput(u64 keysDown, u64 keysHeld, const HidTouchState &touchPos, HidAnalogStickState joyStickPosLeft, HidAnalogStickState joyStickPosRight)
{
if((keysDown & HidNpadButton_A) == HidNpadButton_A || (keysDown & HidNpadButton_B) == HidNpadButton_B)
{
while(tsl::Overlay::get()->getCurrentGui() != nullptr) {
tsl::goBack();
}
return true;
}
return false;
}

View File

@@ -0,0 +1,29 @@
/*
* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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 <list>
#include "base_gui.h"
class FatalGui : public BaseGui
{
protected:
std::string message;
std::string info;
public:
FatalGui(const std::string message, const std::string info);
~FatalGui() {}
tsl::elm::Element* baseUI() override;
bool handleInput(u64 keysDown, u64 keysHeld, const HidTouchState &touchPos, HidAnalogStickState joyStickPosLeft, HidAnalogStickState joyStickPosRight);
static void openWithResultCode(std::string tag, Result rc);
};

View File

@@ -0,0 +1,65 @@
/*
* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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
* --------------------------------------------------------------------------
*/
#include "freq_choice_gui.h"
#include "../format.h"
#include "fatal_gui.h"
FreqChoiceGui::FreqChoiceGui(std::uint32_t selectedMHz, SysClkModule module, SysClkProfile profile, FreqChoiceListener listener)
{
this->hzTable = new SysClkFrequencyTable;
Result rc = sysclkIpcGetFrequencyTable(module, profile, hzTable);
if (R_FAILED(rc)) {
FatalGui::openWithResultCode("sysclkIpcGetFrequencyTable", rc);
}
this->selectedMHz = selectedMHz;
this->listener = listener;
}
FreqChoiceGui::~FreqChoiceGui() {
delete this->hzTable;
}
tsl::elm::ListItem* FreqChoiceGui::createFreqListItem(std::uint32_t mhz, bool selected)
{
tsl::elm::ListItem* listItem = new tsl::elm::ListItem(formatListFreqMhz(mhz));
listItem->setValue(selected ? "\uE14B" : "");
listItem->setClickListener([this, mhz](u64 keys) {
if((keys & HidNpadButton_A) == HidNpadButton_A && this->listener)
{
if(this->listener(mhz))
{
tsl::goBack();
}
return true;
}
return false;
});
return listItem;
}
void FreqChoiceGui::listUI()
{
this->listElement->addItem(this->createFreqListItem(0, this->selectedMHz == 0));
size_t idx = 0;
uint32_t freq;
while(idx < FREQ_TABLE_MAX_ENTRY_COUNT && (freq = this->hzTable->freq[idx]))
{
uint32_t mhz = freq / 1000'000;
this->listElement->addItem(this->createFreqListItem(mhz, mhz == this->selectedMHz));
idx++;
}
}

View File

@@ -0,0 +1,33 @@
/*
* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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 <list>
#include "base_menu_gui.h"
using FreqChoiceListener = std::function<bool(std::uint32_t mhz)>;
#define FREQ_DEFAULT_TEXT "Do not override"
class FreqChoiceGui : public BaseMenuGui
{
protected:
std::uint32_t selectedMHz;
SysClkFrequencyTable* hzTable;
FreqChoiceListener listener;
tsl::elm::ListItem* createFreqListItem(std::uint32_t mhz, bool selected);
public:
FreqChoiceGui(std::uint32_t selectedMHz, SysClkModule module, SysClkProfile profile, FreqChoiceListener listener);
~FreqChoiceGui();
void listUI() override;
};

View File

@@ -0,0 +1,83 @@
/*
* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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
* --------------------------------------------------------------------------
*/
#include "global_override_gui.h"
#include "fatal_gui.h"
#include "../format.h"
GlobalOverrideGui::GlobalOverrideGui()
{
for(std::uint16_t m = 0; m < SysClkModule_EnumMax; m++)
{
this->listItems[m] = nullptr;
this->listHz[m] = 0;
}
}
void GlobalOverrideGui::openFreqChoiceGui(SysClkModule module)
{
tsl::changeTo<FreqChoiceGui>(this->context->overrideFreqs[module] / 1000'000, module, this->context->profile, [this, module](std::uint32_t mhz) {
Result rc = sysclkIpcSetOverride(module, mhz * 1000'000);
if(R_FAILED(rc))
{
FatalGui::openWithResultCode("sysclkIpcSetOverride", rc);
return false;
}
this->lastContextUpdate = armGetSystemTick();
this->context->overrideFreqs[module] = mhz * 1000'000;
return true;
});
}
void GlobalOverrideGui::addModuleListItem(SysClkModule module)
{
tsl::elm::ListItem* listItem = new tsl::elm::ListItem(sysclkFormatModule(module, true));
listItem->setValue(formatListFreqMhz(0));
listItem->setClickListener([this, module](u64 keys) {
if((keys & HidNpadButton_A) == HidNpadButton_A)
{
this->openFreqChoiceGui(module);
return true;
}
return false;
});
this->listElement->addItem(listItem);
this->listItems[module] = listItem;
}
void GlobalOverrideGui::listUI()
{
this->addModuleListItem(SysClkModule_CPU);
this->addModuleListItem(SysClkModule_GPU);
this->addModuleListItem(SysClkModule_MEM);
}
void GlobalOverrideGui::refresh()
{
BaseMenuGui::refresh();
if(this->context)
{
for(std::uint16_t m = 0; m < SysClkModule_EnumMax; m++)
{
if(this->listItems[m] != nullptr && this->listHz[m] != this->context->overrideFreqs[m])
{
this->listItems[m]->setValue(formatListFreqHz(this->context->overrideFreqs[m]));
this->listHz[m] = this->context->overrideFreqs[m];
}
}
}
}

View File

@@ -0,0 +1,31 @@
/*
* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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 "../../ipc.h"
#include "base_menu_gui.h"
#include "freq_choice_gui.h"
class GlobalOverrideGui : public BaseMenuGui
{
protected:
tsl::elm::ListItem* listItems[SysClkModule_EnumMax];
std::uint32_t listHz[SysClkModule_EnumMax];
void openFreqChoiceGui(SysClkModule module);
void addModuleListItem(SysClkModule module);
public:
GlobalOverrideGui();
~GlobalOverrideGui() {}
void listUI() override;
void refresh() override;
};

View File

@@ -0,0 +1,92 @@
/*
* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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
* --------------------------------------------------------------------------
*/
#include "main_gui.h"
#include "fatal_gui.h"
#include "app_profile_gui.h"
#include "global_override_gui.h"
#include "misc_gui.h"
void MainGui::listUI()
{
this->enabledToggle = new tsl::elm::ToggleListItem("Enable", false);
enabledToggle->setStateChangedListener([this](bool state) {
Result rc = sysclkIpcSetEnabled(state);
if(R_FAILED(rc))
{
FatalGui::openWithResultCode("sysclkIpcSetEnabled", rc);
}
this->lastContextUpdate = armGetSystemTick();
this->context->enabled = state;
});
this->listElement->addItem(this->enabledToggle);
tsl::elm::ListItem* appProfileItem = new tsl::elm::ListItem("Edit app profile");
appProfileItem->setClickListener([this](u64 keys) {
if((keys & HidNpadButton_A) == HidNpadButton_A && this->context)
{
AppProfileGui::changeTo(this->context->applicationId);
return true;
}
return false;
});
this->listElement->addItem(appProfileItem);
this->listElement->addItem(new tsl::elm::CategoryHeader("Advanced"));
tsl::elm::ListItem* globalOverrideItem = new tsl::elm::ListItem("Temporary overrides");
globalOverrideItem->setClickListener([this](u64 keys) {
if((keys & HidNpadButton_A) == HidNpadButton_A)
{
tsl::changeTo<GlobalOverrideGui>();
return true;
}
return false;
});
this->listElement->addItem(globalOverrideItem);
tsl::elm::ListItem* globalProfileItem = new tsl::elm::ListItem("Global profile");
globalProfileItem->setClickListener([this](u64 keys) {
if((keys & HidNpadButton_A) == HidNpadButton_A && this->context)
{
AppProfileGui::changeTo(SYSCLK_GLOBAL_PROFILE_TID);
return true;
}
return false;
});
this->listElement->addItem(globalProfileItem);
tsl::elm::ListItem* miscItem = new tsl::elm::ListItem("Miscellaneous");
miscItem->setClickListener([this](u64 keys) {
if((keys & HidNpadButton_A) == HidNpadButton_A && this->context)
{
tsl::changeTo<MiscGui>();
return true;
}
return false;
});
this->listElement->addItem(miscItem);
}
void MainGui::refresh()
{
BaseMenuGui::refresh();
if(this->context)
{
this->enabledToggle->setState(this->context->enabled);
}
}

View File

@@ -0,0 +1,25 @@
/*
* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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 "base_menu_gui.h"
class MainGui : public BaseMenuGui
{
protected:
tsl::elm::ToggleListItem* enabledToggle;
public:
MainGui() {}
~MainGui() {}
void listUI() override;
void refresh() override;
};

View File

@@ -0,0 +1,183 @@
/* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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
* --------------------------------------------------------------------------
*/
#include "misc_gui.h"
#include "fatal_gui.h"
#include "../format.h"
MiscGui::MiscGui()
{
smInitialize();
this->configList = new SysClkConfigValueList {};
this->chargeInfo = new PsmChargeInfo {};
this->i2cInfo = new I2cInfo {};
sysclkIpcGetIsMariko(&this->isMariko);
}
MiscGui::~MiscGui()
{
delete this->configList;
delete this->chargeInfo;
delete this->i2cInfo;
this->configToggles.clear();
smExit();
}
void MiscGui::addConfigToggle(SysClkConfigValue configVal, const char* altName = nullptr) {
const char* configName = altName ? altName : sysclkFormatConfigValue(configVal, true);
tsl::elm::ToggleListItem* toggle = new tsl::elm::ToggleListItem(configName, this->configList->values[configVal]);
toggle->setStateChangedListener([this, configVal](bool state) {
this->configList->values[configVal] = uint64_t(state);
Result rc = sysclkIpcSetConfigValues(this->configList);
if (R_FAILED(rc))
FatalGui::openWithResultCode("sysclkIpcSetConfigValues", rc);
this->lastContextUpdate = armGetSystemTick();
});
this->listElement->addItem(toggle);
this->configToggles[configVal] = toggle;
}
void MiscGui::updateConfigToggles() {
for (const auto& [value, toggle] : this->configToggles) {
if (toggle != nullptr)
toggle->setState(this->configList->values[value]);
}
}
void MiscGui::listUI()
{
// Config list
sysclkIpcGetConfigValues(this->configList);
this->listElement->addItem(new tsl::elm::CategoryHeader("Config"));
addConfigToggle(SysClkConfigValue_AutoCPUBoost, this->isMariko ? nullptr : "Auto CPU Boost (Unsafe)");
addConfigToggle(SysClkConfigValue_SyncReverseNXMode);
addConfigToggle(SysClkConfigValue_GovernorExperimental);
// Charging Current
this->chargingCurrentHeader = new tsl::elm::CategoryHeader("");
this->listElement->addItem(this->chargingCurrentHeader);
constexpr size_t current_steps = CHARGING_CURRENT_MA_LIMIT / 100;
this->chargingCurrentBar = new StepTrackBarIcon("", current_steps + 1);
this->chargingCurrentBar->setProgress(this->configList->values[SysClkConfigValue_ChargingCurrentLimit]);
this->chargingCurrentBar->setValueChangedListener([this](u8 val) {
if (val < 1) {
val = 1;
this->chargingCurrentBar->setProgress(val);
}
if (val > current_steps) {
val = current_steps;
this->chargingCurrentBar->setProgress(val);
}
uint32_t current_ma = val * 100;
this->configList->values[SysClkConfigValue_ChargingCurrentLimit] = current_ma;
snprintf(chargingCurrentBarDesc, sizeof(chargingCurrentBarDesc), "Charging Current: %lu mA (Now: %+d mA)", this->configList->values[SysClkConfigValue_ChargingCurrentLimit], (int)this->i2cInfo->batCurrent);
this->chargingCurrentHeader->setText(chargingCurrentBarDesc);
Result rc = sysclkIpcSetConfigValues(this->configList);
if (R_FAILED(rc))
FatalGui::openWithResultCode("sysclkIpcSetConfigValues", rc);
this->lastContextUpdate = armGetSystemTick();
});
this->listElement->addItem(this->chargingCurrentBar);
// Charging Limit
this->chargingLimitHeader = new tsl::elm::CategoryHeader("");
this->listElement->addItem(this->chargingLimitHeader);
this->chargingLimitBar = new StepTrackBarIcon("", 100 + 1);
this->chargingLimitBar->setProgress(this->configList->values[SysClkConfigValue_ChargingLimitPercentage]);
this->chargingLimitBar->setValueChangedListener([this](u8 val) {
if (val < 20) {
val = 20;
this->chargingLimitBar->setProgress(val);
}
this->configList->values[SysClkConfigValue_ChargingLimitPercentage] = val;
snprintf(chargingLimitBarDesc, sizeof(chargingLimitBarDesc), "Battery Charging Limit: %lu%% (Now: %u%%)", this->configList->values[SysClkConfigValue_ChargingLimitPercentage], this->batteryChargePerc);
this->chargingLimitHeader->setText(chargingLimitBarDesc);
this->chargingLimitBar->setIcon(PsmGetBatteryStateIcon(this->chargeInfo));
Result rc = sysclkIpcSetConfigValues(this->configList);
if (R_FAILED(rc))
FatalGui::openWithResultCode("sysclkIpcSetConfigValues", rc);
this->lastContextUpdate = armGetSystemTick();
});
this->listElement->addItem(this->chargingLimitBar);
this->listElement->addItem(new tsl::elm::CustomDrawer([](tsl::gfx::Renderer* renderer, s32 x, s32 y, s32 w, s32 h) {
renderer->drawString("\uE016 Long-term use may render the battery gauge \ninaccurate!", false, x, y + 20, SMALL_TEXT_SIZE, DESC_COLOR);
}), SMALL_TEXT_SIZE * 2 + 20);
// Temporary toggles
this->listElement->addItem(new tsl::elm::CategoryHeader("Temporary toggles"));
this->chargingDisabledOverrideToggle = new tsl::elm::ToggleListItem("Force Disable Charging", false);
chargingDisabledOverrideToggle->setStateChangedListener([this](bool state) {
Result rc = sysclkIpcSetBatteryChargingDisabledOverride(state);
if (R_FAILED(rc))
FatalGui::openWithResultCode("sysclkIpcSetBatteryChargingDisabledOverride", rc);
this->lastContextUpdate = armGetSystemTick();
});
this->listElement->addItem(this->chargingDisabledOverrideToggle);
this->backlightToggle = new tsl::elm::ToggleListItem("Screen Backlight", false);
backlightToggle->setStateChangedListener([this](bool state) {
LblUpdate(true);
});
this->listElement->addItem(this->backlightToggle);
// Info
this->listElement->addItem(new tsl::elm::CategoryHeader("Info"));
this->listElement->addItem(new tsl::elm::CustomDrawer([this](tsl::gfx::Renderer *renderer, s32 x, s32 y, s32 w, s32 h) {
renderer->drawString(this->infoNames, false, x, y + 20, SMALL_TEXT_SIZE, DESC_COLOR);
renderer->drawString(this->infoVals, false, x + 120, y + 20, SMALL_TEXT_SIZE, VALUE_COLOR);
}), SMALL_TEXT_SIZE * 12 + 20);
}
void MiscGui::refresh() {
BaseMenuGui::refresh();
if (this->context && ++frameCounter >= 60)
{
frameCounter = 0;
sysclkIpcGetConfigValues(this->configList);
updateConfigToggles();
PsmUpdate();
this->chargingLimitBar->setIcon(PsmGetBatteryStateIcon(this->chargeInfo));
bool chargingDisabledOverride;
Result rc = sysclkIpcGetBatteryChargingDisabledOverride(&chargingDisabledOverride);
if (R_FAILED(rc))
FatalGui::openWithResultCode("sysclkIpcGetBatteryChargingDisabledOverride", rc);
this->chargingDisabledOverrideToggle->setState(chargingDisabledOverride);
LblUpdate();
this->backlightToggle->setState(lblstatus);
this->chargingCurrentBar->setProgress(this->configList->values[SysClkConfigValue_ChargingCurrentLimit] / 100);
snprintf(chargingCurrentBarDesc, sizeof(chargingCurrentBarDesc), "Charging Current: %lu mA (Now: %+d mA)", this->configList->values[SysClkConfigValue_ChargingCurrentLimit], (int)this->i2cInfo->batCurrent);
this->chargingCurrentHeader->setText(chargingCurrentBarDesc);
this->chargingLimitBar->setProgress(this->configList->values[SysClkConfigValue_ChargingLimitPercentage]);
snprintf(chargingLimitBarDesc, sizeof(chargingLimitBarDesc), "Charging Limit: %lu%% (Now: %u%%)", this->configList->values[SysClkConfigValue_ChargingLimitPercentage], this->batteryChargePerc);
this->chargingLimitHeader->setText(chargingLimitBarDesc);
I2cGetInfo(this->i2cInfo);
UpdateInfo(this->infoVals, sizeof(this->infoVals));
}
}

View File

@@ -0,0 +1,182 @@
/* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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 "../../ipc.h"
#include "base_menu_gui.h"
#include <inttypes.h>
class StepTrackBarIcon : public tsl::elm::StepTrackBar {
public:
StepTrackBarIcon(const char icon[3], size_t numSteps):
tsl::elm::StepTrackBar(icon, numSteps) { }
const char* getIcon() { return this->m_icon; }
void setIcon(const char* icon) { this->m_icon = icon; }
};
class MiscGui : public BaseMenuGui
{
public:
MiscGui();
~MiscGui();
void listUI() override;
void refresh() override;
protected:
typedef struct {
float batCurrent;
u32 cpuVolt;
u32 gpuVolt;
u32 emcVddq;
u32 memVdd2;
} I2cInfo;
void PsmUpdate(uint32_t dispatchId = 0)
{
psmInitialize();
if (dispatchId)
{
serviceDispatch(psmGetServiceSession(), dispatchId);
svcSleepThread(1000);
}
serviceDispatchOut(psmGetServiceSession(), 17, *(this->chargeInfo));
psmGetBatteryChargePercentage(&(this->batteryChargePerc));
psmExit();
}
void I2cGetInfo(I2cInfo* i2cInfo)
{
i2cInitialize();
float batCurrent = I2c_Max17050_GetBatteryCurrent();
i2cInfo->batCurrent = std::abs(batCurrent) < 10. ? 0. : batCurrent;
if (isMariko) {
i2cInfo->cpuVolt = I2c_BuckConverter_GetMvOut(&I2c_Mariko_CPU);
i2cInfo->gpuVolt = I2c_BuckConverter_GetMvOut(&I2c_Mariko_GPU);
i2cInfo->emcVddq = I2c_BuckConverter_GetMvOut(&I2c_Mariko_DRAM_VDDQ);
i2cInfo->memVdd2 = I2c_BuckConverter_GetMvOut(&I2c_Mariko_DRAM_VDD2);
} else {
i2cInfo->cpuVolt = I2c_BuckConverter_GetMvOut(&I2c_Erista_CPU);
i2cInfo->gpuVolt = I2c_BuckConverter_GetMvOut(&I2c_Erista_GPU);
i2cInfo->emcVddq = I2c_BuckConverter_GetMvOut(&I2c_Erista_DRAM);
i2cInfo->memVdd2 = i2cInfo->emcVddq;
}
I2c_Bq24193_GetFastChargeCurrentLimit(reinterpret_cast<u32 *>(&(chargeInfo->ChargeCurrentLimit)));
i2cExit();
}
void UpdateInfo(char* out, size_t outsize)
{
float chargerVoltLimit = (float)chargeInfo->ChargerVoltageLimit / 1000;
float chargerCurrLimit = (float)chargeInfo->ChargerCurrentLimit / 1000;
float chargerOutWatts = chargerVoltLimit * chargerCurrLimit;
char chargeVoltLimit[20] = "";
if (chargeInfo->ChargeVoltageLimit)
snprintf(chargeVoltLimit, sizeof(chargeVoltLimit), ", %umV", chargeInfo->ChargeVoltageLimit);
char chargWattsInfo[30] = "";
if (chargeInfo->ChargerType)
snprintf(chargWattsInfo, sizeof(chargWattsInfo), " %.1fV/%.1fA (%.1fW)", chargerVoltLimit, chargerCurrLimit, chargerOutWatts);
char batCurInfo[30] = "";
snprintf(batCurInfo, sizeof(batCurInfo), "%+.2fmA (%+.2fW)",
i2cInfo->batCurrent, i2cInfo->batCurrent * (float)chargeInfo->VoltageAvg / 1000'000);
snprintf(out, outsize,
"%s%s\n"
"%.3fV %.2f\u00B0C\n"
"+%umA, -%umA\n"
"+%umA%s\n"
"%.2f%%\n"
"%.2f%%\n"
"%s\n"
"%s\n\n"
"%dmV\n"
"%dmV\n"
"Vddq %dmV, Vdd2 %dmV\n"
,
PsmInfoChargerTypeToStr(chargeInfo->ChargerType), chargWattsInfo,
(float)chargeInfo->VoltageAvg / 1000, (float)chargeInfo->BatteryTemperature / 1000,
chargeInfo->InputCurrentLimit, chargeInfo->VBUSCurrentLimit,
chargeInfo->ChargeCurrentLimit, chargeVoltLimit,
(float)chargeInfo->RawBatteryCharge / 1000,
(float)chargeInfo->BatteryAge / 1000,
PsmPowerRoleToStr(chargeInfo->PowerRole),
batCurInfo,
i2cInfo->cpuVolt,
i2cInfo->gpuVolt,
i2cInfo->emcVddq, i2cInfo->memVdd2
);
}
void PsmChargingToggler(bool* enable)
{
if (!PsmIsChargerConnected(this->chargeInfo))
{
*enable = false;
return;
}
PsmUpdate(*enable ? 2 : 3);
*enable = (PsmIsCharging(this->chargeInfo) == *enable);
}
void LblUpdate(bool shouldSwitch = false)
{
lblInitialize();
lblGetBacklightSwitchStatus(&lblstatus);
if (shouldSwitch)
lblstatus ? lblSwitchBacklightOff(0) : lblSwitchBacklightOn(0);
lblExit();
}
bool isMariko = false;
std::map<SysClkConfigValue, tsl::elm::ToggleListItem*> configToggles;
void addConfigToggle(SysClkConfigValue, const char*);
void updateConfigToggles();
tsl::elm::ToggleListItem *chargingDisabledOverrideToggle, *backlightToggle;
tsl::elm::CategoryHeader *chargingCurrentHeader, *chargingLimitHeader;
StepTrackBarIcon *chargingCurrentBar, *chargingLimitBar;
SysClkConfigValueList* configList;
PsmChargeInfo* chargeInfo;
I2cInfo* i2cInfo;
LblBacklightSwitchStatus lblstatus = LblBacklightSwitchStatus_Disabled;
const char* infoNames =
"Charger:\n"\
"Battery:\n"\
"Current Limit:\n"\
"Charging Limit:\n"\
"Raw Charge:\n"\
"Battery Age:\n"\
"Power Role:\n"\
"Current Flow:\n\n"\
"CPU Volt:\n"\
"GPU Volt:\n"\
"DRAM Volt:";
char infoVals[300] = "";
char chargingLimitBarDesc[40] = "";
char chargingCurrentBarDesc[50] = "";
u32 batteryChargePerc = 0;
u8 frameCounter = 60;
};

View File

@@ -0,0 +1,20 @@
/*
* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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 <tesla.hpp>
#define TEXT_COLOR tsl::gfx::Renderer::a(0xFFFF)
#define DESC_COLOR tsl::gfx::Renderer::a({ 0xC, 0xC, 0xC, 0xF })
#define VALUE_COLOR tsl::gfx::Renderer::a({ 0x5, 0xC, 0xA, 0xF })
#define SMALL_TEXT_SIZE 15
#define LABEL_SPACING 7
#define LABEL_FONT_SIZE 15

View File

@@ -0,0 +1,2 @@
/out
/build

View File

@@ -0,0 +1,164 @@
#---------------------------------------------------------------------------------
.SUFFIXES:
#---------------------------------------------------------------------------------
ifeq ($(strip $(DEVKITPRO)),)
$(error "Please set DEVKITPRO in your environment. export DEVKITPRO=<path to>/devkitpro")
endif
TOPDIR ?= $(CURDIR)
include $(DEVKITPRO)/libnx/switch_rules
#---------------------------------------------------------------------------------
# TARGET is the name of the output
# BUILD is the directory where object files & intermediate files will be placed
# SOURCES is a list of directories containing source code
# DATA is a list of directories containing data files
# INCLUDES is a list of directories containing header files
# EXEFS_SRC is the optional input directory containing data copied into exefs, if anything this normally should only contain "main.npdm".
#---------------------------------------------------------------------------------
TARGET := sys-clk-OC
BUILD := build
OUTDIR := out
RESOURCES := res
SOURCES := src src/nx/ipc ../common/src
DATA := data
INCLUDES := ../common/include
EXEFS_SRC := exefs_src
LIBNAMES := minIni nxExt
#---------------------------------------------------------------------------------
# version control constants
#---------------------------------------------------------------------------------
TARGET_VERSION := 1.8.3
#---------------------------------------------------------------------------------
# options for code generation
#---------------------------------------------------------------------------------
DEFINES := -DDISABLE_IPC -DTARGET="\"$(TARGET)\"" -DTARGET_VERSION="\"$(TARGET_VERSION)\""
ARCH := -march=armv8-a+crc+crypto -mtune=cortex-a57 -mtp=soft -fPIE
CFLAGS := -g -Wall -O3 -ffunction-sections \
$(ARCH) $(DEFINES)
CFLAGS += $(INCLUDE) -D__SWITCH__
CXXFLAGS := $(CFLAGS) -fno-rtti -std=gnu++20
ASFLAGS := -g $(ARCH)
LDFLAGS = -specs=$(DEVKITPRO)/libnx/switch.specs -g $(ARCH) -Wl,-Map,$(notdir $*.map)
LIBS := -lnx $(foreach lib,$(LIBNAMES),-l$(lib))
#---------------------------------------------------------------------------------
# list of directories containing libraries, this must be the top level containing
# include and lib
#---------------------------------------------------------------------------------
LIBDIRS := $(PORTLIBS) $(LIBNX) $(foreach lib,$(LIBNAMES),$(TOPDIR)/lib/$(lib))
#---------------------------------------------------------------------------------
# no real need to edit anything past this point unless you need to add additional
# rules for different file extensions
#---------------------------------------------------------------------------------
ifneq ($(BUILD),$(notdir $(CURDIR)))
#---------------------------------------------------------------------------------
export OUTPUT := $(CURDIR)/$(OUTDIR)/$(TARGET)
export TOPDIR := $(CURDIR)
export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \
$(foreach dir,$(DATA),$(CURDIR)/$(dir))
export DEPSDIR := $(CURDIR)/$(BUILD)
CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c)))
CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp)))
SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s)))
BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*)))
#---------------------------------------------------------------------------------
# use CXX for linking C++ projects, CC for standard C
#---------------------------------------------------------------------------------
ifeq ($(strip $(CPPFILES)),)
#---------------------------------------------------------------------------------
export LD := $(CC)
#---------------------------------------------------------------------------------
else
#---------------------------------------------------------------------------------
export LD := $(CXX)
#---------------------------------------------------------------------------------
endif
#---------------------------------------------------------------------------------
export OFILES := $(addsuffix .o,$(BINFILES)) \
$(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o)
export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \
$(foreach dir,$(LIBDIRS),-I$(dir)/include) \
-I$(CURDIR)/$(BUILD)
export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)/lib)
export BUILD_EXEFS_SRC := $(TOPDIR)/$(EXEFS_SRC)
export APP_JSON := $(TOPDIR)/perms.json
.PHONY: $(BUILD) clean clean-libs clean-build all libs
#---------------------------------------------------------------------------------
all: $(BUILD)
libs:
@$(foreach lib,$(LIBNAMES),$(MAKE) --no-print-directory -C $(TOPDIR)/lib/$(lib) && ) true
$(LIBNAMES):
@echo $@
$(BUILD): libs
@[ -d $@ ] || mkdir -p $@
@[ -d $(OUTDIR) ] || mkdir -p $(OUTDIR)
@$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile
#---------------------------------------------------------------------------------
clean-libs:
@echo clean libs $(LIBNAMES) ...
@$(foreach lib,$(LIBNAMES),$(MAKE) -C $(TOPDIR)/lib/$(lib) clean && ) true
clean-build:
@echo clean build ...
@rm -fr $(BUILD) $(TARGET).kip $(TARGET).nsp $(TARGET).npdm $(TARGET).nso $(TARGET).elf $(OUTDIR)
clean: clean-libs clean-build
#---------------------------------------------------------------------------------
else
.PHONY: all $(LIBFILES)
LIBFILES := $(foreach lib,$(LIBNAMES),$(TOPDIR)/lib/$(lib)/lib/lib$(lib).a)
DEPENDS := $(OFILES:.o=.d)
#---------------------------------------------------------------------------------
# main targets
#---------------------------------------------------------------------------------
all: $(OUTPUT).nsp
$(OUTPUT).nsp: $(OUTPUT).nso $(OUTPUT).npdm
$(OUTPUT).elf: $(OFILES) $(LIBFILES)
#---------------------------------------------------------------------------------
# you need a rule like this for each extension you use as binary data
#---------------------------------------------------------------------------------
%.bin.o : %.bin
#---------------------------------------------------------------------------------
@echo $(notdir $<)
@$(bin2o)
-include $(DEPENDS)
#---------------------------------------------------------------------------------------
endif
#---------------------------------------------------------------------------------------

View File

@@ -0,0 +1,13 @@
# Editor files
*.swp
*~
# Objects
*.o
*.a
*.so
# Lib
lib
release
debug

View File

@@ -0,0 +1,12 @@
; DO NOT EDIT (unless you know what you are doing)
;
; This subdirectory is a git "subrepo", and this file is maintained by the
; git-subrepo command. See https://github.com/git-commands/git-subrepo#readme
;
[subrepo]
remote = https://github.com/compuphase/minIni
branch = master
commit = 8ce144c3c287fa4e59f8ed4c405cd8b7e29f189b
parent = f32c0b1bca87a6d7e55fb341f8db9ef33b13819f
method = merge
cmdver = 0.4.0

View File

@@ -0,0 +1,189 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
EXCEPTION TO THE APACHE 2.0 LICENSE
As a special exception to the Apache License 2.0 (and referring to the
definitions in Section 1 of this license), you may link, statically or
dynamically, the "Work" to other modules to produce an executable file
containing portions of the "Work", and distribute that executable file
in "Object" form under the terms of your choice, without any of the
additional requirements listed in Section 4 of the Apache License 2.0.
This exception applies only to redistributions in "Object" form (not
"Source" form) and only if no modifications have been made to the "Work".
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.

View File

@@ -0,0 +1,133 @@
#---------------------------------------------------------------------------------
.SUFFIXES:
#---------------------------------------------------------------------------------
ifeq ($(strip $(DEVKITPRO)),)
$(error "Please set DEVKITPRO in your environment. export DEVKITPRO=<path to>/devkitpro")
endif
include $(DEVKITPRO)/libnx/switch_rules
#---------------------------------------------------------------------------------
# TARGET is the name of the output
# SOURCES is a list of directories containing source code
# DATA is a list of directories containing data files
# INCLUDES is a list of directories containing header files
#---------------------------------------------------------------------------------
TARGET := $(notdir $(CURDIR))
SOURCES := dev
DATA := data
INCLUDES := dev
SRC_H_FILES :=
#---------------------------------------------------------------------------------
# options for code generation
#---------------------------------------------------------------------------------
ARCH := -march=armv8-a+crc+crypto -mtune=cortex-a57 -mtp=soft -fPIC -ftls-model=local-exec
CFLAGS := -g -Wall -Werror \
-ffunction-sections \
-fdata-sections \
$(ARCH) \
$(BUILD_CFLAGS)
CFLAGS += $(INCLUDE)
CXXFLAGS := $(CFLAGS) -fno-rtti -fno-exceptions
ASFLAGS := -g $(ARCH)
#---------------------------------------------------------------------------------
# list of directories containing libraries, this must be the top level containing
# include and lib
#---------------------------------------------------------------------------------
LIBDIRS := $(PORTLIBS) $(LIBNX)
#---------------------------------------------------------------------------------
# no real need to edit anything past this point unless you need to add additional
# rules for different file extensions
#---------------------------------------------------------------------------------
ifneq ($(BUILD),$(notdir $(CURDIR)))
#---------------------------------------------------------------------------------
export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \
$(foreach dir,$(DATA),$(CURDIR)/$(dir))
CFILES := minIni.c
CPPFILES :=
SFILES :=
BINFILES :=
#---------------------------------------------------------------------------------
# use CXX for linking C++ projects, CC for standard C
#---------------------------------------------------------------------------------
ifeq ($(strip $(CPPFILES)),)
#---------------------------------------------------------------------------------
export LD := $(CC)
#---------------------------------------------------------------------------------
else
#---------------------------------------------------------------------------------
export LD := $(CXX)
#---------------------------------------------------------------------------------
endif
#---------------------------------------------------------------------------------
export OFILES_BIN := $(addsuffix .o,$(BINFILES))
export OFILES_SRC := $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o)
export OFILES := $(OFILES_BIN) $(OFILES_SRC)
export HFILES := $(addsuffix .h,$(subst .,_,$(BINFILES)))
export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \
$(foreach dir,$(LIBDIRS),-I$(dir)/include) \
-I$(CURDIR)/$(BUILD)
.PHONY: clean all lib/lib$(TARGET).a
#---------------------------------------------------------------------------------
all: lib/lib$(TARGET).a
lib:
@[ -d $@ ] || mkdir -p $@
release:
@[ -d $@ ] || mkdir -p $@
debug:
@[ -d $@ ] || mkdir -p $@
lib/lib$(TARGET).a : lib release $(SOURCES) $(INCLUDES)
@$(MAKE) BUILD=release OUTPUT=$(CURDIR)/$@ \
BUILD_CFLAGS="-DNDEBUG=1 -O2" \
DEPSDIR=$(CURDIR)/release \
--no-print-directory -C release \
-f $(CURDIR)/Makefile
#---------------------------------------------------------------------------------
clean:
@echo clean ...
@rm -fr release debug lib
#---------------------------------------------------------------------------------
else
DEPENDS := $(OFILES:.o=.d)
#---------------------------------------------------------------------------------
# main targets
#---------------------------------------------------------------------------------
$(OUTPUT) : $(OFILES)
$(OFILES_SRC) : $(HFILES)
#---------------------------------------------------------------------------------
%_bin.h %.bin.o : %.bin
#---------------------------------------------------------------------------------
@echo $(notdir $<)
@$(bin2o)
-include $(DEPENDS)
#---------------------------------------------------------------------------------------
endif
#---------------------------------------------------------------------------------------

View File

@@ -0,0 +1,12 @@
minIni is a programmer's library to read and write "INI" files in embedded
systems. The library takes little resources and can be configured for various
kinds of file I/O libraries.
The method for portable INI file management in minIni is, in part based, on the
article "Multiplatform .INI Files" by Joseph J. Graf in the March 1994 issue of
Dr. Dobb's Journal.
The C++ class in minIni.h was contributed by Steven Van Ingelgem.
The option to compile minIni as a read-only library was contributed by Luca
Bassanello.

View File

@@ -0,0 +1,170 @@
# minIni
minIni is a portable and configurable library for reading and writing ".INI" files. At 830 lines of commented source
code
(version 1.2), minIni truly is a "mini" INI file parser, especially considering its features.
The library does not require the file I/O functions from the standard C/C++ library, but instead lets you configure
the file I/O interface to use via macros. minIni uses limited stack space and does not use dynamic memory (malloc and
friends) at all.
Some minor variations on standard INI files are supported too, notably minIni supports INI files that lack sections.
# Acknowledgement
minIni is derived from an earlier INI file parser (which I wrote) for desktop systems.
In turn, that earlier parser was a re-write of the code from the article "Multiplatform .INI Files" by Joseph J. Graf
in the March 1994 issue of Dr. Dobb's Journal. In other words, minIni has its roots in the work of Joseph Graf (even
though the code has been almost completely re-written).
# Features
minIni is a programmer's library to read and write "INI" files in embedded systems. minIni takes little resources,
can be configured for various kinds of file I/O libraries and provides functionality for reading, writing and
deleting keys from an INI file.
Although the main feature of minIni is that it is small and minimal, it has a few other features:
* minIni supports reading keys that are outside a section, and it thereby supports configuration files that do not use sections (but that are otherwise compatible with INI files).
* You may use a colon to separate key and value; the colon is equivalent to the equal sign. That is, the strings "Name: Value" and "Name=Value" have the same meaning.
* The hash character ("#") is an alternative for the semicolon to start a comment. Trailing comments (i.e. behind a key/value pair on a line) are allowed.
* Leading and trailing white space around key names and values is ignored.
* When writing a value that contains a comment character (";" or "#"), that value will automatically be put between double quotes; when reading the value, these quotes are removed. When a double-quote itself appears in the setting, these characters are escaped.
* Section and key enumeration are supported.
* You can optionally set the line termination (for text files) that minIni will use. (This is a compile-time setting, not a run-time setting.)
* Since writing speed is much lower than reading speed in Flash memory (SD/MMC cards, USB memory sticks), minIni minimizes "file writes" at the expense of double "file reads".
* The memory footprint is deterministic. There is no dynamic memory allocation.
## INI file reading paradigms
There are two approaches to reading settings from an INI file. One way is to call a function, such as
GetProfileString() for every section and key that you need. This is especially convenient if there is a large
INI file, but you only need a few settings from that file at any time &mdash;especially if the INI file can also
change while your program runs. This is the approach that the Microsoft Windows API uses.
The above procedure is quite inefficient, however, when you need to retrieve quite a few settings in a row from
the INI file &mdash;especially if the INI file is not cached in memory (which it isn't, in minIni). A different approach
to getting settings from an INI file is to call a "parsing" function and let that function call the application
back with the section and key names plus the associated data. XML parsing libraries often use this approach; see
for example the Expat library.
minIni supports both approaches. For reading a single setting, use functions like ini_gets(). For the callback
approach, implement a callback and call ini_browse(). See the minIni manual for details.
# INI file syntax
INI files are best known from Microsoft Windows, but they are also used with applications that run on other
platforms (although their file extension is sometimes ".cfg" instead of ".ini").
INI files have a simple syntax with name/value pairs in a plain text file. The name must be unique (per section)
and the value must fit on a single line. INI files are commonly separated into sections &mdash;in minIni, this is
optional. A section is a name between square brackets, like "[Network]" in the example below.
```
[Network]
hostname=My Computer
address=dhcp
dns = 192.168.1.1
```
In the API and in this documentation, the "name" for a setting is denoted as the key for the setting. The key
and the value are separated by an equal sign ("="). minIni supports the colon (":") as an alternative to the
equal sign for the key/value delimiter.
Leading a trailing spaces around values or key names are removed. If you need to include leading and/or trailing
spaces in a value, put the value between double quotes. The ini_gets() function (from the minIni library, see the
minIni manual) strips off the double quotes from the returned value. Function ini_puts() adds double quotes if
the value to write contains trailing white space (or special characters).
minIni ignores spaces around the "=" or ":" delimiters, but it does not ignore spaces between the brackets in a
section name. In other words, it is best not to put spaces behind the opening bracket "[" or before the closing
bracket "]" of a section name.
Comments in the INI must start with a semicolon (";") or a hash character ("#"), and run to the end of the line.
A comment can be a line of its own, or it may follow a key/value pair (the "#" character and trailing comments
are extensions of minIni).
For more details on the format, please see http://en.wikipedia.org/wiki/INI_file.
# Adapting minIni to a file system
The minIni library must be configured for a platform with the help of a so- called "glue file". This glue file
contains macros (and possibly functions) that map file reading and writing functions used by the minIni library
to those provided by the operating system. The glue file must be called "minGlue.h".
To get you started, the minIni distribution comes with the following example glue files:
* a glue file that maps to the standard C/C++ library (specifically the file I/O functions from the "stdio" package),
* a glue file for Microchip's "Memory Disk Drive File System Library" (see http://www.microchip.com/),
* a glue file for the FAT library provided with the CCS PIC compiler (see http://www.ccsinfo.com/)
* a glue file for the EFS Library (EFSL, http://www.efsl.be/),
* and a glue file for the FatFs and Petit-FatFs libraries (http://elm-chan.org/fsw/ff/00index_e.html).
The minIni library does not rely on the availability of a standard C library, because embedded operating systems
may have limited support for file I/O. Even on full operating systems, separating the file I/O from the INI format
parsing carries advantages, because it allows you to cache the INI file and thereby enhance performance.
The glue file must specify the type that identifies a file, whether it is a handle or a pointer. For the standard
C/C++ file I/O library, this would be:
```C
#define INI_FILETYPE FILE*
```
If you are not using the standard C/C++ file I/O library, chances are that you need a different handle or
"structure" to identify the storage than the ubiquitous "FILE*" type. For example, the glue file for the FatFs
library uses the following declaration:
```C
#define INI_FILETYPE FIL
```
The minIni functions declare variables of this INI_FILETYPE type and pass these variables to sub-functions
(including the glue interface functions) by reference.
For "write support", another type that must be defined is for variables that hold the "current position" in a
file. For the standard C/C++ I/O library, this is "fpos_t".
Another item that needs to be configured is the buffer size. The functions in the minIni library allocate this
buffer on the stack, so the buffer size is directly related to the stack usage. In addition, the buffer size
determines the maximum line length that is supported in the INI file and the maximum path name length for the
temporary file. For example, minGlue.h could contain the definition:
```C
#define INI_BUFFERSIZE 512
```
The above macro limits the line length of the INI files supported by minIni to 512 characters.
The temporary file is only used when writing to INI files. The minIni routines copy/change the INI file to a
temporary file and then rename that temporary file to the original file. This approach uses the least amount of
memory. The path name of the temporary file is the same as the input file, but with the last character set to a
tilde ("~").
Below is an example of a glue file (this is the one that maps to the C/C++ "stdio" library).
```C
#include <stdio.h>
#define INI_FILETYPE FILE*
#define ini_openread(filename,file) ((*(file) = fopen((filename),"r")) != NULL)
#define ini_openwrite(filename,file) ((*(file) = fopen((filename),"w")) != NULL)
#define ini_close(file) (fclose(*(file)) == 0)
#define ini_read(buffer,size,file) (fgets((buffer),(size),*(file)) != NULL)
#define ini_write(buffer,file) (fputs((buffer),*(file)) >= 0)
#define ini_rename(source,dest) (rename((source), (dest)) == 0)
#define ini_remove(filename) (remove(filename) == 0)
#define INI_FILEPOS fpos_t
#define ini_tell(file,pos) (fgetpos(*(file), (pos)) == 0)
#define ini_seek(file,pos) (fsetpos(*(file), (pos)) == 0)
```
As you can see, a glue file is mostly a set of macros that wraps one function definition around another.
The glue file may contain more settings, for support of rational numbers, to explicitly set the line termination
character(s), or to disable write support (for example). See the manual that comes with the archive for the details.

View File

@@ -0,0 +1,37 @@
/* Glue functions for the minIni library, based on the FatFs and Petit-FatFs
* libraries, see http://elm-chan.org/fsw/ff/00index_e.html
*
* By CompuPhase, 2008-2012
* This "glue file" is in the public domain. It is distributed without
* warranties or conditions of any kind, either express or implied.
*
* (The FatFs and Petit-FatFs libraries are copyright by ChaN and licensed at
* its own terms.)
*/
#define INI_BUFFERSIZE 256 /* maximum line length, maximum path length */
/* You must set _USE_STRFUNC to 1 or 2 in the include file ff.h (or tff.h)
* to enable the "string functions" fgets() and fputs().
*/
#include "ff.h" /* include tff.h for Tiny-FatFs */
#define INI_FILETYPE FIL
#define ini_openread(filename,file) (f_open((file), (filename), FA_READ+FA_OPEN_EXISTING) == FR_OK)
#define ini_openwrite(filename,file) (f_open((file), (filename), FA_WRITE+FA_CREATE_ALWAYS) == FR_OK)
#define ini_close(file) (f_close(file) == FR_OK)
#define ini_read(buffer,size,file) f_gets((buffer), (size),(file))
#define ini_write(buffer,file) f_puts((buffer), (file))
#define ini_remove(filename) (f_unlink(filename) == FR_OK)
#define INI_FILEPOS DWORD
#define ini_tell(file,pos) (*(pos) = f_tell((file)))
#define ini_seek(file,pos) (f_lseek((file), *(pos)) == FR_OK)
static int ini_rename(TCHAR *source, const TCHAR *dest)
{
/* Function f_rename() does not allow drive letters in the destination file */
char *drive = strchr(dest, ':');
drive = (drive == NULL) ? dest : drive + 1;
return (f_rename(source, drive) == FR_OK);
}

View File

@@ -0,0 +1,64 @@
/* minIni glue functions for FAT library by CCS, Inc. (as provided with their
* PIC MCU compiler)
*
* By CompuPhase, 2011-2012
* This "glue file" is in the public domain. It is distributed without
* warranties or conditions of any kind, either express or implied.
*
* (The FAT library is copyright (c) 2007 Custom Computer Services, and
* licensed at its own terms.)
*/
#define INI_BUFFERSIZE 256 /* maximum line length, maximum path length */
#ifndef FAT_PIC_C
#error FAT library must be included before this module
#endif
#define const /* keyword not supported by CCS */
#define INI_FILETYPE FILE
#define ini_openread(filename,file) (fatopen((filename), "r", (file)) == GOODEC)
#define ini_openwrite(filename,file) (fatopen((filename), "w", (file)) == GOODEC)
#define ini_close(file) (fatclose((file)) == 0)
#define ini_read(buffer,size,file) (fatgets((buffer), (size), (file)) != NULL)
#define ini_write(buffer,file) (fatputs((buffer), (file)) == GOODEC)
#define ini_remove(filename) (rm_file((filename)) == 0)
#define INI_FILEPOS fatpos_t
#define ini_tell(file,pos) (fatgetpos((file), (pos)) == 0)
#define ini_seek(file,pos) (fatsetpos((file), (pos)) == 0)
#ifndef INI_READONLY
/* CCS FAT library lacks a rename function, so instead we copy the file to the
* new name and delete the old file
*/
static int ini_rename(char *source, char *dest)
{
FILE fr, fw;
int n;
if (fatopen(source, "r", &fr) != GOODEC)
return 0;
if (rm_file(dest) != 0)
return 0;
if (fatopen(dest, "w", &fw) != GOODEC)
return 0;
/* With some "insider knowledge", we can save some memory: the "source"
* parameter holds a filename that was built from the "dest" parameter. It
* was built in a local buffer with the size INI_BUFFERSIZE. We can reuse
* this buffer for copying the file.
*/
while (n=fatread(source, 1, INI_BUFFERSIZE, &fr))
fatwrite(source, 1, n, &fw);
fatclose(&fr);
fatclose(&fw);
/* Now we need to delete the source file. However, we have garbled the buffer
* that held the filename of the source. So we need to build it again.
*/
ini_tempname(source, dest, INI_BUFFERSIZE);
return rm_file(source) == 0;
}
#endif

View File

@@ -0,0 +1,63 @@
/* Glue functions for the minIni library, based on the EFS Library, see
* http://www.efsl.be/
*
* By CompuPhase, 2008-2012
* This "glue file" is in the public domain. It is distributed without
* warranties or conditions of any kind, either express or implied.
*
* (EFSL is copyright 2005-2006 Lennart Ysboodt and Michael De Nil, and
* licensed under the GPL with an exception clause for static linking.)
*/
#define INI_BUFFERSIZE 256 /* maximum line length, maximum path length */
#define INI_LINETERM "\r\n" /* set line termination explicitly */
#include "efs.h"
extern EmbeddedFileSystem g_efs;
#define INI_FILETYPE EmbeddedFile
#define ini_openread(filename,file) (file_fopen((file), &g_efs.myFs, (char*)(filename), 'r') == 0)
#define ini_openwrite(filename,file) (file_fopen((file), &g_efs.myFs, (char*)(filename), 'w') == 0)
#define ini_close(file) file_fclose(file)
#define ini_read(buffer,size,file) (file_read((file), (size), (buffer)) > 0)
#define ini_write(buffer,file) (file_write((file), strlen(buffer), (char*)(buffer)) > 0)
#define ini_remove(filename) rmfile(&g_efs.myFs, (char*)(filename))
#define INI_FILEPOS euint32
#define ini_tell(file,pos) (*(pos) = (file)->FilePtr))
#define ini_seek(file,pos) file_setpos((file), (*pos))
#if ! defined INI_READONLY
/* EFSL lacks a rename function, so instead we copy the file to the new name
* and delete the old file
*/
static int ini_rename(char *source, const char *dest)
{
EmbeddedFile fr, fw;
int n;
if (file_fopen(&fr, &g_efs.myFs, source, 'r') != 0)
return 0;
if (rmfile(&g_efs.myFs, (char*)dest) != 0)
return 0;
if (file_fopen(&fw, &g_efs.myFs, (char*)dest, 'w') != 0)
return 0;
/* With some "insider knowledge", we can save some memory: the "source"
* parameter holds a filename that was built from the "dest" parameter. It
* was built in buffer and this buffer has the size INI_BUFFERSIZE. We can
* reuse this buffer for copying the file.
*/
while (n=file_read(&fr, INI_BUFFERSIZE, source))
file_write(&fw, n, source);
file_fclose(&fr);
file_fclose(&fw);
/* Now we need to delete the source file. However, we have garbled the buffer
* that held the filename of the source. So we need to build it again.
*/
ini_tempname(source, dest, INI_BUFFERSIZE);
return rmfile(&g_efs.myFs, source) == 0;
}
#endif

View File

@@ -0,0 +1,26 @@
/* Glue functions for the minIni library, based on the "FAT Filing System"
* library by embedded-code.com
*
* By CompuPhase, 2008-2012
* This "glue file" is in the public domain. It is distributed without
* warranties or conditions of any kind, either express or implied.
*
* (The "FAT Filing System" library itself is copyright embedded-code.com, and
* licensed at its own terms.)
*/
#define INI_BUFFERSIZE 256 /* maximum line length, maximum path length */
#include <mem-ffs.h>
#define INI_FILETYPE FFS_FILE*
#define ini_openread(filename,file) ((*(file) = ffs_fopen((filename),"r")) != NULL)
#define ini_openwrite(filename,file) ((*(file) = ffs_fopen((filename),"w")) != NULL)
#define ini_close(file) (ffs_fclose(*(file)) == 0)
#define ini_read(buffer,size,file) (ffs_fgets((buffer),(size),*(file)) != NULL)
#define ini_write(buffer,file) (ffs_fputs((buffer),*(file)) >= 0)
#define ini_rename(source,dest) (ffs_rename((source), (dest)) == 0)
#define ini_remove(filename) (ffs_remove(filename) == 0)
#define INI_FILEPOS long
#define ini_tell(file,pos) (ffs_fgetpos(*(file), (pos)) == 0)
#define ini_seek(file,pos) (ffs_fsetpos(*(file), (pos)) == 0)

View File

@@ -0,0 +1,58 @@
/* minIni glue functions for Microchip's "Memory Disk Drive" file system
* library, as presented in Microchip application note AN1045.
*
* By CompuPhase, 2011-2014
* This "glue file" is in the public domain. It is distributed without
* warranties or conditions of any kind, either express or implied.
*
* (The "Microchip Memory Disk Drive File System" is copyright (c) Microchip
* Technology Incorporated, and licensed at its own terms.)
*/
#define INI_BUFFERSIZE 256 /* maximum line length, maximum path length */
#include "MDD File System\fsio.h"
#include <string.h>
#define INI_FILETYPE FSFILE*
#define ini_openread(filename,file) ((*(file) = FSfopen((filename),FS_READ)) != NULL)
#define ini_openwrite(filename,file) ((*(file) = FSfopen((filename),FS_WRITE)) != NULL)
#define ini_openrewrite(filename,file) ((*(file) = fopen((filename),FS_READPLUS)) != NULL)
#define ini_close(file) (FSfclose(*(file)) == 0)
#define ini_write(buffer,file) (FSfwrite((buffer), 1, strlen(buffer), (*file)) > 0)
#define ini_remove(filename) (FSremove((filename)) == 0)
#define INI_FILEPOS long int
#define ini_tell(file,pos) (*(pos) = FSftell(*(file)))
#define ini_seek(file,pos) (FSfseek(*(file), *(pos), SEEK_SET) == 0)
/* Since the Memory Disk Drive file system library reads only blocks of files,
* the function to read a text line does so by "over-reading" a block of the
* of the maximum size and truncating it behind the end-of-line.
*/
static int ini_read(char *buffer, int size, INI_FILETYPE *file)
{
size_t numread = size;
char *eol;
if ((numread = FSfread(buffer, 1, size, *file)) == 0)
return 0; /* at EOF */
if ((eol = strchr(buffer, '\n')) == NULL)
eol = strchr(buffer, '\r');
if (eol != NULL) {
/* terminate the buffer */
*++eol = '\0';
/* "unread" the data that was read too much */
FSfseek(*file, - (int)(numread - (size_t)(eol - buffer)), SEEK_CUR);
} /* if */
return 1;
}
#ifndef INI_READONLY
static int ini_rename(const char *source, const char *dest)
{
FSFILE* ftmp = FSfopen((source), FS_READ);
FSrename((dest), ftmp);
return FSfclose(ftmp) == 0;
}
#endif

View File

@@ -0,0 +1,31 @@
/* Glue functions for the minIni library, based on the C/C++ stdio library
*
* Or better said: this file contains macros that maps the function interface
* used by minIni to the standard C/C++ file I/O functions.
*
* By CompuPhase, 2008-2014
* This "glue file" is in the public domain. It is distributed without
* warranties or conditions of any kind, either express or implied.
*/
/* map required file I/O types and functions to the standard C library */
#include <stdio.h>
#define INI_FILETYPE FILE*
#define ini_openread(filename,file) ((*(file) = fopen((filename),"rb")) != NULL)
#define ini_openwrite(filename,file) ((*(file) = fopen((filename),"wb")) != NULL)
#define ini_openrewrite(filename,file) ((*(file) = fopen((filename),"r+b")) != NULL)
#define ini_close(file) (fclose(*(file)) == 0)
#define ini_read(buffer,size,file) (fgets((buffer),(size),*(file)) != NULL)
#define ini_write(buffer,file) (fputs((buffer),*(file)) >= 0)
#define ini_rename(source,dest) (rename((source), (dest)) == 0)
#define ini_remove(filename) (remove(filename) == 0)
#define INI_FILEPOS long int
#define ini_tell(file,pos) (*(pos) = ftell(*(file)))
#define ini_seek(file,pos) (fseek(*(file), *(pos), SEEK_SET) == 0)
/* for floating-point support, define additional types and functions */
#define INI_REAL float
#define ini_ftoa(string,value) sprintf((string),"%f",(value))
#define ini_atof(string) (INI_REAL)strtod((string),NULL)

View File

@@ -0,0 +1,35 @@
/* Glue functions for the minIni library, based on the C/C++ stdio library
*
* Or better said: this file contains macros that maps the function interface
* used by minIni to the standard C/C++ file I/O functions.
*
* By CompuPhase, 2008-2014
* This "glue file" is in the public domain. It is distributed without
* warranties or conditions of any kind, either express or implied.
*/
/* map required file I/O types and functions to the standard C library */
#include <stdio.h>
#define INI_FILETYPE FILE*
#define ini_openread(filename,file) ((*(file) = fopen((filename),"rb")) != NULL)
#define ini_openwrite(filename,file) ((*(file) = fopen((filename),"wb")) != NULL)
#define ini_openrewrite(filename,file) ((*(file) = fopen((filename),"r+b")) != NULL)
#define ini_close(file) (fclose(*(file)) == 0)
#define ini_read(buffer,size,file) (fgets((buffer),(size),*(file)) != NULL)
#define ini_write(buffer,file) (fputs((buffer),*(file)) >= 0)
#define ini_rename(source,dest) (rename((source), (dest)) == 0)
#define ini_remove(filename) (remove(filename) == 0)
#define INI_FILEPOS long int
#define ini_tell(file,pos) (*(pos) = ftell(*(file)))
#define ini_seek(file,pos) (fseek(*(file), *(pos), SEEK_SET) == 0)
/* for floating-point support, define additional types and functions */
//#define INI_REAL float
//#define ini_ftoa(string,value) sprintf((string),"%f",(value))
//#define ini_atof(string) (INI_REAL)strtod((string),NULL)
#define INI_ANSIONLY
#define INI_LINETERM "\n"
#define PORTABLE_STRNICMP

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,158 @@
/* minIni - Multi-Platform INI file parser, suitable for embedded systems
*
* Copyright (c) CompuPhase, 2008-2017
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* Version: $Id: minIni.h 53 2015-01-18 13:35:11Z thiadmer.riemersma@gmail.com $
*/
#ifndef MININI_H
#define MININI_H
#include "minGlue.h"
#if (defined _UNICODE || defined __UNICODE__ || defined UNICODE) && !defined INI_ANSIONLY
#include <tchar.h>
#define mTCHAR TCHAR
#else
/* force TCHAR to be "char", but only for minIni */
#define mTCHAR char
#endif
#if !defined INI_BUFFERSIZE
#define INI_BUFFERSIZE 512
#endif
#if defined __cplusplus
extern "C" {
#endif
int ini_getbool(const mTCHAR *Section, const mTCHAR *Key, int DefValue, const mTCHAR *Filename);
long ini_getl(const mTCHAR *Section, const mTCHAR *Key, long DefValue, const mTCHAR *Filename);
int ini_gets(const mTCHAR *Section, const mTCHAR *Key, const mTCHAR *DefValue, mTCHAR *Buffer, int BufferSize, const mTCHAR *Filename);
int ini_getsection(int idx, mTCHAR *Buffer, int BufferSize, const mTCHAR *Filename);
int ini_getkey(const mTCHAR *Section, int idx, mTCHAR *Buffer, int BufferSize, const mTCHAR *Filename);
#if defined INI_REAL
INI_REAL ini_getf(const mTCHAR *Section, const mTCHAR *Key, INI_REAL DefValue, const mTCHAR *Filename);
#endif
#if !defined INI_READONLY
int ini_putl(const mTCHAR *Section, const mTCHAR *Key, long Value, const mTCHAR *Filename);
int ini_puts(const mTCHAR *Section, const mTCHAR *Key, const mTCHAR *Value, const mTCHAR *Filename);
int ini_putsection(const mTCHAR *Section, const mTCHAR **Keys, const mTCHAR **Values, const mTCHAR *Filename);
#if defined INI_REAL
int ini_putf(const mTCHAR *Section, const mTCHAR *Key, INI_REAL Value, const mTCHAR *Filename);
#endif
#endif /* INI_READONLY */
#if !defined INI_NOBROWSE
typedef int (*INI_CALLBACK)(const mTCHAR *Section, const mTCHAR *Key, const mTCHAR *Value, void *UserData);
int ini_browse(INI_CALLBACK Callback, void *UserData, const mTCHAR *Filename);
#endif /* INI_NOBROWSE */
#if defined __cplusplus
}
#endif
#if defined __cplusplus
#if defined __WXWINDOWS__
#include "wxMinIni.h"
#else
#include <string>
/* The C++ class in minIni.h was contributed by Steven Van Ingelgem. */
class minIni
{
public:
minIni(const std::string& filename) : iniFilename(filename)
{ }
bool getbool(const std::string& Section, const std::string& Key, bool DefValue=false) const
{ return ini_getbool(Section.c_str(), Key.c_str(), int(DefValue), iniFilename.c_str()) != 0; }
long getl(const std::string& Section, const std::string& Key, long DefValue=0) const
{ return ini_getl(Section.c_str(), Key.c_str(), DefValue, iniFilename.c_str()); }
int geti(const std::string& Section, const std::string& Key, int DefValue=0) const
{ return static_cast<int>(this->getl(Section, Key, long(DefValue))); }
std::string gets(const std::string& Section, const std::string& Key, const std::string& DefValue="") const
{
char buffer[INI_BUFFERSIZE];
ini_gets(Section.c_str(), Key.c_str(), DefValue.c_str(), buffer, INI_BUFFERSIZE, iniFilename.c_str());
return buffer;
}
std::string getsection(int idx) const
{
char buffer[INI_BUFFERSIZE];
ini_getsection(idx, buffer, INI_BUFFERSIZE, iniFilename.c_str());
return buffer;
}
std::string getkey(const std::string& Section, int idx) const
{
char buffer[INI_BUFFERSIZE];
ini_getkey(Section.c_str(), idx, buffer, INI_BUFFERSIZE, iniFilename.c_str());
return buffer;
}
#if defined INI_REAL
INI_REAL getf(const std::string& Section, const std::string& Key, INI_REAL DefValue=0) const
{ return ini_getf(Section.c_str(), Key.c_str(), DefValue, iniFilename.c_str()); }
#endif
#if ! defined INI_READONLY
bool put(const std::string& Section, const std::string& Key, long Value)
{ return ini_putl(Section.c_str(), Key.c_str(), Value, iniFilename.c_str()) != 0; }
bool put(const std::string& Section, const std::string& Key, int Value)
{ return ini_putl(Section.c_str(), Key.c_str(), (long)Value, iniFilename.c_str()) != 0; }
bool put(const std::string& Section, const std::string& Key, bool Value)
{ return ini_putl(Section.c_str(), Key.c_str(), (long)Value, iniFilename.c_str()) != 0; }
bool put(const std::string& Section, const std::string& Key, const std::string& Value)
{ return ini_puts(Section.c_str(), Key.c_str(), Value.c_str(), iniFilename.c_str()) != 0; }
bool put(const std::string& Section, const std::string& Key, const char* Value)
{ return ini_puts(Section.c_str(), Key.c_str(), Value, iniFilename.c_str()) != 0; }
#if defined INI_REAL
bool put(const std::string& Section, const std::string& Key, INI_REAL Value)
{ return ini_putf(Section.c_str(), Key.c_str(), Value, iniFilename.c_str()) != 0; }
#endif
bool del(const std::string& Section, const std::string& Key)
{ return ini_puts(Section.c_str(), Key.c_str(), 0, iniFilename.c_str()) != 0; }
bool del(const std::string& Section)
{ return ini_puts(Section.c_str(), 0, 0, iniFilename.c_str()) != 0; }
#endif
#if !defined INI_NOBROWSE
bool browse(INI_CALLBACK Callback, void *UserData) const
{ return ini_browse(Callback, UserData, iniFilename.c_str()) != 0; }
#endif
private:
std::string iniFilename;
};
#endif /* __WXWINDOWS__ */
#endif /* __cplusplus */
#endif /* MININI_H */

View File

@@ -0,0 +1,117 @@
/* Simple test program
*
* gcc -o test test.c minIni.c
*/
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include "minIni.h"
#define sizearray(a) (sizeof(a) / sizeof((a)[0]))
const char inifile[] = "test.ini";
const char inifile2[] = "testplain.ini";
int Callback(const char *section, const char *key, const char *value, void *userdata)
{
(void)userdata; /* this parameter is not used in this example */
printf(" [%s]\t%s=%s\n", section, key, value);
return 1;
}
int main(void)
{
char str[100];
long n;
int s, k;
char section[50];
/* string reading */
n = ini_gets("first", "string", "dummy", str, sizearray(str), inifile);
assert(n==4 && strcmp(str,"noot")==0);
n = ini_gets("second", "string", "dummy", str, sizearray(str), inifile);
assert(n==4 && strcmp(str,"mies")==0);
n = ini_gets("first", "undefined", "dummy", str, sizearray(str), inifile);
assert(n==5 && strcmp(str,"dummy")==0);
/* ----- */
n = ini_gets("", "string", "dummy", str, sizearray(str), inifile2);
assert(n==4 && strcmp(str,"noot")==0);
n = ini_gets(NULL, "string", "dummy", str, sizearray(str), inifile2);
assert(n==4 && strcmp(str,"noot")==0);
/* ----- */
printf("1. String reading tests passed\n");
/* value reading */
n = ini_getl("first", "val", -1, inifile);
assert(n==1);
n = ini_getl("second", "val", -1, inifile);
assert(n==2);
n = ini_getl("first", "undefined", -1, inifile);
assert(n==-1);
/* ----- */
n = ini_getl(NULL, "val", -1, inifile2);
assert(n==1);
/* ----- */
printf("2. Value reading tests passed\n");
/* string writing */
n = ini_puts("first", "alt", "flagged as \"correct\"", inifile);
assert(n==1);
n = ini_gets("first", "alt", "dummy", str, sizearray(str), inifile);
assert(n==20 && strcmp(str,"flagged as \"correct\"")==0);
/* ----- */
n = ini_puts("second", "alt", "correct", inifile);
assert(n==1);
n = ini_gets("second", "alt", "dummy", str, sizearray(str), inifile);
assert(n==7 && strcmp(str,"correct")==0);
/* ----- */
n = ini_puts("third", "test", "correct", inifile);
assert(n==1);
n = ini_gets("third", "test", "dummy", str, sizearray(str), inifile);
assert(n==7 && strcmp(str,"correct")==0);
/* ----- */
n = ini_puts("second", "alt", "overwrite", inifile);
assert(n==1);
n = ini_gets("second", "alt", "dummy", str, sizearray(str), inifile);
assert(n==9 && strcmp(str,"overwrite")==0);
/* ----- */
n = ini_puts("second", "alt", "123456789", inifile);
assert(n==1);
n = ini_gets("second", "alt", "dummy", str, sizearray(str), inifile);
assert(n==9 && strcmp(str,"123456789")==0);
/* ----- */
n = ini_puts(NULL, "alt", "correct", inifile2);
assert(n==1);
n = ini_gets(NULL, "alt", "dummy", str, sizearray(str), inifile2);
assert(n==7 && strcmp(str,"correct")==0);
/* ----- */
printf("3. String writing tests passed\n");
/* section/key enumeration */
printf("4. Section/key enumeration, file structure follows\n");
for (s = 0; ini_getsection(s, section, sizearray(section), inifile) > 0; s++) {
printf(" [%s]\n", section);
for (k = 0; ini_getkey(section, k, str, sizearray(str), inifile) > 0; k++) {
printf("\t%s\n", str);
} /* for */
} /* for */
/* browsing through the file */
printf("5. browse through all settings, file field list follows\n");
ini_browse(Callback, NULL, inifile);
/* string deletion */
n = ini_puts("first", "alt", NULL, inifile);
assert(n==1);
n = ini_puts("second", "alt", NULL, inifile);
assert(n==1);
n = ini_puts("third", NULL, NULL, inifile);
assert(n==1);
/* ----- */
n = ini_puts(NULL, "alt", NULL, inifile2);
assert(n==1);
printf("6. String deletion tests passed\n");
return 0;
}

View File

@@ -0,0 +1,8 @@
[First]
String=noot # trailing commment
Val=1
[Second]
Val = 2
#comment=3
String = mies

View File

@@ -0,0 +1,80 @@
/*
gcc -o minIni.o -c minIni.c
g++ -o test2.o -c test2.cc
g++ -o test2 test2.o minIni.o
./test2
*/
#include <assert>
#include <iostream>
#include <string>
using namespace std ;
#include "minIni.h"
int main(void)
{
minIni ini("test.ini");
string s;
/* string reading */
s = ini.gets( "first", "string" , "aap" );
assert(s == "noot");
s = ini.gets( "second", "string" , "aap" );
assert(s == "mies");
s = ini.gets( "first", "dummy" , "aap" );
assert(s == "aap");
cout << "1. String reading tests passed" << endl ;
/* value reading */
long n;
n = ini.getl("first", "val", -1 );
assert(n==1);
n = ini.getl("second", "val", -1);
assert(n==2);
n = ini.getl("first", "dummy", -1);
assert(n==-1);
cout << "2. Value reading tests passed" << endl ;
/* string writing */
bool b;
b = ini.put("first", "alt", "flagged as \"correct\"");
assert(b);
s = ini.gets("first", "alt", "aap");
assert(s=="flagged as \"correct\"");
b = ini.put("second", "alt", "correct");
assert(b);
s = ini.gets("second", "alt", "aap");
assert(s=="correct");
b = ini.put("third", "alt", "correct");
assert(b);
s = ini.gets("third", "alt", "aap" );
assert(s=="correct");
cout << "3. String writing tests passed" << endl;
/* section/key enumeration */
cout << "4. section/key enumeration; file contents follows" << endl;
string section;
for (int is = 0; section = ini.getsection(is), section.length() > 0; is++) {
cout << " [" << section.c_str() << "]" << endl;
for (int ik = 0; s = ini.getkey(section, ik), s.length() > 0; ik++) {
cout << "\t" << s.c_str() << endl;
}
}
/* string deletion */
b = ini.del("first", "alt");
assert(b);
b = ini.del("second", "alt");
assert(b);
b = ini.del("third");
assert(b);
cout << "5. string deletion passed " << endl;
return 0;
}

View File

@@ -0,0 +1,3 @@
String=noot # trailing commment
#comment=3
Val=1

View File

@@ -0,0 +1,101 @@
/* minIni - Multi-Platform INI file parser, wxWidgets interface
*
* Copyright (c) CompuPhase, 2008-2012
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* Version: $Id: wxMinIni.h 44 2012-01-04 15:52:56Z thiadmer.riemersma@gmail.com $
*/
#ifndef WXMININI_H
#define WXMININI_H
#include <wx/wx.h>
#include "minIni.h"
class minIni
{
public:
minIni(const wxString& filename) : iniFilename(filename)
{ }
bool getbool(const wxString& Section, const wxString& Key, bool DefValue=false) const
{ return ini_getbool(Section.utf8_str(), Key.utf8_str(), int(DefValue), iniFilename.utf8_str()) != 0; }
long getl(const wxString& Section, const wxString& Key, long DefValue=0) const
{ return ini_getl(Section.utf8_str(), Key.utf8_str(), DefValue, iniFilename.utf8_str()); }
int geti(const wxString& Section, const wxString& Key, int DefValue=0) const
{ return static_cast<int>(ini_getl(Section.utf8_str(), Key.utf8_str(), (long)DefValue, iniFilename.utf8_str())); }
wxString gets(const wxString& Section, const wxString& Key, const wxString& DefValue=wxT("")) const
{
char buffer[INI_BUFFERSIZE];
ini_gets(Section.utf8_str(), Key.utf8_str(), DefValue.utf8_str(), buffer, INI_BUFFERSIZE, iniFilename.utf8_str());
wxString result = wxString::FromUTF8(buffer);
return result;
}
wxString getsection(int idx) const
{
char buffer[INI_BUFFERSIZE];
ini_getsection(idx, buffer, INI_BUFFERSIZE, iniFilename.utf8_str());
wxString result = wxString::FromUTF8(buffer);
return result;
}
wxString getkey(const wxString& Section, int idx) const
{
char buffer[INI_BUFFERSIZE];
ini_getkey(Section.utf8_str(), idx, buffer, INI_BUFFERSIZE, iniFilename.utf8_str());
wxString result = wxString::FromUTF8(buffer);
return result;
}
#if defined INI_REAL
INI_REAL getf(const wxString& Section, wxString& Key, INI_REAL DefValue=0) const
{ return ini_getf(Section.utf8_str(), Key.utf8_str(), DefValue, iniFilename.utf8_str()); }
#endif
#if ! defined INI_READONLY
bool put(const wxString& Section, const wxString& Key, long Value) const
{ return ini_putl(Section.utf8_str(), Key.utf8_str(), Value, iniFilename.utf8_str()) != 0; }
bool put(const wxString& Section, const wxString& Key, int Value) const
{ return ini_putl(Section.utf8_str(), Key.utf8_str(), (long)Value, iniFilename.utf8_str()) != 0; }
bool put(const wxString& Section, const wxString& Key, bool Value) const
{ return ini_putl(Section.utf8_str(), Key.utf8_str(), (long)Value, iniFilename.utf8_str()) != 0; }
bool put(const wxString& Section, const wxString& Key, const wxString& Value) const
{ return ini_puts(Section.utf8_str(), Key.utf8_str(), Value.utf8_str(), iniFilename.utf8_str()) != 0; }
bool put(const wxString& Section, const wxString& Key, const char* Value) const
{ return ini_puts(Section.utf8_str(), Key.utf8_str(), Value, iniFilename.utf8_str()) != 0; }
#if defined INI_REAL
bool put(const wxString& Section, const wxString& Key, INI_REAL Value) const
{ return ini_putf(Section.utf8_str(), Key.utf8_str(), Value, iniFilename.utf8_str()) != 0; }
#endif
bool del(const wxString& Section, const wxString& Key) const
{ return ini_puts(Section.utf8_str(), Key.utf8_str(), 0, iniFilename.utf8_str()) != 0; }
bool del(const wxString& Section) const
{ return ini_puts(Section.utf8_str(), 0, 0, iniFilename.utf8_str()) != 0; }
#endif
private:
wxString iniFilename;
};
#endif /* WXMININI_H */

View File

@@ -0,0 +1,21 @@
/*
* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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
#ifdef __cplusplus
extern "C"
{
#endif
#include "../dev/minIni.h"
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,13 @@
# Editor files
*.swp
*~
# Objects
*.o
*.a
*.so
# Lib
lib
release
debug

View File

@@ -0,0 +1,132 @@
#---------------------------------------------------------------------------------
.SUFFIXES:
#---------------------------------------------------------------------------------
ifeq ($(strip $(DEVKITPRO)),)
$(error "Please set DEVKITPRO in your environment. export DEVKITPRO=<path to>/devkitpro")
endif
include $(DEVKITPRO)/libnx/switch_rules
#---------------------------------------------------------------------------------
# TARGET is the name of the output
# SOURCES is a list of directories containing source code
# DATA is a list of directories containing data files
# INCLUDES is a list of directories containing header files
#---------------------------------------------------------------------------------
TARGET := $(notdir $(CURDIR))
SOURCES := src
DATA := data
INCLUDES := include
#---------------------------------------------------------------------------------
# options for code generation
#---------------------------------------------------------------------------------
ARCH := -march=armv8-a+crc+crypto -mtune=cortex-a57 -mtp=soft -fPIC -ftls-model=local-exec
CFLAGS := -g -Wall -Werror \
-ffunction-sections \
-fdata-sections \
$(ARCH) \
$(BUILD_CFLAGS)
CFLAGS += $(INCLUDE)
CXXFLAGS := $(CFLAGS) -fno-rtti -fno-exceptions
ASFLAGS := -g $(ARCH)
#---------------------------------------------------------------------------------
# list of directories containing libraries, this must be the top level containing
# include and lib
#---------------------------------------------------------------------------------
LIBDIRS := $(PORTLIBS) $(LIBNX)
#---------------------------------------------------------------------------------
# no real need to edit anything past this point unless you need to add additional
# rules for different file extensions
#---------------------------------------------------------------------------------
ifneq ($(BUILD),$(notdir $(CURDIR)))
#---------------------------------------------------------------------------------
export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \
$(foreach dir,$(DATA),$(CURDIR)/$(dir))
CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c)))
CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp)))
SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s)))
BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*)))
#---------------------------------------------------------------------------------
# use CXX for linking C++ projects, CC for standard C
#---------------------------------------------------------------------------------
ifeq ($(strip $(CPPFILES)),)
#---------------------------------------------------------------------------------
export LD := $(CC)
#---------------------------------------------------------------------------------
else
#---------------------------------------------------------------------------------
export LD := $(CXX)
#---------------------------------------------------------------------------------
endif
#---------------------------------------------------------------------------------
export OFILES_BIN := $(addsuffix .o,$(BINFILES))
export OFILES_SRC := $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o)
export OFILES := $(OFILES_BIN) $(OFILES_SRC)
export HFILES := $(addsuffix .h,$(subst .,_,$(BINFILES)))
export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \
$(foreach dir,$(LIBDIRS),-I$(dir)/include) \
-I$(CURDIR)/$(BUILD)
.PHONY: clean all lib/lib$(TARGET).a lib/lib$(TARGET)d.a
#---------------------------------------------------------------------------------
all: lib/lib$(TARGET).a lib/lib$(TARGET)d.a
lib:
@[ -d $@ ] || mkdir -p $@
release:
@[ -d $@ ] || mkdir -p $@
debug:
@[ -d $@ ] || mkdir -p $@
lib/lib$(TARGET).a : lib release $(SOURCES) $(INCLUDES)
@$(MAKE) BUILD=release OUTPUT=$(CURDIR)/$@ \
BUILD_CFLAGS="-DNDEBUG=1 -O2" \
DEPSDIR=$(CURDIR)/release \
--no-print-directory -C release \
-f $(CURDIR)/Makefile
#---------------------------------------------------------------------------------
clean:
@echo clean ...
@rm -fr release debug lib
#---------------------------------------------------------------------------------
else
DEPENDS := $(OFILES:.o=.d)
#---------------------------------------------------------------------------------
# main targets
#---------------------------------------------------------------------------------
$(OUTPUT) : $(OFILES)
$(OFILES_SRC) : $(HFILES)
#---------------------------------------------------------------------------------
%_bin.h %.bin.o : %.bin
#---------------------------------------------------------------------------------
@echo $(notdir $<)
@$(bin2o)
-include $(DEPENDS)
#---------------------------------------------------------------------------------------
endif
#---------------------------------------------------------------------------------------

View File

@@ -0,0 +1,15 @@
/*
* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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 "nxExt/apm_ext.h"
#include "nxExt/ipc_server.h"
#include "nxExt/cpp/lockable_mutex.h"

View File

@@ -0,0 +1,39 @@
/*
* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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
#ifdef __cplusplus
extern "C"
{
#endif
#include <switch.h>
Result apmExtInitialize(void);
void apmExtExit(void);
// Silently fail
Result apmExtSysRequestPerformanceMode(u32 mode);
Result apmExtSysSetCpuBoostMode(u32 mode);
Result apmExtGetPerformanceMode(u32 *out_mode);
Result apmExtGetCurrentPerformanceConfiguration(u32 *out_conf);
inline bool apmExtIsCPUBoosted(u32 conf_id) { // CPU boosted to 1785 MHz
return (conf_id == 0x92220009 || conf_id == 0x9222000A);
};
inline bool apmExtIsBoostMode(u32 conf_id) { // GPU throttled to 76.8 MHz
return (conf_id >= 0x92220009 && conf_id <= 0x9222000C);
};
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,64 @@
/*
* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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
#ifdef __cplusplus
#include <mutex>
#include <switch.h>
class LockableMutex
{
public:
LockableMutex()
{
mutexInit(&this->m);
}
virtual ~LockableMutex() {}
void Lock()
{
mutexLock(&this->m);
}
bool TryLock()
{
return mutexTryLock(&this->m);
}
void Unlock()
{
mutexUnlock(&this->m);
}
// snake_case aliases in order to implement Lockable
void lock()
{
this->Lock();
}
bool try_lock()
{
return this->TryLock();
}
void unlock()
{
this->Unlock();
}
private:
Mutex m;
};
#endif

View File

@@ -0,0 +1,64 @@
/*
* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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
#ifdef __cplusplus
extern "C"
{
#endif
#pragma once
#include <switch.h>
#define IPC_SERVER_EXT_RESPONSE_MAX_DATA_SIZE (0x100 - 0x10 - sizeof(IpcServerRawHeader))
typedef struct
{
u64 magic;
union
{
u64 cmdId;
u64 result;
};
} IpcServerRawHeader;
typedef struct
{
SmServiceName srvName;
Handle handles[MAX_WAIT_OBJECTS];
u32 max;
u32 count;
} IpcServer;
typedef struct
{
u64 cmdId;
void* ptr;
size_t size;
} IpcServerRequestData;
typedef struct
{
HipcParsedRequest hipc;
IpcServerRequestData data;
} IpcServerRequest;
typedef Result (*IpcServerRequestHandler)(void* userdata, const IpcServerRequest* r, u8* out_data, size_t* out_dataSize);
Result ipcServerInit(IpcServer* server, const char* name, u32 max_sessions);
Result ipcServerExit(IpcServer* server);
Result ipcServerProcess(IpcServer* server, IpcServerRequestHandler handler, void* userdata);
Result ipcServerParseCommand(const IpcServerRequest* r, size_t *out_datasize, void** out_data, u64* out_cmd);
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,64 @@
/*
* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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
* --------------------------------------------------------------------------
*/
#include "nxExt/apm_ext.h"
#include <stdatomic.h>
static Service g_apmSrv;
static Service g_apmSysSrv;
static atomic_size_t g_refCnt;
Result apmExtInitialize(void)
{
g_refCnt++;
if (serviceIsActive(&g_apmSrv))
return 0;
Result rc = smGetService(&g_apmSrv, "apm");
if(R_SUCCEEDED(rc))
rc = smGetService(&g_apmSysSrv, "apm:sys");
if (R_FAILED(rc))
apmExtExit();
return rc;
}
void apmExtExit(void)
{
if (--g_refCnt == 0)
{
serviceClose(&g_apmSrv);
serviceClose(&g_apmSysSrv);
}
}
Result apmExtSysSetCpuBoostMode(u32 mode)
{
return serviceDispatchIn(&g_apmSysSrv, 6, mode);
}
Result apmExtGetPerformanceMode(u32 *out_mode)
{
return serviceDispatchOut(&g_apmSrv, 1, *out_mode);
}
Result apmExtSysRequestPerformanceMode(u32 mode)
{
return serviceDispatchIn(&g_apmSysSrv, 0, mode);
}
Result apmExtGetCurrentPerformanceConfiguration(u32 *out_conf)
{
return serviceDispatchOut(&g_apmSysSrv, 7, *out_conf);
}

View File

@@ -0,0 +1,204 @@
/*
* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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
* --------------------------------------------------------------------------
*/
#include "nxExt/ipc_server.h"
#include <string.h>
Result ipcServerInit(IpcServer* server, const char* name, u32 max_sessions)
{
if(max_sessions < 1 || max_sessions > (MAX_WAIT_OBJECTS - 1))
{
return MAKERESULT(Module_Libnx, LibnxError_BadInput);
}
server->srvName = smEncodeName(name);
server->max = max_sessions + 1;
server->count = 0;
Result rc = smRegisterService(&server->handles[0], server->srvName, false, max_sessions);
if(R_SUCCEEDED(rc))
{
server->count = 1;
}
return rc;
}
Result ipcServerExit(IpcServer* server)
{
for(u32 i = 0; i < server->count; i++)
{
svcCloseHandle(server->handles[i]);
}
server->count = 0;
return smUnregisterService(server->srvName);
}
static Result _ipcServerAddSession(IpcServer* server, Handle session)
{
if(server->count >= server->max)
{
return MAKERESULT(Module_Libnx, LibnxError_OutOfMemory);
}
server->handles[server->count] = session;
server->count++;
return 0;
}
static Result _ipcServerDeleteSession(IpcServer* server, u32 index)
{
if(!index || index >= server->count)
{
return MAKERESULT(Module_Libnx, LibnxError_BadInput);
}
svcCloseHandle(server->handles[index]);
for(u32 j = index; j < (server->count - 1); j++)
{
server->handles[j] = server->handles[j + 1];
}
server->count--;
return 0;
}
static Result _ipcServerParseRequest(IpcServerRequest* r)
{
u8* base = armGetTls();
r->hipc = hipcParseRequest(base);
r->data.cmdId = 0;
r->data.size = 0;
r->data.ptr = NULL;
if(r->hipc.meta.type == CmifCommandType_Request)
{
IpcServerRawHeader* header = cmifGetAlignedDataStart(r->hipc.data.data_words, base);
size_t dataSize = r->hipc.meta.num_data_words * 4;
if(!header || dataSize < sizeof(IpcServerRawHeader) || header->magic != CMIF_IN_HEADER_MAGIC)
{
return MAKERESULT(Module_Libnx, LibnxError_BadInput);
}
r->data.cmdId = header->cmdId;
if(dataSize > sizeof(IpcServerRawHeader))
{
r->data.size = dataSize - sizeof(IpcServerRawHeader);
r->data.ptr = ((u8*)header) + sizeof(IpcServerRawHeader);
}
}
return 0;
}
static void _ipcServerPrepareResponse(Result rc, void* data, size_t dataSize)
{
u8* base = armGetTls();
HipcRequest hipc = hipcMakeRequestInline(base,
.type = CmifCommandType_Request,
.num_data_words = (sizeof(IpcServerRawHeader) + dataSize + 0x10) / 4,
);
IpcServerRawHeader* rawHeader = cmifGetAlignedDataStart(hipc.data_words, base);
rawHeader->magic = CMIF_OUT_HEADER_MAGIC;
rawHeader->result = rc;
if(R_SUCCEEDED(rc))
{
memcpy(((u8*)rawHeader) + sizeof(IpcServerRawHeader), data, dataSize);
}
}
static Result _ipcServerProcessNewSession(IpcServer* server)
{
Handle session;
Result rc = svcAcceptSession(&session, server->handles[0]);
if(R_SUCCEEDED(rc) && R_FAILED(rc = _ipcServerAddSession(server, session)))
{
svcCloseHandle(session);
}
return rc;
}
static Result _ipcServerProcessSession(IpcServer* server, IpcServerRequestHandler handler, void* userdata, u32 handleIndex)
{
s32 unusedIndex;
IpcServerRequest r;
size_t dataSize = 0;
u8 data[IPC_SERVER_EXT_RESPONSE_MAX_DATA_SIZE];
bool close = false;
Result rc = svcReplyAndReceive(&unusedIndex, &server->handles[handleIndex], 1, 0, UINT64_MAX);
if(R_SUCCEEDED(rc))
{
rc = _ipcServerParseRequest(&r);
}
if(R_SUCCEEDED(rc))
{
switch(r.hipc.meta.type)
{
case CmifCommandType_Request:
_ipcServerPrepareResponse(
handler(userdata, &r, data, &dataSize),
data,
dataSize
);
break;
case CmifCommandType_Close:
_ipcServerPrepareResponse(0, NULL, 0);
close = true;
break;
default:
_ipcServerPrepareResponse(MAKERESULT(11, 403), NULL, 0);
break;
}
rc = svcReplyAndReceive(&unusedIndex, &server->handles[handleIndex], 0, server->handles[handleIndex], 0);
if(rc == KERNELRESULT(TimedOut))
{
rc = 0;
}
}
if(R_FAILED(rc) || close)
{
_ipcServerDeleteSession(server, handleIndex);
}
return rc;
}
Result ipcServerProcess(IpcServer* server, IpcServerRequestHandler handler, void* userdata)
{
s32 handleIndex = -1;
Result rc = svcWaitSynchronization(&handleIndex, server->handles, server->count, UINT64_MAX);
if(R_SUCCEEDED(rc) && (handleIndex < 0 || handleIndex >= server->count))
{
rc = MAKERESULT(Module_Libnx, LibnxError_NotFound);
}
if(R_SUCCEEDED(rc))
{
if(handleIndex)
{
rc = _ipcServerProcessSession(server, handler, userdata, handleIndex);
}
else
{
rc = _ipcServerProcessNewSession(server);
}
}
return rc;
}

View File

@@ -0,0 +1,103 @@
{
"name": "sysclkOC",
"title_id": "0x00FF0000636C6BFF",
"title_id_range_min": "0x00FF0000636C6BFF",
"title_id_range_max": "0x00FF0000636C6BFF",
"main_thread_stack_size": "0x00004000",
"main_thread_priority": 49,
"default_cpu_id": 3,
"process_category": 0,
"is_retail": true,
"pool_partition": 2,
"is_64_bit": true,
"address_space_type": 3,
"filesystem_access": {
"permissions": "0xFFFFFFFFFFFFFFFF"
},
"service_access": [
"*"
],
"service_host": [
"sysclkOC"
],
"kernel_capabilities": [
{
"type": "kernel_flags",
"value": {
"highest_thread_priority": 63,
"lowest_thread_priority": 24,
"lowest_cpu_id": 0,
"highest_cpu_id": 3
}
},
{
"type": "syscalls",
"value": {
"svcSetHeapSize": "0x01",
"svcSetMemoryPermission": "0x02",
"svcSetMemoryAttribute": "0x03",
"svcMapMemory": "0x04",
"svcUnmapMemory": "0x05",
"svcQueryMemory": "0x06",
"svcExitProcess": "0x07",
"svcCreateThread": "0x08",
"svcStartThread": "0x09",
"svcExitThread": "0x0a",
"svcSleepThread": "0x0b",
"svcGetThreadPriority": "0x0c",
"svcSetThreadPriority": "0x0d",
"svcGetThreadCoreMask": "0x0e",
"svcSetThreadCoreMask": "0x0f",
"svcGetCurrentProcessorNumber": "0x10",
"svcSignalEvent": "0x11",
"svcClearEvent": "0x12",
"svcMapSharedMemory": "0x13",
"svcUnmapSharedMemory": "0x14",
"svcCreateTransferMemory": "0x15",
"svcCloseHandle": "0x16",
"svcResetSignal": "0x17",
"svcWaitSynchronization": "0x18",
"svcCancelSynchronization": "0x19",
"svcArbitrateLock": "0x1a",
"svcArbitrateUnlock": "0x1b",
"svcWaitProcessWideKeyAtomic": "0x1c",
"svcSignalProcessWideKey": "0x1d",
"svcGetSystemTick": "0x1e",
"svcConnectToNamedPort": "0x1f",
"svcSendSyncRequestLight": "0x20",
"svcSendSyncRequest": "0x21",
"svcSendSyncRequestWithUserBuffer": "0x22",
"svcSendAsyncRequestWithUserBuffer": "0x23",
"svcGetProcessId": "0x24",
"svcGetThreadId": "0x25",
"svcBreak": "0x26",
"svcOutputDebugString": "0x27",
"svcReturnFromException": "0x28",
"svcGetInfo": "0x29",
"svcSetThreadActivity": "0x32",
"svcWaitForAddress": "0x34",
"svcSignalToAddress": "0x35",
"svcCreateSession": "0x40",
"svcAcceptSession": "0x41",
"svcReplyAndReceiveLight": "0x42",
"svcReplyAndReceive": "0x43",
"svcReplyAndReceiveWithUserBuffer": "0x44",
"svcCreateEvent": "0x45",
"svcCreateInterruptEvent": "0x53",
"svcReadWriteRegister": "0x4E",
"svcQueryIoMapping": "0x55",
"svcCreateDeviceAddressSpace": "0x56",
"svcAttachDeviceAddressSpace": "0x57",
"svcDetachDeviceAddressSpace": "0x58",
"svcMapDeviceAddressSpaceAligned": "0x5a",
"svcUnmapDeviceAddressSpace": "0x5c",
"svcGetSystemInfo": "0x6f",
"svcCallSecureMonitor": "0x7f"
}
},
{
"type": "min_kernel_version",
"value": "0x0060"
}
]
}

View File

@@ -0,0 +1,384 @@
/*
* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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
* --------------------------------------------------------------------------
*/
#include <nxExt.h>
#include "errors.h"
#include "clock_manager.h"
#include "file_utils.h"
#include "clocks.h"
#include "process_management.h"
#include <cstring>
ClockManager* ClockManager::instance = NULL;
ClockManager* ClockManager::GetInstance()
{
return instance;
}
void ClockManager::Exit()
{
if(instance)
{
delete instance;
}
}
void ClockManager::Initialize()
{
if(!instance)
{
instance = new ClockManager();
}
}
ClockManager::ClockManager()
{
this->config = Config::CreateDefault();
this->context = new SysClkContext;
this->context->applicationId = 0;
this->context->profile = SysClkProfile_Handheld;
this->context->enabled = false;
for(unsigned int i = 0; i < SysClkModule_EnumMax; i++)
{
this->context->freqs[i] = 0;
this->context->overrideFreqs[i] = 0;
}
this->context->perfConfId = 0;
this->running = false;
this->lastTempLogNs = 0;
this->lastCsvWriteNs = 0;
this->oc = new SysClkOcExtra;
this->oc->systemCoreBoostCPU = false;
this->oc->batteryChargingDisabledOverride = false;
this->oc->realProfile = SysClkProfile_Handheld;
this->rnxSync = new ReverseNXSync;
this->governor = new Governor();
}
ClockManager::~ClockManager()
{
delete this->governor;
delete this->rnxSync;
delete this->oc;
delete this->context;
delete this->config;
}
void ClockManager::SetRunning(bool running)
{
this->running = running;
}
bool ClockManager::Running()
{
return this->running;
}
uint32_t ClockManager::GetHz(SysClkModule module)
{
/* Temp override setting */
uint32_t hz = this->context->overrideFreqs[module];
/* Per-Game setting */
if (!hz)
hz = this->config->GetAutoClockHz(this->context->applicationId, module, this->context->profile);
/* Global profile */
if (!hz)
hz = this->config->GetAutoClockHz(SYSCLK_GLOBAL_PROFILE_TID, module, this->context->profile);
/* Return pre-set hz */
ReverseNXMode mode;
if (!hz && (mode = this->rnxSync->GetMode()))
{
switch (module)
{
case SysClkModule_CPU:
hz = 1020'000'000;
break;
case SysClkModule_GPU:
hz = (mode == ReverseNX_Docked ||
this->oc->realProfile == SysClkProfile_Docked) ?
768'000'000 : 460'800'000;
break;
case SysClkModule_MEM:
hz = MEM_CLOCK_DOCK;
break;
default:
break;
}
}
if (hz)
{
/* Considering realProfile frequency limit */
hz = Clocks::GetNearestHz(module, this->oc->realProfile, hz);
}
/* Handle CPU Auto Boost, no user-defined hz required */
if (module == SysClkModule_CPU)
{
if (this->oc->systemCoreBoostCPU && hz < Clocks::boostCpuFreq)
return Clocks::boostCpuFreq;
if (!hz)
/* Trigger RefreshContext() and Tick(), resetting default CPU frequency */
return 1020'000'000;
}
return hz;
}
void ClockManager::Tick()
{
std::scoped_lock lock{this->contextMutex};
if (this->RefreshContext() && this->context->enabled)
{
for (unsigned int module = 0; module < SysClkModule_EnumMax; module++)
{
uint32_t hz = GetHz((SysClkModule)module);
if (module == SysClkModule_CPU) {
this->governor->SetMinHz(*Clocks::freqRange[module].first, SysClkModule_CPU);
if (Clocks::GetIsMariko() && hz > (uint32_t)1020'000'000) {
this->governor->SetMinHz(1020'000'000, SysClkModule_CPU);
}
}
this->governor->SetMaxHz(hz, (SysClkModule)module);
if (hz && hz != this->context->freqs[module] && !this->governor->IsHandledByGovernor((SysClkModule)module))
{
// Skip setting CPU or GPU clocks in CpuBoostMode if CPU <= boostCPUFreq or GPU >= 76.8MHz
bool skipBoost = apmExtIsBoostMode(this->context->perfConfId) &&
((module == SysClkModule_CPU && hz <= Clocks::boostCpuFreq) || module == SysClkModule_GPU);
if (!skipBoost) {
FileUtils::LogLine("[mgr] %s clock set : %u.%u MHz", Clocks::GetModuleName((SysClkModule)module, true), hz/1000000, hz/100000 - hz/1000000*10);
Clocks::SetHz((SysClkModule)module, hz);
uint32_t hz_now = Clocks::GetCurrentHz((SysClkModule)module);
if (hz != hz_now)
FileUtils::LogLine("[mgr] Cannot set %s clock to %u.%u MHz", Clocks::GetModuleName((SysClkModule)module, true), hz/1000000, hz/100000 - hz/1000000*10);
this->context->freqs[module] = hz_now;
}
}
}
}
}
void ClockManager::WaitForNextTick()
{
/* Self-check system core (#3) usage via idleticks at intervals (Not enabled at higher CPU freq or without charger) */
uint64_t tickWaitTimeMs = this->GetConfig()->GetConfigValue(SysClkConfigValue_PollingIntervalMs);
if (this->governor->IsHandledByGovernor(SysClkModule_CPU)) {
svcSleepThread(tickWaitTimeMs * 1000'000ULL);
return;
}
bool boostOK =
this->GetConfig()->GetConfigValue(SysClkConfigValue_AutoCPUBoost) &&
this->context->enabled &&
this->oc->realProfile != SysClkProfile_Handheld &&
this->context->freqs[SysClkModule_CPU] <= Clocks::boostCpuFreq;
if (boostOK) {
uint32_t core3Util = CpuCoreUtil(3, tickWaitTimeMs * 1000'000ULL).Get();
bool lastBoost = this->oc->systemCoreBoostCPU;
this->oc->systemCoreBoostCPU = (core3Util >= BOOST_THRESHOLD);
if (lastBoost && !this->oc->systemCoreBoostCPU)
Clocks::SetHz(SysClkModule_CPU, GetHz(SysClkModule_CPU));
if (!lastBoost && this->oc->systemCoreBoostCPU)
Clocks::SetHz(SysClkModule_CPU, Clocks::boostCpuFreq);
return;
}
if (this->oc->systemCoreBoostCPU) {
this->oc->systemCoreBoostCPU = false;
Clocks::SetHz(SysClkModule_CPU, GetHz(SysClkModule_CPU));
}
svcSleepThread(tickWaitTimeMs * 1000'000ULL);
}
bool ClockManager::RefreshContext()
{
PsmExt::ChargingHandler(this->GetInstance());
bool hasChanged = false;
SysClkProfile realProfile = Clocks::GetCurrentProfile();
if (realProfile != this->oc->realProfile)
{
FileUtils::LogLine("[mgr] Profile change: %s", Clocks::GetProfileName(realProfile, true));
this->oc->realProfile = realProfile;
// Signal that power state has been changed, reset the override
this->SetBatteryChargingDisabledOverride(false);
hasChanged = true;
}
hasChanged = this->config->Refresh();
if (hasChanged) {
this->rnxSync->ToggleSync(this->GetConfig()->GetConfigValue(SysClkConfigValue_SyncReverseNXMode));
bool allowUnsafe = this->GetConfig()->GetConfigValue(SysClkConfigValue_AllowUnsafeFrequencies);
Clocks::SetAllowUnsafe(allowUnsafe);
this->governor->SetAutoCPUBoost(this->GetConfig()->GetConfigValue(SysClkConfigValue_AutoCPUBoost));
this->governor->SetCPUBoostHz(Clocks::GetNearestHz(SysClkModule_CPU, this->oc->realProfile, Clocks::boostCpuFreq));
}
bool enabled = this->GetConfig()->Enabled();
if(enabled != this->context->enabled)
{
this->context->enabled = enabled;
FileUtils::LogLine("[mgr] " TARGET " status: %s", enabled ? "enabled" : "disabled");
hasChanged = true;
}
std::uint64_t applicationId = ProcessManagement::GetCurrentApplicationId();
if (applicationId != this->context->applicationId)
{
FileUtils::LogLine("[mgr] TitleID change: %016lX", applicationId);
this->context->applicationId = applicationId;
hasChanged = true;
/* Clear ReverseNX state */
this->rnxSync->Reset(applicationId);
}
SysClkOcGovernorConfig governorConfig = SysClkOcGovernorConfig_AllDisabled;
if (this->GetConfig()->GetConfigValue(SysClkConfigValue_GovernorExperimental)) {
auto governorHandheldOnly = this->GetConfig()->GetConfigValue(SysClkConfigValue_GovernorHandheldOnly);
governorConfig = SysClkOcGovernorConfig_Default;
SysClkOcGovernorConfig governorConfigTitle = this->GetConfig()->GetTitleGovernorConfig(applicationId);
if (governorConfig != governorConfigTitle)
governorConfig = governorConfigTitle;
// Set governor config to disabled if Handheld Only is true
if (governorHandheldOnly && (realProfile != SysClkProfile_Handheld))
governorConfig = SysClkOcGovernorConfig_AllDisabled;
}
this->governor->SetConfig(governorConfig);
/* Update PerformanceConfigurationId */
{
uint32_t confId = 0;
Result rc = 0;
rc = apmExtGetCurrentPerformanceConfiguration(&confId);
ASSERT_RESULT_OK(rc, "apmExtGetCurrentPerformanceConfiguration");
if (this->context->perfConfId != confId)
{
this->context->perfConfId = confId;
this->governor->SetPerfConf(confId);
hasChanged = true;
}
}
{
SysClkProfile current = this->context->profile;
SysClkProfile expected = this->rnxSync->GetProfile(this->oc->realProfile);
this->context->profile = expected;
if (current != expected)
hasChanged = true;
}
// let ptm module handle boost clocks rather than resetting
if (hasChanged && !apmExtIsBoostMode(this->context->perfConfId)) {
Clocks::ResetToStock();
}
std::uint32_t hz = 0;
for (unsigned int module = 0; module < SysClkModule_EnumMax; module++)
{
hz = Clocks::GetCurrentHz((SysClkModule)module);
if (hz != 0 && hz != this->context->freqs[module])
{
this->context->freqs[module] = hz;
if (!this->governor->IsHandledByGovernor((SysClkModule)module)) {
FileUtils::LogLine("[mgr] %s clock change: %u.%u MHz", Clocks::GetModuleName((SysClkModule)module, true), hz/1000000, hz/100000 - hz/1000000*10);
hasChanged = true;
}
}
hz = this->GetConfig()->GetOverrideHz((SysClkModule)module);
if (hz != this->context->overrideFreqs[module])
{
if(hz)
{
FileUtils::LogLine("[mgr] %s override change: %u.%u MHz", Clocks::GetModuleName((SysClkModule)module, true), hz/1000000, hz/100000 - hz/1000000*10);
}
else
{
FileUtils::LogLine("[mgr] %s override disabled", Clocks::GetModuleName((SysClkModule)module, true));
Clocks::ResetToStock(module);
}
this->context->overrideFreqs[module] = hz;
hasChanged = true;
}
}
// temperatures do not and should not force a refresh, hasChanged untouched
std::uint32_t millis = 0;
std::uint64_t ns = armTicksToNs(armGetSystemTick());
std::uint64_t tempLogInterval = this->GetConfig()->GetConfigValue(SysClkConfigValue_TempLogIntervalMs) * 1000000ULL;
bool shouldLogTemp = tempLogInterval && ((ns - this->lastTempLogNs) > tempLogInterval);
for (unsigned int sensor = 0; sensor < SysClkThermalSensor_EnumMax; sensor++)
{
millis = Clocks::GetTemperatureMilli((SysClkThermalSensor)sensor);
if(shouldLogTemp)
{
FileUtils::LogLine("[mgr] %s temp: %u.%u °C", Clocks::GetThermalSensorName((SysClkThermalSensor)sensor, true), millis/1000, (millis - millis/1000*1000) / 100);
}
this->context->temps[sensor] = millis;
}
if(shouldLogTemp)
{
this->lastTempLogNs = ns;
}
std::uint64_t csvWriteInterval = this->GetConfig()->GetConfigValue(SysClkConfigValue_CsvWriteIntervalMs) * 1000000ULL;
if(csvWriteInterval && ((ns - this->lastCsvWriteNs) > csvWriteInterval))
{
FileUtils::WriteContextToCsv(this->context);
this->lastCsvWriteNs = ns;
}
return hasChanged;
}
void ClockManager::SetRNXRTMode(ReverseNXMode mode) {
this->rnxSync->SetRTMode(mode);
}
SysClkContext ClockManager::GetCurrentContext()
{
std::scoped_lock lock{this->contextMutex};
return *this->context;
}
Config* ClockManager::GetConfig()
{
return this->config;
}
bool ClockManager::GetBatteryChargingDisabledOverride() {
return this->oc->batteryChargingDisabledOverride;
}
Result ClockManager::SetBatteryChargingDisabledOverride(bool toggle_true) {
this->oc->batteryChargingDisabledOverride = toggle_true;
return 0;
}

View File

@@ -0,0 +1,61 @@
/*
* --------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <p-sam@d3vs.net>, <natinusala@gmail.com>, <m4x@m4xw.net>
* 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 <atomic>
#include <sysclk.h>
#include "config.h"
#include "clocks.h"
#include <nxExt/cpp/lockable_mutex.h>
#include "oc_extra.h"
// Forward declaration
class ReverseNXSync;
class Governor;
class ClockManager
{
public:
static ClockManager* GetInstance();
static void Initialize();
static void Exit();
void SetRunning(bool running);
bool Running();
void Tick();
void WaitForNextTick();
void SetRNXRTMode(ReverseNXMode mode);
SysClkContext GetCurrentContext();
Config* GetConfig();
bool GetBatteryChargingDisabledOverride();
Result SetBatteryChargingDisabledOverride(bool toggle_true);
protected:
ClockManager();
virtual ~ClockManager();
bool RefreshContext();
uint32_t GetHz(SysClkModule);
static ClockManager *instance;
std::atomic_bool running;
LockableMutex contextMutex;
Config *config;
SysClkContext *context;
std::uint64_t lastTempLogNs;
std::uint64_t lastCsvWriteNs;
SysClkOcExtra *oc;
ReverseNXSync *rnxSync;
Governor *governor;
};

Some files were not shown because too many files have changed in this diff Show More