NVS sector erase

In the Zephyr documentation, the explanation for NVS sector erase is a little ambiguous. 

Elements, represented as id-data pairs, are stored in flash using a FIFO-managed circular buffer. The flash area is divided into sectors. Elements are appended to a sector until storage space in the sector is exhausted. Then a new sector in the flash area is prepared for use (erased). Before erasing the sector it is checked that identifier - data pairs exist in the sectors in use, if not the id-data pair is copied.

Suppose we use a 4 bytes state variable that is changed every minute and needs to be restored after reboot. NVS has been defined with a sector_size equal to the pagesize (1024 bytes) and 2 sectors have been defined.

Each write of the state variable requires 12 bytes of flash storage: 8 bytes for the metadata and 4 bytes for the data. When storing the data the first sector will be full after 1024/12 = 85.33 minutes. After another 85.33 minutes, the second sector is full. When this happens, because we’re using only two sectors, the first sector will be used for storage and will be erased after 171 minutes of system time. With the expected device life of 20,000 writes, with two sectors writing every 171 minutes, the device should last about 171 * 20,000 minutes, or about 6.5 years.

In my firmware, i'm writing to the NVS continuously, but the data does not automatically get overwritten when it reaches the end of the last sector. I could manually delete half of my data in order to simulate a sector delete, but I think that would wear out the flash by erasing the same sector multiple times. How can I manually delete a sector of the NVS space using the NVS library? It is not very obvious to me.

Parents Reply
  • Hi,

     

    Wavecake said:

    How can nvs_delete remove a single entry without erasing the whole sector? 

    Would multiple calls to nvs_delete for a single entry erase the sector multiple times?

    NVS is a minimalistic filesystem that only erases when required, ie. when there's no more free space (ie. the flash content is != 0xFFFFFFFF). This is different from an "nvs erased entry", which is your previous data, just that it has been invalidated and an updated entry is placed in flash.

    At that point, it parses its own flash area to see which entries are invalidated (ie. marked as "deleted"), and will do a garbage collection to remove all invalidated entries.

     

    Kind regards,

    Håkon

Children
  • Just to update for posterity, I thought I'd add what I learned after working through this issue.

    My main concern was flash lifetime when using the NVS driver. The NVS driver will minimize page erases on its own. If you write to an ID repeatedly, the driver will append the data to the flash. It will only erase a page of flash when it is full. When it erases a page of flash, it does garbage collection to preserve any ID-data that it needs to copy before the erase. 

Related