Skip to content

Commit 05c98bb

Browse files
[nrf fromtree] fs: nvs: Allow application to switch sector to get free space
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. (cherry picked from commit b09972b) Signed-off-by: Adrien Ricciardi <[email protected]>
1 parent a415e2d commit 05c98bb

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

include/zephyr/fs/nvs.h

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,30 @@ ssize_t nvs_read_hist(struct nvs_fs *fs, uint16_t id, void *data, size_t len, ui
164164
*/
165165
ssize_t nvs_calc_free_space(struct nvs_fs *fs);
166166

167+
/**
168+
* @brief Tell how many contiguous free space remains in the currently active NVS sector.
169+
*
170+
* @param fs Pointer to the file system.
171+
*
172+
* @return Number of free bytes.
173+
*/
174+
size_t nvs_sector_max_data_size(struct nvs_fs *fs);
175+
176+
/**
177+
* @brief Close the currently active sector and switch to the next one.
178+
*
179+
* @note The garbage collector is called on the new sector.
180+
*
181+
* @warning This routine is made available for specific use cases.
182+
* It breaks the aim of the NVS to avoid any unnecessary flash erases.
183+
* Using this routine extensively can result in premature failure of the flash device.
184+
*
185+
* @param fs Pointer to the file system.
186+
*
187+
* @return 0 on success. On error, returns negative value of errno.h defined error codes.
188+
*/
189+
int nvs_sector_use_next(struct nvs_fs *fs);
190+
167191
/**
168192
* @}
169193
*/

subsys/fs/nvs/nvs.c

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1392,3 +1392,40 @@ ssize_t nvs_calc_free_space(struct nvs_fs *fs)
13921392
}
13931393
return free_space;
13941394
}
1395+
1396+
size_t nvs_sector_max_data_size(struct nvs_fs *fs)
1397+
{
1398+
size_t ate_size;
1399+
1400+
if (!fs->ready) {
1401+
LOG_ERR("NVS not initialized");
1402+
return -EACCES;
1403+
}
1404+
1405+
ate_size = nvs_al_size(fs, sizeof(struct nvs_ate));
1406+
1407+
return fs->ate_wra - fs->data_wra - ate_size - NVS_DATA_CRC_SIZE;
1408+
}
1409+
1410+
int nvs_sector_use_next(struct nvs_fs *fs)
1411+
{
1412+
int ret;
1413+
1414+
if (!fs->ready) {
1415+
LOG_ERR("NVS not initialized");
1416+
return -EACCES;
1417+
}
1418+
1419+
k_mutex_lock(&fs->nvs_lock, K_FOREVER);
1420+
1421+
ret = nvs_sector_close(fs);
1422+
if (ret != 0) {
1423+
goto end;
1424+
}
1425+
1426+
ret = nvs_gc(fs);
1427+
1428+
end:
1429+
k_mutex_unlock(&fs->nvs_lock);
1430+
return ret;
1431+
}

0 commit comments

Comments
 (0)