/*
 *               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
removeTDs(struct ohci_ed *ed)
{
    struct ohci_td *head = (struct ohci_td *) (OHCI_TO_CPU32(ed->headP) & 0xfffffff0);
    struct ohci_td *tail = (struct ohci_td *)OHCI_TO_CPU32(ed->tailP);
    /* If head == node */
    while (isValidTD(head) && tail != head) {
        ed->headP = head->nextTD;
        /* XXX Need to check if this is a real TD */
        freeTD(head);
        OHCI_DBG("Freed %p\n", head);
        head = (struct ohci_td *)OHCI_TO_CPU32(ed->headP);
    }
    if (0 == isValidTD(head)) { /* bad stuff has happened */
        ed->headP = ed->tailP = CPU_TO_OHCI32(allocTD());
        OHCI_DBG("Allocated new dummy td\n");
    }
    return;
}

static u8
processTDError(struct ohci_hcd *hcd, struct ohci_td *t, u32 flag)
{
    u8 errid = flag >> OHCI_TD_CC_SHIFT;

    IOS_FlushMem(hcd->hc_wb);
    IOS_InvalidateRdb(IOS_RB_IOD);
    OHCI_DBG("OHCI TD error: %s\n", td_err[errid]);
    /* Is ED halted because of this error? */
    if (OHCI_TO_CPU32(t->irp->ed->headP) & OHCI_ED_HLT_MASK) {
        OHCI_DBG("OHCI ED for IRP %p halted\n", t->irp);
    }
    /* Dequeue all TDs in the ED associated with this transfer */
    removeTDs(t->irp->ed);
    /* Clear halt. Restart ED. */
    clearEDHalt(hcd, t->irp->ed);
    return errid;
}

static void
handleWDH(struct ohci_hcd *hcd)
{
    struct ohci_td *t = (struct ohci_td *) 
        (OHCI_TO_CPU32((struct ohci_hcca *)(hcd->hcca)->donehead) & 0xfffffff0);
    struct ohci_td *tmp;
    u32 td_flag = 0;

    hcd->hcca->donehead = 0;
   
    IOS_FlushMem(hcd->hc_wb);
    IOS_InvalidateRdb(IOS_RB_IOD);

    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; /* one less TD remaining */

        /* Check if TD failed */
        td_flag = OHCI_TD_CC_MASK & OHCI_TO_CPU32(t->flags);
        if (OHCI_CC_NOERROR != td_flag ) {
            ++t->irp->err;
            processTDError(hcd, t, td_flag); 
            t->irp->ntd = 0; /* Aborted */
        }
        /* Bookkeeping for amount of data transferred */
        if ((t->len > 0) && (OHCI_CC_NOERROR == td_flag)) { 
            /* 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 (t->irp->ntd > 0) {
            OHCI_DBG("Remaining td's for transfer %p : %d\n", t->irp, t->irp->ntd);
        
        }
        else {
            OHCI_DBG("Reply already sent for IRP %p : %d\n", t->irp);
        }

        if (0 == t->irp->ntd) { /* Last TD done => IRP done */
            /* 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
            {
                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

            if (t->irp->qid > 0) {
                /* Internal buffers are allocated from non-cached space.
                 * No need to flush
                 */
                OHCI_DBG("sending message to queue id %d\n", t->irp->qid);
                IOS_SendMessage(t->irp->qid, t->irp->done, IOS_MESSAGE_BLOCK);
            }
            else {
                OHCI_DBG("send resource reply with req %p\n", t->irp->req);
                /* Invalidate user's buffer */
                if (0 != t->irp->datalen)
                    IOS_InvalidateDCache(t->irp->data, t->irp->datalen); 
                IOS_ResourceReply(t->irp->req, t->irp->done);
            }

            memset(t->irp, 0, sizeof(OHCIrp));
            IOS_Free(__ohcdHeapId, t->irp);
            memset(t, 0, sizeof(struct ohci_td));
        }
        freeTD(t); /* Cleanup */
        t = tmp;
    }
}

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, reg);
    }
    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) {            
            //            OHCI_DBG("Received event: %u (OH0 = %u OH1 = %u)\n", hc_event,
            //                    IOS_EVENT_OH0, IOS_EVENT_OH1);
            handleOHCIIntr(hcd);
            IOS_ClearAndEnableEvent(hc_event);
        }
    }
done:
    return;
}
