/*
 * flash_spi_hal.c
 *
 *  Created on: 3/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. *
 */

#include "flash_spi_hal.h"
#include "ptx.h"


/////////////////////////////////////////////////////////////////////////////
#include <trace_probes.h>

#ifndef trace_flash_rd
trace_need(flash_wr)
trace_need(flash_wrwe)
trace_need(flash_rd)
#endif


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

//< размер данных,для которого предпочитается ожидать блокирующего завершения SSP транзакции,
//  для больших буферов - возвращается BUSY/ptWAITING, и ведется ожидание ниткой приложения
#ifndef SSP_TRANSACTION_WAIT_TH
#define SSP_TRANSACTION_WAIT_TH     8
#endif



//////////////////////////////////////////////////////////////////////////////
///     методы flashspi
/// TODO: опубликовать их?

DevResult  flashspi_select(FLASH_Device* self, unsigned csid);
FlashState flashspi_state(FLASH_Device* self);


DevResult  flashspi_write_enable(FLASH_Device* self, bool onoff);
DevResult  flashspi_erase_all(FLASH_Device* self);
PTResult  flashspi_read_one(FLASH_Device* self, flash_addr_t addr, void* dst, unsigned len);
PTResult  flashspi_read_pages(FLASH_Device* self, flash_addr_t addr, void* dst, unsigned len);

PTResult flashspi_erase_sectors(FLASH_Device* self, flash_addr_t sec, unsigned len);
PTResult flashspi_write(FLASH_Device* self, flash_addr_t addr, const void* src, unsigned len);
PTResult flashspi_flush(FLASH_Device* self);



DevResult flashspi_init(SPIFlash_GenDevice* this){
    flash_init(&this->flash);
    this->flash.select      = flashspi_select;
    this->flash.erase_all   = flashspi_erase_all;
    this->flash.state       = flashspi_state;
    this->flash.read        = flashspi_read_one;
    this->flash.write       = flashspi_write;
    this->flash.write_enable= flashspi_write_enable;
    this->flash.erase_sectors = flashspi_erase_sectors;
    this->flash.flush       = flashspi_flush;
    this->CMD_SE            = FLASH_CMD_SE_4K;
    return DEV_OK;
}

DevResult flashspi_deinit(SPIFlash_GenDevice* this);



// \arg cs - линия выбора флешки
DevResult flashspi_select(FLASH_Device* self, unsigned csid) {
    SPIFlash_GenDevice* this = (SPIFlash_GenDevice*)self;
    sspio_set_cs( &this->ssp.io, csid);
    return DEV_OK;
};

PTResult flashspi_flush(FLASH_Device* self){
    SPIFlash_GenDevice* this = (SPIFlash_GenDevice*)self;

    return  sspdev_wait_flush(&this->ssp, 0);// self->wait_ready(self, self->info->burn_page_ticks);
};

FlashState flashspi_state(FLASH_Device* self){
    SPIFlash_GenDevice* this = (SPIFlash_GenDevice*)self;

    uint8_t  buf[2];
    buf[0] = FLASH_CMD_RDSR;
    buf[1] = 0xff;

    sspio_cs_hold(&this->ssp.io, false);
    SSPResult ok = sspdev_ioData(&this->ssp, buf, buf, 2);

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

    if (ok == 2){
        this->flash.status_cache = buf[1] | FLASH_sSTATUS;
        return this->flash.status_cache;
    }
    return DEV_FAIL;
}


// базовые операции со страницами. Они не обязаны корректно пересекать
//  границы страниц
PTResult flashspi_post_page(FLASH_Device* self, void* src, flash_page_t page, unsigned len){
    SPIFlash_GenDevice* this = (SPIFlash_GenDevice*)self;

    flashspi_force_busy(this);

    trace_flash_wr_on();
    // flash burn starts after CS disabled
    sspio_cs_hold(&this->ssp.io, false);
    flash_busy_start(self);
    int writen = sspdev_postCmdData(&this->ssp, FLASH_CMD_PP, page, (const void*)src, len);
    trace_flash_wr_off();
    if (writen == 0)
        return ptWAITING;
    if (writen >= 0)
        return (writen == (int)len)? ptOK :ptNOK;
    else
        return writen;
}

DevResult flashspi_write_page(FLASH_Device* self, void* src, flash_page_t page, unsigned len){
    SPIFlash_GenDevice* this = (SPIFlash_GenDevice*)self;

    flashspi_force_busy(this);

    trace_flash_wr_on();
    // flash burn starts after CS disabled
    sspio_cs_hold(&this->ssp.io, false);
    flash_busy_start(self);
    int writen = sspdev_writeCmdData(&this->ssp, FLASH_CMD_PP, page, (const void*)src, len);
    trace_flash_wr_off();
    if (writen >= 0)
        return (writen == (int)len)? DEV_OK:DEV_NOK;
    else
        return writen;
}

PTResult flashspi_ask_page(FLASH_Device* self, void* dst, flash_page_t page, unsigned len){
    SPIFlash_GenDevice* this = (SPIFlash_GenDevice*)self;

    trace_flash_rd_twist();
    int readen = sspdev_askCmdData(&this->ssp, FLASH_CMD_READ, page, dst, len);
    if (readen == 0)
        return ptWAITING;
    if (readen > 0)
        return (readen == (int)len)? ptOK :ptNOK;
    else
        return readen;
}

DevResult flashspi_read_page(FLASH_Device* self, void* dst, flash_page_t page, unsigned len){
    SPIFlash_GenDevice* this = (SPIFlash_GenDevice*)self;

    trace_flash_rd_twist();
    int readen = sspdev_readCmdData(&this->ssp, FLASH_CMD_READ, page, dst, len);
    if (readen >= 0)
        return (readen == (int)len)? DEV_OK:DEV_NOK;
    else
        return readen;
}

DevResult flashspi_wr_cmd1(FLASH_Device* self, flash_page_t page, uint8_t cmd){
    SPIFlash_GenDevice* this = (SPIFlash_GenDevice*)self;

    flashspi_force_busy(this);

    sspio_cs_hold(&this->ssp.io, false);
    flash_busy_start(self);
    int writen = sspdev_write_cmdadress(&this->ssp, cmd, page);
    if (writen > 0)
        return DEV_OK;
    else
        return writen;
}

DevResult flashspi_erase_sec(FLASH_Device* self, void* dst, flash_page_t page, unsigned len){
    (void)dst;(void)len;
    SPIFlash_GenDevice* this = (SPIFlash_GenDevice*)self;
    return flashspi_wr_cmd1(self, page, this->CMD_SE);
}

DevResult flashspi_erase_64k(FLASH_Device* self, void* dst, flash_page_t page, unsigned len){
    (void)dst;(void)len;
    return flashspi_wr_cmd1(self, page, FLASH_CMD_SE_64K);
}


PTResult  flashspi_read_one(FLASH_Device* self, flash_addr_t page, void* dst, unsigned len){
    SPIFlash_GenDevice* this = (SPIFlash_GenDevice*)self;

    DevResult ok  = self->select_addr(self, page);
    if (ok != DEV_OK) return AS_PTRESULT(ok);

    if (len <= SSP_TRANSACTION_WAIT_TH )
    if ( flash_is_ready( this->flash.status_cache ) )
    {
        return AS_PTRESULT( flashspi_ask_page(self, dst, page, len) );
    }

    //прерванный цикл только ожидает завершения SSP
    flash_cycles_abort(self);

    // если флеша занята, справоцирую cycle ожидать её готовность
    if ( !flash_is_ready( this->flash.status_cache ) )
        self->cycx.cycle_to = FLASH_toSPIN;

    return flashspi_ask_page(self, dst, page, len);
}

PTResult  flashspi_read_pages(FLASH_Device* self, flash_addr_t page, void* dst, unsigned len) {
    // if Flash is per-byte writing (pagesie ==1), then suppose that it can
    //      continue read though all chip
    if ( flash_in_single_page(self, page, len) )
        return flashspi_read_one(self, page, dst, len);

    return flash_read_pages(self, page, dst, len, (flash_page_op)&flashspi_ask_page);
}

DevResult  flashspi_write_enable(FLASH_Device* self, bool onoff){
    SPIFlash_GenDevice* this = (SPIFlash_GenDevice*)self;

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

    uint8_t op = (onoff)? FLASH_CMD_WREN : FLASH_CMD_WRDI;
    return sspio_ASDEVRESULT(sspdev_ioByte(&this->ssp, NULL, op), 1);
}


PTResult flashspi_write(FLASH_Device* self, flash_addr_t page, const void* src, unsigned len){
    return flash_write_pages(self, page, src, len, (flash_page_op)&flashspi_post_page);
}



DevResult  flashspi_erase_all(FLASH_Device* self){
    SPIFlash_GenDevice* this = (SPIFlash_GenDevice*)self;
    flashspi_force_busy(this);
    return sspio_ASDEVRESULT( sspdev_ioByte(&this->ssp, NULL, FLASH_CMD_BE), 1);
}

PTResult flashspi_erase_sectors(FLASH_Device* self, flash_addr_t _from, unsigned _len){
    return flash_erase_sectors(self, _from, _len,  (flash_page_op)(flashspi_erase_sec) );
}



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

DevResult eepromspi_erase_all_dummy(FLASH_Device* this){
    (void)this;
    return DEV_OK;
}

PTResult eepromspi_erase_sectors_dummy(FLASH_Device* self, flash_addr_t sec, unsigned len){
    (void)self; (void)sec; (void)len;
    return ptOK;
}

// EEPROM device have no erase functions - they leave dummy.
DevResult eepromspi_init(SPIFlash_GenDevice* this){
    flash_init(&this->flash);
    this->flash.select      = flashspi_select;
    this->flash.state       = flashspi_state;
    this->flash.read        = flashspi_read_one;
    this->flash.write       = flashspi_write;
    this->flash.write_enable= flashspi_write_enable;
    this->flash.flush       = flashspi_flush;
    this->flash.erase_all   = eepromspi_erase_all_dummy;
    this->flash.erase_sectors = eepromspi_erase_sectors_dummy;
    this->CMD_SE            = FLASH_CMD_SE_4K;
    return DEV_OK;
}



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

typedef DevResult (*flash_write_enable_f)(FLASH_Device* this, bool onoff);

DevResult wre_flashspi_write_enable(SPIFlash_WritableDevice* self, bool onoff);
FlashState wre_flashspi_state(FLASH_Device* self);
PTResult wre_flashspi_erase_sectors(FLASH_Device* self, flash_addr_t _from, unsigned _len);
PTResult wre_flashspi_write(FLASH_Device* self, flash_addr_t page, const void* src, unsigned len);

DevResult wre_flashspi_init(SPIFlash_WritableDevice* this){
    DevResult ok = flashspi_init(this);
    this->flash.write_enable= (flash_write_enable_f)wre_flashspi_write_enable;
    this->flash.state       = wre_flashspi_state;
    this->flash.write       = wre_flashspi_write;
    this->flash.erase_sectors = wre_flashspi_erase_sectors;
    return ok;
}

DevResult wre_eepromspi_init(SPIFlash_WritableDevice* this){
    DevResult ok = eepromspi_init(this);
    this->flash.write_enable= (flash_write_enable_f)wre_flashspi_write_enable;
    this->flash.state       = wre_flashspi_state;
    this->flash.write       = wre_flashspi_write;
    return ok;
}



/** все операции модификации снимают разрешение записи (WE) после выполнения.
 *  Поэтому все операции модификации предваряю разрешением записи в соответсвии с выставленым значением через
 *          wre_flashspi_write_enable.
 *  заданное WE храню в status_cache, и wre_flashspi_state должен чтобы оно не терялось
 * @param this
 * @param onoff
 * @return
 */
DevResult wre_flashspi_write_enable(SPIFlash_WritableDevice* this, bool onoff){
    DevResult ok = DEV_OK;
    if ( (this->flash.status_cache & FLASH_sWE) == 0) {
        ok = flashspi_write_enable(&this->flash, onoff);
        if (ok == DEV_OK)
            this->flash.status_cache |= FLASH_sWE;
    }
    this->flash.status_cache |= FLASH_sWELOCK;
    return ok;
}

FlashState wre_flashspi_state(FLASH_Device* self){
    SPIFlash_WritableDevice* this = (SPIFlash_WritableDevice*)self;

    // preserve cache WEL status bit from changes
    unsigned WE_state = this->flash.status_cache & FLASH_sWELOCK;
    int ok = flashspi_state(self) | WE_state;
    this->flash.status_cache    |= WE_state;
    if (ok >=0){
        //ok          |= WE_state;
        //status_cache|= WE_state;
    }
    return ok;
}


DevResult wre_flashspi_enable_wr(SPIFlash_WritableDevice* this){
    if ( (this->flash.status_cache & FLASH_sWE) != 0)
        return DEV_OK;

    trace_flash_wrwe_on();
    DevResult ok;
#if FLASHDEV_WE_SURE
    cs_hold(false);
    ok = DEV_NOK;
    if (ioByte(NULL, CMD_WREN) == 1){
        trace_flash_wrwe_on();
        FLASH_Device* self = &this->flash;
        int st = self->state(self);
        trace_flash_wrwe_off();
        if ( flash_is_writable(st) && flash_is_ready(st) )
            ok = DEV_OK;
    }
#else
    sspio_cs_hold(&this->ssp.io, false);
    ok = sspio_ASDEVRESULT( sspdev_ioByte(&this->ssp, NULL, FLASH_CMD_WREN), 1); //writeByte(CMD_WREN);
    trace_flash_wrwe_off();
#endif
    return ok;
}

DevResult wre_flashspi_check_wr(SPIFlash_WritableDevice* this, int ioresult ){
    DevResult res = sspio_ASDEVRESULT(ioresult, this->ssp.io.ssp_msg.word_count); //writeByte(CMD_WREN);
#if FLASHDEV_WE_SURE
    if (res == DEV_OK){
        FLASH_Device* self = &this->flash;
        int st = self->state(self);
        if ( flash_is_writable(ok) )
            // операция записи флеши должна снять флаг WE
            return DEV_NOK;
    }
#endif
    return res;
}

PTResult wre_flashspi_post_page(FLASH_Device* self, void* src, flash_addr_t page, unsigned len){
    SPIFlash_WritableDevice* this = (SPIFlash_WritableDevice*)self;

    if (!flashspi_is_WEL(this))
        return DEV_WRITE_DISABLED_ERR;

    PTResult ok = ptNOK;
    //TRACE_GUARD(wr, flash_wr);
    trace_flash_wr_on();

    if (wre_flashspi_enable_wr(this) == DEV_OK) {
        flashspi_force_busy(this);
        sspio_cs_hold(&this->ssp.io, false);
        flash_busy_start(self);
        int writen = sspdev_postCmdData(&this->ssp, FLASH_CMD_PP, page, (const void*)src, len);
        ok = AS_PTRESULT( wre_flashspi_check_wr(this, writen) );
    }

    trace_flash_wr_off();
    return ok;
}

DevResult wre_flashspi_write_page(FLASH_Device* self, void* src, flash_addr_t page, unsigned len){
    SPIFlash_WritableDevice* this = (SPIFlash_WritableDevice*)self;

    if (!flashspi_is_WEL(this))
        return DEV_WRITE_DISABLED_ERR;

    //TRACE_GUARD(wr, flash_wr);

    DevResult ok = wre_flashspi_post_page(self, src, page, len);
    if (ok == DEV_OK) {
        trace_flash_wr_on();
        ok = sspdev_wait_trx( &this->ssp );
    }

    trace_flash_wr_off();
    return ok;
}

DevResult wre_flashspi_wr_cmd1(FLASH_Device* self, flash_page_t page, uint8_t cmd) {
    SPIFlash_WritableDevice* this = (SPIFlash_WritableDevice*)self;

    if (!flashspi_is_WEL(this))
        return DEV_WRITE_DISABLED_ERR;

    DevResult ok = DEV_NOK;

    //TRACE_GUARD(wr, flash_wr);
    trace_flash_wr_on();

    if (wre_flashspi_enable_wr(this) == DEV_OK){
        flashspi_force_busy(this);
        sspio_cs_hold(&this->ssp.io, false);
        flash_busy_start(self);
        int writen = sspdev_write_cmdadress(&this->ssp, cmd, page);
        ok = wre_flashspi_check_wr(this, writen);
    }

    trace_flash_wr_off();
    return ok;
}

DevResult wre_flashspi_erase_sec(FLASH_Device* self, void* dst, flash_page_t page, unsigned len){
    (void)dst; (void)len;
    SPIFlash_WritableDevice* this = (SPIFlash_WritableDevice*)self;

    return  wre_flashspi_wr_cmd1(self, page, this->CMD_SE);
}

DevResult wre_flashspi_erase_64k(FLASH_Device* self, void* dst, flash_page_t page, unsigned len){
    (void)dst; (void)len;
    return  wre_flashspi_wr_cmd1(self, page, FLASH_CMD_SE_64K);
}


//virtual
DevResult wre_flashspi_erase_all(FLASH_Device* self){
    SPIFlash_WritableDevice* this = (SPIFlash_WritableDevice*)self;

    DevResult res;
    if (flashspi_is_WEL(this)){
        res = wre_flashspi_enable_wr(this);
        if (res != DEV_OK)
            return res;
    }
    else
        return DEV_WRITE_DISABLED_ERR;
    return sspio_ASDEVRESULT(sspdev_ioByte(&this->ssp, NULL, FLASH_CMD_BE), 1); //writeByte(CMD_BE);
}

//virtual
PTResult wre_flashspi_erase_sectors(FLASH_Device* self, flash_addr_t _from, unsigned _len){
    SPIFlash_WritableDevice* this = (SPIFlash_WritableDevice*)self;
    struct pt* pt = &self->oppt;

    if (pt->lc == 0)
    if (!flashspi_is_WEL(this))
        return AS_PTRESULT(DEV_WRITE_DISABLED_ERR);

    return flash_erase_sectors(self, _from, _len, wre_flashspi_erase_sec);
}

//virtual
PTResult wre_flashspi_write(FLASH_Device* self, flash_addr_t page, const void* src, unsigned len){
    SPIFlash_WritableDevice* this = (SPIFlash_WritableDevice*)self;
    struct pt* pt = &self->oppt;

    if (pt->lc == 0)
    if (!flashspi_is_WEL(this))
        return AS_PTRESULT(DEV_WRITE_DISABLED_ERR);

    return flash_write_pages(self, page, src, len, (flash_page_op)&wre_flashspi_post_page );
}
