/*
 * Copyright (c) 2014-2019, Texas Instruments Incorporated
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * *  Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * *  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.
 *
 * *  Neither the name of Texas Instruments Incorporated 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 OWNER 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.
 */
/**
 *  \file main_gateway.c
 *
 *  \brief Main file for Gateway application.
 *
 */

 /* ========================================================================== */
/*                             Include Files                                  */
/* ========================================================================== */

#include <string.h>
#include <stdlib.h>

/* BIOS Header files */
#include <ti/sysbios/BIOS.h>
#include <ti/sysbios/knl/Task.h>
#include <ti/sysbios/family/arm/v8a/Mmu.h>
#include <ti/sysbios/utils/Load.h>

#include <xdc/runtime/System.h>
#include <xdc/runtime/Types.h>
#include <xdc/runtime/Timestamp.h>
#include <ti/sysbios/hal/Seconds.h>

/* CSL Header files */
#include <ti/csl/soc.h>
#include <ti/csl/arch/r5/csl_arm_r5.h>

/* NDK headers */
#include <ti/ndk/inc/netmain.h>
#include <ti/ndk/inc/stkmain.h>
#include <ti/ndk/inc/socket.h>
#include <sys/time.h>
#include <ti/ndk/inc/_stack.h>
#include <ti/ndk/inc/tools/servers.h>
#include <ti/ndk/inc/tools/console.h>

/* OSAL Header files */
#include <ti/osal/osal.h>

#if defined (SOC_AM65XX)
/* UART Header files */
#include <ti/drv/uart/UART.h>
#include <ti/drv/uart/UART_stdio.h>
/* BOARD Header files */
#include <ti/board/board.h>
#endif

/* EMAC Driver Header File. */
#include <ti/drv/emac/emac_drv.h>
#include <ti/drv/emac/src/v5/emac_drv_v5.h>
#include <ti/drv/emac/soc/emac_soc_v5.h>

/* This applications Header file */
#include <network_api.h>
#include <utils_prf.h>

/* ========================================================================== */
/*                           Macros & Typedefs                                */
/* ========================================================================== */

#define NIMU_MAX_TABLE_ENTRIES                              (9U)
#define NIMU_NUM_PORTS                                      (1U)
#define NIMU_TEST_MAX_SUB_RX_CHANS_PER_PORT                 (2U)
#define NIMU_TEST_MAX_CHANS_PER_PORT                        (2U)
#define NIMU_EMAC_PORT_ICSS                                 (0U)
#define NIMU_EMAC_PORT_CPSW                                 (6U)

/* brief Number of ring entries - we can prime this much memcpy operations */
#define NIMU_TEST_APP_RING_ENTRIES                          (128U)
/* Size (in bytes) of each ring entry (Size of pointer - 64-bit) */
#define NIMU_TEST_APP_RING_ENTRY_SIZE                       (sizeof(uint64_t))
 /* Total ring memory */
#define NIMU_TEST_APP_RING_MEM_SIZE                         \
                (NIMU_TEST_APP_RING_ENTRIES * NIMU_TEST_APP_RING_ENTRY_SIZE)

/*
 * UDMA host mode buffer descriptor memory size. Make it multiple of 128 byte
 * alignment
 */
#define NIMU_TEST_APP_DESC_SIZE                             \
             (sizeof(CSL_UdmapCppi5HMPD) + (128U - sizeof(CSL_UdmapCppi5HMPD)))

#define GATEWAYAPP_NDKSERVERS

/* ========================================================================== */
/*                         Structure Declarations                             */
/* ========================================================================== */

typedef struct app_statistics_s
{
    uint32_t gCpuLoad[100U];
    uint32_t gHwiLoad[100U];
    uint32_t gTaskLoad[100U];
}app_statistics;


/* ========================================================================== */
/*                          Function Declarations                             */
/* ========================================================================== */

extern int32_t (*NimuEmacInitFxn[NIMU_MAX_TABLE_ENTRIES])(STKEVENT_Handle hEvent);
void GatewayApp_statsTask(UArg arg0, UArg arg1);
void GatewayApp_initEmacK3(uint32_t portNum, uint32_t index);
void GatewayApp_stackInitHook(void* hCfg);
void GatewayApp_netOpenHook(void);
void GatewayApp_netCloseHook(void);

/* ========================================================================== */
/*                            Global Variables                                */
/* ========================================================================== */

#define NIMU_TOTAL_DESC_SIZE        (NIMU_TEST_APP_RING_ENTRIES * NIMU_TEST_APP_DESC_SIZE)
#define NIMU_TOTAL_CHANNELS         (NIMU_NUM_PORTS * NIMU_TEST_MAX_CHANS_PER_PORT)
#define NIMU_TOTAL_SUB_RX_CHANNELS  (NIMU_NUM_PORTS * NIMU_TEST_MAX_SUB_RX_CHANS_PER_PORT)

/* UDMA driver objects */
struct Udma_ChObj       gUdmaTxChObj[NIMU_TOTAL_CHANNELS];
struct Udma_ChObj       gUdmaRxChObj[NIMU_NUM_PORTS];
struct Udma_EventObj    gUdmaRxCqEventObj[NIMU_TOTAL_SUB_RX_CHANNELS];
struct Udma_ChObj       gUdmaRxCfgPsiChObj[NIMU_NUM_PORTS];
struct Udma_EventObj    gUdmaRxCfgPsiCqEventObj[NIMU_TOTAL_SUB_RX_CHANNELS];
static uint8_t          gUdmapDescRamTx[NIMU_TOTAL_CHANNELS][NIMU_TOTAL_DESC_SIZE]
                                __attribute__ ((aligned(UDMA_CACHELINE_ALIGNMENT)));
static uint8_t          gUdmapDescRamRx[NIMU_TOTAL_CHANNELS][NIMU_TOTAL_DESC_SIZE]
                                __attribute__ ((aligned(UDMA_CACHELINE_ALIGNMENT)));
static uint8_t          gUdmapDescRamRxCfgPsi[NIMU_TOTAL_CHANNELS][NIMU_TOTAL_DESC_SIZE]
                                __attribute__ ((aligned(UDMA_CACHELINE_ALIGNMENT)));
/*
 * UDMA Memories
 */
static uint8_t          gTxRingMem[NIMU_TOTAL_CHANNELS][NIMU_TEST_APP_RING_MEM_SIZE]
                                __attribute__ ((aligned(UDMA_CACHELINE_ALIGNMENT)));
static uint8_t          gTxCompRingMem[NIMU_TOTAL_SUB_RX_CHANNELS]
                                    [NIMU_TEST_MAX_CHANS_PER_PORT]
                                    [NIMU_TEST_APP_RING_MEM_SIZE]
                                __attribute__ ((aligned(UDMA_CACHELINE_ALIGNMENT)));
struct                  Udma_FlowObj gUdmaFlowHnd[NIMU_NUM_PORTS]
                                __attribute__ ((aligned(UDMA_CACHELINE_ALIGNMENT)));
struct                  Udma_RingObj gUdmaRxRingHnd[NIMU_TOTAL_CHANNELS]
                                __attribute__ ((aligned(UDMA_CACHELINE_ALIGNMENT)));
struct                  Udma_RingObj gUdmaRxCompRingHnd[NIMU_TOTAL_CHANNELS]
                                __attribute__ ((aligned(UDMA_CACHELINE_ALIGNMENT)));
struct                  Udma_RingObj gUdmaRxRingHndCfgPsi[NIMU_TOTAL_CHANNELS]
                                __attribute__ ((aligned(UDMA_CACHELINE_ALIGNMENT)));
struct                  Udma_RingObj gUdmaRxCompRingHndCfgPsi[NIMU_TOTAL_CHANNELS]
                                __attribute__ ((aligned(UDMA_CACHELINE_ALIGNMENT)));
static uint8_t          gRxRingMem[NIMU_TOTAL_SUB_RX_CHANNELS][NIMU_TEST_APP_RING_MEM_SIZE]
                                __attribute__ ((aligned(UDMA_CACHELINE_ALIGNMENT)));
static uint8_t          gRxCompRingMem[NIMU_TOTAL_SUB_RX_CHANNELS]
                                      [NIMU_TEST_APP_RING_MEM_SIZE]
                                __attribute__ ((aligned(UDMA_CACHELINE_ALIGNMENT)));
static uint8_t          gRxRingMemCfgPsi[NIMU_TOTAL_SUB_RX_CHANNELS]
                                        [NIMU_TEST_APP_RING_MEM_SIZE]
                                __attribute__ ((aligned(UDMA_CACHELINE_ALIGNMENT)));
static uint8_t          gRxCompRingMemCfgPsi[NIMU_TOTAL_SUB_RX_CHANNELS]
                                            [NIMU_TEST_APP_RING_MEM_SIZE]
                                __attribute__ ((aligned(UDMA_CACHELINE_ALIGNMENT)));
struct                  Udma_FlowObj gUdmaFlowHndCfgPsi[NIMU_NUM_PORTS]
                                __attribute__ ((aligned(UDMA_CACHELINE_ALIGNMENT)));

typedef void *         HANDLE;
static HANDLE           hEcho = 0;
static HANDLE           hEchoUdp = 0;
static HANDLE           hData = 0;
static HANDLE           hNull = 0;
static HANDLE           hOob = 0;

Task_Handle             main_task;
NIMU_DEVICE_TABLE_ENTRY NIMUDeviceTable[NIMU_MAX_TABLE_ENTRIES];

extern uint32_t gCanMsgRxCnt, gCanMsgTxCnt;

/* ========================================================================== */
/*                          Function Definitions                              */
/* ========================================================================== */

/*
 *  ======== GatewayApp_initEmacK3========
 */
void GatewayApp_initEmacK3(uint32_t portNum, uint32_t index)
{
    EMAC_HwAttrs_V5 emac_cfg;
    EMAC_socGetInitCfg(0, &emac_cfg);
    int32_t chanNum = 0;
    int32_t subChanNum = 0;

    for (chanNum = 0; chanNum < emac_cfg.portCfg[portNum].nTxChans; chanNum++)
    {
        emac_cfg.portCfg[portNum].txChannel[chanNum].chHandle = (void *)&gUdmaTxChObj[index * chanNum];
        emac_cfg.portCfg[portNum].txChannel[chanNum].freeRingMem= (void*)&gTxRingMem[index * chanNum][0];
        emac_cfg.portCfg[portNum].txChannel[chanNum].compRingMem= (void*)&gTxCompRingMem[index * chanNum][0];
        emac_cfg.portCfg[portNum].txChannel[chanNum].hPdMem = (void*)&gUdmapDescRamTx[index * chanNum][0];
    }
    emac_cfg.portCfg[portNum].rxChannel.chHandle = (void *)&gUdmaRxChObj[index];
    emac_cfg.portCfg[portNum].rxChannel.flowHandle= (void *)&gUdmaFlowHnd[index];

    for (subChanNum = 0; subChanNum < emac_cfg.portCfg[portNum].rxChannel.nsubChan; subChanNum++)
    {
        emac_cfg.portCfg[portNum].rxChannel.subChan[subChanNum].freeRingMem[0] = (void*)&gRxRingMem[index * subChanNum][0];
        emac_cfg.portCfg[portNum].rxChannel.subChan[subChanNum].freeRingHandle[0] = (void*)&gUdmaRxRingHnd[index * subChanNum];
        emac_cfg.portCfg[portNum].rxChannel.subChan[subChanNum].compRingMem= (void*)&gRxCompRingMem[index * subChanNum][0];
        emac_cfg.portCfg[portNum].rxChannel.subChan[subChanNum].compRingHandle= (void*)&gUdmaRxCompRingHnd[index * subChanNum];
        emac_cfg.portCfg[portNum].rxChannel.subChan[subChanNum].hPdMem[0] = (void*)&gUdmapDescRamRx[index * subChanNum][0];
        emac_cfg.portCfg[portNum].rxChannel.subChan[subChanNum].eventHandle = (void *)&gUdmaRxCqEventObj[index * subChanNum];
    }
    emac_cfg.portCfg[portNum].rxChannelCfgOverPSI.chHandle = (void *)&gUdmaRxCfgPsiChObj[index];
    emac_cfg.portCfg[portNum].rxChannelCfgOverPSI.flowHandle= (void *)&gUdmaFlowHndCfgPsi[index];

    for (subChanNum = 0; subChanNum < emac_cfg.portCfg[portNum].rxChannelCfgOverPSI.nsubChan; subChanNum++)
    {
        emac_cfg.portCfg[portNum].rxChannelCfgOverPSI.subChan[subChanNum].freeRingMem[0] = (void*)&gRxRingMemCfgPsi[index * subChanNum][0];
        emac_cfg.portCfg[portNum].rxChannelCfgOverPSI.subChan[subChanNum].freeRingHandle[0] = (void*)&gUdmaRxRingHndCfgPsi[index * subChanNum];
        emac_cfg.portCfg[portNum].rxChannelCfgOverPSI.subChan[subChanNum].compRingMem= (void*)&gRxCompRingMemCfgPsi[index * subChanNum][0];
        emac_cfg.portCfg[portNum].rxChannelCfgOverPSI.subChan[subChanNum].compRingHandle= (void*)&gUdmaRxCompRingHndCfgPsi[index * subChanNum];
        emac_cfg.portCfg[portNum].rxChannelCfgOverPSI.subChan[subChanNum].hPdMem[0] = (void*)&gUdmapDescRamRxCfgPsi[index * subChanNum][0];
        emac_cfg.portCfg[portNum].rxChannelCfgOverPSI.subChan[subChanNum].eventHandle = (void *)&gUdmaRxCfgPsiCqEventObj[index * subChanNum];
    }

    EMAC_socSetInitCfg(0, &emac_cfg);

}

#ifdef ENABLE_CPSW_HW_STATS
/**
 *  \name GatewayApp_statsTask
 *  \brief get statistics
 *  \param a0
 *  \param a1
 *  \return none
 *
 */
void GatewayApp_statsTask(UArg a0, UArg a1)
{
    EMAC_STATISTICS_T cpswStats;

    uint32_t pNum = (uint32_t) a0;
    while (1)
    {
        memset(&cpswStats, 0, sizeof(EMAC_STATISTICS_T));
        if ((pNum == 6) &&  (emac_get_statistics(pNum, &cpswStats) == EMAC_DRV_RESULT_OK))
        {
            Utils_consolePrintf("**********CPSW stats for PORT NUMBER %d**********\n", pNum);
            Utils_consolePrintf("-----------------------------------------------------------------------------------------------------------------\n");
            Utils_consolePrintf(" RX |     Good:      %12u | Bcast:       %12u | Mcast:     %12u | Oct:          %12u |\n",
                            cpswStats.RxGoodFrames,
                            cpswStats.RxBCastFrames,
                            cpswStats.RxMCastFrames,
                            cpswStats.RxOctets);
            Utils_consolePrintf(" TX |     Good:      %12u | Bcast:       %12u | Mcast:     %12u | Oct           %12u |\n",
                            cpswStats.TxGoodFrames,
                            cpswStats.TxBCastFrames,
                            cpswStats.TxMCastFrames,
                            cpswStats.TxOctets);
            Utils_consolePrintf("---------------------------------------------------------------------------------------------------------------\n");
            Task_sleep(10000U);
        }
    }
}
#endif


/*
 *  ======== main ========
 */
int main(void)
{
    uint32_t nimu_device_index = 0U;
    Board_STATUS boardInitStatus =0;

    Board_initCfg cfg = BOARD_INIT_UART_STDIO |
                        BOARD_INIT_PINMUX_CONFIG |
                        BOARD_INIT_MODULE_CLOCK  |
                        BOARD_INIT_ETH_PHY;

    boardInitStatus = Board_init(cfg);
    if (boardInitStatus !=BOARD_SOK)
    {
        Utils_consolePrintf("Board_init failure\n");
        return(0);
    }
    Utils_consolePrintf("Board_init success\n");

    GatewayApp_initEmacK3(NIMU_EMAC_PORT_CPSW, nimu_device_index);

    /* Port 7 is "virtual port" configuration will will map to use Port 3 as tx and Port 0 as Rx */
    /* Port 8 is "virtual port" configuration will will map to use Port 1 as tx and Port 2 as Rx */
    /* with presence of interposer Card, we will use virtual port 7 in this example */
    {
        NIMUDeviceTable[nimu_device_index++].init =  NimuEmacInitFxn[NIMU_EMAC_PORT_CPSW];
    }

    NIMUDeviceTable[nimu_device_index].init =  NULL;

#ifdef ENABLE_CPSW_HW_STATS
    Task_Params     taskParams;
    Task_Params_init(&taskParams);
    taskParams.priority = 1U;
    taskParams.stackSize = 0x1400;
    taskParams.arg0 = (UArg)NIMU_EMAC_PORT_CPSW;
    Task_create (GatewayApp_statsTask, &taskParams, NULL);
#endif

    BIOS_start ();

    return 0;
}

void GatewayApp_stackInitHook(void* hCfg)
{
    int             rc;

   /* increase stack size */
   rc = 16384U;
   CfgAddEntry(hCfg, CFGTAG_OS, CFGITEM_OS_TASKSTKBOOT,CFG_ADDMODE_UNIQUE, sizeof(uint32_t), (uint8_t *)&rc, 0U );
}

void GatewayApp_netOpenHook(void)
{
#ifdef GATEWAYAPP_NDKSERVERS

    /* Create our local servers */
    hEcho = DaemonNew( SOCK_STREAMNC, 0U, 7U, dtask_tcp_echo,
                       OS_TASKPRINORM, OS_TASKSTKNORM, 0U, 3U );
    hEchoUdp = DaemonNew( SOCK_DGRAM, 0U, 7U, dtask_udp_echo,
                          OS_TASKPRINORM, OS_TASKSTKNORM, 0U, 1U );
    hData = DaemonNew( SOCK_STREAM, 0U, 1002U, dtask_tcp_datasrv,
                       OS_TASKPRINORM, OS_TASKSTKNORM, 0U, 3U );
    hNull = DaemonNew( SOCK_STREAMNC, 0U, 1001U, dtask_tcp_nullsrv,
                       OS_TASKPRINORM, OS_TASKSTKNORM, 0U, 3U );
    hOob  = DaemonNew( SOCK_STREAMNC, 0U, 999U, dtask_tcp_oobsrv,
                       OS_TASKPRINORM, OS_TASKSTKNORM, 0U, 3U );
#endif
}

void GatewayApp_netCloseHook(void)
{
#ifdef GATEWAYAPP_NDKSERVERS
    DaemonFree(hOob);
    DaemonFree(hNull);
    DaemonFree(hData);
    DaemonFree(hEchoUdp);
    DaemonFree(hEcho);
#endif
}


/* ========================================================================== */
/*                          Static Function Definitions                       */
/* ========================================================================== */
