 /*!
    \file  usbd_lld_int.c
    \brief USB device low level interrupt routines

    \version 2018-06-01, V1.0.0, firmware for GD32 USBD
*/

/*
    Copyright (c) 2018, GigaDevice Semiconductor Inc.

    All rights reserved.

    Redistribution and use in source and binary forms, with or without modification, 
are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice, this 
       list of conditions and the following disclaimer.
    2. Redistributions in binary form must reproduce the above copyright notice, 
       this list of conditions and the following disclaimer in the documentation 
       and/or other materials provided with the distribution.
    3. Neither the name of the copyright holder nor the names of its contributors 
       may be used to endorse or promote products derived from this software without 
       specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY 
OF SUCH DAMAGE.
*/

#include <stddef.h>
#include "usbd_int.h"
#include "drv_usbd.h"

usbd_int_cb_struct *usbd_int_fops = NULL;

__IO uint8_t g_ESOF_count = 0U;
__IO uint8_t g_suspend_enabled = 1U;
__IO uint8_t g_remote_wakeup_on = 0U;

#ifdef LPM_ENABLED
__IO uint32_t L1_remote_wakeup = 0U;
__IO uint32_t besl = 0U;
__IO uint32_t L1_resume = 0U;
#endif /* LPM_ENABLED */

extern usb_dev udev;

/*!
    \brief      handle USB suspend event
    \param[in]  udev: pointer to USB device instance
    \param[out] none
    \retval     none
*/
static void usbd_int_suspend (void)
{
    /* enter USB in suspend and mcu system in low power mode */
    if (g_suspend_enabled) {
        usbd_suspend();
    } else {
        /* if not possible then resume after xx ms */
        g_ESOF_count = 3U;
    }
}

/*!
    \brief      handle USB high priority successful transfer event
    \param[in]  udev: pointer to USB device instance
    \param[out] none
    \retval     none
*/
void usbd_int_hpst (void)
{
    __IO uint16_t int_status = 0U;

    uint8_t data_buf[64];

    /* wait till interrupts are not pending */
    while ((int_status = USBD_INTF) & (uint16_t)INTF_STIF) {
        /* get endpoint number */
        uint8_t ep_num = (uint8_t)(int_status & INTF_EPNUM);

        if (int_status & INTF_DIR) {
            if (USBD_EPxCS(ep_num) & EPxCS_RX_ST) {
                /* clear successful receive interrupt flag */
                USBD_EP_ST_CLEAR(ep_num, RX);

                udev.xfer_count = usbd_ep_data_read(data_buf, ep_num, EP_BUF_DBL);

                user_buffer_free(ep_num, DBUF_EP_OUT);

                /* wait for adding code */
            }
        } else {
            /* handle the in direction transaction */
            if (USBD_EPxCS(ep_num) & EPxCS_TX_ST) {
                /* clear successful transmit interrupt flag */
                USBD_EP_ST_CLEAR(ep_num, TX);

                /* wait for adding code */
            }
        }
    }
}

/*!
    \brief      handle USB low priority successful transfer event
    \param[in]  udev: pointer to USB device instance
    \param[out] none
    \retval     none
*/
void usbd_int_lpst (void)
{
    __IO uint16_t int_status = USBD_INTF;

    /* wait till interrupts are not pending */
    while ((int_status = USBD_INTF) & (uint16_t)INTF_STIF) {
        /* get endpoint number */
        uint8_t ep_num = (uint8_t)(int_status & INTF_EPNUM);

        if (int_status & INTF_DIR) {
            if (USBD_EPxCS(ep_num) & EPxCS_RX_ST) {
                /* clear successful receive interrupt flag */
                USBD_EP_ST_CLEAR(ep_num, RX);

                if (USBD_EPxCS(ep_num) & EPxCS_SETUP) {
                    udev.xfer_count = usbd_ep_data_read(udev.setup_packet, 0, EP_BUF_SNG);

                    if (udev.xfer_count == 8U) {
                        usbd_setup_stage_callback ((struct urequest *)udev.setup_packet);
                    }
                } else {
                    udev.xfer_count = usbd_ep_data_read(udev.xfer_buf, ep_num, EP_BUF_SNG);

                    usbd_data_out_stage_callback(ep_num, udev.xfer_count);
                }
            }
        } else {
            /* handle the in direction transaction */
            if (USBD_EPxCS(ep_num) & EPxCS_TX_ST) {
                /* clear successful transmit interrupt flag */
                USBD_EP_ST_CLEAR(ep_num, TX);

                usbd_data_in_stage_callback(ep_num, 0);

                if (udev.dev_addr != 0) {
                    USBD_DADDR = DADDR_USBEN | udev.dev_addr;

                    udev.dev_addr = 0;
                }
            }
        }
    }
}

/*!
    \brief      USB interrupt events service routine
    \param[in]  none
    \param[out] none
    \retval     none
*/
void usbd_isr (void)
{
    __IO uint16_t int_flag = USBD_INTF & (USBD_CTL & USBD_INTEN);

    if (INTF_STIF & int_flag) {
        usbd_int_lpst();
    }

    if (INTF_WKUPIF & int_flag) {
        /* clear wakeup interrupt flag in INTF */
        CLR(WKUPIF);

#ifdef LPM_ENABLED
        if ((0U == udev->pm.remote_wakeup_on) && (0U == L1_resume)) {
            resume_mcu(udev);
        } else if (1U == udev->pm.remote_wakeup_on) {
            /* no operation */
        } else {
            L1_resume = 0U;
        }

        /* clear L1 remote wakeup flag */
        L1_remote_wakeup = 0U;
#else
        if (0U == g_remote_wakeup_on) {
            usbd_leave_suspend();
        }
#endif /* LPM_ENABLED */
    }

    if (INTF_SPSIF & int_flag) {
        if(!(USBD_CTL & CTL_RSREQ)) {
            usbd_int_suspend ();

            /* clear of suspend interrupt flag bit must be done after setting of CTLR_SETSPS */
            CLR(SPSIF);
        }
    }

    if (INTF_SOFIF & int_flag) {
        /* clear SOF interrupt flag in INTF */
        CLR(SOFIF);

        /* if necessary, user can add code here */
        if (NULL != usbd_int_fops) {
            usbd_int_fops->SOF();
        }

//        usbd_sof_callback();
    }

    if (INTF_ESOFIF & int_flag) {
        /* clear ESOF interrupt flag in INTF */
        CLR(ESOFIF);

        /* control resume time by ESOFs */
        if (g_ESOF_count > 0U) {
            if (0U == --g_ESOF_count) {
                if (g_remote_wakeup_on) {
                    USBD_CTL &= ~CTL_RSREQ;

                    g_remote_wakeup_on = 0U;
                } else {
                    USBD_CTL |= CTL_RSREQ;

                    g_ESOF_count = 3U;
                    g_remote_wakeup_on = 1U;
                }
            }
        }
    }

    if (INTF_RSTIF & int_flag) {
        /* clear reset interrupt flag in INTF */
        CLR(RSTIF);

        usbd_ep_reset();

        usbd_reset_callback();
    }

#ifdef LPM_ENABLED
    if (INTF_L1REQ & int_flag) {
        /* clear L1 ST bit in LPM INTF */
        USBD_INTF = CLR(L1REQ);

        /* read BESL field from subendpoint0 register which corresponds to HIRD parameter in LPM spec */
        besl = (USBD_LPMCS & LPMCS_BLSTAT) >> 4;

        /* read BREMOTEWAKE bit from subendpoint0 register which corresponding to bRemoteWake bit in LPM request */
        L1_remote_wakeup = (USBD_LPMCS & LPMCS_REMWK) >> 8;

        /* process USB device core layer suspend routine */
        usbd_int_suspend(udev);
    }
#endif /* LPM_ENABLED */
}
