#ident "$Id: card-api.c,v 1.41 2007/02/21 01:44:59 paulm 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.
 *
 */

/*
 * NetCard version of the Nitro CARD API
 *
 * This file contains the non-backup memory functions necessary
 * to implement the CARD API using NetCard instead of a DS card.
 * When a DS game is launched from the NetCard, the CARD
 * calls must access the boot content file on the NetCard
 * instead of the actual DS card.
 *
 * The goal of this API is to match both the documented and undocumented
 * behavior of the DS Card API.
 *
 * Functions whose names begin with 'CARD_' are API functions.
 * Functions whose names begin with 'CARDi_' are internal functions
 * that applications are not supposed to call.
 *
 */

#include <nitro.h>

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

#include "ds-debug.h"

#define         THREAD_STACK_SIZE       1024
#define         BUSY_QUEUE_SIZE         4
#define         LOCK_QUEUE_SIZE         4


/*
 * CardStatus contains zero or more of the following flags:
 * CARD_BUSY, CARD_ASYNC_BUSY, CARD_CANCEL_BACKUP_OP
 */
volatile u32            CardStatus;
OSThreadQueue           CardBusyQueue[BUSY_QUEUE_SIZE];

typedef struct threadInfo_t {
    OSThread            id;
    u32                 priority;
    void                (*funcToCall) (cardCommand_t *);
    cardCommand_t       *cardCommand;
} threadInfo_t;

threadInfo_t    AsyncThread;
OSThread        *CurrentThread;

typedef struct busLock_t {
    volatile CARDiOwner         owner;
    CARDTargetMode              target;
    OSThreadQueue               lock_queue[LOCK_QUEUE_SIZE];
    volatile int                references;
} busLock_t;

busLock_t       BusLock;

cardCommand_t   CardCommand;
u8              AsyncThreadStack[THREAD_STACK_SIZE]     ATTRIBUTE_ALIGN(4);
void            CARDi_AsyncMain(void *arg);
static BOOL     CARD_EnableFlag = FALSE;

CARDTargetMode  CARDi_GetTargetMode(void);
void            CARDi_InitBusLock(busLock_t *lock);
void            CARDi_InitCardCommand(cardCommand_t *command);
static void     CARDi_ReadRomNetCardSync();
static void     CARDi_EndRomRead();
void            CARDi_EndCardAccess(BOOL isOwnTask);
static void     CARDi_SendToPxi(u32 data, u32 wait);
static void     CARDi_PulledOutCallback(PXIFifoTag tag, u32 data, BOOL err);
void            CARDi_AssignAsyncWork(void (*whichFunc) (cardCommand_t *command));
static void     CARDi_InitPulledOutCallback(void);

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

/* Offset from start of boot content file to where the ROM image starts */
static u32 CardRomBase;

char        *TitleDataDir;
static char DataDirBuf[ISFS_PATH_MAXLEN];

static BOOL             InitCalled = FALSE;

extern void CARDi_setInitialBackupType();

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

/*
 * Note: CARD_Init is called by OS_Init
 */

void
CARD_Init(void)
{
    MARK;
    if (InitCalled == FALSE) {
        ESTitleId       titleId;

        CARDi_InitPulledOutCallback();

        CardStatus = 0;
        OS_InitThreadQueue(CardBusyQueue);

        CARDi_InitBusLock(&BusLock);
        CARDi_InitCardCommand(&CardCommand);
        if (!CTRDG_IsEnabled()) {
            OS_InitThread();
            CTRDG_Init();
            CTRDG_Enable(TRUE);
        }
        /*
         * ELF Merge puts a special segment at ROM_BASE_LOCATION
         * in GBA ROM space to tell the CARD API emulation code
         * the offset within the boot content file at which the
         * actual DS CARD ROM image starts.
         */
        CTRDG_Read32((u32 *) ROM_BASE_LOCATION, &CardRomBase);
        DEBUG("$$$$ (%s) Rom base: 0x%x\n", __FUNCTION__, CardRomBase); 

        /*
         * This code should not be called by a wireless-downloaded program.
         * The program is coming from the NetCard.
         */
        SDK_ASSERT(!MB_IsMultiBootChild());

        // MI_CpuCopy8 args are: source, destination, size
        // HW_CARD_ROM_HEADER: HW_MAIN_MEM + 0x007ffa80
        // HW_ROM_HEADER_BUF:  HW_MAIN_MEM + 0x007ffe00
        MI_CpuCopy8((const void *)HW_ROM_HEADER_BUF, (void *)HW_CARD_ROM_HEADER,
                    HW_CARD_ROM_HEADER_SIZE);
 
        {
        const CARDRomRegion *const fat = CARD_GetRomRegionFAT();
        DEBUG("$$$ Fat size: %u\n", fat->length); 
        }
        /*
         * Create and start the thread that handles asynchronous requests
         * Note: CARD_THREAD_PRIORITY_DEFAULT defined in
         * include/nitro/card/common.h
         */
        AsyncThread.priority = CARD_THREAD_PRIORITY_DEFAULT;
        OS_CreateThread(&(AsyncThread.id), CARDi_AsyncMain, NULL,
                        AsyncThreadStack + sizeof(AsyncThreadStack),
                        sizeof(AsyncThreadStack), AsyncThread.priority);
        OS_WakeupThreadDirect(&(AsyncThread.id));

        /* The IPC layer requires that IRQs be enabled */
        (void) OS_EnableIrq();
        if (ES_InitLib() != ES_ERR_OK) {
            CARDi_FatalError("Initializing the ES library failed");
        }
        if (ES_GetTitleId(&titleId) != ES_ERR_OK) {
            CARDi_FatalError("Getting Title Id");
        }
        CARDi_setInitialBackupType();
        if (ES_GetDataDir(titleId, DataDirBuf) == ES_ERR_OK) {
            TitleDataDir = DataDirBuf;
        }
        else {
            /*
             * Don't do an OS_Panic here, since the data directory
             * will only be used if backup/save game functions
             * are used.
             */
            TitleDataDir = NULL;
        }
        CARD_Enable(TRUE);
    }
    InitCalled = TRUE;
}

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

int
CARD_IsAvailable(void)
{
    return(InitCalled);
}

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

BOOL
CARD_IsEnabled(void)
{
    return(CARD_EnableFlag);
}

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

/*
 * Description:  Terminate program if CARD is not accessible
 */

void
CARD_CheckEnabled(void)
{
    if (!CARD_IsEnabled())
    {
        CARDi_FatalError("NITRO-CARD permission denied");
    }
}

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

/*
 * Description:  Set card access permission mode.
 * Arguments:    enable  -  permission mode to be set.
 */

void
CARD_Enable(BOOL enable)
{
    CARD_EnableFlag = enable;
}

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

/*
 * Description:  get result code of latest command.
 * Arguments:    None.
 * Returns:      result code of latest command.
 */
CARDResult
CARD_GetResultCode(void)
{
    SDK_ASSERT(CARD_IsAvailable());

    return(CardCommand.result);
}

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

u32
CARD_GetThreadPriority(void)
{
    SDK_ASSERT(CARD_IsAvailable());

    return(AsyncThread.priority);
}

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

/*
 * Description:  set priority of internal thread which deal with
 *               asynchronous CARD-ROM tasks.
 *               
 * Returns:      old priority of internal thread.
 */
u32
CARD_SetThreadPriority(u32 newPriority)
{
    u32         oldPriority;
    OSIntrMode  curMode;

    SDK_ASSERT(CARD_IsAvailable());

    curMode = OS_DisableInterrupts();

    oldPriority = AsyncThread.priority;
    
    SDK_ASSERT((newPriority >= OS_THREAD_PRIORITY_MIN) && (newPriority <= OS_THREAD_PRIORITY_MAX));
    AsyncThread.priority = newPriority;
    (void) OS_SetThreadPriority(&(AsyncThread.id), AsyncThread.priority);
    (void) OS_RestoreInterrupts(curMode);
    return(oldPriority);
} // CARD_SetThreadPriority

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

const u8 *
CARD_GetRomHeader(void)
{
    return (const u8 *) HW_CARD_ROM_HEADER;
}

/* ------------------------------------------------------------------------ */
/*                    ROM ACCESS FUNCTIONS                                  */
/* ------------------------------------------------------------------------ */

/*
 * Note: The following are defined in NitroSDK/include/nitro/card:
 *       CARD_ReadRom(u32 dma, const void *src, void *dst, u32 len)
 */
/* ------------------------------------------------------------------------ */

/*
 * The CARD_[Lock|Unlock][Rom|Backup] functions lock/unlock the access bus
 * used to reach the ROM/Backup memory on the card.  There is no need
 * to do when accessing the NetCard, but a lock operation is done
 * anyway to maintain maximum compatibility with existing software.
 */

void
CARD_LockRom(u16 lock_id)
{
    // printf("%s: Enter\n", __FUNCTION__);
    SDK_ASSERT(CARD_IsAvailable());

    CARDi_LockResource(lock_id, CARD_TARGET_ROM);
}

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

/* See comment for CARD_LockRom */
void
CARD_UnlockRom(u16 lock_id)
{
    // printf("%s: Enter\n", __FUNCTION__);
    SDK_ASSERT(CARD_IsAvailable());
    CARDi_UnlockResource(lock_id, CARD_TARGET_ROM);
}

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

BOOL
CARD_TryWaitRomAsync(void)
{
    return(CARDi_IsIdle());
}

/* ------------------------------------------------------------------------ */
void
CARD_WaitRomAsync(void)
{
    (void) CARD_WaitDone();     // Equilvalent to CARDi_WaitAsync
}

/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
/*                    REMOVAL DETECTION FUNCTIONS                           */
/* ------------------------------------------------------------------------ */


/*
 * This routine needs to do these operations, or else the application
 * won't run at all.
 */
static void
CARDi_InitPulledOutCallback(void)
{
    PXI_Init();

    PXI_SetFifoRecvCallback(PXI_FIFO_TAG_CARD, CARDi_PulledOutCallback);
}

/* ------------------------------------------------------------------------ */
static void
CARDi_PulledOutCallback(PXIFifoTag tag, u32 data, BOOL err)
{
    // TODO - The DS card has been pulled out - what is the right
    // thing to do here?

    // Compiler fodder
    tag = tag;
    data = data;
    err = err;
}

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

BOOL
CARD_IsPulledOut(void)
{
    BOOL        returnVal;

    DEBUG("%s: Enter\n", __FUNCTION__);
    returnVal = CTRDG_IsPulledOut();
    DEBUG("%s: Exit : returning %d\n", __FUNCTION__, returnVal);
    return(returnVal);
    // return(FALSE);
}

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

/*
 * TODO (maybe) - Write code to check that the user doesn't call
 * CTRDG_SetPulledOutCallback which overwrites what we set here.
 */
void
CARD_SetPulledOutCallback(CARDPulledOutCallback callback)
{
    DEBUG("%s: Enter\n", __FUNCTION__);
    CTRDG_SetPulledOutCallback((CTRDGPulledOutCallback) callback);
    DEBUG("%s: Exit\n", __FUNCTION__);
}

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

void
CARD_CheckPulledOut(void)
{
    DEBUG("%s: Enter\n", __FUNCTION__);
    CTRDG_CheckPulledOut();
    DEBUG("%s: Exit\n", __FUNCTION__);
}

/* ------------------------------------------------------------------------ */
/*
 * Code taken directly from DS Card API library.
 */
void
CARD_TerminateForPulledOut(void)
{
    BOOL    should_be_halt = TRUE;
    //---- if folding, power off
    if (PAD_DetectFold())
    {
        /* Retry while the wireless SPI exclusive control fails.*/
        u32 res;
        while ((res = PM_ForceToPowerOff()) == SPI_PXI_RESULT_EXCLUSIVE)
        {
            /* Wait for 10ms before retry*/
            OS_SpinWait(HW_CPU_CLOCK_ARM9 / 100);
        }
        if (res == PM_RESULT_SUCCESS)
        {
            /*
             * If ARM7 is busy, there is a chance that the power off
             * will occur before the Terminate process,
             * preventing system shutdown.
             * If the PM_ForceToPowerOff function is successful,
             * do not send the Terminate command to the ARM7 side.
             */
            should_be_halt = FALSE;
        }
    }

    /*
     * The ARM7 needs to be stopped if the clamshell is not closed
     * or the PM_ForceToPowerOff function fails, so send Terminate command.
     */
    if (should_be_halt)
    {
        //---- send 'TERMINATE' command to ARM7, and terminate itself immediately
        CARDi_SendToPxi(CARD_PXI_COMMAND_TERMINATE, 1);
    }

    OS_Terminate();
}

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

/*
 * The following are "helper" functions that are not part of the
 * card API
 */

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

/*
 * Assign some work to the asynchronous thread.
 *
 * Equivalent to CARDi_SetTask.
 *
 * Internal function
 */
void
CARDi_AssignAsyncWork(void (*whichFunc) (cardCommand_t *command))
{
    /*
    printf("%s: Setting thread priority from %u to %u\n",
               __FUNCTION__, OS_GetThreadPriority(&(AsyncThread.id)),
               AsyncThread.priority);
    */
    /*
     * N.B.: The async thread is already at AsyncThread.priority, but
     *       calling SetThreadPriority with a thread's existing
     *       priority is NOT a no-op.  Thus, we still do the call
     *       here, just like it is done in the original CARD library.
     */
    (void)OS_SetThreadPriority(&(AsyncThread.id), AsyncThread.priority);

    CurrentThread = &(AsyncThread.id);
    AsyncThread.funcToCall = whichFunc;
    CardStatus |= CARD_ASYNC_BUSY;
    THREAD_DEBUG("%s: Waking thread\n", __FUNCTION__);
    OS_WakeupThreadDirect(&(AsyncThread.id));
    THREAD_DEBUG("%s: Done waking thread\n", __FUNCTION__);
}

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

/*
 * This is the entry procedure for the thread that handles asynchronous
 * requests.
 *
 * Corresponds to CARDi_TaskThread in Nintendo's card code
 * Internal function
 */
static void
CARDi_AsyncMain(void *arg)
{
    while (1) {
        OSIntrMode mode;
        // printf ("$$$$ %s: Top of loop\n", __FUNCTION__ );

        arg = arg;               // Compiler fodder - arg isn't used
        mode = OS_DisableInterrupts();
        while ((CardStatus & CARD_ASYNC_BUSY) == 0) {
            THREAD_DEBUG("$$$$ %s: Sleeping\n", __FUNCTION__ );
            CurrentThread = &(AsyncThread.id);
            OS_SleepThread(NULL);
        }
        (void) OS_RestoreInterrupts(mode);
        THREAD_DEBUG("$$$$ %s: Calling command\n", __FUNCTION__ );
        (*AsyncThread.funcToCall)(AsyncThread.cardCommand);
    }
}

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

/*
 * The API functions in rom.h call this function
 * Internal function
 */
void
CARDi_ReadRom(u32 dma, const void *src, void *dst, u32 len,
              MIDmaCallback callback, void *arg, BOOL is_async)
{

    MARK;
    DEBUG("### %s: src: 0x%x; dest: 0x%x; length: %u; async: %d\n",
           __FUNCTION__, (u32) src, (u32) dst, len, is_async);
    dma = dma;          // Compiler fodder
    /* Determine whether CARD_Init has been called*/
    SDK_ASSERT(CARD_IsAvailable());
    SDK_ASSERT(CARDi_GetTargetMode() == CARD_TARGET_ROM);
    SDK_ASSERTMSG((dma != 0), "cannot specify DMA channel 0");

    CARD_CheckEnabled();

    // Must be called before setting the callbacks and its args
    CARD_WaitIdle();

    CardCommand.callbackFunc    = callback;
    CardCommand.callbackArg     = arg;

    DEBUG("$$$$ (%s) Rom base: 0x%x\n", __FUNCTION__, CardRomBase); 
    CardCommand.srcAddr = ((u32) src + CardRomBase);
    CardCommand.destAddr = (u32) dst;
    CardCommand.length = len;

    if (is_async) {
        CARDi_AssignAsyncWork(CARDi_ReadRomNetCardSync);
    }
    else {
        CurrentThread = OS_GetCurrentThread();
        CARDi_ReadRomNetCardSync();
    }
    MARK;

} // CARDi_ReadRom

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

/*
 * Do the actual read from the net card.
 * This is a synchronous operation executed by either the requesting
 * thread or the CARD library asynchronous thread.
 *
 * The equivalent of CARDi_ReadRomSyncCore() in the original CARD library.
 *
 * Internal function
 */
#define CHUNK_SIZE (112*1024)


static void
CARDi_ReadRomNetCardSync()
{
    // The ES file descriptor corresponding to the emulated DS card ROM
#ifdef IMPORT_RUNNING
    s32         romFd = -1;
#else
    static s32 romFd = -1;
#endif
    ESError     esError;
    u32         bytesLeft = CardCommand.length;
    u8          *dst  = (u8 *)CardCommand.destAddr;

    MARK;
    /*
     * It is possible to get called with length == 0.
     * ES will choke on it (with a -1017 error), so check
     * for it here
     */
    if (CardCommand.length == 0) {
        goto end;
    }

#ifdef IMPORT_RUNNING
    /*
     * The content file is opened and closed on every read because
     * otherwise it is impossible to import the running application
     */
    romFd = ES_OpenContentFile(ROM_CONTENT_ID);
#else
    if (romFd == -1) {
        romFd = ES_OpenContentFile(ROM_CONTENT_ID);
    }
#endif

    if (romFd < 0) {
        CARDi_FatalError("Opening ROM content file failed");
    }

    esError = ES_SeekContentFile(romFd, (long) CardCommand.srcAddr,
                                 IOS_SEEK_SET);
    if (esError < 0) {
        ERROR("(CARDi_ReadRom) ES_SeekContentFile failed: rv = %d\n",
                   esError);
        CARDi_FatalError("ES_SeekContentFile failed\n");
    }
    else if (esError != CardCommand.srcAddr) {
        CARDi_FatalError(
                    "ES_SeekContentFile failed - return val != input val\n");
    }

    while (bytesLeft > 0) {
        u32 bytes = bytesLeft > CHUNK_SIZE ? CHUNK_SIZE : bytesLeft;
        esError = ES_ReadContentFile(romFd, dst, bytes);
        if (esError < 0) break;
        bytesLeft -= bytes;
        dst += bytes;
    }

    if (esError < 0) {
        ERROR("(CARDi_ReadRom) ES_ReadContentFile failed: rv = %d\n", esError);

        CARDi_FatalError("ES_ReadContentFile failed\n");
    }
    else if (bytesLeft) {
        CARDi_FatalError("ES_ReadContentFile failed - not enough bytes were read\n");
    }

#ifdef CARD_READ_DEBUG
    // DO NOT REMOVE - DO NOT REMOVE - DO NOT REMOVE - DO NOT REMOVE
    printf("!!! src: 0x%x; dest: 0x%x; length: 0x%x\n",
            CardCommand.srcAddr, CardCommand.destAddr, CardCommand.length);
    printf("!!! %s: MD5 Sum:", __FUNCTION__);
    printMD5sum((void *) CardCommand.destAddr, CardCommand.length);
    printf("\n");
    // DO NOT REMOVE - DO NOT REMOVE - DO NOT REMOVE - DO NOT REMOVE
#endif

end:

#ifdef IMPORT_RUNNING
    if (romFd >= 0) {
        esError = ES_CloseContentFile(romFd);
        if (esError != ES_ERR_OK ) {
            CARDi_FatalError("Closing ROM content file failed");
        }
        romFd = -1;
    }
#endif
    CARDi_EndRomRead();
} // CARDi_ReadRomNetCardSync()

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

/*
 * Corresponds to CARDi_ReadEnd
 */
static void
CARDi_EndRomRead()
{

    // FIXME - check for pulled out card here?

    CardCommand.result = CARD_RESULT_SUCCESS;
    CARDi_EndCardAccess(TRUE);
}

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

/*
 * Set the card status to "not busy"
 * Wake up all threads that are waiting for the card to be "not busy".
 * If the card operation was done by the asynchronous thread, and there
 * was a callback registered, call it.
 * 
 * Equivalent to CARDi_EndTask.
 * Internal function
 */
void
CARDi_EndCardAccess(BOOL isOwnTask)
{
    OSIntrMode  curMode;

    curMode = OS_DisableInterrupts();

    CardStatus &= ~(CARD_BUSY | CARD_ASYNC_BUSY | CARD_CANCEL_BACKUP_OP);
    OS_WakeupThread(CardBusyQueue);

    OS_RestoreInterrupts(curMode);

    if (isOwnTask && CardCommand.callbackFunc != NULL) {
        /*
        printf ("$$$$ %s: Calling callback at 0x%x\n",
                __FUNCTION__, CardCommand.callbackFunc);
        */
        (*CardCommand.callbackFunc) (CardCommand.callbackArg);
    }
} // CARDi_EndCardAccess

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

/*
 * Internal function
 * When accessing a real DS card, a bus needs to be locked by the
 * accessing thread before the card can be properly accessed.
 * While this is not needed when accessing a NetCard, the same
 * operations are done in order to provide maximum compatibility.
 *
 */

void
CARDi_LockResource(CARDiOwner owner, CARDTargetMode target)
{
    OSIntrMode curMode;

    curMode = OS_DisableInterrupts();
    if (BusLock.owner == owner) {
        if (BusLock.target != target) {
            OS_TPanic("card-lock : can not reuse same ID for locking without unlocking!");
        }
    }
    else {
        while (BusLock.owner != OS_LOCK_ID_ERROR)
            OS_SleepThread(BusLock.lock_queue);
        BusLock.owner = owner;
        BusLock.target = target;
    }
    BusLock.references++;
    CardCommand.result = CARD_RESULT_SUCCESS;
    (void) OS_RestoreInterrupts(curMode);
}

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

/*
 * Unlocks the virtual bus if the owner passed in is the current
 * "owner" of the bus.
 * See comment for CARDi_LockResource for more details.
 * Internal function
 */

void
CARDi_UnlockResource(CARDiOwner owner, CARDTargetMode target)
{
    OSIntrMode curMode;

    curMode = OS_DisableInterrupts();

    if ((BusLock.owner != owner) || BusLock.references == 0) {
        OS_TPanic("card-unlock : specified ID for unlocking is not locking one!");
    }
    else {
        if (BusLock.target != target) {
            CARDi_FatalError("card-unlock : locking target and unlocking one are different!");
        }
        if (--BusLock.references == 0) {
            BusLock.owner = OS_LOCK_ID_ERROR;
            BusLock.target = CARD_TARGET_NONE;
            OS_WakeupThread(BusLock.lock_queue);
        }
    }
    CardCommand.result = CARD_RESULT_SUCCESS;
    (void) OS_RestoreInterrupts(curMode);
}

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

/*
 * RETURNS: One of CARD_TARGET_NONE, CARD_TARGET_ROM, or CARD_TARGET_BACKUP.
 *          Helps to emulate a real DS card in which the bus to access the
 *          card is locked to either the ROM, the backup memory, or nothing
 */
static CARDTargetMode
CARDi_GetTargetMode(void)
{
    return(BusLock.target);
}

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

/*
 * Equivalent to CARDi_TryWaitAsync, which actually checks the busy bit
 * and not the asynchronous busy bit.
 * And it doesn't wait.
 * And it isn't asynchronous.
 */
BOOL
CARDi_IsIdle(void)
{
    SDK_ASSERT(CARD_IsAvailable());

    return !(CardStatus & CARD_BUSY);
}

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

/*
 * Initialize the bus lock to be unlocked, and initialize the thread
 * queue waiting on the bus lock
 */
static void
CARDi_InitBusLock(busLock_t *lock)
{
    lock->owner  = OS_LOCK_ID_ERROR;
    lock->target = CARD_TARGET_NONE;
    OS_InitThreadQueue(lock->lock_queue);
    lock->references = 0;
}

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

static void
CARDi_InitCardCommand(cardCommand_t *command)
{
    command->srcAddr      = 0;
    command->length       = 0;
    command->destAddr     = 0;
    command->callbackFunc = NULL;
    command->callbackArg  = NULL;
}

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

/*
 * Used by the function CARD_TerminateForPulledOut
 */
static void
CARDi_SendToPxi(u32 data, u32 wait)
{
    while (PXI_SendWordByFifo(PXI_FIFO_TAG_CARD, data, FALSE)
           != PXI_FIFO_SUCCESS) {
        SVC_WaitByLoop((s32)wait);
    }
}

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

extern void textPrintf(char *fmt, ...);

void
CARDi_FatalError(const char* const message)
{
    // TODO - when done debugging, change to OS_Panic
    ERROR("Fatal error: %s\n", message);
    while (1) {
    }
    // OS_Panic(message);
}

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