/****************************************************************************
/*  F i l e   D a t a                                                        
/*                                                                           
/*  Module       : FileManager                                                   
/*  C.I. No.     :                                                           
/*  $Revision: 1.18 $
/*  $Date: 2005/03/20 18:17:45 $
/*  Belonging to :                                                           
/*               :                                                           
/*  $RCSfile: FT_MMSUManager_op.c,v $
/*  Program Type :                                                           
/*  Sub-modules  :                                                           
/*                                                                           
/****************************************************************************
/*  S W   D e v e l o p m e n t   E n v i r o n m e n t                      
/*                                                                           
/*  Host system  :                                                           
/*  SW Compiler  :                                                           
/*  $Author: sebastiani $
/*               :                                                           
/****************************************************************************
/*  U p d a t i n g                                                          
/*                                                                           
/*  $Log: FT_MMSUManager_op.c,v $
/*  Revision 1.18  2005/03/20 18:17:45  sebastiani
/*  PRH_VAR_TIM_MMSU_DMA_DELAY cancelled
/*
/*  Revision 1.17  2005/03/06 14:54:16  sebastiani
/*  fix log
/*
/*  Revision 1.16  2005/02/21 08:58:28  sebastiani
/*  all log comments completed
/*
/*  Revision 1.15  2005/01/26 18:46:28  sebastiani
/*  *** empty log message ***
/*
/*  Revision 1.14  2004/09/09 14:50:41  sebastiani
/*  add debug output console
/*
/*  Revision 1.13  2004/08/26 16:54:07  sebastiani
/*  fix some bug
/*
/*  Revision 1.12  2004/06/30 07:26:24  sebastiani
/*  *** empty log message ***
/*
/*  Revision 1.11  2004/06/15 08:13:28  sebastiani
/*  FT_opPendingSaveRequests introduced
/*
/*  Revision 1.10  2004/05/20 09:04:06  sebastiani
/*  ok
/*
/*  Revision 1.9  2004/05/19 08:44:25  sebastiani
/*  fix bug
/*
/*  Revision 1.8  2004/03/03 11:23:43  tassa
/*  Start downlink manager by timer+message
/*
/*  Revision 1.7  2003/11/10 12:21:11  sebastiani
/*  FS_piInitFileSystem() not invoked any more inside the FT_opChangeOpMode. This fixes the bug that reinitialized the Mass Memory at every change to active/maintenance
/*
/*  Revision 1.6  2003/10/21 16:09:12  alfarano
/*  LU_LOG_INFN replacement for all remaining original log functions
/*
/*  Revision 1.5  2003/10/17 08:25:48  sebastiani
/*  FILE1 bugfixes,
/*  downlink various bugfixes, VRL switch on/off introduced,
/*  FT_ifStopDownLink_CallBack function introduced,
/*  "case" FT_STOP_DOWNLINK introduced for the MSSUManager task
/*
/*  Revision 1.4  2003/09/10 13:44:00  laben
/*  New File System model: just one file used like a circular buffer.
/*  NEw donwlink procedure: downlink next sector until the timer expires.
/*
/*  Revision 1.3  2003/08/27 09:49:17  wizard
/*  Fix last sector in donwload.
/*  Set Sector size to 1024*1015
/*  Fix Donwload procedure... ( set size set lastsector flag.....)
/*  bye
/*
/*  Revision 1.2  2003/08/07 08:44:14  wizard
/*  SIMULATOR bugs ifdef/ifndef corrected
/*  laben bug "GetFileInfo" for FS_ERC32 id accepted in order to fix SM_pi_GetPacket
/*
/*  Revision 1.1.1.1  2003/08/04 09:40:21  sebastiani
/*  Imported sources laben rel. 19.06.2003 integrated with pam2
/*
/*  Revision 1.15  2003/06/09 10:23:22  aurora
/*  improved the management of data acquisition
/*
/*  Revision 1.14  2003/05/06 15:43:28  aurora
/*  deleted the check of CMD I/F register on ISR WriteEOT.
/*  The transfer on CMD I/F doesn't rise any interrupt
/*
/*  Revision 1.13  2003/04/11 08:24:55  aurora
/*  Fixed Memory Module TEST
/*
/*  Revision 1.12  2003/03/12 10:53:49  aurora
/*  the channel for write on CMD is unlocked immediately after send
/*
/*  Revision 1.11  2003/01/22 13:58:04  aurora
/*  removed bug in WriteEOT ISR
/*
/*  Revision 1.10  2002/10/17 10:05:18  zulia
/*  fixed ON/OFF memory module
/*  optimised PIFReset
/*
/*  Revision 1.9  2002/07/31 14:27:00  zulia
/*  Correct EXE_MEM_CONF and init memory module
/*
/*  Revision 1.8  2002/05/09 13:44:26  aurora
/*  Column latchup recovery updated
/*
/*  Revision 1.7  2002/05/09 08:16:34  zulia
/*  *  acceptance release
/*
/*                                                                           
/*****************************************************************************/

 
/*============================= Include File ================================*/


#include <src/INFN/LU_SourceFileID_INFN.h>
#define __FILEID__ _FT_MMSUManager_op__c
#include <src/INFN/PRH_ParamHandler_INFN.h>
#include <src/INFN/LU_LogUtility_INFN.h>
#include <src/INFN/PRH_ParamHandler_INFN_auto.h>
LU_DECL_MASK();

  
#include <src/FileManager/MMSUManager/FT_MMSUManager_op.h>
#include <src/FileManager/MMSUManager/FT_MMSUManager_int.h>
#include <src/TM_TCManager/TMTCManager/TM_TMTCManager_p.h>
#include <src/INFN/LU_LogUtility_INFN.h>
#include <src/INFN/MH_ModeHandler_INFN.h>

/*============================== local define ===============================*/

#define WPBEOT  ERC32_INTERRUPT_EXTERNAL_4
#define RPBEOT  ERC32_INTERRUPT_EXTERNAL_3

/*****************************************************************************/
/*======================== Object internal structure ========================*/
/*****************************************************************************/

/*======================== Object Internal variables ========================*/

/*****************************************************************************/
/* @Constant: FT_MemModTestDef                                               */
/* @Purpose :                                                                */
/*  Array of FT_MOD_TEST structures.                                         */
/*  Test pattern.                                                            */
/* @@                                                                        */
/*****************************************************************************/
const  FT_MOD_TEST  FT_MemModTestDef[]={
    {FT_TEST_PATTERN_EN,FT_TEST_PATTERN_VAR,0x0000,FT_TEST_MOD_NOT_PERFORMED,0x0000},
    {FT_TEST_PATTERN_EN,FT_TEST_PATTERN_FIX,0xaaaa,FT_TEST_MOD_NOT_PERFORMED,0x0000},
    {FT_TEST_PATTERN_EN,FT_TEST_PATTERN_FIX,0x5555,FT_TEST_MOD_NOT_PERFORMED,0x0000},
    {FT_TEST_PATTERN_EN,FT_TEST_PATTERN_FIX,0xffff,FT_TEST_MOD_NOT_PERFORMED,0x0000},
    {FT_TEST_PATTERN_EN,FT_TEST_PATTERN_FIX,0x0000,FT_TEST_MOD_NOT_PERFORMED,0x0000}};



/*****************************************************************************/
/* @Variable: FT_MMSUStatus                                                  */
/* @Purpose :                                                                */
/*   FT_ALL_MMSU_STATUS  structure                                           */
/*   MMSU Local and Remote hardware status.                                  */
/* @@                                                                        */
/*****************************************************************************/
static FT_MMSU_STATUS     FT_MMSUStatus;

/*****************************************************************************/
/* @Variable: FT_TestModuleStatus                                            */
/* @Purpose :                                                                */
/*   FT_TEST_MOD_STATUS  structure                                           */
/*   Memory Module test status.                                              */
/* @@                                                                        */
/*****************************************************************************/
static FT_TEST_MOD_STATUS  FT_TestModuleStatus;

/*****************************************************************************/
/* @Variable: FT_RWChannel                                                   */
/* @Purpose :                                                                */
/*   FT_TEST_MOD_STATUS  structure                                           */
/*   Info about the read channel: downlink status, file to be downlinked ... */
/*   Info about the write channel: write enable/disable, store in progress ..*/
/* @@                                                                        */
/*****************************************************************************/
static FT_RW_CH   FT_RWChannel;

// XXXDEBUG MASSIMO BEGIN -------------------------------------------------------------------------------------------------------------------
// task a cui mandare la notifica di fine DOWNLOAD

static UINT32  FT_task2notify_EOD;

// XXXDEBUG MASSIMO END   -------------------------------------------------------------------------------------------------------------------

/*****************************************************************************/

/*==== M M S U M a n a g e r   O P E R A T I O N A L   F U N C T I O N S ====*/

/*****************************************************************************/
/* @Function: FT_opInitMMSUManager                                           */
/* @Purpose :                                                                */
/*  The function initializes the MMSUManager object.  The OS directive are   */
/*  called to set priority and to ready the MMSUManager task.                */
/*  The function also performs the following initializations:                */
/*      - PSCU status initalization                                          */
/*      - MMSU test running initialization                                   */
/*      - Last Bite filler word initialization                               */
/*                                                                           */
/* @@                                                                        */
/* @Parameter Name      @Mode   @Description                                 */
/* status_code          OUT     Return code                                  */
/* @@                                                                        */
/*****************************************************************************/

status_code FT_opInitMMSUManager (void)
{
status_code  status;
unsigned int OldPriority;
unsigned int i,c;

    status  =SUCCESSFUL;

    /* Task initialization                        */
    if (OS_piTaskReady(FT_TASK,FT_tkMMSUManager) != SUCCESSFUL)
    {
        /* Task is not correctly started          */
        /*@LOG LOG_INFN HA_piLogHistoryEntry10(HA_E10_SW_FT,HA_E10_TSK_READY_ERR,status); */
	LU_INFN_LOG(LU_CRITICAL,LU_MASK(__FILEID__),__FILEID__,__LINE__,status);
        status  =UNSATISFIED;
    }
    if (OS_piTaskPriority(FT_TASK,MMSU_PRIORITY,&OldPriority) != SUCCESSFUL)
    {
        /* Task priority is not correctly updated */
        /*@LOG LOG_INFN HA_piLogHistoryEntry10(HA_E10_SW_FT,HA_E10_TSK_PRIORITY_ERR,status); */
	LU_INFN_LOG(LU_CRITICAL,LU_MASK(__FILEID__),__FILEID__,__LINE__,status);
        status  =UNSATISFIED;
    }


    /* DSHA status initalization                   */
    FT_ifMMSUStatusInit(&FT_MMSUStatus,(void*)&FT_MemModTestDef[0]);

    /* MMSU test running initialization            */
    FT_TestModuleStatus.State   =FT_TEST_NO_RUNNING;
    FT_TestModuleStatus.Module  =0xffffffff; /* No Module index  */
    FT_TestModuleStatus.TestIdx =0xffffffff; /* No Pattern index */

    /* Init the RWChannel                          */
    FT_ifRWChannelInit(&FT_RWChannel,
                       FT_MEM_MOD_1,
                       &FT_MMSUStatus.Module[FT_MEM_MOD_1]);
    FT_RWChannel.CMDWriteFail = 0;

    return (status);
}



/*****************************************************************************/
/* @Function: FT_opSndMsgMMSUManager                                         */
/* @Purpose :                                                                */
/*  The function  invokes the directive of the OS to send a message to the   */
/*  MMSUManager mailbox.                                                     */
/*                                                                           */
/* @@                                                                        */
/* @Parameter Name      @Mode   @Description                                 */
/*  SndMsg               IN      Pointer to the message task information     */
/*                               (MsgTsk type)                               */
/*  status_code          OUT     Return code                                 */
/* @@                                                                        */
/*****************************************************************************/

status_code FT_opSndMsgMMSUManager(MsgTsk* SndMsg)
{
status_code   status;

    /* Call the OS directive to put a message into the task mailbox  */
    status =OS_piMsgQueueSend(FT_MAILBOX,SndMsg,sizeof(MsgTsk));
    return (status);

}



/*****************************************************************************/
/* @Function: FT_tkMMSUManager                                               */
/* @Purpose :                                                                */
/*  The function is the task handler of the MMSUManager object.              */
/*  When a message is received into task mailbox it wakes up.                */
/*  The information contained in the message (MsgTsk structure) define       */
/*  parameters (Info field), and the operation type that the task performs   */
/*  (Code field).                                                            */
/*  The MMSUManager task activity is to manage the MMSU operations.          */
/*  The operations performed by task are:                                    */
/*                                                                           */
/* @@                                                                        */
/* @Parameter Name      @Mode   @Description                                 */
/* @@                                                                        */
/*****************************************************************************/

task FT_tkMMSUManager  (task_argument unused)
{
MsgTsk         RxMsg;
unsigned int   MsgSize;
FT_SAVEREQUEST saveReq;
unsigned int   reqSize;

    while( FOREVER ) 
    {
        RxMsg.Code =NULL_MSG_FT;
        /* Wait for a message to become available                            */
        if ((OS_piMsgQueueReceive (FT_MAILBOX,(void*)&RxMsg,
             &MsgSize,NO_WAIT, 0)) == SUCCESSFUL)
        {
	  /*@LOG MMSUManager Task: operation code received */
	  LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,RxMsg.Code);
	  switch (RxMsg.Code)
            {
	    case FT_MCMD_DOWN_LINK : /*=== MCMD DOWN LINK management     */
	      FT_ifMCMDDownLinkExec((MA_HEADER_MCMD*)RxMsg.Info,
				    &FT_RWChannel);
	      break;
	    case FT_MCMD_BITE :    /*=== MCMD BITE management            */
	      FT_ifMCMDBiteExec((MA_HEADER_MCMD*)RxMsg.Info,
				&FT_MMSUStatus,
				&FT_TestModuleStatus,
				&FT_RWChannel);
	      break;
	    case FT_STOP_DOWNLINK:
	      FT_ifStopDownLink(&FT_RWChannel);
	      break;
	    case FT_START_DOWNLINK:
	      FT_ifStartDownLink(&FT_RWChannel);
	      break;
	    case FT_ABORT :    /*=== MCMD ABORT management              */
                    FT_ifMCMDAbordExec((MA_HEADER_MCMD*)RxMsg.Info,
				       &FT_RWChannel,
				       &FT_TestModuleStatus);
                    break;
	    case FT_MCMD_EXE_MEM_CONF :/*=== MCMD MEMERY.CONF.management */  
	      FT_ifMCMDExeMemConf((MA_HEADER_MCMD*)RxMsg.Info,
				  &FT_MMSUStatus, &FT_RWChannel);
	      break;
	    case FT_MEM_MODULE_TEST :/*=== Mem. Module TEST management   */
	      FT_ifMemModuleTestExec(&FT_MMSUStatus,
				     &FT_TestModuleStatus,
				     (void*)&FT_MemModTestDef[0]);
	      break;
	    case FT_TEST_MODULE_END:/*=== End TEST module menagement     */
	      FT_ifTestModuleEnd(*(unsigned int*)RxMsg.Info,
				 &FT_MMSUStatus,
				 &FT_TestModuleStatus);
	      break;
	    case FT_LATCHUP_RECOVERY:/*=== LatchUp recovery management   */
	      FT_ifLatchUpRecovery(*(unsigned int*)RxMsg.Info,
				   &FT_MMSUStatus, &FT_RWChannel);
	      break;
	    case FT_HW_ERROR_RECOVERY :/*=== HW error recovery management*/
	      FT_ifHwErrorRecovery(*(unsigned int*)RxMsg.Info,
				   &FT_MMSUStatus, &FT_RWChannel);
	      break;
	    case FT_INIT_FS:
	      FS_piInitFileSystem();
	      break;	      
	    default:
	      break;
            };
        }

        if ( (OS_piMsgQueueReceive (SAVE_MBOX, &saveReq, 
                              &reqSize, WAIT, 20) == SUCCESSFUL))
        {
               /* write pending save request on Memory Module          */
               FT_opPacket2MMSU (saveReq);
        }
    }
}


/*****************************************************************************/
/* @Function: FT_opMemBoardMod                                               */
/* @Purpose :                                                                */
/*  The function handles the Memory Module interrupt raised by the DRAMMA    */
/*  device due to an internal failure.  The -MemModule- parameter            */
/*  specify the MMSU and Memory Module where the failure is matched.         */
/*  Different kinds of failure are managed:                                  */
/*      - Hardware OR and AND erorr. A message to MMSUManager is sent to     */
/*        manage HW error recovery.                                          */
/*      - Scrabbing Adrres Overflow error. This interrrupt normally disabled,*/
/*        it is enabled only during the procedure of Memory Module scrabbing */
/*        used in the Test or Bite operation. This interrupt goes active     */
/*        every time the scubber completes a cycle on the whole memory.      */
/*        At this time if the Bite operations are active, the Bite Down Link */
/*        procedure is started. Otherwise if Memory Module Test operations   */
/*        are active is started the next Memory Module test.                 */
/*      - Latch UP Monitor error. When this interrupt goes active, means     */
/*        that one or more columns of the memory have gone in Latch Up mode. */
/*        The task invoked by the interrupt handler will provide to execute  */
/*        the Latch Up recovery procedure.                                   */
/*                                                                           */
/* @@                                                                        */
/* @Parameter Name      @Mode   @Description                                 */
/*  MemModule            IN      Memory Module (FT_MEMORY_MODULE type)       */
/*  status_code          OUT     Return code                                 */
/* @@                                                                        */
/*****************************************************************************/

status_code FT_opMemBoardMod  (unsigned int MemModule)
{
#ifndef SIMULATOR
  status_code  status;
  unsigned int pendingInt;
  unsigned int latchupBit;
  FT_MEM_MOD*  pMemMod;
  unsigned int hwErr;
  unsigned int ch;

  /* Check parameters                                 */
  pMemMod =&FT_MMSUStatus.Module[MemModule];
  
  /* Read all memory module interrupts                */
  FD_piDrammaRdRPBUSReg(MemModule,FD_PENDING_INT,&pendingInt);
  pendingInt =FD_MM_INTER_BIT(pendingInt);
  
  /* Check Memory Module interrupts                   */
  if ((pendingInt & FD_MM_INT_HW_OR) || (pendingInt & FD_MM_INT_HW_AND))
    {
      /*====== Hardware OR and AND erorr =============*/
      /* Mask all memory module interrupts            */
      FD_piDrammaWrWPBUSReg(MemModule,FD_INTMSK,FD_MM_INT_ALL);
      /* Read Hard Error Register                     */
        FD_piDrammaRdRPBUSReg(MemModule,FD_HARD_ERROR_REG,&hwErr);
        /* HW error rocovery menagement                 */
        FT_ifHwErrorInter(MemModule);
        /*======== Entry 11 Log in History Area ========*/
        /*@LOG LOG_INFN HA_piLogHistoryEntry11(HA_E11_MEMORY_MODULE, HA_E11_MOD_INT_HW_ERR,MemModule, hwErr); */
	LU_INFN_LOG(LU_CRITICAL,LU_MASK(__FILEID__),__FILEID__,__LINE__,hwErr);
    }
  
    if (pendingInt & FD_MM_INT_SW_OVL)
      {
        /*====== Software Overflow error ===============*/
      }
    
    if (pendingInt & FD_MM_INT_SA_OVL)
      {
        OS_piCancelTimer(FT_TIM);
        /*====== Scrabbing Adrres Overflow error =========*/
        /* This function checks if Module is in TEST mode,*/
        /* if is it Test Module procedure is managed      */
        FT_ifMemModuleTestInter (&FT_MMSUStatus,&FT_TestModuleStatus);
        /* Check if Module is in BITE mode                */
        if (pMemMod->Mode==FT_MODE_MEM_MOD_BITE) 
	  {
            /*========= Entry 0 Log in History Area ==========*/
            /*@LOG LOG_INFN HA_piLogHistoryEntry0(HA_E0_EXITING,HA_E0_BITE,0); */
	    LU_INFN_LOG(LU_CRITICAL,LU_MASK(__FILEID__),__FILEID__,__LINE__,0);
            /* Check if memory fill is OK                 */
            if (pMemMod->State==FT_STATE_MOD_OK)
	      {
		/* Interrupt unmask: LATCHUP_MONITOR,HW_OR,HW_AND */
		/* Interrupt masked: SA_OVL ,SFT_OVL              */
		FD_piDrammaWrWPBUSReg(MemModule,FD_INTMSK,FD_MM_INT_ABIL_ALL);
		/* Memory fill OK                         */
		/* Start Down Link procedure              */
		pMemMod->Mode = FT_MODE_MEM_MOD_ON;
	      }
            else
	      {
                /* Memory fill not OK                     */
                /* Close BITE operative mode              */
                pMemMod->Mode = FT_MODE_MEM_MOD_ON;
	      }
	  }
      }
    
    if (pendingInt & FD_MM_INT_LM_C_ALL)
      {
        /*=========== Latch UP Monitor error =============*/
        FT_ifColLatchUpInter(MemModule,FD_MM_LTATCHUP_BIT(pendingInt));
        /*======== Entry 11 Log in History Area ========*/
	/*@LOG LOG_INFN HA_piLogHistoryEntry11(HA_E11_MEMORY_MODULE, HA_E11_MOD_INT_LATCHUP,MemModule, pendingInt); */
	LU_INFN_LOG(LU_CRITICAL,LU_MASK(__FILEID__),__FILEID__,__LINE__,pendingInt);
      }
    
    /* Clear all Memory Module interrupts                 */
    FD_piDrammaWrWPBUSReg(MemModule,FD_INTCLR,FD_MM_INT_ALL);
#endif // SIMULATOR
    return (SUCCESSFUL);
}






/*****************************************************************************/
/* @Function: FT_opMemModuleON                                               */
/* @Purpose :                                                                */
/*  The function switches ON a Memory Module.                                */
/*  The -MemModule- parameter  specifies the Memory Module that  must be     */
/*  switched ON.                                                             */
/*  The Memory Module will be switched ON if module is OFF and his state is  */
/*  OK.  The procedure to switch ON the 10 colums (8 columns date, 2 CRC     */
/*  columns) of th module is the following:                                  */
/*      -  Clear and mask all Memory Module interrupts.                      */
/*      -  Program Dramma SCRUBBING and REFRESH register.                    */
/*      -  Switch ON the 10 columns programming ON a column at a time in     */
/*         the CONFIGURATION Register. One ms of delay is executed before    */
/*         activate the next column.                                         */
/*      -  Check possible Latch Up monitor errors.                           */
/*      -  If  Latch Up errors are found  the recovery procedure is executed */
/*      -  If Memory Module switching is OK, a power-up memory sequence is   */
/*         started programmming DRAMMA INIT Register. Memory Module sectors  */
/*         are inserted into FAT.                                            */
/*      -  Else Memory Module is put OFF and his state in FAIL.              */
/*      -  Unmask all memory module interrupts.                              */
/*                                                                           */
/* @@                                                                        */
/* @Parameter Name      @Mode   @Description                                 */
/*  MemModule            IN      Memory Module (FT_MEMORY_MODULE type)       */
/*  status_code          OUT     Return code                                 */
/* @@                                                                        */
/*****************************************************************************/

status_code FT_opMemModuleON (unsigned int MemModule)
{
#ifndef SIMULATOR
  status_code  status;
  unsigned int retCode;
  FT_MEM_MOD*  pMod;
  FT_MEM_MOD   mod;
  unsigned int configRegVal;
  unsigned int memModule;
  unsigned int maskCol;
  unsigned int pendingVal;
  unsigned int colLatchup;
  unsigned int colEnable;
  unsigned int colError;
  unsigned int colOn;
  unsigned int i;

    /* Check parameters                                                 */
    memModule =MemModule & FD_BOARD_ADDR_MASK;

    /* Get module pointer of the MMSU status structure                  */
    pMod =&FT_MMSUStatus.Module[memModule];
    /* Assign the Memory Module status structure to the local structure */
    mod = *pMod;
    if (pMod->Mode==FT_MODE_MEM_MOD_OFF)
    {
        /* Memory Module OFF, try to switch ON                          */
        status     =FT_MEM_MOD_SW_ON_OK;
        /* Clear all Memory Module interrupts                           */
        FD_piDrammaWrWPBUSReg (memModule,FD_INTCLR,FD_MM_INT_ALL);        
        /* Mask all Memory Module interrupts                            */
        FD_piDrammaWrWPBUSReg (memModule,FD_INTMSK,FD_MM_INT_ALL);        
        /* Set Dramma SCRUBBING and REFRESH register                    */
        FD_piDrammaWrWPBUSReg (memModule,FD_SCRUBBER_REFRESH,FD_SCRABBER_REFRESH_VALUE);
        
        /* Active the 10 Columns writing a CONFIGURATION REGISTER       */
        configRegVal =FD_CONFIG_REG_27_11_B | (MemModule << 22);
        for (i=0, maskCol =FD_CONFIG_REG_COL_01; i<FD_MAX_COLUMN_ENABLE; i++,maskCol <<=1)
        {
            /* Column ON                                                */
            configRegVal |=maskCol;
            FD_piDrammaWrWPBUSReg (memModule,FD_CONFIGURATION,configRegVal);
            /* Program Latchup Retry counter 3 ms                       */ 
            FD_piDrammaWrWPBUSReg (memModule,FD_LATCH_UP_RETRY,FD_LATCHUP_RETRY_VAL); 
            
             mod.Column[i] =FT_COLUMN_ON;
            /* Wait 6 ms  before to activate the next column            */
            OS_piTaskSuspend (7);
        }
        /* Check Latch Up monitor interrupts                            */
        FD_piDrammaRdRPBUSReg (memModule,FD_PENDING_INT,&pendingVal);
        /* Take only the Latch Up bits                                  */
        colLatchup  =FD_MM_LTATCHUP_BIT(pendingVal);
        /* Check if there are columns in Latch Up condition             */
        if (colLatchup)
        {
            /*==========  Column Latch Up recovery procedure  ==========*/
            /* Clear all memory module interrupts                       */
            FD_piDrammaWrWPBUSReg (memModule,FD_INTCLR,FD_MM_INT_ALL);
            /* Try to activate the columns in Latch Up                  */ 
            retCode =FT_ifColumnLatchUp(memModule,configRegVal,
                                        colLatchup,FALSE,&colError,&pendingVal);
            /* Check if there are Column in error                       */
            if (retCode==SUCCESSFUL && colError)
            {
                /* There is 1 column error, try to use Spare column     */
        
                /* Column in fail OFF                                   */
                configRegVal &=~colError;
                 FD_piDrammaWrWPBUSReg (MemModule,FD_CONFIGURATION,configRegVal);
                /* Column spare switched ON                             */
                configRegVal |=FD_CONFIG_REG_COL_11;
                /* Program Latchup Retry counter 3 ms                   */
                FD_piDrammaWrWPBUSReg (memModule,FD_LATCH_UP_RETRY,FD_LATCHUP_RETRY_VAL);
                /* Column ON                                            */
                FD_piDrammaWrWPBUSReg (memModule,FD_CONFIGURATION,configRegVal);
                mod.Column[FT_SPARE_COL] =FT_COLUMN_ON;
                /* Wait 6 ms                                            */
                OS_piTaskSuspend (7);
                /* Check if Spare column is in Latch Up                 */
                FD_piDrammaRdRPBUSReg (memModule,FD_PENDING_INT,&pendingVal);
                colLatchup  =FD_MM_LTATCHUP_BIT(pendingVal); 
                if (colLatchup)
                {
                    /*======= Column Latch Up recovery procedure =======*/
                    /* Clear all memory module interrupts               */
                    FD_piDrammaWrWPBUSReg (memModule, FD_INTCLR, FD_MM_INT_ALL);		    
                    retCode =FT_ifColumnLatchUp(memModule,configRegVal,FD_CONFIG_REG_COL_11,
                                                FALSE,&colError,&pendingVal);
                    if (colError)
                    {
                        /* The Spare column is still in Latch Up        */
                        status =FT_MEM_MOD_SW_ON_ERROR;
                        mod.Column[FT_SPARE_COL] =FT_COLUMN_FAIL;
                    }
                }
            }
            else if (retCode!=SUCCESSFUL)
            {
                status =FT_MEM_MOD_SW_ON_ERROR;
            }
        }
        
  if(status==FT_MEM_MOD_SW_ON_OK)
        {
            /*===========  Column not in Latch Up condition  ===========*/
            /* Check if all 10 columns have been enabled                */
            /* Take columns enabled                                     */
            colEnable =FD_COLUMN_ENABLE(pendingVal);
            for (i=0,colOn=0,maskCol=1; i<FD_MAX_COLUMNS; i++,maskCol <<=1)
            {
                if (colEnable & maskCol)
                {
                    colOn++;
                }
            }
            if (colOn == FD_MAX_COLUMN_ENABLE)
            {
                /* Start a Memory Module operation and fill all 0 the memory */
                FD_piDrammaWrWPBUSReg (memModule,FD_INITREG,FD_INITREG_MODULE_INIT);
                /* Wait 2 ms,time necessary to complete the start operations */
                OS_piTaskSuspend (2);
                mod.State =FT_STATE_MOD_OK;
                mod.Mode  =FT_MODE_MEM_MOD_ON;
            }
            else
            {
                /* The columns are not correctly switched on            */
                status =FT_MEM_MOD_SW_ON_ERROR;        
            }
        }
        if (status == FT_MEM_MOD_SW_ON_ERROR)
        {
            /* Memory Module switched OFF                               */
            FT_opMemModuleOFF(memModule);
            mod.State =FT_STATE_MOD_FAIL;
            mod.Mode  =FT_MODE_MEM_MOD_OFF;

            /*============= Entry 11 Log in History Area ===============*/
	    /*@LOG LOG_INFN HA_piLogHistoryEntry11(HA_E11_MEMORY_MODULE, HA_E11_MOD_ON_ERR,MemModule, colError); */
	    LU_INFN_LOG(LU_CRITICAL,LU_MASK(__FILEID__),__FILEID__,__LINE__,colError);
        }

        /* Assign the Memory Module state                               */
        *pMod =mod;
        /* Unmask all memory module interrupts                          */
        FD_piDrammaWrWPBUSReg (memModule,FD_INTMSK,FD_MM_INT_ABIL_ALL);
    }
    else
    {
        /* Memory Module already ON, or in fail                         */
        status =(pMod->State==FT_STATE_MOD_OK) ? FT_MEM_MOD_ALREADY_ON:
                                                 FT_MEM_MOD_STATE_FAIL;
    }
    
    return (status);
#else
    return SUCCESSFUL;
#endif // SIMULATOR
}



/*****************************************************************************/
/* @Function: FT_opMemModuleOFF                                              */
/* @Purpose :                                                                */
/*  The function switches OFF a Memory Module.                               */
/*  The -MemModule- parameter  specifies the Memory Module that              */
/*  must be switched OFF.                                                    */
/*  The procedure to switch OFF all columns is the following:                */
/*      -  Clear and mask all Memory Module interrupts.                      */
/*      -  Switch OFF all columns programming OFF a column at a time in      */
/*         the CONFIGURATION Register. One ms of delay is executed before    */
/*         activate the next column.                                         */
/*      -  Unmask all memory module interrupts.                              */
/*                                                                           */
/* @@                                                                        */
/* @Parameter Name      @Mode   @Description                                 */
/*  MemModule            IN      Memory Module (FT_MEMORY_MODULE type)       */
/*  status_code          OUT     Return code                                 */
/* @@                                                                        */
/*****************************************************************************/

status_code FT_opMemModuleOFF (unsigned int MemModule)
{
#ifndef SIMULATOR
  status_code status;
  unsigned int memModule;
  FT_MEM_MOD*  pMod;
  FT_MEM_MOD   mod;
  unsigned int configRegVal;
  unsigned int pendingVal;
  unsigned int maskCol;
  unsigned int i;
  
  /* Check parameters                                 */
  memModule =MemModule & FD_BOARD_ADDR_MASK;

    /* Initialization local variable                    */
    pMod =&FT_MMSUStatus.Module[memModule]; 

    /* Assign the Memory Module status structure to the */
    /* local variable                                   */
    mod = *pMod;
    for (i=0; i<FD_MAX_COLUMNS; i++)
    {
        mod.Column[i] =FT_COLUMN_OFF;
    }
    mod.State =pMod->State; /* Maintain the old state   */
    mod.Mode  =FT_MODE_MEM_MOD_OFF;
        
    /* Program Dramma REINT register                    */
    FD_piDrammaWrWPBUSReg(MemModule,FD_REINIT,0);
    /* Mask all Memory Module interrupts                */
    FD_piDrammaWrWPBUSReg(MemModule,FD_INTMSK,FD_MM_INT_ALL);
    /* Get Columns enabled (Bit 16..24)                 */
    FD_piDrammaRdRPBUSReg (memModule,FD_PENDING_INT,&pendingVal);
    /* Memory Module switched OFF                       */
    configRegVal =FD_CONFIG_REG_27_11_B | (MemModule << 22);
    configRegVal =FD_CONFIG_REG_27_11_B | FD_COLUMN_ENABLE(pendingVal);
    for (i=0,maskCol  =FD_CONFIG_REG_COL_01 ;i<FD_MAX_COLUMNS; i++,maskCol <<=1)
    {
        /* Column OFF                                   */
        configRegVal &=(~maskCol);
        FD_piDrammaWrWPBUSReg(MemModule,FD_CONFIGURATION,configRegVal);
        /* Wait 2 ms before to activate the next column */
        OS_piTaskSuspend (2);
    }
    /* Assign the Memory Module state                   */
    *pMod =mod;
#endif // SIMULATOR
    
    return (FT_MEM_MOD_SW_OFF_OK);
}

/*****************************************************************************/
/* @Function: FT_opSavePage                                                  */
/* @Purpose :                                                                */
/*  This function store the selected SRAM page into the memory module. If a  */
/*  previous storage is in progress than the store request is saved in the   */
/*  store request queue.                                                     */
/* @@                                                                        */
/* @Parameter Name      @Mode   @Description                                 */
/*  PageId               IN      ID of the SRAM page to be saved             */
/*  PageInfo             IN      DAQ write result for the SRAM page          */
/*  FileId               IN      Destination file                            */
/*  FT_SAVE_RESULT       OUT     Return code                                 */
/* @@                                                                        */
/*****************************************************************************/

FT_SAVE_RESULT FT_opSavePage(SM_PAGEID PageId, SD_DAQ_WRESULT PageInfo,
                             FS_FILEID FileId)
{
unsigned int intLevel;
FT_SAVE_RESULT status = FT_SUCCESS;
FT_SAVEREQUEST saveReq;

  /* Filter the save page requests base on the store channel status: */
  /* FT_STR_NONE reject all the requests                             */
  /* FT_STR_ALL  accept all the requests                             */
  /* FT_STR_CMD  accept only save requests towards the CMD I/F       */
  if((FT_RWChannel.StoreEnable != FT_STR_NONE &&
     (FT_RWChannel.StoreEnable == FT_STR_ALL ||
     FileId == FS_CMD)) || FileId == FS_ERC32 ) 
  {
    /* Disable ISR that access the store queue data structures */
    OS_piInterDisable(&intLevel);
    SD_piMaskInt(SD_DATA_TO);
    OS_piInterEnable(intLevel);

    saveReq.PageId = PageId;
    saveReq.PageInfo = PageInfo;

    /* force the file id to FILE1 for synchronize both files                 */
    // if (FileId == FS_HK)
    //    FileId = FS_FILE1;
    saveReq.FileId = FileId;

    if(OS_piMsgQueueSend(SAVE_MBOX, &saveReq, sizeof(saveReq)) != SUCCESSFUL)
    {
      status = FT_TOOMANYREQUESTS;
    }

    /* Re-enable ISR that access the store queue data structures */
    OS_piInterDisable(&intLevel);
    SD_piUnMaskInt(SD_DATA_TO);
    OS_piInterEnable(intLevel);
  }
  else 
      status = FT_STOREDISABLED;

  return (status);
}

/*****************************************************************************/
/* @Function: FT_opPendingSaveRequests                                       */
/* @Purpose :                                                                */
/*  This function returns the number of Save Request pending                 */
/*                                                                           */
/* @@                                                                        */
/* @Parameter Name      @Mode   @Description                                 */
/* @@                                                                        */
/*****************************************************************************/

status_code FT_opPendingSaveRequests(UINT32* counter)
{
  return OS_piMessageQueueGetNumberPending_INFN (SAVE_MBOX,
                                                 counter);  
}


/*****************************************************************************/
/* @Function: FT_opGetCMDWErrorCounter                                       */
/* @Purpose :                                                                */
/*  This function returns the number of write errors towards the CMD I/F     */
/*                                                                           */
/* @@                                                                        */
/* @Parameter Name      @Mode   @Description                                 */
/* @@                                                                        */
/*****************************************************************************/

void FT_opGetCMDWErrorCounter(UINT32* Counter)
{
unsigned int intLevel;

  OS_piInterDisable(&intLevel);
  *Counter = FT_RWChannel.CMDWriteFail;
  OS_piInterEnable(intLevel);
}

/*****************************************************************************/
/* @Function: FT_opWriteEOT                                                  */
/* @Purpose :                                                                */
/*  This function is called by the WPBUS EOT interrupt and closes the store  */
/*  of a single SRAM page. If the save requests queue is not empty then the  */
/*  new SRAM page store is started                                           */
/* @@                                                                        */
/* @Parameter Name      @Mode   @Description                                 */
/* @@                                                                        */
/*****************************************************************************/

void FT_opWriteEOT(void)
{
unsigned int intLevel;
UINT32 writeAddr;
UINT32 writeSize;
FT_SAVEREQUEST saveReq;
BOOL  Done = FALSE;
UINT32 reqSize;
UINT32 algn;

/* Clear the WEOT interrupt */

 SD_piClearInt(SD_WPB_EOT);
 ERC32_Clear_interrupt(ERC32_INTERRUPT_EXTERNAL_4);

  /* Check if the store channel is enabled */
  if(FT_RWChannel.StoreEnable != FT_STR_NONE)
  {
     /* Notify the SRAMPageManager that a SRAM page was saved and can be reused */
     PM_piPageWasSaved(FT_RWChannel.FileId);
     /* Tell the FileManager to finalize the new file info                      */
     FS_piUpdateFile();
     /* Free the store channel                                                  */
     FT_RWChannel.SaveInProgress = FALSE;

  }
  else
  {
    /* Unespected WPBUS Write EOT             */
    /*@LOG LOG_INFN HA_piLogHistoryEntry10(HA_E10_SW_SM,HA_E10_UNESPECTED_WPBEOT,HA_E10_REP2_NULL); */
    LU_INFN_LOG(LU_CRITICAL,LU_MASK(__FILEID__),__FILEID__,__LINE__,HA_E10_REP2_NULL);
  }
  LU_UART_CR('F');
  /* wake up the File Manager Task for an other store                        */
  OS_piResourceRelease ( FT_RES );     
}

/*****************************************************************************/
/* @Function: FT_opReadEOT                                                   */
/* @Purpose :                                                                */
/*  This function is called by the RPBUS EOT interrupt and signals the end   */
/*  of a single sector transfer to the TAM I/F. If the there are some more   */
/*  sector left than a new transfer is started.                              */
/* @@                                                                        */
/* @Parameter Name      @Mode   @Description                                 */
/* @@                                                                        */
/*****************************************************************************/

void FT_opReadEOT(void)
{
  unsigned int intLevel,code;
  FS_SECT_DESCR sectorInfo;
  MsgTsk  Msg;
  //int     led [4] = {0x4, 0xC, 0x4C, 0xCC};                                    // XXXDEBUG MASSIMO

  /* Clear the REOT interrupt   */
  SD_piClearInt(SD_RPB_EOT);
  ERC32_Clear_interrupt(ERC32_INTERRUPT_EXTERNAL_3);

  /*
    Start Download next sector.
  */
  
  FT_RWChannel.ReadSectors++;
  /* Retrive the info of the next sector to be downloaded   */
  FS_piGetNextSector(&sectorInfo);
  /* Program the DRAMMA with the address of the next sector */
  FD_piDrammaWrWPBUSReg(FT_RWChannel.ActiveModule, FD_RADDR1_WPBUS, sectorInfo.SectAddr);
  FD_piSetBlockLength         (FT_SECTSIZE / FT_SAMPLESIZE);
  FD_piStartTransferFromMemory(FT_RWChannel.ActiveModule, TRUE);
  
  //---------  


//   /* Playback Automa states     */
//   switch(FT_RWChannel.PlayBackStatus) {
//     /* The playback is running  */
//     case FT_RUN: {
//       FT_RWChannel.ReadSectors++;

//       //TM_piSendTC (TM_DBL_CMD, led[FT_RWChannel.ReadSectors - 1]);             // XXXDEBUG MASSIMO

//       /* Retrive the info of the next sector to be downloaded   */
//       FS_piGetNextSector(&sectorInfo);
//       /* Program the DRAMMA with the address of the next sector */
//       FD_piDrammaWrWPBUSReg(FT_RWChannel.ActiveModule, FD_RADDR1_WPBUS, sectorInfo.SectAddr);

//       if(!sectorInfo.LastSectFlag) {
//         /* If no LSF reached then start a new transfer          */
    
// 	// XXXDEBUG MASSIMO BEGIN -------------------------------------------------------------------------------------------------------------------
// 	// per consentire il download di settori da 1024*1015 byte, abbiamo aggiunto la seguente istruzione e cambiato quella successiva

// 	FD_piSetBlockLength         (FT_SECTSIZE / FT_SAMPLESIZE);
// 	FD_piStartTransferFromMemory(FT_RWChannel.ActiveModule, TRUE);   // FD_piStartTransferFromMemory(FT_RWChannel.ActiveModule, FALSE);
// 	// XXXDEBUG MASSIMO END ---------------------------------------------------------------------------------------------------------------------------------------------------------
//       }
//       else {
//         /* If LSF was reached then set the last sector length   */
//         /* without starting a new transfer                      */
        
// 	FD_piSetBlockLength         (FT_SECTSIZE / FT_SAMPLESIZE);       	// XXXDEBUG MASSIMO FD_piSetBlockLength(sectorInfo.LastSectLength);

// 	// XXXDEBUG MASSIMO BEGIN -------------------------------------------------------------------------------------------------------------------
// 	/*
// 	  in order to fix the "End of 1-MB gap problem" we have commented next line and added the subsequent two lines.
// 	  ( view in file FT_MMSUManager_in.c function FT_ifStartDownlink the change 
// 	  indroduced by zulianello@laben in his visit in Roma, 28.07.2003)
// 	*/

// 	// FT_RWChannel.PlayBackStatus = FT_LSF;
// 	FT_RWChannel.PlayBackStatus = FT_LST;
// 	FD_piStartTransferFromMemory(FT_RWChannel.ActiveModule, TRUE);
// 	// XXXDEBUG MASSIMO END ---------------------------------------------------------------------------------------------------------------------------------------------------------
//       }
//     } break;
//   case FT_LSF: {
//       /* A LSF was perviously reached so do nothing but start a new transfer */
//       FT_RWChannel.PlayBackStatus = FT_LST;
//       FD_piStartTransferFromMemory(FT_RWChannel.ActiveModule, TRUE);
//       FT_RWChannel.ReadSectors++;
//     } break;
//     case FT_LST: {
//       /* The last sector was transfered so disable playback related Interrupts  */
//       /* and close the read channel                                             */
//       OS_piInterDisable(&intLevel);
//       SD_piMaskInt(SD_RPB_EOT);
//       OS_piInterEnable(intLevel);
//       FT_RWChannel.PlayBackStatus = FT_END;
//       FT_RWChannel.ReadSectors++;
//       FT_ifDownLinkClose(&FT_RWChannel);

//       // XXXDEBUG MASSIMO BEGIN -------------------------------------------------------------------------------------------------------------------
//       // invio dell'evento di fine DOWNLOAD

//       //TM_piSendTC (TM_DBL_CMD, led[FT_RWChannel.ReadSectors - 1]);             // XXXDEBUG MASSIMO

//       TM_piSendTC      (TM_HL_CMD_24, 0x1);
//       LU_INFN_LOG(LU_WARNING,0xffffffff,__FILEID__,__LINE__,FT_task2notify_EOD);
//       code=OS_piEventSend   (FT_task2notify_EOD, OS_EVENT_END_OF_DOWNLINK);
//       LU_INFN_LOG(LU_WARNING,0xffffffff,__FILEID__,__LINE__,FT_task2notify_EOD);
//       LU_INFN_LOG(LU_WARNING,0xffffffff,__FILEID__,__LINE__,code);
//       // XXXDEBUG MASSIMO END   -------------------------------------------------------------------------------------------------------------------
//     } break;
//     default:{
//       /* Unespected RPBUS Read EOT             */
//       HA_piLogHistoryEntry10(HA_E10_SW_SM,HA_E10_UNESPECTED_RPBEOT,HA_E10_REP2_NULL);
//     }
//   }
}

/*****************************************************************************/
/* @Function: FT_opMemModuleStat                                             */
/* @Purpose :                                                                */
/*  This function return a 16 bit word containing the status of the memory   */
/*  modules as described in RTF Data Area Layout                             */
/* @@                                                                        */
/* @Parameter Name      @Mode   @Description                                 */
/*  status_code          OUT     status of the operation                     */
/*  PtrModStat           OUT     modules status word                         */
/* @@                                                                        */
/*****************************************************************************/

void FT_opMemModuleStat(UINT16* PtrModStat)
{
UINT16 ModStat = 0x0000;

  /* Retrive the mass memory modules status for the RTF telemetry */
  if(FT_MMSUStatus.Module[FT_MEM_MOD_1].Column[FT_SPARE_COL] != FT_COLUMN_OFF)
    ModStat |= FT_RTF_MOD1_NOSPARE;
  if(FT_MMSUStatus.Module[FT_MEM_MOD_1].Mode != FT_MODE_MEM_MOD_OFF)
    ModStat |= FT_RTF_MOD1_ON;
  if(FT_MMSUStatus.Module[FT_MEM_MOD_2].Column[FT_SPARE_COL] != FT_COLUMN_OFF)
    ModStat |= FT_RTF_MOD2_NOSPARE;
  if(FT_MMSUStatus.Module[FT_MEM_MOD_2].Mode != FT_MODE_MEM_MOD_OFF)
    ModStat |= FT_RTF_MOD2_ON;
  if(FT_MMSUStatus.Module[FT_MEM_MOD_1].State == FT_STATE_MOD_FAIL)
    ModStat |= FT_RTF_MOD1_NOTWORK;
  if(FT_MMSUStatus.Module[FT_MEM_MOD_2].State == FT_STATE_MOD_FAIL)
    ModStat |= FT_RTF_MOD2_NOTWORK;
  *PtrModStat = ModStat;
}

/*****************************************************************************/
/* @Function: FT_opChangeAcqMode                                             */
/* @Purpose :                                                                */
/*  This function is used to switch between the three possible acquisition   */
/*  type.                                                                    */
/* @@                                                                        */
/* @Parameter Name      @Mode   @Description                                 */
/*  FT_CHACQ_RESULT      OUT     Return code                                 */
/*  mode                 IN      Acquisition mode                            */
/* @@                                                                        */
/*****************************************************************************/

FT_CHACQ_RESULT FT_opChangeAcqMode(SM_ACQMODE mode)
{
FT_CHACQ_RESULT status = FT_CHACQ_OK;

  if(mode < SM_MAXMODES)
  {
    /* Stop ongoing acquisition               */
    PM_pi_SetAcqMode(SM_IDLE);
    /* Disable the store channel              */
    FT_ifDisableStore(&FT_RWChannel, TRUE);
    /* Enable the Store channel               */
    FT_ifEnableStore(&FT_RWChannel);
    /* Start the acquisition in the new mode  */
    PM_pi_SetAcqMode(mode);
  }
  else
  {
    status =  FT_CHACQ_WRONGMODE;
  }
  return (status);
}

/*****************************************************************************/
/* @Function: FT_opChangeOpMode                                              */
/* @Purpose :                                                                */
/*  The function performs all the operations necessary to switch the system  */
/*  operational status                                                       */
/*                                                                           */
/* @@                                                                        */
/* @Parameter Name      @Mode   @Description                                 */
/*  FT_CHMODE_RESULT    OUT      Return code                                 */
/* @@                                                                        */
/*****************************************************************************/

FT_CHMODE_RESULT FT_opChangeOpMode(MC_STATE state)
{
FT_CHMODE_RESULT status = FT_CHMODE_OK;
UINT32 ModeLog;

  /* Set the system state   */
  switch(state) {
    /* Enter the Maintenance operative mode */
    case MC_MAINTENANCE_STATE: {
#ifndef SIMULATOR
      /* Stop any ongoing downlink        */
      FT_ifDownlinkAbort(&FT_RWChannel);
#endif 
      /* Stop any ongoing acquisition     */
      PM_pi_SetAcqMode(SM_IDLE);
#ifndef SIMULATOR
      /* Stop any ongoing store operation */
      FT_ifDisableStore(&FT_RWChannel,TRUE);
#endif
      /* Reinit the SRAMPageManager and   */
      /* The Read/Write channel           */
      PM_piSRAMPageManagerInit(FALSE);
#ifndef SIMULATOR
      FT_ifRWChannelInit(&FT_RWChannel,
                          FT_RWChannel.ActiveModule,
                          FT_RWChannel.PtrModuleStatus);
#endif
      ModeLog = HA_E0_MAINTENANCE;
    } break;
    case MC_ACTIVE_STATE: {
      /* Reset the Filesystem             */
      // FS_piInitFileSystem();
      /* Reinit the SRAMPageManager and   */
      /* The Read/Write channel           */
      PM_piSRAMPageManagerInit(FALSE);
      FT_ifRWChannelInit(&FT_RWChannel,
			 FT_RWChannel.ActiveModule,
			 FT_RWChannel.PtrModuleStatus);
      FT_ifEnableStore(&FT_RWChannel);
      // PM_pi_SetAcqMode(SM_IDLE);
      ModeLog = HA_E0_ACTIVE;
    } break;
  }
  /*========= Entry 0 Log in History Area ==========*/
  /*@LOG LOG_INFN HA_piLogHistoryEntry0(HA_E0_STARTING,ModeLog,0); */
  LU_INFN_LOG(LU_CRITICAL,LU_MASK(__FILEID__),__FILEID__,__LINE__,0xbabe);
  return (status);
}

/*****************************************************************************/
/* @Function: FT_opModuleTest                                                  */
/* @Purpose :                                                                */
/*  The function sends a message to the MMSUManager task in order to start   */
/*  the memory module test                                                   */
/*                                                                           */
/* @@                                                                        */
/* @Parameter Name      @Mode   @Description                                 */
/* @@                                                                        */
/*****************************************************************************/

void FT_opModuleTest(void)
{
MsgTsk sndMsgMCMD;

  sndMsgMCMD.Code = FT_MEM_MODULE_TEST;
  FT_piSndMsgMMSUManager(&sndMsgMCMD);
}

/*****************************************************************************/
/* @Function: FT_opPacket2MMSU                                               */
/* @Purpose :                                                                */
/*  This function is used to store a packet in Memory Module or for send a   */
/*  packet on CMD I/F                                                        */
/*                                                                           */
/* @@                                                                        */
/* @Parameter Name      @Mode   @Description                                 */
/*  PtrRWChannel         IN      Pointer to the RWchannel manage structure   */
/* @@                                                                        */
/*****************************************************************************/

void FT_opPacket2MMSU (FT_SAVEREQUEST saveReq)
{
  UINT32 writeSize;
  UINT32 writeAddr;
  UINT32 pktSize;
  BYTE* target;
  UINT32 intLevel;
  
  OS_piResourceObtain  ( FT_RES, WAIT, NO_TIMEOUT);

  /* Disable ISR that access the store queue data structures */
  OS_piInterDisable(&intLevel);
  SD_piMaskInt(SD_WPB_EOT);
  OS_piInterEnable(intLevel);

  /* Start a new data transfer as in the SavePage function                  */
  FT_RWChannel.SaveInProgress = TRUE;
  FT_RWChannel.CurrentPageId = saveReq.PageId;
  writeSize = (saveReq.PageInfo+1) - ((UINT32)saveReq.PageId * SM_SRAMPAGESIZE);

  if(FS_piWriteFile(saveReq.FileId, writeSize, &writeAddr) != FS_SUCCESS) 
    {
      PM_piPageWasSaved(saveReq.FileId);
      FT_RWChannel.SaveInProgress = FALSE;
      OS_piResourceRelease ( FT_RES );
      
      // LU_UART_CR('r');
    }
  else /* SUCCESS */
    {      
      if(saveReq.FileId < FS_REGFILES) 
	{
	  LU_UART_CR('S');

	  FT_RWChannel.FileId = saveReq.FileId;	   
	  SD_piSetWPBUSReadPage(FT_RWChannel.CurrentPageId);
	  SD_piSetWPBUSReadParams(saveReq.PageInfo);
	  FD_piDrammaWrWPBUSReg(FT_RWChannel.ActiveModule, FD_WADDR_WPBUS, writeAddr);
	  FD_piStartTransferToMemory(FT_RWChannel.ActiveModule);
	}
      
      if(saveReq.FileId == FS_CMD)
	{
	  LU_UART_CR('C');
	  SD_piSetCMDBUSReadPage(FT_RWChannel.CurrentPageId);
	  SD_piSetCMDBUSReadParams(saveReq.PageInfo);
	  SD_piStartTransferToCMD();
	  /* Free the store channel                                */
	  FT_RWChannel.SaveInProgress = FALSE;	  
	  /* wake up the File Manager Task for an other store                        */
	  OS_piResourceRelease ( FT_RES );     
	}

      if(saveReq.FileId == FS_ERC32)
	{
	  /* Evaluate the packet size in bytes */
	  pktSize = (saveReq.PageInfo+1) - (UINT32)(saveReq.PageId * SM_SRAMPAGESIZE);
	  /* Init the source hbus I/O SRAM address */
	  SD_piSetSRAMRWAddress(saveReq.PageId * SM_SRAMPAGESIZE);
	  /* Init the destination RAM address*/
	  target = (BYTE *)writeAddr;
	  /* Copy the packet */
	  while(pktSize--)
	    {
	      *target = (BYTE)SD_piReadSRAM();
	      target++;
	    }
	  PM_piPageWasSaved(FS_ERC32);
	  /* Free the store channel                                */
	  FT_RWChannel.SaveInProgress = FALSE;
	  /* wake up the File Manager Task for an other store                        */
	  LU_UART_CR('M');
	  OS_piResourceRelease ( FT_RES );     
	}
    }
  /* Re-enable ISR that access the store queue data structures */
  OS_piInterDisable(&intLevel);
  SD_piUnMaskInt(SD_WPB_EOT);
  OS_piInterEnable(intLevel);
}


// XXXDEBUG MASSIMO BEGIN -------------------------------------------------------------------------------------------------------------------------------------------------------

BOOL FT_opSaveInProgress (void)
{
  return  FT_RWChannel.SaveInProgress;
}

BOOL FT_opDownloadInProgress (void)
{
  return  (FT_RWChannel.PlayBackStatus != FT_END);
}

  // per definire il task a cui mandare la notifica di fine DOWNLOAD

void FT_opSetTask2Notify_EOD  (UINT32 task)
  { 
    FT_task2notify_EOD = task;
  }



