diff --git a/subsys/settings/include/settings/settings_nvs.h b/subsys/settings/include/settings/settings_nvs.h index ce34e192c2..6db576da63 100644 --- a/subsys/settings/include/settings/settings_nvs.h +++ b/subsys/settings/include/settings/settings_nvs.h @@ -45,6 +45,8 @@ struct settings_nvs { } cache[CONFIG_SETTINGS_NVS_NAME_CACHE_SIZE]; uint16_t cache_next; + uint16_t cache_total; + bool loaded; #endif }; diff --git a/subsys/settings/src/settings_nvs.c b/subsys/settings/src/settings_nvs.c index c6efa6cb28..6764c7587a 100644 --- a/subsys/settings/src/settings_nvs.c +++ b/subsys/settings/src/settings_nvs.c @@ -74,6 +74,8 @@ int settings_nvs_dst(struct settings_nvs *cf) } #if CONFIG_SETTINGS_NVS_NAME_CACHE +#define SETTINGS_NVS_CACHE_OVFL(cf) ((cf)->cache_total > ARRAY_SIZE((cf)->cache)) + static void settings_nvs_cache_add(struct settings_nvs *cf, const char *name, uint16_t name_id) { @@ -129,12 +131,22 @@ static int settings_nvs_load(struct settings_store *cs, ssize_t rc1, rc2; uint16_t name_id = NVS_NAMECNT_ID; +#if CONFIG_SETTINGS_NVS_NAME_CACHE + uint16_t cached = 0; + + cf->loaded = false; +#endif + name_id = cf->last_name_id + 1; while (1) { name_id--; if (name_id == NVS_NAMECNT_ID) { +#if CONFIG_SETTINGS_NVS_NAME_CACHE + cf->loaded = true; + cf->cache_total = cached; +#endif break; } @@ -186,6 +198,7 @@ static int settings_nvs_load(struct settings_store *cs, #if CONFIG_SETTINGS_NVS_NAME_CACHE settings_nvs_cache_add(cf, name, name_id); + cached++; #endif ret = settings_call_set_handler( @@ -231,6 +244,13 @@ static int settings_nvs_save(struct settings_store *cs, const char *name, write_name_id = cf->last_name_id + 1; write_name = true; +#if CONFIG_SETTINGS_NVS_NAME_CACHE + /* We can skip reading NVS if we know that the cache wasn't overflowed. */ + if (cf->loaded && !SETTINGS_NVS_CACHE_OVFL(cf)) { + goto found; + } +#endif + while (1) { name_id--; if (name_id == NVS_NAMECNT_ID) { @@ -325,6 +345,9 @@ found: #if CONFIG_SETTINGS_NVS_NAME_CACHE if (!name_in_cache) { settings_nvs_cache_add(cf, name, write_name_id); + if (cf->loaded && !SETTINGS_NVS_CACHE_OVFL(cf)) { + cf->cache_total++; + } } #endif