/**
*   @file    demo_app_services.h
*

*   @brief   demo application services.
*   @details This file contains function declaration used for demo app services.
*
*   @addtogroup demo_app_services
*   @{
*/
/*==================================================================================================
*
*   Copyright 2020-2021 NXP.
*
*   This software is owned or controlled by NXP and may only be used strictly in accordance with
*   the applicable license terms. By expressly accepting such terms or by downloading, installing,
*   activating and/or otherwise using the software, you are agreeing that you have read, and that
*   you agree to comply with and are bound by, such license terms. If you do not agree to
*   be bound by the applicable license terms, then you may not retain, install, activate or
*   otherwise use the software.
==================================================================================================*/

#ifndef DEMO_APP_SERVICES_H
#define DEMO_APP_SERVICES_H


#ifdef __cplusplus
extern "C"{
#endif


/*==================================================================================================
*                                        INCLUDE FILES
* 1) system and project includes
* 2) needed interfaces from external units
* 3) internal and external interfaces from this unit
==================================================================================================*/
#include "hse_srv_attr.h"
#include "std_typedefs.h"
#include "global_variables.h"
/*==================================================================================================
*                              SOURCE FILE VERSION INFORMATION
==================================================================================================*/

/*==================================================================================================
*                                     FILE VERSION CHECKS
==================================================================================================*/

/*==================================================================================================
*                                          CONSTANTS
==================================================================================================*/

/*==================================================================================================
*                                      DEFINES AND MACROS
==================================================================================================*/
/**< @brief HSE FW pink image is in primary location (specified in IVT, currently running) */

#define MU0                             (0U)
#define MU1                             (1U)
#define MU2                             (2U)
#define MU3                             (3U)

#define CH0                             (0U)
#define CH1                             (1U)

#define PTR_TO_HOST_ADDR(ptr)           ((HOST_ADDR)(uintptr_t)(ptr))

#define BOOT_IMG_TAG_LEN                (16UL)

#define USE_SHE_BASED_SECURE_BOOT       3U
#define USE_ADVANCED_SECURE_BOOT        2U
#define USE_BASIC_SECURE_BOOT           1U

#define ADKP_LENGTH                     (uint8_t)16U
#define UINT64_MAX_VAL                  0xFFFFFFFFFFFFFFFFUL
#define HSEFWFEATUREFLAG_ENABLED_VALUE  0xAABBCCDDDDCCBBAAUL

#define FXOSC_ENABLE_MAGIC_NUMBER       (0xAAAA5555u)
#define FXOSC_ENABLE_MAGIC_NUMBER_POS   (32u)
#define FXOSC_GMSEL                     (0x0cu)
#define FXOSC_GMSEL_POS                 (28u)
#define FXOSC_EOCV                      (0x9du)
#define FXOSC_EOCV_POS                  (20u)
#define FXOSC_CRYSTAL_FREQ              (16000u)
#define FXOSC_CRYSTAL_FREQ_POS          (0u)

#define UTEST_BASE_ADDRESS              0x1B000000UL
#define IVT_GMAC_FLAG_OFFSET            0x208UL
#define UID_OFFSET                      0x40UL
#define BLOCK0_IVT_ADDRESS              0x00400000U
#define BLOCK1_IVT_ADDRESS              0x00500000U
#define BLOCK2_IVT_ADDRESS              0x00600000U
#define BLOCK3_IVT_ADDRESS              0x00700000U
#define IVT_BOOT_CFG_WORD_BOOT_SEQ_POS  (3UL)
#define IVT_BOOT_CFG_WORD_BOOT_SEQ      (1UL << IVT_BOOT_CFG_WORD_BOOT_SEQ_POS)
#define IVT_BOOT_CFG_WORD_PLL_ENABLE_POS  (4UL)
#define IVT_BOOT_CFG_WORD_PLL_ENABLE      (1UL << IVT_BOOT_CFG_WORD_PLL_ENABLE_POS)
#define MU_REG_WRITE64(address, value)  ((*(volatile uint64_t*)(address))= (value))
#define MU_REG_READ64(address)          (*(volatile uint64_t*)(address))
#define MU_REG_READ8(address)           (*(volatile uint8_t*)(address))



/* Following macro defines chip mode
 * 1 - Lockstep operation.
 * 0 - Decoupled operation. */
#define LOCKSTEP_EN   (1)

/* From here, user should not modify the code */
#define PROGRAM_DATA1  (0x00100004)  /* UTEST_MISC DCF Control Word */
#if (LOCKSTEP_EN == 1)
    #define PROGRAM_DATA0  (0x00000101)  /* UTEST_MISC Data Word */
#elif (LOCKSTEP_EN == 0)
    #define PROGRAM_DATA0  (0x00000100)  /* UTEST_MISC Data Word */
#else
    #error "Only two options are supported for LOCKSTEP_EN: [0, 1]."
#endif

/* HSE_CLK_MODE_AND_GSKT_CTRL : hse Clock mode selection and Bypass HSE IAHB gasket control
 * in UTEST Miscellaneous Register (UTEST_MISC):dcf_client_utest_misc 30-29
 * Field description :
 * These bits control the HSE clock control and HSE_IAHB gasket operation in different clocking options as listed in field descripiton.
 * The values in different clocking options are as listed below:
    00 =  Applicable for clocking option A.
            Ratio of 1:2 in between HSE subsystem programming interface clock
            (AIPS_SLOW_CLK) and HSE module clock (HSE_CLK). HSE_IAHB gasket enabled.
    01 =  Applicable for clocking option C, D, E, E2, and F.
            Ratio of 1:2 in between HSE subsystem programming interface clock
            (AIPS_SLOW_CLK) and HSE module clock (HSE_CLK). HSE_IAHB gasket bypass.
    1x = 10b and 11b both are applicable for clocking option B in same way.
            Ratio of 1:4 in between HSE subsystem programming interface clock
            (AIPS_SLOW_CLK) and HSE module clock (HSE_CLK). HSE_IAHB gasket enabled.
 * OPTION A : HSE_CLK 80M
 * OPTION B : HSE_CLK 120M
 * */
#define HSE_CLK_MODE_AND_GSKT_CTRL              (0x02u)
#define HSE_CLK_MODE_AND_GSKT_CTRL_POS          (29u)


/* UTest DCF Record Space : 5376 Bytes
 * 0x1B000700 - 0x1B001BFF */
#define DCF_RECORD_START_ADDRESS  (0x1B000700)  /* UTEST DCF record start address */
#define DCF_RECORD_END_ADDRESS    (0x1B001B00)  /* UTEST DCF record end address */



/* aes 256bit - 32byte - 0x20 */
#define AES_MAC_LEN (0x20)
/* hmac 1024bit - 128byte - 0x80 */
#define HMAC_MAC_LEN (0x80)
/* rsa 4096bit - 512byte - 0x200 */
#define RSA_SIGN_LEN (0x200)
/* ecc 521bit - 65byte - 0x41 ~0x50 */
#define ECC_SIGN_LEN (0x50)

#ifndef SECURE_BOOT_CFG
#define AUTH_TAG_BASE_ADDR                         (0x00502000u)
#else
extern uint32_t __int_flash_auth_tag_0_start__ ;
#define AUTH_TAG_BASE_ADDR                          ((uint32_t)(&__int_flash_auth_tag_0_start__))
#endif

#define AUTH_TAG_MARKER_HIGH_ADDRESS_VAL            (0xAAAAAAAAu)
#define AUTH_TAG_MARKER_LOW_ADDRESS_VAL             (0x55555555u)
#define AUTH_TAG_MARKER_ADDRESS                     (AUTH_TAG_BASE_ADDR)
#define AUTH_TAG_MARKER_ADDRESS_LEN                 (0x20u)

#define CMAC_TAG_CODE_FLASH_ADDRESS                 (AUTH_TAG_MARKER_ADDRESS + AUTH_TAG_MARKER_ADDRESS_LEN )

#define GMAC_TAG_CODE_FLASH_ADDRESS                 (CMAC_TAG_CODE_FLASH_ADDRESS+AES_MAC_LEN)

#define HMAC_TAG_CODE_FLASH_ADDRESS                 (GMAC_TAG_CODE_FLASH_ADDRESS+AES_MAC_LEN)

#define ECDSA_TAG1_CODE_FLASH_ADDRESS               (HMAC_TAG_CODE_FLASH_ADDRESS+HMAC_MAC_LEN)

#define ECDSA_TAG2_CODE_FLASH_ADDRESS               (ECDSA_TAG1_CODE_FLASH_ADDRESS+ECC_SIGN_LEN)

#define RSA_PSS_TAG_CODE_FLASH_ADDRESS              (ECDSA_TAG2_CODE_FLASH_ADDRESS+ECC_SIGN_LEN)

#define RSA_PKCS1_TAG_CODE_FLASH_ADDRESS            (RSA_PSS_TAG_CODE_FLASH_ADDRESS+RSA_SIGN_LEN)

#define EDDSA_TAG1_CODE_FLASH_ADDRESS               (RSA_PKCS1_TAG_CODE_FLASH_ADDRESS+RSA_SIGN_LEN)

#define EDDSA_TAG2_CODE_FLASH_ADDRESS               (EDDSA_TAG1_CODE_FLASH_ADDRESS+ECC_SIGN_LEN)



/*==================================================================================================
*                                             ENUMS
==================================================================================================*/
typedef enum
{
    APP_NO_TEST_RUNNING = 0,
    APP_PROGRAM_HSE_ATTRIBUTE = 1,
    APP_RUN_HSE_CRYPTOGRAPHIC_SERVICES = 2,
    APP_HSE_FW_UPDATE = 4,
    APP_SECURE_BOOT_CONFIGURED = 8,
    APP_ENABLE_HSE_IVT_AUTH = 16
}eRunExmapleTests;

typedef enum
{
    NON_SECURE_IVT = 0,
    SECURE_IVT
}ivt_type_t;

typedef enum
{
    ADVANCED_SECURE_BOOT = 0,
    SHE_BASED_SECURE_BOOT = 1
}eSecureBootType;

typedef enum
{
    AES128 = 1,
    AES256 = 2,
    HMAC = 4,
    ECC = 8,
    RSA = 16
}secureboot_authtypes_t;

/*==================================================================================================
                                 STRUCTURES AND OTHER TYPEDEFS
==================================================================================================*/

/*==================================================================================================
                                 GLOBAL VARIABLE DECLARATIONS
==================================================================================================*/
extern const uint8_t aesEcbCiphertext[];
extern const uint8_t aesEcbPlaintext[];
extern const uint8_t aesEcbKey[];
extern const uint32_t aesEcbKeyLength;
extern const uint32_t aesEcbPlaintextLength;
extern const uint32_t aesEcbCiphertextLength;
extern const uint16_t gAESProvisionKeyLength;
extern const uint8_t eccP256PubKey[];
extern const uint8_t eccP256PrivKey[];
extern const uint8_t message[];
extern const uint8_t hmacKeyUpdated[];
extern const uint8_t gAES128ProvisionKey[];
extern const uint8_t rsa2048CustAuthKeyModulus[];
extern const uint16_t rsa2048CustAuthKeyModulusLength;
extern const uint8_t rsa2048CustAuthKeyPubExp[];
extern const uint16_t rsa2048CustAuthKeyPubExpLength;
extern const uint8_t rsa2048CustAuthKeyPrivExp[];
extern const uint16_t rsa2048CustAuthKeyPrivExpLength;
extern const uint8_t hmacKeyInitial[];
extern const uint32_t hmacKeyInitialLength;
extern volatile bool_t authentication_type[];
/*==================================================================================================
                                     FUNCTION PROTOTYPES
==================================================================================================*/
void HSE_CMAC_Calculation_Testing(void);
void HSE_Status(void);

/*
    Function: HSE_GetVersion_Example

    @brief    Get HSE version example
    @detailed Simplest HSE request used for confirmation of running HSE
 */
hseSrvResponse_t HSE_GetVersion_Example( hseAttrFwVersion_t *pHseFwVersion );

/*
    Function: HSE_SaveVersion_Example

    @brief    save version number
    @detailed save version number in global var of running HSE FW in the device
 */
void HSE_SaveVersion(hseAttrFwVersion_t *pOldHseFwVersion, hseAttrFwVersion_t *pHseFwVersion);
/*
    Function: HSE_Config

    @brief    Example of configuring HSE services
    @detailed Configure NVM attributes, key catalogs, install NVM keys and handle SYS_IMG
 */
hseSrvResponse_t HSE_Config(void);
/*
    Function: HSE_Crypto

    @brief    HSE crypto services examples
    @detailed Examples of symmetric/asymmetric, sync/async HSE crypto operations and SYS authorization
 */
hseSrvResponse_t HSE_Crypto(void);

/*
    Function: SetCustAuthorizationKey

    @brief    Import keys for sys authorization
    @detailed Example of importing keys for SYS authorization
 */
hseSrvResponse_t SetCustAuthorizationKey( void );

/*
    Function: DoHseFwUpdate

    @brief    Returns whether FW update is applicable or not
 */
bool_t DoHseFwUpdate(void);
/*
    Function: HSE_UpdateFW

    @brief    HSE FW update example
    @detailed Example of FW Blue Image generation from new/current FW pink image
 */
void HSE_UpdateFW(void);

hseSrvResponse_t HSE_UpdateSBAF(uint32_t storeSBAFFWAddr, hseAccessMode_t updateMode, uint32_t sbafSize);

/*
    Function: IsSecureBootEnabled

    @brief    Returns whether Secure Boot is enabled or not (in IVT)
 */
bool_t IsSecureBootEnabled(void);
/*
    Function: HSE_EnableSecureBoot

    @brief    Secure Boot configuration examples
    @detailed Example HSE services usage for secure boot enablement (SMR/CR entries install / BSB tag generation,
              DCD/SelfTest images signing of FW Blue Image generation from new/current FW pink image)
 */
hseSrvResponse_t HSE_EnableSecureBoot(void);
/*
    Function: HSE_CompareVersion

    @brief    Compares hse fw version before and after firmware updated
    @detailed this function is used after firmware update request is completed by HSE and expected is version is
              also updated. hence it will compare version of updated hse with hse running before fw update. If
              version is greater or equal to, then fw update is considered successful.
 */
bool_t HSE_CompareVersion(hseAttrFwVersion_t *pOldHseFwVersion, hseAttrFwVersion_t *pHseFwVersion);
/*
    Function: HSE_CompareAdkp

    @brief    Compares ADKP hash that is calculated with the one that is read
    @detailed
 */
bool_t HSE_CompareAdkp( uint8_t *pDebugKey, uint8_t *pAdkpHash );
/*
    Function: HSE_ProgramAdkp

    @brief    Programs ADKP key in UTEST area
    @detailed
 */
hseSrvResponse_t HSE_ProgramAdkp( void );
/*
    Function: HSE_ReadAdkp

    @brief    Reads ADKP hash from UTEST area
    @detailed
 */
hseSrvResponse_t HSE_ReadAdkp( uint8_t *pDebugKey );
/*
    Function: HSE_CalculateHASH

    @brief    calculates hash of ADKP that is programmed
    @detailed
 */
hseSrvResponse_t HSE_CalculateHASH( uint8_t *pAdkpHash );
/*
    Function: HSE_FwUpdateExample

    @brief    firmware update request
    @detailed
 */
void HSE_FwUpdateExample(uint32_t newHseFwaddress);
/*
    Function: HSE_ActivatePassiveBlock

    @brief    Activates Passive Block for OTA-E FW udpate
    @detailed
 */
hseSrvResponse_t HSE_ActivatePassiveBlock(void);

/*
    Function: SecureBootConfiguration

    @brief    Configures secure boot depending upon secure boot type
    @detailed
 */
hseSrvResponse_t SecureBootConfiguration(void);
/*
    Function: HSE_EnableIVTAuthentication

    @brief    Enables boot authentication bit in UTEST area
    @detailed
 */
hseSrvResponse_t HSE_EnableIVTAuthentication(void);
/*
    Function: HSE_GetIVTauthbit

    @brief    Reads boot authentication bit programmed in UTEST area
    @detailed
 */
hseSrvResponse_t HSE_GetIVTauthbit(  hseAttrConfigBootAuth_t *pIvtValue );
/*
    Function: HSE_CompareAdkp

    @brief    Advances lifecycle from CUST_DEL
    @detailed
 */
void HSE_AdvanceLifecycle(hseAttrSecureLifecycle_t targetLifeCycle);
/*
    Function: HSE_ReadLifecycle

    @brief    returns current LC of the device
    @detailed
 */
hseSrvResponse_t HSE_ReadLifecycle( hseAttrSecureLifecycle_t *plifecycle );
/*
    Function: HSE_GetCapabilities_Example

    @brief    returns HSE FW capabilities
    @detailed
 */
hseSrvResponse_t HSE_GetCapabilities_Example(  uint8_t *phseCapabilites  );
/*
    Function: HSE_ConfigDebugAuthorization

    @brief    updates debug auth mode to CR
    @detailed enabling Challenge-Response debug auth
 */
void HSE_ConfigDebugAuthorization(void);

/**
   Function      HSE_SetDebugAuthModeToChalResp
   @brief         Set debug-authorization mode bit to Challenge Response.
   @details       Needed for debug-authorization protocol in OEM_PROD & INFIELD lifecycles.
*/
hseSrvResponse_t HSE_SetDebugAuthModeToChalResp( void );
/*
    Function: HSE_ReadAttrExtendCustSecurityPolicy

    @brief
    @detailed
 */
hseSrvResponse_t HSE_ReadAttrExtendCustSecurityPolicy( hseAttrExtendCustSecurityPolicy_t *pSecurityPolicy );
/*
    Function: HSE_GetDebugAuthMode

    @brief    reads current debug auth mode
    @detailed
 */
hseSrvResponse_t HSE_GetDebugAuthMode(  hseAttrDebugAuthMode_t*pDebugAuthValue );
/*
    Function: HSE_AttrExtendCustSecurityPolicy

    @brief    enables extend cust security policy
    @detailed
 */
hseSrvResponse_t HSE_AttrExtendCustSecurityPolicy( bool_t EnableAdkmBit, bool_t StartAsUserBit );
/*
    Function: HSE_ConfigNvmAttributes

    @brief    configures NVM attributes
    @detailed
 */
#if 0
hseSrvResponse_t HSE_ConfigNvmAttributes(  hseMUConfig_t gMuConfig );
#endif
/*
    Function: HSE_GetMUAttribute

    @brief    reads current NVM attribute
    @detailed
 */
hseSrvResponse_t HSE_GetMUAttribute( hseAttrMUConfig_t *pMuConfigValue );

/*
    Function: EnableHSEFWUsage

    @brief    Enables HSE FW usage flag in UTEST
    @detailed
 */
hseSrvResponse_t EnableHSEFWUsage(void);


bool_t checkHseFwFeatureFlagEnabled(void);

void EnableFXOSCUsage(void);

void ChangeDcfClockOption(void) ;

/*
    Function: HSE_SignBootImage

    @brief    Signs IVT or app image for Basic Secure Boot (AppBSB)
    @detailed
 */
hseSrvResponse_t HSE_SignBootImage
(
    const uint8_t *pInImage,
    const uint32_t inTagLength,
    uint8_t *pOutTagAddr
);
/*
    Function: HSE_HashDataNonBlocking

    @brief    Non blocking hash calculation example
    @detailed
 */
hseSrvResponse_t HSE_HashDataNonBlocking
(
    uint8_t u8MuInstance,
    hseAccessMode_t accessMode,
    uint32_t streamId,
    hseHashAlgo_t hashAlgo,
    const uint8_t *pInput,
    uint32_t inputLength,
    uint8_t *pHash,
    uint32_t *pHashLength
);
/*
    Function: check_debug_password_programmed_status

    @brief    check if debug password is already programmed
    @detailed
 */
bool_t check_debug_password_programmed_status(void);
/*
    Function: Grant_SuperUser_Rights

    @brief    Does sys authorization for formatting SHE keys
    @detailed
 */
hseSrvResponse_t Grant_SuperUser_Rights(void);
/*
    Function: HSE_EraseKeys

    @brief    Erases nvm data
    @detailed
 */
hseSrvResponse_t HSE_EraseKeys( void );
/*
    Function: Sys_Auth

    @brief    do sys authorization when LC is advanced to OEM
    @detailed
 */
hseSrvResponse_t Sys_Auth( void );
hseSrvResponse_t LoadBootMacKey( void );
hseSrvResponse_t Generic_ImportKeys( void );
hseSrvResponse_t UpdateIvt( uint32_t UpdateAddress , uint32_t SourceAddress , ivt_type_t IvtType );
hseSrvResponse_t HSE_HashDataBlocking
(
    uint8_t u8MuInstance,
    hseAccessMode_t accessMode,
    uint32_t streamId,
    hseHashAlgo_t hashAlgo,
    const uint8_t *pInput,
    uint32_t inputLength,
    uint8_t *pHash,
    uint32_t *pHashLength
);
#ifdef __cplusplus
}
#endif

#endif /* DEMO_APP_SERVICES_H */

/** @} */
