#ident "$Id: card-backup-api.c,v 1.32 2007/07/02 23:42:51 tong Exp $"
/*
 *               Copyright (C) 2006, BroadOn Communications Corp.
 *
 *  These coded instructions, statements, and computer programs contain
 *  unpublished  proprietary information of BroadOn Communications Corp.,
 *  and  are protected by Federal copyright law. They may not be disclosed
 *  to  third  parties or copied or duplicated in any form, in whole or in
 *  part, without the prior written consent of BroadOn Communications Corp.
 *
 */

/*
 * Implements the backup memory functions for emulating
 * a DS card using a NetCard.
 * 
 */

#include <nitro.h>

#include "card-api.h"
#include "card-lock.h"
#include "es.h"
#include "netcard/fs.h"
#include "string.h"

#ifndef MIN
#define MIN(a, b)       ((a) <= (b) ? (a) : (b))
#endif

#include "ds-debug.h"


/*
 * Note: Most Nitro OS sys calls don't return anything, thus you won't
 *       see the return value being checked
 */

/*
 * The CARD_IsBackupXXXX() functions are defined in
 * NitroSDK/include/nitro/card/XXXX.h.  The functions call
 * CARD_GetCurrentBackupType().
 *
 * Similarly, NitroSDK/include/nitro/card/XXXX.h defines:
 *       CARD_ReadXXXX                -> CARD_ReadBackup()
 *       CARD_ReadXXXXAsync           -> CARD_ReadBackupAsync()
 *       CARD_VerifyXXXX              -> CARD_VerifyBackup()
 *       CARD_VerifyXXXXAsync         -> CARD_VerifyBackupAsync()
 *       CARD_VerifyXXXXAsync         -> CARD_VerifyBackupAsync()
 *
 *   For Flash:
 *       CARD_WriteXXXX               -> CARD_WriteBackup()
 *       CARD_WriteXXXXAsync          -> CARD_WriteBackupAsync()
 *       CARD_WriteAndVerifyXXXX      -> CARD_WriteAndVerifyBackup()
 *       CARD_WriteAndVerifyXXXXAsync -> CARD_WriteAndVerifyBackupAsync()
 * 
 *   For EEPROM and FRAM:
 *       CARD_WriteXXXX               -> CARD_ProgramBackup()
 *       CARD_WriteXXXXAsync          -> CARD_ProgramBackupAsync()
 *       CARD_WriteAndVerifyXXXX      -> CARD_ProgramAndVerifyBackup()
 *       CARD_WriteAndVerifyXXXXAsync -> CARD_ProgramAndVerifyBackupAsync()
 *
 *    Then, the functions like CARD_WriteBackup are changed into calls
 *    to CARDi_RequestStreamCommand in NITRO_SDK/include/card/backup.h
 */

static void CARDi_SetUpAndRunBackupOperation();
static BOOL CARDi_DoBackupOperation(cardCommand_t *CardCommand);

typedef enum FileStatus_t {
    FileInvalidStatus,
    FileOpenRead,               // Original file is opened read-only
    FileOpenWriteOrig,          // Reads and write go to the original file
    FileOpenWriteTemp,          // Reads and writes go to copy of file
    FileClosed
} FileStatus_t;

static IOSFd            BackupFileFd = -1;
static FileStatus_t     FileStatus = FileClosed;
static BOOL             CARDi_OpenBackupFileRead(const char* const backupFilePath);
static BOOL             CARDi_DoCardRead(), CARDi_DoCardWrite();
static BOOL             CARDi_DoCardVerify(const u8* const compareBuf,
                                     const u32 offset,
                                     const u32 length);
static ISFSError        CopyFile(const IOSFd sourceFd, const char* destPath);
static BOOL             CARDi_OpenBackupFileWrite();

/*
 * TRANSFER_SIZE is the size of the buffer used to copy a NetCard file
 * to another, and when verifying the contents of the emulated backup
 * memory
 */
#define         TRANSFER_SIZE   (4 * 1024)

/*
 * Put this on the heap, because stack space is quite limited
 */
static u8          TransferBuf[TRANSFER_SIZE];

typedef struct backupMemParams {
    // CARDBackupType is defined in NitroSDK/include/nitro/card
    CARDBackupType      type;
    u32                 memSize;
    u32                 pageSize;
    u32                 sectorSize;
} backupMemParams_t;

static backupMemParams_t        backupMemParams;

static void   CARDi_setInvalidBackup(backupMemParams_t *memParams);
void          CARDi_setInitialBackupType();
static BOOL   CARDi_DoNetCardWrite(const u32 srcAddr, s32 destAddr,
                             const u32 length);
static BOOL   CARDi_RevertBackupToOriginal();

/* ------------------------------------------------------------------------ */
/*                    GENERAL BACKUP FUNCTIONS                              */
/* ------------------------------------------------------------------------ */

/*
 * Lock the emulated bus.  This operation is done only to more closely
 * emulate the behavior of the real DS CARD library, which does need
 * to lock a real bus.
 */
void
CARD_LockBackup(u16 lock_id)
{
    MARK;
    SDK_ASSERT(CARD_IsAvailable());
    CARDi_LockResource(lock_id, CARD_TARGET_BACKUP);
}
/* ------------------------------------------------------------------------ */

/*
 * Does the following:
 *      1. Closes the SFS file corresponding to the backup memory
 *         If the current file is the temporary copy made for writes,
 *         copy it back to the original file location.
 *      2. Unlocks the emulated bus.
 */
void
CARD_UnlockBackup(u16 lock_id)
{
    ISFSError   error;

    MARK;

    SDK_ASSERT(CARD_IsAvailable());
    SDK_ASSERT(cardi_common.lock_target == CARD_TARGET_BACKUP);
    switch (FileStatus) {

        case FileOpenRead:
            error = ISFS_Close(BackupFileFd);
            if (error == ISFS_ERROR_INVALID) {
                CARDi_FatalError("Invalid backup file descriptor on file close (status = FileOpenRead");
            }
            /*
             * Ignore other errors - calling software doesn't look
             * for errors on Unlock
             */
            break;

        case FileOpenWriteOrig:
            error = ISFS_Close(BackupFileFd);
            if (error == ISFS_ERROR_INVALID) {
                CARDi_FatalError("Invalid backup file descriptor on file close (status = FileOpenRead");
            }
            else if (error != ISFS_ERROR_OK) {
                /*
                 * Fatal error here, because it is possible that the data
                 * written has been corrupted and there is no way to
                 * signal an error to the caller.
                 */
                CARDi_FatalError("Closing of file opened for write failed");
            }
            break;

        case FileOpenWriteTemp:
            error = ISFS_Close(BackupFileFd);
            if (error == ISFS_ERROR_OK) {
                char        tempFilePath[ISFS_PATH_MAXLEN];
                char        origFilePath[ISFS_PATH_MAXLEN];

                sprintf(origFilePath,
                        "%s/%s", TitleDataDir, BACKUP_MEM_FILE_NAME);
                sprintf(tempFilePath, "%s/%s",
                        TEMP_DIRECTORY_NAME, BACKUP_MEM_FILE_NAME);
                error = ISFS_Rename( (const u8 *) tempFilePath,
                                     (const u8 *) origFilePath);
                if (error != ISFS_ERROR_OK) {
                    CARDi_FatalError("Rename of temporary backup file to actual file failed");
                }
            }
            else if (error == ISFS_ERROR_INVALID) {
                CARDi_FatalError("Invalid backup file descriptor on file close (status = FileOpenRead");
            }
            else {
                /*
                 * Fatal error here, because it is possible that the data
                 * written has been corrupted and there is no way to
                 * signal an error to the caller.
                 */
                CARDi_FatalError("Closing of file opened for write failed");
            }
            break;

        case FileClosed:
            break;

        case FileInvalidStatus:
            CARDi_FatalError("Invalid file status");
            break;

        default:
            CARDi_FatalError("Default case reached");
            break;
    }
    FileStatus = FileClosed;
    BackupFileFd = -1;

    CARDi_UnlockResource(lock_id, CARD_TARGET_BACKUP);
} // CardUnlockBackup

/* ------------------------------------------------------------------------ */

/*
 * This function is used by the application to tell the CARD library
 * what kind of backup memory is attached.
 *
 * Note: All calls to CARD_IdentifyBackup return true, no matter what
 * backup memory is attached.  See message in nitro.general newsgroup
 * on Warioworld dated 7/21/06
 */

BOOL
CARD_IdentifyBackup(CARDBackupType backupType)
{
    // FIXME - Find out if this call is needed
    // SDK_USING_BACKUP();

    /*
    printf ("(%s) enter: backupMemParams.type = 0x%x\n",
             __FUNCTION__, backupMemParams.type);
    */
    MARK;
    if (backupType == CARD_BACKUP_TYPE_NOT_USE)
    {
        OS_TPanic("cannot specify CARD_BACKUP_TYPE_NOT_USE.");
    }
    SDK_ASSERT(CARD_IsAvailable());
    SDK_ASSERTMSG((CARDi_GetTargetMode() == CARD_TARGET_BACKUP),
                  "CARD_IdentifyBackup() must be called with CARD locked by CARD_LockBackup()!");
    CARD_CheckEnabled();

    /*
     * Do CARD_WaitIdle even if a request is not necessary in order to
     * more closely duplicate
     * the way it is done on real backup cards.
     * Following 3 lines are same as DS CARD library call
     * CARDi_WaitTask(p, NULL, NULL)
     */
    CARD_WaitIdle();
    CardCommand.callbackFunc = NULL;
    CardCommand.callbackArg  = NULL;

    CardCommand.result = CARD_RESULT_SUCCESS;           // Default value

    if (backupType != CARD_BACKUP_TYPE_NOT_USE) {
        int     device;

        // Code derived from CARDi_IdentifyBackupCore
        backupMemParams.memSize = (u32) (1 << ((backupType >> CARD_BACKUP_TYPE_SIZEBIT_SHIFT) &
                                         CARD_BACKUP_TYPE_SIZEBIT_MASK));

        device = (   (backupType >> CARD_BACKUP_TYPE_DEVICE_SHIFT)
                   & CARD_BACKUP_TYPE_DEVICE_MASK);

        if (device == CARD_BACKUP_TYPE_DEVICE_EEPROM) {
            /*
             * NOTE: If you change the code in the switch statement,
             *       look at the switch
             *       statement in CARDi_setInitialBackupType
             */
            switch (backupMemParams.memSize) {

            case 0x000200:        // CARD_BACKUP_TYPE_EEPROM_4KBITS
                backupMemParams.pageSize   = 0x10;
                backupMemParams.sectorSize = backupMemParams.pageSize;
                break;

            case 0x002000:        // CARD_BACKUP_TYPE_EEPROM_64KBITS
                backupMemParams.pageSize   = 0x20;
                backupMemParams.sectorSize = backupMemParams.pageSize;
                break;

            case 0x010000:        // CARD_BACKUP_TYPE_EEPROM_512KBITS
                backupMemParams.pageSize   = 0x80;
                backupMemParams.sectorSize = backupMemParams.pageSize;
                break;

            default:
                CARDi_setInvalidBackup(&backupMemParams);
                break;
            } // switch
        }  // EEPROM
        else if (device == CARD_BACKUP_TYPE_DEVICE_FLASH) {
            switch (backupMemParams.memSize) {

            case 0x040000:        // CARD_BACKUP_TYPE_FLASH_2MBITS
            case 0x080000:        // CARD_BACKUP_TYPE_FLASH_4MBITS
            case 0x100000:        // CARD_BACKUP_TYPE_FLASH_8MBITS
            case 0x200000:        // CARD_BACKUP_TYPE_FLASH_16MBITS
            case 0x800000:        // CARD_BACKUP_TYPE_FLASH_64MBITS
                backupMemParams.pageSize   = 0x00100;
                backupMemParams.sectorSize = 0x10000;
                break;

            default:
                CARDi_setInvalidBackup(&backupMemParams);
                break;
            } // switch
        }  // FLASH
        else if (device == CARD_BACKUP_TYPE_DEVICE_FRAM) {
            switch (backupMemParams.memSize) {

            case 0x002000:        // #CARD_BACKUP_TYPE_FRAM_64KBITS
            case 0x008000:        // #CARD_BACKUP_TYPE_FRAM_64KBITS
                 backupMemParams.pageSize = backupMemParams.memSize;
                 backupMemParams.sectorSize = backupMemParams.memSize;
                 break;

            default:
                CARDi_setInvalidBackup(&backupMemParams);
                break;
            } // switch
        }  // FRAM
        else {
            CARDi_setInvalidBackup(&backupMemParams);
        }  // EEPROM
    }
    CurrentThread = OS_GetCurrentThread();

    /*
     * FIXME - Should we do a read here to determine if a NetCard is readable?
     */
    backupMemParams.type = backupType;
    /*
    printf ("(%s) exit: backupMemParams.type = 0x%x\n",
             __FUNCTION__, backupMemParams.type);
    */
    CARDi_EndCardAccess(TRUE);
    return(CardCommand.result == CARD_RESULT_SUCCESS);
} // CARD_IdentifyBackup
/* ------------------------------------------------------------------------ */

static void
CARDi_setInvalidBackup(backupMemParams_t *memParams)
{
    memParams->type    = CARD_BACKUP_TYPE_NOT_USE;
    memParams->memSize = 0;
    CardCommand.result = CARD_RESULT_UNSUPPORTED;
}
/* ------------------------------------------------------------------------ */

CARDBackupType
CARD_GetCurrentBackupType(void)
{
    return(backupMemParams.type);
}
/* ------------------------------------------------------------------------ */
u32
CARD_GetBackupSectorSize(void)
{
    return(backupMemParams.sectorSize);
}
/* ------------------------------------------------------------------------ */

u32
CARD_GetBackupTotalSize(void)
{
    return(backupMemParams.memSize);
}
/* ------------------------------------------------------------------------ */

u32
CARD_GetBackupPageSize(void)
{
    return(backupMemParams.pageSize);
}
/* ------------------------------------------------------------------------ */

BOOL
CARD_TryWaitBackupAsync(void)
{
    return(CARD_WaitDone());
}
/* ------------------------------------------------------------------------ */
BOOL
CARD_WaitBackupAsync(void)
{
    return(CARD_WaitDone());
}
/* ------------------------------------------------------------------------ */
void
CARD_CancelBackupAsync(void)
{
    OSIntrMode  curMode;

    curMode = OS_DisableInterrupts();
    CardStatus |= CARD_CANCEL_BACKUP_OP;
    OS_RestoreInterrupts(curMode);
}
/* ------------------------------------------------------------------------ */

/* ------------------------------------------------------------------------ */
/*                    BACKUP DEVICE FUNCTIONS                               */
/* ------------------------------------------------------------------------ */

/*
 * Most of the backup device functions are implemented with calls to
 * CARDi_RequestStreamCommand
 */


/*---------------------------------------------------------------------------*
  Name:         CARDi_RequestStreamCommand

  Description:  Issues request for command to transfer data.

  Arguments:    src        Transfer origin offset or memory address
                dst        Transfer destination offset or memory address
                len        Transfer size
                callback   Completion callback (NULL if not used)
                arg        Argument of completion callback (ignored if not used)
                is_async   If async operation was specified, TRUE
                req_type   Command request type
                req_retry  Max. no. of retries when command request fails
                req_mode   Command request operation mode

  Returns:      If action is successful, TRUE.
 *---------------------------------------------------------------------------*/
BOOL CARDi_RequestStreamCommand(u32 src, u32 dst, u32 len,
                                MIDmaCallback callback, void *arg,
                                BOOL is_async, CARDRequest req_type,
                                int req_retry, CARDRequestMode req_mode)
{

    // FIXME - Find out if this call is needed
    // SDK_USING_BACKUP();

    MARK;
    SDK_ASSERT(CARD_IsAvailable());
    SDK_ASSERT(CARD_GetCurrentBackupType() != CARD_BACKUP_TYPE_NOT_USE);
    SDK_ASSERTMSG(CARDi_GetTargetMode() == CARD_TARGET_BACKUP,
                  "[CARD] current locking target is not backup.");

    CARD_WaitIdle();
    CardCommand.callbackFunc = callback;
    CardCommand.callbackArg  = arg;

    CardCommand.srcAddr    = src;
    /* Destination buffer on read; Destination address on write */
    CardCommand.destAddr   = dst;  
    CardCommand.length     = len;
    CardCommand.req_type   = req_type;
    CardCommand.req_retry  = req_retry;
    CardCommand.req_mode   = req_mode;

    MARK;

    if (is_async)
    {
        MARK;
        CARDi_AssignAsyncWork(CARDi_SetUpAndRunBackupOperation);
        return(TRUE);
    }
    else
    {
        MARK;
        CurrentThread = OS_GetCurrentThread();
        CARDi_SetUpAndRunBackupOperation();
        return (CardCommand.result == CARD_RESULT_SUCCESS);
    }
}

/* ------------------------------------------------------------------------ */

/*
 * Check if there has been a cancel request.
 * If not, do the backup operation.
 * 
 * Roughly equivalent to CARDi_RequestStreamCommandCore, but much
 * simpler because SFS library handles cache invalidations, caching
 * of flash content, and using the proper block size for
 * reading/writing/erasing
 */

static void
CARDi_SetUpAndRunBackupOperation()
{
    cardCommand_t         CommandCopy;
    BOOL                  success = FALSE;

    // FIXME - Find out if this call is needed
    // SDK_USING_BACKUP();

    CommandCopy = CardCommand;

    MARK;
    /* Stops here if there has been a cancel request*/
    if ((CardStatus & CARD_CANCEL_BACKUP_OP) != 0)
    {
        CardStatus &= ~CARD_CANCEL_BACKUP_OP;
        CardCommand.result = CARD_RESULT_CANCELED;
        success = FALSE;
    }
    else {
        /* Send request */
        if (CARDi_DoBackupOperation(&CardCommand)) {
            success = TRUE;
        }
        else {
            success = FALSE;
        }
    }
    CARDi_EndCardAccess(TRUE);
} // CARD_SetupAndRunBackupOperation

/* ------------------------------------------------------------------------ */

/*
 * Based upon the request type passed in, call internal function(s)
 * to satisfy the request.

 * Counterpart to CARDi_Request in DS CARD library.
 */
static BOOL
CARDi_DoBackupOperation(cardCommand_t *cardCommand)
{
    BOOL        retVal = TRUE;


    MARK;

    switch (cardCommand->req_type) {

    case CARD_REQ_INIT:
    case CARD_REQ_ACK:            
    case CARD_REQ_IDENTIFY:
    case CARD_REQ_READ_ID:
    case CARD_REQ_READ_ROM:
    case CARD_REQ_WRITE_ROM:
        break;                              /* No action */

    /* CardReadBackup, CardReadBackupAsync */
    case CARD_REQ_READ_BACKUP:
        retVal = CARDi_DoCardRead();
        break;
      
    case CARD_REQ_WRITE_BACKUP:   /* CARD_WriteBackup, Card_WriteBackupAsync */
    case CARD_REQ_PROGRAM_BACKUP: /* CARD_ProgramBackup, Card_ProgramBackupAsync */
        retVal = CARDi_DoCardWrite();
        if (retVal == TRUE
             && cardCommand->req_mode == CARD_REQUEST_MODE_SEND_VERIFY) {
            retVal = CARDi_DoCardVerify((const u8* const) cardCommand->srcAddr,
                                   cardCommand->destAddr, cardCommand->length);
        }
        break;

    case CARD_REQ_VERIFY_BACKUP:
        retVal = CARDi_DoCardVerify((const u8* const) cardCommand->srcAddr,
                              cardCommand->destAddr, cardCommand->length);
        break;

    case CARD_REQ_ERASE_PAGE_BACKUP:
    case CARD_REQ_ERASE_SECTOR_BACKUP:
    case CARD_REQ_ERASE_CHIP_BACKUP:
        CARDi_FatalError("Erase commands not implemented yet");
        break;

    default:
        CARDi_FatalError("Default case reached in CardDoBackupOperation");
        break;
    }
    return(retVal);
} // CARD_DoBackupOperation

/* ------------------------------------------------------------------------ */

/*
 * Read bytes from the backup file that emulates the 
 * RETURNS:
 *          TRUE -  if the read succeeded.  Also sets
 *                  CardCommand.result to CARD_RESULT_SUCCESS.
 *
 * Note that reads wrap around the end of the backup memory back to
 * the beginning.  In addition, source addresses given that are beyond the
 * end of the backup memory are treated as the address modulo the
 * size of the memory
 *    
 */
static BOOL
CARDi_DoCardRead()
{
    ISFSError   bytesRead, seekError;
    char        backupFilePath[ISFS_PATH_MAXLEN];
    s32         seekVal;
    u32         bytesLeftToRead, bytesToRead;
    u32         fileBytesRemaining;
    u8          *destPtr;

    if (backupMemParams.type == CARD_BACKUP_TYPE_NOT_USE) {
        CardCommand.result = CARD_RESULT_NO_RESPONSE;
        return(FALSE);
    }

    if (FileStatus == FileClosed) {
        /* The '+2' consists of 1 for the '/' and 1 for the NULL terminator */
        if (  strlen(TitleDataDir)
            + strlen(BACKUP_MEM_FILE_NAME)
            + 2                              >= ISFS_PATH_MAXLEN) {
            CARDi_FatalError("(CARDi_DoCardRead) Path name is too long");
        }
        sprintf(backupFilePath, "%s/%s", TitleDataDir, BACKUP_MEM_FILE_NAME);
        //printf ("%s: Opening file : %s\n", __FUNCTION__, backupFilePath);
        /* Note: CARDi_OpenBackupFileRead sets FileStatus on success */
        if (CARDi_OpenBackupFileRead(backupFilePath) == FALSE) {
            CardCommand.result = CARD_RESULT_ERROR;
            return(FALSE);
        }
    }
    else if (FileStatus == FileInvalidStatus) {
        CARDi_FatalError("(CARDi_DoCardRead) InvalidFileStatus");
    }
    /*
    printf ("%s: Reading %u bytes from 0x%x\n",
            __FUNCTION__, CardCommand.length, CardCommand.srcAddr);
    */

    seekVal = (s32) CardCommand.srcAddr & ((s32) backupMemParams.memSize - 1);

    seekError = ISFS_Seek(BackupFileFd, seekVal, IOS_SEEK_SET);
    if (seekError == ISFS_ERROR_INVALID) {
        CardCommand.result = CARD_RESULT_INVALID_PARAM;
        return(FALSE);
    }
    else if (seekError < 0) {
        CardCommand.result = CARD_RESULT_FAILURE;
        return(FALSE);
    }

    bytesLeftToRead    = CardCommand.length;
    fileBytesRemaining = backupMemParams.memSize - seekVal;
    destPtr            = (u8 *) CardCommand.destAddr;

    while (bytesLeftToRead > 0) {

        bytesToRead = MIN(bytesLeftToRead, fileBytesRemaining);

        bytesRead = ISFS_Read(BackupFileFd, destPtr, bytesToRead);

        if (bytesRead == bytesToRead) {         // Successful read!
            bytesLeftToRead    -= bytesRead;
            fileBytesRemaining -= bytesRead;
            destPtr            += bytesRead;

            if (fileBytesRemaining == 0) {
                fileBytesRemaining = backupMemParams.memSize;
                seekError = ISFS_Seek(BackupFileFd, 0, IOS_SEEK_SET);
                if (seekError == ISFS_ERROR_INVALID) {
                    CardCommand.result = CARD_RESULT_INVALID_PARAM;
                    return(FALSE);
                }
                else if (seekError < 0) {
                    CardCommand.result = CARD_RESULT_FAILURE;
                    return(FALSE);
                }
            }
        }
        else if (bytesRead == ISFS_ERROR_INVALID) {
            CardCommand.result = CARD_RESULT_INVALID_PARAM;
            return(FALSE);
        }
        else if (bytesRead < 0) {
            CardCommand.result = CARD_RESULT_FAILURE;
            return(FALSE);
        }
        else {                                  // Short read
            /*
            printf ("%s: Bytes read is %d; length = %u\n",
                    __FUNCTION__, bytesRead, CardCommand.length);
            */
            CardCommand.result = CARD_RESULT_FAILURE;
            return(FALSE);
        }
    }
#ifdef CARD_READ_DEBUG
    // DO NOT REMOVE - DO NOT REMOVE - DO NOT REMOVE - DO NOT REMOVE
    printf("!!! %s: MD5 Sum of %u bytes\n", __FUNCTION__, CardCommand.length);
    printMD5sum((void *) CardCommand.destAddr, CardCommand.length);
    printf("\n");
    printf("!!! %s: MD5 Sum of %u bytes\n", __FUNCTION__, CardCommand.length);
    // DO NOT REMOVE - DO NOT REMOVE - DO NOT REMOVE - DO NOT REMOVE
#endif
    CardCommand.result = CARD_RESULT_SUCCESS;
    return(TRUE);
} // DoRead

/* ------------------------------------------------------------------------ */

/*
 * Writes past the end of the emulated memory wrap around to the beginning,
 * just like they do on a real card.
 */
static BOOL
CARDi_DoCardWrite()
{
    BOOL        returnVal = FALSE;
    ISFSError   fsError;
    s32         seekVal, curDestAddr;
    /*
     * How many bytes are there from the current position in the
     * NetCard file to the end of the NetCard file
     */
    u32         fileBytesRemaining;
    u32         remainingLength;
    u32         curSrcAddr, bytesToWrite;

    MARK;
    /*
    printf ("%s:%d - backup memory type: %d; size: %u\n",
             __FUNCTION__, __LINE__, backupMemParams.type,
             backupMemParams.memSize);
    */
    if (backupMemParams.type == CARD_BACKUP_TYPE_NOT_USE) {
        CardCommand.result = CARD_RESULT_NO_RESPONSE;
        return(FALSE);
    }
    if (backupMemParams.memSize == 0) {
        ERROR("(%s:%d) %s: Backup memory present, but memory size is zero\n",
                __FILE__, __LINE__, __FUNCTION__);
        CardCommand.result = CARD_RESULT_ERROR;
        return(FALSE);
    }
    if (FileStatus == FileOpenRead) {
        MARK;
        fsError = ISFS_Close(BackupFileFd);
        if (fsError != ISFS_ERROR_OK) {
            CardCommand.result = CARD_RESULT_FAILURE;
            goto end;
        }
        FileStatus = FileClosed;
    }


    if (FileStatus == FileClosed) {
        MARK;
        /* CARDi_OpenBackupFileWrite sets FileStatus - DO NOT SET IT HERE */
        if (CARDi_OpenBackupFileWrite() == FALSE) {
            WARN("CARDi_OpenBackupFileWrite failed\n");
            CardCommand.result = CARD_RESULT_FAILURE;
            goto end;
        }
    }
    else if (FileStatus == FileInvalidStatus) {
        MARK;
        CARDi_FatalError("(CARDi_DoCardWrite) InvalidFileStatus");
    }
    MARK;

    if (FileStatus != FileOpenWriteOrig && FileStatus != FileOpenWriteTemp) {
        MARK;
        CARDi_FatalError("(CARDi_DoCardWrite) FileStatus has incorrect value");
    }

    /* Addresses greater than the size of the memory wrap around */
    seekVal = (s32) CardCommand.destAddr & ((s32) backupMemParams.memSize - 1);
    fsError = ISFS_Seek(BackupFileFd, (s32) seekVal, IOS_SEEK_SET);

    if (fsError == ISFS_ERROR_INVALID) {
        CardCommand.result = CARD_RESULT_INVALID_PARAM;
        ERROR("%s: (%s%d) ISFS_Seek failed\n", __FUNCTION__,
               __FILE__, __LINE__);
        goto end;
    }
    else if (fsError < 0) {
        CardCommand.result = CARD_RESULT_FAILURE;
        goto end;
    }

    remainingLength = CardCommand.length;

    curDestAddr = seekVal;
    curSrcAddr = CardCommand.srcAddr;

    fileBytesRemaining = backupMemParams.memSize - curDestAddr;

    /*
    printf ("Mem size %u; cur dest addr: %u\n",
             backupMemParams.memSize, curDestAddr);
    */
    // TODO (maybe) Eliminate writes which will be overwritten by
    //              another write.
    while (remainingLength > 0) {
        /*
        printf ("Remaining length: %u; fileBytesRemaining: %u\n",
                 remainingLength, fileBytesRemaining);
        */
        MARK;
        bytesToWrite = MIN(remainingLength, fileBytesRemaining);
        if (CARDi_DoNetCardWrite(curSrcAddr, curDestAddr, bytesToWrite) == FALSE) {
            goto end;
        }
        // printf ("bytesToWrite: %u\n", bytesToWrite);
        fileBytesRemaining -= bytesToWrite;
        remainingLength    -= bytesToWrite;
        curDestAddr        += bytesToWrite;
        curSrcAddr         += bytesToWrite;
        /* Wrap at end of backup file */
        if (fileBytesRemaining == 0) {
            fileBytesRemaining = backupMemParams.memSize;
            curDestAddr = 0;
        }
        fsError = ISFS_Seek(BackupFileFd, (s32) curDestAddr, IOS_SEEK_SET);
        if (fsError == ISFS_ERROR_INVALID) {
            CardCommand.result = CARD_RESULT_INVALID_PARAM;
            ERROR("%s: (%s%d) ISFS_Seek failed\n", __FUNCTION__, __FILE__, __LINE__);
            goto end;
        }
        else if (fsError < 0) {
            CardCommand.result = CARD_RESULT_FAILURE;
            goto end;
        }
    }
    returnVal = TRUE;
end:
    MARK;
    return(returnVal);
} // CARDi_DoCardWrite

/* ------------------------------------------------------------------------ */

/*
 * Do the actual write to the NetCard file.  This function assumes
 * that the backup file is open and has write access.
 */
static BOOL
CARDi_DoNetCardWrite(const u32 srcAddr, s32 destAddr, const u32 length)
{
    BOOL        returnVal = FALSE;
    ISFSError   fsError, bytesWritten;

    bytesWritten  = ISFS_Write(BackupFileFd, (u8 *) srcAddr, length);


    DEBUG("(%s:%d) bytes written: %d\n", __FUNCTION__, __LINE__, bytesWritten);
    if (bytesWritten == length) {
        CardCommand.result = CARD_RESULT_SUCCESS;
        returnVal = TRUE;
        goto end;
    }
    else if (bytesWritten == ISFS_ERROR_INVALID) {
        ERROR("(%s:%d) ISFS_Write failed\n", __FUNCTION__, __LINE__);
        CardCommand.result = CARD_RESULT_INVALID_PARAM;
        goto end;
    }
    else if (   bytesWritten == ISFS_ERROR_MAXBLOCKS 
             && FileStatus == FileOpenWriteTemp) {
        char                origFilePath[ISFS_PATH_MAXLEN];
        char                tempFilePath[ISFS_PATH_MAXLEN];
        /*
         * No space is left.  Handle this by reverting to
         * not using a temporary file.  Move the temporary file
         * back to the permanent file, and retry the write.
         */
        /*
        printf ("(%s:%d) %s: Reverting to not using temp file.\n",
                  __FILE__, __LINE__, __FUNCTION__);
        */
        fsError = ISFS_Close(BackupFileFd);
        if (fsError != ISFS_ERROR_OK) {
            CardCommand.result = CARD_RESULT_FAILURE;
            goto end;
        }
        sprintf(origFilePath,
                "%s/%s", TitleDataDir, BACKUP_MEM_FILE_NAME);
        sprintf(tempFilePath,
                "%s/%s", TEMP_DIRECTORY_NAME, BACKUP_MEM_FILE_NAME);
        fsError = ISFS_Rename( (const u8 *) tempFilePath,
                             (const u8 *) origFilePath);
        if (fsError != ISFS_ERROR_OK) {
            CARDi_FatalError("Rename of temporary backup file to actual file failed");
        }
        if (fsError != ISFS_ERROR_OK) {
            CARDi_FatalError("Rename of temporary backup file to actual file failed");
        }
        BackupFileFd = ISFS_Open((u8 *) origFilePath, ISFS_RW_ACCESS);
        if (BackupFileFd < 0) {
            CardCommand.result = CARD_RESULT_FAILURE;
            goto end;
        }
        FileStatus = FileOpenWriteOrig;

        /* Now try the write again */
        fsError = ISFS_Seek(BackupFileFd, (s32) destAddr, IOS_SEEK_SET);
        if (fsError == ISFS_ERROR_INVALID) {
            CardCommand.result = CARD_RESULT_INVALID_PARAM;
            goto end;
        }
        else if (fsError < 0) {
            CardCommand.result = CARD_RESULT_FAILURE;
            goto end;
        }
        bytesWritten  = ISFS_Write(BackupFileFd, (u8 *) srcAddr, length);

        if (bytesWritten == CardCommand.length) {
            CardCommand.result = CARD_RESULT_SUCCESS;
            returnVal = TRUE;
            goto end;
        }
        else if (bytesWritten == ISFS_ERROR_INVALID) {
            CardCommand.result = CARD_RESULT_INVALID_PARAM;
            goto end;
        }
        else {
            CardCommand.result = CARD_RESULT_FAILURE;
            goto end;
        }
    }
    else {
        /*
         * Some error other than invalid parameter or the file system
         * filling up when writing the temporary file
         */
        CardCommand.result = CARD_RESULT_FAILURE;
        if (FileStatus == FileOpenWriteTemp) {
            CARDi_RevertBackupToOriginal();
        }
        goto end;
    }
end:
    DEBUG("%s: Returning val = %d\n", __FUNCTION__, returnVal);
    return(returnVal);
} // CARDi_DoNetCardWrite
/* ------------------------------------------------------------------------ */

/*
 * A write to the temporary file has failed.
 * Revert to the original file so that no attempt is made later
 * to copy the corrupted temporary file back to the original.
 */
static BOOL
CARDi_RevertBackupToOriginal()
{
    ISFSError   fsError;
    char        tempFilePath[ISFS_PATH_MAXLEN];
    
    DEBUG("(%s:%d) %s - Enter\n", __FILE__, __LINE__, __FUNCTION__);
    if (FileStatus != FileOpenWriteTemp) {
        CARDi_FatalError("RevertToOriginal called, but file status is not FileOpenWriteTemp");
    }
    FileStatus = FileClosed;
    fsError = ISFS_Close(BackupFileFd);
    if (fsError != ISFS_ERROR_OK) {
        return(FALSE);
    }
    sprintf(tempFilePath,
            "%s/%s", TEMP_DIRECTORY_NAME, BACKUP_MEM_FILE_NAME);
    fsError = ISFS_Delete((const u8 *) tempFilePath);
    if (fsError != ISFS_ERROR_OK) {
        return(FALSE);
    }
    return(TRUE);
} // CARDi_RevertBackupToOriginal


/* ------------------------------------------------------------------------ */

/*
 * Verify that bytes in the NetCard file emulating the backup memory match
 * what is expected.
 *
 * RETURNS:
 *           TRUE:
 *                 if the 'length' bytes in the backup file at offset 'offset'
 *                 match the bytes in compareBuf
 *           FALSE: Otherwise
 */
static BOOL
CARDi_DoCardVerify(const u8* const compareBuf, const u32 offset,
                   const u32 length)
{
    u32                 bytesRemaining, bytesVerified;
    ISFSError           seekError;
    char                backupFilePath[ISFS_PATH_MAXLEN];

    if (FileStatus == FileClosed) {
        /* The '+2' consists of 1 for the '/' and 1 for the NULL terminator */
        if (  strlen(TitleDataDir)
            + strlen(BACKUP_MEM_FILE_NAME)
            + 2                              >= ISFS_PATH_MAXLEN) {
            CARDi_FatalError("(CARDi_DoCardRead) Path name is too long");
        }
        sprintf(backupFilePath, "%s/%s", TitleDataDir, BACKUP_MEM_FILE_NAME);
        /* Note: CARDi_OpenBackupFileRead sets FileStatus on success */
        if (CARDi_OpenBackupFileRead(backupFilePath) == FALSE) {
            CardCommand.result = CARD_RESULT_ERROR;
            return(FALSE);
        }
    }
    else if (FileStatus == FileInvalidStatus) {
        CARDi_FatalError("(CARDi_DoCardRead) InvalidFileStatus");
    }

    seekError = ISFS_Seek(BackupFileFd, (s32) offset, IOS_SEEK_SET);
    if (seekError < 0) {
        return(FALSE);
    }

    bytesRemaining = length;
    bytesVerified = 0;

    while (bytesRemaining != 0) {
        u32             bytesToRead;
        ISFSError       bytesRead;


        bytesToRead = MIN(bytesRemaining, TRANSFER_SIZE);

        bytesRead = ISFS_Read(BackupFileFd, TransferBuf, bytesToRead);

        if (bytesRead < 0) {
            CardCommand.result = CARD_RESULT_ERROR;
            return(FALSE);
        }
        if (bytesRead != bytesToRead) {
            CardCommand.result = CARD_RESULT_ERROR;
            return(FALSE);
        }
        // FIXME - Handle signed->unsigned conversion in last arg.
        if (memcmp(TransferBuf, compareBuf + bytesVerified,
                   (u32) bytesRead) != 0) {
            /* TODO - Verify that this is the correct failure code */
            CardCommand.result = CARD_RESULT_FAILURE;
            return(FALSE);
        }
        bytesRemaining -= bytesRead;
        bytesVerified  += bytesRead;
    }
    CardCommand.result = CARD_RESULT_SUCCESS;
    return(TRUE);
} // CARDi_DoCardVerify

/* ------------------------------------------------------------------------ */

/*
 * Open the NetCard file that corresponds to the backup memory on
 * a DS card for both reading AND writing.  The file should be
 * closed on entry to this function.
 *
 * If NO_COPY_ON_WRITE is defined, do not make or use a
 * temporary copy of the NetCard file.
 *
 * If it is not defined, then try to make a temporary
 * copy of it if possible, since writing to a file risks corrupting
 * it if the power is turned off during the write.
 * Note that making
 *
 * On success, BackupFileFd is set to a postive number and FileStatus
 * is set to FileOpenWriteOrig or FileOpenWriteTemp.
 * TRUE is returned
 *
 * On failure, FALSE is returned.
 */

static BOOL
CARDi_OpenBackupFileWrite()
{
    char                tempFilePath[ISFS_PATH_MAXLEN];
    char                origFilePath[ISFS_PATH_MAXLEN];
    IOSFd               statFd = -1;
    ISFSError           fsError;
    ISFSFileStats       fileStats;
    ISFSStats           fileSystemStats;
    u32                 numFileBlocks;
    BOOL                returnVal = FALSE, makeTempCopy;


    sprintf(origFilePath,
            "%s/%s", TitleDataDir, BACKUP_MEM_FILE_NAME);
    sprintf(tempFilePath,
            "%s/%s", TEMP_DIRECTORY_NAME, BACKUP_MEM_FILE_NAME);

    MARK;
    statFd = ISFS_Open((u8 *) origFilePath, ISFS_READ_ACCESS);

    /*
     * Create the non-temporary file corresponding to the backup memory
     * if it doesn not exist.
     */
    if (statFd == ISFS_ERROR_NOEXISTS) {
        MARK;
        fsError = ISFS_CreateFile((const u8 *) origFilePath,
                                  0,                // fileAttr
                                  ISFS_RW_ACCESS,   // Owner access
                                  0,                // Group access
                                  0);               // Other access 
        if (fsError != ISFS_ERROR_OK) {
            return(FALSE);
        }
        statFd = ISFS_Open((u8 *) origFilePath, ISFS_READ_ACCESS);
    }

    if (statFd < 0) {
        ERROR("ISFS_Open failed: %d\n", statFd);
        goto end;
    }
    if (ISFS_GetFileStats(statFd, &fileStats) != ISFS_ERROR_OK) {
        // GetFileStats: Error
        goto end;
    }
    if (ISFS_GetStats(&fileSystemStats) != ISFS_ERROR_OK) {
        // GetStats: Error
        goto end;
    }
    numFileBlocks = fileStats.size / ISFS_BLOCK_SIZE;
    if (numFileBlocks * ISFS_BLOCK_SIZE <  fileStats.size) {
        numFileBlocks++;
    }

#if defined(NO_COPY_ON_WRITE)
    makeTempCopy = FALSE;
#else
    makeTempCopy = numFileBlocks < fileSystemStats.freeBlocks ? TRUE : FALSE;
#endif

    /*
     * If current file length is less than the number of free blocks,
     * try to make a temporary file copy
     */
    if (makeTempCopy) {
        ISFSError       copyError;

        MARK;
        /*
        printf ("(%s:%d) %s: Making temporary copy.\n",
                 __FILE__, __LINE__, __FUNCTION__);
        */
        copyError = CopyFile(statFd, tempFilePath);
        MARK;
        if (copyError == ISFS_ERROR_OK) {
            /*
            printf ("(%s:%d) %s: Making temporary copy succeeded\n",
                      __FILE__, __LINE__, __FUNCTION__);
            */
            BackupFileFd = ISFS_Open((u8 *) tempFilePath, ISFS_RW_ACCESS);
            if (BackupFileFd >= 0) {
                // Success!
                MARK;
                FileStatus = FileOpenWriteTemp;
            }
            else {
                /* Copy succeeded but opening the temp failed */
                ERROR("Open temp failed");
                MARK;
                goto end;
            }
        }
        else if (copyError == ISFS_ERROR_MAXBLOCKS) {
            /*
            printf ("(%s:%d) %s: Making temporary copy failed - too few blocks.\n",
                      __FILE__, __LINE__, __FUNCTION__);
            */
            BackupFileFd = ISFS_Open((u8 *) origFilePath, ISFS_RW_ACCESS);
            if (BackupFileFd >= 0) {
                // Success!
                FileStatus = FileOpenWriteOrig;
                MARK;
            }
            else {
                /* Opening orignal file failed */
                ERROR("Open original file failed");
                MARK;
                goto end;
            }
        }
        else {
            /* Copy failed but not because flash filled up */
            ERROR("Copy of backup file failed, but flash isn't full");
            MARK;
            goto end;
        }
    }
    else {                                   // ! makeTempCopy
        /*
        printf ("(%s:%d) %s: Not making temporary copy\n",
                 __FILE__, __LINE__, __FUNCTION__);
        */
        BackupFileFd = ISFS_Open((u8 *) origFilePath, ISFS_RW_ACCESS);
        if (BackupFileFd >= 0) {
            FileStatus = FileOpenWriteOrig;
        }
        else {
            /* Opening orignal file failed */
            MARK;
            goto end;
        }
    }
    returnVal = TRUE;
end:
    MARK;
    if (statFd >= 0) {
        (void) ISFS_Close(statFd);
    }
    DEBUG("%s: Returning val = %d\n", __FUNCTION__, returnVal);
    return(returnVal);
} // CARDi_OpenBackupFileWrite
/* ------------------------------------------------------------------------ */

/*
 * Copy a open file with descriptor sourceFd to destPath
 * in the Secure Flash File system.
 *
 * INPUTS:
 *          sourceFd - a file descriptor pointing to the source
 *                     file with read access.
 *          destPath - the name of the destination file
 * RETURNS: ISFS_ERROR_OK if the copy succeeded
 *          the ISFS error code of the failing ISFS call otherwise
 */

static ISFSError
CopyFile(const IOSFd sourceFd, const char* destPath)
{
    IOSFd               destFd = -1;
    ISFSError           fsError;
    ISFSFileStats       fileStats;
    u32                 bytesRemaining;

    MARK;

    /*
     * Delete dest file if it already exists
     */
    fsError = ISFS_Delete((const u8 *) destPath);
    if (fsError != ISFS_ERROR_OK && fsError != ISFS_ERROR_NOEXISTS) {
        MARK;
        goto end;
    }

    /* At this point, the temp file does not exist - create it */
    fsError = ISFS_CreateFile((const u8 *) destPath,
                              0,                // fileAttr
                              ISFS_RW_ACCESS,   // Owner access
                              0,                // Group access
                              0);               // Other access 
    if (fsError != ISFS_ERROR_OK) {
        goto end;
    }
    MARK;

    destFd = ISFS_Open((const u8 *) destPath, ISFS_WRITE_ACCESS);
    if (destFd < 0) {
        fsError = destFd;
        goto end;
    }
    fsError = ISFS_GetFileStats(sourceFd, &fileStats);
    if (fsError != ISFS_ERROR_OK) {
        goto end;
    }
    fsError = ISFS_Seek(sourceFd, 0, IOS_SEEK_SET);     // Rewind to beginning
    if (fsError < 0) {
        goto end;
    }
    bytesRemaining = fileStats.size;

    MARK;

    /* Do the actual file copy */
    while (bytesRemaining != 0) {
        u32             bytesToRead;
        ISFSError       bytesRead, bytesWritten;


        bytesToRead = MIN(bytesRemaining, TRANSFER_SIZE);

        DEBUG ("%s:%d - sourceFd: %d; bytesToRead : %u\n",
             __FUNCTION__, __LINE__, sourceFd, bytesToRead);
        bytesRead = ISFS_Read(sourceFd, TransferBuf, bytesToRead);
        MARK;

        if (bytesRead < 0) {
            fsError = bytesRead;
            goto end;
        }
        if (bytesRead != bytesToRead) {
            fsError = ISFS_ERROR_UNKNOWN;
            goto end;
        }
        bytesWritten = ISFS_Write(destFd, TransferBuf, (u32) bytesRead);
        MARK;
        if (bytesWritten < 0) {
            fsError = bytesWritten;
            goto end;
        }
        if (bytesWritten != bytesRead) {
            fsError = ISFS_ERROR_UNKNOWN;
            goto end;
        }
        /*
        */
        bytesRemaining -= bytesRead;
    }

    // return(ISFS_ERROR_OK);
    fsError = ISFS_Close(destFd);
    MARK;

end:
    MARK;
    DEBUG("%s: Returning val = %d\n", __FUNCTION__, fsError);
    return(fsError);
} // copyFile

/* ------------------------------------------------------------------------ */

/*
 * Open the file 'backupFilePath' with read access.
 * Create it if it doesn't exist.
 * Sets FileStatus to FileOpenRead on success.
 * RETURNS: TRUE        if all went well, and set BackupFileFd to the
 *                      file descriptor
 *          FALSE       otherwise
 */

static BOOL
CARDi_OpenBackupFileRead(const char* backupFilePath)
{
    ISFSError   fsError;
    int i, bytes; 
    u32 size;
    u8 tmpFilePath[ISFS_PATH_MAXLEN];
    IOSFd tmpFileFd;
    ISFSFileStats fileStats;

    if (TitleDataDir == NULL) {
        CARDi_FatalError("(CARDi_OpenBackupFileRead) Data directory name is NULL");
    }

    //printf("backupfile: %s type=%d size=%d\n", backupFilePath, backupMemParams.type, backupMemParams.memSize);
    BackupFileFd = ISFS_Open((u8 *) backupFilePath, ISFS_READ_ACCESS);

    if (BackupFileFd == ISFS_ERROR_NOEXISTS) {
        sprintf((char*)tmpFilePath, "%s/%s", TEMP_DIRECTORY_NAME, BACKUP_MEM_FILE_NAME);
        ISFS_Delete(tmpFilePath);
        fsError = ISFS_CreateFile(tmpFilePath,
                                  0,                // fileAttr
                                  ISFS_RW_ACCESS,   // Owner access
                                  0,                // Group access
                                  0);               // Other access 
        if (fsError != ISFS_ERROR_OK) {
            CardCommand.result = CARD_RESULT_FAILURE;
            return(FALSE);
        }
        
        tmpFileFd = ISFS_Open(tmpFilePath, ISFS_RW_ACCESS);
        if (tmpFileFd<0) {
            CardCommand.result = CARD_RESULT_FAILURE;
            return(FALSE);
        }

        size = (backupMemParams.type==CARD_BACKUP_TYPE_EEPROM_4KBITS) 
               ? backupMemParams.memSize : TRANSFER_SIZE;
        memset(TransferBuf, 0, size);
        for (i=0; i< (backupMemParams.memSize / size); i++) {
            bytes = ISFS_Write(tmpFileFd, TransferBuf, size);
            if (bytes!=size) {
                ISFS_Close(tmpFileFd);
                CardCommand.result = CARD_RESULT_FAILURE;
                return(FALSE);
            }
        }
        ISFS_Close(tmpFileFd);
        fsError = ISFS_Rename(tmpFilePath, (u8*)backupFilePath);
        if (fsError!=ISFS_ERROR_OK) {
            CardCommand.result = CARD_RESULT_FAILURE;
            return(FALSE);
        }

        BackupFileFd = ISFS_Open((u8 *) backupFilePath, ISFS_READ_ACCESS);
    }

    if (BackupFileFd >= 0) {
        fsError = ISFS_GetFileStats(BackupFileFd, &fileStats);
        if (fsError != ISFS_ERROR_OK || fileStats.size!=backupMemParams.memSize) {
            ISFS_Close(BackupFileFd);
            CardCommand.result = CARD_RESULT_FAILURE;
            return(FALSE);
        }
        FileStatus = FileOpenRead;
        return(TRUE);
    }
    else {
        CardCommand.result = CARD_RESULT_FAILURE;
        return(FALSE);
    }
} // CARDi_OpenBackupFileRead
/* ------------------------------------------------------------------------ */
/*
 * Get the type of the backup memory which was specified when the title was
 * published (using the -s option).  If successful, set the backupMemParams
 * structure accordingly.
 */
void
CARDi_setInitialBackupType()
{
    u32        accessRights;
    ESError    error;

    backupMemParams.type = CARD_BACKUP_TYPE_NOT_USE;

    //printf ("%s: Calling ES_GetAccessRights\n", __FUNCTION__);
    error = ES_GetAccessRights(&accessRights);
    //printf ("%s: ES_GetAccessRights returned\n", __FUNCTION__);

    if (error == ES_ERR_OK) {
        //printf ("%s: GetAccessRights value: 0x%x\n", __FUNCTION__, accessRights);

        //printf ("%s: Mem size: %u \n", __FUNCTION__, backupMemParams.memSize);
        switch (accessRights & 0x7) {


        case 0x0:
            backupMemParams.type = CARD_BACKUP_TYPE_NOT_USE;
            break;

        case 0x1:
            backupMemParams.type = CARD_BACKUP_TYPE_FLASH_2MBITS;
            backupMemParams.pageSize   = 0x00100;
            backupMemParams.sectorSize = 0x10000;
            break;

        case 0x2:
            backupMemParams.type = CARD_BACKUP_TYPE_FLASH_4MBITS;
            backupMemParams.pageSize   = 0x00100;
            backupMemParams.sectorSize = 0x10000;
            break;

        case 0x3:
            backupMemParams.type = CARD_BACKUP_TYPE_FLASH_8MBITS;
            backupMemParams.pageSize   = 0x00100;
            backupMemParams.sectorSize = 0x10000;
            break;

        case 0x4:
            backupMemParams.type = CARD_BACKUP_TYPE_EEPROM_4KBITS;
            backupMemParams.pageSize   = 0x10;
            backupMemParams.sectorSize = backupMemParams.pageSize;
            break;

        case 0x5:
            backupMemParams.type = CARD_BACKUP_TYPE_EEPROM_64KBITS;
            backupMemParams.pageSize   = 0x20;
            backupMemParams.sectorSize = backupMemParams.pageSize;
            break;

        case 0x6:
            backupMemParams.type = CARD_BACKUP_TYPE_EEPROM_512KBITS;
            backupMemParams.pageSize   = 0x80;
            backupMemParams.sectorSize = backupMemParams.pageSize;
            break;

        case 0x7:
            backupMemParams.type = CARD_BACKUP_TYPE_FRAM_256KBITS;
            backupMemParams.memSize = (u32) (1 << ((backupMemParams.type >> CARD_BACKUP_TYPE_SIZEBIT_SHIFT) & CARD_BACKUP_TYPE_SIZEBIT_MASK));
            backupMemParams.pageSize = backupMemParams.memSize;
            backupMemParams.sectorSize = backupMemParams.memSize;
            break;

        default:
            ERROR("%s: Programming logic error in switch statement\n", __FUNCTION__);
            break;
        }
        if (backupMemParams.type != CARD_BACKUP_TYPE_NOT_USE) {
            backupMemParams.memSize = (u32) (1 << ((backupMemParams.type >> CARD_BACKUP_TYPE_SIZEBIT_SHIFT) & CARD_BACKUP_TYPE_SIZEBIT_MASK));
        }
    }
    else {
        ERROR ("%s: GetAccessRights failed: rv = %d\n", __FUNCTION__, error);
    }
} // CARDi_setInitialBackupType
/* ------------------------------------------------------------------------ */
