/* pll test;
 * tester monitors pll outputs on gba bus;
 * tph file must unmask all outputs;
 * frequency counter in tester is used to measure frequencies;
 * tester should measure: sys pll, aud pll, usb pll, and SDR_CLK;
 * :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;
// can only run one system pll config at a time;

int 
testProc(void *p)
{
	DVCmdStructPnt pcmd;
	int pllcfg, nclks;

	// first option is system pll config;
	// second option is test runtime;

    pcmd = (DVCmdStructPnt) p;
	if(pcmd->argc != 3)
		return(1);

	// 'start' has already loaded the boot code;

	pllcfg = atoi(pcmd->argv[1]);
	nclks = atoi(pcmd->argv[2]);

	// simulator is at time 0;
	// must use SYS_RESET for deteministic por timing;
	// no pll bypassing;

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

	// programm xtal clock, then trigger por_barrier,
	// which enables the xtal clock generator;

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

	// set system pll configuration;
	// deassert SYS_RESET after four xtal clocks;
	// wait for system to come out of reset;
	// TESTMODE is only looked at after chip is unlocked;

	DV_XtalStall(1);
	DV_CpuBdSetValue("sim.syspll_cfg", pllcfg, 0);
	DV_XtalStall(4);
	DV_CpuBdSetSysReset(1);
	DV_CpuWaitReset();

	// prevent cpu from booting;
	// turn flash off by forcing ready/busy 1;

	DV_CpuBdSetValue("sim.fl_off", 1, 0);

	// put gba interface in reset;
	// gba ad[23:14] become outputs, pll/audio clocks;
	// gba ad[13:0] become test inputs;

	DV_CpuBdSetGbaRd(0);
	DV_CpuBdSetGbaWr(0);
	DV_CpuBdSetValue("sim.gba.ad_oe", 0x003fff, 0);
	DV_CpuBdSetValue("sim.gba.ad_out", 0x002000, 0);

	// set testmode;
	// this enables pll controls/outputs on GBA bus;

	DV_XtalStall(1);
	DV_CpuBdSetSysTestmode(1);

	// audio & usb plls start locking after SYS_TESTMODE=1;
	// give these plls time to lock;
	// reset of audio clock divider need audio pll clock;

	DV_XtalStall(10000);
	DV_CpuBdSetValue("sim.gba.ad_out", 0x000000, 0);

	// give tester time to measure;

	DV_XtalStall(nclks);

	return(0);
}

