/* 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) 2023. 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.
 */

/*!
 * @file system_ac7803x.c
 *
 * @brief This file provides system clock config integration functions.
 *
 */

/* ===========================================  Includes  =========================================== */
#include "ac7803x.h"

/* ============================================  Define  ============================================ */
#define MAX_SYSTICK_COUNT         (SysTick_LOAD_RELOAD_Msk + 1U)  /* systemTick max count value */

/* for eFlash clock config */
#define SYS_EFLASH_UNLOCK_KEY1    (0x00ac7803UL)
#define SYS_EFLASH_UNLOCK_KEY2    (0x01234567UL)

/* ===========================================  Typedef  ============================================ */

/* ==========================================  Variables  =========================================== */
/* systemTick us delay factor */
static uint32_t s_facus = 0U;

/* systemTick ms delay factor */
static uint32_t s_facms = 0U;

/* system clock frequency save */
uint32_t SystemCoreClock = __SYSTEM_CLOCK;

/* apbclk frequency save */
uint32_t g_periphAPBClock = APB_BUS_FREQ;

/* ====================================  Functions declaration  ===================================== */
/* Externals declaration */
#if defined (__VTOR_PRESENT) && (__VTOR_PRESENT == 1U)
extern uint32_t __Vectors;
#endif

/* ======================================  Functions define  ======================================== */
/*!
 * @brief Set eFlash clock.
 *
 * @param[in] none
 * @return none
 */
void SetEflashClock(void)
{
    uint32_t eflashFreq, timeout = 100U;

    do
    {
        WRITE_REG32(EFLASH->UKR, SYS_EFLASH_UNLOCK_KEY1);
        WRITE_REG32(EFLASH->UKR, SYS_EFLASH_UNLOCK_KEY2);
        timeout--;
    } while ((EFLASH->GSR & EFLASH_GSR_LOCK_Msk) && (timeout > 0U));

    eflashFreq = ((uint32_t)__SYSTEM_CLOCK / 1000000U + 1U) & 0x7FU;
    MODIFY_REG32(EFLASH->GCR, EFLASH_GCR_FREQ_Msk, EFLASH_GCR_FREQ_Pos, eflashFreq);

    SET_BIT32(EFLASH->GSR, EFLASH_GSR_LOCK_Msk);
}

/*!
 * @brief Set system clock to PLL.
 *
 * @param[in] refClk: reference clock
 *                   - PLL_REF_INTERNAL_OSC
 *                   - PLL_REF_EXTERNAL_OSC
 * @return status 0: success; 1: ref clk change to hsi; other: error
 */
uint8_t SetSysClkToPLL(PLL_ReferenceType refClk)
{
    uint8_t ret = 0U;

    /* Check current clock source, switch clock to internal clock first */
    if ((CKGEN->CTRL & CKGEN_CTRL_SYSCLK_SEL_Msk) != (uint32_t)SYSCLK_SRC_INTERNAL_OSC)
    {
        CKGEN_SetSysclkSrc(SYSCLK_SRC_INTERNAL_OSC);
    }

    if (PLL_REF_EXTERNAL_OSC == refClk)
    {
        /* Set xosc bypass mode */
        #if (CKGEN_HSE_BYPASS_ENABLE)
        SPM_EnableXOSCBypassMode(ENABLE);
        #endif
        /* Enable XOSC */
        if (SPM_EnableXOSC(ENABLE) == ERROR)
        {
            ret = 1U;
        }
        #if (CKGEN_XOSC_MONITOR_ENABLE)
        else
        {
            CKGEN_EnableXOSCMonitor(ENABLE);
        }
        #endif
    }

    /* Configure PLL */
    if (0U == ret)
    {
        CKGEN_SetPLLReference(refClk);
    }
    else
    {
        #if (USE_XTAL == XTAL_8M)
        (void)SPM_EnableXOSC(DISABLE);
        /* If XOSC is fail, auto select hsi as reference clock */
        CKGEN_SetPLLReference(PLL_REF_INTERNAL_OSC);
        #else
        return 2U;
        #endif
    }
    CKGEN_SetPllPrevDiv(PLL_PREDIV);
    CKGEN_SetPllPostDiv(PLL_POSDIV);
    CKGEN_SetPllFeedbackDiv(PLL_FBKDIV);
    MODIFY_REG32(ANA->SYSPLL1_CFG1, ANA_SYSPLL1_CFG1_LD_DLY_SEL_Msk, ANA_SYSPLL1_CFG1_LD_DLY_SEL_Pos, 7U);
    MODIFY_REG32(ANA->SYSPLL1_CFG1, ANA_SYSPLL1_CFG1_LD_UNLOCK_SEL_Msk, ANA_SYSPLL1_CFG1_LD_UNLOCK_SEL_Pos, 3U);
    /* Disable reset after pll unlock */
    CLEAR_BIT32(CKGEN->RESET_CTRL, CKGEN_RESET_CTRL_PLL_UNLOCK_RST_EN_Msk);
    /* Enable PLL */
    if (SPM_EnablePLL(ENABLE) == ERROR)
    {
        ret = 3U;
    }

    if (ret != 3U)
    {
        SetEflashClock();
        /* If PLL is success, set system clock to PLL */
        CKGEN_SetSysclkSrc(SYSCLK_SRC_PLL_OUTPUT);
    }

    return ret;
}

/*!
 * @brief Set system clock to HSE.
 *
 * @param[in] none
 * @return none
 */
void SetSysClkToHSE(void)
{
    /* Set xosc bypass mode */
    #if (CKGEN_HSE_BYPASS_ENABLE)
    SPM_EnableXOSCBypassMode(ENABLE);
    #endif
    /* Enable XOSC */
    if (SPM_EnableXOSC(ENABLE) == SUCCESS)
    {
        #if (CKGEN_XOSC_MONITOR_ENABLE)
        CKGEN_EnableXOSCMonitor(ENABLE);
        #endif
        SetEflashClock();
        /* xosc enable success, use external osc as system clock */
        CKGEN_SetSysclkSrc(SYSCLK_SRC_EXTERNAL_OSC);
    }
}

/*!
 * @brief Set system clock to HSI.
 *
 * @param[in] none
 * @return none
 */
void SetSysClkToHSI(void)
{
    SetEflashClock();
    CKGEN_SetSysclkSrc(SYSCLK_SRC_INTERNAL_OSC);
}

/*!
 * @brief Set system clock.
 *
 * @param[in] none
 * @return none
 */
void SetSysClock(void)
{
    CKGEN_SetSysclkDiv(SYSCLK_DIV);
#if AC780X_CLOCK_SRC == IC_CLOCK_SRC_HSE
    SetSysClkToHSE();
#elif AC780X_CLOCK_SRC == IC_CLOCK_SRC_HSI_PLL
    (void)SetSysClkToPLL(PLL_REF_INTERNAL_OSC);
#elif AC780X_CLOCK_SRC == IC_CLOCK_SRC_HSE_PLL
    (void)SetSysClkToPLL(PLL_REF_EXTERNAL_OSC);
#else
    SetSysClkToHSI();
#endif
}

/*!
 * @brief Delay until the syctick count tick to 0.
 *
 * @param[in] tick: systick count value
 * @return none
 */
static void SysTickDelay(uint32_t tick)
{
    uint32_t tickFlag;

    SysTick->LOAD = tick - 1U;
    SysTick->VAL = 0x00U;
    SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_ENABLE_Msk;
    do
    {
        tickFlag = SysTick->CTRL;
    } while ((tickFlag & SysTick_CTRL_ENABLE_Msk) && \
            (!(tickFlag & SysTick_CTRL_COUNTFLAG_Msk)));

    SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk;
    SysTick->VAL = 0x00U;
}

/*!
 * @brief Repeatlly delay the ticks for the given times.
 *
 * @param[in] times: the times of delay the tick
 * @param[in] tick: each tick to delay
 * @return none
 */
static void SysTickRepeatDelay(uint32_t times, uint32_t tick)
{
    uint32_t i;

    for (i = 0U; i < times; i++)
    {
        SysTickDelay(tick);
    }
}

/*!
 * @brief Init delay count factor, 1s = TICKS * (1/f) s.
 *
 * @param[in] none
 * @return none
 */
void InitDelay(void)
{
    s_facus = __SYSTEM_CLOCK / 1000000U;
    s_facms = s_facus * 1000U;
}

/*!
 * @brief Delay us.
 *
 * @param[in] us: us for delay
 * @return none
 */
void udelay(uint32_t us)
{
    uint32_t tick = us * s_facus;

    SysTickRepeatDelay(tick / MAX_SYSTICK_COUNT, MAX_SYSTICK_COUNT);

    SysTickDelay(tick % MAX_SYSTICK_COUNT);
}

/*!
 * @brief Delay ms.
 *
 * @param[in] ms: ms for delay
 * @return none
 */
void mdelay(uint32_t ms)
{
    uint32_t tick = ms * s_facms;

    SysTickRepeatDelay(tick / MAX_SYSTICK_COUNT, MAX_SYSTICK_COUNT);

    SysTickDelay(tick % MAX_SYSTICK_COUNT);
}

/*!
 * @brief Setup the microcontroller system. Initialize the System.
 *
 * @param[in] none
 * @return none
 */
void SystemInit(void)
{
    /* Disable LVR if need */
#if (LVR_DISABLE)
    SPM_EnableLVR(DISABLE);
    SPM_EnableDPWRLVR(DISABLE);
#endif

    /* Configure system clock and bus clock */
    SetSysClock();
    CKGEN_SetAPBClockDivider(APBCLK_DIV);

    /* Disable watchdog */
#if (WDG_DISABLE)
    WDG->CNT = 0xE064D987U;
    WDG->CNT = 0x868A8478U;
    WDG->CS0 = 0x20U;
#endif

    /* Relocate vector table */
#if defined (__VTOR_PRESENT) && (__VTOR_PRESENT == 1U)
    SCB->VTOR = (uint32_t) &__Vectors;
#endif
}

/*!
 * @brief Get system clock frequence.
 *
 * @param[in] none
 * @return none
 */
void SystemCoreClockUpdate(void)
{
    uint8_t clkSrc, sysClkDiv, apbClkDiv;
    uint8_t pllRef, preDiv, postDiv, fbkDiv;
    uint32_t srcFreq = 0U;

    clkSrc = CKGEN->CTRL & CKGEN_CTRL_SYSCLK_SEL_Msk;
    sysClkDiv = ((CKGEN->CTRL & CKGEN_CTRL_SYSCLK_DIV_Msk) >> CKGEN_CTRL_SYSCLK_DIV_Pos) + 1U;
    apbClkDiv = ((CKGEN->CTRL & CKGEN_CTRL_APBCLK_DIV_Msk) >> CKGEN_CTRL_APBCLK_DIV_Pos) + 1U;
    switch (clkSrc)
    {
    case SYSCLK_SRC_INTERNAL_OSC:  /* HSI clock */
        srcFreq = HSI_FREQ;
        break;

    case SYSCLK_SRC_PLL_OUTPUT:  /* PLL clock */
        pllRef = (CKGEN->CTRL & CKGEN_CTRL_PLL_REF_SEL_Msk) >> CKGEN_CTRL_PLL_REF_SEL_Pos;
        preDiv = ((ANA->SYSPLL1_CFG0 & ANA_SYSPLL1_CFG0_SYSPLL1_PREDIV_Msk) >> ANA_SYSPLL1_CFG0_SYSPLL1_PREDIV_Pos) + 1U;
        postDiv = ((ANA->SYSPLL1_CFG0 & ANA_SYSPLL1_CFG0_SYSPLL1_POSDIV_Msk) >> ANA_SYSPLL1_CFG0_SYSPLL1_POSDIV_Pos) * 2U;
        fbkDiv = (ANA->SYSPLL1_CFG0 & ANA_SYSPLL1_CFG0_SYSPLL1_FBKDIV_Msk) >> ANA_SYSPLL1_CFG0_SYSPLL1_FBKDIV_Pos;
        if (pllRef)
        {
            srcFreq = USE_XTAL;  /* HSE reference clock */
        }
        else
        {
            srcFreq = HSI_FREQ;  /* HSI reference clock */
        }

        srcFreq = (srcFreq / preDiv) * fbkDiv / postDiv;
        break;

    case SYSCLK_SRC_EXTERNAL_OSC:  /* HSE clock */
        srcFreq = USE_XTAL;
        break;

    default:
        break;
    }

    SystemCoreClock = srcFreq / sysClkDiv;           /* system clock freq */
    g_periphAPBClock = SystemCoreClock / apbClkDiv;  /* apb clock freq */
}

/*!
 * @brief Get CPU ID.
 *
 * @param[in] none
 * @return return the CPUID
 */
uint32_t GetCPUID(void)
{
    return SCB->CPUID;
}

/*!
 * @brief Enter the Standby mode.
 *
 * @param[in] none
 * @return none
 */
void SysStandby(void)
{
    SPM_SetLowPowerMode(LOW_POWER_MODE_STANDBY);
    /* Set the SLEEPDEEP bit to enable deep sleep mode */
    SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk;

#if defined ( __GNUC__)
    __asm volatile("wfi");
#else
    __asm("wfi");
#endif
}

/*!
 * @brief Enter the stop mode.
 *
 * @param[in] none
 * @return none
 */
void SysStop(void)
{
    SPM_SetLowPowerMode(LOW_POWER_MODE_STOP);
    /* Set the SLEEPDEEP bit to enable deep sleep mode */
    SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk;

#if defined ( __GNUC__)
    __asm volatile("wfi");
#else
    __asm("wfi");
#endif
    /* Add Debug Interface to enable printf after wakeup */
}

/*!
 * @brief Enter the CPU sleep mode.
 *
 * @param[in] none
 * @return none
 */
void SysSleep(void)
{
    /* Clear the SLEEPDEEP bit to make sure we go into WAIT (sleep) mode instead of deep sleep. */
    SCB->SCR &= ~SCB_SCR_SLEEPDEEP_Msk;

#if defined ( __GNUC__)
    __asm volatile("wfi");
#else
    __asm("wfi");
#endif
}

/*!
 * @brief Get uuid from device.
 *
 * @param[in] uuidBuffer: uuid buffer
 * @return none
 */
void GetUUID(uint32_t *uuidBuffer)
{
#define UUID_BASE_ADDRESS  0x40002054U

    uint8_t i;

    if (uuidBuffer != NULL)
    {
        for (i = 0U; i < 4U; i++)
        {
            uuidBuffer[i] = (*(__IO uint32_t *)(UUID_BASE_ADDRESS + i * 4U));
        }
    }
}

/*!
 * @brief Get cpu type from device.
 *
 * @param[in] none
 * @return cpu type: AC7803
 */
uint32_t GetCpuType(void)
{
#define CPU_TYPE_BASE_ADDRESS  0x40002050U

    return (*(__IO uint32_t *)(CPU_TYPE_BASE_ADDRESS));
}

/*!
 * @brief Get reset status.
 *
 * @param[in] none
 * @return reset status
 *            - bit0: POR_RESET_STATUS
 *            - bit1: LVR_RESET_STATUS
 *            - bit2: EXT_RESET_STATUS
 *            - bit3: ECC2_RESET_STATUS
 *            - bit4: WDG_32K_RESET_STATUS
 *            - bit5: WDG_RESET_STATUS
 *            - bit6: CPU_SYSRESET_STATUS
 *            - bit7: CPU_LOCKUP_RST_STATUS
 *            - bit8: PLL_UNLOCK_RST_STATUS
 *            - bit9: XOSC_LOSS_RST_STATUS
 *            - bit10: FLASH_ECC2_RST_STATUS
 */
uint32_t GetResetStatus(void)
{
    return (CKGEN->RESET_STATUS);
}

/*!
 * @brief Clear all reset status.
 *
 * @param[in] none
 * @return none
 */
void ClearAllResetStatus(void)
{
    SET_BIT32(CKGEN->RESET_STATUS, CKGEN_RESET_STATUS_CLR_RESET_STATUS_Msk);
}

/*!
 * @brief Enable/disable external reset.
 *
 * @param[in] enable: enable state
 *                   - ENABLE
 *                   - DISABLE
 * @return none
 */
void SetExternalReset(ACTION_Type enable)
{
    MODIFY_REG32(CKGEN->RESET_CTRL, CKGEN_RESET_CTRL_EXT_RST_EN_Msk, CKGEN_RESET_CTRL_EXT_RST_EN_Pos, (uint32_t)enable);
}

/*!
 * @brief Configure external reset filter.
 *
 * @param[in] enable: enable state
 *                   - ENABLE
 *                   - DISABLE
 * @param[in] value: filter value
 * @return none
 */
void SetExternalResetFilter(ACTION_Type enable, uint8_t value)
{
    MODIFY_REG32(CKGEN->RESET_CTRL, CKGEN_RESET_CTRL_EXT_RST_DEGLITCH_EN_Msk, CKGEN_RESET_CTRL_EXT_RST_DEGLITCH_EN_Pos, (uint32_t)enable);
    MODIFY_REG32(CKGEN->RESET_CTRL, CKGEN_RESET_CTRL_EXT_RST_DEGLITCH_VALUE_Msk, CKGEN_RESET_CTRL_EXT_RST_DEGLITCH_VALUE_Pos, value);
}

/* =============================================  EOF  ============================================== */
