Initial commit of SPI flash device

pull/7774/head
Christopher Haster 2017-02-14 10:57:42 -06:00
commit 18005bcc56
5 changed files with 847 additions and 0 deletions

165
LICENSE Normal file
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.

42
README.md Normal file
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
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();
}
```

341
SPIFBlockDevice.cpp Normal file
View File

@ -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<uint8_t *>(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<const uint8_t *>(buffer));
buffer = static_cast<const uint8_t*>(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;
}

154
SPIFBlockDevice.h Normal file
View File

@ -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 <mbed.h>
#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 */

View File

@ -0,0 +1,145 @@
#include "mbed.h"
#include "greentea-client/test_env.h"
#include "unity.h"
#include "utest.h"
#include "SPIFBlockDevice.h"
#include <stdlib.h>
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);
}