
/*
 *               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: sdmon.c,v 1.5 2008/10/29 20:50:36 horti Exp $";
 *
 */


#include <ios.h>
#include <iostypes.h>
#include <ioslibc.h>
#include <apputils.h>

#include "sdi.h"

#include <sd_api.h>	/* includes sdio_api shared */	

/* Alle eer aan die Redder, ons lig in die Hemel */

#define STACK_SIZE                  1024
const u8        _initStack[STACK_SIZE];
const u32       _initStackSize = sizeof(_initStack);
const u32       _initPriority = 11;

static SDDev dev;
static SDDevHandle fd = &dev;

u32 data[2048*512] __attribute__((aligned(4096)));   
#define BUF_SIZE (sizeof(data)/512) /* blocks */

static int writeFile(char *args, char *d);
static int readFile(char *args, char *d);
static int sdCardSize(char *args, char *d);
static int printStatus(char *args, char *d);

static Command commands[] = {
    {"help",    help,
        "help                       - Print this message", commands},
    {"read",  readFile,
        "read offset (in blocks) size (in blocks) filename  - Read from sd card data @offset into a file", 0},
    {"write", writeFile,
        "write offset (in blocks) filename      - Write file to sd card @offset", 0},
    {"size", sdCardSize,
        "size                       - Show sd card size", 0},
    {"stat", printStatus,
        "stat                       - Print SD card type and status"},
    {"source", source, "source <file>      - Execute commands from file", commands},
    {0},
};

/* 
 * Card Specific Data Register, size etc.
 */
int sdCardSize(char *args, char *d)
{
    s32 rc;
    u32 totalSize, totalSectors, sectorSize;

    rc = ISD_GetCardSize (fd, &totalSize, &totalSectors, &sectorSize);
    if (rc != IOS_ERROR_OK) {
    	printf("ISD_GetCardSize ERROR\n");
    } else {
    	printf("ISD_GetCardSize OK\n");
        printf("     1 block = 512 bytes\n");
        printf("     Sector Size   = %d blocks\n",sectorSize);
        printf("     Total Sectors = %d\n",totalSectors);
    	printf("     Card Capacity = %d blocks\n",totalSize); 
    }   
    return rc;
}
        
/* test for multiblock async, callback to done at filesys integration */                    
static int        
__readBlocks(SDDevHandle fd, u32 offset, u32 *buf, u32 length, FILE *fp)
{
    int rc;
    memset(buf, 0xa, BUF_SIZE << 9);
    rc = ISD_ReadMultiBlockAsync(fd, offset, buf, length, NULL, NULL);
    if (rc != IOS_ERROR_OK) {
        printf("SD Read Error:0x%x\n", rc);
        goto out;
    }  
    rc = fwrite(data, length << 9, 1, fp);
    if (rc != 1) {
        printf ("%s: bad write on file\n", __FUNCTION__);
        rc = -1;
        goto out;
    }
out:
    return rc;
}

int
sdReadFile(SDDevHandle fd, char *name, u32 offset, u32 length)
{
    FILE *fp = NULL;
    u32 i, niter, nrem;
    IOSError rc = IOS_ERROR_OK;
    
    printf("ISD_ReadMultiBlock(offset=0x%x (blocks) to data=0x%x blocks=%d)\n",
        offset, (unsigned int)data, length);

    niter = length / BUF_SIZE;
    nrem = length % BUF_SIZE;
    printf("niter: %u nrem: %u\n", niter, nrem);
   
    if (NULL == (fp = fopen(name, "wb"))) {
        printf ("%s: Can't open %s\n", __FUNCTION__, name);
        rc = -1;
        goto out;
    }
    for (i = 0; i < niter; ++i) {
        printf("%u:\n", i);
        rc =__readBlocks(fd, offset, data, BUF_SIZE, fp);
        if (rc < 0) {
            printf("reading %u blocks at offset %u failed\n", BUF_SIZE, offset);
            goto out;
        }
        printf("read: %u  blocks, offset %u blocks\n", BUF_SIZE, offset);
        offset += BUF_SIZE;
    }
    if (nrem) {
        rc =__readBlocks(fd, offset, data, nrem, fp);
        if (rc < 0) {
            printf("reading %u blocks at offset %u failed\n", nrem, offset);
            goto out;
        }
        printf("read: %u  blocks, offset %u blocks\n", nrem, offset);
    }
out:
    if (fp) fclose(fp);
    return rc;
}  

static int 
__writeBlocks(SDDevHandle fd, u32 offset, u32 data, u32 length, FILE *fp)
{
    int rc;
    rc = fread((char *)data, length << 9, 1, fp);
    if (rc != 1){
        printf ("%s: bad read on input file\n", __FUNCTION__);
        rc = -1;
        goto out;
    }
    rc = ISD_WriteMultiBlockAsync (fd, offset, data, length, NULL, NULL);
    if (rc != IOS_ERROR_OK) {
        printf("Write error:0x%x\n",rc);
        goto out;
    }
out:
    return rc;
}

int
sdWriteFile(SDDevHandle fd, char* name, u32 offset)
{
    FILE *fp = NULL;
    u32 length;
    u32 i, niter, nrem;
    int rc = 0;

    if (NULL == (fp = fopen(name, "rb"))) {
        printf ("%s: Can't open %s\n", __FUNCTION__, name);
        rc = -1;
        goto out;
    } 

    length = flen(fp);

    if (length % 512) {
        printf("File length: %u (not multiple of block size 512).\n", length);
        printf("Will write %u blocks\n", (length >> 9));
    }
    length >>= 9;
    niter = length / BUF_SIZE;
    nrem = length % BUF_SIZE;

    for (i = 0; i < niter; ++i) {
        rc = __writeBlocks(fd, offset, (u32)data, BUF_SIZE, fp);
        if (rc < 0) {
            printf("writing %u blocks at offset %u failed\n", BUF_SIZE, offset);            goto out;
        }
        offset += BUF_SIZE;
    }
    if (nrem) {
        rc = __writeBlocks(fd, offset, (u32)data, nrem, fp);
        if (rc < 0) {
            printf("writing %u blocks at offset %u failed\n", BUF_SIZE, offset);            goto out;
        }
    }

out:
    if (fp) fclose(fp);
    return rc;
}

static IOSError
readFile(char *args, char *d)
{
    IOSError rc = 0;
    u32 addr;
    u32 length;
    char *ptr;

    if (getNextToken(&ptr, &args) == 0) {
        rc = IOS_ERROR_INVALID;
        goto out;
    }
    addr = asciiToInt(ptr); /* blocks */

    if (getNextToken(&ptr, &args) == 0) {
        rc = IOS_ERROR_INVALID;
        goto out;
    }

    length = asciiToInt(ptr); /* blocks */
    if (getNextToken(&ptr, &args) == 0) {
        rc = IOS_ERROR_INVALID;
        goto out;
    }
    printf("Filename %s\n", ptr);

    sdReadFile(fd, ptr, addr, length);

out:
    return rc;

}

static IOSError
writeFile(char *args, char *d)
{
    IOSError rc = IOS_ERROR_OK;
    u32 addr;
    char *ptr;

    /* Get address on card to write to */
    if (getNextToken(&ptr, &args) == 0) {
        rc = IOS_ERROR_INVALID;
        goto out;
    }
    addr = asciiToInt(ptr);

    if (getNextToken(&ptr, &args) == 0) {
        rc = IOS_ERROR_INVALID;
        goto out;
    }

    printf("Filename %s\n", ptr);
    sdWriteFile(fd, ptr, addr); 

out:

    if (rc != IOS_ERROR_OK) {
        printf("write file failed, rc=%d\n", rc);
    }

    return (rc);
}

static int
printStatus(char *args, char *d)
{
    int rc;
    u32 stat;
    rc = ISD_GetDeviceStatus(fd, &stat);
    if (rc < 0) {
        printf("ISD_GetDeviceStatus failed: %d\n", rc);
        goto out;
    } else {
        printf("ISD_GetDeviceStatus: \n");
    }
    if (SD_CARD_REMOVED & stat) {
        printf("\tNo card present.\n");
        goto out;
    }
    if (SD_TYPE_UNKNOWN == (stat & 0xffff0000)) {
        printf("\tType: Unknown. Error.\n");
        goto out;
    }
    if (stat & SD_TYPE_MEMORY) {
        if (stat & SD_TYPE_HC) {
            printf("\tType: SDHC card\n");
        } else {
            printf("\tType: standard capacity SD card\n");
        }
    } else if (stat & SD_TYPE_SDIO) {
        printf("\tType: SDIO card\n");
    } else if (stat & SD_TYPE_MMC) {
        printf("\tType: MMC card\n");
    } else if (stat & SD_TYPE_COMBO) {
        printf("\tType: Combo card\n");
    }
    printf("\tCard state:");
    if (stat & SD_CARD_INSERTED) {
        printf("inserted ");
    }
    if (stat & SD_CARD_WPROTECTED) {
        printf("write protected");
    }
    printf("\n");
out:
    return rc;
}
#define LINE_SIZE 256

void
main(void)
{
    int rc;
    char line[LINE_SIZE];
    fd->SDDevSlot = 0;
    fd->SDDevFd = -1;

    printf("sdmon [");
    printf("built: " BUILD_TIME "]\n\n");

    rc = ISD_InitCard();
    rc = ISD_MountCard (fd->SDDevSlot,&fd); /* open */
    rc = ISD_ResetDevice(fd);  

    while (1) {
        printf("Enter command: ");
        gets(line);
        if (parseCommand(line, commands) < 0) {
            help(line, (void *)commands);
        }
    }
}
