/*
 * Copyright 2020 NXP
 * All rights reserved.
 *
 *
 * SPDX-License-Identifier: BSD-3-Clause
 */

#include "fsl_device_registers.h"
#include "fsl_imu.h"
#include "mcmgr.h"
#include "mcmgr_internal_core_api.h"

#define IMU_ISR_COUNT (2U)

#if defined(IMU_CPU_INDEX) && (IMU_CPU_INDEX == 1U)
#define IMU_LINK kIMU_LinkCpu1Cpu2
#elif defined(IMU_CPU_INDEX) && (IMU_CPU_INDEX == 2U)
#define IMU_LINK kIMU_LinkCpu2Cpu1
#endif

/* Weak MU ISR stubs */
/* implement these in your application to override */

void MU_TxEmptyFlagISR(void);
void MU_RxFullFlagISR(void);

__attribute__((weak)) void MU_TxEmptyFlagISR(void){};
__attribute__((weak)) void MU_RxFullFlagISR(void){};

/* If IMU is located in an other power domain that is in lowpower, these routines shall be implemented
     to request/release the IMU power domain to get active      */
__attribute__((weak)) void PLATFORM_RemoteActiveReq(void)
{
}
__attribute__((weak)) void PLATFORM_RemoteActiveRel(void)
{
}

/* MU ISR table */
void (*const MU_interrupts[IMU_ISR_COUNT])(void) = {
    MU_TxEmptyFlagISR,
    MU_RxFullFlagISR,
};

/* MU ISR router */
static void imu_rx_isr(void)
{
    PLATFORM_RemoteActiveReq();
    MU_RxFullFlagISR();
    IMU_ClearPendingInterrupts(IMU_LINK, IMU_MSG_FIFO_CNTL_MSG_RDY_INT_CLR_MASK);

    /* Need to release active request only after IMU interrupt clearing */
    PLATFORM_RemoteActiveRel();
}

#if defined(IMU_CPU_INDEX) && (IMU_CPU_INDEX == 1U)
int32_t RF_IMU0_IRQHandler(void)
{
    imu_rx_isr();
    SDK_ISR_EXIT_BARRIER;
    return 0;
}
#endif

#if defined(IMU_CPU_INDEX) && (IMU_CPU_INDEX == 2U)
int32_t CPU2_MSG_RDY_INT_IRQHandler(void)
{
    imu_rx_isr();
    SDK_ISR_EXIT_BARRIER;
    return 0;
}
#endif /* IMU_CPU_INDEX */
