Source code for the Trusted Boot Module.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
tbm-mcu/source/core/flash.c

176 lines
2.7 KiB

#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <flash.h>
#include <macros.h>
static int default_flash_is_val(struct flash_dev *dev, uint32_t addr, uint8_t val)
{
uint8_t data[32];
size_t i, nbytes, len = 1 << dev->log2_block_size;
addr <<= dev->log2_block_size;
while (len) {
nbytes = min(32, len);
if (flash_read(dev, addr, data, nbytes) == 0)
return 0;
for (i = 0; i < sizeof(data); ++i) {
if (data[i] != val)
return 0;
}
addr += nbytes;
len -= nbytes;
}
return 1;
}
int default_flash_is_zero(struct flash_dev *dev, uint32_t addr)
{
return default_flash_is_val(dev, addr, 0);
}
int default_flash_is_one(struct flash_dev *dev, uint32_t addr)
{
return default_flash_is_val(dev, addr, 0xff);
}
size_t default_flash_copy(struct flash_dev *dev, uint32_t dst, uint32_t src,
size_t len)
{
uint8_t data[32];
size_t nbytes, ret = 0;
while (len) {
nbytes = min(sizeof data, len);
if (flash_read(dev, src, data, nbytes) == 0)
return ret;
if (flash_write(dev, dst, data, nbytes) == 0)
return ret;
dst += nbytes;
src += nbytes;
len -= nbytes;
ret += nbytes;
}
return ret;
}
void flash_release(struct flash_dev *dev)
{
if (!dev)
return;
dev->ops->release(dev);
}
size_t flash_get_size(struct flash_dev *dev)
{
if (!dev)
return 0;
return dev->ops->get_size(dev);
}
size_t flash_get_capacity(struct flash_dev *dev)
{
if (!dev)
return 0;
return dev->ops->get_capacity(dev);
}
size_t flash_read(struct flash_dev *dev, uint32_t addr, void *data, size_t len)
{
if (!dev)
return -1;
return dev->ops->read(dev, addr, data, len);
}
size_t flash_write(struct flash_dev *dev, uint32_t addr, const void *data,
size_t len)
{
if (!dev)
return -1;
return dev->ops->write(dev, addr, data, len);
}
size_t flash_write0(struct flash_dev *dev, uint32_t addr, size_t len)
{
uint8_t data[32];
size_t nbytes, ret = 0;
memset(data, 0, 32);
while (len) {
nbytes = min(sizeof data, len);
if (flash_write(dev, addr, data, nbytes) == 0)
return ret;
addr += nbytes;
len -= nbytes;
ret += nbytes;
}
return ret;
}
size_t flash_copy(struct flash_dev *dev, uint32_t dst, uint32_t src, size_t len)
{
if (!dev)
return 0;
return dev->ops->copy(dev, dst, src, len);
}
int flash_is_erased(struct flash_dev *dev, uint32_t addr, size_t len)
{
if (!dev)
return -1;
while (len--) {
if (!dev->ops->is_erased(dev, addr))
return 0;
++addr;
}
return 1;
}
int flash_erase(struct flash_dev *dev, uint32_t addr, size_t len)
{
if (!dev)
return -1;
while (len--) {
if (dev->ops->erase(dev, addr) < 0)
return -1;
++addr;
}
return 0;
}
int flash_sync(struct flash_dev *dev)
{
if (!dev)
return -1;
if (!dev->ops->sync)
return 0;
return dev->ops->sync(dev);
}