/*
 * Copyright 2022 MindMotion Microelectronics Co., Ltd.
 * All rights reserved.
 *
 * SPDX-License-Identifier: BSD-3-Clause
 */


#include "board_init.h"

/*
* Definitions.
*/

/*
* Declerations.
*/
void BOARD_InitExternalFlash(void);

/*
* Functions.
*/
void BOARD_Init(void)
{
    BOARD_InitBootClocks();
    BOARD_InitPins();
}

void BOARD_InitExternalFlash(void)
{
    /* init qspi hardware. */
    QSPI_Init_Type qspi_init;
    qspi_init.SckDiv            = BOARD_QSPI_SCK_DIV;
    qspi_init.CsHighLevelCycles = BOARD_QSPI_CS_HIGH_LEVEL_TIME;
    qspi_init.RxSampleDelay     = BOARD_QSPI_RX_DELAY_CYCLES;
    qspi_init.SpiMode           = QSPI_SpiMode_3; /* suggest using SPI Mode 3. */
    /* init qspi. */
    QSPI_Init(QSPI, &qspi_init);

    /* enable qspi direct read mode. */
    QSPI_DirectXferConf_Type direct_conf;
    direct_conf.CmdBusWidth   = BOARD_EXT_FLASH_CMD_BUS_WIDTH;
    direct_conf.CmdValue      = BOARD_EXT_FLASH_CMD_VALUE;
    direct_conf.AddrBusWidth  = BOARD_EXT_FLASH_ADDR_BUS_WIDTH;
    direct_conf.AddrWordWidth = BOARD_EXT_FLASH_ADDR_WORD_WIDTH;
    direct_conf.AltBusWidth   = QSPI_BusWidth_None;
    direct_conf.DummyCycles   = BOARD_EXT_FLASH_DUMMY_CYCLES;
    direct_conf.DataBusWidth  = BOARD_EXT_FLASH_DATA_BUS_WIDTH;

    QSPI_EnableDirectRead(QSPI, &direct_conf);
}

/* jump 2 app. */
uint32_t * vtor;
void jump_to_app(uint32_t app_base)
{
    vtor = (uint32_t *)app_base;
    
    __disable_irq();
    SCB->VTOR = app_base;
    
    __ISB();
    __DSB();

    __set_MSP(vtor[0]);
    __set_PSP(vtor[0]);

    __enable_irq();
    ((void(*)(void))vtor[1])();
}

/* EOF. */
