/*
 *               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 <types.h>
#include <sc/sc.h>
#include "ft.h"

/*
 * initialize usb unit;
 */
void
usb_init(u32 cpu, test_thread_t *thp)
{
	// sim zeros msg area;

	thp->msg = (test_msg_u *)MEM_USB;

	// turn on usb clock, reset;
	// reset usb engine;
	// program device id;

	IO_WRITE(PWR_CTRL_REG, PWR_CTRL_ASSERT_RST << PWR_CTRL_USB_SHIFT);
	IO_WRITE(PWR_CTRL_REG, PWR_CTRL_CLOCK_ON << PWR_CTRL_USB_SHIFT);
	IO_WRITE(PWR_CTRL_REG, PWR_CTRL_DEASSERT_RST << PWR_CTRL_USB_SHIFT);
	IO_WRITE(USB_CTRL_REG, 0);
	IO_WRITE(USB_ID_REG, ID_USB);

	thp->state = TT_REQ;
}

/*
 * request usb work from sim;
 */
void
usb_req(u32 cpu, test_thread_t *thp)
{
	usb_msg_t *msg = &(thp->msg)->usb;

	msg->req = MSG_REQ;
	msg_wbi(msg, sizeof(usb_msg_t));
	thp->state = TT_REPLY;
}

/*
 * poll for sim reply;
 */
void
usb_reply(u32 cpu, test_thread_t *thp)
{
	usb_msg_t *msg = &(thp->msg)->usb;

	msg_wbi(msg, sizeof(usb_msg_t));
	if(msg->req == MSG_NONE)
		thp->state = TT_START;		// got reply;
}

/*
 * start usb operation;
 */
void
usb_start(u32 cpu, test_thread_t *thp)
{
	usb_msg_t *msg = &(thp->msg)->usb;

	IO_WRITE(USB_CTRL_REG, msg->ctrl);
	IO_WRITE(USB_IN0_PTR_REG, msg->iptr[0]);
	IO_WRITE(USB_IN1_PTR_REG, msg->iptr[1]);
	IO_WRITE(USB_IN2_PTR_REG, msg->iptr[2]);
	IO_WRITE(USB_OUT0_PTR_REG, msg->optr[0]);
	IO_WRITE(USB_OUT1_PTR_REG, msg->optr[1]);
	IO_WRITE(USB_OUT3_PTR_REG, msg->optr[2]);
	IO_WRITE(USB_IN0_LEN_REG, msg->ilen[0]);
	IO_WRITE(USB_IN1_LEN_REG, msg->ilen[1]);
	IO_WRITE(USB_IN2_LEN_REG, msg->ilen[2]);
	IO_WRITE(USB_OUT0_LEN_REG, msg->olen[0]);
	IO_WRITE(USB_OUT1_LEN_REG, msg->olen[1]);
	IO_WRITE(USB_OUT3_LEN_REG, msg->olen[2]);
	thp->state = TT_WAIT;
}

/*
 * wait for usb operation to finish;
 */
void
usb_wait(u32 cpu, test_thread_t *thp)
{
	u32 ctrl;

	ctrl = IO_READ(msg->wait[0]);
	if((ctrl & msg->wait[1]) == msg->wait[2]) {
		thp->state = TT_POST;
		return;
	}
	//XXX timeout;
}

/*
 * usb post-op;
 */
void
usb_post(u32 cpu, test_thread_t *thp)
{
	thp->state = TT_REQ;
}

