#include <sc/sc.h>
#include "sce.h"
#include "sctrl.h"
#include "cpu.h"
#include "memory.h"
#include "fl.h"

#define ECC_UNIT 512
typedef struct {
    /* Flash controller registers */
    u32 id;
    u32 ctrl;
    u32 conf;
    u32 ad0;
    u32 ad1;
    u32 ma0;
    u32 ma1;

    /* Internal flash controller state */
    u32 spare;  /* Size of spare area: only set if ECC is on */
    u32 ima1;   /* Internal ma1 counter that increments */
    bool intr;  /* Boolean indicating if an interrupt is pending */
    u8 buffer[16]; /* Cacheline buffer */
    u8 *ptr;    /* ptr into cacheline buffer */
    bool seen_busy; /* have we seen busy yet? */
    u8 eccBuffer[ECC_UNIT];
    u8 *eccPtr;
    u32 eccUnit;
} Fl;

static Fl fl;

Nand *nand = NULL;

extern Nand samsung64;
extern Nand samsung128;
extern Nand toshiba64;
extern Nand toshiba128;

static u32
__flComputeEcc(const u8 *buf)
{
    u32     ecc = 0x0, count = 0;
    u8      parity[12], parity_p[12];

    for (count = 0; count < 12; count++) {
        parity[count] = 0x0;
        parity_p[count] = 0x0;
    }

    for (count = 0; count < ECC_UNIT; count++) {
        u8  bits[8], bitCount = 0, allBits = 0x0, parityCount = 0;

        for (bitCount = 0; bitCount < 8; bitCount++) {
            bits[bitCount] = ((buf[count] & (1 << bitCount)) >> bitCount);
        }
        allBits = bits[0] ^ bits[1] ^ bits[2] ^ bits[3] ^ bits[4] ^
                bits[5] ^ bits[6] ^ bits[7];

        /* Column parity */
        parity[0] ^= bits[1] ^ bits[3] ^ bits[5] ^ bits[7];
        parity_p[0] ^= bits[0] ^ bits[2] ^ bits[4] ^ bits[6];
        parity[1] ^= bits[2] ^ bits[3] ^ bits[6] ^ bits[7];
        parity_p[1] ^= bits[0] ^ bits[1] ^ bits[4] ^ bits[5];
        parity[2] ^= bits[4] ^ bits[5] ^ bits[6] ^ bits[7];
        parity_p[2] ^= bits[0] ^ bits[1] ^ bits[2] ^ bits[3];

        /* Row parity */
        for (parityCount = 3; parityCount < 12; parityCount++) {
            if ((count >> (parityCount - 3)) & 0x1) {
                parity[parityCount] ^= allBits;
            } else {
                parity_p[parityCount] ^= allBits;
            }
        }
    }

    /* Combine parity into ECC syndrome */
    for (count = 0; count < 12; count++) {
        ecc |= ((parity[count] & 0x1) << (16 + count)) |
                ((parity_p[count] & 0x1) << count);
    }


    return (ecc);
}

void flConfWrite(u32 val)
{
    fl.conf = val;
    nand->enable(val & FL_CONF_DEV);
    nand->wp(val & FL_CONF_WP);
}

void flCtrlWrite(u32 val)
{
    if (val & FL_CTRL_EXEC) {
        if (fl.ctrl & FL_CTRL_EXEC) {
            /* flash ctrl is already busy */
            error("FL: attempt to exec new cmd while flash is busy\n");
            return;
        } else {
            /* start a new flash command */
            log(LOG_FLASH, "FL: exec flash cmd: %08x\n", val);
            if (!(fl.conf & FL_CONF_DEV)) {
                error("FL: attempt to exec new cmd while flash device is disabled\n");
            }
            fl.ctrl = val & ~(0xf|FL_CTRL_MVIOL);

            /* Compute size of spare area if ECC is enabled */
            fl.spare = (val & FL_CTRL_ECC) ? FL_CTRL_SIZE(val) & 511 : 0;
            fl.eccPtr = fl.eccBuffer;
            fl.eccUnit = 0;

            /* Reset internal ma1 pointer */
            fl.ima1 = fl.ma1;

            /* Reset cacheline buffer pointer */
            fl.ptr = fl.buffer;
            
            /* Reset busy status */
            fl.seen_busy = false;

            /* send command */
            nand->mode(NAND_MODE_CMD);
            u8 data = FL_CTRL_CMD(fl.ctrl);
            nand->io(MEMORY_WRITE, &data);

            /* send the address, if necessary */
            u8 adp = FL_CTRL_ADP(fl.ctrl);
            if (adp) {
                u64 addr = (fl.ad0 & FL_AD0_PTR_MASK) |
                      ((fl.ad1 & FL_AD1_PTR_MASK) << 16);
                nand->mode(NAND_MODE_ADDR);
                while (adp) {
                    if (adp & 1) {
                        data = addr;
                        nand->io(MEMORY_WRITE, &data);
                    }
                    addr >>= 8;
                    adp >>= 1;
                }
            }

            /* enter read/write phase */
            u32 t;
            if ((t = (fl.ctrl & (FL_CTRL_RDP|FL_CTRL_WDP)))) {
                if (t == (FL_CTRL_RDP|FL_CTRL_WDP)) {
                    error("FL: illegal flash command with read and write phase: %08x\n", fl.ctrl);
                }
                nand->mode(NAND_MODE_DATA);
            }
        }
    } else {
        fl.ctrl &= ~FL_CTRL_EXEC;
        fl.intr = 0;
    }

}

int flTick(void)
{
    u32 *addr;

    if (fl.ctrl & FL_CTRL_EXEC) {
        if (fl.ctrl & FL_CTRL_RDY) {
            if (fl.seen_busy) {
                if (nand->busy()) {
                    goto wait_busy;
                }
            } else {
                if (nand->busy()) {
                    fl.seen_busy = 1;
                }
                goto wait_busy;
            }
        }
        bool finished = 1;
        bool read = fl.ctrl & FL_CTRL_RDP;
        bool write = fl.ctrl & FL_CTRL_WDP;
        u32 size = FL_CTRL_SIZE(fl.ctrl);
        u32 tid = FL_ID_DTID(fl.id);
        if (read|write) {
            if (size > 0) {
                if (read) nand->io(MEMORY_READ, fl.ptr++);
                addr = (size > fl.spare) ? &fl.ma0 : &fl.ima1;
                if ((write && (size-- & 0xf) == 0) ||
                    (read  && (--size & 0xf) == 0)) {
                    if (SCMemoryAccess(MEMORY_SRC_DEV, tid, MODE_USR, BUS_TO_CPU_ADDR(*addr), fl.buffer, sizeof(fl.buffer), read ? MEMORY_WRITE : MEMORY_READ, NULL, NULL) < 0) {
                        fl.ctrl |= FL_CTRL_MVIOL;
                        goto done;
                    }
                    if (fl.ctrl & FL_CTRL_ECC) {
                        memcpy(fl.eccPtr, fl.buffer, sizeof(fl.buffer));
                        fl.eccPtr += sizeof(fl.buffer);
                        if ((fl.eccPtr - fl.eccBuffer) == ECC_UNIT) {
                            u32 ecc = __flComputeEcc(fl.eccBuffer);
                            if (SCMemoryAccess(MEMORY_SRC_DEV, tid, MODE_USR, BUS_TO_CPU_ADDR(fl.ma1+64+sizeof(ecc)*fl.eccUnit), (u8*)&ecc, sizeof(ecc), MEMORY_WRITE, NULL, NULL) < 0) {
                                fl.ctrl |= FL_CTRL_MVIOL;
                                goto done;
                            }
                            fl.eccPtr = fl.eccBuffer;
                            ++fl.eccUnit;
                        }
                    }
                    *addr += 16;
                    fl.ptr = fl.buffer;    
                }
                if (write) nand->io(MEMORY_WRITE, fl.ptr++);
                fl.ctrl &= ~FL_CTRL_SIZE_MASK;
                fl.ctrl |= (size << FL_CTRL_SIZE_SHIFT);
                finished = 0;
            }
        }
done:
        if (finished) {
            fl.ctrl &= ~FL_CTRL_EXEC;
            if (fl.ctrl & FL_CTRL_MASK) {
                fl.intr = 1;
            }
        }
    }
wait_busy:
    return fl.intr;
}

extern u32 flashSize;
void flInit(void)
{
    u32 *i = &fl.id;
    regmap[FL_ID_REG] = Register(&fl.id, i, 0xffffffff, KO);
    regmap[FL_CTRL_REG] = Register(&fl.ctrl, i, 0, RW, flCtrlWrite);
    regmap[FL_CONF_REG] = Register(&fl.conf, i, 0, RW, flConfWrite);
    regmap[FL_AD0_REG] = Register(&fl.ad0, i, FL_AD0_PTR_MASK);
    regmap[FL_AD1_REG] = Register(&fl.ad1, i, FL_AD1_PTR_MASK);
    regmap[FL_MA0_REG] = Register(&fl.ma0, i, FL_MA0_PTR_MASK);
    regmap[FL_MA1_REG] = Register(&fl.ma1, i, FL_MA1_PTR_MASK);

    if (flashSize == 2048) {
        nand = &samsung128;
    } else if (flashSize == 512) {
        nand = &toshiba64;
    } else {
        error("Unknown flash size: %d\n", flashSize);
        exit(-1);
    }

    nand->init();
}

void flReset(void)
{
    memset(&fl, 0, sizeof(fl));
    fl.conf = (  FL_CONF_WP | 
               (  7 << FL_CONF_EOC_SHIFT) |
               (  5 << FL_CONF_RSA_SHIFT) |
               ( 62 << FL_CONF_REA_SHIFT) |
               ( 62 << FL_CONF_WEA_SHIFT) |
               (255 << FL_CONF_CAA_SHIFT)
              );
}

void flShutdown(void)
{
    nand->shutdown();
}
