diff --git a/subsys/fs/nvs/Kconfig b/subsys/fs/nvs/Kconfig index 8b7dfdbab40..208be140f22 100644 --- a/subsys/fs/nvs/Kconfig +++ b/subsys/fs/nvs/Kconfig @@ -37,6 +37,14 @@ config NVS_DATA_CRC 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. +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-str = nvs source "subsys/logging/Kconfig.template.log_config" diff --git a/subsys/fs/nvs/nvs.c b/subsys/fs/nvs/nvs.c index e45e93e1982..2c7c4ff5606 100644 --- a/subsys/fs/nvs/nvs.c +++ b/subsys/fs/nvs/nvs.c @@ -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) { +#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; goto end; +#endif } if (i == fs->sector_count) {