/* 
 *  Ipc client to connect to simulator 
 *      
 *  :set expandtab
 *  :set shiftwidth=4
 *  :set tabstop=4
 */

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "dv.h"

static struct _IPC_SOCKET {
    char *name;
    char *ip;
    int  portn;
    int  fd;
    int  commit;
} __dvSock[IPC_SOCK_NUM+1] = {
    { "CPU0", "127.0.0.1", 8006, -1, 0 },
    { "CPU1", "127.0.0.1", 8007, -1, 0 },
    { "GBA",  "127.0.0.1", 8008, -1, 0 },
    { "NONE", "127.0.0.1", -1, -1, 0 }
};

int 
dvSocketRecv(int fd, char *buf, int nbytes)
{
    int nleft, nread;
    
    bzero(buf, nbytes);
    nleft = nbytes;

    while (nleft > 0) {
        nread = recv(fd, buf, nleft, 0);
        if (nread < 0) {
            printf("IpcReceive: recv failed, errno=%d\n", errno);
            return IPC_ERROR;
        }

        nleft -= nread;
        buf += nread;
    }

    return (nleft > 0) ? IPC_ERROR : IPC_OK;
}

int
dvSocketSend(int fd, char *buf, int nbytes)
{
    int nleft, nwritten;

    nleft = nbytes;
    while (nleft > 0) {
        nwritten = send(fd, buf, nleft, 0);
        if (nwritten <= 0) {
            printf("IpcSend: send failed, errno=%d\n", errno);
            return IPC_ERROR;
        }

        nleft -= nwritten;
        buf += nwritten;
    }

    return (nleft > 0) ? IPC_ERROR : IPC_OK;
}

int 
DV_IpcConnect(int which, int verbose)
{
    int fd;
    struct sockaddr_in      addr;
    int                     addrLen = sizeof (addr);
    char *simServer, *simPort;

    if (which >= IPC_SOCK_NUM) {
        printf("ERROR: connect %d socket not exist \n", which);
        return 0;
    }

    if (__dvSock[which].fd > 0) {
        printf("WARNING: %s already connected \n", __dvSock[which].name);
        return __dvSock[which].fd;
    }

    simServer = getenv("IOSIM_SERVER");
    if (simServer != NULL)
        __dvSock[which].ip = simServer;    

    simPort = getenv("IOSIM_PORT");
    if (simPort != NULL) 
        __dvSock[which].portn = strtoul(simPort, NULL, 0) + which;

    fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd <= 0) {
        printf("ERROR: Cannot open AF_INET socket\n");
        return 0;
    }

    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr(__dvSock[which].ip);
    addr.sin_port = htons(__dvSock[which].portn);

    if (connect(fd, (struct sockaddr *)&addr, addrLen) < 0) {
        close(fd);
        if (verbose) {
            printf("INFO: %s connect failed \n", __dvSock[which].name);
        }
        return 0;
    } else {
        __dvSock[which].fd = fd;
    }

    if (verbose) {
        printf("INFO: %s connect fd = %d \n", __dvSock[which].name, fd);
    }
    
    return fd;
}


int 
DV_IpcClose(int which, int verbose)
{
    if (which >= IPC_SOCK_NUM) {
        printf("ERROR: close %d socket not exist \n", which);
        return -1;
    } 
    
    if (__dvSock[which].fd < 0) {
        printf("ERROR: close %s socket not connected yet \n",
                    __dvSock[which].name);
        return -2;
    }

    if (verbose) {
        printf("INFO: %s(fd=%d) closed\n", 
            __dvSock[which].name, __dvSock[which].fd);
    }

    close(__dvSock[which].fd);
    __dvSock[which].fd    = -1;

    return 0;
}

int 
DV_IpcWaitTillConnected(int which, int verbose)
{
    int count;

    if (which >= IPC_SOCK_NUM) {
        printf("ERROR: %d socket not exist\n", which);
        return -1;
    } 
    
    if (__dvSock[which].fd > 0) {
        printf("WARNING: %s already connected\n", __dvSock[which].name);
        return 0;
    } 
    
    for (count = 0; ;++count) {
        if (DV_IpcConnect(which, verbose) <= 0) {
            if (errno == ECONNREFUSED) {
                printf("INFO: %s trying to connect to simulator [%d]\n",
                    __dvSock[which].name, count);
                if (count >= 20) return -1;
                sleep(3);
            } else return -1;
        } else break; 
    }
    return 0;
}    

int 
DV_IpcSendPkt(int which, p_ipc_pkth pkt, unsigned char *pdata)
{
    int i, len;
    unsigned int *ptmp;

    if (which >= IPC_SOCK_NUM) {
        printf("ERROR: %d send not exist \n", which);
        return -1;
    } 
    
    if (__dvSock[which].fd < 0) {
        printf("WARNING: send through %s not connected \n", __dvSock[which].name);
        return -1;
    }

    len = pkt->length;
    if (pkt->cmd_id & IPC_REQ_ID_COMMIT) {
       __dvSock[which].commit = 1;
    }

    if ((len > sizeof(ipc_pkth)) && (pdata == NULL)) {
        printf("ERROR: no data send at %s \n",
                    __dvSock[which].name);
    }

    ptmp = (unsigned int *) pkt;
    for (i=0; i<sizeof(ipc_pkth); i+=sizeof(int), ptmp++)
        *ptmp = htonl(*ptmp);
    dvSocketSend(__dvSock[which].fd, (char *) pkt, sizeof(ipc_pkth));

    if (len > sizeof(ipc_pkth)) {
        /* No endian convertion for data, 
           since we will send out the different size data
        ptmp = pdata;
        for (i=sizeof(ipc_pkth); i<len; i+=4, ptmp++)
            *ptmp = htonl(*ptmp);
        */
        dvSocketSend(__dvSock[which].fd, (char *)pdata, len-sizeof(ipc_pkth));
    } 

    return 0;
}

int
DV_IpcRecvPktHd(int which, p_ipc_pkth pkt)
{
    unsigned int *ptmp;
    int i;

    if (which >= IPC_SOCK_NUM) {
        printf("ERROR: %d recv_h not exist \n", which);
        return -1;
    } 
    
    if (__dvSock[which].fd < 0) {
        printf("WARNING: recv_h through %s not connected \n", __dvSock[which].name);
        return -1;
    }

    dvSocketRecv(__dvSock[which].fd, (char *) pkt, sizeof(ipc_pkth));
    ptmp = (unsigned int *) pkt;
    for (i=0; i<sizeof(ipc_pkth); i+=4, ptmp++)
        *ptmp = ntohl(*ptmp);

    if ((ptmp[0] == IPC_PKT_MAGIC && ptmp[1] == 0xffffffff &&
         ptmp[2] == 0xffffffff &&  ptmp[3] == 0xffffffff)) {
        DV_Exception(DV_EXP_ERROR, "Test timeout Pkt recv!");
    }

    return 0;
}

int
DV_IpcRecvPktData(int which, unsigned char *pdata, int sz)
{
    if (which >= IPC_SOCK_NUM) {
        printf("ERROR: %d recv_d not exist \n", which);
        return IPC_ERROR;
    } 
    
    if (__dvSock[which].fd < 0) {
        printf("WARNING: recv_d through %s not connected \n", __dvSock[which].name);
        return IPC_ERROR;
    }

    dvSocketRecv(__dvSock[which].fd, (char *) pdata, sz);
    /*  No endian conversion as well
    ptmp = pdata;
    for (i=0; i<count; i+=4, ptmp++) {
        *ptmp = ntohl(*ptmp);
    } */

    return IPC_OK;
} 

int 
DV_SocketSelect()
{
    fd_set rfd;
    struct timeval tm;
    int i, sel=0, nfd=0;
    
    tm.tv_sec = 0;
    tm.tv_usec = 1000;

    FD_ZERO(&rfd);
    for (i=0; i<IPC_SOCK_NUM; i++) {
        if (__dvSock[i].fd > 0) {
            FD_SET(__dvSock[i].fd, &rfd);
            if (__dvSock[i].fd > nfd)
                nfd = __dvSock[i].fd;
        }
    }

    if (select(nfd+1, &rfd, NULL, NULL, &tm) > 0) {
        for (i=0; i<IPC_SOCK_NUM; i++) {
            if ((__dvSock[i].fd > 0) && FD_ISSET(__dvSock[i].fd, &rfd)) {
                sel |= (1<<i);
            }
        }
    }

    return sel;
}

int 
DV_IpcIsConnected(int which)
{
    if ((which >= IPC_SOCK_NUM) || (which < 0)) {
        return 0;
    }

    return (__dvSock[which].fd > 0);
}

int 
DV_IpcIsCommit(int which)
{
    if ((which >= IPC_SOCK_NUM) || (which < 0))
        return 0;

    return (__dvSock[which].commit != 0);
}

int DV_IpcSetCommit(int which, int v)
{
    if ((which >= IPC_SOCK_NUM) || (which < 0))
        return 0;

    __dvSock[which].commit = v;

    return 1;
}

  /* SIM Ready State*/
int 
DV_IsAllSocketCommit()
{
    int i, commit=0;

    for (i=0; i<IPC_SOCK_NUM; i++) {
        if (__dvSock[i].fd > 0) {
            if (__dvSock[i].commit == 0) {
                commit = 0;
                break;
            }
            commit = 1;
        }
    }

    return commit;
}

char *
DV_IpcSocketName(int which)
{
    if ((which >= IPC_SOCK_NUM) || (which < 0)) {
        return __dvSock[IPC_SOCK_NUM].name;
    }

    return __dvSock[which].name;
}

int
DV_IpcIssueReq(
    const char *debug_msg,  /* Debug message*/
    int  which,             /* which socket */
    int  reqLen,            /* request packet size */
    int  cmd,               /* cmd */
    int  cmd_id,            /* command id */
    unsigned char *pdata    /* data buffer */
    )
{
    ipc_pkth r;

    if (which >= IPC_SOCK_NUM) {
        DV_Exception(DV_EXP_ERROR, "ERROR: socket %d not exist for %s", 
                which, debug_msg);
        return IPC_ERROR;
    }

    if (!DV_IpcIsConnected(which)) {
        DV_Exception(DV_EXP_ERROR, "ERROR: %s via %s not connect", 
                    debug_msg, DV_IpcSocketName(which));
        return IPC_ERROR;
    }

    if ((reqLen > sizeof(ipc_pkth)) && (pdata == NULL)) {
        DV_Exception(DV_EXP_ERROR, "ERROR: %s issue data is empty", debug_msg);
        return IPC_ERROR;
    }

    r.magic = IPC_PKT_MAGIC;
    r.length = reqLen;
    r.cmd = cmd; 
    r.cmd_id = cmd_id;

    DV_IpcSendPkt(which, &r, pdata);
    return IPC_OK;
}

int
DV_IpcBdRequest(
    const char *debug_msg,  /* Debug message*/
    int  which,             /* which socket */
    int  reqLen,            /* request packet size */
    int  replyLen,          /* reply packet size */
    int  cmd,               /* cmd */
    int  cmd_id,            /* command id */
    unsigned char *in,      /* data need to send out */
    unsigned char *out      /* data for reply */
    )
{
    ipc_pkth r;

    if ((replyLen > sizeof(ipc_pkth)) && (out==NULL)) {
        DV_Exception(DV_EXP_ERROR, "ERROR: %s recv data NULL", debug_msg);
        return IPC_ERROR;
    }

    DV_IpcIssueReq(debug_msg, which, reqLen, cmd, cmd_id, in);
    memset(&r, 0, sizeof(ipc_pkth));
    DV_IpcRecvPktHd(which, &r);

    if (r.magic != IPC_PKT_MAGIC) {
        DV_Exception(DV_EXP_ERROR, "ERROR: %s invalid packet", debug_msg);
        return IPC_ERROR;
    }
    
    if (r.length != replyLen) {
        DV_DiscardPktData(which, r.length);
        DV_Exception(DV_EXP_ERROR, "ERROR: %s invalid len=%d", 
                debug_msg, r.length);
        return IPC_ERROR;
    }

    if (r.cmd_id & IPC_REQ_ID_ERROR) {
        DV_DiscardPktData(which, r.length);
        DV_Exception(DV_EXP_ERROR, "ERROR: %s return error from simulator",
                 debug_msg);
        return IPC_ERROR;
    }

    if ((r.cmd_id & IPC_REQ_CMD_ID_MASK) != (cmd_id & IPC_REQ_CMD_ID_MASK)) {
        DV_DiscardPktData(which, r.length);
        DV_Exception(DV_EXP_ERROR, "ERROR: %s wrong id=0x%x", debug_msg, r.cmd_id);
        return IPC_ERROR;
    }

    if (replyLen > sizeof(ipc_pkth)) {
        DV_IpcRecvPktData(which, out, replyLen-sizeof(ipc_pkth));
    }

    return IPC_OK;
}

int 
DV_IpcWaitReplyId(
    const char *debug_msg,
    unsigned int which,
    unsigned int id,
    unsigned int replyMinLen,
    unsigned int replyMaxLen)
{
    ipc_pkth r;
    unsigned int *pdata;
    int len;

    while (1) {
        DV_IpcRecvPktHd(which, &r);

        if (r.cmd_id & IPC_REQ_ID_ERROR) {
            DV_DiscardPktData(which, r.length);
            DV_Exception(DV_EXP_ERROR, "ERROR: Simulator got the error");
            return 0;
        }

        if ( ((r.cmd_id & IPC_REQ_CMD_ID_MASK) == (id & IPC_REQ_CMD_ID_MASK)) 
            && ((r.length >= replyMinLen) && (r.length <= replyMaxLen)) ) {
            return r.length;
        }

        len = r.length - sizeof(ipc_pkth);
        if (len > 0) {
            pdata = (unsigned int *) malloc(len);
            if (pdata == NULL) {
                DV_Exception(DV_EXP_ERROR, "ERROR: %s alloc mem failed", debug_msg);
                return 0;
            }
            DV_IpcRecvPktData(which, (unsigned char *)pdata, len);
            free(pdata);
        }

        
        if ( (r.cmd_id & IPC_REQ_CMD_ID_MASK) == (id & IPC_REQ_CMD_ID_MASK) ) {
            if (r.cmd_id & IPC_REQ_ID_ERROR) { 
                DV_Exception(DV_EXP_ERROR, "ERROR: %s return error", debug_msg);
                return 0;
            } 

            if ((r.length < replyMinLen) || (r.length > replyMaxLen)) {
                DV_Exception(DV_EXP_ERROR, "ERROR: %s reply length is not correct", debug_msg);
                return 0;
            }
        }

        DV_Exception(DV_EXP_WARNING, "INFO: recv(in %s) id=0x%x cmd=0x%x len=%d ",
                debug_msg, r.cmd_id, r.cmd, r.length);
        DV_SimContinue(which);
    }

    return 0;
}

int
DV_DiscardPktData(int which, int len)
{
    unsigned int *pdata;

    if (len > sizeof(ipc_pkth)) {
        pdata = (unsigned int *) malloc(len - sizeof(ipc_pkth));
        
        if (pdata == NULL) {
            DV_Exception(DV_EXP_ERROR, "ERROR: DV_WaitCpuReset mem alloc failed");
            return IPC_ERROR;
        }

        DV_IpcRecvPktData(which, (unsigned char *)pdata, len - sizeof(ipc_pkth));
        free(pdata);
    }

    return IPC_OK;
}
