fs: nvs: Add recovery path for corrupted NVS

When all sectors have non-zero data, NVS would fail to init.
Add recovery path option to erase the all sectors and reinitialize.
This could occur due to non-empty sectors, or corrupted data.

Signed-off-by: Cory Andrew Mayer <corymayer@meta.com>
This commit is contained in:
Cory Andrew Mayer 2024-12-21 07:45:45 -08:00 committed by Benjamin Cabé
parent 19dee0e937
commit 58514c291c
2 changed files with 22 additions and 1 deletions

View file

@ -37,6 +37,14 @@ config NVS_DATA_CRC
The CRC-32 is transparently stored at the end of the data field, The CRC-32 is transparently stored at the end of the data field,
in the NVS data section, so 4 more bytes are needed per NVS element. in the NVS data section, so 4 more bytes are needed per NVS element.
config NVS_INIT_BAD_MEMORY_REGION
bool "Non-volatile Storage bad memory region recovery"
help
Enable automatic initialization of a NVS on a memory region that does
not contain a valid NVS. A region containing an invalid NVS can be
caused by corruption or by providing a non-empty region. This option
ensures a new NVS can be created.
module = NVS module = NVS
module-str = nvs module-str = nvs
source "subsys/logging/Kconfig.template.log_config" source "subsys/logging/Kconfig.template.log_config"

View file

@ -781,10 +781,23 @@ static int nvs_startup(struct nvs_fs *fs)
} }
} }
} }
/* all sectors are closed, this is not a nvs fs */ /* all sectors are closed, this is not a nvs fs or irreparably corrupted */
if (closed_sectors == fs->sector_count) { if (closed_sectors == fs->sector_count) {
#ifdef CONFIG_NVS_INIT_BAD_MEMORY_REGION
LOG_WRN("All sectors closed, erasing all sectors...");
rc = flash_flatten(fs->flash_device, fs->offset,
fs->sector_size * fs->sector_count);
if (rc) {
goto end;
}
i = fs->sector_count;
addr = ((fs->sector_count - 1) << ADDR_SECT_SHIFT) +
(uint16_t)(fs->sector_size - ate_size);
#else
rc = -EDEADLK; rc = -EDEADLK;
goto end; goto end;
#endif
} }
if (i == fs->sector_count) { if (i == fs->sector_count) {