Add 'components/storage/blockdevice/COMPONENT_SPIF/' from commit '622382ae8fab0c18d3a3576bbce9c3b448459282'

git-subtree-dir: components/storage/blockdevice/COMPONENT_SPIF
git-subtree-mainline: 90866170ea
git-subtree-split: 622382ae8f
pull/7774/head
Yossi Levy 2018-08-29 11:47:21 +03:00
commit 5294ef72b7
7 changed files with 1925 additions and 0 deletions

View File

@ -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

View File

@ -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.

View File

@ -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
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();
}
```

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,295 @@
/* 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.
*/
#ifndef MBED_SPIF_BLOCK_DEVICE_H
#define MBED_SPIF_BLOCK_DEVICE_H
#include "SPI.h"
#include "DigitalOut.h"
#include "BlockDevice.h"
/** Enum spif standard error codes
*
* @enum qpif_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_WREN_FAILED = -4004, /* Write Enable Failed */
};
#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();
* }
* @endcode
*/
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 = 40000000);
/** Initialize a block device
*
* @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 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 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);
/** 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 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);
/** 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 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);
/** Get the size of a readable block
*
* @return Size of a readable block in bytes
*/
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() 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() 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)
* @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
* 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
*/
virtual bd_size_t size() const;
private:
// Internal functions
/****************************************/
/* 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, int basic_param_table_size, int& read_inst);
// Set Page size for program
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 *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);
/********************************/
/* 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
mbed::SPI _spi;
// Enable CS control (low/high) for SPI driver operatios
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
static SingletonPtr<PlatformMutex> _mutex;
// Command Instructions
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)
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[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[SPIF_MAX_REGIONS];
unsigned int _min_common_erase_size; // minimal common erase size for all regions (0 if none exists)
unsigned int _page_size_bytes; // Page size - 256 Bytes default
bd_size_t _device_size_bytes;
// 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
uint32_t _init_ref_count;
bool _is_initialized;
};
#endif /* MBED_SPIF_BLOCK_DEVICE_H */

View File

@ -0,0 +1,293 @@
/* 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 <stdlib.h>
using namespace utest::v1;
#define TEST_BLOCK_COUNT 10
#define TEST_ERROR_MASK 16
#define SPIF_TEST_NUM_OF_THREADS 5
const struct {
const char *name;
bd_size_t (BlockDevice::*method)() const;
} ATTRS[] = {
{"read size", &BlockDevice::get_read_size},
{"program size", &BlockDevice::get_program_size},
{"erase size", &BlockDevice::get_erase_size},
{"total size", &BlockDevice::size},
};
static SingletonPtr<PlatformMutex> _mutex;
// 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();
// 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);
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_spif_random_program_read_erase()
{
utest_printf("\nTest Random Program Read Erase Starts..\n");
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);
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;
}
for (int b = 0; b < TEST_BLOCK_COUNT; b++) {
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_spif_unaligned_program()
{
utest_printf("\nTest Unaligned Program Starts..\n");
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);
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
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);
err = blockD.erase(block, block_size);
TEST_ASSERT_EQUAL(0, err);
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);
// Check that the data was unmodified
srand(seed);
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_spif_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_spif_multi_threads()
{
utest_printf("\nTest Multi Threaded Erase/Program/Read Starts..\n");
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);
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;
}
}
}
rtos::Thread spif_bd_thread[SPIF_TEST_NUM_OF_THREADS];
osStatus threadStatus;
int i_ind;
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 < SPIF_TEST_NUM_OF_THREADS; i_ind++) {
spif_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(60, "default_auto");
return verbose_test_setup_handler(number_of_cases);
}
Case cases[] = {
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);
int main()
{
mbed_trace_init();
utest_printf("MAIN STARTS\n");
return !Harness::run(specification);
}

View File

@ -0,0 +1,66 @@
{
"name": "spif-driver",
"config": {
"SPI_MOSI": "NC",
"SPI_MISO": "NC",
"SPI_CLK": "NC",
"SPI_CS": "NC",
"SPI_FREQ": "40000000"
},
"target_overrides": {
"K82F": {
"SPI_MOSI": "PTE2",
"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"
},
"NRF52840_DK": {
"SPI_MOSI": "p20",
"SPI_MISO": "p21",
"SPI_CLK": "p19",
"SPI_CS": "p17"
},
"HEXIWEAR": {
"SPI_MOSI": "PTD6",
"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"
},
"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"
},
"MTB_ADV_WISE_1570": {
"SPI_MOSI": "PA_7",
"SPI_MISO": "PA_6",
"SPI_CLK": "PA_5",
"SPI_CS": "PB_12"
}
}
}