diff --git a/examples/OTA_Flashing/hello.bin b/examples/OTA_Flashing/hello.bin new file mode 100755 index 0000000..61b353c Binary files /dev/null and b/examples/OTA_Flashing/hello.bin differ diff --git a/examples/OTA_Flashing/upload.sh b/examples/OTA_Flashing/upload.sh new file mode 100755 index 0000000..b466937 --- /dev/null +++ b/examples/OTA_Flashing/upload.sh @@ -0,0 +1 @@ +./arduinoOTA -address 192.168.88.34 -port 65280 -username arduino -password password -sketch hello.bin -b -upload /sketch diff --git a/src/ArduinoOTA.h b/src/ArduinoOTA.h index 20a921f..f0d3a45 100644 --- a/src/ArduinoOTA.h +++ b/src/ArduinoOTA.h @@ -47,7 +47,9 @@ class ArduinoOTAClass : public WiFiOTAClass { NetServer server; public: - ArduinoOTAClass() : server(OTA_PORT) {}; + ArduinoOTAClass() : server(OTA_PORT) + { + }; void begin(IPAddress localIP, const char* name, const char* password, OTAStorage& storage) { WiFiOTAClass::begin(localIP, name, password, storage); diff --git a/src/InternalStorage.cpp b/src/InternalStorage.cpp index e71a09a..e1ddce2 100644 --- a/src/InternalStorage.cpp +++ b/src/InternalStorage.cpp @@ -27,12 +27,23 @@ #include "InternalStorage.h" +#if defined(__SAM3X8E__) +#include "flash_efc.h" +#include "efc.h" +#endif + + InternalStorageClass::InternalStorageClass() : + MAX_PARTIONED_SKETCH_SIZE((MAX_FLASH - SKETCH_START_ADDRESS) / 2), STORAGE_START_ADDRESS(SKETCH_START_ADDRESS + MAX_PARTIONED_SKETCH_SIZE) -{ +{ _writeIndex = 0; _writeAddress = nullptr; + _sketchSize = 0; +#if defined(__SAM3X8E__) + flash_init(FLASH_ACCESS_MODE_128, 6); +#endif } extern "C" { @@ -45,6 +56,8 @@ extern "C" { while (!NVMCTRL->INTFLAG.bit.READY); #elif defined(ARDUINO_ARCH_NRF5) while (NRF_NVMC->READY == NVMC_READY_READY_Busy); +#elif defined(__SAM3X8E__) +// Not used #endif } @@ -75,78 +88,270 @@ extern "C" { waitForReady(); NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Wen << NVMC_CONFIG_WEN_Pos; waitForReady(); +#elif defined(__SAM3X8E__) + + //Erase secondary bank; + Serial.println("Erase flash"); + flash_erase_all(address); #endif } + + +#if defined(__SAM3X8E__) +#define us_num_pages_in_region (IFLASH0_LOCK_REGION_SIZE / IFLASH0_PAGE_SIZE) +#define RAMFUNC __attribute__ ((section(".ramfunc"))) + +extern void copyFlashAndReset(int dest, int src, int length, int pageSize); +RAMFUNC void copyFlashAndReset(int dest, int src, int length, int pageSize) + +{ +static uint32_t(*iap_perform_command) (uint32_t, uint32_t); +uint32_t ul_efc_nb; +/* Use IAP function with 2 parameters in ROM. */ +iap_perform_command = (uint32_t(*)(uint32_t, uint32_t)) *((uint32_t *) CHIP_FLASH_IAP_ADDRESS); +ul_efc_nb = 0; + + + +//Bank swithch forction not working on SAM with firmware>64K - see Errata +/* +// Not actual copy, just switch banks + +flash_set_gpnvm(1); //Booting from FLASH + +if (FLASH_RC_YES == flash_is_gpnvm_set(2)) // BANK1 is active +{ +Serial.println("Switching to BANK0"); +delay(500); +noInterrupts(); +//flash_clear_gpnvm(2); +iap_perform_command(ul_efc_nb, EEFC_FCR_FKEY(0x5Au) | EEFC_FCR_FARG(2) | + EEFC_FCR_FCMD(EFC_FCMD_CGPB)); +} + +else +{ +Serial.println("Switching to BANK1"); +delay(500); +noInterrupts(); +//flash_set_gpnvm(2); +iap_perform_command(ul_efc_nb, EEFC_FCR_FKEY(0x5Au) | EEFC_FCR_FARG(2) | + EEFC_FCR_FCMD(EFC_FCMD_SGPB)); +} + +RSTC->RSTC_CR = 0xA5000005; +*/ +// Since bank swithing is not working - just copy to bank0 from bank1 + +Efc *p_efc; +uint16_t us_page; +uint32_t *p_src; +uint32_t *p_dest; +int32_t left; + + +Serial.print("Flashing bytes:"); +Serial.println(length); +Serial.print("From:"); +Serial.println(src,HEX); +Serial.print("To:"); +Serial.println(dest,HEX); +Serial.print("PageSize:"); +Serial.println(pageSize); + + +delay(300); +watchdogReset(); + + +flash_set_gpnvm(1); //Booting from FLASH + +// Preparing to flashing + +p_efc = EFC0; +us_page = 0; + +efc_set_wait_state(p_efc, 6); +p_dest = (uint32_t *) dest; +p_src = (uint32_t *) src; +left = length; + +noInterrupts(); + +while (left>0) + { + // Dangerous zone - no exterlal flash based routines allowed below + + // Unlock range + if (! (us_page % us_num_pages_in_region)) + iap_perform_command(ul_efc_nb, + EEFC_FCR_FKEY(0x5Au) | EEFC_FCR_FARG(us_page) | + EEFC_FCR_FCMD(EFC_FCMD_CLB)); + + // Copy page + for (int ul_idx = 0; ul_idx < (IFLASH0_PAGE_SIZE / sizeof(uint32_t)); ++ul_idx) + { + *p_dest++ = *p_src++; + } + + + if ((us_page+1) % us_num_pages_in_region) + + // Erase & write page + iap_perform_command(ul_efc_nb, + EEFC_FCR_FKEY(0x5Au) | EEFC_FCR_FARG(us_page) | + EEFC_FCR_FCMD(EFC_FCMD_EWP)); + // result at (p_efc->EEFC_FSR & EEFC_ERROR_FLAGS); + + else // last page in the lock region + // Erase, write, lock page + iap_perform_command(ul_efc_nb, + EEFC_FCR_FKEY(0x5Au) | EEFC_FCR_FARG(us_page) | + EEFC_FCR_FCMD(EFC_FCMD_EWPL)); + // result at (p_efc->EEFC_FSR & EEFC_ERROR_FLAGS); + + + + + us_page++; + left -= IFLASH0_PAGE_SIZE; + //watchdogReset(); + + } +// End low-level flashing code + + + +//Restart +RSTC->RSTC_CR = 0xA5000005; + +} + + +#else + __attribute__ ((long_call, noinline, section (".data#"))) static void copyFlashAndReset(int dest, int src, int length, int pageSize) { uint32_t* d = (uint32_t*)dest; uint32_t* s = (uint32_t*)src; + // disable interrupts, as vector table will be erase during flash sequence + noInterrupts(); + eraseFlash(dest, length, pageSize); for (int i = 0; i < length; i += 4) { *d++ = *s++; - + waitForReady(); } NVIC_SystemReset(); - } } +#endif + +} //extern C + + int InternalStorageClass::open(int length) { (void)length; _writeIndex = 0; - _writeAddress = (uint32_t*)STORAGE_START_ADDRESS; + _writeAddress = (addressData*)STORAGE_START_ADDRESS; + +Serial.println("Open flash for write\n"); #ifdef ARDUINO_ARCH_SAMD // enable auto page writes NVMCTRL->CTRLB.bit.MANW = 0; #endif - eraseFlash(STORAGE_START_ADDRESS, MAX_PARTIONED_SKETCH_SIZE, PAGE_SIZE); +#if defined(__SAM3X8E__) + + int retCode = flash_unlock((uint32_t)STORAGE_START_ADDRESS, (uint32_t) STORAGE_START_ADDRESS + MAX_PARTIONED_SKETCH_SIZE - 1, 0, 0); + if (retCode != FLASH_RC_OK) { + Serial.println("Failed to unlock flash for write\n"); + } +#endif + +eraseFlash(STORAGE_START_ADDRESS, MAX_PARTIONED_SKETCH_SIZE, PAGE_SIZE); return 1; } + + size_t InternalStorageClass::write(uint8_t b) { - _addressData.u8[_writeIndex] = b; - _writeIndex++; + +#if defined(__SAM3X8E__) + _addressData[_writeIndex] = b; + _writeIndex++; - if (_writeIndex == 4) { + if ( _writeIndex == IFLASH0_PAGE_SIZE ) { _writeIndex = 0; - - *_writeAddress = _addressData.u32; - + + watchdogReset(); + Serial.print("="); + int retCode = flash_write((uint32_t) _writeAddress, &_addressData, IFLASH0_PAGE_SIZE, 0); //1? + if (retCode != FLASH_RC_OK) + { + Serial.println("Flash write failed\n"); + return 0; + } _writeAddress++; + } +#else + _addressData.u8[_writeIndex] = b; + _writeIndex++; + + if (_writeIndex == sizeof(addressData)) { + _writeIndex = 0; + _writeAddress->u32 = _addressData.u32; + _writeAddress++; + waitForReady(); + } +#endif - waitForReady(); - } - - return 1; +return 1; } -void InternalStorageClass::close() +void InternalStorageClass::close() { +#if defined(__SAM3X8E__) +_sketchSize = (uint32_t)_writeAddress-STORAGE_START_ADDRESS+_writeIndex; + +while (_writeIndex) write(0xff); //Finish block + +Serial.print("\nReceived bytes:"); +Serial.println(_sketchSize); +#else + while ((int)_writeAddress % PAGE_SIZE) { - write(0xff); - } + write(0xff); + } +#endif + } void InternalStorageClass::clear() { } + void InternalStorageClass::apply() { - // disable interrupts, as vector table will be erase during flash sequence - noInterrupts(); + //noInterrupts(); moved inside routine +#if defined(__SAM3X8E__) + copyFlashAndReset(SKETCH_START_ADDRESS, STORAGE_START_ADDRESS, _sketchSize, PAGE_SIZE); +#else copyFlashAndReset(SKETCH_START_ADDRESS, STORAGE_START_ADDRESS, MAX_PARTIONED_SKETCH_SIZE, PAGE_SIZE); +#endif + } long InternalStorageClass::maxSize() diff --git a/src/InternalStorage.h b/src/InternalStorage.h index 1e055de..4d3d98f 100644 --- a/src/InternalStorage.h +++ b/src/InternalStorage.h @@ -40,14 +40,22 @@ class InternalStorageClass : public OTAStorage { private: const uint32_t MAX_PARTIONED_SKETCH_SIZE, STORAGE_START_ADDRESS; + uint32_t _sketchSize; - union { + +#if defined(__SAM3X8E__) +// Buffer for page + typedef uint8_t addressData[256]; + addressData _addressData; +#else + union addressData{ uint32_t u32; uint8_t u8[4]; } _addressData; +#endif int _writeIndex; - uint32_t* _writeAddress; + addressData * _writeAddress; }; extern InternalStorageClass InternalStorage; diff --git a/src/OTAStorage.cpp b/src/OTAStorage.cpp index 7451004..989a0b8 100644 --- a/src/OTAStorage.cpp +++ b/src/OTAStorage.cpp @@ -18,10 +18,14 @@ char * __isr_vector(); #endif OTAStorage::OTAStorage() : -#if defined(ARDUINO_ARCH_SAMD) +#if defined(ARDUINO_ARCH_SAMD) SKETCH_START_ADDRESS((uint32_t) __text_start__), PAGE_SIZE(pageSizes[NVMCTRL->PARAM.bit.PSZ]), MAX_FLASH(PAGE_SIZE * NVMCTRL->PARAM.bit.NVMP - eepromSizes[EEPROM_EMULATION_RESERVATION]) +#elif defined(__SAM3X8E__) + SKETCH_START_ADDRESS((uint32_t) IFLASH0_ADDR), + PAGE_SIZE(IFLASH0_PAGE_SIZE), + MAX_FLASH((uint32_t) IFLASH0_ADDR+512*1024) #elif defined(ARDUINO_ARCH_NRF5) SKETCH_START_ADDRESS((uint32_t) __isr_vector), PAGE_SIZE((size_t) NRF_FICR->CODEPAGESIZE), diff --git a/src/OTAStorage.h b/src/OTAStorage.h index ca65394..2786d93 100644 --- a/src/OTAStorage.h +++ b/src/OTAStorage.h @@ -26,6 +26,7 @@ #include + class OTAStorage { public: diff --git a/src/efc.cpp b/src/efc.cpp new file mode 100644 index 0000000..74f0c8a --- /dev/null +++ b/src/efc.cpp @@ -0,0 +1,340 @@ +/** + * \file + * + * \brief Enhanced Embedded Flash Controller (EEFC) driver for SAM. + * + * Copyright (c) 2011-2012 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. 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. + * + * 3. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#include "efc.h" + +/// @cond 0 +/**INDENT-OFF**/ +#ifdef __cplusplus +extern "C" { +#endif +/**INDENT-ON**/ +/// @endcond + +/** + * \defgroup sam_drivers_efc_group Enhanced Embedded Flash Controller (EEFC) + * + * The Enhanced Embedded Flash Controller ensures the interface of the Flash + * block with the 32-bit internal bus. + * + * @{ + */ + +/* Address definition for read operation */ +# define READ_BUFF_ADDR0 IFLASH0_ADDR +# define READ_BUFF_ADDR1 IFLASH1_ADDR + +/* Flash Writing Protection Key */ +#define FWP_KEY 0x5Au + +#if (SAM4S || SAM4E) +#define EEFC_FCR_FCMD(value) \ + ((EEFC_FCR_FCMD_Msk & ((value) << EEFC_FCR_FCMD_Pos))) +#define EEFC_ERROR_FLAGS (EEFC_FSR_FLOCKE | EEFC_FSR_FCMDE | EEFC_FSR_FLERR) +#else +#define EEFC_ERROR_FLAGS (EEFC_FSR_FLOCKE | EEFC_FSR_FCMDE) +#endif + + + +/* + * Local function declaration. + * Because they are RAM functions, they need 'extern' declaration. + */ +extern void efc_write_fmr(Efc *p_efc, uint32_t ul_fmr); +extern uint32_t efc_perform_fcr(Efc *p_efc, uint32_t ul_fcr); + +/** + * \brief Initialize the EFC controller. + * + * \param ul_access_mode 0 for 128-bit, EEFC_FMR_FAM for 64-bit. + * \param ul_fws The number of wait states in cycle (no shift). + * + * \return 0 if successful. + */ +uint32_t efc_init(Efc *p_efc, uint32_t ul_access_mode, uint32_t ul_fws) +{ + efc_write_fmr(p_efc, ul_access_mode | EEFC_FMR_FWS(ul_fws)); + return EFC_RC_OK; +} + +/** + * \brief Enable the flash ready interrupt. + * + * \param p_efc Pointer to an EFC instance. + */ +void efc_enable_frdy_interrupt(Efc *p_efc) +{ + uint32_t ul_fmr = p_efc->EEFC_FMR; + + efc_write_fmr(p_efc, ul_fmr | EEFC_FMR_FRDY); +} + +/** + * \brief Disable the flash ready interrupt. + * + * \param p_efc Pointer to an EFC instance. + */ +void efc_disable_frdy_interrupt(Efc *p_efc) +{ + uint32_t ul_fmr = p_efc->EEFC_FMR; + + efc_write_fmr(p_efc, ul_fmr & (~EEFC_FMR_FRDY)); +} + +/** + * \brief Set flash access mode. + * + * \param p_efc Pointer to an EFC instance. + * \param ul_mode 0 for 128-bit, EEFC_FMR_FAM for 64-bit. + */ +void efc_set_flash_access_mode(Efc *p_efc, uint32_t ul_mode) +{ + uint32_t ul_fmr = p_efc->EEFC_FMR & (~EEFC_FMR_FAM); + + efc_write_fmr(p_efc, ul_fmr | ul_mode); +} + +/** + * \brief Get flash access mode. + * + * \param p_efc Pointer to an EFC instance. + * + * \return 0 for 128-bit or EEFC_FMR_FAM for 64-bit. + */ +uint32_t efc_get_flash_access_mode(Efc *p_efc) +{ + return (p_efc->EEFC_FMR & EEFC_FMR_FAM); +} + +/** + * \brief Set flash wait state. + * + * \param p_efc Pointer to an EFC instance. + * \param ul_fws The number of wait states in cycle (no shift). + */ +void efc_set_wait_state(Efc *p_efc, uint32_t ul_fws) +{ + uint32_t ul_fmr = p_efc->EEFC_FMR & (~EEFC_FMR_FWS_Msk); + + efc_write_fmr(p_efc, ul_fmr | EEFC_FMR_FWS(ul_fws)); +} + +/** + * \brief Get flash wait state. + * + * \param p_efc Pointer to an EFC instance. + * + * \return The number of wait states in cycle (no shift). + */ +uint32_t efc_get_wait_state(Efc *p_efc) +{ + return ((p_efc->EEFC_FMR & EEFC_FMR_FWS_Msk) >> EEFC_FMR_FWS_Pos); +} + +/** + * \brief Perform the given command and wait until its completion (or an error). + * + * \note Unique ID commands are not supported, use efc_read_unique_id. + * + * \param p_efc Pointer to an EFC instance. + * \param ul_command Command to perform. + * \param ul_argument Optional command argument. + * + * \note This function will automatically choose to use IAP function. + * + * \return 0 if successful, otherwise returns an error code. + */ +uint32_t efc_perform_command(Efc *p_efc, uint32_t ul_command, + uint32_t ul_argument) +{ + /* Unique ID commands are not supported. */ + if (ul_command == EFC_FCMD_STUI || ul_command == EFC_FCMD_SPUI) { + return EFC_RC_NOT_SUPPORT; + } + + /* Use IAP function with 2 parameters in ROM. */ + static uint32_t(*iap_perform_command) (uint32_t, uint32_t); + uint32_t ul_efc_nb = (p_efc == EFC0) ? 0 : 1; + + iap_perform_command = + (uint32_t(*)(uint32_t, uint32_t)) + *((uint32_t *) CHIP_FLASH_IAP_ADDRESS); + iap_perform_command(ul_efc_nb, + EEFC_FCR_FKEY(FWP_KEY) | EEFC_FCR_FARG(ul_argument) | + EEFC_FCR_FCMD(ul_command)); + return (p_efc->EEFC_FSR & EEFC_ERROR_FLAGS); +} + +/** + * \brief Get the current status of the EEFC. + * + * \note This function clears the value of some status bits (FLOCKE, FCMDE). + * + * \param p_efc Pointer to an EFC instance. + * + * \return The current status. + */ +uint32_t efc_get_status(Efc *p_efc) +{ + return p_efc->EEFC_FSR; +} + +/** + * \brief Get the result of the last executed command. + * + * \param p_efc Pointer to an EFC instance. + * + * \return The result of the last executed command. + */ +uint32_t efc_get_result(Efc *p_efc) +{ + return p_efc->EEFC_FRR; +} + +/** + * \brief Perform read sequence. Supported sequences are read Unique ID and + * read User Signature + * + * \param p_efc Pointer to an EFC instance. + * \param ul_cmd_st Start command to perform. + * \param ul_cmd_sp Stop command to perform. + * \param p_ul_buf Pointer to an data buffer. + * \param ul_size Buffer size. + * + * \return 0 if successful, otherwise returns an error code. + */ +RAMFUNC +uint32_t efc_perform_read_sequence(Efc *p_efc, + uint32_t ul_cmd_st, uint32_t ul_cmd_sp, + uint32_t *p_ul_buf, uint32_t ul_size) +{ + volatile uint32_t ul_status; + uint32_t ul_cnt; + + uint32_t *p_ul_data = + (uint32_t *) ((p_efc == EFC0) ? + READ_BUFF_ADDR0 : READ_BUFF_ADDR1); + + if (p_ul_buf == NULL) { + return EFC_RC_INVALID; + } + + p_efc->EEFC_FMR |= (0x1u << 16); + + /* Send the Start Read command */ + + p_efc->EEFC_FCR = EEFC_FCR_FKEY(FWP_KEY) | EEFC_FCR_FARG(0) + | EEFC_FCR_FCMD(ul_cmd_st); + /* Wait for the FRDY bit in the Flash Programming Status Register + * (EEFC_FSR) falls. + */ + do { + ul_status = p_efc->EEFC_FSR; + } while ((ul_status & EEFC_FSR_FRDY) == EEFC_FSR_FRDY); + + /* The data is located in the first address of the Flash + * memory mapping. + */ + for (ul_cnt = 0; ul_cnt < ul_size; ul_cnt++) { + p_ul_buf[ul_cnt] = p_ul_data[ul_cnt]; + } + + /* To stop the read mode */ + p_efc->EEFC_FCR = + EEFC_FCR_FKEY(FWP_KEY) | EEFC_FCR_FARG(0) | + EEFC_FCR_FCMD(ul_cmd_sp); + /* Wait for the FRDY bit in the Flash Programming Status Register (EEFC_FSR) + * rises. + */ + do { + ul_status = p_efc->EEFC_FSR; + } while ((ul_status & EEFC_FSR_FRDY) != EEFC_FSR_FRDY); + + p_efc->EEFC_FMR &= ~(0x1u << 16); + + return EFC_RC_OK; +} + +/** + * \brief Set mode register. + * + * \param p_efc Pointer to an EFC instance. + * \param ul_fmr Value of mode register + */ +RAMFUNC +void efc_write_fmr(Efc *p_efc, uint32_t ul_fmr) +{ + p_efc->EEFC_FMR = ul_fmr; +} + +/** + * \brief Perform command. + * + * \param p_efc Pointer to an EFC instance. + * \param ul_fcr Flash command. + * + * \return The current status. + */ +RAMFUNC +uint32_t efc_perform_fcr(Efc *p_efc, uint32_t ul_fcr) +{ + volatile uint32_t ul_status; + + p_efc->EEFC_FCR = ul_fcr; + do { + ul_status = p_efc->EEFC_FSR; + } while ((ul_status & EEFC_FSR_FRDY) != EEFC_FSR_FRDY); + + return (ul_status & EEFC_ERROR_FLAGS); +} + +//@} + +/// @cond 0 +/**INDENT-OFF**/ +#ifdef __cplusplus +} +#endif +/**INDENT-ON**/ +/// @endcond diff --git a/src/efc.h b/src/efc.h new file mode 100644 index 0000000..4481b98 --- /dev/null +++ b/src/efc.h @@ -0,0 +1,139 @@ +/** + * \file + * + * \brief Embedded Flash Controller (EFC) driver for SAM. + * + * Copyright (c) 2011-2012 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. 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. + * + * 3. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef EFC_H_INCLUDED +#define EFC_H_INCLUDED + +#include +#include + +#define SAM3XA +#define RAMFUNC __attribute__ ((section(".ramfunc"))) + +/// @cond 0 +/**INDENT-OFF**/ +#ifdef __cplusplus +extern "C" { +#endif +/**INDENT-ON**/ +/// @endcond + +/*! \name EFC return codes */ +//! @{ +typedef enum efc_rc { + EFC_RC_OK = 0, //!< Operation OK + EFC_RC_YES = 0, //!< Yes + EFC_RC_NO = 1, //!< No + EFC_RC_ERROR = 1, //!< General error + EFC_RC_INVALID, //!< Invalid argument input + EFC_RC_NOT_SUPPORT = 0xFFFFFFFF //!< Operation is not supported +} efc_rc_t; +//! @} + +/*! \name EFC command */ +//! @{ +#define EFC_FCMD_GETD 0x00 //!< Get Flash Descriptor +#define EFC_FCMD_WP 0x01 //!< Write page +#define EFC_FCMD_WPL 0x02 //!< Write page and lock +#define EFC_FCMD_EWP 0x03 //!< Erase page and write page +#define EFC_FCMD_EWPL 0x04 //!< Erase page and write page then lock +#define EFC_FCMD_EA 0x05 //!< Erase all +#if (SAM3SD8) +#define EFC_FCMD_EPL 0x06 //!< Erase plane +#endif +#if (SAM4S || SAM4E) +#define EFC_FCMD_EPA 0x07 //!< Erase pages +#endif +#define EFC_FCMD_SLB 0x08 //!< Set Lock Bit +#define EFC_FCMD_CLB 0x09 //!< Clear Lock Bit +#define EFC_FCMD_GLB 0x0A //!< Get Lock Bit +#define EFC_FCMD_SGPB 0x0B //!< Set GPNVM Bit +#define EFC_FCMD_CGPB 0x0C //!< Clear GPNVM Bit +#define EFC_FCMD_GGPB 0x0D //!< Get GPNVM Bit +#define EFC_FCMD_STUI 0x0E //!< Start unique ID +#define EFC_FCMD_SPUI 0x0F //!< Stop unique ID +#if (!SAM3U && !SAM3SD8 && !SAM3S8) +#define EFC_FCMD_GCALB 0x10 //!< Get CALIB Bit +#endif +#if (SAM4S || SAM4E) +#define EFC_FCMD_ES 0x11 //!< Erase sector +#define EFC_FCMD_WUS 0x12 //!< Write user signature +#define EFC_FCMD_EUS 0x13 //!< Erase user signature +#define EFC_FCMD_STUS 0x14 //!< Start read user signature +#define EFC_FCMD_SPUS 0x15 //!< Stop read user signature +#endif +//! @} + +/*! The IAP function entry address */ +#define CHIP_FLASH_IAP_ADDRESS (IROM_ADDR + 8) + +/*! \name EFC access mode */ +//! @{ +#define EFC_ACCESS_MODE_128 0 +#define EFC_ACCESS_MODE_64 EEFC_FMR_FAM +//! @} + +uint32_t efc_init(Efc *p_efc, uint32_t ul_access_mode, uint32_t ul_fws); +void efc_enable_frdy_interrupt(Efc *p_efc); +void efc_disable_frdy_interrupt(Efc *p_efc); +void efc_set_flash_access_mode(Efc *p_efc, uint32_t ul_mode); +uint32_t efc_get_flash_access_mode(Efc *p_efc); +void efc_set_wait_state(Efc *p_efc, uint32_t ul_fws); +uint32_t efc_get_wait_state(Efc *p_efc); +uint32_t efc_perform_command(Efc *p_efc, uint32_t ul_command, + uint32_t ul_argument); +uint32_t efc_get_status(Efc *p_efc); +uint32_t efc_get_result(Efc *p_efc); +uint32_t efc_perform_read_sequence(Efc *p_efc, + uint32_t ul_cmd_st, uint32_t ul_cmd_sp, + uint32_t *p_ul_buf, uint32_t ul_size); + +/// @cond 0 +/**INDENT-OFF**/ +#ifdef __cplusplus +} +#endif +/**INDENT-ON**/ +/// @endcond + +#endif /* EFC_H_INCLUDED */ diff --git a/src/flash_efc.cpp b/src/flash_efc.cpp new file mode 100644 index 0000000..c7b3aa8 --- /dev/null +++ b/src/flash_efc.cpp @@ -0,0 +1,916 @@ +/** + * \file + * + * \brief Embedded Flash service for SAM. + * + * Copyright (c) 2011-2013 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. 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. + * + * 3. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#include +#include +#include "flash_efc.h" + +/// @cond 0 +/**INDENT-OFF**/ +#ifdef __cplusplus +extern "C" { +#endif +/**INDENT-ON**/ +/// @endcond + +/** + * \defgroup sam_services_flash_efc_group Embedded Flash Service + * + * The Embedded Flash service provides functions for internal flash operations. + * + * @{ + */ + +#if SAM4E +/* User signature size */ +# define FLASH_USER_SIG_SIZE (512) +#endif + +#if SAM4S +/* Internal Flash Controller 0. */ +# define EFC EFC0 +/* User signature size */ +# define FLASH_USER_SIG_SIZE (512) +/* Internal Flash 0 base address. */ +# define IFLASH_ADDR IFLASH0_ADDR +/* Internal flash page size. */ +# define IFLASH_PAGE_SIZE IFLASH0_PAGE_SIZE +/* Internal flash lock region size. */ +# define IFLASH_LOCK_REGION_SIZE IFLASH0_LOCK_REGION_SIZE +#endif + +/* Internal Flash Controller 0. */ +# define EFC EFC0 +/* The max GPNVM number. */ +# define GPNVM_NUM_MAX 3 +/* Internal Flash 0 base address. */ +# define IFLASH_ADDR IFLASH0_ADDR +/* Internal flash page size. */ +# define IFLASH_PAGE_SIZE IFLASH0_PAGE_SIZE +/* Internal flash lock region size. */ +# define IFLASH_LOCK_REGION_SIZE IFLASH0_LOCK_REGION_SIZE + +/* Flash page buffer for alignment */ +static uint32_t gs_ul_page_buffer[IFLASH_PAGE_SIZE / sizeof(uint32_t)]; + +/** + * \brief Translate the given flash address to page and offset values. + * \note pus_page and pus_offset must not be null in order to store the + * corresponding values. + * + * \param pp_efc Pointer to an EFC pointer. + * \param ul_addr Address to translate. + * \param pus_page The first page accessed. + * \param pus_offset Byte offset in the first page. + */ +static void translate_address(Efc **pp_efc, uint32_t ul_addr, + uint16_t *pus_page, uint16_t *pus_offset) +{ + Efc *p_efc; + uint16_t us_page; + uint16_t us_offset; + + if (ul_addr >= IFLASH1_ADDR) { + p_efc = EFC1; + us_page = (ul_addr - IFLASH1_ADDR) / IFLASH1_PAGE_SIZE; + us_offset = (ul_addr - IFLASH1_ADDR) % IFLASH1_PAGE_SIZE; + } else { + p_efc = EFC0; + us_page = (ul_addr - IFLASH0_ADDR) / IFLASH0_PAGE_SIZE; + us_offset = (ul_addr - IFLASH0_ADDR) % IFLASH0_PAGE_SIZE; + } + + /* Store values */ + if (pp_efc) { + *pp_efc = p_efc; + } + + if (pus_page) { + *pus_page = us_page; + } + + if (pus_offset) { + *pus_offset = us_offset; + } +} + +/** + * \brief Compute the address of a flash by the given page and offset. + * + * \param p_efc Pointer to an EFC instance. + * \param us_page Page number. + * \param us_offset Byte offset inside page. + * \param pul_addr Computed address (optional). + */ +static void compute_address(Efc *p_efc, uint16_t us_page, uint16_t us_offset, + uint32_t *pul_addr) +{ + uint32_t ul_addr; + +/* Dual bank flash */ +#ifdef EFC1 + /* Compute address */ + ul_addr = (p_efc == EFC0) ? + IFLASH0_ADDR + us_page * IFLASH_PAGE_SIZE + us_offset : + IFLASH1_ADDR + us_page * IFLASH_PAGE_SIZE + us_offset; + +/* One bank flash */ +#else + /* avoid Cppcheck Warning */ + UNUSED(p_efc); + /* Compute address */ + ul_addr = IFLASH_ADDR + us_page * IFLASH_PAGE_SIZE + us_offset; +#endif + + /* Store result */ + if (pul_addr != NULL) { + *pul_addr = ul_addr; + } +} + +/** + * \brief Compute the lock range associated with the given address range. + * + * \param ul_start Start address of lock range. + * \param ul_end End address of lock range. + * \param pul_actual_start Actual start address of lock range. + * \param pul_actual_end Actual end address of lock range. + */ +static void compute_lock_range(uint32_t ul_start, uint32_t ul_end, + uint32_t *pul_actual_start, uint32_t *pul_actual_end) +{ + uint32_t ul_actual_start, ul_actual_end; + + ul_actual_start = ul_start - (ul_start % IFLASH_LOCK_REGION_SIZE); + ul_actual_end = ul_end - (ul_end % IFLASH_LOCK_REGION_SIZE) + + IFLASH_LOCK_REGION_SIZE - 1; + + if (pul_actual_start) { + *pul_actual_start = ul_actual_start; + } + + if (pul_actual_end) { + *pul_actual_end = ul_actual_end; + } +} + +/** + * \brief Initialize the flash service. + * + * \param ul_mode FLASH_ACCESS_MODE_128 or FLASH_ACCESS_MODE_64. + * \param ul_fws The number of wait states in cycle (no shift). + * + * \return 0 if successful; otherwise returns an error code. + */ +uint32_t flash_init(uint32_t ul_mode, uint32_t ul_fws) +{ + efc_init(EFC, ul_mode, ul_fws); + +#ifdef EFC1 + efc_init(EFC1, ul_mode, ul_fws); +#endif + + return FLASH_RC_OK; +} + +/** + * \brief Set flash wait state. + * + * \param ul_address Flash bank start address. + * \param ul_fws The number of wait states in cycle (no shift). + * + * \return 0 if successful; otherwise returns an error code. + */ +uint32_t flash_set_wait_state(uint32_t ul_address, uint32_t ul_fws) +{ + Efc *p_efc; + + translate_address(&p_efc, ul_address, NULL, NULL); + efc_set_wait_state(p_efc, ul_fws); + + return FLASH_RC_OK; +} + +/** + * \brief Set flash wait state. + * + * \param ul_address Flash bank start address. + * \param ul_fws The number of wait states in cycle (no shift). + * + * \return 0 if successful; otherwise returns an error code. + */ +uint32_t flash_set_wait_state_adaptively(uint32_t ul_address) +{ + Efc *p_efc; + uint32_t clock = SystemCoreClock; + + translate_address(&p_efc, ul_address, NULL, NULL); + + /* Set FWS for embedded Flash access according to operating frequency */ + if (clock < CHIP_FREQ_FWS_0) { + efc_set_wait_state(p_efc, 0); + } else if (clock < CHIP_FREQ_FWS_1) { + efc_set_wait_state(p_efc, 1); + } else if (clock < CHIP_FREQ_FWS_2) { + efc_set_wait_state(p_efc, 2); + } else if (clock < CHIP_FREQ_FWS_3) { + efc_set_wait_state(p_efc, 3); + } else { + efc_set_wait_state(p_efc, 4); + } + return FLASH_RC_OK; +} + +/** + * \brief Get flash wait state. + * + * \param ul_address Flash bank start address. + * + * \return The number of wait states in cycle (no shift). + */ +uint32_t flash_get_wait_state(uint32_t ul_address) +{ + Efc *p_efc; + + translate_address(&p_efc, ul_address, NULL, NULL); + return efc_get_wait_state(p_efc); +} + +/** + * \brief Get flash descriptor. + * + * \param ul_address Flash bank start address. + * \param pul_flash_descriptor Pointer to a data buffer to store flash descriptor. + * \param ul_size Data buffer size in DWORD. + * + * \return The actual descriptor length. + */ +uint32_t flash_get_descriptor(uint32_t ul_address, + uint32_t *pul_flash_descriptor, uint32_t ul_size) +{ + Efc *p_efc; + uint32_t ul_tmp; + uint32_t ul_cnt; + + translate_address(&p_efc, ul_address, NULL, NULL); + + /* Command fails */ + if (FLASH_RC_OK != efc_perform_command(p_efc, EFC_FCMD_GETD, 0)) { + return 0; + } else { + /* Read until no result */ + for (ul_cnt = 0;; ul_cnt++) { + ul_tmp = efc_get_result(p_efc); + if ((ul_size > ul_cnt) && (ul_tmp != 0)) { + *pul_flash_descriptor++ = ul_tmp; + } else { + break; + } + } + } + + return ul_cnt; +} + +/** + * \brief Get flash total page count for the specified bank. + * + * \note The flash descriptor must be fetched from flash_get_descriptor + * function first. + * + * \param pul_flash_descriptor Pointer to a flash descriptor. + * + * \return The flash total page count. + */ +uint32_t flash_get_page_count(const uint32_t *pul_flash_descriptor) +{ + return (pul_flash_descriptor[1] / pul_flash_descriptor[2]); +} + +/** + * \brief Get flash page count per region (plane) for the specified bank. + * + * \note The flash descriptor must be fetched from flash_get_descriptor + * function first. + * + * \param pul_flash_descriptor Pointer to a flash descriptor. + * + * \return The flash page count per region (plane). + */ +uint32_t flash_get_page_count_per_region(const uint32_t *pul_flash_descriptor) +{ + return (pul_flash_descriptor[4] / pul_flash_descriptor[2]); +} + +/** + * \brief Get flash region (plane) count for the specified bank. + * + * \note The flash descriptor must be fetched from flash_get_descriptor + * function first. + * + * \param pul_flash_descriptor Pointer to a flash descriptor. + * + * \return The flash region (plane) count. + */ +uint32_t flash_get_region_count(const uint32_t *pul_flash_descriptor) +{ + return (pul_flash_descriptor[3]); +} + +/** + * \brief Erase the entire flash. + * + * \note Only the flash bank including ul_address will be erased. If there are + * two flash banks, we need to call this function twice with each bank start + * address. + * + * \param ul_address Flash bank start address. + * + * \return 0 if successful; otherwise returns an error code. + */ +uint32_t flash_erase_all(uint32_t ul_address) +{ + Efc *p_efc; + + translate_address(&p_efc, ul_address, NULL, NULL); + + if (EFC_RC_OK != efc_perform_command(p_efc, EFC_FCMD_EA, 0)) { + return FLASH_RC_ERROR; + } + + return FLASH_RC_OK; +} + +#if SAM3SD8 +/** + * \brief Erase the flash by plane. + * + * \param ul_address Flash plane start address. + * + * \note Erase plane command needs a page number parameter which belongs to + * the plane to be erased. + * + * \return 0 if successful; otherwise returns an error code. + */ +uint32_t flash_erase_plane(uint32_t ul_address) +{ + Efc *p_efc; + uint16_t us_page; + + translate_address(&p_efc, ul_address, &us_page, NULL); + + if (EFC_RC_OK != efc_perform_command(p_efc, EFC_FCMD_EPL, us_page)) { + return FLASH_RC_ERROR; + } + + return FLASH_RC_OK; +} +#endif + +#if (SAM4S || SAM4E) +/** + * \brief Erase the specified pages of flash. + * + * \param ul_address Flash bank start address. + * + * \return 0 if successful; otherwise returns an error code. + */ +uint32_t flash_erase_page(uint32_t ul_address, uint8_t uc_page_num) +{ + Efc *p_efc; + uint16_t us_page; + + if (uc_page_num >= IFLASH_ERASE_PAGES_INVALID) { + return FLASH_RC_INVALID; + } + + if (ul_address & (IFLASH_PAGE_SIZE - 1)) { + return FLASH_RC_INVALID; + } + + translate_address(&p_efc, ul_address, &us_page, NULL); + + if (EFC_RC_OK != efc_perform_command(p_efc, EFC_FCMD_EPA, + (us_page | uc_page_num))) { + return FLASH_RC_ERROR; + } + + return FLASH_RC_OK; +} + +/** + * \brief Erase the flash sector. + * + * \note Erase sector command needs a page number parameter which belongs to + * the sector to be erased. + * + * \param ul_address Flash sector start address. + * + * \return 0 if successful; otherwise returns an error code. + */ +uint32_t flash_erase_sector(uint32_t ul_address) +{ + Efc *p_efc; + uint16_t us_page; + + translate_address(&p_efc, ul_address, &us_page, NULL); + + if (EFC_RC_OK != efc_perform_command(p_efc, EFC_FCMD_ES, us_page)) { + return FLASH_RC_ERROR; + } + + return FLASH_RC_OK; +} +#endif + +/** + * \brief Write a data buffer on flash. + * + * \note This function works in polling mode, and thus only returns when the + * data has been effectively written. + * \note For dual bank flash, this function doesn't support cross write from + * bank 0 to bank 1. In this case, flash_write must be called twice (ie for + * each bank). + * + * \param ul_address Write address. + * \param p_buffer Data buffer. + * \param ul_size Size of data buffer in bytes. + * \param ul_erase_flag Flag to set if erase first. + * + * \return 0 if successful, otherwise returns an error code. + */ +uint32_t flash_write(uint32_t ul_address, const void *p_buffer, + uint32_t ul_size, uint32_t ul_erase_flag) +{ + Efc *p_efc; + uint32_t ul_fws_temp; + uint16_t us_page; + uint16_t us_offset; + uint32_t writeSize; + uint32_t ul_page_addr; + uint16_t us_padding; + uint32_t ul_error; + uint32_t ul_idx; + uint32_t *p_aligned_dest; + uint8_t *puc_page_buffer = (uint8_t *) gs_ul_page_buffer; + + translate_address(&p_efc, ul_address, &us_page, &us_offset); + + /* According to the errata, set the wait state value to 6. */ + ul_fws_temp = efc_get_wait_state(p_efc); + efc_set_wait_state(p_efc, 6); + + /* Write all pages */ + while (ul_size > 0) { + /* Copy data in temporary buffer to avoid alignment problems. */ + writeSize = Min((uint32_t) IFLASH_PAGE_SIZE - us_offset, + ul_size); + compute_address(p_efc, us_page, 0, &ul_page_addr); + us_padding = IFLASH_PAGE_SIZE - us_offset - writeSize; + + /* Pre-buffer data */ + memcpy(puc_page_buffer, (void *)ul_page_addr, us_offset); + + /* Buffer data */ + memcpy(puc_page_buffer + us_offset, p_buffer, writeSize); + + /* Post-buffer data */ + memcpy(puc_page_buffer + us_offset + writeSize, + (void *)(ul_page_addr + us_offset + writeSize), + us_padding); + + /* Write page. + * Writing 8-bit and 16-bit data is not allowed and may lead to + * unpredictable data corruption. + */ + p_aligned_dest = (uint32_t *) ul_page_addr; + for (ul_idx = 0; ul_idx < (IFLASH_PAGE_SIZE / sizeof(uint32_t)); + ++ul_idx) { + *p_aligned_dest++ = gs_ul_page_buffer[ul_idx]; + } + + if (ul_erase_flag) { + ul_error = efc_perform_command(p_efc, EFC_FCMD_EWP, + us_page); + } else { + ul_error = efc_perform_command(p_efc, EFC_FCMD_WP, + us_page); + } + + if (ul_error) { + return ul_error; + } + + /* Progression */ + p_buffer = (void *)((uint32_t) p_buffer + writeSize); + ul_size -= writeSize; + us_page++; + us_offset = 0; + } + + /* According to the errata, restore the wait state value. */ + efc_set_wait_state(p_efc, ul_fws_temp); + + return FLASH_RC_OK; +} + + +/** + * \brief Lock all the regions in the given address range. The actual lock + * range is reported through two output parameters. + * + * \param ul_start Start address of lock range. + * \param ul_end End address of lock range. + * \param pul_actual_start Start address of the actual lock range (optional). + * \param pul_actual_end End address of the actual lock range (optional). + * + * \return 0 if successful, otherwise returns an error code. + */ +uint32_t flash_lock(uint32_t ul_start, uint32_t ul_end, + uint32_t *pul_actual_start, uint32_t *pul_actual_end) +{ + Efc *p_efc; + uint32_t ul_actual_start, ul_actual_end; + uint16_t us_start_page, us_end_page; + uint32_t ul_error; + uint16_t us_num_pages_in_region = + IFLASH_LOCK_REGION_SIZE / IFLASH_PAGE_SIZE; + + /* Compute actual lock range and store it */ + compute_lock_range(ul_start, ul_end, &ul_actual_start, &ul_actual_end); + + if (pul_actual_start != NULL) { + *pul_actual_start = ul_actual_start; + } + + if (pul_actual_end != NULL) { + *pul_actual_end = ul_actual_end; + } + + /* Compute page numbers */ + translate_address(&p_efc, ul_actual_start, &us_start_page, 0); + translate_address(0, ul_actual_end, &us_end_page, 0); + + /* Lock all pages */ + while (us_start_page < us_end_page) { + ul_error = efc_perform_command(p_efc, EFC_FCMD_SLB, us_start_page); + + if (ul_error) { + return ul_error; + } + us_start_page += us_num_pages_in_region; + } + + return FLASH_RC_OK; +} + +/** + * \brief Unlock all the regions in the given address range. The actual unlock + * range is reported through two output parameters. + * + * \param ul_start Start address of unlock range. + * \param ul_end End address of unlock range. + * \param pul_actual_start Start address of the actual unlock range (optional). + * \param pul_actual_end End address of the actual unlock range (optional). + * + * \return 0 if successful, otherwise returns an error code. + */ +uint32_t flash_unlock(uint32_t ul_start, uint32_t ul_end, + uint32_t *pul_actual_start, uint32_t *pul_actual_end) +{ + Efc *p_efc; + uint32_t ul_actual_start, ul_actual_end; + uint16_t us_start_page, us_end_page; + uint32_t ul_error; + uint16_t us_num_pages_in_region = + IFLASH_LOCK_REGION_SIZE / IFLASH_PAGE_SIZE; + + /* Compute actual unlock range and store it */ + compute_lock_range(ul_start, ul_end, &ul_actual_start, &ul_actual_end); + if (pul_actual_start != NULL) { + *pul_actual_start = ul_actual_start; + } + if (pul_actual_end != NULL) { + *pul_actual_end = ul_actual_end; + } + + /* Compute page numbers */ + translate_address(&p_efc, ul_actual_start, &us_start_page, 0); + translate_address(0, ul_actual_end, &us_end_page, 0); + + /* Unlock all pages */ + while (us_start_page < us_end_page) { + ul_error = efc_perform_command(p_efc, EFC_FCMD_CLB, + us_start_page); + if (ul_error) { + return ul_error; + } + us_start_page += us_num_pages_in_region; + } + + return FLASH_RC_OK; +} + +/** + * \brief Get the number of locked regions inside the given address range. + * + * \param ul_start Start address of range + * \param ul_end End address of range. + * + * \return The number of locked regions inside the given address range. + */ +uint32_t flash_is_locked(uint32_t ul_start, uint32_t ul_end) +{ + Efc *p_efc; + uint16_t us_start_page, us_end_page; + uint8_t uc_start_region, uc_end_region; + uint16_t us_num_pages_in_region; + uint32_t ul_status; + uint32_t ul_error; + uint32_t ul_num_locked_regions = 0; + uint32_t ul_count = 0; + uint32_t ul_bit = 0; + + /* Compute page numbers */ + translate_address(&p_efc, ul_start, &us_start_page, 0); + translate_address(0, ul_end, &us_end_page, 0); + + /* Compute region numbers */ + us_num_pages_in_region = IFLASH_LOCK_REGION_SIZE / IFLASH_PAGE_SIZE; + uc_start_region = us_start_page / us_num_pages_in_region; + uc_end_region = us_end_page / us_num_pages_in_region; + + /* Retrieve lock status */ + ul_error = efc_perform_command(p_efc, EFC_FCMD_GLB, 0); + + /* Skip unrequested regions (if necessary) */ + ul_status = efc_get_result(p_efc); + while (!(ul_count <= uc_start_region && + uc_start_region < (ul_count + 32))) { + ul_status = efc_get_result(p_efc); + ul_count += 32; + } + + /* Check status of each involved region */ + ul_bit = uc_start_region - ul_count; + + /* Number of region to check (must be > 0) */ + ul_count = uc_end_region - uc_start_region + 1; + + while (ul_count > 0) { + if (ul_status & (1 << (ul_bit))) { + ul_num_locked_regions++; + } + + ul_count -= 1; + ul_bit += 1; + if (ul_bit == 32) { + ul_status = efc_get_result(p_efc); + ul_bit = 0; + } + } + + return ul_num_locked_regions; +} + +/** + * \brief Set the given GPNVM bit. + * + * \param ul_gpnvm GPNVM bit index. + * + * \return 0 if successful; otherwise returns an error code. + */ +uint32_t flash_set_gpnvm(uint32_t ul_gpnvm) +{ + if (ul_gpnvm >= GPNVM_NUM_MAX) { + return FLASH_RC_INVALID; + } + + if (FLASH_RC_YES == flash_is_gpnvm_set(ul_gpnvm)) { + return FLASH_RC_OK; + } + + if (EFC_RC_OK == efc_perform_command(EFC, EFC_FCMD_SGPB, ul_gpnvm)) { + return FLASH_RC_OK; + } + + return FLASH_RC_ERROR; +} + +/** + * \brief Clear the given GPNVM bit. + * + * \param ul_gpnvm GPNVM bit index. + * + * \return 0 if successful; otherwise returns an error code. + */ +uint32_t flash_clear_gpnvm(uint32_t ul_gpnvm) +{ + if (ul_gpnvm >= GPNVM_NUM_MAX) { + return FLASH_RC_INVALID; + } + + if (FLASH_RC_NO == flash_is_gpnvm_set(ul_gpnvm)) { + return FLASH_RC_OK; + } + + if (EFC_RC_OK == efc_perform_command(EFC, EFC_FCMD_CGPB, ul_gpnvm)) { + return FLASH_RC_OK; + } + + return FLASH_RC_ERROR; +} + +/** + * \brief Check if the given GPNVM bit is set or not. + * + * \param ul_gpnvm GPNVM bit index. + * + * \retval 1 If the given GPNVM bit is currently set. + * \retval 0 If the given GPNVM bit is currently cleared. + */ +uint32_t flash_is_gpnvm_set(uint32_t ul_gpnvm) +{ + uint32_t ul_gpnvm_bits; + + if (ul_gpnvm >= GPNVM_NUM_MAX) { + return FLASH_RC_INVALID; + } + + if (EFC_RC_OK != efc_perform_command(EFC, EFC_FCMD_GGPB, 0)) { + return FLASH_RC_ERROR; + } + + ul_gpnvm_bits = efc_get_result(EFC); + if (ul_gpnvm_bits & (1 << ul_gpnvm)) { + return FLASH_RC_YES; + } + + return FLASH_RC_NO; +} + +/** + * \brief Set security bit. + * + * \return 0 if successful; otherwise returns an error code. + */ +uint32_t flash_enable_security_bit(void) +{ + return flash_set_gpnvm(0); +} + +/** + * \brief Check if the security bit is set or not. + * + * \retval 1 If the security bit is currently set. + * \retval 0 If the security bit is currently cleared. + */ +uint32_t flash_is_security_bit_enabled(void) +{ + return flash_is_gpnvm_set(0); +} + +/** + * \brief Read the flash unique ID. + * + * \param pul_data Pointer to a data buffer to store 128-bit unique ID. + * \param ul_size Data buffer size in DWORD. + * + * \return 0 if successful; otherwise returns an error code. + */ +uint32_t flash_read_unique_id(uint32_t *pul_data, uint32_t ul_size) +{ + uint32_t uid_buf[4]; + uint32_t ul_idx; + + if (FLASH_RC_OK != efc_perform_read_sequence(EFC, EFC_FCMD_STUI, + EFC_FCMD_SPUI, uid_buf, 4)) { + return FLASH_RC_ERROR; + } + + if (ul_size > 4) { + /* Only 4 dword to store unique ID */ + ul_size = 4; + } + + for (ul_idx = 0; ul_idx < ul_size; ul_idx++) { + pul_data[ul_idx] = uid_buf[ul_idx]; + } + + return FLASH_RC_OK; +} + +#if (SAM4S || SAM4E) +/** + * \brief Read the flash user signature. + * + * \param p_data Pointer to a data buffer to store 512 bytes of user signature. + * \param ul_size Data buffer size. + * + * \return 0 if successful; otherwise returns an error code. + */ +uint32_t flash_read_user_signature(uint32_t *p_data, uint32_t ul_size) +{ + if (ul_size > FLASH_USER_SIG_SIZE) { + /* Only 512 byte to store unique ID */ + ul_size = FLASH_USER_SIG_SIZE; + } + + /* Send the read user signature commands */ + if (FLASH_RC_OK != efc_perform_read_sequence(EFC, EFC_FCMD_STUS, + EFC_FCMD_SPUS, p_data, ul_size)) { + return FLASH_RC_ERROR; + } + + return FLASH_RC_OK; +} + +/** + * \brief Write the flash user signature. + * + * \param ul_address Write address. + * \param p_data Pointer to a data buffer to store 512 bytes of user signature. + * \param ul_size Data buffer size. + * + * \return 0 if successful; otherwise returns an error code. + */ +uint32_t flash_write_user_signature(uint32_t ul_address, const void *p_buffer, + uint32_t ul_size) +{ + /* The user signature should be no longer than 512 bytes */ + if (ul_size > FLASH_USER_SIG_SIZE) { + return FLASH_RC_INVALID; + } + + /* Write the full page */ + flash_write(ul_address, p_buffer, ul_size, 0); + + /* Send the write signature command */ + if (FLASH_RC_OK != efc_perform_command(EFC, EFC_FCMD_WUS, 0)) { + return FLASH_RC_ERROR; + } + + return FLASH_RC_OK; +} + +/** + * \brief Erase the flash user signature. + * + * \return 0 if successful; otherwise returns an error code. + */ +uint32_t flash_erase_user_signature(void) +{ + /* Perform the erase user signature command */ + return efc_perform_command(EFC, EFC_FCMD_EUS, 0); +} +#endif + +//@} + +/// @cond 0 +/**INDENT-OFF**/ +#ifdef __cplusplus +} +#endif +/**INDENT-ON**/ +/// @endcond diff --git a/src/flash_efc.h b/src/flash_efc.h new file mode 100644 index 0000000..bd52033 --- /dev/null +++ b/src/flash_efc.h @@ -0,0 +1,151 @@ +/** + * \file + * + * \brief Embedded Flash service for SAM. + * + * Copyright (c) 2011-2013 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. 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. + * + * 3. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef FLASH_H_INCLUDED +#define FLASH_H_INCLUDED + +#include +#include "efc.h" + +/* Internal Flash 0 base address. */ +#define IFLASH_ADDR IFLASH0_ADDR + /* Internal flash page size. */ +#define IFLASH_PAGE_SIZE IFLASH0_PAGE_SIZE + +/* Last page start address. */ +#define IFLASH_LAST_PAGE_ADDRESS (IFLASH1_ADDR + IFLASH1_SIZE - IFLASH1_PAGE_SIZE) + +/// @cond 0 +/**INDENT-OFF**/ +#ifdef __cplusplus + extern "C" { +#endif +/**INDENT-ON**/ +/// @endcond + +/*! \name Flash driver return codes */ +//! @{ +typedef enum flash_rc { + FLASH_RC_OK = 0, //!< Operation OK + FLASH_RC_YES = 0, //!< Yes + FLASH_RC_NO = 1, //!< No + FLASH_RC_ERROR = 0x10, //!< General error + FLASH_RC_INVALID, //!< Invalid argument input + FLASH_RC_NOT_SUPPORT = 0xFFFFFFFF //!< Operation is not supported +} flash_rc_t; +//! @} + +/*! \name Flash erase page num in FARG[1:0] + \note The erase page commands should be cautiouly used as EPA4/EPA32 will not + take effect according to errata and EPA8/EPA16 must module 8/16 page addresses.*/ +//! @{ +typedef enum flash_farg_page_num { + /* 4 of pages to be erased with EPA command*/ + IFLASH_ERASE_PAGES_4=0, + /* 8 of pages to be erased with EPA command*/ + IFLASH_ERASE_PAGES_8, + /* 16 of pages to be erased with EPA command*/ + IFLASH_ERASE_PAGES_16, + /* 32 of pages to be erased with EPA command*/ + IFLASH_ERASE_PAGES_32, + /* Parameter is not support */ + IFLASH_ERASE_PAGES_INVALID, +}flash_farg_page_num_t; +//! @} + +/*! \name Flash access mode */ +//! @{ +#define FLASH_ACCESS_MODE_128 EFC_ACCESS_MODE_128 +#define FLASH_ACCESS_MODE_64 EFC_ACCESS_MODE_64 +//! @} + +uint32_t flash_init(uint32_t ul_mode, uint32_t ul_fws); +uint32_t flash_set_wait_state(uint32_t ul_address, uint32_t ul_fws); +uint32_t flash_set_wait_state_adaptively(uint32_t ul_address); +uint32_t flash_get_wait_state(uint32_t ul_address); +uint32_t flash_get_descriptor(uint32_t ul_address, + uint32_t *pul_flash_descriptor, uint32_t ul_size); +uint32_t flash_get_page_count(const uint32_t *pul_flash_descriptor); +uint32_t flash_get_page_count_per_region(const uint32_t *pul_flash_descriptor); +uint32_t flash_get_region_count(const uint32_t *pul_flash_descriptor); +uint32_t flash_erase_all(uint32_t ul_address); + +#if SAM3SD8 +uint32_t flash_erase_plane(uint32_t ul_address); +#endif + +#if (SAM4S || SAM4E) +uint32_t flash_erase_page(uint32_t ul_address, uint8_t uc_page_num); +uint32_t flash_erase_sector(uint32_t ul_address); +#endif + +uint32_t flash_write(uint32_t ul_address, const void *p_buffer, + uint32_t ul_size, uint32_t ul_erase_flag); +uint32_t flash_lock(uint32_t ul_start, uint32_t ul_end, + uint32_t *pul_actual_start, uint32_t *pul_actual_end); +uint32_t flash_unlock(uint32_t ul_start, uint32_t ul_end, + uint32_t *pul_actual_start, uint32_t *pul_actual_end); +uint32_t flash_is_locked(uint32_t ul_start, uint32_t ul_end); +uint32_t flash_set_gpnvm(uint32_t ul_gpnvm); +uint32_t flash_clear_gpnvm(uint32_t ul_gpnvm); +uint32_t flash_is_gpnvm_set(uint32_t ul_gpnvm); +uint32_t flash_enable_security_bit(void); +uint32_t flash_is_security_bit_enabled(void); +uint32_t flash_read_unique_id(uint32_t *pul_data, uint32_t ul_size); + +#if (SAM4S || SAM4E) +uint32_t flash_read_user_signature(uint32_t *p_data, uint32_t ul_size); +uint32_t flash_write_user_signature(uint32_t ul_address, const void *p_buffer, + uint32_t ul_size); +uint32_t flash_erase_user_signature(void); +#endif + +/// @cond 0 +/**INDENT-OFF**/ +#ifdef __cplusplus +} +#endif +/**INDENT-ON**/ +/// @endcond + +#endif /* FLASH_H_INCLUDED */