/******************************************************************************
 
   Copyright (C), 2013, Texas Instrument.
 
  ******************************************************************************
   File Name	 : I2C_loopback_test.c
   Version		 : Initial Draft
   Author		 : Brighton Feng
   Created		 : August 14, 2013
   Last Modified : 
   Description	 : I2C loopback test on Keystone
   History		 :
   1.Date		 : August 14, 2013
   Author 	 	 : Brighton Feng
   Modification: Created file
 
 ******************************************************************************/
#include "K2_common.h"
#include "K2_I2C_init_drv.h"
#include "I2C_loopback_test.h"

Uint8 i2cRxBuf[I2C_LOOP_TEST_BUF_SIZE];
Uint8 i2cTxBuf[I2C_LOOP_TEST_BUF_SIZE];

int I2C_loopback_test_one_time(Uint32 i2cNum, Uint8 dataPattern)
{
	int i, iByteSuccess;
	Uint32 startCCNT, cycles, throughput;
	
	for(i=0; i<I2C_LOOP_TEST_BUF_SIZE; i++)
	{
		i2cTxBuf[i]= dataPattern;
		i2cRxBuf[i]= ~dataPattern;
	}

	startCCNT= CP15_read_CCNT();
	iByteSuccess= K2_I2C_loopback(i2cNum, 0x55, I2C_LOOP_TEST_BUF_SIZE, 
		i2cTxBuf, i2cRxBuf);
	cycles= CCNT_count_cycle_from(startCCNT);

	if(iByteSuccess!=I2C_LOOP_TEST_BUF_SIZE)
	{
		printf("I2C %d loopback test failed. TX %d bytes, RX %d bytes!\n",
			i2cNum, I2C_LOOP_TEST_BUF_SIZE, iByteSuccess);
		return iByteSuccess;
	}
		
	for(i=0; i<I2C_LOOP_TEST_BUF_SIZE; i++)
	{
		if(i2cTxBuf[i]!=i2cRxBuf[i])
		{
			printf("I2C %d loopback test failed at word %d: TX 0x%x, RX 0x%x\n",
				i2cNum, i, i2cTxBuf[i], i2cRxBuf[i]);
			return i;
		}
	}

    throughput = (unsigned long long)I2C_LOOP_TEST_BUF_SIZE*8*gMain_Core_Speed_Hz/
    	((unsigned long long)cycles*1000);

	printf("I2C %d loopback test passed with data pattern 0x%x. Throughput= %dKbps\n",
		i2cNum, dataPattern, throughput);
		
	return I2C_LOOP_TEST_BUF_SIZE;
}


void I2C_loopback_test(Uint32 i2cNum)
{
	K2_I2C_Master_Init(i2cNum, 400);

	I2C_loopback_test_one_time(i2cNum, 0);
	I2C_loopback_test_one_time(i2cNum, 0xFF);
	I2C_loopback_test_one_time(i2cNum, 0x55);
}

