/*
 *               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 <iostypes.h>
#include <ioslibc.h>
#include <estypes.h>
#include <es.h>

#include <sc/sc.h>
#include <sc/addr_map.h>
#include "lock.h"
#include "thread.h"
#include "except.h"
#include "message.h"
#include "memory.h"
#include "sklog.h"
#include "resource.h"

#define IOS_PATH_MAX 63

#define IOS_NUM_RESOURCES    18
typedef struct IOSResource {
    char path[IOS_PATH_MAX+1];
    u32 pathLen;
    IOSMessageQueue *mq;
    u32 owner;
} IOSResource;
static IOSResource __resources[IOS_NUM_RESOURCES];

#define IOS_DESCRIPTOR_MAX  8
typedef struct {
    IOSResourceHandle handle;
    IOSResource *resource;
} IOSResourceDescriptor;
static IOSResourceDescriptor __descriptors[IOS_PROCESS_MAX][IOS_DESCRIPTOR_MAX];

static IOSMessageQueue __responseQueues[IOS_THREAD_MAX];
static IOSMessage __responses[IOS_THREAD_MAX];
static char __paths[IOS_THREAD_MAX][IOS_PATH_MAX+1] __attribute__((aligned(16)));

typedef struct {
    IOSResourceRequest req;
    IOSMessageQueue *mq;
    IOSResourceRequest *reply;
    IOSThreadId tid;
    u32 inUse;
} IOSResourceCommandBlock;

#define IOS_ASYNC_CMD_MAX        16
#define IOS_ASYNC_PER_THREAD_MAX 4
static IOSResourceCommandBlock __requests[IOS_THREAD_MAX+IOS_ASYNC_CMD_MAX] __attribute__((aligned(16)));
static u32 __activeRequests[IOS_THREAD_MAX];

#define CHECK_PATH(path, pathLen) \
    if (((pathLen) = strnlen((path), IOS_PATH_MAX+1)) > IOS_PATH_MAX) { \
        rv = IOS_ERROR_INVALID; \
        goto end; \
    } \
    CHECK_READABLE_BUFFER((path), (pathLen), THIS_THREAD->pidMask)

#define CHECK_RESOURCE_OWNER(res) \
    if ((res).owner != THIS_THREAD->pidMask) { \
        rv = IOS_ERROR_ACCESS; \
        goto end; \
    } else

#define CHECK_FD(fd) \
    if ( (((fd) != IOS_AES_FD) && ((fd) != IOS_SHA_FD) && ((fd) != IOS_HMAC_FD)) && \
         (((fd) < 0) || ((fd) >= IOS_DESCRIPTOR_MAX) || \
          (!__descriptors[THIS_THREAD->pid][(fd)].resource)) ) { \
        rv = IOS_ERROR_INVALID; \
        goto end; \
    } else

#define LOCK_RESOURCE()  __iosLockDisable(&__iosGlobalLock)
#define UNLOCK_RESOURCE(mask)  __iosUnlockRestore(&__iosGlobalLock, (mask))

#define GET_CMD_BLOCK() \
    if ((rv = __getCmdBlock(mq != 0, &blk)) != IOS_ERROR_OK) { \
        goto end; \
    } else

#define RELEASE_CMD_BLOCK() \
    if (blk && mq && rv != IOS_ERROR_OK) { \
        blk->inUse = 0; \
        __activeRequests[blk->tid]--; \
    } else

static IOSResourceDescriptor __aesDesc, __shaDesc, __hmacDesc;
#define GET_DESCRIPTOR(fd) ((fd) == IOS_AES_FD) ? &__aesDesc : ((fd) == IOS_SHA_FD) ? &__shaDesc : ((fd) == IOS_HMAC_FD) ? &__hmacDesc : (&__descriptors[THIS_THREAD->pid][(fd)])

static IOSError
__getCmdBlock(u32 async, IOSResourceCommandBlock **blk) {
    IOSError rv = IOS_ERROR_OK;
    IOSThreadId id = iosGetThreadId();

    if (!async) {
        *blk = __requests + id;
    } else {
        int i;
        if (__activeRequests[id] == IOS_ASYNC_PER_THREAD_MAX) {
            rv = IOS_ERROR_MAX;
            goto end;
        }
        for (i = 0; i < IOS_ASYNC_CMD_MAX; ++i) {
            if (__requests[i+IOS_THREAD_MAX].inUse == 0) {
                break;
            }
        }
        if (i == IOS_ASYNC_CMD_MAX) {
            rv = IOS_ERROR_MAX;
            goto end;
        }
        *blk = __requests + (i + IOS_THREAD_MAX);
        __activeRequests[id]++;
        (*blk)->inUse = 1;
        (*blk)->tid = id;
    }

    /* Clean the request block before giving it to someone else */
    if (rv == IOS_ERROR_OK) {
        memset(&(*blk)->req, 0, sizeof(IOSResourceRequest));
    }

end:
    return rv;
}

#define SET_POWER(dev, on, id, p) \
    if (THIS_THREAD && THIS_THREAD->pid && THIS_THREAD->pid != p) {\
        rv = IOS_ERROR_ACCESS; \
        goto end; \
    } else if (on) { \
        u32 exp = p; \
        if (exp) { \
            exp = ((1 << (exp - 1)) << DEVID_RTID_SHIFT) | \
                  ((1 << (exp - 1)) << DEVID_DTID_SHIFT); \
        } \
        IO_WRITE(PWR_CTRL_REG, PWR_CTRL_CLOCK_ON << PWR_CTRL_##dev##_SHIFT); \
        IO_WRITE(PWR_CTRL_REG, PWR_CTRL_DEASSERT_RST << PWR_CTRL_##dev##_SHIFT); \
        IO_WRITE(id##_ID_REG, exp); \
    } else { \
        IO_WRITE(PWR_CTRL_REG, PWR_CTRL_ASSERT_RST << PWR_CTRL_##dev##_SHIFT); \
        IO_WRITE(PWR_CTRL_REG, PWR_CTRL_CLOCK_OFF << PWR_CTRL_##dev##_SHIFT); \
    }
        
IOSError
iosSetPower(u32 device, u32 on)
{
    IOSError rv = IOS_ERROR_OK;

    switch (device) {
    case IOS_DEVICE_SHA:
        SET_POWER(SHA, on, SHA, 0);
        break;
    case IOS_DEVICE_AES:
        SET_POWER(AES, on, AES, 0);
        break;
    case IOS_DEVICE_FLASH:
        SET_POWER(FLASH, on, FL, IOS_FS_PROCESS);
        break;
    case IOS_DEVICE_AUDIO:
        SET_POWER(AUD, on, AUD, IOS_AUDIO_PROCESS);
        break;
    case IOS_DEVICE_USB:
        SET_POWER(USB, on, USB, IOS_USB_PROCESS);
        break;
    }
end:
    return rv;
}

IOSError
__iosInitResourceManager(void)
{
    int i;
    for (i = 0; i < sizeof(__responseQueues)/sizeof(__responseQueues[0]); ++i) {
        IOSMessageQueue *mq = __responseQueues + i;
        mq->emptyQ = (IOSThread *)&__iosThreadTail;
        mq->fullQ = (IOSThread *)&__iosThreadTail;
        mq->count = 0;
        mq->rptr = 0;
        mq->size = 1;
        mq->buffer = __responses + i;
        mq->owner = 0;
    }

    /* Set permissions for devices */
    iosSetPower(IOS_DEVICE_AES, 1);
    iosSetPower(IOS_DEVICE_SHA, 1);
    iosSetPower(IOS_DEVICE_FLASH, 1);
    iosSetPower(IOS_DEVICE_AUDIO, 1);
    iosSetPower(IOS_DEVICE_USB, 1);

    return IOS_ERROR_OK;
}

IOSError
iosRegisterResourceManager(char *path, IOSMessageQueueId mqid)
{
    IOSError rv = IOS_ERROR_OK;
    u32 i, pathLen;
    u32 mask;
    IOSMessageQueue *mq;

    IOS_ENTRY();

    mask = LOCK_RESOURCE();

    CHECK_PATH(path, pathLen);
    CHECK_MESSAGE_QUEUE_ID(mqid);

    mq = __iosQueues + mqid;

    CHECK_MESSAGE_QUEUE_OWNER(mq);

    for (i = 0; i < IOS_NUM_RESOURCES; ++i) {
        if (!strncmp(path, __resources[i].path, IOS_PATH_MAX)) {
            rv = IOS_ERROR_EXISTS;
            goto end;
        }
        if (__resources[i].path[0] == '\0') {
            break;
        }
    }
    
    if (i == IOS_NUM_RESOURCES) {
        rv = IOS_ERROR_MAX;
        goto end;
    }

    memcpy(__resources[i].path, path, pathLen + 1);
    __resources[i].pathLen = pathLen;
    __resources[i].mq = mq;
    __resources[i].owner = THIS_THREAD->pidMask;

    if (!memcmp(path, "/dev/aes", sizeof("/dev/aes"))) {
        __aesDesc.resource = __resources + i;
    }
    if (!memcmp(path, "/dev/sha", sizeof("/dev/sha"))) {
        __shaDesc.resource = __resources + i;
    }
    if (!memcmp(path, "/dev/hmac", sizeof("/dev/hmac"))) {
        __hmacDesc.resource = __resources + i;
    }

end:
    UNLOCK_RESOURCE(mask);

    IOS_EXIT();

    return rv;
}

IOSError
__issueRequest(IOSResourceCommandBlock *blk, IOSResource *rm)
{
    IOSError rv = IOS_ERROR_OK;
    IOSMessage response;
    IOSResourceRequest *req = (IOSResourceRequest *)blk;
    IOSMessageQueue *mq = blk->mq;

    __iosSetMemAccess(PT_ACCESS_NONE, PT_ACCESS_READ, rm->owner, req, sizeof(IOSResourceRequest));
    if ((rv = __iosSendMessage(rm->mq, (u32)req, IOS_MESSAGE_BLOCK)) != IOS_ERROR_OK) {
        goto end;
    }

    if (!mq) {
        if ((rv = __iosReceiveMessage(__responseQueues + ((IOSResourceCommandBlock *)req-__requests), &response, IOS_MESSAGE_BLOCK)) != IOS_ERROR_OK) {
            goto end;
        }
        if (response != (IOSMessage) req) {
            rv = IOS_ERROR_INVALID;
            goto end;
        }
    }

end:
    return rv;
}

IOSFd
__iosOpen(const char *path, u32 flags)
{
    IOSError rv;
    u32 i, j, pathLen;
    IOSThreadId tid = iosGetThreadId();

    CHECK_PATH(path, pathLen);
    strncpy(__paths[tid], path, pathLen + 1);

    rv = IOS_ERROR_NOEXISTS;
    for (i = 0; i < IOS_NUM_RESOURCES; ++i) {
        if (__resources[i].pathLen && !strncmp(path, __resources[i].path, __resources[i].pathLen)) {
            IOSResourceCommandBlock *blk = __requests + tid;
            IOSResourceRequest *req = &blk->req;
            req->cmd = IOS_OPEN;
            req->args.open.path = (u8 *)__paths[tid];
            req->args.open.flags = flags;
            req->args.open.uid = __iosUids[THIS_THREAD->pid];
            req->args.open.gid = __iosGids[THIS_THREAD->pid];
            __iosSetMemAccess(PT_ACCESS_NONE, PT_ACCESS_RW, __resources[i].owner, &__paths[tid], IOS_PATH_MAX+1);
            blk->mq = 0;
            blk->reply = 0;
            rv = __issueRequest(blk, __resources + i);
            if ((rv = req->status) != IOS_ERROR_NOEXISTS) {
                if (rv >= 0) {
                    for (j = 0; j < IOS_DESCRIPTOR_MAX; ++j) {
                        if (__descriptors[THIS_THREAD->pid][j].resource == 0) {
                            break;
                        }
                    }
                    if (j == IOS_DESCRIPTOR_MAX) {
                        rv = IOS_ERROR_MAX;
                    } else {
                        __descriptors[THIS_THREAD->pid][j].handle = rv;
                        __descriptors[THIS_THREAD->pid][j].resource = __resources + i;
                        rv = j;
                    }
                }
                break;
            }
        }
    }
    
end:
    __iosSetMemAccess(PT_ACCESS_NONE, PT_ACCESS_RW, 0, &__paths[tid], IOS_PATH_MAX+1);
    return rv;
}

IOSFd
iosOpen(const char *path, u32 flags)
{
    IOSError rv = IOS_ERROR_OK;
    u32 mask;
    IOS_ENTRY();
    mask = LOCK_RESOURCE();
    rv = __iosOpen(path, flags);
    UNLOCK_RESOURCE(mask);
    IOS_EXIT();
    return rv;
}

/* XXXwheeler: async open is hard... 
 * need some time to think about this one some more, for now, just call sync open */
IOSError
iosOpenAsync(const char *pathname, u32 flags, IOSMessageQueueId mqid,
             IOSResourceRequest *reply)
{
    s32 rv = IOS_ERROR_OK;
    IOSMessageQueue *mq;
    u32 mask;

    IOS_ENTRY();

    mask = LOCK_RESOURCE();
    CHECK_MESSAGE_QUEUE_ID(mqid);
    mq = __iosQueues + mqid;
    CHECK_MESSAGE_QUEUE_OWNER(mq);
    CHECK_WRITABLE_BUFFER(reply, sizeof(IOSResourceRequest), 0);
    if ((rv = __iosOpen(pathname, flags)) >= 0) {
        reply->cmd = IOS_REPLY;
        reply->status = rv;
        rv = __iosSendMessage(mq, (IOSMessage) reply, IOS_MESSAGE_NOBLOCK);
    }

end:
    UNLOCK_RESOURCE(mask);
    IOS_EXIT();
    return rv;
}

IOSError
__iosClose(IOSFd fd, IOSMessageQueue *mq, IOSResourceRequest *reply)
{
    IOSError rv = IOS_ERROR_OK;
    IOSResourceCommandBlock *blk = 0;

    IOS_ENTRY();

    CHECK_FD(fd);

    GET_CMD_BLOCK();
    IOSResourceRequest *req = &blk->req;
    IOSResourceDescriptor *d = GET_DESCRIPTOR(fd);
    req->cmd = IOS_CLOSE;
    req->handle = d->handle;
    blk->mq = mq;
    blk->reply = reply;
    rv = __issueRequest(blk, d->resource);
    if (fd != IOS_AES_FD && fd != IOS_SHA_FD && fd != IOS_HMAC_FD) {
        memset(d, 0, sizeof(IOSResourceDescriptor));
    }
    if (!mq && rv == IOS_ERROR_OK) {
        rv = req->status;
    }

end:
    RELEASE_CMD_BLOCK();
    IOS_EXIT();
    return rv;
}

IOSError
iosClose(IOSFd fd)
{
    IOSError rv = IOS_ERROR_OK;
    u32 mask;
    IOS_ENTRY();
    mask = LOCK_RESOURCE();
    rv = __iosClose(fd, 0, 0);
    UNLOCK_RESOURCE(mask);
    IOS_EXIT();
    return rv;
}

IOSError
iosCloseAsync(IOSFd fd, IOSMessageQueueId mqid, IOSResourceRequest *reply)
{
    s32 rv = IOS_ERROR_OK;
    IOSMessageQueue *mq;
    u32 mask;

    IOS_ENTRY();

    mask = LOCK_RESOURCE();
    CHECK_MESSAGE_QUEUE_ID(mqid);
    mq = __iosQueues + mqid;
    CHECK_MESSAGE_QUEUE_OWNER(mq);
    CHECK_WRITABLE_BUFFER(reply, sizeof(IOSResourceRequest), 0);
    rv = __iosClose(fd, mq, reply);

end:
    UNLOCK_RESOURCE(mask);
    IOS_EXIT();
    return rv;
}

s32
__iosRead(IOSFd fd, void *buf, u32 count, IOSMessageQueue *mq, IOSResourceRequest *reply)
{
    IOSError rv = IOS_ERROR_OK;
    IOSResourceCommandBlock *blk = 0;

    CHECK_FD(fd);

    GET_CMD_BLOCK();
    IOSResourceRequest *req = &blk->req;
    IOSResourceDescriptor *d = GET_DESCRIPTOR(fd);
    req->cmd = IOS_READ;
    req->handle = d->handle;
    req->args.read.outPtr = buf;
    req->args.read.outLen = count;
    blk->mq = mq;
    blk->reply = reply;
    CHECK_WRITABLE_BUFFER(buf, count, d->resource->owner);
    rv = __issueRequest(blk, d->resource);
    if (!mq && rv == IOS_ERROR_OK) {
        rv = req->status;
    }

end:
    RELEASE_CMD_BLOCK();
    return rv;
}

s32
iosRead(IOSFd fd, void *buf, u32 count)
{
    s32 rv;
    u32 mask;
    IOS_ENTRY();
    mask = LOCK_RESOURCE();
    rv = __iosRead(fd, buf, count, 0, 0);
    UNLOCK_RESOURCE(mask);
    IOS_EXIT();
    return rv;
}

IOSError
iosReadAsync(IOSFd fd, void *buf, u32 count, IOSMessageQueueId mqid,
            IOSResourceRequest *reply)
{
    s32 rv = IOS_ERROR_OK;
    IOSMessageQueue *mq;
    u32 mask;

    IOS_ENTRY();

    mask = LOCK_RESOURCE();
    CHECK_MESSAGE_QUEUE_ID(mqid);
    mq = __iosQueues + mqid;
    CHECK_MESSAGE_QUEUE_OWNER(mq);
    CHECK_WRITABLE_BUFFER(reply, sizeof(IOSResourceRequest), 0);
    rv = __iosRead(fd, buf, count, mq, reply);

end:
    UNLOCK_RESOURCE(mask);
    IOS_EXIT();
    return rv;
}

s32
__iosWrite(IOSFd fd, void *buf, u32 count, IOSMessageQueue *mq, IOSResourceRequest *reply)
{
    IOSError rv = IOS_ERROR_OK;
    IOSResourceCommandBlock *blk = 0;

    IOS_ENTRY();

    CHECK_FD(fd);

    GET_CMD_BLOCK();
    IOSResourceRequest *req = &blk->req;
    IOSResourceDescriptor *d = GET_DESCRIPTOR(fd);
    req->cmd = IOS_WRITE;
    req->handle = d->handle;
    req->args.write.inPtr = buf;
    req->args.write.inLen = count;
    blk->mq = mq;
    blk->reply = reply;
    CHECK_READABLE_BUFFER(buf, count, d->resource->owner);
    rv = __issueRequest(blk, d->resource);

    if (!mq && rv == IOS_ERROR_OK) {
        rv = req->status;
    }
end:
    RELEASE_CMD_BLOCK();
    IOS_EXIT();
    return rv;
}

s32
iosWrite(IOSFd fd, void *buf, u32 count)
{
    s32 rv;
    u32 mask;
    IOS_ENTRY();
    mask = LOCK_RESOURCE();
    rv = __iosWrite(fd, buf, count, 0, 0);
    UNLOCK_RESOURCE(mask);
    IOS_EXIT();
    return rv;
}

IOSError
iosWriteAsync(IOSFd fd, void *buf, u32 count, IOSMessageQueueId mqid,
             IOSResourceRequest *reply)
{
    s32 rv = IOS_ERROR_OK;
    IOSMessageQueue *mq;
    u32 mask;

    IOS_ENTRY();

    mask = LOCK_RESOURCE();
    CHECK_MESSAGE_QUEUE_ID(mqid);
    mq = __iosQueues + mqid;
    CHECK_MESSAGE_QUEUE_OWNER(mq);
    CHECK_WRITABLE_BUFFER(reply, sizeof(IOSResourceRequest), 0);
    rv = __iosWrite(fd, buf, count, mq, reply);

end:
    UNLOCK_RESOURCE(mask);
    IOS_EXIT();
    return rv;
}

s32
__iosSeek(IOSFd fd, s32 offset, u32 whence, IOSMessageQueue *mq, IOSResourceRequest *reply)
{
    IOSError rv = IOS_ERROR_OK;
    IOSResourceCommandBlock *blk = 0;

    IOS_ENTRY();

    CHECK_FD(fd);

    GET_CMD_BLOCK();
    IOSResourceRequest *req = &blk->req;
    IOSResourceDescriptor *d = GET_DESCRIPTOR(fd);
    req->cmd = IOS_SEEK;
    req->handle = d->handle;
    req->args.seek.offset = offset;
    req->args.seek.whence = whence;
    blk->mq = mq;
    blk->reply = reply;
    rv = __issueRequest(blk, d->resource);

    if (!mq && rv == IOS_ERROR_OK) {
        rv = req->status;
    }
end:
    RELEASE_CMD_BLOCK();
    IOS_EXIT();
    return rv;
}

s32
iosSeek(IOSFd fd, s32 offset, u32 whence)
{
    s32 rv;
    u32 mask;
    IOS_ENTRY();
    mask = LOCK_RESOURCE();
    rv = __iosSeek(fd, offset, whence, 0, 0);
    UNLOCK_RESOURCE(mask);
    IOS_EXIT();
    return rv;
}

IOSError
iosSeekAsync(IOSFd fd, s32 offset, u32 whence, IOSMessageQueueId mqid,
            IOSResourceRequest *reply)
{
    s32 rv = IOS_ERROR_OK;
    IOSMessageQueue *mq;
    u32 mask;

    IOS_ENTRY();

    mask = LOCK_RESOURCE();
    CHECK_MESSAGE_QUEUE_ID(mqid);
    mq = __iosQueues + mqid;
    CHECK_MESSAGE_QUEUE_OWNER(mq);
    CHECK_WRITABLE_BUFFER(reply, sizeof(IOSResourceRequest), 0);
    rv = __iosSeek(fd, offset, whence, mq, reply);

end:
    UNLOCK_RESOURCE(mask);
    IOS_EXIT();
    return rv;
}

IOSError
__iosIoctl(IOSFd fd, s32 cmd, void *input, u32 inputLen, void *output, u32 outputLen, IOSMessageQueue *mq, IOSResourceRequest *reply)
{
    IOSError rv = IOS_ERROR_OK;
    IOSResourceCommandBlock *blk = 0;

    IOS_ENTRY();

    CHECK_FD(fd);

    GET_CMD_BLOCK();
    IOSResourceRequest *req = &blk->req;
    IOSResourceDescriptor *d = GET_DESCRIPTOR(fd);
    req->cmd = IOS_IOCTL;
    req->handle = d->handle;
    req->args.ioctl.cmd = cmd;
    req->args.ioctl.inPtr = input;
    req->args.ioctl.inLen = inputLen;
    req->args.ioctl.outPtr = output;
    req->args.ioctl.outLen = outputLen;
    blk->mq = mq;
    blk->reply = reply;
    CHECK_READABLE_BUFFER(input, inputLen, d->resource->owner);
    CHECK_WRITABLE_BUFFER(output, outputLen, d->resource->owner);

    rv = __issueRequest(blk, d->resource);

    if (!mq && rv == IOS_ERROR_OK) {
        rv = req->status;
    }
end:
    RELEASE_CMD_BLOCK();
    IOS_EXIT();
    return rv;
}

IOSError
iosIoctl(IOSFd fd, s32 cmd, void *input, u32 inputLen, void *output, u32 outputLen)
{
    s32 rv;
    u32 mask;
    IOS_ENTRY();
    mask = LOCK_RESOURCE();
    rv = __iosIoctl(fd, cmd, input, inputLen, output, outputLen, 0, 0);
    UNLOCK_RESOURCE(mask);
    IOS_EXIT();
    return rv;
}

IOSError
iosIoctlAsync(IOSFd fd, s32 cmd, void *input, u32 inputLen,
             void *output, u32 outputLen, IOSMessageQueueId mqid,
             IOSResourceRequest *reply)
{
    s32 rv = IOS_ERROR_OK;
    IOSMessageQueue *mq;
    u32 mask;

    IOS_ENTRY();

    mask = LOCK_RESOURCE();
    CHECK_MESSAGE_QUEUE_ID(mqid);
    mq = __iosQueues + mqid;
    CHECK_MESSAGE_QUEUE_OWNER(mq);
    CHECK_WRITABLE_BUFFER(reply, sizeof(IOSResourceRequest), 0);
    rv = __iosIoctl(fd, cmd, input, inputLen, output, outputLen, mq, reply);

end:
    UNLOCK_RESOURCE(mask);
    IOS_EXIT();
    return rv;
}

IOSError
__iosIoctlv(IOSFd fd, s32 cmd, u32 readCount, u32 writeCount, IOSIoVector *vector, IOSMessageQueue *mq, IOSResourceRequest *reply, int check)
{
    IOSError rv = IOS_ERROR_OK;
    IOSResourceCommandBlock *blk = 0;
    int i;

    IOS_ENTRY();

    CHECK_FD(fd);

    GET_CMD_BLOCK();
    IOSResourceRequest *req = &blk->req;
    IOSResourceDescriptor *d = GET_DESCRIPTOR(fd);
    req->cmd = IOS_IOCTLV;
    req->handle = d->handle;
    req->args.ioctlv.cmd = cmd;
    req->args.ioctlv.readCount = readCount;
    req->args.ioctlv.writeCount = writeCount;
    req->args.ioctlv.vector = vector;
    blk->mq = mq;
    blk->reply = reply;
    if (check) {
      CHECK_READABLE_BUFFER(vector, (readCount+writeCount)*sizeof(IOSIoVector), d->resource->owner);
      for (i = 0; i < readCount; ++i) {
        CHECK_READABLE_BUFFER(vector[i].base, vector[i].length,
                              d->resource->owner);
      }
      for (i = 0; i < writeCount; ++i) {
        CHECK_WRITABLE_BUFFER(vector[i+readCount].base,
                              vector[i+readCount].length,
                              d->resource->owner);
      }
    }
    rv = __issueRequest(blk, d->resource);

    if (!mq && rv == IOS_ERROR_OK) {
        rv = req->status;
    }
end:
    RELEASE_CMD_BLOCK();
    IOS_EXIT();
    return rv;
}


IOSError
__iosIoctlvInt(IOSFd fd, s32 cmd, u32 readCount, u32 writeCount, IOSIoVector *vector)
{
    s32 rv;
    u32 mask;
    IOS_ENTRY();
    mask = LOCK_RESOURCE();
    rv = __iosIoctlv(fd, cmd, readCount, writeCount, vector, 0, 0, 0);
    UNLOCK_RESOURCE(mask);
    IOS_EXIT();
    return rv;
}

IOSError
__iosIoctlvAsyncInt(IOSFd fd, s32 cmd, u32 readCount, u32 writeCount,
              IOSIoVector *vector, IOSMessageQueueId mqid,
              IOSResourceRequest *reply)
{
    s32 rv = IOS_ERROR_OK;
    IOSMessageQueue *mq;
    u32 mask;

    IOS_ENTRY();

    mask = LOCK_RESOURCE();
    CHECK_MESSAGE_QUEUE_ID(mqid);
    mq = __iosQueues + mqid;
    CHECK_MESSAGE_QUEUE_OWNER(mq);
    CHECK_WRITABLE_BUFFER(reply, sizeof(IOSResourceRequest), 0);
    rv = __iosIoctlv(fd, cmd, readCount, writeCount, vector, mq, reply, 0);

end:
    UNLOCK_RESOURCE(mask);
    IOS_EXIT();
    return rv;
}

IOSError
iosIoctlv(IOSFd fd, s32 cmd, u32 readCount, u32 writeCount, IOSIoVector *vector)
{
    s32 rv;
    u32 mask;
    IOS_ENTRY();
    mask = LOCK_RESOURCE();
    rv = __iosIoctlv(fd, cmd, readCount, writeCount, vector, 0, 0, 1);
    UNLOCK_RESOURCE(mask);
    IOS_EXIT();
    return rv;
}

IOSError
iosIoctlvAsync(IOSFd fd, s32 cmd, u32 readCount, u32 writeCount,
              IOSIoVector *vector, IOSMessageQueueId mqid,
              IOSResourceRequest *reply)
{
    s32 rv = IOS_ERROR_OK;
    IOSMessageQueue *mq;
    u32 mask;

    IOS_ENTRY();

    mask = LOCK_RESOURCE();
    CHECK_MESSAGE_QUEUE_ID(mqid);
    mq = __iosQueues + mqid;
    CHECK_MESSAGE_QUEUE_OWNER(mq);
    CHECK_WRITABLE_BUFFER(reply, sizeof(IOSResourceRequest), 0);
    rv = __iosIoctlv(fd, cmd, readCount, writeCount, vector, mq, reply, 1);

end:
    UNLOCK_RESOURCE(mask);
    IOS_EXIT();
    return rv;
}

IOSError
iosResourceReply(IOSResourceRequest *req, IOSError status)
{
    IOSError rv = IOS_ERROR_OK;
    IOSResourceCommandBlock *blk = (IOSResourceCommandBlock *)req;
    int i;
    u32 mask;

    IOS_ENTRY();

    mask = LOCK_RESOURCE();

    i = blk - __requests;
    if (i < 0 || i >= sizeof(__requests)/sizeof(__requests[0])) {
        rv = IOS_ERROR_INVALID;
        goto end;
    }
    __iosSetMemAccess(PT_ACCESS_NONE, PT_ACCESS_RW, 0, blk, sizeof(IOSResourceRequest));
    req->status = status;
    if (blk->mq) {
        blk->reply->status = status;
        blk->reply->cmd = IOS_REPLY;
        if ((rv = __iosSendMessage(blk->mq, (IOSMessage) blk->reply, IOS_MESSAGE_NOBLOCK)) != IOS_ERROR_OK) {
            goto end;
        }
        blk->inUse = 0; // Mark cmd block as free
        __activeRequests[blk->tid]--;
    } else {
        if ((rv = __iosSendMessage(__responseQueues + i, (IOSMessage) blk, IOS_MESSAGE_BLOCK)) != IOS_ERROR_OK) {
            goto end;
        }
    }
end:
    UNLOCK_RESOURCE(mask);
    IOS_EXIT();
    return rv;
}

#if defined(GET_USAGE)
char *
__iosGetResourceUsage(int i, char *start, char *end)
{
    IOSResource *r = __resources + i;
    start += snprintf(start, end-start, "Resource %d [%08x]: (%s)\n", i, r, r->path);
    if (!*r->path) goto end;
    start += snprintf(start, end-start, "  owner: %d, mq: %08x\n", r->owner, r->mq);
end:
    return start;
}

char *
__iosGetResourcesUsage(char *start, char *end)
{
    int i;
    
    for (i = 0; i < IOS_NUM_RESOURCES; ++i) {
        start = __iosGetResourceUsage(i, start, end);
    }
    start += snprintf(start, end-start, "\n");
    return start;
}
#endif

/*
 * ds mode ressource;
 */
IOSError
iosDsMode(IOSMessageQueueId mqid, IOSResourceRequest *req)
{
	IOSError rv;
	IOSFd fd;
	char es_dev[16];
	struct {
		IOSIoVector es_vec[3];
		u32 es_tcnt;
		ESTitleId es_tid;
		ESTicketView es_tv[4];
	} *p;
	extern void *iosAllocAligned(u32, u32, u32);

	// open es;
	// must have name aligned and access rights set;

	req->args.ds.rom_base = 0;
	strncpy(es_dev, "/dev/es", sizeof(es_dev));
	rv = iosOpen(es_dev, 0);
	if(rv < IOS_ERROR_OK) {
		goto end;
        }
	fd = rv;

	// get ticket views for title;

	//XXX p = iosAllocAligned(0, sizeof(*p), 16);
	p = (void *)0x08001000;
	rv = IOS_ERROR_MAX;
	if( !p) {
		goto close;
        }

        /*
         * Get size of ticket list first, since ES_GetTicketView
         * throws an error if you don't ask for exactly the
         * right number.  There should only be one ticket, but
         * just in case ...
         */
	p->es_tid = ES_TITLE_ID_DS_VIEWER_64;
	p->es_tcnt = sizeof(p->es_tv)/sizeof(p->es_tv[0]);
	p->es_vec[0].base = (u8 *)&p->es_tid;
	p->es_vec[0].length = sizeof(p->es_tid);
	p->es_vec[1].base = (u8 *)&p->es_tcnt;
	p->es_vec[1].length = sizeof(p->es_tcnt);
	rv = iosIoctlv(fd, ES_CMD_GET_TICKET_VIEW_CNT, 1, 1, p->es_vec);
	if(rv != IOS_ERROR_OK) {
		goto close;
	} 
	if(p->es_tcnt > sizeof(p->es_tv)/sizeof(p->es_tv[0])) {
		rv = IOS_ERROR_INVALID_SIZE;
		goto close;
	}
	p->es_vec[0].base = (u8 *)&p->es_tid;
	p->es_vec[0].length = sizeof(p->es_tid);
	p->es_vec[1].base = (u8 *)&p->es_tcnt;
	p->es_vec[1].length = sizeof(p->es_tcnt);
	p->es_vec[2].base = (u8 *)&p->es_tv[0];
	p->es_vec[2].length = p->es_tcnt * sizeof(p->es_tv[0]);
	rv = iosIoctlv(fd, ES_CMD_GET_TICKET_VIEWS, 2, 1, p->es_vec);
	if(rv != IOS_ERROR_OK) {
		goto close;
	} 

	// launch ds viewer;

	p->es_vec[1].base = (u8 *)&p->es_tv[0];
	p->es_vec[1].length = sizeof(p->es_tv[0]);
	rv = iosIoctlv(fd, ES_CMD_LAUNCH_TITLE, 2, 0, p->es_vec);

	// close es;
close:
	iosClose(fd);
	if(p)
		iosFree(0, p);
	if(rv != IOS_ERROR_OK)
		goto end;

	// passing args to ds side, allows more flexibility
	// for updates, even though they are hard-coded here;
	// it is the DS rom that cannot change;

	req->args.ds.rom_base = DS_ROM_BASE;
end:
	return(rv);
}
