/*
 *               Copyright (C) 2005, 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 <nitro.h>
#include <nitro/hw/ARM9/mmap_global.h>
#include <nitro/ctrdg/common/ctrdg_common.h>
#include <iostypes.h>
#include <sc/addr_map.h>
#include <ios.h>

//#define IOS_DEBUG
#ifdef IOS_DEBUG
#define LOG(s, args...)	OS_Printf(s, ## args)
#else
#define LOG(s, args...)
#endif

#define IOS_IPC_PENDING 0xdeadbeef

#define IPC_OUT_L_REG   IPC_SP_START + 0x0
#define IPC_OUT_H_REG   IPC_SP_START + 0x2

#define IPC_IN_L_REG    IPC_SP_START + 0x4
#define IPC_IN_H_REG    IPC_SP_START + 0x6

#define IPC_CTRL_REG    IPC_SP_START + 0x8
#define IPC_CTRL_MASK_WE_MASK   0x8000
#define IPC_CTRL_MASK_ACK_MASK  0x0200
#define IPC_CTRL_MASK_MSG_MASK  0x0100

#define IPC_CTRL_IN_ACK_MASK    0x0008
#define IPC_CTRL_IN_MSG_MASK    0x0004
#define IPC_CTRL_OUT_ACK_MASK   0x0002
#define IPC_CTRL_OUT_MSG_MASK   0x0001

/*
 * Access to the GBA cartridge bus from the DS ARM9 is
 * fundamentally different from ARM7 access in pure GBA mode:
 *
 * the bus must be locked and data copied either manually by
 * the cpu or using one of the DMA channels (the CTRDG_ routines
 * in the Nitro SDK).
 * 
 * The IPC implementation must copy command blocks and buffers
 * in both directions.
 *
 * This is done by reserving a block in GBA space starting 
 * just below the 16MB boundary.  Since only one IPC can be in
 * flight at a time, this is the simplest approach.
 *
 * The layout of this area is (from lower to higher addresses):
 *
 *   req block
 *   ioctl vector (if present)
 *   input buffers
 *   output buffers
 *
 * Buffers are rounded to 4 byte boundaries for efficiency in copying.
 */

static u16 __IO_READ16(u16 *);
static u32 __IO_READ(u32 *);

#define IO_READ16(addr)         __IO_READ16((u16 *)(addr))
#define IO_READ(addr)           __IO_READ((u32 *)(addr))
#define IO_WRITE16(addr, val)   (void) CTRDG_Write16((u16 *)(addr), (u16)(val))
#define IO_WRITE(addr, val)     (void) CTRDG_Write32((u32 *)(addr), (u32)(val))

static u16
__IO_READ16(u16 *addr)
{
    u16 val;
    CTRDG_Read16(addr, &val);
    return val;
}

static u32
__IO_READ(u32 *addr)
{
    u32 val;
    CTRDG_Read32(addr, &val);
    return val;
}


#define MAX_BLOCKS  8
typedef struct {
    IOSResourceRequest req;
    u32 ipcStatus;
    OSThread *thread;
    u32 inUse;
    u32 pad;        /* Pad to cacheline size */
} IPC;

static IPC __blocks[MAX_BLOCKS] __attribute__ ((aligned(16)));

#define IPC_BASE        (DS_IPC_BASE)
#define IPC_ALIGN_MASK  (63)
#define IPC_VECTOR      ((IPC_BASE + sizeof(IPC) + IPC_ALIGN_MASK) & ~IPC_ALIGN_MASK)

#define IOS_PATH_MAX 63

static u32 __DsToNcAddr(u32 a) {
    u32 rv = 0;
    if (a >= HW_MAIN_MEM && a < HW_MAIN_MEM_END) {
        rv = (a & (HW_MAIN_MEM_SIZE-1)) + IPC_BASE;
    } else if (a >= HW_DTCM && a < HW_DTCM_END) {
        rv = (a - HW_DTCM) + IPC_BASE + HW_MAIN_MEM_SIZE;
    } else {
        OS_Printf("DS_TO_NC_ADDR(): unhandled address (%08x)\n", a);
        rv = 0;
    }
//OS_Printf("DS_TO_NC(%08x) = %08x\n", a, rv);
    return rv;
}

static u32 __NcToDsAddr(u32 a) {
    u32 off = a - IPC_BASE;
    u32 rv = 0;
    if (a < IPC_BASE || off > (HW_MAIN_MEM_SIZE + HW_DTCM_SIZE)) {
        OS_Printf("NC_TO_DS_ADDR(): invalid address (%08x)\n", a);
    } else if (off < HW_MAIN_MEM_SIZE) {
        rv = HW_MAIN_MEM + off;
    } else {
        rv = HW_DTCM + off - HW_MAIN_MEM_SIZE;
    }
//OS_Printf("NC_TO_DS(%08x) = %08x\n", a, rv);
    return rv;
}

#define DS_TO_NC_ADDR(a) (__DsToNcAddr((u32) (a)))
#define NC_TO_DS_ADDR(a) (__NcToDsAddr((u32) (a)))

#define NC_WRITE_BYTE(addr, b) \
    if (1) { \
        u32 offset = (u32) (addr) & (sizeof(u32)-1); \
        u32 *aDst = (u32 *) ((addr) - offset); \
        u32 v = IO_READ(aDst); \
        v = (v & ~(0xff << (8 * offset))) | ((b) << (8 * offset)); \
        IO_WRITE(aDst, v); \
    } else

/*
 * Copy from DRAM into cartridge space
 */
static u8 *
__copyOutBuf(u8 *src, u32 len)
{
    u8 *dst = (u8 *)DS_TO_NC_ADDR(src);
    u8 *rv = dst;

    switch (((u32)dst | (u32)src) & 3) {
    case 0:
        CTRDG_CpuCopy32(src, dst, len & ~3);
        dst += len & ~3;
        src += len & ~3;
        len &= 3;
        break;
    case 2:
        CTRDG_CpuCopy16(src, dst, len & ~1);
        dst += len & ~1;
        src += len & ~1;
        len &= 1;
        break;
    }

    while (len--) {
        NC_WRITE_BYTE(dst, *src);
        ++dst;
        ++src;
    }

    return rv;
}

u32 strnlen(const char *strp, int len);

static unsigned char *
__copyOutString(const char *sp)
{
    u32 n;

    /* copy at most IOS_PATH_MAX characters */
    n = strnlen(sp, IOS_PATH_MAX + 1);
    if (n > IOS_PATH_MAX) {
        return NULL;
    }

    return __copyOutBuf((u8 *) sp, n+1);

}

/*
 * Copy data from GBA IPC area to DRAM
 */
static u8 *
__copyInBuf(u8 *src, u32 len)
{
    u8 *dst = (u8 *)NC_TO_DS_ADDR(src);

    switch (((u32)dst | (u32)src) & 3) {
    case 0:
        CTRDG_CpuCopy32(src, dst, len & ~3);
        if (len & 3) {
            src += (len & ~3);
            dst += (len & ~3);
            CTRDG_CpuCopy8(src, dst, len & 3);
        }
        break;
    case 2:
        CTRDG_CpuCopy16(src, dst, len & ~1);
        if (len & 1) {
            src += (len & ~1);
            dst += (len & ~1);
            CTRDG_CpuCopy8(src, dst, len & 1);
        }
        break;
    case 1:
    case 3:
        CTRDG_CpuCopy8(src, dst, len);
        break;
    }
    return dst;
}

static void
__cartHandler(void)
{
    u16 reg = IO_READ16(IPC_CTRL_REG);

    if (reg & IPC_CTRL_IN_MSG_MASK) {
        IPC *ipc = (IPC *)__copyInBuf((u8*)IO_READ(IPC_IN_L_REG), sizeof(IPC));
        IO_WRITE16(IPC_CTRL_REG, IPC_CTRL_IN_MSG_MASK|IPC_CTRL_OUT_ACK_MASK);
        OS_WakeupThreadDirect(ipc->thread);
    }
}

static IOSResourceRequest *
__getCommandBlock(void)
{
    static int isInitialized = 0;

    OSIntrMode enabled;
    IPC *rv = NULL;
    int i;

    enabled = OS_DisableInterrupts();

    /*
     * Make sure the CTRDG interface is initialized
     */
    if (!isInitialized) {
        if (!CTRDG_IsEnabled()) {
            OS_InitThread();
            CTRDG_Init();
            CTRDG_Enable(TRUE);
        }

        /*
         * Enable cartridge interrupts and install handler
         */
        IO_WRITE16(IPC_CTRL_REG, IPC_CTRL_IN_MSG_MASK);
        OS_SetIrqFunction(OS_IE_CARTRIDGE, __cartHandler);
        OS_EnableIrqMask(OS_IE_CARTRIDGE);
        IO_WRITE16(IPC_CTRL_REG, IPC_CTRL_MASK_WE_MASK|IPC_CTRL_MASK_MSG_MASK|IPC_CTRL_OUT_ACK_MASK);

        isInitialized++;
    }

    for (i = 0; i < MAX_BLOCKS; ++i) {
        if (__blocks[i].inUse == 0) {
            break;
        }
    }

    if (i < MAX_BLOCKS) {
        rv = __blocks + i;
        rv->inUse = 1;
    }

    OS_RestoreInterrupts(enabled);

    return (IOSResourceRequest *)rv;
}

static void
__releaseCommandBlock(IOSResourceRequest *req)
{
    IPC *ipc = (IPC *) req;
    ipc->inUse = 0;
}

//#define IPC_PERF 1

#if defined(IPC_PERF)
u32 __ipcCount = 0;
u64 __ipcTotTicks = 0;
u64 __ipcMaxTicks = 0;
#endif

static IOSError
__issueRequest(IOSResourceRequest *req)
{
    IPC *ipc = (IPC *)req;
    IPC *gipc;
    OSIntrMode enabled;

#if defined(IPC_PERF)
    u64 startTick;
    u64 endTick;

    __ipcCount++;
    startTick = OS_GetTick();
#endif

    enabled = OS_DisableInterrupts();

    /* Wait for mailbox to become available */
    while ((IO_READ16(IPC_CTRL_REG) & IPC_CTRL_IN_ACK_MASK) == 0) {
        /* do nothing */
    }
    /* Clear the IN_ACK bit again */
    IO_WRITE16(IPC_CTRL_REG, IPC_CTRL_IN_ACK_MASK);
    
    /* Mark buffer as pending */
    ipc->ipcStatus = IOS_IPC_PENDING;
    ipc->thread = OS_GetCurrentThread();

    /* Copy req block to cartridge space */
    gipc = (IPC *)__copyOutBuf((u8 *)ipc, sizeof(*ipc));

    /* Write command buffer address to mailbox and issue command */
    IO_WRITE(IPC_OUT_L_REG, gipc);
    IO_WRITE16(IPC_CTRL_REG, IPC_CTRL_OUT_MSG_MASK);
    { int foo;
        foo = OS_DisableIrq();
        if (!foo) {
            OS_TPrintf("==IR: Re-enable IRQ in IME\n");
        }
    }
    (void) OS_EnableIrq();

    OS_SleepThread(NULL);

#if defined(IPC_PERF)
    endTick = OS_GetTick();
    endTick -= startTick;
    __ipcTotTicks += endTick;
    if (endTick > __ipcMaxTicks) __ipcMaxTicks = endTick;
#endif

    OS_RestoreInterrupts(enabled);

    return req->status;
}

IOSFd
IOS_Open(const char *path, u32 flags)
{
    IOSResourceRequest *req;
    IOSError rv;

#if defined(IPC_PERF)
    if (!OS_IsTickAvailable()) {
        OS_InitTick();
    }
#endif

    /* Allocate a cmd block */
    if ((req = __getCommandBlock()) == NULL) {
        rv = IOS_ERROR_MAX;
        goto end;
    }

    /* Fill out cmd block */
    req->cmd = IOS_OPEN;
    req->handle = 0;
    req->args.open.path = (const unsigned char *)__copyOutString(path);
    req->args.open.flags = flags;

    /* issue request to NC and spin until done */
    rv = __issueRequest(req);

    /* Free cmd block */
    __releaseCommandBlock(req);

end:
    return rv;
}

IOSError
IOS_Close(IOSFd fd)
{
    IOSResourceRequest *req;
    IOSError rv;

    /* Allocate a cmd block */
    if ((req = __getCommandBlock()) == NULL) {
        rv = IOS_ERROR_MAX;
        goto end;
    }

    /* Fill out cmd block */
    req->cmd = IOS_CLOSE;
    req->handle = (u32)fd;

    /* issue request to NC and spin until done */
    rv = __issueRequest(req);

    /* Free cmd block */
    __releaseCommandBlock(req);

end:
    return rv;
}

s32
IOS_Read(IOSFd fd, void *buf, u32 count)
{
    IOSResourceRequest *req;
    IOSError rv;

    /* Allocate a cmd block */
    if ((req = __getCommandBlock()) == NULL) {
        rv = IOS_ERROR_MAX;
        goto end;
    }

    /* Fill out cmd block */
    req->cmd = IOS_READ;
    req->handle = (u32)fd;
    req->args.read.outPtr = (u8 *)DS_TO_NC_ADDR(buf);
    req->args.read.outLen = count;

    /* issue request to NC and spin until done */
    rv = __issueRequest(req);

    /* copy back the read data (XXX even if error?) */
    __copyInBuf(req->args.read.outPtr, count);

    /* Free cmd block */
    __releaseCommandBlock(req);

end:
    return rv;
}

s32
IOS_Write(IOSFd fd, void *buf, u32 count)
{
    IOSResourceRequest *req;
    IOSError rv;
    u8 *gbuf = __copyOutBuf(buf, count);

    /* Allocate a cmd block */
    if ((req = __getCommandBlock()) == NULL) {
        rv = IOS_ERROR_MAX;
        goto end;
    }

    /* Fill out cmd block */
    req->cmd = IOS_WRITE;
    req->handle = (u32)fd;
    req->args.write.inPtr = gbuf;
    req->args.write.inLen = count;

    /* issue request to NC and spin until done */
    rv = __issueRequest(req);

    /* Free cmd block */
    __releaseCommandBlock(req);

end:
    return rv;
}

s32
IOS_Seek(IOSFd fd, s32 offset, u32 whence)
{
    IOSResourceRequest *req;
    IOSError rv;

    /* Allocate a cmd block */
    if ((req = __getCommandBlock()) == NULL) {
        rv = IOS_ERROR_MAX;
        goto end;
    }

    /* Fill out cmd block */
    req->cmd = IOS_SEEK;
    req->handle = (u32)fd;
    req->args.seek.offset = offset;
    req->args.seek.whence = whence;

    /* issue request to NC and spin until done */
    rv = __issueRequest(req);

    /* Free cmd block */
    __releaseCommandBlock(req);

end:
    return rv;
}

IOSError
IOS_Ioctl(IOSFd fd, s32 cmd, void *input, u32 input_bytes,
		   void *output, u32 output_bytes)
{
    IOSResourceRequest *req;
    IOSError rv;
    u8 *gInput = __copyOutBuf((u8 *)input, input_bytes);

    /* Allocate a cmd block */
    if ((req = __getCommandBlock()) == NULL) {
        rv = IOS_ERROR_MAX;
        goto end;
    }
//OS_Printf("Ioctl: cmd=%d, in=%08x (%d), out=%08x (%d)\n", cmd, input, input_bytes, output, output_bytes);

    /* Fill out cmd block */
    req->cmd = IOS_IOCTL;
    req->handle = (u32)fd;
    req->args.ioctl.cmd = (u32)cmd;
    req->args.ioctl.inPtr = gInput;
    req->args.ioctl.inLen = input_bytes;
    req->args.ioctl.outPtr = (u8 *)DS_TO_NC_ADDR(output);
    req->args.ioctl.outLen = output_bytes;

    /* issue request to NC and spin until done */
    rv = __issueRequest(req);

    /* copy back the output data (XXX even if error?) */
    __copyInBuf(req->args.ioctl.outPtr, output_bytes);

    /* Free cmd block */
    __releaseCommandBlock(req);

end:
    return rv;
}

#define MAX_VECTOR_SIZE 16

IOSError
IOS_Ioctlv(IOSFd fd, s32 cmd, u32 readCount, u32 writeCount,
		    IOSIoVector *vector)
{
    IOSResourceRequest *req;
    IOSIoVector lVector[MAX_VECTOR_SIZE];
    IOSError rv;
    u32 i;

    /* Allocate a cmd block */
    if ((req = __getCommandBlock()) == NULL) {
        rv = IOS_ERROR_MAX;
        goto end;
    }

    /* Reserve space for io vectors */
    if (readCount + writeCount > MAX_VECTOR_SIZE) {
        rv = IOS_ERROR_MAX;
        goto end;
    }
//OS_Printf("Ioctlv: cmd=%d readCount=%d, writeCount=%d\n", cmd, readCount, writeCount);
    //for (i = 0; i < readCount  + writeCount; ++i) {
        //OS_Printf("v[%d]: base=%08x, len=%d\n", i, vector[i].base, vector[i].length);
    //}

    /* Fill out cmd block */
    req->cmd = IOS_IOCTLV;
    req->handle = (u32)fd;
    req->args.ioctlv.cmd = (u32)cmd;
    req->args.ioctlv.readCount = readCount;
    req->args.ioctlv.writeCount = writeCount;

    for (i = 0; i < readCount; i++) {
        lVector[i].base = __copyOutBuf(vector[i].base, vector[i].length);
        lVector[i].length = vector[i].length;
    }
    for ( ; i < readCount + writeCount; i++) {
        lVector[i].base = (u8 *)DS_TO_NC_ADDR(vector[i].base);
        lVector[i].length = vector[i].length;
    }

    req->args.ioctlv.vector = (IOSIoVector *)__copyOutBuf((u8 *)lVector, i * sizeof(IOSIoVector));

    /* issue request to NC and spin until done */
    rv = __issueRequest(req);

    /* Copy data back for "out" vectors */
    for (i = readCount; i < readCount + writeCount; i++) {
        __copyInBuf(lVector[i].base, vector[i].length);
    }

    /* Free cmd block */
    __releaseCommandBlock(req);

end:
    return rv;
}
