/*
 *               Copyright (C) 2006, BroadOn Communications Corp.
 *
 *  These coded instructions, statements, and computer programs contain
 *  unpublished  proprietary information of BroadOn Communications Corp.,
 *  and  are protected by Federal copyright law. They may not be disclosed
 *  to  third  parties or copied or duplicated in any form, in whole or in
 *  part, without the prior written consent of BroadOn Communications Corp.
 *
 */
#include <iostypes.h>
#include <priority.h>
#include <addr_map.h>
#include "thread.h"
#include "message.h"
#include "ios.h"
#include "hw.h"
#include "iosressrv.h"
#include "ioslibc.h"
#include "ahbops.h"

extern void iosInvalidateDCache(void *ptr, u32 bytes);
extern void iosFlushDCache(void *ptr, u32 bytes);

#ifdef LOG_FL
#   define IPC_LOG(...)       printf("IPC: " __VA_ARGS__)
#else
#   define IPC_LOG(...)
#endif

#ifdef DUMP_IPC
void dumpBytes (const u8* const ptr, const int length);
#endif

#define iosVirtualToPhysical(x) (u32)(x)
#define iosPhysicalToVirtual(x) (void*)(x)

#define REGION_IN_RANGE(p0, p1, s, e) \
    ( ((p0) <= (p1)) && ((p0) >= ((s)) && ((p1) <= (e))) )

#define CHECK_PPC_BUFFER(ptr, len) \
    do {\
        if (len) { \
            if (!REGION_IN_RANGE((u32)ptr, (u32)((u32)ptr + len) ,  \
                        DDR_BASE, IOP_GDDR3_START + DI_DMA_SP_SIZE) \
                    && !REGION_IN_RANGE((u32)ptr, (u32) ((u32)ptr + len), \
                        NAPA_BASE, NAPA_BASE + NAPA_SIZE)) { \
                printf("IPC: failed buf check: ptr=%08x len=%d\n", ptr, len); \
                rv = IOS_ERROR_ACCESS; \
                goto end; \
            } \
        } \
    } while (0)

static
IOSMessageQueueId __ipcMQ;

static u32 __mailboxAck;
static u32 __inFlight;

#define MAX_MSG_QUEUE       50
#define MAX_SRV_INFLIGHT    48

static struct 
{
    u32                 count;
    u32                 rptr;
    u32                 wptr;
    IOSResourceRequest *buf[MAX_SRV_INFLIGHT];
} __responses;

static inline void
iosWriteIPCIOPCtrlReg(u32 val)
{
    busWrt32(ACR_IPCIOPCTRL_TRUSTED, val);
}

static inline u32
iosReadIPCPPCCtrlReg(void)
{
    return busRd32(ACR_IPCPPCCTRL_TRUSTED);
}

static inline void
iosWriteIPCPPCCtrlReg(u32 val)
{
    busWrt32(ACR_IPCPPCCTRL_TRUSTED, val);
}

static inline u32
iosReadIPCIOPCtrlReg(void)
{
    return busRd32(ACR_IPCIOPCTRL_TRUSTED);
}

static void
__iosQueueResponse(IOSResourceRequest *resp)
{
    IPC_LOG("__iosQueueResponse: cnt: %d val: %p\n", 
            __responses.count, resp);
    __responses.buf[__responses.wptr] = resp;
    __responses.wptr = (__responses.wptr + 1) % 
                       (sizeof(__responses.buf) / sizeof(__responses.buf[0]));
    __responses.count++;
}

static void
__iosSendResponse(void)
{
    u32 bitm = IPCIOPCTRL_OUT_MSG_MASK, // generate MSG IPC interrupt
        req;

    IPC_LOG("__iosSendResponse: ack: %d, cnt: %d val: %x\n", 
            __mailboxAck, __responses.count, 
            (u32)__responses.buf[__responses.rptr]);

    if (!__mailboxAck || __responses.count == 0)
    {
        goto out;   // ignore
    }

    req = iosVirtualToPhysical((u32)__responses.buf[__responses.rptr]);
    iosFlushDCache((void*)req, sizeof(IOSResourceRequest));

    /* Flush status back to GBA */
    //iosFlushMem(IOS_WB_IOD);

    // write the reply address
    IO_WRITE(ACR_IPCS2PMSG_TRUSTED, req);

    __responses.rptr = (__responses.rptr + 1) % (sizeof(__responses.buf) 
                            / sizeof(__responses.buf[0]));
    __responses.count--;

    if (__inFlight == sizeof(__responses.buf) / sizeof(__responses.buf[0])) 
    {
            // ACK the last IPC request - when buf[] got full, the last request 
            // was not ACK'ed
            bitm |= IPCIOPCTRL_OUT_ACK_MASK;
            IPC_LOG("__iosSendResponse: ACK\n"); 
    }
    __inFlight--;
    IPC_LOG("__iosSendResponse: count: %d inflight: %d\n", 
                __responses.count, __inFlight); 
    __mailboxAck = 0;
    iosWriteIPCIOPCtrlReg((iosReadIPCIOPCtrlReg() 
                                & (IPCIOPCTRL_ACK_INTR_MASK 
                                   | IPCIOPCTRL_MSG_INTR_MASK)) 
                               | bitm);
out:
    return;
}

static void
__iosProcessIpc(IOSResourceRequest *req)
{
    /* Need to flush results back */
    {
        /* req->cmd saved in req->handle */
        switch (req->handle) 
        {
        case IOS_READ:
            req->args.read.outPtr = (u8*)iosVirtualToPhysical(
                                            req->args.read.outPtr);

            iosFlushDCache(req->args.read.outPtr, req->status);
            break;

        case IOS_IOCTL:
            req->args.ioctl.outPtr = (u8*)iosVirtualToPhysical(
                                            req->args.ioctl.outPtr);

            iosFlushDCache(req->args.ioctl.inPtr, req->args.ioctl.inLen);
            iosFlushDCache(req->args.ioctl.outPtr, req->args.ioctl.outLen);
            break;

        case IOS_IOCTLV:
        {
            u32 i;
            IOSResourceIoctlv *v = &req->args.ioctlv;
/*
            for (i = 0; i < req->args.ioctlv.writeCount; ++i) 
            {
                v->vector[v->readCount + i].base = (u8*)iosVirtualToPhysical(
                                        (u32)v->vector[v->readCount + i].base);
            }
*/
            // convert everything
            for (i = 0; 
                 i < (req->args.ioctlv.readCount + req->args.ioctlv.writeCount);
                 ++i) 
            {
                v->vector[i].base = (u8*)iosVirtualToPhysical(
                                        (u32)v->vector[i].base);
                iosFlushDCache(v->vector[i].base, v->vector[i].length);
            }
            req->args.ioctlv.vector = (IOSIoVector*)iosVirtualToPhysical(
                                                      req->args.ioctlv.vector);
            iosFlushDCache(&v->vector, (req->args.ioctlv.readCount +
                           req->args.ioctlv.writeCount) * sizeof(IOSIoVector));
            break;
        }
        default:
            // check for invalid cmd/handle 
            break;
        }
    }

    /* Flush status back to GBA */
    //iosFlushMem(IOS_WB_IOD);

    __iosQueueResponse(req);
    __iosSendResponse();
}

static void
__iosDispatchIpc(u32 v)
{
    IOSResourceRequest *req = NULL;
    IOSError rv = IOS_ERROR_OK;
    IOSFd fd;
    int   i;
    u32 reqValid = 0;

    CHECK_PPC_BUFFER(v, sizeof(IOSResourceRequest));
    reqValid = 1;

    /* Examine cmd header */
    req = (IOSResourceRequest *)v;

    req = (IOSResourceRequest*)iosPhysicalToVirtual(req);
    //iosInvalidateRdb(IOS_RB_IOD);
    iosInvalidateDCache(req, sizeof(*req));

    fd = req->handle;
    req->handle = req->cmd;

    IPC_LOG("CMD: %d\n", req->cmd);
    switch (req->cmd) 
    {
    case IOS_OPEN:
    { 
        u32 len = 0;
        u8 *path = NULL; 

        CHECK_PPC_BUFFER(req->args.open.path, IOS_PATH_MAX + 1);
        req->args.open.path = (u8*)iosPhysicalToVirtual(req->args.open.path);
        iosInvalidateDCache((void*)req->args.open.path, IOS_PATH_MAX + 1);
        path = (u8 *)req->args.open.path;
        len = strnlen(path, IOS_PATH_MAX + 1);
        if (len > IOS_PATH_MAX) {
            printf("IPC: failed open path check: path=%s len=%d\n", path, len);
            rv = IOS_ERROR_INVALID;
            goto end;
        }
        IPC_LOG("OPEN: path=%s, flags=%d, q=0x%x\n", 
                req->args.open.path, req->args.open.flags, __ipcMQ);

        rv = iosOpenAsync(req->args.open.path, req->args.open.flags, 
                          __ipcMQ, req);
        break;
    }
    case IOS_CLOSE:
        IPC_LOG("CLOSE: fd=%d q=0x%x\n", fd, __ipcMQ);

        rv = iosCloseAsync(fd, __ipcMQ, req);
        break;

    case IOS_READ:
        IPC_LOG("READ: fd=%d buf=0x%x len=%d q=0x%x\n", 
               fd, req->args.read.outPtr, req->args.read.outLen, __ipcMQ);

        CHECK_PPC_BUFFER(req->args.read.outPtr, req->args.read.outLen);
        req->args.read.outPtr = (u8*)iosPhysicalToVirtual(req->args.read.outPtr);
        rv = iosReadAsync(fd, req->args.read.outPtr, req->args.read.outLen, 
                          __ipcMQ, req);
        break;

    case IOS_WRITE:
        IPC_LOG("WRITE: fd=%d buf=0x%x len=%d q=0x%x\n", 
               fd, req->args.write.inPtr, req->args.write.inLen, __ipcMQ);

        CHECK_PPC_BUFFER(req->args.write.inPtr, req->args.write.inLen);
        req->args.write.inPtr = (u8*)iosPhysicalToVirtual(req->args.write.inPtr);
        iosInvalidateDCache(req->args.write.inPtr, req->args.write.inLen);
        rv = iosWriteAsync(fd, req->args.write.inPtr, req->args.write.inLen, 
                           __ipcMQ, req);
        break;

    case IOS_SEEK:
        IPC_LOG("SEEK: fd=%d offset=0x%x whence=%d q=0x%x\n", 
               fd, req->args.seek.offset, req->args.seek.whence, __ipcMQ);

        rv = iosSeekAsync(fd, req->args.seek.offset, req->args.seek.whence, 
                          __ipcMQ, req);
        break;

    case IOS_IOCTL:
        IPC_LOG("IOCTL: fd=%d cmd=%d inbuf=0x%x inlen=%d outbuf=0x%x "
               "outLen=%d q=0x%x\n",
               fd, req->args.ioctl.cmd, req->args.ioctl.inPtr,
               req->args.ioctl.inLen, req->args.ioctl.outPtr, 
               req->args.ioctl.outLen, __ipcMQ);

        CHECK_PPC_BUFFER(req->args.ioctl.inPtr, req->args.ioctl.inLen);
        CHECK_PPC_BUFFER(req->args.ioctl.outPtr, req->args.ioctl.outLen);

        req->args.ioctl.inPtr = (u8*)iosPhysicalToVirtual(req->args.ioctl.inPtr);
        req->args.ioctl.outPtr = (u8*)iosPhysicalToVirtual(
                                        req->args.ioctl.outPtr);
        iosInvalidateDCache(req->args.ioctl.inPtr, req->args.ioctl.inLen);
        iosInvalidateDCache(req->args.ioctl.outPtr, req->args.ioctl.outLen);

#ifdef DUMP_IPC
        printf ("IPC input bytes:\n");
        dumpBytes(req->args.ioctl.inPtr, req->args.ioctl.inLen);
#endif
        rv = iosIoctlAsync(fd, req->args.ioctl.cmd, req->args.ioctl.inPtr, 
                           req->args.ioctl.inLen, req->args.ioctl.outPtr, 
                           req->args.ioctl.outLen, __ipcMQ, req);
        break;

    case IOS_IOCTLV:
    {
        u32 rcount, wcount;
        IOSResourceIoctlv *v = &req->args.ioctlv;

        rcount = v->readCount;
        wcount = v->writeCount;
                
        IPC_LOG("IOCTLV: fd=%d cmd=%d rcount=%d wcount=%d vector=0x%x q=0x%x\n",
               fd, req->args.ioctlv.cmd, rcount, wcount, 
               req->args.ioctlv.vector, __ipcMQ);

        CHECK_PPC_BUFFER(v->vector, (rcount + wcount) * sizeof(IOSIoVector));
        req->args.ioctlv.vector = (IOSIoVector*)iosPhysicalToVirtual(
                                                    req->args.ioctlv.vector);
        iosInvalidateDCache(&v->vector[0], (rcount + wcount) * sizeof(IOSIoVector));

        for (i = 0; i < (rcount + wcount); ++i) {
            CHECK_PPC_BUFFER(v->vector[i].base, v->vector[i].length);
            v->vector[i].base = (u8*)iosPhysicalToVirtual(v->vector[i].base);
            iosInvalidateDCache(v->vector[i].base, v->vector[i].length);
        }
        
        rv = iosIoctlvAsync(fd, req->args.ioctlv.cmd, rcount, wcount, 
                            req->args.ioctlv.vector, __ipcMQ, req);
        break;
    }

    default:
        rv = IOS_ERROR_INVALID;
        printf("Dispatch switch ERROR: %d cmd: %d\n", rv, req->cmd);
    }

end:
    if (reqValid && rv < 0) {
        // no reply expected, report the error
        IPC_LOG("Dispatch ERROR: %d cmd: %d\n", rv, req->cmd);
        req->status = rv;
        __iosProcessIpc(req);
    }
    /* If request is invalid, it is ignored. No reply is sent. This
     * will stall further IPC requests. This is probably OK, because
     * getting an invalid request is a fatal error.
     */
    return;
}

extern IOSError iosSetThreadPriority(IOSThreadId id, u32 priority);
void
__iosIpcThread(u32 arg)
{
    static IOSMessage array[MAX_MSG_QUEUE];
    IOSMessage msg;
    static IOSResourceRequest ipcMsg;
    IOSError   rv;

    iosSetThreadPriority(0, IOS_PRIORITY_IPC);

    ipcMsg.cmd = IOS_IPC_MSG;

    /* Create queue and register to handle events */
    if ((__ipcMQ = iosCreateMessageQueue(array, sizeof(array) / 
                                         sizeof(array[0]))) < 0) 
    {
        IPC_LOG("Unable to create IPC message queue: %d\n", __ipcMQ);
        goto out;
    }

    if ((rv = iosHandleEvent(IOS_EVENT_IPCIOP, __ipcMQ, (u32)&ipcMsg)) 
                != IOS_ERROR_OK) 
    {
        IPC_LOG("Unable to register IPC MSG event handler: %d\n", rv);
        goto out;
    }
    if ((iosReadIPCPPCCtrlReg() & 
        (IPCPPCCTRL_ACK_INTR_MASK | IPCPPCCTRL_MSG_INTR_MASK)) == 0)
        // if not IOS relaunch
        iosWriteIPCPPCCtrlReg(0);

    /* Enable IPC interrupts and allow incoming message */
    iosClearAndEnableIPCIOPIntr();
    /* XXXwheeler: don't ack the IPC mailbox until ES says to do it */
#if 0
    iosWriteIPCIOPCtrlReg(IPCIOPCTRL_ACK_INTR_MASK 
                           | IPCIOPCTRL_MSG_INTR_MASK 
                           | IPCIOPCTRL_OUT_ACK_MASK);
#endif

    while (1) 
    {
        if (iosReceiveMessage(__ipcMQ, &msg, IOS_MESSAGE_BLOCK) == 
                IOS_ERROR_OK) 
        {
            IOSResourceRequest *req = (IOSResourceRequest*)msg;
            IPC_LOG("Got Msg %x\n", msg);

            switch (req->cmd)
            {
            case IOS_REPLY:
                IPC_LOG("Got REPLY: rv=%d\n", req->status);
                __iosProcessIpc(req);
                break;

            case IOS_IPC_MSG:
            {
                u32 bm = iosReadIPCIOPCtrlReg();

                IPC_LOG("bitmask %x\n", bm);
                if (bm & IPCIOPCTRL_IN_ACK_MASK) {
                    /* ACK interrupt */
                    __mailboxAck = 1;

                    IPC_LOG("Got ACK\n");

                    // clear ACK INTR bit
                    iosWriteIPCIOPCtrlReg((iosReadIPCIOPCtrlReg() 
                                            & (IPCIOPCTRL_ACK_INTR_MASK 
                                            | IPCIOPCTRL_MSG_INTR_MASK))
                                           | IPCIOPCTRL_IN_ACK_MASK);
                    iosClearAndEnableIPCIOPIntr();
                    __iosSendResponse();
                }
                else
                if (bm & IPCIOPCTRL_IN_MSG_MASK) {
                    /* IPC request */
                    IPC_LOG("Got MSG\n");

                    u32 m = (u32)IO_READ(ACR_IPCP2SMSG_TRUSTED);
                    bm = IPCIOPCTRL_IN_MSG_MASK; // clear MSG INTR bit

                    IPC_LOG("MSG READ: ipcp2smsg: %x inflight: %d\n", 
                            m, __inFlight);

                    if (__inFlight < (sizeof(__responses.buf) 
                                      / sizeof(__responses.buf[0]) - 1)) 
                    {
                        // generate ACK 
                        bm |= IPCIOPCTRL_OUT_ACK_MASK;
                        IPC_LOG("OUT_ACK\n");
                    } else {
                        IPC_LOG("max inflight  = %d limit reached\n", sizeof(__responses.buf)/ sizeof(__responses.buf[0]));
                    }

                    iosWriteIPCIOPCtrlReg((iosReadIPCIOPCtrlReg() 
                                            & (IPCIOPCTRL_ACK_INTR_MASK 
                                               | IPCIOPCTRL_MSG_INTR_MASK)) 
                                           | bm);
                    iosClearAndEnableIPCIOPIntr();
                    __inFlight++;
                    __iosDispatchIpc(m);
                }
                else {
                    printf("UNKNOWN INTERRUPT: %x / %x\n", 
                            busRd32(ACR_IOPINTSTS_TRUSTED),
                            busRd32(ACR_INTMASK_TRUSTED));
                    IPC_LOG("Invalid INT\n");
                }
                break;
            }
            default:
                printf("UNKNOWN MESSAGE: %u\n", req->cmd);
                // error
                break;
            }
        }
    }

out:
    return;
}

/* ----------------------------------------------------------------------- */
#ifdef DUMP_IPC
void
dumpBytes (const u8* const ptr, const int length)
{
    int i;

    for (i = 0; i < length; i++) {
        if (i % 20 == 0)
            printf ("\n");
        printf ("%02x ", ptr[i]);
    }
    printf ("\n");
}
#endif
    
/* ----------------------------------------------------------------------- */
