/*
 *               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.
 *
 */
/* IRP management */
#include <iostypes.h>
#include <ios.h>
#include <iop.h>
#include <ioslibc.h>
#include "ehci.h"
#include "ehci_regs.h"

#include "ehci_core.h"

#define ENABLE_QTD_DBG 1

extern struct ehci_device __ehci_dev[EHCI_DEV_MAX]; 

static IOSError
LOCK_IRP(ehci_hcd *hcd)
{
    IOSMessage msg;
    IOSError rv;
    rv = IOS_ReceiveMessage(hcd->irp.mqid, &msg, IOS_MESSAGE_BLOCK);
    if (rv < 0) {
        EHCI_ERR("Acquiring mutex failed: %d\n", rv);
    }
    return rv;
}

static IOSError
UNLOCK_IRP(ehci_hcd *hcd)
{ 
    IOSError rv;
    rv = IOS_SendMessage(hcd->irp.mqid, 0xabcd1234, IOS_MESSAGE_BLOCK);
    if (rv < 0) {
        EHCI_ERR("Releasing mutex failed: %d\n", rv);
    }
    return rv;
}

static IOSError
__dequeueIRP(ehci_hcd *hcd, EHCIrp *irp)
{
    IOSError rv = IOS_ERROR_OK;
    {
        EHCIrp *tmp;
        EHCIrp *prev;

        if (hcd->irp.hd == irp) {
            hcd->irp.hd = irp->nxt;
            goto done;
        }

        prev = hcd->irp.hd;
        tmp = prev->nxt;
        while (NULL != tmp) {
            if (irp == tmp) {
                prev->nxt = tmp->nxt;
                goto done;
            }
            prev = tmp;
            tmp = tmp->nxt;
        }
    }
done:
#ifdef EHCI_ENABLE_DBG
    dumpIRPList(hcd);
#endif
    return rv;
}

static void
__replyAndFreeIRP(ehci_hcd *hcd, EHCIrp *irp, s32 stat)
{
    if (NULL == irp) {
        EHCI_ERR("NULL irp does not need to be freed\n");
        goto done;
    }
    /* Send reply to IRP and free it */
    if (irp->qid > 0) {
        /* Internal buffers are allocated from non-cached space.
         * No need to flush
         */
        if (hcd->rm_qid == irp->qid) { /* Hub reply */
            u32 msg = HCD_RHUB_EVENT;
            msg |= (((IUSB_ERROR_NOERROR != stat)?
                        HCD_HUB_STAT_FAIL: HCD_HUB_STAT_SUCC) |irp->devnum);
            EHCI_DBG("sending hub status change msg %x to qid %d\n", msg, irp->qid);
            IOS_SendMessage(irp->qid, msg, IOS_MESSAGE_NOBLOCK);
        } else { /* ctrl msg */
            EHCI_DBG("sending message to queue id %d\n", irp->qid);
            IOS_SendMessage(irp->qid, irp->done, IOS_MESSAGE_BLOCK);
        }
    } else {
        EHCI_DBG("send resource reply with req %p\n", irp->req);
        /* If no other errors have occurred, set return value to
         * cancelled code. Otherwise, retain original error.*/
        if (irp->done >= 0 && stat < 0) {
            irp->done = IUSB_ERROR_CANCELLED;
            EHCI_DBG("%s: transfer cancelled\n", __FUNCTION__);
        } else {
            /* Invalidate user's buffer */
            if (0 != irp->datalen) {
                IOS_InvalidateDCache(irp->data, irp->datalen); 
            }
        }
        EHCI_DBG("%s: sending resource reply = %d\n", __FUNCTION__, irp->done);
        if (irp->done < 0) {
            EHCI_ERR("Returning IRP completion error: %d\n", irp->done);
            SD_LOG(sdLogBuf, 64, 1, "\nReturning IRP completion error: %d\n", irp->done);
        }
        IOS_ResourceReply(irp->req, irp->done);
    }
    if (NULL != irp->clean1) {
        IOS_Free(__ehcdHeapId, irp->clean1);
    }
    if (NULL != irp->itd) {
        freeITD((ehci_itd*) irp->itd);
    }
    if (NULL != irp->sitd) {
        u32 i;
        for (i = 0; i < irp->ntd; ++i) {
            EHCI_DBG("freeing sitd[%d] %x\n", i, irp->sitd[i]);
            freeSITD(irp->sitd[i]);
        }
        EHCI_DBG("freeing sitd ptr array %x\n", i, irp->sitd);
        IOS_Free(__ehcdHeapId, irp->sitd);
    }
    memset(irp, 0, sizeof(EHCIrp));
    IOS_Free(__ehcdHeapId, irp);
done:
    return;
}

static IOSError
__checkSitdError(u32 stat)
{ 
    IOSError rv = IOS_ERROR_OK;
    if (stat & SITD_STAT_ACT_MASK) {
        rv = IOS_ERROR_NOTREADY;
        goto done;
    }
    if (stat & SITD_STAT_ERR_MASK) {
        rv = IUSB_ERROR_TT_ERR;
        goto done;
    }
    if (stat & SITD_STAT_DBERR_MASK) {
        rv = IUSB_ERROR_DBUFFER;
        goto done;
    }
    if (stat & SITD_STAT_BBL_MASK) {
        rv = IUSB_ERROR_BABBLE;
        goto done;
    }
    if (stat & SITD_STAT_XACTERR_MASK) {
        rv = IUSB_ERROR_XACT_ERR;
        goto done;
    }
    if (stat & SITD_STAT_MUF_MASK) {
        rv = IUSB_ERROR_MUF_ERR;
        goto done;
    }

done:
    return rv;
}

static IOSError
__processSitdIRP(ehci_hcd *hcd, EHCIrp *irp)
{
    IOSError rv = IOS_ERROR_OK;
    u32 i;
    u32 stat;
    ehci_sitd **sitd_list = irp->sitd;
    /* Check if all sitds are done */
    for (i = 0; i < irp->ntd; ++i) {
        stat = EHCI_TO_CPU32(sitd_list[i]->stat & SITD_STAT_STAT_MASK);
        if (stat & SITD_STAT_ACT_MASK) {
            EHCI_ERR("sitd %d still active\n", i);
            goto done;
        }
    }
    /* process done request */
    for (i = 0; i < irp->ntd; ++i) {
        stat = EHCI_TO_CPU32(sitd_list[i]->stat) & SITD_STAT_STAT_MASK
            & ~SITD_STAT_SPLT_MASK;
        if (stat) {
            EHCI_ERR("sitd %d failed: status = 0x%02x\n", __FUNCTION__, i, stat);
            rv = __checkSitdError(stat);
            goto done;
        }
        irp->done  += sitd_list[i]->len;
    }
    EHCI_DBG("%s: irp %p done. transferred bytes: %u\n", __FUNCTION__, irp, irp->done); 
done:
    return  rv;
} 

static IOSError
__processIRP(ehci_hcd *hcd, EHCIrp *irp)
{
    IOSError rv;

    if (NULL != irp->itd) {
        EHCI_DBG("%s: handling completed itd\n", __FUNCTION__);
        rv = IOS_ERROR_OK;
        //        rv = __processItdIRP(hcd, irp);
        goto clean;
    } else if (NULL != irp->sitd) {
        EHCI_DBG("%s: handling completed sitd\n", __FUNCTION__);
        rv = __processSitdIRP(hcd, irp);
        goto clean;
    }

    { /* Transfers with QHs */
        u32 i;
        u32 ntd = irp->ntd;
        ehci_qtd *q = irp->qtd;
        /* Do nothing until all qtds are processed */
        for (i = 0; i < ntd; ++i) {
            if (0 != (EHCI_TO_CPU32(q->token) & QTD_TOKEN_STAT_ACT_MASK)) {
                goto done;
            } 
            q  = (ehci_qtd *) (EHCI_TO_CPU32(q->nextQTD) & QTD_NXT_NXT_MASK);
        }

        /* All qtds for this IRP are done */
        q = irp->qtd;
        for (i = 0; i < ntd; ++i) {
            ehci_qtd *qtmp  = (ehci_qtd *) 
                (EHCI_TO_CPU32(q->nextQTD) & QTD_NXT_NXT_MASK);
            u32 nbytes = (EHCI_TO_CPU32(q->token) & QTD_TOKEN_NBYTES_MASK) >>
                QTD_TOKEN_NBYTES_SHIFT;
            irp->done += q->len - nbytes;
            --irp->ntd;
            freeQTD(q);
            q = qtmp;
        }
    }
    /* Fall through */
clean:
    EHCI_DBG("IRP %p completed. Sending reply %u\n", irp, irp->done);
    __dequeueIRP(hcd, irp);
    __replyAndFreeIRP(hcd, irp, IUSB_ERROR_NOERROR);
done:
    return rv;
}

IOSError 
handleCompletions(ehci_hcd *hcd)
{
    EHCIrp *nxt;
    EHCIrp *i = hcd->irp.hd;
    LOCK_IRP(hcd);
    IOS_FlushMem(IOS_WB_EHCI);
    IOS_InvalidateRdb(IOS_RB_IOD);
    while (NULL != i) { 
        EHCI_DBG("%s: processing irp %p\n", __FUNCTION__, i);
        nxt = i->nxt;
        __processIRP(hcd, i);
        i = nxt;
    } 
    IOS_FlushMem(IOS_WB_IOD);
    IOS_InvalidateRdb(IOS_RB_EHCI);
    UNLOCK_IRP(hcd);
    return IOS_ERROR_OK;
}

IOSError
enqueueIRP(ehci_hcd *hcd, EHCIrp *irp)
{
    IOSError rv = IOS_ERROR_OK;
    EHCIrp *list;
    LOCK_IRP(hcd);
    IOS_FlushMem(IOS_WB_EHCI);
    IOS_InvalidateRdb(IOS_RB_IOD);
    {
        list = hcd->irp.hd;
        hcd->irp.hd = irp;
        irp->nxt = list;
    }
#ifdef EHCI_ENABLE_DBG
    dumpIRPList(hcd);
#endif
    IOS_FlushMem(IOS_WB_IOD);
    IOS_InvalidateRdb(IOS_RB_EHCI);
    UNLOCK_IRP(hcd);
    return rv;
}

void 
replyAndFreeIRP(ehci_hcd *hcd, EHCIrp *irp, s32 stat)
{
    LOCK_IRP(hcd);
    IOS_FlushMem(IOS_WB_EHCI);
    IOS_InvalidateRdb(IOS_RB_IOD);
    __replyAndFreeIRP(hcd, irp, stat);
    IOS_FlushMem(IOS_WB_IOD);
    IOS_InvalidateRdb(IOS_RB_EHCI);
    UNLOCK_IRP(hcd);
}

static IOSError
__checkQTDError(u32 token)
{
    IOSError rv = IOS_ERROR_OK;
    EHCI_DBG("%s: status token = %x\n", __FUNCTION__, 
            token & QTD_TOKEN_STAT_MASK);
    if (token & QTD_TOKEN_STAT_DBERR_MASK) {
        EHCI_ERR("%s: Data buffer error detected\n", __FUNCTION__);
        SD_LOG(sdLogBuf, 32, 1, "\nData buffer error\n");
        rv = IUSB_ERROR_DBUFFER;
        goto done;
    }
    if (token & QTD_TOKEN_STAT_BBL_MASK) {
        EHCI_ERR("%s: Babble detected by host controller\n", __FUNCTION__);
        SD_LOG(sdLogBuf, 32, 1, "\nBabble error\n");
        rv = IUSB_ERROR_BABBLE;
        goto done;
    } 
    if (token & QTD_TOKEN_STAT_HLT_MASK) {
        EHCI_ERR("%s: Endpoint halt detected\n", __FUNCTION__);
        SD_LOG(sdLogBuf, 32, 1, "\nEndpoint halted\n");
        rv = IUSB_ERROR_HALT;
        goto done;
    } 
    if (token & QTD_TOKEN_STAT_XACTERR_MASK) {
        EHCI_ERR("%s: Transaction error detected\n", __FUNCTION__);
        SD_LOG(sdLogBuf, 32, 1, "\nTransaction error\n");
        rv = IUSB_ERROR_DEVERR;
        goto done;
    }
    if (token & QTD_TOKEN_STAT_MUF_MASK) {
        EHCI_ERR("%s: missed microframe error detected\n", __FUNCTION__);
        SD_LOG(sdLogBuf, 32, 1, "\nMissed microframe error detected\n");
        rv = IUSB_ERROR_MUF_ERR;
        goto done;
    }
done:
    return rv;
}

/* Called with IRP list already locked */
static void
__abortIRP(ehci_hcd *hcd, EHCIrp *irp)
{
    u32 i;
    u32 ntd = irp->ntd;
    ehci_qtd *q = irp->qtd;
    for (i = 0; i < ntd; ++i) {
        freeQTD(q);
        q  = (ehci_qtd *) (EHCI_TO_CPU32(q->nextQTD) & QTD_NXT_NXT_MASK);
    }
    __replyAndFreeIRP(hcd, irp, -1 /* abort */);
}

/* Abort, reply, free all IRPs in the queue which have 
 * requests for specified ep. Active qtds (on queue) should
 * be halted and freed before calling this function.
 */
void 
abortAndFreeIRP(ehci_hcd *hcd, usb20_dev_ep *ep)
{
  EHCIrp *irp;

  LOCK_IRP(hcd);
  IOS_FlushMem(IOS_WB_EHCI);
  IOS_InvalidateRdb(IOS_RB_IOD);
  {
      irp = hcd->irp.hd;
      while (NULL != irp) {
          if (irp->qh->ep == (u32) ep) {
              EHCI_DBG("%s: found irp %p with ep 0x%x\n", __FUNCTION__, irp, ep);
              __abortIRP(hcd, irp);
          }
          irp = irp->nxt;
      }
  }
  IOS_FlushMem(IOS_WB_IOD);
  IOS_InvalidateRdb(IOS_RB_EHCI);
  UNLOCK_IRP(hcd);
}

static IOSError
__processIRPError(ehci_hcd *hcd, EHCIrp *irp)
{
    u32 i;
    IOSError rv = IOS_ERROR_OK;
    u32 ntd = irp->ntd;
    ehci_qtd *q = irp->qtd;

    for (i = 0; i < ntd; ++i) {
        if (0 != (EHCI_TO_CPU32(q->token) & QTD_TOKEN_STAT_ACT_MASK)) {
            continue;
        } /* else qtd is inactive */
        if (IOS_ERROR_OK != (rv = __checkQTDError(EHCI_TO_CPU32(q->token)))) {
            EHCI_DBG("Found qtd with error: %d\n", rv);
#ifdef ENABLE_QTD_DBG
            dumpQTD(q);
#endif
            break;
        }
        q  = (ehci_qtd *) (EHCI_TO_CPU32(q->nextQTD) & QTD_NXT_NXT_MASK);
    }
    if (IOS_ERROR_OK != rv) {
        /* At least 1 qtd has completed with an error */
        /* abort and free all QTDs for this QH, send replies. */
        irp->done = rv;
        EHCI_ERR("Completion status for failed transfer: %d\n", irp->done);
        SD_LOG(sdLogBuf, 128, 1, "Completion status for failed transfer: %d\n", irp->done);
        EHCI_DBG("%s: calling abort QH for irp %p ep 0x%x\n", __FUNCTION__, 
                q->irp, q->irp->qh->ep);
        /* Some of the QTDs in this IRP may have succeeded. Need 
         * to clean up current IRP. For large transfers, bulk and intr
         * may need this too.
         */
        abortQH(hcd, (usb20_dev_ep *) q->irp->qh->ep, __ehci_dev[irp->devnum].dev.spd, 0 /* don't clean IRPs */);
        __abortIRP(hcd, irp);
    }
    return rv;
}

IOSError 
handleCompletionErrors(ehci_hcd *hcd)
{
    EHCIrp *nxt;
    EHCIrp *i = hcd->irp.hd;
    LOCK_IRP(hcd);
    IOS_FlushMem(IOS_WB_EHCI);
    IOS_InvalidateRdb(IOS_RB_IOD);
    EHCI_DBG("%s: processing completion error\n", __FUNCTION__, i);
    while (NULL != i) { 
        EHCI_DBG("%s: processing irp %p\n", __FUNCTION__, i);
        nxt = i->nxt;
        __processIRPError(hcd, i);
        i = nxt;
    }
    IOS_FlushMem(IOS_WB_IOD);
    IOS_InvalidateRdb(IOS_RB_EHCI);
    UNLOCK_IRP(hcd);
    return IOS_ERROR_OK;
}
