/*
 *               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.
 *
 */
/* Handle OHCI events */
#include <iostypes.h>
#include <ios.h>
#include <iop.h>
#include <ioslibc.h>
#include "ohci.h"
#include "ohci_regs.h"

#include "ohci_core.h"

static void
__replyAndFreeIRP(ohci_hcd *hcd, OHCIrp *irp, s32 stat)
{
    if (NULL == irp) {
        OHCI_DBG("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);
            
            OHCI_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 */
            OHCI_DBG("sending message to queue id %d\n", irp->qid);
            /* RM is blocked waiting for this msg */
            IOS_SendMessage(irp->qid, irp->done, IOS_MESSAGE_BLOCK);
        }
    } else {
        OHCI_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;
            OHCI_DBG("%s: transfer cancelled\n", __FUNCTION__);
        } else {
            /* Invalidate user's buffer */
            if (0 != irp->datalen) {
                IOS_InvalidateDCache(irp->data, irp->datalen); 
            }
        }
        OHCI_DBG("sending resource reply = %d\n", irp->done);
        IOS_ResourceReply(irp->req, irp->done);
    }
    if (NULL != irp->clean1) {
        IOS_Free(__ohcdHeapId, irp->clean1);
    }
    memset(irp, 0, sizeof(OHCIrp));
    IOS_Free(__ohcdHeapId, irp);
done:
    return;
}

static struct ohci_td *
__reverseTDList(struct ohci_td *head)
{
  u32 cur = (u32)CPU_TO_OHCI32(head);
  struct ohci_td *tmp;
  struct ohci_td tmp_rev; /* dummy */
  struct ohci_td *rev = &tmp_rev;

//  OHCI_DBG("list before reversing:\n");
//  dumpTDList(head);
  rev->nextTD = NULL;
  while (NULL != cur) {
      tmp = (struct ohci_td *)OHCI_TO_CPU32(cur);
      cur  = tmp->nextTD;
   
      tmp->nextTD = rev->nextTD;
      rev->nextTD = CPU_TO_OHCI32(tmp);
  } 
  tmp =  (struct ohci_td *) OHCI_TO_CPU32(rev->nextTD);
//  OHCI_DBG("list after reversing:\n");
//  dumpTDList(tmp);
  return tmp;
}

void
abortTDs(ohci_hcd *hcd, ohci_ed *ed)
{
    struct ohci_td *head;
    struct ohci_td *tail;
    OHCIrp *irp;
    u32 flag;

    IOS_FlushMem(hcd->hc_wb);
    IOS_InvalidateRdb(hcd->hc_rdb);
    head = (struct ohci_td *) (OHCI_TO_CPU32(ed->headP) & 0xfffffff0);
    flag =  OHCI_TO_CPU32(ed->headP) & 0x2;
    tail = (struct ohci_td *)OHCI_TO_CPU32(ed->tailP);
    if (head == tail) {
        goto done;
    }
  
    while (isValidTD(head) && tail != head) {
        irp = head->irp;
        --irp->ntd;
        ed->headP = head->nextTD;
        IOS_FlushDCache(ed, sizeof(struct ohci_ed));
        freeTD(head);
        if (0 == irp->ntd) {
            __replyAndFreeIRP(hcd, irp, -1 /* abort */);
        }
        head = (struct ohci_td *)(OHCI_TO_CPU32(ed->headP) & 0xfffffff0);
    }
done:
    /* Always clear possible ed halt */
    ed->headP = CPU_TO_OHCI32(OHCI_TO_CPU32(ed->headP)|flag);
    IOS_FlushDCache(ed, sizeof(struct ohci_ed));
    IOS_InvalidateRdb(hcd->hc_rdb);
    return;
}

static void
__processDoneIRP(ohci_hcd *hcd, ohci_td *t, s32 stat)
{
    IOS_FlushMem(hcd->hc_wb);
    IOS_InvalidateRdb(IOS_RB_IOD);
    __replyAndFreeIRP(hcd, t->irp, stat);
}

static u8
__processTDError(struct ohci_hcd *hcd, struct ohci_td *t, s32 stat)
{
    OHCIrp *irp = t->irp;
    struct ohci_ed *ed = irp->ed;

    OHCI_ERR("OHCI processing TD error for td  %p with irp %p td_flag %d\n", 
            t, t->irp, stat);
    OHCI_ERR("TD error for ed  %p; ed flag = 0x%x headP = 0x%x\n", ed,
            OHCI_TO_CPU32(ed->flags), OHCI_TO_CPU32(ed->headP));
    /* If no other TD errrors have already occurred and an error
     * has occurred now, set error */
    if (irp->done >= 0 && stat < 0) {
        irp->done = stat;
    }
    IOS_FlushMem(hcd->hc_wb);
    IOS_InvalidateRdb(IOS_RB_IOD);
    stopED(hcd, ed);
    /* Send reply to failed TD, if needed */
    if (0 == irp->ntd) {
        __processDoneIRP(hcd, t, stat);
    } 
    freeTD(t);

    /* Dequeue all TDs in the ED associated with this transfer */
    abortTDs(hcd, ed);
    /* Is ED halted because of this error? */
    if (OHCI_TO_CPU32(ed->headP) & OHCI_ED_HLT_MASK) {
        OHCI_ERR("OHCI ED %p halted: headP = 0x%x\n", ed, 
                OHCI_TO_CPU32(ed->headP));
        clearEDHalt(hcd, ed);
    }
    return 0;
}

/* ISO eds are never halted. No need to abort remaining xfers.
 * Only 1 TD per ISO xfer. So send reply.
 */
static void
__processITDError(ohci_hcd *hcd, ohci_td *t)
{
    OHCIrp *irp = t->irp;
    OHCI_DBG("Processing failed itd %p\n", t);
    irp->done = -(OHCI_TO_CPU32(t->flags & OHCI_TD_CC_MASK) >>28);
    OHCI_DBG("%s: itd return value set to %d\n", __FUNCTION__, irp->done);
    IOS_ResourceReply(irp->req, irp->done);
    memset(irp, 0, sizeof(OHCIrp)); /* For ISO, clean1 is NULL */
    IOS_Free(__ohcdHeapId, irp);
    freeTD(t); 
    return;
}

/* ISO xfers have 1 TD per xfer. Process and send reply. */
static void
__processDoneITD(ohci_hcd *hcd, ohci_td *t)
{
    OHCIrp *irp = t->irp;
    u8 i;
    u32 psw = 0;
    u32 flag = 1;
    
    OHCI_DBG("Processing completed itd %p\n", t);
    IOS_FlushMem(hcd->hc_wb);
    IOS_InvalidateRdb(IOS_RB_IOD);
   
    irp->done = 0;
    for (i = 0; i < irp->numPkts; ++i) {
        if (flag) {
            psw = OHCI_TO_CPU32(t->psw[i/2]);
            irp->pswSize[i] = (psw & 0x0000ffff);
            flag = 0;
        } else {
            irp->pswSize[i] = (psw & 0xffff0000) >> 16;
            flag = 1;
        }
    }

    freeTD(t);
    IOS_ResourceReply(irp->req, IOS_ERROR_OK);
    memset(irp, 0, sizeof(OHCIrp));
    IOS_Free(__ohcdHeapId, irp);
}

static void
__processDoneTD(ohci_hcd *hcd, ohci_td *t)
{
    OHCI_DBG("Processing completed td %p\n", t);
    if (t->len > 0) { /* Bookkeeping for data transferred */
        /* Since we only use the difference, no need to
         * translate DMA->CPU SRAM addresses.
         */
        u32 start = OHCI_TO_CPU32(t->cbp);
        u32 end = OHCI_TO_CPU32(t->be);
        if (0 != start) {
            t->irp->done += t->len - (end - start + 1);
        } else {
            t->irp->done += t->len;
        }
    }
    if (0 == t->irp->ntd) { /* Last TD done => IRP done */
        __processDoneIRP(hcd, t, IUSB_ERROR_NOERROR);
    }
    freeTD(t);
}


static void
handleWDH(struct ohci_hcd *hcd)
{
    struct ohci_td *t;
    struct ohci_td *tmp;
    u32 td_flag = 0;

    IOS_FlushMem(hcd->hc_wb);
    IOS_InvalidateRdb(IOS_RB_IOD);
    t = (struct ohci_td *) 
        (OHCI_TO_CPU32((struct ohci_hcca *)(hcd->hcca)->donehead) & 0xfffffff0);
    t = __reverseTDList(t);

    while (NULL != t) {
        OHCI_DBG("Processing completed td %p\n", t);
        tmp = (struct ohci_td *) OHCI_TO_CPU32(t->nextTD);
        
        --t->irp->ntd; 
        td_flag = OHCI_TO_CPU32(t->flags);
        if ((OHCI_TD_TYPE_ITD & td_flag) &&
            (OHCI_CC_NOERROR != (td_flag & OHCI_TD_CC_MASK))) {
            __processITDError(hcd, t);
        } else if (OHCI_CC_NOERROR != (td_flag & OHCI_TD_CC_MASK)) { 
            OHCI_DBG("TD error: td flag = 0x%08x\n", td_flag);
            __processTDError(hcd, t, IUSB_CC_ERR(td_flag)); 
            /* current TD freed as part of aborting EP */
        } else if (OHCI_TD_TYPE_ITD & td_flag) { 
            __processDoneITD(hcd, t); 
        } else {
            __processDoneTD(hcd, t); 
        }

        t = tmp; 
    }
    IOS_FlushMem(IOS_WB_IOD);
    IOS_InvalidateRdb(hcd->hc_rdb);
//    hcd->hcca->donehead = 0;
}

static void
handleOHCIIntr(struct ohci_hcd *hcd)
{
    u32 reg = OHCI_READ(hcd->opregs->int_stat);
    u32 mask = OHCI_READ(hcd->opregs->int_en);
    //  OHCI_DBG("Int status = %x mask = %x\n", reg, mask); 

    if (reg & OHCI_INTSTAT_WDH_MASK && mask & OHCI_INTEN_WDH_MASK) {
        handleWDH(hcd);
        OHCI_WRITE(hcd->opregs->int_stat, OHCI_INTSTAT_WDH_MASK);
        reg &= ~OHCI_INTSTAT_WDH_MASK;
    }
    if (reg & OHCI_INTSTAT_RHSC_MASK && mask & OHCI_INTEN_RHSC_MASK) {
        if (hcd->flags & HCD_RHUB_INIT_MASK) { /* RH initialized */
            OHCI_DBG("Detected RH status change\n");
            if (hcd->flags & HCD_RM_INIT_MASK) {
                IOS_SendMessage(hcd->rm_qid, HCD_RHUB_EVENT, IOS_MESSAGE_NOBLOCK);
            }
        }
        OHCI_WRITE(hcd->opregs->int_stat, OHCI_INTSTAT_RHSC_MASK);
        reg &= ~OHCI_INTSTAT_RHSC_MASK;
    }
    OHCI_WRITE(hcd->opregs->int_stat, reg);
}

static void
__clearOHCIIntr(struct ohci_hcd *hcd)
{
    OHCI_WRITE(hcd->opregs->int_stat, 0xffffffff);
} 

#define HCD_QUEUE_SIZE 4
void
initOHCEvent(u32 arg)
{ 
    IOSMessageQueueId hcdQId;
    IOSMessage hcdQ[HCD_QUEUE_SIZE];
    IOSError rv = IOS_ERROR_OK;
    struct ohci_hcd *hcd = (struct ohci_hcd *)arg;
    IOSEvent hc_event = hcd->event;

    OHCI_DBG("OHC event handler running...\n");
    /* Create message queue */
    hcdQId = IOS_CreateMessageQueue(hcdQ, sizeof(hcdQ));
    if ((rv = IOS_HandleEvent(hc_event, hcdQId, 0)) != IOS_ERROR_OK) {
        OHCI_DBG("Unable to register ohci event handler: %d\n", rv);
        goto done;
    }

    /* Loop forever while waiting for OHCI events */
    __clearOHCIIntr(hcd);
    IOS_ClearAndEnableEvent(hc_event);
    while (1) {
        if (IOS_ReceiveMessage(hcdQId, NULL, IOS_MESSAGE_BLOCK) == IOS_ERROR_OK) {            
            handleOHCIIntr(hcd);
            IOS_ClearAndEnableEvent(hc_event);
        }
    }
done:
    return;
}
