/*
 * eeprom_m95m04.c
 *
 *  Created on: 6/06/2021
 *      Author: alexrayne <alexraynepe196@gmail.com>
  ------------------------------------------------------------------------
    Copyright (c) alexrayne

   All rights reserved.
   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:
   - Redistributions of source code must retain the above copyright
     notice, this list of conditions and the following disclaimer.
   - 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.
   - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. *
  ------------------------------------------------------------------------
 * драйвера чипов SPI флеш xx25xxx:
 *  MX25R3235F - macronix 32M spi/qpi flash
 */

#include <c_compat.h>
#include "flashspi_x25.h"
#include <OsTime.h>


/////////////////////////////////////////////////////////////////////////////

/* maximum timeouts for ultra low power mode
 * */
const struct FlashChipDescribe   info_mx25r32 = {
    struct_field(nb_sectors)          MX25R32_SECTORS ,
    struct_field(nb_pages_in_sector)  MX25R32_SEC_PAGES,
    struct_field(page_size)           MX25_PAGE_SIZE ,
    //                                                                     1byte write takes 100us
    struct_field(burn_page_ticks)     (FLASH_toYIELD*2) +CLOCKMS_MORE(10) +3*FLASH_toSPIN ,
    struct_field(erase_ticks)         CLOCKMS_MORE(240) ,
    struct_field(erase_all_ticks)     TICK_AS_FLASHTO( 120*CLOCK_SECOND ) ,
    // erase 64K: 3500ms
};

DevResult mx25ru_bind(FLASH_Device* self){
    SPIFLASH_MX25R* this = (SPIFLASH_MX25R*)self;

    flash_assign_info(self, &info_mx25r32);

    union {
        int32_t     raw;
        struct{
            uint8_t     manufid;
            uint8_t     memid;
            uint8_t     sizeid;
        };
    } id;

    id.raw = mx25ru_read_id(this);
    if (id.raw <= 0)
        return DEV_NOK;

    if ( id.manufid == FLASHID_MACRONIX )
    if ( (id.memid == FLASHID_MX25R) || (id.memid == FLASHID_MX25U) )
    {
        unsigned  sizeid = id.sizeid & 0x1f;

        // suspicious ID, macronix not declared it
        if (sizeid < 0x15)
            return DEV_NO_SUPPORT_IDMEM_ERR;

        if (sizeid > 0x18){
            /* For Macronix MX25xxx, if the MEMORY_CAPACITY ID is bigger than 0x18, the falsh's desity is larger than 128Mbit,
                so the 4 bytes address is needed */
            sspdev_style(&this->ssp, SSPDEV_addr4BYTE | SSPDEV_addrMSB);
        }

        /* get the memory capacity in MByte units from the MEMORY_CAPACITY ID information */
        self->_size = 1ul << sizeid;

        return DEV_OK;
    }
    return DEV_NO_SUPPORT_ID_ERR;
}


DevResult mx25ru_init(SPIFLASH_MX25R* this){
    wre_flashspi_init(this);
    this->flash.bind    = mx25ru_bind;
    this->CMD_SE        = FLASH_CMD_SE_4K;

    sspio_set_mode(&this->ssp.io, sspio_mode_default_8bit);
    sspdev_style(&this->ssp, SSPDEV_addr3BYTE | SSPDEV_addrLE);

    this->flash.id      = NULL;

    return DEV_OK;
}

void mx25ru_connect(SPIFLASH_MX25R* this, SSP_IOPort*    _port){
    sspio_connect(&this->ssp.io, _port, sspio_mode_default_8bit, SSP_speedKEEP);
}


long mx25ru_read_id(SPIFLASH_MX25R* self){
    SPIFlash_GenDevice* this = (SPIFlash_GenDevice*)self;
    uint32_t            idtmp = FLASH_CMD_RDID;

    int readen = sspdev_ioData(&this->ssp, &idtmp, &idtmp, 4);

    if (readen >= 0) {
        if (readen == 4)
            return (idtmp >> 8);
        return -readen;
    }
    else
        return readen;
}

int         mx25ru_read_cfg(SPIFLASH_MX25R* self){
    SPIFlash_GenDevice* this = (SPIFlash_GenDevice*)self;
    uint32_t            idtmp = FLASH_CMD_RDSR;

    sspio_cs_hold(&this->ssp.io, false);
    int readen = sspdev_ioData(&this->ssp, &idtmp, &idtmp, 4);

    if ( readen == SSP_errBUSY ){
        // если последняя операция с портом была неблокирующая, дождусь пока порт станет готов к обмену
        DevResult res = sspdev_wait_trx(&this->ssp);
        if ( res != DEV_OK ){
            return res;
        }
        readen = sspdev_ioData(&this->ssp, &idtmp, &idtmp, 4);
    }

    if (readen == 4) {
        this->flash.status_cache = ((idtmp >> 8) & 0xff) | FLASH_sSTATUS;
        return (idtmp >> 16);
    }
    else if (readen >= 0) {
        return -readen;
    }
    else
        return readen;
}

DevResult   mx25ru_write_cfg(SPIFLASH_MX25R* self, unsigned cfg){
    SPIFlash_GenDevice* this = (SPIFlash_GenDevice*)self;
    uint32_t            idtmp = FLASH_CMD_WRSR;
    idtmp |= (this->flash.status_cache & 0xff) << 8;
    idtmp |= (cfg & 0xffff) << 16;

    sspio_cs_hold(&this->ssp.io, false);

    int sent = sspdev_ioData(&this->ssp, &idtmp, &idtmp, 4);
    return sspio_ASDEVRESULT(sent, 4);
}
