/*---------------------------------------------------------------------------*\
 *   
 *   Copyright (C) 2006 AVM GmbH <fritzbox_info@avm.de>
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation version 2 of the License.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 
\*---------------------------------------------------------------------------*/

#include "ahcidef.h"
#include "ahcicopy.h"
#include "ahcireg.h"

/*---------------------------------------------------------------------------*\
\*---------------------------------------------------------------------------*/
void AHCI_CopyToAlignedHW (PAHCI_REGISTER pTo, char * pFrom, unsigned len) {
	assert (AHCI_isAligned (pTo));
	if (len != 0) {
		unsigned restlen = len &3;
		len -= restlen;
		
		if (len != 0) {
			AHCI_DWORDCopyToAlignedHW (pTo, pFrom, len);
		}

		if (restlen != 0) {
			unsigned tmpvalue;
			AHCI_DWORD * pLastDWORD = (AHCI_DWORD *)(((char*)pTo)+len);
			
			assert (AHCI_isAligned (pLastDWORD));

			pFrom += len;

			memcpy (&tmpvalue, pFrom, restlen);
			AHCI_WRITE_REGISTER (pLastDWORD, tmpvalue);
		}
	}
}

/*---------------------------------------------------------------------------*\
\*---------------------------------------------------------------------------*/
void AHCI_CopyToHWSafe (void *pTo, char * pFrom, unsigned len) {
	unsigned rel_adr = ((unsigned)pTo) & 3;
	if (rel_adr != 0) {
		unsigned tmpvalue;
		unsigned sublen = 4 - rel_adr;
		AHCI_DWORD * pFirstDWORD = (AHCI_DWORD *)(((char*)pTo)-rel_adr);

		if (sublen > len) {
			sublen = len;
		}

		assert (AHCI_isAligned (pFirstDWORD));
		// save old bytes for restore
		tmpvalue = AHCI_READ_REGISTER (pFirstDWORD);
		
		memcpy (((char*)(&tmpvalue))+rel_adr, pFrom, sublen);
		AHCI_WRITE_REGISTER (pFirstDWORD, tmpvalue);

		len -= sublen;
		pFrom += sublen;
		pTo = pFirstDWORD+1;
	}
	
	AHCI_CopyToAlignedHW (pTo, pFrom, len);
}
