/*
 *               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 cif unit;
 */
void
cif_init(u32 cpu, test_thread_t *thp)
{
	// sim zeros msg area;

	thp->msg = (test_msg_u *)MEM_CIF;
	thp->state = TT_REQ;
}

/*
 * request cif work from sim;
 * this requests programming of the cif ctrl regs;
 * the sim side also generates gba bus cycles;
 */
void
cif_req(u32 cpu, test_thread_t *thp)
{
	cif_msg_t *msg = &(thp->msg)->cif;

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

/*
 * poll for sim reply;
 */
void
cif_reply(u32 cpu, test_thread_t *thp)
{
	cif_msg_t *msg = &(thp->msg)->cif;

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

/*
 * setup for rom/sram test;
 */
void
cif_rsm(void)
{
	u32 ctrl;

	// no rom window, no ipc, 32MB rom, no rom intr;

	ctrl = ROM_CFG1_TYPE | 0;
	IO_WRITE(IPC_CTRL_REG, ctrl);
	ctrl = 0;
	IO_WRITE(IPC_CTRL_REG, ctrl);

	// no ipc, clear pending intr;

	ctrl = IPC_CTRL_MASK_WE;
	IO_WRITE(IPC_CTRL_REG, ctrl);

	// sram mapped to DRAM, timer off;

	ctrl = 0x02000000;
	IO_WRITE(SRAM_CFG_REG, ctrl);

	// eerom emulation is off;

	IO_WRITE(EEROM_CFG_REG, 0);

	// flash emulation is off;

	IO_WRITE(BUFL_CFG_REG, 0);
	IO_WRITE(BUFL_ADDA_REG, 0);

	// enable cif, clear all intr;

	ctrl = CIF_CTRL_EMU | CIF_CTRL_EMU_SRAM | CIF_CTRL_EMU_ROM
		| CIF_CTRL_INTR_ROM | CIF_CTRL_INTR_IPC
		| CIF_CTRL_INTR_FLASH | CIF_CTRL_INTR_EEROM
		| CIF_CTRL_SRAM_TIMER
		| CIF_CTRL_SRAM_VIOL | CIF_CTRL_ROM_VIOL
		| CIF_CTRL_BUS_INV | CIF_CTRL_BUS_VAL;
	IO_WRITE(CIF_CTRL_REG, ctrl);
}

/*
 * start cif operation;
 */
void
cif_start(u32 cpu, test_thread_t *thp)
{
	cif_msg_t *msg = &(thp->msg)->cif;

	switch(msg->setup) {
		case CIF_RSM:				// rom/sram test;
			cif_rsm();
			break;
		default:					// turn cif off;
			IO_WRITE(CIF_CTRL_REG, CIF_CTRL_EMU);
	}
	thp->state = TT_WAIT;
}

/*
 * wait for cif operation to finish;
 * spin until cif goes invalid, as reset by sim;
 */
void
cif_wait(u32 cpu, test_thread_t *thp)
{
	u32 ctrl;

	ctrl = IO_READ(CIF_CTRL_REG);
	if(ctrl & CIF_CTRL_BUS_INV)
		thp->state = TT_POST;
	//XXX timeout;
}

/*
 * cif post-op;
 */
void
cif_post(u32 cpu, test_thread_t *thp)
{
	u32 ctrl;

	ctrl = IO_READ(CIF_CTRL_REG);
	if(ctrl & CIF_CTRL_BUS_VAL)
		thp->state = TT_REQ;
}

