#include "PalmType.h"
#include "p_util.h"

void SdramWriteData(USHORT iIndex, UCHAR iLen)
{
	X_VAL(Sdram_pDataCache, SDRAM_DATA_LENGTH) = iLen;
	SdramWrite(P_HIBYTE(iIndex), (UCHAR)iIndex, SRAM_DMA_HALF_DWORD);
}

void SdramReadAll(USHORT iIndex)
{
	SdramRead(P_HIBYTE(iIndex), (UCHAR)iIndex, SRAM_DMA_DWORD);
}

void SdramWriteAll(USHORT iIndex)
{
	SdramWrite(P_HIBYTE(iIndex), (UCHAR)iIndex, SRAM_DMA_DWORD);
}

void SdramReadOptions()
{
	SdramReadAll(OPTIONS_SDRAM_POS+OPTIONS_SDRAM_LO);
}

void SdramWriteOptions()
{
	SdramWriteAll(OPTIONS_SDRAM_POS+OPTIONS_SDRAM_LO);
}

void SdramReadFlags()
{
	SdramRead(OPTIONS_SDRAM_HI, FLAGS_SDRAM_LO, FLAGS_MAX_DWORD);
}

void SdramWriteFlags()
{
	SdramWrite(OPTIONS_SDRAM_HI, FLAGS_SDRAM_LO, FLAGS_MAX_DWORD);
}

void SdramUpdateFlagByte(UCHAR iPos, UCHAR iVal)
{
	SdramReadFlags();
	X_VAL(Sdram_pDataCache, iPos) = iVal;
	SdramWriteFlags();			
}

UCHAR SdramReadData(USHORT iIndex)
{
	SdramRead(P_HIBYTE(iIndex), (UCHAR)iIndex, SRAM_DMA_HALF_DWORD);
	return X_VAL(Sdram_pDataCache, SDRAM_DATA_LENGTH);
}

UCHAR SdramCopyData(USHORT iSrcIndex, PXCHAR pDst)
{
	DCHAR iLen;
	iLen = SdramReadData(iSrcIndex);
	if (iLen)
	{
		p_memcpy_x2x(pDst, (PXCHAR)Sdram_pDataCache, iLen);
	}
	return iLen;
}

UCHAR SdramCopyData_0(USHORT iSrcIndex, PXCHAR pDst)
{
	DCHAR iLen;
	iLen = SdramReadData(iSrcIndex);
	if (iLen)
	{
		p_memcpy_x2x_0(pDst, (PXCHAR)Sdram_pDataCache, iLen);
	}
	return iLen;
}

void SdramSaveData(USHORT iDstIndex, PXCHAR pSrc, UCHAR iLen)
{
	if (iLen)
	{
		p_memcpy_x2x_0((PXCHAR)Sdram_pDataCache, pSrc, iLen);
	}
	SdramWriteData(iDstIndex, iLen);
}

void SdramCopyAll(USHORT iIndex, PXCHAR pDst)
{
	SdramReadAll(iIndex);
	p_wmemcpy_x2x(pDst, (PXCHAR)Sdram_pDataCache, SRAM_DMA_BYTE);
}

void SdramSaveAll(USHORT iIndex, PXCHAR pSrc)
{
	p_wmemcpy_x2x((PXCHAR)Sdram_pDataCache, pSrc, SRAM_DMA_BYTE);
	SdramWriteAll(iIndex);
}

void SdramCopyEthernetFrame(USHORT iIndex, PXCHAR pDst, USHORT iLen)
{
	if (iLen)		// load from sdram
	{
		SdramCopyAll(iIndex, pDst);
		if (iLen > SRAM_DMA_BYTE)
		{
			SdramCopyAll((USHORT)(iIndex+2), (PXCHAR)(pDst+SRAM_DMA_BYTE));
			if (iLen > SRAM_DMA_BYTE*2)
			{
				SdramCopyAll((USHORT)(iIndex+4), (PXCHAR)(pDst+SRAM_DMA_BYTE*2));
			}
		}
	}
}

void SdramSaveEthernetFrame(USHORT iIndex, PXCHAR pSrc, USHORT iLen)
{
	if (iLen)		// save to sdram
	{
		SdramSaveAll(iIndex, pSrc);
		if (iLen > SRAM_DMA_BYTE)
		{
			SdramSaveAll((USHORT)(iIndex+2), (PXCHAR)(pSrc+SRAM_DMA_BYTE));
			if (iLen > SRAM_DMA_BYTE*2)
			{
				SdramSaveAll((USHORT)(iIndex+4), (PXCHAR)(pSrc+SRAM_DMA_BYTE*2));
			}
		}
	}
}

void SdramClearDataCache()
{
	p_memset_x((PXCHAR)Sdram_pDataCache, 0, (UCHAR)256);
	p_memset_x((PXCHAR)Sdram_pDataCache2, 0, (UCHAR)256);
}
