/******************************************************************************/
/*                                                                            */
/*  Copyright (C), 1995-2007, SanDisk IL Ltd. All rights reserved.            */
/*                                                                            */
/*  Redistribution and use in source and binary forms, with or without        */
/*  modification, are permitted provided that the following conditions are    */
/*  met:                                                                      */
/*  1. Redistributions of source code must retain the above copyright notice, */
/*     this list of conditions and the following disclaimer.                  */
/*  2. Redistributions in binary form must reproduce the above copyright      */
/*     notice, this list of conditions and the following disclaimer in the    */
/*     documentation and/or other materials provided with the distribution.   */
/*  3. Neither the name of SanDisk IL nor the names of its contributors may be*/
/*     used to endorse or promote products derived from this software without */
/*     specific prior written permission.                                     */
/*                                                                            */
/*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS       */
/*  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED */
/*  TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR             */
/*  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT      */
/*  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,     */
/*  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED  */
/*  TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR    */
/*  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF    */
/*  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING      */
/*  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS        */
/*  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.              */
/*                                                                            */
/*  NOTWITHSTANDING ANYTHING STATED TO THE CONTRARY, SANDISK'S TOTAL LIABILITY*/
/*  ARISING OUT OF OR RELATED TO THE SOFTWARE OR ANY SUPPORT SERVICES         */
/*  PROVIDED WITH RESPECT THERETO SHALL NOT EXCEED $100.                      */
/*                                                                            */
/*  The laws of the State of California, United States of America, exclusive  */
/*  of conflict-of-laws provisions, shall govern this license in all respects.*/
/*  The the federal or state courts of competent jurisdiction in the State    */ 
/*  of California shall have exclusive jurisdiction with respect to all       */
/*  actions commenced in relation to the software. Licensee agrees not        */ 
/*  to export or re-export, directly or indirectly any technical data         */ 
/*  acquired from SanDisk or any products utilizing such data in violation    */
/*  of applicable export laws and regulations.                                */
/*                                                                            */
/******************************************************************************/

/*
 * $Log:   V:/PVCSDB/DiskOnChip/archives/Test for 7.x/src/H3/hal_nor.c-arc  $
 * 
 *    Rev 1.25   Oct 22 2007 11:34:54   einat.avidan
 * update copyrights header
 * 
 *    Rev 1.24   Mar 11 2007 16:41:20   einat.avidan
 * bug fix: working on x86 requires read buffer not to be paged out
 * replace the former solution (access to the begining and the end of the buffer under NO_INIT_MMU_PAGES compilation flag) 
 * with full solution: usage of a buffer that is locked on RAM
 * 
 *    Rev 1.23   Sep 11 2006 13:45:26   yaniv.iarovici
 * Legal header added
 * 
 *    Rev 1.22   Aug 09 2006 17:26:56   Polina.Marimont
 * initial for DOC Driver 1.0
 * 
 */

/*
 * includes
 */
#include "flbase.h"
#include "hal_nor.h"
#include "doch_sys.h"
#include "doch_ata.h"

#ifdef FL_MIGRATION_VERSION
#include "docsys.h"
#endif /*FL_MIGRATION_VERSION*/

#ifdef __cplusplus
extern "C" {
#endif

/*
 * Externals
 */
extern FLDword gAccessLayerType;

#ifdef __cplusplus
}
#endif


#ifdef DOCH_USE_FUNC

#ifdef __cplusplus
extern "C" {
#endif

/*
 * Externals
 */
extern FLDword gAccessLayerType;

/*
 * global vars
 */

/****************************************************************************** 
 *                                                                            * 
 *                        d o c h _ s y s _ i n i t                           * 
 *                                                                            * 
 *  Initialize BSP specific part of DOCH driver.                              * 
 *                                                                            * 
 *  Parameters :                                                              *
 *      socketNo            : Socket # (0...DOCH_MAX_SOCKETS-1)               *
 *                                                                            * 
 *  Returns :                                                                 * 
 *      0 if success, otherwise respective error code.                        *
 *                                                                            * 
 ******************************************************************************/

DOCH_Error hal_init_nor ( FLSNative socketNo)
{
	DOCH_Socket* pdev;
	DOCH_get_socket(pdev, socketNo);

	/*If socket is not registered, return error*/
	if(pdev == NULL)
		return DOCH_DiskNotFound;

	/*Register access layer routines*/
	pdev->halRoutines.hal_get_ata_reg	= hal_get_ata_reg_nor;
	pdev->halRoutines.hal_set_ata_reg	= hal_set_ata_reg_nor;
	pdev->halRoutines.hal_get_ctrl_reg	= hal_get_ctrl_reg_nor;
	pdev->halRoutines.hal_set_ctrl_reg	= hal_set_ctrl_reg_nor;
	pdev->halRoutines.hal_blk_read		= hal_blk_read_nor;
	pdev->halRoutines.hal_blk_write		= hal_blk_write_nor;
	pdev->halRoutines.hal_doch_release	= doch_sys_release_nor;

	gAccessLayerType = DOCH_AL_NOR;

	return DOCH_OK;
}

/*********************************************************/
/* Function name	: doch_sys_release_nor*/
/* Description	    : */
/* Return type		: */
/* Argument         : int socketNo*/
/*********************************************************/
FLSNative doch_sys_release_nor(int socketNo)
{	
	return flOK;
}

/****************************************************************************** 
 *                                                                            * 
 *                   d o c h_ s y s _ g e t _ r e g X                         * 
 *                                                                            * 
 *  Reads DOCH register.                                                      * 
 *                                                                            * 
 *  Parameters :                                                              *
 *      base                 : pointer to the base of DOCH register set       *
 *      reg                  : ATA register number						      *
 *                                                                            * 
 *  Returns :                                                                 * 
 *      value of specified register                                           *
 *                                                                            * 
 ******************************************************************************/
FLByte hal_get_ata_reg_nor(volatile FLByte *base, FLSNative  reg)
{
	volatile FLWord* vPtr = (volatile FLWord*)addToFarPointer(base, (reg<<1) + DOCH_CONT_REG_AREA);
	FLWord val = DOCHREAD_IO_WORD(vPtr);

#ifdef DOCH_BIG_ENDIAN
	return (FLByte)(val>>8);	/*Value is returned in the higher byte*/
#else /*DOCH_BIG_ENDIAN*/
	return (FLByte)(val);
#endif /*DOCH_BIG_ENDIAN*/
}

FLWord hal_get_ctrl_reg_nor ( volatile FLByte * base, 
							  FLSNative         reg )
{
	volatile FLWord* vPtr = (volatile FLWord*)addToFarPointer(base, reg);
	FLWord			 regVal = DOCHREAD_IO_WORD(vPtr);

#ifdef DOCH_BIG_ENDIAN
	return ((regVal<<8) | (regVal>>8));	/*Swap high/low bytes*/
#else /*DOCH_BIG_ENDIAN*/
	return regVal;
#endif /*DOCH_BIG_ENDIAN*/
}

/****************************************************************************** 
 *                                                                            * 
 *                  d o c h _ s y s _ s e t _ r e g X                         * 
 *                                                                            * 
 *  Writes DOCH register.                                                     * 
 *                                                                            * 
 *  Parameters :                                                              *
 *      base                 : pointer to the base of DOCH register set       *
 *      reg                  : ATA register number						      *
 *      val                  : value to write to register                     *
 *                                                                            * 
 *  Returns :                                                                 * 
 *      value of specified register                                           *
 *                                                                            * 
 ******************************************************************************/

void hal_set_ata_reg_nor( volatile FLByte * base, 
					   FLSNative			reg,
					   FLNative				val )
{
	volatile FLWord* vPtr = (volatile FLWord*)addToFarPointer(base, (reg<<1) + DOCH_CONT_REG_AREA);

#ifdef DOCH_BIG_ENDIAN
	val = ((val>>8) | (val<<8));
#endif /*DOCH_BIG_ENDIAN*/

	DOCHWRITE_IO_WORD((FLWord)val, vPtr);
}

void hal_set_ctrl_reg_nor ( volatile FLByte *   base, 
                         FLSNative				reg,
                         FLNative				val )
{
#ifdef DOCH_BIG_ENDIAN
	val = ((val>>8) | (val<<8));
#endif /*DOCH_BIG_ENDIAN*/

	DOCHWRITE_IO_WORD((FLWord)val, (base + reg));
}

/****************************************************************************** 
 *                                                                            * 
 *            b l k _ r e a d_ u s i n g _ d a t a _ r e g					  * 
 *                                                                            * 
 *  Read specified # of bytes through the ATA data register					  *
 *                                                                            * 
 *  Parameters :                                                              *
 *      base                 : pointer to the base of DOCH register set       *
 *      buf                  : buffer to write from                           *
 *      bytes                : number of bytes to write						  *
 *                                                                            * 
 *  Returns :                                                                 * 
 *      NONE				                                                  *
 *                                                                            * 
 ******************************************************************************/
void blk_read_using_data_reg ( volatile FLByte * base,
							   FLByte          * buf, 
							   FLSNative         bytes )
{	
	register FLWord * buf16 ;
	register FLSNative  max;

	buf16 = (FLWord *) buf;
	max   = (FLSNative)buf + bytes; 

	/* retrieve data */
	for (; (FLSNative)buf16 < max; buf16+=8)
	{
		buf16[0] = DOCHREAD_IO_WORD(base);
		buf16[1] = DOCHREAD_IO_WORD(base);
		buf16[2] = DOCHREAD_IO_WORD(base);
		buf16[3] = DOCHREAD_IO_WORD(base);
		buf16[4] = DOCHREAD_IO_WORD(base);
		buf16[5] = DOCHREAD_IO_WORD(base);
		buf16[6] = DOCHREAD_IO_WORD(base);
		buf16[7] = DOCHREAD_IO_WORD(base);
	}
}

/****************************************************************************** 
 *                                                                            * 
 *                  h a l _ b l k _ r e a d _ n o r                           * 
 *                                                                            * 
 *  Read 'sectors' sectors from DOCH										  *
 *                                                                            * 
 *  Parameters :                                                              *
 *      base                 : pointer to the base of DOCH register set       *
 *      dest                 : buffer to read to                              *
 *      sectors              : number of sectors to read					  *
 *                                                                            * 
 *  Returns :                                                                 * 
 *      always zero (success)                                                 *
 *                                                                            * 
 ******************************************************************************/

FLSNative hal_blk_read_nor ( volatile FLByte * base, 
							 FLByte          * dest, 
							 FLSNative         sectors )
{
   volatile FLWord FAR0 * swin = (volatile FLWord FAR0 *)(addToFarPointer(base, DOCH_DATA_PORT_AREA));
   FLSNative              count = sectors<<DOCH_SECTOR_SIZE_BITS;
   register int           i;      
   register FLWord        tmp;

#ifndef FL_NO_PF_PROTECTED_READ_MEM
   /******************************************************************
   For page fault during read immunity use protected buffer.
   This is a buffer that is locked on the RAM and cannot be paged out.
   It is required to use it when working on x86 CPUs.
	******************************************************************/
   FLByte				* OrigDest =dest;
   if (! bInitializedBuffer)
		return (-1);
   dest=protectedBuffer;
#endif /* FL_NO_PF_PROTECTED_READ_MEM */

   if( (FLDword)dest & 0x1 )
   {
      /* rare case: unaligned target buffer */
      for (i = 0; i < (int)count; )
      {
         tmp = DOCHREAD_IO_WORD(swin);
#ifdef DOCH_BIG_ENDIAN
         dest[i++] = (FLByte)(tmp>>8);
         dest[i++] = (FLByte)tmp;
#else
         dest[i++] = (FLByte)tmp;
         dest[i++] = (FLByte)(tmp>>8);
#endif /* DOCH_BIG_ENDIAN */
      }
   }
   else
   {   /* mainstream case */
      /* Some memcpy implementations from none 4 bytes aligned destination
	   * buffer may use a for loop of single byte calls to the first 2 
	   * bytes. This implementation may be good for RAM, but will be 
	   * problematic to 16bit DiskOnChip that does not have a BHE signal.
	   * so if the buffer is not dword aligned we would not perform memcpy */

      if (((FLDword)dest&0x3)==0)
      {
        DOCHCPY_FROM_IO_16_BITS( (volatile byte *)swin, dest, count ); 
      }
      else
      {   /* read in short words */
         for (i = 0, count = count >> 1; i < (int)count; i++)
            ((FLWord FAR1 *)dest)[i] = DOCHREAD_IO_WORD(swin);
      }
   }
#ifndef FL_NO_PF_PROTECTED_READ_MEM
	tffscpy(OrigDest,protectedBuffer,count);
#endif /* FL_NO_PF_PROTECTED_READ_MEM */

   return 0;
}

/****************************************************************************** 
 *                                                                            * 
 *            b l k _ w r i t e _ u s i n g _ d a t a _ r e g                 * 
 *                                                                            * 
 *  Write specified # of bytes through the ATA data register				  *
 *                                                                            * 
 *  Parameters :                                                              *
 *      base                 : pointer to the base of DOCH register set       *
 *      buf                  : buffer to write from                           *
 *      bytes                : number of bytes to write						  *
 *                                                                            * 
 *  Returns :                                                                 * 
 *      NONE				                                                  *
 *                                                                            * 
 ******************************************************************************/
void blk_write_using_data_reg ( volatile FLByte * base, 
								FLByte          * buf, 
								FLSNative         bytes )
{
	volatile FLWord * reg16  = (FLWord*)base;
	register FLWord * buf16 ;
	register FLSNative  max;

	buf16 = (FLWord *) buf;
	max   = (FLSNative)buf + bytes; 

	/* write data */
	for (; (FLSNative)buf16 < max; buf16+=8)
	{
		DOCHWRITE_IO_WORD(((FLWord FAR1 *)buf16)[0],reg16);
		DOCHWRITE_IO_WORD(((FLWord FAR1 *)buf16)[1],reg16);
		DOCHWRITE_IO_WORD(((FLWord FAR1 *)buf16)[2],reg16);
		DOCHWRITE_IO_WORD(((FLWord FAR1 *)buf16)[3],reg16);
		DOCHWRITE_IO_WORD(((FLWord FAR1 *)buf16)[4],reg16);
		DOCHWRITE_IO_WORD(((FLWord FAR1 *)buf16)[5],reg16);
		DOCHWRITE_IO_WORD(((FLWord FAR1 *)buf16)[6],reg16);
		DOCHWRITE_IO_WORD(((FLWord FAR1 *)buf16)[7],reg16);
	}
}

/****************************************************************************** 
 *                                                                            * 
 *                  h a l _ b l k _ w r i t e _ n o r                         * 
 *                                                                            * 
 *  write 'sectors' sectors to DOCH										      *
 *                                                                            * 
 *  Parameters :                                                              *
 *      base                 : pointer to the base of DOCH register set       *
 *      src                  : buffer to write from                           *
 *      sectors              : number of sectors to write					  *
 *                                                                            * 
 *  Returns :                                                                 * 
 *      always zero (success)                                                 *
 *                                                                            * 
 ******************************************************************************/

FLSNative hal_blk_write_nor ( volatile FLByte * base, 
							  FLByte          * src, 
							  FLSNative         sectors )
{
   volatile FLWord FAR0 * swin = (volatile FLWord FAR0 *)addToFarPointer(base, DOCH_DATA_PORT_AREA);
   FLSNative             count = sectors<<DOCH_SECTOR_SIZE_BITS;
   register int          i;
   register FLWord       tmp;

   if( (FLDword)src & 0x1 ) /* rare case: unaligned source buffer */
   {
       for (i = 0; i < (int)count; i+=2)
       {
          /* tmp variable is just a precaution from compiler optimizations */
#ifdef DOCH_BIG_ENDIAN
          tmp = ((FLWord)src[i]<<8) + (FLWord)src[i+1];
#else
          tmp = (FLWord)src[i] + ((FLWord)src[i+1]<<8);
#endif /* DOCH_BIG_ENDIAN */
         DOCHWRITE_IO_WORD(tmp,swin);
        }
   }
   else /* mainstream case */
   {
       /* Some memcpy implementations from none 4 bytes aligned destination
	   * buffer may use a for loop of single byte calls to the first 2 
	   * bytes. This implementation may be good for RAM, but will be 
	   * problematic to 16bit DiskOnChip that does not have a BHE signal.
	   * so if the buffer is not dword aligned we would not perform memcpy */

	  if (((FLDword)src&0x3)==0)
      {
        DOCHCPY_TO_IO_16_BITS((volatile FLByte *)swin,src,count);
      }
      else
      {
         /* write in short words */
         for (i = 0, count = count >> 1; i < (int)count; i++)
           /* while incrementing buffer offset */
           /* but do not increament DiskOnChip offset */
            DOCHWRITE_IO_WORD(((FLWord FAR1 *)src)[i],swin);
      }
   }
   return 0;
}


#ifdef __cplusplus
}
#endif

#else /*DOCH_USE_FUNC*/

DOCH_Error hal_init_nor_noFunc ( FLSNative  socketNo)
{
	gAccessLayerType = DOCH_AL_NOR;
	
	return DOCH_OK;
}

#endif /*DOCH_USE_FUNC*/

