/*
 * Copyright (c) 2013-2014, Freescale Semiconductor, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * o Redistributions of source code must retain the above copyright notice, this list
 *   of conditions and the following disclaimer.
 *
 * o Redistributions in binary form must reproduce the above copyright notice, this
 *   list of conditions and the following disclaimer in the documentation and/or
 *   other materials provided with the distribution.
 *
 * o Neither the name of Freescale Semiconductor, Inc. nor the names of its
 *   contributors may be used to endorse or promote products derived from this
 *   software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <string.h>
#include <stdio.h>

#include "board.h"
#include "pin_mux.h"
#include "gpio_pins.h"
#include "fsl_gpio_driver.h"
#include "spi_flash/spi_flash.h"
#include "fsl_device_registers.h"
#include "fsl_misc_utilities.h"

#include "cmd_handle.h"
#include "char_handle.h"

#ifndef SF_DEFAULT_SPEED
#define SF_DEFAULT_SPEED    1000000
#endif
#ifndef SF_DEFAULT_MODE
#define SF_DEFAULT_MODE     SPI_MODE_0
#endif
#ifndef SF_DEFAULT_CS
#define SF_DEFAULT_CS       0
#endif
#ifndef SF_DEFAULT_BUS
#define SF_DEFAULT_BUS      0
#endif

int32_t spi_cs_activate(spi_slave_dev *spi)
{
    switch (spi->cs)
    {
    case 0:
        gpio_write_pin_output(kGpioSpi0Cs0, spi->ss_pol);
        break;
    case 1:
        gpio_write_pin_output(kGpioSpi0Cs1, spi->ss_pol);
        break;
    default:
        break;
    }

    return 0;
}

int32_t spi_cs_deactivate(spi_slave_dev *spi)
{
    switch (spi->cs)
    {
    case 0:
        gpio_write_pin_output(kGpioSpi0Cs0, !(spi->ss_pol));
        break;
    case 1:
        gpio_write_pin_output(kGpioSpi0Cs1, !(spi->ss_pol));
        break;
    default:
        break;
    }

    return 0;
}

static spi_flash *flash;

#ifdef SPI_FLASH_CMD_TEST
#define MAX_LINE_LENGTH_BYTES (64)
#define DEFAULT_LINE_LENGTH_BYTES (16)
/*!
 * @brief Print data buffer in hex and ascii form to the terminal.
 *
 * data reads are buffered so that each memory address is only read once.
 * Useful when displaying the contents of volatile registers.
 *
 * @param[in] addr       Starting address to display at start of line
 * @param[in] data       Pointer to data buffer
 * @param[in] width      Data value width.  May be 1, 2, or 4.
 * @param[in] count      Number of values to display
 * @param[in] linelen    Number of values to print per line; specify 0 for default length
 */
int32_t print_buffer(uint32_t addr, uint8_t *data, uint32_t width, uint32_t count, uint32_t linelen)
{
    uint8_t linebuf[MAX_LINE_LENGTH_BYTES];
    uint32_t *uip = (void *)linebuf;
    uint16_t *usp = (void *)linebuf;
    uint8_t  *ucp = (void *)linebuf;
    int32_t i;

    if (linelen * width > MAX_LINE_LENGTH_BYTES)
    {
        linelen = MAX_LINE_LENGTH_BYTES / width;
    }
    if (linelen < 1)
    {
        linelen = DEFAULT_LINE_LENGTH_BYTES / width;
    }

    while (count)
    {
        printf("%08lx:", addr);

        /* check for overflow condition */
        if (count < linelen)
        {
            linelen = count;
        }

        /* Copy from memory into linebuf and print hex values */
        for (i = 0; i < linelen; i++)
        {
            if (width == 4)
            {
                uip[i] = *(volatile uint32_t *)data;
                printf(" %08x", uip[i]);
            }
            else if (width == 2)
            {
                usp[i] = *(volatile uint16_t *)data;
                printf(" %04x", usp[i]);
            }
            else
            {
                ucp[i] = *(volatile uint8_t *)data;
                printf(" %02x", ucp[i]);
            }
            data += width;
        }

        putc ('\r\n');

        /* update references */
        addr += linelen * width;
        count -= linelen;
    }

    return 0;
}
#endif

static int32_t do_spi_flash_probe(int32_t argc, char *argv[])
{
    uint32_t bus = SF_DEFAULT_BUS;
    uint32_t cs = SF_DEFAULT_CS;
    uint32_t speed = SF_DEFAULT_SPEED;
    uint32_t mode = SF_DEFAULT_MODE;
    char *endp;
    spi_flash *new_sf;

    if (argc >= 2)
    {
        cs = strtoul(argv[1], &endp, 0);
        if (*argv[1] == 0 || (*endp != 0 && *endp != ':'))
        {
            return 1;
        }
        if (*endp == ':')
        {
            if (endp[1] == 0)
            {
                return 1;
            }

            bus = cs;
            cs = strtoul(endp + 1, &endp, 0);
            if (*endp != 0)
            {
                return 1;
            }
        }
    }

    if (argc >= 3)
    {
        speed = strtoul(argv[2], &endp, 0);
        if (*argv[2] == 0 || *endp != 0)
        {
            return 1;
        }
    }

    if (argc >= 4)
    {
        mode = strtoul(argv[3], &endp, 16);
        if (*argv[3] == 0 || *endp != 0)
        {
            return 1;
        }
    }

    new_sf = spi_flash_probe(bus, cs, speed, mode);
    if (!new_sf)
    {
        printf("Failed to initialize SPI flash at %u:%u\r\n", (unsigned int)bus, (unsigned int)cs);
        return 1;
    }

    if (flash)
    {
        spi_flash_free(flash);
    }

    flash = new_sf;

    return 0;
}

/*!
 * @brief Write a block of data to SPI flash, first checking if it is different from
 * what is already there.
 *
 * If the data being written is the same, then *skipped is incremented by len.
 *
 * @param[in] flash      flash context pointer
 * @param[in] offset     flash offset to write
 * @param[in] len        number of bytes to write
 * @param[in] buf        buffer to write from
 * @param[in] cmp_buf    read buffer to use to compare data
 * @param[in] skipped    Count of skipped data (incremented by this function)
 *
 * @return NULL if OK, else a string containing the stage which failed
 */
static const char *spi_flash_update_block(spi_flash *flash, uint32_t offset,
        size_t len, const int8_t *buf, int8_t *cmp_buf, size_t *skipped)
{
#ifdef DEBUG_SF
    printf("offset=%x, sector_size=%x, len=%x\r\n",
        offset, flash->sector_size, len);
#endif
    if (spi_flash_read(flash, offset, len, cmp_buf))
    {
        return "read";
    }
    if (memcmp(cmp_buf, buf, len) == 0)
    {
        printf("Skip region %x size %x: no change\r\n",
            (unsigned int)offset, (unsigned int)len);
        *skipped += len;
        return NULL;
    }
    if (spi_flash_erase(flash, offset, len))
    {
        return "erase";
    }
    if (spi_flash_write(flash, offset, len, buf))
    {
        return "write";
    }
    return NULL;
}

/*!
 * @briedf Update an area of SPI flash by erasing and writing any blocks which need
 * to change. Existing blocks with the correct data are left unchanged.
 *
 * @param[in] flash      flash context pointer
 * @param[in] offset     flash offset to write
 * @param[in] len        number of bytes to write
 * @param[in] buf        buffer to write from
 *
 * @return 0 if ok, 1 on error
 */
static int32_t spi_flash_update(spi_flash *flash, uint32_t offset,
        size_t len, const int8_t *buf)
{
    const char *err_oper = NULL;
    int8_t *cmp_buf;
    const int8_t *end = buf + len;
    size_t todo;        /* number of bytes to do in this pass */
    size_t skipped = 0;    /* statistics */

    cmp_buf = malloc(flash->sector_size);
    if (cmp_buf)
    {
        for (; buf < end && !err_oper; buf += todo, offset += todo)
        {
            todo = MIN(end - buf, flash->sector_size);
            err_oper = spi_flash_update_block(flash, offset, todo,
                    buf, cmp_buf, &skipped);
        }
    }
    else
    {
        err_oper = "malloc";
    }
    free(cmp_buf);
    putc('\r');
    if (err_oper)
    {
        printf("SPI flash failed in %s step\r\n", err_oper);
        return 1;
    }

    printf("%u bytes written, %u bytes skipped\r\n", len - skipped,
        skipped);

    return 0;
}

static int32_t do_spi_flash_read_write(int32_t argc, char *argv[])
{
    uint32_t addr;
    uint32_t offset;
    uint32_t len;
    void *buf;
    char *endp;
    int32_t ret = 1;

    if (argc < 4)
    {
        return 1;
    }

    /* Command require a selected device */
    if (!flash)
    {
        cmd_puts("No SPI flash selected. Please run `probe' first\r\n");
        return 1;
    }

    addr = strtoul(argv[1], &endp, 16);
    if (*argv[1] == 0 || *endp != 0)
    {
        return 1;
    }
    offset = strtoul(argv[2], &endp, 16);
    if (*argv[2] == 0 || *endp != 0)
    {
        return 1;
    }
    len = strtoul(argv[3], &endp, 16);
    if (*argv[3] == 0 || *endp != 0)
    {
        return 1;
    }

    /* Consistency checking */
    if (offset + len > flash->size)
    {
        printf("ERROR: attempting %s past flash size (%#x)\r\n",
            argv[0], (unsigned int)flash->size);
        return 1;
    }

    buf = (void *)addr;
    if (strcmp(argv[0], "update") == 0)
    {
        ret = spi_flash_update(flash, offset, len, buf);
    }
    if (strcmp(argv[0], "read") == 0)
    {
        ret = spi_flash_read(flash, offset, len, buf);
    }
    if (strcmp(argv[0], "write") == 0)
    {
        ret = spi_flash_write(flash, offset, len, buf);
    }

    if (ret)
    {
        printf("SPI flash %s failed\r\n", argv[0]);
        return 1;
    }

    return 0;
}

/*!
 * @brief This function computes the length argument for the erase command.
 *
 * The length on which the command is to operate can be given in two forms:
 * 1. <cmd> offset len  - operate on <'offset',  'len')
 * 2. <cmd> offset +len - operate on <'offset',  'round_up(len)')
 * If the second form is used and the length doesn't fall on the
 * sector boundary, than it will be adjusted to the next sector boundary.
 * If it isn't in the flash, the function will fail (return 1).
 *
 * @param[in]   arg        length specification (i.e. both command arguments)
 * @param[out]  len        computed length for operation
 *
 * @return:
 *    1: success
 *   -1: failure (bad format, bad address).
 */
static int32_t sf_parse_len_arg(char *arg, uint32_t *len)
{
    char *ep;
    int8_t round_up_len; /* indicates if the "+length" form used */
    uint32_t len_arg;

    round_up_len = 0;
    if (*arg == '+')
    {
        round_up_len = 1;
        ++arg;
    }

    len_arg = strtoul(arg, &ep, 16);
    if (ep == arg || *ep != '\0')
    {
        return 1;
    }

    if (round_up_len && flash->sector_size > 0)
    {
        *len = ROUND(len_arg, flash->sector_size);
    }
    else
    {
        *len = len_arg;
    }

    return 0;
}

static int32_t do_spi_flash_erase(int32_t argc, char *argv[])
{
    uint32_t offset;
    uint32_t len;
    char *endp;
    int32_t ret;

    if (argc < 3)
    {
        return 1;
    }

    /* Command require a selected device */
    if (!flash)
    {
        cmd_puts("No SPI flash selected. Please run `probe' first\r\n");
        return 1;
    }

    offset = strtoul(argv[1], &endp, 16);
    if (*argv[1] == 0 || *endp != 0)
    {
        return 1;
    }

    if (sf_parse_len_arg(argv[2], &len))
    {
        return 1;
    }

    /* Consistency checking */
    if (offset + len > flash->size)
    {
        printf("ERROR: attempting %s past flash size (%#x)\r\n",
            argv[0], (unsigned int)flash->size);
        return 1;
    }

    ret = spi_flash_erase(flash, offset, len);
    if (ret)
    {
        printf("SPI flash %s failed\r\n", argv[0]);
        return 1;
    }

    return 0;
}

static int32_t do_spi_flash_print_usage(int32_t argc, char *argv[])
{
    printf("SPI flash sub-system\r\n"
    "probe [[bus:]cs] [hz] [mode]    - init flash device on given SPI bus\r\n"
    "                  and chip select\r\n"
    "read addr offset len     - read `len' bytes starting at\r\n"
    "                  `offset' to memory at `addr'\r\n"
    "write addr offset len    - write `len' bytes from memory\r\n"
    "                  at `addr' to flash at `offset'\r\n"
    "update addr offset len  - erase and write `len' bytes from memory\r\n"
    "                  at `addr' to flash at `offset'\r\n"
    "erase offset [+]len        - erase `len' bytes from `offset'\r\n"
    "                  `+len' round up `len' to block size\r\n"
    "help - print usage\r\n"
    );

    return 0;
}

cmd_tbl_t sf_cmd_tbl[SPI_FLASH_FUNC_NUM] = {
    { "probe", 4, do_spi_flash_probe },
    { "read",  4, do_spi_flash_read_write },
    { "write", 4, do_spi_flash_read_write },
    { "update", 4, do_spi_flash_read_write },
    { "erase", 3, do_spi_flash_erase },
    { "help",  1, do_spi_flash_print_usage },
};

void main(void)
{
    /* Init hardware and debug uart */
    hardware_init();
    dbg_uart_init();

    configure_spi_cs0_pin_mux(0);
    configure_spi_cs1_pin_mux(0);
    
    gpio_init(NULL, spiCsPin);

    /* Print out message */
    printf("\r\n\tSPI Flash Subsystem Test\r\n\r\n");

    for (;;)
    {
        cmd_handle_loop();
    }
}

