Skip to content

Commit

Permalink
fs: nvs: Allow application to switch sector to get free space
Browse files Browse the repository at this point in the history
Add an API function allowing the application to determine the amount of
free bytes in the current sector.

Add a second API function allowing the application to switch to the next
NVS sector, calling the garbage collector on such sector.

The goal is togive more granularity to the application to control when
the garbage collector is triggered.

Signed-off-by: Adrien Ricciardi <[email protected]>
  • Loading branch information
RICCIARDI-Adrien authored and nashif committed Jul 28, 2024
1 parent ea1a0a6 commit b09972b
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
24 changes: 24 additions & 0 deletions include/zephyr/fs/nvs.h
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,30 @@ ssize_t nvs_read_hist(struct nvs_fs *fs, uint16_t id, void *data, size_t len, ui
*/
ssize_t nvs_calc_free_space(struct nvs_fs *fs);

/**
* @brief Tell how many contiguous free space remains in the currently active NVS sector.
*
* @param fs Pointer to the file system.
*
* @return Number of free bytes.
*/
size_t nvs_sector_max_data_size(struct nvs_fs *fs);

/**
* @brief Close the currently active sector and switch to the next one.
*
* @note The garbage collector is called on the new sector.
*
* @warning This routine is made available for specific use cases.
* It breaks the aim of the NVS to avoid any unnecessary flash erases.
* Using this routine extensively can result in premature failure of the flash device.
*
* @param fs Pointer to the file system.
*
* @return 0 on success. On error, returns negative value of errno.h defined error codes.
*/
int nvs_sector_use_next(struct nvs_fs *fs);

/**
* @}
*/
Expand Down
37 changes: 37 additions & 0 deletions subsys/fs/nvs/nvs.c
Original file line number Diff line number Diff line change
Expand Up @@ -1358,3 +1358,40 @@ ssize_t nvs_calc_free_space(struct nvs_fs *fs)
}
return free_space;
}

size_t nvs_sector_max_data_size(struct nvs_fs *fs)
{
size_t ate_size;

if (!fs->ready) {
LOG_ERR("NVS not initialized");
return -EACCES;
}

ate_size = nvs_al_size(fs, sizeof(struct nvs_ate));

return fs->ate_wra - fs->data_wra - ate_size - NVS_DATA_CRC_SIZE;
}

int nvs_sector_use_next(struct nvs_fs *fs)
{
int ret;

if (!fs->ready) {
LOG_ERR("NVS not initialized");
return -EACCES;
}

k_mutex_lock(&fs->nvs_lock, K_FOREVER);

ret = nvs_sector_close(fs);
if (ret != 0) {
goto end;
}

ret = nvs_gc(fs);

end:
k_mutex_unlock(&fs->nvs_lock);
return ret;
}

0 comments on commit b09972b

Please sign in to comment.