From 4e1d1ea4a32210ee2a91ee6f5ac40878616ebbae Mon Sep 17 00:00:00 2001 From: R Date: Sat, 13 Apr 2024 23:56:36 +0100 Subject: [PATCH] more reliable but still wtf --- bootloader.c | 18 +++++++++++++----- startup.S | 4 +++- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/bootloader.c b/bootloader.c index 4314dcb..5e03ef3 100644 --- a/bootloader.c +++ b/bootloader.c @@ -196,6 +196,10 @@ const uint8_t ROOT_DIR[32 * 3] __attribute__((aligned(2))) = { #define R32_EXTEN_CTR (*(volatile uint32_t*)0x40023800) +#define STK_CTLR (*(volatile uint32_t*)0xE000F000) +#define STK_SR (*(volatile uint32_t*)0xE000F004) +#define STK_CMPLR (*(volatile uint32_t*)0xE000F010) + #define PFIC_CFGR (*(volatile uint32_t*)0xE000E048) // state[7:0] = addr @@ -286,9 +290,8 @@ __attribute__((always_inline)) static inline void synthesize_block(uint32_t bloc } __attribute__((naked)) int main(void) { - // clear all reset causes + // Don't reenter bootloader again R16_BKP_DATAR10 = 0; - R32_RCC_RSTSCKR = 1 << 24; // PLL setup: system clock 96 MHz R32_EXTEN_CTR |= (1 << 4); // sneaky div2 @@ -810,11 +813,16 @@ error_csw: break; case STATE_SENT_CSW_REBOOT: // todo reboot into ram - for (int i = 0; i < 1000000; i++) - asm volatile(""); + STK_CMPLR = (50 /* ms */ * 12000 /* assume 96 MHz system clock, div8 */); + STK_CTLR = 0b111000; + STK_CTLR = 0b111001; + while (!(STK_SR & 1)) {} + STK_CTLR = 0; + STK_SR = 0; R16_USBD_CNTR = 0b11; R32_EXTEN_CTR &= ~(1 << 1); - asm volatile("csrw mepc, zero\n"); + // wtf why does this work and the other stuff doesn't? + R16_BKP_DATAR10 = 0x4170; PFIC_CFGR = 0xbeef0080; while (1) { asm volatile(""); } break; diff --git a/startup.S b/startup.S index 0eb6ef1..58ad2aa 100644 --- a/startup.S +++ b/startup.S @@ -45,7 +45,7 @@ _start: la a3, R16_BKP_DATAR10 lhu a1, (a3) la a2, BOOT_MAGIC_APP_IMMEDIATELY - beq a1, a2, _enter_application_code + beq a1, a2, _enter_application_code_magic la a2, BOOT_MAGIC_BOOTLOADER beq a1, a2, _enter_bootloader @@ -69,6 +69,8 @@ _start: sh zero, (a3) // If the delay expires, boot the application after all +_enter_application_code_magic: + sh zero, (a3) _enter_application_code: // Clear all of these enables that we had set la a0, R32_PWR_CTLR