From 18005bcc564494f4ae86972b3b5db0970b3b1530 Mon Sep 17 00:00:00 2001 From: Christopher Haster Date: Tue, 14 Feb 2017 10:57:42 -0600 Subject: [PATCH 01/29] Initial commit of SPI flash device --- LICENSE | 165 +++++++++++++++ README.md | 42 ++++ SPIFBlockDevice.cpp | 341 +++++++++++++++++++++++++++++++ SPIFBlockDevice.h | 154 ++++++++++++++ TESTS/block_device/spif/main.cpp | 145 +++++++++++++ 5 files changed, 847 insertions(+) create mode 100644 LICENSE create mode 100644 README.md create mode 100644 SPIFBlockDevice.cpp create mode 100644 SPIFBlockDevice.h create mode 100644 TESTS/block_device/spif/main.cpp diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000..59cd3f8a32 --- /dev/null +++ b/LICENSE @@ -0,0 +1,165 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and +distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright +owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities +that control, are controlled by, or are under common control with that entity. +For the purposes of this definition, "control" means (i) the power, direct or +indirect, to cause the direction or management of such entity, whether by +contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the +outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising +permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including +but not limited to software source code, documentation source, and configuration +files. + +"Object" form shall mean any form resulting from mechanical transformation or +translation of a Source form, including but not limited to compiled object code, +generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made +available under the License, as indicated by a copyright notice that is included +in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that +is based on (or derived from) the Work and for which the editorial revisions, +annotations, elaborations, or other modifications represent, as a whole, an +original work of authorship. For the purposes of this License, Derivative Works +shall not include works that remain separable from, or merely link (or bind by +name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version +of the Work and any modifications or additions to that Work or Derivative Works +thereof, that is intentionally submitted to Licensor for inclusion in the Work +by the copyright owner or by an individual or Legal Entity authorized to submit +on behalf of the copyright owner. For the purposes of this definition, +"submitted" means any form of electronic, verbal, or written communication sent +to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, and +issue tracking systems that are managed by, or on behalf of, the Licensor for +the purpose of discussing and improving the Work, but excluding communication +that is conspicuously marked or otherwise designated in writing by the copyright +owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf +of whom a Contribution has been received by Licensor and subsequently +incorporated within the Work. + +2. Grant of Copyright License. + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable copyright license to reproduce, prepare Derivative Works of, +publicly display, publicly perform, sublicense, and distribute the Work and such +Derivative Works in Source or Object form. + +3. Grant of Patent License. + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable (except as stated in this section) patent license to make, have +made, use, offer to sell, sell, import, and otherwise transfer the Work, where +such license applies only to those patent claims licensable by such Contributor +that are necessarily infringed by their Contribution(s) alone or by combination +of their Contribution(s) with the Work to which such Contribution(s) was +submitted. If You institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Work or a +Contribution incorporated within the Work constitutes direct or contributory +patent infringement, then any patent licenses granted to You under this License +for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. + +You may reproduce and distribute copies of the Work or Derivative Works thereof +in any medium, with or without modifications, and in Source or Object form, +provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of +this License; and +You must cause any modified files to carry prominent notices stating that You +changed the files; and +You must retain, in the Source form of any Derivative Works that You distribute, +all copyright, patent, trademark, and attribution notices from the Source form +of the Work, excluding those notices that do not pertain to any part of the +Derivative Works; and +If the Work includes a "NOTICE" text file as part of its distribution, then any +Derivative Works that You distribute must include a readable copy of the +attribution notices contained within such NOTICE file, excluding those notices +that do not pertain to any part of the Derivative Works, in at least one of the +following places: within a NOTICE text file distributed as part of the +Derivative Works; within the Source form or documentation, if provided along +with the Derivative Works; or, within a display generated by the Derivative +Works, if and wherever such third-party notices normally appear. The contents of +the NOTICE file are for informational purposes only and do not modify the +License. You may add Your own attribution notices within Derivative Works that +You distribute, alongside or as an addendum to the NOTICE text from the Work, +provided that such additional attribution notices cannot be construed as +modifying the License. +You may add Your own copyright statement to Your modifications and may provide +additional or different license terms and conditions for use, reproduction, or +distribution of Your modifications, or for any such Derivative Works as a whole, +provided Your use, reproduction, and distribution of the Work otherwise complies +with the conditions stated in this License. + +5. Submission of Contributions. + +Unless You explicitly state otherwise, any Contribution intentionally submitted +for inclusion in the Work by You to the Licensor shall be under the terms and +conditions of this License, without any additional terms or conditions. +Notwithstanding the above, nothing herein shall supersede or modify the terms of +any separate license agreement you may have executed with Licensor regarding +such Contributions. + +6. Trademarks. + +This License does not grant permission to use the trade names, trademarks, +service marks, or product names of the Licensor, except as required for +reasonable and customary use in describing the origin of the Work and +reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. + +Unless required by applicable law or agreed to in writing, Licensor provides the +Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, +including, without limitation, any warranties or conditions of TITLE, +NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are +solely responsible for determining the appropriateness of using or +redistributing the Work and assume any risks associated with Your exercise of +permissions under this License. + +8. Limitation of Liability. + +In no event and under no legal theory, whether in tort (including negligence), +contract, or otherwise, unless required by applicable law (such as deliberate +and grossly negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, incidental, +or consequential damages of any character arising as a result of this License or +out of the use or inability to use the Work (including but not limited to +damages for loss of goodwill, work stoppage, computer failure or malfunction, or +any and all other commercial damages or losses), even if such Contributor has +been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. + +While redistributing the Work or Derivative Works thereof, You may choose to +offer, and charge a fee for, acceptance of support, warranty, indemnity, or +other liability obligations and/or rights consistent with this License. However, +in accepting such obligations, You may act only on Your own behalf and on Your +sole responsibility, not on behalf of any other Contributor, and only if You +agree to indemnify, defend, and hold each Contributor harmless for any liability +incurred by, or claims asserted against, such Contributor by reason of your +accepting any such warranty or additional liability. diff --git a/README.md b/README.md new file mode 100644 index 0000000000..7f7113fa3a --- /dev/null +++ b/README.md @@ -0,0 +1,42 @@ +# SPI Flash Driver + +Block device driver for NOR based SPI flash devices that support SFDP. + +NOR based SPI flash supports byte-sized read and writes, with an erase size of around 4kbytes. An erase sets a block to all 1s, with successive writes clearing set bits. + +More info on NOR flash can be found on wikipedia: +https://en.wikipedia.org/wiki/Flash_memory#NOR_memories + +``` cpp +// Here's an example using the MX25R SPI flash device on the K82F +#include "mbed.h" +#include "SPIFBlockDevice.h" + +// Create flash device on SPI bus with PTE5 as chip select +SPIFBlockDevice spif(PTE2, PTE4, PTE1, PTE5); + +int main() { + printf("spif test\n"); + + // Initialize the SPI flash device and print the memory layout + spif.init(); + printf("spif size: %llu\n", spif.size()); + printf("spif read size: %llu\n", spif.get_read_size()); + printf("spif program size: %llu\n", spif.get_program_size()); + printf("spif erase size: %llu\n", spif.get_erase_size()); + + // Write "Hello World!" to the first block + uint8_t *buffer = malloc(spif.get_erase_size()); + sprintf(buffer, "Hello World!\n"); + spif.erase(0, spif.get_erase_size()); + spif.program(buffer, 0, spif.get_erase_size()); + + // Read back what was stored + spif.read(buffer, 0, spif.get_erase_size()); + printf("%s", buffer); + + // Deinitialize the device + spif.deinit(); +} +``` + diff --git a/SPIFBlockDevice.cpp b/SPIFBlockDevice.cpp new file mode 100644 index 0000000000..728c70e526 --- /dev/null +++ b/SPIFBlockDevice.cpp @@ -0,0 +1,341 @@ +/* mbed Microcontroller Library + * Copyright (c) 2016 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "SPIFBlockDevice.h" + + +// Read/write/erase sizes +#define SPIF_READ_SIZE 1 +#define SPIF_PROG_SIZE 1 +#define SPIF_SE_SIZE 4096 +#define SPIF_TIMEOUT 10000 + +// Debug available +#define SPIF_DEBUG 0 + +// MX25R Series Register Command Table. +enum ops { + SPIF_NOP = 0x00, // No operation + SPIF_READ = 0x03, // Read data + SPIF_PROG = 0x02, // Program data + SPIF_SE = 0x20, // 4KB Sector Erase + SPIF_CE = 0xc7, // Chip Erase + SPIF_SFDP = 0x5a, // Read SFDP + SPIF_WREN = 0x06, // Write Enable + SPIF_WRDI = 0x04, // Write Disable + SPIF_RDSR = 0x05, // Read Status Register + SPIF_RDID = 0x9f, // Read Manufacturer and JDEC Device ID +}; + +// Status register from RDSR +// [- stuff -| wel | wip ] +// [- 6 -| 1 | 1 ] +#define SPIF_WEL 0x2 +#define SPIF_WIP 0x1 + + +SPIFBlockDevice::SPIFBlockDevice( + PinName mosi, PinName miso, PinName sclk, PinName cs, int freq) + : _spi(mosi, miso, sclk), _cs(cs), _size(0) +{ + _cs = 1; + _spi.frequency(freq); +} + +bd_error_t SPIFBlockDevice::init() +{ + // Check for vendor specific hacks, these should move into more general + // handling when possible. RDID is not used to verify a device is attached. + uint8_t id[3]; + _cmdread(SPIF_RDID, 0, 3, 0x0, id); + + switch (id[0]) { + case 0xbf: + // SST devices come preset with block protection + // enabled for some regions, issue gbpu instruction to clear + _wren(); + _cmdwrite(0x98, 0, 0, 0x0, NULL); + break; + } + + // Check that device is doing ok + bd_error_t err = _sync(); + if (err) { + return BD_ERROR_NO_DEVICE; + } + + // Check JEDEC serial flash discoverable parameters for device + // specific info + uint8_t header[16]; + _cmdread(SPIF_SFDP, 4, 16, 0x0, header); + + // Verify SFDP signature for sanity + // Also check that major/minor version is acceptable + if (!(memcmp(&header[0], "SFDP", 4) == 0 && header[5] == 1)) { + return BD_ERROR_DEVICE_ERROR; + } + + // The SFDP spec indicates the standard table is always at offset 0 + // in the parameter headers, we check just to be safe + if (!(header[8] == 0 && header[10] == 1)) { + return BD_ERROR_DEVICE_ERROR; + } + + // Parameter table pointer, spi commands are BE, SFDP is LE, + // also sfdp command expects extra read wait byte + uint32_t table_addr = ( + (header[14] << 24) | + (header[13] << 16) | + (header[12] << 8 )); + uint8_t table[8]; + _cmdread(SPIF_SFDP, 4, 8, table_addr, table); + + // Check erase size, currently only supports 4kbytes + // TODO support erase size != 4kbytes? + // TODO support other erase opcodes from the sector descriptions + if ((table[0] & 0x3) != 0x1 || table[1] != SPIF_SE) { + return BD_ERROR_DEVICE_ERROR; + } + + // Check address size, currently only supports 3byte addresses + // TODO support address > 3bytes? + // TODO check for devices larger than 2Gbits? + if ((table[2] & 0x4) != 0 || (table[7] & 0x80) != 0) { + return BD_ERROR_DEVICE_ERROR; + } + + // Get device density, stored as size in bits - 1 + uint32_t density = ( + (table[7] << 24) | + (table[6] << 16) | + (table[5] << 8 ) | + (table[4] << 0 )); + _size = (density/8) + 1; + + return 0; +} + +bd_error_t SPIFBlockDevice::deinit() +{ + // Latch write disable just to keep noise + // from changing the device + _cmdwrite(SPIF_WRDI, 0, 0, 0x0, NULL); + + return 0; +} + +void SPIFBlockDevice::_cmdread( + uint8_t op, uint32_t addrc, uint32_t retc, + uint32_t addr, uint8_t *rets) +{ + _cs = 0; + _spi.write(op); + + for (uint32_t i = 0; i < addrc; i++) { + _spi.write(0xff & (addr >> 8*(addrc-1 - i))); + } + + for (uint32_t i = 0; i < retc; i++) { + rets[i] = _spi.write(0); + } + _cs = 1; + + if (SPIF_DEBUG) { + printf("spif <- %02x", op); + for (uint32_t i = 0; i < addrc; i++) { + if (i < addrc) { + printf("%02lx", 0xff & (addr >> 8*(addrc-1 - i))); + } else { + printf(" "); + } + } + printf(" "); + for (uint32_t i = 0; i < 16 && i < retc; i++) { + printf("%02x", rets[i]); + } + if (retc > 16) { + printf("..."); + } + printf("\n"); + } +} + +void SPIFBlockDevice::_cmdwrite( + uint8_t op, uint32_t addrc, uint32_t argc, + uint32_t addr, const uint8_t *args) +{ + _cs = 0; + _spi.write(op); + + for (uint32_t i = 0; i < addrc; i++) { + _spi.write(0xff & (addr >> 8*(addrc-1 - i))); + } + + for (uint32_t i = 0; i < argc; i++) { + _spi.write(args[i]); + } + _cs = 1; + + if (SPIF_DEBUG) { + printf("spif -> %02x", op); + for (uint32_t i = 0; i < addrc; i++) { + if (i < addrc) { + printf("%02lx", 0xff & (addr >> 8*(addrc-1 - i))); + } else { + printf(" "); + } + } + printf(" "); + for (uint32_t i = 0; i < 16 && i < argc; i++) { + printf("%02x", args[i]); + } + if (argc > 16) { + printf("..."); + } + printf("\n"); + } +} + +bd_error_t SPIFBlockDevice::_sync() +{ + for (int i = 0; i < SPIF_TIMEOUT; i++) { + // Read status register until write not-in-progress + uint8_t status; + _cmdread(SPIF_RDSR, 0, 1, 0x0, &status); + + // Check WIP bit + if (!(status & SPIF_WIP)) { + return 0; + } + + wait_ms(1); + } + + return BD_ERROR_DEVICE_ERROR; +} + +bd_error_t SPIFBlockDevice::_wren() +{ + _cmdwrite(SPIF_WREN, 0, 0, 0x0, NULL); + + for (int i = 0; i < SPIF_TIMEOUT; i++) { + // Read status register until write latch is enabled + uint8_t status; + _cmdread(SPIF_RDSR, 0, 1, 0x0, &status); + + // Check WEL bit + if (status & SPIF_WEL) { + return 0; + } + + wait_ms(1); + } + + return BD_ERROR_DEVICE_ERROR; +} + +bd_error_t SPIFBlockDevice::read(void *buffer, bd_addr_t addr, bd_size_t size) +{ + // Check the address and size fit onto the chip. + if (!is_valid_read(addr, size)) { + return BD_ERROR_PARAMETER; + } + + _cmdread(SPIF_READ, 3, size, addr, static_cast(buffer)); + return 0; +} + +bd_error_t SPIFBlockDevice::program(const void *buffer, bd_addr_t addr, bd_size_t size) +{ + // Check the address and size fit onto the chip. + if (!is_valid_program(addr, size)) { + return BD_ERROR_PARAMETER; + } + + while (size > 0) { + bd_error_t err = _wren(); + if (err) { + return err; + } + + // Write up to 256 bytes a page + // TODO handle unaligned programs + uint32_t off = addr % 256; + uint32_t chunk = (off + size < 256) ? size : (256-off); + _cmdwrite(SPIF_PROG, 3, chunk, addr, static_cast(buffer)); + buffer = static_cast(buffer) + chunk; + addr += chunk; + size -= chunk; + + wait_ms(1); + + err = _sync(); + if (err) { + return err; + } + } + + return 0; +} + +bd_error_t SPIFBlockDevice::erase(bd_addr_t addr, bd_size_t size) +{ + // Check the address and size fit onto the chip. + if (!is_valid_erase(addr, size)) { + return BD_ERROR_PARAMETER; + } + + while (size > 0) { + bd_error_t err = _wren(); + if (err) { + return err; + } + + // Erase 4kbyte sectors + // TODO support other erase sizes? + uint32_t chunk = 4096; + _cmdwrite(SPIF_SE, 3, 0, addr, NULL); + addr += chunk; + size -= chunk; + + err = _sync(); + if (err) { + return err; + } + } + + return 0; +} + +bd_size_t SPIFBlockDevice::get_read_size() +{ + return SPIF_READ_SIZE; +} + +bd_size_t SPIFBlockDevice::get_program_size() +{ + return SPIF_PROG_SIZE; +} + +bd_size_t SPIFBlockDevice::get_erase_size() +{ + return SPIF_SE_SIZE; +} + +bd_size_t SPIFBlockDevice::size() +{ + return _size; +} diff --git a/SPIFBlockDevice.h b/SPIFBlockDevice.h new file mode 100644 index 0000000000..2093230d6d --- /dev/null +++ b/SPIFBlockDevice.h @@ -0,0 +1,154 @@ +/* mbed Microcontroller Library + * Copyright (c) 2016 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef MBED_SPIF_BLOCK_DEVICE_H +#define MBED_SPIF_BLOCK_DEVICE_H + +/* If the target has no SPI support then SPIF is not supported */ +#ifdef DEVICE_SPI + +#include +#include "BlockDevice.h" + + +/** BlockDevice for SPI based flash devices + * such as the MX25R or SST26F016B + * + * @code + * #include "mbed.h" + * #include "SPIFBlockDevice.h" + * + * // Create mx25r on SPI bus with PTE5 as chip select + * SPIFBlockDevice mx25r(PTE2, PTE4, PTE1, PTE5); + * + * int main() { + * printf("mx25r test\n"); + * mx52r.init(); + * printf("mx25r size: %llu\n", mx25r.size()); + * printf("mx25r read size: %llu\n", mx25r.get_read_size()); + * printf("mx25r program size: %llu\n", mx25r.get_program_size()); + * printf("mx25r erase size: %llu\n", mx25r.get_erase_size()); + * + * uint8_t *buffer = malloc(mx25r.get_erase_size()); + * sprintf(buffer, "Hello World!\n"); + * mx25r.erase(0, mx25r.get_erase_size()); + * mx25r.program(buffer, 0, mx25r.get_erase_size()); + * mx25r.read(buffer, 0, mx25r.get_erase_size()); + * printf("%s", buffer); + * + * mx25r.deinit(); + * } + */ +class SPIFBlockDevice : public BlockDevice { +public: + /** Creates a SPIFBlockDevice on a SPI bus specified by pins + * + * @param mosi SPI master out, slave in pin + * @param miso SPI master in, slave out pin + * @param sclk SPI clock pin + * @param csel SPI chip select pin + * @param freq Clock speed of the SPI bus (defaults to 40MHz) + */ + SPIFBlockDevice(PinName mosi, PinName miso, PinName sclk, PinName csel, int freq=4000000); + + /** Initialize a block device + * + * @return 0 on success or a negative error code on failure + */ + virtual bd_error_t init(); + + /** Deinitialize a block device + * + * @return 0 on success or a negative error code on failure + */ + virtual bd_error_t deinit(); + + /** Read blocks from a block device + * + * @param buffer Buffer to write blocks to + * @param addr Address of block to begin reading from + * @param size Size to read in bytes, must be a multiple of read block size + * @return 0 on success, negative error code on failure + */ + virtual bd_error_t read(void *buffer, bd_addr_t addr, bd_size_t size); + + /** Program blocks to a block device + * + * The blocks must have been erased prior to being programmed + * + * @param buffer Buffer of data to write to blocks + * @param addr Address of block to begin writing to + * @param size Size to write in bytes, must be a multiple of program block size + * @return 0 on success, negative error code on failure + */ + virtual bd_error_t program(const void *buffer, bd_addr_t addr, bd_size_t size); + + /** Erase blocks on a block device + * + * The state of an erased block is undefined until it has been programmed + * + * @param addr Address of block to begin erasing + * @param size Size to erase in bytes, must be a multiple of erase block size + * @return 0 on success, negative error code on failure + */ + virtual bd_error_t erase(bd_addr_t addr, bd_size_t size); + + /** Get the size of a readable block + * + * @return Size of a readable block in bytes + */ + virtual bd_size_t get_read_size(); + + /** Get the size of a programable block + * + * @return Size of a programable block in bytes + * @note Must be a multiple of the read size + */ + virtual bd_size_t get_program_size(); + + /** Get the size of a eraseable block + * + * @return Size of a eraseable block in bytes + * @note Must be a multiple of the program size + */ + virtual bd_size_t get_erase_size(); + + /** Get the total size of the underlying device + * + * @return Size of the underlying device in bytes + */ + virtual bd_size_t size(); + +private: + // Master side hardware + SPI _spi; + DigitalOut _cs; + + // Device configuration discovered through sfdp + bd_size_t _size; + + // Internal functions + bd_error_t _wren(); + bd_error_t _sync(); + void _cmdread(uint8_t op, uint32_t addrc, uint32_t retc, + uint32_t addr, uint8_t *rets); + void _cmdwrite(uint8_t op, uint32_t addrc, uint32_t argc, + uint32_t addr, const uint8_t *args); +}; + + +#endif /* DEVICE_SPI */ + +#endif /* MBED_SPIF_BLOCK_DEVICE_H */ diff --git a/TESTS/block_device/spif/main.cpp b/TESTS/block_device/spif/main.cpp new file mode 100644 index 0000000000..8fb231cb95 --- /dev/null +++ b/TESTS/block_device/spif/main.cpp @@ -0,0 +1,145 @@ +#include "mbed.h" +#include "greentea-client/test_env.h" +#include "unity.h" +#include "utest.h" + +#include "SPIFBlockDevice.h" +#include + +using namespace utest::v1; + +#ifndef SPIF_INSTALLED +#define SPIF_INSTALLED defined(TARGET_K82F) +#endif + +#if !SPIF_INSTALLED +#error [NOT_SUPPORTED] SPIF Required +#endif + +#if defined(TARGET_K82F) +#define TEST_PINS PTE2, PTE4, PTE1, PTE5 +#define TEST_FREQ 40000000 +#else +#define TEST_PINS D11, D12, D13, D10 +#define TEST_FREQ 1000000 +#endif + +#define TEST_BLOCK_COUNT 10 +#define TEST_ERROR_MASK 16 + +const struct { + const char *name; + bd_size_t (BlockDevice::*method)(); +} ATTRS[] = { + {"read size", &BlockDevice::get_read_size}, + {"program size", &BlockDevice::get_program_size}, + {"erase size", &BlockDevice::get_erase_size}, + {"total size", &BlockDevice::size}, +}; + + +void test_read_write() { + SPIFBlockDevice bd(TEST_PINS, TEST_FREQ); + + int err = bd.init(); + TEST_ASSERT_EQUAL(0, err); + + for (unsigned a = 0; a < sizeof(ATTRS)/sizeof(ATTRS[0]); a++) { + static const char *prefixes[] = {"", "k", "M", "G"}; + for (int i = 3; i >= 0; i--) { + bd_size_t size = (bd.*ATTRS[a].method)(); + if (size >= (1ULL << 10*i)) { + printf("%s: %llu%sbytes (%llubytes)\n", + ATTRS[a].name, size >> 10*i, prefixes[i], size); + break; + } + } + } + + bd_size_t block_size = bd.get_erase_size(); + uint8_t *write_block = new uint8_t[block_size]; + uint8_t *read_block = new uint8_t[block_size]; + uint8_t *error_mask = new uint8_t[TEST_ERROR_MASK]; + unsigned addrwidth = ceil(log(bd.size()-1) / log(16))+1; + + for (int b = 0; b < TEST_BLOCK_COUNT; b++) { + // Find a random block + bd_addr_t block = (rand()*block_size) % bd.size(); + + // Use next random number as temporary seed to keep + // the address progressing in the pseudorandom sequence + unsigned seed = rand(); + + // Fill with random sequence + srand(seed); + for (bd_size_t i = 0; i < block_size; i++) { + write_block[i] = 0xff & rand(); + } + + // Write, sync, and read the block + printf("test %0*llx:%llu...\n", addrwidth, block, block_size); + + err = bd.write(write_block, block, block_size); + TEST_ASSERT_EQUAL(0, err); + + printf("write %0*llx:%llu ", addrwidth, block, block_size); + for (int i = 0; i < 16; i++) { + printf("%02x", write_block[i]); + } + printf("...\n"); + + err = bd.read(read_block, block, block_size); + TEST_ASSERT_EQUAL(0, err); + + printf("read %0*llx:%llu ", addrwidth, block, block_size); + for (int i = 0; i < 16; i++) { + printf("%02x", read_block[i]); + } + printf("...\n"); + + // Find error mask for debugging + memset(error_mask, 0, TEST_ERROR_MASK); + bd_size_t error_scale = block_size / (TEST_ERROR_MASK*8); + + srand(seed); + for (bd_size_t i = 0; i < TEST_ERROR_MASK*8; i++) { + for (bd_size_t j = 0; j < error_scale; j++) { + if ((0xff & rand()) != read_block[i*error_scale + j]) { + error_mask[i/8] |= 1 << (i%8); + } + } + } + + printf("error %0*llx:%llu ", addrwidth, block, block_size); + for (int i = 0; i < 16; i++) { + printf("%02x", error_mask[i]); + } + printf("\n"); + + // Check that the data was unmodified + srand(seed); + for (bd_size_t i = 0; i < block_size; i++) { + TEST_ASSERT_EQUAL(0xff & rand(), read_block[i]); + } + } + + err = bd.deinit(); + TEST_ASSERT_EQUAL(0, err); +} + + +// Test setup +utest::v1::status_t test_setup(const size_t number_of_cases) { + GREENTEA_SETUP(30, "default_auto"); + return verbose_test_setup_handler(number_of_cases); +} + +Case cases[] = { + Case("Testing read write random blocks", test_read_write), +}; + +Specification specification(test_setup, cases); + +int main() { + return !Harness::run(specification); +} From 6e3dcd91038d237919d49c83d1106eb4c1097a87 Mon Sep 17 00:00:00 2001 From: Christopher Haster Date: Tue, 7 Mar 2017 17:27:46 -0600 Subject: [PATCH 02/29] Updated to match API changes in mbed OS --- SPIFBlockDevice.cpp | 42 ++++++++++++++------------------ SPIFBlockDevice.h | 27 +++++++++----------- TESTS/block_device/spif/main.cpp | 17 +++++-------- 3 files changed, 35 insertions(+), 51 deletions(-) diff --git a/SPIFBlockDevice.cpp b/SPIFBlockDevice.cpp index 728c70e526..12308d09e9 100644 --- a/SPIFBlockDevice.cpp +++ b/SPIFBlockDevice.cpp @@ -55,7 +55,7 @@ SPIFBlockDevice::SPIFBlockDevice( _spi.frequency(freq); } -bd_error_t SPIFBlockDevice::init() +int SPIFBlockDevice::init() { // Check for vendor specific hacks, these should move into more general // handling when possible. RDID is not used to verify a device is attached. @@ -72,9 +72,9 @@ bd_error_t SPIFBlockDevice::init() } // Check that device is doing ok - bd_error_t err = _sync(); + int err = _sync(); if (err) { - return BD_ERROR_NO_DEVICE; + return BD_ERROR_DEVICE_ERROR; } // Check JEDEC serial flash discoverable parameters for device @@ -128,7 +128,7 @@ bd_error_t SPIFBlockDevice::init() return 0; } -bd_error_t SPIFBlockDevice::deinit() +int SPIFBlockDevice::deinit() { // Latch write disable just to keep noise // from changing the device @@ -209,7 +209,7 @@ void SPIFBlockDevice::_cmdwrite( } } -bd_error_t SPIFBlockDevice::_sync() +int SPIFBlockDevice::_sync() { for (int i = 0; i < SPIF_TIMEOUT; i++) { // Read status register until write not-in-progress @@ -227,7 +227,7 @@ bd_error_t SPIFBlockDevice::_sync() return BD_ERROR_DEVICE_ERROR; } -bd_error_t SPIFBlockDevice::_wren() +int SPIFBlockDevice::_wren() { _cmdwrite(SPIF_WREN, 0, 0, 0x0, NULL); @@ -247,26 +247,22 @@ bd_error_t SPIFBlockDevice::_wren() return BD_ERROR_DEVICE_ERROR; } -bd_error_t SPIFBlockDevice::read(void *buffer, bd_addr_t addr, bd_size_t size) +int SPIFBlockDevice::read(void *buffer, bd_addr_t addr, bd_size_t size) { // Check the address and size fit onto the chip. - if (!is_valid_read(addr, size)) { - return BD_ERROR_PARAMETER; - } + MBED_ASSERT(is_valid_read(addr, size)); _cmdread(SPIF_READ, 3, size, addr, static_cast(buffer)); return 0; } -bd_error_t SPIFBlockDevice::program(const void *buffer, bd_addr_t addr, bd_size_t size) +int SPIFBlockDevice::program(const void *buffer, bd_addr_t addr, bd_size_t size) { // Check the address and size fit onto the chip. - if (!is_valid_program(addr, size)) { - return BD_ERROR_PARAMETER; - } + MBED_ASSERT(is_valid_program(addr, size)); while (size > 0) { - bd_error_t err = _wren(); + int err = _wren(); if (err) { return err; } @@ -291,15 +287,13 @@ bd_error_t SPIFBlockDevice::program(const void *buffer, bd_addr_t addr, bd_size_ return 0; } -bd_error_t SPIFBlockDevice::erase(bd_addr_t addr, bd_size_t size) +int SPIFBlockDevice::erase(bd_addr_t addr, bd_size_t size) { // Check the address and size fit onto the chip. - if (!is_valid_erase(addr, size)) { - return BD_ERROR_PARAMETER; - } + MBED_ASSERT(is_valid_erase(addr, size)); while (size > 0) { - bd_error_t err = _wren(); + int err = _wren(); if (err) { return err; } @@ -320,22 +314,22 @@ bd_error_t SPIFBlockDevice::erase(bd_addr_t addr, bd_size_t size) return 0; } -bd_size_t SPIFBlockDevice::get_read_size() +bd_size_t SPIFBlockDevice::get_read_size() const { return SPIF_READ_SIZE; } -bd_size_t SPIFBlockDevice::get_program_size() +bd_size_t SPIFBlockDevice::get_program_size() const { return SPIF_PROG_SIZE; } -bd_size_t SPIFBlockDevice::get_erase_size() +bd_size_t SPIFBlockDevice::get_erase_size() const { return SPIF_SE_SIZE; } -bd_size_t SPIFBlockDevice::size() +bd_size_t SPIFBlockDevice::size() const { return _size; } diff --git a/SPIFBlockDevice.h b/SPIFBlockDevice.h index 2093230d6d..b9d0f7ef05 100644 --- a/SPIFBlockDevice.h +++ b/SPIFBlockDevice.h @@ -16,9 +16,6 @@ #ifndef MBED_SPIF_BLOCK_DEVICE_H #define MBED_SPIF_BLOCK_DEVICE_H -/* If the target has no SPI support then SPIF is not supported */ -#ifdef DEVICE_SPI - #include #include "BlockDevice.h" @@ -67,13 +64,13 @@ public: * * @return 0 on success or a negative error code on failure */ - virtual bd_error_t init(); + virtual int init(); /** Deinitialize a block device * * @return 0 on success or a negative error code on failure */ - virtual bd_error_t deinit(); + virtual int deinit(); /** Read blocks from a block device * @@ -82,7 +79,7 @@ public: * @param size Size to read in bytes, must be a multiple of read block size * @return 0 on success, negative error code on failure */ - virtual bd_error_t read(void *buffer, bd_addr_t addr, bd_size_t size); + virtual int read(void *buffer, bd_addr_t addr, bd_size_t size); /** Program blocks to a block device * @@ -93,7 +90,7 @@ public: * @param size Size to write in bytes, must be a multiple of program block size * @return 0 on success, negative error code on failure */ - virtual bd_error_t program(const void *buffer, bd_addr_t addr, bd_size_t size); + virtual int program(const void *buffer, bd_addr_t addr, bd_size_t size); /** Erase blocks on a block device * @@ -103,33 +100,33 @@ public: * @param size Size to erase in bytes, must be a multiple of erase block size * @return 0 on success, negative error code on failure */ - virtual bd_error_t erase(bd_addr_t addr, bd_size_t size); + virtual int erase(bd_addr_t addr, bd_size_t size); /** Get the size of a readable block * * @return Size of a readable block in bytes */ - virtual bd_size_t get_read_size(); + virtual bd_size_t get_read_size() const; /** Get the size of a programable block * * @return Size of a programable block in bytes * @note Must be a multiple of the read size */ - virtual bd_size_t get_program_size(); + virtual bd_size_t get_program_size() const; /** Get the size of a eraseable block * * @return Size of a eraseable block in bytes * @note Must be a multiple of the program size */ - virtual bd_size_t get_erase_size(); + virtual bd_size_t get_erase_size() const; /** Get the total size of the underlying device * * @return Size of the underlying device in bytes */ - virtual bd_size_t size(); + virtual bd_size_t size() const; private: // Master side hardware @@ -140,8 +137,8 @@ private: bd_size_t _size; // Internal functions - bd_error_t _wren(); - bd_error_t _sync(); + int _wren(); + int _sync(); void _cmdread(uint8_t op, uint32_t addrc, uint32_t retc, uint32_t addr, uint8_t *rets); void _cmdwrite(uint8_t op, uint32_t addrc, uint32_t argc, @@ -149,6 +146,4 @@ private: }; -#endif /* DEVICE_SPI */ - #endif /* MBED_SPIF_BLOCK_DEVICE_H */ diff --git a/TESTS/block_device/spif/main.cpp b/TESTS/block_device/spif/main.cpp index 8fb231cb95..4dc97562e4 100644 --- a/TESTS/block_device/spif/main.cpp +++ b/TESTS/block_device/spif/main.cpp @@ -8,14 +8,6 @@ using namespace utest::v1; -#ifndef SPIF_INSTALLED -#define SPIF_INSTALLED defined(TARGET_K82F) -#endif - -#if !SPIF_INSTALLED -#error [NOT_SUPPORTED] SPIF Required -#endif - #if defined(TARGET_K82F) #define TEST_PINS PTE2, PTE4, PTE1, PTE5 #define TEST_FREQ 40000000 @@ -29,7 +21,7 @@ using namespace utest::v1; const struct { const char *name; - bd_size_t (BlockDevice::*method)(); + bd_size_t (BlockDevice::*method)() const; } ATTRS[] = { {"read size", &BlockDevice::get_read_size}, {"program size", &BlockDevice::get_program_size}, @@ -60,7 +52,7 @@ void test_read_write() { uint8_t *write_block = new uint8_t[block_size]; uint8_t *read_block = new uint8_t[block_size]; uint8_t *error_mask = new uint8_t[TEST_ERROR_MASK]; - unsigned addrwidth = ceil(log(bd.size()-1) / log(16))+1; + unsigned addrwidth = ceil(log(float(bd.size()-1)) / log(float(16)))+1; for (int b = 0; b < TEST_BLOCK_COUNT; b++) { // Find a random block @@ -79,7 +71,10 @@ void test_read_write() { // Write, sync, and read the block printf("test %0*llx:%llu...\n", addrwidth, block, block_size); - err = bd.write(write_block, block, block_size); + err = bd.erase(block, block_size); + TEST_ASSERT_EQUAL(0, err); + + err = bd.program(write_block, block, block_size); TEST_ASSERT_EQUAL(0, err); printf("write %0*llx:%llu ", addrwidth, block, block_size); From 8ef4d3d9f2cbfbfd5c3efd1980220b917080e2f5 Mon Sep 17 00:00:00 2001 From: canhkha Date: Sun, 12 Mar 2017 06:33:05 +0700 Subject: [PATCH 03/29] Update SPIFBlockDevice.h Fix default spi speed to 40mhz --- SPIFBlockDevice.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SPIFBlockDevice.h b/SPIFBlockDevice.h index b9d0f7ef05..a443da02a5 100644 --- a/SPIFBlockDevice.h +++ b/SPIFBlockDevice.h @@ -58,7 +58,7 @@ public: * @param csel SPI chip select pin * @param freq Clock speed of the SPI bus (defaults to 40MHz) */ - SPIFBlockDevice(PinName mosi, PinName miso, PinName sclk, PinName csel, int freq=4000000); + SPIFBlockDevice(PinName mosi, PinName miso, PinName sclk, PinName csel, int freq=40000000); /** Initialize a block device * From cc15f37141ee238c3dc749554b5b6cb8d3a9afd7 Mon Sep 17 00:00:00 2001 From: Christopher Haster Date: Sun, 16 Jul 2017 13:01:58 -0500 Subject: [PATCH 04/29] Renamed LICENSE -> LICENSE.md --- LICENSE => LICENSE.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename LICENSE => LICENSE.md (100%) diff --git a/LICENSE b/LICENSE.md similarity index 100% rename from LICENSE rename to LICENSE.md From c46b2a762d03874eb712250c7849759f9b13a093 Mon Sep 17 00:00:00 2001 From: Christopher Haster Date: Sun, 16 Jul 2017 13:21:14 -0500 Subject: [PATCH 05/29] Added support for Travis CI --- .travis.yml | 28 ++++++++++++++++++++++++++++ README.md | 2 +- SPIFBlockDevice.h | 42 +++++++++++++++++++++++++----------------- 3 files changed, 54 insertions(+), 18 deletions(-) create mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000000..bc3c5de502 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,28 @@ +script: + # Check that examples compile + - sed -n '/``` cpp/,${/```$/q;/```/d;p}' README.md > main.cpp && + PYTHONPATH=mbed-os python mbed-os/tools/make.py -t GCC_ARM -m K82F + --source=. --build=BUILD/K82F/GCC_ARM -j0 && + rm main.cpp + - sed -n '/@code/,${/@endcode/q;/@/d;s/^ \*//;p}' SPIFBlockDevice.h > main.cpp && + PYTHONPATH=mbed-os python mbed-os/tools/make.py -t GCC_ARM -m K82F + --source=. --build=BUILD/K82F/GCC_ARM -j0 && + rm main.cpp + + # Check that tests compile + - rm -r BUILD && PYTHONPATH=mbed-os python mbed-os/tools/test.py + -t GCC_ARM -m K82F --source=. --build=BUILD/TESTS/K82F/GCC_ARM -j0 + -n tests* + +python: + - "2.7" + +install: + # Get arm-none-eabi-gcc + - sudo add-apt-repository -y ppa:terry.guo/gcc-arm-embedded + - sudo apt-get update -qq + - sudo apt-get install -qq gcc-arm-none-eabi --force-yes + # Get dependencies + - git clone https://github.com/armmbed/mbed-os.git + # Install python dependencies + - sudo pip install -r mbed-os/requirements.txt diff --git a/README.md b/README.md index 7f7113fa3a..1f9c3ae41b 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ int main() { printf("spif erase size: %llu\n", spif.get_erase_size()); // Write "Hello World!" to the first block - uint8_t *buffer = malloc(spif.get_erase_size()); + char *buffer = (char*)malloc(spif.get_erase_size()); sprintf(buffer, "Hello World!\n"); spif.erase(0, spif.get_erase_size()); spif.program(buffer, 0, spif.get_erase_size()); diff --git a/SPIFBlockDevice.h b/SPIFBlockDevice.h index a443da02a5..c4ee447e2f 100644 --- a/SPIFBlockDevice.h +++ b/SPIFBlockDevice.h @@ -24,29 +24,37 @@ * such as the MX25R or SST26F016B * * @code + * // Here's an example using the MX25R SPI flash device on the K82F * #include "mbed.h" * #include "SPIFBlockDevice.h" - * - * // Create mx25r on SPI bus with PTE5 as chip select - * SPIFBlockDevice mx25r(PTE2, PTE4, PTE1, PTE5); - * + * + * // Create flash device on SPI bus with PTE5 as chip select + * SPIFBlockDevice spif(PTE2, PTE4, PTE1, PTE5); + * * int main() { - * printf("mx25r test\n"); - * mx52r.init(); - * printf("mx25r size: %llu\n", mx25r.size()); - * printf("mx25r read size: %llu\n", mx25r.get_read_size()); - * printf("mx25r program size: %llu\n", mx25r.get_program_size()); - * printf("mx25r erase size: %llu\n", mx25r.get_erase_size()); - * - * uint8_t *buffer = malloc(mx25r.get_erase_size()); + * printf("spif test\n"); + * + * // Initialize the SPI flash device and print the memory layout + * spif.init(); + * printf("spif size: %llu\n", spif.size()); + * printf("spif read size: %llu\n", spif.get_read_size()); + * printf("spif program size: %llu\n", spif.get_program_size()); + * printf("spif erase size: %llu\n", spif.get_erase_size()); + * + * // Write "Hello World!" to the first block + * char *buffer = (char*)malloc(spif.get_erase_size()); * sprintf(buffer, "Hello World!\n"); - * mx25r.erase(0, mx25r.get_erase_size()); - * mx25r.program(buffer, 0, mx25r.get_erase_size()); - * mx25r.read(buffer, 0, mx25r.get_erase_size()); + * spif.erase(0, spif.get_erase_size()); + * spif.program(buffer, 0, spif.get_erase_size()); + * + * // Read back what was stored + * spif.read(buffer, 0, spif.get_erase_size()); * printf("%s", buffer); - * - * mx25r.deinit(); + * + * // Deinitialize the device + * spif.deinit(); * } + * @endcode */ class SPIFBlockDevice : public BlockDevice { public: From 27042d8871d3224efd81dc54f7b5c047081d5a63 Mon Sep 17 00:00:00 2001 From: Marcus Chang Date: Wed, 1 Nov 2017 07:58:56 -0700 Subject: [PATCH 06/29] Add default pin macro names and default pins on select set of boards --- mbed_lib.json | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 mbed_lib.json diff --git a/mbed_lib.json b/mbed_lib.json new file mode 100644 index 0000000000..51442badba --- /dev/null +++ b/mbed_lib.json @@ -0,0 +1,24 @@ +{ + "name": "spif-driver", + "config": { + "SPI_MOSI": "NC", + "SPI_MISO": "NC", + "SPI_CLK": "NC", + "SPI_CS": "NC" + }, + "target_overrides": { + "K82F": { + "SPI_MOSI": "PTE3", + "SPI_MISO": "PTE4", + "SPI_CLK": "PTE1", + "SPI_CS": "PTE5" + }, + "LPC54114": { + "SPI_MOSI": "P0_20", + "SPI_MISO": "P0_18", + "SPI_CLK": "P0_19", + "SPI_CS": "P1_2" + } + } +} + From a69ca3757e9355e0648f2afcb378fe696399912a Mon Sep 17 00:00:00 2001 From: Christopher Haster Date: Fri, 15 Dec 2017 17:20:49 -0600 Subject: [PATCH 07/29] Fixed pin definition for K82F --- mbed_lib.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mbed_lib.json b/mbed_lib.json index 51442badba..4b4f15da3f 100644 --- a/mbed_lib.json +++ b/mbed_lib.json @@ -8,7 +8,7 @@ }, "target_overrides": { "K82F": { - "SPI_MOSI": "PTE3", + "SPI_MOSI": "PTE2", "SPI_MISO": "PTE4", "SPI_CLK": "PTE1", "SPI_CS": "PTE5" From 616c97708cc69251c7b1d8ca2f54aa9e8ca5847b Mon Sep 17 00:00:00 2001 From: Kevin Gilbert Date: Fri, 15 Dec 2017 17:36:07 -0600 Subject: [PATCH 08/29] Add NRF52840_DK SPIF pins --- mbed_lib.json | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/mbed_lib.json b/mbed_lib.json index 51442badba..307cfa8e8c 100644 --- a/mbed_lib.json +++ b/mbed_lib.json @@ -18,6 +18,12 @@ "SPI_MISO": "P0_18", "SPI_CLK": "P0_19", "SPI_CS": "P1_2" + }, + "NRF52840_DK": { + "SPI_MOSI": "p20", + "SPI_MISO": "p21", + "SPI_CLK": "p19", + "SPI_CS": "p17" } } } From 6d8dc65b3fafeb365b20f9ee72d5cdba4a308422 Mon Sep 17 00:00:00 2001 From: maclobdell Date: Mon, 5 Mar 2018 11:23:13 -0600 Subject: [PATCH 09/29] add support for hexiwear spi flash --- mbed_lib.json | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/mbed_lib.json b/mbed_lib.json index ec0269146f..4e9204ad16 100644 --- a/mbed_lib.json +++ b/mbed_lib.json @@ -24,6 +24,12 @@ "SPI_MISO": "p21", "SPI_CLK": "p19", "SPI_CS": "p17" + }, + "HEXIWEAR": { + "SPI_MOSI": "PTD6", + "SPI_MISO": "PTD7", + "SPI_CLK": "PTD5", + "SPI_CS": "PTD4" } } } From d46ad652cc7c109527fa0f15374d0e6596c829da Mon Sep 17 00:00:00 2001 From: David Saada Date: Thu, 12 Apr 2018 21:35:00 +0300 Subject: [PATCH 10/29] Implement the get_erase_value function --- SPIFBlockDevice.cpp | 5 +++++ SPIFBlockDevice.h | 11 +++++++++++ 2 files changed, 16 insertions(+) diff --git a/SPIFBlockDevice.cpp b/SPIFBlockDevice.cpp index 12308d09e9..64bf16e83c 100644 --- a/SPIFBlockDevice.cpp +++ b/SPIFBlockDevice.cpp @@ -333,3 +333,8 @@ bd_size_t SPIFBlockDevice::size() const { return _size; } + +int SPIFBlockDevice::get_erase_value() const +{ + return 0xFF; +} diff --git a/SPIFBlockDevice.h b/SPIFBlockDevice.h index c4ee447e2f..811a9f81bb 100644 --- a/SPIFBlockDevice.h +++ b/SPIFBlockDevice.h @@ -130,6 +130,17 @@ public: */ virtual bd_size_t get_erase_size() const; + /** Get the value of storage when erased + * + * If get_erase_value returns a non-negative byte value, the underlying + * storage is set to that value when erased, and storage containing + * that value can be programmed without another erase. + * + * @return The value of storage when erased, or -1 if you can't + * rely on the value of erased storage + */ + virtual int get_erase_value() const; + /** Get the total size of the underlying device * * @return Size of the underlying device in bytes From 210674e22e11a2de8517903ec3b4b9629e95e406 Mon Sep 17 00:00:00 2001 From: Netanel Gonen Date: Tue, 27 Mar 2018 16:26:23 +0300 Subject: [PATCH 11/29] Add odin module target to json file --- mbed_lib.json | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/mbed_lib.json b/mbed_lib.json index 4e9204ad16..930a7cdd8a 100644 --- a/mbed_lib.json +++ b/mbed_lib.json @@ -30,6 +30,12 @@ "SPI_MISO": "PTD7", "SPI_CLK": "PTD5", "SPI_CS": "PTD4" + }, + "MTB_UBLOX_ODIN_W2": { + "SPI_MOSI": "PE_14", + "SPI_MISO": "PE_13", + "SPI_CLK": "PE_12", + "SPI_CS": "PE_11" } } } From b92b57bc08309fa06ff9d14ae27c418a61e53788 Mon Sep 17 00:00:00 2001 From: Alon Nof Date: Tue, 24 Apr 2018 14:58:43 +0300 Subject: [PATCH 12/29] add support for new modules add support for: MTB_ADV_WISE_1530 MTB_MXCHIP_EMW3166 MTB_USI_WM_BN_BM_22 --- mbed_lib.json | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/mbed_lib.json b/mbed_lib.json index 930a7cdd8a..db97bae54a 100644 --- a/mbed_lib.json +++ b/mbed_lib.json @@ -36,7 +36,23 @@ "SPI_MISO": "PE_13", "SPI_CLK": "PE_12", "SPI_CS": "PE_11" - } - } + }, + "MTB_ADV_WISE_1530": { + "SPI_MOSI": "PC_3", + "SPI_MISO": "PC_2", + "SPI_CLK": "PB_13", + "SPI_CS": "PC_12" + }, + "MTB_MXCHIP_EMW3166": { + "SPI_MOSI": "PB_15", + "SPI_MISO": "PB_14", + "SPI_CLK": "PB_13", + "SPI_CS": "PA_10" + }, + "MTB_USI_WM_BN_BM_22": { + "SPI_MOSI": "PC_3", + "SPI_MISO": "PC_2", + "SPI_CLK": "PB_13", + "SPI_CS": "PA_6" + } } - From 61792dfe71d9f4659b4a28c612df43096367a153 Mon Sep 17 00:00:00 2001 From: Alonof Date: Tue, 24 Apr 2018 15:15:53 +0300 Subject: [PATCH 13/29] update comma --- mbed_lib.json | 31 ++++++++++++++++--------------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/mbed_lib.json b/mbed_lib.json index db97bae54a..ff91c86d2a 100644 --- a/mbed_lib.json +++ b/mbed_lib.json @@ -37,22 +37,23 @@ "SPI_CLK": "PE_12", "SPI_CS": "PE_11" }, - "MTB_ADV_WISE_1530": { - "SPI_MOSI": "PC_3", - "SPI_MISO": "PC_2", - "SPI_CLK": "PB_13", - "SPI_CS": "PC_12" + "MTB_ADV_WISE_1530": { + "SPI_MOSI": "PC_3", + "SPI_MISO": "PC_2", + "SPI_CLK": "PB_13", + "SPI_CS": "PC_12" }, - "MTB_MXCHIP_EMW3166": { - "SPI_MOSI": "PB_15", - "SPI_MISO": "PB_14", - "SPI_CLK": "PB_13", - "SPI_CS": "PA_10" + "MTB_MXCHIP_EMW3166": { + "SPI_MOSI": "PB_15", + "SPI_MISO": "PB_14", + "SPI_CLK": "PB_13", + "SPI_CS": "PA_10" }, - "MTB_USI_WM_BN_BM_22": { - "SPI_MOSI": "PC_3", - "SPI_MISO": "PC_2", - "SPI_CLK": "PB_13", - "SPI_CS": "PA_6" + "MTB_USI_WM_BN_BM_22": { + "SPI_MOSI": "PC_3", + "SPI_MISO": "PC_2", + "SPI_CLK": "PB_13", + "SPI_CS": "PA_6" } + } } From 58d6ffba2e06dd2500026eca30dfef06495e0a09 Mon Sep 17 00:00:00 2001 From: Juho Eskeli Date: Mon, 18 Jun 2018 15:56:13 +0300 Subject: [PATCH 14/29] add mtb_adv_wise_1570 --- mbed_lib.json | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/mbed_lib.json b/mbed_lib.json index ff91c86d2a..890f0c7e20 100644 --- a/mbed_lib.json +++ b/mbed_lib.json @@ -54,6 +54,12 @@ "SPI_MISO": "PC_2", "SPI_CLK": "PB_13", "SPI_CS": "PA_6" + }, + "MTB_ADV_WISE_1570": { + "SPI_MOSI": "PA_7", + "SPI_MISO": "PA_6", + "SPI_CLK": "PA_5", + "SPI_CS": "PB_12" } } } From 4ca2c9ff3b99942d9a3fc0d5b3603494db61b61c Mon Sep 17 00:00:00 2001 From: Juho Eskeli Date: Wed, 20 Jun 2018 14:25:34 +0300 Subject: [PATCH 15/29] Option to specify SPI frequency --- mbed_lib.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/mbed_lib.json b/mbed_lib.json index 890f0c7e20..4c08223703 100644 --- a/mbed_lib.json +++ b/mbed_lib.json @@ -4,7 +4,8 @@ "SPI_MOSI": "NC", "SPI_MISO": "NC", "SPI_CLK": "NC", - "SPI_CS": "NC" + "SPI_CS": "NC", + "SPI_FREQ": "40000000" }, "target_overrides": { "K82F": { From dce716d6d402e9d5b29aa9faf25738aa78c8fde1 Mon Sep 17 00:00:00 2001 From: David Saada Date: Wed, 4 Jul 2018 16:36:11 +0300 Subject: [PATCH 16/29] Implement the get_erase_size API (based on address) --- SPIFBlockDevice.cpp | 5 +++++ SPIFBlockDevice.h | 8 ++++++++ 2 files changed, 13 insertions(+) diff --git a/SPIFBlockDevice.cpp b/SPIFBlockDevice.cpp index 64bf16e83c..e2a0a9e11d 100644 --- a/SPIFBlockDevice.cpp +++ b/SPIFBlockDevice.cpp @@ -329,6 +329,11 @@ bd_size_t SPIFBlockDevice::get_erase_size() const return SPIF_SE_SIZE; } +bd_size_t SPIFBlockDevice::get_erase_size(bd_addr_t addr) const +{ + return SPIF_SE_SIZE; +} + bd_size_t SPIFBlockDevice::size() const { return _size; diff --git a/SPIFBlockDevice.h b/SPIFBlockDevice.h index 811a9f81bb..853d0c5796 100644 --- a/SPIFBlockDevice.h +++ b/SPIFBlockDevice.h @@ -130,6 +130,14 @@ public: */ virtual bd_size_t get_erase_size() const; + /** Get the size of an erasable block given address + * + * @param addr Address within the erasable block + * @return Size of an erasable block in bytes + * @note Must be a multiple of the program size + */ + virtual bd_size_t get_erase_size(bd_addr_t addr) const; + /** Get the value of storage when erased * * If get_erase_value returns a non-negative byte value, the underlying From d04c8e31412d3505d54a860958d9da52f07c312e Mon Sep 17 00:00:00 2001 From: David Saada Date: Thu, 2 Aug 2018 19:07:16 +0300 Subject: [PATCH 17/29] Add some logic related to initialization: - Add an initialization flag on which read/program/erase actions depend. - Add an init reference count. --- SPIFBlockDevice.cpp | 43 +++++++++++++++++++++++++++++++++++++++++-- SPIFBlockDevice.h | 3 +++ 2 files changed, 44 insertions(+), 2 deletions(-) diff --git a/SPIFBlockDevice.cpp b/SPIFBlockDevice.cpp index e2a0a9e11d..329e0a5806 100644 --- a/SPIFBlockDevice.cpp +++ b/SPIFBlockDevice.cpp @@ -15,7 +15,7 @@ */ #include "SPIFBlockDevice.h" - +#include "mbed_critical.h" // Read/write/erase sizes #define SPIF_READ_SIZE 1 @@ -49,7 +49,7 @@ enum ops { SPIFBlockDevice::SPIFBlockDevice( PinName mosi, PinName miso, PinName sclk, PinName cs, int freq) - : _spi(mosi, miso, sclk), _cs(cs), _size(0) + : _spi(mosi, miso, sclk), _cs(cs), _size(0), _is_initialized(false), _init_ref_count(0) { _cs = 1; _spi.frequency(freq); @@ -57,6 +57,16 @@ SPIFBlockDevice::SPIFBlockDevice( int SPIFBlockDevice::init() { + if (!_is_initialized) { + _init_ref_count = 0; + } + + uint32_t val = core_util_atomic_incr_u32(&_init_ref_count, 1); + + if (val != 1) { + return BD_ERROR_OK; + } + // Check for vendor specific hacks, these should move into more general // handling when possible. RDID is not used to verify a device is attached. uint8_t id[3]; @@ -125,15 +135,28 @@ int SPIFBlockDevice::init() (table[4] << 0 )); _size = (density/8) + 1; + _is_initialized = true; return 0; } int SPIFBlockDevice::deinit() { + if (!_is_initialized) { + _init_ref_count = 0; + return 0; + } + + uint32_t val = core_util_atomic_decr_u32(&_init_ref_count, 1); + + if (val) { + return 0; + } + // Latch write disable just to keep noise // from changing the device _cmdwrite(SPIF_WRDI, 0, 0, 0x0, NULL); + _is_initialized = false; return 0; } @@ -249,6 +272,10 @@ int SPIFBlockDevice::_wren() int SPIFBlockDevice::read(void *buffer, bd_addr_t addr, bd_size_t size) { + if (!_is_initialized) { + return BD_ERROR_DEVICE_ERROR; + } + // Check the address and size fit onto the chip. MBED_ASSERT(is_valid_read(addr, size)); @@ -261,6 +288,10 @@ int SPIFBlockDevice::program(const void *buffer, bd_addr_t addr, bd_size_t size) // Check the address and size fit onto the chip. MBED_ASSERT(is_valid_program(addr, size)); + if (!_is_initialized) { + return BD_ERROR_DEVICE_ERROR; + } + while (size > 0) { int err = _wren(); if (err) { @@ -292,6 +323,10 @@ int SPIFBlockDevice::erase(bd_addr_t addr, bd_size_t size) // Check the address and size fit onto the chip. MBED_ASSERT(is_valid_erase(addr, size)); + if (!_is_initialized) { + return BD_ERROR_DEVICE_ERROR; + } + while (size > 0) { int err = _wren(); if (err) { @@ -336,6 +371,10 @@ bd_size_t SPIFBlockDevice::get_erase_size(bd_addr_t addr) const bd_size_t SPIFBlockDevice::size() const { + if (!_is_initialized) { + return BD_ERROR_DEVICE_ERROR; + } + return _size; } diff --git a/SPIFBlockDevice.h b/SPIFBlockDevice.h index 853d0c5796..fceef50f2a 100644 --- a/SPIFBlockDevice.h +++ b/SPIFBlockDevice.h @@ -163,6 +163,9 @@ private: // Device configuration discovered through sfdp bd_size_t _size; + bool _is_initialized; + uint32_t _init_ref_count; + // Internal functions int _wren(); int _sync(); From a96b528987965664b9f5b641b0598a83dcbe027f Mon Sep 17 00:00:00 2001 From: Offir Kochalsky Date: Thu, 9 Aug 2018 11:50:43 +0300 Subject: [PATCH 18/29] removed mbed.h from h file --- SPIFBlockDevice.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SPIFBlockDevice.h b/SPIFBlockDevice.h index fceef50f2a..2cce398d81 100644 --- a/SPIFBlockDevice.h +++ b/SPIFBlockDevice.h @@ -16,7 +16,7 @@ #ifndef MBED_SPIF_BLOCK_DEVICE_H #define MBED_SPIF_BLOCK_DEVICE_H -#include +#include #include "BlockDevice.h" From 5a52620172f13f89cb7bc95eca00d8acf71d296f Mon Sep 17 00:00:00 2001 From: Offir Kochalsky Date: Thu, 9 Aug 2018 18:50:55 +0300 Subject: [PATCH 19/29] Initial changes save --- SPIFBlockDevice.cpp | 476 +++++++++++++++++++++++++++++++++++--------- SPIFBlockDevice.h | 119 ++++++++++- 2 files changed, 490 insertions(+), 105 deletions(-) diff --git a/SPIFBlockDevice.cpp b/SPIFBlockDevice.cpp index 329e0a5806..057deb120d 100644 --- a/SPIFBlockDevice.cpp +++ b/SPIFBlockDevice.cpp @@ -53,10 +53,108 @@ SPIFBlockDevice::SPIFBlockDevice( { _cs = 1; _spi.frequency(freq); + _address_size = QSPI_CFG_ADDR_SIZE_24; + // Initial SFDP read tables are read with 8 dummy cycles + _read_dummy_and_mode_cycles = 8; + _dummy_and_mode_cycles = 8; + } int SPIFBlockDevice::init() { + + uint8_t vendor_device_ids[4]; + size_t data_length = 3; + int status = SPIF_BD_ERROR_OK; + uint32_t basic_table_addr = NULL; + size_t basic_table_size = 0; + uint32_t sector_map_table_addr = NULL; + size_t sector_map_table_size = 0; + int qspi_status = QSPI_STATUS_OK; + + _mutex.lock(); + if (_is_initialized == true) { + goto exit_point; + } + + // Soft Reset + /* + if ( -1 == _reset_flash_mem()) { + tr_error("ERROR: init - Unable to initialize flash memory, tests failed\n"); + status = QSPIF_BD_ERROR_DEVICE_ERROR; + goto exit_point; + } else { + tr_info("INFO: Initialize flash memory OK\n"); + } + */ + + /* Read Manufacturer ID (1byte), and Device ID (2bytes)*/ + qspi_status = _qspi_send_read_command(QSPIF_RDID, (char *)vendor_device_ids, 0x0 /*address*/, data_length); + if (qspi_status != QSPI_STATUS_OK) { + tr_error("ERROR: init - Read Vendor ID Failed"); + status = QSPIF_BD_ERROR_DEVICE_ERROR; + goto exit_point; + } + + switch (vendor_device_ids[0]) { + case 0xbf: + // SST devices come preset with block protection + // enabled for some regions, issue write disable instruction to clear + _set_write_enable(); + _qspi_send_general_command(QSPIF_WRDI, -1, NULL, 0, NULL, 0); + break; + } + + //Synchronize Device + if ( false == _is_mem_ready()) { + tr_error("ERROR: init - _is_mem_ready Failed"); + status = QSPIF_BD_ERROR_READY_FAILED; + goto exit_point; + } + + /**************************** Parse SFDP Header ***********************************/ + if ( 0 != _sfdp_parse_sfdp_headers(basic_table_addr, basic_table_size, sector_map_table_addr, sector_map_table_size)) { + tr_error("ERROR: init - Parse SFDP Headers Failed"); + status = QSPIF_BD_ERROR_PARSING_FAILED; + goto exit_point; + } + + + /**************************** Parse Basic Parameters Table ***********************************/ + if ( 0 != _sfdp_parse_basic_param_table(basic_table_addr, basic_table_size) ) { + tr_error("ERROR: init - Parse Basic Param Table Failed"); + status = QSPIF_BD_ERROR_PARSING_FAILED; + goto exit_point; + } + + /**************************** Parse Sector Map Table ***********************************/ + _region_size_bytes[0] = + _device_size_bytes; // If there's no region map, we have a single region sized the entire device size + _region_high_boundary[0] = _device_size_bytes - 1; + + if ( (sector_map_table_addr != NULL) && (0 != sector_map_table_size) ) { + tr_info("INFO: init - Parsing Sector Map Table - addr: 0x%xh, Size: %d", sector_map_table_addr, + sector_map_table_size); + if (0 != _sfdp_parse_sector_map_table(sector_map_table_addr, sector_map_table_size) ) { + tr_error("ERROR: init - Parse Sector Map Table Failed"); + status = QSPIF_BD_ERROR_PARSING_FAILED; + goto exit_point; + } + } + + // Configure BUS Mode to 1_1_1 for all commands other than Read + _qspi_configure_format(QSPI_CFG_BUS_SINGLE, QSPI_CFG_BUS_SINGLE, QSPI_CFG_ADDR_SIZE_24, QSPI_CFG_BUS_SINGLE, + QSPI_CFG_ALT_SIZE_8, QSPI_CFG_BUS_SINGLE, 0); + + _is_initialized = true; + +exit_point: + _mutex.unlock(); + + return status; + + +/**************************************************************************************************************/ if (!_is_initialized) { _init_ref_count = 0; } @@ -67,6 +165,9 @@ int SPIFBlockDevice::init() return BD_ERROR_OK; } + // Initial SFDP read tables are read with 8 dummy cycles + _read_dummy_and_mode_cycles = 8; + // Check for vendor specific hacks, these should move into more general // handling when possible. RDID is not used to verify a device is attached. uint8_t id[3]; @@ -160,76 +261,64 @@ int SPIFBlockDevice::deinit() return 0; } -void SPIFBlockDevice::_cmdread( - uint8_t op, uint32_t addrc, uint32_t retc, - uint32_t addr, uint8_t *rets) + + +void SPIFBlockDevice::_cmdread(uint8_t inst, uint32_t addr, uint32_t data_size, uint8_t *data) { _cs = 0; - _spi.write(op); + uint32_t dummy_bytes = _dummy_and_mode_cycles / 8; + uint8_t dummy_byte = 0x00; + uint8_t *addr_byte_ptr = &addr; + addr_byte_ptr += (_address_size-1) - for (uint32_t i = 0; i < addrc; i++) { - _spi.write(0xff & (addr >> 8*(addrc-1 - i))); + // Write 1 byte Instruction + _spi.write(inst); + + // Write Address (can be either 3 or 4 bytes long) + for (uint32_t i = 0; i < _address_size; i++) { + _spi.write(*addr_byte_ptr); + addr_byte_ptr--; } - for (uint32_t i = 0; i < retc; i++) { - rets[i] = _spi.write(0); + // Write Dummy Cycles Bytes + for (uint32_t i = 0; i < dummy_bytes; i++) { + _spi.write(dummy_byte); + } + + // Read Data + for (uint32_t i = 0; i < data_size; i++) { + data[i] = _spi.write(0); } _cs = 1; - - if (SPIF_DEBUG) { - printf("spif <- %02x", op); - for (uint32_t i = 0; i < addrc; i++) { - if (i < addrc) { - printf("%02lx", 0xff & (addr >> 8*(addrc-1 - i))); - } else { - printf(" "); - } - } - printf(" "); - for (uint32_t i = 0; i < 16 && i < retc; i++) { - printf("%02x", rets[i]); - } - if (retc > 16) { - printf("..."); - } - printf("\n"); - } } -void SPIFBlockDevice::_cmdwrite( - uint8_t op, uint32_t addrc, uint32_t argc, - uint32_t addr, const uint8_t *args) +void SPIFBlockDevice::_cmdwrite(uint8_t inst, uint32_t addr, uint32_t data_size, const uint8_t *data) { _cs = 0; - _spi.write(op); + uint32_t dummy_bytes = _dummy_and_mode_cycles / 8; + uint8_t dummy_byte = 0x00; + uint8_t *addr_byte_ptr = &addr; + addr_byte_ptr += (_address_size-1) - for (uint32_t i = 0; i < addrc; i++) { - _spi.write(0xff & (addr >> 8*(addrc-1 - i))); + // Write 1 byte Instruction + _spi.write(inst); + + // Write Address (can be either 3 or 4 bytes long) + for (uint32_t i = 0; i < _address_size; i++) { + _spi.write(*addr_byte_ptr); + addr_byte_ptr--; } - for (uint32_t i = 0; i < argc; i++) { - _spi.write(args[i]); + // Write Dummy Cycles Bytes + for (uint32_t i = 0; i < dummy_bytes; i++) { + _spi.write(dummy_byte); + } + + // Write Data + for (uint32_t i = 0; i < data_size; i++) { + _spi.write(data[i]); } _cs = 1; - - if (SPIF_DEBUG) { - printf("spif -> %02x", op); - for (uint32_t i = 0; i < addrc; i++) { - if (i < addrc) { - printf("%02lx", 0xff & (addr >> 8*(addrc-1 - i))); - } else { - printf(" "); - } - } - printf(" "); - for (uint32_t i = 0; i < 16 && i < argc; i++) { - printf("%02x", args[i]); - } - if (argc > 16) { - printf("..."); - } - printf("\n"); - } } int SPIFBlockDevice::_sync() @@ -270,52 +359,179 @@ int SPIFBlockDevice::_wren() return BD_ERROR_DEVICE_ERROR; } + +void SPIFBlockDevice::_spi_send_read_command(uint8_t read_inst, void *buffer, bd_addr_t addr, bd_size_t size) +{ + uint32_t dummy_bytes = _dummy_and_mode_cycles / 8; + uint8_t dummy_byte = 0x00; + uint8_t *addr_byte_ptr = addr; + uint8_t *data = (uint8_t *)buffer; + addr_byte_ptr += (_address_size-1); + + // Write 1 byte Instruction + _spi.write(read_inst); + + // Write Address (can be either 3 or 4 bytes long) + for (uint32_t i = 0; i < _address_size; i++) { + _spi.write(*addr_byte_ptr); + addr_byte_ptr--; + } + + // Write Dummy Cycles Bytes + for (uint32_t i = 0; i < dummy_bytes; i++) { + _spi.write(dummy_byte); + } + + // Read Data + for (bd_size_t i = 0; i < size; i++) { + data[i] = _spi.write(0); + } + + return; +} + +void SPIFBlockDevice::_spi_send_program_command(unsigned int prog_inst, const void *buffer, bd_addr_t addr, bd_size_t size) +{ + // Send Program (write) command to device driver + uint32_t dummy_bytes = _dummy_and_mode_cycles / 8; + uint8_t dummy_byte = 0x00; + uint8_t *addr_byte_ptr = addr; + uint8_t *data = (uint8_t *)buffer; + addr_byte_ptr += (_address_size-1) + + // Write 1 byte Instruction + _spi.write(prog_inst); + + // Write Address (can be either 3 or 4 bytes long) + for (uint32_t i = 0; i < _address_size; i++) { + _spi.write(*addr_byte_ptr); + addr_byte_ptr--; + } + + // Write Dummy Cycles Bytes + for (uint32_t i = 0; i < dummy_bytes; i++) { + _spi.write(dummy_byte); + } + + // Write Data + for (bd_size_t i = 0; i < size; i++) { + _spi.write(data[i]); + } + + return; +} + +qspi_status_t SPIFBlockDevice::_spi_send_erase_command(unsigned int erase_inst, bd_addr_t addr, bd_size_t size) +{ + tr_info("INFO: Inst: 0x%xh, addr: %llu, size: %llu", erase_inst, addr, size); + _spi_send_general_command(erase_inst, addr) + return; +} + +qspi_status_t SPIFBlockDevice::_spi_send_general_command(unsigned int instruction, bd_addr_t addr) +{ + // Send a general command Instruction to driver + uint32_t dummy_bytes = _dummy_and_mode_cycles / 8; + uint8_t dummy_byte = 0x00; + uint8_t *addr_byte_ptr = (((int)addr) & 0x00FFF000); + uint8_t *data = (uint8_t *)buffer; + addr_byte_ptr += (_address_size-1) + + // Write 1 byte Instruction + _spi.write(instruction); + + // Write Address (can be either 3 or 4 bytes long) + for (uint32_t i = 0; i < _address_size; i++) { + _spi.write(*addr_byte_ptr); + addr_byte_ptr--; + } + + // Write Dummy Cycles Bytes + for (uint32_t i = 0; i < dummy_bytes; i++) { + _spi.write(dummy_byte); + } + + return; +} + + + int SPIFBlockDevice::read(void *buffer, bd_addr_t addr, bd_size_t size) { if (!_is_initialized) { return BD_ERROR_DEVICE_ERROR; } - // Check the address and size fit onto the chip. - MBED_ASSERT(is_valid_read(addr, size)); + int status = SPIF_BD_ERROR_OK; + + tr_info("INFO Inst: 0x%xh", _read_instruction); + + _mutex.lock(); + + // Set Dummy Cycles for Specific Read Command Mode + _dummy_and_mode_cycles = _read_dummy_and_mode_cycles; + + _spi_send_read_command(_read_instruction, buffer, addr, size); + + // Set Dummy Cycles for all other command modes + _dummy_and_mode_cycles = 0; + + _mutex.unlock(); + return status; - _cmdread(SPIF_READ, 3, size, addr, static_cast(buffer)); - return 0; } int SPIFBlockDevice::program(const void *buffer, bd_addr_t addr, bd_size_t size) { - // Check the address and size fit onto the chip. - MBED_ASSERT(is_valid_program(addr, size)); - if (!_is_initialized) { return BD_ERROR_DEVICE_ERROR; } - while (size > 0) { - int err = _wren(); - if (err) { - return err; - } + qspi_status_t result = QSPI_STATUS_OK; + bool program_failed = false; + int status = SPIF_BD_ERROR_OK; + uint32_t offset = 0; + uint32_t chunk = 0; - // Write up to 256 bytes a page - // TODO handle unaligned programs - uint32_t off = addr % 256; - uint32_t chunk = (off + size < 256) ? size : (256-off); - _cmdwrite(SPIF_PROG, 3, chunk, addr, static_cast(buffer)); - buffer = static_cast(buffer) + chunk; - addr += chunk; - size -= chunk; + tr_debug("DEBUG: program - Buff: 0x%x, addr: %llu, size: %llu", buffer, addr, size); - wait_ms(1); + while (size > 0) { - err = _sync(); - if (err) { - return err; - } + // Write on _page_size_bytes boundaries (Default 256 bytes a page) + offset = addr % _page_size_bytes; + chunk = (offset + size < _page_size_bytes) ? size : (_page_size_bytes - offset); + + _mutex.lock(); + + //Send WREN + if (_set_write_enable() != 0) { + tr_error("ERROR: Write Enabe failed\n"); + program_failed = true; + status = QSPIF_BD_ERROR_WREN_FAILED; + goto exit_point; + } + + _spi_send_program_command(_prog_instruction, buffer, addr, chunk); + + buffer = static_cast(buffer) + chunk; + addr += chunk; + size -= chunk; + + if ( false == _is_mem_ready()) { + tr_error("ERROR: Device not ready after write, failed\n"); + program_failed = true; + status = QSPIF_BD_ERROR_READY_FAILED; + goto exit_point; + } + _mutex.unlock(); + } + +exit_point: + if (program_failed) { + _mutex.unlock(); } - return 0; + return status; } int SPIFBlockDevice::erase(bd_addr_t addr, bd_size_t size) @@ -327,26 +543,69 @@ int SPIFBlockDevice::erase(bd_addr_t addr, bd_size_t size) return BD_ERROR_DEVICE_ERROR; } + int type = 0; + uint32_t chunk = 4096; + unsigned int cur_erase_inst = _erase_instruction; + int size = (int)in_size; + bool erase_failed = false; + int status = QSPIF_BD_ERROR_OK; + // Find region of erased address + int region = _utils_find_addr_region(addr); + // Erase Types of selected region + uint8_t bitfield = _region_erase_types_bitfield[region]; + + tr_debug("DEBUG: erase - addr: %llu, in_size: %llu", addr, in_size); + + // For each iteration erase the largest section supported by current region while (size > 0) { - int err = _wren(); - if (err) { - return err; + + // iterate to find next Largest erase type ( a. supported by region, b. smaller than size) + // find the matching instruction and erase size chunk for that type. + type = _utils_iterate_next_largest_erase_type(bitfield, size, (int)addr, _region_high_boundary[region]); + cur_erase_inst = _erase_type_inst_arr[type]; + chunk = _erase_type_size_arr[type]; + + tr_debug("DEBUG: erase - addr: %llu, size:%d, Inst: 0x%xh, chunk: %d , ", + addr, size, cur_erase_inst, chunk); + tr_debug("DEBUG: erase - Region: %d, Type:%d", + region, type); + + _mutex.lock(); + + if (_set_write_enable() != 0) { + tr_error("ERROR: QSPI Erase Device not ready - failed"); + erase_failed = true; + status = QSPIF_BD_ERROR_READY_FAILED; + goto exit_point; } - - // Erase 4kbyte sectors - // TODO support other erase sizes? - uint32_t chunk = 4096; - _cmdwrite(SPIF_SE, 3, 0, addr, NULL); + + _spi_send_erase_command(cur_erase_inst, addr, size); + addr += chunk; size -= chunk; - err = _sync(); - if (err) { - return err; + if ( (size > 0) && (addr > _region_high_boundary[region]) ) { + // erase crossed to next region + region++; + bitfield = _region_erase_types_bitfield[region]; } + + if ( false == _is_mem_ready()) { + tr_error("ERROR: QSPI After Erase Device not ready - failed\n"); + erase_failed = true; + status = QSPIF_BD_ERROR_READY_FAILED; + goto exit_point; + } + + _mutex.unlock(); } - return 0; +exit_point: + if (erase_failed) { + _mutex.unlock(); + } + + return status; } bd_size_t SPIFBlockDevice::get_read_size() const @@ -364,11 +623,40 @@ bd_size_t SPIFBlockDevice::get_erase_size() const return SPIF_SE_SIZE; } -bd_size_t SPIFBlockDevice::get_erase_size(bd_addr_t addr) const +// Find minimal erase size supported by the region to which the address belongs to +bd_size_t SPIFBlockDevice::get_erase_size(bd_addr_t addr) { - return SPIF_SE_SIZE; + // Find region of current address + int region = _utils_find_addr_region(addr); + + int min_region_erase_size = _min_common_erase_size; + int8_t type_mask = ERASE_BITMASK_TYPE1; + int i_ind = 0; + + + if (region != -1) { + type_mask = 0x01; + + for (i_ind = 0; i_ind < 4; i_ind++) { + // loop through erase types bitfield supported by region + if (_region_erase_types_bitfield[region] & type_mask) { + + min_region_erase_size = _erase_type_size_arr[i_ind]; + break; + } + type_mask = type_mask << 1; + } + + if (i_ind == 4) { + tr_error("ERROR: no erase type was found for region addr"); + } + } + + return (bd_size_t)min_region_erase_size; } + + bd_size_t SPIFBlockDevice::size() const { if (!_is_initialized) { diff --git a/SPIFBlockDevice.h b/SPIFBlockDevice.h index 2cce398d81..6916b1c3eb 100644 --- a/SPIFBlockDevice.h +++ b/SPIFBlockDevice.h @@ -19,12 +19,28 @@ #include #include "BlockDevice.h" +namespace mbed { + +/** Enum qspif standard error codes + * + * @enum qspif_bd_error + */ +enum qspif_bd_error { + SPIF_BD_ERROR_OK = 0, /*!< no error */ + SPIF_BD_ERROR_DEVICE_ERROR = BD_ERROR_DEVICE_ERROR, /*!< device specific error -4001 */ + SPIF_BD_ERROR_PARSING_FAILED = -4002, /* SFDP Parsing failed */ + SPIF_BD_ERROR_READY_FAILED = -4003, /* Wait for Mem Ready failed */ + SPIF_BD_ERROR_WREN_FAILED = -4004, /* Write Enable Failed */ +}; + + +#define SPIF_MAX_REGIONS 10 +#define MAX_NUM_OF_ERASE_TYPES 4 -/** BlockDevice for SPI based flash devices - * such as the MX25R or SST26F016B +/** BlockDevice for SFDP based flash devices over SPI bus * * @code - * // Here's an example using the MX25R SPI flash device on the K82F + * // Here's an example using SPI flash device on K82F target * #include "mbed.h" * #include "SPIFBlockDevice.h" * @@ -138,7 +154,15 @@ public: */ virtual bd_size_t get_erase_size(bd_addr_t addr) const; - /** Get the value of storage when erased + /** Get the size of minimal eraseable sector size of given address + * + * @param addr Any address within block queried for erase sector size (can be any address within flash size offset) + * @return Size of minimal erase sector size, in given address region, in bytes + * @note Must be a multiple of the program size + */ + virtual bd_size_t get_erase_size(bd_addr_t addr); + + /** Get the value of storage byte after it was erased * * If get_erase_value returns a non-negative byte value, the underlying * storage is set to that value when erased, and storage containing @@ -155,6 +179,48 @@ public: */ virtual bd_size_t size() const; +private: + + /* SFDP Detection and Parsing Functions */ + /****************************************/ + // Parse SFDP Headers and retrieve Basic Param and Sector Map Tables (if exist) + int _sfdp_parse_sfdp_headers(uint32_t& basic_table_addr, size_t& basic_table_size, + uint32_t& sector_map_table_addr, size_t& sector_map_table_size); + + // Parse and Detect required Basic Parameters from Table + int _sfdp_parse_basic_param_table(uint32_t basic_table_addr, size_t basic_table_size); + + // Parse and read information required by Regions Secotr Map + int _sfdp_parse_sector_map_table(uint32_t sector_map_table_addr, size_t sector_map_table_size); + + // Detect fastest read Bus mode supported by device + int _sfdp_detect_best_bus_read_mode(uint8_t *basic_param_table_ptr, bool& set_quad_enable, bool& is_qpi_mode, + unsigned int& read_inst); + + // Set Page size for program + int _sfdp_detect_page_size(uint8_t *basic_param_table_ptr); + + // Detect all supported erase types + int _sfdp_detect_erase_types_inst_and_size(uint8_t *basic_param_table_ptr, unsigned int& erase4k_inst, + unsigned int *erase_type_inst_arr, unsigned int *erase_type_size_arr); + + /* Utilities Functions */ + /***********************/ + // Find the region to which the given offset belong to + int _utils_find_addr_region(bd_size_t offset); + + // Iterate on all supported Erase Types of the Region to which the offset belong to. + // Iterates from highest type to lowest + int _utils_iterate_next_largest_erase_type(uint8_t& bitfield, int size, int offset, int boundry); + + // Internal functions + int _wren(); + int _sync(); + void _cmdread(uint8_t op, uint32_t addrc, uint32_t retc, + uint32_t addr, uint8_t *rets); + void _cmdwrite(uint8_t op, uint32_t addrc, uint32_t argc, + uint32_t addr, const uint8_t *args); + private: // Master side hardware SPI _spi; @@ -166,14 +232,45 @@ private: bool _is_initialized; uint32_t _init_ref_count; - // Internal functions - int _wren(); - int _sync(); - void _cmdread(uint8_t op, uint32_t addrc, uint32_t retc, - uint32_t addr, uint8_t *rets); - void _cmdwrite(uint8_t op, uint32_t addrc, uint32_t argc, - uint32_t addr, const uint8_t *args); + bool _is_initialized; + + // Mutex is used to protect Flash device for some QSPI Driver commands that must be done sequentially with no other commands in between + // e.g. (1)Set Write Enable, (2)Program, (3)Wait Memory Ready + PlatformMutex _mutex; + + // Command Instructions + unsigned int _read_instruction; + unsigned int _prog_instruction; + unsigned int _erase_instruction; + unsigned int _erase4k_inst; // Legacy 4K erase instruction (default 0x20h) + + // Up To 4 Erase Types are supported by SFDP (each with its own command Instruction and Size) + unsigned int _erase_type_inst_arr[MAX_NUM_OF_ERASE_TYPES]; + unsigned int _erase_type_size_arr[MAX_NUM_OF_ERASE_TYPES]; + + // Sector Regions Map + int _regions_count; //number of regions + int _region_size_bytes[QSPIF_MAX_REGIONS]; //regions size in bytes + bd_size_t _region_high_boundary[QSPIF_MAX_REGIONS]; //region high address offset boundary + //Each Region can support a bit combination of any of the 4 Erase Types + uint8_t _region_erase_types_bitfield[QSPIF_MAX_REGIONS]; + int _min_common_erase_size; // minimal common erase size for all regions (0 if none exists) + + int _page_size_bytes; // Page size - 256 Bytes default + bd_size_t _device_size_bytes; + + // Bus speed configuration + qspi_bus_width_t _inst_width; //Bus width for Instruction phase + qspi_bus_width_t _address_width; //Bus width for Address phase + qspi_address_size_t _address_size; // number of bytes for address + qspi_bus_width_t _data_width; //Bus width for Data phase + int _dummy_and_mode_cycles; // Number of Dummy and Mode Bits required by Current Bus Mode + + + + }; +} //namespace mbed #endif /* MBED_SPIF_BLOCK_DEVICE_H */ From ed83b8e4c1b43e45b1f40908903ed79dccfae235 Mon Sep 17 00:00:00 2001 From: Offir Kochalsky Date: Thu, 16 Aug 2018 18:18:53 +0300 Subject: [PATCH 20/29] Changes Ready for PR --- SPIFBlockDevice.cpp | 1105 ++++++++++++++++++++++++++++--------------- SPIFBlockDevice.h | 140 +++--- 2 files changed, 805 insertions(+), 440 deletions(-) diff --git a/SPIFBlockDevice.cpp b/SPIFBlockDevice.cpp index 057deb120d..fde6e12c8b 100644 --- a/SPIFBlockDevice.cpp +++ b/SPIFBlockDevice.cpp @@ -1,5 +1,5 @@ /* mbed Microcontroller Library - * Copyright (c) 2016 ARM Limited + * Copyright (c) 2018 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,82 +17,140 @@ #include "SPIFBlockDevice.h" #include "mbed_critical.h" -// Read/write/erase sizes -#define SPIF_READ_SIZE 1 -#define SPIF_PROG_SIZE 1 -#define SPIF_SE_SIZE 4096 -#define SPIF_TIMEOUT 10000 +#include +#include "mbed_wait_api.h" -// Debug available -#define SPIF_DEBUG 0 +#include "mbed_trace.h" +#define TRACE_GROUP "SPIF" -// MX25R Series Register Command Table. -enum ops { - SPIF_NOP = 0x00, // No operation +/* Default SPIF Parameters */ +/****************************/ +#define SPIF_DEFAULT_READ_SIZE 1 +#define SPIF_DEFAULT_PROG_SIZE 1 +#define SPIF_DEFAULT_PAGE_SIZE 256 +#define SPIF_DEFAULT_SE_SIZE 4096 +#define SPI_MAX_STATUS_REGISTER_SIZE 2 +#define SPI_NO_ADDRESS_COMMAND UINT64_MAX +// Status Register Bits +#define SPIF_STATUS_BIT_WIP 0x1 //Write In Progress +#define SPIF_STATUS_BIT_WEL 0x2 // Write Enable Latch + +/* SFDP Header Parsing */ +/***********************/ +#define SPIF_SFDP_HEADER_SIZE 8 +#define SPIF_PARAM_HEADER_SIZE 8 + +/* Basic Parameters Table Parsing */ +/**********************************/ +#define SFDP_DEFAULT_BASIC_PARAMS_TABLE_SIZE_BYTES 64 /* 16 DWORDS */ +//READ Instruction support according to BUS Configuration +#define SPIF_BASIC_PARAM_TABLE_FAST_READ_SUPPORT_BYTE 2 +#define SPIF_BASIC_PARAM_TABLE_QPI_READ_SUPPORT_BYTE 16 +#define SPIF_BASIC_PARAM_TABLE_222_READ_INST_BYTE 23 +#define SPIF_BASIC_PARAM_TABLE_122_READ_INST_BYTE 15 +#define SPIF_BASIC_PARAM_TABLE_112_READ_INST_BYTE 13 +#define SPIF_BASIC_PARAM_TABLE_PAGE_SIZE_BYTE 40 +// Address Length +#define SPIF_ADDR_SIZE_3_BYTES 3 +// Erase Types Params +#define SPIF_BASIC_PARAM_ERASE_TYPE_1_BYTE 29 +#define SPIF_BASIC_PARAM_ERASE_TYPE_2_BYTE 31 +#define SPIF_BASIC_PARAM_ERASE_TYPE_3_BYTE 33 +#define SPIF_BASIC_PARAM_ERASE_TYPE_4_BYTE 35 +#define SPIF_BASIC_PARAM_ERASE_TYPE_1_SIZE_BYTE 28 +#define SPIF_BASIC_PARAM_ERASE_TYPE_2_SIZE_BYTE 30 +#define SPIF_BASIC_PARAM_ERASE_TYPE_3_SIZE_BYTE 32 +#define SPIF_BASIC_PARAM_ERASE_TYPE_4_SIZE_BYTE 34 +#define SPIF_BASIC_PARAM_4K_ERASE_TYPE_BYTE 1 + +// Erase Types Per Region BitMask +#define ERASE_BITMASK_TYPE4 0x08 +#define ERASE_BITMASK_TYPE1 0x01 +#define ERASE_BITMASK_NONE 0x00 +#define ERASE_BITMASK_ALL 0x0F + +#define IS_MEM_READY_MAX_RETRIES 10000 + +namespace mbed { + +enum spif_default_instructions { + SPIF_NOP = 0x00, // No operation + SPIF_PP = 0x02, // Page Program data SPIF_READ = 0x03, // Read data - SPIF_PROG = 0x02, // Program data - SPIF_SE = 0x20, // 4KB Sector Erase - SPIF_CE = 0xc7, // Chip Erase - SPIF_SFDP = 0x5a, // Read SFDP - SPIF_WREN = 0x06, // Write Enable + SPIF_SE = 0x20, // 4KB Sector Erase + SPIF_SFDP = 0x5a, // Read SFDP + SPIF_WRSR = 0x01, // Write Status/Configuration Register SPIF_WRDI = 0x04, // Write Disable - SPIF_RDSR = 0x05, // Read Status Register - SPIF_RDID = 0x9f, // Read Manufacturer and JDEC Device ID + SPIF_RDSR = 0x05, // Read Status Register + SPIF_WREN = 0x06, // Write Enable + SPIF_RSTEN = 0x66, // Reset Enable + SPIF_RST = 0x99, // Reset + SPIF_RDID = 0x9f, // Read Manufacturer and JDEC Device ID }; -// Status register from RDSR -// [- stuff -| wel | wip ] -// [- 6 -| 1 | 1 ] -#define SPIF_WEL 0x2 -#define SPIF_WIP 0x1 +// Mutex is used for some SPI Driver commands that must be done sequentially with no other commands in between +// e.g. (1)Set Write Enable, (2)Program, (3)Wait Memory Ready +SingletonPtr SPIFBlockDevice::_mutex; - +// Local Function +static unsigned int local_math_power(int base, int exp); + +//*********************** +// SPIF Block Device APIs +//*********************** SPIFBlockDevice::SPIFBlockDevice( - PinName mosi, PinName miso, PinName sclk, PinName cs, int freq) - : _spi(mosi, miso, sclk), _cs(cs), _size(0), _is_initialized(false), _init_ref_count(0) + PinName mosi, PinName miso, PinName sclk, PinName csel, int freq) + : _spi(mosi, miso, sclk), _cs(csel), _device_size_bytes(0), _is_initialized(false) { - _cs = 1; - _spi.frequency(freq); - _address_size = QSPI_CFG_ADDR_SIZE_24; + _address_size = SPIF_ADDR_SIZE_3_BYTES; // Initial SFDP read tables are read with 8 dummy cycles + // Default Bus Setup 1_1_1 with 0 dummy and mode cycles _read_dummy_and_mode_cycles = 8; - _dummy_and_mode_cycles = 8; + _write_dummy_and_mode_cycles = 0; + _dummy_and_mode_cycles = _read_dummy_and_mode_cycles; + _min_common_erase_size = 0; + _regions_count = 1; + _region_erase_types_bitfield[0] = ERASE_BITMASK_NONE; + + if (SPIF_BD_ERROR_OK != _spi_set_frequency(freq)) { + tr_error("ERROR: SPI Set Frequency Failed"); + } + + _cs = 1; } int SPIFBlockDevice::init() { - uint8_t vendor_device_ids[4]; size_t data_length = 3; int status = SPIF_BD_ERROR_OK; - uint32_t basic_table_addr = NULL; + uint32_t basic_table_addr = 0; size_t basic_table_size = 0; - uint32_t sector_map_table_addr = NULL; + uint32_t sector_map_table_addr = 0; size_t sector_map_table_size = 0; - int qspi_status = QSPI_STATUS_OK; + spif_bd_error spi_status = SPIF_BD_ERROR_OK; - _mutex.lock(); + _mutex->lock(); if (_is_initialized == true) { goto exit_point; } // Soft Reset - /* if ( -1 == _reset_flash_mem()) { tr_error("ERROR: init - Unable to initialize flash memory, tests failed\n"); - status = QSPIF_BD_ERROR_DEVICE_ERROR; + status = SPIF_BD_ERROR_DEVICE_ERROR; goto exit_point; } else { tr_info("INFO: Initialize flash memory OK\n"); } - */ + /* Read Manufacturer ID (1byte), and Device ID (2bytes)*/ - qspi_status = _qspi_send_read_command(QSPIF_RDID, (char *)vendor_device_ids, 0x0 /*address*/, data_length); - if (qspi_status != QSPI_STATUS_OK) { + spi_status = _spi_send_read_command(SPIF_RDID, vendor_device_ids, 0x0 /*address*/, data_length); + if (spi_status != SPIF_BD_ERROR_OK) { tr_error("ERROR: init - Read Vendor ID Failed"); - status = QSPIF_BD_ERROR_DEVICE_ERROR; + status = SPIF_BD_ERROR_DEVICE_ERROR; goto exit_point; } @@ -101,21 +159,21 @@ int SPIFBlockDevice::init() // SST devices come preset with block protection // enabled for some regions, issue write disable instruction to clear _set_write_enable(); - _qspi_send_general_command(QSPIF_WRDI, -1, NULL, 0, NULL, 0); + _spi_send_general_command(SPIF_WRDI, SPI_NO_ADDRESS_COMMAND, NULL, 0, NULL, 0); break; } //Synchronize Device if ( false == _is_mem_ready()) { tr_error("ERROR: init - _is_mem_ready Failed"); - status = QSPIF_BD_ERROR_READY_FAILED; + status = SPIF_BD_ERROR_READY_FAILED; goto exit_point; } /**************************** Parse SFDP Header ***********************************/ if ( 0 != _sfdp_parse_sfdp_headers(basic_table_addr, basic_table_size, sector_map_table_addr, sector_map_table_size)) { tr_error("ERROR: init - Parse SFDP Headers Failed"); - status = QSPIF_BD_ERROR_PARSING_FAILED; + status = SPIF_BD_ERROR_PARSING_FAILED; goto exit_point; } @@ -123,7 +181,7 @@ int SPIFBlockDevice::init() /**************************** Parse Basic Parameters Table ***********************************/ if ( 0 != _sfdp_parse_basic_param_table(basic_table_addr, basic_table_size) ) { tr_error("ERROR: init - Parse Basic Param Table Failed"); - status = QSPIF_BD_ERROR_PARSING_FAILED; + status = SPIF_BD_ERROR_PARSING_FAILED; goto exit_point; } @@ -132,330 +190,47 @@ int SPIFBlockDevice::init() _device_size_bytes; // If there's no region map, we have a single region sized the entire device size _region_high_boundary[0] = _device_size_bytes - 1; - if ( (sector_map_table_addr != NULL) && (0 != sector_map_table_size) ) { + if ( (sector_map_table_addr != 0) && (0 != sector_map_table_size) ) { tr_info("INFO: init - Parsing Sector Map Table - addr: 0x%xh, Size: %d", sector_map_table_addr, sector_map_table_size); if (0 != _sfdp_parse_sector_map_table(sector_map_table_addr, sector_map_table_size) ) { tr_error("ERROR: init - Parse Sector Map Table Failed"); - status = QSPIF_BD_ERROR_PARSING_FAILED; + status = SPIF_BD_ERROR_PARSING_FAILED; goto exit_point; } } // Configure BUS Mode to 1_1_1 for all commands other than Read - _qspi_configure_format(QSPI_CFG_BUS_SINGLE, QSPI_CFG_BUS_SINGLE, QSPI_CFG_ADDR_SIZE_24, QSPI_CFG_BUS_SINGLE, - QSPI_CFG_ALT_SIZE_8, QSPI_CFG_BUS_SINGLE, 0); - + // Dummy And Mode Cycles Back default 0 + _dummy_and_mode_cycles = _write_dummy_and_mode_cycles; _is_initialized = true; exit_point: - _mutex.unlock(); + _mutex->unlock(); return status; - - -/**************************************************************************************************************/ - if (!_is_initialized) { - _init_ref_count = 0; - } - - uint32_t val = core_util_atomic_incr_u32(&_init_ref_count, 1); - - if (val != 1) { - return BD_ERROR_OK; - } - - // Initial SFDP read tables are read with 8 dummy cycles - _read_dummy_and_mode_cycles = 8; - - // Check for vendor specific hacks, these should move into more general - // handling when possible. RDID is not used to verify a device is attached. - uint8_t id[3]; - _cmdread(SPIF_RDID, 0, 3, 0x0, id); - - switch (id[0]) { - case 0xbf: - // SST devices come preset with block protection - // enabled for some regions, issue gbpu instruction to clear - _wren(); - _cmdwrite(0x98, 0, 0, 0x0, NULL); - break; - } - - // Check that device is doing ok - int err = _sync(); - if (err) { - return BD_ERROR_DEVICE_ERROR; - } - - // Check JEDEC serial flash discoverable parameters for device - // specific info - uint8_t header[16]; - _cmdread(SPIF_SFDP, 4, 16, 0x0, header); - - // Verify SFDP signature for sanity - // Also check that major/minor version is acceptable - if (!(memcmp(&header[0], "SFDP", 4) == 0 && header[5] == 1)) { - return BD_ERROR_DEVICE_ERROR; - } - - // The SFDP spec indicates the standard table is always at offset 0 - // in the parameter headers, we check just to be safe - if (!(header[8] == 0 && header[10] == 1)) { - return BD_ERROR_DEVICE_ERROR; - } - - // Parameter table pointer, spi commands are BE, SFDP is LE, - // also sfdp command expects extra read wait byte - uint32_t table_addr = ( - (header[14] << 24) | - (header[13] << 16) | - (header[12] << 8 )); - uint8_t table[8]; - _cmdread(SPIF_SFDP, 4, 8, table_addr, table); - - // Check erase size, currently only supports 4kbytes - // TODO support erase size != 4kbytes? - // TODO support other erase opcodes from the sector descriptions - if ((table[0] & 0x3) != 0x1 || table[1] != SPIF_SE) { - return BD_ERROR_DEVICE_ERROR; - } - - // Check address size, currently only supports 3byte addresses - // TODO support address > 3bytes? - // TODO check for devices larger than 2Gbits? - if ((table[2] & 0x4) != 0 || (table[7] & 0x80) != 0) { - return BD_ERROR_DEVICE_ERROR; - } - - // Get device density, stored as size in bits - 1 - uint32_t density = ( - (table[7] << 24) | - (table[6] << 16) | - (table[5] << 8 ) | - (table[4] << 0 )); - _size = (density/8) + 1; - - _is_initialized = true; - return 0; } + int SPIFBlockDevice::deinit() { - if (!_is_initialized) { - _init_ref_count = 0; - return 0; + _mutex->lock(); + if (_is_initialized == false) { + _mutex->unlock(); + return SPIF_BD_ERROR_OK; } - uint32_t val = core_util_atomic_decr_u32(&_init_ref_count, 1); - - if (val) { - return 0; + // Disable Device for Writing + spif_bd_error status = _spi_send_general_command(SPIF_WRDI, SPI_NO_ADDRESS_COMMAND, NULL, 0, NULL, 0); + if (status != SPIF_BD_ERROR_OK) { + tr_error("ERROR: Write Disable failed"); } - - // Latch write disable just to keep noise - // from changing the device - _cmdwrite(SPIF_WRDI, 0, 0, 0x0, NULL); - _is_initialized = false; - return 0; + _mutex->unlock(); + + return status; } - - -void SPIFBlockDevice::_cmdread(uint8_t inst, uint32_t addr, uint32_t data_size, uint8_t *data) -{ - _cs = 0; - uint32_t dummy_bytes = _dummy_and_mode_cycles / 8; - uint8_t dummy_byte = 0x00; - uint8_t *addr_byte_ptr = &addr; - addr_byte_ptr += (_address_size-1) - - // Write 1 byte Instruction - _spi.write(inst); - - // Write Address (can be either 3 or 4 bytes long) - for (uint32_t i = 0; i < _address_size; i++) { - _spi.write(*addr_byte_ptr); - addr_byte_ptr--; - } - - // Write Dummy Cycles Bytes - for (uint32_t i = 0; i < dummy_bytes; i++) { - _spi.write(dummy_byte); - } - - // Read Data - for (uint32_t i = 0; i < data_size; i++) { - data[i] = _spi.write(0); - } - _cs = 1; -} - -void SPIFBlockDevice::_cmdwrite(uint8_t inst, uint32_t addr, uint32_t data_size, const uint8_t *data) -{ - _cs = 0; - uint32_t dummy_bytes = _dummy_and_mode_cycles / 8; - uint8_t dummy_byte = 0x00; - uint8_t *addr_byte_ptr = &addr; - addr_byte_ptr += (_address_size-1) - - // Write 1 byte Instruction - _spi.write(inst); - - // Write Address (can be either 3 or 4 bytes long) - for (uint32_t i = 0; i < _address_size; i++) { - _spi.write(*addr_byte_ptr); - addr_byte_ptr--; - } - - // Write Dummy Cycles Bytes - for (uint32_t i = 0; i < dummy_bytes; i++) { - _spi.write(dummy_byte); - } - - // Write Data - for (uint32_t i = 0; i < data_size; i++) { - _spi.write(data[i]); - } - _cs = 1; -} - -int SPIFBlockDevice::_sync() -{ - for (int i = 0; i < SPIF_TIMEOUT; i++) { - // Read status register until write not-in-progress - uint8_t status; - _cmdread(SPIF_RDSR, 0, 1, 0x0, &status); - - // Check WIP bit - if (!(status & SPIF_WIP)) { - return 0; - } - - wait_ms(1); - } - - return BD_ERROR_DEVICE_ERROR; -} - -int SPIFBlockDevice::_wren() -{ - _cmdwrite(SPIF_WREN, 0, 0, 0x0, NULL); - - for (int i = 0; i < SPIF_TIMEOUT; i++) { - // Read status register until write latch is enabled - uint8_t status; - _cmdread(SPIF_RDSR, 0, 1, 0x0, &status); - - // Check WEL bit - if (status & SPIF_WEL) { - return 0; - } - - wait_ms(1); - } - - return BD_ERROR_DEVICE_ERROR; -} - - -void SPIFBlockDevice::_spi_send_read_command(uint8_t read_inst, void *buffer, bd_addr_t addr, bd_size_t size) -{ - uint32_t dummy_bytes = _dummy_and_mode_cycles / 8; - uint8_t dummy_byte = 0x00; - uint8_t *addr_byte_ptr = addr; - uint8_t *data = (uint8_t *)buffer; - addr_byte_ptr += (_address_size-1); - - // Write 1 byte Instruction - _spi.write(read_inst); - - // Write Address (can be either 3 or 4 bytes long) - for (uint32_t i = 0; i < _address_size; i++) { - _spi.write(*addr_byte_ptr); - addr_byte_ptr--; - } - - // Write Dummy Cycles Bytes - for (uint32_t i = 0; i < dummy_bytes; i++) { - _spi.write(dummy_byte); - } - - // Read Data - for (bd_size_t i = 0; i < size; i++) { - data[i] = _spi.write(0); - } - - return; -} - -void SPIFBlockDevice::_spi_send_program_command(unsigned int prog_inst, const void *buffer, bd_addr_t addr, bd_size_t size) -{ - // Send Program (write) command to device driver - uint32_t dummy_bytes = _dummy_and_mode_cycles / 8; - uint8_t dummy_byte = 0x00; - uint8_t *addr_byte_ptr = addr; - uint8_t *data = (uint8_t *)buffer; - addr_byte_ptr += (_address_size-1) - - // Write 1 byte Instruction - _spi.write(prog_inst); - - // Write Address (can be either 3 or 4 bytes long) - for (uint32_t i = 0; i < _address_size; i++) { - _spi.write(*addr_byte_ptr); - addr_byte_ptr--; - } - - // Write Dummy Cycles Bytes - for (uint32_t i = 0; i < dummy_bytes; i++) { - _spi.write(dummy_byte); - } - - // Write Data - for (bd_size_t i = 0; i < size; i++) { - _spi.write(data[i]); - } - - return; -} - -qspi_status_t SPIFBlockDevice::_spi_send_erase_command(unsigned int erase_inst, bd_addr_t addr, bd_size_t size) -{ - tr_info("INFO: Inst: 0x%xh, addr: %llu, size: %llu", erase_inst, addr, size); - _spi_send_general_command(erase_inst, addr) - return; -} - -qspi_status_t SPIFBlockDevice::_spi_send_general_command(unsigned int instruction, bd_addr_t addr) -{ - // Send a general command Instruction to driver - uint32_t dummy_bytes = _dummy_and_mode_cycles / 8; - uint8_t dummy_byte = 0x00; - uint8_t *addr_byte_ptr = (((int)addr) & 0x00FFF000); - uint8_t *data = (uint8_t *)buffer; - addr_byte_ptr += (_address_size-1) - - // Write 1 byte Instruction - _spi.write(instruction); - - // Write Address (can be either 3 or 4 bytes long) - for (uint32_t i = 0; i < _address_size; i++) { - _spi.write(*addr_byte_ptr); - addr_byte_ptr--; - } - - // Write Dummy Cycles Bytes - for (uint32_t i = 0; i < dummy_bytes; i++) { - _spi.write(dummy_byte); - } - - return; -} - - - int SPIFBlockDevice::read(void *buffer, bd_addr_t addr, bd_size_t size) { if (!_is_initialized) { @@ -463,20 +238,18 @@ int SPIFBlockDevice::read(void *buffer, bd_addr_t addr, bd_size_t size) } int status = SPIF_BD_ERROR_OK; - - tr_info("INFO Inst: 0x%xh", _read_instruction); - - _mutex.lock(); + tr_info("INFO Read - Inst: 0x%xh", _read_instruction); + _mutex->lock(); // Set Dummy Cycles for Specific Read Command Mode _dummy_and_mode_cycles = _read_dummy_and_mode_cycles; - _spi_send_read_command(_read_instruction, buffer, addr, size); + status = _spi_send_read_command(_read_instruction, static_cast(buffer), addr, size); // Set Dummy Cycles for all other command modes - _dummy_and_mode_cycles = 0; + _dummy_and_mode_cycles = _write_dummy_and_mode_cycles; - _mutex.unlock(); + _mutex->unlock(); return status; } @@ -487,7 +260,6 @@ int SPIFBlockDevice::program(const void *buffer, bd_addr_t addr, bd_size_t size) return BD_ERROR_DEVICE_ERROR; } - qspi_status_t result = QSPI_STATUS_OK; bool program_failed = false; int status = SPIF_BD_ERROR_OK; uint32_t offset = 0; @@ -501,13 +273,13 @@ int SPIFBlockDevice::program(const void *buffer, bd_addr_t addr, bd_size_t size) offset = addr % _page_size_bytes; chunk = (offset + size < _page_size_bytes) ? size : (_page_size_bytes - offset); - _mutex.lock(); + _mutex->lock(); //Send WREN if (_set_write_enable() != 0) { tr_error("ERROR: Write Enabe failed\n"); program_failed = true; - status = QSPIF_BD_ERROR_WREN_FAILED; + status = SPIF_BD_ERROR_WREN_FAILED; goto exit_point; } @@ -520,35 +292,32 @@ int SPIFBlockDevice::program(const void *buffer, bd_addr_t addr, bd_size_t size) if ( false == _is_mem_ready()) { tr_error("ERROR: Device not ready after write, failed\n"); program_failed = true; - status = QSPIF_BD_ERROR_READY_FAILED; + status = SPIF_BD_ERROR_READY_FAILED; goto exit_point; } - _mutex.unlock(); + _mutex->unlock(); } exit_point: if (program_failed) { - _mutex.unlock(); + _mutex->unlock(); } return status; } -int SPIFBlockDevice::erase(bd_addr_t addr, bd_size_t size) +int SPIFBlockDevice::erase(bd_addr_t addr, bd_size_t in_size) { - // Check the address and size fit onto the chip. - MBED_ASSERT(is_valid_erase(addr, size)); - if (!_is_initialized) { return BD_ERROR_DEVICE_ERROR; } int type = 0; uint32_t chunk = 4096; - unsigned int cur_erase_inst = _erase_instruction; + int cur_erase_inst = _erase_instruction; int size = (int)in_size; bool erase_failed = false; - int status = QSPIF_BD_ERROR_OK; + int status = SPIF_BD_ERROR_OK; // Find region of erased address int region = _utils_find_addr_region(addr); // Erase Types of selected region @@ -561,7 +330,7 @@ int SPIFBlockDevice::erase(bd_addr_t addr, bd_size_t size) // iterate to find next Largest erase type ( a. supported by region, b. smaller than size) // find the matching instruction and erase size chunk for that type. - type = _utils_iterate_next_largest_erase_type(bitfield, size, (int)addr, _region_high_boundary[region]); + type = _utils_iterate_next_largest_erase_type(bitfield, size, (unsigned int)addr, _region_high_boundary[region]); cur_erase_inst = _erase_type_inst_arr[type]; chunk = _erase_type_size_arr[type]; @@ -570,12 +339,12 @@ int SPIFBlockDevice::erase(bd_addr_t addr, bd_size_t size) tr_debug("DEBUG: erase - Region: %d, Type:%d", region, type); - _mutex.lock(); + _mutex->lock(); if (_set_write_enable() != 0) { - tr_error("ERROR: QSPI Erase Device not ready - failed"); + tr_error("ERROR: SPI Erase Device not ready - failed"); erase_failed = true; - status = QSPIF_BD_ERROR_READY_FAILED; + status = SPIF_BD_ERROR_READY_FAILED; goto exit_point; } @@ -591,18 +360,18 @@ int SPIFBlockDevice::erase(bd_addr_t addr, bd_size_t size) } if ( false == _is_mem_ready()) { - tr_error("ERROR: QSPI After Erase Device not ready - failed\n"); + tr_error("ERROR: SPI After Erase Device not ready - failed\n"); erase_failed = true; - status = QSPIF_BD_ERROR_READY_FAILED; + status = SPIF_BD_ERROR_READY_FAILED; goto exit_point; } - _mutex.unlock(); + _mutex->unlock(); } exit_point: if (erase_failed) { - _mutex.unlock(); + _mutex->unlock(); } return status; @@ -610,17 +379,20 @@ exit_point: bd_size_t SPIFBlockDevice::get_read_size() const { - return SPIF_READ_SIZE; + // Assuming all devices support 1byte read granularity + return SPIF_DEFAULT_READ_SIZE; } bd_size_t SPIFBlockDevice::get_program_size() const { - return SPIF_PROG_SIZE; + // Assuming all devices support 1byte program granularity + return SPIF_DEFAULT_PROG_SIZE; } bd_size_t SPIFBlockDevice::get_erase_size() const { - return SPIF_SE_SIZE; + // return minimal erase size supported by all regions (0 if none exists) + return _min_common_erase_size; } // Find minimal erase size supported by the region to which the address belongs to @@ -629,11 +401,10 @@ bd_size_t SPIFBlockDevice::get_erase_size(bd_addr_t addr) // Find region of current address int region = _utils_find_addr_region(addr); - int min_region_erase_size = _min_common_erase_size; + unsigned int min_region_erase_size = _min_common_erase_size; int8_t type_mask = ERASE_BITMASK_TYPE1; int i_ind = 0; - if (region != -1) { type_mask = 0x01; @@ -655,18 +426,590 @@ bd_size_t SPIFBlockDevice::get_erase_size(bd_addr_t addr) return (bd_size_t)min_region_erase_size; } - - bd_size_t SPIFBlockDevice::size() const { if (!_is_initialized) { - return BD_ERROR_DEVICE_ERROR; + return SPIF_BD_ERROR_DEVICE_ERROR; } - return _size; + return _device_size_bytes; } int SPIFBlockDevice::get_erase_value() const { return 0xFF; } + +/***************************************************/ +/*********** SPI Driver API Functions **************/ +/***************************************************/ +spif_bd_error SPIFBlockDevice::_spi_set_frequency(int freq) +{ + _spi.frequency(freq); + return SPIF_BD_ERROR_OK; +} + +spif_bd_error SPIFBlockDevice::_spi_send_read_command(int read_inst, uint8_t *buffer, bd_addr_t addr, bd_size_t size) +{ + uint32_t dummy_bytes = _dummy_and_mode_cycles / 8; + int dummy_byte = 0; + + // csel must go low for the entire command (Inst, Address and Data) + _cs = 0; + + // Write 1 byte Instruction + _spi.write(read_inst); + + // Write Address (can be either 3 or 4 bytes long) + for (int address_shift = ((_address_size-1) * 8); address_shift >= 0; address_shift -= 8) { + _spi.write((addr >> address_shift) & 0xFF); + } + + // Write Dummy Cycles Bytes + for (uint32_t i = 0; i < dummy_bytes; i++) { + _spi.write(dummy_byte); + } + + // Read Data + for (bd_size_t i = 0; i < size; i++) { + buffer[i] = _spi.write(0); + } + + // csel back to high + _cs = 1; + return SPIF_BD_ERROR_OK; +} + +spif_bd_error SPIFBlockDevice::_spi_send_program_command(int prog_inst, const void *buffer, bd_addr_t addr, bd_size_t size) +{ + // Send Program (write) command to device driver + uint32_t dummy_bytes = _dummy_and_mode_cycles / 8; + int dummy_byte = 0; + uint8_t *data = (uint8_t *)buffer; + + // csel must go low for the entire command (Inst, Address and Data) + _cs = 0; + + // Write 1 byte Instruction + _spi.write(prog_inst); + + // Write Address (can be either 3 or 4 bytes long) + for (int address_shift = ((_address_size-1) * 8); address_shift >= 0; address_shift -= 8) { + _spi.write((addr >> address_shift) & 0xFF); + } + + // Write Dummy Cycles Bytes + for (uint32_t i = 0; i < dummy_bytes; i++) { + _spi.write(dummy_byte); + } + + // Write Data + for (bd_size_t i = 0; i < size; i++) { + _spi.write(data[i]); + } + + // csel back to high + _cs = 1; + + return SPIF_BD_ERROR_OK; +} + +spif_bd_error SPIFBlockDevice::_spi_send_erase_command(int erase_inst, bd_addr_t addr, bd_size_t size) +{ + tr_info("INFO: Erase Inst: 0x%xh, addr: %llu, size: %llu", erase_inst, addr, size); + addr = (((int)addr) & 0x00FFF000); + _spi_send_general_command(erase_inst, addr, NULL, 0, NULL, 0); + return SPIF_BD_ERROR_OK; +} + +spif_bd_error SPIFBlockDevice::_spi_send_general_command(int instruction, bd_addr_t addr, char *tx_buffer, + size_t tx_length, char *rx_buffer, size_t rx_length) +{ + // Send a general command Instruction to driver + uint32_t dummy_bytes = _dummy_and_mode_cycles / 8; + uint8_t dummy_byte = 0x00; + + // csel must go low for the entire command (Inst, Address and Data) + _cs = 0; + + // Write 1 byte Instruction + _spi.write(instruction); + + // Reading SPI Bus registers does not require Flash Address + if (addr != SPI_NO_ADDRESS_COMMAND) { + // Write Address (can be either 3 or 4 bytes long) + for (int address_shift = ((_address_size-1) * 8); address_shift >= 0; address_shift -= 8) { + _spi.write((addr >> address_shift) & 0xFF); + } + + // Write Dummy Cycles Bytes + for (uint32_t i = 0; i < dummy_bytes; i++) { + _spi.write(dummy_byte); + } + } + + // Read/Write Data + _spi.write(tx_buffer, (int)tx_length, rx_buffer, (int)rx_length); + + // csel back to high + _cs = 1; + + return SPIF_BD_ERROR_OK; +} + +/*********************************************************/ +/********** SFDP Parsing and Detection Functions *********/ +/*********************************************************/ +int SPIFBlockDevice::_sfdp_parse_sector_map_table(uint32_t sector_map_table_addr, size_t sector_map_table_size) +{ + uint8_t sector_map_table[SFDP_DEFAULT_BASIC_PARAMS_TABLE_SIZE_BYTES]; /* Up To 16 DWORDS = 64 Bytes */ + uint32_t tmp_region_size = 0; + int i_ind = 0; + int prev_boundary = 0; + // Default set to all type bits 1-4 are common + int min_common_erase_type_bits = ERASE_BITMASK_ALL; + + + spif_bd_error status = _spi_send_read_command(SPIF_SFDP, sector_map_table, sector_map_table_addr /*address*/, + sector_map_table_size); + if (status != SPIF_BD_ERROR_OK) { + tr_error("ERROR: init - Read SFDP First Table Failed"); + return -1; + } + + // Currently we support only Single Map Descriptor + if (! ( (sector_map_table[0] & 0x3) == 0x03 ) && (sector_map_table[1] == 0x0) ) { + tr_error("ERROR: Sector Map - Supporting Only Single! Map Descriptor (not map commands)"); + return -1; + } + + _regions_count = sector_map_table[2] + 1; + if (_regions_count > SPIF_MAX_REGIONS) { + tr_error("ERROR: Supporting up to %d regions, current setup to %d regions - fail", + SPIF_MAX_REGIONS, _regions_count); + return -1; + } + + // Loop through Regions and set for each one: size, supported erase types, high boundary offset + // Calculate minimum Common Erase Type for all Regions + for (i_ind = 0; i_ind < _regions_count; i_ind++) { + tmp_region_size = ((*((uint32_t *)§or_map_table[(i_ind + 1) * 4])) >> 8) & 0x00FFFFFF; // bits 9-32 + _region_size_bytes[i_ind] = (tmp_region_size + 1) * 256; // Region size is 0 based multiple of 256 bytes; + _region_erase_types_bitfield[i_ind] = sector_map_table[(i_ind + 1) * 4] & 0x0F; // bits 1-4 + min_common_erase_type_bits &= _region_erase_types_bitfield[i_ind]; + _region_high_boundary[i_ind] = (_region_size_bytes[i_ind] - 1) + prev_boundary; + prev_boundary = _region_high_boundary[i_ind] + 1; + } + + // Calc minimum Common Erase Size from min_common_erase_type_bits + uint8_t type_mask = ERASE_BITMASK_TYPE1; + for (i_ind = 0; i_ind < 4; i_ind++) { + if (min_common_erase_type_bits & type_mask) { + _min_common_erase_size = _erase_type_size_arr[i_ind]; + break; + } + type_mask = type_mask << 1; + } + + if (i_ind == 4) { + // No common erase type was found between regions + _min_common_erase_size = 0; + } + + return 0; +} + +int SPIFBlockDevice::_sfdp_parse_basic_param_table(uint32_t basic_table_addr, size_t basic_table_size) +{ + uint8_t param_table[SFDP_DEFAULT_BASIC_PARAMS_TABLE_SIZE_BYTES]; /* Up To 16 DWORDS = 64 Bytes */ + //memset(param_table, 0, SFDP_DEFAULT_BASIC_PARAMS_TABLE_SIZE_BYTES); + + spif_bd_error status = _spi_send_read_command(SPIF_SFDP, param_table, basic_table_addr /*address*/, + basic_table_size); + if (status != SPIF_BD_ERROR_OK) { + tr_error("ERROR: init - Read SFDP First Table Failed"); + return -1; + } + + // Check address size, currently only supports 3byte addresses + if ((param_table[2] & 0x4) != 0 || (param_table[7] & 0x80) != 0) { + tr_error("ERROR: init - verify 3byte addressing Failed"); + return -1; + } + + // Get device density (stored in bits - 1) + uint32_t density_bits = ( + (param_table[7] << 24) | + (param_table[6] << 16) | + (param_table[5] << 8 ) | + param_table[4] ); + _device_size_bytes = (density_bits + 1) / 8; + + // Set Default read/program/erase Instructions + _read_instruction = SPIF_READ; + _prog_instruction = SPIF_PP; + _erase_instruction = SPIF_SE; + + // Set Page Size (SPI write must be done on Page limits) + _page_size_bytes = _sfdp_detect_page_size(param_table, basic_table_size); + + // Detect and Set Erase Types + _sfdp_detect_erase_types_inst_and_size(param_table, basic_table_size, _erase4k_inst, _erase_type_inst_arr, _erase_type_size_arr); + _erase_instruction = _erase4k_inst; + + // Detect and Set fastest Bus mode (default 1-1-1) + _sfdp_detect_best_bus_read_mode(param_table, basic_table_size, _read_instruction); + + return 0; +} + +int SPIFBlockDevice::_sfdp_parse_sfdp_headers(uint32_t& basic_table_addr, size_t& basic_table_size, + uint32_t& sector_map_table_addr, size_t& sector_map_table_size) +{ + uint8_t sfdp_header[16]; + uint8_t param_header[SPIF_SFDP_HEADER_SIZE]; + size_t data_length = SPIF_SFDP_HEADER_SIZE; + bd_addr_t addr = 0x0; + + // Set 1-1-1 bus mode for SFDP header parsing + // Initial SFDP read tables are read with 8 dummy cycles + _read_dummy_and_mode_cycles = 8; + _dummy_and_mode_cycles = 8; + + spif_bd_error status = _spi_send_read_command(SPIF_SFDP, sfdp_header, addr /*address*/, data_length); + if (status != SPIF_BD_ERROR_OK) { + tr_error("ERROR: init - Read SFDP Failed"); + return -1; + } + + // Verify SFDP signature for sanity + // Also check that major/minor version is acceptable + if (!(memcmp(&sfdp_header[0], "SFDP", 4) == 0 && sfdp_header[5] == 1)) { + tr_error("ERROR: init - _verify SFDP signature and version Failed"); + return -1; + } else { + tr_info("INFO: init - verified SFDP Signature and version Successfully"); + } + + // Discover Number of Parameter Headers + int number_of_param_headers = (int)(sfdp_header[6]) + 1; + tr_debug("DEBUG: number of Param Headers: %d", number_of_param_headers); + + + addr += SPIF_SFDP_HEADER_SIZE; + data_length = SPIF_PARAM_HEADER_SIZE; + + // Loop over Param Headers and parse them (currently supported Basic Param Table and Sector Region Map Table) + for (int i_ind = 0; i_ind < number_of_param_headers; i_ind++) { + + status = _spi_send_read_command(SPIF_SFDP, param_header, addr, data_length); + if (status != SPIF_BD_ERROR_OK) { + tr_error("ERROR: init - Read Param Table %d Failed", i_ind + 1); + return -1; + } + + // The SFDP spec indicates the standard table is always at offset 0 + // in the parameter headers, we check just to be safe + if (param_header[2] != 1) { + tr_error("ERROR: Param Table %d - Major Version should be 1!", i_ind + 1); + return -1; + } + + if ((param_header[0] == 0) && (param_header[7] == 0xFF)) { + // Found Basic Params Table: LSB=0x00, MSB=0xFF + tr_debug("DEBUG: Found Basic Param Table at Table: %d", i_ind + 1); + basic_table_addr = ( (param_header[6] << 16) | (param_header[5] << 8) | (param_header[4]) ); + // Supporting up to 64 Bytes Table (16 DWORDS) + basic_table_size = ((param_header[3] * 4) < SFDP_DEFAULT_BASIC_PARAMS_TABLE_SIZE_BYTES) ? (param_header[3] * 4) : 64; + + } else if ((param_header[0] == 81) && (param_header[7] == 0xFF)) { + // Found Sector Map Table: LSB=0x81, MSB=0xFF + tr_debug("DEBUG: Found Sector Map Table at Table: %d", i_ind + 1); + sector_map_table_addr = ( (param_header[6] << 16) | (param_header[5] << 8) | (param_header[4]) ); + sector_map_table_size = param_header[3] * 4; + + } + addr += SPIF_PARAM_HEADER_SIZE; + + } + return 0; +} + +unsigned int SPIFBlockDevice::_sfdp_detect_page_size(uint8_t *basic_param_table_ptr, int basic_param_table_size) +{ + unsigned int page_size = SPIF_DEFAULT_PAGE_SIZE; + + if (basic_param_table_size > SPIF_BASIC_PARAM_TABLE_PAGE_SIZE_BYTE) { + // Page Size is specified by 4 Bits (N), calculated by 2^N + int page_to_power_size = ( (int)basic_param_table_ptr[SPIF_BASIC_PARAM_TABLE_PAGE_SIZE_BYTE]) >> 4; + page_size = local_math_power(2, page_to_power_size); + tr_debug("DEBUG: Detected Page Size: %d", page_size); + } + else { + tr_debug("DEBUG: Using Default Page Size: %d", page_size); + } + return page_size; +} + +int SPIFBlockDevice::_sfdp_detect_erase_types_inst_and_size(uint8_t *basic_param_table_ptr, int basic_param_table_size, int& erase4k_inst, + int *erase_type_inst_arr, unsigned int *erase_type_size_arr) +{ + erase4k_inst = 0xff; + bool found_4Kerase_type = false; + uint8_t bitfield = 0x01; + + // Erase 4K Inst is taken either from param table legacy 4K erase or superseded by erase Instruction for type of size 4K + erase4k_inst = basic_param_table_ptr[SPIF_BASIC_PARAM_4K_ERASE_TYPE_BYTE]; + + if (basic_param_table_size > SPIF_BASIC_PARAM_ERASE_TYPE_1_SIZE_BYTE) { + // Loop Erase Types 1-4 + for (int i_ind = 0; i_ind < 4; i_ind++) { + erase_type_inst_arr[i_ind] = 0xff; //0xFF default for unsupported type + erase_type_size_arr[i_ind] = local_math_power(2, + basic_param_table_ptr[SPIF_BASIC_PARAM_ERASE_TYPE_1_SIZE_BYTE + 2 * i_ind]); // Size given as 2^N + tr_info("DEBUG: Erase Type(A) %d - Inst: 0x%xh, Size: %d", (i_ind + 1), erase_type_inst_arr[i_ind], + erase_type_size_arr[i_ind]); + if (erase_type_size_arr[i_ind] > 1) { + // if size==1 type is not supported + erase_type_inst_arr[i_ind] = basic_param_table_ptr[SPIF_BASIC_PARAM_ERASE_TYPE_1_BYTE + 2 * i_ind]; + + if ((erase_type_size_arr[i_ind] < _min_common_erase_size) || (_min_common_erase_size == 0) ) { + //Set default minimal common erase for singal region + _min_common_erase_size = erase_type_size_arr[i_ind]; + } + + // SFDP standard requires 4K Erase type to exist and its instruction to be identical to legacy field erase instruction + if (erase_type_size_arr[i_ind] == 4096) { + found_4Kerase_type = true; + if (erase4k_inst != erase_type_inst_arr[i_ind]) { + //Verify 4KErase Type is identical to Legacy 4K erase type specified in Byte 1 of Param Table + erase4k_inst = erase_type_inst_arr[i_ind]; + tr_warning("WARNING: _detectEraseTypesInstAndSize - Default 4K erase Inst is different than erase type Inst for 4K"); + + } + } + _region_erase_types_bitfield[0] |= bitfield; // If there's no region map, set region "0" types bitfield as defualt; + } + + tr_info("INFO: Erase Type %d - Inst: 0x%xh, Size: %d", (i_ind + 1), erase_type_inst_arr[i_ind], + erase_type_size_arr[i_ind]); + bitfield = bitfield << 1; + } + } + + if (false == found_4Kerase_type) { + tr_warning("WARNING: Couldn't find Erase Type for 4KB size"); + } + return 0; +} + +int SPIFBlockDevice::_sfdp_detect_best_bus_read_mode(uint8_t *basic_param_table_ptr, int basic_param_table_size, int& read_inst) +{ + do { + + // TBD - SPIF Dual Read Modes Require SPI driver support + /* + uint8_t examined_byte; + + if (basic_param_table_size > SPIF_BASIC_PARAM_TABLE_QPI_READ_SUPPORT_BYTE) { + examined_byte = basic_param_table_ptr[SPIF_BASIC_PARAM_TABLE_QPI_READ_SUPPORT_BYTE]; + if (examined_byte & 0x01) { + // Fast Read 2-2-2 Supported + read_inst = basic_param_table_ptr[SPIF_BASIC_PARAM_TABLE_222_READ_INST_BYTE]; + _read_dummy_and_mode_cycles = (basic_param_table_ptr[SPIF_BASIC_PARAM_TABLE_222_READ_INST_BYTE - 1] >> 5) + + (basic_param_table_ptr[SPIF_BASIC_PARAM_TABLE_222_READ_INST_BYTE - 1] & 0x1F); + tr_info("\nDEBUG: Read Bus Mode set to 2-2-2, Instruction: 0x%xh", read_inst); + break; + } + } + examined_byte = basic_param_table_ptr[SPIF_BASIC_PARAM_TABLE_FAST_READ_SUPPORT_BYTE]; + if (examined_byte & 0x20) { + // Fast Read 1-2-2 Supported + read_inst = basic_param_table_ptr[SPIF_BASIC_PARAM_TABLE_122_READ_INST_BYTE]; + _read_dummy_and_mode_cycles = (basic_param_table_ptr[SPIF_BASIC_PARAM_TABLE_122_READ_INST_BYTE - 1] >> 5) + + (basic_param_table_ptr[SPIF_BASIC_PARAM_TABLE_122_READ_INST_BYTE - 1] & 0x1F); + tr_debug("\nDEBUG: Read Bus Mode set to 1-2-2, Instruction: 0x%xh", read_inst); + break; + } + if (examined_byte & 0x01) { + // Fast Read 1-1-2 Supported + read_inst = basic_param_table_ptr[SPIF_BASIC_PARAM_TABLE_112_READ_INST_BYTE]; + _read_dummy_and_mode_cycles = (basic_param_table_ptr[SPIF_BASIC_PARAM_TABLE_112_READ_INST_BYTE - 1] >> 5) + + (basic_param_table_ptr[SPIF_BASIC_PARAM_TABLE_112_READ_INST_BYTE - 1] & 0x1F); + tr_debug("\nDEBUG: Read Bus Mode set to 1-1-2, Instruction: 0x%xh", _read_instruction); + break; + } + */ + _read_dummy_and_mode_cycles = 0; + tr_debug("\nDEBUG: Read Bus Mode set to 1-1-1, Instruction: 0x%xh", read_inst); + } while (false); + + return 0; +} + +int SPIFBlockDevice::_reset_flash_mem() +{ + // Perform Soft Reset of the Device prior to initialization + int status = 0; + char status_value[2] = {0}; + tr_info("INFO: _reset_flash_mem:\n"); + //Read the Status Register from device + if (SPIF_BD_ERROR_OK == _spi_send_general_command(SPIF_RDSR, SPI_NO_ADDRESS_COMMAND, NULL, 0, status_value, 1) ) { + // store received values in status_value + tr_debug("DEBUG: Reading Status Register Success: value = 0x%x\n", (int)status_value[0]); + } else { + tr_debug("ERROR: Reading Status Register failed\n"); + status = -1; + } + + if (0 == status) { + //Send Reset Enable + if (SPIF_BD_ERROR_OK == _spi_send_general_command(SPIF_RSTEN, SPI_NO_ADDRESS_COMMAND, NULL, 0, NULL, 0) ) { + // store received values in status_value + tr_debug("DEBUG: Sending RSTEN Success\n"); + } else { + tr_error("ERROR: Sending RSTEN failed\n"); + status = -1; + } + + if (0 == status) { + //Send Reset + if (SPIF_BD_ERROR_OK == _spi_send_general_command(SPIF_RST, SPI_NO_ADDRESS_COMMAND, NULL, 0, NULL, 0)) { + // store received values in status_value + tr_debug("DEBUG: Sending RST Success\n"); + } else { + tr_error("ERROR: Sending RST failed\n"); + status = -1; + } + _is_mem_ready(); + } + } + + return status; +} + +bool SPIFBlockDevice::_is_mem_ready() +{ + // Check Status Register Busy Bit to Verify the Device isn't Busy + char status_value[2]; + int retries = 0; + bool mem_ready = true; + + do { + wait_ms(1); + retries++; + //Read the Status Register from device + if (SPIF_BD_ERROR_OK != _spi_send_general_command(SPIF_RDSR, SPI_NO_ADDRESS_COMMAND, NULL, 0, status_value, + 1)) { // store received values in status_value + tr_error("ERROR: Reading Status Register failed\n"); + } + } while ( (status_value[0] & SPIF_STATUS_BIT_WIP) != 0 && retries < IS_MEM_READY_MAX_RETRIES ); + + if ((status_value[0] & SPIF_STATUS_BIT_WIP) != 0) { + tr_error("ERROR: _is_mem_ready FALSE\n"); + mem_ready = false; + } + return mem_ready; +} + +int SPIFBlockDevice::_set_write_enable() +{ + // Check Status Register Busy Bit to Verify the Device isn't Busy + char status_value[2]; + int status = -1; + + do { + if (SPIF_BD_ERROR_OK != _spi_send_general_command(SPIF_WREN, SPI_NO_ADDRESS_COMMAND, NULL, 0, NULL, 0)) { + tr_error("ERROR:Sending WREN command FAILED\n"); + break; + } + + if ( false == _is_mem_ready()) { + tr_error("ERROR: Device not ready, write failed"); + break; + } + + memset(status_value, 0, 2); + if (SPIF_BD_ERROR_OK != _spi_send_general_command(SPIF_RDSR, SPI_NO_ADDRESS_COMMAND, NULL, 0, status_value, + 1)) { // store received values in status_value + tr_error("ERROR: Reading Status Register failed\n"); + break; + } + + if ((status_value[0] & SPIF_STATUS_BIT_WEL) == 0) { + tr_error("ERROR: _set_write_enable failed\n"); + break; + } + status = 0; + } while (false); + return status; +} + +/*********************************************/ +/************* Utility Functions *************/ +/*********************************************/ +int SPIFBlockDevice::_utils_find_addr_region(bd_size_t offset) +{ + //Find the region to which the given offset belong to + if ((offset > _device_size_bytes) || (_regions_count == 0)) { + return -1; + } + + if (_regions_count == 1) { + return 0; + } + + for (int i_ind = _regions_count - 2; i_ind >= 0; i_ind--) { + + if (offset > _region_high_boundary[i_ind]) { + return (i_ind + 1); + } + } + return -1; + +} + +int SPIFBlockDevice::_utils_iterate_next_largest_erase_type(uint8_t& bitfield, int size, int offset, int boundry) +{ + // Iterate on all supported Erase Types of the Region to which the offset belong to. + // Iterates from highest type to lowest + uint8_t type_mask = ERASE_BITMASK_TYPE4; + int i_ind = 0; + int largest_erase_type = 0; + for (i_ind = 3; i_ind >= 0; i_ind--) { + if (bitfield & type_mask) { + largest_erase_type = i_ind; + if ( (size > _erase_type_size_arr[largest_erase_type]) && + ((boundry - offset) > _erase_type_size_arr[largest_erase_type]) ) { + break; + } else { + bitfield &= ~type_mask; + } + } + type_mask = type_mask >> 1; + } + + if (i_ind == 4) { + tr_error("ERROR: no erase type was found for current region addr"); + } + return largest_erase_type; + +} + +/*********************************************/ +/************** Local Functions **************/ +/*********************************************/ +static unsigned int local_math_power(int base, int exp) +{ + // Integer X^Y function, used to calculate size fields given in 2^N format + int result = 1; + while (exp) { + result *= base; + exp--; + } + return result; +} + +} //namespace mbed + + diff --git a/SPIFBlockDevice.h b/SPIFBlockDevice.h index 6916b1c3eb..2acee0a6a1 100644 --- a/SPIFBlockDevice.h +++ b/SPIFBlockDevice.h @@ -1,5 +1,5 @@ /* mbed Microcontroller Library - * Copyright (c) 2016 ARM Limited + * Copyright (c) 2018 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,20 +16,21 @@ #ifndef MBED_SPIF_BLOCK_DEVICE_H #define MBED_SPIF_BLOCK_DEVICE_H +#include #include #include "BlockDevice.h" namespace mbed { -/** Enum qspif standard error codes +/** Enum spif standard error codes * - * @enum qspif_bd_error + * @enum qpif_bd_error */ -enum qspif_bd_error { +enum spif_bd_error { SPIF_BD_ERROR_OK = 0, /*!< no error */ SPIF_BD_ERROR_DEVICE_ERROR = BD_ERROR_DEVICE_ERROR, /*!< device specific error -4001 */ SPIF_BD_ERROR_PARSING_FAILED = -4002, /* SFDP Parsing failed */ - SPIF_BD_ERROR_READY_FAILED = -4003, /* Wait for Mem Ready failed */ + SPIF_BD_ERROR_READY_FAILED = -4003, /* Wait for Mem Ready failed */ SPIF_BD_ERROR_WREN_FAILED = -4004, /* Write Enable Failed */ }; @@ -86,22 +87,30 @@ public: /** Initialize a block device * - * @return 0 on success or a negative error code on failure + * @return SPIF_BD_ERROR_OK(0) - success + * SPIF_BD_ERROR_DEVICE_ERROR - device driver transaction failed + * SPIF_BD_ERROR_READY_FAILED - Waiting for Memory ready failed or timedout + * SPIF_BD_ERROR_PARSING_FAILED - unexpected format or values in one of the SFDP tables */ virtual int init(); /** Deinitialize a block device * - * @return 0 on success or a negative error code on failure + * @return SPIF_BD_ERROR_OK(0) - success */ virtual int deinit(); + /** Desctruct SPIFBlockDevie + */ + ~SPIFBlockDevice() {deinit();} + /** Read blocks from a block device * * @param buffer Buffer to write blocks to * @param addr Address of block to begin reading from * @param size Size to read in bytes, must be a multiple of read block size - * @return 0 on success, negative error code on failure + * @return SPIF_BD_ERROR_OK(0) - success + * SPIF_BD_ERROR_DEVICE_ERROR - device driver transaction failed */ virtual int read(void *buffer, bd_addr_t addr, bd_size_t size); @@ -112,7 +121,10 @@ public: * @param buffer Buffer of data to write to blocks * @param addr Address of block to begin writing to * @param size Size to write in bytes, must be a multiple of program block size - * @return 0 on success, negative error code on failure + * @return SPIF_BD_ERROR_OK(0) - success + * SPIF_BD_ERROR_DEVICE_ERROR - device driver transaction failed + * SPIF_BD_ERROR_READY_FAILED - Waiting for Memory ready failed or timed out + * SPIF_BD_ERROR_WREN_FAILED - Write Enable failed */ virtual int program(const void *buffer, bd_addr_t addr, bd_size_t size); @@ -122,7 +134,10 @@ public: * * @param addr Address of block to begin erasing * @param size Size to erase in bytes, must be a multiple of erase block size - * @return 0 on success, negative error code on failure + * @return SPIF_BD_ERROR_OK(0) - success + * SPIF_BD_ERROR_DEVICE_ERROR - device driver transaction failed + * SPIF_BD_ERROR_READY_FAILED - Waiting for Memory ready failed or timed out + * SPIF_BD_ERROR_WREN_FAILED - Write Enable failed */ virtual int erase(bd_addr_t addr, bd_size_t size); @@ -146,14 +161,6 @@ public: */ virtual bd_size_t get_erase_size() const; - /** Get the size of an erasable block given address - * - * @param addr Address within the erasable block - * @return Size of an erasable block in bytes - * @note Must be a multiple of the program size - */ - virtual bd_size_t get_erase_size(bd_addr_t addr) const; - /** Get the size of minimal eraseable sector size of given address * * @param addr Any address within block queried for erase sector size (can be any address within flash size offset) @@ -181,6 +188,9 @@ public: private: + // Internal functions + + /****************************************/ /* SFDP Detection and Parsing Functions */ /****************************************/ // Parse SFDP Headers and retrieve Basic Param and Sector Map Tables (if exist) @@ -194,16 +204,16 @@ private: int _sfdp_parse_sector_map_table(uint32_t sector_map_table_addr, size_t sector_map_table_size); // Detect fastest read Bus mode supported by device - int _sfdp_detect_best_bus_read_mode(uint8_t *basic_param_table_ptr, bool& set_quad_enable, bool& is_qpi_mode, - unsigned int& read_inst); + int _sfdp_detect_best_bus_read_mode(uint8_t *basic_param_table_ptr, int basic_param_table_size, int& read_inst); // Set Page size for program - int _sfdp_detect_page_size(uint8_t *basic_param_table_ptr); + unsigned int _sfdp_detect_page_size(uint8_t *basic_param_table_ptr, int basic_param_table_size); // Detect all supported erase types - int _sfdp_detect_erase_types_inst_and_size(uint8_t *basic_param_table_ptr, unsigned int& erase4k_inst, - unsigned int *erase_type_inst_arr, unsigned int *erase_type_size_arr); + int _sfdp_detect_erase_types_inst_and_size(uint8_t *basic_param_table_ptr, int basic_param_table_size, int& erase4k_inst, + int *erase_type_inst_arr, unsigned int *erase_type_size_arr); + /***********************/ /* Utilities Functions */ /***********************/ // Find the region to which the given offset belong to @@ -213,62 +223,74 @@ private: // Iterates from highest type to lowest int _utils_iterate_next_largest_erase_type(uint8_t& bitfield, int size, int offset, int boundry); - // Internal functions - int _wren(); - int _sync(); - void _cmdread(uint8_t op, uint32_t addrc, uint32_t retc, - uint32_t addr, uint8_t *rets); - void _cmdwrite(uint8_t op, uint32_t addrc, uint32_t argc, - uint32_t addr, const uint8_t *args); + /********************************/ + /* Calls to SPI Driver APIs */ + /********************************/ + // Send Program => Write command to Driver + spif_bd_error _spi_send_program_command(int prog_inst, const void *buffer, bd_addr_t addr, bd_size_t size); + + // Send Read command to Driver + //spif_bd_error _spi_send_read_command(uint8_t read_inst, void *buffer, bd_addr_t addr, bd_size_t size); + spif_bd_error _spi_send_read_command(int read_inst, uint8_t *buffer, bd_addr_t addr, bd_size_t size); + + // Send Erase Instruction using command_transfer command to Driver + spif_bd_error _spi_send_erase_command(int erase_inst, bd_addr_t addr, bd_size_t size); + + // Send Generic command_transfer command to Driver + spif_bd_error _spi_send_general_command(int instruction, bd_addr_t addr, char *tx_buffer, + size_t tx_length, char *rx_buffer, size_t rx_length); + + // Send set_frequency command to Driver + spif_bd_error _spi_set_frequency(int freq); + /********************************/ + + // Soft Reset Flash Memory + int _reset_flash_mem(); + + // Configure Write Enable in Status Register + int _set_write_enable(); + + // Wait on status register until write not-in-progress + bool _is_mem_ready(); private: // Master side hardware SPI _spi; + // Enable CS control (low/high) for SPI driver operatios DigitalOut _cs; - // Device configuration discovered through sfdp - bd_size_t _size; - - bool _is_initialized; - uint32_t _init_ref_count; - - bool _is_initialized; - - // Mutex is used to protect Flash device for some QSPI Driver commands that must be done sequentially with no other commands in between + // Mutex is used to protect Flash device for some SPI Driver commands that must be done sequentially with no other commands in between // e.g. (1)Set Write Enable, (2)Program, (3)Wait Memory Ready - PlatformMutex _mutex; + static SingletonPtr _mutex; // Command Instructions - unsigned int _read_instruction; - unsigned int _prog_instruction; - unsigned int _erase_instruction; - unsigned int _erase4k_inst; // Legacy 4K erase instruction (default 0x20h) + int _read_instruction; + int _prog_instruction; + int _erase_instruction; + int _erase4k_inst; // Legacy 4K erase instruction (default 0x20h) // Up To 4 Erase Types are supported by SFDP (each with its own command Instruction and Size) - unsigned int _erase_type_inst_arr[MAX_NUM_OF_ERASE_TYPES]; + int _erase_type_inst_arr[MAX_NUM_OF_ERASE_TYPES]; unsigned int _erase_type_size_arr[MAX_NUM_OF_ERASE_TYPES]; // Sector Regions Map int _regions_count; //number of regions - int _region_size_bytes[QSPIF_MAX_REGIONS]; //regions size in bytes - bd_size_t _region_high_boundary[QSPIF_MAX_REGIONS]; //region high address offset boundary + int _region_size_bytes[SPIF_MAX_REGIONS]; //regions size in bytes + bd_size_t _region_high_boundary[SPIF_MAX_REGIONS]; //region high address offset boundary //Each Region can support a bit combination of any of the 4 Erase Types - uint8_t _region_erase_types_bitfield[QSPIF_MAX_REGIONS]; - int _min_common_erase_size; // minimal common erase size for all regions (0 if none exists) + uint8_t _region_erase_types_bitfield[SPIF_MAX_REGIONS]; + unsigned int _min_common_erase_size; // minimal common erase size for all regions (0 if none exists) - int _page_size_bytes; // Page size - 256 Bytes default + unsigned int _page_size_bytes; // Page size - 256 Bytes default bd_size_t _device_size_bytes; - // Bus speed configuration - qspi_bus_width_t _inst_width; //Bus width for Instruction phase - qspi_bus_width_t _address_width; //Bus width for Address phase - qspi_address_size_t _address_size; // number of bytes for address - qspi_bus_width_t _data_width; //Bus width for Data phase - int _dummy_and_mode_cycles; // Number of Dummy and Mode Bits required by Current Bus Mode - - - + // Bus configuration + unsigned int _address_size; // number of bytes for address + unsigned int _read_dummy_and_mode_cycles; // Number of Dummy and Mode Bits required by Read Bus Mode + unsigned int _write_dummy_and_mode_cycles; // Number of Dummy and Mode Bits required by Write Bus Mode + unsigned int _dummy_and_mode_cycles; // Number of Dummy and Mode Bits required by Current Bus Mode + bool _is_initialized; }; } //namespace mbed From 4cd9132db82b78ec63fa4032e6ee2761dd10ffd4 Mon Sep 17 00:00:00 2001 From: Offir Kochalsky Date: Thu, 16 Aug 2018 18:45:48 +0300 Subject: [PATCH 21/29] Added Ref Count --- SPIFBlockDevice.cpp | 360 +++++++++++++++++++++++--------------------- SPIFBlockDevice.h | 25 +-- 2 files changed, 203 insertions(+), 182 deletions(-) diff --git a/SPIFBlockDevice.cpp b/SPIFBlockDevice.cpp index fde6e12c8b..faacb5adc8 100644 --- a/SPIFBlockDevice.cpp +++ b/SPIFBlockDevice.cpp @@ -100,7 +100,7 @@ static unsigned int local_math_power(int base, int exp); //*********************** SPIFBlockDevice::SPIFBlockDevice( PinName mosi, PinName miso, PinName sclk, PinName csel, int freq) - : _spi(mosi, miso, sclk), _cs(csel), _device_size_bytes(0), _is_initialized(false) + : _spi(mosi, miso, sclk), _cs(csel), _device_size_bytes(0), _is_initialized(false), _init_ref_count(0) { _address_size = SPIF_ADDR_SIZE_3_BYTES; // Initial SFDP read tables are read with 8 dummy cycles @@ -117,7 +117,7 @@ SPIFBlockDevice::SPIFBlockDevice( tr_error("ERROR: SPI Set Frequency Failed"); } - _cs = 1; + _cs = 1; } int SPIFBlockDevice::init() @@ -132,7 +132,14 @@ int SPIFBlockDevice::init() spif_bd_error spi_status = SPIF_BD_ERROR_OK; _mutex->lock(); - if (_is_initialized == true) { + + if (!_is_initialized) { + _init_ref_count = 0; + } + + _init_ref_count++; + + if (_init_ref_count != 1) { goto exit_point; } @@ -214,18 +221,29 @@ exit_point: int SPIFBlockDevice::deinit() { + spif_bd_error status = SPIF_BD_ERROR_OK; + _mutex->lock(); - if (_is_initialized == false) { - _mutex->unlock(); - return SPIF_BD_ERROR_OK; + + if (!_is_initialized) { + _init_ref_count = 0; + goto exit_point; + } + + _init_ref_count--; + + if (_init_ref_count) { + goto exit_point; } // Disable Device for Writing - spif_bd_error status = _spi_send_general_command(SPIF_WRDI, SPI_NO_ADDRESS_COMMAND, NULL, 0, NULL, 0); + status = _spi_send_general_command(SPIF_WRDI, SPI_NO_ADDRESS_COMMAND, NULL, 0, NULL, 0); if (status != SPIF_BD_ERROR_OK) { tr_error("ERROR: Write Disable failed"); } _is_initialized = false; + +exit_point: _mutex->unlock(); return status; @@ -251,52 +269,51 @@ int SPIFBlockDevice::read(void *buffer, bd_addr_t addr, bd_size_t size) _mutex->unlock(); return status; - } - + int SPIFBlockDevice::program(const void *buffer, bd_addr_t addr, bd_size_t size) { if (!_is_initialized) { return BD_ERROR_DEVICE_ERROR; } - bool program_failed = false; - int status = SPIF_BD_ERROR_OK; - uint32_t offset = 0; - uint32_t chunk = 0; + bool program_failed = false; + int status = SPIF_BD_ERROR_OK; + uint32_t offset = 0; + uint32_t chunk = 0; - tr_debug("DEBUG: program - Buff: 0x%x, addr: %llu, size: %llu", buffer, addr, size); + tr_debug("DEBUG: program - Buff: 0x%x, addr: %llu, size: %llu", buffer, addr, size); - while (size > 0) { + while (size > 0) { - // Write on _page_size_bytes boundaries (Default 256 bytes a page) - offset = addr % _page_size_bytes; - chunk = (offset + size < _page_size_bytes) ? size : (_page_size_bytes - offset); + // Write on _page_size_bytes boundaries (Default 256 bytes a page) + offset = addr % _page_size_bytes; + chunk = (offset + size < _page_size_bytes) ? size : (_page_size_bytes - offset); - _mutex->lock(); + _mutex->lock(); - //Send WREN - if (_set_write_enable() != 0) { - tr_error("ERROR: Write Enabe failed\n"); - program_failed = true; - status = SPIF_BD_ERROR_WREN_FAILED; - goto exit_point; - } + //Send WREN + if (_set_write_enable() != 0) { + tr_error("ERROR: Write Enabe failed\n"); + program_failed = true; + status = SPIF_BD_ERROR_WREN_FAILED; + goto exit_point; + } - _spi_send_program_command(_prog_instruction, buffer, addr, chunk); + _spi_send_program_command(_prog_instruction, buffer, addr, chunk); - buffer = static_cast(buffer) + chunk; - addr += chunk; - size -= chunk; + buffer = static_cast(buffer) + chunk; + addr += chunk; + size -= chunk; - if ( false == _is_mem_ready()) { - tr_error("ERROR: Device not ready after write, failed\n"); - program_failed = true; - status = SPIF_BD_ERROR_READY_FAILED; - goto exit_point; - } - _mutex->unlock(); - } + if ( false == _is_mem_ready()) { + tr_error("ERROR: Device not ready after write, failed\n"); + program_failed = true; + status = SPIF_BD_ERROR_READY_FAILED; + goto exit_point; + } + _mutex->unlock(); + } exit_point: if (program_failed) { @@ -445,116 +462,117 @@ int SPIFBlockDevice::get_erase_value() const /***************************************************/ spif_bd_error SPIFBlockDevice::_spi_set_frequency(int freq) { - _spi.frequency(freq); + _spi.frequency(freq); return SPIF_BD_ERROR_OK; } spif_bd_error SPIFBlockDevice::_spi_send_read_command(int read_inst, uint8_t *buffer, bd_addr_t addr, bd_size_t size) { - uint32_t dummy_bytes = _dummy_and_mode_cycles / 8; - int dummy_byte = 0; + uint32_t dummy_bytes = _dummy_and_mode_cycles / 8; + int dummy_byte = 0; - // csel must go low for the entire command (Inst, Address and Data) - _cs = 0; + // csel must go low for the entire command (Inst, Address and Data) + _cs = 0; - // Write 1 byte Instruction - _spi.write(read_inst); + // Write 1 byte Instruction + _spi.write(read_inst); - // Write Address (can be either 3 or 4 bytes long) - for (int address_shift = ((_address_size-1) * 8); address_shift >= 0; address_shift -= 8) { - _spi.write((addr >> address_shift) & 0xFF); - } + // Write Address (can be either 3 or 4 bytes long) + for (int address_shift = ((_address_size - 1) * 8); address_shift >= 0; address_shift -= 8) { + _spi.write((addr >> address_shift) & 0xFF); + } - // Write Dummy Cycles Bytes - for (uint32_t i = 0; i < dummy_bytes; i++) { - _spi.write(dummy_byte); - } + // Write Dummy Cycles Bytes + for (uint32_t i = 0; i < dummy_bytes; i++) { + _spi.write(dummy_byte); + } - // Read Data - for (bd_size_t i = 0; i < size; i++) { - buffer[i] = _spi.write(0); - } + // Read Data + for (bd_size_t i = 0; i < size; i++) { + buffer[i] = _spi.write(0); + } - // csel back to high - _cs = 1; - return SPIF_BD_ERROR_OK; + // csel back to high + _cs = 1; + return SPIF_BD_ERROR_OK; } -spif_bd_error SPIFBlockDevice::_spi_send_program_command(int prog_inst, const void *buffer, bd_addr_t addr, bd_size_t size) +spif_bd_error SPIFBlockDevice::_spi_send_program_command(int prog_inst, const void *buffer, bd_addr_t addr, + bd_size_t size) { // Send Program (write) command to device driver - uint32_t dummy_bytes = _dummy_and_mode_cycles / 8; - int dummy_byte = 0; - uint8_t *data = (uint8_t *)buffer; + uint32_t dummy_bytes = _dummy_and_mode_cycles / 8; + int dummy_byte = 0; + uint8_t *data = (uint8_t *)buffer; - // csel must go low for the entire command (Inst, Address and Data) - _cs = 0; + // csel must go low for the entire command (Inst, Address and Data) + _cs = 0; - // Write 1 byte Instruction - _spi.write(prog_inst); + // Write 1 byte Instruction + _spi.write(prog_inst); - // Write Address (can be either 3 or 4 bytes long) - for (int address_shift = ((_address_size-1) * 8); address_shift >= 0; address_shift -= 8) { - _spi.write((addr >> address_shift) & 0xFF); - } + // Write Address (can be either 3 or 4 bytes long) + for (int address_shift = ((_address_size - 1) * 8); address_shift >= 0; address_shift -= 8) { + _spi.write((addr >> address_shift) & 0xFF); + } - // Write Dummy Cycles Bytes - for (uint32_t i = 0; i < dummy_bytes; i++) { - _spi.write(dummy_byte); - } + // Write Dummy Cycles Bytes + for (uint32_t i = 0; i < dummy_bytes; i++) { + _spi.write(dummy_byte); + } - // Write Data - for (bd_size_t i = 0; i < size; i++) { - _spi.write(data[i]); - } + // Write Data + for (bd_size_t i = 0; i < size; i++) { + _spi.write(data[i]); + } - // csel back to high - _cs = 1; + // csel back to high + _cs = 1; return SPIF_BD_ERROR_OK; } spif_bd_error SPIFBlockDevice::_spi_send_erase_command(int erase_inst, bd_addr_t addr, bd_size_t size) { - tr_info("INFO: Erase Inst: 0x%xh, addr: %llu, size: %llu", erase_inst, addr, size); - addr = (((int)addr) & 0x00FFF000); - _spi_send_general_command(erase_inst, addr, NULL, 0, NULL, 0); - return SPIF_BD_ERROR_OK; + tr_info("INFO: Erase Inst: 0x%xh, addr: %llu, size: %llu", erase_inst, addr, size); + addr = (((int)addr) & 0x00FFF000); + _spi_send_general_command(erase_inst, addr, NULL, 0, NULL, 0); + return SPIF_BD_ERROR_OK; } spif_bd_error SPIFBlockDevice::_spi_send_general_command(int instruction, bd_addr_t addr, char *tx_buffer, size_t tx_length, char *rx_buffer, size_t rx_length) { // Send a general command Instruction to driver - uint32_t dummy_bytes = _dummy_and_mode_cycles / 8; - uint8_t dummy_byte = 0x00; + uint32_t dummy_bytes = _dummy_and_mode_cycles / 8; + uint8_t dummy_byte = 0x00; - // csel must go low for the entire command (Inst, Address and Data) - _cs = 0; + // csel must go low for the entire command (Inst, Address and Data) + _cs = 0; - // Write 1 byte Instruction - _spi.write(instruction); + // Write 1 byte Instruction + _spi.write(instruction); - // Reading SPI Bus registers does not require Flash Address - if (addr != SPI_NO_ADDRESS_COMMAND) { - // Write Address (can be either 3 or 4 bytes long) - for (int address_shift = ((_address_size-1) * 8); address_shift >= 0; address_shift -= 8) { - _spi.write((addr >> address_shift) & 0xFF); - } + // Reading SPI Bus registers does not require Flash Address + if (addr != SPI_NO_ADDRESS_COMMAND) { + // Write Address (can be either 3 or 4 bytes long) + for (int address_shift = ((_address_size - 1) * 8); address_shift >= 0; address_shift -= 8) { + _spi.write((addr >> address_shift) & 0xFF); + } - // Write Dummy Cycles Bytes - for (uint32_t i = 0; i < dummy_bytes; i++) { - _spi.write(dummy_byte); - } - } + // Write Dummy Cycles Bytes + for (uint32_t i = 0; i < dummy_bytes; i++) { + _spi.write(dummy_byte); + } + } - // Read/Write Data - _spi.write(tx_buffer, (int)tx_length, rx_buffer, (int)rx_length); + // Read/Write Data + _spi.write(tx_buffer, (int)tx_length, rx_buffer, (int)rx_length); - // csel back to high - _cs = 1; + // csel back to high + _cs = 1; - return SPIF_BD_ERROR_OK; + return SPIF_BD_ERROR_OK; } /*********************************************************/ @@ -654,7 +672,8 @@ int SPIFBlockDevice::_sfdp_parse_basic_param_table(uint32_t basic_table_addr, si _page_size_bytes = _sfdp_detect_page_size(param_table, basic_table_size); // Detect and Set Erase Types - _sfdp_detect_erase_types_inst_and_size(param_table, basic_table_size, _erase4k_inst, _erase_type_inst_arr, _erase_type_size_arr); + _sfdp_detect_erase_types_inst_and_size(param_table, basic_table_size, _erase4k_inst, _erase_type_inst_arr, + _erase_type_size_arr); _erase_instruction = _erase4k_inst; // Detect and Set fastest Bus mode (default 1-1-1) @@ -673,8 +692,8 @@ int SPIFBlockDevice::_sfdp_parse_sfdp_headers(uint32_t& basic_table_addr, size_t // Set 1-1-1 bus mode for SFDP header parsing // Initial SFDP read tables are read with 8 dummy cycles - _read_dummy_and_mode_cycles = 8; - _dummy_and_mode_cycles = 8; + _read_dummy_and_mode_cycles = 8; + _dummy_and_mode_cycles = 8; spif_bd_error status = _spi_send_read_command(SPIF_SFDP, sfdp_header, addr /*address*/, data_length); if (status != SPIF_BD_ERROR_OK) { @@ -737,21 +756,21 @@ int SPIFBlockDevice::_sfdp_parse_sfdp_headers(uint32_t& basic_table_addr, size_t unsigned int SPIFBlockDevice::_sfdp_detect_page_size(uint8_t *basic_param_table_ptr, int basic_param_table_size) { - unsigned int page_size = SPIF_DEFAULT_PAGE_SIZE; + unsigned int page_size = SPIF_DEFAULT_PAGE_SIZE; - if (basic_param_table_size > SPIF_BASIC_PARAM_TABLE_PAGE_SIZE_BYTE) { - // Page Size is specified by 4 Bits (N), calculated by 2^N - int page_to_power_size = ( (int)basic_param_table_ptr[SPIF_BASIC_PARAM_TABLE_PAGE_SIZE_BYTE]) >> 4; - page_size = local_math_power(2, page_to_power_size); - tr_debug("DEBUG: Detected Page Size: %d", page_size); - } - else { - tr_debug("DEBUG: Using Default Page Size: %d", page_size); - } + if (basic_param_table_size > SPIF_BASIC_PARAM_TABLE_PAGE_SIZE_BYTE) { + // Page Size is specified by 4 Bits (N), calculated by 2^N + int page_to_power_size = ( (int)basic_param_table_ptr[SPIF_BASIC_PARAM_TABLE_PAGE_SIZE_BYTE]) >> 4; + page_size = local_math_power(2, page_to_power_size); + tr_debug("DEBUG: Detected Page Size: %d", page_size); + } else { + tr_debug("DEBUG: Using Default Page Size: %d", page_size); + } return page_size; } -int SPIFBlockDevice::_sfdp_detect_erase_types_inst_and_size(uint8_t *basic_param_table_ptr, int basic_param_table_size, int& erase4k_inst, +int SPIFBlockDevice::_sfdp_detect_erase_types_inst_and_size(uint8_t *basic_param_table_ptr, int basic_param_table_size, + int& erase4k_inst, int *erase_type_inst_arr, unsigned int *erase_type_size_arr) { erase4k_inst = 0xff; @@ -762,39 +781,39 @@ int SPIFBlockDevice::_sfdp_detect_erase_types_inst_and_size(uint8_t *basic_param erase4k_inst = basic_param_table_ptr[SPIF_BASIC_PARAM_4K_ERASE_TYPE_BYTE]; if (basic_param_table_size > SPIF_BASIC_PARAM_ERASE_TYPE_1_SIZE_BYTE) { - // Loop Erase Types 1-4 - for (int i_ind = 0; i_ind < 4; i_ind++) { - erase_type_inst_arr[i_ind] = 0xff; //0xFF default for unsupported type - erase_type_size_arr[i_ind] = local_math_power(2, - basic_param_table_ptr[SPIF_BASIC_PARAM_ERASE_TYPE_1_SIZE_BYTE + 2 * i_ind]); // Size given as 2^N - tr_info("DEBUG: Erase Type(A) %d - Inst: 0x%xh, Size: %d", (i_ind + 1), erase_type_inst_arr[i_ind], - erase_type_size_arr[i_ind]); - if (erase_type_size_arr[i_ind] > 1) { - // if size==1 type is not supported - erase_type_inst_arr[i_ind] = basic_param_table_ptr[SPIF_BASIC_PARAM_ERASE_TYPE_1_BYTE + 2 * i_ind]; + // Loop Erase Types 1-4 + for (int i_ind = 0; i_ind < 4; i_ind++) { + erase_type_inst_arr[i_ind] = 0xff; //0xFF default for unsupported type + erase_type_size_arr[i_ind] = local_math_power(2, + basic_param_table_ptr[SPIF_BASIC_PARAM_ERASE_TYPE_1_SIZE_BYTE + 2 * i_ind]); // Size given as 2^N + tr_info("DEBUG: Erase Type(A) %d - Inst: 0x%xh, Size: %d", (i_ind + 1), erase_type_inst_arr[i_ind], + erase_type_size_arr[i_ind]); + if (erase_type_size_arr[i_ind] > 1) { + // if size==1 type is not supported + erase_type_inst_arr[i_ind] = basic_param_table_ptr[SPIF_BASIC_PARAM_ERASE_TYPE_1_BYTE + 2 * i_ind]; - if ((erase_type_size_arr[i_ind] < _min_common_erase_size) || (_min_common_erase_size == 0) ) { - //Set default minimal common erase for singal region - _min_common_erase_size = erase_type_size_arr[i_ind]; - } + if ((erase_type_size_arr[i_ind] < _min_common_erase_size) || (_min_common_erase_size == 0) ) { + //Set default minimal common erase for singal region + _min_common_erase_size = erase_type_size_arr[i_ind]; + } - // SFDP standard requires 4K Erase type to exist and its instruction to be identical to legacy field erase instruction - if (erase_type_size_arr[i_ind] == 4096) { - found_4Kerase_type = true; - if (erase4k_inst != erase_type_inst_arr[i_ind]) { - //Verify 4KErase Type is identical to Legacy 4K erase type specified in Byte 1 of Param Table - erase4k_inst = erase_type_inst_arr[i_ind]; - tr_warning("WARNING: _detectEraseTypesInstAndSize - Default 4K erase Inst is different than erase type Inst for 4K"); + // SFDP standard requires 4K Erase type to exist and its instruction to be identical to legacy field erase instruction + if (erase_type_size_arr[i_ind] == 4096) { + found_4Kerase_type = true; + if (erase4k_inst != erase_type_inst_arr[i_ind]) { + //Verify 4KErase Type is identical to Legacy 4K erase type specified in Byte 1 of Param Table + erase4k_inst = erase_type_inst_arr[i_ind]; + tr_warning("WARNING: _detectEraseTypesInstAndSize - Default 4K erase Inst is different than erase type Inst for 4K"); - } - } - _region_erase_types_bitfield[0] |= bitfield; // If there's no region map, set region "0" types bitfield as defualt; - } + } + } + _region_erase_types_bitfield[0] |= bitfield; // If there's no region map, set region "0" types bitfield as defualt; + } - tr_info("INFO: Erase Type %d - Inst: 0x%xh, Size: %d", (i_ind + 1), erase_type_inst_arr[i_ind], - erase_type_size_arr[i_ind]); - bitfield = bitfield << 1; - } + tr_info("INFO: Erase Type %d - Inst: 0x%xh, Size: %d", (i_ind + 1), erase_type_inst_arr[i_ind], + erase_type_size_arr[i_ind]); + bitfield = bitfield << 1; + } } if (false == found_4Kerase_type) { @@ -803,24 +822,25 @@ int SPIFBlockDevice::_sfdp_detect_erase_types_inst_and_size(uint8_t *basic_param return 0; } -int SPIFBlockDevice::_sfdp_detect_best_bus_read_mode(uint8_t *basic_param_table_ptr, int basic_param_table_size, int& read_inst) +int SPIFBlockDevice::_sfdp_detect_best_bus_read_mode(uint8_t *basic_param_table_ptr, int basic_param_table_size, + int& read_inst) { do { - // TBD - SPIF Dual Read Modes Require SPI driver support - /* - uint8_t examined_byte; + // TBD - SPIF Dual Read Modes Require SPI driver support + /* + uint8_t examined_byte; - if (basic_param_table_size > SPIF_BASIC_PARAM_TABLE_QPI_READ_SUPPORT_BYTE) { - examined_byte = basic_param_table_ptr[SPIF_BASIC_PARAM_TABLE_QPI_READ_SUPPORT_BYTE]; - if (examined_byte & 0x01) { - // Fast Read 2-2-2 Supported - read_inst = basic_param_table_ptr[SPIF_BASIC_PARAM_TABLE_222_READ_INST_BYTE]; - _read_dummy_and_mode_cycles = (basic_param_table_ptr[SPIF_BASIC_PARAM_TABLE_222_READ_INST_BYTE - 1] >> 5) - + (basic_param_table_ptr[SPIF_BASIC_PARAM_TABLE_222_READ_INST_BYTE - 1] & 0x1F); - tr_info("\nDEBUG: Read Bus Mode set to 2-2-2, Instruction: 0x%xh", read_inst); - break; - } + if (basic_param_table_size > SPIF_BASIC_PARAM_TABLE_QPI_READ_SUPPORT_BYTE) { + examined_byte = basic_param_table_ptr[SPIF_BASIC_PARAM_TABLE_QPI_READ_SUPPORT_BYTE]; + if (examined_byte & 0x01) { + // Fast Read 2-2-2 Supported + read_inst = basic_param_table_ptr[SPIF_BASIC_PARAM_TABLE_222_READ_INST_BYTE]; + _read_dummy_and_mode_cycles = (basic_param_table_ptr[SPIF_BASIC_PARAM_TABLE_222_READ_INST_BYTE - 1] >> 5) + + (basic_param_table_ptr[SPIF_BASIC_PARAM_TABLE_222_READ_INST_BYTE - 1] & 0x1F); + tr_info("\nDEBUG: Read Bus Mode set to 2-2-2, Instruction: 0x%xh", read_inst); + break; + } } examined_byte = basic_param_table_ptr[SPIF_BASIC_PARAM_TABLE_FAST_READ_SUPPORT_BYTE]; if (examined_byte & 0x20) { @@ -839,8 +859,8 @@ int SPIFBlockDevice::_sfdp_detect_best_bus_read_mode(uint8_t *basic_param_table_ tr_debug("\nDEBUG: Read Bus Mode set to 1-1-2, Instruction: 0x%xh", _read_instruction); break; } - */ - _read_dummy_and_mode_cycles = 0; + */ + _read_dummy_and_mode_cycles = 0; tr_debug("\nDEBUG: Read Bus Mode set to 1-1-1, Instruction: 0x%xh", read_inst); } while (false); @@ -855,7 +875,7 @@ int SPIFBlockDevice::_reset_flash_mem() tr_info("INFO: _reset_flash_mem:\n"); //Read the Status Register from device if (SPIF_BD_ERROR_OK == _spi_send_general_command(SPIF_RDSR, SPI_NO_ADDRESS_COMMAND, NULL, 0, status_value, 1) ) { - // store received values in status_value + // store received values in status_value tr_debug("DEBUG: Reading Status Register Success: value = 0x%x\n", (int)status_value[0]); } else { tr_debug("ERROR: Reading Status Register failed\n"); @@ -865,7 +885,7 @@ int SPIFBlockDevice::_reset_flash_mem() if (0 == status) { //Send Reset Enable if (SPIF_BD_ERROR_OK == _spi_send_general_command(SPIF_RSTEN, SPI_NO_ADDRESS_COMMAND, NULL, 0, NULL, 0) ) { - // store received values in status_value + // store received values in status_value tr_debug("DEBUG: Sending RSTEN Success\n"); } else { tr_error("ERROR: Sending RSTEN failed\n"); @@ -875,7 +895,7 @@ int SPIFBlockDevice::_reset_flash_mem() if (0 == status) { //Send Reset if (SPIF_BD_ERROR_OK == _spi_send_general_command(SPIF_RST, SPI_NO_ADDRESS_COMMAND, NULL, 0, NULL, 0)) { - // store received values in status_value + // store received values in status_value tr_debug("DEBUG: Sending RST Success\n"); } else { tr_error("ERROR: Sending RST failed\n"); diff --git a/SPIFBlockDevice.h b/SPIFBlockDevice.h index 2acee0a6a1..0292082fa3 100644 --- a/SPIFBlockDevice.h +++ b/SPIFBlockDevice.h @@ -37,37 +37,37 @@ enum spif_bd_error { #define SPIF_MAX_REGIONS 10 #define MAX_NUM_OF_ERASE_TYPES 4 - + /** BlockDevice for SFDP based flash devices over SPI bus * * @code * // Here's an example using SPI flash device on K82F target * #include "mbed.h" * #include "SPIFBlockDevice.h" - * + * * // Create flash device on SPI bus with PTE5 as chip select * SPIFBlockDevice spif(PTE2, PTE4, PTE1, PTE5); - * + * * int main() { * printf("spif test\n"); - * + * * // Initialize the SPI flash device and print the memory layout * spif.init(); * printf("spif size: %llu\n", spif.size()); * printf("spif read size: %llu\n", spif.get_read_size()); * printf("spif program size: %llu\n", spif.get_program_size()); * printf("spif erase size: %llu\n", spif.get_erase_size()); - * + * * // Write "Hello World!" to the first block * char *buffer = (char*)malloc(spif.get_erase_size()); * sprintf(buffer, "Hello World!\n"); * spif.erase(0, spif.get_erase_size()); * spif.program(buffer, 0, spif.get_erase_size()); - * + * * // Read back what was stored * spif.read(buffer, 0, spif.get_erase_size()); * printf("%s", buffer); - * + * * // Deinitialize the device * spif.deinit(); * } @@ -83,7 +83,7 @@ public: * @param csel SPI chip select pin * @param freq Clock speed of the SPI bus (defaults to 40MHz) */ - SPIFBlockDevice(PinName mosi, PinName miso, PinName sclk, PinName csel, int freq=40000000); + SPIFBlockDevice(PinName mosi, PinName miso, PinName sclk, PinName csel, int freq = 40000000); /** Initialize a block device * @@ -185,7 +185,7 @@ public: * @return Size of the underlying device in bytes */ virtual bd_size_t size() const; - + private: // Internal functions @@ -210,7 +210,8 @@ private: unsigned int _sfdp_detect_page_size(uint8_t *basic_param_table_ptr, int basic_param_table_size); // Detect all supported erase types - int _sfdp_detect_erase_types_inst_and_size(uint8_t *basic_param_table_ptr, int basic_param_table_size, int& erase4k_inst, + int _sfdp_detect_erase_types_inst_and_size(uint8_t *basic_param_table_ptr, int basic_param_table_size, + int& erase4k_inst, int *erase_type_inst_arr, unsigned int *erase_type_size_arr); /***********************/ @@ -238,7 +239,7 @@ private: // Send Generic command_transfer command to Driver spif_bd_error _spi_send_general_command(int instruction, bd_addr_t addr, char *tx_buffer, - size_t tx_length, char *rx_buffer, size_t rx_length); + size_t tx_length, char *rx_buffer, size_t rx_length); // Send set_frequency command to Driver spif_bd_error _spi_set_frequency(int freq); @@ -289,7 +290,7 @@ private: unsigned int _read_dummy_and_mode_cycles; // Number of Dummy and Mode Bits required by Read Bus Mode unsigned int _write_dummy_and_mode_cycles; // Number of Dummy and Mode Bits required by Write Bus Mode unsigned int _dummy_and_mode_cycles; // Number of Dummy and Mode Bits required by Current Bus Mode - + uint32_t _init_ref_count; bool _is_initialized; }; From cc9ec128babaf7f2be0d000feee872ed8a5373c0 Mon Sep 17 00:00:00 2001 From: Offir Kochalsky Date: Sun, 19 Aug 2018 11:51:50 +0300 Subject: [PATCH 22/29] Include DigitalOut.h instead of mbed.h --- SPIFBlockDevice.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/SPIFBlockDevice.h b/SPIFBlockDevice.h index 0292082fa3..5290cee494 100644 --- a/SPIFBlockDevice.h +++ b/SPIFBlockDevice.h @@ -16,8 +16,8 @@ #ifndef MBED_SPIF_BLOCK_DEVICE_H #define MBED_SPIF_BLOCK_DEVICE_H -#include -#include +#include "SPI.h" +#include "DigitalOut.h" #include "BlockDevice.h" namespace mbed { From 86e039d8f8fa32644448b10c12b51609462cff1b Mon Sep 17 00:00:00 2001 From: Offir Kochalsky Date: Sun, 19 Aug 2018 14:29:00 +0300 Subject: [PATCH 23/29] Updated tests and config --- TESTS/block_device/spif/main.cpp | 294 +++++++++++++++++++++++-------- mbed_lib.json | 10 +- 2 files changed, 227 insertions(+), 77 deletions(-) diff --git a/TESTS/block_device/spif/main.cpp b/TESTS/block_device/spif/main.cpp index 4dc97562e4..918512e8aa 100644 --- a/TESTS/block_device/spif/main.cpp +++ b/TESTS/block_device/spif/main.cpp @@ -1,23 +1,30 @@ -#include "mbed.h" +/* mbed Microcontroller Library + * Copyright (c) 2018 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #include "greentea-client/test_env.h" #include "unity.h" #include "utest.h" - #include "SPIFBlockDevice.h" +#include "mbed_trace.h" #include using namespace utest::v1; -#if defined(TARGET_K82F) -#define TEST_PINS PTE2, PTE4, PTE1, PTE5 -#define TEST_FREQ 40000000 -#else -#define TEST_PINS D11, D12, D13, D10 -#define TEST_FREQ 1000000 -#endif - #define TEST_BLOCK_COUNT 10 #define TEST_ERROR_MASK 16 +#define QSPIF_TEST_NUM_OF_THREADS 5 const struct { const char *name; @@ -29,34 +36,133 @@ const struct { {"total size", &BlockDevice::size}, }; +static SingletonPtr _mutex; -void test_read_write() { - SPIFBlockDevice bd(TEST_PINS, TEST_FREQ); +// Mutex is protecting rand() per srand for buffer writing and verification. +// Mutex is also protecting printouts for clear logs. +// Mutex is NOT protecting Block Device actions: erase/program/read - which is the purpose of the multithreaded test! +void basic_erase_program_read_test(SPIFBlockDevice& blockD, bd_size_t block_size, uint8_t *write_block, + uint8_t *read_block, unsigned addrwidth) +{ + int err = 0; + _mutex->lock(); + // Find a random block + bd_addr_t block = (rand() * block_size) % blockD.size(); - int err = bd.init(); + // Use next random number as temporary seed to keep + // the address progressing in the pseudorandom sequence + unsigned seed = rand(); + + // Fill with random sequence + srand(seed); + for (bd_size_t i_ind = 0; i_ind < block_size; i_ind++) { + write_block[i_ind] = 0xff & rand(); + } + // Write, sync, and read the block + utest_printf("\ntest %0*llx:%llu...", addrwidth, block, block_size); + _mutex->unlock(); + + err = blockD.erase(block, block_size); TEST_ASSERT_EQUAL(0, err); - for (unsigned a = 0; a < sizeof(ATTRS)/sizeof(ATTRS[0]); a++) { + err = blockD.program(write_block, block, block_size); + TEST_ASSERT_EQUAL(0, err); + + err = blockD.read(read_block, block, block_size); + TEST_ASSERT_EQUAL(0, err); + + _mutex->lock(); + // Check that the data was unmodified + srand(seed); + int val_rand; + for (bd_size_t i_ind = 0; i_ind < block_size; i_ind++) { + val_rand = rand(); + if ( (0xff & val_rand) != read_block[i_ind] ) { + utest_printf("\n Assert Failed Buf Read - block:size: %llx:%llu \n", block, block_size); + utest_printf("\n pos: %llu, exp: %02x, act: %02x, wrt: %02x \n", i_ind, (0xff & val_rand), read_block[i_ind], + write_block[i_ind] ); + } + TEST_ASSERT_EQUAL(0xff & val_rand, read_block[i_ind]); + } + _mutex->unlock(); +} + +void test_qspif_random_program_read_erase() +{ + utest_printf("\nTest Random Program Read Erase Starts..\n"); + + SPIFBlockDevice blockD(MBED_CONF_SPIF_SPI_MOSI, MBED_CONF_SPIF_SPI_MISO, MBED_CONF_SPIF_SPI_CLK, MBED_CONF_SPIF_SPI_CS); + + int err = blockD.init(); + TEST_ASSERT_EQUAL(0, err); + + for (unsigned atr = 0; atr < sizeof(ATTRS) / sizeof(ATTRS[0]); atr++) { static const char *prefixes[] = {"", "k", "M", "G"}; - for (int i = 3; i >= 0; i--) { - bd_size_t size = (bd.*ATTRS[a].method)(); - if (size >= (1ULL << 10*i)) { - printf("%s: %llu%sbytes (%llubytes)\n", - ATTRS[a].name, size >> 10*i, prefixes[i], size); + for (int i_ind = 3; i_ind >= 0; i_ind--) { + bd_size_t size = (blockD.*ATTRS[atr].method)(); + if (size >= (1ULL << 10 * i_ind)) { + utest_printf("%s: %llu%sbytes (%llubytes)\n", + ATTRS[atr].name, size >> 10 * i_ind, prefixes[i_ind], size); break; } } } - bd_size_t block_size = bd.get_erase_size(); - uint8_t *write_block = new uint8_t[block_size]; - uint8_t *read_block = new uint8_t[block_size]; - uint8_t *error_mask = new uint8_t[TEST_ERROR_MASK]; - unsigned addrwidth = ceil(log(float(bd.size()-1)) / log(float(16)))+1; + bd_size_t block_size = blockD.get_erase_size(); + unsigned addrwidth = ceil(log(float(blockD.size() - 1)) / log(float(16))) + 1; + + uint8_t *write_block = new (std::nothrow) uint8_t[block_size]; + uint8_t *read_block = new (std::nothrow) uint8_t[block_size]; + if (!write_block || !read_block) { + utest_printf("\n Not enough memory for test"); + goto end; + } for (int b = 0; b < TEST_BLOCK_COUNT; b++) { - // Find a random block - bd_addr_t block = (rand()*block_size) % bd.size(); + basic_erase_program_read_test(blockD, block_size, write_block, read_block, addrwidth); + } + + err = blockD.deinit(); + TEST_ASSERT_EQUAL(0, err); + +end: + delete[] write_block; + delete[] read_block; +} + +void test_qspif_unaligned_program() +{ + utest_printf("\nTest Unaligned Program Starts..\n"); + + SPIFBlockDevice blockD(MBED_CONF_SPIF_SPI_MOSI, MBED_CONF_SPIF_SPI_MISO, MBED_CONF_SPIF_SPI_CLK, MBED_CONF_SPIF_SPI_CS); + + int err = blockD.init(); + TEST_ASSERT_EQUAL(0, err); + + for (unsigned atr = 0; atr < sizeof(ATTRS) / sizeof(ATTRS[0]); atr++) { + static const char *prefixes[] = {"", "k", "M", "G"}; + for (int i_ind = 3; i_ind >= 0; i_ind--) { + bd_size_t size = (blockD.*ATTRS[atr].method)(); + if (size >= (1ULL << 10 * i_ind)) { + utest_printf("%s: %llu%sbytes (%llubytes)\n", + ATTRS[atr].name, size >> 10 * i_ind, prefixes[i_ind], size); + break; + } + } + } + + bd_size_t block_size = blockD.get_erase_size(); + unsigned addrwidth = ceil(log(float(blockD.size() - 1)) / log(float(16))) + 1; + + uint8_t *write_block = new (std::nothrow) uint8_t[block_size]; + uint8_t *read_block = new (std::nothrow) uint8_t[block_size]; + if (!write_block || !read_block ) { + utest_printf("\n Not enough memory for test"); + goto end; + } + + { + bd_addr_t block = (rand() * block_size) % blockD.size() + 15; // Use next random number as temporary seed to keep // the address progressing in the pseudorandom sequence @@ -64,77 +170,121 @@ void test_read_write() { // Fill with random sequence srand(seed); - for (bd_size_t i = 0; i < block_size; i++) { - write_block[i] = 0xff & rand(); + for (bd_size_t i_ind = 0; i_ind < block_size; i_ind++) { + write_block[i_ind] = 0xff & rand(); } // Write, sync, and read the block - printf("test %0*llx:%llu...\n", addrwidth, block, block_size); + utest_printf("\ntest %0*llx:%llu...", addrwidth, block, block_size); - err = bd.erase(block, block_size); + err = blockD.erase(block, block_size); TEST_ASSERT_EQUAL(0, err); - err = bd.program(write_block, block, block_size); + err = blockD.program(write_block, block, block_size); TEST_ASSERT_EQUAL(0, err); - printf("write %0*llx:%llu ", addrwidth, block, block_size); - for (int i = 0; i < 16; i++) { - printf("%02x", write_block[i]); - } - printf("...\n"); - - err = bd.read(read_block, block, block_size); + err = blockD.read(read_block, block, block_size); TEST_ASSERT_EQUAL(0, err); - printf("read %0*llx:%llu ", addrwidth, block, block_size); - for (int i = 0; i < 16; i++) { - printf("%02x", read_block[i]); - } - printf("...\n"); - - // Find error mask for debugging - memset(error_mask, 0, TEST_ERROR_MASK); - bd_size_t error_scale = block_size / (TEST_ERROR_MASK*8); - - srand(seed); - for (bd_size_t i = 0; i < TEST_ERROR_MASK*8; i++) { - for (bd_size_t j = 0; j < error_scale; j++) { - if ((0xff & rand()) != read_block[i*error_scale + j]) { - error_mask[i/8] |= 1 << (i%8); - } - } - } - - printf("error %0*llx:%llu ", addrwidth, block, block_size); - for (int i = 0; i < 16; i++) { - printf("%02x", error_mask[i]); - } - printf("\n"); - // Check that the data was unmodified srand(seed); - for (bd_size_t i = 0; i < block_size; i++) { - TEST_ASSERT_EQUAL(0xff & rand(), read_block[i]); + for (bd_size_t i_ind = 0; i_ind < block_size; i_ind++) { + TEST_ASSERT_EQUAL(0xff & rand(), read_block[i_ind]); + } + + err = blockD.deinit(); + TEST_ASSERT_EQUAL(0, err); + } +end: + delete[] write_block; + delete[] read_block; +} + +static void test_qspif_thread_job(void *vBlockD/*, int thread_num*/) +{ + static int thread_num = 0; + thread_num++; + SPIFBlockDevice *blockD = (SPIFBlockDevice *)vBlockD; + utest_printf("\n Thread %d Started \n", thread_num); + + bd_size_t block_size = blockD->get_erase_size(); + unsigned addrwidth = ceil(log(float(blockD->size() - 1)) / log(float(16))) + 1; + + uint8_t *write_block = new (std::nothrow) uint8_t[block_size]; + uint8_t *read_block = new (std::nothrow) uint8_t[block_size]; + if (!write_block || !read_block ) { + utest_printf("\n Not enough memory for test"); + goto end; + } + + for (int b = 0; b < TEST_BLOCK_COUNT; b++) { + basic_erase_program_read_test((*blockD), block_size, write_block, read_block, addrwidth); + } + +end: + delete[] write_block; + delete[] read_block; +} + +void test_qspif_multi_threads() +{ + utest_printf("\nTest Multi Threaded Erase/Program/Read Starts..\n"); + + SPIFBlockDevice blockD(MBED_CONF_SPIF_SPI_MOSI, MBED_CONF_SPIF_SPI_MISO, MBED_CONF_SPIF_SPI_CLK, MBED_CONF_SPIF_SPI_CS); + + int err = blockD.init(); + TEST_ASSERT_EQUAL(0, err); + + for (unsigned atr = 0; atr < sizeof(ATTRS) / sizeof(ATTRS[0]); atr++) { + static const char *prefixes[] = {"", "k", "M", "G"}; + for (int i_ind = 3; i_ind >= 0; i_ind--) { + bd_size_t size = (blockD.*ATTRS[atr].method)(); + if (size >= (1ULL << 10 * i_ind)) { + utest_printf("%s: %llu%sbytes (%llubytes)\n", + ATTRS[atr].name, size >> 10 * i_ind, prefixes[i_ind], size); + break; + } } } - - err = bd.deinit(); + + rtos::Thread qspif_bd_thread[QSPIF_TEST_NUM_OF_THREADS]; + + osStatus threadStatus; + int i_ind; + + for (i_ind = 0; i_ind < QSPIF_TEST_NUM_OF_THREADS; i_ind++) { + threadStatus = qspif_bd_thread[i_ind].start(test_qspif_thread_job, (void *)&blockD); + if (threadStatus != 0) { + utest_printf("\n Thread %d Start Failed!", i_ind + 1); + } + } + + for (i_ind = 0; i_ind < QSPIF_TEST_NUM_OF_THREADS; i_ind++) { + qspif_bd_thread[i_ind].join(); + } + + err = blockD.deinit(); TEST_ASSERT_EQUAL(0, err); } - // Test setup -utest::v1::status_t test_setup(const size_t number_of_cases) { - GREENTEA_SETUP(30, "default_auto"); +utest::v1::status_t test_setup(const size_t number_of_cases) +{ + GREENTEA_SETUP(60, "default_auto"); return verbose_test_setup_handler(number_of_cases); } Case cases[] = { - Case("Testing read write random blocks", test_read_write), + Case("Testing unaligned program blocks", test_qspif_unaligned_program), + Case("Testing read write random blocks", test_qspif_random_program_read_erase), + Case("Testing Multi Threads Erase Program Read", test_qspif_multi_threads) }; Specification specification(test_setup, cases); -int main() { +int main() +{ + mbed_trace_init(); + utest_printf("MAIN STARTS\n"); return !Harness::run(specification); } diff --git a/mbed_lib.json b/mbed_lib.json index 4c08223703..40971a8da4 100644 --- a/mbed_lib.json +++ b/mbed_lib.json @@ -1,5 +1,5 @@ { - "name": "spif-driver", + "name": "spif", "config": { "SPI_MOSI": "NC", "SPI_MISO": "NC", @@ -9,10 +9,10 @@ }, "target_overrides": { "K82F": { - "SPI_MOSI": "PTE2", - "SPI_MISO": "PTE4", - "SPI_CLK": "PTE1", - "SPI_CS": "PTE5" + "SPI_MOSI": "PTE2", + "SPI_MISO": "PTE4", + "SPI_CLK": "PTE1", + "SPI_CS": "PTE5" }, "LPC54114": { "SPI_MOSI": "P0_20", From 5b170461e418af9ca4594c2e73554e8f3a675a20 Mon Sep 17 00:00:00 2001 From: Offir Kochalsky Date: Sun, 19 Aug 2018 14:34:27 +0300 Subject: [PATCH 24/29] qspi to spi typo --- TESTS/block_device/spif/main.cpp | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/TESTS/block_device/spif/main.cpp b/TESTS/block_device/spif/main.cpp index 918512e8aa..c3fccbbfb5 100644 --- a/TESTS/block_device/spif/main.cpp +++ b/TESTS/block_device/spif/main.cpp @@ -24,7 +24,7 @@ using namespace utest::v1; #define TEST_BLOCK_COUNT 10 #define TEST_ERROR_MASK 16 -#define QSPIF_TEST_NUM_OF_THREADS 5 +#define SPIF_TEST_NUM_OF_THREADS 5 const struct { const char *name; @@ -87,7 +87,7 @@ void basic_erase_program_read_test(SPIFBlockDevice& blockD, bd_size_t block_size _mutex->unlock(); } -void test_qspif_random_program_read_erase() +void test_spif_random_program_read_erase() { utest_printf("\nTest Random Program Read Erase Starts..\n"); @@ -130,7 +130,7 @@ end: delete[] read_block; } -void test_qspif_unaligned_program() +void test_spif_unaligned_program() { utest_printf("\nTest Unaligned Program Starts..\n"); @@ -200,7 +200,7 @@ end: delete[] read_block; } -static void test_qspif_thread_job(void *vBlockD/*, int thread_num*/) +static void test_spif_thread_job(void *vBlockD/*, int thread_num*/) { static int thread_num = 0; thread_num++; @@ -226,7 +226,7 @@ end: delete[] read_block; } -void test_qspif_multi_threads() +void test_spif_multi_threads() { utest_printf("\nTest Multi Threaded Erase/Program/Read Starts..\n"); @@ -247,20 +247,20 @@ void test_qspif_multi_threads() } } - rtos::Thread qspif_bd_thread[QSPIF_TEST_NUM_OF_THREADS]; + rtos::Thread spif_bd_thread[SPIF_TEST_NUM_OF_THREADS]; osStatus threadStatus; int i_ind; - for (i_ind = 0; i_ind < QSPIF_TEST_NUM_OF_THREADS; i_ind++) { - threadStatus = qspif_bd_thread[i_ind].start(test_qspif_thread_job, (void *)&blockD); + for (i_ind = 0; i_ind < SPIF_TEST_NUM_OF_THREADS; i_ind++) { + threadStatus = spif_bd_thread[i_ind].start(test_spif_thread_job, (void *)&blockD); if (threadStatus != 0) { utest_printf("\n Thread %d Start Failed!", i_ind + 1); } } - for (i_ind = 0; i_ind < QSPIF_TEST_NUM_OF_THREADS; i_ind++) { - qspif_bd_thread[i_ind].join(); + for (i_ind = 0; i_ind < SPIF_TEST_NUM_OF_THREADS; i_ind++) { + spif_bd_thread[i_ind].join(); } err = blockD.deinit(); @@ -275,9 +275,9 @@ utest::v1::status_t test_setup(const size_t number_of_cases) } Case cases[] = { - Case("Testing unaligned program blocks", test_qspif_unaligned_program), - Case("Testing read write random blocks", test_qspif_random_program_read_erase), - Case("Testing Multi Threads Erase Program Read", test_qspif_multi_threads) + Case("Testing unaligned program blocks", test_spif_unaligned_program), + Case("Testing read write random blocks", test_spif_random_program_read_erase), + Case("Testing Multi Threads Erase Program Read", test_spif_multi_threads) }; Specification specification(test_setup, cases); From 834a96c74283897c54ea42bd6593da754c7d3713 Mon Sep 17 00:00:00 2001 From: Offir Kochalsky Date: Mon, 20 Aug 2018 13:58:30 +0300 Subject: [PATCH 25/29] Fixing Warnings --- SPIFBlockDevice.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/SPIFBlockDevice.cpp b/SPIFBlockDevice.cpp index faacb5adc8..b772b1c12c 100644 --- a/SPIFBlockDevice.cpp +++ b/SPIFBlockDevice.cpp @@ -198,7 +198,7 @@ int SPIFBlockDevice::init() _region_high_boundary[0] = _device_size_bytes - 1; if ( (sector_map_table_addr != 0) && (0 != sector_map_table_size) ) { - tr_info("INFO: init - Parsing Sector Map Table - addr: 0x%xh, Size: %d", sector_map_table_addr, + tr_info("INFO: init - Parsing Sector Map Table - addr: 0x%lxh, Size: %d", sector_map_table_addr, sector_map_table_size); if (0 != _sfdp_parse_sector_map_table(sector_map_table_addr, sector_map_table_size) ) { tr_error("ERROR: init - Parse Sector Map Table Failed"); @@ -282,7 +282,7 @@ int SPIFBlockDevice::program(const void *buffer, bd_addr_t addr, bd_size_t size) uint32_t offset = 0; uint32_t chunk = 0; - tr_debug("DEBUG: program - Buff: 0x%x, addr: %llu, size: %llu", buffer, addr, size); + tr_debug("DEBUG: program - Buff: 0x%lxh, addr: %llu, size: %llu", (uint32_t)buffer, addr, size); while (size > 0) { @@ -351,7 +351,7 @@ int SPIFBlockDevice::erase(bd_addr_t addr, bd_size_t in_size) cur_erase_inst = _erase_type_inst_arr[type]; chunk = _erase_type_size_arr[type]; - tr_debug("DEBUG: erase - addr: %llu, size:%d, Inst: 0x%xh, chunk: %d , ", + tr_debug("DEBUG: erase - addr: %llu, size:%d, Inst: 0x%xh, chunk: %lu , ", addr, size, cur_erase_inst, chunk); tr_debug("DEBUG: erase - Region: %d, Type:%d", region, type); @@ -999,8 +999,8 @@ int SPIFBlockDevice::_utils_iterate_next_largest_erase_type(uint8_t& bitfield, i for (i_ind = 3; i_ind >= 0; i_ind--) { if (bitfield & type_mask) { largest_erase_type = i_ind; - if ( (size > _erase_type_size_arr[largest_erase_type]) && - ((boundry - offset) > _erase_type_size_arr[largest_erase_type]) ) { + if ( (size > (int)(_erase_type_size_arr[largest_erase_type])) && + ((boundry - offset) > (int)(_erase_type_size_arr[largest_erase_type])) ) { break; } else { bitfield &= ~type_mask; From f1f7664e316d15b4f575b6924d64e4f63dd06826 Mon Sep 17 00:00:00 2001 From: Offir Kochalsky Date: Mon, 20 Aug 2018 16:02:26 +0300 Subject: [PATCH 26/29] RDID is a register read that should use general command --- SPIFBlockDevice.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/SPIFBlockDevice.cpp b/SPIFBlockDevice.cpp index b772b1c12c..bc94d466df 100644 --- a/SPIFBlockDevice.cpp +++ b/SPIFBlockDevice.cpp @@ -154,7 +154,8 @@ int SPIFBlockDevice::init() /* Read Manufacturer ID (1byte), and Device ID (2bytes)*/ - spi_status = _spi_send_read_command(SPIF_RDID, vendor_device_ids, 0x0 /*address*/, data_length); + spi_status = _spi_send_general_command(SPIF_RDID, SPI_NO_ADDRESS_COMMAND, NULL, 0, (char *)vendor_device_ids, + data_length); if (spi_status != SPIF_BD_ERROR_OK) { tr_error("ERROR: init - Read Vendor ID Failed"); status = SPIF_BD_ERROR_DEVICE_ERROR; From 662c4a64af58296aa18a28ba7186d2b81386d85b Mon Sep 17 00:00:00 2001 From: Christopher Haster Date: Tue, 21 Aug 2018 12:33:32 -0500 Subject: [PATCH 27/29] Revert of namespace mbed Currently breaking backwards compatibility, including CI dependencies --- SPIFBlockDevice.cpp | 5 +---- SPIFBlockDevice.h | 8 ++------ 2 files changed, 3 insertions(+), 10 deletions(-) diff --git a/SPIFBlockDevice.cpp b/SPIFBlockDevice.cpp index bc94d466df..2f753813e8 100644 --- a/SPIFBlockDevice.cpp +++ b/SPIFBlockDevice.cpp @@ -22,6 +22,7 @@ #include "mbed_trace.h" #define TRACE_GROUP "SPIF" +using namespace mbed; /* Default SPIF Parameters */ /****************************/ @@ -71,8 +72,6 @@ #define IS_MEM_READY_MAX_RETRIES 10000 -namespace mbed { - enum spif_default_instructions { SPIF_NOP = 0x00, // No operation SPIF_PP = 0x02, // Page Program data @@ -1031,6 +1030,4 @@ static unsigned int local_math_power(int base, int exp) return result; } -} //namespace mbed - diff --git a/SPIFBlockDevice.h b/SPIFBlockDevice.h index 5290cee494..4c46da81ea 100644 --- a/SPIFBlockDevice.h +++ b/SPIFBlockDevice.h @@ -20,8 +20,6 @@ #include "DigitalOut.h" #include "BlockDevice.h" -namespace mbed { - /** Enum spif standard error codes * * @enum qpif_bd_error @@ -256,9 +254,9 @@ private: private: // Master side hardware - SPI _spi; + mbed::SPI _spi; // Enable CS control (low/high) for SPI driver operatios - DigitalOut _cs; + mbed::DigitalOut _cs; // Mutex is used to protect Flash device for some SPI Driver commands that must be done sequentially with no other commands in between // e.g. (1)Set Write Enable, (2)Program, (3)Wait Memory Ready @@ -294,6 +292,4 @@ private: bool _is_initialized; }; -} //namespace mbed - #endif /* MBED_SPIF_BLOCK_DEVICE_H */ From b042ba6d191ec43bd50fa46cdea8d542f4e47cb2 Mon Sep 17 00:00:00 2001 From: Offir Kochalsky Date: Wed, 22 Aug 2018 15:50:09 +0300 Subject: [PATCH 28/29] changed conf back to spid-driver --- TESTS/block_device/spif/main.cpp | 9 ++++++--- mbed_lib.json | 2 +- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/TESTS/block_device/spif/main.cpp b/TESTS/block_device/spif/main.cpp index c3fccbbfb5..6ba06c9e64 100644 --- a/TESTS/block_device/spif/main.cpp +++ b/TESTS/block_device/spif/main.cpp @@ -91,7 +91,8 @@ void test_spif_random_program_read_erase() { utest_printf("\nTest Random Program Read Erase Starts..\n"); - SPIFBlockDevice blockD(MBED_CONF_SPIF_SPI_MOSI, MBED_CONF_SPIF_SPI_MISO, MBED_CONF_SPIF_SPI_CLK, MBED_CONF_SPIF_SPI_CS); + SPIFBlockDevice blockD(MBED_CONF_SPIF_DRIVER_SPI_MOSI, MBED_CONF_SPIF_DRIVER_SPI_MISO, MBED_CONF_SPIF_DRIVER_SPI_CLK, + MBED_CONF_SPIF_DRIVER_SPI_CS); int err = blockD.init(); TEST_ASSERT_EQUAL(0, err); @@ -134,7 +135,8 @@ void test_spif_unaligned_program() { utest_printf("\nTest Unaligned Program Starts..\n"); - SPIFBlockDevice blockD(MBED_CONF_SPIF_SPI_MOSI, MBED_CONF_SPIF_SPI_MISO, MBED_CONF_SPIF_SPI_CLK, MBED_CONF_SPIF_SPI_CS); + SPIFBlockDevice blockD(MBED_CONF_SPIF_DRIVER_SPI_MOSI, MBED_CONF_SPIF_DRIVER_SPI_MISO, MBED_CONF_SPIF_DRIVER_SPI_CLK, + MBED_CONF_SPIF_DRIVER_SPI_CS); int err = blockD.init(); TEST_ASSERT_EQUAL(0, err); @@ -230,7 +232,8 @@ void test_spif_multi_threads() { utest_printf("\nTest Multi Threaded Erase/Program/Read Starts..\n"); - SPIFBlockDevice blockD(MBED_CONF_SPIF_SPI_MOSI, MBED_CONF_SPIF_SPI_MISO, MBED_CONF_SPIF_SPI_CLK, MBED_CONF_SPIF_SPI_CS); + SPIFBlockDevice blockD(MBED_CONF_SPIF_DRIVER_SPI_MOSI, MBED_CONF_SPIF_DRIVER_SPI_MISO, MBED_CONF_SPIF_DRIVER_SPI_CLK, + MBED_CONF_SPIF_DRIVER_SPI_CS); int err = blockD.init(); TEST_ASSERT_EQUAL(0, err); diff --git a/mbed_lib.json b/mbed_lib.json index 40971a8da4..07fc85b1a4 100644 --- a/mbed_lib.json +++ b/mbed_lib.json @@ -1,5 +1,5 @@ { - "name": "spif", + "name": "spif-driver", "config": { "SPI_MOSI": "NC", "SPI_MISO": "NC", From 2d756825d982cc0ffb41689d3d705821a54a8f61 Mon Sep 17 00:00:00 2001 From: Offir Kochalsky Date: Thu, 23 Aug 2018 09:44:23 +0300 Subject: [PATCH 29/29] Fix undefined macro error in ARM build --- SPIFBlockDevice.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/SPIFBlockDevice.cpp b/SPIFBlockDevice.cpp index 2f753813e8..7845d27db0 100644 --- a/SPIFBlockDevice.cpp +++ b/SPIFBlockDevice.cpp @@ -31,6 +31,9 @@ using namespace mbed; #define SPIF_DEFAULT_PAGE_SIZE 256 #define SPIF_DEFAULT_SE_SIZE 4096 #define SPI_MAX_STATUS_REGISTER_SIZE 2 +#ifndef UINT64_MAX +#define UINT64_MAX -1 +#endif #define SPI_NO_ADDRESS_COMMAND UINT64_MAX // Status Register Bits #define SPIF_STATUS_BIT_WIP 0x1 //Write In Progress