#ifndef SPIFLASH_H
#define SPIFLASH_H

#include <inttypes.h>
#include <stddef.h>
#include <string.h>

/*
 * Firmware blob data header. A dlen of 0 means no futher blobs.
 * dlen == zlen means raw binary data, not compressed.
 */
#define SPIFLASH_MAGIC		0xe301e7eb
#define SPIFLASH_HEADER_CRC32	0x99d8ef20

struct spiflash_header {
    uint32_t magic;		/* Magic number */
    uint32_t zlen;		/* Compressed data length */
    uint32_t dlen;		/* Uncompressed data length */
    uint32_t crc32;		/* CRC32 of (raw) data block */
    uint32_t address;		/* Target address in flash (block aligned) */
    uint32_t resv[2];		/* Set to zero for now */
    uint32_t header_crc32;	/* CRC32 of above fields */
};

/*
 * A page is the maximum amount that can be programmed in one operation.
 * A sector is the minimum amount that can be erased in one operation.
 * A block is the optimal amount that can be erased in one operation.
 *
 * These are defined in hardware!
 */
#define SPIFLASH_PAGE_SHIFT	8
#define SPIFLASH_PAGE_SIZE	(1 << SPIFLASH_PAGE_SHIFT)
#define SPIFLASH_SECTOR_SHIFT	12
#define SPIFLASH_SECTOR_SIZE	(1 << SPIFLASH_SECTOR_SHIFT)
#define SPIFLASH_BLOCK_SHIFT	16
#define SPIFLASH_BLOCK_SIZE	(1 << SPIFLASH_BLOCK_SHIFT)

/*
 * Interface to the host. This structure should be passed in to the
 * initialization routine and will not be modified by the spiflash
 * routines.
 *
 * The spiflash code is reentrant if there are multiple SPI flash
 * devices. None are timing critical and may be preempted at any
 * time if applicable. When CS# is active (during spi_read or spi_write),
 * it MUST NOT be deasserted; if the bus is shared HOLD# can be asserted
 * (without deasserting CS#) to make the device release the bus without
 * affecting the state of the device.
 *
 * CS# will not be asserted while running in the core code or when
 * blocking for I/O; the host is obviously allowed to prefetch I/O
 * within the above constraints if the bus is shared.
 *
 * A private cookie pointer is passed to each function; this can be a
 * pointer back to the spiflash_ops structure, but does not have to
 * be.
 */
struct spiflash_ops {
    /*
     * Read input data for flash write. Return the number of bytes
     * read.  A short read or a 0 byte return value represents end of
     * file/end of data; a negative value is treated as 0, and will be
     * returned from the top-level operation as a status code.
     *
     * It is not required to detect end of input if and only if the
     * input is a gzip file, as in that case the gzip data will contain
     * an end of stream indicator.
     *
     * The buffer initially passed to this function will always be
     * aligned to a malloc() alignment boundary; it will preserve
     * alignment boundaries if and only if short read returns only byte
     * counts in multiple of those alignment boundaries.
     *
     * If there is a memory buffer available containing full or
     * partial input data on entry, pass it to spiflash_flash_file();
     * If this memory buffer contains all available input, this
     * function can be NULL.
     *
     * A partial memory buffer must contain the full stream header.
     *
     * A full memory buffer must either be expanded to a multiple
     * of SPIFLASH_BLOCK_SIZE or safely allow the flash code to do so.
     */
    int (*read_data)(void *cookie, void *buf, unsigned int bufsize);

    /*
     * Indicates that no more data will be read (end of stream detected
     * or an error happened.) May be NULL. A nonzero value will be passed
     * to the top-level routine as an error.
     */
    int (*close_data)(const z_stream *zs, void *cookie);

    /*
     * Perform a SPI write operation. The SPI write operation consists of:
     * 1. Assert CS# (and deassert HOLD# if applicable)
     * 2. Transmit the command bytes (discard MISO input)
     * 3. Transmit the data bytes (discard MISO input)
     * 4. Deassert CS#
     * 5. Wait tCHSL (see SPI data table below)
     *
     * The number of data bytes may be zero. Note that the command
     * and data operations are identical and are separated only to
     * avoid unnecessary data copies.
     *
     * If this returns nonzero, no further operations are performed
     * and the top-level flash routine terminates immediately with
     * the returned value as a status code.
     *
     * It is not required that this routine blocks until tCHSL
     * is satisfied, however, the host is responsible to not assert
     * CS# again until tCHSL is satisfied. The SPI clock may run
     * or not during that time period.
     *
     * The SPI flash supports SPI modes 0 and 3.
     */
    int (*spi_write)(void *cookie,
		     const void *cmd, unsigned int cmd_len,
		     const void *data, unsigned int data_len,
		     int tshsl);

    /*
     * Perform a SPI read operation. The SPI read operation consists of:
     * 1. Assert CS# (and deassert HOLD# if applicable)
     * 2. Transmit the command bytes (discard MISO input)
     * 3. Receive the data bytes (MOSI is don't care)
     * 4. Deassert CS#
     * 5. Wait tCHSL (see SPI data table below)
     *
     * The number of data bytes may be zero. Note that the command
     * and data operations are identical and are separated only to
     * avoid unnecessary data copies.
     *
     * If this returns nonzero, no further operations are performed
     * and the top-level flash routine terminates immediately with
     * the returned value as a status code.
     *
     * It is not required that this routine blocks until tCHSL
     * is satisfied, however, the host is responsible to not assert
     * CS# again until tCHSL is satisfied. The SPI clock may run
     * or not during that time period.
     *
     * The SPI flash supports SPI modes 0 and 3.
     */
    int (*spi_read)(void *cookie,
		    const void *cmd, unsigned int cmd_len,
		    void *data, unsigned int data_len,
		    int tshsl);

    /*
     * Inform the host that the spiflash code is waiting for an
     * program or erase operation to complete. This can be used to
     * yield the host for other operations.
     *
     * The value passed in is the corresponding from the SPI data
     * table below; these are arbitrary cookies/units as far as the
     * spiflash code is concerned.
     *
     * This function may be NULL, in which case the SPI flash is polled
     * continously.
     */
    void (*yield)(void *cookie, int delay);
};

/*
 * This table provides some parameters for the SPI flash.
 */
enum spiflash_addr_mode {
    SPIFLASH_ADDR_DYNAMIC,	/* 24-bit for < 16 MB, otherwise 32 bit */
    SPIFLASH_ADDR_24BIT,	/* 24-bit addressing only */
    SPIFLASH_ADDR_32BIT		/* 32-bit addressing only */
};

struct spiflash_param {
    /*
     * Addressing mode (see above.) If SPIFLASH_ADDR_DYNAMIC is
     * specified (default), the chip is assumed to be in 24-bit-default
     * mode, and 32-bit opcodes will be used as needed.
     */
    enum spiflash_addr_mode addr;

    /*
     * CS# deselect times passed to spi_read() and spi_write().
     * Arbitrary units or cookies that are only interpreted by
     * the spi_read and spi_write routines.
     */
    int tshsl;			/* All other operations */
    int tshsl1;			/* Read operations */
    int tshsl2;			/* Erase, Program, and Write operations */

    /*
     * Delay values to pass to the yield operation. Arbitrary units
     * or cookies that are only interpreted by the yield routine.
     *
     * Not all of these are used by the current code, but are specified
     * for future-proofing reasons.
     */
    int trst;			/* Reset command to next instruction */
    int tw;			/* Write Status Register Time */
    int tpp;			/* Page Program Time */
    int tse;			/* Sector Erase Time (4K) */
    int tbe1;			/* Block Erase Time (32K) */
    int tbe2;			/* Block Erase Time (64K) */
    int tce;			/* Chip Erase Time */
};

/* Common structure for the above */
struct spiflash {
    const struct spiflash_ops *ops;
    void *cookie;		/* Pointer passed to spiflash_ops functions */
    const struct spiflash_param *param;
};

/*
 * Additional error codes
 */
#define SPIFLASH_ERR_ERASE_FAILED	(-7)
#define SPIFLASH_ERR_PROGRAM_FAILED	(-8)

/*
 * Top-level operations. These may return an error value from the ops
 * functions, any of the negative error values defined in zlib.h,
 * or one of the above error codes.
 */
int spiflash_flash_file(const struct spiflash *flash,
			void *data, size_t datalen);

/*
 * Read identifying data from SPI flash.
 */
#define SPIFLASH_ID_LEN 8
int spiflash_read_id(const struct spiflash *flash, void *id);

#define SPIFLASH_VDID_LEN 2
int spiflash_read_vdid(const struct spiflash *flash, void *vdid);

#endif
