/*
 *               Copyright (C) 2005, 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.
 *
 */

#include <types.h>
#include <sc/sc.h>
#include <ioslibc.h>
#include <apputils.h>
#include <sc/elf.h>

#include "minimon.h"

#define LINE_SIZE 256

int
quit(char *args, char *d)
{
    printf("Quitting...\n");
    exit(0);
    return 0;
}

int
reset(char *args, char *d)
{
    printf("Reseting...\n");
    IO_WRITE(SYS_CTRL_REG, SYS_CTRL_SOFT_RST);
    return 0;
}

int
load(char *args, char *d)
{
    char *name;
    FILE *fp = 0;
    int len = 0;

    if (getNextToken(&name, &args)) {
        int offset = MINIMON_BUF_OFFSET;
        char *offStr;
        if (getNextToken(&offStr, &args)) {
            offset = asciiToInt(offStr);
        }
        fp = fopen(name, "rb");
        if (fp == 0) {
            printf("fopen: unable to load file '%s'\n", name);
            goto out;
        }
        len = flen(fp);
        printf("Loading %d bytes from '%s' @ %#08x\n", len, name, offset);
        fread((void *)offset, len, 1, fp);
        if (offset >= MEM0_START) {
            SCWriteback((void *)offset, len);
            CCInvalidate((void *)offset, len);
        }
    } else {
        printf("Usage: load file [offset]\n");
    }
    printf("Load: '%s'\n", name);

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

#if defined(MINIMON_NOTROM) || !defined(FLASH)
int
os(char *args, char *d)
{
    char *name;
    FILE *fp = 0;
    int i, len = 0;
    Elf32_Ehdr ehdr;
    char buffer[1024];
    Elf32_Phdr *phdr = (Elf32_Phdr *)buffer;

    if (getNextToken(&name, &args)) {
        fp = fopen(name, "rb");
        if (fp == 0) {
            printf("fopen: unable to load file '%s'\n", name);
            goto out;
        }
        fread(&ehdr, sizeof(ehdr), 1, fp);
        u32 psize = ehdr.e_phentsize * ehdr.e_phnum;
        if (psize > sizeof(buffer)) {
            printf("Program headers too big (%d bytes)\n", psize);
            goto out;
        }
        fread(buffer, psize, 1, fp);
        for (i = 0; i < ehdr.e_phnum; ++i) {
            if (phdr[i].p_type == PT_LOAD) {
                u8 *buf = (u8*)phdr[i].p_vaddr;

#ifdef MINIMON_NOTROM
                /*
                 * Handle the special case when the first 32 bytes are
                 * involved (i.e. when copying the kernel). The first
                 * 32 bytes must have EXEC permission during semi-hosting
                 * operations
                 */
                if (phdr[i].p_vaddr < MINIMON_BUF_OFFSET) {
                    u8 tmpBuf[MINIMON_BUF_OFFSET];
                    u32 sz;

                    sz = MINIMON_BUF_OFFSET - phdr[i].p_vaddr;
                    fseek(fp, phdr[i].p_offset, SEEK_SET);
                    fread(tmpBuf, sz, 1, fp);

                    IO_WRITE(DAX_START, PT_ACCESS_RW << PT_SC_PROT_SHIFT);
                    IO_WRITE(DAX_START+16, PT_ACCESS_RW << PT_SC_PROT_SHIFT);
                    memcpy((void *)phdr[i].p_vaddr, tmpBuf, sz);

                    IO_WRITE(DAX_START, PT_ACCESS_EXEC << PT_SC_PROT_SHIFT);
                    IO_WRITE(DAX_START+16, PT_ACCESS_EXEC << PT_SC_PROT_SHIFT);
                }
#else
                if (phdr[i].p_vaddr < DA_START) buf += DA_START;
#endif

                if (phdr[i].p_filesz > 0) {
                    fseek(fp, phdr[i].p_offset, SEEK_SET);
                    fread(buf, phdr[i].p_filesz, 1, fp);
                }
                if (phdr[i].p_memsz > phdr[i].p_filesz) {
                    memset(buf + phdr[i].p_filesz, 0, phdr[i].p_memsz - phdr[i].p_filesz);
                }
                SCWriteback(buf, phdr[i].p_memsz);
                printf("Loaded segment [%08x, %08x]\n", phdr[i].p_vaddr, phdr[i].p_vaddr+phdr[i].p_memsz);
            }
        }
    } else {
        printf("Usage: os file\n");
        goto out;
    }
    printf("Launching OS\n");

    if (fp) {
        fclose(fp);
        fp = NULL;
    }
    for (i = 0; i < 256; i+=16) {
        IO_WRITE(DAX_START+i, PT_ACCESS_EXEC << PT_SC_PROT_SHIFT);
    }
    extern void mem_flip(void);
    for (i = 0; i < 4096; i+=16) {
        IO_WRITE(L1_DI_START+i, 1);
        IO_WRITE(L1_II_START+i, 1);
    }
    mem_flip();
out:
    if (fp) fclose(fp);
    return len;
}
#endif

int
exec(char *args, char *d)
{
    char *name;

    if (getNextToken(&name, &args)) {
        int i, len;
        u8 tmp[32];
        FILE *fp = fopen(name, "rb");
        if (fp == 0) {
            printf("fopen: unable to load file '%s'\n", name);
            goto out;
        }
        len = flen(fp);
        /* Mark dest as read/write while loading */
        fread(tmp, 32, 1, fp);
        IO_WRITE(DAX_START, PT_ACCESS_RW << PT_SC_PROT_SHIFT);
        IO_WRITE(DAX_START+16, PT_ACCESS_RW << PT_SC_PROT_SHIFT);
#ifdef MINIMON_NOTROM
        memcpy(0, tmp, 32);
#else
        memcpy((void *)DA_START, tmp, 32);
#endif
        IO_WRITE(DAX_START, PT_ACCESS_EXEC << PT_SC_PROT_SHIFT);
        IO_WRITE(DAX_START+16, PT_ACCESS_EXEC << PT_SC_PROT_SHIFT);
        for (i = 32; i < len; i+=16) {
            IO_WRITE(DAX_START+i, PT_ACCESS_RW << PT_SC_PROT_SHIFT);
        }
#ifdef MINIMON_NOTROM
        fread((void*)32, len-32, 1, fp);
#else
        fread((void*)DA_START+32, len-32, 1, fp);
#endif
        /* Mark dest as read/exec and invalidate L1 I/D caches */
        for (i = 32; i < len; i+=16) {
            IO_WRITE(DAX_START+i, PT_ACCESS_EXEC << PT_SC_PROT_SHIFT);
        }
        extern void mem_flip(void);
        for (i = 0; i < 4096; i+=16) {
            IO_WRITE(L1_DI_START+i, 1);
            IO_WRITE(L1_II_START+i, 1);
        }
        mem_flip();
    } else {
        printf("Usage: exec file\n");
    }
out:
    return 0;
}

int
dump(char *args, char *d)
{
    char *tok;
    unsigned long addr = 0;
    unsigned long words = 1, i;

    if (getNextToken(&tok, &args)) {
        addr = asciiToInt(tok);
        if (getNextToken(&tok, &args)) {
            words = asciiToInt(tok);
        }
    }

    for (i = 0; i < words; ++i) {
        if ((i & 3) == 0) {
            printf("%#08x: ", addr);
        }
        printf("%08x ", IO_READ(addr));
        addr += 4;
        if ((i & 3) == 3) {
            printf("\n");
        }
    }
    if ((i & 3) != 0) {
        printf("\n");
    }

    return 0;
}

#if 0
int
aes(char *args, char *d)
{
    char *tok;
    unsigned long from = 0, to = 0;
    unsigned long blocks = 0;

    if (getNextToken(&tok, &args)) {
        from = asciiToInt(tok);
        if (getNextToken(&tok, &args)) {
            to = asciiToInt(tok);
            if (getNextToken(&tok, &args)) {
                blocks = asciiToInt(tok);
            }
        }
    }
    printf("Move %#x bytes from %#08x -> %#08x\n", blocks*16, from, to);
    IO_WRITE(AES_RPTR_REG, CPU_TO_BUS_ADDR(from));
    IO_WRITE(AES_WPTR_REG, CPU_TO_BUS_ADDR(to));
    IO_WRITE(AES_CTRL_REG, AES_CTRL_EXEC | (AES_DMA_CMD << AES_CTRL_CMD_SHIFT) | ((blocks - 1)<<AES_CTRL_SIZE_SHIFT));
    while (IO_READ(AES_CTRL_REG) & AES_CTRL_EXEC);
    return 0;
}

int
sha(char *args, char *d)
{
    char *tok;
    unsigned long from = 0;
    unsigned long blocks = 0;
    int i;

    if (getNextToken(&tok, &args)) {
        from = asciiToInt(tok);
        if (getNextToken(&tok, &args)) {
            blocks = asciiToInt(tok);
        }
    }
    printf("Compute hash over %#x bytes from %#08x\n", blocks*64, from);
    /* Set initial values */
    IO_WRITE(SHA_CTRL_REG, 0x10 << 16);
    IO_WRITE(SHA_DATA_REG, 0x67452301);
    IO_WRITE(SHA_DATA_REG, 0xefcdab89);
    IO_WRITE(SHA_DATA_REG, 0x98badcfe);
    IO_WRITE(SHA_DATA_REG, 0x10325476);
    IO_WRITE(SHA_DATA_REG, 0xc3d2e1f0);

    IO_WRITE(SHA_MPTR_REG, CPU_TO_BUS_ADDR(from));

    IO_WRITE(SHA_CTRL_REG, SHA_CTRL_EXEC | ((blocks-1) << SHA_CTRL_SIZE_SHIFT));
    while (IO_READ(SHA_CTRL_REG) & SHA_CTRL_EXEC);
    IO_WRITE(SHA_CTRL_REG, 0x10 << 16);
    IO_READ(SHA_DATA_REG);
    for (i = 0; i < 5; ++i) {
        printf("%08x\n", IO_READ(SHA_DATA_REG));
    }
    return 0;
}
#endif

int
block(char *args, char *d)
{
    char *tok;
    unsigned long addr = 0, value = 0;
    unsigned long words = 0, i;

    if (getNextToken(&tok, &args)) {
        addr = asciiToInt(tok);
        if (getNextToken(&tok, &args)) {
            value = asciiToInt(tok);
            if (getNextToken(&tok, &args)) {
                words = asciiToInt(tok);
            }
        }
    }
    printf("Block fill %#x words from %#08x with %#08x\n", words, addr, value);
    for (i = 0; i < words; ++i) {
        IO_WRITE(addr, value);
        addr += 4;
    }
    return 0;
}

int
cif(char *args, char *d)
{
    char *tok;
    u32 DA = 0;
    u32 size = 0;
    u32 GBA = 0;
    int i;

    if (getNextToken(&tok, &args)) {
        DA = asciiToInt(tok);
        if (getNextToken(&tok, &args)) {
            size = asciiToInt(tok);
            if (getNextToken(&tok, &args)) {
                GBA = asciiToInt(tok);
            }
        }
    }
    IO_WRITE(CIF_CTRL_REG, CIF_CTRL_EMU | CIF_CTRL_EMU_ROM);
    IO_WRITE(ROM_CFG1_REG, ROM_CFG1_WIN_EN | 
                           ROM_CFG1_TYPE |
                           (GBA & ROM_CFG1_BASE_MASK));
    IO_WRITE(ROM_CFG2_REG, (size << ROM_CFG2_SIZE_SHIFT) |
                           (DA & ROM_CFG2_DA_MASK));
    for (i = 0; i < (16 << size); i+=16) {
        IO_WRITE(DAX_START+DA+i, (PT_ACCESS_RW << PT_CC_PROT_SHIFT) |
                                 (PT_ACCESS_RW << PT_SC_PROT_SHIFT));
    }
    printf("CIF_CTRL = %08x\n", IO_READ(CIF_CTRL_REG));
    printf("ROM_CFG1 = %08x\n", IO_READ(ROM_CFG1_REG));
    printf("ROM_CFG2 = %08x\n", IO_READ(ROM_CFG2_REG));
    return 0;
}

int
inf(char *args, char *d)
{
    while (1);
    return 0;
}

int
speed(char *args, char *d)
{
    unsigned int start, end;
    unsigned int sys_start, sys_end;
    unsigned int hz, ipart, dpart;
    volatile int i;
    printf("Running speed test...\n");
    start = time(0);
    sys_start = IO_READ(SYS_TIMER_REG);
    for (i = 0; i < 4000000; ++i);
    sys_end = IO_READ(SYS_TIMER_REG);
    end = time(0);
    hz = 200*(sys_end-sys_start)/(end-start);
    ipart = hz/1000000;
    dpart = (hz % 1000000)/10000;
    printf("speed = %d.%02dMHz\n", ipart, dpart);
    return 0;
}


#ifdef MINIMON_NOTROM

static u32 kpWriteProtect = 1;

/*
 * Wait on KP
 */
u32
kpWait()
{
    u32 ctrl;

    do {
        ctrl = IO_READ(KP_CTRL_REG);
        if( !(ctrl & KP_CTRL_EXEC)) {
            return(ctrl);
	}
    } while (1);

    return(0);
}

/*
 * read kilopass bit;
 * returns ctrl register;
 */
u32
kpReadBit(u32 addr)
{
    IO_WRITE(KP_CTRL_REG, KP_CTRL_EXEC | KP_CTRL_ISSUE_RST | addr);
    return((kpWait() & KP_CTRL_R) ? 1 : 0);
}

/*
 * write  kilopass bit;
 * returns ctrl register;
 */
u32
kpWriteBit(u32 addr)
{
    if (!kpWriteProtect) {
	if (addr > 0xffff) {
	    printf("Illegal address 0x%x\n", addr);
	    goto out;
	}
	IO_WRITE(KP_CTRL_REG, KP_CTRL_EXEC | KP_CTRL_ISSUE_RST |
		 KP_CTRL_WR | KP_CTRL_W | addr);
	return(kpWait());
    } else {
	printf("Write protect on 0x%x\n", addr);
    }

out:
    return 0;
}

/* 
 * Write up to 32 bits 
 */
int
kpWriteN(char *args, char *d)
{
    int i;
    char *tok;
    u32 addr = 0, n = 0, w = 0;

    if (getNextToken(&tok, &args)) {
        addr = asciiToInt(tok);
        if (getNextToken(&tok, &args)) {
            n = asciiToInt(tok);
            if (getNextToken(&tok, &args)) {
                w = asciiToInt(tok);
            }
        }
    } else {
        printf("Specify an address\n");
        goto out;
    }

    if ((n < 0) || (n > 32)) {
	printf("Illegal length (0<n<=32) %d\n", n);
	goto out;
    }
    for (i=0; i<n; i++) {
	if ((w>>i)&1) {
	    kpWriteBit(addr+i);
	}
    }
out:
    return 0;
}

/* 
 * Read up to 32 bits
 */
int
kpReadN(char *args, char *d)
{
    int i;
    u32 w = 0;
    char *tok;
    u32 addr = 0, n = 0;

    if (getNextToken(&tok, &args)) {
        addr = asciiToInt(tok);
        if (getNextToken(&tok, &args)) {
            n = asciiToInt(tok);
        }
    }
    if ((n < 0) || (n > 32)) {
	printf("Illegal length (0<n<=32) %d\n", n);
	return 0;
    }

    for (i=0; i<n; i++) {
	w |= (kpReadBit(addr+i)<<i);
    }
    printf("0x%x 0x%x\n", addr, w);

    return 0;
}

int
kpSetWp(char *args, char *d)
{
    char *tok;

    kpWriteProtect = 1;
    if (getNextToken(&tok, &args)) {
	if (strncmp(tok, "off", 3) == 0) {
	    printf("KP write protect is OFF!\n");
	    kpWriteProtect = 0;
	}
    }
    return 0;
}

int 
kpWriteF(char *args, char *d)
{
    int i, j;
    char *name;
    char *tok;
    u32 addr;
    FILE *fp;
    u8 ch;
    int len;
    int n = 8; // 8 bits at a time

    if (getNextToken(&name, &args)) {
        fp = fopen(name, "rb");
        if (fp == 0) {
            printf("fopen: unable to open file '%s'\n", name);
            goto out;
        }
	if (getNextToken(&tok, &args)) {
	    addr = asciiToInt(tok);
	    len = flen(fp);
	    printf("Writing %d bytes from '%s' to 0x%x\n", len, name, addr);
	    for (j=0; j<len; j++, addr+=n) {
		fread(&ch, 1, 1, fp);
		for (i=0; i<n; i++) {
		    if ((ch>>i)&1) {
			kpWriteBit(addr+i);
		    }
		}
	    }
        }
    }

out:
    return 0;

}

int 
kpReadH(char *args, char *d)
{
    int i;
    char *tok;
    u32 addr = 0;
    u8 buffer[20];

    memset(buffer, 0, sizeof(buffer));
    if (getNextToken(&tok, &args)) {
        addr = asciiToInt(tok);
    } 

    for (i = 0; i < 160; ++i) {
        buffer[i >> 3] |= (kpReadBit(addr+i) << (i & 7));
    }

    printf("0x%05x: ", addr);
    for (i=0; i<20; i++) {
        printf("0x%02x ", buffer[i]);
    }
    printf("\n");
    return 0;
}

#endif

static Command commands[] = {
    {"block", block, "block addr value words - Fill memory with a single value", 0},
    {"dump",  dump,  "dump addr [words]      - Dump data to screen", 0},
    {"exec",  exec,  "exec file              - Load, flip mem, and execute file", 0},
    {"load",  load,  "load file [address]    - Load file to address", 0},
#ifdef FLASH
    {"flash", flash, "flash                  - Access flash device", 0},
#endif
    //{"aes",   aes,   "aes from to blocks     - Move data in 16 byte blocks", 0},
    //{"sha",   sha,   "sha from blocks        - Compute SHA over 64 byte blocks", 0},
    {"cif",   cif,   "cif <DA base> size <GBA base>    - Setup cif for rom emulation", 0},
    {"inf",   inf,   "inf                    - Go into an infinite loop", 0},
#if defined(MINIMON_NOTROM) || !defined(FLASH)
    {"os",    os,    "os <file>              - Load an os image and execute it", 0},
#endif
#ifdef MINIMON_NOTROM
    {"kw", kpWriteN, "kw addr length data    - write kilopass", 0},
    {"kr", kpReadN,  "kr addr length         - read kilopass", 0},
    {"kwf",kpWriteF, "kwf file addr          - write kilopass from file", 0},
    {"krh",kpReadH, "krh addr                - read hash from kilopass", 0},
    {"kwp", kpSetWp, "kwp on/off             - set kilopass write protect", 0},
#endif
    {"speed", speed, "speed                  - Guess processor speed", 0},
    {"source",source,"source <file>          - Execute commands from file", commands},
    {"reset", reset, "reset                  - Reset the system", 0},
    {"help",  help,  "help                   - Print this message", commands},
    {"quit",  quit,  "quit                   - Exit the program", 0},
    {0},
};

#define MC_CTRL_TAP_1_8V    (12 << MC_CTRL_TAP_SHIFT)

void
__initSdram(int cl3)
{
    int i;
    u32 delay=10;

    /* Zero the SC & CC before changing cache configuration */
    for (i = 0; i < 64*1024; i+=16) {
        IO_WRITE(DAX_START+(192+64)*1024+i, 0);
        IO_WRITE(DAX_START+(192)*1024+i, 0);
    }

    /* Setup a cache configuration with DA, CC, and SC */
    IO_WRITE(SYS_CTRL_REG, (IO_READ(SYS_CTRL_REG) &
                        ~(SYS_CTRL_CACHE_CONF_MASK | SYS_CTRL_SOFT_RST)) |
                        SYS_CACHE_CONF_DA_192_CC_64_SC_64 | SYS_CTRL_CFG_EN);

    IO_WRITE(MC_CTRL_REG, MC_CTRL_TAP_1_8V);
    while (delay--);
    delay=150;

    /* Enable the SDRAM */
    IO_WRITE(MC_CTRL_REG, MC_CTRL_TAP_1_8V | MC_CTRL_ENA | MC_CTRL_PALL | 0x400);
    while (delay--);
    delay = 150;
    IO_WRITE(MC_CTRL_REG, MC_CTRL_TAP_1_8V | MC_CTRL_ENA | MC_CTRL_MRS | 0x2a);
    while (delay--);
    delay = 150;
    IO_WRITE(MC_CTRL_REG, MC_CTRL_TAP_1_8V | MC_CTRL_ENA);
    while (delay--);

    delay=10;
    IO_WRITE(MC_CTRL_REG, MC_CTRL_TAP_1_8V | MC_CTRL_ENA | MC_CTRL_DQM_ENA);
    while (delay--);

    /* Make first 32MB RW */
    u32 v = (((PT_ACCESS_RW << PT_CC_PROT_SHIFT) | (PT_ACCESS_RW << PT_SC_PROT_SHIFT)) << PT_ENTRY_SHIFT);
    u32 step = 16384;
    for (i = PT_START; i < PT_START+32*1024*1024; i += step) {
        IO_WRITE(i, v);
    }

    /* Invalidate the L1 caches */
    for (i = 0; i < 4096; i+=16) {
        IO_WRITE(L1_DI_START+i, 1);
        IO_WRITE(L1_II_START+i, 1);
    }

}

void
minimon(void)
{
    char line[LINE_SIZE];

    printf("SC Mini Monitor\n");
    printf("built: " BUILD_TIME "\n\n");

    IO_WRITE(PWR_CTRL_REG, PWR_CTRL_CLOCK_ON << PWR_CTRL_FLASH_SHIFT);
    IO_WRITE(PWR_CTRL_REG, PWR_CTRL_DEASSERT_RST << PWR_CTRL_FLASH_SHIFT);
    IO_WRITE(PWR_CTRL_REG, PWR_CTRL_CLOCK_ON << PWR_CTRL_AES_SHIFT);
    IO_WRITE(PWR_CTRL_REG, PWR_CTRL_DEASSERT_RST << PWR_CTRL_AES_SHIFT);
    IO_WRITE(PWR_CTRL_REG, PWR_CTRL_CLOCK_ON << PWR_CTRL_SHA_SHIFT);
    IO_WRITE(PWR_CTRL_REG, PWR_CTRL_DEASSERT_RST << PWR_CTRL_SHA_SHIFT);

    __initSdram(0);

    /* Enable ROM emulation */
    IO_WRITE(CIF_CTRL_REG, CIF_CTRL_EMU | CIF_CTRL_EMU_ROM);

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