Littlefs is a small fail-safe filesystem designed for microcontrollers and licensed with BDS-3-Clause. It is designed to handle random power failures and dynamic wear leveling. It has bounded memory which means it doesn't increase when the filesystem gets larger. This blog will show you how to integrate littlefs to a CMSIS flash driver when using a Renesas EK-RA6M4 board.
Our previous post implemented the CMSIS flash driver for the Renesas EK-RA6M4 board Quad-SPI flash memory. Adding filesystem layer on top of this driver should be quite trivial. FSP configurator actually supports littlefs directly but only when used with Renesas internal data flash memory with r_flash_hp driver. As we want to use our own CMSIS driver with external flash memory we have to do the littlefs integration by ourselves.
At first, I downloaded the sources for the littlefs from the GitHub repository and added those to my e2 studio project. I added that new folder to the include search path and copied the example code to update boot count from README.md to hal_entry function.
The following code includes my CMSIS flash memory driver, header for the filesystem and a new wrapper header created for all things to be implemented by the filesystem user. Memory needed by the filesystem and one file are allocated with the lfs and file variables. lfs_config structure specifies callback function pointers and a memory configuration, here we have a forward declaration for the structure which is implemented in my wrapper. After driver initialization, this code follows the example from the README.md:
The main point of the integration is the implementation of the lfs_config structure. Here is my implementation for the filesystem configuration and function callbacks. Block device configuration definitions are from CMSIS flash memory driver header. Each block device operation will call corresponding CMSIS flash memory driver function and map the error from the driver error code to the littlefs error code. Nothing fancy.
Becuase I added my test code to the hal_entry function which is run only during boot, I needed to restart the debug session couple of times to make sure that the boot_count variable was loaded correctly from the filesystem. After this I can verify that the file was stored correctly to the filesystem.
After having the CMSIS flash memory driver implemented, it was trivial to add filesystem layer on top of that. The only thing you need to do is to create the filesystem configuration structure and implement those functions callbacks specified in lfs.h header which contains also most of the documentation for the filesystem. And if you really want to know what is going on, you should read littlefs DESIGN.md and SPEC.md files.