/**
 * @file
 * Ethernet Interface Skeleton
 *
 */

/*
 * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
 * 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. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
 *
 * This file is part of the lwIP TCP/IP stack.
 *
 * Author: Adam Dunkels <adam@sics.se>
 *
 */

/*
 * This file is a skeleton for developing Ethernet network interface
 * drivers for lwIP. Add code to the low_level functions and do a
 * search-and-replace for the word "ethernetif" to replace it with
 * something that better describes your network interface.
 */
#include "board_init.h"
#include "lwip/opt.h"
#include "lwip/mem.h"
#include "lwip/memp.h"
#include "lwip/timeouts.h"
#include "ethernetif.h"
#include "lwip/etharp.h"
#include "lwip/ethip6.h"
#include "hal_enet.h"

/* Define those to better describe your network interface. */
#define IFNAME0 'm'
#define IFNAME1 'm'

uint8_t app_enet_txbuf[ENET_TX_NUM][ENET_TX_BUFLEN];
uint8_t app_enet_rxbuf[ENET_RX_NUM][ENET_RX_BUFLEN];
ENET_TxDmaDesp_Type TxDmaDespTab[ENET_TX_NUM];
ENET_RxDmaDesp_Type RxDmaDespTab[ENET_RX_NUM];
ENET_RxDmaDesp_Type * RxDmaDespGet;
ENET_RxDmaDespInfo_Type * RxDmaDespInfo;

/**
 * Helper struct to hold private data used to operate your ethernet interface.
 * Keeping the ethernet address of the MAC in this struct is not necessary
 * as it is already kept in the struct netif.
 * But this is only an example, anyway...
 */
struct ethernetif {
  struct eth_addr *ethaddr;
  /* Add whatever per-interface state that is needed here. */
};

static void arp_timer(void *arg);
void enet_init(void);

/**
 * In this function, the hardware should be initialized.
 * Called from ethernetif_init().
 *
 * @param netif the already initialized lwip network interface structure
 *        for this ethernetif
 */
static void low_level_init(struct netif *netif)
{
    /* Initialization enet driver. */
    enet_init();

    /* Set MAC hardware address length */
    netif->hwaddr_len = ETHARP_HWADDR_LEN;

    /* Set MAC hardware address */
    netif->hwaddr[0] = BOARD_MAC_ADDR0;
    netif->hwaddr[1] = BOARD_MAC_ADDR1;
    netif->hwaddr[2] = BOARD_MAC_ADDR2;
    netif->hwaddr[3] = BOARD_MAC_ADDR3;
    netif->hwaddr[4] = BOARD_MAC_ADDR4;
    netif->hwaddr[5] = BOARD_MAC_ADDR5;

    ENET_SetupMacAddrFilter(BOARD_DEBUG_ENET_PORT, ENET_FILTERS_RECEIVE_ALL | ENET_FILTERS_BOARDCAST_FILTER, ENET_ADDR_FILTER_NUM, 0u, netif->hwaddr);

    /* Maximum transfer unit */
    netif->mtu = NETIF_MTU;

    /* Device capabilities. */
    /* Don't set NETIF_FLAG_ETHARP if this device is not an ethernet one. */
    netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_LINK_UP;

    /* Set tx dma desp link. */
    for (uint32_t i = 0u; i < ENET_TX_NUM; i++)
    {
        if (i == 0u)
        {
            ENET_LinkTxDmaDesp(BOARD_DEBUG_ENET_PORT, &TxDmaDespTab[0], app_enet_txbuf[0], 0u, &TxDmaDespTab[0]);
        }
        else
        {
            ENET_LinkTxDmaDesp(BOARD_DEBUG_ENET_PORT, &TxDmaDespTab[i], app_enet_txbuf[i], 0u, &TxDmaDespTab[i-1]);
        }
        if (i == (ENET_TX_NUM - 1u) )
        {
            TxDmaDespTab[ENET_TX_NUM - 1u].TBA2 = (uint32_t)&TxDmaDespTab[0];
        }
        TxDmaDespTab[i].OWN = 0u;
    }

    /* Set rx dma desp link. */
    ENET_LinkRxDmaDesp(BOARD_DEBUG_ENET_PORT, RxDmaDespTab, &app_enet_rxbuf[0][0], ENET_RX_BUFLEN, ENET_RX_NUM);
    ENET_SetTxDmaDesp(BOARD_DEBUG_ENET_PORT, (uint32_t)TxDmaDespTab);
    ENET_SetRxDmaDesp(BOARD_DEBUG_ENET_PORT, (uint32_t)RxDmaDespTab);
    RxDmaDespGet = RxDmaDespTab;
    RxDmaDespInfo->RxDespCnt = 0u;

    ENET_EnableRxDma(BOARD_DEBUG_ENET_PORT, true);
    ENET_EnableTxDma(BOARD_DEBUG_ENET_PORT, true);
}

/**
 * This function should do the actual transmission of the packet. The packet is
 * contained in the pbuf that is passed to the function. This pbuf
 * might be chained.
 *
 * @param netif the lwip network interface structure for this ethernetif
 * @param p the MAC packet to send (e.g. IP packet including MAC addresses and type)
 * @return ERR_OK if the packet could be sent
 *         an err_t value if the packet couldn't be sent
 *
 * @note Returning ERR_MEM here if a DMA queue of your MAC is full can lead to
 *       strange results. You might consider waiting for space in the DMA queue
 *       to become available since the stack doesn't retry to send a packet
 *       dropped because of memory failure (except for the TCP timers).
 */

static err_t low_level_output(struct netif *netif, struct pbuf *p)
{
    struct pbuf *q;

    /* Get current destination address. */
    ENET_TxDmaDesp_Type * TxDmaDesp;
    TxDmaDesp = (ENET_TxDmaDesp_Type*)ENET_GetCurrentTxDesp(BOARD_DEBUG_ENET_PORT);

    uint8_t *buffer = (uint8_t *)(TxDmaDesp->TBA1);

    ENET_TxDmaDesp_Type *TempDesp;
    uint32_t framelen = 0u;
    uint32_t bufoffset = 0u;
    uint32_t byteslefttocopy = 0u;
    uint32_t payloadoffset = 0u;
    TempDesp = TxDmaDesp;

    if (1u == TempDesp->OWN)
    {
        return ERR_USE;
    }

#if ETH_PAD_SIZE
    pbuf_remove_header(p, ETH_PAD_SIZE); /* drop the padding word */
#endif

    for (q = p; q != NULL; q = q->next)
    {
        /* Send the data from the pbuf to the interface, one pbuf at a time. The size of the data in each pbuf is kept in the ->len variable. */
        /* Get bytes in current lwIP buffer. */
        byteslefttocopy = q->len;
        payloadoffset = 0u;
        /* Check if the length of data to copy is bigger than Tx buffer size. */
        while ( (byteslefttocopy + bufoffset) > ENET_TX_BUFLEN )
        {
            /* Copy data to Tx buffer. */
            memcpy( (uint8_t*)((uint8_t*)buffer + bufoffset), (uint8_t*)((uint8_t*)q->payload + payloadoffset), (ENET_TX_BUFLEN - bufoffset) );
            /* Point to next descriptor. */
            TempDesp = (ENET_TxDmaDesp_Type *)(TempDesp->TBA2);
            /* Check if the buffer is available. */
            if(1u == TempDesp->OWN)
            {
                return ERR_USE;
            }
            buffer = (uint8_t *)(TempDesp->TBA1);  /* Next tx fifo address. */
            byteslefttocopy = byteslefttocopy - (ENET_TX_BUFLEN - bufoffset);
            payloadoffset = payloadoffset + (ENET_TX_BUFLEN - bufoffset);
            framelen = framelen + (ENET_TX_BUFLEN - bufoffset);
            bufoffset = 0u;
        }
        /* Copy the remaining bytes. */
        memcpy( (uint8_t*)((uint8_t*)buffer + bufoffset), (uint8_t*)((uint8_t*)q->payload + payloadoffset), byteslefttocopy);
        bufoffset = bufoffset + byteslefttocopy;
        framelen = framelen + byteslefttocopy;
    }

    /* Set and send frame. */
    uint32_t cnt = 0u;
    TempDesp = (ENET_TxDmaDesp_Type*)ENET_GetCurrentTxDesp(BOARD_DEBUG_ENET_PORT);
    buffer = (uint8_t *)(TempDesp->TBA1);
    if (framelen > ENET_TX_BUFLEN)
    {
        cnt = framelen / ENET_TX_BUFLEN;
        if (cnt % ENET_TX_BUFLEN)
        {
            cnt++;
        }
    }
    else
    {
        cnt = 1u;
    }
    if (cnt == 1u)
    {
        TempDesp->TFS = 1u;
        TempDesp->TLS = 1u;
        TempDesp->TEIE = 1u;
        TempDesp->TBS1 = framelen;
        TempDesp->OWN = 1u;
        TempDesp = (ENET_TxDmaDesp_Type*)(TempDesp->TBA2);
    }
    else
    {
        for (uint32_t i = 0u; i < cnt; i++)
        {
            if (i == 0u)
            {
                TempDesp->TFS = 1u;
                TempDesp->TLS = 0u;
                TempDesp->TBS1 = ENET_TX_BUFLEN;
            }
            else if (i == (cnt - 1u) )
            {
                TempDesp->TEIE = 1u;
                TempDesp->TFS = 0u;
                TempDesp->TLS = 1u;
                TempDesp->TBS1 = ( framelen - ((cnt - 1u) * ENET_TX_BUFLEN) );
            }
            else
            {
                TempDesp->TFS = 0u;
                TempDesp->TLS = 0u;
                TempDesp->TBS1 = ENET_TX_BUFLEN;
            }
            TempDesp->OWN = 1u;
            TempDesp = (ENET_TxDmaDesp_Type*)(TempDesp->TBA2);
        }
    }
    TxDmaDesp = TempDesp;

    if (0u != (ENET_GetDmaStatus(BOARD_DEBUG_ENET_PORT) & ENET_STATUS_DMA_TX_FIFO_UNACTIVE ) )
    {
        ENET_WakeupTxDma(BOARD_DEBUG_ENET_PORT, 0u);
    }

  return ERR_OK;
}

/**
 * Should allocate a pbuf and transfer the bytes of the incoming
 * packet from the interface into the pbuf.
 *
 * @param netif the lwip network interface structure for this ethernetif
 * @return a pbuf filled with the received packet (including MAC header)
 *         NULL on memory error
 */
static struct pbuf *low_level_input(struct netif *netif)
{
    struct pbuf *p = NULL;
    struct pbuf *q = NULL;
    uint16_t len = 0u;
    uint8_t *buffer;
    ENET_RxDmaDesp_Type *tempdesp;
    uint32_t bufoffset = 0u;
    uint32_t payloadoffset = 0u;
    uint32_t byteslefttocopy = 0u;

    /* Obtain the size of the packet and put it into the "len" variable. */
    if (false == ENET_CheckRxLastDesp(BOARD_DEBUG_ENET_PORT, RxDmaDespGet, RxDmaDespInfo) )
    {
        return p;
    }
    len = (RxDmaDespGet->FL - 4u);
    buffer = (uint8_t *)RxDmaDespInfo->RxFirstDesp->RBA1;
    RxDmaDespGet = (ENET_RxDmaDesp_Type*)RxDmaDespGet->RBA2;

#if ETH_PAD_SIZE
    len += ETH_PAD_SIZE; /* allow room for Ethernet padding */
#endif

    /* Allocate a pbuf chain of pbufs from the pool. */
    if (len > 0u)
    {
        p = pbuf_alloc(PBUF_RAW, len, PBUF_POOL);
    }

    if (p != NULL)
    {

#if ETH_PAD_SIZE
    pbuf_remove_header(p, ETH_PAD_SIZE); /* drop the padding word */
#endif
        tempdesp = RxDmaDespInfo->RxFirstDesp; //RxDmaFirstDesp;
        bufoffset = 0u;

    /* Iterate over the pbuf chain until we have read the entire packet into the pbuf. */
    for (q = p; q != NULL; q = q->next)
    {
      /* Read enough bytes to fill this pbuf in the chain. The available data in the pbuf is given by the q->len variable.
       * This does not necessarily have to be a memcpy, you can also preallocate pbufs for a DMA-enabled MAC and after receiving truncate it to the
       * actually received size. In this case, ensure the tot_len member of the pbuf is the sum of the chained pbuf len members. */
        byteslefttocopy = q->len;
        payloadoffset = 0u;
        while( (byteslefttocopy + bufoffset) > ENET_RX_BUFLEN )
        {
            /* Copy data to pbuf. */
            memcpy( (uint8_t*)((uint8_t*)q->payload + payloadoffset), (uint8_t*)((uint8_t*)buffer + bufoffset), (ENET_RX_BUFLEN - bufoffset));
            /* Point to next descriptor. */
            tempdesp = (ENET_RxDmaDesp_Type *)(tempdesp->RBA2);
            buffer = (uint8_t *)(tempdesp->RBA1);
            byteslefttocopy = byteslefttocopy - (ENET_RX_BUFLEN - bufoffset);
            payloadoffset = payloadoffset + (ENET_RX_BUFLEN - bufoffset);
            bufoffset = 0u;
        }
        /* Copy remaining data in pbuf. */
        memcpy( (uint8_t*)((uint8_t*)q->payload + payloadoffset), (uint8_t*)((uint8_t*)buffer + bufoffset), byteslefttocopy);
        bufoffset = bufoffset + byteslefttocopy;
    }
    }
    /* Acknowledge that packet has been read(); */
    tempdesp = RxDmaDespInfo->RxFirstDesp;
    for (uint32_t i = 0u; i < RxDmaDespInfo->RxDespCnt; i++)
    {
        tempdesp->OWN = 1u;
        tempdesp = (ENET_RxDmaDesp_Type *)(tempdesp->RBA2);
    }
    RxDmaDespInfo->RxDespCnt = 0u;
    if (0u != (ENET_GetDmaStatus(BOARD_DEBUG_ENET_PORT) & ENET_STATUS_DMA_RX_FIFO_UNACTIVE) )
    {
        ENET_WakeupRxDma(BOARD_DEBUG_ENET_PORT, 0u);
    }

    return p;
}

/**
 * This function should be called when a packet is ready to be read
 * from the interface. It uses the function low_level_input() that
 * should handle the actual reception of bytes from the network
 * interface. Then the type of the received packet is determined and
 * the appropriate input function is called.
 *
 * @param netif the lwip network interface structure for this ethernetif
 */
void ethernetif_input(struct netif *netif)
{
    struct pbuf *p;

    /* Move received packet into a new pbuf */
    p = low_level_input(netif);
    /* If no packet could be read, silently ignore this */
    if (p == NULL)
    {
        return;
    }

    if (p != NULL)
    {
        /* pass all packets to ethernet_input, which decides what packets it supports */
        if (netif->input(p, netif) != ERR_OK)
        {
          LWIP_DEBUGF(NETIF_DEBUG, ("ethernetif_input: IP input error\n"));
          pbuf_free(p);
          p = NULL;
        }
    }
}

/**
 * Should be called at the beginning of the program to set up the
 * network interface. It calls the function low_level_init() to do the
 * actual setup of the hardware.
 *
 * This function should be passed as a parameter to netif_add().
 *
 * @param netif the lwip network interface structure for this ethernetif
 * @return ERR_OK if the loopif is initialized
 *         ERR_MEM if private data couldn't be allocated
 *         any other err_t on error
 */
err_t ethernetif_init(struct netif *netif)
{
    struct ethernetif *ethernetif;

    LWIP_ASSERT("netif != NULL", (netif != NULL));

    ethernetif = mem_malloc(sizeof(struct ethernetif));
    if (ethernetif == NULL)
    {
      return ERR_MEM;
    }

#if LWIP_NETIF_HOSTNAME
  /* Initialize interface hostname */
    netif->hostname = "lwip";
#endif /* LWIP_NETIF_HOSTNAME */

    /*
     * Initialize the snmp variables and counters inside the struct netif.
     * The last argument should be replaced with your link speed, in units
     * of bits per second.
     */
    netif->state = ethernetif;
    netif->name[0] = IFNAME0;
    netif->name[1] = IFNAME1;
    /* We directly use etharp_output() here to save a function call.
     * You can instead declare your own function an call etharp_output()
     * from it if you have to do some checks before sending (e.g. if link
     * is available...) */
#if LWIP_IPV4
    netif->output = etharp_output;
#endif /* LWIP_IPV4 */
#if LWIP_IPV6
    netif->output_ip6 = ethip6_output;
#endif /* LWIP_IPV6 */
    netif->linkoutput = low_level_output;

    /* initialize the hardware */
    low_level_init(netif);
    ethernetif->ethaddr = (struct eth_addr *) & (netif->hwaddr[0]);

    return ERR_OK;
}

static void arp_timer(void *arg)
{
    etharp_tmr();
    sys_timeout(ARP_TMR_INTERVAL, arp_timer, NULL);
}

/* Initialization enet. */
void enet_init(void)
{
    /* Initialization enet smi. */
    uint32_t *m_enet_smi_data = 0u;
    /* Initialization smi. */
    ENET_InitSmi(BOARD_DEBUG_ENET_PORT, ENET_SmiClockAlt_Alt1);
    ENET_WriteMacPhyReg(BOARD_DEBUG_ENET_PORT, ENET_PHY_ADDR, ENET_PHY_CONTROLREG, ENET_PHY_RESET);
    ENET_ReadMacPhyReg(BOARD_DEBUG_ENET_PORT, ENET_PHY_ADDR, ENET_PHY_CONTROLREG, m_enet_smi_data);
    while (0u != (*m_enet_smi_data & ENET_PHY_RESET) )
    {
        ENET_ReadMacPhyReg(BOARD_DEBUG_ENET_PORT, ENET_PHY_ADDR, ENET_PHY_CONTROLREG, m_enet_smi_data);
    }
    /* Set PHY. */
    uint16_t temp = ENET_PHY_SPEED100M | ENET_PHY_FULLDUPLEX;
    temp &= ~ENET_PHY_AUTONEGOTIATION;
    ENET_WriteMacPhyReg(BOARD_DEBUG_ENET_PORT,ENET_PHY_ADDR, ENET_PHY_CONTROLREG, temp);
    ENET_ReadMacPhyReg(BOARD_DEBUG_ENET_PORT, ENET_PHY_ADDR, ENET_PHY_STATUSREG, m_enet_smi_data);
    while( 0u == (*m_enet_smi_data & ENET_PHY_LINK) || (0u != (*m_enet_smi_data & ENET_PHY_UNIDIRECTIONAL) ) )
    {
        ENET_ReadMacPhyReg(BOARD_DEBUG_ENET_PORT, ENET_PHY_ADDR, ENET_PHY_STATUSREG, m_enet_smi_data);
    }

    ENET_Init_Type enet_init;

    /* Initialization mac. */
    enet_init.SourceAddrReplace = ENET_SourceAddrReplaceAlt_Alt0;
    enet_init.StripCRC = false;
    enet_init.DisableWatchdog = false;
    enet_init.DisableJabberCount = false;
    enet_init.InterframeGap = ENET_InterFrameGap_96;
    enet_init.EnableLoopback = false;
    enet_init.DuplexMode = ENET_DuplexMode_FullDuplex;
    enet_init.EnableIPChecksumOffload = false;
    enet_init.EnableAutoStripCRCPAD = false;

    /* Set enet dma. */
    enet_init.DmaXferPrior = ENET_DmaXferPrior_CyclicPriorRxTx1;
    enet_init.EnableAdvancedDesp = false;
    enet_init.AdressAlign = true;
    enet_init.EnableOperateOnSecondFrame = false;
    enet_init.TxFifoMode = ENET_FifoXferMode_StoreForward;
    enet_init.RxFifoMode = ENET_FifoXferMode_StoreForward;
    enet_init.MultipleProgrammableBurstLen = false;
    enet_init.TxBurstLen = ENET_DmaBurstLen_32Beat;
    enet_init.RxBurstLen = ENET_DmaBurstLen_32Beat;
    enet_init.TxThreshold = ENET_TxThreshold_64;
    enet_init.RxThreshold = ENET_RxThreshold_64;

    ENET_InitMacController(BOARD_DEBUG_ENET_PORT, &enet_init);
    ENET_InitDmaController(BOARD_DEBUG_ENET_PORT, &enet_init);

    ENET_EnableDmaInterrupts(BOARD_DEBUG_ENET_PORT, ENET_INT_NORMAL | ENET_INT_RX_DONE | ENET_INT_TX_DONE, true);  /* Enable dma interrupt. */
    NVIC_EnableIRQ(BOARD_DEBUG_ENET_IRQn);
}
