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

#include "ohci_core.h"

#ifdef OHCI_ENABLE_DBG
static char * 
td_err[] = {
    "No error",
    "CRC error",
    "Bitstuffing error",
    "Data toggle mismatch",
    "Endpoint stalled",
    "Device not responding",
    "PID check failure",
    "Unexpected PID",
    "Data overrun",
    "Data underrun",
    "Unknown (reserved) error",
    "Unknown (reserved) error",
    "Buffer overrun",
    "Buffer underrun",
    "TD not accessed"
};
#endif /* OHCI_ENABLE_DBG */

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(struct ohci_hcd *hcd, struct 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) & 0xf;
    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(irp);
        }
        head = (struct ohci_td *)(OHCI_TO_CPU32(ed->headP) & 0xfffffff0);
    }
    ed->headP = CPU_TO_OHCI32(OHCI_TO_CPU32(ed->headP)|flag);
    IOS_FlushDCache(ed, sizeof(struct ohci_ed));
    IOS_InvalidateRdb(hcd->hc_rdb);
done:
    return;
}

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

    printf("OHCI processing TD error for td  %p with irp %p\n", t, t->irp);
    printf("TD error for ed  %p; ed flag = 0x%x headP = 0x%x\n", ed,
            OHCI_TO_CPU32(ed->flags), OHCI_TO_CPU32(ed->headP));
    printf("TD error for ed  %p\n", ed);

    IOS_FlushMem(hcd->hc_wb);
    IOS_InvalidateRdb(IOS_RB_IOD);
    stopED(hcd, ed);
    /* 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) {
        printf("OHCI ED %p halted: headP = 0x%x\n", ed, 
                OHCI_TO_CPU32(ed->headP));
        clearEDHalt(hcd, ed);
    }
    return 0;
}

void
replyAndFreeIRP(OHCIrp *irp)
{
    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
         */
        OHCI_DBG("sending message to queue id %d\n", irp->qid);
        IOS_SendMessage(irp->qid, irp->done, IOS_MESSAGE_BLOCK);
    } else {
        OHCI_DBG("send resource reply with req %p\n", irp->req);
        /* Invalidate user's buffer */
        if (0 != irp->datalen)
            IOS_InvalidateDCache(irp->data, irp->datalen); 
        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;
}

#ifdef XFER_DBG
static void
__xferDbgLog(struct ohci_hcd *hcd, struct ohci_td *t)
{
    u8 reqTyp;
    reqTyp = t->irp->req->args.ioctl.cmd;
    if (OHC_CTRL_MSG == reqTyp) {
        reqTyp = DBG_REQ_TYPE_CTRL;
    } else if (OHC_BLK_MSG == reqTyp) {
        reqTyp = DBG_REQ_TYPE_BLK;
    } else {
        reqTyp = DBG_REQ_TYPE_INTR;
    }
    postDbgMsg(hcd, dbgGetMsgId(hcd), reqTyp, DBG_REQ_DIR_UNDEF, t->irp->dbgId, t->irp->done, DBG_MSG_TYPE_REPLY);
}
#endif

static void
__processDoneIRP(struct ohci_hcd *hcd, struct ohci_td *t)
{
    /* Flush any remaining bytes in HC's AHB write buffer */
    IOS_FlushMem(hcd->hc_wb);
    if (t->irp->err != 0) {
        OHCI_DBG("Errors encountered while processing IRP:%p\n", t->irp);
    }
#ifdef XFER_DBG
    __xferDbgLog(hcd, t);
#endif
    replyAndFreeIRP(t->irp);
}

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);

        /* Process completed TD */
        --t->irp->ntd; 

        /* Check if TD failed */
        td_flag = OHCI_TD_CC_MASK & OHCI_TO_CPU32(t->flags);
        if (OHCI_CC_NOERROR != td_flag ) {
            ++t->irp->err;
            printf("OHCI processing TD error: 0x%x\n", td_flag);
            processTDError(hcd, t); 
            /* current TD freed as part of aborting EP */
        } else {
            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);
            }
            freeTD(t);
        }
        t = tmp; /* Process next TD */
    }
//    hcd->hcca->donehead = 0;
}

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

    if (reg & OHCI_INTSTAT_WDH_MASK) {
        handleWDH(hcd);
        OHCI_WRITE(hcd->opregs->int_stat, OHCI_INTSTAT_WDH_MASK);
    }
    if (reg & OHCI_INTSTAT_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_BLOCK);
            }
        }
        OHCI_WRITE(hcd->opregs->int_stat, OHCI_INTSTAT_RHSC_MASK);
    }
    reg &= ~(OHCI_INTSTAT_WDH_MASK | OHCI_INTSTAT_RHSC_MASK);
    OHCI_WRITE(hcd->opregs->int_stat, reg);
}

static inline 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;
}
