Skip to content

Commit

Permalink
at32: re-program sram config during boot
Browse files Browse the repository at this point in the history
  • Loading branch information
bkleiner committed Jul 3, 2023
1 parent 3f91a23 commit 31135db
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions src/driver/at32/reset.c
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

#define BKP_INDEX ERTC_DT4
#define BOOTLOADER_OFFSET 0x1FFF0000
#define SRAM_CONFIG FLASH_EOPB0_SRAM_384K

static void backup_register_write(uint32_t val) {
crm_periph_clock_enable(CRM_PWC_PERIPH_CLOCK, TRUE);
Expand All @@ -20,7 +21,46 @@ void system_reset_to_bootloader() {
system_reset();
}

static inline void wait_for_flash() {
while (FLASH->sts_bit.obf != RESET)
;
}

static inline void write_eopb0_config(flash_usd_eopb0_type data) {
// unlock all the flash
FLASH->unlock = FLASH_UNLOCK_KEY1;
FLASH->unlock = FLASH_UNLOCK_KEY2;
FLASH->unlock2 = FLASH_UNLOCK_KEY1;
FLASH->unlock2 = FLASH_UNLOCK_KEY2;

// unlock user bytes
FLASH->usd_unlock = FLASH_UNLOCK_KEY1;
FLASH->usd_unlock = FLASH_UNLOCK_KEY2;

// wait for unlock success
while (FLASH->ctrl_bit.usdulks == RESET)
;

// erase user flash
FLASH->ctrl_bit.usders = TRUE;
FLASH->ctrl_bit.erstr = TRUE;
wait_for_flash();
FLASH->ctrl_bit.usders = FALSE;

// re-program FAP and set EOPB0
FLASH->ctrl_bit.usdprgm = TRUE;
USD->fap = (uint16_t)FAP_RELIEVE_KEY;
USD->eopb0 = (uint16_t)data;
wait_for_flash();
FLASH->ctrl_bit.usdprgm = FALSE;
}

__attribute__((__used__)) void system_check_for_bootloader() {
if (((USD->eopb0) & 0x07) != SRAM_CONFIG) {
write_eopb0_config(SRAM_CONFIG);
system_reset();
}

const uint32_t magic = ertc_bpr_data_read(BKP_INDEX);

switch (magic) {
Expand Down

0 comments on commit 31135db

Please sign in to comment.