/*
 *               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.
 *
 * $Id: sdlog.c,v 1.2 2008/01/26 00:04:54 horti Exp $
 */


#include <stdarg.h>
#include <iostypes.h>
#include <iop.h>
#include <ios.h>
#include <ioslibc.h>

#include <sd_api.h>

// #define ENABLE_DEBUG 1

#ifdef ENABLE_DEBUG
#define DBG_PRINT(format, ...) printf(format, ##__VA_ARGS__)
#else
#define DBG_PRINT(format, ...)
#endif

/* SD card page size */
#define SD_PAGE_SIZE_SHIFT      9
#define SD_PAGE_SIZE            (1 << SD_PAGE_SIZE_SHIFT)

/* Offsets used on SD card
 *   - File header info = 20MB
 *   - File base        = 21MB
 */
#define FILE_HDR_OFFSET         0x1400000
#define FILE_OFFSET             (FILE_HDR_OFFSET+0x100000)

#define DATA_BUF_SIZE           512
#define HDR_BUF_SIZE            256

static SDDevHandle  sdFd;            /* File descriptor for the SD card */
static u32 sdFileOfs = FILE_OFFSET;  /* Default offset to be at 1MB */
static u32 sdFileHdrOfs = FILE_HDR_OFFSET;  /* Default offset to be at 1MB */
static u32 sdFileLen = 0;

static u8 *dataBuf = NULL;
static u8 *hdrBuf  = NULL;
static u32 dbIdx = 0;


/*
 * Open the SD device
 */
static IOSError
sdInit(void)
{
    IOSError    rc = IOS_ERROR_OK;

    rc = ISD_InitCard();
    if (rc != IOS_ERROR_OK) {
  	    printf("%s: ISD_InitCard() failed, rc=%d\n", __FUNCTION__, rc);
        goto out;
    }

    /* Allocate structure from shared heap */
    sdFd = (SDDevHandle) IOS_Alloc(0, sizeof(SDDev));
    if (sdFd == NULL) {
        printf("%s: Alloc SD handle failed!\n", __FUNCTION__);
        goto out;
    }

    /* Assume that we are using slot 0 */
    sdFd->SDDevSlot = 0;
    sdFd->SDDevFd = -1;
    rc = ISD_MountCard(sdFd->SDDevSlot, &sdFd);
    if (rc != IOS_ERROR_OK) {
	    printf("%s: ISD_MountCard() failed, rc=%d\n", __FUNCTION__, rc);
        goto out;
    }

    /* Reset the device */
    rc = ISD_ResetDevice(sdFd);

out:

    return (rc);
}


static IOSError
sdWriteFile(u32 addr, u32 offset, u32 size)
{
    IOSError rc = IOS_ERROR_OK;
    u32 len, ofs;

    /* Round up length to multiple of 512 bytes */
    len = (size + 511) & ~511;

    /* If no offset specified, use global static offset */
    if (offset == 0) {
        ofs = sdFileOfs;
        sdFileOfs += len;
        sdFileLen += len;
    }
    else
        ofs = offset;

    DBG_PRINT("%s: writing %d bytes to SD at ofs(0x%08x)\n",
              __FUNCTION__, len, ofs);

    rc = ISD_WriteMultiBlock(sdFd, ofs, addr, len);

    return rc;

}  /* sdWriteFile */


void
sdLog(u8 *msg, u32 offset, s32 size, u8 immediate)
{
    IOSError rc = IOS_ERROR_OK;
    static u8 initialized = 0;
    s32 len, len1, msgIdx, rem;

    if (!initialized) {
        DBG_PRINT("%s: initializing SD\n", __FUNCTION__ );
        rc = sdInit();
        if (rc != IOS_ERROR_OK) {
            printf("%s: SD card initialization failed, rc=%d\n", 
                __FUNCTION__, rc);
            goto out;
        }
        /* Allocate buffers from shared heap */
        dataBuf = IOS_Alloc(0, DATA_BUF_SIZE);
        if (dataBuf == NULL) {
            printf("%s: Alloc data buffer failed!\n", __FUNCTION__);
            goto out;
        }
        hdrBuf = IOS_Alloc(0, HDR_BUF_SIZE);
        if (hdrBuf == NULL) {
            printf("%s: Alloc header buffer failed!\n", __FUNCTION__);
            goto out;
        }
        memset(dataBuf, 0, DATA_BUF_SIZE);
        memset(hdrBuf, 0, HDR_BUF_SIZE);
        dbIdx = 0;
        initialized = 1;
    }

    /* Fill up buffer until full and then write to SD */
    msgIdx = 0, rem = 0, len1 = 0;
    len = size;

    DBG_PRINT("%s: logging message (%s) of size %d\n", __FUNCTION__, msg, size);
    while (len > 0) {
        DBG_PRINT("%s: dbIdx=%d msgIdx=%d len=%d len1=%d rem=%d\n",
             __FUNCTION__, dbIdx, msgIdx, len, len1, rem);
        rem = DATA_BUF_SIZE - 1 - dbIdx;
        if (rem > len)  {
            len1 = len;
        }
        else {
            len1 = rem;
        }

        DBG_PRINT("%s: copy %d bytes from msgIdx(%d) to bufIdx(%d), imm=%d\n",
             __FUNCTION__, len1, msgIdx, dbIdx, immediate );

        memcpy(dataBuf+dbIdx, msg+msgIdx, len1);
        dbIdx += len1;
        msgIdx += len1;
        if (immediate || (dbIdx >= DATA_BUF_SIZE-1)) {
            DBG_PRINT("%s: writing data to SD @ ofs(0x%08x)\n", 
                __FUNCTION__, offset);
            dataBuf[DATA_BUF_SIZE-1]=0x0a;
            rc = sdWriteFile((u32)dataBuf, offset, DATA_BUF_SIZE);
            if (rc != IOS_ERROR_OK) {
                printf("%s: writing data to SD card failed, rc=%d\n",
                    __FUNCTION__, rc);
                goto out;
            }
            memset(hdrBuf, 0, DATA_BUF_SIZE);
            snprintf(hdrBuf, 64, "\nEHCI: %s\nFile size = %d\n",
                BUILD_TIME, sdFileLen);
            DBG_PRINT("%s: writing header to SD @ ofs(0x%08x)\n", 
                __FUNCTION__, sdFileHdrOfs);
            hdrBuf[DATA_BUF_SIZE-1]=0x0a;
            rc = sdWriteFile((u32)hdrBuf, sdFileHdrOfs, DATA_BUF_SIZE);
            if (rc != IOS_ERROR_OK) {
                printf("%s: writing header to SD card failed, rc=%d\n",
                    __FUNCTION__, rc);
                goto out;
            }
            dbIdx = 0;
            memset(dataBuf, 0, DATA_BUF_SIZE);
        }
        len -= len1;
    }

out:
    return;

}  /* sdLog */


void
sdLogPrintf(char *str, size_t size, int immediate, const char *fmt, ...)
{
    va_list ap;
    int rv;

    va_start(ap, fmt);
    rv = vsnprintf(str, size, fmt, ap);
    va_end(ap);
    
    sdLog(str, 0, size, (u8)immediate);

    return;

}  /* sdLogPrintf */


