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

#include "fsl_common.h"

/*!
 * @defgroup flexcan FlexCAN Driver
 * @details This document consists of sections titled with <b>Driver Overview</b>, <b>Data Structures</b>,
 *          <b>Enumerations</b>, <b>Functions</b>, etc., each with an overview list and detailed documentation.
 *          It is recommended to read the <b>Driver Overview</b> first for it includes a comprehensive description
 *          of the peripheral, driver and driver changes. Other sections give detailed information for APIs, enums,
 *          macros, etc., for your further reference.
 * @{
 */

/*******************************************************************************
 * ChangeLog
 ******************************************************************************/
/*!
 * @defgroup flexcan_driver_log The Driver Change Log
 * @ingroup flexcan
 * @{
 * The current FLEXCAN driver version is 2.0.0.
 *
 *   - 2.0.0
 *     - Initial version.
 * @}
 */

/*******************************************************************************
 * Introduction of peripheral and driver
 ******************************************************************************/
/*!
 * @defgroup flexcan_intro FlexCAN Peripheral and Driver Overview
 * @ingroup flexcan
 * @brief Content including 1) peripheral features, work logic and work method; 2) driver design logic and use method;
 *        3) typical use case.
 * @{
 *
 * Peripheral feature and how this peripheral works
 * =================================================
 * The FlexCAN module is a full implementation of the CAN protocol specification, the CAN with Flexible Data rate (CAN
 * FD) protocol, and the CAN 2.0 version B protocol, which supports both standard and extended message frames and long
 * payloads up to 64 bytes, transferred at faster rates (up to 8 Mbps). The FlexCAN module can be divided into several
 * submodules : The "Protocol Engine" (PE) submodule, The "Controller Host Interface" (CHI) submodule and The "Bus
 * Interface Unit" (BIU) submodule.
 *
 * Features
 * --------------------------
 *   + Protocol level support
 *      - Support for Flexible Data Rate (CAN FD) protocol specification and CAN 2.0 B protocol specifications.
 *      - Compliant with the ISO 11898-1 standard.
 *
 *   + Multiple functional modes
 *      - Normal mode, operates receiving and/or transmitting message frames, errors are managed normally, and all CAN
 *        Protocol functions are enabled. It can be further divided into user mode and supervisor mode, which differ in
 *        the access to some restricted control registers.
 *      - Freeze mode, in this mode, no transmission or reception of frames is done and synchronicity to the CAN bus is
 *        lost. All memory-mapped register are configurable, except the PE submodule clock source select bit
 *        CTRL1[CLKSRC].
 *      - Loop-Back mode, in this mode, FlexCAN performs an internal loop back that can be used for self-test operation.
 *        The bit stream output of the transmitter is internally fed back to the receiver input. The Rx input pin will
 *        be ignored and the Tx output pin always to the recessive state (means logic 1).
 *      - Listen-Only mode, in this mode, transmission is disabled, all error counters are frozen, and the module
 *        operates in a CAN Error Passive mode. Only messages acknowledged by another CAN station will be received.
 *      - CAN FD Active mode, in this mode, FlexCAN is capable of transmitting and receiving all messages formatted
 *        according to the CAN FD Protocol and CAN 2.0 Protocol 2.0 in an interleaved fashion.
 *
 *   + Multiple low-power modes with programmable wake up on bus activity (only Doze/Stop mode)
 *      - Disable mode, this low-power mode is entered when MCR[MDIS] is asserted by the software and MCR[LPM_ACK] is
 *        asserted by FlexCAN.  When in disable mode, the module issues a request to disable the clocks to the CAN
 *        Protocol Engine and Controller Host Interface submodules.
 *      - Doze modes, this low power mode is entered when MCR[DOZE] is asserted and Doze mode is requested at chip
 *        level, and MCR[ LPM_ACK] is asserted by FlexCAN. When in Doze mode, the module issues a request to disable the
 *        clocks to the CAN Protocol Engine and the CAN Controller-Host Interface submodules.
 *      - Stop modes, this low power mode is entered when Stop mode is requested at chip level and MCR[LPM_ACK] is
 *        asserted by the FlexCAN. When in Stop Mode, the module puts itself in an inactive state and then informs the
 *        CPU that the clocks can be shut down globally.
 *
 *   + Flexible message buffers (MBs) RAM to storing Rx/Tx CAN/CANFD frame
 *      - Each MBs can configurable as Rx or Tx, all supporting standard (11 bits ID) and extended (29 bits ID) frame.
 *      - MBs RAM not used by reception or transmission can be used as general purpose RAM space.
 *      - Support configurable MBs size to 8/16/32/64 bytes, and the corresponding number of MB is 32/21/12/7.
 *      - Support individual/global Rx Mask for each MBs.
 *      - Support record Rx/Tx frames time stamp based on 16-bit free running timer, with an optional external time
 *        tick.
 *      - Support configure MB0~5 to be full-featured Rx FIFO under no-FD mode, with storage capacity for up to six 8
 *        bytes frames and automatic internal pointer handling with DMA support.
 *      - Support powerful Rx FIFO ID filtering, capable of matching incoming IDs against either 128 extended, 256
 *        standard, or 512 partial (8 bit) IDs, with up to 32 individual masking capability.
 *      - Support selectable priority between MBs and Rx FIFO during matching process.
 *      - Support indicates which Identifier Acceptance filter was hit by the received message in Rx FIFO.
 *      - Support programmable Tx MBs priority scheme: lowest ID, lowest buffer number, or highest priority.
 *         + lowest ID : the Tx MB's frame have a lowest ID will be sent in the next opportunity.
 *         + lowest buffer number : the first (lowest number) active Tx MB found will be sent in the next opportunity.
 *         + highest priority : the Tx MB's frame have a highest local PRIO value (3 bits) will be sent in the next
 *           opportunity.
 *
 *   + Clock and bit timing
 *      - Support programmable clock source to the PE submodule, either peripheral clock or oscillator clock.
 *      - Support extends CAN bit timing settings, which extends the range of the timing variables defined by protocol.
 *      - Support a second set of CAN bit timing variables to be applied at the data phase of CAN FD frames with the Bit
 *        Rate Switch (BRS) set.
 *      - Support transceiver delay compensation feature when transmitting CAN FD frames with the Bit Rate Switch (BRS)
 *        set.
 *
 *   + Other software programmable features
 *      - Self reception capability, can't be enabled under Loop-Back mode.
 *      - Transmission abort capability.
 *      - Support global network time, which resets the free running timer each time a specific message received.
 *      - Support configure remote request frames be managed automatically or by software.
 *
 *   + Interrupts support
 *      - Message buffers interrupt.
 *      - Bus Off interrupt.
 *      - Error interrupt.
 *      - Rx Warning interrupt.
 *      - Tx Warning interrupt.
 *      - Wake Up interrupt.
 *
 *   + DMA support
 *      -  Support DMA feature for RX FIFO.
 *
 * How this driver are designed to make this peripheral works
 * ===========================================================
 * The FlexCAN driver provides APIs with Functional layer and Transactional layer. The Functional Layer is provided with
 * highly optimized implementation and highly flexible usage of the peripheral features. The Transactional layer is
 * provided with high abstraction, limited flexibility/optimization, and not all features are covered.
 *
 * Functional Layer
 * ----------------
 * + Initialization and De-initialization Interfaces.
 *     The APIs in this function group can be used to initialize or de-initialize the FlexCAN module.
 * + Freeze Mode Operation.
 *     The APIs in this function group used to make FlexCAN module enter/exit the freeze mode.
 * + Timing Calculation Helper Functions.
 *     The APIs in this function group used to help user get improved timing values for CAN and CAN FD by
 *     specific baudrates.
 * + Timing Configuration.
 *     The APIs in this function group used to configure the CAN and CAN FD timing characteristic.
 * + Message Buffer Configuration.
 *     The APIs in this function group can be used to configure Message Buffer (MB) mask status, clean and select as
 *     Tx/Rx MB, configures the Rx FIFO feature.
 * + Status Interface.
 *     The APIs in this function group can be used to get or clear the FlexCAN module status flag, get the Tx/Rx error
 *     counter value.
 * + Message Buffer Status Get/Clear Interfaces.
 *     The APIs in this function group can be used to get or clear the status flag of MBs.
 * + Interrupt Interfaces.
 *     The APIs in this function group can be used to enable/disable FlexCAN module interrupts.
 * + Message Buffer Interrupts Interfaces.
 *     The APIs in this function group can be used to enable/disable MBs interrupts.
 * + DMA Control Interfaces.
 *     The APIs in this function group used to enable/disable FlexCAN Rx FIFO DMA request, get the Rx FIFO Head address.
 * + Bus Operations.
 *     The APIs in this function group used to enable/disable FlexCAN module, write/read the MBs' frame.
 * + Transactional Blocking Interface.
 *     The APIs in this function group used to send/receive frame to/from CAN bus with polling mode.
 *
 * Transactional Layer
 * -------------------
 * Transactional layer is state retained thus it use the @ref flexcan_handle_t to specify the peripheral. User need to
 * initialize the handle by calling @ref FLEXCAN_TransferCreateHandle API.
 *
 * + Transactional Non-Blocking Interfaces.
 *     The APIs in this function group used to send/receive frame to/from CAN bus with interrupt way.
 *
 * How to use this driver
 * =============================
 * General Control Macro
 * ------------------------
 * + FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL
 *     SDK genneral Macro, controls whether to ungate/gate peripheral's clock source inside driver. Set it to none-zero
 *     value then driver will not ungate/gate clock source during initialization/de-initialization.
 * - FLEXCAN_WAIT_TIMEOUT
 *     FlexCAN specific Macro, controls the timeout ticks about wait Low-Power mode acknowledge.
 *
 * Configuration Items Before Calling FlexCAN Driver APIs
 * --------------------------------------------------
 *  + Mux the FlexCAN TX/RX signals to on-board pins, and configure them with expected feature.
 *  + Ungate the FlexCAN clock if user wish to do it outside driver by setting FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL to
 *    non-zero value.
 *  + If user wish to use interrupt for FlexCAN transfer while other modules' interrupt sources are also enabled, set
 * proper interrupt priority before initiating FlexCAN transfer, so that FlexCAN IRQ service can be properly executed.
 *  + Enable DMA and configure DMA channel trigger source in application codes if FlexCAN module is expected to
 *    generator DMA request on RX FIFO full/empty.
 *
 * Initialize
 * ------------------------
 * - Init CAN as classic CAN or CAN FD. @ref FLEXCAN_GetDefaultConfig or @ref FLEXCAN_GetFDDefaultConfig can help
 *   user to get a ready-to-use init data structure. Note the CAN FD mode need use both GetDefaultConfig APIs.
 *
 * CAN Timing calculation
 * -------------------------
 * - Calculation classic CAN bit rate or CAN FD data phase bit rate. Note the CAN FD need both bit rate and data phase
 *   bit rate.
 *
 * Message buffer configre and transaction
 * -------------------------
 * - For send node.
 *    + Setup Tx Message Buffer.
 *    + Send frame use Non-Blocking/Blocking way.
 * - For receive node.
 *    + Setup Rx Message Buffer.
 *    + Receive frame use Non-Blocking/Blocking way.
 *
 * Typical Use Case
 * =============================
 *  1. Send/receive CAN FD frame to/from CAN bus with interrupt mode.\n
 *     Send node
 *     @code
 *        flexcan_handle_t g_sFlexcanHandle;
 *        flexcan_config_t sFlexcanConfig;
 *        flexcan_fd_config_t sFDConfig;
 *        FLEXCAN_GetDefaultConfig(&sFlexcanConfig, EXAMPLE_CAN_CLK_FREQ);
 *        FLEXCAN_GetFDDefaultConfig(&sFDConfig);
 *        FLEXCAN_FDCalculateImprovedTimingValues(&sFlexcanConfig.sTimingConfig,
 *            &sFlexcanConfig.psFDConfig->sTimingConfig, sFlexcanConfig.u32BaudRateBps,
 *            sFlexcanConfig.psFDConfig->u32BaudRateBps, sFlexcanConfig.u32ClkFreqHz);
 *        sFlexcanConfig.psFDConfig = &sFDConfig;
 *        // Module initialization
 *        FLEXCAN_Init(CAN, &sFlexcanConfig);
 *        // Set up send transfer configuration
 *        flexcan_mb_transfer_t g_sTxXfer;
 *        flexcan_frame_t g_sFrame;
 *        // Create FlexCAN handle structure and set call back function.
 *        FLEXCAN_TransferCreateHandle(CAN, &g_sFlexcanHandle, flexcan_callback, NULL);
 *        // Clean Tx Message Buffer.
 *        FLEXCAN_SetFDTxMbConfig(CAN, TX_MESSAGE_BUFFER_NUM, true);
 *        g_sFrame.bitsId     = FLEXCAN_ID_STD(g_u32TxIdentifier);
 *        g_sFrame.bitFormat  = (uint8_t)kFLEXCAN_FrameFormatStandard;
 *        g_sFrame.bitType    = (uint8_t)kFLEXCAN_FrameTypeData;
 *        g_sFrame.bitsLength = 15U;
 *        g_sFrame.bitBrs = 1U;
 *        g_sTxXfer.u8MsgBufIdx = (uint8_t)TX_MESSAGE_BUFFER_NUM;
 *        g_sTxXfer.psFrameFD = &g_sFrame;
 *        // Send node interrupt transfer
 *        FLEXCAN_TransferFDSendNonBlocking(&g_sFlexcanHandle, &g_sTxXfer);
 *     @endcode
 *
 *     Receive node
 *     @code
 *        flexcan_handle_t g_sFlexcanHandle;
 *        flexcan_config_t sFlexcanConfig;
 *        flexcan_fd_config_t sFDConfig;
 *        FLEXCAN_GetDefaultConfig(&sFlexcanConfig, EXAMPLE_CAN_CLK_FREQ);
 *        FLEXCAN_GetFDDefaultConfig(&sFDConfig);
 *        FLEXCAN_FDCalculateImprovedTimingValues(&sFlexcanConfig.sTimingConfig,
 *            &sFlexcanConfig.psFDConfig->sTimingConfig, sFlexcanConfig.u32BaudRateBps,
 *            sFlexcanConfig.psFDConfig->u32BaudRateBps, sFlexcanConfig.u32ClkFreqHz);
 *        sFlexcanConfig.psFDConfig = &sFDConfig;
 *        // Module initialization
 *        FLEXCAN_Init(CAN, &sFlexcanConfig);
 *        // Set up send transfer configuration
 *        flexcan_mb_transfer_t g_sTxXfer;
 *        flexcan_frame_t g_sFrame;
 *        // Create FlexCAN handle structure and set call back function.
 *        FLEXCAN_TransferCreateHandle(CAN, &g_sFlexcanHandle, flexcan_callback, NULL);
 *        // Set Rx Masking mechanism.
 *        FLEXCAN_SetRxMbGlobalMask(CAN, FLEXCAN_RX_MB_STD_MASK(g_u32RxIdentifier, 0, 0));
 *        // Setup Rx Message Buffer.
 *        sRxMbConfig.eFormat = kFLEXCAN_FrameFormatStandard;
 *        sRxMbConfig.eType   = kFLEXCAN_FrameTypeData;
 *        sRxMbConfig.u32Id   = FLEXCAN_ID_STD(g_u32RxIdentifier);
 *        // Clean Rx Message Buffer.
 *        FLEXCAN_SetFDRxMbConfig(CAN, RX_MESSAGE_BUFFER_NUM, &sRxMbConfig, true);
 *        g_sTxXfer.u8MsgBufIdx = (uint8_t)RX_MESSAGE_BUFFER_NUM;
 *        g_sTxXfer.psFrameFD = &g_sFrame;
 *        // Receive node interrupt transfer
 *        FLEXCAN_TransferFDSendNonBlocking(&g_sFlexcanHandle, &g_sTxXfer);
 *     @endcode
 *
 * @}
 */

/******************************************************************************
 * Definitions
 *****************************************************************************/

/*! @name Driver version */
/*@{*/
/*! @brief FlexCAN driver version 2.0.0. */
#define FSL_FLEXCAN_DRIVER_VERSION (MAKE_VERSION(2, 0, 0))
/*@}*/

#if !(defined(FLEXCAN_WAIT_TIMEOUT) && FLEXCAN_WAIT_TIMEOUT)
/* Define to 1000 means keep waiting 1000 times until the flag is assert/deassert.  */
#define FLEXCAN_WAIT_TIMEOUT (1000U)
#endif

/*! @brief FlexCAN Frame ID helper macro. */
#define FLEXCAN_ID_STD(id) \
    (((uint32_t)(((uint32_t)(id)) << CAN_ID_STD_SHIFT)) & CAN_ID_STD_MASK) /*!< Standard Frame ID helper macro. */
#define FLEXCAN_ID_EXT(id)                                \
    (((uint32_t)(((uint32_t)(id)) << CAN_ID_EXT_SHIFT)) & \
     (CAN_ID_EXT_MASK | CAN_ID_STD_MASK)) /*!< Extend Frame ID helper macro. */

/*! @brief FlexCAN Rx Message Buffer Mask helper macro. */
#define FLEXCAN_RX_MB_STD_MASK(id, rtr, ide)                                   \
    (((uint32_t)((uint32_t)(rtr) << 31) | (uint32_t)((uint32_t)(ide) << 30)) | \
     FLEXCAN_ID_STD(id)) /*!< Standard Rx Message Buffer Mask helper macro. */
#define FLEXCAN_RX_MB_EXT_MASK(id, rtr, ide)                                   \
    (((uint32_t)((uint32_t)(rtr) << 31) | (uint32_t)((uint32_t)(ide) << 30)) | \
     FLEXCAN_ID_EXT(id)) /*!< Extend Rx Message Buffer Mask helper macro. */

/*! @brief FlexCAN Rx FIFO Mask helper macro. */
#define FLEXCAN_RX_FIFO_STD_MASK_TYPE_A(id, rtr, ide)                          \
    (((uint32_t)((uint32_t)(rtr) << 31) | (uint32_t)((uint32_t)(ide) << 30)) | \
     (FLEXCAN_ID_STD(id) << 1)) /*!< Standard Rx FIFO Mask helper macro Type A helper macro. */
#define FLEXCAN_RX_FIFO_STD_MASK_TYPE_B_HIGH(id, rtr, ide)                     \
    (((uint32_t)((uint32_t)(rtr) << 31) | (uint32_t)((uint32_t)(ide) << 30)) | \
     (((uint32_t)(id)&0x7FF) << 19)) /*!< Standard Rx FIFO Mask helper macro Type B upper part helper macro. */
#define FLEXCAN_RX_FIFO_STD_MASK_TYPE_B_LOW(id, rtr, ide)                      \
    (((uint32_t)((uint32_t)(rtr) << 15) | (uint32_t)((uint32_t)(ide) << 14)) | \
     (((uint32_t)(id)&0x7FF) << 3)) /*!< Standard Rx FIFO Mask helper macro Type B lower part helper macro. */
#define FLEXCAN_RX_FIFO_STD_MASK_TYPE_C_HIGH(id) \
    (((uint32_t)(id)&0x7F8) << 21) /*!< Standard Rx FIFO Mask helper macro Type C upper part helper macro. */
#define FLEXCAN_RX_FIFO_STD_MASK_TYPE_C_MID_HIGH(id) \
    (((uint32_t)(id)&0x7F8) << 13) /*!< Standard Rx FIFO Mask helper macro Type C mid-upper part helper macro. */
#define FLEXCAN_RX_FIFO_STD_MASK_TYPE_C_MID_LOW(id) \
    (((uint32_t)(id)&0x7F8) << 5) /*!< Standard Rx FIFO Mask helper macro Type C mid-lower part helper macro. */
#define FLEXCAN_RX_FIFO_STD_MASK_TYPE_C_LOW(id) \
    (((uint32_t)(id)&0x7F8) >> 3) /*!< Standard Rx FIFO Mask helper macro Type C lower part helper macro. */
#define FLEXCAN_RX_FIFO_EXT_MASK_TYPE_A(id, rtr, ide)                          \
    (((uint32_t)((uint32_t)(rtr) << 31) | (uint32_t)((uint32_t)(ide) << 30)) | \
     (FLEXCAN_ID_EXT(id) << 1)) /*!< Extend Rx FIFO Mask helper macro Type A helper macro. */
#define FLEXCAN_RX_FIFO_EXT_MASK_TYPE_B_HIGH(id, rtr, ide)                        \
    (                                                                             \
        ((uint32_t)((uint32_t)(rtr) << 31) | (uint32_t)((uint32_t)(ide) << 30)) | \
        ((FLEXCAN_ID_EXT(id) & 0x1FFF8000)                                        \
         << 1)) /*!< Extend Rx FIFO Mask helper macro Type B upper part helper macro. */
#define FLEXCAN_RX_FIFO_EXT_MASK_TYPE_B_LOW(id, rtr, ide)                      \
    (((uint32_t)((uint32_t)(rtr) << 15) | (uint32_t)((uint32_t)(ide) << 14)) | \
     ((FLEXCAN_ID_EXT(id) & 0x1FFF8000) >>                                     \
      15)) /*!< Extend Rx FIFO Mask helper macro Type B lower part helper macro. */
#define FLEXCAN_RX_FIFO_EXT_MASK_TYPE_C_HIGH(id) \
    ((FLEXCAN_ID_EXT(id) & 0x1FE00000) << 3) /*!< Extend Rx FIFO Mask helper macro Type C upper part helper macro. */
#define FLEXCAN_RX_FIFO_EXT_MASK_TYPE_C_MID_HIGH(id) \
    ((FLEXCAN_ID_EXT(id) & 0x1FE00000) >>            \
     5) /*!< Extend Rx FIFO Mask helper macro Type C mid-upper part helper macro. */
#define FLEXCAN_RX_FIFO_EXT_MASK_TYPE_C_MID_LOW(id) \
    ((FLEXCAN_ID_EXT(id) & 0x1FE00000) >>           \
     13) /*!< Extend Rx FIFO Mask helper macro Type C mid-lower part helper macro. */
#define FLEXCAN_RX_FIFO_EXT_MASK_TYPE_C_LOW(id) \
    ((FLEXCAN_ID_EXT(id) & 0x1FE00000) >> 21) /*!< Extend Rx FIFO Mask helper macro Type C lower part helper macro. */

/*! @brief FlexCAN Rx FIFO Filter helper macro. */
#define FLEXCAN_RX_FIFO_STD_FILTER_TYPE_A(id, rtr, ide) \
    FLEXCAN_RX_FIFO_STD_MASK_TYPE_A(id, rtr, ide) /*!< Standard Rx FIFO Filter helper macro Type A helper macro. */
#define FLEXCAN_RX_FIFO_STD_FILTER_TYPE_B_HIGH(id, rtr, ide) \
    FLEXCAN_RX_FIFO_STD_MASK_TYPE_B_HIGH(                    \
        id, rtr, ide) /*!< Standard Rx FIFO Filter helper macro Type B upper part helper macro. */
#define FLEXCAN_RX_FIFO_STD_FILTER_TYPE_B_LOW(id, rtr, ide) \
    FLEXCAN_RX_FIFO_STD_MASK_TYPE_B_LOW(                    \
        id, rtr, ide) /*!< Standard Rx FIFO Filter helper macro Type B lower part helper macro. */
#define FLEXCAN_RX_FIFO_STD_FILTER_TYPE_C_HIGH(id) \
    FLEXCAN_RX_FIFO_STD_MASK_TYPE_C_HIGH(          \
        id) /*!< Standard Rx FIFO Filter helper macro Type C upper part helper macro. */
#define FLEXCAN_RX_FIFO_STD_FILTER_TYPE_C_MID_HIGH(id) \
    FLEXCAN_RX_FIFO_STD_MASK_TYPE_C_MID_HIGH(          \
        id) /*!< Standard Rx FIFO Filter helper macro Type C mid-upper part helper macro. */
#define FLEXCAN_RX_FIFO_STD_FILTER_TYPE_C_MID_LOW(id) \
    FLEXCAN_RX_FIFO_STD_MASK_TYPE_C_MID_LOW(          \
        id) /*!< Standard Rx FIFO Filter helper macro Type C mid-lower part helper macro. */
#define FLEXCAN_RX_FIFO_STD_FILTER_TYPE_C_LOW(id) \
    FLEXCAN_RX_FIFO_STD_MASK_TYPE_C_LOW(          \
        id) /*!< Standard Rx FIFO Filter helper macro Type C lower part helper macro.  */
#define FLEXCAN_RX_FIFO_EXT_FILTER_TYPE_A(id, rtr, ide) \
    FLEXCAN_RX_FIFO_EXT_MASK_TYPE_A(id, rtr, ide) /*!< Extend Rx FIFO Filter helper macro Type A helper macro. */
#define FLEXCAN_RX_FIFO_EXT_FILTER_TYPE_B_HIGH(id, rtr, ide) \
    FLEXCAN_RX_FIFO_EXT_MASK_TYPE_B_HIGH(                    \
        id, rtr, ide) /*!< Extend Rx FIFO Filter helper macro Type B upper part helper macro. */
#define FLEXCAN_RX_FIFO_EXT_FILTER_TYPE_B_LOW(id, rtr, ide) \
    FLEXCAN_RX_FIFO_EXT_MASK_TYPE_B_LOW(                    \
        id, rtr, ide) /*!< Extend Rx FIFO Filter helper macro Type B lower part helper macro. */
#define FLEXCAN_RX_FIFO_EXT_FILTER_TYPE_C_HIGH(id) \
    FLEXCAN_RX_FIFO_EXT_MASK_TYPE_C_HIGH(          \
        id) /*!< Extend Rx FIFO Filter helper macro Type C upper part helper macro.           */
#define FLEXCAN_RX_FIFO_EXT_FILTER_TYPE_C_MID_HIGH(id) \
    FLEXCAN_RX_FIFO_EXT_MASK_TYPE_C_MID_HIGH(          \
        id) /*!< Extend Rx FIFO Filter helper macro Type C mid-upper part helper macro. */
#define FLEXCAN_RX_FIFO_EXT_FILTER_TYPE_C_MID_LOW(id) \
    FLEXCAN_RX_FIFO_EXT_MASK_TYPE_C_MID_LOW(          \
        id) /*!< Extend Rx FIFO Filter helper macro Type C mid-lower part helper macro. */
#define FLEXCAN_RX_FIFO_EXT_FILTER_TYPE_C_LOW(id) \
    FLEXCAN_RX_FIFO_EXT_MASK_TYPE_C_LOW(id) /*!< Extend Rx FIFO Filter helper macro Type C lower part helper macro. */

/*!
 * @brief FlexCAN transfer status codes, used by bus operation APIs and transactional APIs as return value to indicate
 *        the current status as the API's execution result, or used in the callback to indicate transfer results.
 */
enum
{
    kStatus_FLEXCAN_TxBusy       = MAKE_STATUS(kStatusGroup_FLEXCAN, 0),   /*!< Tx Message Buffer is Busy. */
    kStatus_FLEXCAN_TxIdle       = MAKE_STATUS(kStatusGroup_FLEXCAN, 1),   /*!< Tx Message Buffer is Idle. */
    kStatus_FLEXCAN_TxSwitchToRx = MAKE_STATUS(kStatusGroup_FLEXCAN, 2),   /*!< Remote Message is send out and Message
                                                                               buffer changed to Receive one. */
    kStatus_FLEXCAN_RxBusy         = MAKE_STATUS(kStatusGroup_FLEXCAN, 3), /*!< Rx Message Buffer is Busy. */
    kStatus_FLEXCAN_RxIdle         = MAKE_STATUS(kStatusGroup_FLEXCAN, 4), /*!< Rx Message Buffer is Idle. */
    kStatus_FLEXCAN_RxOverflow     = MAKE_STATUS(kStatusGroup_FLEXCAN, 5), /*!< Rx Message Buffer is Overflowed. */
    kStatus_FLEXCAN_RxFifoBusy     = MAKE_STATUS(kStatusGroup_FLEXCAN, 6), /*!< Rx Message FIFO is Busy. */
    kStatus_FLEXCAN_RxFifoIdle     = MAKE_STATUS(kStatusGroup_FLEXCAN, 7), /*!< Rx Message FIFO is Idle. */
    kStatus_FLEXCAN_RxFifoOverflow = MAKE_STATUS(kStatusGroup_FLEXCAN, 8), /*!< Rx Message FIFO is overflowed. */
    kStatus_FLEXCAN_RxFifoWarning  = MAKE_STATUS(kStatusGroup_FLEXCAN, 9), /*!< Rx Message FIFO is almost overflowed. */
    kStatus_FLEXCAN_ErrorStatus    = MAKE_STATUS(kStatusGroup_FLEXCAN, 10), /*!< FlexCAN Module Error and Status. */
    kStatus_FLEXCAN_WakeUp         = MAKE_STATUS(kStatusGroup_FLEXCAN, 11), /*!< FlexCAN is waken up from STOP mode. */
    kStatus_FLEXCAN_UnHandled      = MAKE_STATUS(kStatusGroup_FLEXCAN, 12), /*!< UnHadled Interrupt asserted. */
    kStatus_FLEXCAN_RxRemote = MAKE_STATUS(kStatusGroup_FLEXCAN, 13), /*!< Rx Remote Message Received in Mail box. */
};

/*!
 * @brief @brief FlexCAN frame format.
 */
typedef enum _flexcan_frame_format
{
    kFLEXCAN_FrameFormatStandard = 0x0U, /*!< Standard frame format attribute. */
    kFLEXCAN_FrameFormatExtend   = 0x1U, /*!< Extend frame format attribute. */
} flexcan_frame_format_t;

/*!
 * @brief @brief FlexCAN frame type.
 */
typedef enum _flexcan_frame_type
{
    kFLEXCAN_FrameTypeData   = 0x0U, /*!< Data frame type attribute. */
    kFLEXCAN_FrameTypeRemote = 0x1U, /*!< Remote frame type attribute. */
} flexcan_frame_type_t;

/*!
 * @brief FlexCAN clock source.
 * @note The user must ensure the protocol engine clock tolerance according to the CAN Protocol standard (ISO 11898-1).
 */
typedef enum _flexcan_clock_source
{
    kFLEXCAN_ClkSrc0 = 0x0U, /*!< FlexCAN Protocol Engine clock selected by user as SRC == 0. */
    kFLEXCAN_ClkSrc1 = 0x1U, /*!< FlexCAN Protocol Engine clock selected by user as SRC == 1. */
} flexcan_clock_source_t;

/*!
 * @brief @brief FlexCAN wake up source.
 */
typedef enum _flexcan_wake_up_source
{
    kFLEXCAN_WakeupSrcUnfiltered = 0x0U, /*!< FlexCAN uses unfiltered Rx input to detect edge. */
    kFLEXCAN_WakeupSrcFiltered   = 0x1U, /*!< FlexCAN uses filtered Rx input to detect edge. */
} flexcan_wake_up_source_t;

/*!
 * @brief @brief FlexCAN Rx Fifo Filter type.
 */
typedef enum _flexcan_rx_fifo_filter_type
{
    kFLEXCAN_RxFifoFilterTypeA = 0x0U, /*!< One full ID (standard and extended) per ID Filter element. */
    kFLEXCAN_RxFifoFilterTypeB = 0x1U, /*!< Two full standard IDs or two partial 14-bit ID slices per
                                          ID Filter Table element. */
    kFLEXCAN_RxFifoFilterTypeC = 0x2U, /*!< Four partial 8-bit Standard or extended ID slices per ID
                                          Filter Table element. */
    kFLEXCAN_RxFifoFilterTypeD = 0x3U, /*!< All frames rejected. */
} flexcan_rx_fifo_filter_type_t;

#if (defined(FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE) && FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE)
/*!
 * @brief FlexCAN Message Buffer Data Size.
 */
typedef enum _flexcan_mb_size
{
    kFLEXCAN_8BperMB  = 0x0U, /*!< Selects 8 bytes per Message Buffer. */
    kFLEXCAN_16BperMB = 0x1U, /*!< Selects 16 bytes per Message Buffer. */
    kFLEXCAN_32BperMB = 0x2U, /*!< Selects 32 bytes per Message Buffer. */
    kFLEXCAN_64BperMB = 0x3U, /*!< Selects 64 bytes per Message Buffer. */
} flexcan_mb_size_t;
#endif

/*!
 * @brief FlexCAN Rx FIFO priority.
 *
 * The matching process starts from the Rx MB(or Rx FIFO) with higher priority.
 * If no MB(or Rx FIFO filter) is satisfied, the matching process goes on with
 * the Rx FIFO(or Rx MB) with lower priority.
 */
typedef enum _flexcan_rx_fifo_priority
{
    kFLEXCAN_RxFifoPriorityLow  = 0x0U, /*!< Matching process start from Rx Message Buffer first. */
    kFLEXCAN_RxFifoPriorityHigh = 0x1U, /*!< Matching process start from Rx FIFO first. */
} flexcan_rx_fifo_priority_t;

/*!
 * @brief FlexCAN interrupt configuration structure, default settings all disabled.
 *
 * This structure contains the settings for all of the FlexCAN Module interrupt configurations.
 * Note: FlexCAN Message Buffers and Rx FIFO have their own interrupts.
 */
enum _flexcan_interrupt_enable
{
    kFLEXCAN_BusOffInterruptEnable    = CAN_CTRL1_BOFFMSK_MASK, /*!< Bus Off interrupt. */
    kFLEXCAN_ErrorInterruptEnable     = CAN_CTRL1_ERRMSK_MASK,  /*!< Error interrupt. */
    kFLEXCAN_RxWarningInterruptEnable = CAN_CTRL1_RWRNMSK_MASK, /*!< Rx Warning interrupt. */
    kFLEXCAN_TxWarningInterruptEnable = CAN_CTRL1_TWRNMSK_MASK, /*!< Tx Warning interrupt. */
    kFLEXCAN_WakeUpInterruptEnable    = CAN_MCR_WAKMSK_MASK,    /*!< Wake Up interrupt. */
    kFLEXCAN_AllInterruptEnable =
        (kFLEXCAN_BusOffInterruptEnable | kFLEXCAN_ErrorInterruptEnable | kFLEXCAN_RxWarningInterruptEnable |
         kFLEXCAN_TxWarningInterruptEnable | kFLEXCAN_WakeUpInterruptEnable)
};

/*!
 * @brief FlexCAN status flags.
 *
 * This provides constants for the FlexCAN status flags for use in the FlexCAN functions.
 * Note: The CPU read action will clears all error flag in FlEXCAN_ErrorFlag.
 * @ref _flexcan_error_flags enumerations.
 */
enum _flexcan_status_flags
{
#if (defined(FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE) && FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE)
    kFLEXCAN_FDStuffingError = CAN_ESR1_STFERR_FAST_MASK,       /*!< Stuffing Error. */
    kFLEXCAN_FDFormError     = CAN_ESR1_FRMERR_FAST_MASK,       /*!< Form Error. */
    kFLEXCAN_FDCrcError      = CAN_ESR1_CRCERR_FAST_MASK,       /*!< Cyclic Redundancy Check Error. */
    kFLEXCAN_FDBit0Error     = CAN_ESR1_BIT0ERR_FAST_MASK,      /*!< Unable to send dominant bit. */
    kFLEXCAN_FDBit1Error     = (int)CAN_ESR1_BIT1ERR_FAST_MASK, /*!< Unable to send recessive bit. */
#endif
    kFLEXCAN_StuffingError = CAN_ESR1_STFERR_MASK,  /*!< Stuffing Error. */
    kFLEXCAN_FormError     = CAN_ESR1_FRMERR_MASK,  /*!< Form Error. */
    kFLEXCAN_CrcError      = CAN_ESR1_CRCERR_MASK,  /*!< Cyclic Redundancy Check Error. */
    kFLEXCAN_AckError      = CAN_ESR1_ACKERR_MASK,  /*!< Received no ACK on transmission. */
    kFLEXCAN_Bit0Error     = CAN_ESR1_BIT0ERR_MASK, /*!< Unable to send dominant bit. */
    kFLEXCAN_Bit1Error     = CAN_ESR1_BIT1ERR_MASK, /*!< Unable to send recessive bit. */
    kFLEXCAN_ErrorFlag     = (int)(                 /*!< All FlexCAN read clear Error Status. */
#if (defined(FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE) && FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE)
                               CAN_ESR1_STFERR_FAST_MASK | CAN_ESR1_FRMERR_FAST_MASK | CAN_ESR1_CRCERR_FAST_MASK |
                               CAN_ESR1_BIT0ERR_FAST_MASK | CAN_ESR1_BIT1ERR_FAST_MASK | CAN_ESR1_ERROVR_MASK |
#endif
                               CAN_ESR1_BIT1ERR_MASK | CAN_ESR1_BIT0ERR_MASK | CAN_ESR1_ACKERR_MASK |
                               CAN_ESR1_CRCERR_MASK | CAN_ESR1_FRMERR_MASK | CAN_ESR1_STFERR_MASK),
#if (defined(FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE) && FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE)
    kFLEXCAN_FDErrorIntFlag    = CAN_ESR1_ERRINT_FAST_MASK, /*!< FD frames Error Interrupt Flag. */
    kFLEXCAN_BusoffDoneIntFlag = CAN_ESR1_BOFFDONEINT_MASK, /*!< Bus Off Done Interrupt Flag. */
    kFLEXCAN_OverrunError      = CAN_ESR1_ERROVR_MASK,      /*!< Error Overrun Status. */
#endif
    kFLEXCAN_TxWarningIntFlag     = CAN_ESR1_TWRNINT_MASK, /*!< Tx Warning Interrupt Flag. */
    kFLEXCAN_RxWarningIntFlag     = CAN_ESR1_RWRNINT_MASK, /*!< Rx Warning Interrupt Flag. */
    kFLEXCAN_BusOffIntFlag        = CAN_ESR1_BOFFINT_MASK, /*!< Bus Off Interrupt Flag. */
    kFLEXCAN_ErrorIntFlag         = CAN_ESR1_ERRINT_MASK,  /*!< Error Interrupt Flag. */
    kFLEXCAN_WakeUpIntFlag        = CAN_ESR1_WAKINT_MASK,  /*!< Wake-Up Interrupt Flag. */
    kFLEXCAN_SynchFlag            = CAN_ESR1_SYNCH_MASK,   /*!< CAN Synchronization Status Flag. */
    kFLEXCAN_TxErrorWarningFlag   = CAN_ESR1_TXWRN_MASK,   /*!< Tx Error Warning Status Flag. */
    kFLEXCAN_RxErrorWarningFlag   = CAN_ESR1_RXWRN_MASK,   /*!< Rx Error Warning Status Flag. */
    kFLEXCAN_IdleFlag             = CAN_ESR1_IDLE_MASK,    /*!< CAN IDLE Status Flag. */
    kFLEXCAN_FaultConfinementFlag = CAN_ESR1_FLTCONF_MASK, /*!< Fault Confinement Status Flag. */
    kFLEXCAN_TransmittingFlag     = CAN_ESR1_TX_MASK,      /*!< FlexCAN In Transmission Status Flag. */
    kFLEXCAN_ReceivingFlag        = CAN_ESR1_RX_MASK,      /*!< FlexCAN In Reception Status Flag. */
    /*! All status/interrupt flags which are write clearable. */
    kFLEXCAN_StatusAllFlags = (
#if (defined(FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE) && FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE)
        kFLEXCAN_FDErrorIntFlag | kFLEXCAN_BusoffDoneIntFlag | kFLEXCAN_OverrunError |
#endif
        kFLEXCAN_TxWarningIntFlag | kFLEXCAN_RxWarningIntFlag | kFLEXCAN_BusOffIntFlag | kFLEXCAN_ErrorIntFlag |
        kFLEXCAN_WakeUpIntFlag),
};

/*!
 * @brief FlexCAN Rx FIFO status flags.
 *
 * The FlexCAN Rx FIFO Status enumerations are used to determine the status of the
 * Rx FIFO. Because Rx FIFO occupy the MB0 ~ MB7 (Rx Fifo filter also occupies
 * more Message Buffer space), Rx FIFO status flags are mapped to the corresponding
 * Message Buffer status flags.
 */
enum _flexcan_mb_flags
{
    kFLEXCAN_RxFifoOverflowFlag = CAN_IFLAG1_BUF7I_MASK, /*!< Rx FIFO overflow flag. */
    kFLEXCAN_RxFifoWarningFlag  = CAN_IFLAG1_BUF6I_MASK, /*!< Rx FIFO almost full flag. */
    kFLEXCAN_RxFifoFrameAvlFlag = CAN_IFLAG1_BUF5I_MASK, /*!< Frames available in Rx FIFO flag. */
};

#if defined(__CC_ARM)
#pragma anon_unions
#endif
/*!
 * @brief FlexCAN message frame structure.
 */
typedef struct _flexcan_frame
{
    struct
    {
        uint32_t bitsTimestamp : 16; /*!< FlexCAN internal Free-Running Counter Time Stamp. */
        uint32_t bitsLength : 4;     /*!< CAN frame payload length in bytes(Range: 0~8). */
        uint32_t bitType : 1;        /*!< CAN Frame Type(DATA or REMOTE). */
        uint32_t bitFormat : 1;      /*!< CAN Frame Identifier(STD or EXT format). */
        uint32_t : 1;                /*!< Reserved. */
        uint32_t bitsIdHit : 9;      /*!< CAN Rx FIFO filter hit id(This value is only used in Rx FIFO receive mode). */
    };
    struct
    {
        uint32_t bitsId : 29; /*!< CAN Frame Identifier, should be set using FLEXCAN_ID_EXT() or
                                 FLEXCAN_ID_STD() macro. */
        uint32_t : 3;         /*!< Reserved. */
    };
    union
    {
        struct
        {
            uint32_t u32DataWord0; /*!< CAN Frame payload word0. */
            uint32_t u32DataWord1; /*!< CAN Frame payload word1. */
        };
        struct
        {
            uint8_t u8DataByte3; /*!< CAN Frame payload byte3. */
            uint8_t u8DataByte2; /*!< CAN Frame payload byte2. */
            uint8_t u8DataByte1; /*!< CAN Frame payload byte1. */
            uint8_t u8DataByte0; /*!< CAN Frame payload byte0. */
            uint8_t u8DataByte7; /*!< CAN Frame payload byte7. */
            uint8_t u8DataByte6; /*!< CAN Frame payload byte6. */
            uint8_t u8DataByte5; /*!< CAN Frame payload byte5. */
            uint8_t u8DataByte4; /*!< CAN Frame payload byte4. */
        };
    };
} flexcan_frame_t;

#if (defined(FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE) && FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE)
/*! @brief CAN FDmessage frame structure. */
typedef struct _flexcan_fd_frame
{
    struct
    {
        uint32_t bitsTimestamp : 16; /*!< FlexCAN internal Free-Running Counter Time Stamp. */
        uint32_t bitsLength : 4;     /*!< CAN frame payload length in bytes(Range: 0~8). */
        uint32_t bitType : 1;        /*!< CAN Frame Type(DATA or REMOTE). */
        uint32_t bitFormat : 1;      /*!< CAN Frame Identifier(STD or EXT format). */
        uint32_t bitSrr : 1;         /*!< Substitute Remote request. */
        uint32_t : 1;
        uint32_t bitsCode : 4; /*!< Message Buffer Code. */
        uint32_t : 1;
        uint32_t bitEsi : 1; /*!< Error State Indicator. */
        uint32_t bitBrs : 1; /*!< Bit Rate Switch. */
        uint32_t bitEdl : 1; /*!< Extended Data Length. */
    };
    struct
    {
        uint32_t bitsId : 29; /*!< CAN Frame Identifier, should be set using FLEXCAN_ID_EXT()
                            or FLEXCAN_ID_STD() macro. */
        uint32_t : 3;         /*!< Reserved. */
    };
    union
    {
        struct
        {
            uint32_t u32DataWord[16]; /*!< CAN FD Frame payload, 16 double word maximum. */
        };
        /* Note: the maximum databyte* below is actually 64, user can add them if needed,
           or just use dataWord[*] instead. */
        struct
        {
            uint8_t u8DataByte3; /*!< CAN Frame payload byte3. */
            uint8_t u8DataByte2; /*!< CAN Frame payload byte2. */
            uint8_t u8DataByte1; /*!< CAN Frame payload byte1. */
            uint8_t u8DataByte0; /*!< CAN Frame payload byte0. */
            uint8_t u8DataByte7; /*!< CAN Frame payload byte7. */
            uint8_t u8DataByte6; /*!< CAN Frame payload byte6. */
            uint8_t u8DataByte5; /*!< CAN Frame payload byte5. */
            uint8_t u8DataByte4; /*!< CAN Frame payload byte4. */
        };
    };
} flexcan_fd_frame_t;
#endif

/*! @brief FlexCAN protocol timing characteristic configuration structure. */
typedef struct _flexcan_timing_config
{
    uint16_t u16PreDivider; /*!< Clock Pre-scaler Division Factor. */
    uint8_t u8RJumpWidth;   /*!< Re-sync Jump Width. */
    uint8_t u8PhaseSeg1;    /*!< Phase Segment 1. */
    uint8_t u8PhaseSeg2;    /*!< Phase Segment 2. */
    uint8_t u8PropSeg;      /*!< Propagation Segment. */
} flexcan_timing_config_t;

/*!
 * @brief Configuration for the Flexcan CAN FD mode. It only cover FD related parts.
 *
 * It is used as member of @ref _flexcan_config to do the CAN FD specific init on init
 * this peripheral.
 */
typedef struct _flexcan_fd_config
{
    uint32_t u32BaudRateBps;               /* BaudRate after the Bit Rate Switch*/
    flexcan_timing_config_t sTimingConfig; /* Timing configuration for CAN FD transaction after BRS */
    flexcan_mb_size_t eMsgSize;            /* Size of the message buffer payload */
    bool bEnableTxDelayCompensation;       /* Enable/Disable transmit delay compensation */
    bool bEnableBitRateSwitch;             /* Enable/disable feature of bit rate switch */
} flexcan_fd_config_t;

/*! @brief FlexCAN module configuration structure. */
typedef struct _flexcan_config
{
    /* Clock and Timing Config */
    uint32_t u32BaudRateBps;               /*!< FlexCAN baud rate in bps. */
    uint32_t u32ClkFreqHz;                 /*!< Clock Frequency */
    flexcan_timing_config_t sTimingConfig; /* Protocol timing . */
    flexcan_clock_source_t eClkSrc;        /*!< Clock source for FlexCAN Protocol Engine. */

    /* Message Buffer Configuration */
    uint8_t u8MaxMsgBufNum;  /*!< The maximum number of Message Buffers used by user. */
    bool bEnableIndividMask; /*!< Enable or Disable Rx Individual Mask. */

    /* Wake Up Config */
    flexcan_wake_up_source_t eWakeupSrc; /*!< Wake up source selection. */
    bool bEnableSelfWakeup;              /*!< Enable or Disable Self Wakeup Mode. */
    bool bEnableLoopBack;                /*!< Enable or Disable Loop Back Self Test Mode. */
    bool bEnableTimerSync;               /*!< Enable or Disable Timer Synchronization. */
    bool bDisableSelfReception;          /*!< Enable or Disable Self Reflection. */
    bool bEnableListenOnlyMode;          /*!< Enable or Disable Listen Only Mode. */
#if (defined(FSL_FEATURE_FLEXCAN_HAS_DOZE_MODE_SUPPORT) && FSL_FEATURE_FLEXCAN_HAS_DOZE_MODE_SUPPORT)
    bool bEnableDoze; /*!< Enable or Disable Doze Mode. */
#endif

#if (defined(FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE) && FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE)
    /* Flexcan FD configuration */
    flexcan_fd_config_t *psFDConfig; /* Flexcan FD configuration*/
#endif
} flexcan_config_t;

/*!
 * @brief FlexCAN Receive Message Buffer configuration structure
 *
 * This structure is used as the parameter of FLEXCAN_SetRxMbConfig() function.
 * The FLEXCAN_SetRxMbConfig() function is used to configure FlexCAN Receive
 * Message Buffer. The function abort previous receiving process, clean the
 * Message Buffer and activate the Rx Message Buffer using given Message Buffer
 * setting.
 */
typedef struct _flexcan_rx_mb_config
{
    uint32_t u32Id;                 /*!< CAN Message Buffer Frame Identifier, should be set using
                                      FLEXCAN_ID_EXT() or FLEXCAN_ID_STD() macro. */
    flexcan_frame_format_t eFormat; /*!< CAN Frame Identifier format(Standard of Extend). */
    flexcan_frame_type_t eType;     /*!< CAN Frame Type(Data or Remote). */
} flexcan_rx_mb_config_t;

/*! @brief FlexCAN Rx FIFO configuration structure. */
typedef struct _flexcan_rx_fifo_config
{
    uint32_t *pu32IdFilterTable;                 /*!< Pointer to the FlexCAN Rx FIFO identifier filter table. */
    uint8_t u8IdFilterNum;                       /*!< The quantity of filter elements. */
    flexcan_rx_fifo_filter_type_t eIdFilterType; /*!< The FlexCAN Rx FIFO Filter type. */
    flexcan_rx_fifo_priority_t ePriority;        /*!< The FlexCAN Rx FIFO receive priority. */
} flexcan_rx_fifo_config_t;

/*! @brief FlexCAN Message Buffer transfer. */
typedef struct _flexcan_mb_transfer
{
#if (defined(FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE) && FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE)
    flexcan_fd_frame_t *psFrameFD;
#endif
    flexcan_frame_t *psFrame; /*!< The buffer of CAN Message to be transfer. */
    uint8_t u8MsgBufIdx;      /*!< The index of Message buffer used to transfer Message. */
} flexcan_mb_transfer_t;

/*! @brief FlexCAN Rx FIFO transfer. */
typedef struct _flexcan_fifo_transfer
{
    flexcan_frame_t *psFrame; /*!< The buffer of CAN Message to be received from Rx FIFO. */
} flexcan_fifo_transfer_t;

/*! @brief FlexCAN handle structure definition. */
typedef struct _flexcan_handle flexcan_handle_t;

/*! @brief FlexCAN transfer callback function.
 *
 *  The FlexCAN transfer callback returns a value from the underlying layer.
 *  If the status equals to kStatus_FLEXCAN_ErrorStatus, the result parameter is the Content of
 *  FlexCAN status register which can be used to get the working status(or error status) of FlexCAN module.
 *  If the status equals to other FlexCAN Message Buffer transfer status, the result is the index of
 *  Message Buffer that generate transfer event.
 *  If the status equals to other FlexCAN Message Buffer transfer status, the result is meaningless and should be
 *  Ignored.
 */
typedef void (*flexcan_transfer_callback_t)(flexcan_handle_t *psHandle,
                                            status_t status,
                                            uint32_t result,
                                            void *pUserData);

/*! @brief FlexCAN handle structure. */
struct _flexcan_handle
{
    CAN_Type *base;                         /* Base address of the CAN Peripheral */
    flexcan_transfer_callback_t pfCallback; /*!< Callback function. */
    void *pUserData;                        /*!< FlexCAN callback function parameter.*/
    flexcan_frame_t *volatile psMbFrameBufs[CAN_WORD1_COUNT];
#if (defined(FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE) && FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE)
    flexcan_fd_frame_t *volatile psFDMbFrameBufs[CAN_WORD1_COUNT];
#endif
    /*!< The buffer for received data from Message Buffers. */
    flexcan_frame_t *volatile psRxFifoFrameBuf;       /*!< The buffer for received data from Rx FIFO. */
    volatile uint8_t u8MsgBufStates[CAN_WORD1_COUNT]; /*!< Message Buffer transfer state. */
    volatile uint8_t u8RxFifoState;                   /*!< Rx FIFO transfer state. */
    volatile uint32_t u32TimeStamps[CAN_WORD1_COUNT]; /*!< Mailbox transfer timestamp. */
};

/******************************************************************************
 * API
 *****************************************************************************/

#if defined(__cplusplus)
extern "C" {
#endif

/*!
 * @name Unsorted @todo
 * @{
 */

/*!
 * @brief Get the FlexCAN instance from peripheral base address.
 *
 * @param base FlexCAN peripheral base address.
 * @return FlexCAN instance.
 */
uint32_t FLEXCAN_GetInstance(CAN_Type *base);

/* @} */

/*!
 * @name Initialization and deinitialization
 * @{
 */

/*!
 * @brief Initializes a FlexCAN instance with classic / FD mode supported.
 *
 * This function initializes the FlexCAN module with user-defined settings.
 * User can call the FELXCAN_GetDefaultConfig function an starting point for
 * the needed init configuration structure.
 *
 * @note If user want to initialize the peripheral in CAN FD mode, user can
 * call the FLEXCAN_GetFDDefaultConfig to get the @ref _flexcan_fd_config_t
 * and assign the address of the data structure to the member psFDConfig of
 * @ref _flexcan_config_t
 *
 * @param base FlexCAN peripheral base address.
 * @param psConfig Pointer to the user-defined configuration structure.
 */
void FLEXCAN_Init(CAN_Type *base, const flexcan_config_t *psConfig);

/*!
 * @brief De-initializes a FlexCAN instance.
 *
 * This function disables the FlexCAN module clock and sets all register values
 * to the reset value.
 *
 * @param base FlexCAN peripheral base address.
 */
void FLEXCAN_Deinit(CAN_Type *base);

/*!
 * @brief Gets the default configuration structure.
 *
 * This function initializes the FlexCAN configuration structure to default values. The default
 * values are as follows. User is requested to provide the clock frequency for the peripheral.
 *
 * @note By default, CAN FD mode is disabled and not configured.
 *
 * @code
    psConfig->u32ClkFreqHz   = u32ClkFreqHz;
    psConfig->eClkSrc        = kFLEXCAN_ClkSrc0;
    psConfig->u32BaudRateBps = 1000000U;
    psConfig->u8MaxMsgBufNum        = 16;
    psConfig->bEnableLoopBack       = false;
    psConfig->bEnableTimerSync      = true;
    psConfig->bEnableSelfWakeup     = false;
    psConfig->eWakeupSrc            = kFLEXCAN_WakeupSrcUnfiltered;
    psConfig->bEnableIndividMask    = false;
    psConfig->bDisableSelfReception = false;
    psConfig->bEnableListenOnlyMode = false;
#if (defined(FSL_FEATURE_FLEXCAN_HAS_DOZE_MODE_SUPPORT) && FSL_FEATURE_FLEXCAN_HAS_DOZE_MODE_SUPPORT)
    psConfig->bEnableDoze = false;
#endif
    psConfig->sTimingConfig.u8PhaseSeg1  = 3;
    psConfig->sTimingConfig.u8PhaseSeg2  = 2;
    psConfig->sTimingConfig.u8PropSeg    = 1;
    psConfig->sTimingConfig.u8RJumpWidth = 1;
    psConfig->psFDConfig = NULL;
   @endcode
 *
 * @param psConfig Pointer to the FlexCAN configuration structure.
 * @param u32ClkFreqHz Flexcan peripheral clock
 */
void FLEXCAN_GetDefaultConfig(flexcan_config_t *psConfig, uint32_t u32ClkFreqHz);

#if (defined(FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE) && FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE)
/*!
 * @brief Gets the default configuration structure for Flexcan FD mode.
 *
 * The function provided the default value of the data structure as code below
 *
 * @code
    psConfig->u32BaudRateBps = 2000000U;
    psConfig->sTimingConfig.u8PhaseSeg1 = 3;
    psConfig->sTimingConfig.u8PhaseSeg2 = 3;
    psConfig->sTimingConfig.u8PropSeg   = 1;
    psConfig->sTimingConfig.u8RJumpWidth = 1;
    psConfig->eMsgSize = kFLEXCAN_64BperMB;
    psConfig->bEnableTxDelayCompensation = true;
    psConfig->bEnableBitRateSwitch = true;
   @endcode
 *
 * @param psConfig          Pointer to the FlexCAN configuration structure.
 */
void FLEXCAN_GetFDDefaultConfig(flexcan_fd_config_t *psConfig);
#endif
/* @} */

/*!
 * @name Freeze Mode Operation
 * @{
 */

/*!
 * @brief Enter FlexCAN Freeze Mode.
 *
 * This function makes the FlexCAN work under Freeze Mode.
 *
 * @param base FlexCAN peripheral base address.
 */
void FLEXCAN_EnterFreezeMode(CAN_Type *base);

/*!
 * @brief Exit FlexCAN Freeze Mode.
 *
 * This function makes the FlexCAN leave Freeze Mode.
 *
 * @param base FlexCAN peripheral base address.
 */
void FLEXCAN_ExitFreezeMode(CAN_Type *base);
/* @} */

/*!
 * @name Timing Calculation Helper Functions
 * @{
 */
#if (defined(FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE) && FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE)
/*!
 * @brief Calculates the improved timing values by specific baudrates for CANFD
 *
 * @param psTimingConfig Pointer to the FlexCAN timing configuration structure.
 * @param psFDTimingConfig Pointer to the FlexCAN FD timing configuration structure.
 * @param u32BaudRateBps  The CANFD bus control speed in bps defined by user
 * @param u32FDBaudRateBps  The CANFD bus data speed in bps defined by user
 * @param u32SrcClkHz The Source clock data speed in bps. Zero to disable baudrate switching
 * @param psTimingConfig Pointer to the FlexCAN timing configuration structure.
 *
 * @return TRUE if timing configuration found, FALSE if failed to find configuration
 */
bool FLEXCAN_FDCalculateImprovedTimingValues(flexcan_timing_config_t *psTimingConfig,
                                             flexcan_timing_config_t *psFDTimingConfig,
                                             uint32_t u32BaudRateBps,
                                             uint32_t u32FDBaudRateBps,
                                             uint32_t u32SrcClkHz);
#endif

/*!
 * @brief Calculates the improved timing values by specific baudrates for classical CAN
 *
 * @param psTimingConfig Pointer to the FlexCAN timing configuration structure.
 * @param u32BaudRateBps The classical CAN speed in bps defined by user
 * @param u32SrcClkHz The Source clock data speed in bps. Zero to disable baudrate switching
 *
 * @return TRUE if timing configuration found, FALSE if failed to find configuration
 */
bool FLEXCAN_CalculateImprovedTimingValues(flexcan_timing_config_t *psTimingConfig,
                                           uint32_t u32BaudRateBps,
                                           uint32_t u32SrcClkHz);

/* @} */

/*!
 * @name Timing Configuration
 * @{
 */

#if (defined(FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE) && FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE)
/*!
 * @brief Sets the FlexCAN FD protocol timing characteristic.
 *
 * This function gives user settings to CAN bus timing characteristic.
 * The function is for an experienced user. For less experienced users, call
 * the FLEXCAN_Init() and fill the baud rate field with a desired value.
 * This provides the default timing characteristics to the module.
 *
 * Note that calling FLEXCAN_SetFDTimingConfig() overrides the baud rate set
 * in FLEXCAN_Init().
 *
 * @param base FlexCAN peripheral base address.
 * @param psConfig Pointer to the timing configuration structure.
 */
void FLEXCAN_SetFDTimingConfig(CAN_Type *base, const flexcan_timing_config_t *psConfig);
#endif

/*!
 * @brief Sets the FlexCAN protocol timing characteristic.
 *
 * This function gives user settings to CAN bus timing characteristic.
 * The function is for an experienced user. For less experienced users, call
 * the FLEXCAN_Init() and fill the baud rate field with a desired value.
 * This provides the default timing characteristics to the module.
 *
 * Note that calling FLEXCAN_SetTimingConfig() overrides the baud rate set
 * in FLEXCAN_Init().
 *
 * @param base FlexCAN peripheral base address.
 * @param psConfig Pointer to the timing configuration structure.
 */
void FLEXCAN_SetTimingConfig(CAN_Type *base, const flexcan_timing_config_t *psConfig);

/* @} */

/*!
 * @name Message Buffer Configuration
 * @{
 */
/*!
 * @brief Sets the FlexCAN receive message buffer global mask.
 *
 * This function sets the global mask for the FlexCAN message buffer in a matching process.
 * The configuration is only effective when the Rx individual mask is disabled in the FLEXCAN_Init().
 *
 * @param base FlexCAN peripheral base address.
 * @param u32RecMsgBufs Rx Message Buffer Global Mask value.
 */
void FLEXCAN_SetRxMbGlobalMask(CAN_Type *base, uint32_t u32RecMsgBufs);

/*!
 * @brief Sets the FlexCAN receive FIFO global mask.
 *
 * This function sets the global mask for FlexCAN FIFO in a matching process.
 *
 * @param base FlexCAN peripheral base address.
 * @param u32RecFifos Rx Fifo Global Mask value.
 */
void FLEXCAN_SetRxFifoGlobalMask(CAN_Type *base, uint32_t u32RecFifos);

/*!
 * @brief Sets the FlexCAN receive individual mask.
 *
 * This function sets the individual mask for the FlexCAN matching process.
 * The configuration is only effective when the Rx individual mask is enabled in the FLEXCAN_Init().
 * If the Rx FIFO is disabled, the individual mask is applied to the corresponding Message Buffer.
 * If the Rx FIFO is enabled, the individual mask for Rx FIFO occupied Message Buffer is applied to
 * the Rx Filter with the same index. Note that only the first 32
 * individual masks can be used as the Rx FIFO filter mask.
 *
 * @param base FlexCAN peripheral base address.
 * @param u8MaskIdx The Index of individual Mask.
 * @param u32Mask Rx Individual Mask value.
 */
void FLEXCAN_SetRxIndividualMask(CAN_Type *base, uint8_t u8MaskIdx, uint32_t u32Mask);

/*!
 * @brief Configures a FlexCAN transmit message buffer.
 *
 * This function aborts the previous transmission, cleans the Message Buffer, and
 * configures it as a Transmit Message Buffer.
 *
 * @param base FlexCAN peripheral base address.
 * @param u8MsgBufIdx The Message Buffer index.
 * @param bEnable Enable/disable Tx Message Buffer.
 *               - true: Enable Tx Message Buffer.
 *               - false: Disable Tx Message Buffer.
 */
void FLEXCAN_SetTxMbConfig(CAN_Type *base, uint8_t u8MsgBufIdx, bool bEnable);

#if (defined(FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE) && FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE)
/*!
 * @brief Configures a FlexCAN transmit message buffer.
 *
 * This function aborts the previous transmission, cleans the Message Buffer, and
 * configures it as a Transmit Message Buffer.
 *
 * @param base FlexCAN peripheral base address.
 * @param u8MsgBufIdx The Message Buffer index.
 * @param bEnable Enable/disable Tx Message Buffer.
 *               - true: Enable Tx Message Buffer.
 *               - false: Disable Tx Message Buffer.
 */
void FLEXCAN_SetFDTxMbConfig(CAN_Type *base, uint8_t u8MsgBufIdx, bool bEnable);
#endif

/*!
 * @brief Configures a FlexCAN Receive Message Buffer.
 *
 * This function cleans a FlexCAN build-in Message Buffer and configures it
 * as a Receive Message Buffer.
 *
 * @param base FlexCAN peripheral base address.
 * @param u8MsgBufIdx The Message Buffer index.
 * @param psRxMsgBufConfig Pointer to the FlexCAN Message Buffer configuration structure.
 * @param bEnable Enable/disable Rx Message Buffer.
 *               - true: Enable Rx Message Buffer.
 *               - false: Disable Rx Message Buffer.
 */
void FLEXCAN_SetRxMbConfig(CAN_Type *base,
                           uint8_t u8MsgBufIdx,
                           const flexcan_rx_mb_config_t *psRxMsgBufConfig,
                           bool bEnable);

#if (defined(FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE) && FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE)
/*!
 * @brief Configures a FlexCAN Receive Message Buffer.
 *
 * This function cleans a FlexCAN build-in Message Buffer and configures it
 * as a Receive Message Buffer.
 *
 * @param base FlexCAN peripheral base address.
 * @param u8MsgBufIdx The Message Buffer index.
 * @param psRxMsgBufConfig Pointer to the FlexCAN Message Buffer configuration structure.
 * @param bEnable Enable/disable Rx Message Buffer.
 *               - true: Enable Rx Message Buffer.
 *               - false: Disable Rx Message Buffer.
 */
void FLEXCAN_SetFDRxMbConfig(CAN_Type *base,
                             uint8_t u8MsgBufIdx,
                             const flexcan_rx_mb_config_t *psRxMsgBufConfig,
                             bool bEnable);
#endif

/*!
 * @brief Configures the FlexCAN Rx FIFO.
 *
 * This function configures the Rx FIFO with given Rx FIFO configuration.
 *
 * @param base FlexCAN peripheral base address.
 * @param psRxFifoConfig Pointer to the FlexCAN Rx FIFO configuration structure.
 * @param bEnable Enable/disable Rx FIFO.
 *               - true: Enable Rx FIFO.
 *               - false: Disable Rx FIFO.
 */
void FLEXCAN_SetRxFifoConfig(CAN_Type *base, const flexcan_rx_fifo_config_t *psRxFifoConfig, bool bEnable);

/* @} */

/*!
 * @name Status Interface
 * @{
 */

/*!
 * @brief Gets the FlexCAN module interrupt flags.
 *
 * This function gets all FlexCAN status flags. The flags are returned as the logical
 * OR value of the enumerators @ref _flexcan_status_flags. To check the specific status,
 * compare the return value with enumerators in @ref _flexcan_status_flags.
 *
 * @param base FlexCAN peripheral base address.
 * @return FlexCAN status flags which are ORed by the enumerators in the @ref _flexcan_status_flags.
 */
static inline uint32_t FLEXCAN_GetStatusFlags(CAN_Type *base)
{
    return base->ESR1;
}

/*!
 * @brief Clears status flags with the provided mask.
 *
 * This function clears the FlexCAN status flags with a provided mask. An automatically cleared flag
 * can't be cleared by this function.
 *
 * @param base FlexCAN peripheral base address.
 * @param u32StatusFlags The status flags to be cleared, it is logical OR value of @ref _flexcan_status_flags.
 */
static inline void FLEXCAN_ClearStatusFlags(CAN_Type *base, uint32_t u32StatusFlags)
{
    /* Write 1 to clear status flag. */
    base->ESR1 = u32StatusFlags;
}

/*!
 * @brief Gets the FlexCAN Bus Error Counter value.
 *
 * This function gets the FlexCAN Bus Error Counter value for both Tx and
 * Rx direction. These values may be needed in the upper layer error handling.
 *
 * @param base FlexCAN peripheral base address.
 * @param pu8TxErrBuf Buffer to store Tx Error Counter value.
 * @param pu8RxErrBuf Buffer to store Rx Error Counter value.
 */
static inline void FLEXCAN_GetBusErrCount(CAN_Type *base, uint8_t *pu8TxErrBuf, uint8_t *pu8RxErrBuf)
{
    if (NULL != pu8TxErrBuf)
    {
        *pu8TxErrBuf = (uint8_t)((base->ECR & CAN_ECR_TXERRCNT_MASK) >> CAN_ECR_TXERRCNT_SHIFT);
    }

    if (NULL != pu8RxErrBuf)
    {
        *pu8RxErrBuf = (uint8_t)((base->ECR & CAN_ECR_RXERRCNT_MASK) >> CAN_ECR_RXERRCNT_SHIFT);
    }
}

/* @} */

/*!
 * @name Message Buffer Status Get/Clear Interfaces
 * @{
 */

/*!
 * @brief Gets the FlexCAN Message Buffer interrupt flags.
 *
 * This function gets the interrupt flags of a given Message Buffers.
 *
 * @param base FlexCAN peripheral base address.
 * @param mask The ORed FlexCAN Message Buffer mask.
 * @return The status of given Message Buffers.
 */
#if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0)
static inline uint64_t FLEXCAN_GetMbStatusFlags(CAN_Type *base, uint64_t mask)
#else
static inline uint32_t FLEXCAN_GetMbStatusFlags(CAN_Type *base, uint32_t mask)
#endif
{
#if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0)
    uint64_t tempflag = (uint64_t)base->IFLAG1;
    return (tempflag | (((uint64_t)base->IFLAG2) << 32)) & mask;
#else
    return (base->IFLAG1 & mask);
#endif
}

/*!
 * @brief Clears the FlexCAN Message Buffer interrupt flags.
 *
 * This function clears the interrupt flags of a given Message Buffers.
 *
 * @param base FlexCAN peripheral base address.
 * @param mask The ORed FlexCAN Message Buffer mask.
 */
#if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0)
static inline void FLEXCAN_ClearMbStatusFlags(CAN_Type *base, uint64_t mask)
#else
static inline void FLEXCAN_ClearMbStatusFlags(CAN_Type *base, uint32_t mask)
#endif
{
#if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0)
    base->IFLAG1 = (uint32_t)(mask & 0xFFFFFFFFU);
    base->IFLAG2 = (uint32_t)(mask >> 32);
#else
    base->IFLAG1 = mask;
#endif
}

/* @} */

/*!
 * @name Interrupt Interfaces
 * @{
 */

/*!
 * @brief Enables FlexCAN interrupts according to the provided mask.
 *
 * This function enables the FlexCAN interrupts according to the provided mask. The mask
 * is a logical OR of enumeration members, see @ref _flexcan_interrupt_enable.
 *
 * @param base FlexCAN peripheral base address.
 * @param u32InterruptFlags The interrupts to enable. Logical OR of @ref _flexcan_interrupt_enable.
 */
static inline void FLEXCAN_EnableInterrupts(CAN_Type *base, uint32_t u32InterruptFlags)
{
    /* Solve Wake Up Interrupt. */
    if ((uint32_t)kFLEXCAN_WakeUpInterruptEnable == (u32InterruptFlags & (uint32_t)kFLEXCAN_WakeUpInterruptEnable))
    {
        base->MCR |= CAN_MCR_WAKMSK_MASK;
    }

    /* Solve others. */
    base->CTRL1 |= (u32InterruptFlags & (~((uint32_t)kFLEXCAN_WakeUpInterruptEnable)));
}

/*!
 * @brief Disables FlexCAN interrupts according to the provided mask.
 *
 * This function disables the FlexCAN interrupts according to the provided mask. The mask
 * is a logical OR of enumeration members, see @ref _flexcan_interrupt_enable.
 *
 * @param base FlexCAN peripheral base address.
 * @param u32InterruptFlags The interrupts to disable. Logical OR of @ref _flexcan_interrupt_enable.
 */
static inline void FLEXCAN_DisableInterrupts(CAN_Type *base, uint32_t u32InterruptFlags)
{
    /* Solve Wake Up Interrupt. */
    if ((uint32_t)kFLEXCAN_WakeUpInterruptEnable == (u32InterruptFlags & (uint32_t)kFLEXCAN_WakeUpInterruptEnable))
    {
        base->MCR &= ~CAN_MCR_WAKMSK_MASK;
    }

    /* Solve others. */
    base->CTRL1 &= ~(u32InterruptFlags & (~((uint32_t)kFLEXCAN_WakeUpInterruptEnable)));
}

/* @} */

/*!
 * @name Message Buffer Interrupts Interfaces
 * @{
 */

/*!
 * @brief Enables FlexCAN Message Buffer interrupts.
 *
 * This function enables the interrupts of given Message Buffers.
 *
 * @param base FlexCAN peripheral base address.
 * @param mask The ORed FlexCAN Message Buffer mask.
 */
#if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0)
static inline void FLEXCAN_EnableMbInterrupts(CAN_Type *base, uint64_t mask)
#else
static inline void FLEXCAN_EnableMbInterrupts(CAN_Type *base, uint32_t mask)
#endif
{
#if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0)
    base->IMASK1 |= (uint32_t)(mask & 0xFFFFFFFFU);
    base->IMASK2 |= (uint32_t)(mask >> 32);
#else
    base->IMASK1 |= mask;
#endif
}

/*!
 * @brief Disables FlexCAN Message Buffer interrupts.
 *
 * This function disables the interrupts of given Message Buffers.
 *
 * @param base FlexCAN peripheral base address.
 * @param mask The ORed FlexCAN Message Buffer mask.
 */
#if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0)
static inline void FLEXCAN_DisableMbInterrupts(CAN_Type *base, uint64_t mask)
#else
static inline void FLEXCAN_DisableMbInterrupts(CAN_Type *base, uint32_t mask)
#endif
{
#if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0)
    base->IMASK1 &= ~((uint32_t)(mask & 0xFFFFFFFFU));
    base->IMASK2 &= ~((uint32_t)(mask >> 32));
#else
    base->IMASK1 &= ~mask;
#endif
}

/* @} */

#if (defined(FSL_FEATURE_FLEXCAN_HAS_RX_FIFO_DMA) && FSL_FEATURE_FLEXCAN_HAS_RX_FIFO_DMA)
/*!
 * @name DMA Control Interfaces
 * @{
 */

/*!
 * @brief Enables or disables the FlexCAN Rx FIFO DMA request.
 *
 * This function enables or disables the DMA feature of FlexCAN build-in Rx FIFO.
 *
 * @param base FlexCAN peripheral base address.
 * @param bEnable true to enable, false to disable.
 */
void FLEXCAN_EnableRxFifoDMA(CAN_Type *base, bool bEnable);

/*!
 * @brief Gets the Rx FIFO Head address.
 *
 * This function returns the FlexCAN Rx FIFO Head address, which is mainly used for the DMA/eDMA use case.
 *
 * @param base FlexCAN peripheral base address.
 * @return FlexCAN Rx FIFO Head address.
 */
static inline uint32_t FLEXCAN_GetRxFifoHeadAddr(CAN_Type *base)
{
    return (uint32_t) & (base->MB[0].CS);
}

/* @} */
#endif /* FSL_FEATURE_FLEXCAN_HAS_RX_FIFO_DMA */

/*!
 * @name Bus Operations
 * @{
 */

/*!
 * @brief Enables or disables the FlexCAN module operation.
 *
 * This function enables or disables the FlexCAN module.
 *
 * @param base FlexCAN base pointer.
 * @param bEnable true to enable, false to disable.
 */
static inline void FLEXCAN_Enable(CAN_Type *base, bool bEnable)
{
    if (bEnable)
    {
        base->MCR &= ~CAN_MCR_MDIS_MASK;

        /* Wait FlexCAN exit from low-power mode. */
        while (0U != (base->MCR & CAN_MCR_LPMACK_MASK))
        {
        }
    }
    else
    {
        base->MCR |= CAN_MCR_MDIS_MASK;

        /* Wait FlexCAN enter low-power mode. */
        while (0U == (base->MCR & CAN_MCR_LPMACK_MASK))
        {
        }
    }
}

/*!
 * @brief Writes a FlexCAN Message to the Transmit Message Buffer.
 *
 * This function writes a CAN Message to the specified Transmit Message Buffer
 * and changes the Message Buffer state to start CAN Message transmit. After
 * that the function returns immediately.
 *
 * @param base FlexCAN peripheral base address.
 * @param u8MsgBufIdx The FlexCAN Message Buffer index.
 * @param psTxFrame Pointer to CAN message frame to be sent.
 * @retval kStatus_Success - Write Tx Message Buffer Successfully.
 * @retval kStatus_Fail    - Tx Message Buffer is currently in use.
 */
status_t FLEXCAN_WriteTxMb(CAN_Type *base, uint8_t u8MsgBufIdx, const flexcan_frame_t *psTxFrame);

/*!
 * @brief Reads a FlexCAN Message from Receive Message Buffer.
 *
 * This function reads a CAN message from a specified Receive Message Buffer.
 * The function fills a receive CAN message frame structure with
 * just received data and activates the Message Buffer again.
 * The function returns immediately.
 *
 * @param base FlexCAN peripheral base address.
 * @param u8MsgBufIdx The FlexCAN Message Buffer index.
 * @param psRxFrame Pointer to CAN message frame structure for reception.
 * @retval kStatus_Success            - Rx Message Buffer is full and has been read successfully.
 * @retval kStatus_FLEXCAN_RxOverflow - Rx Message Buffer is already overflowed and has been read successfully.
 * @retval kStatus_Fail               - Rx Message Buffer is empty.
 */
status_t FLEXCAN_ReadRxMb(CAN_Type *base, uint8_t u8MsgBufIdx, flexcan_frame_t *psRxFrame);

/*!
 * @brief Reads a FlexCAN Message from Rx FIFO.
 *
 * This function reads a CAN message from the FlexCAN build-in Rx FIFO.
 *
 * @param base FlexCAN peripheral base address.
 * @param psRxFrame Pointer to CAN message frame structure for reception.
 * @retval kStatus_Success - Read Message from Rx FIFO successfully.
 * @retval kStatus_Fail    - Rx FIFO is not enabled.
 */
status_t FLEXCAN_ReadRxFifo(CAN_Type *base, flexcan_frame_t *psRxFrame);

#if (defined(FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE) && FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE)
/*!
 * @brief Writes a FlexCAN FD Message to the Transmit Message Buffer.
 *
 * This function writes a CAN FD Message to the specified Transmit Message Buffer
 * and changes the Message Buffer state to start CAN FD Message transmit. After
 * that the function returns immediately.
 *
 * @param base FlexCAN peripheral base address.
 * @param u8MsgBufIdx The FlexCAN FD Message Buffer index.
 * @param psTxFrame Pointer to CAN FD message frame to be sent.
 * @retval kStatus_Success - Write Tx Message Buffer Successfully.
 * @retval kStatus_Fail    - Tx Message Buffer is currently in use.
 */
status_t FLEXCAN_WriteFDTxMb(CAN_Type *base, uint8_t u8MsgBufIdx, const flexcan_fd_frame_t *psTxFrame);

/*!
 * @brief Reads a FlexCAN FD Message from Receive Message Buffer.
 *
 * This function reads a CAN FD message from a specified Receive Message Buffer.
 * The function fills a receive CAN FD message frame structure with
 * just received data and activates the Message Buffer again.
 * The function returns immediately.
 *
 * @param base FlexCAN peripheral base address.
 * @param u8MsgBufIdx The FlexCAN FD Message Buffer index.
 * @param psRxFrame Pointer to CAN FD message frame structure for reception.
 * @retval kStatus_Success            - Rx Message Buffer is full and has been read successfully.
 * @retval kStatus_FLEXCAN_RxOverflow - Rx Message Buffer is already overflowed and has been read successfully.
 * @retval kStatus_Fail               - Rx Message Buffer is empty.
 */
status_t FLEXCAN_ReadFDRxMb(CAN_Type *base, uint8_t u8MsgBufIdx, flexcan_fd_frame_t *psRxFrame);
#endif

/* @} */

/*!
 * @name Transactional Blocking Interface
 * @{
 */

/*!
 * @brief Performs a polling send transaction on the CAN bus.
 *
 * Note that a transfer handle does not need to be created  before calling this API.
 *
 * @param base FlexCAN peripheral base pointer.
 * @param u8MsgBufIdx The FlexCAN Message Buffer index.
 * @param psTxFrame Pointer to CAN message frame to be sent.
 * @retval kStatus_Success - Write Tx Message Buffer Successfully.
 * @retval kStatus_Fail    - Tx Message Buffer is currently in use.
 */
status_t FLEXCAN_TransferSendBlocking(CAN_Type *base, uint8_t u8MsgBufIdx, flexcan_frame_t *psTxFrame);

/*!
 * @brief Performs a polling receive transaction on the CAN bus.
 *
 * Note that a transfer handle does not need to be created  before calling this API.
 *
 * @param base FlexCAN peripheral base pointer.
 * @param u8MsgBufIdx The FlexCAN Message Buffer index.
 * @param psRxFrame Pointer to CAN message frame structure for reception.
 * @retval kStatus_Success            - Rx Message Buffer is full and has been read successfully.
 * @retval kStatus_FLEXCAN_RxOverflow - Rx Message Buffer is already overflowed and has been read successfully.
 * @retval kStatus_Fail               - Rx Message Buffer is empty.
 */
status_t FLEXCAN_TransferReceiveBlocking(CAN_Type *base, uint8_t u8MsgBufIdx, flexcan_frame_t *psRxFrame);

/*!
 * @brief Performs a polling receive transaction from Rx FIFO on the CAN bus.
 *
 * Note that a transfer handle does not need to be created  before calling this API.
 *
 * @param base FlexCAN peripheral base pointer.
 * @param psRxFrame Pointer to CAN message frame structure for reception.
 * @retval kStatus_Success - Read Message from Rx FIFO successfully.
 * @retval kStatus_Fail    - Rx FIFO is not enabled.
 */
status_t FLEXCAN_TransferReceiveFifoBlocking(CAN_Type *base, flexcan_frame_t *psRxFrame);

#if (defined(FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE) && FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE)
/*!
 * @brief Performs a polling send transaction on the CAN bus.
 *
 * Note that a transfer handle does not need to be created before calling this API.
 *
 * @param base FlexCAN peripheral base pointer.
 * @param u8MsgBufIdx The FlexCAN FD Message Buffer index.
 * @param psTxFrame Pointer to CAN FD message frame to be sent.
 * @retval kStatus_Success - Write Tx Message Buffer Successfully.
 * @retval kStatus_Fail    - Tx Message Buffer is currently in use.
 */
status_t FLEXCAN_TransferFDSendBlocking(CAN_Type *base, uint8_t u8MsgBufIdx, flexcan_fd_frame_t *psTxFrame);

/*!
 * @brief Performs a polling receive transaction on the CAN bus.
 *
 * Note that a transfer handle does not need to be created before calling this API.
 *
 * @param base FlexCAN peripheral base pointer.
 * @param u8MsgBufIdx The FlexCAN FD Message Buffer index.
 * @param psRxFrame Pointer to CAN FD message frame structure for reception.
 * @retval kStatus_Success            - Rx Message Buffer is full and has been read successfully.
 * @retval kStatus_FLEXCAN_RxOverflow - Rx Message Buffer is already overflowed and has been read successfully.
 * @retval kStatus_Fail               - Rx Message Buffer is empty.
 */
status_t FLEXCAN_TransferFDReceiveBlocking(CAN_Type *base, uint8_t u8MsgBufIdx, flexcan_fd_frame_t *psRxFrame);
#endif

/* @} */

/*!
 * @name Transactional Non-Blocking Interfaces
 * @{
 */

/*!
 * @brief Initializes the FlexCAN handle.
 *
 * This function initializes the FlexCAN handle, which can be used for other FlexCAN
 * transactional APIs. Usually, for a specified FlexCAN instance,
 * call this API once to get the initialized handle.
 *
 * @param base FlexCAN peripheral base address.
 * @param psHandle FlexCAN handle pointer.
 * @param pfCallback The callback function.
 * @param pUserData The parameter of the callback function.
 */
void FLEXCAN_TransferCreateHandle(CAN_Type *base,
                                  flexcan_handle_t *psHandle,
                                  flexcan_transfer_callback_t pfCallback,
                                  void *pUserData);

/*!
 * @brief Sends a message using IRQ.
 *
 * This function sends a message using IRQ. This is a non-blocking function, which returns
 * right away. When messages have been sent out, the send callback function is called.
 *
 * @param psHandle FlexCAN handle pointer.
 * @param psMsgBufXfer FlexCAN Message Buffer transfer structure. See the #flexcan_mb_transfer_t.
 * @retval kStatus_Success        Start Tx Message Buffer sending process successfully.
 * @retval kStatus_Fail           Write Tx Message Buffer failed.
 * @retval kStatus_FLEXCAN_TxBusy Tx Message Buffer is in use.
 */
status_t FLEXCAN_TransferSendNonBlocking(flexcan_handle_t *psHandle, flexcan_mb_transfer_t *psMsgBufXfer);

/*!
 * @brief Receives a message using IRQ.
 *
 * This function receives a message using IRQ. This is non-blocking function, which returns
 * right away. When the message has been received, the receive callback function is called.
 *
 * @param psHandle FlexCAN handle pointer.
 * @param psMsgBufXfer FlexCAN Message Buffer transfer structure. See the #flexcan_mb_transfer_t.
 * @retval kStatus_Success        - Start Rx Message Buffer receiving process successfully.
 * @retval kStatus_FLEXCAN_RxBusy - Rx Message Buffer is in use.
 */
status_t FLEXCAN_TransferReceiveNonBlocking(flexcan_handle_t *psHandle, flexcan_mb_transfer_t *psMsgBufXfer);

/*!
 * @brief Receives a message from Rx FIFO using IRQ.
 *
 * This function receives a message using IRQ. This is a non-blocking function, which returns
 * right away. When all messages have been received, the receive callback function is called.
 *
 * @param psHandle FlexCAN handle pointer.
 * @param psFifoXfer FlexCAN Rx FIFO transfer structure. See the @ref flexcan_fifo_transfer_t.
 * @retval kStatus_Success            - Start Rx FIFO receiving process successfully.
 * @retval kStatus_FLEXCAN_RxFifoBusy - Rx FIFO is currently in use.
 */
status_t FLEXCAN_TransferReceiveFifoNonBlocking(flexcan_handle_t *psHandle, flexcan_fifo_transfer_t *psFifoXfer);

/*!
 * @brief Gets the detail index of Mailbox's Timestamp by handle.
 *
 * Then function can only be used when calling non-blocking Data transfer (TX/RX) API,
 * After TX/RX data transfer done (User can get the status by handler's callback function),
 * we can get the detail index of Mailbox's timestamp by handle,
 * Detail non-blocking data transfer API (TX/RX) contain.
 *   -FLEXCAN_TransferSendNonBlocking
 *   -FLEXCAN_TransferFDSendNonBlocking
 *   -FLEXCAN_TransferReceiveNonBlocking
 *   -FLEXCAN_TransferFDReceiveNonBlocking
 *   -FLEXCAN_TransferReceiveFifoNonBlocking
 *
 * @param psHandle FlexCAN handle pointer.
 * @param u8MsgBufIdx The FlexCAN FD Message Buffer index.
 * @retval the index of mailbox 's timestamp stored in the handle.
 *
 */
uint32_t FLEXCAN_GetTimeStamp(flexcan_handle_t *psHandle, uint8_t u8MsgBufIdx);

/*!
 * @brief Aborts the interrupt driven message send process.
 *
 * This function aborts the interrupt driven message send process.
 *
 * @param psHandle FlexCAN handle pointer.
 * @param u8MsgBufIdx The FlexCAN Message Buffer index.
 */
void FLEXCAN_TransferAbortSend(flexcan_handle_t *psHandle, uint8_t u8MsgBufIdx);

/*!
 * @brief Aborts the interrupt driven message receive process.
 *
 * This function aborts the interrupt driven message receive process.
 *
 * @param psHandle FlexCAN handle pointer.
 * @param u8MsgBufIdx The FlexCAN Message Buffer index.
 */
void FLEXCAN_TransferAbortReceive(flexcan_handle_t *psHandle, uint8_t u8MsgBufIdx);

/*!
 * @brief Aborts the interrupt driven message receive from Rx FIFO process.
 *
 * This function aborts the interrupt driven message receive from Rx FIFO process.
 *
 * @param psHandle FlexCAN handle pointer.
 */
void FLEXCAN_TransferAbortReceiveFifo(flexcan_handle_t *psHandle);

/*!
 * @brief FlexCAN IRQ handle function.
 *
 * This function handles the FlexCAN Error, the Message Buffer, and the Rx FIFO IRQ request.
 *
 * @param psHandle FlexCAN handle pointer.
 */
void FLEXCAN_TransferHandleIRQ(flexcan_handle_t *psHandle);

#if (defined(FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE) && FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE)
/*!
 * @brief Sends a message using IRQ.
 *
 * This function sends a message using IRQ. This is a non-blocking function, which returns
 * right away. When messages have been sent out, the send callback function is called.
 *
 * @param psHandle FlexCAN handle pointer.
 * @param psMsgBufXfer FlexCAN FD Message Buffer transfer structure. See the #flexcan_mb_transfer_t.
 * @retval kStatus_Success        Start Tx Message Buffer sending process successfully.
 * @retval kStatus_Fail           Write Tx Message Buffer failed.
 * @retval kStatus_FLEXCAN_TxBusy Tx Message Buffer is in use.
 */
status_t FLEXCAN_TransferFDSendNonBlocking(flexcan_handle_t *psHandle, flexcan_mb_transfer_t *psMsgBufXfer);

/*!
 * @brief Receives a message using IRQ.
 *
 * This function receives a message using IRQ. This is non-blocking function, which returns
 * right away. When the message has been received, the receive callback function is called.
 *
 * @param psHandle FlexCAN handle pointer.
 * @param psMsgBufXfer FlexCAN FD Message Buffer transfer structure. See the #flexcan_mb_transfer_t.
 * @retval kStatus_Success        - Start Rx Message Buffer receiving process successfully.
 * @retval kStatus_FLEXCAN_RxBusy - Rx Message Buffer is in use.
 */
status_t FLEXCAN_TransferFDReceiveNonBlocking(flexcan_handle_t *psHandle, flexcan_mb_transfer_t *psMsgBufXfer);

/*!
 * @brief Aborts the interrupt driven message send process.
 *
 * This function aborts the interrupt driven message send process.
 *
 * @param psHandle FlexCAN handle pointer.
 * @param u8MsgBufIdx The FlexCAN FD Message Buffer index.
 */
void FLEXCAN_TransferFDAbortSend(flexcan_handle_t *psHandle, uint8_t u8MsgBufIdx);

/*!
 * @brief Aborts the interrupt driven message receive process.
 *
 * This function aborts the interrupt driven message receive process.
 *
 * @param psHandle FlexCAN handle pointer.
 * @param u8MsgBufIdx The FlexCAN FD Message Buffer index.
 */
void FLEXCAN_TransferFDAbortReceive(flexcan_handle_t *psHandle, uint8_t u8MsgBufIdx);
#endif

/* @} */

#if defined(__cplusplus)
}
#endif

/*! @}*/

#endif /* _FSL_FLEXCAN_H_ */
