/* Copyright Statement:
 *
 * This software/firmware and related documentation ("AutoChips Software") are
 * protected under relevant copyright laws. The information contained herein is
 * confidential and proprietary to AutoChips Inc. and/or its licensors. Without
 * the prior written permission of AutoChips inc. and/or its licensors, any
 * reproduction, modification, use or disclosure of AutoChips Software, and
 * information contained herein, in whole or in part, shall be strictly
 * prohibited.
 *
 * AutoChips Inc. (C) 2024. All rights reserved.
 *
 * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
 * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("AUTOCHIPS SOFTWARE")
 * RECEIVED FROM AUTOCHIPS AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER
 * ON AN "AS-IS" BASIS ONLY. AUTOCHIPS EXPRESSLY DISCLAIMS ANY AND ALL
 * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
 * NONINFRINGEMENT. NEITHER DOES AUTOCHIPS PROVIDE ANY WARRANTY WHATSOEVER WITH
 * RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY,
 * INCORPORATED IN, OR SUPPLIED WITH THE AUTOCHIPS SOFTWARE, AND RECEIVER AGREES
 * TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO.
 * RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO
 * OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN AUTOCHIPS
 * SOFTWARE. AUTOCHIPS SHALL ALSO NOT BE RESPONSIBLE FOR ANY AUTOCHIPS SOFTWARE
 * RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
 * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND AUTOCHIPS'S
 * ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE AUTOCHIPS SOFTWARE
 * RELEASED HEREUNDER WILL BE, AT AUTOCHIPS'S OPTION, TO REVISE OR REPLACE THE
 * AUTOCHIPS SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE
 * CHARGE PAID BY RECEIVER TO AUTOCHIPS FOR SUCH AUTOCHIPS SOFTWARE AT ISSUE.
 */
/******************************************************************************
 * @version: V3.1.0  AC7840x  Demo
 ******************************************************************************/

#include "osif.h"
#include "clock_config.h"
#include "debugout_ac7840x.h"
#include "cse_functions.h"
#include "flash.h"
#include "cse_keys.h"

/*!
 *例程说明：
 *AC7840x CSE模块例程:
 *计算Boot的MAC ，使能顺序引导模式
 */

/*! 秘钥属性说明
 * bit5 Write Protection enable: 1 disable: 0
 * bit4 Boot Protection  enable: 1 disable: 0
 * bit3 Debugger Protection enable:1 disable:0
 * bit2 Key Usage enable:1 generate & verify cmac  disable: 0 encryption and decryption
 * bit1 Wildcard enable:1 disable:0
 * bit0 Verify Only enable:1  disable:0
*/
#define CSE_ATTRIBUTE_WP_Msk            0x20
#define CSE_ATTRIBUTE_WP_Pos            5
#define CSE_ATTRIBUTE_BP_Msk            0x10
#define CSE_ATTRIBUTE_BP_Pos            4
#define CSE_ATTRIBUTE_DP_Msk            0x8
#define CSE_ATTRIBUTE_DP_Pos            3
#define CSE_ATTRIBUTE_KEYUSER_Msk       0x4
#define CSE_ATTRIBUTE_KEYUSER_Pos       2
#define CSE_ATTRIBUTE_Wildcard_Msk      0x2
#define CSE_ATTRIBUTE_Wildcard_Pos      1
#define CSE_ATTRIBUTE_VerifyOnly_Msk    0x1
#define CSE_ATTRIBUTE_VerifyOnly_Pos    0

#define     BOOT_START_ADD      0x00000000
#define     BOOT_SIZE           0x00010000

#define     APP_START_ADD       0x00010000

#define     BOOT_SIZE_1K_BYTE   8*1024  /*1K bytes */

typedef void (*Func)(void);
Func Jump_To_App;


flash_config_t  flash_Config = {0};
uint8_t         M1[16] = {0};
uint8_t         M2[32] = {0};
uint8_t         M3[16] = {0};
uint8_t         M4[32] = {0};
uint8_t         M5[16] = {0};
uint8_t         M4_out[32]= {0};
uint8_t         M5_out[16]= {0};

uint8_t rnd[16] = {0};
cse_state_t cse_State;

/*!
 * @brief 时钟配置函数
 *
 * @param[in] none
 *
 * @return none
 */
static void SystemClock_Config(void);

/*!
 * @brief BOOT 跳转 APP
 *
 * @param[in] none
 *
 * @return none
 */
static void Go_To_App(void);

/*!
 * @brief main
 *
 * @param[in]  none
 *
 * @return 0: success, other: error value
 */
int main(void)
{
    /*
    CSE_BOOT_STRICT         严格引导模式
    CSE_BOOT_SERIAL         顺序引导模式
    CSE_BOOT_PARALLEL       并行引导模式
    CSE_BOOT_NOT_DEFINED
    */
    cse_boot_flavor_t User_boot_flavor = CSE_BOOT_SERIAL;   /* 顺序引导模式 */
    uint32_t *flash_pointer = (uint32_t *)(0x00000000);
    uint32_t Boot_Size_Bit = BOOT_SIZE_1K_BYTE * 64;
    uint8_t  Boot_MAC[16] = {0u};
    status_t Res;

    SystemClock_Config();

    InitDebug();

    printf("demo start...\r\n");

    printf("BOOT\r\n");

    FLASH_DRV_Init(&Flash1_InitConfig, &flash_Config);

    if (flash_Config.flexRAMSize == 0)
    {
        FLASH_DRV_UnlockCtrl();
        Res = FLASH_DRV_Partition(&flash_Config, 0x00, 0x03, true);
        printf("FLASH_DRV_Partition,Res = 0x%x \r\n", Res);
        OSIF_TimeDelay(5);
        NVIC_SystemReset();
    }

    /* Initialize CSE driver */
    CSE_DRV_Init(&cse_State);

    /*initialize RNG*/
    Res = CSE_DRV_InitRNG();
    printf("CSE_DRV_InitRNG,Res = 0x%x \r\n", Res);

    /*load CSE_MASTER_ECU*/
    Res = CalculateM1ToM5(BLANK_KEY, MASTER_ECU_KEY, CSE_MASTER_ECU, CSE_MASTER_ECU, 1u, 0u, M1, M2, M3, M4, M5); /* Calculate M1 to M5 in Software */
    printf("CalculateM1ToM5,Res = 0x%x \r\n", Res);

    Res = CSE_DRV_LoadKey(CSE_MASTER_ECU, M1, M2, M3, M4_out, M5_out);
    printf("CSE_DRV_LoadKey,Res = 0x%x \r\n", Res);

    /* Step-1 Program the code/program flash with the code to be protected. */

    /* Step-2 Program BOOT_MAC_KEY into secure flash */
    Res = CalculateM1ToM5(MASTER_ECU_KEY, BOOT_MAC_KEY, CSE_MASTER_ECU, CSE_BOOT_MAC_KEY, 1u, 0x0u, M1, M2, M3, M4, M5); /* Calculate M1 to M5 in Software */
    printf("CalculateM1ToM5,Res = 0x%x \r\n", Res);
    Res = CSE_DRV_LoadKey(CSE_BOOT_MAC_KEY, M1, M2, M3, M4_out, M5_out);
    printf("CSE_DRV_LoadKey,Res = 0x%x \r\n", Res);

    /* Step-3 Define the secure boot flavor and the BOOT_SIZE*/
    if (false == CSE_IsSecureBootEnabled())
    {
        Res = CSE_DRV_BootDefine(Boot_Size_Bit, User_boot_flavor);      /* 严格的顺序安全引导模式 */
        printf("CSE_DRV_BootDefine,Res = 0x%x \r\n", Res);

        /* Step-4 Calculate the CMAC using RAM_KEY feature of the CSEc */
        if (0 == Res)
        {
            /*Load BOOT_MAC_KEY into RAM_KEY slot*/
            Res = CSE_DRV_LoadPlainKey(BOOT_MAC_KEY);
            printf("CSE_DRV_LoadPlainKey,Res = 0x%x \r\n", Res);

            Res = CSE_DRV_GenerateMACAddrMode(CSE_RAM_KEY, (uint8_t *)flash_pointer, Boot_Size_Bit, Boot_MAC);
            printf("CSE_DRV_GenerateMACAddrMode,Res = 0x%x \r\n", Res);

            /* Calculate M1 to M5 in Software */ /* Wildcard protect */
            Res = CalculateM1ToM5(MASTER_ECU_KEY, Boot_MAC, CSE_MASTER_ECU, CSE_BOOT_MAC, 1u, CSE_ATTRIBUTE_Wildcard_Msk, M1, M2, M3, M4, M5);
            printf("CalculateM1ToM5,Res = 0x%x \r\n", Res);

            Res = CSE_DRV_LoadKey(CSE_BOOT_MAC, M1, M2, M3, M4_out, M5_out); /* Load the key using M1 to M3, returns M4 and M5 */
            printf("CSE_DRV_LoadKey,Res = 0x%x \r\n", Res);

            OSIF_TimeDelay(5);
            /* After the configuration is complete, secure boot reset takes effect */
            /* NVIC_SystemReset(); */
        }
    }
    else
    {
        if (false == CSE_IsSecureBootSuccessful())
        {
            Res = CSE_DRV_BootFailure();
            printf("CSE_DRV_BootFailure,Res = 0x%x \r\n", Res);
        }
        else
        {
            Res = CSE_DRV_BootOK();
            printf("CSE_DRV_BootOK,Res = 0x%x \r\n", Res);
        }

        printf("Jump to APP\r\n");

        Go_To_App();
    }

    (void)Res;
    printf("demo end...\r\n");

    while (1);
}

/*!
 * @brief BOOT 跳转 APP
 *
 * @param[in] none
 *
 * @return none
 */
static void Go_To_App(void)
{
    if (((*(__IO uint32_t *)APP_START_ADD) >= 0x1FFF0000) && ((*(__IO uint32_t *)APP_START_ADD) <= 0x2000EFFF))
    {
        DisableInterrupts;                                              /* 关全局中断 */
        Jump_To_App = (Func)(*(__IO uint32_t *)(APP_START_ADD + 4));    /* 指向APP程序的Reset中断*/
        __set_MSP(*(__IO uint32_t*)APP_START_ADD);
        Jump_To_App();
    }
    printf("Jump to APP Fault\r\n");
}

/*!
 * @brief 时钟配置函数
 *
 * @param[in] none
 *
 * @return none
 */
static void SystemClock_Config(void)
{
    CKGEN_SYS_Init(g_clockManConfigsArr, CLOCK_MANAGER_CONFIG_CNT,
                   g_clockManCallbacksArr, CLOCK_MANAGER_CALLBACK_CNT);
    CKGEN_DRV_UpdateConfiguration(0, CLOCK_MANAGER_POLICY_AGREEMENT);
}
