Select Git revision
st3m_fs_flash.c 7.70 KiB
#include "st3m_fs_flash.h"
#include "esp_log.h"
#include "esp_system.h"
#include "esp_vfs.h"
#include "esp_vfs_fat.h"
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "diskio.h"
#include "diskio_impl.h"
#include "diskio_wl.h"
#include "vfs_fat_internal.h"
static const char *TAG = "st3m-fs-flash";
static SemaphoreHandle_t _mu = NULL;
static st3m_fs_flash_status_t _status = st3m_fs_flash_status_unmounted;
// Handle of the wear levelling library instance
static wl_handle_t _wl_handle = WL_INVALID_HANDLE;
void st3m_fs_flash_init(void) {
assert(_mu == NULL);
_mu = xSemaphoreCreateMutex();
assert(_mu != NULL);
const esp_partition_t *data_partition = esp_partition_find_first(
ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_ANY, "vfs");
if (data_partition == NULL) {
ESP_LOGE(TAG, "Could not find data partition.");
return;
}
esp_err_t res = wl_mount(data_partition, &_wl_handle);
if (res != ESP_OK) {
ESP_LOGE(TAG, "Mounting wear leveling failed.");
return;
}
}
st3m_fs_flash_status_t st3m_fs_flash_get_status(void) {
xSemaphoreTake(_mu, portMAX_DELAY);
st3m_fs_flash_status_t st = _status;
xSemaphoreGive(_mu);
return st;
}
static esp_err_t _f_mount_rw(FATFS *fs, const char *drv,
const esp_vfs_fat_mount_config_t *mount_config) {
FRESULT fresult = f_mount(fs, drv, 1);
if (fresult != FR_OK) {
ESP_LOGW(TAG, "f_mount failed (%d)", fresult);
bool need_mount_again =
(fresult == FR_NO_FILESYSTEM || fresult == FR_INT_ERR) &&
mount_config->format_if_mount_failed;
if (!need_mount_again) {
return ESP_FAIL;
}
const size_t workbuf_size = 4096;
void *workbuf = ff_memalloc(workbuf_size);
if (workbuf == NULL) {
return ESP_ERR_NO_MEM;
}
size_t alloc_unit_size = esp_vfs_fat_get_allocation_unit_size(
CONFIG_WL_SECTOR_SIZE, mount_config->allocation_unit_size);
ESP_LOGI(TAG, "Formatting FATFS partition, allocation unit size=%d",