diff --git a/include/littlefs_shim.h b/include/littlefs_shim.h new file mode 100644 index 0000000..685d648 --- /dev/null +++ b/include/littlefs_shim.h @@ -0,0 +1,31 @@ +#ifndef ROCKETLIB_LITTLEFS_SHIM_H +#define ROCKETLIB_LITTLEFS_SHIM_H + +#include "lfs.h" +#include "stm32h7xx_hal_sd.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// External SD handle used by the shim +extern SD_HandleTypeDef *lfsshim_hsd; + +extern uint32_t lfsshim_first_block_offset; + +// LittleFS-compatible SD card interface functions +int lfsshim_read(const struct lfs_config *c, lfs_block_t block, lfs_off_t off, void *buffer, + lfs_size_t size); + +int lfsshim_write(const struct lfs_config *c, lfs_block_t block, lfs_off_t off, const void *buffer, + lfs_size_t size); + +int lfsshim_erase(const struct lfs_config *c, lfs_block_t block); + +int lfsshim_sync(const struct lfs_config *c); + +#ifdef __cplusplus +} +#endif + +#endif // ROCKETLIB_LITTLEFS_SHIM_H diff --git a/stm32h7/littlefs_shim.c b/stm32h7/littlefs_shim.c new file mode 100644 index 0000000..17342a4 --- /dev/null +++ b/stm32h7/littlefs_shim.c @@ -0,0 +1,68 @@ +#include "stm32h7xx_hal.h" +#include "lfs.h" +#include "common.h" + +#define SD_RW_TIMEOUT_MS 50 + +SD_HandleTypeDef* lfsshim_hsd; +uint32_t lfsshim_first_block_offset = 0; + +int lfsshim_read(const struct lfs_config *c, lfs_block_t block, lfs_off_t off, void *buffer, + lfs_size_t size) { + uint32_t block_addr = block + lfsshim_first_block_offset; + + w_assert((size % c->block_size) == 0); + w_assert(off == 0); + + uint32_t num_blocks = size / c->block_size; + + HAL_StatusTypeDef hal = + HAL_SD_ReadBlocks(lfsshim_hsd, (uint8_t *)buffer, block_addr, num_blocks, SD_RW_TIMEOUT_MS); + if (hal != HAL_OK) { + return -1; // LFS_ERR_IO + } + + // Wait for card to be ready (polling) + uint32_t start = HAL_GetTick(); + while (HAL_SD_GetCardState(lfsshim_hsd) != HAL_SD_CARD_TRANSFER) { + if ((HAL_GetTick() - start) > SD_RW_TIMEOUT_MS) { + return -1; // timeout -> LFS_ERR_IO + } + } + + return 0; // success +} + +int lfsshim_write(const struct lfs_config *c, lfs_block_t block, lfs_off_t off, const void *buffer, + lfs_size_t size) { + uint32_t block_addr = block + lfsshim_first_block_offset; + + w_assert((size % c->block_size) == 0); + w_assert(off == 0); + + uint32_t num_blocks = size / c->block_size; + + HAL_StatusTypeDef hal = + HAL_SD_WriteBlocks(lfsshim_hsd, (uint8_t *)buffer, block_addr, num_blocks, SD_RW_TIMEOUT_MS); + if (hal != HAL_OK) { + return -1; // LFS_ERR_IO + } + + // Wait for card to be ready (polling) + uint32_t start = HAL_GetTick(); + while (HAL_SD_GetCardState(lfsshim_hsd) != HAL_SD_CARD_TRANSFER) { + if ((HAL_GetTick() - start) > SD_RW_TIMEOUT_MS) { + return -1; // timeout -> LFS_ERR_IO + } + } + + return 0; // success +} + +int lfsshim_erase(const struct lfs_config *c, lfs_block_t block) { + return 0; // SD does not require explicit erase +} + +int lfsshim_sync(const struct lfs_config *c) { + return 0; +}