/*
 *               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 "iosresclt.h"
#include "ios.h"
#include <stdio.h>

// HW register/bits (IPCP2SMSG, IPCP2SMSG, IPCPPCCTRL) definitions
#include "hw.h"
#include "ipc.h"


#define diff(a, b)                                                           \
    ((a) < (b)) ? ((u32)0xffffffff - (b) + (a) + 1) : (a - b)

//static 
//u32 __inFlight = 0;

// temp declarations (not in RVL_OS.h yet)

// tunable
#define MAX_INQUEUE         16 

// related to MAX_INFLIGHT - RPC server
#define MAX_CLT_INFLIGHT    (MAX_INQUEUE + MAX_SRV_INFLIGHT + 8) 

#define IPC_LOG(...)
//#define IPC_LOG(...)       printf("CLT: " __VA_ARGS__)

typedef struct IOSRpcRequest
{
    // DON'T move this req field; otherwise code will break
    IOSResourceRequest  req;
    IOSIpcCb            cb;
    u32                 idx;    // slab allocation idx
    // for sync. calls
    IOSMessageQueueId   mqId;
} IOSRpcRequest;

#define IOS_WAIT_INIT(rpc)                                                    \
    {                                                                         \
    IOSMessage msgArray, msg;                                                 \
                                                                              \
    if ((rpc->mqId = IOS_CreateMessageQueue(&msgArray, 1)) < 0)               \
    {                                                                         \
        ret = rpc->mqId;                                                      \
        IPC_LOG("ERROR IOS_CreateMessageQueue: %d", ret);                     \
        goto err;                                                             \
    }

#define IOS_WAIT(rpc)                                                         \
                                                                              \
    if (ret != IOS_ERROR_OK)                                                  \
    {                                                                         \
        IPC_LOG("ERROR __iosQueueRequest: %d", ret);                          \
        goto err;                                                             \
    }                                                                         \
    if ((ret = IOS_ReceiveMessage(rpc->mqId, &msg, IOS_MESSAGE_BLOCK))        \
                != IOS_ERROR_OK)                                              \
    {                                                                         \
        IPC_LOG("ERROR IOS_ReceiveMessage: %d", ret);                         \
        goto err;                                                             \
    }                                                                         \
    }

static 
u32 __mailboxAck = 1;

#define OSVirtualToPhysical(addr)    (u32)(addr)
#define OSPhysicalToVirtual(addr)    (void*)(addr)

#define DCFlushRange(addr, size)
#define DCInvalidateRange(addr, size) (addr) = (addr)

#define IO_DISABLE(ctrl, val)
#define IO_ENABLE(ctrl)

#define __OSSetInterruptHandler(inter, handler)                               \
        ipcIntHandler(inter, handler)

static IOSRpcRequest buff[MAX_CLT_INFLIGHT];

extern
IOSMessageQueueId __ipcMQ;

#   undef IO_WRITE
#   undef IO_READ

// ignore ACK_INTR, MSG_INTR, IN_ACK, IN_MSG
static
IOSError ioWriteClt(u32 addr, u32 val)
{
    IOSError rv = IOS_ERROR_OK;

    if ((addr) == IPCP2SMSG)
    {
        ipcp2smsg = (u32)(val);
        IPC_LOG("WRITE: ipcp2smsg: %x\n", val);
    }
    else
    {
        if (((u32)(val) & OUT_ACK) == OUT_ACK)
        {
            static
            u32   _ipcAck = IOS_IPC_ACK;
            IPC_LOG("WRITE ACK\n");
            if ((rv = IOS_SendMessage(__ipcMQ, (u32)&_ipcAck,
                                IOS_MESSAGE_BLOCK)) != IOS_ERROR_OK)
            {
                IPC_LOG("IOS_SendMessage() err: %d\n", rv);
                goto out;
            }
        }
        if (((u32)(val) & OUT_MSG) == OUT_MSG)
        {
            static
            u32   _ipcMsg = IOS_IPC_MSG;
            IPC_LOG("WRITE MSG\n");
            if ((rv = IOS_SendMessage(__ipcMQ, (u32)&_ipcMsg,
                                IOS_MESSAGE_BLOCK)) != IOS_ERROR_OK)
            {
                IPC_LOG("IOS_SendMessage() err: %d\n", rv);
                goto out;
            }
        }
    }
out:
    return rv;
}

#define   IO_WRITE(addr, val)                                                 \
        if (ioWriteClt(addr, val) != IOS_ERROR_OK)                            \
        {                                                                     \
            goto out;                                                         \
        }

#define   IO_READ(addr)                                                       \
        ((u32)(addr) == (u32)IPCP2SMSG) ? ipcs2pmsg : 0

static struct 
{
    // separate counters to avoid disable/enable interrupts (critical section)
    // between an application RM call and IpcAckHandler()
    u32            rcount;  // read counter
    u32            wcount;  // write counter
    u32            rptr;    // read ptr
    u32            wptr;    // write ptr
    IOSRpcRequest *buf[MAX_INQUEUE];

} __responses;

// slab allocator {

static
IOSRpcRequest *__rpcArr = 0;

static
u32 __freeRpc[MAX_CLT_INFLIGHT];

static
u32 __freeIdx = 0;

static IOSRpcRequest *
ipcAlloc(void)
{
    IOSRpcRequest *ret = 0;
    u32 idx;

    // disable IPC INT
    IO_DISABLE(IPCPPCCTRL, MSG_INTR);

    if (__freeIdx >= sizeof(__freeRpc) / sizeof(__freeRpc[0]))
    {
        goto err;
    }

    idx = __freeRpc[__freeIdx];

    ret = (IOSRpcRequest*)&__rpcArr[idx];

    ret->idx = idx;

    __freeIdx++;

err:
    IO_ENABLE(IPCPPCCTRL);
    return ret;
}


static IOSError 
IpcFree(IOSRpcRequest *rpc)
{
    IOSError ret = IOS_ERROR_OK;

    // disable IPC INT
    IO_DISABLE(IPCPPCCTRL, MSG_INTR);

    if (__freeIdx == 0)
    {
        ret = IOS_ERROR_INVALID;
        goto err;
    }

    __freeIdx--;

    __freeRpc[__freeIdx] = rpc->idx;

err:
    IO_ENABLE(IPCPPCCTRL);
    return ret;
}

// } slab allocator


static IOSError
__ipcQueueRequest(IOSRpcRequest *req)
{
    IOSError ret = IOS_ERROR_OK;
    IPC_LOG("__ipcQueueRequest(%p)\n", req);

    if (diff(__responses.wcount, __responses.rcount) >= 
            sizeof(__responses.buf) / sizeof(__responses.buf[0]))
    {
        ret = IOS_ERROR_QFULL;
        IPC_LOG("ERROR IpcReplyHandler()\n");
        goto err;
    }

    // flush the IPC request struct and input buffers here 
    // rather than in IPC ACK handler
    DCFlushRange(req, sizeof(req->req));

    // enqueue it 
    __responses.buf[__responses.wptr] = req;
    __responses.wptr = (__responses.wptr + 1) % (sizeof(__responses.buf) 
                                                / sizeof(__responses.buf[0]));
    __responses.wcount++;

    //__inFlight++;

err:
    return ret;
}


static void
__ipcSendRequest(void)
{
    if (diff(__responses.wcount, __responses.rcount) > 0) 
    {
        // set the IPC message (ptr)
        IO_WRITE(IPCP2SMSG, 
                 OSVirtualToPhysical(__responses.buf[__responses.rptr]));

        // dequeue it
        __responses.rptr = (__responses.rptr + 1) % (sizeof(__responses.buf) 
                                                  / sizeof(__responses.buf[0]));
        __responses.rcount++;


        __mailboxAck = 0;

        // sets the IOP IPC interrupt
        IO_WRITE(IPCPPCCTRL, OUT_MSG);
    }
out:
    return;
}

void 
IpcReplyHandler(
    __OSInterrupt   interrupt,
    OSContext      *context);

void 
IpcReplyHandler(
    __OSInterrupt   interrupt,
    OSContext      *context)
{
    IOSResourceRequest *req;
    // read the reply address

    //ASSERT(interrupt == OS_INTERRUPT_INT_IPC);

    IPC_LOG("IpcReplyHandler() {\n");

    IOSRpcRequest *rep;
    rep = (IOSRpcRequest*)OSPhysicalToVirtual(IO_READ(IPCP2SMSG));
    IPC_LOG("READ: ipcs2pmsg: %x\n", ipcs2pmsg);                

    req = &rep->req;

    // invalidate the reply struct
    DCInvalidateRange(req, sizeof(*req));

    // invalidate the output buffers
    switch (req->handle) // former cmd
    {
    case IOS_READ: // former cmd

        DCInvalidateRange(req->args.read.outPtr, req->args.read.outLen);
        break;

    case IOS_IOCTL:

        DCInvalidateRange(req->args.ioctl.outPtr, req->args.ioctl.outLen);
        break;

    case IOS_IOCTLV:
    {
        int i;
        IOSResourceIoctlv *v = &req->args.ioctlv;

        for (i = 0; i < req->args.ioctlv.readCount; ++i) 
        {
            DCInvalidateRange(v->vector[i].base, v->vector[i].length);
        }

        break;
    }
    default:
        break;
    }

    // callback
    if (rep->cb)
        rep->cb(req);

    // free the request memory
    IpcFree(rep);

    // ACK & Clear the message
    IO_WRITE(IPCPPCCTRL, OUT_ACK | IN_MSG);

    //__inFlight--;
out:
    IPC_LOG("IpcReplyHandler() }\n");
    return;
}


void 
IpcAckHandler(
    __OSInterrupt   interrupt,
    OSContext      *context);

void 
IpcAckHandler(
    __OSInterrupt   interrupt,
    OSContext      *context)
{
    //ASSERT(interrupt == OS_INTERRUPT_INT_IPC_ACK);
    IPC_LOG("IpcAckHandler()\n");

    __mailboxAck = 1;
    __ipcSendRequest();

    // clear ACK
    IO_WRITE(IPCPPCCTRL, IN_ACK);
out:
    return;
}

IOSError  iosReleaseCb(IOSResourceRequest *req)
{
    IOSRpcRequest *rpc = (IOSRpcRequest*)req;
    return IOS_SendMessage(rpc->mqId, 0, IOS_MESSAGE_BLOCK);
}

IOSError
IpcCltInit(void)
{
    u32 i;
    IOSError ret = IOS_ERROR_OK;
    // initialize the shared (between IOP and Broadway) DDR heap

    // allocate RPC request structures
    __rpcArr = (IOSRpcRequest *) &buff;

    // init the free rpc struct indexes
    for (i = 0; i < sizeof(__freeRpc) / sizeof(__freeRpc[0]); i++)
    {
        __freeRpc[i] = i;
    }

    // setup int handler for IPC REQ (actually replies on the RPC client)
    __OSSetInterruptHandler(IOS_EVENT_IPC_MSG, IpcReplyHandler);

    // setup int handler for IPC ACK
    __OSSetInterruptHandler(IOS_EVENT_IPC_ACK, IpcAckHandler);

    // enable IPC ACK & IPC & set IPC ACK
    IO_WRITE(IPCPPCCTRL, ACK_INTR | MSG_INTR | OUT_ACK);
out:
    return ret;
}

/*
    "path" needs to be allocated in shared DDR memory
*/
                                             
IOSError 
IOS_OpenAsync(
        const char *path, 
        u32         flags, 
        IOSIpcCb    cb)
{
    IOSError ret = IOS_ERROR_OK;
    IOSResourceRequest *req;

    // allocate the RPC request structure
    IOSRpcRequest *rpc = (IOSRpcRequest *) ipcAlloc();
    if (rpc == 0)
    {
        ret = IOS_ERROR_NOMEM;
        goto err;
    }

    req = &rpc->req;

    // initialize the RPC request
    rpc->cb = cb;
    req->cmd = IOS_OPEN;

    req->args.open.path = path;
    req->args.open.flags = flags;

    // send the RPC request
    if ((ret = __ipcQueueRequest(rpc)) == IOS_ERROR_OK && __mailboxAck)
        __ipcSendRequest();

err:
    return ret;

}

IOSError
_IOS_Open(
        const char *path,
        u32         flags)
{
    IOSError ret = IOS_ERROR_OK;
    IOSResourceRequest *req;

    // allocate the RPC request structure
    IOSRpcRequest *rpc = (IOSRpcRequest *) ipcAlloc();
    if (rpc == 0)
    {
        ret = IOS_ERROR_NOMEM;
        goto err;
    }

    req = &rpc->req;

    // initialize the RPC request
    rpc->cb = iosReleaseCb;
    req->cmd = IOS_OPEN;

    req->args.open.path = path;
    req->args.open.flags = flags;

    IOS_WAIT_INIT(rpc);

    // send the RPC request
    if ((ret = __ipcQueueRequest(rpc)) == IOS_ERROR_OK && __mailboxAck)
        __ipcSendRequest();

    IOS_WAIT(rpc);

    ret = req->status;

err:
    return ret;


}

IOSError 
IOS_CloseAsync(
        IOSFd     fd, 
        IOSIpcCb  cb)
{
    IOSError ret = IOS_ERROR_OK;
    IOSResourceRequest *req;

    // allocate the RPC request structure
    IOSRpcRequest *rpc = (IOSRpcRequest *) ipcAlloc();
    if (rpc == 0)
    {
        ret = IOS_ERROR_NOMEM;
        goto err;
    }

    req = &rpc->req;

    // initialize the RPC request
    rpc->cb = cb;
    req->cmd = IOS_CLOSE;
    req->handle = (u32)fd;

    // send the RPC request
    if ((ret = __ipcQueueRequest(rpc)) == IOS_ERROR_OK && __mailboxAck)
        __ipcSendRequest();

err:
    return ret;
}

IOSError
_IOS_Close(
        IOSFd     fd)
{
    IOSError ret = IOS_ERROR_OK;
    IOSResourceRequest *req;

    // allocate the RPC request structure
    IOSRpcRequest *rpc = (IOSRpcRequest *) ipcAlloc();
    if (rpc == 0)
    {
        ret = IOS_ERROR_NOMEM;
        goto err;
    }

    req = &rpc->req;

    // initialize the RPC request
    rpc->cb = iosReleaseCb;
    req->cmd = IOS_CLOSE;
    req->handle = (u32)fd;

    IOS_WAIT_INIT(rpc);

    // send the RPC request
    if ((ret = __ipcQueueRequest(rpc)) == IOS_ERROR_OK && __mailboxAck)
        __ipcSendRequest();

    IOS_WAIT(rpc);

    ret = req->status;

err:
    return ret;
}

/*
    "buf" needs to be allocated in shared DDR memory
*/
IOSError 
IOS_ReadAsync(
        IOSFd     fd, 
        void     *buf, 
        u32       len, 
        IOSIpcCb  cb)
{
    IOSError ret = IOS_ERROR_OK;
    IOSResourceRequest *req;

    // allocate the RPC request structure
    IOSRpcRequest *rpc = (IOSRpcRequest *) ipcAlloc();
    if (rpc == 0)
    {
        ret = IOS_ERROR_NOMEM;
        goto err;
    }

    req = &rpc->req;

    // initialize the RPC request
    rpc->cb = cb;
    req->cmd = IOS_READ;
    req->handle = (u32)fd;

    req->args.read.outPtr = buf;
    req->args.read.outLen = len;

    // send the RPC request
    if ((ret = __ipcQueueRequest(rpc)) == IOS_ERROR_OK && __mailboxAck)
        __ipcSendRequest();

err:
    return ret;
}

IOSError
_IOS_Read(
        IOSFd     fd,
        void     *buf,
        u32       len)
{
    IOSError ret = IOS_ERROR_OK;
    IOSResourceRequest *req;

    // allocate the RPC request structure
    IOSRpcRequest *rpc = (IOSRpcRequest *) ipcAlloc();
    if (rpc == 0)
    {
        ret = IOS_ERROR_NOMEM;
        goto err;
    }

    req = &rpc->req;

    // initialize the RPC request
    rpc->cb = iosReleaseCb;
    req->cmd = IOS_READ;
    req->handle = (u32)fd;

    req->args.read.outPtr = buf;
    req->args.read.outLen = len;

    IOS_WAIT_INIT(rpc);

    // send the RPC request
    if ((ret = __ipcQueueRequest(rpc)) == IOS_ERROR_OK && __mailboxAck)
        __ipcSendRequest();

    IOS_WAIT(rpc);

    ret = req->status;

err:
    return ret;
}

/*
    "buf" needs to be allocated in shared DDR memory
*/

IOSError 
IOS_WriteAsync(
        IOSFd     fd, 
        void     *buf, 
        u32       len, 
        IOSIpcCb  cb)
{
    IOSError ret = IOS_ERROR_OK;
    IOSResourceRequest *req;

    // allocate the RPC request structure
    IOSRpcRequest *rpc = (IOSRpcRequest *) ipcAlloc();
    if (rpc == 0)
    {
        ret = IOS_ERROR_NOMEM;
        goto err;
    }

    req = &rpc->req;

    // initialize the RPC request
    rpc->cb = cb;
    req->cmd = IOS_WRITE;
    req->handle = (u32)fd;

    req->args.write.inPtr = buf;
    req->args.write.inLen = len;

    // flush the buffer
    DCFlushRange(buf, len);

    // send the RPC request
    if ((ret = __ipcQueueRequest(rpc)) == IOS_ERROR_OK && __mailboxAck)
        __ipcSendRequest();

err:
    return ret;
}

IOSError
_IOS_Write(
        IOSFd     fd,
        void     *buf,
        u32       len)
{
    IOSError ret = IOS_ERROR_OK;
    IOSResourceRequest *req;

    // allocate the RPC request structure
    IOSRpcRequest *rpc = (IOSRpcRequest *) ipcAlloc();
    if (rpc == 0)
    {
        ret = IOS_ERROR_NOMEM;
        goto err;
    }

    req = &rpc->req;

    // initialize the RPC request
    rpc->cb = iosReleaseCb;
    req->cmd = IOS_WRITE;
    req->handle = (u32)fd;

    req->args.write.inPtr = buf;
    req->args.write.inLen = len;

    // flush the buffer
    DCFlushRange(buf, len);

    IOS_WAIT_INIT(rpc);

    // send the RPC request
    if ((ret = __ipcQueueRequest(rpc)) == IOS_ERROR_OK && __mailboxAck)
        __ipcSendRequest();

    IOS_WAIT(rpc);

    ret = req->status;

err:
    return ret;
}

IOSError 
IOS_SeekAsync(
        IOSFd     fd, 
        s32       offset, 
        u32       whence, 
        IOSIpcCb  cb)
{
    IOSError ret = IOS_ERROR_OK;
    IOSResourceRequest *req;

    // allocate the RPC request structure
    IOSRpcRequest *rpc = (IOSRpcRequest *) ipcAlloc();
    if (rpc == 0)
    {
        ret = IOS_ERROR_NOMEM;
        goto err;
    }

    req = &rpc->req;

    // initialize the RPC request
    rpc->cb = cb;
    req->cmd = IOS_SEEK;
    req->handle = (u32)fd;

    req->args.seek.offset = offset;
    req->args.seek.whence = whence;

    // send the RPC request
    if ((ret = __ipcQueueRequest(rpc)) == IOS_ERROR_OK && __mailboxAck)
        __ipcSendRequest();

err:
    return ret;
}

IOSError
_IOS_Seek(
        IOSFd     fd,
        s32       offset,
        u32       whence)
{
    IOSError ret = IOS_ERROR_OK;
    IOSResourceRequest *req;

    // allocate the RPC request structure
    IOSRpcRequest *rpc = (IOSRpcRequest *) ipcAlloc();
    if (rpc == 0)
    {
        ret = IOS_ERROR_NOMEM;
        goto err;
    }

    req = &rpc->req;

    // initialize the RPC request
    rpc->cb = iosReleaseCb;
    req->cmd = IOS_SEEK;
    req->handle = (u32)fd;

    req->args.seek.offset = offset;
    req->args.seek.whence = whence;

    IOS_WAIT_INIT(rpc);

    // send the RPC request
    if ((ret = __ipcQueueRequest(rpc)) == IOS_ERROR_OK && __mailboxAck)
        __ipcSendRequest();

    IOS_WAIT(rpc);

    ret = req->status;

err:
    return ret;
}

/*
    "input", "output" need to be allocated in shared DDR memory
*/
IOSError
IOS_IoctlAsync(
        IOSFd     fd, 
        s32       cmd,
        void     *input, 
        u32       inputLen,
        void     *output, 
        u32       outputLen,
        IOSIpcCb  cb)
{
    IOSError ret = IOS_ERROR_OK;
    IOSResourceRequest *req;

    // allocate the RPC request structure
    IOSRpcRequest *rpc = (IOSRpcRequest *) ipcAlloc();
    if (rpc == 0)
    {
        ret = IOS_ERROR_NOMEM;
        goto err;
    }

    req = &rpc->req;

    // initialize the RPC request
    rpc->cb = cb;
    req->cmd = IOS_IOCTL;
    req->handle = (u32)fd;

    req->args.ioctl.cmd = (u32)cmd;
    req->args.ioctl.outPtr = output;
    req->args.ioctl.outLen = outputLen;
    req->args.ioctl.inPtr = input;
    req->args.ioctl.inLen = inputLen;

    DCFlushRange(input, inputLen);

    // send the RPC request
    if ((ret = __ipcQueueRequest(rpc)) == IOS_ERROR_OK && __mailboxAck)
        __ipcSendRequest();

err:
    return ret;
}

IOSError
_IOS_Ioctl(
        IOSFd     fd,
        s32       cmd,
        void     *input,
        u32       inputLen,
        void     *output,
        u32       outputLen)
{
    IOSError ret = IOS_ERROR_OK;
    IOSResourceRequest *req;

    // allocate the RPC request structure
    IOSRpcRequest *rpc = (IOSRpcRequest *) ipcAlloc();
    if (rpc == 0)
    {
        ret = IOS_ERROR_NOMEM;
        goto err;
    }

    req = &rpc->req;

    // initialize the RPC request
    rpc->cb = iosReleaseCb;
    req->cmd = IOS_IOCTL;
    req->handle = (u32)fd;

    req->args.ioctl.cmd = (u32)cmd;
    req->args.ioctl.outPtr = output;
    req->args.ioctl.outLen = outputLen;
    req->args.ioctl.inPtr = input;
    req->args.ioctl.inLen = inputLen;

    DCFlushRange(input, inputLen);

    IOS_WAIT_INIT(rpc);

    // send the RPC request
    if ((ret = __ipcQueueRequest(rpc)) == IOS_ERROR_OK && __mailboxAck)
        __ipcSendRequest();

    IOS_WAIT(rpc);

    ret = req->status;

err:
    return ret;
}

/*
    vector's "input", "output" need to be allocated in shared DDR memory
*/
IOSError 
IOS_IoctlvAsync(
        IOSFd        fd, 
        s32          cmd,
        u32          readCount,
        u32          writeCount,
        IOSIoVector *vect,
        IOSIpcCb     cb)
{
    IOSError ret = IOS_ERROR_OK;
    IOSResourceRequest *req;
    IOSResourceIoctlv  *v;
    u32 i, j;

    // allocate the RPC request structure
    IOSRpcRequest *rpc = (IOSRpcRequest *) ipcAlloc();
    if (rpc == 0)
    {
        ret = IOS_ERROR_NOMEM;
        goto err;
    }

    req = &rpc->req;

    // initialize the RPC request
    rpc->cb = cb;
    req->cmd = IOS_IOCTLV;
    req->handle = (u32)fd;

    req->args.ioctlv.cmd = (u32)cmd;
    req->args.ioctlv.readCount = readCount;
    req->args.ioctlv.writeCount = writeCount;
    req->args.ioctlv.vector = vect;

    v = &req->args.ioctlv;
    for (i = 0, j = v->readCount; i < req->args.ioctlv.writeCount; ++i) 
    {
        DCFlushRange(v->vector[j + i].base, v->vector[j + i].length);
    }

    // send the RPC request
    if ((ret = __ipcQueueRequest(rpc)) == IOS_ERROR_OK && __mailboxAck)
        __ipcSendRequest();

err:
    return ret;
}

IOSError
_IOS_Ioctlv(
        IOSFd        fd,
        s32          cmd,
        u32          readCount,
        u32          writeCount,
        IOSIoVector *vect)
{
    IOSError ret = IOS_ERROR_OK;
    IOSResourceRequest *req;
    IOSResourceIoctlv  *v;
    u32 i, j;

    // allocate the RPC request structure
    IOSRpcRequest *rpc = (IOSRpcRequest *) ipcAlloc();
    if (rpc == 0)
    {
        ret = IOS_ERROR_NOMEM;
        goto err;
    }

    req = &rpc->req;

    // initialize the RPC request
    rpc->cb = iosReleaseCb;
    req->cmd = IOS_IOCTLV;
    req->handle = (u32)fd;

    req->args.ioctlv.cmd = (u32)cmd;
    req->args.ioctlv.readCount = readCount;
    req->args.ioctlv.writeCount = writeCount;
    req->args.ioctlv.vector = vect;

    v = &req->args.ioctlv;
    for (i = 0, j = v->readCount; i < req->args.ioctlv.writeCount; ++i)
    {
        DCFlushRange(v->vector[j + i].base, v->vector[j + i].length);
    }

    IOS_WAIT_INIT(rpc);

    // send the RPC request
    if ((ret = __ipcQueueRequest(rpc)) == IOS_ERROR_OK && __mailboxAck)
        __ipcSendRequest();

    IOS_WAIT(rpc);

    ret = req->status;

err:
    return ret;
}

