/**************************************************************
$Workfile:   bmetest.c  $
***************************************************************
**
** FIRMWARE, Copyright (C) 2000-2002
** Ikanos Communication, Fremont, CA  
** All rights reserved.
**
** The information and contents of this file are the
** proprietary information of Ikanos Communication and may not
** be disclosed or used without the formal written approval of
** Ikanos Communication
**
$Revision: 1.1 $
$Date: 2006/10/16 04:34:50 $
**************************************************************/

/* #includes */
#include "vxWorks.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "apiosmacro.h"

#include "dapi_define.h"
#include "dapi_parms.h"
#include "mem.h"
#include "bmehwapi.h"
#include "time.h"
 
#include "diag.h"
/* #defines */
ipos_sem_id			semDiagHic = NULL; //semaphore for HIC access protection 

/* global vars */
/* extern vars */
extern BYTE HostCpuEndianType;
extern BYTE BMECodeArray[];
extern BYTE BmeResetVecCode[BME_RESET_VEC_CODE_SIZE];	
extern BYTE BmeResetVecCode2[BME_RESET_VEC_CODE_SIZE];
extern STATUS remoteUpLoadImage( int len, char *hostName, char *fileName);
extern tBmeStruct Bme[5];


/* function prototypes */
/* extern functions */
extern void EventLog(const char *output, ...);
extern void delay (void);
void ClearMem();

#ifdef _PARALLEL_IO_INTERFACE_
#undef  _PARALLEL_IO_INTERFACE_
#endif /*  _PARALLEL_IO_INTERFACE_ */

#define PLPRCR(base) ((UINT32 *)((0xFF000000) + 0x0284))
#define	SYPCR(base)	((UINT32 *)((0xFF000000) + 0x0004)) /* Protection Ctrl */
#define SYPCR_BME	0x00000080	/* Bus Monitor Enable */
#define MPTPR(base)	((UINT16 *)((0xFF000000) + 0x017A)) /* Mem Timer Presc*/

#ifdef _PARALLEL_IO_INTERFACE_
BYTE bRdEnable = 0;
extern BYTE bRdDataVal; /* var which gives the read data */
extern BYTE ledState; /* toggling flag to switch on & off LEDS */
extern BYTE RdySig; /* flag signifying Ready signal is being asserted */
extern unsigned long lRdCount; 
extern unsigned long bErrCnt;

#define	PBDIR(base)	((UINT32 *)((0xFF000000) + 0x0AB8)) /* PB data dir */
#define	PBPAR(base)	((UINT32 *)((0xFF000000) + 0x0ABC)) /* PB pin ass*/
#define	PBODR(base)	((UINT32 *)((0xFF000000) + 0x0AC0)) /* PB open drain*/
#define	PBDAT(base)	((UINT32 *)((0xFF000000) + 0x0AC4)) /* PB Data Reg*/

#define	PADIR(base)	((UINT32 *)((0xFF000000) + 0x0950)) /* PB data dir */
#define	PAPAR(base)	((UINT32 *)((0xFF000000) + 0x0952)) /* PB pin ass*/
#define	PAODR(base)	((UINT32 *)((0xFF000000) + 0x0954)) /* PB open drain*/
#define	PADAT(base)	((UINT32 *)((0xFF000000) + 0x0956)) /* PB Data Reg*/

#define	PCDIR(base)	((UINT32 *)((0xFF000000) + 0x0960)) /* PB data dir */
#define	PCPAR(base)	((UINT32 *)((0xFF000000) + 0x0962)) /* PB pin ass*/
#define	PCDAT(base)	((UINT32 *)((0xFF000000) + 0x0966)) /* PB Data Reg*/

#define	PDDIR(base)	((UINT32 *)((0xFF000000) + 0x0970)) /* PB data dir */
#define	PDPAR(base)	((UINT32 *)((0xFF000000) + 0x0972)) /* PB pin ass*/
#define	PDDAT(base)	((UINT32 *)((0xFF000000) + 0x0976)) /* PB Data Reg*/

#define PB31    (0x00001)
#define PB30    (0x00002)
#define PB29    (0x00004)
#define PB28    (0x00008)
#define PB27    (0x00010)
#define PB26    (0x00020)
#define PB25    (0x00040)
#define PB24    (0x00080)
#define PB23    (0x00100)
#define PB22    (0x00200)
#define PB21    (0x00400)
#define PB20    (0x00800)
#define PB19    (0x01000)
#define PB18    (0x02000)
#define PB17    (0x04000)
#define PB16    (0x08000)
#define PB15    (0x10000)
#define PB14    (0x20000)

#define PD3		(0x1000)
#define PD4		(0x0800)
#define PD5		(0x0400)
#define PD6		(0x0200)
#define PD7		(0x0100)
#define PD8		(0x0080)
#define PD9		(0x0040)
#define PD10	(0x0020)
#define PD11 	(0x0010)
#define PD12	(0x0008)
#define PD13	(0x0004)

#define CS		1	/* chip select */
#define OE		2	/* data strobe */ 
#define RW 		3	/* read write */
#define ADDR	4	/* address */
#define DATA	5	/* data */

#endif /* _PARALLEL_IO_INTERFACE */

/* Local Prototypes */
void pio_read (UINT32 srcAddr, UINT32 *data);
void pio_write (UINT32 destAddr, UINT32 data);
void pollStatus (int BmeNum);
void testDMARead (int BmeNum, UINT32 addr,int size);


/* External Prototypes */
extern HWAPI_RET_VAL bmeVerifyCodeDnld (tBmeStruct *bmeStruct);
extern HWAPI_RET_VAL bmeDnldProcedure (tBmeStruct *bmeStruct);
extern void InitDmaChannel15 (tBmeStruct *bmeStruct);
extern void testPIOWrite (int BmeNum, unsigned long addr, unsigned long data);
extern int testPIORead (int BmeNum, unsigned long addr);
extern void iposDelay (void);
extern void InitPortParms(tBmeStruct *pBme, int PortNum);
extern int testPIORead_diag (int BmeNum, unsigned long addr);

extern char tmpBuf[];

BYTE AtmCell[53] = {0x00,0x30,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,   
		    0x00,0x30,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,  
		    0x00,0x30,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,  
		    0x00,0x30,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,  
		    0x00,0x30,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,  
		    0x00,0x30,0xaa};

UINT32 bmeReset[50];

BYTE DmaArray[0x2000];

BYTE evlogBme = 1;
/****************************************************************************/
/**									   **/
/**		PIO/ DMA Basic functionality Functions			   **/
/**									   **/
/****************************************************************************/
							

/****************************************************************************/
/*                                                                          */
/* Function.. : InitDma	                              			            */
/*                                                   	                    */
/* Purpose... : function to initialize Dma channel 15 						*/
/*																			*/
/* Parameters : None														*/
/*                                                                          */
/* Returns... : N/A                                                         */
/*                                                                          */
/* Notes..... : None                                                        */
/*                                                                          */
/****************************************************************************/

void InitDma (int BmeNum)
{

	HostCpuEndianType = 2; /* big endian format */
	Bme[BmeNum].BMEbaseAddr = BME_BASE_ADDR; /* memory mapped BME interface base address */
	InitDmaChannel15(&Bme[BmeNum]);

	return;
}

/****************************************************************************/
/*                                                                          */
/* Function.. : testDMAWrite                           			            */
/*                                                   	                    */
/* Purpose... : function to test DMA write thru DMA FIFO interface			*/
/*									    */
/* Parameters : None														*/
/*                                                                          */
/* Returns... : N/A                                                         */
/*                                                                          */
/* Notes..... : None                                                        */
/*                                                                          */
/****************************************************************************/

void testDMAWrite (int BmeNum,int flag)
{
	UINT32 data=0;
	HostCpuEndianType = 2;
	Bme[BmeNum].BMEbaseAddr = BME_BASE_ADDR;

	printf ("\ntestDMAWrite");
	bmePioRead (&Bme[BmeNum], DMA_CCR(0, DMA_CH_15), (BYTE *)&data);
	printf ("\nBefore bmeWrMemory DMA_CCR 0x%08lx", data);

if (flag==0)
{
	bmePioRead (&Bme[BmeNum], DMA_CCR(0, DMA_CH_15), (BYTE *)&data);
	printf ("\nDMA_CCR 0x%08lx", data);
	/* write to external memory, 16 bytes of data */
	bmeWrMemory (&Bme[BmeNum], 0x40000000/*0x40008000*/, &BmeResetVecCode2[0],56);
}


if (flag==1)
{	Bme[BmeNum].FifoFlag=1;
	/* XFIFO */
	testPIOWrite (BmeNum,0xE0040000,0x0000002F);
	testPIOWrite (BmeNum,0xE0040100,0);

	bmeWrMemory (&Bme[BmeNum], 0xC0000000, &BmeResetVecCode[0],BME_RESET_VEC_CODE_SIZE);	
}	/* XFIFO */
if (flag==2)
{	testPIOWrite(BmeNum,0xe0068100, 0x00000000);
	testPIOWrite(BmeNum,0xe0068000, 0x0000002b);
	Bme[BmeNum].FifoFlag=1;
	/* CFIFO */
	bmeWrMemory (&Bme[BmeNum], 0xC6000000, &AtmCell[0],53);	
}	/* CFIFO */
	
 	/* after writing poll for DMA_DONE status */

	return;
}


/****************************************************************************/
/*                                                                          */
/* Function.. : testDma	                              			            */
/*                                                   	                    */
/* Purpose... : function to test DMA write & DMA read thru DMA FIFO 		*/
/*				interface													*/
/*																			*/
/* Parameters : None														*/
/*                                                                          */
/* Returns... : N/A                                                         */
/*                                                                          */
/* Notes..... : None                                                        */
/*                                                                          */
/****************************************************************************/

void testDMA(int BmeNum,int flag)
{
	HostCpuEndianType = 2;
	Bme[BmeNum].BMEbaseAddr = BME_BASE_ADDR;
	

	printf ("\nTestDMA");
	
	/* Initialize DMA channel 15 */
	InitDma(BmeNum); 


	/* test DMA write */
	testDMAWrite(BmeNum,flag);

	/* poll for DMA_DONE bit / DW_H status bit to be set */
	pollStatus(BmeNum);

	return;
}

/****************************************************************************/
/*                                                                          */
/* Function.. : rdDMARegs	                              			        */
/*                                                   	                    */
/* Purpose... : function to read all registers of DMA channel 15			*/
/*		 		DMA_SAR, DMA_DAR, DMA_ECR, DMA_CCR							*/
/*																			*/
/* Parameters : None														*/
/*                                                                          */
/* Returns... : N/A                                                         */
/*                                                                          */
/* Notes..... : None                                                        */
/*                                                                          */
/****************************************************************************/

void rdDMARegs ()
{
	UINT32 data = 0;

	printf ("\nRead DMA regs : ");

	/* read DMA Source Address Reg */
	bmePioRead (&Bme[1], DMA_SAR(0, DMA_CH_15), (BYTE *)&data);
	printf ("\nDMA_SAR 0x%08lx", data); 

	/* read DMA Destination Address Reg */	
	data = 0;  
	bmePioRead (&Bme[1], DMA_DAR(0, DMA_CH_15), (BYTE *)&data);
	printf ("\nDMA_DAR 0x%08lx", data);

	/* read DMA Event Control Reg */
	data = 0;
	bmePioRead (&Bme[1], DMA_ECR(0, DMA_CH_15), (BYTE *)&data);
	printf ("\nDMA_ECR 0x%08lx", data);

	/* read DMA Channel Control Reg */
	data = 0;
	bmePioRead (&Bme[1], DMA_CCR(0, DMA_CH_15), (BYTE *)&data);
	printf ("\nDMA_CCR 0x%08lx", data);

	return;

}

/****************************************************************************/
/*                                                                          */
/* Function.. : clrDMADone                             			            */
/*                                                   	                    */
/* Purpose... : function to read DMA_CCR reg - check for DMA_DONE bit, clear*/
/*				DMA_DONE bit, read it back & check again			 		*/
/*																			*/
/* Parameters : None														*/
/*                                                                          */
/* Returns... : N/A                                                         */
/*                                                                          */
/* Notes..... : None                                                        */
/*                                                                          */
/****************************************************************************/

void clrDMADone ()
{
	UINT32 data;

	/* read DMA Channel Control Reg */
    data = 0;
#ifdef BME_CPE_20
    bmePioRead (&Bme[1], DMA_CCR(0, DMA_CH_7), (BYTE *)&data);
#else
    bmePioRead (&Bme[1], DMA_CCR(0, DMA_CH_15), (BYTE *)&data);
#endif
	printf ("\nDMA_CCR 0x%08lx", data);

	/* write/clear DMA_DONE bit in DMA Channel Control Reg */
	data = 0x00001800;
#ifdef BME_CPE_20
	bmePioWrite (&Bme[1], DMA_CCR(0, DMA_CH_7), (BYTE *)&data);
#else
	bmePioWrite (&Bme[1], DMA_CCR(0, DMA_CH_15), (BYTE *)&data);
#endif
	printf ("\nDMA_CCR 0x%08lx", data);

	/* read DMA Channel Control Reg */	
	data = 0;
#ifdef BME_CPE_20
    bmePioRead (&Bme[1], DMA_CCR(0, DMA_CH_7), (BYTE *)&data);
#else
    bmePioRead (&Bme[1], DMA_CCR(0, DMA_CH_15), (BYTE *)&data);
#endif
	printf ("\nDMA_CCR 0x%08lx", data);
	
	return;
}

/****************************************************************************/
/*                                                                          */
/* Function.. : testDMAThruPIO	                              			    */
/*                                                   	                    */
/* Purpose... : function to test DMA programming thru PIO interface			*/
/*																			*/
/* Parameters : None														*/
/*                                                                          */
/* Returns... : N/A                                                         */
/*                                                                          */
/* Notes..... : None                                                        */
/*                                                                          */
/****************************************************************************/

void testDMAThruPIO(int BmeNum)
{
	UINT32 data = 0;
	int iCount = 0;

	HostCpuEndianType = 2;
	Bme[1].BMEbaseAddr = BME_BASE_ADDR;

	printf ("\nTestDMAThruPIO");

	/* program DMA_SAR with HIC_FIFO address */
	data = 0xc7000000;  
	bmePioWrite (&Bme[BmeNum], DMA_SAR(0, DMA_CH_15), (BYTE *)&data);
	
	/* read DMA_SAR reg */
	data = 0;
	bmePioRead (&Bme[BmeNum], DMA_SAR(0, DMA_CH_15), (BYTE *)&data);
	printf ("\nDMA_SAR 0x%08lx", data); 

	/* program DMA_DAR with external memory address */
	data = 0x40000000;  
	bmePioWrite (&Bme[BmeNum], DMA_DAR(0, DMA_CH_15), (BYTE *)&data);

	/* read DMA_DAR reg */	
	data = 0;
	bmePioRead (&Bme[BmeNum], DMA_DAR(0, DMA_CH_15), (BYTE *)&data);
	printf ("\nDMA_DAR 0x%08lx", data);

	/* program DMA_ECR reg */
	data = 0x80000000;  
	bmePioWrite (&Bme[BmeNum], DMA_ECR(0, DMA_CH_15), (BYTE *)&data);
	
	/* read DMA_ECR Reg */
	data = 0;
	bmePioRead (&Bme[BmeNum], DMA_ECR(0, DMA_CH_15), (BYTE *)&data);
	printf ("\nDMA_ECR 0x%08lx", data);

	/* program DMA_CCR reg */
	data = 0x00001800;  
	bmePioWrite (&Bme[BmeNum], DMA_CCR(0, DMA_CH_15), (BYTE *)&data);
	printf ("\nDMA_CCR 0x%08lx", data);

	/* write data to DMA FIFO */
	bmeWrMemory(&Bme[BmeNum], 0x40000000, &BmeResetVecCode[0], BME_RESET_VEC_CODE_SIZE); 
	
	while (1)
	{
		/* read DMA_CCR & poll for DMA_DONE bit being set */
		data = 0;
		bmePioRead (&Bme[BmeNum], DMA_CCR(0, DMA_CH_15), (BYTE *)&data);
		printf ("\nDMA_CCR 0x%08lx", data);
		if ((data & 0x100) == 0x100)
		{
			printf ("\nDMA_DONE");
			/* poll for DW_H status bit to be set in DMA_STATUS_PORT */
			pollStatus(BmeNum);
			break;
		}
		else
		{
			iCount++;
			if (iCount < 0x60)
				continue;
			else
				break;
		}
	}

	return;
}


/****************************************************************************/
/*                                                                          */
/* Function.. : pollStatus                             			            */
/*                                                   	                    */
/* Purpose... : function to poll for DW_H status bit to be set in DMA_		*/
/*				STATUS_PORT													*/
/*																			*/
/* Parameters : None														*/
/*                                                                          */
/* Returns... : N/A                                                         */
/*                                                                          */
/* Notes..... : None                                                        */
/*                                                                          */
/****************************************************************************/

void pollStatus (int BmeNum)
{
	BYTE bDmaStatus = 0;
	int iCount = 0; 
	UINT32 data = 0;

#if NO_STATUS_BIT_SET
	/* if DW_H status is not set, but DMA_DONE bit, clear DMA_DONE bit & read the data */
	clrDMADone ();
	//testDMARead();
#endif
//	printf ("\npollStatus ");
//	testPIORead (BmeNum,0xe003003c);

	while (1)
	{
		/* read DMA_STATUS_PORT */
		bDmaStatus = bmeRdStatus (&Bme[BmeNum]);
		
		/* check if it is DMA_WRITE_DONE interrupt */
		if (bDmaStatus & DW_H_DMA_WRITE_DONE)
		{
//			printf ("\nDMA status : 0x%x success", bDmaStatus);
//			testPIORead (BmeNum,0xe003003c);
//			printf ("\n Clearing Status");
			/* if set, clear the status */
			bmeClrStatus (&Bme[BmeNum], CLR_DW_H_DMA_WRITE_DONE);
			/*testPIORead (0xe003003c);*/

			/* can read DMA here */

			data = 0x00000000;  
#ifdef BME_CPE_20
			bmePioWrite (&Bme[BmeNum], DMA_CCR(0, DMA_CH_7), (BYTE *)&data);
#else
			bmePioWrite (&Bme[BmeNum], DMA_CCR(0, DMA_CH_15), (BYTE *)&data);
#endif
			/*testPIORead (0xe003003c);*/

			break;
		}
		else
		{
			/* if not set, wait for sometime & then poll again */
			iCount++;
			if (iCount < 0x20)
				iposDelay();	
			else
			{
				/* read DMA_CCR reg */
#ifdef BME_CPE_20
			bmePioWrite (&Bme[BmeNum], DMA_CCR(0, DMA_CH_7), (BYTE *)&data);
#else
			bmePioWrite (&Bme[BmeNum], DMA_CCR(0, DMA_CH_15), (BYTE *)&data);
#endif
				printf ("\nAfter DMA fail: DMA_CCR 0x%08lx", data);
				printf ("\nDMA status : 0x%x failure", bDmaStatus);
				break;
			}
		}	

	}

	return;
}

/****************************************************************************/
/*                                                                          */
/* Function.. : testDMAReadThruPIO                     			            */
/*                                                   	                    */
/* Purpose... : function to test DMA read thru PIO interface (4 bytes at a  */
/*				time)														*/
/*																			*/
/* Parameters : None														*/
/*                                                                          */
/* Returns... : N/A                                                         */
/*                                                                          */
/* Notes..... : None                                                        */
/*                                                                          */
/****************************************************************************/

void testDMAReadThruPIO ()
{
	BYTE bRstVec[32];
	int index = 0;

	HostCpuEndianType = 2;
	Bme[1].BMEbaseAddr = BME_BASE_ADDR;

	/* read first 4 bytes of data */
	bmePioRead (&Bme[1], 0x40000000, &bRstVec[0]);
	
	/* read next 4 bytes of data */
	bmePioRead (&Bme[1], 0x40000004, &bRstVec[4]);

	/* read next 4 bytes of data */	
	bmePioRead (&Bme[1], 0x40000008, &bRstVec[8]);
	
	/* read next 4 bytes of data */
	bmePioRead (&Bme[1], 0x4000000c, &bRstVec[12]);
	
	printf ("\nDMA Read Data Thru PIO Read : ");

	for (index = 0; index < 0x10; index++)
	{
		printf ("0x%02x ", bRstVec[index]);
	}

	return;
}

void readStatus(int BmeNum)
{
BYTE bDmaStatus;
	HostCpuEndianType = 2;
	Bme[BmeNum].BMEbaseAddr = BME_BASE_ADDR;

		bDmaStatus = bmeRdStatus (&Bme[BmeNum]);
		printf ("\nDMA status : 0x%x", bDmaStatus);

}

/****************************************************************************/
/*                                                                          */
/* Function.. : testDMARead                            			            */
/*                                                   	                    */
/* Purpose... : function to test DMA read thru DMA FIFO interface			*/
/*																			*/
/* Parameters : None														*/
/*                                                                          */
/* Returns... : N/A                                                         */
/*                                                                          */
/* Notes..... : None                                                        */
/*                                                                          */
/****************************************************************************/

void testDMARead (int BmeNum, UINT32 addr,int size)
{
	int i;
        BYTE bRstVec[300], bDmaStatus = 0;
	int  index = 0, iCount = 0;
	UINT32 data = 0;

	HostCpuEndianType = 2;
	Bme[BmeNum].BMEbaseAddr = BME_BASE_ADDR;

		bDmaStatus = bmeRdStatus (&Bme[BmeNum]);
		printf ("\nDMA status : 0x%x", bDmaStatus);


for (i=0;i<1;i++)
{
	/*printf ("\n %i TestDMARead",i);*/


	Bme[BmeNum].FifoFlag=1;
	bmeTrMemory (&Bme[BmeNum], addr,size);

	/* poll for DMA_DONE bit / DW_H status bit to set */
	bmePioRead (&Bme[BmeNum], DMA_CCR(0, DMA_CH_15), (BYTE *)&data);
	printf ("\nafter bmeTrMemory: DMA_CCR 0x%08lx", data);

/*	if ((data & 0x100) == 0x100)
	{
		printf ("\nDMA_DONE was set. Clear DMA CCR");
		testPIORead (0xe003003c);
	}*/



#if NO_STATUS_BIT_SET
	while (1)
	{
		data = 0;
		bmePioRead (&Bme[BmeNum], DMA_CCR(0, DMA_CH_15), (BYTE *)&data);
		if ((data & 0x100) == 0x100)
		{
			printf ("\nDMA_DONE");
			break;
		}
		else
		{
			iCount++;
			if (iCount < 0x60)
				continue;
			else
			{	bmePioRead (&Bme[BmeNum], DMA_CCR(0, DMA_CH_15), (BYTE *)&data);
				printf ("\nEnd Read Fail: DMA_CCR 0x%08lx", data);
				printf ("\nDMA status : 0x%x", bDmaStatus);
				return;
			}
		}
	}
#endif

	while (1)
	{
		/* poll for DW_H status bit to be set */
		bDmaStatus = bmeRdStatus (&Bme[BmeNum]);
		printf ("\nDMA status : 0x%x", bDmaStatus);
		testPIORead (BmeNum,0xe003003c);


		/* check if it is DMA_WRITE_DONE interrupt */
		if (bDmaStatus & DW_H_DMA_WRITE_DONE)
		{
			testPIORead (BmeNum,0xe003003c);

			Bme[BmeNum].dataLen = size;
			/* read data from HIC_FIFO */
			bmeRdMemory (&Bme[BmeNum], &bRstVec[0]);
			
			printf ("\nClearing status bit");
			bmeClrStatus (&Bme[BmeNum], CLR_DW_H_DMA_WRITE_DONE);
			bmeClrStatus (&Bme[BmeNum], CLR_MSG_RDY_IN_BME_DPRAM);
			printf ("\nDMA status transfer success : 0x%x", bDmaStatus);
		
			data = 0x00000000;  
			bmePioWrite (&Bme[BmeNum], DMA_CCR(0, DMA_CH_15), (BYTE *)&data);
			testPIORead (BmeNum,0xe003003c);

			break;
		}
		else
		{
			iCount++;
			if (iCount < 0x20)
				iposDelay();	
			else
			{
				printf ("\nDMA status : 0x%x failure", bDmaStatus);
				return;
			
			}
			
		}	
	}
	index=0;
	while (index < BME_RESET_VEC_CODE_SIZE)
		{
		if (bRstVec[index]!=BmeResetVecCode[index])
		{ printf ("\nFailed match at index %i, exp byte %x read byte %x",index,BmeResetVecCode[index],bRstVec[index]);
		break;
		}
		index++;
		}
	printf ("\n");
	for (index=0;index<size;index++)
		{
		printf (" 0x%x",bRstVec[index]);
		if (index%16==0) printf ("\n");
		}
} // for loop

printf ("\nDMA Read Done . ");

}


#ifndef _PARALLEL_IO_INTERFACE_
/****************************************************************************/
/*                                                                          */
/* Function.. : tPIO		                           			            */
/*                                                   	                    */
/* Purpose... : function to write data to BME memory mapped interface byte  */
/*				by byte														*/
/*																			*/
/* Parameters : 															*/
/* No		Name		Type				Description						*/
/* --       ----        ----        		-----------						*/
/*	1.		count		int		 			no.of times to write data		*/
/*	2.		addr		BYTE				memory mapped port address (0-b)*/
/*	3.		data		BYTE				data to write					*/
/*                                                                          */
/* Returns... : N/A                                                         */
/*                                                                          */
/* Notes..... : None                                                        */
/*                                                                          */
/****************************************************************************/

void tPIO (int count, BYTE addr, BYTE data)
{

	BYTE *baseAddr;
	int index = 0;

	printf ("\ntestPIO");
	HostCpuEndianType = 2;
 	baseAddr =  (BYTE *)BME_BASE_ADDR;

	printf("\nbase addr %lx", (UINT32) baseAddr);

	for (index =0; index < count; index++) 
	{
		printf ("\nData %x", index);
		/* if data is zero, write index value as data */
		if (!data)
			*(baseAddr+addr) = (BYTE)index; 
		else
			*(baseAddr+addr) = data;
	}

	printf ("\nAddr %x, Data %x", addr, data);

	return;
}

#endif /* _PARALLEL_IO_INTERFACE_ */

/****************************************************************************/
/*                                                                          */
/* Function.. : loopTestPIOWrite                          			        */
/*                                                   	                    */
/* Purpose... : function to write data to BME memory thru PIO interface in a*/
/*				loop														*/
/*																			*/
/* Parameters : 															*/
/* No		Name		Type				Description						*/
/* --       ----        ----        		-----------						*/
/*	1.		addr		unsigned long		BME memory address (ext / int )	*/
/*	2.		data		unsigned long		4 bytes of data to write		*/
/*                                                                          */
/* Returns... : N/A                                                         */
/*                                                                          */
/* Notes..... : 												            */
/*                                                                          */
/****************************************************************************/

void loopPIOWrite (int BmeNum, unsigned long addr, unsigned long data)
{
	HWAPI_RET_VAL retVal;
	int index = 0;
	
	HostCpuEndianType = 2;
	Bme[BmeNum].BMEbaseAddr = BME_BASE_ADDR;	
	
	printf ("\nloopTestPIOWrite");
	
	printf ("\nBme base address %lx", Bme[BmeNum].BMEbaseAddr);

	for (index=0;index<0xFFFFFF;index++)
	{	printf ("\n%i",index);
		retVal = bmePioWrite (&Bme[BmeNum], addr, (BYTE *)&data);
	/*	retVal = bmePioRead_diag (&Bme[1], addr, (BYTE *)&data2);
		if (data!=data2) {
		printf("Data mismatch wr data 0x%08lx rd data 0x%08lx",data,data2); 
		break;}*/
	}

	printf ("\nloopPIOWrite end");

	return;
}

void loopPIOWriteRead (int BmeNum, unsigned long addr, unsigned long data)
{
	HWAPI_RET_VAL retVal;
	int index = 0;
	unsigned long data2=0;
	
	HostCpuEndianType = 2;
	Bme[BmeNum].BMEbaseAddr = BME_BASE_ADDR;	
	
	printf ("\nloopTestPIOWrite");
	
	printf ("\nBme base address %lx", Bme[BmeNum].BMEbaseAddr);

	for (index=0;index<0xFFFFFF;index++)
	{	printf ("\n%i",index);
		retVal = bmePioWrite (&Bme[BmeNum], addr, (BYTE *)&data);
		retVal = bmePioRead (&Bme[BmeNum], addr, (BYTE *)&data2);
		if (data!=data2) {
		printf("Data mismatch wr data 0x%08lx rd data 0x%08lx",data,data2); 
		break;}
	}

	printf ("\nloopPIOWrite end");

	return;
}

/****************************************************************************/
/*                                                                          */
/* Function.. : loopTestPIORead                          			        */
/*                                                   	                    */
/* Purpose... : function to read data from BME memory thru PIO interface in a*/
/*				loop														*/
/*																			*/
/* Parameters : 															*/
/* No		Name		Type				Description						*/
/* --       ----        ----        		-----------						*/
/*	1.		addr		unsigned long		BME memory address (ext / int )	*/
/*                                                                          */
/* Returns... : N/A                                                         */
/*                                                                          */
/* Notes..... : 												            */
/*                                                                          */
/****************************************************************************/

void loopPIORead (int BmeNum, unsigned long addr)
{
	HWAPI_RET_VAL retVal;
	int index = 0;
	UINT32 data = 0;

	HostCpuEndianType = 2;
	Bme[BmeNum].BMEbaseAddr = BME_BASE_ADDR;	
	
	printf ("\nloopTestPIORead");

	printf ("\nBme base address %lx", Bme[BmeNum].BMEbaseAddr);

	for (index = 0; index < 0xFFFFFF; index++) 
	{
		retVal = bmePioRead (&Bme[BmeNum], addr, (BYTE *)&data);
		iposDelay();
	}
	printf("\nRead data 0x%08lx, index %i", data, index);
	printf ("\nloopTestPIORead end");
	
	return;
}

/****************************************************************************/
/**									   **/
/**		Uitility  functions					   **/
/**									   **/
/****************************************************************************/

/****************************************************************************/
/*                                                                          */
/* Function.. : binToByteArray	                         			        */
/*                                                   	                    */
/* Purpose... : function to convert bin file to a byte array				*/
/*																			*/
/* Parameters : None														*/
/*                                                                          */
/* Returns... : N/A                                                         */
/*                                                                          */
/* Notes..... : can't run this function on the fly in shell. b'cos path as  */
/*				as the vxWorks.bin file will not be present in the target   */
/*				so we need to make an executable file for this function		*/ 
/****************************************************************************/

void binToByteArray (void)
{
	unsigned int numread = 0, tot = 0;
	unsigned char tmpChar;
	
	FILE *binFile = NULL;
	FILE *arrayFile = NULL;
	
	binFile = fopen("vxWorks.bin","rb");
	arrayFile = fopen("bmeCode.h","w");
	
	fwrite ("BYTE BMECodeArray[512*1024] = {\n", sizeof(char), 17, arrayFile);
	
	if (binFile)
	{
		while (1)
		{
			/* Attempt to read in 4 characters at a time */
			numread = fread(&tmpChar, sizeof(char), 1, binFile);
			tot += numread;
			
			if (numread <=0) 
			{
				fwrite ("\n};", sizeof (char), 3, arrayFile);
				break;
			}					

			fprintf (arrayFile, "0x%02x, ", tmpChar);

			if (!(tot%16))
				fwrite("\n", sizeof(char), 1, arrayFile);

		}
		fclose(binFile);	
		fclose(arrayFile);
	}
	printf("File total %d %d\n", tot, numread);

	return;	
} 


/****************************************************************************/
/*                                                                          */
/* Function.. : getPLPRCR		                        			        */
/*                                                   	                    */
/* Purpose... : function to read the PLPRCR (PLL, Low Power & Reset Control	*/
/*				Register) reg												*/
/*																			*/
/* Parameters : None														*/
/*                                                                          */
/* Returns... : N/A                                                         */
/*                                                                          */
/* Notes..... : 	                                                        */
/****************************************************************************/

void getPLPRCR (void)
{
	printf ("\nPLPRCR val : %lx", *PLPRCR(immrval));
	return;
}


#ifdef _PARALLEL_IO_INTERFACE_

/****************************************************************************/
/*                                                                          */
/* Function.. : relCS		                        			        	*/
/*                                                   	                    */
/* Purpose... : function to release/deassert the CS* & other control 		*/
/*				signals of the host, in parallel i/o interface, if Rdy 		*/
/*				signal is not being asserted by BME properly				*/
/*																			*/
/* Parameters : None														*/
/*                                                                          */
/* Returns... : N/A                                                         */
/*                                                                          */
/* Notes..... : 	                                                        */
/****************************************************************************/

void relCS (void)
{
	if (bRdEnable)
	{
		/* assert DATA pins, CS* pin */
		bRdDataVal = (BYTE)(*PDDAT( immrVal ) >> 0x03);

		/* printf ("\nRead Data %x", bRdDataVal); */
	
		bRdEnable = 0;
	}

	/* PB21 - OE* - deasserted */
	*PDDAT( immrVal ) |= PD13; /* value 1 */

	/* PB18 - CS* - deasserted - active low */
	*PBDAT( immrVal ) |= (PB18); /* value 1 */

	/* PB20 - R/W* - deasserted - active low */
	*PBDAT( immrVal ) |= PB22; /* value 1 */	

	/* make addr as 0 */
	*PBDAT(immrVal) &= ~(PB14 | PB15 | PB16 | PB17);

	/* make data as 0 */
	*PDDAT(immrVal) &= ~(PD5 | PD6 | PD7 | PD8 | PD9 | PD10 | PD11 | PD12);

	return;
}

/****************************************************************************/
/*                                                                          */
/* Function.. : DOut		                        			        	*/
/*                                                   	                    */
/* Purpose... : function to set the direction of parallel port D pins as	*/
/*				output pins (data pins). Direction of data pins are output 	*/
/*				during write transaction. since the same 8 pins are used for*/
/*				write as well as read transactions, we need to change the	*/
/*				direction of the pins appropriately during each transaction	*/
/*																			*/
/* Parameters : None														*/
/*                                                                          */
/* Returns... : N/A                                                         */
/*                                                                          */
/* Notes..... : 	                                                        */
/****************************************************************************/

void DOut (void)
{
	/* PDDIR - data pin directions */
	*PDDIR(immrVal) |= (PD5 | PD6 | PD7 | PD8 | PD9 | PD10 | PD11 | PD12); /* value 1 */
	return;
}

/****************************************************************************/
/*                                                                          */
/* Function.. : DIn			                        			        	*/
/*                                                   	                    */
/* Purpose... : function to set the direction of parallel port D pins as	*/
/*				input pins (data pins). Direction of data pins are input 	*/
/*				during read transaction. since the same 8 pins are used for	*/
/*				write as well as read transactions, we need to change the	*/
/*				direction of the pins appropriately during each transaction	*/
/*																			*/
/* Parameters : None														*/
/*                                                                          */
/* Returns... : N/A                                                         */
/*                                                                          */
/* Notes..... : 	                                                        */
/****************************************************************************/

void DIn (void)
{
	/* PDDIR - data pin directions */
	*PDDIR(immrVal) &= ~(PD5 | PD6 | PD7 | PD8 | PD9 | PD10 | PD11 | PD12); /* value 0 */
	return;
}

/****************************************************************************/
/*                                                                          */
/* Function.. : cSig			                        			       	*/
/*                                                   	                    */
/* Purpose... : function to set/reset - assert/deassert the value of 		*/
/* 				parallel port B & D pins programmed as control pins 	 	*/
/*				in parallel i/o interface. Assertion/deassertion of signals */
/*				are done in a sequential order, one after the other, as 	*/
/*				& when we get BME_CLK interrupt. Synchronizing assertion/	*/
/*				deassertion of signals with Bme clock.						*/
/*																			*/
/* Parameters : None														*/
/*                                                                          */
/* Returns... : N/A                                                         */
/*                                                                          */
/* Notes..... : 	                                                        */
/****************************************************************************/

void cSig (BYTE bSignal, BYTE bVal)
{
	/* bSignal is set in Bme Clock ISR, whenever we get a Bme clock interrupt */
	switch (bSignal)
	{
		case CS: /* PB18 */
			/* deassert CS* signal */
			if (bVal)
				*PBDAT(immrVal) |= PB18; /* value 1 */
			/* assert CS* signal */
			else
				*PBDAT(immrVal) &= ~(PB18); /* value 0 */
			break;
		
		case OE: /* PD13 */
			/* deassert DS* signal */
			if (bVal)
				*PDDAT(immrVal) |= PD13; /* value 1 */
			/* assert DS* signal */
			else
				*PDDAT(immrVal) &= ~(PD13); /* value 0 */
			break;
		
		case RW: /* PB22 */
			/* deasert R/W* signal */
			if (bVal)
				*PBDAT(immrVal) |= PB22; /* value 1 */
			/* assert R/W* signal */
			else
				*PBDAT(immrVal) &= ~(PB22); /* value 0 */
			break;

		case ADDR: /* PB14 - PB17 */
			/* assert ADDR lines */
			*PBDAT(immrVal) |= (bVal << 0x0e);
			break;

		case DATA: /* PD5 - PD12 */
			/* assert DATA lines */			
			*PDDAT(immrVal) |= (bVal << 0x03);
			break;

		default:
			break;
	}

	return;
}

/****************************************************************************/
/*                                                                          */
/* Function.. : wrLoop			                          			        */
/*                                                   	                    */
/* Purpose... : function to write data to BME memory mapped interface 		*/
/*				(control port 1) byte by byte thru parallel i/o interface 	*/
/*				in a loop													*/
/*																			*/
/* Parameters : None														*/
/*                                                                          */
/* Returns... : N/A                                                         */
/*                                                                          */
/* Notes..... : 												            */
/*                                                                          */
/****************************************************************************/

void wrLoop (void)
{
	int index = 0, count = 0, rdyCount = 0;

	/* deassert all the control signals before starting to write */
	relCS();

	while (1)
	{

		/* write 1 byte of data to control port 1 */
		wrBme(1,0x98+count);	
		count++;

		/* after writing 20 bytes, come out */
		if (count == 0x20)
			break;

		while (1)
		{
			/* if Rdy signal is asserted, continue writing */
			if (RdySig)
				break;
			else
			{
				/* else, poll for Rdy signal assertion for some time */
				rdyCount++;
				if (rdyCount < 0x20)
					iposDelay();
				else
				{
					/* if no Rdy signal, give an error */
					printf ("\nNo ready signal!!!");
					return;
				}
			}
		} /* while */
	} /* while */

	return;
}

/****************************************************************************/
/*                                                                          */
/* Function.. : Rdy 				                          			    */
/*                                                   	                    */
/* Purpose... : asserting the Rdy signal explicitly by setting the flag		*/
/*																			*/
/* Parameters : None														*/
/*                                                                          */
/* Returns... : N/A                                                         */
/*                                                                          */
/* Notes..... : 												            */
/*                                                                          */
/****************************************************************************/

void Rdy (void)
{
	/* set the flag, which will be set in RdyISR, when Rdy signal is asserted */
	RdySig = 1;
	RdRdy();

	return;
}

/****************************************************************************/
/*                                                                          */
/* Function.. : RdRdy 				                          			    */
/*                                                   	                    */
/* Purpose... : reading the Rdy signal flag status							*/
/*																			*/
/* Parameters : None														*/
/*                                                                          */
/* Returns... : N/A                                                         */
/*                                                                          */
/* Notes..... : 												            */
/*                                                                          */
/****************************************************************************/

void RdRdy ()
{
	printf ("\nRdy status %d", RdySig);

	return;
}

#endif /* _PARALLEL_IO_INTERFACE_ */

/****************************************************************************/
/**									   **/
/**		Software download  functions				   **/
/**									   **/
/****************************************************************************/
/****************************************************************************/
/*                                                                          */
/* Function.. : doDnld			                          			        */
/*                                                   	                    */
/* Purpose... : function to download data to BME memory thru DMA FIFO 		*/
/*				interface in chunks of 256									*/
/*																			*/
/* Parameters : 															*/
/* No		Name		Type				Description						*/
/* --       ----        ----        		-----------						*/
/*	1.		cnt			int		BME memory block count (block size - 256 	*/
/*								bytes)from where to stat writing			*/
/*	2.		len			int		block size to write							*/
/*                                                                          */
/* Returns... : N/A                                                         */
/*                                                                          */
/* Notes..... : 												            */
/*                                                                          */
/****************************************************************************/

void doDnld (int cnt, int len)
{
	/* set the BME code size & download address */
	Bme[1].BMECodeSize = len; /* 0x56ecc - 356044 */
	Bme[1].BMECodeDnldAddr = (BME_CODE_DNLD_ADDR + ((cnt - 1) * 256));
	Bme[1].dataPtr = &BMECodeArray[0+((cnt-1)*256)];

	if (bmeSoftwareDnld(&Bme[1]) != HWAPI_DNLD_SUCCESS)
	{ 
		printf ("\nError downloading BME software!");
		return;
	}

	printf ("\nBme software code downloaded successfully");

	return;

}

/****************************************************************************/
/*                                                                          */
/* Function.. : wrDnld			                          			        */
/*                                                   	                    */
/* Purpose... : function to write/download code to BME memory thru DMA FIFO */
/*				interface in a loop											*/
/*																			*/
/* Parameters : 															*/
/* No		Name		Type				Description						*/
/* --       ----        ----        		-----------						*/
/*	1.		cnt			int		number of times to download code		 	*/
/*                                                                          */
/* Returns... : N/A                                                         */
/*                                                                          */
/* Notes..... : 												            */
/*                                                                          */
/****************************************************************************/

void wrDnld (int BmeNum,int cnt)
{
	int index = 0;

	HostCpuEndianType = 2;
	Bme[BmeNum].BMEbaseAddr = BME_BASE_ADDR;

	printf ("\nWrite Download");

	for (index=0;index<cnt;index++)
	{
	
		Bme[BmeNum].BmeState = INACTIVE;
		printf ("\nStart Download, cnt %i",index);

		bmeDnldProcedure (&Bme[BmeNum]);	
		
		printf ("\n************************************");
		printf ("\nDownload completed!, cnt %i",index);
		printf ("\n************************************\n");

	}

	return;
}

/****************************************************************************/
/*                                                                          */
/* Function.. : rdDnld			                          			        */
/*                                                   	                    */
/* Purpose... : function to read the downloaded code from BME memory thru 	*/
/*				DMA FIFO interface											*/
/*																			*/
/* Parameters : 															*/
/* No		Name		Type				Description						*/
/* --       ----        ----        		-----------						*/
/*	1.		cnt			int		BME memory block count (block size - 256 	*/
/*								bytes)to read								*/
/*	2.		len			int		block size to read 							*/
/*                                                                          */
/* Returns... : N/A                                                         */
/*                                                                          */
/* Notes..... : 												            */
/*                                                                          */
/****************************************************************************/

void rdDnld (int cnt, int len)
{


	HostCpuEndianType = 2;
	Bme[1].BMEbaseAddr = BME_BASE_ADDR;

	printf ("\nRead Download Code");

	/* set the BME code size & download address */
	Bme[1].BMECodeSize = len; /* 0x56ecc - 356044 */
	Bme[1].BMECodeDnldAddr = (BME_CODE_DNLD_ADDR + ((cnt - 1) * 256));

	/* verify code check sum */	
	if (bmeVerifyCodeDnld(&Bme[1]) != HWAPI_CODE_CHKSUM_SUCCESS)
	{
		printf("\nError verifying code download!");
		return;
	}

	printf ("\nBme software code verified successfully");
	
	return;
}

/****************************************************************************/
/**									   **/
/**		Register utility functions					   **/
/**									   **/
/****************************************************************************/

/****************************************************************************/
/*                                                                          */
/* Function.. : get_br_or_reg_vals         		     		        		*/
/*                                                   	                    */
/* Purpose... : function to read BR & OR reg vals of a specific chip select	*/
/*																			*/
/* Parameters : 	 														*/
/* No		Name		Type		Description								*/
/* --		----		----		-----------								*/
/*	1.		regNum		char		chip select number						*/
/*                                                                          */
/* Returns... : N/A                                                         */
/*                                                                          */
/* Notes..... : 														    */
/****************************************************************************/

void get_or (char regNum)
{
	unsigned long brRegVal;
	unsigned long orRegVal;

	brRegVal = *(unsigned long *)((0xFF000000) + 0x100 + (0x8 * regNum));
	orRegVal = *(unsigned long *)((0xFF000000) + 0x104 + (0x8 * regNum));
	
	printf("\nBR%d 0x%lx, OR%d 0x%lx", regNum, brRegVal, regNum, orRegVal);
	
	return;			
	
}

/****************************************************************************/
/*                                                                          */
/* Function.. : get_siu_reg_vals                         			        */
/*                                                   	                    */
/* Purpose... : function to read the interrupt related SIU regs				*/
/*																			*/
/* Parameters : None														*/
/*                                                                          */
/* Returns... : N/A                                                         */
/*                                                                          */
/* Notes..... : 	                                                        */
/****************************************************************************/

void get_int (void)
{
	unsigned long immrVal = 0xff000000;
	unsigned long sipend, simask, siel, sivec;

	sipend = *(unsigned long *)((immrVal & 0xFFFF0000) + 0x010);
	simask = *(unsigned long *)((immrVal & 0xFFFF0000) + 0x014);
	siel = *(unsigned long *)((immrVal & 0xFFFF0000) + 0x018);
	sivec = *(unsigned long *)((immrVal & 0xFFFF0000) + 0x01c);	

	printf ("\nsipend 0x%08lx", sipend);
	printf ("\nsimask 0x%08lx", simask);
	printf ("\nsiel   0x%08lx", siel);
	printf ("\nsivec  0x%08lx", sivec);

	return;
}



/****************************************************************************/
/*                                                                          */
/* Function.. : get_br_or_all_reg_vals         		     		        	*/
/*                                                   	                    */
/* Purpose... : function to read BR & OR reg vals of all chip selects (0-6)	*/
/*																			*/
/* Parameters : None 														*/
/*                                                                          */
/* Returns... : N/A                                                         */
/*                                                                          */
/* Notes..... : 														    */
/****************************************************************************/

void get_or_all (void)
{
	char index = 0;
	
	for (index = 0; index < 8; index++)
		get_or (index);

	return;
}

/****************************************************************************/
/*                                                                          */
/* Function.. : WrRdDram	                   		     		        	*/
/*                                                   	                    */
/* Purpose... : function to write & read one byte of data from Dram	    */
/*																			*/
/* Parameters : None 							    */
/*                                                                          */
/* Returns... : N/A                                                         */
/*                                                                          */
/* Notes..... : To capture the memory bus behaviour for Dram memory	    */
/****************************************************************************/

void WrRdDram ()
{
	*(BYTE *)0x0 = 0xbb;
	printf ("\nDram addr 0x0 data 0x%x", *(BYTE *)0x0);
	
	return;
}

/****************************************************************************/
/*                                                                          */
/* Function.. : WrRdSram	                   		     		        	*/
/*                                                   	                    */
/* Purpose... : function to write & read one byte of data from Sram			*/
/*																			*/
/* Parameters : None 														*/
/*                                                                          */
/* Returns... : N/A                                                         */
/*                                                                          */
/* Notes..... : To capture the memory bus behaviour for Sram memory	        */
/****************************************************************************/

void WrRdSram ()
{
	*(BYTE *)0x04000000 = 0xaa;
	printf ("\nSram addr 0x04000000 Data 0x%x", *(BYTE *)0x04000000);

	return;
}

/****************************************************************************/
/*                                                                          */
/* Function.. : WrRdLed		                   		     		        	*/
/*                                                   	                    */
/* Purpose... : function to write & read one byte of data from LED			*/
/*																			*/
/* Parameters : None 														*/
/*                                                                          */
/* Returns... : N/A                                                         */
/*                                                                          */
/* Notes..... : To capture the memory bus behaviour for LED memory        	*/
/****************************************************************************/

void WrRdLed ()
{
	*(BYTE *)0x10000000 = 0xcc;
	printf ("\nLed addr 0x10000000 Data 0x%x", *(BYTE *)0x10000000);
	return;
}

/****************************************************************************/
/*                                                                          */
/* Function.. : RdFlash		                   		     		        	*/
/*                                                   	                    */
/* Purpose... : function to read one byte of data from Flash				*/
/*																			*/
/* Parameters : None														*/
/*                                                                          */
/* Returns... : N/A                                                         */
/*                                                                          */
/* Notes..... : To capture the memory bus behaviour for Flash memory        */
/****************************************************************************/

void RdFlash ()
{
	printf ("\nFlash addr 0xfff00000 Data 0x%x", *(BYTE *)0xfff00000);
	return;
}

/****************************************************************************/
/*                                                                          */
/* Function.. : tWr		                   		     			        	*/
/*                                                   	                    */
/* Purpose... : function to write data to BME memory thru PIO interface		*/
/*																			*/
/* Parameters : 															*/
/* No		Name		Type				Description						*/
/* --       ----        ----        		-----------						*/
/*	1.		addr		unsigned long		BME memory address (ext / int )	*/
/*	2.		data		unsigned long		4 bytes of data to write		*/
/*                                                                          */
/* Returns... : N/A                                                         */
/*                                                                          */
/* Notes..... : 	                                                        */
/****************************************************************************/

void tWr (unsigned long addr, unsigned long data)
{
	
	
	HostCpuEndianType = 2;
	Bme[1].BMEbaseAddr = BME_BASE_ADDR;	
	
	printf ("\nBme base address %lx", Bme[1].BMEbaseAddr);

	/* program DMA_ECR15 - Event Control Register */
	/* sw DMA request */
	bmePioWrite (&Bme[1], addr, (BYTE *)&data);
	
	printf ("\nWrite data 0x%08lx dest: 0x%08lx", data,addr);	
		
	return;
}

/****************************************************************************/
/*                                                                          */
/* Function.. : tRd		                   		     			        	*/
/*                                                   	                    */
/* Purpose... : function to read data from BME memory thru PIO interface	*/
/*																			*/
/* Parameters : 															*/
/* No		Name		Type				Description						*/
/* --       ----        ----        		-----------						*/
/*	1.		addr		unsigned long		BME memory address (ext / int )	*/
/*                                                                          */
/* Returns... : N/A                                                         */
/*                                                                          */
/* Notes..... : 	                                                        */
/****************************************************************************/

void tRd (unsigned long addr)
{
	HWAPI_RET_VAL retVal;
	UINT32 data = 0;	

	HostCpuEndianType = 2;
	Bme[1].BMEbaseAddr = BME_BASE_ADDR;	

	printf ("\ntestPIORead");	

	printf ("\nBme base address %lx", Bme[1].BMEbaseAddr);
		
	retVal = bmePioRead (&Bme[1], addr, (BYTE *)&data);
	printf("\nRead data 0x%08lx, dest 0x%08lx\n", data, addr);	
	
	return;
}

/****************************************************************************/
/*                                                                          */
/* Function.. : getSYPCR	               		     			        	*/
/*                                                   	                    */
/* Purpose... : function to read SYPCR (SYstem Protection Control Reg)		*/
/*																			*/
/* Parameters : None														*/
/*                                                                          */
/* Returns... : N/A                                                         */
/*                                                                          */
/* Notes..... : 	                                                        */
/****************************************************************************/

void getSYPCR (void)
{
	printf ("\nSYPCR val : %lx", *SYPCR(immrval));	

	return;
}

/****************************************************************************/
/*                                                                          */
/* Function.. : sSYPCR	                   		     			        	*/
/*                                                   	                    */
/* Purpose... : function to set SYPCR (SYstem Protection Control Reg)		*/
/*																			*/
/* Parameters : None														*/
/*                                                                          */
/* Returns... : N/A                                                         */
/*                                                                          */
/* Notes..... : 	                                                        */
/****************************************************************************/

void sSYPCR (void)
{
	*SYPCR(immrval) &= ~(SYPCR_BME);
	printf ("\nSYPCR val : %lx", *SYPCR(immrval));	

	return;
}

/****************************************************************************/
/*                                                                          */
/* Function.. : getMPTPR	                        			        	*/
/*                                                   	                    */
/* Purpose... : function to read MPTPR (Memory Periodic Timer Prescaler Reg)*/
/*																			*/
/* Parameters : None														*/
/*                                                                          */
/* Returns... : N/A                                                         */
/*                                                                          */
/* Notes..... : 	                                                        */
/****************************************************************************/

void getMPTPR (void)
{
	printf ("\nMPTPR val : %lx", (UINT32) *MPTPR(immrval));	

	return;
}

/****************************************************************************/
/*                                                                          */
/* Function.. : setMPTPR	                        			        	*/
/*                                                   	                    */
/* Purpose... : function to set MPTPR (Memory Periodic Timer Prescaler Reg)	*/
/*																			*/
/* Parameters : None														*/
/*                                                                          */
/* Returns... : N/A                                                         */
/*                                                                          */
/* Notes..... : 	                                                        */
/****************************************************************************/

void setMPTPR (void)
{
	*MPTPR(immrval) = 0x100;
	printf ("\nMPTPR val : %lx", (UINT32) *MPTPR(immrval));

	return;	
}

/*************************************************************************
	Function: InitBmeStruct
	
	Description: Initializes parameter in the BME structure
	
	Return: None
************************************************************************/
void InitBmeStruct(tBmeStruct *pBme, int BmeNum)
	{
	int PortNum;

	/* Initialize Bme state to Inactive state */
	pBme->BmeState = INACTIVE;

	/* Initialize Bme Download Verification State to DW_T_BIT_UNKNOWN_STATE */
	pBme->BmeDnldVerifyState = DW_T_BIT_UNKNOWN_STATE;


	pBme->BmeNum=BmeNum;
	
	/* Initialize all port parms to zero */
	for (PortNum=0;PortNum< IPOS_MAX_PORT_PER_BME ;PortNum++)
	{
		InitPortParms(pBme,PortNum);
	};

	/*InitEMIParms (pBme);*/

	/* dummy data */
		pBme->BMEbaseAddr = BME_BASE_ADDR;
		pBme->srcAddr=DPRAM_BASE_ADDR;	/* =1 Source address on BME DPRAM */
		pBme->destAddr=DPRAM_BASE_ADDR;	/* =1 Destination address on BME DPRAM */
		pBme->dpramBaseRxAddr=DPRAM_RX_BASE_ADDR;
		pBme->dpramBaseTxAddr=DPRAM_TX_BASE_ADDR;
		pBme->BMEResetLineAddr=0xde;
		pBme->BMECodeDnldAddr=BME_CODE_DNLD_ADDR; /* 0x40010000 addr in BME - SRAM */
		pBme->BMECodeSize=BME_CODE_SIZE;

		/* Data pointer points to Bme message buffer. Can 
		alternately point to BME software aray*/
		pBme->dataPtr=&(pBme->BmeMsg[0]);
 
	/* BEGIN: TEST CODE */
		pBme->BmeMsg[_BmeMsgSRC_]	=0x01;
		pBme->BmeMsg[_BmeMsgDEST_]	=0x01;
		pBme->BmeMsg[_BmeMsgOPCODE_]=0x01;
		pBme->BmeMsg[_BmeMsgACK_]	=0x01;
		pBme->BmeMsg[_BmeMsgCTAG_]	=0x01;
		pBme->BmeMsg[_BmeDataLENGTH_]=0;
	
		pBme->dataLen=6;

	/* END: TEST CODE */

/*	pBme->pBmeIntrFcn=&NotifyHost;*/

	} /* InitBmeStruct */



/**********************************************************/
/*  Host API Wrappers                                     */
/**********************************************************/
void pio_read (UINT32 srcAddr, UINT32 *data)
{

	HWAPI_RET_VAL retVal;	

	HostCpuEndianType = 2;
	Bme[1].BMEbaseAddr = BME_BASE_ADDR;	

/*	printf ("\ntestPIORead");	
*/
	/* PIO read from DMA_SAR reg */		
	retVal = bmePioRead (&Bme[1], srcAddr, (BYTE *)data);
/*	printf("\nRead data 0x%08lx, src 0x%08lx\n", *data,srcAddr);	
	*/


}

void pio_write (UINT32 destAddr, UINT32 data)
{

	HostCpuEndianType = 2;
	Bme[1].BMEbaseAddr = BME_BASE_ADDR;	

	/* sw DMA request */
	bmePioWrite (&Bme[1],(unsigned long) destAddr, (BYTE *)&data);
	
	/*printf ("\nWrite data 0x%08lx dest: 0x%08lx", data,destAddr);			*/

}



void doDmaWrite(UINT32 destAddr, BYTE *dataPtr, UINT32 dataLen, int destFifoFlag)
{
	UINT32 data=0;
	HostCpuEndianType = 2;
	Bme[1].BMEbaseAddr = BME_BASE_ADDR;
	Bme[1].BmeNum=1;

//	printf ("\n\nDMA Write dataLen %i. First val 0x%x",(int)dataLen, *dataPtr);
//	printf ("\ndestAddr 0x%08lx",destAddr);

	/* Initialize DMA channel 15 */
	InitDma(1); 

	/* test DMA write */
	Bme[1].FifoFlag=destFifoFlag;

	/* write to external memory */
	bmeWrMemory (&Bme[1], destAddr,dataPtr, dataLen);
#ifdef BME_CPE_20
	bmePioRead (&Bme[1], DMA_CCR(0, DMA_CH_7), (BYTE *)&data);
#else
	bmePioRead (&Bme[1], DMA_CCR(0, DMA_CH_15), (BYTE *)&data);
#endif
//	printf ("\nDMA_CCR 0x%08lx", data);

	/* poll for DMA_DONE bit / DW_H status bit to be set */

	pollStatus(1);

}
 
#define MAX_DMA_SIZE 256

void doDmaRead_diag (UINT32 srcAddr, UINT32 codeLen, BYTE * BmeCodeArrayPtr, int destFifoFlag)
{
	BYTE bDmaStatus = 0;
	int iCount = 0;
	UINT32 data = 0;

	HostCpuEndianType = 2;
	Bme[1].BMEbaseAddr = BME_BASE_ADDR;
	Bme[1].BmeNum=1;

	Bme[1].FifoFlag=destFifoFlag;

	/* initiate data transfer from memory to HIC_FIFO */
	bmeTrMemory (&Bme[1], srcAddr,codeLen);

	/* poll for DMA_DONE bit / DW_H status bit to set */
#ifdef BME_CPE_20
    bmePioRead (&Bme[1], DMA_CCR(0, DMA_CH_7), (BYTE *)&data);
#else
    bmePioRead (&Bme[1], DMA_CCR(0, DMA_CH_15), (BYTE *)&data);
#endif
	while (1)
	{
		/* poll for DW_H status bit to be set */
		bDmaStatus = bmeRdStatus (&Bme[1]);
        iposDelay();

		/* check if it is DMA_WRITE_DONE interrupt */
		if (bDmaStatus & DW_H_DMA_WRITE_DONE)
		{
			Bme[1].dataLen = codeLen;
			/* read data from HIC_FIFO */
			bmeRdMemory (&Bme[1], BmeCodeArrayPtr);
			break;
		}
		else
		{
			if (iCount < 0x20)
			{
				iCount++;
				iposDelay();	
			}
			else
			{
				printf ("\nDMA status : 0x%x failure", bDmaStatus);
				break;

			
			}
			
		}	
	}
}


HWAPI_RET_VAL bmePioWrite_diag (tBmeStruct *bmeStruct, UINT32 destAddr, BYTE *dataPtr)
{
	BYTE *baseAddr;
	BYTE tempVal, index;

#if defined(BME_CPE_20)
	/* get the base address of the BME chip */
	baseAddr = (BYTE *)BME_BASE_ADDR;
#else
	baseAddr = (BYTE *)bmeStruct->BMEbaseAddr;
#endif

  if (!semDiagHic)
    semDiagHic = iposSemCreate (); //    semBCreate(SEM_Q_FIFO,SEM_FULL);

	if(iposSemTake(semDiagHic, WAIT_FOREVER) == OK)
  {
//    printf("-W-");

	  /* set the PIO addr Port with the destination address to transfer data to. */
	  for (index = 0; index < MAX_ADDR_LINES; index++) 
	  {
		  tempVal = (BYTE)((destAddr & (0xff000000 >> (index * 8))) >> ((MAX_ADDR_LINES - (index + 1)) * 8));
		  writeControlPort_diag (baseAddr, (PIO_ADDR_PORT), tempVal);
	  }

	  /* write the data from dataPtr to PIO data port. */
	  for (index = 0; index < MAX_ADDR_LINES; index++)
	  {
		  writeControlPort_diag (baseAddr, (PIO_DATA_PORT), *(dataPtr+index));
	  }
  }
	/* set the Command Port to PIO write register command. */
	writeControlPort_diag (baseAddr, (COMMAND_PORT), PIO_WRITE_REG_CMD);
  
  // Release Semaphore
  iposSemGive(semDiagHic);
		
	return (HWAPI_PIO_WRITE_SUCCESS);
}

/************************************************************************************/
HWAPI_RET_VAL bmePioRead_diag (tBmeStruct *bmeStruct, UINT32 srcAddr, BYTE *dataPtr)
{
	BYTE *baseAddr;
	BYTE tempVal, index;

#if defined(BME_CPE_20)
	/* get the base address of the BME chip */
	baseAddr = (BYTE *)BME_BASE_ADDR;
#else
	baseAddr = (BYTE *)bmeStruct->BMEbaseAddr;
#endif

  if (!semDiagHic)
    semDiagHic = iposSemCreate(); //(SEM_Q_FIFO,SEM_FULL);

	if(iposSemTake(semDiagHic, WAIT_FOREVER) == OK)
  {
//    printf("-R-");

	  /* set the PIO addr Port with the source address to transfer data from. */
	  for (index = 0; index < MAX_ADDR_LINES; index++)
	  {
		  tempVal = (BYTE)((srcAddr & (0xff000000 >> (index * 8))) >> ((MAX_ADDR_LINES - (index + 1)) * 8));
		  writeControlPort_diag (baseAddr, (PIO_ADDR_PORT), tempVal);
	  }

	  /* set the Command Port to PIO read register command.
	  The read data will be placed in PIO data port. */
	  writeControlPort_diag (baseAddr, (COMMAND_PORT), PIO_READ_REG_CMD);
	  /* Read the data from PIO data port and put it in dataPtr being passed. */
	  for (index = 0; index < MAX_ADDR_LINES; index++)
	  {
#ifndef _BME_TEST_CODE_
		  readControlPort_diag (baseAddr, (PIO_DATA_PORT), *(dataPtr+index));
#else /* _BME_TEST_CODE_ */
		  readControlPort_diag (baseAddr, (PIO_DATA_PORT), (dataPtr+index));
#endif /* _BME_TEST_CODE_ */

#ifdef _PARALLEL_IO_INTERFACE_
		  *(dataPtr+index) = bRdDataVal;
		  bRdDataVal = 0x0;
#endif /* _PARALLEL_IO_INTERFACE_ */
	  }
  }
  // Release Semaphore
  iposSemGive(semDiagHic);

	return (HWAPI_PIO_READ_SUCCESS);
}


void testDoDmaWrite()
{
doDmaWrite (0x40000000,&BmeResetVecCode[0], BME_RESET_VEC_CODE_SIZE,1);
}

void testDoDmaRead()
{
BYTE bRstVec[32];
 doDmaRead_diag (0x40000000, BME_RESET_VEC_CODE_SIZE, (char *)&bRstVec[0], 1);
}

/**************************************************/
/*   Single host control port test functions       */
/**************************************************/
void wpa(int BmeNum,BYTE data)
{
BYTE *baseAddr;

Bme[BmeNum].BMEbaseAddr=BME_BASE_ADDR;
baseAddr = (BYTE *)Bme[BmeNum].BMEbaseAddr;
writeControlPort(baseAddr, (PIO_ADDR_PORT|((BmeNum-1)<<4)), data);

}

void wpc(int BmeNum, BYTE data)
{
BYTE *baseAddr;

Bme[BmeNum].BMEbaseAddr=BME_BASE_ADDR;
baseAddr = (BYTE *)Bme[BmeNum].BMEbaseAddr;
writeControlPort(baseAddr, (COMMAND_PORT|((BmeNum-1)<<4)), data);

}

void wpd(int BmeNum, BYTE data)     
{
BYTE *baseAddr;

Bme[BmeNum].BMEbaseAddr=BME_BASE_ADDR;
baseAddr = (BYTE *)Bme[BmeNum].BMEbaseAddr;
writeControlPort(baseAddr,(PIO_DATA_PORT|((BmeNum-1)<<4)), data);

}

void wpg(int BmeNum,BYTE addr,BYTE data)
{
BYTE *baseAddr;

Bme[BmeNum].BMEbaseAddr=BME_BASE_ADDR;
baseAddr = (BYTE *)Bme[BmeNum].BMEbaseAddr;
writeControlPort(baseAddr,(addr|((BmeNum-1)<<4)), data);

}

void loopwpg(int BmeNum,BYTE addr,BYTE data)
{
BYTE i;
for (i=0;i<0xFFFFF;i++) {printf ("%i\r",i); wpg(BmeNum,addr,data);}
}



void rp(int BmeNum)
{

BYTE data;
BYTE *baseAddr;

Bme[BmeNum].BMEbaseAddr=BME_BASE_ADDR;
baseAddr = (BYTE *)Bme[BmeNum].BMEbaseAddr;

readControlPort (baseAddr,(0x07/*PIO_DATA_PORT*/|(BmeNum-1)),data);

printf ("%x\n",data);

}

void rpg(int BmeNum,BYTE addr)
{

BYTE data;
BYTE *baseAddr;


Bme[BmeNum].BMEbaseAddr=BME_BASE_ADDR;
baseAddr = (BYTE *)Bme[BmeNum].BMEbaseAddr;

readControlPort (baseAddr,(addr|(BmeNum-1)),data);
printf (" %x\n",data);

}

void looprpg(int BmeNum, BYTE addr,BYTE data)
{
BYTE i;
for (i=0;i<0xFFFFF;i++) {printf ("%i\r",i); rpg(BmeNum,addr);}
}

/**************************************************/
/*   File access test functions                   */
/**************************************************/

void new () 
{
FILE *pFile;
pFile=NULL;

pFile = fopen ("/tgtsvr/testfile","w");
if (pFile!=NULL)
    {
    fprintf (pFile,"hello world");
    fclose (pFile);
    }
else 
    printf ("failed open");

}


#define FLASH_VERSION_STR "Flash Image Version "

int calCS (int address, int length)
{
	int xsum = 0;              
	int i;

	for (i = 0;i < length;i++)
	{
		xsum += ( * ((volatile char *)(address+i)));
	}

	return xsum;
}

void lfts (char cs) 
{
FILE *pFile;
int i,j=0,*buf;
UINT32 data = 0;
char line[8], ver[40];	
#if (!cs)
    strcpy (ver ,FLASH_VERSION_STR);
    printf("Enter verion number (Max. 8 charactors):");
    scanf ("%s",line);
    memcpy (&ver[0]+20, &line[0], 8);
#endif
    printf("\r\nStarting copying......");

    pFile = fopen ("/tgtsvr/flashfile.bin","w");
    if (pFile!=NULL)
    {
	    buf = (int *)&tmpBuf[0];
	    for (i = 0x80000000;i < 0x80200000;i+=4)
	    {
		    data = testPIORead_diag (1, i);
		    buf [j++] = data;
	    }
	    fwrite(buf, sizeof(int), 0x200000/4, pFile);
    }
    else printf ("\r\nfailed open a file.");
    fclose (pFile);
#if (!cs)
    pFile = fopen ("/tgtsvr/flashver","w");
    if (pFile!=NULL)
    {
        buf = (int *)&ver[0];
        buf[7] = 0;
        buf[8] = calCS((int)&tmpBuf[0], 0x200000);
        buf[9] = 0x200000;
	    fwrite(buf, sizeof(int), 10, pFile);
    }
    else printf ("\r\nfailed open a file.");
    printf ("\r\nDone.");
    fclose (pFile);
#endif
}

void lftftp (int len, char *hostName, char *fileName) 
{
int i,j=0,*buf;
UINT32 data = 0;
    printf("\r\nStarting copying file...");

    buf = (int *)&tmpBuf[0];
    for (i = 0x80000000;i < 0x80200000;i+=4)
    {
        data = testPIORead_diag (1, i);
        buf [j++] = data;
    }
    remoteUpLoadImage(len, hostName, fileName);
}

void ClearMem(int BmeNum)
{
unsigned long addr;

addr=0x40000000;
while (addr<0x40200000){
testPIOWrite (BmeNum,addr,0x0);
addr+=4;
}
printf ("\ndone memory clear addr 0x%08lx\n",addr);
}

/* Multi-BME access test functions */
void piow (int BmeNum,unsigned long addr,unsigned long data)
{
	HostCpuEndianType = 2;
	Bme[BmeNum].BMEbaseAddr = BME_BASE_ADDR;	
	
	bmePioWrite (&Bme[BmeNum], addr, (BYTE *)&data);
}


void pior (int BmeNum, unsigned long addr)
{
	HWAPI_RET_VAL retVal;
	UINT32 data = 0;	
	HostCpuEndianType = 2;
	Bme[BmeNum].BMEbaseAddr = BME_BASE_ADDR;	

	/* PIO read from DMA_SAR reg */		
	retVal = bmePioRead (&Bme[BmeNum],  addr, (BYTE *)&data);
	printf("\nRead data 0x%08lx, dest 0x%08lx\n",data,addr);	
}

void dmaw (int BmeNum,int flag)
{
testDMA (BmeNum,flag);


}

void dmar (int BmeNum)
{
	HostCpuEndianType = 2; /* big endian format */
	Bme[BmeNum].BMEbaseAddr = BME_BASE_ADDR; /* memory mapped BME interface base address */

	InitDmaChannel15(&Bme[BmeNum]);



}

void write_to_file(
                        BYTE *list_of_bytes,
                        int list_length,
                        char *filename
                        ) {
FILE *filehandle;
int count;
char s[100];

/*open the file and set it up*/
strcpy(s,"/tgtsvr/");

filehandle = fopen(strcat(s,filename),"w");

if(filehandle==NULL)  {
        printf ("\nFailed to open file for write\n");
        printf ("\n ### Relaunch shell. Do Not Reset Host CPU \n");
        exit (0);
}

for(count=0; count< list_length; count++){
 fprintf(filehandle, "%x\n", *(list_of_bytes + count));
}

fclose(filehandle);
}


/* END_OF_FILE */