/* por test;
 * brings chip through por reset;
 * returns when cpus come out of reset;
 * :set tabstop=4
 */

#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include "dv.h"
#include "dv_boot.h"

// test entry;
// assume kilopass is empty, hash is 0;

int 
testProc(void *p)
{
	DVCmdStructPnt pcmd;
	int xtal;
	long long to;

	// first option is xtal period in ps;
	// number must be divisible by 8 and 6;
	// cannot have fractions smaller than 100ps for tester;

	pcmd = (DVCmdStructPnt) p;
	xtal=76800;
	if(pcmd->argc == 2)
		xtal = atoi(pcmd->argv[1]);
	else if(pcmd->argc != 1)
		return(1);

	// 'start' has already loaded the boot code;
	// pll configuration does not matter;
	// set simulator timeout based on xtal;
	// use 25k xtal clocks, which is 2ms at 12Mhz;

	to = ((long long)xtal * 25000) / 1000;
	DV_SetTestTimeout((int)to);

	// simulator is at time 0;
	// must drive SYS_RESET=1 and use bypass clocks;

	DV_CpuBdSetSysReset(1);
	DV_CpuBdSetValue("sim.syspll_bypass", 1, 0);
	DV_CpuBdSetValue("sim.audpll_bypass", 1, 0);
	DV_CpuBdSetValue("sim.usbpll_bypass", 1, 0);

	// drive AUD_GPIO[7]=0 from outside;

	DV_CpuBdSetValue("sim.audio_gpio.out", 0, 0);
	DV_CpuBdSetValue("sim.audio_gpio.oe", 0x80, 0);

	// programm xtal, then trigger por_barrier,
	// which program bypass clocks and enables the xtal clock generator;

	DV_CpuBdSetValue("sim.clkgen_xtal.period", xtal, 0);
	DV_CpuBdSetValue("sim.por_barrier", 1, 0);

	// set system pll configuration;
	// update PLI's periods;

	DV_XtalStall(1);
	DV_CpuSetXtalPeriod(xtal);
	DV_XtalStall(1);
	DV_CpuBdSetValue("sim.syspll_cfg", 0, 0);
	DV_CpuBdSetValue("sim.gba.phi_en", 1, 0);

	// wait 64 xtal clocks for por circuit uncertainty;
	// bypass clocks must still be off;
	// enable gba phi for gba model initialization;
	// wait 2^12 xtal clocks for pullup stabilization;

	DV_XtalStall(80);
	DV_CpuBdSetValue("sim.gba.ready", 1, 0);
	DV_XtalStall(1 << 12);

	// feed in system clocks for system reset to work;
	// soft_rst would otherwise cause Xs;
	// leave audio/usb bypass clocks still off,
	// they need device initialization to be useful;

	DV_CpuBdSetValue("sim.clkgen_sys_byp.ena", 1, 0);

	// wait for system to come out of reset;
	// cpu0 is starting to run boot rom code;

	DV_CpuWaitReset();

	return(0);
}

