/*******************************************************************************
** Document: FW_mainbus_api.c
** Copyright (c) 2004 R&D Center, Tailyn Communication Company, Ltd.  
** Created by: Alfred
** Date: Dec. 24, 2004
** Description: Main bus Firmware interface API.(Support all bus, except Host SDRAM)
** Version: 0.1
*******************************************************************************/
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>

#include <FW_mainbus/FW_mainbus_api.h>

#include <umap_type.h>

UMAP_S32 FW_ReadMainBus(UMAP_U32 addr, UMAP_U32 size, void *data)
{
	UMAP_S32 host_bus_file;
	UMAP_U32 result;
	
	host_bus_file = open(MAINBUS_DEVICE_FILE_NAME, O_RDONLY);
	if(host_bus_file < 0)
	{
		result = host_bus_file;
		return result; // open fail!!
	}

	result = lseek(host_bus_file, addr, SEEK_SET);
	if(result != addr)
	{	
		close(host_bus_file);
		return result; // lseek fail!!
	}
	
	result = read(host_bus_file, data, size);
	if(result < 0)
	{	
		close(host_bus_file);
		return result; // read fail!!
	}
	
	close(host_bus_file);
		
	return 0; // succeed
}


UMAP_S32 FW_WriteMainBus(UMAP_U32 addr, UMAP_U32 size, void *data)
{
	UMAP_S32 host_bus_file;
	UMAP_U32 result;
	
	host_bus_file = open(MAINBUS_DEVICE_FILE_NAME, O_WRONLY);
	if(host_bus_file < 0)
	{
		result = host_bus_file;
		return result; // open fail!!
	}
	
	result = lseek(host_bus_file, addr, SEEK_SET);
	if(result != addr)
	{	
		close(host_bus_file);
		return result; // lseek fail!!
	}
	
	result = write(host_bus_file, data, size);
	if(result < 0)
	{	
		close(host_bus_file);
		return result; // read fail!!
	}
	
	close(host_bus_file);
	
	return 0; // succeed
}

UMAP_S32 FW_MipsReset(void)
{
	int rc;
	unsigned int value;
	
	rc = FW_ReadMainBus(0x1f010c40, 4, &value);
	if(rc) return rc;
	value &= 0xff000000;
	rc = FW_WriteMainBus(0x1f010c40, 4, &value);
	if(rc) return rc;
	
	return 0;
}
