services/storage/nvs/nvs.html · services/storage/nvs/nvs.rst 공식 원문 ↗

Zephyr 3.7.0 · Storage · Persistent Values

Non-Volatile Storage (NVS)

16-bit ID와 data를 power-loss에 견디는 circular flash log로 저장합니다.

Official pathservices/storage/nvs/nvs.html
Source fileservices/storage/nvs/nvs.rst
Source versionZephyr 3.7.0
TranslationFull · reviewed

본문 기준: Zephyr 3.7.0 LTS3 · 이후 유지보수 패치는 별도입니다.

Part 1

요약·해설

Data와 metadata의 양방향 sector layout, copy-forward reclaim, CRC 선택, endurance 계산과 MPU troubleshooting을 설명합니다.

Layout

Data · 8-byte metadata

Recovery

CRC · append ordering

Lifetime

Erase-cycle calculation

Part 2

접을 수 있는 영어 원문 전체

영어 원문 전체 펼치기
원문 SHA-256 6999435C4414658952C4FE15C63679AA2B93E729B1674F99FE2A23B1DF0A532A
.. _nvs_api:

Non-Volatile Storage (NVS)
##########################

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.

The id is a 16-bit unsigned number. NVS ensures that for each used id there is
at least one id-data pair stored in flash at all time.

NVS allows storage of binary blobs, strings, integers, longs, and any
combination of these.

Each element is stored in flash as metadata (8 byte) and data. The metadata is
written in a table starting from the end of a nvs sector, the data is
written one after the other from the start of the sector. The metadata consists
of: id, data offset in sector, data length, part (unused), and a CRC. This CRC is
only calculated over the metadata and only ensures that a write has been
completed. The actual data of the element can be protected by a different (and optional)
CRC-32. Use the :kconfig:option:`CONFIG_NVS_DATA_CRC` configuration item to enable
the data part CRC.

.. note:: The data CRC is checked only when the whole data of the element is read.
  The data CRC is not checked for a partial read, as it is stored at the end of the
  element data area.

.. note:: Enabling the data CRC feature on a previously existing NVS content without
  data CRC will make all existing data invalid.

A write of data to nvs always starts with writing the data, followed by a write
of the metadata. Data that is written in flash without metadata is ignored
during initialization.

During initialization NVS will verify the data stored in flash, if it
encounters an error it will ignore any data with missing/incorrect metadata.

NVS checks the id-data pair before writing data to flash. If the id-data pair
is unchanged no write to flash is performed.

To protect the flash area against frequent erases it is important that there is
sufficient free space. NVS has a protection mechanism to avoid getting in a
endless loop of flash page erases when there is limited free space. When such
a loop is detected NVS returns that there is no more space available.

For NVS the file system is declared as:

.. code-block:: c

	static struct nvs_fs fs = {
	.flash_device = NVS_FLASH_DEVICE,
	.sector_size = NVS_SECTOR_SIZE,
	.sector_count = NVS_SECTOR_COUNT,
	.offset = NVS_STORAGE_OFFSET,
	};

where

- ``NVS_FLASH_DEVICE`` is a reference to the flash device that will be used. The
  device needs to be operational.
- ``NVS_SECTOR_SIZE`` is the sector size, it has to be a multiple of
  the flash erase page size and a power of 2.
- ``NVS_SECTOR_COUNT`` is the number of sectors, it is at least 2, one
  sector is always kept empty to allow copying of existing data.
- ``NVS_STORAGE_OFFSET`` is the offset of the storage area in flash.


Flash wear
**********

When writing data to flash a study of the flash wear is important. Flash has a
limited life which is determined by the number of times flash can be erased.
Flash is erased one page at a time and the pagesize is determined by the
hardware. As an example a nRF51822 device has a pagesize of 1024 bytes and each
page can be erased about 20,000 times.

Calculating expected device lifetime
====================================

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.

More generally then, with

- ``NS`` as the number of storage requests per minute,
- ``DS`` as the data size in bytes,
- ``SECTOR_SIZE`` in bytes, and
- ``PAGE_ERASES`` as the number of times the page can be erased,

the expected device life (in minutes) can be calculated as::

   SECTOR_COUNT * SECTOR_SIZE * PAGE_ERASES / (NS * (DS+8)) minutes

From this formula it is also clear what to do in case the expected life is too
short: increase ``SECTOR_COUNT`` or ``SECTOR_SIZE``.

Flash write block size migration
********************************
It is possible that during a DFU process, the flash driver used by the NVS
changes the supported minimal write block size.
The NVS in-flash image will stay compatible unless the
physical ATE size changes.
Especially, migration between 1,2,4,8-bytes write block sizes is allowed.

Sample
******

A sample of how NVS can be used is supplied in ``samples/subsys/nvs``.

Troubleshooting
***************

MPU fault while using NVS, or ``-ETIMEDOUT`` error returned
   NVS can use the internal flash of the SoC.  While the MPU is enabled,
   the flash driver requires MPU RWX access to flash memory, configured
   using :kconfig:option:`CONFIG_MPU_ALLOW_FLASH_WRITE`.  If this option is
   disabled, the NVS application will get an MPU fault if it references
   the internal SoC flash and it's the only thread running.  In a
   multi-threaded application, another thread might intercept the fault
   and the NVS API will return an ``-ETIMEDOUT`` error.


API Reference
*************

The NVS subsystem APIs are provided by ``nvs.h``:

.. doxygengroup:: nvs_data_structures

.. doxygengroup:: nvs_high_level_api

.. comment
   not documenting
   .. doxygengroup:: nvs

Part 3

한국어 전문 번역

NVS(Non-Volatile Storage)는 16-bit ID와 binary data의 쌍을 flash에 저장하는 작은 key-value storage입니다. Flash area를 여러 sector로 나누고 FIFO 방식의 circular buffer로 관리합니다.

Element는 active sector에 차례로 append됩니다. 공간이 다 차면 새 sector를 erase해 사용 준비를 합니다. 오래된 sector를 지우기 전, 다른 active sector에 아직 같은 ID의 최신 id-data pair가 있는지 확인하고 없으면 살아 있는 값을 새 sector로 복사합니다. 따라서 사용 중인 각 ID에는 항상 최소 하나의 저장본이 남습니다.

Data는 binary blob, string, integer, long 또는 이들의 조합일 수 있습니다. NVS는 payload의 형식을 해석하지 않고 caller가 준 byte sequence로 보존합니다.

Element 하나는 payload data와 8-byte metadata로 저장됩니다. Data는 sector 시작에서 뒤쪽으로 자라고, metadata table은 sector 끝에서 앞쪽으로 자랍니다. Metadata에는 ID, sector 내부 data offset, data length, 사용하지 않는 part field와 CRC가 들어갑니다.

Metadata CRC는 payload 무결성이 아니라 metadata write가 끝까지 완료됐는지만 확인합니다. Payload 자체를 CRC-32로 보호하려면 CONFIG_NVS_DATA_CRC를 켭니다. Data CRC는 element 전체를 읽을 때만 검사합니다. CRC가 payload 끝에 있으므로 partial read에서는 검증하지 않습니다.

Write 순서는 payload data가 먼저이고 metadata가 나중입니다. 전원이 끊겨 data만 쓰이고 metadata가 없는 fragment는 mount 시 무시됩니다. 초기화 과정에서도 metadata가 없거나 잘못된 data는 건너뜁니다.

NVS는 write 전에 기존 id-data pair와 비교합니다. 값이 완전히 같으면 flash write를 생략해 endurance를 아낍니다. Free space가 지나치게 적어 erase page를 끝없이 순환하는 상황을 감지하면 더 이상 공간이 없다는 오류를 반환합니다.

NVS sector의 양방향 성장과 순환
Sector startdata가 앞에서 뒤로 연속 기록됨
free space가 감소
Sector end8-byte ATE metadata가 뒤에서 앞으로 기록됨
sector full
Next sectorerase 후 active sector로 전환
live ID 보존
Old sector reclaim최신 id-data pair를 복사한 뒤 erase

NVS instance는 다음처럼 nvs_fs에 backing flash와 geometry를 지정해 선언합니다.

static struct nvs_fs fs = {
.flash_device = NVS_FLASH_DEVICE,
.sector_size = NVS_SECTOR_SIZE,
.sector_count = NVS_SECTOR_COUNT,
.offset = NVS_STORAGE_OFFSET,
};
  • NVS_FLASH_DEVICE: 사용할 flash device reference이며 operational 상태여야 합니다.
  • NVS_SECTOR_SIZE: flash erase page size의 배수이자 2의 거듭제곱이어야 합니다.
  • NVS_SECTOR_COUNT: 최소 2입니다. 기존 data를 복사할 수 있도록 항상 sector 하나를 비워 둡니다.
  • NVS_STORAGE_OFFSET: flash device 안 storage area의 시작 offset입니다.

Flash wear

Flash는 erase 횟수에 한계가 있으므로 NVS write 주기와 page endurance를 함께 계산해야 합니다. Erase는 hardware가 정한 page 단위로 일어납니다. 예를 들어 nRF51822는 page size가 1024 byte이고 page당 약 20,000회 erase할 수 있습니다.

Calculating expected device lifetime

4-byte state variable을 매분 갱신하고 reboot 뒤 복원한다고 가정합니다. Sector size는 page size와 같은 1024 byte, sector 수는 2입니다. 한 write는 metadata 8 byte와 data 4 byte를 합친 12 byte를 소비합니다.

첫 sector는 1024/12 = 85.33분 뒤 가득 차고, 다음 85.33분 뒤 두 번째 sector도 가득 찹니다. 두 sector만 쓰므로 약 171분마다 첫 sector를 다시 쓰기 위해 erase합니다. 20,000회 erase endurance라면 171 × 20,000분, 약 6.5년이 됩니다.

일반식에서 NS는 분당 저장 횟수, DS는 data byte 수, SECTOR_SIZE는 byte 단위 sector 크기, PAGE_ERASES는 허용 erase 횟수입니다.

SECTOR_COUNT * SECTOR_SIZE * PAGE_ERASES / (NS * (DS+8)) minutes

계산 결과가 너무 짧다면 SECTOR_COUNT 또는 SECTOR_SIZE를 늘려 erase 주기를 길게 해야 합니다. 같은 data를 다시 쓸 때 write를 생략하는 특성도 실제 수명을 늘려 줍니다.

Flash write block size migration

DFU 과정에서 NVS가 사용하는 flash driver가 바뀌며 minimum write block size가 달라질 수 있습니다. Physical ATE 크기가 바뀌지 않는 한 on-flash image는 호환됩니다. 특히 1, 2, 4, 8-byte write block size 사이 migration은 허용됩니다.

Sample

NVS 사용 예제는 samples/subsys/nvs에 있습니다. Mount, typed value write/read, reboot persistence와 delete 흐름을 실제 application으로 확인할 수 있습니다.

Troubleshooting

NVS 사용 중 MPU fault가 발생하거나 -ETIMEDOUT이 반환되면 internal SoC flash write 권한을 확인합니다. MPU가 활성화된 환경에서 flash driver는 flash memory에 RWX access가 필요하며 CONFIG_MPU_ALLOW_FLASH_WRITE로 설정합니다.

이 option이 꺼진 상태에서 NVS application만 실행되면 internal flash access가 MPU fault를 냅니다. Multi-thread application에서는 다른 thread가 fault를 가로채 NVS API가 -ETIMEDOUT으로 보일 수도 있습니다.

API Reference

NVS subsystem API는 nvs.h가 제공합니다. Structure field는 mount 뒤의 write cursor와 geometry를 설명하고, high-level function은 mount·clear·write·delete·latest/history read와 free-space 계산을 제공합니다.

nvs_fs
NVS instance의 flash geometry, current write addresses, ready state, lock과 backing device 정보를 보관합니다.
nvs_fs.offset
Flash device 시작점에서 NVS storage area까지의 offset입니다.
nvs_fs.ate_wra
다음 allocation table entry metadata를 쓸 주소입니다.
nvs_fs.data_wra
다음 element payload data를 쓸 주소입니다.
nvs_fs.sector_size
NVS sector 크기입니다. Flash erase page size의 배수이면서 2의 거듭제곱이어야 합니다.
nvs_fs.sector_count
순환에 사용하는 sector 수입니다. Live data 복사를 위한 빈 sector 하나를 유지하므로 최소 2입니다.
nvs_fs.ready
Mount와 초기 scan이 끝나 instance를 사용할 수 있는지 나타냅니다.
nvs_fs.nvs_lock
동시 NVS access와 internal state 변경을 직렬화하는 mutex입니다.
nvs_fs.flash_device
Element를 저장할 operational flash device pointer입니다.
nvs_fs.flash_parameters
Write block size와 erase value 같은 backing flash parameter cache입니다.
nvs_mount
Geometry를 검증하고 flash를 scan해 write pointer와 valid element를 복원한 뒤 NVS를 mount합니다.
nvs_clear
NVS가 사용하는 flash area를 지워 empty file system으로 만듭니다.
nvs_write
16-bit ID와 data를 기록합니다. 같은 ID·같은 data면 flash를 쓰지 않고 0을 반환하며, 길이 0은 delete와 같습니다.
nvs_delete
ID의 현재 값을 삭제된 것으로 기록합니다. 길이 0 element와 삭제 상태는 구분할 수 없습니다.
nvs_read
ID의 최신 값을 읽습니다. 반환값이 요청 길이보다 크면 일부만 읽었고 더 많은 data가 있다는 뜻입니다.
nvs_read_hist
같은 ID의 과거 값을 읽습니다. cnt=0은 최신, 1은 그 이전 version입니다.
nvs_calc_free_space
아직 쓸 수 있는 byte 수를 계산합니다. 전체 scan 때문에 특히 SPI flash에서는 시간이 오래 걸릴 수 있습니다.

Source

출처

영어 원문에는 문단, 문서 지시문, 표, 코드, 코드 심벌, 경로를 그대로 보존했습니다.